mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 12:35:42 +00:00
Compare commits
143
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9960c07010 | ||
|
|
df60ba5c96 | ||
|
|
16e15e8fb3 | ||
|
|
03812bb3b7 | ||
|
|
cbcf39d7c2 | ||
|
|
91a217879f | ||
|
|
605f85b4b9 | ||
|
|
fb14b99d50 | ||
|
|
f1a0b7e2ff | ||
|
|
cdecd09e3c | ||
|
|
a8aff1c1a3 | ||
|
|
fc0f8a8530 | ||
|
|
d0398fd853 | ||
|
|
4e3eeea5e2 | ||
|
|
2e64ae7575 | ||
|
|
a62933d023 | ||
|
|
ab7e17a09d | ||
|
|
de5f0fe6df | ||
|
|
5dd973587f | ||
|
|
a4558c841a | ||
|
|
decab6ea90 | ||
|
|
de70e37f30 | ||
|
|
33cd43237e | ||
|
|
253756d45f | ||
|
|
4759a01ef3 | ||
|
|
7dedf945c2 | ||
|
|
4527e93118 | ||
|
|
56fabbdbf0 | ||
|
|
b424bfa353 | ||
|
|
1570d4457c | ||
|
|
75c321123d | ||
|
|
fbb705cf6f | ||
|
|
448d296a2b | ||
|
|
a9524ea991 | ||
|
|
73ccae2425 | ||
|
|
6384b220fc | ||
|
|
e3d86c4b17 | ||
|
|
76aa3771b7 | ||
|
|
9c349e185e | ||
|
|
c2663ebee8 | ||
|
|
f15c0af34e | ||
|
|
68f1d5baa3 | ||
|
|
293ed4fb08 | ||
|
|
52e8028609 | ||
|
|
9ce6d45be8 | ||
|
|
ae9bac225d | ||
|
|
7b4b86b0f3 | ||
|
|
a7032530da | ||
|
|
7254a88391 | ||
|
|
fdf3d98c36 | ||
|
|
6f7d7f827f | ||
|
|
059711cfe1 | ||
|
|
87cd74c4bf | ||
|
|
3087309d3c | ||
|
|
b6d77bc3d8 | ||
|
|
99bf382ae8 | ||
|
|
eb190f2dd7 | ||
|
|
a3be5f7ae2 | ||
|
|
87c571f443 | ||
|
|
c847659789 | ||
|
|
aa3a599ec6 | ||
|
|
2cb51103ac | ||
|
|
269d462825 | ||
|
|
d8b3c66b95 | ||
|
|
84b7295f11 | ||
|
|
50fbcf8b2a | ||
|
|
76c4de5b5d | ||
|
|
2183b05573 | ||
|
|
e816d79581 | ||
|
|
f502b8b3e6 | ||
|
|
30d103280b | ||
|
|
f6d1794624 | ||
|
|
e8d28c164a | ||
|
|
9a964ba221 | ||
|
|
b3ebd54d87 | ||
|
|
6d1a0d9fd0 | ||
|
|
bc929c08b2 | ||
|
|
0b8a3f1ee8 | ||
|
|
1e6aebd216 | ||
|
|
8a37e71e10 | ||
|
|
13b05656aa | ||
|
|
58af2e136b | ||
|
|
69b612be1f | ||
|
|
392562bfae | ||
|
|
1b65508f56 | ||
|
|
cd945a520a | ||
|
|
d33f4b4896 | ||
|
|
33dbd8755f | ||
|
|
d058bab64f | ||
|
|
c57cc33125 | ||
|
|
83de0e7f8c | ||
|
|
f33181e430 | ||
|
|
bb05e20d1b | ||
|
|
1b732c1b65 | ||
|
|
827ab2d485 | ||
|
|
d63193393d | ||
|
|
b841b232b4 | ||
|
|
9cc37d0a12 | ||
|
|
bd4bfce3af | ||
|
|
60098d4a1b | ||
|
|
b5f6122d49 | ||
|
|
39a4a1b60c | ||
|
|
b52ce7e4c5 | ||
|
|
b1b6ab7931 | ||
|
|
dacfee64ab | ||
|
|
76f0c51235 | ||
|
|
a1dfb96708 | ||
|
|
52bf19ad8e | ||
|
|
bd022f04be | ||
|
|
a5712c0d20 | ||
|
|
08a8de9bc4 | ||
|
|
514f796428 | ||
|
|
3b1366f85c | ||
|
|
c8dec0a8bc | ||
|
|
a8237e8927 | ||
|
|
da5a36151b | ||
|
|
01bfe8519e | ||
|
|
cd05c96d10 | ||
|
|
b303423001 | ||
|
|
1882520cac | ||
|
|
7da27d4ff4 | ||
|
|
02a5be62da | ||
|
|
956f17239b | ||
|
|
92d4959970 | ||
|
|
65554a544c | ||
|
|
f4503c2eda | ||
|
|
8ee50e5b38 | ||
|
|
afd2d91662 | ||
|
|
3230ccdc73 | ||
|
|
c177b1eed1 | ||
|
|
8e02be2440 | ||
|
|
a7bd6ed299 | ||
|
|
8961d088f2 | ||
|
|
2953739f1e | ||
|
|
ea48036811 | ||
|
|
b3c61cf0bf | ||
|
|
3b6d13a8d7 | ||
|
|
1d247d212b | ||
|
|
7d5aae724c | ||
|
|
263e96469f | ||
|
|
4fea462223 | ||
|
|
8a01432313 | ||
|
|
213b2f850f |
No files matched your search
+63
-10
@@ -127,6 +127,7 @@ jobs:
|
|||||||
name: xbox-arm64
|
name: xbox-arm64
|
||||||
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-xbox
|
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-xbox
|
||||||
retention-days: 14
|
retention-days: 14
|
||||||
|
overwrite: true
|
||||||
- uses: actions/upload-artifact@v4
|
- uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: xbox-corresponding-source
|
name: xbox-corresponding-source
|
||||||
@@ -135,6 +136,7 @@ jobs:
|
|||||||
app/build/xbox/runtime/*-source.tar.xz
|
app/build/xbox/runtime/*-source.tar.xz
|
||||||
if-no-files-found: error
|
if-no-files-found: error
|
||||||
retention-days: 14
|
retention-days: 14
|
||||||
|
overwrite: true
|
||||||
|
|
||||||
components-runner:
|
components-runner:
|
||||||
needs: source
|
needs: source
|
||||||
@@ -330,6 +332,7 @@ jobs:
|
|||||||
if-no-files-found: error
|
if-no-files-found: error
|
||||||
compression-level: 0
|
compression-level: 0
|
||||||
retention-days: 14
|
retention-days: 14
|
||||||
|
overwrite: true
|
||||||
|
|
||||||
build-runner:
|
build-runner:
|
||||||
needs: [components]
|
needs: [components]
|
||||||
@@ -562,6 +565,12 @@ jobs:
|
|||||||
command -v x86_64-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-x86-64; }
|
command -v x86_64-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-x86-64; }
|
||||||
bash tools/ubisoft-launcher/build.sh
|
bash tools/ubisoft-launcher/build.sh
|
||||||
|
|
||||||
|
- name: Rockstar launcher service (32-bit and 64-bit)
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
command -v i686-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-i686; }
|
||||||
|
bash tools/rockstar-launcher/build.sh
|
||||||
|
|
||||||
- uses: actions/download-artifact@v4
|
- uses: actions/download-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: xbox-arm64
|
name: xbox-arm64
|
||||||
@@ -617,12 +626,11 @@ jobs:
|
|||||||
- name: Check out MaliBridge
|
- name: Check out MaliBridge
|
||||||
run: git submodule update --init external/MaliBridge
|
run: git submodule update --init external/MaliBridge
|
||||||
- name: Fetch the Mali (Venus) component (tools/venus/release.env)
|
- name: Fetch the Mali (Venus) component (tools/venus/release.env)
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ github.token }}
|
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
. tools/venus/release.env
|
. tools/venus/release.env
|
||||||
gh release download "${VENUS_TAG}" -R "${VENUS_REPO}" -p venus.tzst -O venus.tzst
|
curl -fsSL --retry 5 --retry-all-errors --retry-delay 10 -o venus.tzst \
|
||||||
|
"https://github.com/${VENUS_REPO}/releases/download/${VENUS_TAG}/venus.tzst"
|
||||||
echo "${VENUS_SHA256} venus.tzst" | sha256sum -c -
|
echo "${VENUS_SHA256} venus.tzst" | sha256sum -c -
|
||||||
tar --use-compress-program=unzstd -xf venus.tzst -C app/src/main
|
tar --use-compress-program=unzstd -xf venus.tzst -C app/src/main
|
||||||
test -f app/src/main/jniLibs/arm64-v8a/libvirgl_test_server.so
|
test -f app/src/main/jniLibs/arm64-v8a/libvirgl_test_server.so
|
||||||
@@ -659,6 +667,7 @@ jobs:
|
|||||||
name: stores-cargo-lock
|
name: stores-cargo-lock
|
||||||
path: app/src/main/rust/stores/Cargo.lock
|
path: app/src/main/rust/stores/Cargo.lock
|
||||||
if-no-files-found: ignore
|
if-no-files-found: ignore
|
||||||
|
overwrite: true
|
||||||
|
|
||||||
- name: Unit tests
|
- name: Unit tests
|
||||||
id: unit-tests
|
id: unit-tests
|
||||||
@@ -682,6 +691,7 @@ jobs:
|
|||||||
app/build/reports/tests/testReleaseUnitTest/
|
app/build/reports/tests/testReleaseUnitTest/
|
||||||
if-no-files-found: ignore
|
if-no-files-found: ignore
|
||||||
retention-days: 14
|
retention-days: 14
|
||||||
|
overwrite: true
|
||||||
|
|
||||||
- name: Sign with the testkey (v1 + v2 + v3)
|
- name: Sign with the testkey (v1 + v2 + v3)
|
||||||
run: |
|
run: |
|
||||||
@@ -719,6 +729,7 @@ jobs:
|
|||||||
if-no-files-found: error
|
if-no-files-found: error
|
||||||
retention-days: 30
|
retention-days: 30
|
||||||
compression-level: 0
|
compression-level: 0
|
||||||
|
overwrite: true
|
||||||
|
|
||||||
- uses: actions/upload-artifact@v4
|
- uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
@@ -727,6 +738,7 @@ jobs:
|
|||||||
if-no-files-found: error
|
if-no-files-found: error
|
||||||
retention-days: 30
|
retention-days: 30
|
||||||
compression-level: 0
|
compression-level: 0
|
||||||
|
overwrite: true
|
||||||
|
|
||||||
- name: Report on the pull request
|
- name: Report on the pull request
|
||||||
if: always() && github.event_name == 'pull_request'
|
if: always() && github.event_name == 'pull_request'
|
||||||
@@ -798,9 +810,11 @@ jobs:
|
|||||||
set -o pipefail
|
set -o pipefail
|
||||||
cd app/src/main/rust/stores
|
cd app/src/main/rust/stores
|
||||||
cargo test --locked 2>&1 | tail -60
|
cargo test --locked 2>&1 | tail -60
|
||||||
- name: Ubisoft launcher service host unit tests
|
- name: Windows launcher service host unit tests
|
||||||
timeout-minutes: 10
|
timeout-minutes: 10
|
||||||
run: cargo test --locked --manifest-path tools/ubisoft-launcher/Cargo.toml
|
run: |
|
||||||
|
cargo test --locked --manifest-path tools/ubisoft-launcher/Cargo.toml
|
||||||
|
cargo test --locked --manifest-path tools/rockstar-launcher/Cargo.toml
|
||||||
|
|
||||||
python-tests:
|
python-tests:
|
||||||
name: Python and native regression tests
|
name: Python and native regression tests
|
||||||
@@ -833,12 +847,9 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
XBOX_SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
|
XBOX_SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
|
||||||
run: test "$(git rev-parse 'HEAD^{tree}')" = "$XBOX_SOURCE_TREE"
|
run: test "$(git rev-parse 'HEAD^{tree}')" = "$XBOX_SOURCE_TREE"
|
||||||
- uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version: '20'
|
|
||||||
- name: Install Python test dependencies
|
- name: Install Python test dependencies
|
||||||
timeout-minutes: 7
|
timeout-minutes: 7
|
||||||
run: bash tools/ci/install-ubuntu-packages.sh python3-yaml gcc-aarch64-linux-gnu libc6-dev-arm64-cross qemu-user libvulkan-dev mesa-vulkan-drivers
|
run: bash tools/ci/install-ubuntu-packages.sh python3-yaml gcc-aarch64-linux-gnu libc6-dev-arm64-cross qemu-user libvulkan-dev mesa-vulkan-drivers spirv-tools
|
||||||
- name: Resolve the pinned Android NDK
|
- name: Resolve the pinned Android NDK
|
||||||
run: bash tools/ci/resolve-ndk.sh
|
run: bash tools/ci/resolve-ndk.sh
|
||||||
|
|
||||||
@@ -868,6 +879,16 @@ jobs:
|
|||||||
-ldl -o /tmp/test-presenter-shutdown
|
-ldl -o /tmp/test-presenter-shutdown
|
||||||
timeout 10 /tmp/test-presenter-shutdown
|
timeout 10 /tmp/test-presenter-shutdown
|
||||||
|
|
||||||
|
- name: Fetch the Mali compatibility layer's headers
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
sdk=$(sed -n 's/^SDK=//p' tools/venus/ci-build.sh)
|
||||||
|
bcdec=$(grep -o 'https://raw.githubusercontent.com/iOrange/bcdec/[^ ]*' tools/venus/ci-build.sh)
|
||||||
|
mkdir -p build/layer-deps/bcdec
|
||||||
|
git -c advice.detachedHead=false clone -q --depth 1 -b "$sdk" https://github.com/KhronosGroup/Vulkan-Headers.git build/layer-deps/vulkan
|
||||||
|
git -c advice.detachedHead=false clone -q --depth 1 -b "$sdk" https://github.com/KhronosGroup/SPIRV-Headers.git build/layer-deps/spirv
|
||||||
|
curl -sSfL -o build/layer-deps/bcdec/bcdec.h "$bcdec"
|
||||||
|
|
||||||
- name: Steam import and game environment tests
|
- name: Steam import and game environment tests
|
||||||
run: bash tools/ci/run-python-tests.sh
|
run: bash tools/ci/run-python-tests.sh
|
||||||
|
|
||||||
@@ -926,7 +947,7 @@ jobs:
|
|||||||
pull-requests: read
|
pull-requests: read
|
||||||
env:
|
env:
|
||||||
CI_REPO: Droid-Deck/DroidDeck-CI
|
CI_REPO: Droid-Deck/DroidDeck-CI
|
||||||
KEEP: 10
|
KEEP_DAYS: 14
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
@@ -971,3 +992,35 @@ jobs:
|
|||||||
if: ${{ always() && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && needs.announce.result != 'skipped' }}
|
if: ${{ always() && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && needs.announce.result != 'skipped' }}
|
||||||
uses: ./.github/workflows/update-catalog.yml
|
uses: ./.github/workflows/update-catalog.yml
|
||||||
secrets: inherit
|
secrets: inherit
|
||||||
|
|
||||||
|
retire-tests:
|
||||||
|
needs: catalog
|
||||||
|
if: ${{ always() && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && needs.catalog.result == 'success' }}
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
timeout-minutes: 10
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
pull-requests: read
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
ref: ${{ github.sha }}
|
||||||
|
persist-credentials: false
|
||||||
|
- uses: actions/create-github-app-token@v2
|
||||||
|
id: ci-token
|
||||||
|
with:
|
||||||
|
app-id: ${{ vars.DROIDDECK_CI_APP_ID }}
|
||||||
|
private-key: ${{ secrets.DROIDDECK_CI_APP_KEY }}
|
||||||
|
owner: Droid-Deck
|
||||||
|
repositories: DroidDeck-CI
|
||||||
|
- name: Delete the test builds this Preview build replaces
|
||||||
|
env:
|
||||||
|
SOURCE_GITHUB_TOKEN: ${{ github.token }}
|
||||||
|
CI_GITHUB_TOKEN: ${{ steps.ci-token.outputs.token }}
|
||||||
|
run: python3 tools/release/retire_test_builds.py
|
||||||
|
|
||||||
|
catalog-after-retire:
|
||||||
|
needs: retire-tests
|
||||||
|
if: ${{ always() && needs.retire-tests.result == 'success' }}
|
||||||
|
uses: ./.github/workflows/update-catalog.yml
|
||||||
|
secrets: inherit
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
name: PR Rebuild On Version Bump
|
||||||
|
run-name: rebuild test builds below versionCode on main
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
paths: [app/build.gradle]
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
actions: write
|
||||||
|
contents: read
|
||||||
|
issues: write
|
||||||
|
pull-requests: read
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: pr-rebuild-on-version
|
||||||
|
cancel-in-progress: false
|
||||||
|
queue: max
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
rebuild:
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
timeout-minutes: 180
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
ref: main
|
||||||
|
fetch-depth: 2
|
||||||
|
persist-credentials: false
|
||||||
|
- name: Rebuild open PRs whose test build Android would refuse over main
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
EVENT_NAME: ${{ github.event_name }}
|
||||||
|
BEFORE: ${{ github.event.before }}
|
||||||
|
PUSHED_AT: ${{ github.event.repository.pushed_at }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
code() { sed -n 's/^[[:space:]]*versionCode[[:space:]][[:space:]]*\([0-9][0-9]*\)[[:space:]]*$/\1/p'; }
|
||||||
|
now=$(code < app/build.gradle)
|
||||||
|
[[ "$now" =~ ^[0-9]+$ ]] || { echo "::error::No numeric versionCode on main"; exit 1; }
|
||||||
|
if [ "$EVENT_NAME" = push ]; then
|
||||||
|
was=$(git show "$BEFORE:app/build.gradle" 2>/dev/null | code || true)
|
||||||
|
if [[ "$was" =~ ^[0-9]+$ ]] && [ "$was" -ge "$now" ]; then
|
||||||
|
echo "versionCode stayed at $now"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
# This run is created right after the push, so a PR build that started earlier may have pinned the old main.
|
||||||
|
bumped=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" --jq .created_at)
|
||||||
|
# A build can finish between the push and this run's creation; the push event carries the push time.
|
||||||
|
if [[ "${PUSHED_AT:-}" =~ ^[0-9]+$ ]]; then
|
||||||
|
pushed=$(date -u -d "@$PUSHED_AT" +%Y-%m-%dT%H:%M:%SZ)
|
||||||
|
[[ "$pushed" < "$bumped" ]] && bumped=$pushed
|
||||||
|
else
|
||||||
|
pushed=$(date -u -d "$bumped - 10 minutes" +%Y-%m-%dT%H:%M:%SZ)
|
||||||
|
fi
|
||||||
|
note() {
|
||||||
|
local number=$1
|
||||||
|
local marker="<!-- droiddeck-rebuild-$now -->"
|
||||||
|
gh api "repos/$GITHUB_REPOSITORY/issues/$number/comments?per_page=100" --jq '.[].body' | grep -qF "$marker" && return 0
|
||||||
|
gh api -X POST "repos/$GITHUB_REPOSITORY/issues/$number/comments" -f body="$marker
|
||||||
|
Main is now at versionCode $now, so this PR's test build no longer installs over current DroidDeck, and its last build is too old for GitHub to re-run. Push a commit or merge main to get a new test build." >/dev/null
|
||||||
|
}
|
||||||
|
latest() {
|
||||||
|
gh api "repos/$GITHUB_REPOSITORY/actions/workflows/build.yml/runs?event=pull_request&head_sha=$1&per_page=20" \
|
||||||
|
--jq '[.workflow_runs[] | select(.head_sha == "'"$1"'")] | sort_by(.created_at) | last // empty | [.id, .status, (.run_started_at // .created_at), .created_at, .updated_at] | @tsv'
|
||||||
|
}
|
||||||
|
consider() {
|
||||||
|
local number=$1 head=$2 built=$3 id status started created updated
|
||||||
|
IFS=$'\t' read -r id status started created updated <<<"$4"
|
||||||
|
if [[ "$started" > "$bumped" ]]; then
|
||||||
|
echo "PR #$number: build $id started after the bump"
|
||||||
|
elif ! gh api "repos/$GITHUB_REPOSITORY/pulls/$number" |
|
||||||
|
jq -e --arg head "$head" '.state == "open" and .draft == false and .base.ref == "main" and .head.sha == $head' >/dev/null; then
|
||||||
|
echo "PR #$number: moved on since the scan, its own build covers it"
|
||||||
|
elif gh run rerun "$id" -R "$GITHUB_REPOSITORY"; then
|
||||||
|
echo "PR #$number: rebuilding ${head:0:7} on main (versionCode $built -> $now)"
|
||||||
|
else
|
||||||
|
echo "::warning::PR #$number: could not rerun build $id"
|
||||||
|
# GitHub only re-runs a workflow within 30 days of its first run.
|
||||||
|
if [[ "$created" < "$(date -u -d '-30 days' +%Y-%m-%dT%H:%M:%SZ)" ]]; then
|
||||||
|
note "$number" || echo "::warning::PR #$number: could not leave a note"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
pending=()
|
||||||
|
declare -A seen=()
|
||||||
|
candidates() {
|
||||||
|
gh api --paginate "repos/Droid-Deck/DroidDeck-CI/releases?per_page=100" \
|
||||||
|
--jq '.[] | select(.tag_name | test("^pr-[0-9]+$")) | [(.tag_name | ltrimstr("pr-")), ((.body // "") | capture("(?m)^VersionCode: (?<v>[0-9]+)").v // "0")] | @tsv'
|
||||||
|
# The latest build of every open PR: one that started before the bump and was still running at it
|
||||||
|
# may have pinned the old main. This also covers a PR's first build and fork builds.
|
||||||
|
gh api --paginate -X GET "repos/$GITHUB_REPOSITORY/pulls" -f state=open -f base=main -f per_page=100 \
|
||||||
|
--jq '.[] | select(.draft | not) | [(.number | tostring), .head.sha] | @tsv' |
|
||||||
|
while IFS=$'\t' read -r number sha; do
|
||||||
|
run=$(latest "$sha")
|
||||||
|
[ -n "$run" ] || continue
|
||||||
|
IFS=$'\t' read -r _ status started _ updated <<<"$run"
|
||||||
|
if [[ "$started" < "$bumped" ]] && { [ "$status" != completed ] || [[ ! "$updated" < "$pushed" ]]; }; then
|
||||||
|
printf '%s\t?\n' "$number"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
}
|
||||||
|
found=$(mktemp)
|
||||||
|
candidates > "$found"
|
||||||
|
while IFS=$'\t' read -r number built; do
|
||||||
|
[ "$built" = "?" ] || [ "$built" -lt "$now" ] || continue
|
||||||
|
[ -z "${seen[$number]:-}" ] || continue
|
||||||
|
seen[$number]=1
|
||||||
|
pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$number") || continue
|
||||||
|
jq -e '.state == "open" and .draft == false and .base.ref == "main"' <<<"$pr" >/dev/null || continue
|
||||||
|
head=$(jq -r .head.sha <<<"$pr")
|
||||||
|
run=$(latest "$head")
|
||||||
|
if [ -z "$run" ]; then
|
||||||
|
echo "PR #$number: no build of ${head:0:7} to rerun"
|
||||||
|
elif [ "$(cut -f2 <<<"$run")" = completed ]; then
|
||||||
|
consider "$number" "$head" "$built" "$run"
|
||||||
|
else
|
||||||
|
pending+=("$number $head $built")
|
||||||
|
fi
|
||||||
|
done < "$found"
|
||||||
|
# Builds still running are polled together so one slow build cannot hold up the rest.
|
||||||
|
deadline=$((SECONDS + 150 * 60))
|
||||||
|
while [ ${#pending[@]} -gt 0 ] && [ "$SECONDS" -lt "$deadline" ]; do
|
||||||
|
sleep 60
|
||||||
|
left=()
|
||||||
|
for item in "${pending[@]}"; do
|
||||||
|
read -r number head built <<<"$item"
|
||||||
|
run=$(latest "$head")
|
||||||
|
if [ -n "$run" ] && [ "$(cut -f2 <<<"$run")" = completed ]; then
|
||||||
|
consider "$number" "$head" "$built" "$run"
|
||||||
|
else
|
||||||
|
left+=("$item")
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
pending=(${left[@]+"${left[@]}"})
|
||||||
|
done
|
||||||
|
for item in ${pending[@]+"${pending[@]}"}; do
|
||||||
|
echo "::warning::PR #${item%% *}: its build did not finish in time"
|
||||||
|
done
|
||||||
@@ -40,36 +40,19 @@ jobs:
|
|||||||
private-key: ${{ secrets.DROIDDECK_CI_APP_KEY }}
|
private-key: ${{ secrets.DROIDDECK_CI_APP_KEY }}
|
||||||
owner: Droid-Deck
|
owner: Droid-Deck
|
||||||
repositories: DroidDeck-CI
|
repositories: DroidDeck-CI
|
||||||
- name: Delete the test build
|
|
||||||
if: ${{ steps.state.outputs.closed == 'true' }}
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ steps.ci-token.outputs.token }}
|
|
||||||
PR_NUMBER: ${{ github.event.pull_request.number }}
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
retry() {
|
|
||||||
for attempt in 1 2 3 4; do
|
|
||||||
"$@" && return 0
|
|
||||||
[ "$attempt" = 4 ] || sleep $((attempt * 20))
|
|
||||||
done
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
existing=$(retry gh api --paginate "repos/Droid-Deck/DroidDeck-CI/releases?per_page=100" --jq '.[].tag_name')
|
|
||||||
found=0
|
|
||||||
for tag in "pr-$PR_NUMBER" "pr-$PR_NUMBER.0"; do
|
|
||||||
if grep -qxF "$tag" <<<"$existing"; then
|
|
||||||
retry gh release delete "$tag" -R Droid-Deck/DroidDeck-CI --yes --cleanup-tag
|
|
||||||
echo "Deleted $tag"
|
|
||||||
found=1
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
[ "$found" = 1 ] || echo "No test build for PR #$PR_NUMBER"
|
|
||||||
|
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
if: ${{ steps.state.outputs.closed == 'true' }}
|
if: ${{ steps.state.outputs.closed == 'true' }}
|
||||||
with:
|
with:
|
||||||
ref: main
|
ref: main
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
|
- name: Delete the test build unless main still needs it
|
||||||
|
if: ${{ steps.state.outputs.closed == 'true' }}
|
||||||
|
env:
|
||||||
|
SOURCE_GITHUB_TOKEN: ${{ github.token }}
|
||||||
|
CI_GITHUB_TOKEN: ${{ steps.ci-token.outputs.token }}
|
||||||
|
PR_NUMBER: ${{ github.event.pull_request.number }}
|
||||||
|
# A merged PR's build stays until a Preview build carries the merge; build.yml and the sweep remove it then.
|
||||||
|
run: python3 tools/release/retire_test_builds.py --pr "$PR_NUMBER"
|
||||||
- name: Retire the Discord PR announcement
|
- name: Retire the Discord PR announcement
|
||||||
if: ${{ steps.state.outputs.closed == 'true' }}
|
if: ${{ steps.state.outputs.closed == 'true' }}
|
||||||
env:
|
env:
|
||||||
|
|||||||
@@ -226,6 +226,8 @@ jobs:
|
|||||||
publish:
|
publish:
|
||||||
needs: [authorize, sign]
|
needs: [authorize, sign]
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
|
outputs:
|
||||||
|
keep: ${{ steps.publish.outputs.keep }}
|
||||||
permissions:
|
permissions:
|
||||||
actions: read
|
actions: read
|
||||||
contents: read
|
contents: read
|
||||||
@@ -322,12 +324,8 @@ jobs:
|
|||||||
cp pr-packs/* signed/ 2>/dev/null || true
|
cp pr-packs/* signed/ 2>/dev/null || true
|
||||||
gh release upload "$tag" signed/* -R "$repo" --clobber
|
gh release upload "$tag" signed/* -R "$repo" --clobber
|
||||||
gh release edit "$tag" -R "$repo" --title "PR #$PR_NUMBER" --notes "$notes" --prerelease
|
gh release edit "$tag" -R "$repo" --title "PR #$PR_NUMBER" --notes "$notes" --prerelease
|
||||||
keep=$(cd signed && ls | jq -R . | jq -sc .)
|
# The previous push's files stay until the catalog names these (the prune job), so a download started from the old catalog still finds its APK.
|
||||||
gh api "repos/$repo/releases/tags/$tag" |
|
echo "keep=$(cd signed && ls | jq -R . | jq -sc .)" >> "$GITHUB_OUTPUT"
|
||||||
jq -r --argjson keep "$keep" '.assets[] | select(.name as $n | $keep | index($n) | not) | .id' |
|
|
||||||
while IFS= read -r id; do
|
|
||||||
gh api --method DELETE "repos/$repo/releases/assets/$id" >/dev/null
|
|
||||||
done
|
|
||||||
|
|
||||||
published=$(gh release view "$tag" -R "$repo" --json tagName,assets)
|
published=$(gh release view "$tag" -R "$repo" --json tagName,assets)
|
||||||
jq -e --arg tag "$tag" '.tagName == $tag and (.assets | length) > 0' <<<"$published" >/dev/null
|
jq -e --arg tag "$tag" '.tagName == $tag and (.assets | length) > 0' <<<"$published" >/dev/null
|
||||||
@@ -417,3 +415,41 @@ jobs:
|
|||||||
if: ${{ always() && needs.publish.result != 'skipped' }}
|
if: ${{ always() && needs.publish.result != 'skipped' }}
|
||||||
uses: ./.github/workflows/update-catalog.yml
|
uses: ./.github/workflows/update-catalog.yml
|
||||||
secrets: inherit
|
secrets: inherit
|
||||||
|
|
||||||
|
prune:
|
||||||
|
needs: [authorize, publish, catalog]
|
||||||
|
if: ${{ always() && needs.publish.result == 'success' && needs.catalog.result == 'success' }}
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
timeout-minutes: 15
|
||||||
|
steps:
|
||||||
|
- uses: actions/create-github-app-token@v2
|
||||||
|
id: ci-token
|
||||||
|
with:
|
||||||
|
app-id: ${{ vars.DROIDDECK_CI_APP_ID }}
|
||||||
|
private-key: ${{ secrets.DROIDDECK_CI_APP_KEY }}
|
||||||
|
owner: Droid-Deck
|
||||||
|
repositories: DroidDeck-CI
|
||||||
|
- name: Remove the previous push's files
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ steps.ci-token.outputs.token }}
|
||||||
|
PR_NUMBER: ${{ needs.authorize.outputs.pr_number }}
|
||||||
|
KEEP: ${{ needs.publish.outputs.keep }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
repo=Droid-Deck/DroidDeck-CI
|
||||||
|
tag="pr-$PR_NUMBER"
|
||||||
|
# An app that read the catalog just before it changed may still be starting that download.
|
||||||
|
sleep 300
|
||||||
|
# Delete nothing the published catalog still names.
|
||||||
|
named=$(gh api -H "Accept: application/vnd.github.raw+json" "repos/$repo/contents/catalog.json?ref=main" |
|
||||||
|
jq -c --argjson pr "$PR_NUMBER" '[.tests[] | select(.pr == $pr) | .apks[].name]')
|
||||||
|
stale=$(jq -nr --argjson named "$named" --argjson keep "$KEEP" '$named - $keep | join(" ")')
|
||||||
|
if [ -n "$stale" ]; then
|
||||||
|
echo "::warning::The catalog still names $stale; keeping every file of $tag"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
gh api "repos/$repo/releases/tags/$tag" |
|
||||||
|
jq -r --argjson keep "$KEEP" '.assets[] | select(.name as $n | $keep | index($n) | not) | .id' |
|
||||||
|
while IFS= read -r id; do
|
||||||
|
gh api --method DELETE "repos/$repo/releases/assets/$id" >/dev/null
|
||||||
|
done
|
||||||
@@ -26,32 +26,18 @@ jobs:
|
|||||||
private-key: ${{ secrets.DROIDDECK_CI_APP_KEY }}
|
private-key: ${{ secrets.DROIDDECK_CI_APP_KEY }}
|
||||||
owner: Droid-Deck
|
owner: Droid-Deck
|
||||||
repositories: DroidDeck-CI
|
repositories: DroidDeck-CI
|
||||||
- name: Delete test builds whose PR is no longer open
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
ref: main
|
||||||
|
persist-credentials: false
|
||||||
|
- name: Delete test builds of closed PRs, and of merged PRs a Preview build carries
|
||||||
env:
|
env:
|
||||||
CI_TOKEN: ${{ steps.ci-token.outputs.token }}
|
SOURCE_GITHUB_TOKEN: ${{ github.token }}
|
||||||
GH_TOKEN: ${{ github.token }}
|
CI_GITHUB_TOKEN: ${{ steps.ci-token.outputs.token }}
|
||||||
run: |
|
run: python3 tools/release/retire_test_builds.py
|
||||||
set -euo pipefail
|
|
||||||
retry() {
|
catalog:
|
||||||
for attempt in 1 2 3 4; do
|
needs: sweep
|
||||||
"$@" && return 0
|
if: ${{ always() }}
|
||||||
[ "$attempt" = 4 ] || sleep $((attempt * 20))
|
uses: ./.github/workflows/update-catalog.yml
|
||||||
done
|
secrets: inherit
|
||||||
return 1
|
|
||||||
}
|
|
||||||
tags=$(GH_TOKEN="$CI_TOKEN" retry gh api --paginate "repos/Droid-Deck/DroidDeck-CI/releases?per_page=100" --jq '.[].tag_name' |
|
|
||||||
grep -E '^pr-[0-9]+(\.0)?$' || true)
|
|
||||||
failed=0
|
|
||||||
for tag in $tags; do
|
|
||||||
number=${tag#pr-}
|
|
||||||
number=${number%.0}
|
|
||||||
state=$(retry gh api "repos/$GITHUB_REPOSITORY/pulls/$number" --jq .state) || { failed=1; continue; }
|
|
||||||
if [ "$state" != open ]; then
|
|
||||||
if GH_TOKEN="$CI_TOKEN" retry gh release delete "$tag" -R Droid-Deck/DroidDeck-CI --yes --cleanup-tag; then
|
|
||||||
echo "Deleted $tag (PR #$number is $state)"
|
|
||||||
else
|
|
||||||
failed=1
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
exit "$failed"
|
|
||||||
@@ -36,3 +36,4 @@ __pycache__/
|
|||||||
app/src/main/assets/directaudio/
|
app/src/main/assets/directaudio/
|
||||||
app/src/main/assets/hybris/
|
app/src/main/assets/hybris/
|
||||||
/tools/vr/out/
|
/tools/vr/out/
|
||||||
|
app/src/main/resources/rockstar/helpers/
|
||||||
@@ -1,3 +1,13 @@
|
|||||||
# Rules
|
# Rules
|
||||||
|
|
||||||
- Comments should be rare, factual, and explain only non-obvious external constraints or business invariants.
|
- Comments should be rare, factual, and explain only non-obvious external constraints or business invariants.
|
||||||
|
|
||||||
|
# Working on the device
|
||||||
|
|
||||||
|
- `dd-lab-build` builds only committed work. Check `git status` and `gh api user` for the identity before committing; if `git config user.name` is empty, use the `gh` login's name and noreply email for this repo, never a guess.
|
||||||
|
- Do not commit or start a build in the same step: a build started next to a failed commit fails too. Commit first, check it, then build.
|
||||||
|
- Uncommitted changes in the tree may not be yours. Read `git diff` before committing them and tell the user what they do.
|
||||||
|
- If `dd-lab-build` says "could not read DroidDeck's state", loopback adb is down and `$ADB_SERIAL` is stale. Run `adb devices`; the port changes whenever wireless debugging is toggled. Ask the user to turn it on rather than retrying.
|
||||||
|
- A build that "did not start" can be adb, not the app. Read `~/.cache/dd-lab-build.json` and `.log` for the real reason; they can be stale from an earlier build, so compare their times with `date`.
|
||||||
|
- Run `dd-lab-build` with `run_in_background` and read its output file. A foreground `sleep` is blocked; wait with Monitor and an until-loop.
|
||||||
|
- The build restarts DroidDeck and ends your process. A turn that ends this way is not a failure.
|
||||||
@@ -25,7 +25,7 @@ DroidDeck brings the SteamOS experience to Android: Steam Gaming Mode, full Linu
|
|||||||
|
|
||||||
<p align="center"><img src="docs/media/steam-to-desktop.gif" width="100%" alt="On a Retroid Pocket Duo: Play Steam from the DroidDeck launcher, open Pac-Man in Steam Big Picture and play it, exit the game, then Switch to Desktop from the Power menu"></p>
|
<p align="center"><img src="docs/media/steam-to-desktop.gif" width="100%" alt="On a Retroid Pocket Duo: Play Steam from the DroidDeck launcher, open Pac-Man in Steam Big Picture and play it, exit the game, then Switch to Desktop from the Power menu"></p>
|
||||||
|
|
||||||
> DroidDeck has no website. Only download it from this repository's [Releases](https://github.com/Droid-Deck/DroidDeck/releases).
|
> The official website is [droid-deck.dev](https://droid-deck.dev). Only download DroidDeck from this repository's [Releases](https://github.com/Droid-Deck/DroidDeck/releases).
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<img src="docs/releases/media/0.6.7/library.gif" width="49%" alt="The Library switching source chips, changing the card size and opening the Filter menu">
|
<img src="docs/releases/media/0.6.7/library.gif" width="49%" alt="The Library switching source chips, changing the card size and opening the Filter menu">
|
||||||
@@ -80,7 +80,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
|
|||||||
- The proot fast path orders bindings like [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later).
|
- The proot fast path orders bindings like [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later).
|
||||||
- DiRT 3 and DiRT Showdown keep their telemetry socket the way RoccoC's DiRTTelemetryErrorFix (MIT) does, based on the fix by Carsten Gottschling.
|
- DiRT 3 and DiRT Showdown keep their telemetry socket the way RoccoC's DiRTTelemetryErrorFix (MIT) does, based on the fix by Carsten Gottschling.
|
||||||
- Zink on PowerVR keeps colour textures in colour with Icenowy Zheng's upstream [Mesa](https://gitlab.freedesktop.org/mesa/mesa) fix d55418dae7 (MIT), carried as a runtime patch.
|
- Zink on PowerVR keeps colour textures in colour with Icenowy Zheng's upstream [Mesa](https://gitlab.freedesktop.org/mesa/mesa) fix d55418dae7 (MIT), carried as a runtime patch.
|
||||||
- Games and AppImage, Flatpak and Snap programs such as emulators use [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's per render pass memory choice. The Steam client and Chromium-based apps keep `TU_DEBUG=sysmem`.
|
- Games and AppImage, Flatpak and Snap programs such as emulators use `TU_DEBUG=sysmem` by default, as does the Steam client. Turnip sysmem rendering can be turned off in Performance settings, except with the Adreno 710/720 driver, which always uses it.
|
||||||
- Black Ops III and Dark Souls Remastered start without [umu-protonfixes](https://github.com/Open-Wine-Components/umu-protonfixes) (BSD-2-Clause), whose `311210.py` and `570940.py` fail under ARM64 Proton.
|
- Black Ops III and Dark Souls Remastered start without [umu-protonfixes](https://github.com/Open-Wine-Components/umu-protonfixes) (BSD-2-Clause), whose `311210.py` and `570940.py` fail under ARM64 Proton.
|
||||||
- [ReSkate](https://github.com/Dingo-Shenanigans/ReSkate) (GPL-3.0) by Dingo Shenanigans uses the launch option from its README and D3D12 feature level 12_1.
|
- [ReSkate](https://github.com/Dingo-Shenanigans/ReSkate) (GPL-3.0) by Dingo Shenanigans uses the launch option from its README and D3D12 feature level 12_1.
|
||||||
- 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).
|
- 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).
|
||||||
@@ -90,14 +90,15 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
|
|||||||
<details>
|
<details>
|
||||||
<summary><b>Stores</b></summary>
|
<summary><b>Stores</b></summary>
|
||||||
|
|
||||||
- Epic Games and GOG build on [Phobos](https://github.com/phobos665)'s adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl). GOG install script registry entries are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher) (GPL-3.0) reads them.
|
- Epic Games and GOG build on [Phobos](https://github.com/phobos665)'s adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl). GOG install script registry entries are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher) (GPL-3.0) reads them. GOG cloud storage requests send the Galaxy communication-service User-Agent that gogdl and [Lutris](https://github.com/lutris/lutris) (GPL-3.0) send.
|
||||||
- Epic's official Linux launcher preview runs through FEX. That setup is outside Epic's listed Linux support.
|
- Epic's official Linux launcher preview runs through FEX. That setup is outside Epic's listed Linux support.
|
||||||
|
- The launcher's .deb gets the WebKitGTK and GTK 3 libraries it needs from unmodified [Debian](https://www.debian.org) 13 packages, following [@zooluis](https://github.com/zooluis)'s research in [#2268](https://github.com/Droid-Deck/DroidDeck/pull/2268).
|
||||||
- Battle.net is by [@kayakyakr](https://github.com/kayakyakr). It runs Blizzard's own client in Proton (downloaded from Blizzard, not included) and shows key art from the [Battle.net Shop](https://shop.battle.net). Without Steam, its games see the pad as an Xbox 360 controller via `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`.
|
- Battle.net is by [@kayakyakr](https://github.com/kayakyakr). It runs Blizzard's own client in Proton (downloaded from Blizzard, not included) and shows key art from the [Battle.net Shop](https://shop.battle.net). Without Steam, its games see the pad as an Xbox 360 controller via `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`.
|
||||||
- The EA store follows the EA app's protocols as documented by [ArmchairDevelopers](https://github.com/ArmchairDevelopers)' [Maxima](https://github.com/ArmchairDevelopers/Maxima) (GPL-3.0): sign-in, the GraphQL queries (included verbatim, since EA matches them by hash), build archives, online activation licences and the LSX game endpoint. The code is DroidDeck's own.
|
- The EA store follows the EA app's protocols as documented by [ArmchairDevelopers](https://github.com/ArmchairDevelopers)' [Maxima](https://github.com/ArmchairDevelopers/Maxima) (GPL-3.0): sign-in, the GraphQL queries (included verbatim, since EA matches them by hash), build archives, online activation licences and the LSX game endpoint. The code is DroidDeck's own.
|
||||||
- Battle.net installs drive Blizzard's Agent the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) does, with requests from [wowdev.wiki](https://wowdev.wiki/Agent). Read without taking code: [@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.
|
- Battle.net installs drive Blizzard's Agent the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) does, with requests from [wowdev.wiki](https://wowdev.wiki/Agent). Read without taking code: [@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.
|
||||||
- World of Warcraft addon imports replace an addon's folder from a temporary copy, as [WowUp](https://github.com/WowUp/WowUp) does, and read flavour folders the way [WoWDeck](https://github.com/sigboe/wowdeck) does. No code from either is used.
|
- World of Warcraft addon imports replace an addon's folder from a temporary copy, as [WowUp](https://github.com/WowUp/WowUp) does, and read flavour folders the way [WoWDeck](https://github.com/sigboe/wowdeck) does. No code from either is used.
|
||||||
- The World of Warcraft addon Download window searches [WoWInterface](https://www.wowinterface.com) through its MMOUI API. [CurseForge](https://www.curseforge.com/wow) opens in the user's browser, with no API and no key.
|
- The World of Warcraft addon Download window searches [WoWInterface](https://www.wowinterface.com) through its MMOUI API. [CurseForge](https://www.curseforge.com/wow) opens in the user's browser, with no API and no key.
|
||||||
- Xbox games load [@domsvoboda](https://github.com/domsvoboda)'s [xodus-nexus](https://github.com/domsvoboda/xodus-nexus) modules (LGPL-2.1-or-later), including `wintypes.dll`. Minecraft's GameInput setup was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT).
|
- Xbox games load [@domsvoboda](https://github.com/domsvoboda)'s [xodus-nexus](https://github.com/domsvoboda/xodus-nexus) modules (LGPL-2.1-or-later), including `wintypes.dll`. Content licensing sends delegation-compact device tickets in the licensing wire form, following the [nexus-backend](https://github.com/domsvoboda/nexus-backend) commit `27c335e`. Minecraft's GameInput setup was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT).
|
||||||
- The Xbox Cloud Gaming player uses the WebRTC client of [@unknownskl](https://github.com/unknownskl)'s [Greenlight](https://github.com/unknownskl/greenlight) (MIT), and its offer tweaks and sharpening follow [@redphx](https://github.com/redphx)'s [Better xCloud](https://github.com/redphx/better-xcloud) (MIT). See `tools/xcloud-player/NOTICE.md`.
|
- The Xbox Cloud Gaming player uses the WebRTC client of [@unknownskl](https://github.com/unknownskl)'s [Greenlight](https://github.com/unknownskl/greenlight) (MIT), and its offer tweaks and sharpening follow [@redphx](https://github.com/redphx)'s [Better xCloud](https://github.com/redphx/better-xcloud) (MIT). See `tools/xcloud-player/NOTICE.md`.
|
||||||
- The itch.io butler pack ships butler's `7z.so`, itch.io's build of [7-Zip](https://www.7-zip.org) by Igor Pavlov (LGPL-2.1, unRAR restriction on RAR code), unmodified. Other archives use Apache Commons Compress and the runtime's bsdtar (libarchive).
|
- The itch.io butler pack ships butler's `7z.so`, itch.io's build of [7-Zip](https://www.7-zip.org) by Igor Pavlov (LGPL-2.1, unRAR restriction on RAR code), unmodified. Other archives use Apache Commons Compress and the runtime's bsdtar (libarchive).
|
||||||
- The Store uses [Flatpak](https://github.com/flatpak/flatpak) (LGPL-2.1) through DroidDeck's own bubblewrap shim. Chromium and Electron apps start directly, since [zypak](https://github.com/refi64/zypak) by [@refi64](https://github.com/refi64) (BSD-3-Clause) always uses Flatpak's spawn portal.
|
- The Store uses [Flatpak](https://github.com/flatpak/flatpak) (LGPL-2.1) through DroidDeck's own bubblewrap shim. Chromium and Electron apps start directly, since [zypak](https://github.com/refi64/zypak) by [@refi64](https://github.com/refi64) (BSD-3-Clause) always uses Flatpak's spawn portal.
|
||||||
|
|||||||
@@ -141,6 +141,7 @@ android {
|
|||||||
buildConfigField "boolean", "CI_BUILD", "${ciBuild}"
|
buildConfigField "boolean", "CI_BUILD", "${ciBuild}"
|
||||||
buildConfigField "String", "RELEASE_SIGNER", "\"${releaseSigner}\""
|
buildConfigField "String", "RELEASE_SIGNER", "\"${releaseSigner}\""
|
||||||
buildConfigField "long", "COMMIT_TIME", "${commitTime}L * 1000L"
|
buildConfigField "long", "COMMIT_TIME", "${commitTime}L * 1000L"
|
||||||
|
buildConfigField "String", "UPDATE_CATALOG_BRANCH", "\"${(System.getenv("DROIDDECK_UPDATE_CATALOG_BRANCH") ?: "main").with { it ==~ /[A-Za-z0-9._-]+/ ? it : "main" }}\""
|
||||||
buildConfigField "String", "VARIANT_SUFFIXES", "\"${variantSuffixes}\""
|
buildConfigField "String", "VARIANT_SUFFIXES", "\"${variantSuffixes}\""
|
||||||
buildConfigField "String", "SGDB_API_KEY", "\"${System.getenv("SGDB_API_KEY") ?: project.findProperty("sgdbApiKey") ?: ""}\""
|
buildConfigField "String", "SGDB_API_KEY", "\"${System.getenv("SGDB_API_KEY") ?: project.findProperty("sgdbApiKey") ?: ""}\""
|
||||||
buildConfigField "String", "DESKTOP_KDE_TAG", "\"${desktopKde.DESKTOP_KDE_TAG}\""
|
buildConfigField "String", "DESKTOP_KDE_TAG", "\"${desktopKde.DESKTOP_KDE_TAG}\""
|
||||||
@@ -277,6 +278,8 @@ def stageRuntimeAssets = tasks.register('stageRuntimeAssets', Sync) {
|
|||||||
dependsOn(stageSessionScripts)
|
dependsOn(stageSessionScripts)
|
||||||
from(layout.projectDirectory.dir('src/main/assets')) { exclude 'pulseaudio.tzst' }
|
from(layout.projectDirectory.dir('src/main/assets')) { exclude 'pulseaudio.tzst' }
|
||||||
from(rootProject.file('tools/linuxfs/innoextract'))
|
from(rootProject.file('tools/linuxfs/innoextract'))
|
||||||
|
from(rootProject.file('tools')) { include 'droiddeckctl', 'adb_device.py', 'proot_profile.py'; into('agent/ctl') }
|
||||||
|
from(rootProject.file('docs/agent-control.md')) { into('agent/ctl') }
|
||||||
from(layout.buildDirectory.dir('prepared-assets'))
|
from(layout.buildDirectory.dir('prepared-assets'))
|
||||||
into(runtimeAssetsDir)
|
into(runtimeAssetsDir)
|
||||||
}
|
}
|
||||||
@@ -292,6 +295,16 @@ if (uvcDir) {
|
|||||||
}
|
}
|
||||||
tasks.named('preBuild').configure { dependsOn(stageRuntimeAssets) }
|
tasks.named('preBuild').configure { dependsOn(stageRuntimeAssets) }
|
||||||
|
|
||||||
|
android.sourceSets.main.java.srcDir(rootProject.file('shortcuts/src/protocol/java'))
|
||||||
|
def stageShortcuts = tasks.register('stageShortcuts', Copy) {
|
||||||
|
dependsOn(':shortcuts:assembleRelease')
|
||||||
|
from(project(':shortcuts').layout.buildDirectory.file('outputs/apk/release/shortcuts-release.apk'))
|
||||||
|
into(layout.buildDirectory.dir('shortcutsAssets'))
|
||||||
|
rename { 'shortcuts.apk' }
|
||||||
|
}
|
||||||
|
android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('shortcutsAssets'))
|
||||||
|
tasks.named('preBuild').configure { dependsOn(stageShortcuts) }
|
||||||
|
|
||||||
def stageGogNotices = tasks.register('stageGogNotices', Copy) {
|
def stageGogNotices = tasks.register('stageGogNotices', Copy) {
|
||||||
from(layout.projectDirectory.dir('src/main/rust/stores/vendor/xdelta3')) { include 'LICENSE', 'README.droiddeck.md' }
|
from(layout.projectDirectory.dir('src/main/rust/stores/vendor/xdelta3')) { include 'LICENSE', 'README.droiddeck.md' }
|
||||||
into(layout.buildDirectory.dir('gogNotices/licenses/xdelta3'))
|
into(layout.buildDirectory.dir('gogNotices/licenses/xdelta3'))
|
||||||
@@ -380,6 +393,11 @@ dependencies {
|
|||||||
implementation 'androidx.activity:activity-compose:1.8.2'
|
implementation 'androidx.activity:activity-compose:1.8.2'
|
||||||
implementation 'androidx.compose.material:material-icons-extended'
|
implementation 'androidx.compose.material:material-icons-extended'
|
||||||
implementation 'io.coil-kt:coil-compose:2.6.0'
|
implementation 'io.coil-kt:coil-compose:2.6.0'
|
||||||
|
implementation 'io.noties.markwon:core:4.6.2'
|
||||||
|
implementation 'io.noties.markwon:ext-strikethrough:4.6.2'
|
||||||
|
implementation 'io.noties.markwon:ext-tables:4.6.2'
|
||||||
|
implementation 'io.noties.markwon:ext-tasklist:4.6.2'
|
||||||
|
implementation 'com.atlassian.commonmark:commonmark-ext-autolink:0.13.0'
|
||||||
implementation 'com.caverock:androidsvg-aar:1.4'
|
implementation 'com.caverock:androidsvg-aar:1.4'
|
||||||
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'
|
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'
|
||||||
implementation 'com.flyfishxu:kadb-android:1.2.1'
|
implementation 'com.flyfishxu:kadb-android:1.2.1'
|
||||||
@@ -387,11 +405,14 @@ dependencies {
|
|||||||
implementation 'androidx.camera:camera-camera2:1.4.2'
|
implementation 'androidx.camera:camera-camera2:1.4.2'
|
||||||
implementation 'androidx.camera:camera-lifecycle:1.4.2'
|
implementation 'androidx.camera:camera-lifecycle:1.4.2'
|
||||||
implementation 'androidx.webkit:webkit:1.12.1'
|
implementation 'androidx.webkit:webkit:1.12.1'
|
||||||
|
implementation 'androidx.palette:palette:1.0.0'
|
||||||
implementation 'io.github.webrtc-sdk:android:125.6422.07'
|
implementation 'io.github.webrtc-sdk:android:125.6422.07'
|
||||||
implementation("com.google.mediapipe:tasks-vision:${trackingPack.MEDIAPIPE_VERSION}") {
|
implementation("com.google.mediapipe:tasks-vision:${trackingPack.MEDIAPIPE_VERSION}") {
|
||||||
exclude group: 'com.google.auto.value', module: 'auto-value'
|
exclude group: 'com.google.auto.value', module: 'auto-value'
|
||||||
}
|
}
|
||||||
implementation 'com.google.zxing:core:3.5.3'
|
implementation 'com.google.zxing:core:3.5.3'
|
||||||
|
implementation 'androidx.media3:media3-exoplayer:1.3.1'
|
||||||
|
implementation 'androidx.media3:media3-session:1.3.1'
|
||||||
|
|
||||||
testImplementation 'junit:junit:4.13.2'
|
testImplementation 'junit:junit:4.13.2'
|
||||||
testImplementation 'org.robolectric:robolectric:4.16.1'
|
testImplementation 'org.robolectric:robolectric:4.16.1'
|
||||||
|
|||||||
@@ -18,8 +18,15 @@
|
|||||||
<action android:name="android.intent.action.MAIN" />
|
<action android:name="android.intent.action.MAIN" />
|
||||||
<category android:name="android.intent.category.SECONDARY_HOME" />
|
<category android:name="android.intent.category.SECONDARY_HOME" />
|
||||||
</intent>
|
</intent>
|
||||||
|
<intent>
|
||||||
|
<action android:name="org.adw.launcher.THEMES" />
|
||||||
|
</intent>
|
||||||
|
<intent>
|
||||||
|
<action android:name="com.novalauncher.THEME" />
|
||||||
|
</intent>
|
||||||
</queries>
|
</queries>
|
||||||
|
|
||||||
|
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
|
||||||
<uses-permission android:name="android.permission.REORDER_TASKS" />
|
<uses-permission android:name="android.permission.REORDER_TASKS" />
|
||||||
<uses-permission android:name="android.permission.INTERNET" />
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
|
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
|
||||||
@@ -82,21 +89,11 @@
|
|||||||
android:label="@string/steam_wall_label"
|
android:label="@string/steam_wall_label"
|
||||||
android:theme="@android:style/Theme.Translucent.NoTitleBar"
|
android:theme="@android:style/Theme.Translucent.NoTitleBar"
|
||||||
android:exported="true" />
|
android:exported="true" />
|
||||||
<service android:name=".input.HomeButtonService"
|
<service android:name=".input.ShortcutsRelay" android:exported="true">
|
||||||
android:label="@string/integration_shortcuts_service"
|
|
||||||
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
|
|
||||||
android:exported="true">
|
|
||||||
<intent-filter>
|
<intent-filter>
|
||||||
<action android:name="android.accessibilityservice.AccessibilityService" />
|
<action android:name="com.droiddeck.shortcuts.RELAY" />
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
<meta-data android:name="android.accessibilityservice" android:resource="@xml/home_button_service" />
|
|
||||||
</service>
|
</service>
|
||||||
<receiver android:name=".core.ShortcutsListingReceiver" android:exported="false"
|
|
||||||
android:process=":shortcuts_sync">
|
|
||||||
<intent-filter>
|
|
||||||
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
|
|
||||||
</intent-filter>
|
|
||||||
</receiver>
|
|
||||||
<meta-data android:name="com.oculus.supportedDevices" android:value="quest2|quest3|quest3s" />
|
<meta-data android:name="com.oculus.supportedDevices" android:value="quest2|quest3|quest3s" />
|
||||||
<activity android:name=".QuestXrActivity" android:exported="true" android:launchMode="singleTask"
|
<activity android:name=".QuestXrActivity" android:exported="true" android:launchMode="singleTask"
|
||||||
android:permission="android.permission.DUMP"
|
android:permission="android.permission.DUMP"
|
||||||
@@ -111,6 +108,17 @@
|
|||||||
</intent-filter>
|
</intent-filter>
|
||||||
</activity>
|
</activity>
|
||||||
|
|
||||||
|
<activity
|
||||||
|
android:name=".DeviceCodeActivity"
|
||||||
|
android:exported="false"
|
||||||
|
android:launchMode="singleTask"
|
||||||
|
android:taskAffinity="${applicationId}.devicecode"
|
||||||
|
android:excludeFromRecents="true"
|
||||||
|
android:supportsPictureInPicture="true"
|
||||||
|
android:resizeableActivity="true"
|
||||||
|
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density|keyboard|keyboardHidden|navigation"
|
||||||
|
android:theme="@style/AppTheme" />
|
||||||
|
|
||||||
<activity
|
<activity
|
||||||
android:name=".PairingGuideActivity"
|
android:name=".PairingGuideActivity"
|
||||||
android:exported="false"
|
android:exported="false"
|
||||||
@@ -134,6 +142,7 @@
|
|||||||
<category android:name="android.intent.category.BROWSABLE" />
|
<category android:name="android.intent.category.BROWSABLE" />
|
||||||
<category android:name="android.intent.category.CAR_LAUNCHER" />
|
<category android:name="android.intent.category.CAR_LAUNCHER" />
|
||||||
<data android:scheme="droiddeck" android:host="game" />
|
<data android:scheme="droiddeck" android:host="game" />
|
||||||
|
<data android:scheme="droiddeck" android:host="soundtrack" />
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
<intent-filter>
|
<intent-filter>
|
||||||
<action android:name="android.intent.action.CREATE_SHORTCUT" />
|
<action android:name="android.intent.action.CREATE_SHORTCUT" />
|
||||||
@@ -304,6 +313,10 @@
|
|||||||
android:theme="@style/SessionTheme" />
|
android:theme="@style/SessionTheme" />
|
||||||
|
|
||||||
<service android:name=".agent.AgentHostService" android:exported="false" />
|
<service android:name=".agent.AgentHostService" android:exported="false" />
|
||||||
|
<service
|
||||||
|
android:name=".update.UpdateWatch"
|
||||||
|
android:permission="android.permission.BIND_JOB_SERVICE"
|
||||||
|
android:exported="false" />
|
||||||
<service
|
<service
|
||||||
android:name=".session.SessionService"
|
android:name=".session.SessionService"
|
||||||
android:exported="false"
|
android:exported="false"
|
||||||
@@ -327,6 +340,14 @@
|
|||||||
android:name=".sync.SyncthingService"
|
android:name=".sync.SyncthingService"
|
||||||
android:exported="false"
|
android:exported="false"
|
||||||
android:foregroundServiceType="dataSync" />
|
android:foregroundServiceType="dataSync" />
|
||||||
|
<service
|
||||||
|
android:name=".playback.SoundtrackService"
|
||||||
|
android:exported="true"
|
||||||
|
android:foregroundServiceType="mediaPlayback">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="androidx.media3.session.MediaSessionService" />
|
||||||
|
</intent-filter>
|
||||||
|
</service>
|
||||||
<provider
|
<provider
|
||||||
android:name="androidx.core.content.FileProvider"
|
android:name="androidx.core.content.FileProvider"
|
||||||
android:authorities="${applicationId}.logs"
|
android:authorities="${applicationId}.logs"
|
||||||
|
|||||||
@@ -1,27 +1,52 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
# GitHub sign-in through Android's browser, with the one-time code typed in for the person.
|
# Starts GitHub's device login, floats its code over Android's browser and opens the approval page.
|
||||||
serial=${ADB_SERIAL:-127.0.0.1:5555}
|
url=https://github.com/login/device
|
||||||
display=${DD_BROWSER_DISPLAY:-0}
|
inbox=${DD_AGENT_INBOX:-}
|
||||||
adb connect "$serial" >/dev/null 2>&1
|
|
||||||
|
# DroidDeck takes $inbox/device-code within a few seconds when it can float the code.
|
||||||
|
float_code() {
|
||||||
|
[ -n "$inbox" ] && [ -d "$inbox" ] || return 1
|
||||||
|
rm -f "$inbox/device-code.result"
|
||||||
|
printf '%s %s\n' "$1" "$url" > "$inbox/device-code.part" && mv -f "$inbox/device-code.part" "$inbox/device-code" || return 1
|
||||||
|
i=0
|
||||||
|
while [ $i -lt 40 ] && [ -e "$inbox/device-code" ]; do
|
||||||
|
sleep 0.2
|
||||||
|
i=$((i + 1))
|
||||||
|
done
|
||||||
|
if [ -e "$inbox/device-code" ]; then
|
||||||
|
rm -f "$inbox/device-code"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
# DroidDeck writes "ok" or "failed" once it has tried to open the page; no answer counts as failed.
|
||||||
|
i=0
|
||||||
|
while [ $i -lt 50 ] && [ ! -e "$inbox/device-code.result" ]; do
|
||||||
|
sleep 0.2
|
||||||
|
i=$((i + 1))
|
||||||
|
done
|
||||||
|
result=$(cat "$inbox/device-code.result" 2>/dev/null)
|
||||||
|
rm -f "$inbox/device-code.result"
|
||||||
|
[ "$result" = ok ]
|
||||||
|
}
|
||||||
|
|
||||||
coproc GH { BROWSER=true gh auth login --hostname github.com --git-protocol https --web 2>&1; }
|
coproc GH { BROWSER=true gh auth login --hostname github.com --git-protocol https --web 2>&1; }
|
||||||
# bash drops GH and GH_PID once gh exits, which can be before the loop reads its last line.
|
gh_pid=$GH_PID
|
||||||
ghpid=$GH_PID
|
|
||||||
exec {ghout}<&"${GH[0]}" {ghin}>&"${GH[1]}"
|
exec {ghout}<&"${GH[0]}" {ghin}>&"${GH[1]}"
|
||||||
typed=
|
shown=
|
||||||
while IFS= read -r line <&"$ghout"; do
|
while IFS= read -r line <&"$ghout"; do
|
||||||
printf '%s\n' "$line"
|
|
||||||
code=$(grep -oE '[A-Z0-9]{4}-[A-Z0-9]{4}' <<<"$line" | head -1)
|
code=$(grep -oE '[A-Z0-9]{4}-[A-Z0-9]{4}' <<<"$line" | head -1)
|
||||||
if [ -n "$code" ] && [ -z "$typed" ]; then
|
# gh's own prompts would push the code out of the one line the setup card shows.
|
||||||
typed=1
|
case "$line" in
|
||||||
|
*"one-time code"* | *"Press Enter"* | *"Open this URL"*) ;;
|
||||||
|
*) printf '%s\n' "$line" ;;
|
||||||
|
esac
|
||||||
|
if [ -n "$code" ] && [ -z "$shown" ]; then
|
||||||
|
shown=1
|
||||||
echo >&"$ghin"
|
echo >&"$ghin"
|
||||||
adb -s "$serial" shell "am start --display $display -a android.intent.action.VIEW -d https://github.com/login/device" >/dev/null 2>&1
|
printf 'GitHub device code: %s · github.com/login/device\n' "$code"
|
||||||
# Chrome drops characters from `input text` and from fast key events on this page.
|
float_code "$code" || android-open "$url"
|
||||||
keys=
|
|
||||||
for ((i = 0; i < ${#code}; i++)); do
|
|
||||||
c=${code:i:1}
|
|
||||||
[ "$c" = - ] || keys+="input -d $display keyevent KEYCODE_$c; sleep 0.4; "
|
|
||||||
done
|
|
||||||
(sleep 7; adb -s "$serial" shell "$keys" >/dev/null 2>&1) &
|
|
||||||
fi
|
fi
|
||||||
done
|
done
|
||||||
wait "$ghpid"
|
wait "$gh_pid"
|
||||||
|
status=$?
|
||||||
|
[ -n "$shown" ] && [ -n "$inbox" ] && [ -d "$inbox" ] && : > "$inbox/device-code"
|
||||||
|
exit $status
|
||||||
Executable
+2
@@ -0,0 +1,2 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
exec python3 /root/.local/share/droiddeck/ctl/droiddeckctl "$@"
|
||||||
Binary file not shown.
@@ -37,6 +37,7 @@
|
|||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
#include <sys/eventfd.h>
|
#include <sys/eventfd.h>
|
||||||
|
#include <sys/file.h>
|
||||||
#include <sys/inotify.h>
|
#include <sys/inotify.h>
|
||||||
#include <sys/ioctl.h>
|
#include <sys/ioctl.h>
|
||||||
#include <sys/mman.h>
|
#include <sys/mman.h>
|
||||||
@@ -157,6 +158,8 @@ struct FakeController {
|
|||||||
bool closed = false;
|
bool closed = false;
|
||||||
bool needs_keyframe = true;
|
bool needs_keyframe = true;
|
||||||
bool mouse = false;
|
bool mouse = false;
|
||||||
|
int playing_ff = -1;
|
||||||
|
pid_t owner = getpid();
|
||||||
|
|
||||||
~FakeController() {
|
~FakeController() {
|
||||||
if (ring) munmap(ring, mapping_size);
|
if (ring) munmap(ring, mapping_size);
|
||||||
@@ -195,6 +198,7 @@ static constexpr size_t kSnapshotButtonCount =
|
|||||||
|
|
||||||
namespace Logger {
|
namespace Logger {
|
||||||
void init();
|
void init();
|
||||||
|
void log(const char *message, ...);
|
||||||
}
|
}
|
||||||
|
|
||||||
static void controller_fork_prepare();
|
static void controller_fork_prepare();
|
||||||
@@ -286,6 +290,68 @@ static bool fake_vibration_enabled() { return config().vibration_enabled; }
|
|||||||
static bool fake_xbox360_identity() { return config().xbox360_identity; }
|
static bool fake_xbox360_identity() { return config().xbox360_identity; }
|
||||||
static bool fake_uinput_enabled() { return config().uinput_enabled; }
|
static bool fake_uinput_enabled() { return config().uinput_enabled; }
|
||||||
|
|
||||||
|
static bool process_is_steam_client();
|
||||||
|
|
||||||
|
// Steam and its Remote Play client write the same shared slots; the caller's mutex serialises its own threads.
|
||||||
|
// Without the lock Steam stays the only writer, as before streaming_client could open these devices. The wait
|
||||||
|
// is bounded because a session freeze can stop the holder, and callers wait with controller_mutex held.
|
||||||
|
class ProcessSlotLock {
|
||||||
|
public:
|
||||||
|
ProcessSlotLock(int &fd, const char *name, int timeout_ms) : fd_(fd) {
|
||||||
|
int saved_errno = errno;
|
||||||
|
if (fd_ < 0) {
|
||||||
|
std::string path = std::string(fake_hook_dir()) + "/." + name + ".lock";
|
||||||
|
fd_ = fd = static_cast<int>(syscall(SYS_openat, AT_FDCWD, path.c_str(), O_CREAT | O_RDWR | O_CLOEXEC, 0600));
|
||||||
|
}
|
||||||
|
int error = fd_ < 0 ? errno : 0;
|
||||||
|
if (fd_ >= 0) {
|
||||||
|
struct timespec start, now, pause = {0, 1000 * 1000};
|
||||||
|
clock_gettime(CLOCK_MONOTONIC, &start);
|
||||||
|
for (;;) {
|
||||||
|
if (flock(fd_, LOCK_EX | LOCK_NB) == 0) {
|
||||||
|
locked_ = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (errno == EINTR) continue;
|
||||||
|
if (errno != EWOULDBLOCK) {
|
||||||
|
error = errno;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
clock_gettime(CLOCK_MONOTONIC, &now);
|
||||||
|
if ((now.tv_sec - start.tv_sec) * 1000 + (now.tv_nsec - start.tv_nsec) / 1000000 >= timeout_ms) {
|
||||||
|
busy_ = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
nanosleep(&pause, nullptr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (busy_) {
|
||||||
|
static std::atomic<unsigned> waits;
|
||||||
|
unsigned n = ++waits;
|
||||||
|
if ((n & (n - 1)) == 0) Logger::log("lock: %s still held after %d ms, skipped (x%u)\n", name, timeout_ms, n);
|
||||||
|
} else if (!locked_) {
|
||||||
|
static std::atomic<bool> noted{false};
|
||||||
|
if (!noted.exchange(true))
|
||||||
|
Logger::log("lock: %s not taken (%s)%s\n", name, strerror(error),
|
||||||
|
process_is_steam_client() ? "" : "; this process leaves the shared slots alone");
|
||||||
|
}
|
||||||
|
errno = saved_errno;
|
||||||
|
}
|
||||||
|
~ProcessSlotLock() {
|
||||||
|
int saved_errno = errno;
|
||||||
|
if (locked_) flock(fd_, LOCK_UN);
|
||||||
|
errno = saved_errno;
|
||||||
|
}
|
||||||
|
bool may_write() const { return locked_ || (!busy_ && process_is_steam_client()); }
|
||||||
|
ProcessSlotLock(const ProcessSlotLock &) = delete;
|
||||||
|
ProcessSlotLock &operator=(const ProcessSlotLock &) = delete;
|
||||||
|
|
||||||
|
private:
|
||||||
|
int fd_;
|
||||||
|
bool locked_ = false;
|
||||||
|
bool busy_ = false;
|
||||||
|
};
|
||||||
|
|
||||||
static bool ring_paths_loaded = false;
|
static bool ring_paths_loaded = false;
|
||||||
static int next_ff_id = 0;
|
static int next_ff_id = 0;
|
||||||
|
|
||||||
@@ -411,22 +477,49 @@ __attribute__((visibility("hidden"))) static void send_ff_effect(const struct ff
|
|||||||
send_vibration(effect.u.periodic.magnitude, effect.u.periodic.magnitude, duration, slot);
|
send_vibration(effect.u.periodic.magnitude, effect.u.periodic.magnitude, duration, slot);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static std::unordered_map<int, const FakeController *> &ff_players() {
|
||||||
|
static auto *players = new std::unordered_map<int, const FakeController *>();
|
||||||
|
return *players;
|
||||||
|
}
|
||||||
|
|
||||||
|
__attribute__((visibility("hidden"))) static void ff_played(FakeController &controller, int id) {
|
||||||
|
controller.playing_ff = id;
|
||||||
|
controller.owner = getpid();
|
||||||
|
ff_players()[controller.slot] = &controller;
|
||||||
|
}
|
||||||
|
|
||||||
|
__attribute__((visibility("hidden"))) static bool ff_release(FakeController &controller) {
|
||||||
|
auto player = ff_players().find(controller.slot);
|
||||||
|
bool current = player != ff_players().end() && player->second == &controller;
|
||||||
|
if (current) ff_players().erase(player);
|
||||||
|
controller.playing_ff = -1;
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
__attribute__((visibility("hidden"))) static void
|
__attribute__((visibility("hidden"))) static void
|
||||||
check_ff_event(const struct input_event *ev, uint16_t slot) {
|
check_ff_event(const struct input_event *ev, FakeController &controller) {
|
||||||
if (ev->type != EV_FF)
|
if (ev->type != EV_FF)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
|
uint16_t slot = static_cast<uint16_t>(controller.slot);
|
||||||
int id = ev->code;
|
int id = ev->code;
|
||||||
if (ev->value > 0) {
|
if (ev->value > 0) {
|
||||||
auto it = ff_effects().find(id);
|
auto it = ff_effects().find(id);
|
||||||
if (it == ff_effects().end())
|
if (it == ff_effects().end())
|
||||||
return;
|
return;
|
||||||
send_ff_effect(it->second, slot);
|
send_ff_effect(it->second, slot);
|
||||||
|
ff_played(controller, id);
|
||||||
} else {
|
} else {
|
||||||
send_vibration(0, 0, 0, slot);
|
send_vibration(0, 0, 0, slot);
|
||||||
|
ff_release(controller);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
__attribute__((visibility("hidden"))) static void stop_ff(FakeController &controller) {
|
||||||
|
bool playing = controller.playing_ff >= 0 && controller.owner == getpid();
|
||||||
|
if (ff_release(controller) && playing) send_vibration(0, 0, 0, static_cast<uint16_t>(controller.slot));
|
||||||
|
}
|
||||||
|
|
||||||
__attribute__((visibility("hidden"))) char *
|
__attribute__((visibility("hidden"))) char *
|
||||||
from_real_to_fake_path(const char *pathname) {
|
from_real_to_fake_path(const char *pathname) {
|
||||||
const char *event = strrchr(pathname, '/') + 1;
|
const char *event = strrchr(pathname, '/') + 1;
|
||||||
@@ -1185,10 +1278,13 @@ struct DeckImu {
|
|||||||
uint32_t controls;
|
uint32_t controls;
|
||||||
uint32_t pad_type;
|
uint32_t pad_type;
|
||||||
uint32_t latency;
|
uint32_t latency;
|
||||||
|
uint32_t remote_imu_mode;
|
||||||
|
uint32_t remote_imu_pid;
|
||||||
};
|
};
|
||||||
static_assert(offsetof(DeckImu, pad_type) == FAKE_INPUT_RING_PAD_TYPE_OFFSET,
|
static_assert(offsetof(DeckImu, pad_type) == FAKE_INPUT_RING_PAD_TYPE_OFFSET,
|
||||||
"DeckImu::pad_type matches FakeInputWriter and the ring reader");
|
"DeckImu::pad_type matches FakeInputWriter and the ring reader");
|
||||||
static_assert(offsetof(DeckImu, latency) == 48, "DeckImu::latency matches FakeInputWriter");
|
static_assert(offsetof(DeckImu, latency) == 48, "DeckImu::latency matches FakeInputWriter");
|
||||||
|
static_assert(offsetof(DeckImu, remote_imu_mode) == 52, "DeckImu::remote_imu_mode matches FakeInputWriter");
|
||||||
static constexpr uint32_t LATENCY_CONTROLLER = 1, LATENCY_TOUCH = 2;
|
static constexpr uint32_t LATENCY_CONTROLLER = 1, LATENCY_TOUCH = 2;
|
||||||
static constexpr int LOW_LATENCY_REPORT_INTERVAL_US = 1000;
|
static constexpr int LOW_LATENCY_REPORT_INTERVAL_US = 1000;
|
||||||
static constexpr uint32_t DECK_EXTRA_L4 = 1, DECK_EXTRA_R4 = 2, DECK_EXTRA_L5 = 4,
|
static constexpr uint32_t DECK_EXTRA_L4 = 1, DECK_EXTRA_R4 = 2, DECK_EXTRA_L5 = 4,
|
||||||
@@ -1395,6 +1491,25 @@ __attribute__((visibility("hidden"))) static bool process_is_steam_client() {
|
|||||||
return known == 1;
|
return known == 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Steam's Remote Play client reads the controller itself, in its own streaming_client process.
|
||||||
|
__attribute__((visibility("hidden"))) static bool process_reads_pads() {
|
||||||
|
static int known;
|
||||||
|
if (known == 0) {
|
||||||
|
bool reader = process_is_steam_client();
|
||||||
|
if (!reader) {
|
||||||
|
char exe[PATH_MAX];
|
||||||
|
ssize_t length = readlink("/proc/self/exe", exe, sizeof(exe) - 1);
|
||||||
|
if (length > 0) {
|
||||||
|
exe[length] = '\0';
|
||||||
|
const char *name = strrchr(exe, '/');
|
||||||
|
reader = !strcmp(name ? name + 1 : exe, "streaming_client");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
known = reader ? 1 : -1;
|
||||||
|
}
|
||||||
|
return known == 1;
|
||||||
|
}
|
||||||
|
|
||||||
__attribute__((constructor)) static void log_client_start() {
|
__attribute__((constructor)) static void log_client_start() {
|
||||||
config();
|
config();
|
||||||
if (process_is_steam_client())
|
if (process_is_steam_client())
|
||||||
@@ -1439,7 +1554,7 @@ __attribute__((visibility("hidden"))) static bool is_withdrawn_pad_path(const ch
|
|||||||
free(fake);
|
free(fake);
|
||||||
return !exposed;
|
return !exposed;
|
||||||
}
|
}
|
||||||
return number == 0 || !process_is_steam_client();
|
return number == 0 || !process_reads_pads();
|
||||||
}
|
}
|
||||||
|
|
||||||
static bool fake_pad_withdrawn(const FakeController &fake) {
|
static bool fake_pad_withdrawn(const FakeController &fake) {
|
||||||
@@ -1654,7 +1769,7 @@ __attribute__((visibility("hidden"))) static void *sony_report_thread(void *arg)
|
|||||||
__attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags, uint8_t sony = 0) {
|
__attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags, uint8_t sony = 0) {
|
||||||
const char *path = sony == 4 ? DS4_HIDRAW_PATH : sony == 5 ? DUALSENSE_HIDRAW_PATH : DECK_HIDRAW_PATH;
|
const char *path = sony == 4 ? DS4_HIDRAW_PATH : sony == 5 ? DUALSENSE_HIDRAW_PATH : DECK_HIDRAW_PATH;
|
||||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
||||||
if (!process_is_steam_client()) {
|
if (!process_reads_pads()) {
|
||||||
Logger::log("deck: %s refused: not the Steam client\n", path);
|
Logger::log("deck: %s refused: not the Steam client\n", path);
|
||||||
errno = ENOENT;
|
errno = ENOENT;
|
||||||
return -1;
|
return -1;
|
||||||
@@ -1863,7 +1978,7 @@ __attribute__((visibility("hidden"))) static void *triton_pad_thread(void *arg)
|
|||||||
|
|
||||||
__attribute__((visibility("hidden"))) static int open_triton_hidraw(int flags, bool emulated) {
|
__attribute__((visibility("hidden"))) static int open_triton_hidraw(int flags, bool emulated) {
|
||||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
||||||
if (!process_is_steam_client()) {
|
if (!process_reads_pads()) {
|
||||||
errno = ENOENT;
|
errno = ENOENT;
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
@@ -2004,15 +2119,19 @@ __attribute__((visibility("hidden"))) static bool touch_plugged() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
__attribute__((visibility("hidden"))) static bool is_touch_hidraw_path(const char *pathname) {
|
__attribute__((visibility("hidden"))) static bool is_touch_hidraw_path(const char *pathname) {
|
||||||
return pathname && !strcmp(pathname, TOUCH_HIDRAW_PATH) && process_is_steam_client() && touch_ring();
|
return pathname && !strcmp(pathname, TOUCH_HIDRAW_PATH) && process_reads_pads() && touch_ring();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static std::mutex touch_state_mutex;
|
||||||
|
static int touch_state_lock_fd = -1;
|
||||||
|
|
||||||
template <typename F>
|
template <typename F>
|
||||||
__attribute__((visibility("hidden"))) static void touch_state(F &&write) {
|
__attribute__((visibility("hidden"))) static void touch_state(F &&write) {
|
||||||
TouchRingFile *ring = touch_ring();
|
TouchRingFile *ring = touch_ring();
|
||||||
if (!ring) return;
|
if (!ring) return;
|
||||||
static std::mutex mutex;
|
std::lock_guard<std::mutex> guard(touch_state_mutex);
|
||||||
std::lock_guard<std::mutex> guard(mutex);
|
ProcessSlotLock slot(touch_state_lock_fd, "touch-state", 20);
|
||||||
|
if (!slot.may_write()) return;
|
||||||
__atomic_fetch_add(&ring->state_seq, 1, __ATOMIC_ACQ_REL);
|
__atomic_fetch_add(&ring->state_seq, 1, __ATOMIC_ACQ_REL);
|
||||||
write(*ring);
|
write(*ring);
|
||||||
__atomic_fetch_add(&ring->state_seq, 1, __ATOMIC_ACQ_REL);
|
__atomic_fetch_add(&ring->state_seq, 1, __ATOMIC_ACQ_REL);
|
||||||
@@ -2264,9 +2383,10 @@ __attribute__((visibility("hidden"))) static void *pad_type_thread(void *) {
|
|||||||
struct timespec settle = {0, 300 * 1000 * 1000};
|
struct timespec settle = {0, 300 * 1000 * 1000};
|
||||||
nanosleep(&settle, nullptr);
|
nanosleep(&settle, nullptr);
|
||||||
int added = pad_type_uevent(now, "add");
|
int added = pad_type_uevent(now, "add");
|
||||||
if (was != PAD_TYPE_XBOX) poke_hidraw_watchers(pad_type_minor(was));
|
bool shared = process_is_steam_client();
|
||||||
if (now != PAD_TYPE_XBOX) poke_hidraw_watchers(pad_type_minor(now));
|
if (shared && was != PAD_TYPE_XBOX) poke_hidraw_watchers(pad_type_minor(was));
|
||||||
if (was == PAD_TYPE_XBOX || now == PAD_TYPE_XBOX) {
|
if (shared && now != PAD_TYPE_XBOX) poke_hidraw_watchers(pad_type_minor(now));
|
||||||
|
if (shared && (was == PAD_TYPE_XBOX || now == PAD_TYPE_XBOX)) {
|
||||||
std::string node = std::string(fake_hook_dir()) + "/event0";
|
std::string node = std::string(fake_hook_dir()) + "/event0";
|
||||||
std::string aside = std::string(fake_hook_dir()) + "/.event0-switching";
|
std::string aside = std::string(fake_hook_dir()) + "/.event0-switching";
|
||||||
if (rename(node.c_str(), aside.c_str()) == 0) {
|
if (rename(node.c_str(), aside.c_str()) == 0) {
|
||||||
@@ -2285,7 +2405,7 @@ __attribute__((visibility("hidden"))) static void *pad_type_thread(void *) {
|
|||||||
|
|
||||||
__attribute__((constructor)) static void start_pad_type_watch() {
|
__attribute__((constructor)) static void start_pad_type_watch() {
|
||||||
config();
|
config();
|
||||||
if (!process_is_steam_client() || !fake_deck_enabled()) return;
|
if (!process_reads_pads() || !fake_deck_enabled()) return;
|
||||||
pthread_t thread;
|
pthread_t thread;
|
||||||
if (pthread_create(&thread, nullptr, pad_type_thread, nullptr) == 0) pthread_detach(thread);
|
if (pthread_create(&thread, nullptr, pad_type_thread, nullptr) == 0) pthread_detach(thread);
|
||||||
}
|
}
|
||||||
@@ -2306,7 +2426,7 @@ __attribute__((visibility("hidden"))) static void *touch_plug_thread(void *) {
|
|||||||
|
|
||||||
__attribute__((constructor)) static void start_touch_controller() {
|
__attribute__((constructor)) static void start_touch_controller() {
|
||||||
config();
|
config();
|
||||||
if (!process_is_steam_client() || !touch_ring()) return;
|
if (!process_reads_pads() || !touch_ring()) return;
|
||||||
pthread_t thread;
|
pthread_t thread;
|
||||||
if (pthread_create(&thread, nullptr, touch_plug_thread, nullptr) == 0) pthread_detach(thread);
|
if (pthread_create(&thread, nullptr, touch_plug_thread, nullptr) == 0) pthread_detach(thread);
|
||||||
}
|
}
|
||||||
@@ -2413,8 +2533,13 @@ __attribute__((visibility("hidden"))) static void publish_imu_mode(const DeckHid
|
|||||||
std::string path = get_ring_path_for_slot(0);
|
std::string path = get_ring_path_for_slot(0);
|
||||||
int fd = path.empty() ? -1 : my_open(path.c_str(), O_WRONLY | O_CLOEXEC);
|
int fd = path.empty() ? -1 : my_open(path.c_str(), O_WRONLY | O_CLOEXEC);
|
||||||
if (fd < 0) return;
|
if (fd < 0) return;
|
||||||
uint32_t value = 0x80000000u | static_cast<uint32_t>(mode);
|
// Steam and its Remote Play client each keep their own word, so one turning motion off does not starve the
|
||||||
if (pwrite(fd, &value, sizeof(value), FAKE_INPUT_RING_SIZE + offsetof(DeckImu, imu_mode)) != sizeof(value))
|
// other; Android reads motion while either wants it. The pid lets it ignore a Remote Play client that has gone.
|
||||||
|
uint32_t value[2] = {0x80000000u | static_cast<uint32_t>(mode), static_cast<uint32_t>(getpid())};
|
||||||
|
bool steam = process_is_steam_client();
|
||||||
|
size_t length = steam ? sizeof(value[0]) : sizeof(value);
|
||||||
|
off_t offset = FAKE_INPUT_RING_SIZE + (steam ? offsetof(DeckImu, imu_mode) : offsetof(DeckImu, remote_imu_mode));
|
||||||
|
if (pwrite(fd, value, length, offset) != static_cast<ssize_t>(length))
|
||||||
Logger::log("deck: imu mode not published (%s)\n", strerror(errno));
|
Logger::log("deck: imu mode not published (%s)\n", strerror(errno));
|
||||||
syscall(SYS_close, fd);
|
syscall(SYS_close, fd);
|
||||||
}
|
}
|
||||||
@@ -2619,7 +2744,10 @@ __attribute__((visibility("hidden"))) static void triton_queue_output(DeckHidraw
|
|||||||
auto *shared = reinterpret_cast<TritonSharedData *>(reinterpret_cast<uint8_t *>(triton.ring) + TRITON_SHARED_OFFSET);
|
auto *shared = reinterpret_cast<TritonSharedData *>(reinterpret_cast<uint8_t *>(triton.ring) + TRITON_SHARED_OFFSET);
|
||||||
if (__atomic_load_n(&shared->magic, __ATOMIC_ACQUIRE) != TRITON_SHARED_MAGIC) return;
|
if (__atomic_load_n(&shared->magic, __ATOMIC_ACQUIRE) != TRITON_SHARED_MAGIC) return;
|
||||||
static std::mutex one_at_a_time;
|
static std::mutex one_at_a_time;
|
||||||
|
static int lock_fd = -1;
|
||||||
std::lock_guard<std::mutex> guard(one_at_a_time);
|
std::lock_guard<std::mutex> guard(one_at_a_time);
|
||||||
|
ProcessSlotLock slot(lock_fd, "triton-output", TRITON_OUTPUT_TIMEOUT_MS * 2);
|
||||||
|
if (!slot.may_write()) return;
|
||||||
for (int waited = 0;
|
for (int waited = 0;
|
||||||
static_cast<uint32_t>(__atomic_load_n(&shared->output_seq, __ATOMIC_ACQUIRE)) !=
|
static_cast<uint32_t>(__atomic_load_n(&shared->output_seq, __ATOMIC_ACQUIRE)) !=
|
||||||
__atomic_load_n(&shared->output_ack, __ATOMIC_ACQUIRE) &&
|
__atomic_load_n(&shared->output_ack, __ATOMIC_ACQUIRE) &&
|
||||||
@@ -2651,7 +2779,13 @@ __attribute__((visibility("hidden"))) static int triton_get_feature(DeckHidraw &
|
|||||||
}
|
}
|
||||||
auto *shared = reinterpret_cast<TritonSharedData *>(reinterpret_cast<uint8_t *>(triton.ring) + TRITON_SHARED_OFFSET);
|
auto *shared = reinterpret_cast<TritonSharedData *>(reinterpret_cast<uint8_t *>(triton.ring) + TRITON_SHARED_OFFSET);
|
||||||
static std::mutex one_at_a_time;
|
static std::mutex one_at_a_time;
|
||||||
|
static int lock_fd = -1;
|
||||||
std::lock_guard<std::mutex> guard(one_at_a_time);
|
std::lock_guard<std::mutex> guard(one_at_a_time);
|
||||||
|
ProcessSlotLock slot(lock_fd, "triton-feature", TRITON_FEATURE_TIMEOUT_MS);
|
||||||
|
if (!slot.may_write()) {
|
||||||
|
errno = EIO;
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
uint8_t report_id = report[0];
|
uint8_t report_id = report[0];
|
||||||
__atomic_store_n(&shared->get_report_id, report_id, __ATOMIC_RELAXED);
|
__atomic_store_n(&shared->get_report_id, report_id, __ATOMIC_RELAXED);
|
||||||
uint64_t request = __atomic_add_fetch(&shared->get_request, 1, __ATOMIC_RELEASE);
|
uint64_t request = __atomic_add_fetch(&shared->get_request, 1, __ATOMIC_RELEASE);
|
||||||
@@ -2839,7 +2973,7 @@ __attribute__((visibility("hidden"))) static int ioctl_triton(DeckHidraw &triton
|
|||||||
__attribute__((visibility("hidden"))) static std::string note_sys_failure(int dirfd, const char *pathname) {
|
__attribute__((visibility("hidden"))) static std::string note_sys_failure(int dirfd, const char *pathname) {
|
||||||
int saved_errno = errno;
|
int saved_errno = errno;
|
||||||
std::string path;
|
std::string path;
|
||||||
if (saved_errno == ENOENT || !pathname || !process_is_steam_client()) {
|
if (saved_errno == ENOENT || !pathname || !process_reads_pads()) {
|
||||||
errno = saved_errno;
|
errno = saved_errno;
|
||||||
return path;
|
return path;
|
||||||
}
|
}
|
||||||
@@ -2878,7 +3012,7 @@ __attribute__((visibility("hidden"))) static std::string note_sys_failure(int di
|
|||||||
|
|
||||||
__attribute__((visibility("hidden"))) static std::string deck_listing_for(const char *path) {
|
__attribute__((visibility("hidden"))) static std::string deck_listing_for(const char *path) {
|
||||||
const char *listing = deck_listing_dir();
|
const char *listing = deck_listing_dir();
|
||||||
if (!path || !listing || errno != EACCES || !fake_deck_enabled() || !process_is_steam_client()) return {};
|
if (!path || !listing || errno != EACCES || !fake_deck_enabled() || !process_reads_pads()) return {};
|
||||||
std::string p(path);
|
std::string p(path);
|
||||||
while (p.size() > 1 && p.back() == '/') p.pop_back();
|
while (p.size() > 1 && p.back() == '/') p.pop_back();
|
||||||
int which = p == "/sys" ? 0 : p == "/sys/class" ? 1 : p == "/sys/bus" ? 2 : -1;
|
int which = p == "/sys" ? 0 : p == "/sys/class" ? 1 : p == "/sys/bus" ? 2 : -1;
|
||||||
@@ -2947,7 +3081,7 @@ EXPORT int statx(int dirfd, const char *path, int flags, unsigned mask, struct s
|
|||||||
constexpr unsigned unique_mount_id = 0x4000;
|
constexpr unsigned unique_mount_id = 0x4000;
|
||||||
if (result == 0 && (mask & STATX_MNT_ID) &&
|
if (result == 0 && (mask & STATX_MNT_ID) &&
|
||||||
!(buf->stx_mask & (STATX_MNT_ID | unique_mount_id)) && fake_deck_enabled() &&
|
!(buf->stx_mask & (STATX_MNT_ID | unique_mount_id)) && fake_deck_enabled() &&
|
||||||
process_is_steam_client() && deck_device_library(__builtin_return_address(0))) {
|
process_reads_pads() && deck_device_library(__builtin_return_address(0))) {
|
||||||
bool recovered = deck_mount_id_from_fdinfo(dirfd, path, flags, buf);
|
bool recovered = deck_mount_id_from_fdinfo(dirfd, path, flags, buf);
|
||||||
static std::atomic<bool> noted_success{false}, noted_failure{false};
|
static std::atomic<bool> noted_success{false}, noted_failure{false};
|
||||||
if (!(recovered ? noted_success : noted_failure).exchange(true))
|
if (!(recovered ? noted_success : noted_failure).exchange(true))
|
||||||
@@ -3136,7 +3270,7 @@ template <typename S, typename Real>
|
|||||||
static int fake_stat_path(const char *pathname, S *statbuf, Real real) {
|
static int fake_stat_path(const char *pathname, S *statbuf, Real real) {
|
||||||
if (is_withdrawn_pad_path(pathname) ||
|
if (is_withdrawn_pad_path(pathname) ||
|
||||||
((is_deck_hidraw_path(pathname) || is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) ||
|
((is_deck_hidraw_path(pathname) || is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) ||
|
||||||
sony_pad_path(pathname)) && !process_is_steam_client())) {
|
sony_pad_path(pathname)) && !process_reads_pads())) {
|
||||||
errno = ENOENT;
|
errno = ENOENT;
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
@@ -3261,9 +3395,9 @@ EXPORT int fstat(int fd, struct stat *buf) {
|
|||||||
EXPORT int access(const char *pathname, int mode) {
|
EXPORT int access(const char *pathname, int mode) {
|
||||||
static auto my_access = reinterpret_cast<decltype(&::access)>(dlsym(RTLD_NEXT, "access"));
|
static auto my_access = reinterpret_cast<decltype(&::access)>(dlsym(RTLD_NEXT, "access"));
|
||||||
if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0;
|
if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0;
|
||||||
if (is_deck_hidraw_path(pathname) && process_is_steam_client()) return 0;
|
if (is_deck_hidraw_path(pathname) && process_reads_pads()) return 0;
|
||||||
if ((is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || sony_pad_path(pathname)) &&
|
if ((is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || sony_pad_path(pathname)) &&
|
||||||
process_is_steam_client())
|
process_reads_pads())
|
||||||
return 0;
|
return 0;
|
||||||
if (is_touch_hidraw_path(pathname)) return 0;
|
if (is_touch_hidraw_path(pathname)) return 0;
|
||||||
if (is_withdrawn_pad_path(pathname) || is_deck_hidraw_path(pathname) || is_triton_hidraw_path(pathname) ||
|
if (is_withdrawn_pad_path(pathname) || is_deck_hidraw_path(pathname) || is_triton_hidraw_path(pathname) ||
|
||||||
@@ -3302,9 +3436,9 @@ EXPORT int access(const char *pathname, int mode) {
|
|||||||
EXPORT int faccessat(int dirfd, const char *pathname, int mode, int flags) {
|
EXPORT int faccessat(int dirfd, const char *pathname, int mode, int flags) {
|
||||||
static auto my_faccessat = reinterpret_cast<decltype(&::faccessat)>(dlsym(RTLD_NEXT, "faccessat"));
|
static auto my_faccessat = reinterpret_cast<decltype(&::faccessat)>(dlsym(RTLD_NEXT, "faccessat"));
|
||||||
if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0;
|
if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0;
|
||||||
if (is_deck_hidraw_path(pathname) && process_is_steam_client()) return 0;
|
if (is_deck_hidraw_path(pathname) && process_reads_pads()) return 0;
|
||||||
if ((is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || sony_pad_path(pathname)) &&
|
if ((is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || sony_pad_path(pathname)) &&
|
||||||
process_is_steam_client())
|
process_reads_pads())
|
||||||
return 0;
|
return 0;
|
||||||
if (is_touch_hidraw_path(pathname)) return 0;
|
if (is_touch_hidraw_path(pathname)) return 0;
|
||||||
if (is_withdrawn_pad_path(pathname) || is_deck_hidraw_path(pathname) || is_triton_hidraw_path(pathname) ||
|
if (is_withdrawn_pad_path(pathname) || is_deck_hidraw_path(pathname) || is_triton_hidraw_path(pathname) ||
|
||||||
@@ -3371,7 +3505,7 @@ EXPORT int inotify_add_watch(int fd, const char *pathname, uint32_t mask) {
|
|||||||
pathname = fake_path;
|
pathname = fake_path;
|
||||||
} else if (!strcmp(pathname, "/dev/input")) {
|
} else if (!strcmp(pathname, "/dev/input")) {
|
||||||
pathname = fake_hook_dir();
|
pathname = fake_hook_dir();
|
||||||
} else if (!strcmp(pathname, "/dev") && fake_deck_enabled() && process_is_steam_client()) {
|
} else if (!strcmp(pathname, "/dev") && fake_deck_enabled() && process_reads_pads()) {
|
||||||
std::string events = hidraw_event_dir();
|
std::string events = hidraw_event_dir();
|
||||||
mkdir(events.c_str(), 0700);
|
mkdir(events.c_str(), 0700);
|
||||||
my_inotify_add_watch(fd, events.c_str(), mask);
|
my_inotify_add_watch(fd, events.c_str(), mask);
|
||||||
@@ -3657,10 +3791,12 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
|
|||||||
effect->id = next_ff_id++;
|
effect->id = next_ff_id++;
|
||||||
ff_effects()[effect->id] = *effect;
|
ff_effects()[effect->id] = *effect;
|
||||||
send_ff_effect(*effect, static_cast<uint16_t>(event_number));
|
send_ff_effect(*effect, static_cast<uint16_t>(event_number));
|
||||||
|
ff_played(*controller->second, effect->id);
|
||||||
return 0;
|
return 0;
|
||||||
} else if (type == 0x45 && number == 0x81) {
|
} else if (type == 0x45 && number == 0x81) {
|
||||||
int id = (intptr_t)argp;
|
int id = (intptr_t)argp;
|
||||||
ff_effects().erase(id);
|
ff_effects().erase(id);
|
||||||
|
if (controller->second->playing_ff == id) stop_ff(*controller->second);
|
||||||
return 0;
|
return 0;
|
||||||
} else if (type == 0x45 && number == 0x84) {
|
} else if (type == 0x45 && number == 0x84) {
|
||||||
int max_effects = 16;
|
int max_effects = 16;
|
||||||
@@ -3740,6 +3876,7 @@ EXPORT int close(int fd) {
|
|||||||
if (controller != controller_map().end()) {
|
if (controller != controller_map().end()) {
|
||||||
Logger::log("Removing controller, fd %d event %s\n", controller->first,
|
Logger::log("Removing controller, fd %d event %s\n", controller->first,
|
||||||
controller->second->event ? controller->second->event : "(unknown)");
|
controller->second->event ? controller->second->event : "(unknown)");
|
||||||
|
stop_ff(*controller->second);
|
||||||
controller->second->closed = true;
|
controller->second->closed = true;
|
||||||
controller_map().erase(fd);
|
controller_map().erase(fd);
|
||||||
}
|
}
|
||||||
@@ -3937,12 +4074,8 @@ EXPORT ssize_t write(int fd, const void *buf, size_t count) {
|
|||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
const struct input_event *ev = nullptr;
|
if (count == sizeof(struct input_event))
|
||||||
uint16_t slot = static_cast<uint16_t>(controller->second->slot);
|
check_ff_event(static_cast<const struct input_event *>(buf), *controller->second);
|
||||||
if (count == sizeof(struct input_event)) {
|
|
||||||
ev = static_cast<const struct input_event *>(buf);
|
|
||||||
check_ff_event(ev, slot);
|
|
||||||
}
|
|
||||||
|
|
||||||
return static_cast<ssize_t>(count);
|
return static_cast<ssize_t>(count);
|
||||||
}
|
}
|
||||||
@@ -3982,14 +4115,10 @@ EXPORT ssize_t writev(int fd, const struct iovec *iov, int iovcnt) {
|
|||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
uint16_t slot = static_cast<uint16_t>(controller->second->slot);
|
|
||||||
ssize_t total = 0;
|
ssize_t total = 0;
|
||||||
for (int i = 0; i < iovcnt; i++) {
|
for (int i = 0; i < iovcnt; i++) {
|
||||||
if (iov[i].iov_len == sizeof(struct input_event)) {
|
if (iov[i].iov_len == sizeof(struct input_event))
|
||||||
const struct input_event *ev =
|
check_ff_event(static_cast<const struct input_event *>(iov[i].iov_base), *controller->second);
|
||||||
static_cast<const struct input_event *>(iov[i].iov_base);
|
|
||||||
check_ff_event(ev, slot);
|
|
||||||
}
|
|
||||||
total += static_cast<ssize_t>(iov[i].iov_len);
|
total += static_cast<ssize_t>(iov[i].iov_len);
|
||||||
}
|
}
|
||||||
return total;
|
return total;
|
||||||
|
|||||||
@@ -0,0 +1,106 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <vulkan/vulkan.h>
|
||||||
|
#include <vulkan/vulkan_android.h>
|
||||||
|
|
||||||
|
struct VkTable {
|
||||||
|
|
||||||
|
PFN_vkCreateInstance CreateInstance;
|
||||||
|
|
||||||
|
PFN_vkDestroyInstance DestroyInstance;
|
||||||
|
PFN_vkEnumeratePhysicalDevices EnumeratePhysicalDevices;
|
||||||
|
PFN_vkGetPhysicalDeviceProperties GetPhysicalDeviceProperties;
|
||||||
|
PFN_vkGetPhysicalDeviceMemoryProperties GetPhysicalDeviceMemoryProperties;
|
||||||
|
PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR GetPhysicalDeviceSurfaceCapabilitiesKHR;
|
||||||
|
PFN_vkGetPhysicalDeviceSurfaceFormatsKHR GetPhysicalDeviceSurfaceFormatsKHR;
|
||||||
|
PFN_vkGetPhysicalDeviceSurfacePresentModesKHR GetPhysicalDeviceSurfacePresentModesKHR;
|
||||||
|
PFN_vkGetPhysicalDeviceQueueFamilyProperties GetPhysicalDeviceQueueFamilyProperties;
|
||||||
|
PFN_vkGetPhysicalDeviceSurfaceSupportKHR GetPhysicalDeviceSurfaceSupportKHR;
|
||||||
|
PFN_vkGetPhysicalDeviceFormatProperties GetPhysicalDeviceFormatProperties;
|
||||||
|
PFN_vkGetPhysicalDeviceFeatures2 GetPhysicalDeviceFeatures2;
|
||||||
|
PFN_vkCreateDevice CreateDevice;
|
||||||
|
PFN_vkDestroySurfaceKHR DestroySurfaceKHR;
|
||||||
|
PFN_vkCreateAndroidSurfaceKHR CreateAndroidSurfaceKHR;
|
||||||
|
|
||||||
|
PFN_vkGetDeviceProcAddr GetDeviceProcAddr;
|
||||||
|
PFN_vkDestroyDevice DestroyDevice;
|
||||||
|
PFN_vkGetDeviceQueue GetDeviceQueue;
|
||||||
|
PFN_vkDeviceWaitIdle DeviceWaitIdle;
|
||||||
|
PFN_vkCreateSwapchainKHR CreateSwapchainKHR;
|
||||||
|
PFN_vkDestroySwapchainKHR DestroySwapchainKHR;
|
||||||
|
PFN_vkGetSwapchainImagesKHR GetSwapchainImagesKHR;
|
||||||
|
PFN_vkAcquireNextImageKHR AcquireNextImageKHR;
|
||||||
|
PFN_vkQueuePresentKHR QueuePresentKHR;
|
||||||
|
PFN_vkQueueSubmit QueueSubmit;
|
||||||
|
PFN_vkCreateQueryPool CreateQueryPool;
|
||||||
|
PFN_vkDestroyQueryPool DestroyQueryPool;
|
||||||
|
PFN_vkCmdResetQueryPool CmdResetQueryPool;
|
||||||
|
PFN_vkCmdWriteTimestamp CmdWriteTimestamp;
|
||||||
|
PFN_vkGetQueryPoolResults GetQueryPoolResults;
|
||||||
|
PFN_vkCreateRenderPass CreateRenderPass;
|
||||||
|
PFN_vkDestroyRenderPass DestroyRenderPass;
|
||||||
|
PFN_vkCreateFramebuffer CreateFramebuffer;
|
||||||
|
PFN_vkDestroyFramebuffer DestroyFramebuffer;
|
||||||
|
PFN_vkCreateImageView CreateImageView;
|
||||||
|
PFN_vkDestroyImageView DestroyImageView;
|
||||||
|
PFN_vkCreateImage CreateImage;
|
||||||
|
PFN_vkDestroyImage DestroyImage;
|
||||||
|
PFN_vkCreateBuffer CreateBuffer;
|
||||||
|
PFN_vkDestroyBuffer DestroyBuffer;
|
||||||
|
PFN_vkAllocateMemory AllocateMemory;
|
||||||
|
PFN_vkFreeMemory FreeMemory;
|
||||||
|
PFN_vkMapMemory MapMemory;
|
||||||
|
PFN_vkFlushMappedMemoryRanges FlushMappedMemoryRanges;
|
||||||
|
PFN_vkBindBufferMemory BindBufferMemory;
|
||||||
|
PFN_vkBindImageMemory BindImageMemory;
|
||||||
|
PFN_vkGetBufferMemoryRequirements GetBufferMemoryRequirements;
|
||||||
|
PFN_vkGetImageMemoryRequirements GetImageMemoryRequirements;
|
||||||
|
PFN_vkCreateDescriptorSetLayout CreateDescriptorSetLayout;
|
||||||
|
PFN_vkDestroyDescriptorSetLayout DestroyDescriptorSetLayout;
|
||||||
|
PFN_vkCreateDescriptorPool CreateDescriptorPool;
|
||||||
|
PFN_vkDestroyDescriptorPool DestroyDescriptorPool;
|
||||||
|
PFN_vkAllocateDescriptorSets AllocateDescriptorSets;
|
||||||
|
PFN_vkFreeDescriptorSets FreeDescriptorSets;
|
||||||
|
PFN_vkUpdateDescriptorSets UpdateDescriptorSets;
|
||||||
|
PFN_vkCreatePipelineLayout CreatePipelineLayout;
|
||||||
|
PFN_vkDestroyPipelineLayout DestroyPipelineLayout;
|
||||||
|
PFN_vkCreateShaderModule CreateShaderModule;
|
||||||
|
PFN_vkDestroyShaderModule DestroyShaderModule;
|
||||||
|
PFN_vkCreateGraphicsPipelines CreateGraphicsPipelines;
|
||||||
|
PFN_vkDestroyPipeline DestroyPipeline;
|
||||||
|
PFN_vkCreateCommandPool CreateCommandPool;
|
||||||
|
PFN_vkDestroyCommandPool DestroyCommandPool;
|
||||||
|
PFN_vkAllocateCommandBuffers AllocateCommandBuffers;
|
||||||
|
PFN_vkFreeCommandBuffers FreeCommandBuffers;
|
||||||
|
PFN_vkBeginCommandBuffer BeginCommandBuffer;
|
||||||
|
PFN_vkEndCommandBuffer EndCommandBuffer;
|
||||||
|
PFN_vkResetCommandBuffer ResetCommandBuffer;
|
||||||
|
PFN_vkCmdBeginRenderPass CmdBeginRenderPass;
|
||||||
|
PFN_vkCmdEndRenderPass CmdEndRenderPass;
|
||||||
|
PFN_vkCmdBindPipeline CmdBindPipeline;
|
||||||
|
PFN_vkCmdBindDescriptorSets CmdBindDescriptorSets;
|
||||||
|
PFN_vkCmdDraw CmdDraw;
|
||||||
|
PFN_vkCmdPushConstants CmdPushConstants;
|
||||||
|
PFN_vkCmdSetViewport CmdSetViewport;
|
||||||
|
PFN_vkCmdSetScissor CmdSetScissor;
|
||||||
|
PFN_vkCmdPipelineBarrier CmdPipelineBarrier;
|
||||||
|
PFN_vkCmdCopyImage CmdCopyImage;
|
||||||
|
PFN_vkCmdBlitImage CmdBlitImage;
|
||||||
|
|
||||||
|
PFN_vkCmdDispatch CmdDispatch;
|
||||||
|
PFN_vkCreateComputePipelines CreateComputePipelines;
|
||||||
|
PFN_vkUnmapMemory UnmapMemory;
|
||||||
|
PFN_vkCmdClearColorImage CmdClearColorImage;
|
||||||
|
PFN_vkResetDescriptorPool ResetDescriptorPool;
|
||||||
|
PFN_vkCmdCopyBufferToImage CmdCopyBufferToImage;
|
||||||
|
PFN_vkCreateSampler CreateSampler;
|
||||||
|
PFN_vkDestroySampler DestroySampler;
|
||||||
|
PFN_vkCreateSemaphore CreateSemaphore;
|
||||||
|
PFN_vkDestroySemaphore DestroySemaphore;
|
||||||
|
PFN_vkCreateFence CreateFence;
|
||||||
|
PFN_vkDestroyFence DestroyFence;
|
||||||
|
PFN_vkWaitForFences WaitForFences;
|
||||||
|
PFN_vkResetFences ResetFences;
|
||||||
|
PFN_vkGetFenceStatus GetFenceStatus;
|
||||||
|
|
||||||
|
PFN_vkGetAndroidHardwareBufferPropertiesANDROID GetAndroidHardwareBufferPropertiesANDROID;
|
||||||
|
};
|
||||||
@@ -1,680 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <vulkan/vulkan.h>
|
|
||||||
#include <list>
|
|
||||||
#include <vulkan/vulkan_android.h>
|
|
||||||
struct VkTable {
|
|
||||||
|
|
||||||
PFN_vkCreateInstance CreateInstance;
|
|
||||||
|
|
||||||
PFN_vkDestroyInstance DestroyInstance;
|
|
||||||
PFN_vkEnumeratePhysicalDevices EnumeratePhysicalDevices;
|
|
||||||
PFN_vkGetPhysicalDeviceProperties GetPhysicalDeviceProperties;
|
|
||||||
PFN_vkGetPhysicalDeviceMemoryProperties GetPhysicalDeviceMemoryProperties;
|
|
||||||
PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR GetPhysicalDeviceSurfaceCapabilitiesKHR;
|
|
||||||
PFN_vkGetPhysicalDeviceSurfaceFormatsKHR GetPhysicalDeviceSurfaceFormatsKHR;
|
|
||||||
PFN_vkGetPhysicalDeviceSurfacePresentModesKHR GetPhysicalDeviceSurfacePresentModesKHR;
|
|
||||||
PFN_vkGetPhysicalDeviceQueueFamilyProperties GetPhysicalDeviceQueueFamilyProperties;
|
|
||||||
PFN_vkGetPhysicalDeviceSurfaceSupportKHR GetPhysicalDeviceSurfaceSupportKHR;
|
|
||||||
PFN_vkGetPhysicalDeviceFormatProperties GetPhysicalDeviceFormatProperties;
|
|
||||||
PFN_vkGetPhysicalDeviceFeatures2 GetPhysicalDeviceFeatures2;
|
|
||||||
PFN_vkCreateDevice CreateDevice;
|
|
||||||
PFN_vkDestroySurfaceKHR DestroySurfaceKHR;
|
|
||||||
PFN_vkCreateAndroidSurfaceKHR CreateAndroidSurfaceKHR;
|
|
||||||
|
|
||||||
PFN_vkGetDeviceProcAddr GetDeviceProcAddr;
|
|
||||||
PFN_vkDestroyDevice DestroyDevice;
|
|
||||||
PFN_vkGetDeviceQueue GetDeviceQueue;
|
|
||||||
PFN_vkDeviceWaitIdle DeviceWaitIdle;
|
|
||||||
PFN_vkCreateSwapchainKHR CreateSwapchainKHR;
|
|
||||||
PFN_vkDestroySwapchainKHR DestroySwapchainKHR;
|
|
||||||
PFN_vkGetSwapchainImagesKHR GetSwapchainImagesKHR;
|
|
||||||
PFN_vkAcquireNextImageKHR AcquireNextImageKHR;
|
|
||||||
PFN_vkQueuePresentKHR QueuePresentKHR;
|
|
||||||
PFN_vkQueueSubmit QueueSubmit;
|
|
||||||
PFN_vkCreateQueryPool CreateQueryPool;
|
|
||||||
PFN_vkDestroyQueryPool DestroyQueryPool;
|
|
||||||
PFN_vkCmdResetQueryPool CmdResetQueryPool;
|
|
||||||
PFN_vkCmdWriteTimestamp CmdWriteTimestamp;
|
|
||||||
PFN_vkGetQueryPoolResults GetQueryPoolResults;
|
|
||||||
PFN_vkCreateRenderPass CreateRenderPass;
|
|
||||||
PFN_vkDestroyRenderPass DestroyRenderPass;
|
|
||||||
PFN_vkCreateFramebuffer CreateFramebuffer;
|
|
||||||
PFN_vkDestroyFramebuffer DestroyFramebuffer;
|
|
||||||
PFN_vkCreateImageView CreateImageView;
|
|
||||||
PFN_vkDestroyImageView DestroyImageView;
|
|
||||||
PFN_vkCreateImage CreateImage;
|
|
||||||
PFN_vkDestroyImage DestroyImage;
|
|
||||||
PFN_vkCreateBuffer CreateBuffer;
|
|
||||||
PFN_vkDestroyBuffer DestroyBuffer;
|
|
||||||
PFN_vkAllocateMemory AllocateMemory;
|
|
||||||
PFN_vkFreeMemory FreeMemory;
|
|
||||||
PFN_vkMapMemory MapMemory;
|
|
||||||
PFN_vkFlushMappedMemoryRanges FlushMappedMemoryRanges;
|
|
||||||
PFN_vkBindBufferMemory BindBufferMemory;
|
|
||||||
PFN_vkBindImageMemory BindImageMemory;
|
|
||||||
PFN_vkGetBufferMemoryRequirements GetBufferMemoryRequirements;
|
|
||||||
PFN_vkGetImageMemoryRequirements GetImageMemoryRequirements;
|
|
||||||
PFN_vkCreateDescriptorSetLayout CreateDescriptorSetLayout;
|
|
||||||
PFN_vkDestroyDescriptorSetLayout DestroyDescriptorSetLayout;
|
|
||||||
PFN_vkCreateDescriptorPool CreateDescriptorPool;
|
|
||||||
PFN_vkDestroyDescriptorPool DestroyDescriptorPool;
|
|
||||||
PFN_vkAllocateDescriptorSets AllocateDescriptorSets;
|
|
||||||
PFN_vkFreeDescriptorSets FreeDescriptorSets;
|
|
||||||
PFN_vkUpdateDescriptorSets UpdateDescriptorSets;
|
|
||||||
PFN_vkCreatePipelineLayout CreatePipelineLayout;
|
|
||||||
PFN_vkDestroyPipelineLayout DestroyPipelineLayout;
|
|
||||||
PFN_vkCreateShaderModule CreateShaderModule;
|
|
||||||
PFN_vkDestroyShaderModule DestroyShaderModule;
|
|
||||||
PFN_vkCreateGraphicsPipelines CreateGraphicsPipelines;
|
|
||||||
PFN_vkDestroyPipeline DestroyPipeline;
|
|
||||||
PFN_vkCreateCommandPool CreateCommandPool;
|
|
||||||
PFN_vkDestroyCommandPool DestroyCommandPool;
|
|
||||||
PFN_vkAllocateCommandBuffers AllocateCommandBuffers;
|
|
||||||
PFN_vkFreeCommandBuffers FreeCommandBuffers;
|
|
||||||
PFN_vkBeginCommandBuffer BeginCommandBuffer;
|
|
||||||
PFN_vkEndCommandBuffer EndCommandBuffer;
|
|
||||||
PFN_vkResetCommandBuffer ResetCommandBuffer;
|
|
||||||
PFN_vkCmdBeginRenderPass CmdBeginRenderPass;
|
|
||||||
PFN_vkCmdEndRenderPass CmdEndRenderPass;
|
|
||||||
PFN_vkCmdBindPipeline CmdBindPipeline;
|
|
||||||
PFN_vkCmdBindDescriptorSets CmdBindDescriptorSets;
|
|
||||||
PFN_vkCmdDraw CmdDraw;
|
|
||||||
PFN_vkCmdPushConstants CmdPushConstants;
|
|
||||||
PFN_vkCmdSetViewport CmdSetViewport;
|
|
||||||
PFN_vkCmdSetScissor CmdSetScissor;
|
|
||||||
PFN_vkCmdPipelineBarrier CmdPipelineBarrier;
|
|
||||||
PFN_vkCmdCopyImage CmdCopyImage;
|
|
||||||
PFN_vkCmdBlitImage CmdBlitImage;
|
|
||||||
|
|
||||||
PFN_vkCmdDispatch CmdDispatch;
|
|
||||||
PFN_vkCreateComputePipelines CreateComputePipelines;
|
|
||||||
PFN_vkUnmapMemory UnmapMemory;
|
|
||||||
PFN_vkCmdClearColorImage CmdClearColorImage;
|
|
||||||
PFN_vkResetDescriptorPool ResetDescriptorPool;
|
|
||||||
PFN_vkCmdCopyBufferToImage CmdCopyBufferToImage;
|
|
||||||
PFN_vkCreateSampler CreateSampler;
|
|
||||||
PFN_vkDestroySampler DestroySampler;
|
|
||||||
PFN_vkCreateSemaphore CreateSemaphore;
|
|
||||||
PFN_vkDestroySemaphore DestroySemaphore;
|
|
||||||
PFN_vkCreateFence CreateFence;
|
|
||||||
PFN_vkDestroyFence DestroyFence;
|
|
||||||
PFN_vkWaitForFences WaitForFences;
|
|
||||||
PFN_vkResetFences ResetFences;
|
|
||||||
PFN_vkGetFenceStatus GetFenceStatus;
|
|
||||||
|
|
||||||
PFN_vkGetAndroidHardwareBufferPropertiesANDROID GetAndroidHardwareBufferPropertiesANDROID;
|
|
||||||
};
|
|
||||||
|
|
||||||
#include <android/log.h>
|
|
||||||
#include <string>
|
|
||||||
#define WLOG_TAG "DroidDeck_Renderer"
|
|
||||||
#define RLOG(...) if(verboseLog) __android_log_print(ANDROID_LOG_DEBUG,WLOG_TAG,__VA_ARGS__)
|
|
||||||
#define RLOG_E(...) __android_log_print(ANDROID_LOG_ERROR,WLOG_TAG,__VA_ARGS__)
|
|
||||||
#define SCANOUT_LOG(...) __android_log_print(ANDROID_LOG_DEBUG,"DroidDeck_Scanout",__VA_ARGS__)
|
|
||||||
|
|
||||||
#include <vulkan/vulkan_android.h>
|
|
||||||
#include <android/hardware_buffer.h>
|
|
||||||
#include <android/native_window.h>
|
|
||||||
#include <vector>
|
|
||||||
#include <unordered_map>
|
|
||||||
#include <thread>
|
|
||||||
#include <atomic>
|
|
||||||
#include <mutex>
|
|
||||||
#include <shared_mutex>
|
|
||||||
#include <condition_variable>
|
|
||||||
#include <chrono>
|
|
||||||
|
|
||||||
#include "../scanout/ScanoutContext.h"
|
|
||||||
|
|
||||||
#include "lsfg/lsfg_probe.h"
|
|
||||||
#include <memory>
|
|
||||||
#include <string>
|
|
||||||
|
|
||||||
namespace lsfg { class Engine; }
|
|
||||||
namespace ddfg { class Engine; }
|
|
||||||
|
|
||||||
static constexpr uint32_t MAX_FRAMES_IN_FLIGHT = 2;
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
struct SgsrPushConstants {
|
|
||||||
float ndc[4];
|
|
||||||
float viewportInfo[4];
|
|
||||||
float edgeSharpness;
|
|
||||||
};
|
|
||||||
struct NisPushConstants {
|
|
||||||
float ndc[4];
|
|
||||||
float viewportInfo[4];
|
|
||||||
float sharpness;
|
|
||||||
};
|
|
||||||
struct EasuPushConstants {
|
|
||||||
float ndc[4];
|
|
||||||
uint32_t con0[4], con1[4], con2[4], con3[4];
|
|
||||||
float outW, outH;
|
|
||||||
};
|
|
||||||
struct RcasPushConstants {
|
|
||||||
float ndc[4];
|
|
||||||
uint32_t con[4];
|
|
||||||
float outW, outH;
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
struct CasPushConstants {
|
|
||||||
float ndc[4];
|
|
||||||
float resolution[2];
|
|
||||||
float sharpness;
|
|
||||||
float _pad;
|
|
||||||
};
|
|
||||||
struct HdrPushConstants {
|
|
||||||
float ndc[4];
|
|
||||||
float resolution[2];
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
struct FxaaPushConstants {
|
|
||||||
float ndc[4];
|
|
||||||
float resolution[2];
|
|
||||||
};
|
|
||||||
struct ToonPushConstants {
|
|
||||||
float ndc[4];
|
|
||||||
float resolution[2];
|
|
||||||
};
|
|
||||||
struct ColorPushConstants {
|
|
||||||
float ndc[4];
|
|
||||||
float brightness;
|
|
||||||
float contrast;
|
|
||||||
float gamma;
|
|
||||||
float saturation;
|
|
||||||
|
|
||||||
|
|
||||||
};
|
|
||||||
struct NtscPushConstants {
|
|
||||||
float ndc[4];
|
|
||||||
float resolution[2];
|
|
||||||
float frameCount;
|
|
||||||
};
|
|
||||||
struct CrtPushConstants {
|
|
||||||
float ndc[4];
|
|
||||||
float resolution[2];
|
|
||||||
};
|
|
||||||
struct DebandPushConstants {
|
|
||||||
float ndc[4];
|
|
||||||
float resolution[2];
|
|
||||||
float strength;
|
|
||||||
};
|
|
||||||
|
|
||||||
class VulkanRendererContext {
|
|
||||||
public:
|
|
||||||
VulkanRendererContext(ANativeWindow* window, int cWidth, int cHeight, void* adrenotoolsHandle = nullptr,
|
|
||||||
bool lsfgVk11Compat = false);
|
|
||||||
~VulkanRendererContext();
|
|
||||||
|
|
||||||
void onSurfaceResized(int width, int height);
|
|
||||||
void setTransform(float ox, float oy, float sx, float sy);
|
|
||||||
void setClipRegion(int x, int y, int w, int h);
|
|
||||||
void updatePointerPosition(short x, short y);
|
|
||||||
void updateWindowContent(int64_t id, void* pixels, short w, short h, short stride, int x, int y);
|
|
||||||
void updateWindowContentAHB(int64_t id, AHardwareBuffer* ahb, short w, short h, int x, int y);
|
|
||||||
void updateCursorImage(void* pixels, short w, short h, short hotX, short hotY);
|
|
||||||
void setCursorVisible(bool visible);
|
|
||||||
void setRenderList(const int64_t* ids, const int* xs, const int* ys, int count);
|
|
||||||
void removeWindow(int64_t id);
|
|
||||||
void clearBackbuffer() {}
|
|
||||||
void beginBatch() {}
|
|
||||||
void endBatch() {}
|
|
||||||
void initScanout();
|
|
||||||
void destroyScanout();
|
|
||||||
void applyScanoutBuffer();
|
|
||||||
void initScanoutFromWindows(ANativeWindow* gameWin, ANativeWindow* cursorWin);
|
|
||||||
void scanoutSetDst(int x, int y, int w, int h);
|
|
||||||
void scanoutSetBuffer(AHardwareBuffer* ahb, int x, int y, int w, int h, int fenceFd = -1);
|
|
||||||
void scanoutSetCursorImage(void* pixels, short w, short h, short stride);
|
|
||||||
void scanoutSetCursorPos(short x, short y, short hotX, short hotY);
|
|
||||||
ScanoutContext scanout;
|
|
||||||
std::atomic<bool>& scanoutActive = scanout.scanoutActive;
|
|
||||||
std::atomic<bool>& gameFrameDelivered = scanout.gameFrameDelivered;
|
|
||||||
std::atomic<bool> surfaceDetached{false};
|
|
||||||
|
|
||||||
void detachSurface();
|
|
||||||
bool reattachSurface(ANativeWindow* newWindow);
|
|
||||||
|
|
||||||
bool verboseLog = true;
|
|
||||||
void setVerboseLog(bool v) { verboseLog = v; scanout.setVerboseLog(v); }
|
|
||||||
void dumpRendererInfo();
|
|
||||||
|
|
||||||
std::string adrenoDriverPath;
|
|
||||||
std::string adrenoDriverName;
|
|
||||||
std::string adrenoNativeLibDir;
|
|
||||||
void* vulkanHandle = nullptr;
|
|
||||||
std::atomic<bool> scanoutBlackFrameDone{false};
|
|
||||||
PFN_vkGetInstanceProcAddr gipa = nullptr;
|
|
||||||
VkTable vk_ = {};
|
|
||||||
void loadCustomDriver();
|
|
||||||
void loadInstanceDispatch();
|
|
||||||
void loadDeviceDispatch();
|
|
||||||
|
|
||||||
void setFilterMode(int mode);
|
|
||||||
void setUpscaler(int mode);
|
|
||||||
void setHqDownscale(bool enabled);
|
|
||||||
void setCas(bool enabled, int sharpness);
|
|
||||||
void setHdr(bool enabled);
|
|
||||||
void setDeband(bool enabled, int strength);
|
|
||||||
void setUpscaleSharpness(int sharpness);
|
|
||||||
void setFxaa(bool enabled);
|
|
||||||
void setToon(bool enabled);
|
|
||||||
void setCrt(bool enabled);
|
|
||||||
void setNtsc(bool enabled);
|
|
||||||
void setColorGrade(float brightness, float contrast, float gamma, float saturation);
|
|
||||||
void setSwapRB(bool enabled);
|
|
||||||
void setPresentMode(VkPresentModeKHR mode);
|
|
||||||
std::vector<int> getSupportedPresentModes() const;
|
|
||||||
|
|
||||||
const lsfg::Caps& lsfgCaps() const { return lsfgCaps_; }
|
|
||||||
|
|
||||||
void setFrameGenArmed(bool armed, int multiplier);
|
|
||||||
bool frameGenArmed() const { return fgArmed_.load(std::memory_order_relaxed); }
|
|
||||||
void frameGenStats(float out[6]) const;
|
|
||||||
int frameGenProblem() const;
|
|
||||||
void setLsfgCachePath(const char* path);
|
|
||||||
static constexpr int32_t kFgCaptureGame = -1;
|
|
||||||
void setFrameGenTuning(float flowScale, float refreshHz, int32_t captureHeight = 0);
|
|
||||||
void setFrameGenEngine(int kind);
|
|
||||||
void setDdFgTuning(int model, int perfPreset);
|
|
||||||
|
|
||||||
private:
|
|
||||||
struct WinTex {
|
|
||||||
VkImage img = VK_NULL_HANDLE;
|
|
||||||
VkDeviceMemory mem = VK_NULL_HANDLE;
|
|
||||||
VkImageView view = VK_NULL_HANDLE;
|
|
||||||
VkDescriptorSet ds = VK_NULL_HANDLE;
|
|
||||||
VkBuffer stg = VK_NULL_HANDLE;
|
|
||||||
VkDeviceMemory stgMem = VK_NULL_HANDLE;
|
|
||||||
void* mapped = nullptr;
|
|
||||||
VkDeviceSize cap = 0;
|
|
||||||
int w = 0;
|
|
||||||
int h = 0;
|
|
||||||
bool dirty = false;
|
|
||||||
bool isAHB = false;
|
|
||||||
bool needsTransition = false;
|
|
||||||
AHardwareBuffer* ahb = nullptr;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct RenderEntry { int64_t id; int x, y; };
|
|
||||||
struct DrawEntry {
|
|
||||||
VkImage img = VK_NULL_HANDLE;
|
|
||||||
VkDescriptorSet ds = VK_NULL_HANDLE;
|
|
||||||
VkBuffer upload = VK_NULL_HANDLE;
|
|
||||||
int x=0, y=0, w=0, h=0;
|
|
||||||
bool needsTransition = false;
|
|
||||||
bool isAHB = false;
|
|
||||||
};
|
|
||||||
|
|
||||||
ANativeWindow* window;
|
|
||||||
int surfaceWidth, surfaceHeight, containerWidth, containerHeight;
|
|
||||||
std::atomic<int> clipRegionX{0}, clipRegionY{0}, clipRegionW{0}, clipRegionH{0};
|
|
||||||
void* adrenotoolsHandle = nullptr;
|
|
||||||
bool lsfgVk11Compat_ = false;
|
|
||||||
int filterMode = 0;
|
|
||||||
bool swapRB = false;
|
|
||||||
float maxAnisotropy = 1.0f;
|
|
||||||
bool cubicSupported = false;
|
|
||||||
VkPhysicalDeviceMemoryProperties memProperties{};
|
|
||||||
VkPresentModeKHR requestedPresentMode = VK_PRESENT_MODE_FIFO_KHR;
|
|
||||||
uint32_t graphicsQueueFamilyIndex = 0;
|
|
||||||
std::vector<VkPresentModeKHR> availablePresentModes;
|
|
||||||
|
|
||||||
std::unordered_map<int64_t, WinTex> texMap;
|
|
||||||
|
|
||||||
std::unordered_map<AHardwareBuffer*, WinTex> ahbImportCache;
|
|
||||||
std::unordered_map<int64_t, std::vector<AHardwareBuffer*>> windowAhbs;
|
|
||||||
|
|
||||||
std::vector<WinTex> deleteQueue;
|
|
||||||
std::vector<RenderEntry> renderList;
|
|
||||||
|
|
||||||
std::vector<DrawEntry> frameDraws;
|
|
||||||
std::vector<VkImageMemoryBarrier> frameAhbTransitions;
|
|
||||||
std::vector<VkImageMemoryBarrier> framePreUpload;
|
|
||||||
std::vector<VkImageMemoryBarrier> framePostUpload;
|
|
||||||
|
|
||||||
|
|
||||||
std::atomic<int> pointerX{0}, pointerY{0};
|
|
||||||
float sceneOffsetX=0.f, sceneOffsetY=0.f, sceneScaleX=1.f, sceneScaleY=1.f;
|
|
||||||
|
|
||||||
std::atomic<bool> cursorVisible{false};
|
|
||||||
short cursorHotX=0, cursorHotY=0, cursorTexW=0, cursorTexH=0;
|
|
||||||
std::vector<uint32_t> cursorPixels;
|
|
||||||
std::atomic<bool> isCursorImageDirty{false};
|
|
||||||
std::atomic<bool> cursorMoved{false};
|
|
||||||
|
|
||||||
VkImage cursorImg = VK_NULL_HANDLE;
|
|
||||||
VkDeviceMemory cursorMem = VK_NULL_HANDLE;
|
|
||||||
VkImageView cursorView = VK_NULL_HANDLE;
|
|
||||||
VkDescriptorSet cursorDS = VK_NULL_HANDLE;
|
|
||||||
VkBuffer cursorStg = VK_NULL_HANDLE;
|
|
||||||
VkDeviceMemory cursorStgM = VK_NULL_HANDLE;
|
|
||||||
void* cursorStgP = nullptr;
|
|
||||||
VkDeviceSize cursorStgC = 0;
|
|
||||||
VkDeviceSize cursorUploadSize = 0;
|
|
||||||
|
|
||||||
VkInstance instance;
|
|
||||||
VkSurfaceKHR surface;
|
|
||||||
VkPhysicalDevice physicalDevice;
|
|
||||||
VkDevice device;
|
|
||||||
VkQueue graphicsQueue;
|
|
||||||
VkSwapchainKHR swapchain = VK_NULL_HANDLE;
|
|
||||||
VkFormat swapchainFmt;
|
|
||||||
VkExtent2D swapchainExt;
|
|
||||||
|
|
||||||
std::vector<VkImage> swapchainImages;
|
|
||||||
std::vector<VkImageView> swapchainViews;
|
|
||||||
std::vector<VkFramebuffer> swapchainFBs;
|
|
||||||
|
|
||||||
VkRenderPass renderPass = VK_NULL_HANDLE;
|
|
||||||
VkDescriptorSetLayout dsLayout = VK_NULL_HANDLE;
|
|
||||||
VkPipelineLayout pipeLayout = VK_NULL_HANDLE;
|
|
||||||
|
|
||||||
VkPipeline pipeline = VK_NULL_HANDLE;
|
|
||||||
|
|
||||||
int upscalerMode = 0;
|
|
||||||
bool hqDownscale = false;
|
|
||||||
|
|
||||||
bool casEnabled = false;
|
|
||||||
int casSharpness = 60;
|
|
||||||
bool hdrEnabled = false;
|
|
||||||
float upscaleSharpness01 = 0.75f;
|
|
||||||
|
|
||||||
bool debandEnabled = false;
|
|
||||||
int debandStrength = 100;
|
|
||||||
|
|
||||||
bool fxaaEnabled = false;
|
|
||||||
bool toonEnabled = false;
|
|
||||||
bool crtEnabled = false;
|
|
||||||
bool ntscEnabled = false;
|
|
||||||
bool colorEnabled = false;
|
|
||||||
float colorBrightness = 0.0f;
|
|
||||||
float colorContrast = 0.0f;
|
|
||||||
float colorGamma = 1.0f;
|
|
||||||
float colorSaturation = 1.0f;
|
|
||||||
uint32_t ntscFrameCounter = 0;
|
|
||||||
|
|
||||||
VkSampler upscaleSampler = VK_NULL_HANDLE;
|
|
||||||
|
|
||||||
struct CompositeTarget {
|
|
||||||
VkImage img = VK_NULL_HANDLE;
|
|
||||||
VkDeviceMemory mem = VK_NULL_HANDLE;
|
|
||||||
VkImageView view = VK_NULL_HANDLE;
|
|
||||||
VkImageView storageView = VK_NULL_HANDLE;
|
|
||||||
VkFramebuffer fb = VK_NULL_HANDLE;
|
|
||||||
VkDescriptorSet ds = VK_NULL_HANDLE;
|
|
||||||
};
|
|
||||||
static constexpr uint32_t kMaxCompositeTargets = 7;
|
|
||||||
|
|
||||||
std::vector<CompositeTarget> compositeTargets;
|
|
||||||
VkRenderPass compositeRenderPass = VK_NULL_HANDLE;
|
|
||||||
uint32_t compositeW = 0, compositeH = 0;
|
|
||||||
uint32_t compositeIndex = 0;
|
|
||||||
bool compositeArmed = false;
|
|
||||||
bool swapchainTransferDst = false;
|
|
||||||
|
|
||||||
std::atomic<bool> fgArmed_{false};
|
|
||||||
std::atomic<int> fgMultiplier_{0};
|
|
||||||
std::atomic<float> fgFlowScale_{1.0f};
|
|
||||||
std::atomic<float> fgRefreshHz_{0.0f};
|
|
||||||
std::atomic<bool> fgConfigDirty_{true};
|
|
||||||
std::atomic<int32_t> fgCaptureHeight_{0};
|
|
||||||
void compositeExtentFor(uint32_t& w, uint32_t& h) const;
|
|
||||||
VkExtent2D renderExtent() const {
|
|
||||||
if (compositeActive() && (compositeW != swapchainExt.width || compositeH != swapchainExt.height))
|
|
||||||
return VkExtent2D{compositeW, compositeH};
|
|
||||||
return swapchainExt;
|
|
||||||
}
|
|
||||||
void recordCompositeToSwapchainTransfer(VkCommandBuffer cb, VkImage src, uint32_t imgIdx);
|
|
||||||
|
|
||||||
bool createCompositeRenderPass();
|
|
||||||
bool ensureCompositeTargets(uint32_t w, uint32_t h, uint32_t count);
|
|
||||||
void destroyCompositeTargets();
|
|
||||||
bool compositeActive() const;
|
|
||||||
VkRenderPass targetRenderPass() const;
|
|
||||||
VkFramebuffer targetFramebuffer(uint32_t imgIdx) const;
|
|
||||||
void copyCompositeToSwapchain(VkCommandBuffer cb, uint32_t imgIdx);
|
|
||||||
|
|
||||||
VkRenderPass cursorOverlayRenderPass = VK_NULL_HANDLE;
|
|
||||||
struct CursorOverlay {
|
|
||||||
bool draw = false;
|
|
||||||
float ox = 0, oy = 0, sx = 0, sy = 0, cw = 0, ch = 0;
|
|
||||||
short ptrX = 0, ptrY = 0, hotX = 0, hotY = 0, w = 0, h = 0;
|
|
||||||
};
|
|
||||||
CursorOverlay cursorOverlay_{};
|
|
||||||
|
|
||||||
bool createCursorOverlayRenderPass();
|
|
||||||
void recordCursorOverlay(VkCommandBuffer cb, uint32_t imgIdx);
|
|
||||||
bool cursorDrawnPerPresent() const;
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
static constexpr uint32_t kMaxPresentsPerFrame = 4;
|
|
||||||
struct FrameGenPlan {
|
|
||||||
uint32_t generations = 0;
|
|
||||||
uint32_t presents = 1;
|
|
||||||
uint32_t imgIdx[kMaxPresentsPerFrame] = {};
|
|
||||||
};
|
|
||||||
FrameGenPlan fgPlan_{};
|
|
||||||
std::unique_ptr<lsfg::Engine> lsfgEngine_;
|
|
||||||
uint64_t fgSourceFrames_ = 0;
|
|
||||||
std::string lsfgCachePath_;
|
|
||||||
bool lsfgEngineTried_ = false;
|
|
||||||
std::unique_ptr<ddfg::Engine> ddfgEngine_;
|
|
||||||
bool ddfgEngineTried_ = false;
|
|
||||||
std::atomic<int> fgEngineKind_{0};
|
|
||||||
std::atomic<int> fgModel_{4};
|
|
||||||
std::atomic<int> fgPerfPreset_{1};
|
|
||||||
bool ensureDdFgEngine();
|
|
||||||
bool fgCapsOk() const;
|
|
||||||
|
|
||||||
uint32_t syncSlot(uint32_t k) const { return currentFrame * kMaxPresentsPerFrame + k; }
|
|
||||||
void recreateSyncObjects();
|
|
||||||
uint32_t fgAcquireFailLog_ = 0;
|
|
||||||
|
|
||||||
float fgPresentedRate_ = 0.0f;
|
|
||||||
float fgSourceRate_ = 0.0f;
|
|
||||||
uint32_t fgSourceAccum_ = 0;
|
|
||||||
uint32_t fgPresentAccum_ = 0;
|
|
||||||
std::chrono::steady_clock::time_point fgRateWindowStart_{};
|
|
||||||
bool fgRateWindowOpen_ = false;
|
|
||||||
void trackPresentedRate(uint32_t presents);
|
|
||||||
|
|
||||||
bool ensureLsfgEngine();
|
|
||||||
uint32_t cmdSlot(uint32_t k) const { return currentFrame * kMaxPresentsPerFrame + k; }
|
|
||||||
void recordFrameGenProcess(VkCommandBuffer cb);
|
|
||||||
void recordFrameGenGeneration(VkCommandBuffer cb, uint32_t g);
|
|
||||||
|
|
||||||
VkQueryPool fgQueryPool_ = VK_NULL_HANDLE;
|
|
||||||
bool fgTimestampsOk_ = false;
|
|
||||||
float fgTimestampPeriodNs_ = 0.0f;
|
|
||||||
bool fgQueryPending_[MAX_FRAMES_IN_FLIGHT] = {};
|
|
||||||
uint32_t fgQueryGens_[MAX_FRAMES_IN_FLIGHT] = {};
|
|
||||||
float fgChainMsPerGen_ = -1.0f;
|
|
||||||
uint32_t fgChainLogCount_ = 0;
|
|
||||||
void ensureFgQueryPool();
|
|
||||||
void destroyFgQueryPool();
|
|
||||||
void readFgQueryResult();
|
|
||||||
|
|
||||||
VkFormat offscreenFmt = VK_FORMAT_R8G8B8A8_UNORM;
|
|
||||||
VkRenderPass offscreenRenderPass = VK_NULL_HANDLE;
|
|
||||||
VkPipelineLayout postPipeLayout = VK_NULL_HANDLE;
|
|
||||||
VkPipeline sgsrPipeline = VK_NULL_HANDLE;
|
|
||||||
VkPipeline nisPipeline = VK_NULL_HANDLE;
|
|
||||||
VkPipeline sgsrQualityPipeline = VK_NULL_HANDLE;
|
|
||||||
VkPipeline easuPipeline = VK_NULL_HANDLE;
|
|
||||||
VkPipeline rcasPipeline = VK_NULL_HANDLE;
|
|
||||||
VkPipeline downscalePipeline = VK_NULL_HANDLE;
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
VkPipeline casPipelineOff = VK_NULL_HANDLE;
|
|
||||||
VkPipeline casPipelineSwap = VK_NULL_HANDLE;
|
|
||||||
VkPipeline hdrPipelineOff = VK_NULL_HANDLE;
|
|
||||||
VkPipeline hdrPipelineSwap = VK_NULL_HANDLE;
|
|
||||||
VkPipeline fxaaPipelineOff = VK_NULL_HANDLE;
|
|
||||||
VkPipeline fxaaPipelineSwap = VK_NULL_HANDLE;
|
|
||||||
VkPipeline toonPipelineOff = VK_NULL_HANDLE;
|
|
||||||
VkPipeline toonPipelineSwap = VK_NULL_HANDLE;
|
|
||||||
VkPipeline colorPipelineOff = VK_NULL_HANDLE;
|
|
||||||
VkPipeline colorPipelineSwap = VK_NULL_HANDLE;
|
|
||||||
VkPipeline ntscPipelineOff = VK_NULL_HANDLE;
|
|
||||||
VkPipeline ntscPipelineSwap = VK_NULL_HANDLE;
|
|
||||||
VkPipeline crtPipelineOff = VK_NULL_HANDLE;
|
|
||||||
VkPipeline crtPipelineSwap = VK_NULL_HANDLE;
|
|
||||||
VkPipeline debandPipelineSwap = VK_NULL_HANDLE;
|
|
||||||
|
|
||||||
VkImage offscreenImg = VK_NULL_HANDLE;
|
|
||||||
VkDeviceMemory offscreenMem = VK_NULL_HANDLE;
|
|
||||||
VkImageView offscreenView = VK_NULL_HANDLE;
|
|
||||||
VkFramebuffer offscreenFB = VK_NULL_HANDLE;
|
|
||||||
VkDescriptorSet offscreenDS = VK_NULL_HANDLE;
|
|
||||||
int offscreenW = 0, offscreenH = 0;
|
|
||||||
|
|
||||||
VkImage midImg = VK_NULL_HANDLE;
|
|
||||||
VkDeviceMemory midMem = VK_NULL_HANDLE;
|
|
||||||
VkImageView midView = VK_NULL_HANDLE;
|
|
||||||
VkFramebuffer midFB = VK_NULL_HANDLE;
|
|
||||||
VkDescriptorSet midDS = VK_NULL_HANDLE;
|
|
||||||
int midW = 0, midH = 0;
|
|
||||||
|
|
||||||
VkImage fx1Img = VK_NULL_HANDLE;
|
|
||||||
VkDeviceMemory fx1Mem = VK_NULL_HANDLE;
|
|
||||||
VkImageView fx1View = VK_NULL_HANDLE;
|
|
||||||
VkFramebuffer fx1FB = VK_NULL_HANDLE;
|
|
||||||
VkDescriptorSet fx1DS = VK_NULL_HANDLE;
|
|
||||||
int fx1W = 0, fx1H = 0;
|
|
||||||
|
|
||||||
VkImage fx2Img = VK_NULL_HANDLE;
|
|
||||||
VkDeviceMemory fx2Mem = VK_NULL_HANDLE;
|
|
||||||
VkImageView fx2View = VK_NULL_HANDLE;
|
|
||||||
VkFramebuffer fx2FB = VK_NULL_HANDLE;
|
|
||||||
VkDescriptorSet fx2DS = VK_NULL_HANDLE;
|
|
||||||
int fx2W = 0, fx2H = 0;
|
|
||||||
|
|
||||||
struct UpscaleFrame {
|
|
||||||
bool active = false;
|
|
||||||
int mode = 0;
|
|
||||||
int outX = 0, outY = 0, outW = 0, outH = 0;
|
|
||||||
bool cas = false;
|
|
||||||
bool hdr = false;
|
|
||||||
bool fxaa = false;
|
|
||||||
bool toon = false;
|
|
||||||
bool color = false;
|
|
||||||
bool ntsc = false;
|
|
||||||
bool crt = false;
|
|
||||||
bool deband = false;
|
|
||||||
SgsrPushConstants sgsrPC{};
|
|
||||||
NisPushConstants nisPC{};
|
|
||||||
EasuPushConstants easuPC{};
|
|
||||||
RcasPushConstants rcasPC{};
|
|
||||||
CasPushConstants casPC{};
|
|
||||||
HdrPushConstants hdrPC{};
|
|
||||||
FxaaPushConstants fxaaPC{};
|
|
||||||
ToonPushConstants toonPC{};
|
|
||||||
ColorPushConstants colorPC{};
|
|
||||||
NtscPushConstants ntscPC{};
|
|
||||||
CrtPushConstants crtPC{};
|
|
||||||
DebandPushConstants debandPC{};
|
|
||||||
} upFrame;
|
|
||||||
|
|
||||||
VkCommandPool cmdPool = VK_NULL_HANDLE;
|
|
||||||
std::vector<VkCommandBuffer> cmdBufs;
|
|
||||||
|
|
||||||
std::vector<VkSemaphore> imgAvailSems;
|
|
||||||
std::vector<VkSemaphore> renderDoneSems;
|
|
||||||
std::vector<VkFence> inFlightFences;
|
|
||||||
std::vector<VkFence> imgInFlight;
|
|
||||||
uint32_t currentFrame = 0;
|
|
||||||
|
|
||||||
VkSampler sampler = VK_NULL_HANDLE;
|
|
||||||
VkDescriptorPool winTexPool = VK_NULL_HANDLE;
|
|
||||||
|
|
||||||
std::atomic<bool> needsRender{false};
|
|
||||||
std::thread renderThread;
|
|
||||||
std::atomic<bool> isRunning{false};
|
|
||||||
std::atomic<bool> fbResized{false};
|
|
||||||
std::mutex renderMutex;
|
|
||||||
std::mutex dirtyMutex;
|
|
||||||
std::condition_variable dirtyCV;
|
|
||||||
std::shared_mutex frameMutex;
|
|
||||||
|
|
||||||
void createInstance();
|
|
||||||
void createSurface();
|
|
||||||
void pickPhysicalDevice();
|
|
||||||
lsfg::Caps lsfgCaps_{};
|
|
||||||
|
|
||||||
void createLogicalDevice();
|
|
||||||
void createSwapchain();
|
|
||||||
void createRenderPass();
|
|
||||||
void createDSLayout();
|
|
||||||
void createPipeline(bool blend, VkPipeline& out);
|
|
||||||
void createFramebuffers();
|
|
||||||
void createCmdPool();
|
|
||||||
void createSampler();
|
|
||||||
void createUpscaleSampler();
|
|
||||||
void createOffscreenRenderPass();
|
|
||||||
void createPostPipelines();
|
|
||||||
VkPipeline createPostPipeline(const uint32_t* fragCode, size_t fragSz, VkRenderPass rp);
|
|
||||||
bool createColorTarget(int w, int h, VkImage& img, VkDeviceMemory& mem,
|
|
||||||
VkImageView& view, VkFramebuffer& fb, VkDescriptorSet& ds);
|
|
||||||
void destroyColorTarget(VkImage& img, VkDeviceMemory& mem, VkImageView& view,
|
|
||||||
VkFramebuffer& fb, VkDescriptorSet& ds);
|
|
||||||
bool ensureOffscreen(int w, int h);
|
|
||||||
bool ensureMid(int w, int h);
|
|
||||||
bool ensureFx1(int w, int h);
|
|
||||||
bool ensureFx2(int w, int h);
|
|
||||||
void recordUpscalePasses(VkCommandBuffer cb, uint32_t imgIdx,
|
|
||||||
const std::vector<DrawEntry>& draws, bool cursorDrawn,
|
|
||||||
short ptrX, short ptrY, short curHotX, short curHotY,
|
|
||||||
short curW, short curH,
|
|
||||||
float ox, float oy, float sx, float sy,
|
|
||||||
float cw, float ch);
|
|
||||||
void planUpscaleFrame();
|
|
||||||
void createWinTexPool();
|
|
||||||
void createCursorPipeline();
|
|
||||||
void createCursorDS();
|
|
||||||
void createCmdBufs();
|
|
||||||
void createSyncObjects();
|
|
||||||
void cleanupSwapchain();
|
|
||||||
|
|
||||||
bool createWinTexResources(WinTex& wt, int w, int h);
|
|
||||||
bool importAHBToWinTex(WinTex& wt, AHardwareBuffer* ahb);
|
|
||||||
void cleanupAllAHBCache();
|
|
||||||
void flushDeleteQueue();
|
|
||||||
void destroyWinTex(WinTex& wt);
|
|
||||||
void ensureCursorTex(short w, short h);
|
|
||||||
void cleanupCursorTex();
|
|
||||||
void ensureCursorStaging(VkDeviceSize sz);
|
|
||||||
|
|
||||||
void recordCmdBuf(VkCommandBuffer cb, uint32_t imgIdx,
|
|
||||||
const std::vector<DrawEntry>& draws,
|
|
||||||
std::vector<VkImageMemoryBarrier>& ahbTransitions,
|
|
||||||
std::vector<VkImageMemoryBarrier>& preUpload,
|
|
||||||
std::vector<VkImageMemoryBarrier>& postUpload,
|
|
||||||
VkBuffer cursorUpload, bool hasCursorUpload,
|
|
||||||
float ox, float oy, float sx, float sy, float cw, float ch,
|
|
||||||
short ptrX, short ptrY, short curHotX, short curHotY,
|
|
||||||
short curW, short curH, bool curVis);
|
|
||||||
void renderLoop();
|
|
||||||
void renderFrame();
|
|
||||||
|
|
||||||
uint32_t findMemType(uint32_t filter, VkMemoryPropertyFlags props);
|
|
||||||
void createBuffer(VkDeviceSize sz, VkBufferUsageFlags usage,
|
|
||||||
VkMemoryPropertyFlags props, VkBuffer& buf, VkDeviceMemory& mem);
|
|
||||||
VkCommandBuffer beginOneTime();
|
|
||||||
void endOneTime(VkCommandBuffer cmd);
|
|
||||||
void transition(VkCommandBuffer cmd, VkImage img,
|
|
||||||
VkImageLayout oldL, VkImageLayout newL,
|
|
||||||
VkAccessFlags srcA, VkAccessFlags dstA,
|
|
||||||
VkPipelineStageFlags srcS, VkPipelineStageFlags dstS);
|
|
||||||
VkShaderModule makeShader(const uint32_t* code, size_t sz);
|
|
||||||
};
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
#include "ddfg_vkd.h"
|
#include "ddfg_vkd.h"
|
||||||
#include "../VulkanRendererContext.h"
|
#include "../VkDispatchTable.h"
|
||||||
#include <android/log.h>
|
#include <android/log.h>
|
||||||
|
|
||||||
bool ddfgVkdInit(const VkTable& table, ddfg::DeviceDispatch& dd, ddfg::InstanceDispatch& id) {
|
bool ddfgVkdInit(const VkTable& table, ddfg::DeviceDispatch& dd, ddfg::InstanceDispatch& id) {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
|
|
||||||
#include "lsfg_probe.h"
|
#include "lsfg_probe.h"
|
||||||
#include "../VulkanRendererContext.h"
|
#include "../VkDispatchTable.h"
|
||||||
|
|
||||||
#include <cstdio>
|
#include <cstdio>
|
||||||
#include <cstring>
|
#include <cstring>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
|
|
||||||
#include "lsfg_vkd.h"
|
#include "lsfg_vkd.h"
|
||||||
#include "../VulkanRendererContext.h"
|
#include "../VkDispatchTable.h"
|
||||||
|
|
||||||
#include <android/log.h>
|
#include <android/log.h>
|
||||||
|
|
||||||
|
|||||||
@@ -1,82 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
|
|
||||||
#include <android/hardware_buffer.h>
|
|
||||||
#include <android/native_window.h>
|
|
||||||
#include <android/rect.h>
|
|
||||||
#include <android/log.h>
|
|
||||||
#include <atomic>
|
|
||||||
#include <mutex>
|
|
||||||
#include <cstdint>
|
|
||||||
|
|
||||||
#ifndef SCANOUT_LOG
|
|
||||||
#define SCANOUT_LOG(...) __android_log_print(ANDROID_LOG_DEBUG,"DroidDeck_Scanout",__VA_ARGS__)
|
|
||||||
#endif
|
|
||||||
|
|
||||||
class ScanoutContext {
|
|
||||||
public:
|
|
||||||
bool loadApi();
|
|
||||||
void initFromWindow(ANativeWindow* win = nullptr);
|
|
||||||
void initFromWindows(ANativeWindow* gameWin, ANativeWindow* cursorWin);
|
|
||||||
void destroy();
|
|
||||||
|
|
||||||
void setBuffer(AHardwareBuffer* ahb, int x, int y, int w, int h, int fenceFd = -1);
|
|
||||||
|
|
||||||
bool setCursorImage(void* pixels, short w, short h, short stride);
|
|
||||||
bool setCursorPos(short x, short y, short hotX, short hotY);
|
|
||||||
void applyPendingCursor();
|
|
||||||
|
|
||||||
void setDst(int x, int y, int w, int h);
|
|
||||||
void setContainerSize(int w, int h) { containerWidth = w; containerHeight = h; }
|
|
||||||
void setSurfaceSize(int w, int h) { surfaceWidth = w; surfaceHeight = h; }
|
|
||||||
void setFallbackWindow(ANativeWindow* win) { window = win; }
|
|
||||||
void setVerboseLog(bool v) { verboseLog = v; }
|
|
||||||
|
|
||||||
bool isActive() const { return scanoutActive.load(); }
|
|
||||||
bool isGameFrameDelivered() const {
|
|
||||||
return gameFrameDelivered.load(std::memory_order_acquire);
|
|
||||||
}
|
|
||||||
void* debugGameSC() const { return scanoutGameSC; }
|
|
||||||
|
|
||||||
std::atomic<bool> scanoutActive{false};
|
|
||||||
std::atomic<bool> gameFrameDelivered{false};
|
|
||||||
|
|
||||||
private:
|
|
||||||
ANativeWindow* window = nullptr;
|
|
||||||
bool verboseLog = true;
|
|
||||||
|
|
||||||
int surfaceWidth = 0, surfaceHeight = 0, containerWidth = 0, containerHeight = 0;
|
|
||||||
|
|
||||||
void* scanoutGameSC = nullptr;
|
|
||||||
void* scanoutCursorSC = nullptr;
|
|
||||||
void* scanoutCursorBuf = nullptr;
|
|
||||||
int32_t scanoutCursorBufW = 0;
|
|
||||||
int32_t scanoutCursorBufH = 0;
|
|
||||||
|
|
||||||
void* scanoutTx = nullptr;
|
|
||||||
void* scanoutGameTx = nullptr;
|
|
||||||
|
|
||||||
ARect scanoutLastSrc{}, scanoutLastDst{};
|
|
||||||
bool scanoutGeoDirty = true;
|
|
||||||
bool scanoutVisShown = false;
|
|
||||||
bool scanoutApiLoaded = false;
|
|
||||||
|
|
||||||
void* fnSCCreateFromWin = nullptr;
|
|
||||||
void* fnSCRelease = nullptr;
|
|
||||||
void* fnSTCreate = nullptr;
|
|
||||||
void* fnSTDelete = nullptr;
|
|
||||||
void* fnSTApply = nullptr;
|
|
||||||
void* fnSTSetBuffer = nullptr;
|
|
||||||
void* fnSTSetZOrder = nullptr;
|
|
||||||
void* fnSTSetVisibility = nullptr;
|
|
||||||
void* fnSTSetGeometry = nullptr;
|
|
||||||
|
|
||||||
int32_t scanoutDstX = 0, scanoutDstY = 0, scanoutDstW = 0, scanoutDstH = 0;
|
|
||||||
bool gameScVisible = false;
|
|
||||||
|
|
||||||
std::mutex scanoutMutex;
|
|
||||||
|
|
||||||
short pendingCursorX = 0, pendingCursorY = 0, pendingCursorHotX = 0, pendingCursorHotY = 0;
|
|
||||||
bool cursorPosDirty = false;
|
|
||||||
bool cursorImageDirty = false;
|
|
||||||
};
|
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
add_library(droiddeckwayland SHARED
|
add_library(droiddeckwayland SHARED
|
||||||
src/compositor.c
|
src/compositor.c
|
||||||
|
src/clock_domain.c
|
||||||
src/vk_present.c
|
src/vk_present.c
|
||||||
src/effects_chain.c
|
src/effects_chain.c
|
||||||
src/cardboard.c
|
src/cardboard.c
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
#define _GNU_SOURCE
|
||||||
|
#include "clock_domain.h"
|
||||||
|
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <pthread.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <sys/mman.h>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <time.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
static const int64_t *g_shift;
|
||||||
|
static pthread_mutex_t g_control_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||||
|
static dev_t g_device;
|
||||||
|
static ino_t g_inode;
|
||||||
|
|
||||||
|
void droiddeck_clock_domain_set_control(const char *path) {
|
||||||
|
int fd;
|
||||||
|
struct stat st;
|
||||||
|
pthread_mutex_lock(&g_control_lock);
|
||||||
|
if (!path || !*path) {
|
||||||
|
const int64_t *previous = g_shift;
|
||||||
|
g_shift = NULL;
|
||||||
|
if (previous) munmap((void *)previous, sizeof(*previous));
|
||||||
|
pthread_mutex_unlock(&g_control_lock);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
fd = open(path, O_RDONLY | O_CLOEXEC);
|
||||||
|
if (fd < 0 || fstat(fd, &st) != 0 || st.st_size < (off_t)sizeof(int64_t)) {
|
||||||
|
if (fd >= 0) close(fd);
|
||||||
|
pthread_mutex_unlock(&g_control_lock);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (g_shift && st.st_dev == g_device && st.st_ino == g_inode) {
|
||||||
|
close(fd);
|
||||||
|
pthread_mutex_unlock(&g_control_lock);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const int64_t *shift = mmap(NULL, sizeof(*shift), PROT_READ, MAP_SHARED, fd, 0);
|
||||||
|
close(fd);
|
||||||
|
if (shift != MAP_FAILED) {
|
||||||
|
g_device = st.st_dev;
|
||||||
|
g_inode = st.st_ino;
|
||||||
|
const int64_t *previous = g_shift;
|
||||||
|
g_shift = shift;
|
||||||
|
if (previous) munmap((void *)previous, sizeof(*previous));
|
||||||
|
}
|
||||||
|
pthread_mutex_unlock(&g_control_lock);
|
||||||
|
}
|
||||||
|
|
||||||
|
static int64_t shift_ns(void) {
|
||||||
|
pthread_mutex_lock(&g_control_lock);
|
||||||
|
const int64_t *mapping = g_shift;
|
||||||
|
int64_t shift = mapping ? __atomic_load_n(mapping, __ATOMIC_RELAXED) : 0;
|
||||||
|
pthread_mutex_unlock(&g_control_lock);
|
||||||
|
return shift > 0 ? shift : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int64_t droiddeck_clock_domain_adjust_ns(int64_t value) {
|
||||||
|
int64_t shift = shift_ns();
|
||||||
|
return value > shift ? value - shift : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int64_t droiddeck_clock_domain_now_ns(void) {
|
||||||
|
struct timespec ts;
|
||||||
|
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||||
|
return droiddeck_clock_domain_adjust_ns((int64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec);
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t droiddeck_clock_domain_now_ms(void) {
|
||||||
|
return (uint32_t)(droiddeck_clock_domain_now_ns() / 1000000LL);
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
#ifndef DROIDDECK_CLOCK_DOMAIN_H
|
||||||
|
#define DROIDDECK_CLOCK_DOMAIN_H
|
||||||
|
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
void droiddeck_clock_domain_set_control(const char *path);
|
||||||
|
int64_t droiddeck_clock_domain_now_ns(void);
|
||||||
|
uint32_t droiddeck_clock_domain_now_ms(void);
|
||||||
|
int64_t droiddeck_clock_domain_adjust_ns(int64_t value);
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -36,6 +36,7 @@
|
|||||||
#include "droiddeck_ext.h"
|
#include "droiddeck_ext.h"
|
||||||
#include "droiddeck_color.h"
|
#include "droiddeck_color.h"
|
||||||
#include "compositor_internal.h"
|
#include "compositor_internal.h"
|
||||||
|
#include "clock_domain.h"
|
||||||
|
|
||||||
#define WLOGI(...) __android_log_print(ANDROID_LOG_INFO, "DroidDeckWayland", __VA_ARGS__)
|
#define WLOGI(...) __android_log_print(ANDROID_LOG_INFO, "DroidDeckWayland", __VA_ARGS__)
|
||||||
#define WLOGE(...) __android_log_print(ANDROID_LOG_ERROR, "DroidDeckWayland", __VA_ARGS__)
|
#define WLOGE(...) __android_log_print(ANDROID_LOG_ERROR, "DroidDeckWayland", __VA_ARGS__)
|
||||||
@@ -126,6 +127,9 @@ static int log_budget(void) {
|
|||||||
#ifndef BTN_RIGHT
|
#ifndef BTN_RIGHT
|
||||||
#define BTN_RIGHT 0x111
|
#define BTN_RIGHT 0x111
|
||||||
#endif
|
#endif
|
||||||
|
#ifndef BTN_MIDDLE
|
||||||
|
#define BTN_MIDDLE 0x112
|
||||||
|
#endif
|
||||||
|
|
||||||
#define INPUT_SPACE_W 1920
|
#define INPUT_SPACE_W 1920
|
||||||
#define INPUT_SPACE_H 1080
|
#define INPUT_SPACE_H 1080
|
||||||
@@ -581,6 +585,13 @@ int droiddeck_cursor_snapshot(int *out, int cap) {
|
|||||||
}
|
}
|
||||||
struct active_touch { struct surface *surface; int pointer_fallback; };
|
struct active_touch { struct surface *surface; int pointer_fallback; };
|
||||||
static struct active_touch g_touch_points[MAX_TOUCH_POINTS];
|
static struct active_touch g_touch_points[MAX_TOUCH_POINTS];
|
||||||
|
#define PEN_IN (1 << 0)
|
||||||
|
#define PEN_TIP (1 << 1)
|
||||||
|
#define PEN_RIGHT (1 << 2)
|
||||||
|
#define PEN_MIDDLE (1 << 3)
|
||||||
|
#define PEN_BIT(button) (1 << ((button) - BTN_LEFT))
|
||||||
|
struct pen_state { int in, buttons; struct surface *grab; };
|
||||||
|
static struct pen_state g_pen;
|
||||||
static void touch_cancel_surface(struct surface *surface);
|
static void touch_cancel_surface(struct surface *surface);
|
||||||
static struct surface *g_grab;
|
static struct surface *g_grab;
|
||||||
static void publish_query_state(void);
|
static void publish_query_state(void);
|
||||||
@@ -727,9 +738,7 @@ static void on_pending_buffer_destroyed(struct wl_listener *l, void *data) {
|
|||||||
static void fire_frames(struct wl_list *frames) {
|
static void fire_frames(struct wl_list *frames) {
|
||||||
struct wl_resource *cb, *tmp;
|
struct wl_resource *cb, *tmp;
|
||||||
uint32_t t;
|
uint32_t t;
|
||||||
struct timespec ts;
|
t = droiddeck_clock_domain_now_ms();
|
||||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
|
||||||
t = (uint32_t)(ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
|
|
||||||
wl_resource_for_each_safe(cb, tmp, frames) {
|
wl_resource_for_each_safe(cb, tmp, frames) {
|
||||||
wl_callback_send_done(cb, t);
|
wl_callback_send_done(cb, t);
|
||||||
wl_resource_destroy(cb);
|
wl_resource_destroy(cb);
|
||||||
@@ -1061,6 +1070,7 @@ static int64_t presented_ns(int64_t render_ns) {
|
|||||||
|
|
||||||
static void feedback_present_all(struct wl_list *list, int64_t t) {
|
static void feedback_present_all(struct wl_list *list, int64_t t) {
|
||||||
struct wl_resource *fb, *tmp;
|
struct wl_resource *fb, *tmp;
|
||||||
|
t = droiddeck_clock_domain_adjust_ns(t);
|
||||||
uint64_t sec = (uint64_t)(t / 1000000000LL);
|
uint64_t sec = (uint64_t)(t / 1000000000LL);
|
||||||
uint32_t nsec = (uint32_t)(t % 1000000000LL);
|
uint32_t nsec = (uint32_t)(t % 1000000000LL);
|
||||||
wl_resource_for_each_safe(fb, tmp, list) {
|
wl_resource_for_each_safe(fb, tmp, list) {
|
||||||
@@ -1339,6 +1349,7 @@ static void surface_resource_destroy(struct wl_resource *r) {
|
|||||||
if (g_grab == s) g_grab = NULL;
|
if (g_grab == s) g_grab = NULL;
|
||||||
if (g_key_target == s) g_key_target = NULL;
|
if (g_key_target == s) g_key_target = NULL;
|
||||||
if (g_ime_click == s) g_ime_click = NULL;
|
if (g_ime_click == s) g_ime_click = NULL;
|
||||||
|
if (g_pen.grab == s) g_pen.grab = NULL;
|
||||||
droiddeck_text_input_surface_gone(r);
|
droiddeck_text_input_surface_gone(r);
|
||||||
if (g_desktop == s) { g_desktop = NULL; droiddeck_log("desktop", "the desktop closed"); }
|
if (g_desktop == s) { g_desktop = NULL; droiddeck_log("desktop", "the desktop closed"); }
|
||||||
if (g_hud_surface == s) { g_hud_surface = NULL; droiddeck_on_game_surface(NULL, NULL); }
|
if (g_hud_surface == s) { g_hud_surface = NULL; droiddeck_on_game_surface(NULL, NULL); }
|
||||||
@@ -2493,8 +2504,7 @@ static void on_vsync(int64_t frame_time_ns) {
|
|||||||
|
|
||||||
|
|
||||||
static uint32_t now_ms(void) {
|
static uint32_t now_ms(void) {
|
||||||
struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts);
|
return droiddeck_clock_domain_now_ms();
|
||||||
return (uint32_t)(ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static void pointer_set_cursor(struct wl_client *c, struct wl_resource *r, uint32_t serial,
|
static void pointer_set_cursor(struct wl_client *c, struct wl_resource *r, uint32_t serial,
|
||||||
@@ -3114,12 +3124,10 @@ static void relative_pointers_pointer_gone(struct wl_resource *pointer) {
|
|||||||
|
|
||||||
static int send_relative_motion(struct wl_client *client, double dx, double dy) {
|
static int send_relative_motion(struct wl_client *client, double dx, double dy) {
|
||||||
struct relative_pointer *rp;
|
struct relative_pointer *rp;
|
||||||
struct timespec ts;
|
|
||||||
uint64_t ut;
|
uint64_t ut;
|
||||||
int sent = 0;
|
int sent = 0;
|
||||||
if (dx == 0 && dy == 0) return 0;
|
if (dx == 0 && dy == 0) return 0;
|
||||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
ut = (uint64_t)(droiddeck_clock_domain_now_ns() / 1000);
|
||||||
ut = (uint64_t)ts.tv_sec * 1000000ULL + (uint64_t)ts.tv_nsec / 1000;
|
|
||||||
wl_list_for_each(rp, &g_relative_pointers, link) {
|
wl_list_for_each(rp, &g_relative_pointers, link) {
|
||||||
if (!rp->pointer || wl_resource_get_client(rp->pointer) != client) continue;
|
if (!rp->pointer || wl_resource_get_client(rp->pointer) != client) continue;
|
||||||
zwp_relative_pointer_v1_send_relative_motion(rp->resource, (uint32_t)(ut >> 32), (uint32_t)ut,
|
zwp_relative_pointer_v1_send_relative_motion(rp->resource, (uint32_t)(ut >> 32), (uint32_t)ut,
|
||||||
@@ -3243,14 +3251,14 @@ static void deliver_pointer(const struct input_msg *m) {
|
|||||||
pointer_event(x, y, m->p1 == 1 ? 0 : BTN_LEFT, m->p1 == 0);
|
pointer_event(x, y, m->p1 == 1 ? 0 : BTN_LEFT, m->p1 == 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
static void input_output_to_scene(int px, int py, double *x, double *y) {
|
static void input_output_to_scene(double px, double py, double *x, double *y) {
|
||||||
int w, h, ow, oh;
|
int w, h, ow, oh;
|
||||||
scene_size(&w, &h);
|
scene_size(&w, &h);
|
||||||
vkp_output_size(&ow, &oh);
|
vkp_output_size(&ow, &oh);
|
||||||
if (ow <= 0 || oh <= 0 ||
|
if (ow <= 0 || oh <= 0 ||
|
||||||
!vkp_output_to_scene((double)px * ow / INPUT_SPACE_W, (double)py * oh / INPUT_SPACE_H, x, y)) {
|
!vkp_output_to_scene(px * ow / INPUT_SPACE_W, py * oh / INPUT_SPACE_H, x, y)) {
|
||||||
*x = (double)px * w / INPUT_SPACE_W;
|
*x = px * w / INPUT_SPACE_W;
|
||||||
*y = (double)py * h / INPUT_SPACE_H;
|
*y = py * h / INPUT_SPACE_H;
|
||||||
}
|
}
|
||||||
if (*x < 0) *x = 0;
|
if (*x < 0) *x = 0;
|
||||||
if (*y < 0) *y = 0;
|
if (*y < 0) *y = 0;
|
||||||
@@ -3479,6 +3487,57 @@ static void deliver_touch(const struct input_msg *m) {
|
|||||||
publish_query_state();
|
publish_query_state();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static void pen_log_target(void) {
|
||||||
|
static struct wl_client *said;
|
||||||
|
for (int i = 0; i < g_nptrs; i++) {
|
||||||
|
if (!g_ptrs[i].focus) continue;
|
||||||
|
struct wl_client *client = wl_resource_get_client(g_ptrs[i].focus);
|
||||||
|
if (client != said && log_budget()) {
|
||||||
|
char name[160];
|
||||||
|
describe(wl_resource_get_user_data(g_ptrs[i].focus), name, sizeof(name));
|
||||||
|
droiddeck_log("pen", "%s gets the pen as the pointer", name);
|
||||||
|
}
|
||||||
|
said = client;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static int pen_buttons(int flags) {
|
||||||
|
int held = 0;
|
||||||
|
if (flags & PEN_TIP) held |= PEN_BIT(BTN_LEFT);
|
||||||
|
if (flags & PEN_RIGHT) held |= PEN_BIT(BTN_RIGHT);
|
||||||
|
if (flags & PEN_MIDDLE) held |= PEN_BIT(BTN_MIDDLE);
|
||||||
|
return held;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void pen_release(int buttons) {
|
||||||
|
for (uint32_t button = BTN_LEFT; button <= BTN_MIDDLE; button++)
|
||||||
|
if (buttons & PEN_BIT(button)) pointer_button(button, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void deliver_pen(const struct input_msg *m) {
|
||||||
|
if (!(m->p1 & PEN_IN)) {
|
||||||
|
pen_release(g_pen.buttons);
|
||||||
|
if (g_pen.in) g_raw_valid = 0;
|
||||||
|
memset(&g_pen, 0, sizeof(g_pen));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
int held = pen_buttons(m->p1);
|
||||||
|
if (!g_pen.in) g_raw_valid = 0;
|
||||||
|
g_pen.in = 1;
|
||||||
|
double x, y;
|
||||||
|
input_output_to_scene(m->p2 / 256.0, m->p3 / 256.0, &x, &y);
|
||||||
|
if (g_pen.buttons) g_grab = g_pen.grab;
|
||||||
|
if (!pointer_locked_for_cursor()) pointer_event(x, y, 0, 0);
|
||||||
|
for (uint32_t button = BTN_LEFT; button <= BTN_MIDDLE; button++)
|
||||||
|
if (held & ~g_pen.buttons & PEN_BIT(button)) pointer_button(button, 1);
|
||||||
|
g_pen.grab = g_grab;
|
||||||
|
pen_release(g_pen.buttons & ~held);
|
||||||
|
if (held) g_grab = g_pen.grab;
|
||||||
|
g_pen.buttons = held;
|
||||||
|
pen_log_target();
|
||||||
|
}
|
||||||
|
|
||||||
static void key_event(uint32_t evdev, int pressed);
|
static void key_event(uint32_t evdev, int pressed);
|
||||||
struct wl_resource *droiddeck_ime_target(void);
|
struct wl_resource *droiddeck_ime_target(void);
|
||||||
static void deliver_key(const struct input_msg *m) {
|
static void deliver_key(const struct input_msg *m) {
|
||||||
@@ -3630,6 +3689,7 @@ static int on_input_readable(int fd, uint32_t mask, void *data) {
|
|||||||
case 10: break;
|
case 10: break;
|
||||||
case 11: axis_event(m.p1, m.p2, 0); break;
|
case 11: axis_event(m.p1, m.p2, 0); break;
|
||||||
case 12: axis_event(m.p1, m.p2, 1); break;
|
case 12: axis_event(m.p1, m.p2, 1); break;
|
||||||
|
case 13: deliver_pen(&m); break;
|
||||||
case 20: stream_take(); break;
|
case 20: stream_take(); break;
|
||||||
case 21: if (!m.p1) stream_forget_all(); schedule_render(); break;
|
case 21: if (!m.p1) stream_forget_all(); schedule_render(); break;
|
||||||
case 22: schedule_render(); break;
|
case 22: schedule_render(); break;
|
||||||
@@ -3669,6 +3729,13 @@ void droiddeck_wayland_send_touch(int action, int pointer_id, int x, int y) {
|
|||||||
(void)n;
|
(void)n;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void droiddeck_wayland_send_pen(int flags, int x, int y) {
|
||||||
|
if (g_input_pipe[1] < 0) return;
|
||||||
|
struct input_msg m = { 13, flags, x, y, 0 };
|
||||||
|
ssize_t n = write(g_input_pipe[1], &m, sizeof(m));
|
||||||
|
(void)n;
|
||||||
|
}
|
||||||
|
|
||||||
void droiddeck_wayland_send_key(int evdev, int state) {
|
void droiddeck_wayland_send_key(int evdev, int state) {
|
||||||
if (g_input_pipe[1] < 0) return;
|
if (g_input_pipe[1] < 0) return;
|
||||||
struct input_msg m = { 1, evdev, state, 0, 0 };
|
struct input_msg m = { 1, evdev, state, 0, 0 };
|
||||||
|
|||||||
@@ -33,7 +33,9 @@ static PFN_vkGetInstanceProcAddr g_gipa;
|
|||||||
static VkPhysicalDevice g_pd;
|
static VkPhysicalDevice g_pd;
|
||||||
static VkQueue g_queue;
|
static VkQueue g_queue;
|
||||||
static uint32_t g_qfam;
|
static uint32_t g_qfam;
|
||||||
static int g_dev_ready, g_dev_lost, g_features_enabled;
|
static _Atomic int g_dev_ready, g_dev_lost;
|
||||||
|
static int g_features_enabled;
|
||||||
|
static _Atomic int g_caps_lsfg_ok, g_caps_ddfg_ok;
|
||||||
static VkPhysicalDeviceMemoryProperties g_memprops;
|
static VkPhysicalDeviceMemoryProperties g_memprops;
|
||||||
static struct {
|
static struct {
|
||||||
PFN_vkCreateImage CreateImage;
|
PFN_vkCreateImage CreateImage;
|
||||||
@@ -141,9 +143,12 @@ static void mark_failed(int kind) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
int vkp_framegen_problem(void) {
|
int vkp_framegen_problem(void) {
|
||||||
if (!g_dev_ready) return -1;
|
if (!atomic_load(&g_dev_ready)) return -1;
|
||||||
int kind = atomic_load(&g_kind);
|
int kind = atomic_load(&g_kind);
|
||||||
if (!fge_caps_ok(kind)) return 1;
|
int caps_ok = kind == VKP_FG_ENGINE_DDFG
|
||||||
|
? atomic_load(&g_caps_ddfg_ok)
|
||||||
|
: atomic_load(&g_caps_lsfg_ok);
|
||||||
|
if (!caps_ok) return 1;
|
||||||
if (start_failed_for(kind)) return 2;
|
if (start_failed_for(kind)) return 2;
|
||||||
if (g_engine_ok && g_engine_kind == kind && fge_unavailable()) return 2;
|
if (g_engine_ok && g_engine_kind == kind && fge_unavailable()) return 2;
|
||||||
return 0;
|
return 0;
|
||||||
@@ -179,13 +184,17 @@ void vkp_framegen_device_ready(VkDevice dev, VkQueue queue, uint32_t qfam, int f
|
|||||||
#undef R
|
#undef R
|
||||||
g_vk.GetPhysicalDeviceMemoryProperties(g_pd, &g_memprops);
|
g_vk.GetPhysicalDeviceMemoryProperties(g_pd, &g_memprops);
|
||||||
fge_device_ready(g_gipa, g_inst, g_pd, dev, queue, qfam, features_enabled);
|
fge_device_ready(g_gipa, g_inst, g_pd, dev, queue, qfam, features_enabled);
|
||||||
g_dev_ready = vk.CreateImage && vk.CreateImageView && vk.CmdPipelineBarrier;
|
atomic_store(&g_caps_lsfg_ok, fge_caps_ok(VKP_FG_ENGINE_LSFG));
|
||||||
|
atomic_store(&g_caps_ddfg_ok, fge_caps_ok(VKP_FG_ENGINE_DDFG));
|
||||||
|
atomic_store(&g_dev_lost, 0);
|
||||||
|
atomic_store(&g_dev_ready,
|
||||||
|
vk.CreateImage && vk.CreateImageView && vk.CmdPipelineBarrier);
|
||||||
FGLOG("engines ready on the compositor's device: LSFG Native %s (%s), DD-FG Native %s",
|
FGLOG("engines ready on the compositor's device: LSFG Native %s (%s), DD-FG Native %s",
|
||||||
fge_caps_ok(VKP_FG_ENGINE_LSFG) ? "available" : "unavailable", fge_caps_reason(),
|
fge_caps_ok(VKP_FG_ENGINE_LSFG) ? "available" : "unavailable", fge_caps_reason(),
|
||||||
fge_caps_ok(VKP_FG_ENGINE_DDFG) ? "available" : "unavailable");
|
fge_caps_ok(VKP_FG_ENGINE_DDFG) ? "available" : "unavailable");
|
||||||
}
|
}
|
||||||
|
|
||||||
void vkp_framegen_device_lost(void) { g_dev_lost = 1; }
|
void vkp_framegen_device_lost(void) { atomic_store(&g_dev_lost, 1); }
|
||||||
|
|
||||||
|
|
||||||
static void destroy_ring(void) {
|
static void destroy_ring(void) {
|
||||||
@@ -244,7 +253,12 @@ static int ensure_ring(uint32_t w, uint32_t h, VkFormat fmt, uint32_t n) {
|
|||||||
|
|
||||||
static int engine_usable(void) {
|
static int engine_usable(void) {
|
||||||
int kind = atomic_load(&g_kind);
|
int kind = atomic_load(&g_kind);
|
||||||
return g_dev_ready && !g_dev_lost && fge_caps_ok(kind) && !start_failed_for(kind);
|
int ready = atomic_load(&g_dev_ready);
|
||||||
|
int lost = atomic_load(&g_dev_lost);
|
||||||
|
int caps_ok = kind == VKP_FG_ENGINE_DDFG
|
||||||
|
? atomic_load(&g_caps_ddfg_ok)
|
||||||
|
: atomic_load(&g_caps_lsfg_ok);
|
||||||
|
return ready && !lost && caps_ok && !start_failed_for(kind);
|
||||||
}
|
}
|
||||||
|
|
||||||
int vkp_framegen_format_ok(VkFormat fmt) {
|
int vkp_framegen_format_ok(VkFormat fmt) {
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
|
|
||||||
#include <android/log.h>
|
#include <android/log.h>
|
||||||
|
|
||||||
#include "VulkanRendererContext.h"
|
#include "VkDispatchTable.h"
|
||||||
#include "lsfg/lsfg_engine.h"
|
#include "lsfg/lsfg_engine.h"
|
||||||
#include "lsfg/lsfg_probe.h"
|
#include "lsfg/lsfg_probe.h"
|
||||||
#include "lsfg/lsfg_vkd.h"
|
#include "lsfg/lsfg_vkd.h"
|
||||||
|
|||||||
@@ -50,6 +50,12 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeFrameGenCapsReason(J
|
|||||||
return (*env)->NewStringUTF(env, r ? r : "");
|
return (*env)->NewStringUTF(env, r ? r : "");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
JNIEXPORT jboolean JNICALL
|
||||||
|
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeFrameGenActive(JNIEnv *env, jclass clazz) {
|
||||||
|
(void)env; (void)clazz;
|
||||||
|
return vkp_framegen_active() ? JNI_TRUE : JNI_FALSE;
|
||||||
|
}
|
||||||
|
|
||||||
JNIEXPORT jfloatArray JNICALL
|
JNIEXPORT jfloatArray JNICALL
|
||||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeFrameGenStats(JNIEnv *env, jclass clazz) {
|
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeFrameGenStats(JNIEnv *env, jclass clazz) {
|
||||||
(void)clazz;
|
(void)clazz;
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <sys/stat.h>
|
#include <sys/stat.h>
|
||||||
#include <android/log.h>
|
#include <android/log.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
#define TAG "DroidDeckWayland"
|
#define TAG "DroidDeckWayland"
|
||||||
|
|
||||||
@@ -45,6 +46,13 @@ int vk_loader_open(const char *driver_path, const char *library_name,
|
|||||||
return g_vk.CreateInstance ? 0 : -1;
|
return g_vk.CreateInstance ? 0 : -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void vk_loader_close(void) {
|
||||||
|
if (g_handle) dlclose(g_handle);
|
||||||
|
g_handle = NULL;
|
||||||
|
g_gip = NULL;
|
||||||
|
memset(&g_vk, 0, sizeof(g_vk));
|
||||||
|
}
|
||||||
|
|
||||||
PFN_vkGetInstanceProcAddr vk_loader_gipa(void) { return g_gip; }
|
PFN_vkGetInstanceProcAddr vk_loader_gipa(void) { return g_gip; }
|
||||||
|
|
||||||
void vk_loader_load_instance(VkInstance instance) {
|
void vk_loader_load_instance(VkInstance instance) {
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
#define VK_GLOBAL_FUNCS(X) X(CreateInstance) X(EnumerateInstanceExtensionProperties)
|
#define VK_GLOBAL_FUNCS(X) X(CreateInstance) X(EnumerateInstanceExtensionProperties)
|
||||||
|
|
||||||
#define VK_INSTANCE_FUNCS(X) \
|
#define VK_INSTANCE_FUNCS(X) \
|
||||||
X(EnumeratePhysicalDevices) X(GetPhysicalDeviceProperties) \
|
X(DestroyInstance) X(EnumeratePhysicalDevices) X(GetPhysicalDeviceProperties) \
|
||||||
X(GetPhysicalDeviceQueueFamilyProperties) X(GetPhysicalDeviceSurfaceSupportKHR) \
|
X(GetPhysicalDeviceQueueFamilyProperties) X(GetPhysicalDeviceSurfaceSupportKHR) \
|
||||||
X(GetPhysicalDeviceSurfaceCapabilitiesKHR) X(GetPhysicalDeviceSurfaceFormatsKHR) \
|
X(GetPhysicalDeviceSurfaceCapabilitiesKHR) X(GetPhysicalDeviceSurfaceFormatsKHR) \
|
||||||
X(CreateAndroidSurfaceKHR) X(DestroySurfaceKHR) X(CreateDevice) \
|
X(CreateAndroidSurfaceKHR) X(DestroySurfaceKHR) X(CreateDevice) \
|
||||||
@@ -43,6 +43,7 @@ extern struct vk_api g_vk;
|
|||||||
|
|
||||||
int vk_loader_open(const char *driver_path, const char *library_name,
|
int vk_loader_open(const char *driver_path, const char *library_name,
|
||||||
const char *native_lib_dir);
|
const char *native_lib_dir);
|
||||||
|
void vk_loader_close(void);
|
||||||
void vk_loader_load_instance(VkInstance instance);
|
void vk_loader_load_instance(VkInstance instance);
|
||||||
void vk_loader_load_device(VkDevice device);
|
void vk_loader_load_device(VkDevice device);
|
||||||
PFN_vkGetInstanceProcAddr vk_loader_gipa(void);
|
PFN_vkGetInstanceProcAddr vk_loader_gipa(void);
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ struct vkp_image {
|
|||||||
static ANativeWindow *g_window;
|
static ANativeWindow *g_window;
|
||||||
static int g_ahb_import;
|
static int g_ahb_import;
|
||||||
static char *g_driver_path, *g_library_name, *g_native_lib_dir;
|
static char *g_driver_path, *g_library_name, *g_native_lib_dir;
|
||||||
|
static int g_allow_driver_fallback;
|
||||||
static int g_dev_state;
|
static int g_dev_state;
|
||||||
static void device_lost(const char *where);
|
static void device_lost(const char *where);
|
||||||
static const char *vk_result_name(VkResult r);
|
static const char *vk_result_name(VkResult r);
|
||||||
@@ -250,6 +251,8 @@ void vk_present_set_driver(const char *driver_path, const char *library_name,
|
|||||||
g_native_lib_dir = native_lib_dir ? strdup(native_lib_dir) : NULL;
|
g_native_lib_dir = native_lib_dir ? strdup(native_lib_dir) : NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void vk_present_set_driver_fallback(int allow) { g_allow_driver_fallback = allow; }
|
||||||
|
|
||||||
static void reset_sync(void) {
|
static void reset_sync(void) {
|
||||||
VkSemaphoreCreateInfo semci = {.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO};
|
VkSemaphoreCreateInfo semci = {.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO};
|
||||||
for (int k = 0; k < MAX_PRESENTS; k++) {
|
for (int k = 0; k < MAX_PRESENTS; k++) {
|
||||||
@@ -426,7 +429,7 @@ static void update_map(int scene_w, int scene_h) {
|
|||||||
else if (align == VKP_ALIGN_PICTURE_RIGHT) g_map.off_x = W - scene_w * g_map.kx;
|
else if (align == VKP_ALIGN_PICTURE_RIGHT) g_map.off_x = W - scene_w * g_map.kx;
|
||||||
g_map.valid = 1;
|
g_map.valid = 1;
|
||||||
pthread_mutex_lock(&g_game_picture_lock);
|
pthread_mutex_lock(&g_game_picture_lock);
|
||||||
g_game_picture_placed = align == VKP_ALIGN_PICTURE_TOP || align == VKP_ALIGN_PICTURE_BOTTOM || align == VKP_ALIGN_PICTURE_LEFT || align == VKP_ALIGN_PICTURE_RIGHT;
|
g_game_picture_placed = mode == VKP_MODE_INTEGER || align == VKP_ALIGN_PICTURE_TOP || align == VKP_ALIGN_PICTURE_BOTTOM || align == VKP_ALIGN_PICTURE_LEFT || align == VKP_ALIGN_PICTURE_RIGHT;
|
||||||
g_game_picture_rect[0] = g_map.off_x;
|
g_game_picture_rect[0] = g_map.off_x;
|
||||||
g_game_picture_rect[1] = g_map.off_y;
|
g_game_picture_rect[1] = g_map.off_y;
|
||||||
g_game_picture_rect[2] = g_map.off_x + scene_w * g_map.kx;
|
g_game_picture_rect[2] = g_map.off_x + scene_w * g_map.kx;
|
||||||
@@ -549,6 +552,18 @@ static int dev_init(void) {
|
|||||||
uint32_t npd = 0;
|
uint32_t npd = 0;
|
||||||
g_vk.EnumeratePhysicalDevices(g_inst, &npd, NULL);
|
g_vk.EnumeratePhysicalDevices(g_inst, &npd, NULL);
|
||||||
if (!npd) {
|
if (!npd) {
|
||||||
|
if (g_allow_driver_fallback && g_driver_path && g_library_name) {
|
||||||
|
LOGE("present: display driver exposed no physical devices; retrying the system Vulkan driver");
|
||||||
|
g_vk.DestroyInstance(g_inst, NULL);
|
||||||
|
g_inst = VK_NULL_HANDLE;
|
||||||
|
vk_loader_close();
|
||||||
|
free(g_driver_path); g_driver_path = NULL;
|
||||||
|
free(g_library_name); g_library_name = NULL;
|
||||||
|
g_allow_driver_fallback = 0;
|
||||||
|
g_colorspace_ext = 0;
|
||||||
|
g_dev_state = 0;
|
||||||
|
return dev_init();
|
||||||
|
}
|
||||||
LOGE("present: no physical devices"); g_dev_state = -1;
|
LOGE("present: no physical devices"); g_dev_state = -1;
|
||||||
set_fault("the display driver exposed no GPU to the app");
|
set_fault("the display driver exposed no GPU to the app");
|
||||||
return -1;
|
return -1;
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
|
|
||||||
void vk_present_set_driver(const char *driver_path, const char *library_name,
|
void vk_present_set_driver(const char *driver_path, const char *library_name,
|
||||||
const char *native_lib_dir);
|
const char *native_lib_dir);
|
||||||
|
void vk_present_set_driver_fallback(int allow);
|
||||||
|
|
||||||
void vk_present_set_window(ANativeWindow *window);
|
void vk_present_set_window(ANativeWindow *window);
|
||||||
int vkp_apply_window_request(void);
|
int vkp_apply_window_request(void);
|
||||||
|
|||||||
@@ -18,11 +18,13 @@
|
|||||||
#include "cardboard.h"
|
#include "cardboard.h"
|
||||||
#include "droiddeck_color.h"
|
#include "droiddeck_color.h"
|
||||||
#include "gpu_clock_pin.h"
|
#include "gpu_clock_pin.h"
|
||||||
|
#include "clock_domain.h"
|
||||||
|
|
||||||
extern int droiddeck_wayland_run(void);
|
extern int droiddeck_wayland_run(void);
|
||||||
extern void droiddeck_wayland_set_scale_mode(int mode, int alignment);
|
extern void droiddeck_wayland_set_scale_mode(int mode, int alignment);
|
||||||
extern void droiddeck_wayland_send_pointer(int action, int x, int y);
|
extern void droiddeck_wayland_send_pointer(int action, int x, int y);
|
||||||
extern void droiddeck_wayland_send_touch(int action, int pointer_id, int x, int y);
|
extern void droiddeck_wayland_send_touch(int action, int pointer_id, int x, int y);
|
||||||
|
extern void droiddeck_wayland_send_pen(int flags, int x, int y);
|
||||||
extern int droiddeck_cursor_snapshot(int *out, int cap);
|
extern int droiddeck_cursor_snapshot(int *out, int cap);
|
||||||
extern int droiddeck_cursor_serial(void);
|
extern int droiddeck_cursor_serial(void);
|
||||||
extern int droiddeck_hud_frame_times(float *out, int len, int64_t *total);
|
extern int droiddeck_hud_frame_times(float *out, int len, int64_t *total);
|
||||||
@@ -252,12 +254,13 @@ static char *dup_jstr(JNIEnv *env, jstring s) {
|
|||||||
JNIEXPORT void JNICALL
|
JNIEXPORT void JNICALL
|
||||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStartWithSurface(
|
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStartWithSurface(
|
||||||
JNIEnv *env, jclass clazz, jobject surface, jstring xdgRuntimeDir,
|
JNIEnv *env, jclass clazz, jobject surface, jstring xdgRuntimeDir,
|
||||||
jstring driverPath, jstring libraryName, jstring nativeLibDir) {
|
jstring driverPath, jstring libraryName, jstring nativeLibDir, jboolean allowDriverFallback) {
|
||||||
set_runtime_dir(env, xdgRuntimeDir);
|
set_runtime_dir(env, xdgRuntimeDir);
|
||||||
char *dp = dup_jstr(env, driverPath);
|
char *dp = dup_jstr(env, driverPath);
|
||||||
char *ln = dup_jstr(env, libraryName);
|
char *ln = dup_jstr(env, libraryName);
|
||||||
char *nl = dup_jstr(env, nativeLibDir);
|
char *nl = dup_jstr(env, nativeLibDir);
|
||||||
vk_present_set_driver(dp, ln, nl);
|
vk_present_set_driver(dp, ln, nl);
|
||||||
|
vk_present_set_driver_fallback(allowDriverFallback == JNI_TRUE);
|
||||||
free(dp); free(ln); free(nl);
|
free(dp); free(ln); free(nl);
|
||||||
if (surface) {
|
if (surface) {
|
||||||
ANativeWindow *win = ANativeWindow_fromSurface(env, surface);
|
ANativeWindow *win = ANativeWindow_fromSurface(env, surface);
|
||||||
@@ -279,6 +282,12 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendTouch(
|
|||||||
droiddeck_wayland_send_touch(action, pointer_id, x, y);
|
droiddeck_wayland_send_touch(action, pointer_id, x, y);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
JNIEXPORT void JNICALL
|
||||||
|
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendPen(
|
||||||
|
JNIEnv *env, jclass clazz, jint flags, jint x, jint y) {
|
||||||
|
droiddeck_wayland_send_pen(flags, x, y);
|
||||||
|
}
|
||||||
|
|
||||||
JNIEXPORT jint JNICALL
|
JNIEXPORT jint JNICALL
|
||||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSnapshot(
|
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSnapshot(
|
||||||
JNIEnv *env, jclass clazz, jintArray out) {
|
JNIEnv *env, jclass clazz, jintArray out) {
|
||||||
@@ -354,6 +363,13 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeVsync(JNIEnv *env, j
|
|||||||
droiddeck_wayland_vsync((int64_t)frameTimeNanos);
|
droiddeck_wayland_vsync((int64_t)frameTimeNanos);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
JNIEXPORT void JNICALL
|
||||||
|
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetClockControl(JNIEnv *env, jclass clazz, jstring path) {
|
||||||
|
const char *value = path ? (*env)->GetStringUTFChars(env, path, NULL) : NULL;
|
||||||
|
droiddeck_clock_domain_set_control(value);
|
||||||
|
if (value) (*env)->ReleaseStringUTFChars(env, path, value);
|
||||||
|
}
|
||||||
|
|
||||||
JNIEXPORT void JNICALL
|
JNIEXPORT void JNICALL
|
||||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetHideShell(JNIEnv *env, jclass clazz, jboolean hide) {
|
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetHideShell(JNIEnv *env, jclass clazz, jboolean hide) {
|
||||||
g_hide_shell = hide ? 1 : 0;
|
g_hide_shell = hide ? 1 : 0;
|
||||||
@@ -440,6 +456,18 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeGamePictureRect(JNIE
|
|||||||
return JNI_TRUE;
|
return JNI_TRUE;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
JNIEXPORT jboolean JNICALL
|
||||||
|
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeOutputSize(JNIEnv *env, jclass clazz, jintArray out) {
|
||||||
|
(void)clazz;
|
||||||
|
if (!out || (*env)->GetArrayLength(env, out) < 2) return JNI_FALSE;
|
||||||
|
int width = 0, height = 0;
|
||||||
|
vkp_output_size(&width, &height);
|
||||||
|
if (width <= 0 || height <= 0) return JNI_FALSE;
|
||||||
|
jint size[2] = {(jint)width, (jint)height};
|
||||||
|
(*env)->SetIntArrayRegion(env, out, 0, 2, size);
|
||||||
|
return JNI_TRUE;
|
||||||
|
}
|
||||||
|
|
||||||
JNIEXPORT void JNICALL
|
JNIEXPORT void JNICALL
|
||||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetUpscaler(JNIEnv *env, jclass clazz, jint mode) {
|
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetUpscaler(JNIEnv *env, jclass clazz, jint mode) {
|
||||||
vkp_effects_set_scaling(mode);
|
vkp_effects_set_scaling(mode);
|
||||||
|
|||||||
@@ -43,16 +43,20 @@ class App : Application() {
|
|||||||
process == "$packageName:shortcuts_sync" || process == "$packageName:bottom_desktop") return
|
process == "$packageName:shortcuts_sync" || process == "$packageName:bottom_desktop") return
|
||||||
CrashHandler.install(this)
|
CrashHandler.install(this)
|
||||||
com.droiddeck.launcher.agent.AgentHost.refresh(this)
|
com.droiddeck.launcher.agent.AgentHost.refresh(this)
|
||||||
if (com.droiddeck.launcher.agent.AgentHost.available) com.droiddeck.launcher.lab.LabNotice.openOnInstall = "agent"
|
com.droiddeck.launcher.agent.AgentTab.load(this)
|
||||||
|
com.droiddeck.launcher.ui.NavTabs.load(this)
|
||||||
|
com.droiddeck.launcher.ui.AgentPet.install(this)
|
||||||
|
if (com.droiddeck.launcher.agent.AgentTab.visible) com.droiddeck.launcher.lab.LabNotice.openOnInstall = "agent"
|
||||||
com.droiddeck.launcher.lab.LabNotice.started(this)
|
com.droiddeck.launcher.lab.LabNotice.started(this)
|
||||||
com.droiddeck.launcher.core.SteamIntegration.syncShortcutsListing(this)
|
|
||||||
com.droiddeck.launcher.session.QuestExperimental.initialize(this)
|
com.droiddeck.launcher.session.QuestExperimental.initialize(this)
|
||||||
com.droiddeck.launcher.session.SessionPrefs.applyNtsyncDefault(this)
|
com.droiddeck.launcher.session.SessionPrefs.applyNtsyncDefault(this)
|
||||||
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
|
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
|
||||||
com.droiddeck.launcher.update.AppUpdates.init(this)
|
com.droiddeck.launcher.update.AppUpdates.init(this)
|
||||||
|
com.droiddeck.launcher.update.UpdateWatch.sync(this, com.droiddeck.launcher.update.AppUpdates.follow(this, null))
|
||||||
com.droiddeck.launcher.core.DownloadSource.init(this)
|
com.droiddeck.launcher.core.DownloadSource.init(this)
|
||||||
prefetchAddonPacks()
|
prefetchAddonPacks()
|
||||||
GpuClockPin.clearLeftover(this)
|
GpuClockPin.clearLeftover(this)
|
||||||
|
com.droiddeck.launcher.input.UsbMouse.returnLeftover(this)
|
||||||
com.droiddeck.launcher.glasses.Glasses.init(this)
|
com.droiddeck.launcher.glasses.Glasses.init(this)
|
||||||
com.droiddeck.launcher.glasses.GlassesMenuMirror.initialize(this)
|
com.droiddeck.launcher.glasses.GlassesMenuMirror.initialize(this)
|
||||||
BwrapSpawner.start(this)
|
BwrapSpawner.start(this)
|
||||||
@@ -70,6 +74,7 @@ class App : Application() {
|
|||||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.ubisoft.UbisoftBackend)
|
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.ubisoft.UbisoftBackend)
|
||||||
com.droiddeck.launcher.stores.ea.EaBackend.app = this
|
com.droiddeck.launcher.stores.ea.EaBackend.app = this
|
||||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.ea.EaBackend)
|
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.ea.EaBackend)
|
||||||
|
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.rockstar.RockstarBackend)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun prefetchAddonPacks() {
|
private fun prefetchAddonPacks() {
|
||||||
|
|||||||
@@ -0,0 +1,167 @@
|
|||||||
|
package com.droiddeck.launcher
|
||||||
|
|
||||||
|
import android.app.ActivityOptions
|
||||||
|
import android.app.PictureInPictureParams
|
||||||
|
import android.content.ClipData
|
||||||
|
import android.content.ClipboardManager
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.res.Configuration
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.util.Rational
|
||||||
|
import androidx.activity.ComponentActivity
|
||||||
|
import androidx.activity.compose.BackHandler
|
||||||
|
import androidx.activity.compose.setContent
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
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.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.widthIn
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import com.droiddeck.launcher.core.AppLanguage
|
||||||
|
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||||
|
import com.droiddeck.launcher.ui.FitText
|
||||||
|
import com.droiddeck.launcher.ui.LocalPalette
|
||||||
|
import com.droiddeck.launcher.ui.PrimaryButton
|
||||||
|
import com.droiddeck.launcher.ui.SecondaryButton
|
||||||
|
import java.lang.ref.WeakReference
|
||||||
|
|
||||||
|
/** Floats a sign-in code over the browser page that asks for it. */
|
||||||
|
class DeviceCodeActivity : ComponentActivity() {
|
||||||
|
private var code by mutableStateOf("")
|
||||||
|
private var url = ""
|
||||||
|
private var display: Int? = null
|
||||||
|
private var inPip by mutableStateOf(false)
|
||||||
|
private var openPending = false
|
||||||
|
|
||||||
|
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
current = WeakReference(this)
|
||||||
|
read(intent)
|
||||||
|
openPending = savedInstanceState == null
|
||||||
|
setContent { DroidDeckTheme { Float() } }
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onNewIntent(intent: Intent) {
|
||||||
|
super.onNewIntent(intent)
|
||||||
|
setIntent(intent)
|
||||||
|
read(intent)
|
||||||
|
openPending = true
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
if (current?.get() === this) current = null
|
||||||
|
super.onDestroy()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onResume() {
|
||||||
|
super.onResume()
|
||||||
|
if (!openPending) return
|
||||||
|
if (isInPictureInPictureMode) {
|
||||||
|
openPage()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
enterPip()
|
||||||
|
if (!inPip) {
|
||||||
|
openPage()
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) {
|
||||||
|
super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig)
|
||||||
|
inPip = isInPictureInPictureMode
|
||||||
|
if (isInPictureInPictureMode && openPending) openPage()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun read(intent: Intent) {
|
||||||
|
code = intent.getStringExtra(EXTRA_CODE).orEmpty()
|
||||||
|
url = intent.getStringExtra(EXTRA_URL).orEmpty()
|
||||||
|
display = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it > 0 }
|
||||||
|
copy()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun copy() {
|
||||||
|
runCatching { getSystemService(ClipboardManager::class.java)?.setPrimaryClip(ClipData.newPlainText("GitHub", code)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun enterPip() {
|
||||||
|
inPip = runCatching {
|
||||||
|
enterPictureInPictureMode(PictureInPictureParams.Builder().setAspectRatio(Rational(16, 9)).build())
|
||||||
|
}.getOrDefault(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun openPage() {
|
||||||
|
openPending = false
|
||||||
|
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
|
val at = display
|
||||||
|
val opened = runCatching {
|
||||||
|
if (at == null) startActivity(intent)
|
||||||
|
else startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(at).toBundle())
|
||||||
|
}.recoverCatching { startActivity(intent) }.isSuccess
|
||||||
|
com.droiddeck.launcher.agent.AgentHost.deviceCodeOpened(applicationContext, opened)
|
||||||
|
}
|
||||||
|
|
||||||
|
@androidx.compose.runtime.Composable
|
||||||
|
private fun Float() {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val accent = LocalPalette.current.signal
|
||||||
|
BackHandler(enabled = !inPip) { enterPip() }
|
||||||
|
Box(Modifier.fillMaxSize().background(colors.background), contentAlignment = Alignment.Center) {
|
||||||
|
Column(
|
||||||
|
Modifier.widthIn(max = 520.dp).fillMaxWidth().padding(if (inPip) 8.dp else 24.dp),
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
verticalArrangement = Arrangement.spacedBy(if (inPip) 2.dp else 16.dp),
|
||||||
|
) {
|
||||||
|
Text(stringResource(R.string.agent_step_github), style = MaterialTheme.typography.labelLarge, color = colors.onSurfaceVariant)
|
||||||
|
FitText(code, maxSize = if (inPip) 40.sp else 56.sp, fontWeight = FontWeight.Bold, color = accent,
|
||||||
|
modifier = Modifier.fillMaxWidth())
|
||||||
|
Text(Uri.parse(url).let { it.host + it.path }, style = MaterialTheme.typography.labelMedium, color = colors.onSurfaceVariant, maxLines = 1)
|
||||||
|
if (!inPip) Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
|
PrimaryButton(stringResource(R.string.fm_copy), onClick = ::copy)
|
||||||
|
SecondaryButton(stringResource(R.string.common_close), onClick = ::finish)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val EXTRA_CODE = "code"
|
||||||
|
private const val EXTRA_URL = "url"
|
||||||
|
private const val EXTRA_DISPLAY = "display"
|
||||||
|
private var current: WeakReference<DeviceCodeActivity>? = null
|
||||||
|
|
||||||
|
/** False when this device cannot float a window, so the caller opens the page itself. */
|
||||||
|
fun show(context: Context, code: String, url: String, display: Int): Boolean {
|
||||||
|
if (!PairingGuideActivity.canFloat(context)) return false
|
||||||
|
val intent = Intent(context, DeviceCodeActivity::class.java)
|
||||||
|
.putExtra(EXTRA_CODE, code).putExtra(EXTRA_URL, url).putExtra(EXTRA_DISPLAY, display)
|
||||||
|
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
|
return runCatching {
|
||||||
|
if (display > 0) context.startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(display).toBundle())
|
||||||
|
else context.startActivity(intent)
|
||||||
|
}.isSuccess
|
||||||
|
}
|
||||||
|
|
||||||
|
fun close() {
|
||||||
|
current?.get()?.finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -286,7 +286,13 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
// Builds before 0.5.0-nad1 turned the bridge on under Auto without recording it, and
|
// Builds before 0.5.0-nad1 turned the bridge on under Auto without recording it, and
|
||||||
// left it on for good (it wins over the pair). Under Auto that switch is taken as Auto's.
|
// left it on for good (it wins over the pair). Under Auto that switch is taken as Auto's.
|
||||||
if (!SessionPrefs.maliFallbackKnown(activity))
|
if (!SessionPrefs.maliFallbackKnown(activity))
|
||||||
SessionPrefs.setMaliFallbackByAuto(activity, if (SessionPrefs.vkBridge(activity)) "bridge" else "")
|
SessionPrefs.setMaliFallbackByAuto(
|
||||||
|
activity,
|
||||||
|
MaliAutoRoute.initialOwnership(
|
||||||
|
SessionPrefs.vkBridge(activity), bridgeExplicit(),
|
||||||
|
SessionPrefs.venus(activity), venusExplicit(),
|
||||||
|
),
|
||||||
|
)
|
||||||
// A lone imported PanVK Android driver set by hand stalls the display the same way
|
// A lone imported PanVK Android driver set by hand stalls the display the same way
|
||||||
// ("black screen with the start-up logo"), so under Auto any imported display goes.
|
// ("black screen with the start-up logo"), so under Auto any imported display goes.
|
||||||
val display = SessionPrefs.androidDriver(activity)
|
val display = SessionPrefs.androidDriver(activity)
|
||||||
@@ -356,8 +362,14 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
val pair = pairs.firstOrNull { it.key == key }
|
val pair = pairs.firstOrNull { it.key == key }
|
||||||
val row = pairRows.firstOrNull { it.key == key }
|
val row = pairRows.firstOrNull { it.key == key }
|
||||||
when {
|
when {
|
||||||
row?.active == true -> autoStatus = problem?.let { activity.getString(R.string.drivers_up_to_date_check_failed, it) }
|
row?.active == true -> {
|
||||||
?: activity.getString(R.string.upd_current_status)
|
if (MaliAutoRoute.shouldEnd(
|
||||||
|
SessionPrefs.maliFallbackByAuto(activity), gpu.family.mali,
|
||||||
|
pair?.key?.let { DriverPairs.isNonAdreno(it) } == true,
|
||||||
|
)) endMaliFallback()
|
||||||
|
autoStatus = problem?.let { activity.getString(R.string.drivers_up_to_date_check_failed, it) }
|
||||||
|
?: activity.getString(R.string.upd_current_status)
|
||||||
|
}
|
||||||
gpu.family == GpuInfo.Family.POWERVR && (pair == null || !pair.complete) -> {
|
gpu.family == GpuInfo.Family.POWERVR && (pair == null || !pair.complete) -> {
|
||||||
// RADV is not published right now: the Xclipse falls back to the system route.
|
// RADV is not published right now: the Xclipse falls back to the system route.
|
||||||
SessionPrefs.ensurePowerVrAutoDrivers(activity)
|
SessionPrefs.ensurePowerVrAutoDrivers(activity)
|
||||||
@@ -397,6 +409,12 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
}, "gpu-driver-auto").start()
|
}, "gpu-driver-auto").start()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun bridgeExplicit(): Boolean =
|
||||||
|
MaliAutoRoute.userChoice(SessionPrefs.vkBridgeExplicit(activity), SessionPrefs.maliFallbackByAuto(activity), MaliAutoRoute.BRIDGE)
|
||||||
|
|
||||||
|
private fun venusExplicit(): Boolean =
|
||||||
|
MaliAutoRoute.userChoice(SessionPrefs.venusExplicit(activity), SessionPrefs.maliFallbackByAuto(activity), MaliAutoRoute.VENUS)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A Mali with no open driver pair to install ([missing] names the unpublished pair, or null when
|
* A Mali with no open driver pair to install ([missing] names the unpublished pair, or null when
|
||||||
* no PanVK build covers this GPU) runs through the phone's own driver: Mali (Venus) where this
|
* no PanVK build covers this GPU) runs through the phone's own driver: Mali (Venus) where this
|
||||||
@@ -410,12 +428,21 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
val oldVulkan = com.droiddeck.launcher.session.VenusComponent.hostVulkanTooOld(activity)
|
val oldVulkan = com.droiddeck.launcher.session.VenusComponent.hostVulkanTooOld(activity)
|
||||||
val venus = oldVulkan == null && com.droiddeck.launcher.session.VenusComponent.available(activity)
|
val venus = oldVulkan == null && com.droiddeck.launcher.session.VenusComponent.available(activity)
|
||||||
if (oldVulkan != null) Log.i(TAG, "auto: Mali driver reports Vulkan $oldVulkan; Venus needs 1.2, the bridge stands in")
|
if (oldVulkan != null) Log.i(TAG, "auto: Mali driver reports Vulkan $oldVulkan; Venus needs 1.2, the bridge stands in")
|
||||||
|
val ownership = MaliAutoRoute.fallbackOwnership(
|
||||||
|
venus,
|
||||||
|
SessionPrefs.vkBridge(activity), bridgeExplicit(),
|
||||||
|
SessionPrefs.venus(activity), venusExplicit(),
|
||||||
|
)
|
||||||
if (venus && !SessionPrefs.venus(activity)) {
|
if (venus && !SessionPrefs.venus(activity)) {
|
||||||
SessionPrefs.setVenus(activity, true)
|
SessionPrefs.setVenus(activity, true)
|
||||||
SessionPrefs.setMaliFallbackByAuto(activity, "venus")
|
if (SessionPrefs.vkBridge(activity) && !bridgeExplicit())
|
||||||
|
SessionPrefs.setVkBridge(activity, false)
|
||||||
|
SessionPrefs.setMaliFallbackByAuto(activity, ownership)
|
||||||
} else if (!venus && !SessionPrefs.vkBridge(activity)) {
|
} else if (!venus && !SessionPrefs.vkBridge(activity)) {
|
||||||
SessionPrefs.setVkBridge(activity, true)
|
SessionPrefs.setVkBridge(activity, true)
|
||||||
SessionPrefs.setMaliFallbackByAuto(activity, "bridge")
|
SessionPrefs.setMaliFallbackByAuto(activity, ownership)
|
||||||
|
} else if (ownership != MaliAutoRoute.NONE) {
|
||||||
|
SessionPrefs.setMaliFallbackByAuto(activity, ownership)
|
||||||
}
|
}
|
||||||
val route = activity.getString(if (venus) R.string.drivers_route_venus else R.string.drivers_route_bridge)
|
val route = activity.getString(if (venus) R.string.drivers_route_venus else R.string.drivers_route_bridge)
|
||||||
Log.i(TAG, "auto: Mali stand-in route $route (missing pair: ${missing ?: "none covers ${gpu.name}"})")
|
Log.i(TAG, "auto: Mali stand-in route $route (missing pair: ${missing ?: "none covers ${gpu.name}"})")
|
||||||
@@ -503,7 +530,9 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
// A route Auto switched on in place of a missing pair goes off now that one is
|
// A route Auto switched on in place of a missing pair goes off now that one is
|
||||||
// here. A Mali bridge or Venus switch the user set stays: it wins for the session
|
// here. A Mali bridge or Venus switch the user set stays: it wins for the session
|
||||||
// (DeviceSupport.vkBridge, VenusComponent.wanted) and the pair waits.
|
// (DeviceSupport.vkBridge, VenusComponent.wanted) and the pair waits.
|
||||||
if (gpu.family.mali && DriverPairs.isNonAdreno(pair.key)) endMaliFallback()
|
if (MaliAutoRoute.shouldEnd(
|
||||||
|
SessionPrefs.maliFallbackByAuto(activity), gpu.family.mali, DriverPairs.isNonAdreno(pair.key),
|
||||||
|
)) endMaliFallback()
|
||||||
val restart = displayChanged && CompositorHost.isStarted
|
val restart = displayChanged && CompositorHost.isStarted
|
||||||
if (auto) {
|
if (auto) {
|
||||||
val trial = AutoDriverTrial.current(activity)
|
val trial = AutoDriverTrial.current(activity)
|
||||||
@@ -744,4 +773,3 @@ internal fun Context.displayNameOf(uri: Uri): String? = if (uri.scheme == "file"
|
|||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -84,7 +84,7 @@ import com.droiddeck.launcher.session.SteamLibraries
|
|||||||
import com.droiddeck.launcher.input.SecondScreenDisplay
|
import com.droiddeck.launcher.input.SecondScreenDisplay
|
||||||
import com.droiddeck.launcher.input.SecondScreenDisplays
|
import com.droiddeck.launcher.input.SecondScreenDisplays
|
||||||
|
|
||||||
class FrontEndActivity : ComponentActivity() {
|
class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPetHost {
|
||||||
override fun attachBaseContext(newBase: android.content.Context) {
|
override fun attachBaseContext(newBase: android.content.Context) {
|
||||||
super.attachBaseContext(newBase)
|
super.attachBaseContext(newBase)
|
||||||
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
|
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
|
||||||
@@ -179,8 +179,10 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
private var syncFallback by mutableStateOf(true)
|
private var syncFallback by mutableStateOf(true)
|
||||||
private var fsyncFirst by mutableStateOf(false)
|
private var fsyncFirst by mutableStateOf(false)
|
||||||
private var gamescopeRealtime by mutableStateOf(false)
|
private var gamescopeRealtime by mutableStateOf(false)
|
||||||
|
private var paceCores by mutableStateOf(true)
|
||||||
private var ramCapMb by mutableStateOf(0)
|
private var ramCapMb by mutableStateOf(0)
|
||||||
private var zramClient by mutableStateOf(true)
|
private var zramClient by mutableStateOf(true)
|
||||||
|
private var zramIdle by mutableStateOf(true)
|
||||||
private var vramCapMb by mutableStateOf(0)
|
private var vramCapMb by mutableStateOf(0)
|
||||||
private var gpuClockPin by mutableStateOf(false)
|
private var gpuClockPin by mutableStateOf(false)
|
||||||
private var prootNoSeccomp by mutableStateOf(false)
|
private var prootNoSeccomp by mutableStateOf(false)
|
||||||
@@ -196,6 +198,7 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
private var stretch16x9 by mutableStateOf(false)
|
private var stretch16x9 by mutableStateOf(false)
|
||||||
private var orientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
|
private var orientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
|
||||||
private var launcherOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
|
private var launcherOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
|
||||||
|
private var homePage by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM)
|
||||||
private var launcherFullscreen by mutableStateOf(true)
|
private var launcherFullscreen by mutableStateOf(true)
|
||||||
private var downloadSource by mutableStateOf(DownloadSource.MODE_AUTO)
|
private var downloadSource by mutableStateOf(DownloadSource.MODE_AUTO)
|
||||||
private var downloadMirror by mutableStateOf("")
|
private var downloadMirror by mutableStateOf("")
|
||||||
@@ -205,6 +208,10 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
private var lowStorageWarning by mutableStateOf(true)
|
private var lowStorageWarning by mutableStateOf(true)
|
||||||
private var launcherIcon by mutableStateOf(LauncherIcon.DARK)
|
private var launcherIcon by mutableStateOf(LauncherIcon.DARK)
|
||||||
private var gameStoresEnabled by mutableStateOf(true)
|
private var gameStoresEnabled by mutableStateOf(true)
|
||||||
|
private var soundtracksEnabled by mutableStateOf(true)
|
||||||
|
private var soundtracksIngame by mutableStateOf(false)
|
||||||
|
private var soundtracks by mutableStateOf<List<Library.SteamGame>>(emptyList())
|
||||||
|
private var soundtracksLoaded by mutableStateOf(false)
|
||||||
private var gameStoresSpeedTier by mutableStateOf("fast")
|
private var gameStoresSpeedTier by mutableStateOf("fast")
|
||||||
private var navRequest by mutableStateOf<String?>(null)
|
private var navRequest by mutableStateOf<String?>(null)
|
||||||
private val gameLaunchRequest = java.util.concurrent.atomic.AtomicLong()
|
private val gameLaunchRequest = java.util.concurrent.atomic.AtomicLong()
|
||||||
@@ -226,6 +233,11 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
refreshWifiDiscovery()
|
refreshWifiDiscovery()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
private val dateReceiver = object : android.content.BroadcastReceiver() {
|
||||||
|
override fun onReceive(context: android.content.Context?, intent: Intent?) {
|
||||||
|
refreshAndroidApps()
|
||||||
|
}
|
||||||
|
}
|
||||||
private val mediaRefresh = Runnable {
|
private val mediaRefresh = Runnable {
|
||||||
refresh()
|
refresh()
|
||||||
refreshAddedGames()
|
refreshAddedGames()
|
||||||
@@ -355,15 +367,78 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
SteamIntegration.Feature.BRIGHTNESS -> integrationSettings(SteamIntegration.brightnessSettings(this))
|
SteamIntegration.Feature.BRIGHTNESS -> integrationSettings(SteamIntegration.brightnessSettings(this))
|
||||||
SteamIntegration.Feature.HOME -> if (HomeApp.isDefault(this)) HomeApp.openSystemHomeSettings(this) else offerHomeScreen()
|
SteamIntegration.Feature.HOME -> if (HomeApp.isDefault(this)) HomeApp.openSystemHomeSettings(this) else offerHomeScreen()
|
||||||
SteamIntegration.Feature.SHORTCUTS -> {
|
SteamIntegration.Feature.SHORTCUTS -> {
|
||||||
if (!integrationState.shortcuts) shortcutsTried = true
|
if (integrationState.shortcuts) openShortcutSettings() else installShortcuts()
|
||||||
SteamIntegration.setShortcutsListed(this, true)
|
|
||||||
integrationSettings(SteamIntegration.shortcutSettings(this), android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun openAppInfo() =
|
private fun openShortcutSettings() =
|
||||||
integrationSettings(Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName")))
|
integrationSettings(SteamIntegration.shortcutSettings(this), android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS)
|
||||||
|
|
||||||
|
private fun installShortcuts() {
|
||||||
|
if (ShortcutsInstall.running) return
|
||||||
|
ShortcutsInstall.running = true
|
||||||
|
Thread({
|
||||||
|
val result = runCatching {
|
||||||
|
val apk = SteamIntegration.bundledShortcuts(this)
|
||||||
|
when {
|
||||||
|
SteamIntegration.shortcutsInstalled(this, apk) -> {
|
||||||
|
ShortcutsInstall.running = false
|
||||||
|
ui.post { shortcutsReady() }
|
||||||
|
}
|
||||||
|
!com.droiddeck.launcher.update.SelfInstaller.canInstall(this) -> {
|
||||||
|
ShortcutsInstall.running = false
|
||||||
|
ui.post { integrationSettings(com.droiddeck.launcher.update.SelfInstaller.permissionIntent(this)) }
|
||||||
|
}
|
||||||
|
else -> com.droiddeck.launcher.update.SelfInstaller.install(this, apk, com.droiddeck.shortcuts.Relay.PACKAGE,
|
||||||
|
SteamIntegration.SHORTCUTS_STATUS) { id -> ShortcutsInstall.session = id }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result.onFailure { e ->
|
||||||
|
ShortcutsInstall.running = false
|
||||||
|
ui.post { shortcutsFailed(e.message) }
|
||||||
|
}
|
||||||
|
}, "shortcuts-install").start()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun shortcutsReady() {
|
||||||
|
shortcutsTried = true
|
||||||
|
Thread({
|
||||||
|
val deadline = android.os.SystemClock.uptimeMillis() + 3000
|
||||||
|
while (!SteamIntegration.shortcutsListed(this) && android.os.SystemClock.uptimeMillis() < deadline) Thread.sleep(100)
|
||||||
|
ui.post { openShortcutSettings() }
|
||||||
|
}, "shortcuts-listed").start()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun shortcutsFailed(message: String?) {
|
||||||
|
android.widget.Toast.makeText(this, message?.let { getString(R.string.integration_shortcuts_install_failed_with, it) }
|
||||||
|
?: getString(R.string.integration_shortcuts_install_failed), android.widget.Toast.LENGTH_LONG).show()
|
||||||
|
}
|
||||||
|
|
||||||
|
private val shortcutsInstallStatus = object : android.content.BroadcastReceiver() {
|
||||||
|
override fun onReceive(context: android.content.Context, intent: Intent) {
|
||||||
|
val session = intent.getIntExtra(android.content.pm.PackageInstaller.EXTRA_SESSION_ID, -1)
|
||||||
|
if (session < 0 || session != ShortcutsInstall.session) return
|
||||||
|
val status = intent.getIntExtra(android.content.pm.PackageInstaller.EXTRA_STATUS,
|
||||||
|
android.content.pm.PackageInstaller.STATUS_FAILURE)
|
||||||
|
if (status != android.content.pm.PackageInstaller.STATUS_PENDING_USER_ACTION) {
|
||||||
|
ShortcutsInstall.session = -1
|
||||||
|
ShortcutsInstall.running = false
|
||||||
|
}
|
||||||
|
when (status) {
|
||||||
|
android.content.pm.PackageInstaller.STATUS_PENDING_USER_ACTION -> {
|
||||||
|
val confirm = if (android.os.Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)
|
||||||
|
else @Suppress("DEPRECATION") intent.getParcelableExtra(Intent.EXTRA_INTENT)
|
||||||
|
val safe = confirm?.let { com.droiddeck.launcher.update.SelfInstaller.safeConfirmIntent(this@FrontEndActivity, it) }
|
||||||
|
if (safe == null || runCatching { startActivity(safe) }.isFailure) shortcutsFailed(null)
|
||||||
|
}
|
||||||
|
android.content.pm.PackageInstaller.STATUS_SUCCESS -> shortcutsReady()
|
||||||
|
else -> shortcutsFailed(intent.getStringExtra(android.content.pm.PackageInstaller.EXTRA_STATUS_MESSAGE))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun openAppInfo() = integrationSettings(SteamIntegration.shortcutsAppInfo())
|
||||||
|
|
||||||
private fun openWifiDiscoverySettings() {
|
private fun openWifiDiscoverySettings() {
|
||||||
if (!WifiDiscovery.permissionGranted(this)) {
|
if (!WifiDiscovery.permissionGranted(this)) {
|
||||||
@@ -524,6 +599,7 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
private var upscaleSharpness by mutableStateOf(75)
|
private var upscaleSharpness by mutableStateOf(75)
|
||||||
private var hdrReason by mutableStateOf<String?>(null)
|
private var hdrReason by mutableStateOf<String?>(null)
|
||||||
private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO)
|
private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO)
|
||||||
|
private var pen by mutableStateOf<SessionPrefs.Pen?>(null)
|
||||||
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
|
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
|
||||||
private var steamDownloadsInBackground by mutableStateOf(false)
|
private var steamDownloadsInBackground by mutableStateOf(false)
|
||||||
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
|
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
|
||||||
@@ -593,6 +669,7 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
private var vacDiagnostics by mutableStateOf(false)
|
private var vacDiagnostics by mutableStateOf(false)
|
||||||
private var agentCommands by mutableStateOf(false)
|
private var agentCommands by mutableStateOf(false)
|
||||||
private var graphicsLogs by mutableStateOf(false)
|
private var graphicsLogs by mutableStateOf(false)
|
||||||
|
private var buildWatermark by mutableStateOf(true)
|
||||||
private var steamGpuDrawing by mutableStateOf(false)
|
private var steamGpuDrawing by mutableStateOf(false)
|
||||||
private var bridgeFellBack by mutableStateOf(false)
|
private var bridgeFellBack by mutableStateOf(false)
|
||||||
private var bridgeFellBackMemory by mutableStateOf(false)
|
private var bridgeFellBackMemory by mutableStateOf(false)
|
||||||
@@ -778,6 +855,11 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
private var shortcutPicker by mutableStateOf(false)
|
private var shortcutPicker by mutableStateOf(false)
|
||||||
private var shortcutLibraryScanning by mutableStateOf(false)
|
private var shortcutLibraryScanning by mutableStateOf(false)
|
||||||
@Volatile private var libraryScanGeneration = 0
|
@Volatile private var libraryScanGeneration = 0
|
||||||
|
private class SoundtrackRemoval(val op: Int, var scan: Int, var settled: Boolean)
|
||||||
|
private val soundtrackRemovals = HashMap<String, SoundtrackRemoval>()
|
||||||
|
private var soundtrackOp = 0
|
||||||
|
private var soundtrackAddScan = -1
|
||||||
|
private val soundtrackWork = java.util.concurrent.Executors.newSingleThreadExecutor { r -> Thread(r, "soundtrack-work").apply { isDaemon = true } }
|
||||||
@Volatile private var lastComponentRestore = 0L
|
@Volatile private var lastComponentRestore = 0L
|
||||||
@Volatile private var componentRestoreRetry = false
|
@Volatile private var componentRestoreRetry = false
|
||||||
private val componentRestoreLock = Any()
|
private val componentRestoreLock = Any()
|
||||||
@@ -828,6 +910,10 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
|
|
||||||
private fun readGameIntent(request: Intent) {
|
private fun readGameIntent(request: Intent) {
|
||||||
request.getStringExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV)?.let { navRequest = it; request.removeExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV) }
|
request.getStringExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV)?.let { navRequest = it; request.removeExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV) }
|
||||||
|
if (navRequest == com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_APPS) {
|
||||||
|
homeAppSelected = HomeApp.isHomeScreenEnabled(this) && HomeApp.isDefault(this)
|
||||||
|
if (!homeAppSelected) navRequest = null
|
||||||
|
}
|
||||||
shortcutPicker = request.action == Intent.ACTION_CREATE_SHORTCUT
|
shortcutPicker = request.action == Intent.ACTION_CREATE_SHORTCUT
|
||||||
if (shortcutPicker) {
|
if (shortcutPicker) {
|
||||||
steamGames = emptyList()
|
steamGames = emptyList()
|
||||||
@@ -836,6 +922,15 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
pendingGameLink = null
|
pendingGameLink = null
|
||||||
gameLinkReading = false
|
gameLinkReading = false
|
||||||
gameLinkTried = false
|
gameLinkTried = false
|
||||||
|
soundtrackLaunch = false
|
||||||
|
val soundtrackId = com.droiddeck.launcher.frontend.SoundtrackShortcuts.read(request)
|
||||||
|
if (soundtrackId != null) {
|
||||||
|
soundtrackLaunch = true
|
||||||
|
navRequest = if (SessionPrefs.soundtracksEnabled(this)) "sound:$soundtrackId" else "app:$soundtrackId"
|
||||||
|
request.data = null
|
||||||
|
request.action = Intent.ACTION_MAIN
|
||||||
|
return
|
||||||
|
}
|
||||||
if (GameLaunchIntent.accepts(request.action)) {
|
if (GameLaunchIntent.accepts(request.action)) {
|
||||||
gameLinkReading = true
|
gameLinkReading = true
|
||||||
com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
|
com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
|
||||||
@@ -859,12 +954,15 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false): Boolean {
|
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false, onHandled: () -> Unit = {}): Boolean {
|
||||||
|
if (!SessionPrefs.soundtracksIngame(this)) com.droiddeck.launcher.playback.SoundtrackController.pause(this)
|
||||||
if (pkgStage != null) {
|
if (pkgStage != null) {
|
||||||
|
onHandled()
|
||||||
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
|
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome)
|
if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome, onHandled)
|
||||||
|
onHandled()
|
||||||
if (SessionState.running) {
|
if (SessionState.running) {
|
||||||
if (SessionState.mode != SessionService.MODE_STEAM || SessionState.stopRequested) {
|
if (SessionState.mode != SessionService.MODE_STEAM || SessionState.stopRequested) {
|
||||||
android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show()
|
android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show()
|
||||||
@@ -908,12 +1006,13 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
.apply { if (returnHome) putExtra(SessionActivity.EXTRA_LINK_TASK, task) }
|
.apply { if (returnHome) putExtra(SessionActivity.EXTRA_LINK_TASK, task) }
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun launchWithoutSteam(game: Library.SteamGame, returnHome: Boolean): Boolean {
|
private fun launchWithoutSteam(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit = {}): Boolean {
|
||||||
val app = applicationContext
|
val app = applicationContext
|
||||||
Thread({
|
Thread({
|
||||||
val added = if (game.library == Library.ADDED) runCatching { com.droiddeck.launcher.session.NoSteamLaunch.addedGame(app, game) }.getOrNull() else null
|
val added = if (com.droiddeck.launcher.session.NoSteamLaunch.needsAddedGame(game)) runCatching { com.droiddeck.launcher.session.NoSteamLaunch.addedGame(app, game) }.getOrNull() else null
|
||||||
val command = com.droiddeck.launcher.session.NoSteamLaunch.command(game, added)
|
val command = com.droiddeck.launcher.session.NoSteamLaunch.command(game, added)
|
||||||
ui.post {
|
ui.post {
|
||||||
|
onHandled()
|
||||||
if (isDestroyed) return@post
|
if (isDestroyed) return@post
|
||||||
if (command == null) {
|
if (command == null) {
|
||||||
android.widget.Toast.makeText(this, R.string.game_link_failed, android.widget.Toast.LENGTH_LONG).show()
|
android.widget.Toast.makeText(this, R.string.game_link_failed, android.widget.Toast.LENGTH_LONG).show()
|
||||||
@@ -1104,9 +1203,12 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
homeChoiceOpen = savedInstanceState?.getBoolean(STATE_HOME_CHOICE_OPEN) == true
|
homeChoiceOpen = savedInstanceState?.getBoolean(STATE_HOME_CHOICE_OPEN) == true
|
||||||
gameSpaceOffered = savedInstanceState?.getBoolean(STATE_GAME_SPACE_OFFERED) == true
|
gameSpaceOffered = savedInstanceState?.getBoolean(STATE_GAME_SPACE_OFFERED) == true
|
||||||
if (savedInstanceState == null) readIntegrationIntent(intent)
|
if (savedInstanceState == null) readIntegrationIntent(intent)
|
||||||
|
val shortcutsFilter = android.content.IntentFilter(SteamIntegration.SHORTCUTS_STATUS)
|
||||||
|
if (android.os.Build.VERSION.SDK_INT >= 33) registerReceiver(shortcutsInstallStatus, shortcutsFilter, RECEIVER_NOT_EXPORTED)
|
||||||
|
else registerReceiver(shortcutsInstallStatus, shortcutsFilter)
|
||||||
readGameIntent(intent)
|
readGameIntent(intent)
|
||||||
// A Lab build is usually the agent's work, so the app comes back where the agent is.
|
// A Lab build is usually the agent's work, so the app comes back where the agent is.
|
||||||
if (savedInstanceState == null && navRequest == null && com.droiddeck.launcher.lab.LabOverlay.promoted && com.droiddeck.launcher.agent.AgentHost.available) navRequest = "agent"
|
if (savedInstanceState == null && navRequest == null && com.droiddeck.launcher.lab.LabOverlay.promoted && com.droiddeck.launcher.agent.AgentTab.visible) navRequest = "agent"
|
||||||
gameSyncFolder = GameFileSync.folder(this)
|
gameSyncFolder = GameFileSync.folder(this)
|
||||||
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
|
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
|
||||||
refreshPhantomStatus()
|
refreshPhantomStatus()
|
||||||
@@ -1121,6 +1223,7 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
orientation = SessionPrefs.orientation(this)
|
orientation = SessionPrefs.orientation(this)
|
||||||
launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
||||||
requestedOrientation = launcherOrientation
|
requestedOrientation = launcherOrientation
|
||||||
|
homePage = com.droiddeck.launcher.core.AppUiPrefs.homePage(this)
|
||||||
launcherFullscreen = SessionPrefs.launcherFullscreen(this)
|
launcherFullscreen = SessionPrefs.launcherFullscreen(this)
|
||||||
downloadSource = DownloadSource.mode(this)
|
downloadSource = DownloadSource.mode(this)
|
||||||
downloadMirror = DownloadSource.mirror(this)
|
downloadMirror = DownloadSource.mirror(this)
|
||||||
@@ -1132,6 +1235,8 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
LauncherIcon.repair(this, intent?.component)
|
LauncherIcon.repair(this, intent?.component)
|
||||||
launcherIcon = LauncherIcon.current(this)
|
launcherIcon = LauncherIcon.current(this)
|
||||||
gameStoresEnabled = SessionPrefs.gameStoresEnabled(this)
|
gameStoresEnabled = SessionPrefs.gameStoresEnabled(this)
|
||||||
|
soundtracksEnabled = SessionPrefs.soundtracksEnabled(this)
|
||||||
|
soundtracksIngame = SessionPrefs.soundtracksIngame(this)
|
||||||
gameStoresSpeedTier = SessionPrefs.gameStoresSpeedTier(this)
|
gameStoresSpeedTier = SessionPrefs.gameStoresSpeedTier(this)
|
||||||
storesShowMature = SessionPrefs.storesShowMature(this)
|
storesShowMature = SessionPrefs.storesShowMature(this)
|
||||||
storesSort = SessionPrefs.storesSort(this)
|
storesSort = SessionPrefs.storesSort(this)
|
||||||
@@ -1178,6 +1283,7 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
gameDebugLogsEnabled = gameDebugLogsEnabled, gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart,
|
gameDebugLogsEnabled = gameDebugLogsEnabled, gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart,
|
||||||
vacDiagnostics = vacDiagnostics, agentCommands = agentCommands,
|
vacDiagnostics = vacDiagnostics, agentCommands = agentCommands,
|
||||||
graphicsLogs = graphicsLogs, steamGpuDrawing = steamGpuDrawing, bridgeFellBack = bridgeFellBack, bridgeFellBackMemory = bridgeFellBackMemory,
|
graphicsLogs = graphicsLogs, steamGpuDrawing = steamGpuDrawing, bridgeFellBack = bridgeFellBack, bridgeFellBackMemory = bridgeFellBackMemory,
|
||||||
|
buildWatermark = buildWatermark,
|
||||||
clearCachedApps = clearCachedApps, adbPaired = adbPaired, memoryHud = memoryHud, backgroundAppLimit = backgroundAppLimit,
|
clearCachedApps = clearCachedApps, adbPaired = adbPaired, memoryHud = memoryHud, backgroundAppLimit = backgroundAppLimit,
|
||||||
tpUbwcMode = drivers.tpUbwcModeForDevice(), tpUbwcRestartRequired = drivers.tpUbwcRestartRequired(), canRestartApp = !runtimeChangesBlocked(),
|
tpUbwcMode = drivers.tpUbwcModeForDevice(), tpUbwcRestartRequired = drivers.tpUbwcRestartRequired(), canRestartApp = !runtimeChangesBlocked(),
|
||||||
steamGames = steamGames, steamGamesX64 = steamGamesX64, emulators = emulatorList, running = runningLabel,
|
steamGames = steamGames, steamGamesX64 = steamGamesX64, emulators = emulatorList, running = runningLabel,
|
||||||
@@ -1216,6 +1322,7 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
showPhantomGate = showPhantomGate,
|
showPhantomGate = showPhantomGate,
|
||||||
orientation = orientation,
|
orientation = orientation,
|
||||||
launcherOrientation = launcherOrientation,
|
launcherOrientation = launcherOrientation,
|
||||||
|
homePage = homePage,
|
||||||
launcherFullscreen = launcherFullscreen,
|
launcherFullscreen = launcherFullscreen,
|
||||||
downloadSource = downloadSource,
|
downloadSource = downloadSource,
|
||||||
downloadMirror = downloadMirror,
|
downloadMirror = downloadMirror,
|
||||||
@@ -1225,6 +1332,10 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
lowStorageWarning = lowStorageWarning,
|
lowStorageWarning = lowStorageWarning,
|
||||||
launcherIcon = launcherIcon,
|
launcherIcon = launcherIcon,
|
||||||
gameStoresEnabled = gameStoresEnabled,
|
gameStoresEnabled = gameStoresEnabled,
|
||||||
|
soundtracksEnabled = soundtracksEnabled,
|
||||||
|
soundtracksIngame = soundtracksIngame,
|
||||||
|
soundtracks = soundtracks,
|
||||||
|
soundtracksLoaded = soundtracksLoaded,
|
||||||
gameStoresSpeedTier = gameStoresSpeedTier,
|
gameStoresSpeedTier = gameStoresSpeedTier,
|
||||||
navigate = navRequest,
|
navigate = navRequest,
|
||||||
addedGamesArt = addedGamesArt,
|
addedGamesArt = addedGamesArt,
|
||||||
@@ -1273,7 +1384,10 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
},
|
},
|
||||||
onEpicLauncher = { openEpicLauncher() },
|
onEpicLauncher = { openEpicLauncher() },
|
||||||
onUninstallEpicLauncher = { uninstallEpicLauncher() },
|
onUninstallEpicLauncher = { uninstallEpicLauncher() },
|
||||||
onGameShortcut = { g -> com.droiddeck.launcher.frontend.GameShortcuts.pin(this, g) },
|
onGameShortcut = { g ->
|
||||||
|
if (g.soundtrack) com.droiddeck.launcher.frontend.SoundtrackShortcuts.pin(this, g)
|
||||||
|
else com.droiddeck.launcher.frontend.GameShortcuts.pin(this, g)
|
||||||
|
},
|
||||||
onExportGameFile = { g -> pickGameExport(g) },
|
onExportGameFile = { g -> pickGameExport(g) },
|
||||||
onSyncGameFiles = { pickGameExport(null) },
|
onSyncGameFiles = { pickGameExport(null) },
|
||||||
onAddGameExe = { path -> addGameExe(path) },
|
onAddGameExe = { path -> addGameExe(path) },
|
||||||
@@ -1298,8 +1412,9 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
}, "game-file-stop-sync").start()
|
}, "game-file-stop-sync").start()
|
||||||
},
|
},
|
||||||
onCopyGameLink = { g ->
|
onCopyGameLink = { g ->
|
||||||
(getSystemService(CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(
|
val link = if (g.soundtrack) com.droiddeck.launcher.frontend.SoundtrackShortcuts.uri(g.appId)
|
||||||
ClipData.newPlainText(g.name, com.droiddeck.launcher.frontend.GameLaunchLink.uri(g.gameIdString)))
|
else com.droiddeck.launcher.frontend.GameLaunchLink.uri(g.gameIdString)
|
||||||
|
(getSystemService(CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(ClipData.newPlainText(g.name, link))
|
||||||
android.widget.Toast.makeText(this, R.string.game_link_copied, android.widget.Toast.LENGTH_SHORT).show()
|
android.widget.Toast.makeText(this, R.string.game_link_copied, android.widget.Toast.LENGTH_SHORT).show()
|
||||||
},
|
},
|
||||||
onDesktop = {
|
onDesktop = {
|
||||||
@@ -1324,6 +1439,7 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
},
|
},
|
||||||
onRom = { g ->
|
onRom = { g ->
|
||||||
val e = emulatorList.first { it.id == g.emulatorId }
|
val e = emulatorList.first { it.id == g.emulatorId }
|
||||||
|
if (!SessionPrefs.soundtracksIngame(this)) com.droiddeck.launcher.playback.SoundtrackController.pause(this)
|
||||||
startActivity(Intent(this, SessionActivity::class.java)
|
startActivity(Intent(this, SessionActivity::class.java)
|
||||||
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN)
|
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN)
|
||||||
.putExtra(SessionService.EXTRA_PROGRAM, e.program)
|
.putExtra(SessionService.EXTRA_PROGRAM, e.program)
|
||||||
@@ -1416,6 +1532,11 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
SessionPrefs.setDetailedGraphicsLogs(this, !SessionPrefs.detailedGraphicsLogs(this))
|
SessionPrefs.setDetailedGraphicsLogs(this, !SessionPrefs.detailedGraphicsLogs(this))
|
||||||
graphicsLogs = SessionPrefs.detailedGraphicsLogs(this)
|
graphicsLogs = SessionPrefs.detailedGraphicsLogs(this)
|
||||||
},
|
},
|
||||||
|
onBuildWatermark = {
|
||||||
|
SessionPrefs.setBuildWatermarkEnabled(this, !SessionPrefs.buildWatermarkEnabled(this))
|
||||||
|
buildWatermark = SessionPrefs.buildWatermarkEnabled(this)
|
||||||
|
com.droiddeck.launcher.ui.BuildWatermark.refresh(this)
|
||||||
|
},
|
||||||
onVacDiagnostics = {
|
onVacDiagnostics = {
|
||||||
SessionPrefs.setVacDiagnostics(this, !SessionPrefs.vacDiagnostics(this))
|
SessionPrefs.setVacDiagnostics(this, !SessionPrefs.vacDiagnostics(this))
|
||||||
vacDiagnostics = SessionPrefs.vacDiagnostics(this)
|
vacDiagnostics = SessionPrefs.vacDiagnostics(this)
|
||||||
@@ -1487,6 +1608,15 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
},
|
},
|
||||||
onPageBack = { showPerformance = false; showComponents = false; showMapping = false },
|
onPageBack = { showPerformance = false; showComponents = false; showMapping = false },
|
||||||
onGameStoresEnabled = { on -> SessionPrefs.setGameStoresEnabled(this, on); gameStoresEnabled = on },
|
onGameStoresEnabled = { on -> SessionPrefs.setGameStoresEnabled(this, on); gameStoresEnabled = on },
|
||||||
|
onSoundtracksEnabled = { on -> SessionPrefs.setSoundtracksEnabled(this, on); soundtracksEnabled = on },
|
||||||
|
onSoundtracksIngame = { on ->
|
||||||
|
SessionPrefs.setSoundtracksIngame(this, on)
|
||||||
|
soundtracksIngame = on
|
||||||
|
com.droiddeck.launcher.playback.SoundtrackController.setIngame(this, on)
|
||||||
|
},
|
||||||
|
onSoundtrackAdded = { folder -> addSoundtrack(folder) },
|
||||||
|
onSoundtracksChanged = { refreshAddedSoundtracks() },
|
||||||
|
onSoundtrackRemoved = { g -> removeSoundtrack(g) },
|
||||||
onTheme = { id -> SessionPrefs.setTheme(this, id); theme = id },
|
onTheme = { id -> SessionPrefs.setTheme(this, id); theme = id },
|
||||||
onLauncherIcon = { style -> switchLauncherIcon(style) },
|
onLauncherIcon = { style -> switchLauncherIcon(style) },
|
||||||
onLanguage = { tag ->
|
onLanguage = { tag ->
|
||||||
@@ -1508,6 +1638,10 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
launcherOrientation = value
|
launcherOrientation = value
|
||||||
requestedOrientation = value
|
requestedOrientation = value
|
||||||
},
|
},
|
||||||
|
onHomePage = { value ->
|
||||||
|
com.droiddeck.launcher.core.AppUiPrefs.setHomePage(this, value)
|
||||||
|
homePage = value
|
||||||
|
},
|
||||||
onLauncherFullscreen = { on ->
|
onLauncherFullscreen = { on ->
|
||||||
SessionPrefs.setLauncherFullscreen(this, on)
|
SessionPrefs.setLauncherFullscreen(this, on)
|
||||||
launcherFullscreen = on
|
launcherFullscreen = on
|
||||||
@@ -1576,6 +1710,7 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
refreshHomeAppState()
|
refreshHomeAppState()
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
onAppIconsChanged = { refreshAndroidApps() },
|
||||||
onAndroidApp = { app, displayId -> launchAndroidApp(app, displayId) },
|
onAndroidApp = { app, displayId -> launchAndroidApp(app, displayId) },
|
||||||
onBackActionsInverted = { inverted ->
|
onBackActionsInverted = { inverted ->
|
||||||
SessionPrefs.setBackActionsInverted(this, inverted)
|
SessionPrefs.setBackActionsInverted(this, inverted)
|
||||||
@@ -1758,6 +1893,8 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
}, "finish-abandoned").start()
|
}, "finish-abandoned").start()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override val petBlocked: Boolean get() = false
|
||||||
|
|
||||||
override fun onNewIntent(intent: Intent) {
|
override fun onNewIntent(intent: Intent) {
|
||||||
super.onNewIntent(intent)
|
super.onNewIntent(intent)
|
||||||
setIntent(intent)
|
setIntent(intent)
|
||||||
@@ -1773,7 +1910,10 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
startSteamAtStartupIfEnabled()
|
startSteamAtStartupIfEnabled()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private var soundtrackLaunch = false
|
||||||
|
|
||||||
private fun startSteamAtStartupIfEnabled(cold: Boolean = false) {
|
private fun startSteamAtStartupIfEnabled(cold: Boolean = false) {
|
||||||
|
if (soundtrackLaunch) return
|
||||||
if (intent.action != Intent.ACTION_MAIN && !(cold && intent.action == null)) return
|
if (intent.action != Intent.ACTION_MAIN && !(cold && intent.action == null)) return
|
||||||
if (isFinishing || isDestroyed) return
|
if (isFinishing || isDestroyed) return
|
||||||
when (SessionPrefs.startupSession(this)) {
|
when (SessionPrefs.startupSession(this)) {
|
||||||
@@ -1851,6 +1991,7 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||||
|
if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true
|
||||||
if (compatLaunch != null) {
|
if (compatLaunch != null) {
|
||||||
if (event.keyCode == KeyEvent.KEYCODE_BACK || event.keyCode == KeyEvent.KEYCODE_BUTTON_B) {
|
if (event.keyCode == KeyEvent.KEYCODE_BACK || event.keyCode == KeyEvent.KEYCODE_BUTTON_B) {
|
||||||
if (event.action == KeyEvent.ACTION_UP) cancelCompatLaunch()
|
if (event.action == KeyEvent.ACTION_UP) cancelCompatLaunch()
|
||||||
@@ -1900,7 +2041,7 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
orientation = SessionPrefs.orientation(this)
|
orientation = SessionPrefs.orientation(this)
|
||||||
launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
||||||
requestedOrientation = launcherOrientation
|
requestedOrientation = launcherOrientation
|
||||||
SteamIntegration.syncShortcutsListing(this)
|
homePage = com.droiddeck.launcher.core.AppUiPrefs.homePage(this)
|
||||||
refreshWifiDiscovery()
|
refreshWifiDiscovery()
|
||||||
com.droiddeck.launcher.stores.StoresState.refresh(this)
|
com.droiddeck.launcher.stores.StoresState.refresh(this)
|
||||||
com.droiddeck.launcher.stores.StoresState.libraryListener = { refreshAddedGames(); refresh() }
|
com.droiddeck.launcher.stores.StoresState.libraryListener = { refreshAddedGames(); refresh() }
|
||||||
@@ -1953,6 +2094,7 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
override fun onStart() {
|
override fun onStart() {
|
||||||
super.onStart()
|
super.onStart()
|
||||||
registerReceiver(wifiLocationReceiver, android.content.IntentFilter(android.location.LocationManager.MODE_CHANGED_ACTION))
|
registerReceiver(wifiLocationReceiver, android.content.IntentFilter(android.location.LocationManager.MODE_CHANGED_ACTION))
|
||||||
|
registerReceiver(dateReceiver, android.content.IntentFilter(Intent.ACTION_DATE_CHANGED))
|
||||||
registerReceiver(mediaReceiver, android.content.IntentFilter().apply {
|
registerReceiver(mediaReceiver, android.content.IntentFilter().apply {
|
||||||
for (action in listOf(Intent.ACTION_MEDIA_MOUNTED, Intent.ACTION_MEDIA_UNMOUNTED, Intent.ACTION_MEDIA_REMOVED,
|
for (action in listOf(Intent.ACTION_MEDIA_MOUNTED, Intent.ACTION_MEDIA_UNMOUNTED, Intent.ACTION_MEDIA_REMOVED,
|
||||||
Intent.ACTION_MEDIA_EJECT, Intent.ACTION_MEDIA_BAD_REMOVAL)) addAction(action)
|
Intent.ACTION_MEDIA_EJECT, Intent.ACTION_MEDIA_BAD_REMOVAL)) addAction(action)
|
||||||
@@ -1998,8 +2140,8 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g, onBlocked = done) {
|
com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g, onBlocked = done) {
|
||||||
if (request != gameLaunchRequest.get() || isFinishing || isDestroyed) { done(); return@beforeLaunch }
|
if (request != gameLaunchRequest.get() || isFinishing || isDestroyed) { done(); return@beforeLaunch }
|
||||||
com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) {
|
com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) {
|
||||||
done()
|
if (request == gameLaunchRequest.get() && !isFinishing && !isDestroyed) launchGame(g, onHandled = done)
|
||||||
if (request == gameLaunchRequest.get() && !isFinishing && !isDestroyed) launchGame(g)
|
else done()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2008,6 +2150,7 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
gameLaunchRequest.incrementAndGet()
|
gameLaunchRequest.incrementAndGet()
|
||||||
cancelCompatLaunch()
|
cancelCompatLaunch()
|
||||||
updates.unregister()
|
updates.unregister()
|
||||||
|
runCatching { unregisterReceiver(shortcutsInstallStatus) }
|
||||||
super.onDestroy()
|
super.onDestroy()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2019,6 +2162,7 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
override fun onStop() {
|
override fun onStop() {
|
||||||
if (!homeChoiceOpen) HomeApp.releaseUnusedHomeEntry(this)
|
if (!homeChoiceOpen) HomeApp.releaseUnusedHomeEntry(this)
|
||||||
unregisterReceiver(wifiLocationReceiver)
|
unregisterReceiver(wifiLocationReceiver)
|
||||||
|
unregisterReceiver(dateReceiver)
|
||||||
unregisterReceiver(mediaReceiver)
|
unregisterReceiver(mediaReceiver)
|
||||||
getSystemService(android.content.pm.LauncherApps::class.java).unregisterCallback(packageCallback)
|
getSystemService(android.content.pm.LauncherApps::class.java).unregisterCallback(packageCallback)
|
||||||
HomeWidgets.stopListening(this)
|
HomeWidgets.stopListening(this)
|
||||||
@@ -2395,6 +2539,7 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
|
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
|
||||||
gpuDrivers = drivers.summary(),
|
gpuDrivers = drivers.summary(),
|
||||||
touchMode = touchMode,
|
touchMode = touchMode,
|
||||||
|
pen = pen,
|
||||||
suspendPolicy = suspendPolicy,
|
suspendPolicy = suspendPolicy,
|
||||||
steamDownloadsInBackground = steamDownloadsInBackground,
|
steamDownloadsInBackground = steamDownloadsInBackground,
|
||||||
pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this),
|
pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this),
|
||||||
@@ -2447,6 +2592,7 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
onUpscaler = { m -> SessionPrefs.setUpscaler(this, m); upscaler = m },
|
onUpscaler = { m -> SessionPrefs.setUpscaler(this, m); upscaler = m },
|
||||||
onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct },
|
onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct },
|
||||||
onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t },
|
onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t },
|
||||||
|
onPen = { key, value -> SessionPrefs.setPenSetting(this, key, value); pen = SessionPrefs.pen(this) },
|
||||||
onSuspendPolicy = { policy -> SessionPrefs.setSuspendPolicy(this, mode, policy); suspendPolicy = policy },
|
onSuspendPolicy = { policy -> SessionPrefs.setSuspendPolicy(this, mode, policy); suspendPolicy = policy },
|
||||||
onSteamDownloadsInBackground = { enabled ->
|
onSteamDownloadsInBackground = { enabled ->
|
||||||
SessionPrefs.setSteamDownloadsInBackground(this, enabled)
|
SessionPrefs.setSteamDownloadsInBackground(this, enabled)
|
||||||
@@ -2549,20 +2695,21 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
private fun PerformanceHost() {
|
private fun PerformanceHost() {
|
||||||
PerformancePage(
|
PerformancePage(
|
||||||
cores = CpuCores.all.map { c -> CoreRow(c, "cpu$c" + (CpuCores.maxGhz(c)?.let { String.format(java.util.Locale.US, " · %.1f GHz", it) } ?: "")) },
|
cores = CpuCores.all.map { c -> CoreRow(c, "cpu$c" + (CpuCores.maxGhz(c)?.let { String.format(java.util.Locale.US, " · %.1f GHz", it) } ?: "")) },
|
||||||
clientOverride = clientOverride, clientCores = clientCores, gameCores = gameCores,
|
clientOverride = clientOverride, clientCores = clientCores, gameCores = gameCores, paceCores = paceCores,
|
||||||
tuSysmem = tuSysmem, zinkLazy = zinkLazy, glThread = glThread, noGlError = noGlError, noXalia = noXalia,
|
tuSysmem = tuSysmem, zinkLazy = zinkLazy, glThread = glThread, noGlError = noGlError, noXalia = noXalia,
|
||||||
fastSync = fastSync,
|
fastSync = fastSync,
|
||||||
syncFallback = syncFallback,
|
syncFallback = syncFallback,
|
||||||
fsyncFirst = fsyncFirst,
|
fsyncFirst = fsyncFirst,
|
||||||
gamescopeRealtime = gamescopeRealtime,
|
gamescopeRealtime = gamescopeRealtime,
|
||||||
gpuClockPin = gpuClockPin,
|
gpuClockPin = gpuClockPin,
|
||||||
ramCapMb = ramCapMb, vramCapMb = vramCapMb, zramClient = zramClient,
|
ramCapMb = ramCapMb, vramCapMb = vramCapMb, zramClient = zramClient, zramIdle = zramIdle,
|
||||||
deviceRamMb = (android.app.ActivityManager.MemoryInfo()
|
deviceRamMb = (android.app.ActivityManager.MemoryInfo()
|
||||||
.also((getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)::getMemoryInfo).totalMem / (1024 * 1024)).toInt(),
|
.also((getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)::getMemoryInfo).totalMem / (1024 * 1024)).toInt(),
|
||||||
ramCapAvailable = com.droiddeck.launcher.core.ZramSupport.supported(),
|
ramCapAvailable = com.droiddeck.launcher.core.ZramSupport.supported(),
|
||||||
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, cursorComposite = cursorComposite,
|
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, cursorComposite = cursorComposite,
|
||||||
guestHostname = guestHostname, phantomWarning = phantomWarning,
|
guestHostname = guestHostname, phantomWarning = phantomWarning,
|
||||||
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
|
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
|
||||||
|
onPaceCores = { on -> SessionPrefs.setPaceCores(this, on); paceCores = on },
|
||||||
onTuSysmem = { on -> SessionPrefs.setTuSysmem(this, on); tuSysmem = on },
|
onTuSysmem = { on -> SessionPrefs.setTuSysmem(this, on); tuSysmem = on },
|
||||||
onZinkLazy = { on -> SessionPrefs.setZinkLazy(this, on); zinkLazy = on },
|
onZinkLazy = { on -> SessionPrefs.setZinkLazy(this, on); zinkLazy = on },
|
||||||
onGlThread = { on -> SessionPrefs.setGlThread(this, on); glThread = on },
|
onGlThread = { on -> SessionPrefs.setGlThread(this, on); glThread = on },
|
||||||
@@ -2575,6 +2722,7 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on },
|
onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on },
|
||||||
onRamCapMb = { mb -> SessionPrefs.setRamCapMb(this, mb); ramCapMb = mb },
|
onRamCapMb = { mb -> SessionPrefs.setRamCapMb(this, mb); ramCapMb = mb },
|
||||||
onZramClient = { on -> SessionPrefs.setZramClient(this, on); zramClient = on },
|
onZramClient = { on -> SessionPrefs.setZramClient(this, on); zramClient = on },
|
||||||
|
onZramIdle = { on -> SessionPrefs.setZramIdle(this, on); zramIdle = on },
|
||||||
onVramCapMb = { mb -> SessionPrefs.setVramCapMb(this, mb); vramCapMb = mb },
|
onVramCapMb = { mb -> SessionPrefs.setVramCapMb(this, mb); vramCapMb = mb },
|
||||||
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
|
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
|
||||||
onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
|
onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
|
||||||
@@ -2614,15 +2762,89 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
val version = (steamArtRefreshes[appId] ?: 0) + 1
|
val version = (steamArtRefreshes[appId] ?: 0) + 1
|
||||||
steamArtRefreshes[appId] = version
|
steamArtRefreshes[appId] = version
|
||||||
Thread({
|
Thread({
|
||||||
val fresh = com.droiddeck.launcher.frontend.Library.steamGames(this).firstOrNull { it.appId == appId } ?: return@Thread
|
val fresh = com.droiddeck.launcher.frontend.Library.steamGames(this, soundtracks = true).firstOrNull { it.appId == appId } ?: return@Thread
|
||||||
ui.post {
|
ui.post {
|
||||||
if (steamArtRefreshes[appId] != version) return@post
|
if (steamArtRefreshes[appId] != version) return@post
|
||||||
steamGames = steamGames.map { if (it.appId == appId && it.library != Library.ADDED) fresh else it }
|
if (fresh.soundtrack) soundtracks = soundtracks.map { if (it.appId == appId && it.library != Library.ADDED) fresh else it }
|
||||||
|
else steamGames = steamGames.map { if (it.appId == appId && it.library != Library.ADDED) fresh else it }
|
||||||
}
|
}
|
||||||
}, "steam-art-update").start()
|
}, "steam-art-update").start()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun addSoundtrack(folder: java.io.File) {
|
||||||
|
val op = ++soundtrackOp
|
||||||
|
soundtrackAddScan = libraryScanGeneration
|
||||||
|
soundtrackWork.execute {
|
||||||
|
val added = com.droiddeck.launcher.frontend.AddedSoundtracks.add(this, folder)
|
||||||
|
val list = com.droiddeck.launcher.frontend.AddedSoundtracks.games(this)
|
||||||
|
ui.post {
|
||||||
|
if (added) {
|
||||||
|
soundtrackRemovals[folder.path]?.takeIf { it.op < op }?.let {
|
||||||
|
soundtrackRemovals.remove(folder.path)
|
||||||
|
com.droiddeck.launcher.playback.SoundtrackController.allow(listOf(folder.path))
|
||||||
|
}
|
||||||
|
val visible = list.filterNot { s -> s.gameFiles?.path?.let { soundtrackRemovals[it] }?.let { it.op > op } == true }
|
||||||
|
soundtracks = soundtracks.filter { it.library != Library.ADDED } + visible
|
||||||
|
} else android.widget.Toast.makeText(this, R.string.soundtracks_add_empty, android.widget.Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun refreshAddedSoundtracks() {
|
||||||
|
val op = soundtrackOp
|
||||||
|
soundtrackWork.execute {
|
||||||
|
val list = com.droiddeck.launcher.frontend.AddedSoundtracks.games(this)
|
||||||
|
ui.post {
|
||||||
|
if (op != soundtrackOp) return@post
|
||||||
|
val visible = list.filterNot { s -> s.gameFiles?.path?.let { soundtrackRemovals[it] } != null }
|
||||||
|
soundtracks = soundtracks.filter { it.library != Library.ADDED } + visible
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun removeSoundtrack(g: Library.SteamGame) {
|
||||||
|
val path = g.gameFiles?.path
|
||||||
|
val added = g.library == Library.ADDED
|
||||||
|
val target = if (added) null else com.droiddeck.launcher.frontend.GameRemoval.steamFiles(g) ?: return
|
||||||
|
com.droiddeck.launcher.playback.SoundtrackController.stopIf(this, g.gameFiles)
|
||||||
|
val marker = SoundtrackRemoval(++soundtrackOp, libraryScanGeneration, added)
|
||||||
|
path?.let { soundtrackRemovals[it] = marker }
|
||||||
|
if (target == null) {
|
||||||
|
soundtracks = soundtracks.filterNot { it.appId == g.appId && it.library == Library.ADDED }
|
||||||
|
soundtrackWork.execute {
|
||||||
|
val removed = com.droiddeck.launcher.frontend.AddedSoundtracks.remove(this, path.orEmpty())
|
||||||
|
val list = if (removed) emptyList() else com.droiddeck.launcher.frontend.AddedSoundtracks.games(this)
|
||||||
|
if (!removed) ui.post {
|
||||||
|
if (path != null && soundtrackRemovals[path] === marker) {
|
||||||
|
soundtrackRemovals.remove(path)
|
||||||
|
com.droiddeck.launcher.playback.SoundtrackController.allow(listOf(path))
|
||||||
|
}
|
||||||
|
soundtracks = soundtracks.filter { it.library != Library.ADDED } + list.filterNot { s -> s.gameFiles?.path?.let { soundtrackRemovals[it] } != null }
|
||||||
|
android.widget.Toast.makeText(this, getString(R.string.gfiles_remove_failed, g.name), android.widget.Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
soundtrackWork.execute {
|
||||||
|
val deleted = com.droiddeck.launcher.frontend.GameRemoval.delete(target)
|
||||||
|
ui.post {
|
||||||
|
if (deleted) {
|
||||||
|
marker.scan = libraryScanGeneration
|
||||||
|
marker.settled = true
|
||||||
|
} else {
|
||||||
|
if (path != null && soundtrackRemovals[path] === marker) {
|
||||||
|
soundtrackRemovals.remove(path)
|
||||||
|
com.droiddeck.launcher.playback.SoundtrackController.allow(listOf(path))
|
||||||
|
}
|
||||||
|
android.widget.Toast.makeText(this, getString(R.string.gfiles_remove_failed, g.name), android.widget.Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun removeGame(g: Library.SteamGame) {
|
private fun removeGame(g: Library.SteamGame) {
|
||||||
|
if (g.soundtrack) { removeSoundtrack(g); return }
|
||||||
val folder = g.gameFiles ?: return
|
val folder = g.gameFiles ?: return
|
||||||
when (com.droiddeck.launcher.frontend.GameRemoval.kind(g)) {
|
when (com.droiddeck.launcher.frontend.GameRemoval.kind(g)) {
|
||||||
com.droiddeck.launcher.frontend.GameRemoval.Kind.LAUNCHER -> Unit
|
com.droiddeck.launcher.frontend.GameRemoval.Kind.LAUNCHER -> Unit
|
||||||
@@ -2718,6 +2940,8 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
upscaleSharpness = SessionPrefs.upscaleSharpness(this)
|
upscaleSharpness = SessionPrefs.upscaleSharpness(this)
|
||||||
hdrReason = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason
|
hdrReason = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason
|
||||||
touchMode = SessionPrefs.touchMode(this)
|
touchMode = SessionPrefs.touchMode(this)
|
||||||
|
if (!SessionPrefs.penSeen(this) && com.droiddeck.launcher.input.PenStream.penConnected()) SessionPrefs.setPenSeen(this)
|
||||||
|
pen = SessionPrefs.pen(this).takeIf { SessionPrefs.penSeen(this) }
|
||||||
suspendPolicy = SessionPrefs.suspendPolicy(this, mode)
|
suspendPolicy = SessionPrefs.suspendPolicy(this, mode)
|
||||||
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
|
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
|
||||||
oscMode = SessionPrefs.oscMode(this)
|
oscMode = SessionPrefs.oscMode(this)
|
||||||
@@ -2795,8 +3019,10 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
syncFallback = SessionPrefs.syncFallback(this)
|
syncFallback = SessionPrefs.syncFallback(this)
|
||||||
fsyncFirst = SessionPrefs.fsyncFirst(this)
|
fsyncFirst = SessionPrefs.fsyncFirst(this)
|
||||||
gamescopeRealtime = SessionPrefs.gamescopeRealtime(this)
|
gamescopeRealtime = SessionPrefs.gamescopeRealtime(this)
|
||||||
|
paceCores = SessionPrefs.paceCores(this)
|
||||||
ramCapMb = SessionPrefs.ramCapMb(this)
|
ramCapMb = SessionPrefs.ramCapMb(this)
|
||||||
zramClient = SessionPrefs.zramClient(this)
|
zramClient = SessionPrefs.zramClient(this)
|
||||||
|
zramIdle = SessionPrefs.zramIdle(this)
|
||||||
vramCapMb = SessionPrefs.vramCapMb(this)
|
vramCapMb = SessionPrefs.vramCapMb(this)
|
||||||
gpuClockPin = SessionPrefs.gpuClockPin(this)
|
gpuClockPin = SessionPrefs.gpuClockPin(this)
|
||||||
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
|
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
|
||||||
@@ -2867,6 +3093,7 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
vacDiagnostics = SessionPrefs.vacDiagnostics(this)
|
vacDiagnostics = SessionPrefs.vacDiagnostics(this)
|
||||||
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
|
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
|
||||||
graphicsLogs = SessionPrefs.detailedGraphicsLogs(this)
|
graphicsLogs = SessionPrefs.detailedGraphicsLogs(this)
|
||||||
|
buildWatermark = SessionPrefs.buildWatermarkEnabled(this)
|
||||||
steamGpuDrawing = SessionPrefs.steamGpuCompositing(this)
|
steamGpuDrawing = SessionPrefs.steamGpuCompositing(this)
|
||||||
bridgeFellBack = SessionPrefs.bridgeFellBack(this)
|
bridgeFellBack = SessionPrefs.bridgeFellBack(this)
|
||||||
bridgeFellBackMemory = SessionPrefs.bridgeFellBackForMemory(this)
|
bridgeFellBackMemory = SessionPrefs.bridgeFellBackForMemory(this)
|
||||||
@@ -2905,6 +3132,19 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
val scannedArch = SessionPrefs.activeSteamClientArch(this)
|
val scannedArch = SessionPrefs.activeSteamClientArch(this)
|
||||||
val scannedX64 = scannedArch == "x86_64"
|
val scannedX64 = scannedArch == "x86_64"
|
||||||
|
val scannedSoundtracks = runCatching {
|
||||||
|
(if (ready || com.droiddeck.launcher.runtime.LinuxRuntime.hasRootfs(this)) Library.soundtracks(this, scannedArch) else emptyList()) +
|
||||||
|
com.droiddeck.launcher.frontend.AddedSoundtracks.games(this)
|
||||||
|
}.getOrDefault(emptyList())
|
||||||
|
ui.post {
|
||||||
|
if (scanGeneration == libraryScanGeneration) {
|
||||||
|
val scanned = if (scanGeneration <= soundtrackAddScan) scannedSoundtracks + soundtracks.filter { cur -> cur.library == Library.ADDED && scannedSoundtracks.none { it.library == Library.ADDED && it.appId == cur.appId } } else scannedSoundtracks
|
||||||
|
val kept = scanned.filterNot { s -> s.gameFiles?.path?.let { p -> soundtrackRemovals[p]?.let { m -> !m.settled || s.library == Library.ADDED || scanGeneration <= m.scan } } == true }
|
||||||
|
com.droiddeck.launcher.playback.SoundtrackController.allow(kept.mapNotNull { it.gameFiles?.path })
|
||||||
|
soundtracks = kept
|
||||||
|
soundtracksLoaded = true
|
||||||
|
}
|
||||||
|
}
|
||||||
val games = if (ready || com.droiddeck.launcher.runtime.LinuxRuntime.hasRootfs(this)) Library.launchableGames(this, arch = scannedArch) else emptyList()
|
val games = if (ready || com.droiddeck.launcher.runtime.LinuxRuntime.hasRootfs(this)) Library.launchableGames(this, arch = scannedArch) else emptyList()
|
||||||
val all = games.distinctBy { it.gameId }
|
val all = games.distinctBy { it.gameId }
|
||||||
if (ready && scanGeneration == libraryScanGeneration) com.droiddeck.launcher.frontend.LibraryCache.save(this, all, scannedX64)
|
if (ready && scanGeneration == libraryScanGeneration) com.droiddeck.launcher.frontend.LibraryCache.save(this, all, scannedX64)
|
||||||
@@ -3046,6 +3286,8 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
com.droiddeck.launcher.core.AppLanguage.setChosen(this, com.droiddeck.launcher.core.AppLanguage.SYSTEM)
|
com.droiddeck.launcher.core.AppLanguage.setChosen(this, com.droiddeck.launcher.core.AppLanguage.SYSTEM)
|
||||||
if (!ok) android.widget.Toast.makeText(this, R.string.setup_reset_settings_partial, android.widget.Toast.LENGTH_LONG).show()
|
if (!ok) android.widget.Toast.makeText(this, R.string.setup_reset_settings_partial, android.widget.Toast.LENGTH_LONG).show()
|
||||||
com.droiddeck.launcher.ui.Motion.refresh(this)
|
com.droiddeck.launcher.ui.Motion.refresh(this)
|
||||||
|
com.droiddeck.launcher.agent.AgentTab.load(this)
|
||||||
|
com.droiddeck.launcher.ui.NavTabs.load(this)
|
||||||
if (!switchLauncherIcon(LauncherIcon.DARK)) recreate()
|
if (!switchLauncherIcon(LauncherIcon.DARK)) recreate()
|
||||||
}
|
}
|
||||||
}, "reset-settings").start()
|
}, "reset-settings").start()
|
||||||
@@ -3132,3 +3374,9 @@ class FrontEndActivity : ComponentActivity() {
|
|||||||
private val WCP_EXT = listOf("wcp")
|
private val WCP_EXT = listOf("wcp")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The install session outlives the activity when Android recreates it mid-install.
|
||||||
|
private object ShortcutsInstall {
|
||||||
|
@Volatile var session = -1
|
||||||
|
@Volatile var running = false
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import android.app.Activity
|
|||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import com.droiddeck.launcher.session.SessionService
|
import com.droiddeck.launcher.session.SessionService
|
||||||
|
import com.droiddeck.launcher.session.SessionState
|
||||||
|
|
||||||
class HomeActivity : Activity() {
|
class HomeActivity : Activity() {
|
||||||
override fun attachBaseContext(newBase: android.content.Context) {
|
override fun attachBaseContext(newBase: android.content.Context) {
|
||||||
@@ -18,15 +19,22 @@ class HomeActivity : Activity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun routeHome() {
|
private fun routeHome() {
|
||||||
val destination = if (HomeApp.isActiveSteamSession()) {
|
val destination = if (HomeApp.isActiveSteamSession() && !SessionState.pipActive) {
|
||||||
Intent(this, SessionActivity::class.java)
|
Intent(this, SessionActivity::class.java)
|
||||||
.setAction(SessionService.ACTION_HOME_GUIDE)
|
.setAction(SessionService.ACTION_HOME_GUIDE)
|
||||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||||
} else {
|
} else {
|
||||||
Intent(this, FrontEndActivity::class.java)
|
Intent(this, FrontEndActivity::class.java)
|
||||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||||
|
.apply {
|
||||||
|
val page = com.droiddeck.launcher.core.AppUiPrefs.homePage(this@HomeActivity)
|
||||||
|
if (page != com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM) {
|
||||||
|
putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, page)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
startActivity(destination)
|
if (SessionState.pipActive && destination.component?.className == FrontEndActivity::class.java.name) HomeApp.showFrontEnd(this, destination)
|
||||||
|
else startActivity(destination)
|
||||||
finish()
|
finish()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -18,6 +18,7 @@ import android.net.Uri
|
|||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.provider.Settings
|
import android.provider.Settings
|
||||||
import androidx.core.graphics.drawable.toBitmap
|
import androidx.core.graphics.drawable.toBitmap
|
||||||
|
import com.droiddeck.launcher.core.AppUiPrefs
|
||||||
import com.droiddeck.launcher.session.SessionService
|
import com.droiddeck.launcher.session.SessionService
|
||||||
import com.droiddeck.launcher.session.SessionState
|
import com.droiddeck.launcher.session.SessionState
|
||||||
import kotlin.math.roundToInt
|
import kotlin.math.roundToInt
|
||||||
@@ -41,7 +42,7 @@ object HomeApp {
|
|||||||
val userSerial: Long = 0L,
|
val userSerial: Long = 0L,
|
||||||
) {
|
) {
|
||||||
val component get() = ComponentName(packageName, className)
|
val component get() = ComponentName(packageName, className)
|
||||||
val key get() = "$packageName/$className" + if (userSerial != 0L) "#$userSerial" else ""
|
val key get() = appKey(packageName, className, userSerial)
|
||||||
val work get() = userSerial != 0L
|
val work get() = userSerial != 0L
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,6 +102,9 @@ object HomeApp {
|
|||||||
?: resolved.loadLabel(pm)?.toString()?.trim()?.takeIf { it.isNotEmpty() }
|
?: resolved.loadLabel(pm)?.toString()?.trim()?.takeIf { it.isNotEmpty() }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun appKey(packageName: String, className: String, userSerial: Long) =
|
||||||
|
"$packageName/$className" + if (userSerial != 0L) "#$userSerial" else ""
|
||||||
|
|
||||||
fun roleRequestIntent(context: Context): Intent? {
|
fun roleRequestIntent(context: Context): Intent? {
|
||||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return null
|
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return null
|
||||||
val roles = context.getSystemService(RoleManager::class.java) ?: return null
|
val roles = context.getSystemService(RoleManager::class.java) ?: return null
|
||||||
@@ -116,13 +120,25 @@ object HomeApp {
|
|||||||
val pm = context.packageManager
|
val pm = context.packageManager
|
||||||
val own = Process.myUserHandle()
|
val own = Process.myUserHandle()
|
||||||
val iconPx = (ICON_DP * context.resources.displayMetrics.density).roundToInt()
|
val iconPx = (ICON_DP * context.resources.displayMetrics.density).roundToInt()
|
||||||
|
val densityDpi = context.resources.displayMetrics.densityDpi
|
||||||
|
val pack = IconPack.active(context)
|
||||||
|
val appColors = IconPack.appColors(context)
|
||||||
|
HomeIcons.load(context)
|
||||||
|
val overrides = HomeIcons.overrides
|
||||||
val apps = users.userProfiles.flatMap { user ->
|
val apps = users.userProfiles.flatMap { user ->
|
||||||
val serial = if (user == own) 0L else users.getSerialNumberForUser(user)
|
val serial = if (user == own) 0L else users.getSerialNumberForUser(user)
|
||||||
runCatching { launcher.getActivityList(null, user) }.getOrDefault(emptyList()).mapNotNull { info ->
|
runCatching { launcher.getActivityList(null, user) }.getOrDefault(emptyList()).mapNotNull { info ->
|
||||||
val component = info.componentName
|
val component = info.componentName
|
||||||
if (component.packageName == context.packageName && user == own) return@mapNotNull null
|
if (component.packageName == context.packageName && user == own) return@mapNotNull null
|
||||||
val label = info.label?.toString()?.trim().orEmpty().ifEmpty { component.packageName }
|
val label = info.label?.toString()?.trim().orEmpty().ifEmpty { component.packageName }
|
||||||
val icon = runCatching { info.getBadgedIcon(0).toBitmap(iconPx, iconPx) }.getOrNull()
|
val icon = runCatching {
|
||||||
|
(overrides[appKey(component.packageName, component.className, serial)]
|
||||||
|
?.let { IconPack.drawable(context, it.pack, it.drawable, densityDpi) }
|
||||||
|
?: pack?.icon(component, densityDpi)
|
||||||
|
?: pack?.plated(info.getIcon(0), iconPx, densityDpi, appColors))
|
||||||
|
?.let { pm.getUserBadgedIcon(it, user) }
|
||||||
|
?.toBitmap(iconPx, iconPx)
|
||||||
|
}.getOrNull() ?: runCatching { info.getBadgedIcon(0).toBitmap(iconPx, iconPx) }.getOrNull()
|
||||||
val app = info.applicationInfo
|
val app = info.applicationInfo
|
||||||
val updated = if (user == own) runCatching { pm.getPackageInfo(component.packageName, 0).lastUpdateTime }.getOrNull() else null
|
val updated = if (user == own) runCatching { pm.getPackageInfo(component.packageName, 0).lastUpdateTime }.getOrNull() else null
|
||||||
@Suppress("DEPRECATION")
|
@Suppress("DEPRECATION")
|
||||||
@@ -181,7 +197,10 @@ object HomeApp {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun syncRecents(activity: android.app.Activity) =
|
private fun syncRecents(activity: android.app.Activity) =
|
||||||
keepOutOfRecents(activity, activity is FrontEndActivity && !SessionState.running && isDefault(activity))
|
keepOutOfRecents(
|
||||||
|
activity,
|
||||||
|
activity is FrontEndActivity && !SessionState.running && isDefault(activity) && AppUiPrefs.hideHomeFromRecents(activity),
|
||||||
|
)
|
||||||
|
|
||||||
internal enum class RecentsStep { HIDE, SHOW, FORGET, NONE }
|
internal enum class RecentsStep { HIDE, SHOW, FORGET, NONE }
|
||||||
|
|
||||||
@@ -243,6 +262,19 @@ object HomeApp {
|
|||||||
fun isActiveSteamSession(): Boolean =
|
fun isActiveSteamSession(): Boolean =
|
||||||
SessionState.running && SessionState.mode == SessionService.MODE_STEAM
|
SessionState.running && SessionState.mode == SessionService.MODE_STEAM
|
||||||
|
|
||||||
|
fun showFrontEnd(context: Context, intent: Intent = Intent(context, FrontEndActivity::class.java)) {
|
||||||
|
val frontEnd = FrontEndActivity::class.java.name
|
||||||
|
val tasks = runCatching { context.getSystemService(android.app.ActivityManager::class.java)?.appTasks }.getOrNull().orEmpty()
|
||||||
|
val own = tasks.firstOrNull { task ->
|
||||||
|
runCatching { task.taskInfo.let { it.baseIntent.component?.className == frontEnd && it.topActivity?.className == frontEnd } }
|
||||||
|
.getOrDefault(false)
|
||||||
|
}
|
||||||
|
val launch = Intent(intent).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||||
|
if (own != null && runCatching { own.startActivity(context, launch, null) }.isSuccess) return
|
||||||
|
// The session task shares the front end's affinity, so without MULTIPLE_TASK the front end lands inside the session's PiP window.
|
||||||
|
context.startActivity(launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK))
|
||||||
|
}
|
||||||
|
|
||||||
fun openSystemHomeSettings(context: Context) {
|
fun openSystemHomeSettings(context: Context) {
|
||||||
try {
|
try {
|
||||||
context.startActivity(settingsIntent())
|
context.startActivity(settingsIntent())
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package com.droiddeck.launcher
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
|
||||||
|
object HomeIcons {
|
||||||
|
private const val PREFS = "home_launcher"
|
||||||
|
private const val KEY = "icon_overrides"
|
||||||
|
private const val SEPARATOR = '\t'
|
||||||
|
|
||||||
|
data class Choice(val pack: String, val drawable: String)
|
||||||
|
|
||||||
|
var overrides by mutableStateOf<Map<String, Choice>>(emptyMap())
|
||||||
|
private set
|
||||||
|
@Volatile private var loaded = false
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun load(context: Context) {
|
||||||
|
if (loaded) return
|
||||||
|
overrides = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||||
|
.getStringSet(KEY, emptySet()).orEmpty().mapNotNull(::decode).toMap()
|
||||||
|
loaded = true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun set(context: Context, key: String, pack: String, drawable: String) = save(context, overrides + (key to Choice(pack, drawable)))
|
||||||
|
|
||||||
|
fun clear(context: Context, key: String) = save(context, overrides - key)
|
||||||
|
|
||||||
|
fun clearAll(context: Context) = save(context, emptyMap())
|
||||||
|
|
||||||
|
private fun save(context: Context, next: Map<String, Choice>) {
|
||||||
|
overrides = next
|
||||||
|
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
|
||||||
|
.putStringSet(KEY, next.map { (key, choice) -> encode(key, choice) }.toSet()).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun encode(key: String, choice: Choice) = listOf(key, choice.pack, choice.drawable).joinToString(SEPARATOR.toString())
|
||||||
|
|
||||||
|
internal fun decode(entry: String): Pair<String, Choice>? {
|
||||||
|
val parts = entry.split(SEPARATOR)
|
||||||
|
if (parts.size != 3 || parts.any { it.isEmpty() }) return null
|
||||||
|
return parts[0] to Choice(parts[1], parts[2])
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,198 @@
|
|||||||
|
package com.droiddeck.launcher
|
||||||
|
|
||||||
|
import android.content.ComponentName
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import android.content.res.Resources
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.graphics.Canvas
|
||||||
|
import android.graphics.Paint
|
||||||
|
import android.graphics.PorterDuff
|
||||||
|
import android.graphics.PorterDuffColorFilter
|
||||||
|
import android.graphics.PorterDuffXfermode
|
||||||
|
import android.graphics.Rect
|
||||||
|
import android.graphics.drawable.Drawable
|
||||||
|
import android.util.Xml
|
||||||
|
import androidx.core.content.res.ResourcesCompat
|
||||||
|
import androidx.core.graphics.createBitmap
|
||||||
|
import androidx.core.graphics.drawable.toBitmap
|
||||||
|
import androidx.core.graphics.drawable.toDrawable
|
||||||
|
import androidx.palette.graphics.Palette
|
||||||
|
import org.xmlpull.v1.XmlPullParser
|
||||||
|
import java.time.LocalDate
|
||||||
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
|
object IconPack {
|
||||||
|
const val NONE = ""
|
||||||
|
private const val PREFS = "home_launcher"
|
||||||
|
private const val KEY = "icon_pack"
|
||||||
|
private const val APP_COLORS = "icon_pack_app_colors"
|
||||||
|
private const val FILTER = "appfilter"
|
||||||
|
private const val DRAWABLES = "drawable"
|
||||||
|
|
||||||
|
private val ACTIONS = listOf("org.adw.launcher.THEMES", "com.novalauncher.THEME")
|
||||||
|
|
||||||
|
data class Pack(val packageName: String, val label: String)
|
||||||
|
|
||||||
|
internal data class Plate(val back: String?, val mask: String?, val upon: String?, val scale: Float)
|
||||||
|
|
||||||
|
internal data class Filter(val icons: Map<String, String>, val calendars: Map<String, String>, val plate: Plate?) {
|
||||||
|
fun names(component: String, day: Int) = listOfNotNull(calendars[component]?.plus(day), icons[component])
|
||||||
|
}
|
||||||
|
|
||||||
|
class Loaded internal constructor(
|
||||||
|
private val resources: Resources,
|
||||||
|
internal val pack: String,
|
||||||
|
internal val updatedAt: Long,
|
||||||
|
private val filter: Filter,
|
||||||
|
) {
|
||||||
|
fun icon(component: ComponentName, densityDpi: Int) =
|
||||||
|
filter.names(component.flattenToString(), LocalDate.now().dayOfMonth).firstNotNullOfOrNull { load(resources, pack, it, densityDpi) }
|
||||||
|
|
||||||
|
val hasBack get() = filter.plate?.back != null
|
||||||
|
|
||||||
|
fun plated(icon: Drawable, size: Int, densityDpi: Int, appColor: Boolean): Drawable? {
|
||||||
|
val plate = filter.plate ?: return null
|
||||||
|
fun image(name: String?) = name?.let { load(resources, pack, it, densityDpi) }?.toBitmap(size, size)
|
||||||
|
val base = icon.toBitmap(size, size)
|
||||||
|
val color = if (appColor) Palette.from(base).generate().getDominantColor(0).takeIf { it != 0 } else null
|
||||||
|
return compose(base, image(plate.back), image(plate.mask), image(plate.upon), plate.scale, color).toDrawable(resources)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Volatile private var cached: Loaded? = null
|
||||||
|
|
||||||
|
fun selected(context: Context): String =
|
||||||
|
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, NONE).orEmpty()
|
||||||
|
|
||||||
|
fun select(context: Context, pack: String) {
|
||||||
|
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, pack).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun appColors(context: Context): Boolean =
|
||||||
|
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(APP_COLORS, false)
|
||||||
|
|
||||||
|
fun setAppColors(context: Context, on: Boolean) {
|
||||||
|
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(APP_COLORS, on).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun installed(context: Context): List<Pack> {
|
||||||
|
val pm = context.packageManager
|
||||||
|
return ACTIONS.flatMap { pm.queryIntentActivities(Intent(it), 0) }
|
||||||
|
.map { it.activityInfo.applicationInfo }
|
||||||
|
.distinctBy { it.packageName }
|
||||||
|
.filter { app -> resources(pm, app.packageName)?.let { withXml(it, app.packageName, FILTER) { true } } == true }
|
||||||
|
.map { app -> Pack(app.packageName, app.loadLabel(pm).toString().trim().ifEmpty { app.packageName }) }
|
||||||
|
.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label })
|
||||||
|
}
|
||||||
|
|
||||||
|
fun active(context: Context): Loaded? {
|
||||||
|
val pack = selected(context)
|
||||||
|
if (pack == NONE) return null
|
||||||
|
val pm = context.packageManager
|
||||||
|
val updatedAt = runCatching { pm.getPackageInfo(pack, 0).lastUpdateTime }.getOrNull() ?: return null
|
||||||
|
cached?.takeIf { it.pack == pack && it.updatedAt == updatedAt }?.let { return it }
|
||||||
|
val resources = resources(pm, pack) ?: return null
|
||||||
|
val filter = withXml(resources, pack, FILTER) { parse(it) } ?: return null
|
||||||
|
return Loaded(resources, pack, updatedAt, filter).also { cached = it }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun drawable(context: Context, pack: String, name: String, densityDpi: Int): Drawable? {
|
||||||
|
val resources = resources(context.packageManager, pack) ?: return null
|
||||||
|
return load(resources, pack, name, densityDpi)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun names(context: Context, pack: String): List<String> {
|
||||||
|
val resources = resources(context.packageManager, pack) ?: return emptyList()
|
||||||
|
return withXml(resources, pack, DRAWABLES) { parseNames(it) }?.takeIf { it.isNotEmpty() }
|
||||||
|
?: withXml(resources, pack, FILTER) { parse(it).icons.values.distinct().sorted() }.orEmpty()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun resources(pm: PackageManager, pack: String): Resources? =
|
||||||
|
runCatching { pm.getResourcesForApplication(pack) }.getOrNull()
|
||||||
|
|
||||||
|
private fun load(resources: Resources, pack: String, name: String, densityDpi: Int): Drawable? {
|
||||||
|
val id = resources.getIdentifier(name, "drawable", pack).takeIf { it != 0 }
|
||||||
|
?: resources.getIdentifier(name, "mipmap", pack).takeIf { it != 0 }
|
||||||
|
?: return null
|
||||||
|
return runCatching { ResourcesCompat.getDrawableForDensity(resources, id, densityDpi, null) }.getOrNull()
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun parseNames(xml: XmlPullParser): List<String> {
|
||||||
|
val names = LinkedHashSet<String>()
|
||||||
|
forEachTag(xml) { if (xml.name == "item") xml.getAttributeValue(null, "drawable")?.trim()?.takeIf { it.isNotEmpty() }?.let { names.add(it) } }
|
||||||
|
return names.toList()
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun parse(xml: XmlPullParser): Filter {
|
||||||
|
val icons = HashMap<String, String>()
|
||||||
|
val calendars = HashMap<String, String>()
|
||||||
|
var back: String? = null
|
||||||
|
var mask: String? = null
|
||||||
|
var upon: String? = null
|
||||||
|
var scale = 1f
|
||||||
|
fun image() = xml.getAttributeValue(null, "img1")?.trim()?.takeIf { it.isNotEmpty() }
|
||||||
|
forEachTag(xml) {
|
||||||
|
when (xml.name) {
|
||||||
|
"item" -> {
|
||||||
|
val key = componentKey(xml.getAttributeValue(null, "component"))
|
||||||
|
val drawable = xml.getAttributeValue(null, "drawable")?.trim()
|
||||||
|
if (key != null && !drawable.isNullOrEmpty()) icons.putIfAbsent(key, drawable)
|
||||||
|
}
|
||||||
|
"calendar" -> {
|
||||||
|
val key = componentKey(xml.getAttributeValue(null, "component"))
|
||||||
|
val prefix = xml.getAttributeValue(null, "prefix")?.trim()
|
||||||
|
if (key != null && !prefix.isNullOrEmpty()) calendars.putIfAbsent(key, prefix)
|
||||||
|
}
|
||||||
|
"iconback" -> back = back ?: image()
|
||||||
|
"iconmask" -> mask = mask ?: image()
|
||||||
|
"iconupon" -> upon = upon ?: image()
|
||||||
|
"scale" -> scale = xml.getAttributeValue(null, "factor")?.toFloatOrNull() ?: scale
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Filter(icons, calendars, if (back == null && mask == null && upon == null) null else Plate(back, mask, upon, scale))
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun compose(icon: Bitmap, back: Bitmap?, mask: Bitmap?, upon: Bitmap?, scale: Float, backColor: Int? = null): Bitmap {
|
||||||
|
val size = icon.width
|
||||||
|
val inset = (size * (1 - scale) / 2).roundToInt()
|
||||||
|
val result = createBitmap(size, size)
|
||||||
|
val canvas = Canvas(result)
|
||||||
|
val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
|
||||||
|
val full = Rect(0, 0, size, size)
|
||||||
|
canvas.drawBitmap(icon, null, Rect(inset, inset, size - inset, size - inset), paint)
|
||||||
|
mask?.let {
|
||||||
|
paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OUT)
|
||||||
|
canvas.drawBitmap(it, null, full, paint)
|
||||||
|
}
|
||||||
|
back?.let {
|
||||||
|
paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OVER)
|
||||||
|
paint.colorFilter = backColor?.let { color -> PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN) }
|
||||||
|
canvas.drawBitmap(it, null, full, paint)
|
||||||
|
}
|
||||||
|
paint.xfermode = null
|
||||||
|
paint.colorFilter = null
|
||||||
|
upon?.let { canvas.drawBitmap(it, null, full, paint) }
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
private inline fun forEachTag(xml: XmlPullParser, block: () -> Unit) {
|
||||||
|
var event = xml.eventType
|
||||||
|
while (event != XmlPullParser.END_DOCUMENT) {
|
||||||
|
if (event == XmlPullParser.START_TAG) block()
|
||||||
|
event = xml.next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun componentKey(component: String?): String? =
|
||||||
|
component?.trim()?.removePrefix("ComponentInfo{")?.removeSuffix("}")?.let(ComponentName::unflattenFromString)?.flattenToString()
|
||||||
|
|
||||||
|
private fun <T> withXml(resources: Resources, pack: String, file: String, block: (XmlPullParser) -> T): T? = runCatching {
|
||||||
|
val xml = resources.getIdentifier(file, "xml", pack)
|
||||||
|
val raw = resources.getIdentifier(file, "raw", pack)
|
||||||
|
if (xml != 0) resources.getXml(xml).use(block)
|
||||||
|
else (if (raw != 0) resources.openRawResource(raw) else resources.assets.open("$file.xml"))
|
||||||
|
.use { stream -> block(Xml.newPullParser().also { it.setInput(stream, null) }) }
|
||||||
|
}.getOrNull()
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package com.droiddeck.launcher
|
||||||
|
|
||||||
|
internal object MaliAutoRoute {
|
||||||
|
const val NONE = ""
|
||||||
|
const val BRIDGE = "bridge"
|
||||||
|
const val VENUS = "venus"
|
||||||
|
|
||||||
|
fun initialOwnership(bridgeOn: Boolean, bridgeExplicit: Boolean, venusOn: Boolean, venusExplicit: Boolean): String =
|
||||||
|
when {
|
||||||
|
venusOn && !venusExplicit -> VENUS
|
||||||
|
bridgeOn && !bridgeExplicit -> BRIDGE
|
||||||
|
else -> NONE
|
||||||
|
}
|
||||||
|
|
||||||
|
fun fallbackOwnership(
|
||||||
|
venusAvailable: Boolean,
|
||||||
|
bridgeOn: Boolean,
|
||||||
|
bridgeExplicit: Boolean,
|
||||||
|
venusOn: Boolean,
|
||||||
|
venusExplicit: Boolean,
|
||||||
|
): String = if (venusAvailable) {
|
||||||
|
if (!venusOn || !venusExplicit) VENUS else NONE
|
||||||
|
} else {
|
||||||
|
if (!bridgeOn || !bridgeExplicit) BRIDGE else NONE
|
||||||
|
}
|
||||||
|
|
||||||
|
fun userChoice(keyStored: Boolean, owner: String, route: String): Boolean = keyStored && owner != route
|
||||||
|
|
||||||
|
fun shouldEnd(ownsRoute: String, mali: Boolean, installedPair: Boolean): Boolean =
|
||||||
|
mali && installedPair && ownsRoute != NONE
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -17,6 +17,7 @@ import com.droiddeck.launcher.ui.UpdatesActions
|
|||||||
import com.droiddeck.launcher.ui.UpdatesState
|
import com.droiddeck.launcher.ui.UpdatesState
|
||||||
import com.droiddeck.launcher.update.AppUpdates
|
import com.droiddeck.launcher.update.AppUpdates
|
||||||
import com.droiddeck.launcher.update.SelfInstaller
|
import com.droiddeck.launcher.update.SelfInstaller
|
||||||
|
import com.droiddeck.launcher.update.UpdateWatch
|
||||||
|
|
||||||
internal class UpdatesMenu(private val activity: Activity, private val ui: Handler) {
|
internal class UpdatesMenu(private val activity: Activity, private val ui: Handler) {
|
||||||
var catalog by mutableStateOf<AppUpdates.Catalog?>(null)
|
var catalog by mutableStateOf<AppUpdates.Catalog?>(null)
|
||||||
@@ -43,6 +44,7 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
|
|||||||
.onFailure { error = activity.getString(R.string.upd_unknown_apps_failed); pending = null }
|
.onFailure { error = activity.getString(R.string.upd_unknown_apps_failed); pending = null }
|
||||||
},
|
},
|
||||||
onDismissPermission = { askPermission = false; pending = null },
|
onDismissPermission = { askPermission = false; pending = null },
|
||||||
|
onSeen = { r -> UpdateWatch.seen(activity, r) },
|
||||||
)
|
)
|
||||||
|
|
||||||
val hasUpdate: Boolean get() = AppUpdates.hasUpdate(catalog, follow)
|
val hasUpdate: Boolean get() = AppUpdates.hasUpdate(catalog, follow)
|
||||||
@@ -77,6 +79,7 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
|
|||||||
|
|
||||||
private fun choose(f: AppUpdates.Follow) {
|
private fun choose(f: AppUpdates.Follow) {
|
||||||
AppUpdates.setFollow(activity, f)
|
AppUpdates.setFollow(activity, f)
|
||||||
|
UpdateWatch.sync(activity, f, catalog?.let { AppUpdates.release(it, f) })
|
||||||
follow = f
|
follow = f
|
||||||
error = null
|
error = null
|
||||||
}
|
}
|
||||||
@@ -93,7 +96,17 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
|
|||||||
percent = 0
|
percent = 0
|
||||||
Thread({
|
Thread({
|
||||||
val result = runCatching {
|
val result = runCatching {
|
||||||
val file = SelfInstaller.download(activity, apk) { pct -> ui.post { percent = pct } }
|
val file = try {
|
||||||
|
SelfInstaller.download(activity, apk) { pct -> ui.post { percent = pct } }
|
||||||
|
} catch (e: java.io.IOException) {
|
||||||
|
// Each push replaces a test build's APK, so a list read before the push names a file that is gone.
|
||||||
|
if (r.pr <= 0) throw e
|
||||||
|
val fresh = runCatching { AppUpdates.refresh(activity) }.getOrNull() ?: throw e
|
||||||
|
ui.post { catalog = fresh }
|
||||||
|
val newer = fresh.tests.firstOrNull { it.tag == r.tag }?.apk?.takeIf { it.url != apk.url } ?: throw e
|
||||||
|
ui.post { percent = 0 }
|
||||||
|
SelfInstaller.download(activity, newer) { pct -> ui.post { percent = pct } }
|
||||||
|
}
|
||||||
ui.post { stage = activity.getString(R.string.upd_stage_installing); percent = -1 }
|
ui.post { stage = activity.getString(R.string.upd_stage_installing); percent = -1 }
|
||||||
SelfInstaller.install(activity, file) { id -> session = id }
|
SelfInstaller.install(activity, file) { id -> session = id }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ object AgentAccess {
|
|||||||
fun requireCommands(context: Context) {
|
fun requireCommands(context: Context) {
|
||||||
if (!commandsAllowed(context)) throw AgentException(
|
if (!commandsAllowed(context)) throw AgentException(
|
||||||
"AGENT_COMMANDS_DISABLED",
|
"AGENT_COMMANDS_DISABLED",
|
||||||
"Debugging tools are off: turn on Setup > Diagnostics > Debugging tools on the device",
|
"Debugging tools are off: turn on Setup > Developer > Debugging tools on the device",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
package com.droiddeck.launcher.agent
|
package com.droiddeck.launcher.agent
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import android.graphics.Bitmap
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.provider.OpenableColumns
|
import android.provider.OpenableColumns
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateListOf
|
import androidx.compose.runtime.mutableStateListOf
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
|
||||||
@@ -50,6 +54,22 @@ object AgentAttachments {
|
|||||||
if (host(context, path).renameTo(moved)) "$GUEST_DIR/$chat/${moved.name}" else path
|
if (host(context, path).renameTo(moved)) "$GUEST_DIR/$chat/${moved.name}" else path
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Copies the running game's frame; set while a session is open. */
|
||||||
|
var gameFrame by mutableStateOf<(((Bitmap?) -> Unit) -> Unit)?>(null)
|
||||||
|
|
||||||
|
/** Saves [frame] for [chat] (or a new conversation) on the calling thread; returns its guest path. */
|
||||||
|
fun saveFrame(context: Context, chat: String?, frame: Bitmap): String? = runCatching {
|
||||||
|
val folder = chat ?: NEW
|
||||||
|
val dir = File(hostDir(context), folder).apply { mkdirs() }
|
||||||
|
val target = File(dir, "game-${System.currentTimeMillis()}.jpg")
|
||||||
|
val written = target.outputStream().use { frame.compress(Bitmap.CompressFormat.JPEG, 88, it) }
|
||||||
|
if (!written) {
|
||||||
|
target.delete()
|
||||||
|
return@runCatching null
|
||||||
|
}
|
||||||
|
"$GUEST_DIR/$folder/${target.name}"
|
||||||
|
}.getOrNull()
|
||||||
|
|
||||||
/** Deletes copies that will not be sent. */
|
/** Deletes copies that will not be sent. */
|
||||||
fun discard(context: Context, files: List<String>) = files.forEach { host(context, it).delete() }
|
fun discard(context: Context, files: List<String>) = files.forEach { host(context, it).delete() }
|
||||||
|
|
||||||
|
|||||||
@@ -37,6 +37,21 @@ object AgentChats {
|
|||||||
}
|
}
|
||||||
.sortedByDescending { it.updated }
|
.sortedByDescending { it.updated }
|
||||||
|
|
||||||
|
/** The chats among [chats] where the user or the agent wrote [query], ignoring case. */
|
||||||
|
fun search(context: Context, chats: List<Chat>, query: String): List<Chat> {
|
||||||
|
val q = query.trim()
|
||||||
|
if (q.isEmpty()) return chats
|
||||||
|
return chats.filter { chat ->
|
||||||
|
chat.title.contains(q, ignoreCase = true) || read(file(context, chat.id)).entries.any { matches(it, q) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun matches(entry: Entry, query: String) = when (entry) {
|
||||||
|
is Entry.Asked -> entry.text.contains(query, ignoreCase = true)
|
||||||
|
is Entry.Said -> entry.text.contains(query, ignoreCase = true)
|
||||||
|
else -> false
|
||||||
|
}
|
||||||
|
|
||||||
fun delete(context: Context, id: String) {
|
fun delete(context: Context, id: String) {
|
||||||
file(context, id).delete()
|
file(context, id).delete()
|
||||||
File(AgentAttachments.hostDir(context), id).deleteRecursively()
|
File(AgentAttachments.hostDir(context), id).deleteRecursively()
|
||||||
@@ -72,9 +87,14 @@ object AgentChats {
|
|||||||
is Entry.Thought -> JSONObject().put("thought", entry.text)
|
is Entry.Thought -> JSONObject().put("thought", entry.text)
|
||||||
is Entry.Result -> JSONObject().put("result", entry.id).put("output", entry.output).put("failed", entry.failed)
|
is Entry.Result -> JSONObject().put("result", entry.id).put("output", entry.output).put("failed", entry.failed)
|
||||||
is Entry.Used -> JSONObject().put("used", entry.tool).put("detail", entry.detail).put("id", entry.id).put("input", entry.input)
|
is Entry.Used -> JSONObject().put("used", entry.tool).put("detail", entry.detail).put("id", entry.id).put("input", entry.input)
|
||||||
|
.apply { if (entry.parent.isNotEmpty()) put("parent", entry.parent) }
|
||||||
.apply { entry.output?.let { put("output", it).put("failed", entry.failed) } }
|
.apply { entry.output?.let { put("output", it).put("failed", entry.failed) } }
|
||||||
is Entry.Finished -> JSONObject().put("finished", true).put("error", entry.error ?: JSONObject.NULL).put("stopped", entry.stopped).apply {
|
is Entry.Finished -> JSONObject().put("finished", true).put("error", entry.error ?: JSONObject.NULL).put("stopped", entry.stopped).apply {
|
||||||
entry.usage?.let { put("ms", it.durationMs).put("cost", it.costUsd).put("in", it.inputTokens).put("out", it.outputTokens) }
|
if (entry.planned) put("planned", true)
|
||||||
|
entry.usage?.let {
|
||||||
|
put("ms", it.durationMs).put("cost", it.costUsd).put("in", it.inputTokens).put("out", it.outputTokens)
|
||||||
|
if (it.context > 0) put("ctx", it.context).put("win", it.window)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}.toString()
|
}.toString()
|
||||||
|
|
||||||
@@ -101,11 +121,12 @@ object AgentChats {
|
|||||||
o.has("said") -> Entry.Said(o.getString("said"))
|
o.has("said") -> Entry.Said(o.getString("said"))
|
||||||
o.has("thought") -> Entry.Thought(o.getString("thought"))
|
o.has("thought") -> Entry.Thought(o.getString("thought"))
|
||||||
o.has("used") -> Entry.Used(o.optString("id"), o.getString("used"), o.optString("detail"), o.optString("input"),
|
o.has("used") -> Entry.Used(o.optString("id"), o.getString("used"), o.optString("detail"), o.optString("input"),
|
||||||
if (o.has("output")) o.optString("output") else null, o.optBoolean("failed"))
|
if (o.has("output")) o.optString("output") else null, o.optBoolean("failed"), o.optString("parent"))
|
||||||
o.has("result") -> Entry.Result(o.getString("result"), o.optString("output"), o.optBoolean("failed"))
|
o.has("result") -> Entry.Result(o.getString("result"), o.optString("output"), o.optBoolean("failed"))
|
||||||
o.has("finished") -> Entry.Finished(
|
o.has("finished") -> Entry.Finished(
|
||||||
if (o.isNull("error")) null else o.optString("error"), o.optBoolean("stopped"),
|
if (o.isNull("error")) null else o.optString("error"), o.optBoolean("stopped"),
|
||||||
if (o.has("ms")) AgentHost.Usage(o.optLong("ms"), o.optDouble("cost", 0.0), o.optLong("in"), o.optLong("out")) else null,
|
if (o.has("ms")) AgentHost.Usage(o.optLong("ms"), o.optDouble("cost", 0.0), o.optLong("in"), o.optLong("out"), o.optLong("ctx"), o.optLong("win")) else null,
|
||||||
|
o.optBoolean("planned"),
|
||||||
)
|
)
|
||||||
else -> null
|
else -> null
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,8 @@ interface AgentHarness {
|
|||||||
val signIn: List<String>
|
val signIn: List<String>
|
||||||
/** Whether [Options.plan] means anything to this CLI. */
|
/** Whether [Options.plan] means anything to this CLI. */
|
||||||
val plans: Boolean
|
val plans: Boolean
|
||||||
|
/** Reasoning effort levels the CLI accepts, lowest first; empty when it has none. */
|
||||||
|
val efforts: List<String>
|
||||||
/** Models to offer besides the CLI's default; [rootfs] is where the CLI's own files can be read. */
|
/** Models to offer besides the CLI's default; [rootfs] is where the CLI's own files can be read. */
|
||||||
fun models(rootfs: File): List<Model>
|
fun models(rootfs: File): List<Model>
|
||||||
/** The guest command for one turn; [conversation] is null for the first one. */
|
/** The guest command for one turn; [conversation] is null for the first one. */
|
||||||
@@ -29,10 +31,12 @@ interface AgentHarness {
|
|||||||
fun parse(line: String): AgentEvent?
|
fun parse(line: String): AgentEvent?
|
||||||
/** Sets the CLI's own defaults in the userland before it runs; [rootfs] is the userland's root. */
|
/** Sets the CLI's own defaults in the userland before it runs; [rootfs] is the userland's root. */
|
||||||
fun prepare(rootfs: File) {}
|
fun prepare(rootfs: File) {}
|
||||||
|
/** Context and plan limits the CLI keeps on disk rather than printing, read once a turn of [conversation] is done. */
|
||||||
|
fun usage(rootfs: File, conversation: String?): AgentEvent? = null
|
||||||
|
|
||||||
data class Model(val id: String, val label: String)
|
data class Model(val id: String, val label: String)
|
||||||
|
|
||||||
data class Options(val model: String? = null, val plan: Boolean = false, val brief: String? = null)
|
data class Options(val model: String? = null, val plan: Boolean = false, val brief: String? = null, val effort: String? = null)
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
val all: List<AgentHarness> = listOf(ClaudeCode, Codex)
|
val all: List<AgentHarness> = listOf(ClaudeCode, Codex)
|
||||||
@@ -48,6 +52,9 @@ data class AgentEvent(
|
|||||||
val thinking: String? = null,
|
val thinking: String? = null,
|
||||||
/** Tokens the conversation's context holds after this step. */
|
/** Tokens the conversation's context holds after this step. */
|
||||||
val context: Long? = null,
|
val context: Long? = null,
|
||||||
|
/** Tokens the model's context can hold. */
|
||||||
|
val window: Long? = null,
|
||||||
|
val limits: List<AgentHost.Limit>? = null,
|
||||||
val usage: AgentHost.Usage? = null,
|
val usage: AgentHost.Usage? = null,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -60,6 +67,7 @@ object ClaudeCode : AgentHarness {
|
|||||||
override val signedIn = listOf("sh", "-c", "$binary auth status | grep -q '\"loggedIn\": true'")
|
override val signedIn = listOf("sh", "-c", "$binary auth status | grep -q '\"loggedIn\": true'")
|
||||||
override val signIn = listOf(binary, "auth", "login", "--claudeai")
|
override val signIn = listOf(binary, "auth", "login", "--claudeai")
|
||||||
override val plans = true
|
override val plans = true
|
||||||
|
override val efforts = listOf("low", "medium", "high", "xhigh", "max")
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Commits and pull requests the agent makes carry no Claude Code credit or co-author line by
|
* Commits and pull requests the agent makes carry no Claude Code credit or co-author line by
|
||||||
@@ -92,6 +100,7 @@ object ClaudeCode : AgentHarness {
|
|||||||
addAll(listOf(binary, "-p", message, "--output-format", "stream-json", "--verbose", "--include-partial-messages"))
|
addAll(listOf(binary, "-p", message, "--output-format", "stream-json", "--verbose", "--include-partial-messages"))
|
||||||
addAll(listOf("--permission-mode", if (options.plan) "plan" else "bypassPermissions"))
|
addAll(listOf("--permission-mode", if (options.plan) "plan" else "bypassPermissions"))
|
||||||
options.model?.let { addAll(listOf("--model", it)) }
|
options.model?.let { addAll(listOf("--model", it)) }
|
||||||
|
options.effort?.let { addAll(listOf("--effort", it)) }
|
||||||
options.brief?.let { addAll(listOf("--append-system-prompt", it)) }
|
options.brief?.let { addAll(listOf("--append-system-prompt", it)) }
|
||||||
if (conversation != null) addAll(listOf("--resume", conversation))
|
if (conversation != null) addAll(listOf("--resume", conversation))
|
||||||
}
|
}
|
||||||
@@ -99,8 +108,11 @@ object ClaudeCode : AgentHarness {
|
|||||||
override fun parse(line: String): AgentEvent? {
|
override fun parse(line: String): AgentEvent? {
|
||||||
val o = runCatching { JSONObject(line) }.getOrNull() ?: return null
|
val o = runCatching { JSONObject(line) }.getOrNull() ?: return null
|
||||||
val conversation = o.optString("session_id").takeIf { it.isNotEmpty() }
|
val conversation = o.optString("session_id").takeIf { it.isNotEmpty() }
|
||||||
|
// A subagent's messages carry the call that started it; only its tool calls are shown, under that call.
|
||||||
|
val parent = o.optString("parent_tool_use_id").takeIf { it.isNotEmpty() && it != "null" }
|
||||||
return when (o.optString("type")) {
|
return when (o.optString("type")) {
|
||||||
"stream_event" -> {
|
"stream_event" -> {
|
||||||
|
if (parent != null) return null
|
||||||
val delta = o.optJSONObject("event")?.takeIf { it.optString("type") == "content_block_delta" }?.optJSONObject("delta") ?: return null
|
val delta = o.optJSONObject("event")?.takeIf { it.optString("type") == "content_block_delta" }?.optJSONObject("delta") ?: return null
|
||||||
when (delta.optString("type")) {
|
when (delta.optString("type")) {
|
||||||
"text_delta" -> AgentEvent(conversation, text = delta.optString("text"))
|
"text_delta" -> AgentEvent(conversation, text = delta.optString("text"))
|
||||||
@@ -114,18 +126,18 @@ object ClaudeCode : AgentHarness {
|
|||||||
val entries = (0 until content.length()).mapNotNull { i ->
|
val entries = (0 until content.length()).mapNotNull { i ->
|
||||||
val block = content.optJSONObject(i) ?: return@mapNotNull null
|
val block = content.optJSONObject(i) ?: return@mapNotNull null
|
||||||
when (block.optString("type")) {
|
when (block.optString("type")) {
|
||||||
"text" -> block.optString("text").trim().takeIf { it.isNotEmpty() }?.let { AgentHost.Entry.Said(it) }
|
"text" -> if (parent != null) null else block.optString("text").trim().takeIf { it.isNotEmpty() }?.let { AgentHost.Entry.Said(it) }
|
||||||
"thinking" -> block.optString("thinking").trim().takeIf { it.isNotEmpty() }?.let { AgentHost.Entry.Thought(it) }
|
"thinking" -> if (parent != null) null else block.optString("thinking").trim().takeIf { it.isNotEmpty() }?.let { AgentHost.Entry.Thought(it) }
|
||||||
"tool_use" -> {
|
"tool_use" -> {
|
||||||
val input = block.optJSONObject("input")
|
val input = block.optJSONObject("input")
|
||||||
AgentHost.Entry.Used(block.optString("id"), block.optString("name"), detail(input), fullInput(block.optString("name"), input))
|
AgentHost.Entry.Used(block.optString("id"), block.optString("name"), detail(input), fullInput(block.optString("name"), input), parent = parent.orEmpty())
|
||||||
}
|
}
|
||||||
else -> null
|
else -> null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
val usage = message?.optJSONObject("usage")
|
val usage = message?.optJSONObject("usage")
|
||||||
val context = usage?.let { it.optLong("input_tokens") + it.optLong("cache_read_input_tokens") + it.optLong("cache_creation_input_tokens") + it.optLong("output_tokens") }
|
val context = usage?.let { it.optLong("input_tokens") + it.optLong("cache_read_input_tokens") + it.optLong("cache_creation_input_tokens") + it.optLong("output_tokens") }
|
||||||
AgentEvent(conversation, entries, context = context?.takeIf { it > 0 })
|
AgentEvent(conversation, entries, context = context?.takeIf { it > 0 && parent == null })
|
||||||
}
|
}
|
||||||
"user" -> {
|
"user" -> {
|
||||||
val content = o.optJSONObject("message")?.optJSONArray("content") ?: return conversation?.let { AgentEvent(it) }
|
val content = o.optJSONObject("message")?.optJSONArray("content") ?: return conversation?.let { AgentEvent(it) }
|
||||||
@@ -135,10 +147,12 @@ object ClaudeCode : AgentHarness {
|
|||||||
}
|
}
|
||||||
AgentEvent(conversation, results)
|
AgentEvent(conversation, results)
|
||||||
}
|
}
|
||||||
|
"rate_limit_event" -> AgentEvent(conversation, limits = limits(o.optJSONObject("rate_limit_info")))
|
||||||
// A resumed session first answers background tasks the last run left behind; that result is not the turn's.
|
// A resumed session first answers background tasks the last run left behind; that result is not the turn's.
|
||||||
"result" -> if (o.optJSONObject("origin")?.optString("kind") == "task-notification") conversation?.let { AgentEvent(it) } else AgentEvent(
|
"result" -> if (o.optJSONObject("origin")?.optString("kind") == "task-notification") conversation?.let { AgentEvent(it) } else AgentEvent(
|
||||||
conversation,
|
conversation,
|
||||||
listOf(AgentHost.Entry.Finished(if (o.optBoolean("is_error")) o.optString("result").ifEmpty { o.optString("subtype") } else null)),
|
listOf(AgentHost.Entry.Finished(if (o.optBoolean("is_error")) o.optString("result").ifEmpty { o.optString("subtype") } else null)),
|
||||||
|
window = window(o.optJSONObject("modelUsage")),
|
||||||
usage = AgentHost.Usage(
|
usage = AgentHost.Usage(
|
||||||
o.optLong("duration_ms"), o.optDouble("total_cost_usd", 0.0),
|
o.optLong("duration_ms"), o.optDouble("total_cost_usd", 0.0),
|
||||||
o.optJSONObject("usage")?.let { it.optLong("input_tokens") + it.optLong("cache_read_input_tokens") + it.optLong("cache_creation_input_tokens") } ?: 0,
|
o.optJSONObject("usage")?.let { it.optLong("input_tokens") + it.optLong("cache_read_input_tokens") + it.optLong("cache_creation_input_tokens") } ?: 0,
|
||||||
@@ -149,6 +163,24 @@ object ClaudeCode : AgentHarness {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private val WINDOW_MINUTES = mapOf("five_hour" to 300, "seven_day" to 10_080)
|
||||||
|
|
||||||
|
@VisibleForTesting
|
||||||
|
internal fun limits(info: JSONObject?): List<AgentHost.Limit>? {
|
||||||
|
val windows = info?.optJSONObject("unifiedWindows") ?: return null
|
||||||
|
return WINDOW_MINUTES.mapNotNull { (key, minutes) ->
|
||||||
|
val w = windows.optJSONObject(key) ?: return@mapNotNull null
|
||||||
|
AgentHost.Limit(minutes, (w.optDouble("utilization", 0.0) * 100).toInt(), w.optLong("resetsAt"))
|
||||||
|
}.takeIf { it.isNotEmpty() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The context window of the model that did most of the turn; subagents may run a smaller one. */
|
||||||
|
private fun window(models: JSONObject?): Long? {
|
||||||
|
models ?: return null
|
||||||
|
return models.keys().asSequence().mapNotNull { models.optJSONObject(it) }
|
||||||
|
.maxByOrNull { it.optDouble("costUSD", 0.0) }?.optLong("contextWindow")?.takeIf { it > 0 }
|
||||||
|
}
|
||||||
|
|
||||||
private fun resultText(content: Any?): String = when (content) {
|
private fun resultText(content: Any?): String = when (content) {
|
||||||
is String -> content
|
is String -> content
|
||||||
is JSONArray -> (0 until content.length()).mapNotNull { i ->
|
is JSONArray -> (0 until content.length()).mapNotNull { i ->
|
||||||
@@ -176,8 +208,8 @@ object ClaudeCode : AgentHarness {
|
|||||||
input ?: return ""
|
input ?: return ""
|
||||||
return when {
|
return when {
|
||||||
tool == "Bash" -> input.optString("command")
|
tool == "Bash" -> input.optString("command")
|
||||||
tool == "Edit" -> "${input.optString("file_path")}\n\n- ${input.optString("old_string").replace("\n", "\n- ")}\n\n+ ${input.optString("new_string").replace("\n", "\n+ ")}"
|
tool == "Edit" -> input.optString("file_path") + "\n" + lineDiff(input.optString("old_string"), input.optString("new_string"))
|
||||||
tool == "Write" -> "${input.optString("file_path")}\n\n${input.optString("content")}"
|
tool == "Write" -> input.optString("file_path") + "\n" + lineDiff("", input.optString("content"))
|
||||||
tool == "TodoWrite" -> todos(input.optJSONArray("todos"))
|
tool == "TodoWrite" -> todos(input.optJSONArray("todos"))
|
||||||
else -> input.toString(2)
|
else -> input.toString(2)
|
||||||
}
|
}
|
||||||
@@ -212,6 +244,7 @@ object Codex : AgentHarness {
|
|||||||
override val signedIn = listOf(binary, "login", "status")
|
override val signedIn = listOf(binary, "login", "status")
|
||||||
override val signIn = listOf(binary, "login")
|
override val signIn = listOf(binary, "login")
|
||||||
override val plans = false
|
override val plans = false
|
||||||
|
override val efforts = listOf("low", "medium", "high")
|
||||||
|
|
||||||
/** Codex keeps the models its account can use in `~/.codex/models_cache.json` once it has run. */
|
/** Codex keeps the models its account can use in `~/.codex/models_cache.json` once it has run. */
|
||||||
override fun models(rootfs: File): List<AgentHarness.Model> = runCatching {
|
override fun models(rootfs: File): List<AgentHarness.Model> = runCatching {
|
||||||
@@ -231,6 +264,7 @@ object Codex : AgentHarness {
|
|||||||
if (conversation != null) addAll(listOf("resume", conversation))
|
if (conversation != null) addAll(listOf("resume", conversation))
|
||||||
addAll(listOf("--json", "--dangerously-bypass-approvals-and-sandbox", "--skip-git-repo-check"))
|
addAll(listOf("--json", "--dangerously-bypass-approvals-and-sandbox", "--skip-git-repo-check"))
|
||||||
options.model?.let { addAll(listOf("-m", it)) }
|
options.model?.let { addAll(listOf("-m", it)) }
|
||||||
|
options.effort?.let { addAll(listOf("-c", "model_reasoning_effort=\"$it\"")) }
|
||||||
// codex exec has no system prompt option, so a new conversation starts with the brief.
|
// codex exec has no system prompt option, so a new conversation starts with the brief.
|
||||||
add(if (conversation == null && options.brief != null) "${options.brief}\n\n$message" else message)
|
add(if (conversation == null && options.brief != null) "${options.brief}\n\n$message" else message)
|
||||||
}
|
}
|
||||||
@@ -281,6 +315,33 @@ object Codex : AgentHarness {
|
|||||||
return if (entries.isEmpty()) null else AgentEvent(entries = entries)
|
return if (entries.isEmpty()) null else AgentEvent(entries = entries)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private const val TOKEN_COUNT = "\"payload\":{\"type\":\"token_count\""
|
||||||
|
|
||||||
|
/** Codex prints no limits with --json; its session log, named after the thread, has a token_count event each step. */
|
||||||
|
override fun usage(rootfs: File, conversation: String?): AgentEvent? {
|
||||||
|
conversation ?: return null
|
||||||
|
val log = File(rootfs, "root/.codex/sessions").walkBottomUp().filter { it.isFile && it.name.endsWith("-$conversation.jsonl") }
|
||||||
|
.maxByOrNull { it.lastModified() } ?: return null
|
||||||
|
val last = runCatching { log.readLines().lastOrNull { it.contains(TOKEN_COUNT) } }.getOrNull() ?: return null
|
||||||
|
return tokenCount(last)
|
||||||
|
}
|
||||||
|
|
||||||
|
@VisibleForTesting
|
||||||
|
internal fun tokenCount(line: String): AgentEvent? {
|
||||||
|
val payload = runCatching { JSONObject(line).optJSONObject("payload") }.getOrNull()?.takeIf { it.optString("type") == "token_count" } ?: return null
|
||||||
|
val info = payload.optJSONObject("info")
|
||||||
|
val rates = payload.optJSONObject("rate_limits")
|
||||||
|
val limits = listOf("primary", "secondary").mapNotNull { key ->
|
||||||
|
val w = rates?.optJSONObject(key) ?: return@mapNotNull null
|
||||||
|
AgentHost.Limit(w.optInt("window_minutes"), w.optDouble("used_percent", 0.0).toInt(), w.optLong("resets_at"))
|
||||||
|
}
|
||||||
|
return AgentEvent(
|
||||||
|
context = info?.optJSONObject("last_token_usage")?.optLong("total_tokens")?.takeIf { it > 0 },
|
||||||
|
window = info?.optLong("model_context_window")?.takeIf { it > 0 },
|
||||||
|
limits = limits.takeIf { it.isNotEmpty() },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
private fun todoEntry(id: String, item: JSONObject): AgentHost.Entry.Used {
|
private fun todoEntry(id: String, item: JSONObject): AgentHost.Entry.Used {
|
||||||
val items = item.optJSONArray("items") ?: JSONArray()
|
val items = item.optJSONArray("items") ?: JSONArray()
|
||||||
val text = (0 until items.length()).mapNotNull { i ->
|
val text = (0 until items.length()).mapNotNull { i ->
|
||||||
@@ -299,6 +360,28 @@ object Codex : AgentHarness {
|
|||||||
@VisibleForTesting
|
@VisibleForTesting
|
||||||
internal fun firstLine(text: String) = text.lineSequence().first().take(160)
|
internal fun firstLine(text: String) = text.lineSequence().first().take(160)
|
||||||
|
|
||||||
|
private const val DIFF_CONTEXT = 2
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [old] against [new], one line per changed or nearby line, each led by ' ', '-' or '+'. Edits
|
||||||
|
* replace a short span, so the lines both share at the start and end are cut to [DIFF_CONTEXT].
|
||||||
|
*/
|
||||||
|
@VisibleForTesting
|
||||||
|
internal fun lineDiff(old: String, new: String): String {
|
||||||
|
val a = if (old.isEmpty()) emptyList() else old.removeSuffix("\n").lines()
|
||||||
|
val b = if (new.isEmpty()) emptyList() else new.removeSuffix("\n").lines()
|
||||||
|
var head = 0
|
||||||
|
while (head < a.size && head < b.size && a[head] == b[head]) head++
|
||||||
|
var tail = 0
|
||||||
|
while (tail < a.size - head && tail < b.size - head && a[a.size - 1 - tail] == b[b.size - 1 - tail]) tail++
|
||||||
|
return buildList {
|
||||||
|
a.subList(maxOf(0, head - DIFF_CONTEXT), head).forEach { add(" $it") }
|
||||||
|
a.subList(head, a.size - tail).forEach { add("-$it") }
|
||||||
|
b.subList(head, b.size - tail).forEach { add("+$it") }
|
||||||
|
a.subList(a.size - tail, minOf(a.size, a.size - tail + DIFF_CONTEXT)).forEach { add(" $it") }
|
||||||
|
}.joinToString("\n")
|
||||||
|
}
|
||||||
|
|
||||||
private val SHELL_WRAPPER = Regex("^/bin/(?:ba)?sh -l?c '(.*)'$", RegexOption.DOT_MATCHES_ALL)
|
private val SHELL_WRAPPER = Regex("^/bin/(?:ba)?sh -l?c '(.*)'$", RegexOption.DOT_MATCHES_ALL)
|
||||||
|
|
||||||
/** Codex runs each command as `/bin/bash -lc '<command>'`; the command is what the user wants to read. */
|
/** Codex runs each command as `/bin/bash -lc '<command>'`; the command is what the user wants to read. */
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import androidx.compose.runtime.mutableStateOf
|
|||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import com.droiddeck.launcher.R
|
import com.droiddeck.launcher.R
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
|
import com.droiddeck.launcher.session.OrphanReaper
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
import com.droiddeck.launcher.session.SessionPrefs
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.nio.file.Files
|
import java.nio.file.Files
|
||||||
@@ -28,13 +29,24 @@ object AgentHost {
|
|||||||
data class Asked(val text: String, val files: List<String> = emptyList()) : Entry
|
data class Asked(val text: String, val files: List<String> = emptyList()) : Entry
|
||||||
data class Said(val text: String) : Entry
|
data class Said(val text: String) : Entry
|
||||||
data class Thought(val text: String) : Entry
|
data class Thought(val text: String) : Entry
|
||||||
/** A tool call; [output] stays null until its result arrives. */
|
/** A tool call; [output] stays null until its result arrives. [parent] is the subagent call it was made under, if any. */
|
||||||
data class Used(val id: String, val tool: String, val detail: String, val input: String = "", val output: String? = null, val failed: Boolean = false) : Entry
|
data class Used(
|
||||||
|
val id: String, val tool: String, val detail: String, val input: String = "", val output: String? = null, val failed: Boolean = false,
|
||||||
|
val parent: String = "",
|
||||||
|
) : Entry
|
||||||
data class Result(val id: String, val output: String, val failed: Boolean) : Entry
|
data class Result(val id: String, val output: String, val failed: Boolean) : Entry
|
||||||
data class Finished(val error: String?, val stopped: Boolean = false, val usage: Usage? = null) : Entry
|
/** [planned]: the turn ran in plan mode, so it ends on a plan that nothing has carried out yet. */
|
||||||
|
data class Finished(val error: String?, val stopped: Boolean = false, val usage: Usage? = null, val planned: Boolean = false) : Entry
|
||||||
}
|
}
|
||||||
|
|
||||||
data class Usage(val durationMs: Long, val costUsd: Double, val inputTokens: Long, val outputTokens: Long)
|
/** [context] of [window] tokens is what the conversation held when the turn ended. */
|
||||||
|
data class Usage(
|
||||||
|
val durationMs: Long, val costUsd: Double, val inputTokens: Long, val outputTokens: Long,
|
||||||
|
val context: Long = 0, val window: Long = 0,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** A plan usage limit over a rolling window of [minutes]; [resetsAt] is in epoch seconds. */
|
||||||
|
data class Limit(val minutes: Int, val usedPercent: Int, val resetsAt: Long)
|
||||||
|
|
||||||
/** A message typed while the agent was working, sent when the turn ends. */
|
/** A message typed while the agent was working, sent when the turn ends. */
|
||||||
data class Queued(val text: String, val files: List<String>)
|
data class Queued(val text: String, val files: List<String>)
|
||||||
@@ -43,6 +55,7 @@ object AgentHost {
|
|||||||
|
|
||||||
private const val TAG = "AgentHost"
|
private const val TAG = "AgentHost"
|
||||||
private const val WORKSPACE = "/root/DroidDeck"
|
private const val WORKSPACE = "/root/DroidDeck"
|
||||||
|
internal const val GUEST_PATH = "/root/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
|
||||||
private const val TICK_MS = 1_000L
|
private const val TICK_MS = 1_000L
|
||||||
private const val IDLE_TICK_MS = 5_000L
|
private const val IDLE_TICK_MS = 5_000L
|
||||||
|
|
||||||
@@ -50,13 +63,20 @@ object AgentHost {
|
|||||||
@VisibleForTesting
|
@VisibleForTesting
|
||||||
internal const val BRIEF = "You run inside DroidDeck on the user's handheld, in its Linux userland (Ubuntu under proot, aarch64), " +
|
internal const val BRIEF = "You run inside DroidDeck on the user's handheld, in its Linux userland (Ubuntu under proot, aarch64), " +
|
||||||
"and the user talks to you from DroidDeck's Agent tab, often on a small screen, so keep replies short. " +
|
"and the user talks to you from DroidDeck's Agent tab, often on a small screen, so keep replies short. " +
|
||||||
"droiddeckctl (in the /root/DroidDeck checkout, tools/droiddeckctl) inspects and drives the app over loopback adb (\$ADB_SERIAL). " +
|
"droiddeckctl inspects and drives the app over loopback adb (\$ADB_SERIAL); its guide is ${AgentSetup.CTL}/agent-control.md. " +
|
||||||
|
"Steam, the desktop and games run in DroidDeck's session, a separate guest from yours: a program you start here is not in it and has no screen. " +
|
||||||
|
"Reach the session through droiddeckctl: state, start steam, stop, launch, quit, focus, screenshot, logs, and guest to run a command inside it. " +
|
||||||
|
"Starting, stopping or restarting a session leaves you running. " +
|
||||||
|
"Never kill by a command-line pattern (pkill -f, pgrep -f piped to kill): your own command line holds the user's message, so the pattern matches you. " +
|
||||||
|
"End a game with droiddeckctl quit, the session with droiddeckctl stop, anything else by its pid. " +
|
||||||
"dd-lab-build builds the checkout as a Lab build and restarts DroidDeck on it (docs/lab-builds.md). DroidDeck runs the build in a " +
|
"dd-lab-build builds the checkout as a Lab build and restarts DroidDeck on it (docs/lab-builds.md). DroidDeck runs the build in a " +
|
||||||
"process of its own and shows the user its progress and time left; dd-lab-build follows that build's log until it is done. " +
|
"process of its own and shows the user its progress and time left; dd-lab-build follows that build's log until it is done. " +
|
||||||
"Run it with run_in_background and keep checking its output, so the user can talk to you meanwhile. " +
|
"Run it with run_in_background and keep checking its output, so the user can talk to you meanwhile. " +
|
||||||
"The restart ends this process, and this conversation continues on the new build. " +
|
"The restart ends this process, and this conversation continues on the new build. " +
|
||||||
"Files the user attaches are listed at the end of their message, under /root/.cache/droiddeck/attachments. " +
|
"Files the user attaches are listed at the end of their message, under /root/.cache/droiddeck/attachments. " +
|
||||||
"Commits and pull requests you make are the user's own: add no co-author line, AI credit or generated-by note."
|
"Commits and pull requests you make are the user's own: add no co-author line, AI credit or generated-by note. " +
|
||||||
|
"To have the user pick between options, end your reply with a fenced code block whose language is choices, one short option per line, " +
|
||||||
|
"and end your turn: DroidDeck shows them as buttons and sends the one picked as the next message."
|
||||||
|
|
||||||
val entries = mutableStateListOf<Entry>()
|
val entries = mutableStateListOf<Entry>()
|
||||||
val queue = mutableStateListOf<Queued>()
|
val queue = mutableStateListOf<Queued>()
|
||||||
@@ -72,6 +92,9 @@ object AgentHost {
|
|||||||
/** The chosen model for [harness]; null is the CLI's default. */
|
/** The chosen model for [harness]; null is the CLI's default. */
|
||||||
var model by mutableStateOf<String?>(null)
|
var model by mutableStateOf<String?>(null)
|
||||||
private set
|
private set
|
||||||
|
/** The chosen reasoning effort for [harness]; null is the CLI's default. */
|
||||||
|
var effort by mutableStateOf<String?>(null)
|
||||||
|
private set
|
||||||
var plan by mutableStateOf(false)
|
var plan by mutableStateOf(false)
|
||||||
private set
|
private set
|
||||||
var chat by mutableStateOf<String?>(null)
|
var chat by mutableStateOf<String?>(null)
|
||||||
@@ -94,6 +117,12 @@ object AgentHost {
|
|||||||
/** Tokens in the conversation's context after its last step. */
|
/** Tokens in the conversation's context after its last step. */
|
||||||
var context by mutableLongStateOf(0L)
|
var context by mutableLongStateOf(0L)
|
||||||
private set
|
private set
|
||||||
|
/** Tokens the model's context can hold; 0 until a turn has told. */
|
||||||
|
var window by mutableLongStateOf(0L)
|
||||||
|
private set
|
||||||
|
/** The account's plan limits as [harness] last reported them. */
|
||||||
|
var limits by mutableStateOf<List<Limit>>(emptyList())
|
||||||
|
private set
|
||||||
var lab by mutableStateOf<LabProgress?>(null)
|
var lab by mutableStateOf<LabProgress?>(null)
|
||||||
private set
|
private set
|
||||||
|
|
||||||
@@ -110,6 +139,7 @@ object AgentHost {
|
|||||||
/** The running Lab build was asked for by the current turn, so stopping the turn stops it. */
|
/** The running Lab build was asked for by the current turn, so stopping the turn stops it. */
|
||||||
private var labFromTurn = false
|
private var labFromTurn = false
|
||||||
private var conversation: String? = null
|
private var conversation: String? = null
|
||||||
|
private var turnPlanned = false
|
||||||
private var loaded = false
|
private var loaded = false
|
||||||
private var appContext: Context? = null
|
private var appContext: Context? = null
|
||||||
|
|
||||||
@@ -117,6 +147,7 @@ object AgentHost {
|
|||||||
|
|
||||||
fun seen() {
|
fun seen() {
|
||||||
unseen = false
|
unseen = false
|
||||||
|
appContext?.let { AgentNotice.clear(it) }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun refresh(context: Context) {
|
fun refresh(context: Context) {
|
||||||
@@ -125,7 +156,9 @@ object AgentHost {
|
|||||||
File(app.filesDir, "agent").mkdirs()
|
File(app.filesDir, "agent").mkdirs()
|
||||||
harness = AgentHarness.byId(prefs(app).getString(HARNESS_KEY, null))
|
harness = AgentHarness.byId(prefs(app).getString(HARNESS_KEY, null))
|
||||||
model = prefs(app).getString(modelKey(harness), null)
|
model = prefs(app).getString(modelKey(harness), null)
|
||||||
|
effort = prefs(app).getString(effortKey(harness), null)?.takeIf { it in harness.efforts }
|
||||||
plan = prefs(app).getBoolean(PLAN_KEY, false)
|
plan = prefs(app).getBoolean(PLAN_KEY, false)
|
||||||
|
limits = decodeLimits(prefs(app).getString(limitsKey(harness), null))
|
||||||
available = LinuxRuntime.hasRootfs(app)
|
available = LinuxRuntime.hasRootfs(app)
|
||||||
installed = harness.files.all { guestFileExists(app, it) }
|
installed = harness.files.all { guestFileExists(app, it) }
|
||||||
if (!installed) state = State.MISSING else if (state == State.MISSING) state = State.IDLE
|
if (!installed) state = State.MISSING else if (state == State.MISSING) state = State.IDLE
|
||||||
@@ -148,7 +181,9 @@ object AgentHost {
|
|||||||
conversation = loaded.conversation
|
conversation = loaded.conversation
|
||||||
entries.clear()
|
entries.clear()
|
||||||
entries.addAll(loaded.entries)
|
entries.addAll(loaded.entries)
|
||||||
context = 0
|
val last = loaded.entries.lastOrNull { it is Entry.Finished && (it.usage?.context ?: 0) > 0 } as? Entry.Finished
|
||||||
|
context = last?.usage?.context ?: 0
|
||||||
|
window = last?.usage?.window ?: 0
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Opens a kept conversation, switching to the CLI it belongs to. */
|
/** Opens a kept conversation, switching to the CLI it belongs to. */
|
||||||
@@ -214,6 +249,11 @@ object AgentHost {
|
|||||||
prefs(context).edit().putString(modelKey(harness), id).apply()
|
prefs(context).edit().putString(modelKey(harness), id).apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun chooseEffort(context: Context, level: String?) {
|
||||||
|
effort = level
|
||||||
|
prefs(context).edit().putString(effortKey(harness), level).apply()
|
||||||
|
}
|
||||||
|
|
||||||
fun choosePlan(context: Context, on: Boolean) {
|
fun choosePlan(context: Context, on: Boolean) {
|
||||||
plan = on
|
plan = on
|
||||||
prefs(context).edit().putBoolean(PLAN_KEY, on).apply()
|
prefs(context).edit().putBoolean(PLAN_KEY, on).apply()
|
||||||
@@ -248,10 +288,15 @@ object AgentHost {
|
|||||||
AgentHostService.start(app)
|
AgentHostService.start(app)
|
||||||
val current = harness
|
val current = harness
|
||||||
val prompt = AgentAttachments.prompt(message, attached)
|
val prompt = AgentAttachments.prompt(message, attached)
|
||||||
val command = current.turn(prompt, conversation, AgentHarness.Options(model, plan && current.plans, BRIEF))
|
turnPlanned = plan && current.plans
|
||||||
|
val command = current.turn(prompt, conversation, AgentHarness.Options(model, turnPlanned, BRIEF, effort))
|
||||||
val workdir = workspace(app)
|
val workdir = workspace(app)
|
||||||
|
var threadConversation = conversation
|
||||||
Thread({
|
Thread({
|
||||||
runCatching { current.prepare(LinuxRuntime.rootDir(app)) }
|
runCatching { current.prepare(LinuxRuntime.rootDir(app)) }
|
||||||
|
runCatching { AgentSetup.installHelpers(app) }
|
||||||
|
// Without a session nothing else keeps the userland's resolver current.
|
||||||
|
runCatching { com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent(app, LinuxRuntime.rootDir(app)).publish() }
|
||||||
val child = try {
|
val child = try {
|
||||||
guest(app, command, workdir).start()
|
guest(app, command, workdir).start()
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
@@ -260,6 +305,7 @@ object AgentHost {
|
|||||||
return@Thread
|
return@Thread
|
||||||
}
|
}
|
||||||
val started = Turn(child, AgentProcesses.pidOf(child))
|
val started = Turn(child, AgentProcesses.pidOf(child))
|
||||||
|
OrphanReaper.keep(started.pid)
|
||||||
main.post { if (generation == gen && state == State.WORKING && turn == null) turn = started else AgentProcesses.killTree(started.pid) }
|
main.post { if (generation == gen && state == State.WORKING && turn == null) turn = started else AgentProcesses.killTree(started.pid) }
|
||||||
child.outputStream.close()
|
child.outputStream.close()
|
||||||
var ended = false
|
var ended = false
|
||||||
@@ -271,13 +317,18 @@ object AgentHost {
|
|||||||
runCatching {
|
runCatching {
|
||||||
child.inputStream.bufferedReader().forEachLine { line ->
|
child.inputStream.bufferedReader().forEachLine { line ->
|
||||||
runCatching { raw?.apply { write(line); newLine(); flush() } }
|
runCatching { raw?.apply { write(line); newLine(); flush() } }
|
||||||
val event = current.parse(line) ?: return@forEachLine
|
val parsed = current.parse(line) ?: return@forEachLine
|
||||||
if (event.entries.any { it is Entry.Finished }) ended = true
|
parsed.conversation?.let { threadConversation = it }
|
||||||
|
val done = parsed.entries.any { it is Entry.Finished }
|
||||||
|
if (done) ended = true
|
||||||
|
val event = if (!done) parsed else runCatching { current.usage(LinuxRuntime.rootDir(app), threadConversation) }.getOrNull()
|
||||||
|
?.let { parsed.copy(context = it.context ?: parsed.context, window = it.window ?: parsed.window, limits = it.limits ?: parsed.limits) } ?: parsed
|
||||||
main.post { if (turn === started) apply(app, event) }
|
main.post { if (turn === started) apply(app, event) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
runCatching { raw?.close() }
|
runCatching { raw?.close() }
|
||||||
val status = runCatching { child.waitFor() }.getOrDefault(-1)
|
val status = runCatching { child.waitFor() }.getOrDefault(-1)
|
||||||
|
OrphanReaper.release(started.pid)
|
||||||
main.post {
|
main.post {
|
||||||
if (turn === started) {
|
if (turn === started) {
|
||||||
turn = null
|
turn = null
|
||||||
@@ -305,6 +356,16 @@ object AgentHost {
|
|||||||
queue.remove(item)
|
queue.remove(item)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Sends [item] now: the running turn stops where it is, and the rest of the queue waits for the next one. */
|
||||||
|
fun sendNow(context: Context, item: Queued) {
|
||||||
|
val app = context.applicationContext
|
||||||
|
if (!queue.remove(item)) return
|
||||||
|
val rest = queue.toList()
|
||||||
|
stop(app)
|
||||||
|
queue.addAll(rest)
|
||||||
|
send(app, item.text, item.files)
|
||||||
|
}
|
||||||
|
|
||||||
/** Starts a new conversation; the current one stays in the history. */
|
/** Starts a new conversation; the current one stays in the history. */
|
||||||
fun forget(context: Context) {
|
fun forget(context: Context) {
|
||||||
stop(context)
|
stop(context)
|
||||||
@@ -313,6 +374,7 @@ object AgentHost {
|
|||||||
chat = null
|
chat = null
|
||||||
conversation = null
|
conversation = null
|
||||||
this.context = 0
|
this.context = 0
|
||||||
|
window = 0
|
||||||
prefs(context).edit().remove(CHAT_KEY).apply()
|
prefs(context).edit().remove(CHAT_KEY).apply()
|
||||||
state = if (installed) State.IDLE else State.MISSING
|
state = if (installed) State.IDLE else State.MISSING
|
||||||
}
|
}
|
||||||
@@ -322,11 +384,11 @@ object AgentHost {
|
|||||||
* proot over the installed rootfs, without a session. Loopback adb is connected first so
|
* proot over the installed rootfs, without a session. Loopback adb is connected first so
|
||||||
* droiddeckctl reaches the app.
|
* droiddeckctl reaches the app.
|
||||||
*/
|
*/
|
||||||
fun guest(app: Context, command: List<String>, workdir: String = "/root", connectAdb: Boolean = true): ProcessBuilder {
|
fun guest(app: Context, command: List<String>, workdir: String = "/root", connectAdb: Boolean = true, fakeRoot: Boolean = false): ProcessBuilder {
|
||||||
val adb = AgentAdb.prepare(app)
|
val adb = AgentAdb.prepare(app)
|
||||||
val env = listOf(
|
val env = listOf(
|
||||||
"/usr/bin/env", "HOME=/root", "PATH=/root/.local/bin:/usr/local/bin:/usr/bin:/bin", "LANG=C.UTF-8",
|
"/usr/bin/env", "HOME=/root", "PATH=$GUEST_PATH", "LANG=C.UTF-8",
|
||||||
"ADB_SERIAL=${adb.serial}", "ADB_VENDOR_KEYS=${adb.vendorKeys}",
|
"ADB_SERIAL=${adb.serial}", "ADB_VENDOR_KEYS=${adb.vendorKeys}", "DROIDDECK_PACKAGE=${app.packageName}",
|
||||||
"DD_AGENT=1", "DD_AGENT_INBOX=${File(app.filesDir, "agent").path}", "BROWSER=/root/.local/bin/android-open", "DD_BROWSER_DISPLAY=${AgentAdb.browserDisplay}",
|
"DD_AGENT=1", "DD_AGENT_INBOX=${File(app.filesDir, "agent").path}", "BROWSER=/root/.local/bin/android-open", "DD_BROWSER_DISPLAY=${AgentAdb.browserDisplay}",
|
||||||
)
|
)
|
||||||
val shell = listOf(
|
val shell = listOf(
|
||||||
@@ -335,7 +397,7 @@ object AgentHost {
|
|||||||
(if (connectAdb) "adb start-server >/dev/null 2>&1; adb connect \"\$ADB_SERIAL\" >/dev/null 2>&1; " else "") +
|
(if (connectAdb) "adb start-server >/dev/null 2>&1; adb connect \"\$ADB_SERIAL\" >/dev/null 2>&1; " else "") +
|
||||||
"cd \"$1\" 2>/dev/null; shift; exec \"$@\"", "sh", workdir,
|
"cd \"$1\" 2>/dev/null; shift; exec \"$@\"", "sh", workdir,
|
||||||
)
|
)
|
||||||
val proot = LinuxRuntime.command(app, null, null, Environment.getExternalStorageDirectory(), env + shell + command)
|
val proot = LinuxRuntime.command(app, null, null, Environment.getExternalStorageDirectory(), null, env + shell + command, fakeRoot)
|
||||||
return ProcessBuilder(proot).redirectErrorStream(true).apply {
|
return ProcessBuilder(proot).redirectErrorStream(true).apply {
|
||||||
environment().apply {
|
environment().apply {
|
||||||
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
|
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
|
||||||
@@ -362,6 +424,11 @@ object AgentHost {
|
|||||||
event.text?.let { live += it }
|
event.text?.let { live += it }
|
||||||
event.thinking?.let { liveThinking += it }
|
event.thinking?.let { liveThinking += it }
|
||||||
event.context?.let { context = it }
|
event.context?.let { context = it }
|
||||||
|
event.window?.let { window = it }
|
||||||
|
event.limits?.let { reported ->
|
||||||
|
limits = (limits.filter { old -> reported.none { it.minutes == old.minutes } } + reported).sortedBy { it.minutes }
|
||||||
|
prefs(app).edit().putString(limitsKey(harness), encodeLimits(limits)).apply()
|
||||||
|
}
|
||||||
for (entry in event.entries) when (entry) {
|
for (entry in event.entries) when (entry) {
|
||||||
is Entry.Finished -> finish(app, entry.error, usage = event.usage)
|
is Entry.Finished -> finish(app, entry.error, usage = event.usage)
|
||||||
else -> {
|
else -> {
|
||||||
@@ -379,7 +446,8 @@ object AgentHost {
|
|||||||
if (!stopped) labFromTurn = false
|
if (!stopped) labFromTurn = false
|
||||||
live = ""
|
live = ""
|
||||||
liveThinking = ""
|
liveThinking = ""
|
||||||
record(app, Entry.Finished(error, stopped, usage))
|
val held = if (context > 0) (usage ?: Usage(0, 0.0, 0, 0)).copy(context = context, window = window) else usage
|
||||||
|
record(app, Entry.Finished(error, stopped, held, planned = turnPlanned && !stopped && error == null))
|
||||||
state = State.IDLE
|
state = State.IDLE
|
||||||
unseen = true
|
unseen = true
|
||||||
failed = error != null
|
failed = error != null
|
||||||
@@ -400,7 +468,19 @@ object AgentHost {
|
|||||||
if (!stopped && queue.isNotEmpty()) {
|
if (!stopped && queue.isNotEmpty()) {
|
||||||
val next = queue.removeAt(0)
|
val next = queue.removeAt(0)
|
||||||
send(app, next.text, next.files)
|
send(app, next.text, next.files)
|
||||||
|
} else if (!stopped) notifyEnded(app, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun notifyEnded(app: Context, error: String?) {
|
||||||
|
val start = entries.indexOfLast { it is Entry.Asked }
|
||||||
|
val said = entries.subList(start + 1, entries.size).lastOrNull { it is Entry.Said } as? Entry.Said
|
||||||
|
val reply = said?.let { choices(it.text) }
|
||||||
|
val kind = when {
|
||||||
|
error != null -> AgentNotice.Kind.FAILED
|
||||||
|
!reply?.options.isNullOrEmpty() -> AgentNotice.Kind.QUESTION
|
||||||
|
else -> AgentNotice.Kind.DONE
|
||||||
}
|
}
|
||||||
|
AgentNotice.post(app, kind, error ?: reply?.text?.takeIf { it.isNotBlank() }?.let { firstLine(it) } ?: "")
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A message typed or retried by the user replaces the automatic resend. */
|
/** A message typed or retried by the user replaces the automatic resend. */
|
||||||
@@ -439,13 +519,14 @@ object AgentHost {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** The latest todo list the agent wrote in this conversation. */
|
/** The latest todo list the agent wrote in this conversation. */
|
||||||
fun todos(): String? = entries.lastOrNull { it is Entry.Used && it.tool == "TodoWrite" }?.let { (it as Entry.Used).input }
|
fun todos(): String? = entries.lastOrNull { it is Entry.Used && it.tool == "TodoWrite" && it.parent.isEmpty() }?.let { (it as Entry.Used).input }
|
||||||
|
|
||||||
private fun tick() {
|
private fun tick() {
|
||||||
now = SystemClock.elapsedRealtime()
|
now = SystemClock.elapsedRealtime()
|
||||||
appContext?.let { app ->
|
appContext?.let { app ->
|
||||||
claimLabRequest(app)
|
claimLabRequest(app)
|
||||||
claimOpenUrl(app)
|
claimOpenUrl(app)
|
||||||
|
claimDeviceCode(app)
|
||||||
// proot comes from an add-on pack fetched after the app starts, so the runtime can become usable later.
|
// proot comes from an add-on pack fetched after the app starts, so the runtime can become usable later.
|
||||||
if (!available && state != State.WORKING) available = LinuxRuntime.hasRootfs(app)
|
if (!available && state != State.WORKING) available = LinuxRuntime.hasRootfs(app)
|
||||||
lab = LabProgress.read(LinuxRuntime.rootDir(app))
|
lab = LabProgress.read(LinuxRuntime.rootDir(app))
|
||||||
@@ -467,15 +548,43 @@ object AgentHost {
|
|||||||
val url = runCatching { claimed.readText().trim() }.getOrNull()
|
val url = runCatching { claimed.readText().trim() }.getOrNull()
|
||||||
claimed.delete()
|
claimed.delete()
|
||||||
if (url == null || !(url.startsWith("https://") || url.startsWith("http://"))) return
|
if (url == null || !(url.startsWith("https://") || url.startsWith("http://"))) return
|
||||||
|
if (!openUrl(app, url)) runCatching { File(app.filesDir, "$OPEN_URL.failed").writeText("") }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** dd-gh-login leaves "<code> <url>" here to float the code over the page, and an empty file when it ends. */
|
||||||
|
private fun claimDeviceCode(app: Context) {
|
||||||
|
val request = File(app.filesDir, DEVICE_CODE)
|
||||||
|
if (!request.isFile) return
|
||||||
|
val claimed = File(app.filesDir, "$DEVICE_CODE.claimed")
|
||||||
|
if (!request.renameTo(claimed)) return
|
||||||
|
val parts = runCatching { claimed.readText().trim() }.getOrDefault("").split(' ', limit = 2)
|
||||||
|
claimed.delete()
|
||||||
|
val code = parts[0]
|
||||||
|
val url = parts.getOrNull(1)?.takeIf { it.startsWith("https://") }
|
||||||
|
if (code.isEmpty() || url == null) {
|
||||||
|
com.droiddeck.launcher.DeviceCodeActivity.close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!com.droiddeck.launcher.DeviceCodeActivity.show(app, code, url, AgentAdb.browserDisplay)) deviceCodeOpened(app, openUrl(app, url))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Tells dd-gh-login whether the device page opened, so it can fall back to android-open. */
|
||||||
|
fun deviceCodeOpened(app: Context, opened: Boolean) {
|
||||||
|
runCatching {
|
||||||
|
val part = File(app.filesDir, "$DEVICE_CODE.result.part")
|
||||||
|
part.writeText(if (opened) "ok" else "failed")
|
||||||
|
part.renameTo(File(app.filesDir, "$DEVICE_CODE.result"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun openUrl(app: Context, url: String): Boolean {
|
||||||
val intent = android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(url))
|
val intent = android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(url))
|
||||||
.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
|
.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
val options = android.app.ActivityOptions.makeBasic().setLaunchDisplayId(AgentAdb.browserDisplay).toBundle()
|
val options = android.app.ActivityOptions.makeBasic().setLaunchDisplayId(AgentAdb.browserDisplay).toBundle()
|
||||||
runCatching { app.startActivity(intent, options) }
|
return runCatching { app.startActivity(intent, options) }
|
||||||
.recoverCatching { app.startActivity(intent) }
|
.recoverCatching { app.startActivity(intent) }
|
||||||
.onFailure {
|
.onFailure { Log.w(TAG, "could not open a sign-in link: ${it.javaClass.simpleName}") }
|
||||||
Log.w(TAG, "could not open a sign-in link: ${it.javaClass.simpleName}")
|
.isSuccess
|
||||||
runCatching { File(app.filesDir, "$OPEN_URL.failed").writeText("") }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -500,9 +609,15 @@ object AgentHost {
|
|||||||
val child = guest(app, listOf("sh", "-c",
|
val child = guest(app, listOf("sh", "-c",
|
||||||
"mkdir -p /root/.cache; DD_LAB_DETACHED=1 exec dd-lab-build \"\$@\" > /root/.cache/dd-lab-build.log 2>&1", "dd-lab-build") + args, cwd).start()
|
"mkdir -p /root/.cache; DD_LAB_DETACHED=1 exec dd-lab-build \"\$@\" > /root/.cache/dd-lab-build.log 2>&1", "dd-lab-build") + args, cwd).start()
|
||||||
main.post { labProcess = child }
|
main.post { labProcess = child }
|
||||||
child.outputStream.close()
|
val pid = AgentProcesses.pidOf(child)
|
||||||
child.inputStream.readBytes()
|
OrphanReaper.keep(pid)
|
||||||
child.waitFor()
|
try {
|
||||||
|
child.outputStream.close()
|
||||||
|
child.inputStream.readBytes()
|
||||||
|
child.waitFor()
|
||||||
|
} finally {
|
||||||
|
OrphanReaper.release(pid)
|
||||||
|
}
|
||||||
}.onFailure { Log.w(TAG, "could not run a Lab build", it) }
|
}.onFailure { Log.w(TAG, "could not run a Lab build", it) }
|
||||||
main.post {
|
main.post {
|
||||||
labProcess = null
|
labProcess = null
|
||||||
@@ -525,12 +640,57 @@ object AgentHost {
|
|||||||
private const val RESUME = "agent/resume"
|
private const val RESUME = "agent/resume"
|
||||||
private const val LAB_REQUEST = "agent/lab-request"
|
private const val LAB_REQUEST = "agent/lab-request"
|
||||||
private const val OPEN_URL = "agent/open-url"
|
private const val OPEN_URL = "agent/open-url"
|
||||||
|
private const val DEVICE_CODE = "agent/device-code"
|
||||||
private const val LAB_CHAT_KEY = "lab_chat"
|
private const val LAB_CHAT_KEY = "lab_chat"
|
||||||
/** The raw output of the latest turn, for working out what a CLI did when the chat shows nothing. */
|
/** The raw output of the latest turn, for working out what a CLI did when the chat shows nothing. */
|
||||||
private const val TURN_LOG = "agent/turn.log"
|
private const val TURN_LOG = "agent/turn.log"
|
||||||
private const val RETRY_MS = 3_000L
|
private const val RETRY_MS = 3_000L
|
||||||
|
|
||||||
private fun modelKey(harness: AgentHarness) = "model_${harness.id}"
|
private fun modelKey(harness: AgentHarness) = "model_${harness.id}"
|
||||||
|
private fun limitsKey(harness: AgentHarness) = "limits_${harness.id}"
|
||||||
|
|
||||||
|
@VisibleForTesting
|
||||||
|
internal fun encodeLimits(list: List<Limit>) = org.json.JSONArray(list.map {
|
||||||
|
org.json.JSONObject().put("minutes", it.minutes).put("used", it.usedPercent).put("resets", it.resetsAt)
|
||||||
|
}).toString()
|
||||||
|
|
||||||
|
@VisibleForTesting
|
||||||
|
internal fun decodeLimits(text: String?): List<Limit> = runCatching {
|
||||||
|
val a = org.json.JSONArray(text ?: return emptyList())
|
||||||
|
(0 until a.length()).map { a.getJSONObject(it) }.map { Limit(it.optInt("minutes"), it.optInt("used"), it.optLong("resets")) }
|
||||||
|
}.getOrDefault(emptyList())
|
||||||
|
private fun effortKey(harness: AgentHarness) = "effort_${harness.id}"
|
||||||
|
|
||||||
internal fun prefs(context: Context) = context.getSharedPreferences("agent", Context.MODE_PRIVATE)
|
internal fun prefs(context: Context) = context.getSharedPreferences("agent", Context.MODE_PRIVATE)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A reply split into its text and the options of a trailing choices block. */
|
||||||
|
internal data class Choices(val text: String, val options: List<String>)
|
||||||
|
|
||||||
|
private val FENCE = Regex("""[ \t]{0,3}(`{3,}|~{3,})(.*)""")
|
||||||
|
|
||||||
|
/** Walks Markdown fences so a choices block counts only at the top level and only as the last thing in the reply. */
|
||||||
|
internal fun choices(reply: String): Choices {
|
||||||
|
val lines = reply.split('\n')
|
||||||
|
var open = ""
|
||||||
|
var opener = -1
|
||||||
|
var openChoices = false
|
||||||
|
var block: IntRange? = null
|
||||||
|
lines.forEachIndexed { i, line ->
|
||||||
|
val fence = FENCE.matchEntire(line)
|
||||||
|
if (open.isEmpty()) {
|
||||||
|
if (fence != null) {
|
||||||
|
open = fence.groupValues[1]
|
||||||
|
opener = i
|
||||||
|
openChoices = fence.groupValues[2].trim() == "choices"
|
||||||
|
block = null
|
||||||
|
} else if (line.isNotBlank()) block = null
|
||||||
|
} else if (fence != null && fence.groupValues[1][0] == open[0] && fence.groupValues[1].length >= open.length && fence.groupValues[2].isBlank()) {
|
||||||
|
block = if (openChoices) opener..i else null
|
||||||
|
open = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val found = block?.takeIf { open.isEmpty() } ?: return Choices(reply, emptyList())
|
||||||
|
val options = lines.subList(found.first + 1, found.last).map { it.trim().removePrefix("- ").removePrefix("* ").trim() }.filter { it.isNotEmpty() }
|
||||||
|
return Choices(lines.subList(0, found.first).joinToString("\n").trimEnd(), options)
|
||||||
|
}
|
||||||
@@ -77,6 +77,9 @@ class AgentHostService : Service() {
|
|||||||
private fun describe(context: Context): String {
|
private fun describe(context: Context): String {
|
||||||
val lab = AgentHost.lab?.takeIf { it.running }
|
val lab = AgentHost.lab?.takeIf { it.running }
|
||||||
if (lab != null) return context.getString(R.string.agent_lab_progress, lab.permille / 10, minutes(lab.etaSeconds.toLong().coerceAtLeast(0)))
|
if (lab != null) return context.getString(R.string.agent_lab_progress, lab.permille / 10, minutes(lab.etaSeconds.toLong().coerceAtLeast(0)))
|
||||||
|
AgentSetup.detail[AgentSetup.Step.GITHUB]?.takeIf {
|
||||||
|
AgentSetup.status[AgentSetup.Step.GITHUB] == AgentSetup.Status.WORKING && it.startsWith("GitHub device code:")
|
||||||
|
}?.let { return it }
|
||||||
if (AgentHost.state != AgentHost.State.WORKING) return context.getString(R.string.agent_setting_up)
|
if (AgentHost.state != AgentHost.State.WORKING) return context.getString(R.string.agent_setting_up)
|
||||||
val tool = AgentHost.running()
|
val tool = AgentHost.running()
|
||||||
val elapsed = minutes((SystemClock.elapsedRealtime() - AgentHost.turnStarted) / 1000)
|
val elapsed = minutes((SystemClock.elapsedRealtime() - AgentHost.turnStarted) / 1000)
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package com.droiddeck.launcher.agent
|
||||||
|
|
||||||
|
import android.app.ActivityManager
|
||||||
|
import android.app.Notification
|
||||||
|
import android.app.NotificationChannel
|
||||||
|
import android.app.NotificationManager
|
||||||
|
import android.app.PendingIntent
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import com.droiddeck.launcher.FrontEndActivity
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
|
import com.droiddeck.launcher.ui.AgentPet
|
||||||
|
|
||||||
|
/** Tells the user a turn has ended when nothing on screen already does. */
|
||||||
|
internal object AgentNotice {
|
||||||
|
private const val CHANNEL_ID = "agent_done"
|
||||||
|
private const val NOTIFICATION_ID = 4108
|
||||||
|
|
||||||
|
enum class Kind { DONE, FAILED, QUESTION }
|
||||||
|
|
||||||
|
fun post(context: Context, kind: Kind, text: String) {
|
||||||
|
if (onScreen(context)) return
|
||||||
|
val manager = context.getSystemService(NotificationManager::class.java) ?: return
|
||||||
|
manager.createNotificationChannel(NotificationChannel(CHANNEL_ID, context.getString(R.string.agent_done_channel), NotificationManager.IMPORTANCE_DEFAULT))
|
||||||
|
val open = PendingIntent.getActivity(context, 2,
|
||||||
|
Intent(context, FrontEndActivity::class.java)
|
||||||
|
.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
|
||||||
|
.putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, "agent"),
|
||||||
|
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||||
|
val title = context.getString(when (kind) {
|
||||||
|
Kind.DONE -> R.string.agent_done
|
||||||
|
Kind.FAILED -> R.string.agent_done_failed
|
||||||
|
Kind.QUESTION -> R.string.agent_done_question
|
||||||
|
})
|
||||||
|
runCatching {
|
||||||
|
manager.notify(NOTIFICATION_ID, Notification.Builder(context, CHANNEL_ID)
|
||||||
|
.setSmallIcon(R.drawable.ic_stat_session)
|
||||||
|
.setContentTitle(title)
|
||||||
|
.setContentText(text)
|
||||||
|
.setStyle(Notification.BigTextStyle().bigText(text))
|
||||||
|
.setContentIntent(open)
|
||||||
|
.setAutoCancel(true)
|
||||||
|
.setCategory(Notification.CATEGORY_STATUS)
|
||||||
|
.build())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clear(context: Context) {
|
||||||
|
context.getSystemService(NotificationManager::class.java)?.cancel(NOTIFICATION_ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The chat in a DroidDeck window in front, or the pet, which shows the reply in its own bubble. */
|
||||||
|
private fun onScreen(context: Context): Boolean {
|
||||||
|
if (AgentPet.floating) return true
|
||||||
|
val state = ActivityManager.RunningAppProcessInfo().also { ActivityManager.getMyMemoryState(it) }
|
||||||
|
return AgentPet.agentOnScreen > 0 && state.importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ import androidx.compose.runtime.mutableStateMapOf
|
|||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
|
import com.droiddeck.launcher.session.OrphanReaper
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.util.concurrent.TimeUnit
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
@@ -39,7 +40,8 @@ object AgentSetup {
|
|||||||
private val main = Handler(Looper.getMainLooper())
|
private val main = Handler(Looper.getMainLooper())
|
||||||
private const val REPO = "https://github.com/Droid-Deck/DroidDeck.git"
|
private const val REPO = "https://github.com/Droid-Deck/DroidDeck.git"
|
||||||
private const val CHECKOUT = "/root/DroidDeck"
|
private const val CHECKOUT = "/root/DroidDeck"
|
||||||
private val HELPERS = listOf("android-open", "dd-gh-login")
|
private val HELPERS = listOf("android-open", "dd-gh-login", "droiddeckctl")
|
||||||
|
internal const val CTL = "/root/.local/share/droiddeck/ctl"
|
||||||
private const val PROBE_TIMEOUT_S = 60L
|
private const val PROBE_TIMEOUT_S = 60L
|
||||||
|
|
||||||
fun check(context: Context) {
|
fun check(context: Context) {
|
||||||
@@ -71,6 +73,8 @@ object AgentSetup {
|
|||||||
Thread({ for ((step, command) in probes) probe(app, harness, step, command) }, "agent-checks").start()
|
Thread({ for ((step, command) in probes) probe(app, harness, step, command) }, "agent-checks").start()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun runsAsRoot(step: Step) = step == Step.INSTALL
|
||||||
|
|
||||||
/** Runs [step]'s action. [CONNECTION] is the app's own pairing flow, so the caller opens it. */
|
/** Runs [step]'s action. [CONNECTION] is the app's own pairing flow, so the caller opens it. */
|
||||||
fun run(context: Context, step: Step) {
|
fun run(context: Context, step: Step) {
|
||||||
val app = context.applicationContext
|
val app = context.applicationContext
|
||||||
@@ -79,7 +83,8 @@ object AgentSetup {
|
|||||||
Step.CONNECTION -> return
|
Step.CONNECTION -> return
|
||||||
Step.INSTALL -> {
|
Step.INSTALL -> {
|
||||||
listOf("sh", "-c", "set -e; export DEBIAN_FRONTEND=noninteractive; " +
|
listOf("sh", "-c", "set -e; export DEBIAN_FRONTEND=noninteractive; " +
|
||||||
"apt-get update; apt-get install -y --no-install-recommends git gh adb curl ca-certificates python3; ${harness.install}")
|
"dpkg --configure -a; apt-get update || echo 'Some package sources could not be refreshed; continuing'; apt-get -f install -y; " +
|
||||||
|
"apt-get install -y --no-install-recommends git gh adb curl ca-certificates python3; ${harness.install}")
|
||||||
}
|
}
|
||||||
Step.SIGN_IN -> harness.signIn
|
Step.SIGN_IN -> harness.signIn
|
||||||
Step.GITHUB -> listOf("dd-gh-login")
|
Step.GITHUB -> listOf("dd-gh-login")
|
||||||
@@ -94,13 +99,25 @@ object AgentSetup {
|
|||||||
val result = runCatching {
|
val result = runCatching {
|
||||||
installHelpers(app)
|
installHelpers(app)
|
||||||
runCatching { harness.prepare(LinuxRuntime.rootDir(app)) }
|
runCatching { harness.prepare(LinuxRuntime.rootDir(app)) }
|
||||||
val child = AgentHost.guest(app, command).start()
|
val child = AgentHost.guest(app, command, fakeRoot = runsAsRoot(step)).start()
|
||||||
child.outputStream.close()
|
val pid = AgentProcesses.pidOf(child)
|
||||||
child.inputStream.bufferedReader().forEachLine { line ->
|
OrphanReaper.keep(pid)
|
||||||
val text = line.trim()
|
try {
|
||||||
if (text.isNotEmpty() && !noise(text)) main.post { detail[step] = text.take(160) }
|
child.outputStream.close()
|
||||||
|
logFile(app, step).apply { parentFile?.mkdirs() }.bufferedWriter().use { log ->
|
||||||
|
child.inputStream.bufferedReader().forEachLine { line ->
|
||||||
|
log.appendLine(line)
|
||||||
|
val text = line.trim()
|
||||||
|
if (text.isNotEmpty() && !noise(text)) main.post {
|
||||||
|
detail[step] = text.take(160)
|
||||||
|
if (step == Step.GITHUB && text.startsWith("GitHub device code:")) AgentHostService.update(app)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
child.waitFor().also { log.appendLine("exit $it") }
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
OrphanReaper.release(pid)
|
||||||
}
|
}
|
||||||
child.waitFor()
|
|
||||||
}
|
}
|
||||||
main.post {
|
main.post {
|
||||||
AgentHostService.setupEnded(app)
|
AgentHostService.setupEnded(app)
|
||||||
@@ -116,6 +133,9 @@ object AgentSetup {
|
|||||||
}, "agent-setup-${step.name.lowercase()}").start()
|
}, "agent-setup-${step.name.lowercase()}").start()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The whole output of a step's last run; the card shows only its last line. */
|
||||||
|
fun logFile(app: Context, step: Step) = File(app.filesDir, "agent/setup-${step.name.lowercase()}.log")
|
||||||
|
|
||||||
fun buildToolsInstalled(app: Context) = AgentHost.guestFileExists(app, "/root/aapt2/aapt2") && AgentHost.guestFileExists(app, "$CHECKOUT/.git")
|
fun buildToolsInstalled(app: Context) = AgentHost.guestFileExists(app, "/root/aapt2/aapt2") && AgentHost.guestFileExists(app, "$CHECKOUT/.git")
|
||||||
|
|
||||||
/** dd-lab-build compiled this install's commit, so a Lab build compiles only what changed. */
|
/** dd-lab-build compiled this install's commit, so a Lab build compiles only what changed. */
|
||||||
@@ -165,12 +185,24 @@ object AgentSetup {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Written before every step, so the helpers a step relies on are there and match this DroidDeck version. */
|
/** Written before every step, so the helpers a step relies on are there and match this DroidDeck version. */
|
||||||
private fun installHelpers(app: Context) {
|
internal fun installHelpers(app: Context) {
|
||||||
val bin = File(LinuxRuntime.rootDir(app), "root/.local/bin").apply { mkdirs() }
|
val root = LinuxRuntime.rootDir(app)
|
||||||
for (name in HELPERS) {
|
val bin = File(root, "root/.local/bin").apply { mkdirs() }
|
||||||
val target = File(bin, name)
|
for (name in HELPERS) copyAsset(app, "agent/$name", File(bin, name))
|
||||||
app.assets.open("agent/$name").use { input -> target.outputStream().use { input.copyTo(it) } }
|
val ctl = File(root, CTL.removePrefix("/")).apply { mkdirs() }
|
||||||
target.setExecutable(true, false)
|
for (name in app.assets.list("agent/ctl").orEmpty()) copyAsset(app, "agent/ctl/$name", File(ctl, name))
|
||||||
}
|
unpinAdbSerial(File(root, "root/.bashrc"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Older tools/agent/setup pinned the adb port in .bashrc, which overrides the live port DroidDeck passes. */
|
||||||
|
internal fun unpinAdbSerial(bashrc: File) {
|
||||||
|
val text = runCatching { bashrc.readText() }.getOrNull() ?: return
|
||||||
|
val fixed = text.replace("ADB_SERIAL=127.0.0.1:5555 ", "ADB_SERIAL=\"\${ADB_SERIAL:-127.0.0.1:5555}\" ")
|
||||||
|
if (fixed != text) runCatching { bashrc.writeText(fixed) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun copyAsset(app: Context, asset: String, target: File) {
|
||||||
|
app.assets.open(asset).use { input -> target.outputStream().use { input.copyTo(it) } }
|
||||||
|
target.setExecutable(true, false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package com.droiddeck.launcher.agent
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import com.droiddeck.launcher.session.SessionPrefs
|
||||||
|
|
||||||
|
object AgentTab {
|
||||||
|
var shown by mutableStateOf(true)
|
||||||
|
private set
|
||||||
|
|
||||||
|
val visible: Boolean get() = shown && AgentHost.available
|
||||||
|
|
||||||
|
fun load(context: Context) {
|
||||||
|
shown = SessionPrefs.agentTab(context)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun set(context: Context, show: Boolean) {
|
||||||
|
shown = show
|
||||||
|
SessionPrefs.setAgentTab(context, show)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
package com.droiddeck.launcher.agent
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
|
import java.io.File
|
||||||
|
import java.nio.file.FileVisitResult
|
||||||
|
import java.nio.file.Files
|
||||||
|
import java.nio.file.LinkOption
|
||||||
|
import java.nio.file.Path
|
||||||
|
import java.nio.file.SimpleFileVisitor
|
||||||
|
import java.nio.file.attribute.BasicFileAttributes
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
/** Claude Code's MCP servers and skills in the userland, through its own CLI and skills folder. */
|
||||||
|
internal object AgentTools {
|
||||||
|
data class Server(val name: String, val target: String, val status: String) {
|
||||||
|
/** Connectors come from the claude.ai account and are managed there, not by the CLI. */
|
||||||
|
val account get() = name.startsWith("claude.ai ")
|
||||||
|
}
|
||||||
|
|
||||||
|
data class Skill(val name: String, val description: String)
|
||||||
|
|
||||||
|
class Result(val ok: Boolean, val output: String)
|
||||||
|
|
||||||
|
private const val SKILLS = "root/.claude/skills"
|
||||||
|
private val SERVER = Regex("""^(.+?): (.+) - (.+)$""")
|
||||||
|
|
||||||
|
fun servers(context: Context): List<Server>? {
|
||||||
|
val result = run(context, listOf(ClaudeCode.binary, "mcp", "list"))
|
||||||
|
if (!result.ok) return null
|
||||||
|
return parseServers(result.output)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun parseServers(output: String): List<Server> = output.lines().mapNotNull { line ->
|
||||||
|
SERVER.find(line.trim())?.destructured?.let { (name, target, status) -> Server(name, target, status) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A URL is added as an HTTP server; anything else is the command that starts a stdio server. */
|
||||||
|
internal fun addCommand(name: String, target: String): List<String> {
|
||||||
|
val t = target.trim()
|
||||||
|
val base = listOf(ClaudeCode.binary, "mcp", "add", "--scope", "user")
|
||||||
|
return if (t.startsWith("http://") || t.startsWith("https://")) base + listOf("--transport", "http", name.trim(), t)
|
||||||
|
else base + listOf(name.trim(), "--") + words(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Splits a command line the way a shell would for quotes and backslashes, without expanding anything. */
|
||||||
|
internal fun words(line: String): List<String> {
|
||||||
|
val words = mutableListOf<String>()
|
||||||
|
val word = StringBuilder()
|
||||||
|
var inWord = false
|
||||||
|
var quote: Char? = null
|
||||||
|
var i = 0
|
||||||
|
while (i < line.length) {
|
||||||
|
val c = line[i]
|
||||||
|
when {
|
||||||
|
quote == '\'' -> if (c == '\'') quote = null else word.append(c)
|
||||||
|
c == '\\' && i + 1 < line.length && (quote == null || line[i + 1] == '"' || line[i + 1] == '\\') -> {
|
||||||
|
word.append(line[++i])
|
||||||
|
inWord = true
|
||||||
|
}
|
||||||
|
quote == '"' -> if (c == '"') quote = null else word.append(c)
|
||||||
|
c == '\'' || c == '"' -> {
|
||||||
|
quote = c
|
||||||
|
inWord = true
|
||||||
|
}
|
||||||
|
c.isWhitespace() -> if (inWord) {
|
||||||
|
words += word.toString()
|
||||||
|
word.clear()
|
||||||
|
inWord = false
|
||||||
|
}
|
||||||
|
else -> {
|
||||||
|
word.append(c)
|
||||||
|
inWord = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
if (inWord) words += word.toString()
|
||||||
|
return words
|
||||||
|
}
|
||||||
|
|
||||||
|
fun add(context: Context, name: String, target: String) = run(context, addCommand(name, target))
|
||||||
|
|
||||||
|
fun remove(context: Context, name: String) = run(context, listOf(ClaudeCode.binary, "mcp", "remove", name))
|
||||||
|
|
||||||
|
fun skills(context: Context): List<Skill> =
|
||||||
|
File(LinuxRuntime.rootDir(context), SKILLS).listFiles { f -> f.isDirectory }.orEmpty().sortedBy { it.name.lowercase() }.map { dir ->
|
||||||
|
Skill(dir.name, description(File(dir, "SKILL.md")))
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun description(file: File): String = runCatching {
|
||||||
|
val lines = file.readLines()
|
||||||
|
if (lines.firstOrNull()?.trim() != "---") return@runCatching ""
|
||||||
|
lines.drop(1).takeWhile { it.trim() != "---" }.firstOrNull { it.startsWith("description:") }
|
||||||
|
?.removePrefix("description:")?.trim()?.trim('"', '\'').orEmpty()
|
||||||
|
}.getOrDefault("")
|
||||||
|
|
||||||
|
fun deleteSkill(context: Context, name: String): Boolean {
|
||||||
|
if (name.isEmpty() || name.contains('/') || name.startsWith(".")) return false
|
||||||
|
val root = File(LinuxRuntime.rootDir(context), SKILLS)
|
||||||
|
val dir = File(root, name)
|
||||||
|
if (dir.parentFile?.path != root.path) return false
|
||||||
|
return deleteTree(dir.toPath())
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Deletes [path] and what is under it; a symbolic link is removed itself, never what it points to. */
|
||||||
|
internal fun deleteTree(path: Path): Boolean = runCatching {
|
||||||
|
if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) return@runCatching true
|
||||||
|
Files.walkFileTree(path, object : SimpleFileVisitor<Path>() {
|
||||||
|
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
|
||||||
|
Files.delete(file)
|
||||||
|
return FileVisitResult.CONTINUE
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun postVisitDirectory(dir: Path, exc: java.io.IOException?): FileVisitResult {
|
||||||
|
if (exc != null) throw exc
|
||||||
|
Files.delete(dir)
|
||||||
|
return FileVisitResult.CONTINUE
|
||||||
|
}
|
||||||
|
})
|
||||||
|
true
|
||||||
|
}.getOrDefault(false)
|
||||||
|
|
||||||
|
private fun run(context: Context, command: List<String>): Result {
|
||||||
|
val child = runCatching { AgentHost.guest(context.applicationContext, command, connectAdb = false).start() }
|
||||||
|
.getOrElse { return Result(false, it.message.orEmpty()) }
|
||||||
|
val output = StringBuffer()
|
||||||
|
// The CLI can hold its output open past the deadline, so it is read beside the wait rather than before it.
|
||||||
|
val reader = Thread({ runCatching { child.inputStream.bufferedReader().forEachLine { output.append(it).append('\n') } } }, "agent-tools").apply { start() }
|
||||||
|
return try {
|
||||||
|
val ended = child.waitFor(90, TimeUnit.SECONDS)
|
||||||
|
if (!ended) child.destroyForcibly()
|
||||||
|
reader.join(2_000)
|
||||||
|
Result(ended && child.exitValue() == 0, output.toString().trim())
|
||||||
|
} catch (e: InterruptedException) {
|
||||||
|
child.destroyForcibly()
|
||||||
|
Thread.currentThread().interrupt()
|
||||||
|
Result(false, output.toString().trim())
|
||||||
|
} finally {
|
||||||
|
runCatching { child.inputStream.close() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -16,6 +16,8 @@ import java.nio.file.Files;
|
|||||||
import java.nio.file.StandardCopyOption;
|
import java.nio.file.StandardCopyOption;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.function.IntConsumer;
|
||||||
|
import java.util.function.IntSupplier;
|
||||||
|
|
||||||
public class PulseAudioComponent extends SessionPart {
|
public class PulseAudioComponent extends SessionPart {
|
||||||
private static final String TAG = "PulseAudio";
|
private static final String TAG = "PulseAudio";
|
||||||
@@ -29,7 +31,55 @@ public class PulseAudioComponent extends SessionPart {
|
|||||||
private final File deviceControls;
|
private final File deviceControls;
|
||||||
private File logFile;
|
private File logFile;
|
||||||
private final String micFifoPath;
|
private final String micFifoPath;
|
||||||
private volatile int pid = -1;
|
private final HostLifecycle host = new HostLifecycle(Process::killProcess);
|
||||||
|
|
||||||
|
static final class HostLifecycle {
|
||||||
|
volatile int pid = -1;
|
||||||
|
private long generation;
|
||||||
|
private long launches;
|
||||||
|
private final IntConsumer terminate;
|
||||||
|
|
||||||
|
HostLifecycle(IntConsumer terminate) {
|
||||||
|
this.terminate = terminate;
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized long begin() {
|
||||||
|
stop();
|
||||||
|
return generation;
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized void stop() {
|
||||||
|
generation++;
|
||||||
|
if (pid > 1) terminate.accept(pid);
|
||||||
|
pid = -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized boolean launch(long expected, IntSupplier launch) {
|
||||||
|
if (expected != generation) return false;
|
||||||
|
launches++;
|
||||||
|
pid = launch.getAsInt();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized boolean current(long expected) {
|
||||||
|
return expected == generation;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The latest launch; a sink guard holds it so it never reconfigures a host started after its own. */
|
||||||
|
synchronized long token() {
|
||||||
|
return launches;
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized boolean live(long token) {
|
||||||
|
return token == launches && pid > 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized boolean exited(long expected) {
|
||||||
|
if (expected != generation || pid <= 1) return false;
|
||||||
|
pid = -1;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public PulseAudioComponent(Context context) {
|
public PulseAudioComponent(Context context) {
|
||||||
this(context, null);
|
this(context, null);
|
||||||
@@ -64,7 +114,12 @@ public class PulseAudioComponent extends SessionPart {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void start() {
|
public void start() {
|
||||||
stop();
|
start(host.begin());
|
||||||
|
}
|
||||||
|
|
||||||
|
private synchronized void start(long generation) {
|
||||||
|
// An exit callback's restart can be overtaken by a newer start; it must not touch the newer host's socket.
|
||||||
|
if (!host.current(generation)) return;
|
||||||
if (!workingDir.isDirectory()) {
|
if (!workingDir.isDirectory()) {
|
||||||
workingDir.mkdirs();
|
workingDir.mkdirs();
|
||||||
FileUtils.chmod(workingDir, 0771);
|
FileUtils.chmod(workingDir, 0771);
|
||||||
@@ -118,17 +173,23 @@ public class PulseAudioComponent extends SessionPart {
|
|||||||
+ " -n --file=default.pa --daemonize=false --use-pid-file=false --exit-idle-time=-1"
|
+ " -n --file=default.pa --daemonize=false --use-pid-file=false --exit-idle-time=-1"
|
||||||
+ " --log-level=info";
|
+ " --log-level=info";
|
||||||
final java.io.PrintWriter out = openLog();
|
final java.io.PrintWriter out = openLog();
|
||||||
pid = HostProcess.start(command, env.toArray(new String[0]), workingDir, null,
|
if (!host.launch(generation, () -> HostProcess.start(command, env.toArray(new String[0]), workingDir, status -> {
|
||||||
|
if (host.exited(generation)) {
|
||||||
|
Log.w(TAG, "audio host exited with status " + status + "; restarting");
|
||||||
|
start(generation);
|
||||||
|
}
|
||||||
|
},
|
||||||
line -> {
|
line -> {
|
||||||
Log.i(TAG, line);
|
Log.i(TAG, line);
|
||||||
if (out != null) synchronized (out) { out.println(line); out.flush(); }
|
if (out != null) synchronized (out) { out.println(line); out.flush(); }
|
||||||
});
|
}))) return;
|
||||||
Thread guard = new Thread(() -> ensureClientSink(out), "pulse-sink-guard");
|
long token = host.token();
|
||||||
|
Thread guard = new Thread(() -> ensureClientSink(out, token), "pulse-sink-guard");
|
||||||
guard.setDaemon(true);
|
guard.setDaemon(true);
|
||||||
guard.start();
|
guard.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ensureClientSink(java.io.PrintWriter out) {
|
private void ensureClientSink(java.io.PrintWriter out, long token) {
|
||||||
try {
|
try {
|
||||||
// Nothing that may block (a sink whose AAudio open hangs: a Galaxy S24 FE (US) hung the
|
// Nothing that may block (a sink whose AAudio open hangs: a Galaxy S24 FE (US) hung the
|
||||||
// daemon's start-up loading one from default.pa) is loaded by the daemon itself; the
|
// daemon's start-up loading one from default.pa) is loaded by the daemon itself; the
|
||||||
@@ -137,14 +198,14 @@ public class PulseAudioComponent extends SessionPart {
|
|||||||
long deadline = started + 30000L;
|
long deadline = started + 30000L;
|
||||||
String sinks = null;
|
String sinks = null;
|
||||||
boolean socketSeen = false;
|
boolean socketSeen = false;
|
||||||
while (System.currentTimeMillis() < deadline && pid > 1) {
|
while (System.currentTimeMillis() < deadline && host.live(token)) {
|
||||||
socketSeen |= socket().exists();
|
socketSeen |= socket().exists();
|
||||||
if (socketSeen && (sinks = pactl("list", "short", "sinks")) != null) break;
|
if (socketSeen && (sinks = pactlFor(token, "list", "short", "sinks")) != null) break;
|
||||||
try { Thread.sleep(250L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
|
try { Thread.sleep(250L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
|
||||||
}
|
}
|
||||||
note(out, "client sink: daemon " + (sinks != null ? "answered" : "did not answer") + " after "
|
note(out, "client sink: daemon " + (sinks != null ? "answered" : "did not answer") + " after "
|
||||||
+ (System.currentTimeMillis() - started) + " ms (socket " + (socketSeen ? "present" : "never appeared") + ", pactl "
|
+ (System.currentTimeMillis() - started) + " ms (socket " + (socketSeen ? "present" : "never appeared") + ", pactl "
|
||||||
+ (new File(workingDir, "pactl").isFile() ? "present" : "MISSING") + ", daemon pid " + pid + ")");
|
+ (new File(workingDir, "pactl").isFile() ? "present" : "MISSING") + ", daemon pid " + host.pid + ")");
|
||||||
String line;
|
String line;
|
||||||
if (sinks == null) {
|
if (sinks == null) {
|
||||||
line = "== client sink: the daemon did not answer in 30 s; no fallback attempted";
|
line = "== client sink: the daemon did not answer in 30 s; no fallback attempted";
|
||||||
@@ -155,15 +216,15 @@ public class PulseAudioComponent extends SessionPart {
|
|||||||
// still switching the output route as the session starts (seen on a Galaxy S24 FE):
|
// still switching the output route as the session starts (seen on a Galaxy S24 FE):
|
||||||
// try DirectAudio again, then the plain sink, a few times over ten seconds.
|
// try DirectAudio again, then the plain sink, a few times over ten seconds.
|
||||||
String loadedAs = null;
|
String loadedAs = null;
|
||||||
for (int attempt = 1; attempt <= 5 && loadedAs == null && pid > 1; attempt++) {
|
for (int attempt = 1; attempt <= 5 && loadedAs == null && host.live(token); attempt++) {
|
||||||
try { Thread.sleep(2000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
|
try { Thread.sleep(2000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
|
||||||
if (pactl("load-module", "module-directaudio-native-sink", "sink_name=DirectAudio", "performance_mode=1",
|
if (pactlFor(token, "load-module", "module-directaudio-native-sink", "sink_name=DirectAudio", "performance_mode=1",
|
||||||
"adaptive=1", "decay=0", "limiter=1", "watchdog=1", "volume=1.0", "control_dir=" + deviceControls) != null
|
"adaptive=1", "decay=0", "limiter=1", "watchdog=1", "volume=1.0", "control_dir=" + deviceControls) != null
|
||||||
&& pactl("set-default-sink", "DirectAudio") != null) {
|
&& pactlFor(token, "set-default-sink", "DirectAudio") != null) {
|
||||||
loadedAs = "DirectAudio on attempt " + attempt;
|
loadedAs = "DirectAudio on attempt " + attempt;
|
||||||
} else if (pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink",
|
} else if (pactlFor(token, "load-module", "module-aaudio-sink", "sink_name=AAudioSink",
|
||||||
"performance_mode=" + (attempt == 1 ? "1" : "0"), "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) != null
|
"performance_mode=" + (attempt == 1 ? "1" : "0"), "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) != null
|
||||||
&& pactl("set-default-sink", "AAudioSink") != null) {
|
&& pactlFor(token, "set-default-sink", "AAudioSink") != null) {
|
||||||
loadedAs = "the plain AAudio sink (AAudioSink) on attempt " + attempt;
|
loadedAs = "the plain AAudio sink (AAudioSink) on attempt " + attempt;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -186,10 +247,14 @@ public class PulseAudioComponent extends SessionPart {
|
|||||||
if (out != null) synchronized (out) { out.println(line); out.flush(); }
|
if (out != null) synchronized (out) { out.println(line); out.flush(); }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private String pactlFor(long token, String... args) {
|
||||||
|
return host.live(token) ? pactl(args) : null;
|
||||||
|
}
|
||||||
|
|
||||||
/** Runs pactl against this daemon; its stdout, or null when it failed or timed out. */
|
/** Runs pactl against this daemon; its stdout, or null when it failed or timed out. */
|
||||||
private String pactl(String... args) {
|
private String pactl(String... args) {
|
||||||
File pactl = new File(workingDir, "pactl");
|
File pactl = new File(workingDir, "pactl");
|
||||||
if (!pactl.isFile() || pid <= 1) return null;
|
if (!pactl.isFile() || host.pid <= 1) return null;
|
||||||
java.lang.Process process = null;
|
java.lang.Process process = null;
|
||||||
try {
|
try {
|
||||||
File modules = new File(workingDir, "modules/arm64");
|
File modules = new File(workingDir, "modules/arm64");
|
||||||
@@ -231,10 +296,7 @@ public class PulseAudioComponent extends SessionPart {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void stop() {
|
public void stop() {
|
||||||
if (pid != -1) {
|
host.stop();
|
||||||
Process.killProcess(pid);
|
|
||||||
pid = -1;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean setSinkSuspended(boolean suspended) {
|
public boolean setSinkSuspended(boolean suspended) {
|
||||||
@@ -247,7 +309,7 @@ public class PulseAudioComponent extends SessionPart {
|
|||||||
|
|
||||||
private boolean suspend(String kind, String name, boolean suspended) {
|
private boolean suspend(String kind, String name, boolean suspended) {
|
||||||
File pactl = new File(workingDir, "pactl");
|
File pactl = new File(workingDir, "pactl");
|
||||||
if (!pactl.isFile() || pid <= 1) {
|
if (!pactl.isFile() || host.pid <= 1) {
|
||||||
Log.w(TAG, "cannot change " + kind + " state: PulseAudio control client or server unavailable");
|
Log.w(TAG, "cannot change " + kind + " state: PulseAudio control client or server unavailable");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.core
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import com.droiddeck.launcher.BuildConfig
|
import com.droiddeck.launcher.BuildConfig
|
||||||
|
import com.droiddeck.launcher.lab.LabOverlay
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.SupervisorJob
|
import kotlinx.coroutines.SupervisorJob
|
||||||
@@ -16,6 +17,7 @@ import java.io.FileInputStream
|
|||||||
internal class AddonPack(
|
internal class AddonPack(
|
||||||
val name: String, private val sha256: String, val size: Long, private val required: List<String>,
|
val name: String, private val sha256: String, val size: Long, private val required: List<String>,
|
||||||
private val reuseDeviceCopy: Boolean = sha256.isEmpty() && !BuildConfig.CI_BUILD,
|
private val reuseDeviceCopy: Boolean = sha256.isEmpty() && !BuildConfig.CI_BUILD,
|
||||||
|
private val labBuild: Boolean = LabOverlay.active != null,
|
||||||
private val bundle: (Context) -> java.io.InputStream = { it.assets.open("packs/$name.tar.zst") },
|
private val bundle: (Context) -> java.io.InputStream = { it.assets.open("packs/$name.tar.zst") },
|
||||||
) {
|
) {
|
||||||
sealed interface State {
|
sealed interface State {
|
||||||
@@ -29,6 +31,9 @@ internal class AddonPack(
|
|||||||
val state: StateFlow<State> = mutableState.asStateFlow()
|
val state: StateFlow<State> = mutableState.asStateFlow()
|
||||||
private val lock = Any()
|
private val lock = Any()
|
||||||
|
|
||||||
|
@Volatile var failure: String? = null
|
||||||
|
private set
|
||||||
|
|
||||||
val available: Boolean get() = sha256.isNotEmpty()
|
val available: Boolean get() = sha256.isNotEmpty()
|
||||||
private val tag get() = "pack-$name-${sha256.take(16)}"
|
private val tag get() = "pack-$name-${sha256.take(16)}"
|
||||||
private val urls get() = listOfNotNull(
|
private val urls get() = listOfNotNull(
|
||||||
@@ -42,7 +47,8 @@ internal class AddonPack(
|
|||||||
|
|
||||||
fun installed(context: Context): Boolean = version(context).isNotEmpty() && File(dir(context), COMPLETE).isFile
|
fun installed(context: Context): Boolean = version(context).isNotEmpty() && File(dir(context), COMPLETE).isFile
|
||||||
|
|
||||||
private fun version(context: Context): String = if (!reuseDeviceCopy) sha256 else deviceCopy(context).orEmpty()
|
private fun version(context: Context): String =
|
||||||
|
if (reuseDeviceCopy || labBuild) deviceCopy(context) ?: sha256 else sha256
|
||||||
|
|
||||||
private fun deviceCopy(context: Context): String? = root(context).listFiles().orEmpty()
|
private fun deviceCopy(context: Context): String? = root(context).listFiles().orEmpty()
|
||||||
.filter { dir ->
|
.filter { dir ->
|
||||||
@@ -64,9 +70,13 @@ internal class AddonPack(
|
|||||||
if (installed(app)) { mutableState.value = State.Ready; return }
|
if (installed(app)) { mutableState.value = State.Ready; return }
|
||||||
if (mutableState.value is State.Downloading) return
|
if (mutableState.value is State.Downloading) return
|
||||||
mutableState.value = State.Downloading(0f)
|
mutableState.value = State.Downloading(0f)
|
||||||
|
failure = null
|
||||||
}
|
}
|
||||||
scope.launch {
|
scope.launch {
|
||||||
val ok = runCatching { install(app) }.onFailure { Log.w(TAG, "$name: install failed", it) }.getOrDefault(false)
|
val ok = runCatching { install(app) }.onFailure {
|
||||||
|
Log.w(TAG, "$name: install failed", it)
|
||||||
|
failure = it.toString()
|
||||||
|
}.getOrDefault(false)
|
||||||
mutableState.value = if (ok) State.Ready else State.Failed
|
mutableState.value = if (ok) State.Ready else State.Failed
|
||||||
if (ok) onReady(app)
|
if (ok) onReady(app)
|
||||||
}
|
}
|
||||||
@@ -90,20 +100,28 @@ internal class AddonPack(
|
|||||||
|
|
||||||
private fun install(context: Context): Boolean {
|
private fun install(context: Context): Boolean {
|
||||||
if (!available) {
|
if (!available) {
|
||||||
Log.w(TAG, if (reuseDeviceCopy) "$name: this build has no pack and none is installed" else "$name: this build has no pack")
|
failure = if (reuseDeviceCopy) "this build has no pack and none is installed" else "this build has no pack"
|
||||||
|
Log.w(TAG, "$name: $failure")
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
val root = root(context).apply { mkdirs() }
|
val root = root(context).apply { mkdirs() }
|
||||||
val archive = File(root, "$sha256.tar.zst")
|
val archive = File(root, "$sha256.tar.zst")
|
||||||
|
val problems = mutableListOf<String>()
|
||||||
val downloaded = bundled(context, archive) || urls.any { url ->
|
val downloaded = bundled(context, archive) || urls.any { url ->
|
||||||
Downloader.downloadFile(url, archive, true, sha256) { p -> mutableState.value = State.Downloading(p.coerceIn(0f, 1f)) }
|
Downloader.downloadFile(url, archive, true, sha256) { p -> mutableState.value = State.Downloading(p.coerceIn(0f, 1f)) }
|
||||||
.also { if (!it) archive.delete() }
|
.also { if (!it) { archive.delete(); Downloader.lastFailure()?.let(problems::add) } }
|
||||||
|
}
|
||||||
|
if (!downloaded) {
|
||||||
|
failure = problems.joinToString("; ").ifEmpty { "download failed" }
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
if (!downloaded) return false
|
|
||||||
val staging = File(root, "$sha256.partial")
|
val staging = File(root, "$sha256.partial")
|
||||||
staging.deleteRecursively()
|
staging.deleteRecursively()
|
||||||
try {
|
try {
|
||||||
if (!FileInputStream(archive).use { TarZst.extract(it, staging) }) return false
|
if (!FileInputStream(archive).use { TarZst.extract(it, staging) }) {
|
||||||
|
failure = "could not unpack the pack"
|
||||||
|
return false
|
||||||
|
}
|
||||||
check(required.all { File(staging, it).isFile }) { "$name pack is incomplete" }
|
check(required.all { File(staging, it).isFile }) { "$name pack is incomplete" }
|
||||||
File(staging, COMPLETE).writeText(sha256)
|
File(staging, COMPLETE).writeText(sha256)
|
||||||
val target = dir(context)
|
val target = dir(context)
|
||||||
|
|||||||
@@ -27,6 +27,32 @@ object AppUiPrefs {
|
|||||||
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putInt("orientation", value).apply()
|
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putInt("orientation", value).apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const val HOME_PAGE_STEAM = "steam"
|
||||||
|
const val HOME_PAGE_APPS = "android-apps"
|
||||||
|
|
||||||
|
val homePageOptions = listOf(
|
||||||
|
HOME_PAGE_STEAM to R.string.rail_steam,
|
||||||
|
HOME_PAGE_APPS to R.string.content_android_apps,
|
||||||
|
)
|
||||||
|
|
||||||
|
fun homePage(context: Context): String =
|
||||||
|
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE)
|
||||||
|
.getString("home-page", null)
|
||||||
|
.takeIf { value -> homePageOptions.any { it.first == value } }
|
||||||
|
?: HOME_PAGE_STEAM
|
||||||
|
|
||||||
|
fun setHomePage(context: Context, value: String) {
|
||||||
|
require(homePageOptions.any { it.first == value })
|
||||||
|
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putString("home-page", value).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun hideHomeFromRecents(context: Context): Boolean =
|
||||||
|
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).getBoolean("hide-home-from-recents", false)
|
||||||
|
|
||||||
|
fun setHideHomeFromRecents(context: Context, hidden: Boolean) {
|
||||||
|
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putBoolean("hide-home-from-recents", hidden).apply()
|
||||||
|
}
|
||||||
|
|
||||||
internal fun normalizeScale(percent: Int): Int = percent.takeIf { it in scales } ?: DEFAULT_SCALE
|
internal fun normalizeScale(percent: Int): Int = percent.takeIf { it in scales } ?: DEFAULT_SCALE
|
||||||
|
|
||||||
fun scale(context: Context): Int = normalizeScale(
|
fun scale(context: Context): Int = normalizeScale(
|
||||||
|
|||||||
@@ -233,6 +233,10 @@ object DeviceReport {
|
|||||||
else "${turnip.displayName(displayId)} ${turnip.driverVersion(displayId)}".trim()
|
else "${turnip.displayName(displayId)} ${turnip.driverVersion(displayId)}".trim()
|
||||||
k("Display driver (chosen)", if (androidChoice.isEmpty()) "Auto -> $displayLabel" else androidChoice)
|
k("Display driver (chosen)", if (androidChoice.isEmpty()) "Auto -> $displayLabel" else androidChoice)
|
||||||
k(" name / version", displayLabel)
|
k(" name / version", displayLabel)
|
||||||
|
turnip.effectiveId().takeIf { it != displayId }?.let { used ->
|
||||||
|
k(" in use", if (used == "system") DeviceInfo.builtinDriverLabel(SystemVulkanDriver.isPowerVr(), runtime = false)
|
||||||
|
else "${turnip.displayName(used)} ${turnip.driverVersion(used)}".trim())
|
||||||
|
}
|
||||||
k(" imported available", turnip.enumerateImported().ifEmpty { listOf("none") }.joinToString(", "))
|
k(" imported available", turnip.enumerateImported().ifEmpty { listOf("none") }.joinToString(", "))
|
||||||
val lm = LinuxVulkanDriverManager(context)
|
val lm = LinuxVulkanDriverManager(context)
|
||||||
run {
|
run {
|
||||||
@@ -242,7 +246,9 @@ object DeviceReport {
|
|||||||
lm.getMinGlibc(id).let { if (it.isEmpty()) "" else " (glibc $it+)" } +
|
lm.getMinGlibc(id).let { if (it.isEmpty()) "" else " (glibc $it+)" } +
|
||||||
if (lm.isInstalled(id)) "" else if (SystemVulkanDriver.isPowerVr()) " [MISSING - select an installed driver or Auto]"
|
if (lm.isInstalled(id)) "" else if (SystemVulkanDriver.isPowerVr()) " [MISSING - select an installed driver or Auto]"
|
||||||
else " [MISSING - falls back to the runtime's own]"
|
else " [MISSING - falls back to the runtime's own]"
|
||||||
k("Linux driver", label)
|
val route = DeviceInfo.hostRoute(context)
|
||||||
|
k("Linux driver", route ?: label)
|
||||||
|
if (route != null) k(" chosen, not used", label)
|
||||||
}
|
}
|
||||||
k("Runtime's own ICD", LinuxRuntime.vulkanIcd(context)?.path)
|
k("Runtime's own ICD", LinuxRuntime.vulkanIcd(context)?.path)
|
||||||
k("Mali (Venus)", if (com.droiddeck.launcher.session.VenusComponent.wanted(context)) "in use"
|
k("Mali (Venus)", if (com.droiddeck.launcher.session.VenusComponent.wanted(context)) "in use"
|
||||||
@@ -274,6 +280,7 @@ object DeviceReport {
|
|||||||
EsyncPacks.status(LinuxRuntime.rootDir(context)).let { k("droiddeck-esync packs", "${it.installed} installed, ${it.wanted} wanted") }
|
EsyncPacks.status(LinuxRuntime.rootDir(context)).let { k("droiddeck-esync packs", "${it.installed} installed, ${it.wanted} wanted") }
|
||||||
k("Linux x86 (FEX)", if (com.droiddeck.launcher.runtime.LinuxFex.ready(context)) "ready" else "not set up")
|
k("Linux x86 (FEX)", if (com.droiddeck.launcher.runtime.LinuxFex.ready(context)) "ready" else "not set up")
|
||||||
k("gamescope realtime", SessionPrefs.gamescopeRealtime(context))
|
k("gamescope realtime", SessionPrefs.gamescopeRealtime(context))
|
||||||
|
k("pace cores", SessionPrefs.paceCores(context))
|
||||||
k("zRAM: compress Steam during games", SessionPrefs.zramClient(context))
|
k("zRAM: compress Steam during games", SessionPrefs.zramClient(context))
|
||||||
k("RAM cap", SessionPrefs.ramCapMb(context).let { if (it > 0) "$it MB" else "off" })
|
k("RAM cap", SessionPrefs.ramCapMb(context).let { if (it > 0) "$it MB" else "off" })
|
||||||
k("VRAM cap", SessionPrefs.vramCapMb(context).let { if (it > 0) "$it MB" else "driver default" })
|
k("VRAM cap", SessionPrefs.vramCapMb(context).let { if (it > 0) "$it MB" else "driver default" })
|
||||||
@@ -289,6 +296,8 @@ object DeviceReport {
|
|||||||
k("Microphone", SessionPrefs.micEnabled(context))
|
k("Microphone", SessionPrefs.micEnabled(context))
|
||||||
k("On-screen controls", SessionPrefs.oscMode(context))
|
k("On-screen controls", SessionPrefs.oscMode(context))
|
||||||
k("Touch mode", SessionPrefs.touchMode(context))
|
k("Touch mode", SessionPrefs.touchMode(context))
|
||||||
|
k("Pen mode", SessionPrefs.penMode(context))
|
||||||
|
k("Pen side button", SessionPrefs.penButton(context))
|
||||||
k("Performance HUD", SessionPrefs.hudEnabled(context))
|
k("Performance HUD", SessionPrefs.hudEnabled(context))
|
||||||
k("Game storage", when (val g = SessionPrefs.gameStorage(context)) {
|
k("Game storage", when (val g = SessionPrefs.gameStorage(context)) {
|
||||||
"" -> "automatic (" + (com.droiddeck.launcher.session.GameStorage.effective(context)?.path ?: "no card present") + ")"
|
"" -> "automatic (" + (com.droiddeck.launcher.session.GameStorage.effective(context)?.path ?: "no card present") + ")"
|
||||||
|
|||||||
@@ -31,8 +31,26 @@ public final class Downloader {
|
|||||||
return thread;
|
return thread;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
private static final ThreadLocal<String> LAST_FAILURE = new ThreadLocal<>();
|
||||||
|
|
||||||
private Downloader() {}
|
private Downloader() {}
|
||||||
|
|
||||||
|
public static String lastFailure() {
|
||||||
|
return LAST_FAILURE.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void failed(String url, String reason) {
|
||||||
|
String host;
|
||||||
|
try { host = new java.net.URI(url).getHost(); } catch (java.net.URISyntaxException e) { host = null; }
|
||||||
|
String entry = (host == null ? url : host) + ": " + reason;
|
||||||
|
String earlier = LAST_FAILURE.get();
|
||||||
|
LAST_FAILURE.set(earlier == null ? entry : earlier + "; " + entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String describe(Exception e) {
|
||||||
|
return e.getMessage() == null ? e.getClass().getSimpleName() : e.getClass().getSimpleName() + ": " + e.getMessage();
|
||||||
|
}
|
||||||
|
|
||||||
public static final class Cancellation implements java.util.function.BooleanSupplier {
|
public static final class Cancellation implements java.util.function.BooleanSupplier {
|
||||||
private final AtomicBoolean cancelled = new AtomicBoolean();
|
private final AtomicBoolean cancelled = new AtomicBoolean();
|
||||||
private final AtomicReference<HttpURLConnection> connection = new AtomicReference<>();
|
private final AtomicReference<HttpURLConnection> connection = new AtomicReference<>();
|
||||||
@@ -87,12 +105,14 @@ public final class Downloader {
|
|||||||
|
|
||||||
public static String downloadString(String url, java.util.function.BooleanSupplier cancelled) {
|
public static String downloadString(String url, java.util.function.BooleanSupplier cancelled) {
|
||||||
List<String> sources = DownloadSource.INSTANCE.candidates(url);
|
List<String> sources = DownloadSource.INSTANCE.candidates(url);
|
||||||
|
LAST_FAILURE.remove();
|
||||||
for (int i = 0; i < sources.size(); i++) {
|
for (int i = 0; i < sources.size(); i++) {
|
||||||
if (isCancelled(cancelled)) return null;
|
if (isCancelled(cancelled)) return null;
|
||||||
if (i > 0) Log.i(TAG, "retrying " + url + " via " + sources.get(i));
|
if (i > 0) Log.i(TAG, "retrying " + url + " via " + sources.get(i));
|
||||||
Fetch fetch = fetch(sources.get(i), cancelled);
|
Fetch fetch = fetch(sources.get(i), cancelled);
|
||||||
if (isCancelled(cancelled)) return null;
|
if (isCancelled(cancelled)) return null;
|
||||||
if (fetch.body != null) {
|
if (fetch.body != null) {
|
||||||
|
LAST_FAILURE.remove();
|
||||||
DownloadSource.INSTANCE.succeeded(sources.get(i));
|
DownloadSource.INSTANCE.succeeded(sources.get(i));
|
||||||
return fetch.body;
|
return fetch.body;
|
||||||
}
|
}
|
||||||
@@ -103,6 +123,7 @@ public final class Downloader {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static String downloadDirect(String url) {
|
public static String downloadDirect(String url) {
|
||||||
|
LAST_FAILURE.remove();
|
||||||
return fetch(url).body;
|
return fetch(url).body;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -138,6 +159,7 @@ public final class Downloader {
|
|||||||
String expectedSha256, java.util.function.BooleanSupplier cancelled,
|
String expectedSha256, java.util.function.BooleanSupplier cancelled,
|
||||||
java.util.function.Consumer<Float> progress) {
|
java.util.function.Consumer<Float> progress) {
|
||||||
Identity identity = loadIdentity(destination, resume, expectedSha256);
|
Identity identity = loadIdentity(destination, resume, expectedSha256);
|
||||||
|
LAST_FAILURE.remove();
|
||||||
for (int i = 0; i < sources.size(); i++) {
|
for (int i = 0; i < sources.size(); i++) {
|
||||||
String source = sources.get(i);
|
String source = sources.get(i);
|
||||||
if (isCancelled(cancelled)) return false;
|
if (isCancelled(cancelled)) return false;
|
||||||
@@ -150,12 +172,14 @@ public final class Downloader {
|
|||||||
if (isCancelled(cancelled)) return false;
|
if (isCancelled(cancelled)) return false;
|
||||||
if (!expectedSha256.equalsIgnoreCase(actualSha256)) {
|
if (!expectedSha256.equalsIgnoreCase(actualSha256)) {
|
||||||
Log.w(TAG, "checksum mismatch from " + source + "; trying another source");
|
Log.w(TAG, "checksum mismatch from " + source + "; trying another source");
|
||||||
|
failed(source, "checksum mismatch");
|
||||||
if (!discardPartial(destination, identity)) return false;
|
if (!discardPartial(destination, identity)) return false;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (isCancelled(cancelled)) return false;
|
if (isCancelled(cancelled)) return false;
|
||||||
resumeFile(destination).delete();
|
resumeFile(destination).delete();
|
||||||
|
LAST_FAILURE.remove();
|
||||||
DownloadSource.INSTANCE.succeeded(source);
|
DownloadSource.INSTANCE.succeeded(source);
|
||||||
if (progress != null) progress.accept(1f);
|
if (progress != null) progress.accept(1f);
|
||||||
return true;
|
return true;
|
||||||
@@ -260,6 +284,7 @@ public final class Downloader {
|
|||||||
}
|
}
|
||||||
if (code / 100 != 2) {
|
if (code / 100 != 2) {
|
||||||
Log.w(TAG, url + " -> HTTP " + code);
|
Log.w(TAG, url + " -> HTTP " + code);
|
||||||
|
failed(url, "HTTP " + code);
|
||||||
return code == HttpURLConnection.HTTP_NOT_FOUND || code == HttpURLConnection.HTTP_GONE
|
return code == HttpURLConnection.HTTP_NOT_FOUND || code == HttpURLConnection.HTTP_GONE
|
||||||
? Outcome.FATAL : Outcome.RETRY;
|
? Outcome.FATAL : Outcome.RETRY;
|
||||||
}
|
}
|
||||||
@@ -308,11 +333,15 @@ public final class Downloader {
|
|||||||
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).detach(input);
|
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).detach(input);
|
||||||
}
|
}
|
||||||
if (isCancelled(cancelled)) return Outcome.CANCELLED;
|
if (isCancelled(cancelled)) return Outcome.CANCELLED;
|
||||||
if (total > 0 && written < total) return Outcome.RETRY;
|
if (total > 0 && written < total) {
|
||||||
|
failed(url, "connection closed after " + written + " of " + total + " bytes");
|
||||||
|
return Outcome.RETRY;
|
||||||
|
}
|
||||||
return Outcome.DONE;
|
return Outcome.DONE;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
if (isCancelled(cancelled)) return Outcome.CANCELLED;
|
if (isCancelled(cancelled)) return Outcome.CANCELLED;
|
||||||
Log.w(TAG, "download " + url, e);
|
Log.w(TAG, "download " + url, e);
|
||||||
|
failed(url, describe(e));
|
||||||
return Outcome.RETRY;
|
return Outcome.RETRY;
|
||||||
} finally {
|
} finally {
|
||||||
if (connection != null) {
|
if (connection != null) {
|
||||||
@@ -357,6 +386,7 @@ public final class Downloader {
|
|||||||
int code = connection.getResponseCode();
|
int code = connection.getResponseCode();
|
||||||
if (code / 100 != 2) {
|
if (code / 100 != 2) {
|
||||||
Log.w(TAG, url + " -> HTTP " + code);
|
Log.w(TAG, url + " -> HTTP " + code);
|
||||||
|
failed(url, "HTTP " + code);
|
||||||
return new Fetch(null, code == HttpURLConnection.HTTP_NOT_FOUND || code == HttpURLConnection.HTTP_GONE);
|
return new Fetch(null, code == HttpURLConnection.HTTP_NOT_FOUND || code == HttpURLConnection.HTTP_GONE);
|
||||||
}
|
}
|
||||||
try (InputStream in = connection.getInputStream();
|
try (InputStream in = connection.getInputStream();
|
||||||
@@ -367,6 +397,7 @@ public final class Downloader {
|
|||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
if (isCancelled(cancelled)) return new Fetch(null, false);
|
if (isCancelled(cancelled)) return new Fetch(null, false);
|
||||||
Log.w(TAG, "GET " + url, e);
|
Log.w(TAG, "GET " + url, e);
|
||||||
|
failed(url, describe(e));
|
||||||
return new Fetch(null, false);
|
return new Fetch(null, false);
|
||||||
} finally {
|
} finally {
|
||||||
if (connection != null) {
|
if (connection != null) {
|
||||||
|
|||||||
@@ -49,6 +49,16 @@ object GameEnvironment {
|
|||||||
return withScopeValue(config, scope, NO_STEAM, if (on) "1" else null)
|
return withScopeValue(config, scope, NO_STEAM, if (on) "1" else null)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const val GAME_RESOLUTION = "DROIDDECK_GAME_RESOLUTION"
|
||||||
|
|
||||||
|
fun gameResolution(config: Config, scope: String): GameResolution.Choice? =
|
||||||
|
if (scope.isEmpty()) null else GameResolution.parse(config.games[scope]?.get(GAME_RESOLUTION))
|
||||||
|
|
||||||
|
fun withGameResolution(config: Config, scope: String, choice: GameResolution.Choice?): Config {
|
||||||
|
require(scope.isNotEmpty() && validScope(scope))
|
||||||
|
return withScopeValue(config, scope, GAME_RESOLUTION, choice?.let(GameResolution::format))
|
||||||
|
}
|
||||||
|
|
||||||
fun effective(config: Config, preset: String, scope: String, forceSsbs: Boolean = false): Map<String, String?> =
|
fun effective(config: Config, preset: String, scope: String, forceSsbs: Boolean = false): Map<String, String?> =
|
||||||
defaults(preset, forceSsbs) + config.shared + if (scope.isEmpty()) emptyMap() else config.games[scope].orEmpty()
|
defaults(preset, forceSsbs) + config.shared + if (scope.isEmpty()) emptyMap() else config.games[scope].orEmpty()
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
package com.droiddeck.launcher.core
|
||||||
|
|
||||||
|
object GameResolution {
|
||||||
|
sealed interface Choice
|
||||||
|
data class Fixed(val width: Int, val height: Int) : Choice
|
||||||
|
data class Scaled(val scale: Float) : Choice
|
||||||
|
|
||||||
|
data class Aspect(val label: String, val sizes: List<Fixed>)
|
||||||
|
|
||||||
|
val aspects = listOf(
|
||||||
|
Aspect("16:9", listOf(Fixed(960, 540), Fixed(1280, 720), Fixed(1600, 900), Fixed(1920, 1080), Fixed(2560, 1440))),
|
||||||
|
Aspect("16:10", listOf(Fixed(1280, 800), Fixed(1440, 900), Fixed(1680, 1050), Fixed(1920, 1200), Fixed(2560, 1600))),
|
||||||
|
Aspect("4:3", listOf(Fixed(640, 480), Fixed(800, 600), Fixed(1024, 768), Fixed(1280, 960), Fixed(1440, 1080))),
|
||||||
|
)
|
||||||
|
|
||||||
|
val scales = listOf(1.5f, 2f, 3f)
|
||||||
|
|
||||||
|
const val MIN_WIDTH = 320
|
||||||
|
const val MIN_HEIGHT = 240
|
||||||
|
const val MAX_SIDE = 7680
|
||||||
|
private const val SCALED_PREFIX = "/"
|
||||||
|
|
||||||
|
fun parse(value: String?): Choice? {
|
||||||
|
val text = value?.trim().orEmpty()
|
||||||
|
if (text.startsWith(SCALED_PREFIX)) {
|
||||||
|
return text.removePrefix(SCALED_PREFIX).toFloatOrNull()?.takeIf { it > 1f && it <= 8f }?.let(::Scaled)
|
||||||
|
}
|
||||||
|
val parts = text.split('x', 'X', '×').map { it.trim().toIntOrNull() }
|
||||||
|
if (parts.size != 2) return null
|
||||||
|
val (w, h) = parts
|
||||||
|
return if (w != null && h != null && valid(w, h)) Fixed(w and 1.inv(), h and 1.inv()) else null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun valid(width: Int, height: Int) = width in MIN_WIDTH..MAX_SIDE && height in MIN_HEIGHT..MAX_SIDE
|
||||||
|
|
||||||
|
fun format(choice: Choice): String = when (choice) {
|
||||||
|
is Fixed -> "${choice.width}x${choice.height}"
|
||||||
|
is Scaled -> SCALED_PREFIX + formatScale(choice.scale)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun formatScale(scale: Float): String =
|
||||||
|
(Math.round(scale * 10) / 10f).let { if (it % 1f == 0f) it.toInt().toString() else it.toString() }
|
||||||
|
|
||||||
|
fun resolve(choice: Choice, output: Pair<Int, Int>): Pair<Int, Int> = when (choice) {
|
||||||
|
is Fixed -> choice.width to choice.height
|
||||||
|
is Scaled -> (Math.round(output.first / choice.scale).coerceAtLeast(MIN_WIDTH) and 1.inv()) to
|
||||||
|
(Math.round(output.second / choice.scale).coerceAtLeast(MIN_HEIGHT) and 1.inv())
|
||||||
|
}
|
||||||
|
|
||||||
|
fun aspectLabel(width: Int, height: Int): String {
|
||||||
|
if (width <= 0 || height <= 0) return ""
|
||||||
|
val ratio = width.toFloat() / height
|
||||||
|
aspects.firstOrNull { a ->
|
||||||
|
val (w, h) = a.label.split(':').map(String::toFloat)
|
||||||
|
kotlin.math.abs(ratio - w / h) < 0.02f
|
||||||
|
}?.let { return it.label }
|
||||||
|
if (kotlin.math.abs(ratio - 64f / 27f) < 0.04f || kotlin.math.abs(ratio - 21f / 9f) < 0.04f) return "21:9"
|
||||||
|
val g = gcd(width, height)
|
||||||
|
return if (width / g <= 32) "${width / g}:${height / g}" else String.format(java.util.Locale.ROOT, "%.2f:1", ratio)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun sizesFor(aspect: Aspect, panel: Pair<Int, Int>): List<Fixed> {
|
||||||
|
val long = maxOf(panel.first, panel.second)
|
||||||
|
val short = minOf(panel.first, panel.second)
|
||||||
|
val fit = aspect.sizes.filter { it.width <= long && it.height <= short }
|
||||||
|
return fit.ifEmpty { aspect.sizes.take(1) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private tailrec fun gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
|
||||||
|
}
|
||||||
@@ -13,6 +13,11 @@ object HostProcess {
|
|||||||
|
|
||||||
@JvmStatic
|
@JvmStatic
|
||||||
fun start(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?, outputFile: File?): Int {
|
fun start(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?, outputFile: File?): Int {
|
||||||
|
return start(command, env, dir, onExit, onLine, outputFile, null)
|
||||||
|
}
|
||||||
|
|
||||||
|
@JvmStatic
|
||||||
|
fun start(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?, outputFile: File?, onOutputComplete: Runnable?): Int {
|
||||||
val argv = split(command)
|
val argv = split(command)
|
||||||
if (argv.isEmpty()) return -1
|
if (argv.isEmpty()) return -1
|
||||||
return try {
|
return try {
|
||||||
@@ -35,6 +40,8 @@ object HostProcess {
|
|||||||
try {
|
try {
|
||||||
process.inputStream.bufferedReader().useLines { lines -> lines.forEach { onLine.accept(it) } }
|
process.inputStream.bufferedReader().useLines { lines -> lines.forEach { onLine.accept(it) } }
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
|
} finally {
|
||||||
|
onOutputComplete?.run()
|
||||||
}
|
}
|
||||||
}, "proc-out-$pid").apply { priority = Thread.NORM_PRIORITY - 1; isDaemon = true; start() }
|
}, "proc-out-$pid").apply { priority = Thread.NORM_PRIORITY - 1; isDaemon = true; start() }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,9 @@ import android.util.Log
|
|||||||
import java.io.BufferedWriter
|
import java.io.BufferedWriter
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.FileOutputStream
|
import java.io.FileOutputStream
|
||||||
|
import java.nio.file.Files
|
||||||
|
import java.nio.file.StandardCopyOption
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger
|
||||||
|
|
||||||
object SessionLogCapture {
|
object SessionLogCapture {
|
||||||
private const val TAG = "SessionLogCapture"
|
private const val TAG = "SessionLogCapture"
|
||||||
@@ -15,7 +18,7 @@ object SessionLogCapture {
|
|||||||
private var syncer: Thread? = null
|
private var syncer: Thread? = null
|
||||||
|
|
||||||
@Synchronized
|
@Synchronized
|
||||||
fun start(target: File) {
|
fun start(target: File, sinceMillis: Long) {
|
||||||
stop()
|
stop()
|
||||||
try {
|
try {
|
||||||
val out = target.bufferedWriter()
|
val out = target.bufferedWriter()
|
||||||
@@ -25,7 +28,7 @@ object SessionLogCapture {
|
|||||||
writer = out
|
writer = out
|
||||||
this.target = target
|
this.target = target
|
||||||
pid = HostProcess.start(
|
pid = HostProcess.start(
|
||||||
"/system/bin/logcat -v threadtime -T 1 --pid=" + Process.myPid(),
|
command(Process.myPid(), sinceMillis),
|
||||||
null, target.parentFile, null,
|
null, target.parentFile, null,
|
||||||
) { line ->
|
) { line ->
|
||||||
synchronized(this) {
|
synchronized(this) {
|
||||||
@@ -46,6 +49,11 @@ object SessionLogCapture {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal fun command(pid: Int, sinceMillis: Long): String {
|
||||||
|
val since = if (sinceMillis > 0) "%d.%03d".format(java.util.Locale.US, sinceMillis / 1000, sinceMillis % 1000) else "1"
|
||||||
|
return "/system/bin/logcat -v threadtime -T $since --pid=$pid"
|
||||||
|
}
|
||||||
|
|
||||||
@Synchronized
|
@Synchronized
|
||||||
fun stopFor(dir: File) {
|
fun stopFor(dir: File) {
|
||||||
val t = target ?: return
|
val t = target ?: return
|
||||||
@@ -104,4 +112,53 @@ object SessionLogCapture {
|
|||||||
Log.w(TAG, "could not dump the crash buffer", e)
|
Log.w(TAG, "could not dump the crash buffer", e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun dumpMemoryPressure(target: File) {
|
||||||
|
var temporary: File? = null
|
||||||
|
try {
|
||||||
|
val staged = File.createTempFile(target.name, ".part", target.parentFile).also { temporary = it }
|
||||||
|
val lines = StringBuilder()
|
||||||
|
val done = java.util.concurrent.CountDownLatch(1)
|
||||||
|
val outputDone = java.util.concurrent.CountDownLatch(1)
|
||||||
|
val exitStatus = AtomicInteger(Int.MIN_VALUE)
|
||||||
|
val pid = HostProcess.start(
|
||||||
|
"/system/bin/logcat -b events -d -v threadtime -t 800", null, target.parentFile,
|
||||||
|
{ status -> exitStatus.set(status); done.countDown() },
|
||||||
|
{ line -> synchronized(lines) { lines.append(line).append('\n') } },
|
||||||
|
null,
|
||||||
|
outputDone::countDown,
|
||||||
|
)
|
||||||
|
val deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(10)
|
||||||
|
val finished = if (pid == -1) false else {
|
||||||
|
val exitTime = deadline - System.nanoTime()
|
||||||
|
exitTime > 0 && done.await(exitTime, java.util.concurrent.TimeUnit.NANOSECONDS) &&
|
||||||
|
(deadline - System.nanoTime()).let { it > 0 && outputDone.await(it, java.util.concurrent.TimeUnit.NANOSECONDS) }
|
||||||
|
}
|
||||||
|
val body = synchronized(lines) { lines.toString() }
|
||||||
|
val status = exitStatus.get()
|
||||||
|
val pressure = runCatching { File("/proc/pressure/memory").readText() }.getOrDefault("unavailable\n")
|
||||||
|
val meminfo = runCatching { File("/proc/meminfo").readText() }.getOrDefault("unavailable\n")
|
||||||
|
val gpu = runCatching { File("/sys/class/kgsl/kgsl/page_alloc").readText() }.getOrDefault("unavailable\n")
|
||||||
|
staged.writeText(
|
||||||
|
"Android memory events:\n" +
|
||||||
|
when {
|
||||||
|
pid == -1 -> "(logcat could not be started at all)\n"
|
||||||
|
status != Int.MIN_VALUE && status != 0 -> "(logcat failed with exit status $status; no Android memory events were captured)\n" +
|
||||||
|
if (body.isEmpty()) "" else "\nlogcat command output:\n$body"
|
||||||
|
!finished -> if (body.isEmpty()) "(logcat did not finish within 10 s; nothing captured)\n"
|
||||||
|
else body + "(logcat did not finish within 10 s; later events may be missing)\n"
|
||||||
|
body.isNotEmpty() -> body
|
||||||
|
else -> "(no readable events were returned)\n"
|
||||||
|
} +
|
||||||
|
"\n/proc/pressure/memory:\n$pressure\n/proc/meminfo:\n$meminfo\n/sys/class/kgsl/kgsl/page_alloc:\n$gpu"
|
||||||
|
)
|
||||||
|
Files.move(
|
||||||
|
staged.toPath(), target.toPath(),
|
||||||
|
StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE,
|
||||||
|
)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
temporary?.delete()
|
||||||
|
Log.w(TAG, "could not dump memory pressure diagnostics", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
package com.droiddeck.launcher.core
|
|
||||||
|
|
||||||
import android.content.BroadcastReceiver
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.Intent
|
|
||||||
|
|
||||||
class ShortcutsListingReceiver : BroadcastReceiver() {
|
|
||||||
override fun onReceive(context: Context, intent: Intent) {
|
|
||||||
if (intent.action == Intent.ACTION_MY_PACKAGE_REPLACED) SteamIntegration.syncShortcutsListing(context)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,20 +1,21 @@
|
|||||||
package com.droiddeck.launcher.core
|
package com.droiddeck.launcher.core
|
||||||
|
|
||||||
import android.accessibilityservice.AccessibilityServiceInfo
|
|
||||||
import android.content.ComponentName
|
import android.content.ComponentName
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.content.pm.PackageManager
|
import android.content.pm.PackageManager
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.provider.Settings
|
import android.provider.Settings
|
||||||
import android.view.accessibility.AccessibilityManager
|
|
||||||
import com.droiddeck.launcher.HomeApp
|
import com.droiddeck.launcher.HomeApp
|
||||||
import com.droiddeck.launcher.input.HomeButtonService
|
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
import com.droiddeck.launcher.session.SessionPrefs
|
||||||
|
import com.droiddeck.shortcuts.Relay
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
object SteamIntegration {
|
object SteamIntegration {
|
||||||
const val ACTION_SETUP = "com.droiddeck.launcher.STEAM_INTEGRATION"
|
const val ACTION_SETUP = "com.droiddeck.launcher.STEAM_INTEGRATION"
|
||||||
const val EXTRA_FEATURE = "integration_feature"
|
const val EXTRA_FEATURE = "integration_feature"
|
||||||
|
const val SHORTCUTS_STATUS = "com.droiddeck.launcher.SHORTCUTS_INSTALL_STATUS"
|
||||||
|
private const val SHORTCUTS_ASSET = "shortcuts.apk"
|
||||||
enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS }
|
enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS }
|
||||||
|
|
||||||
data class State(
|
data class State(
|
||||||
@@ -36,11 +37,7 @@ object SteamIntegration {
|
|||||||
locationOn = WifiDiscovery.locationEnabled(context),
|
locationOn = WifiDiscovery.locationEnabled(context),
|
||||||
brightness = Settings.System.canWrite(context),
|
brightness = Settings.System.canWrite(context),
|
||||||
home = HomeApp.isDefault(context),
|
home = HomeApp.isDefault(context),
|
||||||
shortcuts = context.getSystemService(AccessibilityManager::class.java)
|
shortcuts = shortcutsEnabled(context),
|
||||||
.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK).any {
|
|
||||||
val service = it.resolveInfo.serviceInfo
|
|
||||||
ComponentName(service.packageName, service.name) == ComponentName(context, HomeButtonService::class.java)
|
|
||||||
},
|
|
||||||
shortcutsRestricted = restrictedSettings(context),
|
shortcutsRestricted = restrictedSettings(context),
|
||||||
suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false),
|
suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false),
|
||||||
)
|
)
|
||||||
@@ -48,48 +45,53 @@ object SteamIntegration {
|
|||||||
private fun restrictedSettings(context: Context): Boolean {
|
private fun restrictedSettings(context: Context): Boolean {
|
||||||
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return false
|
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return false
|
||||||
val mode = runCatching {
|
val mode = runCatching {
|
||||||
|
val uid = context.packageManager.getApplicationInfo(Relay.PACKAGE, 0).uid
|
||||||
context.getSystemService(android.app.AppOpsManager::class.java)
|
context.getSystemService(android.app.AppOpsManager::class.java)
|
||||||
.unsafeCheckOpNoThrow("android:access_restricted_settings", android.os.Process.myUid(), context.packageName)
|
.unsafeCheckOpNoThrow("android:access_restricted_settings", uid, Relay.PACKAGE)
|
||||||
}.getOrDefault(android.app.AppOpsManager.MODE_ALLOWED)
|
}.getOrDefault(android.app.AppOpsManager.MODE_ALLOWED)
|
||||||
return mode == android.app.AppOpsManager.MODE_ERRORED || mode == android.app.AppOpsManager.MODE_IGNORED
|
return mode == android.app.AppOpsManager.MODE_ERRORED || mode == android.app.AppOpsManager.MODE_IGNORED
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun shortcutsComponent(context: Context) = ComponentName(context, HomeButtonService::class.java)
|
private val shortcutsComponent = ComponentName(Relay.PACKAGE, Relay.SERVICE)
|
||||||
|
|
||||||
fun shortcutsChosen(context: Context): Boolean = shortcutsSelection(context) == true
|
fun shortcutsEnabled(context: Context): Boolean {
|
||||||
|
|
||||||
private fun shortcutsSelection(context: Context): Boolean? {
|
|
||||||
val target = shortcutsComponent(context)
|
|
||||||
val enabled = runCatching {
|
val enabled = runCatching {
|
||||||
Settings.Secure.getString(context.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES)
|
Settings.Secure.getString(context.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES)
|
||||||
}.getOrElse { return null }.orEmpty()
|
}.getOrNull().orEmpty()
|
||||||
return enabled.split(':').any { ComponentName.unflattenFromString(it.trim()) == target }
|
return enabled.split(':').any { ComponentName.unflattenFromString(it.trim()) == shortcutsComponent }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun setShortcutsListed(context: Context, listed: Boolean) {
|
fun shortcutsListed(context: Context): Boolean =
|
||||||
|
context.getSystemService(android.view.accessibility.AccessibilityManager::class.java)
|
||||||
|
?.installedAccessibilityServiceList.orEmpty()
|
||||||
|
.any { ComponentName(it.resolveInfo.serviceInfo.packageName, it.resolveInfo.serviceInfo.name) == shortcutsComponent }
|
||||||
|
|
||||||
|
fun bundledShortcuts(context: Context): File {
|
||||||
|
val target = File(context.cacheDir, SHORTCUTS_ASSET)
|
||||||
|
context.assets.open(SHORTCUTS_ASSET).use { input -> target.outputStream().use { input.copyTo(it) } }
|
||||||
|
return target
|
||||||
|
}
|
||||||
|
|
||||||
|
fun shortcutsInstalled(context: Context, bundled: File): Boolean {
|
||||||
val packages = context.packageManager
|
val packages = context.packageManager
|
||||||
val component = shortcutsComponent(context)
|
@Suppress("DEPRECATION")
|
||||||
val state = if (listed) PackageManager.COMPONENT_ENABLED_STATE_ENABLED else PackageManager.COMPONENT_ENABLED_STATE_DISABLED
|
val installed = runCatching { packages.getPackageInfo(Relay.PACKAGE, 0).versionCode }.getOrNull() ?: return false
|
||||||
runCatching {
|
@Suppress("DEPRECATION")
|
||||||
if (packages.getComponentEnabledSetting(component) != state) {
|
val shipped = packages.getPackageArchiveInfo(bundled.absolutePath, 0)?.versionCode ?: return true
|
||||||
packages.setComponentEnabledSetting(component, state, PackageManager.DONT_KILL_APP)
|
return installed >= shipped
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun syncShortcutsListing(context: Context) {
|
|
||||||
shortcutsSelection(context)?.let { setShortcutsListed(context, it) }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun dismissSuggestion(context: Context) {
|
fun dismissSuggestion(context: Context) {
|
||||||
SessionPrefs.sessionPrefs(context).edit().putBoolean("steam_integration_seen", true).apply()
|
SessionPrefs.sessionPrefs(context).edit().putBoolean("steam_integration_seen", true).apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun shortcutsAppInfo() = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${Relay.PACKAGE}"))
|
||||||
|
|
||||||
fun brightnessSettings(context: Context) = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
|
fun brightnessSettings(context: Context) = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
|
||||||
Uri.parse("package:${context.packageName}"))
|
Uri.parse("package:${context.packageName}"))
|
||||||
|
|
||||||
fun shortcutSettings(context: Context): Intent {
|
fun shortcutSettings(context: Context): Intent {
|
||||||
val service = ComponentName(context, HomeButtonService::class.java).flattenToString()
|
val service = shortcutsComponent.flattenToString()
|
||||||
return Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
|
return Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
|
||||||
.putExtra(":settings:fragment_args_key", service)
|
.putExtra(":settings:fragment_args_key", service)
|
||||||
.putExtra(":settings:show_fragment_args", android.os.Bundle().apply { putString(":settings:fragment_args_key", service) })
|
.putExtra(":settings:show_fragment_args", android.os.Bundle().apply { putString(":settings:fragment_args_key", service) })
|
||||||
|
|||||||
@@ -112,6 +112,10 @@ private const val HISTORY_LIMIT = 50
|
|||||||
internal fun canNavigateUp(currentDir: File, currentRoot: File): Boolean =
|
internal fun canNavigateUp(currentDir: File, currentRoot: File): Boolean =
|
||||||
currentDir != currentRoot && currentDir.parentFile?.exists() == true
|
currentDir != currentRoot && currentDir.parentFile?.exists() == true
|
||||||
|
|
||||||
|
// Back leaves after a drive hop instead of replaying a stack of hops one press at a time.
|
||||||
|
internal fun backExitsAtRootHop(currentDir: File, currentRoot: File, previous: Pair<File, File>): Boolean =
|
||||||
|
currentDir == currentRoot && previous.first == previous.second
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun FileManagerScreen(
|
fun FileManagerScreen(
|
||||||
@@ -269,8 +273,10 @@ fun FileManagerScreen(
|
|||||||
if (showFavorites) showFavorites = false
|
if (showFavorites) showFavorites = false
|
||||||
else {
|
else {
|
||||||
while (history.isNotEmpty() && !history.last().first.isDirectory) history.removeAt(history.lastIndex)
|
while (history.isNotEmpty() && !history.last().first.isDirectory) history.removeAt(history.lastIndex)
|
||||||
val previous = history.removeLastOrNull()
|
val previous = history.lastOrNull()
|
||||||
if (previous != null) {
|
if (previous != null && backExitsAtRootHop(currentDir, currentRoot, previous)) onExit?.invoke()
|
||||||
|
else if (previous != null) {
|
||||||
|
history.removeLastOrNull()
|
||||||
currentRoot = previous.second
|
currentRoot = previous.second
|
||||||
loadDirectory(previous.first, record = false)
|
loadDirectory(previous.first, record = false)
|
||||||
} else if (canNavigateUp(currentDir, currentRoot)) currentDir.parentFile?.let { loadDirectory(it, record = false) }
|
} else if (canNavigateUp(currentDir, currentRoot)) currentDir.parentFile?.let { loadDirectory(it, record = false) }
|
||||||
|
|||||||
@@ -97,15 +97,16 @@ object AddedGames {
|
|||||||
return File(LinuxRuntime.rootDir(context), guest.removePrefix("/"))
|
return File(LinuxRuntime.rootDir(context), guest.removePrefix("/"))
|
||||||
}
|
}
|
||||||
|
|
||||||
fun candidates(folder: File): List<File> = rank(folder).exes
|
fun candidates(folder: File, reuse: Boolean = false): List<File> = rank(folder, reuse).exes
|
||||||
|
|
||||||
fun rank(folder: File, reuse: Boolean = false): GameExePicker.Ranking {
|
fun rank(folder: File, reuse: Boolean = false): GameExePicker.Ranking {
|
||||||
val key = "${folder.path}|${folder.lastModified()}"
|
val declared = declaredExes(folder)
|
||||||
|
val stamp = declared.fold(0L) { hash, exe -> hash * 31 + exe.path.hashCode() }
|
||||||
|
val key = "${folder.path}|${folder.lastModified()}|$stamp"
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
ranked[key]?.takeIf { now - it.first < RANK_FRESH_MS }?.let { return it.second }
|
ranked[key]?.takeIf { now - it.first < RANK_FRESH_MS }?.let { return it.second }
|
||||||
if (reuse) kept?.rank(folder)?.let { return it }
|
if (reuse) kept?.rank(folder, stamp)?.let { return it }
|
||||||
val guessed = GameExePicker.rank(folder) { !skipExe(it.name) }
|
val guessed = GameExePicker.rank(folder) { !skipExe(it.name) }
|
||||||
val declared = declaredExes(folder)
|
|
||||||
val preferred = declared.map { it.path }.toSet()
|
val preferred = declared.map { it.path }.toSet()
|
||||||
val result = if (declared.isEmpty()) guessed else GameExePicker.Ranking(
|
val result = if (declared.isEmpty()) guessed else GameExePicker.Ranking(
|
||||||
declared + guessed.exes.filter { it.path !in preferred },
|
declared + guessed.exes.filter { it.path !in preferred },
|
||||||
@@ -115,7 +116,7 @@ object AddedGames {
|
|||||||
)
|
)
|
||||||
if (ranked.size > 256) ranked.clear()
|
if (ranked.size > 256) ranked.clear()
|
||||||
ranked[key] = now to result
|
ranked[key] = now to result
|
||||||
kept?.keepRank(folder, result)
|
kept?.keepRank(folder, result, stamp)
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -200,8 +201,7 @@ object AddedGames {
|
|||||||
private val scanning = Any()
|
private val scanning = Any()
|
||||||
|
|
||||||
fun scan(context: Context): List<Game> = synchronized(scanning) {
|
fun scan(context: Context): List<Game> = synchronized(scanning) {
|
||||||
val file = File(context.filesDir, AddedGamesCache.FILE)
|
val cache = cache(context)
|
||||||
val cache = kept?.takeIf { it.file == file } ?: AddedGamesCache(file).also { kept = it }
|
|
||||||
try {
|
try {
|
||||||
scanAll(context)
|
scanAll(context)
|
||||||
} finally {
|
} finally {
|
||||||
@@ -209,6 +209,13 @@ object AddedGames {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private val keeping = Any()
|
||||||
|
|
||||||
|
private fun cache(context: Context): AddedGamesCache = synchronized(keeping) {
|
||||||
|
val file = File(context.filesDir, AddedGamesCache.FILE)
|
||||||
|
kept?.takeIf { it.file == file } ?: AddedGamesCache(file).also { kept = it }
|
||||||
|
}
|
||||||
|
|
||||||
private fun scanAll(context: Context): List<Game> {
|
private fun scanAll(context: Context): List<Game> {
|
||||||
val out = ArrayList<Game>()
|
val out = ArrayList<Game>()
|
||||||
GamesFolderMigration.run(context)
|
GamesFolderMigration.run(context)
|
||||||
@@ -241,11 +248,17 @@ object AddedGames {
|
|||||||
return out.distinctBy { it.folder.canonicalPath }
|
return out.distinctBy { it.folder.canonicalPath }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun single(context: Context, folderPath: String): Game? {
|
fun single(context: Context, folderPath: String, reuse: Boolean = false): Game? {
|
||||||
val folder = File(folderPath)
|
val folder = File(folderPath)
|
||||||
if (!folder.isDirectory || folderPath in SessionPrefs.removedAddedGames(context)) return null
|
if (!folder.isDirectory || folderPath in SessionPrefs.removedAddedGames(context)) return null
|
||||||
val out = ArrayList<Game>(1)
|
val out = ArrayList<Game>(1)
|
||||||
scanGame(context, folder, out, single = AddedExes.list(context).firstOrNull { it.folder == folderPath })
|
val entry = AddedExes.list(context).firstOrNull { it.folder == folderPath }
|
||||||
|
val cache = if (reuse) cache(context) else null
|
||||||
|
try {
|
||||||
|
scanGame(context, folder, out, single = entry, reuse = reuse)
|
||||||
|
} finally {
|
||||||
|
cache?.save()
|
||||||
|
}
|
||||||
return out.firstOrNull()
|
return out.firstOrNull()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -418,6 +431,7 @@ object AddedGames {
|
|||||||
private fun scanGame(context: Context, folder: File, out: MutableList<Game>, single: AddedExes.Entry? = null, reuse: Boolean = false) {
|
private fun scanGame(context: Context, folder: File, out: MutableList<Game>, single: AddedExes.Entry? = null, reuse: Boolean = false) {
|
||||||
run {
|
run {
|
||||||
val sidecar = StoreGameSidecar.read(folder)?.let { com.droiddeck.launcher.stores.StoreLaunch.adopt(folder, it) }
|
val sidecar = StoreGameSidecar.read(folder)?.let { com.droiddeck.launcher.stores.StoreLaunch.adopt(folder, it) }
|
||||||
|
if (sidecar?.store == Store.ROCKSTAR && sidecar.launcher != com.droiddeck.launcher.stores.StoreLaunch.LAUNCHER) return
|
||||||
sidecar?.takeIf { it.id.isNotEmpty() }?.let { SessionPrefs.followStoreGame(context, "${it.store.id}:${it.id}", folder.path) { old -> !File(old).exists() } }
|
sidecar?.takeIf { it.id.isNotEmpty() }?.let { SessionPrefs.followStoreGame(context, "${it.store.id}:${it.id}", folder.path) { old -> !File(old).exists() } }
|
||||||
val ranking = rank(folder, reuse)
|
val ranking = rank(folder, reuse)
|
||||||
val candidates = ranking.exes
|
val candidates = ranking.exes
|
||||||
@@ -433,6 +447,7 @@ object AddedGames {
|
|||||||
val autoName = sidecar?.title ?: identifiedName(folder, found) ?: folder.name
|
val autoName = sidecar?.title ?: identifiedName(folder, found) ?: folder.name
|
||||||
val crc = CRC32().apply { update(("\"${foundGuest.replaceFirst(Regex("^$LIBRARY/"), "$LEGACY_LIBRARY/")}\"" + autoName).toByteArray()) }.value
|
val crc = CRC32().apply { update(("\"${foundGuest.replaceFirst(Regex("^$LIBRARY/"), "$LEGACY_LIBRARY/")}\"" + autoName).toByteArray()) }.value
|
||||||
val appId = SessionPrefs.addedGameAppId(context, folder.path, crc or 0x80000000L)
|
val appId = SessionPrefs.addedGameAppId(context, folder.path, crc or 0x80000000L)
|
||||||
|
if (sidecar?.store == Store.ROCKSTAR) com.droiddeck.launcher.stores.rockstar.RockstarLaunch.applyDefaults(context, sidecar.id, appId)
|
||||||
val config = accountConfig(SessionPrefs.activeSteamRoot(context))
|
val config = accountConfig(SessionPrefs.activeSteamRoot(context))
|
||||||
val record = config?.let { shortcutRecord(it, appId) }
|
val record = config?.let { shortcutRecord(it, appId) }
|
||||||
val rev = record?.optInt("rev", 0) ?: 0
|
val rev = record?.optInt("rev", 0) ?: 0
|
||||||
@@ -527,6 +542,17 @@ object AddedGames {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class Listed(val appId: Long, val name: String, val launchOptions: String)
|
||||||
|
|
||||||
|
fun listed(context: Context): List<Listed>? = runCatching {
|
||||||
|
val file = File(context.filesDir, "session/added-games.json")
|
||||||
|
if (!file.isFile) return null
|
||||||
|
val entries = org.json.JSONArray(file.readText())
|
||||||
|
(0 until entries.length()).mapNotNull { i ->
|
||||||
|
entries.optJSONObject(i)?.takeIf { it.has("appid") }?.let { Listed(it.optLong("appid") and 0xFFFFFFFFL, it.optString("name"), it.optString("launch")) }
|
||||||
|
}
|
||||||
|
}.getOrNull()
|
||||||
|
|
||||||
fun writeListing(context: Context, games: List<Game>,
|
fun writeListing(context: Context, games: List<Game>,
|
||||||
extra: List<JSONObject> = listOfNotNull(com.droiddeck.launcher.stores.epic.EpicClient.steamListing(context))): File {
|
extra: List<JSONObject> = listOfNotNull(com.droiddeck.launcher.stores.epic.EpicClient.steamListing(context))): File {
|
||||||
val file = File(context.filesDir, "session/added-games.json").apply { parentFile?.mkdirs() }
|
val file = File(context.filesDir, "session/added-games.json").apply { parentFile?.mkdirs() }
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import java.io.File
|
|||||||
import java.util.concurrent.ConcurrentHashMap
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
|
|
||||||
internal class AddedGamesCache(val file: File) {
|
internal class AddedGamesCache(val file: File) {
|
||||||
private class Rank(val modified: Long, val at: Long, val ranking: GameExePicker.Ranking)
|
private class Rank(val modified: Long, val declared: Long, val at: Long, val ranking: GameExePicker.Ranking)
|
||||||
private class Name(val name: String, val at: Long)
|
private class Name(val name: String, val at: Long)
|
||||||
|
|
||||||
private val ranks = ConcurrentHashMap<String, Rank>()
|
private val ranks = ConcurrentHashMap<String, Rank>()
|
||||||
@@ -22,7 +22,7 @@ internal class AddedGamesCache(val file: File) {
|
|||||||
val exes = o.getJSONArray("exes")
|
val exes = o.getJSONArray("exes")
|
||||||
val scores = o.getJSONArray("scores")
|
val scores = o.getJSONArray("scores")
|
||||||
require(exes.length() > 0 && exes.length() == scores.length())
|
require(exes.length() > 0 && exes.length() == scores.length())
|
||||||
ranks[path] = Rank(o.getLong("modified"), o.getLong("at"), GameExePicker.Ranking(
|
ranks[path] = Rank(o.getLong("modified"), o.optLong("declared"), o.getLong("at"), GameExePicker.Ranking(
|
||||||
List(exes.length()) { File(exes.getString(it)) }, List(scores.length()) { scores.getInt(it) }, o.optBoolean("uncertain"),
|
List(exes.length()) { File(exes.getString(it)) }, List(scores.length()) { scores.getInt(it) }, o.optBoolean("uncertain"),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
@@ -32,19 +32,19 @@ internal class AddedGamesCache(val file: File) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun rank(folder: File): GameExePicker.Ranking? {
|
fun rank(folder: File, declared: Long = 0): GameExePicker.Ranking? {
|
||||||
val kept = ranks[folder.path] ?: return null
|
val kept = ranks[folder.path] ?: return null
|
||||||
val age = System.currentTimeMillis() - kept.at
|
val age = System.currentTimeMillis() - kept.at
|
||||||
val top = kept.ranking.exes.first()
|
val top = kept.ranking.exes.first()
|
||||||
return kept.ranking.takeIf { kept.modified == folder.lastModified() && age in 0 until KEEP_MS && top.isFile }
|
return kept.ranking.takeIf { kept.modified == folder.lastModified() && kept.declared == declared && age in 0 until KEEP_MS && top.isFile }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun keepRank(folder: File, ranking: GameExePicker.Ranking) {
|
fun keepRank(folder: File, ranking: GameExePicker.Ranking, declared: Long = 0) {
|
||||||
if (ranking.exes.isEmpty()) {
|
if (ranking.exes.isEmpty()) {
|
||||||
if (ranks.remove(folder.path) != null) changed = true
|
if (ranks.remove(folder.path) != null) changed = true
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ranks[folder.path] = Rank(folder.lastModified(), System.currentTimeMillis(), ranking)
|
ranks[folder.path] = Rank(folder.lastModified(), declared, System.currentTimeMillis(), ranking)
|
||||||
changed = true
|
changed = true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,7 +62,7 @@ internal class AddedGamesCache(val file: File) {
|
|||||||
val oldest = System.currentTimeMillis() - KEEP_MS
|
val oldest = System.currentTimeMillis() - KEEP_MS
|
||||||
val keptRanks = JSONObject()
|
val keptRanks = JSONObject()
|
||||||
ranks.forEach { (path, r) ->
|
ranks.forEach { (path, r) ->
|
||||||
if (r.at >= oldest) keptRanks.put(path, JSONObject().put("modified", r.modified).put("at", r.at)
|
if (r.at >= oldest) keptRanks.put(path, JSONObject().put("modified", r.modified).put("declared", r.declared).put("at", r.at)
|
||||||
.put("exes", JSONArray(r.ranking.exes.map { it.path })).put("scores", JSONArray(r.ranking.scores))
|
.put("exes", JSONArray(r.ranking.exes.map { it.path })).put("scores", JSONArray(r.ranking.scores))
|
||||||
.put("uncertain", r.ranking.uncertain))
|
.put("uncertain", r.ranking.uncertain))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package com.droiddeck.launcher.frontend
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
object AddedSoundtracks {
|
||||||
|
private fun file(context: Context) = File(context.filesDir, "added-soundtracks.json")
|
||||||
|
|
||||||
|
class Entry(val path: String, val name: String, val id: Int = 0)
|
||||||
|
|
||||||
|
internal fun assignIds(list: List<Entry>): List<Entry> {
|
||||||
|
val used = list.filter { it.id != 0 }.map { it.id }.toMutableSet()
|
||||||
|
return list.map { e ->
|
||||||
|
if (e.id != 0) e else {
|
||||||
|
var id = idOf(e.path)
|
||||||
|
while (id == 0 || !used.add(id)) id = (id + 1) or Int.MIN_VALUE
|
||||||
|
Entry(e.path, e.name, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun entries(context: Context): List<Entry> = runCatching {
|
||||||
|
val f = file(context).takeIf { it.isFile } ?: return emptyList()
|
||||||
|
val array = JSONArray(f.readText())
|
||||||
|
val raw = List(array.length()) { i -> array.getJSONObject(i).let { Entry(it.getString("path"), it.getString("name"), it.optInt("id", 0)) } }
|
||||||
|
val ready = assignIds(raw)
|
||||||
|
if (raw.any { it.id == 0 }) save(context, ready)
|
||||||
|
ready
|
||||||
|
}.getOrDefault(emptyList())
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
private fun save(context: Context, list: List<Entry>): Boolean =
|
||||||
|
runCatching {
|
||||||
|
val array = JSONArray()
|
||||||
|
list.forEach { array.put(JSONObject().put("path", it.path).put("name", it.name).put("id", it.id)) }
|
||||||
|
val f = file(context)
|
||||||
|
val tmp = File(f.path + ".tmp")
|
||||||
|
tmp.writeText(array.toString())
|
||||||
|
if (tmp.renameTo(f)) true else { tmp.delete(); false }
|
||||||
|
}.getOrDefault(false)
|
||||||
|
|
||||||
|
fun add(context: Context, folder: File): Boolean {
|
||||||
|
if (!folder.isDirectory || Soundtrack.audioFiles(folder).isEmpty()) return false
|
||||||
|
return synchronized(this) {
|
||||||
|
val list = entries(context)
|
||||||
|
list.any { it.path == folder.path } || save(context, assignIds(list + Entry(folder.path, folder.name)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun remove(context: Context, path: String): Boolean =
|
||||||
|
synchronized(this) { save(context, entries(context).filterNot { it.path == path }) }
|
||||||
|
|
||||||
|
internal fun idOf(path: String): Int = path.hashCode() or Int.MIN_VALUE
|
||||||
|
|
||||||
|
fun games(context: Context): List<Library.SteamGame> = entries(context).mapNotNull { e ->
|
||||||
|
val dir = File(e.path).takeIf { it.isDirectory } ?: return@mapNotNull null
|
||||||
|
game(context, e, dir, e.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun game(context: Context, e: Entry, dir: File, id: Int): Library.SteamGame {
|
||||||
|
return Library.SteamGame(
|
||||||
|
appId = id, name = e.name, art = SoundtrackCollectionArt.chosen(context, id) ?: Soundtrack.firstCover(context, dir), library = Library.ADDED, gameId = id.toLong() and 0xFFFFFFFFL,
|
||||||
|
gameFiles = dir, source = Library.ADDED, soundtrack = true,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -43,11 +43,14 @@ object GameFileSync {
|
|||||||
val storageSetting = SessionPrefs.gameStorage(context)
|
val storageSetting = SessionPrefs.gameStorage(context)
|
||||||
val previousStorage = prefs(context).getString("storagePath", null)
|
val previousStorage = prefs(context).getString("storagePath", null)
|
||||||
if (storageSetting.isEmpty() && prefs(context).getString("storageSetting", null) == storageSetting && previousStorage != null) {
|
if (storageSetting.isEmpty() && prefs(context).getString("storageSetting", null) == storageSetting && previousStorage != null) {
|
||||||
check(File(previousStorage).isDirectory) { context.getString(R.string.game_sync_err_previous_sd) }
|
check(libraryReadable(File(previousStorage))) { context.getString(R.string.game_sync_err_previous_sd) }
|
||||||
}
|
}
|
||||||
storage?.let { check(File(it.path).listFiles() != null) { context.getString(R.string.game_sync_err_game_storage) } }
|
storage?.let { check(libraryReadable(File(it.path))) { context.getString(R.string.game_sync_err_game_storage) } }
|
||||||
AddedGames.roots(context).forEach { check(it.host.listFiles() != null) { context.getString(R.string.game_sync_err_added_games) } }
|
AddedGames.roots(context).forEach { check(it.host.listFiles() != null) { context.getString(R.string.game_sync_err_added_games) } }
|
||||||
GameFiles.sync(context, folder, Library.launchableGames(context, strictRead = true))
|
GameFiles.sync(context, folder, Library.launchableGames(context, strictRead = true))
|
||||||
prefs(context).edit().putString("storageSetting", storageSetting).putString("storagePath", storage?.path).apply()
|
prefs(context).edit().putString("storageSetting", storageSetting).putString("storagePath", storage?.path).apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal fun libraryReadable(dir: File): Boolean =
|
||||||
|
dir.listFiles() != null || (!dir.exists() && dir.parentFile?.isDirectory == true)
|
||||||
}
|
}
|
||||||
@@ -21,7 +21,7 @@ object GameRemoval {
|
|||||||
fun steamFiles(game: Library.SteamGame): SteamFiles? {
|
fun steamFiles(game: Library.SteamGame): SteamFiles? {
|
||||||
val dir = game.gameFiles ?: return null
|
val dir = game.gameFiles ?: return null
|
||||||
val common = dir.parentFile ?: return null
|
val common = dir.parentFile ?: return null
|
||||||
if (common.name != "common") return null
|
if (common.name != (if (game.soundtrack) "music" else "common")) return null
|
||||||
val steamapps = common.parentFile ?: return null
|
val steamapps = common.parentFile ?: return null
|
||||||
if (steamapps.name != "steamapps") return null
|
if (steamapps.name != "steamapps") return null
|
||||||
val manifest = File(steamapps, "appmanifest_${game.appId}.acf")
|
val manifest = File(steamapps, "appmanifest_${game.appId}.acf")
|
||||||
|
|||||||
@@ -19,9 +19,10 @@ object Library {
|
|||||||
val storeId: String? = null,
|
val storeId: String? = null,
|
||||||
val logo: File? = null,
|
val logo: File? = null,
|
||||||
val installedAt: Long = 0L,
|
val installedAt: Long = 0L,
|
||||||
|
val soundtrack: Boolean = false,
|
||||||
) {
|
) {
|
||||||
fun withArt(art: File?, hero: File?, icon: File?, logo: File? = this.logo) =
|
fun withArt(art: File?, hero: File?, icon: File?, logo: File? = this.logo) =
|
||||||
SteamGame(appId, name, art, library, gameId, hero, lastPlayed, gameFiles, protonPrefix, icon, source, storeId, logo, installedAt)
|
SteamGame(appId, name, art, library, gameId, hero, lastPlayed, gameFiles, protonPrefix, icon, source, storeId, logo, installedAt, soundtrack)
|
||||||
|
|
||||||
val gameIdString: String get() = java.lang.Long.toUnsignedString(gameId)
|
val gameIdString: String get() = java.lang.Long.toUnsignedString(gameId)
|
||||||
val launchKey: String get() = if (storeId != null) "$source:$storeId" else gameIdString
|
val launchKey: String get() = if (storeId != null) "$source:$storeId" else gameIdString
|
||||||
@@ -38,6 +39,7 @@ object Library {
|
|||||||
const val BATTLENET_LAUNCHER = "battlenet-launcher"
|
const val BATTLENET_LAUNCHER = "battlenet-launcher"
|
||||||
const val XBOX_CLOUD = "xbox-cloud"
|
const val XBOX_CLOUD = "xbox-cloud"
|
||||||
const val SOURCE_STEAM = "steam"
|
const val SOURCE_STEAM = "steam"
|
||||||
|
const val SOURCE_COLLECTION = "collection"
|
||||||
|
|
||||||
class Rom(val name: String, val hostPath: File, val guestPath: String, val emulatorId: String, val art: File? = null)
|
class Rom(val name: String, val hostPath: File, val guestPath: String, val emulatorId: String, val art: File? = null)
|
||||||
class Emulator(val id: String, val name: String, val system: String, val program: String, val installed: Boolean, val games: List<Rom>) {
|
class Emulator(val id: String, val name: String, val system: String, val program: String, val installed: Boolean, val games: List<Rom>) {
|
||||||
@@ -123,9 +125,13 @@ object Library {
|
|||||||
.distinctBy { runCatching { it.canonicalPath }.getOrDefault(it.absolutePath) }
|
.distinctBy { runCatching { it.canonicalPath }.getOrDefault(it.absolutePath) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun soundtracks(context: Context, arch: String = SessionPrefs.activeSteamClientArch(context)): List<SteamGame> =
|
||||||
|
steamGames(context, arch = arch, withShared = false, soundtracks = true, soundtracksOnly = true)
|
||||||
|
|
||||||
fun steamGames(
|
fun steamGames(
|
||||||
context: Context, strictRead: Boolean = false, arch: String = SessionPrefs.activeSteamClientArch(context),
|
context: Context, strictRead: Boolean = false, arch: String = SessionPrefs.activeSteamClientArch(context),
|
||||||
withShared: Boolean = true,
|
withShared: Boolean = true, soundtracks: Boolean = false, soundtracksOnly: Boolean = false,
|
||||||
|
onlyAppIds: Set<Int>? = null,
|
||||||
): List<SteamGame> {
|
): List<SteamGame> {
|
||||||
val root = SessionPrefs.steamRoot(context, arch)
|
val root = SessionPrefs.steamRoot(context, arch)
|
||||||
val cache = File(root, "appcache/librarycache")
|
val cache = File(root, "appcache/librarycache")
|
||||||
@@ -138,21 +144,26 @@ object Library {
|
|||||||
if (strictRead && steamapps.isDirectory) check(manifests != null) { context.getString(R.string.game_sync_err_manifests) }
|
if (strictRead && steamapps.isDirectory) check(manifests != null) { context.getString(R.string.game_sync_err_manifests) }
|
||||||
manifests?.sortedBy { it.name }?.forEach { manifest ->
|
manifests?.sortedBy { it.name }?.forEach { manifest ->
|
||||||
val appId = manifest.name.removePrefix("appmanifest_").removeSuffix(".acf").toIntOrNull() ?: return@forEach
|
val appId = manifest.name.removePrefix("appmanifest_").removeSuffix(".acf").toIntOrNull() ?: return@forEach
|
||||||
if (appId in NOT_GAMES || out.containsKey(appId)) return@forEach
|
if (appId in NOT_GAMES || out.containsKey(appId) ||
|
||||||
|
(onlyAppIds != null && appId !in onlyAppIds)
|
||||||
|
) return@forEach
|
||||||
val text = try { manifest.readText() } catch (e: Exception) { if (strictRead) throw e; return@forEach }
|
val text = try { manifest.readText() } catch (e: Exception) { if (strictRead) throw e; return@forEach }
|
||||||
val name = NAME.find(text)?.groupValues?.get(1)?.trim().orEmpty()
|
val name = NAME.find(text)?.groupValues?.get(1)?.trim().orEmpty()
|
||||||
val flags = STATE.find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0
|
val flags = STATE.find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0
|
||||||
if (name.isEmpty() || flags and 4 == 0) return@forEach
|
if (name.isEmpty() || flags and 4 == 0) return@forEach
|
||||||
|
val installDir = INSTALL_DIR.find(text)?.groupValues?.get(1)?.trim()
|
||||||
|
?.takeIf { it.isNotEmpty() && it != "." && it != ".." && '/' !in it && '\\' !in it }
|
||||||
|
val gameFiles = installDir?.let { File(steamapps, "common/$it").takeIf(File::isDirectory) }
|
||||||
|
val musicFiles = if (gameFiles == null) installDir?.let { File(steamapps, "music/$it").takeIf(File::isDirectory) } else null
|
||||||
|
if (musicFiles != null && !soundtracks) return@forEach
|
||||||
|
if (soundtracksOnly && musicFiles == null) return@forEach
|
||||||
val images = SteamCacheImages(File(cache, appId.toString()))
|
val images = SteamCacheImages(File(cache, appId.toString()))
|
||||||
val art = images.find(STEAM_CAPSULES)
|
val art = images.find(STEAM_CAPSULES)
|
||||||
val hero = images.find(STEAM_HEROES)
|
val hero = images.find(STEAM_HEROES)
|
||||||
val lastPlayed = LAST_PLAYED.find(text)?.groupValues?.get(1)?.toLongOrNull() ?: 0L
|
val lastPlayed = LAST_PLAYED.find(text)?.groupValues?.get(1)?.toLongOrNull() ?: 0L
|
||||||
val installDir = INSTALL_DIR.find(text)?.groupValues?.get(1)?.trim()
|
|
||||||
?.takeIf { it.isNotEmpty() && it != "." && it != ".." && '/' !in it && '\\' !in it }
|
|
||||||
val gameFiles = installDir?.let { File(steamapps, "common/$it").takeIf(File::isDirectory) }
|
|
||||||
out[appId] = SteamGameArt.withOverrides(context, SteamGame(
|
out[appId] = SteamGameArt.withOverrides(context, SteamGame(
|
||||||
appId, name, art, label, hero = hero, lastPlayed = lastPlayed,
|
appId, name, art ?: musicFiles?.let { Soundtrack.firstCover(context, it) }, label, hero = hero, lastPlayed = lastPlayed,
|
||||||
gameFiles = gameFiles,
|
gameFiles = gameFiles ?: musicFiles, soundtrack = musicFiles != null,
|
||||||
protonPrefix = protonPrefix(context, appId.toLong(), library, roots),
|
protonPrefix = protonPrefix(context, appId.toLong(), library, roots),
|
||||||
icon = images.icon(),
|
icon = images.icon(),
|
||||||
logo = images.find(STEAM_LOGOS),
|
logo = images.find(STEAM_LOGOS),
|
||||||
@@ -161,16 +172,42 @@ object Library {
|
|||||||
}
|
}
|
||||||
if (withShared) {
|
if (withShared) {
|
||||||
val other = if (arch == "x86_64") "arm64" else "x86_64"
|
val other = if (arch == "x86_64") "arm64" else "x86_64"
|
||||||
val shared = sharedApps(context, arch) - out.keys
|
val shared = try {
|
||||||
if (shared.isNotEmpty()) runCatching { steamGames(context, arch = other, withShared = false) }.getOrDefault(emptyList())
|
sharedApps(context, arch) - out.keys
|
||||||
.filter { it.appId in shared }.forEach { out[it.appId] = it }
|
} catch (e: IllegalStateException) {
|
||||||
|
if (strictRead) throw e
|
||||||
|
emptySet()
|
||||||
|
}
|
||||||
|
if (shared.isNotEmpty()) {
|
||||||
|
val otherGames = try {
|
||||||
|
steamGames(
|
||||||
|
context,
|
||||||
|
strictRead = strictRead,
|
||||||
|
arch = other,
|
||||||
|
withShared = false,
|
||||||
|
soundtracks = soundtracks,
|
||||||
|
onlyAppIds = shared,
|
||||||
|
)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
if (strictRead) throw e
|
||||||
|
emptyList()
|
||||||
|
}
|
||||||
|
otherGames.forEach { out[it.appId] = it }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return out.values.toList()
|
return out.values.toList()
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun sharedApps(context: Context, arch: String): Set<Int> {
|
internal fun sharedApps(context: Context, arch: String): Set<Int> {
|
||||||
val view = File(LinuxRuntime.rootDir(context), "root/.droiddeck-x64/shared/${if (arch == "x86_64") "arm64" else "x86-64"}/steamapps")
|
val view = File(LinuxRuntime.rootDir(context), "root/.droiddeck-x64/shared/${if (arch == "x86_64") "arm64" else "x86-64"}/steamapps")
|
||||||
return view.list().orEmpty().mapNotNull { Regex("appmanifest_(\\d+)\\.acf").matchEntire(it)?.groupValues?.get(1)?.toIntOrNull() }.toSet()
|
val entries = view.list()
|
||||||
|
if (entries == null) {
|
||||||
|
if (!view.exists()) return emptySet()
|
||||||
|
throw IllegalStateException("Unable to read the shared Steam library.")
|
||||||
|
}
|
||||||
|
return entries.mapNotNull {
|
||||||
|
Regex("appmanifest_(\\d+)\\.acf").matchEntire(it)?.groupValues?.get(1)?.toIntOrNull()
|
||||||
|
}.toSet()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun steamLibraryArt(context: Context): List<Pair<Int, File>> {
|
fun steamLibraryArt(context: Context): List<Pair<Int, File>> {
|
||||||
|
|||||||
@@ -0,0 +1,308 @@
|
|||||||
|
package com.droiddeck.launcher.frontend
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.media.MediaMetadataRetriever
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
object Soundtrack {
|
||||||
|
class Track(
|
||||||
|
val file: File, val title: String, val disc: Int, val number: Int, val durationMs: Long, val artist: String = "",
|
||||||
|
val discLabel: String = disc.toString(),
|
||||||
|
) {
|
||||||
|
val id: String get() = file.path
|
||||||
|
}
|
||||||
|
|
||||||
|
class Album(val disc: Map<Int, List<Track>>, val artist: String, val cover: File?) {
|
||||||
|
val tracks: List<Track> get() = disc.values.flatten()
|
||||||
|
val discs: List<Int> get() = disc.keys.toList()
|
||||||
|
val multiDisc: Boolean get() = disc.size > 1
|
||||||
|
val totalMs: Long get() = tracks.sumOf { it.durationMs }
|
||||||
|
}
|
||||||
|
|
||||||
|
class Raw(
|
||||||
|
val file: File, val folder: String, val tagDisc: Int?, val tagTrack: Int?, val tagTitle: String?, val tagArtist: String?,
|
||||||
|
val durationMs: Long, val size: Long = file.length(),
|
||||||
|
)
|
||||||
|
|
||||||
|
val EXTENSIONS = setOf("mp3", "flac", "ogg", "oga", "opus", "wav", "m4a", "aac")
|
||||||
|
private val LOSSLESS = setOf("flac", "wav")
|
||||||
|
private val COVERS = listOf("AlbumArtwork", "albumartwork", "cover", "Cover", "folder", "Folder", "front", "Front", "artwork", "Artwork")
|
||||||
|
internal val COVER_EXT = listOf("png", "jpg", "jpeg", "webp")
|
||||||
|
private val LEADING = Regex("^\\s*\\d+\\s*[.\\-_)]*\\s+")
|
||||||
|
private val DIGITS = Regex("^\\s*(\\d+)")
|
||||||
|
|
||||||
|
fun isAudio(file: File): Boolean = file.isFile && file.extension.lowercase() in EXTENSIONS
|
||||||
|
|
||||||
|
fun cleanTitle(fileName: String): String {
|
||||||
|
val base = fileName.substringBeforeLast('.', fileName).trim()
|
||||||
|
val tail = if (" - " in base) base.substringAfterLast(" - ") else base
|
||||||
|
val stripped = tail.replace(LEADING, "").trim()
|
||||||
|
return stripped.ifEmpty { tail.ifEmpty { base } }
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun leadingNumber(fileName: String): Int? = DIGITS.find(fileName.substringAfterLast(" - "))?.groupValues?.get(1)?.toIntOrNull()
|
||||||
|
|
||||||
|
private fun identity(r: Raw): String {
|
||||||
|
val d = r.tagDisc
|
||||||
|
val t = r.tagTrack
|
||||||
|
if (d != null && t != null) return "n:$d:$t"
|
||||||
|
val title = (r.tagTitle?.takeIf { it.isNotBlank() } ?: cleanTitle(r.file.name)).lowercase().filter { it.isLetterOrDigit() }
|
||||||
|
return "t:$title:${leadingNumber(r.file.name)}"
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun better(a: Raw, b: Raw): Raw {
|
||||||
|
val la = a.file.extension.lowercase() in LOSSLESS
|
||||||
|
val lb = b.file.extension.lowercase() in LOSSLESS
|
||||||
|
return when {
|
||||||
|
la != lb -> if (la) a else b
|
||||||
|
a.size != b.size -> if (a.size > b.size) a else b
|
||||||
|
else -> if (a.file.path <= b.file.path) a else b
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun group(raws: List<Raw>): Map<Int, List<Track>> {
|
||||||
|
if (raws.isEmpty()) return emptyMap()
|
||||||
|
val unique = LinkedHashMap<String, Raw>()
|
||||||
|
val home = HashMap<String, String>()
|
||||||
|
val disc = HashMap<String, Int>()
|
||||||
|
val track = HashMap<String, Int>()
|
||||||
|
val title = HashMap<String, String>()
|
||||||
|
for (r in raws) {
|
||||||
|
val id = identity(r)
|
||||||
|
unique[id] = unique[id]?.let { better(it, r) } ?: r
|
||||||
|
if (r.folder.isNotEmpty() && home[id].isNullOrEmpty()) home[id] = r.folder
|
||||||
|
r.tagDisc?.let { disc.putIfAbsent(id, it) }
|
||||||
|
r.tagTrack?.let { track.putIfAbsent(id, it) }
|
||||||
|
r.tagTitle?.takeIf { it.isNotBlank() }?.let { title.putIfAbsent(id, it) }
|
||||||
|
}
|
||||||
|
val kept = unique.map { (id, r) ->
|
||||||
|
Raw(
|
||||||
|
r.file, home[id] ?: r.folder, disc[id] ?: r.tagDisc, track[id] ?: r.tagTrack, title[id] ?: r.tagTitle, r.tagArtist,
|
||||||
|
r.durationMs, r.size,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val folders = kept.filter { it.tagDisc == null }.map { it.folder }.distinct().sortedWith(naturalOrder)
|
||||||
|
val discs = kept.groupBy { r ->
|
||||||
|
r.tagDisc ?: if (folders.size <= 1 && kept.none { it.tagDisc != null }) 0 else folders.indexOf(r.folder) + 1
|
||||||
|
}
|
||||||
|
return discs.toSortedMap().mapValues { (disc, list) ->
|
||||||
|
list.sortedWith(
|
||||||
|
compareBy<Raw>({ leadingNumber(it.file.name) ?: it.tagTrack ?: Int.MAX_VALUE }, { it.tagTrack ?: Int.MAX_VALUE }, { it.file.name.lowercase() }),
|
||||||
|
).mapIndexed { i, r ->
|
||||||
|
Track(
|
||||||
|
r.file, r.tagTitle?.takeIf { it.isNotBlank() } ?: cleanTitle(r.file.name), disc, i + 1,
|
||||||
|
r.durationMs, r.tagArtist.orEmpty(), labelOf(r, disc),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val FOLDER_LABEL = Regex("[0-9][0-9 +&,.\\-]*")
|
||||||
|
|
||||||
|
private fun labelOf(r: Raw, disc: Int): String {
|
||||||
|
if (r.tagDisc != null) return disc.toString()
|
||||||
|
val name = r.folder.substringAfterLast('/')
|
||||||
|
return if (FOLDER_LABEL.matches(name)) name else disc.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
private val naturalOrder = Comparator<String> { a, b ->
|
||||||
|
val x = Regex("\\d+|\\D+").findAll(a.lowercase()).map { it.value }.toList()
|
||||||
|
val y = Regex("\\d+|\\D+").findAll(b.lowercase()).map { it.value }.toList()
|
||||||
|
var i = 0
|
||||||
|
var out = 0
|
||||||
|
while (out == 0 && i < minOf(x.size, y.size)) {
|
||||||
|
val nx = x[i].toBigIntegerOrNull()
|
||||||
|
val ny = y[i].toBigIntegerOrNull()
|
||||||
|
out = if (nx != null && ny != null) nx.compareTo(ny) else x[i].compareTo(y[i])
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
if (out != 0) out else x.size.compareTo(y.size)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun cover(dir: File): File? {
|
||||||
|
for (name in COVERS) for (ext in COVER_EXT) File(dir, "$name.$ext").takeIf { it.isFile }?.let { return it }
|
||||||
|
return dir.listFiles()?.filter { it.isFile && it.extension.lowercase() in COVER_EXT }?.minByOrNull { it.name.lowercase() }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseNumber(value: String?): Int? = value?.substringBefore('/')?.trim()?.toIntOrNull()
|
||||||
|
|
||||||
|
private fun read(file: File, root: File): Raw {
|
||||||
|
val folder = file.parentFile?.let { parent ->
|
||||||
|
if (parent.path == root.path) "" else parent.path.removePrefix(root.path).trimStart('/')
|
||||||
|
}.orEmpty()
|
||||||
|
val retriever = MediaMetadataRetriever()
|
||||||
|
return try {
|
||||||
|
retriever.setDataSource(file.path)
|
||||||
|
Raw(
|
||||||
|
file, folder,
|
||||||
|
parseNumber(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DISC_NUMBER)),
|
||||||
|
parseNumber(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CD_TRACK_NUMBER)),
|
||||||
|
retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE),
|
||||||
|
retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST)
|
||||||
|
?: retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST),
|
||||||
|
retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull() ?: 0L,
|
||||||
|
)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Raw(file, folder, null, null, null, null, 0L)
|
||||||
|
} finally {
|
||||||
|
runCatching { retriever.release() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun cacheFile(context: Context, root: File) = File(context.filesDir, "soundtrack-index/${root.path.hashCode().toUInt()}.json")
|
||||||
|
|
||||||
|
private fun fromCache(context: Context, root: File, files: List<File>): List<Raw>? = runCatching {
|
||||||
|
val f = cacheFile(context, root).takeIf { it.isFile } ?: return null
|
||||||
|
val json = JSONObject(f.readText())
|
||||||
|
if (json.optString("root") != root.path) return null
|
||||||
|
val rows = json.getJSONArray("rows")
|
||||||
|
val byPath = HashMap<String, JSONObject>()
|
||||||
|
for (i in 0 until rows.length()) rows.getJSONObject(i).let { byPath[it.getString("p")] = it }
|
||||||
|
if (byPath.size != files.size) return null
|
||||||
|
files.map { file ->
|
||||||
|
val row = byPath[file.path] ?: return null
|
||||||
|
if (row.getLong("s") != file.length() || row.getLong("m") != file.lastModified()) return null
|
||||||
|
Raw(
|
||||||
|
file, row.getString("f"), row.optInt("d", -1).takeIf { it >= 0 }, row.optInt("n", -1).takeIf { it >= 0 },
|
||||||
|
row.optString("t").takeIf { it.isNotEmpty() }, row.optString("a").takeIf { it.isNotEmpty() }, row.optLong("l"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}.getOrNull()
|
||||||
|
|
||||||
|
private fun toCache(context: Context, root: File, raws: List<Raw>) {
|
||||||
|
runCatching {
|
||||||
|
val rows = JSONArray()
|
||||||
|
for (r in raws) rows.put(
|
||||||
|
JSONObject().put("p", r.file.path).put("s", r.file.length()).put("m", r.file.lastModified()).put("f", r.folder)
|
||||||
|
.put("d", r.tagDisc ?: -1).put("n", r.tagTrack ?: -1).put("t", r.tagTitle.orEmpty()).put("a", r.tagArtist.orEmpty())
|
||||||
|
.put("l", r.durationMs),
|
||||||
|
)
|
||||||
|
val f = cacheFile(context, root)
|
||||||
|
f.parentFile?.mkdirs()
|
||||||
|
val tmp = File(f.path + ".tmp")
|
||||||
|
tmp.writeText(JSONObject().put("root", root.path).put("rows", rows).toString())
|
||||||
|
if (!tmp.renameTo(f)) tmp.delete()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun audioFiles(root: File): List<File> {
|
||||||
|
val out = ArrayList<File>()
|
||||||
|
fun walk(dir: File, depth: Int) {
|
||||||
|
val children = dir.listFiles() ?: return
|
||||||
|
for (c in children.sortedBy { it.name.lowercase() }) {
|
||||||
|
if (c.isDirectory) { if (depth < 4) walk(c, depth + 1) } else if (isAudio(c)) out += c
|
||||||
|
}
|
||||||
|
}
|
||||||
|
walk(root, 0)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun coverCache(context: Context, root: File): File {
|
||||||
|
val digest = java.security.MessageDigest.getInstance("SHA-256").digest(root.path.toByteArray(Charsets.UTF_8))
|
||||||
|
val key = digest.take(16).joinToString("") { "%02x".format(it) }
|
||||||
|
return File(context.filesDir, "soundtrack-index/cover-$key.jpg")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun cachedCover(context: Context, root: File): File? = coverCache(context, root).takeIf { it.isFile && it.length() > 0L }
|
||||||
|
|
||||||
|
private fun embeddedBytes(file: File): ByteArray? = runCatching {
|
||||||
|
val retriever = MediaMetadataRetriever()
|
||||||
|
try {
|
||||||
|
retriever.setDataSource(file.path)
|
||||||
|
retriever.embeddedPicture
|
||||||
|
} finally {
|
||||||
|
runCatching { retriever.release() }
|
||||||
|
}
|
||||||
|
}.getOrNull()?.takeIf { it.isNotEmpty() }
|
||||||
|
|
||||||
|
private fun hashOf(bytes: ByteArray): String =
|
||||||
|
java.security.MessageDigest.getInstance("SHA-256").digest(bytes).take(16).joinToString("") { "%02x".format(it) }
|
||||||
|
|
||||||
|
private fun embeddedCover(context: Context, root: File, files: List<File>): File? {
|
||||||
|
cachedCover(context, root)?.let { return it }
|
||||||
|
val miss = File(coverCache(context, root).path + ".none")
|
||||||
|
val probed = files.take(8)
|
||||||
|
val signature = hashOf(probed.joinToString("\n") { "${it.path}|${it.length()}|${it.lastModified()}" }.toByteArray(Charsets.UTF_8))
|
||||||
|
if (runCatching { miss.isFile && miss.readText().trim() == signature }.getOrDefault(false)) return null
|
||||||
|
for (file in probed) {
|
||||||
|
val bytes = embeddedBytes(file) ?: continue
|
||||||
|
val out = coverCache(context, root)
|
||||||
|
runCatching {
|
||||||
|
out.parentFile?.mkdirs()
|
||||||
|
out.writeBytes(bytes)
|
||||||
|
}.onSuccess { return out }
|
||||||
|
}
|
||||||
|
runCatching {
|
||||||
|
miss.parentFile?.mkdirs()
|
||||||
|
miss.writeText(signature)
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun firstCover(context: Context, root: File): File? = cover(root) ?: embeddedCover(context, root, audioFiles(root))
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun trackCover(context: Context, file: File): File? {
|
||||||
|
val dir = File(context.filesDir, "soundtrack-index/track-covers")
|
||||||
|
val marker = File(dir, "t-" + hashOf("${file.path}|${file.length()}|${file.lastModified()}".toByteArray(Charsets.UTF_8)))
|
||||||
|
if (marker.isFile) {
|
||||||
|
val name = runCatching { marker.readText().trim() }.getOrDefault("")
|
||||||
|
if (name.isEmpty()) return null
|
||||||
|
File(dir, name).takeIf { it.isFile && it.length() > 0L }?.let {
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
|
marker.setLastModified(now)
|
||||||
|
it.setLastModified(now)
|
||||||
|
return it
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val bytes = embeddedBytes(file)
|
||||||
|
return runCatching {
|
||||||
|
dir.mkdirs()
|
||||||
|
if (bytes == null) {
|
||||||
|
marker.writeText("")
|
||||||
|
prune(dir, setOf(marker.name))
|
||||||
|
null
|
||||||
|
} else {
|
||||||
|
val out = File(dir, "c-" + hashOf(bytes) + ".jpg")
|
||||||
|
if (!out.isFile || out.length() == 0L) out.writeBytes(bytes)
|
||||||
|
marker.writeText(out.name)
|
||||||
|
prune(dir, setOf(marker.name, out.name))
|
||||||
|
out
|
||||||
|
}
|
||||||
|
}.getOrNull()
|
||||||
|
}
|
||||||
|
|
||||||
|
private const val TRACK_COVER_BYTES = 64L * 1024 * 1024
|
||||||
|
private const val TRACK_COVER_FILES = 2000
|
||||||
|
|
||||||
|
private fun prune(dir: File, keep: Set<String>) {
|
||||||
|
val all = dir.listFiles()?.filter { it.isFile } ?: return
|
||||||
|
var bytes = all.sumOf { it.length() }
|
||||||
|
var count = all.size
|
||||||
|
for (f in all.sortedBy { it.lastModified() }) {
|
||||||
|
if (bytes <= TRACK_COVER_BYTES && count <= TRACK_COVER_FILES) break
|
||||||
|
if (f.name in keep) continue
|
||||||
|
bytes -= f.length()
|
||||||
|
count--
|
||||||
|
f.delete()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun load(context: Context, root: File, coverHint: File? = null): Album {
|
||||||
|
val files = audioFiles(root)
|
||||||
|
val raws = fromCache(context, root, files) ?: files.map { read(it, root) }.also { toCache(context, root, it) }
|
||||||
|
val disc = SoundtrackOrder.apply(context, root, group(raws))
|
||||||
|
val artist = disc.values.flatten().map { it.artist }.filter { it.isNotBlank() }.groupingBy { it }.eachCount().maxByOrNull { it.value }?.key.orEmpty()
|
||||||
|
return Album(disc, artist, coverHint ?: cover(root) ?: embeddedCover(context, root, files))
|
||||||
|
}
|
||||||
|
|
||||||
|
fun formatLength(ms: Long): String {
|
||||||
|
val total = ms / 1000
|
||||||
|
val h = total / 3600
|
||||||
|
val m = (total % 3600) / 60
|
||||||
|
val s = total % 60
|
||||||
|
return if (h > 0) "%d:%02d:%02d".format(h, m, s) else "%d:%02d".format(m, s)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package com.droiddeck.launcher.frontend
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
object SoundtrackCollectionArt {
|
||||||
|
internal fun dir(context: Context, id: Int) = File(context.filesDir, "soundtrack-art/$id")
|
||||||
|
|
||||||
|
private fun sourceFile(context: Context, id: Int) = File(dir(context, id), "source")
|
||||||
|
|
||||||
|
fun chosen(context: Context, id: Int): File? = dir(context, id).takeIf { it.isDirectory }?.let { AddedGameArt.chosen(it, AddedGameArt.Slot.COVER) }
|
||||||
|
|
||||||
|
fun source(context: Context, id: Int): String =
|
||||||
|
sourceFile(context, id).takeIf { it.isFile }?.readText()?.trim().orEmpty().substringAfter('|', "")
|
||||||
|
|
||||||
|
fun options(context: Context, id: Int, root: File?): List<AddedGameArt.Option> {
|
||||||
|
val paths = if (root != null) {
|
||||||
|
val images = root.listFiles()?.filter { it.isFile && it.extension.lowercase() in Soundtrack.COVER_EXT }?.sortedBy { it.name.lowercase() }.orEmpty()
|
||||||
|
(images + listOfNotNull(Soundtrack.firstCover(context, root))).map { it.path }
|
||||||
|
} else SoundtrackCollections.tracksOf(id).map { it.cover }
|
||||||
|
return paths.filter { it.isNotEmpty() && File(it).isFile }.distinct().map { AddedGameArt.Option(AddedGameArt.FOLDER, it, it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun choose(context: Context, id: Int, option: AddedGameArt.Option): Boolean {
|
||||||
|
val folder = dir(context, id)
|
||||||
|
val fresh = AddedGameArt.storeNew(folder, AddedGameArt.Slot.COVER, option) ?: return false
|
||||||
|
AddedGameArt.dropOlder(folder, AddedGameArt.Slot.COVER, fresh)
|
||||||
|
sourceFile(context, id).writeText(option.group + "|" + option.full)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun reset(context: Context, id: Int) {
|
||||||
|
chosen(context, id)?.delete()
|
||||||
|
sourceFile(context, id).delete()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun describe(context: Context, id: Int, root: File? = null): List<AddedGameArt.SlotState> {
|
||||||
|
val own = chosen(context, id)
|
||||||
|
val state = if (own != null) AddedGameArt.SlotState(AddedGameArt.Slot.COVER, own, AddedGameArt.FILE, true)
|
||||||
|
else {
|
||||||
|
val auto = if (root != null) Soundtrack.firstCover(context, root) else SoundtrackCollections.autoCover(id)
|
||||||
|
AddedGameArt.SlotState(AddedGameArt.Slot.COVER, auto, if (auto != null) AddedGameArt.FOLDER else AddedGameArt.AUTO, false)
|
||||||
|
}
|
||||||
|
return listOf(state)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clear(context: Context, id: Int) {
|
||||||
|
dir(context, id).deleteRecursively()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
package com.droiddeck.launcher.frontend
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.File
|
||||||
|
import java.util.concurrent.Executors
|
||||||
|
|
||||||
|
object SoundtrackCollections {
|
||||||
|
const val FAVORITES_ID = 2_000_000_000
|
||||||
|
|
||||||
|
class TrackRef(val path: String, val title: String, val artist: String, val album: String, val durationMs: Long, val cover: String = "")
|
||||||
|
class Collection(val id: Int, val name: String, val tracks: List<TrackRef>)
|
||||||
|
class Snapshot(val favorites: List<TrackRef>, val collections: List<Collection>)
|
||||||
|
|
||||||
|
private val state = mutableStateOf(Snapshot(emptyList(), emptyList()))
|
||||||
|
private var loaded = false
|
||||||
|
private val writer = Executors.newSingleThreadExecutor { r -> Thread(r, "soundtrack-collections").apply { isDaemon = true } }
|
||||||
|
|
||||||
|
val snapshot: Snapshot get() = state.value
|
||||||
|
|
||||||
|
private fun file(context: Context) = File(context.filesDir, "soundtrack-collections.json")
|
||||||
|
|
||||||
|
internal fun toggled(list: List<TrackRef>, ref: TrackRef): List<TrackRef> =
|
||||||
|
if (list.any { it.path == ref.path }) list.filterNot { it.path == ref.path } else list + ref
|
||||||
|
|
||||||
|
internal fun merged(list: List<TrackRef>, add: List<TrackRef>): List<TrackRef> {
|
||||||
|
val have = list.mapTo(HashSet()) { it.path }
|
||||||
|
return list + add.filter { have.add(it.path) }
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun cleanName(raw: String): String = raw.trim().replace(Regex("\\s+"), " ")
|
||||||
|
|
||||||
|
internal fun nameTaken(collections: List<Collection>, name: String, except: Int? = null): Boolean =
|
||||||
|
collections.any { it.id != except && it.name.equals(name, ignoreCase = true) }
|
||||||
|
|
||||||
|
internal fun nextId(collections: List<Collection>): Int =
|
||||||
|
(collections.maxOfOrNull { it.id } ?: FAVORITES_ID).coerceAtLeast(FAVORITES_ID) + 1
|
||||||
|
|
||||||
|
private fun encode(s: Snapshot): String {
|
||||||
|
fun refs(list: List<TrackRef>) = JSONArray().also { array ->
|
||||||
|
list.forEach {
|
||||||
|
array.put(
|
||||||
|
JSONObject().put("path", it.path).put("title", it.title).put("artist", it.artist).put("album", it.album)
|
||||||
|
.put("duration", it.durationMs).put("cover", it.cover),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val collections = JSONArray()
|
||||||
|
s.collections.forEach { collections.put(JSONObject().put("id", it.id).put("name", it.name).put("tracks", refs(it.tracks))) }
|
||||||
|
return JSONObject().put("favorites", refs(s.favorites)).put("collections", collections).toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun decode(text: String): Snapshot {
|
||||||
|
fun refs(array: JSONArray?): List<TrackRef> = if (array == null) emptyList() else List(array.length()) { i ->
|
||||||
|
array.getJSONObject(i).let {
|
||||||
|
TrackRef(it.getString("path"), it.optString("title"), it.optString("artist"), it.optString("album"), it.optLong("duration"), it.optString("cover"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val root = JSONObject(text)
|
||||||
|
val collections = root.optJSONArray("collections")
|
||||||
|
return Snapshot(
|
||||||
|
refs(root.optJSONArray("favorites")),
|
||||||
|
if (collections == null) emptyList() else List(collections.length()) { i ->
|
||||||
|
collections.getJSONObject(i).let { Collection(it.getInt("id"), it.getString("name"), refs(it.optJSONArray("tracks"))) }
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun load(context: Context) {
|
||||||
|
if (loaded) return
|
||||||
|
loaded = true
|
||||||
|
val f = file(context)
|
||||||
|
if (f.isFile) runCatching { state.value = decode(f.readText()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun commit(context: Context, next: Snapshot) {
|
||||||
|
state.value = next
|
||||||
|
val f = file(context)
|
||||||
|
val json = encode(next)
|
||||||
|
writer.execute {
|
||||||
|
runCatching {
|
||||||
|
val tmp = File(f.path + ".tmp")
|
||||||
|
tmp.writeText(json)
|
||||||
|
if (!tmp.renameTo(f)) tmp.delete()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun tracksOf(id: Int): List<TrackRef> =
|
||||||
|
if (id == FAVORITES_ID) snapshot.favorites else snapshot.collections.firstOrNull { it.id == id }?.tracks.orEmpty()
|
||||||
|
|
||||||
|
fun isFavorite(path: String): Boolean = snapshot.favorites.any { it.path == path }
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun toggleFavorite(context: Context, ref: TrackRef) {
|
||||||
|
load(context)
|
||||||
|
val s = snapshot
|
||||||
|
commit(context, Snapshot(toggled(s.favorites, ref), s.collections))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun create(context: Context, rawName: String, tracks: List<TrackRef>): Int? {
|
||||||
|
load(context)
|
||||||
|
val s = snapshot
|
||||||
|
val name = cleanName(rawName)
|
||||||
|
if (name.isEmpty() || nameTaken(s.collections, name)) return null
|
||||||
|
val id = nextId(s.collections)
|
||||||
|
commit(context, Snapshot(s.favorites, s.collections + Collection(id, name, merged(emptyList(), tracks))))
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun rename(context: Context, id: Int, rawName: String): Boolean {
|
||||||
|
load(context)
|
||||||
|
val s = snapshot
|
||||||
|
val name = cleanName(rawName)
|
||||||
|
if (id == FAVORITES_ID || name.isEmpty() || nameTaken(s.collections, name, id)) return false
|
||||||
|
commit(context, Snapshot(s.favorites, s.collections.map { if (it.id == id) Collection(id, name, it.tracks) else it }))
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun delete(context: Context, id: Int) {
|
||||||
|
load(context)
|
||||||
|
val s = snapshot
|
||||||
|
if (id == FAVORITES_ID) return
|
||||||
|
commit(context, Snapshot(s.favorites, s.collections.filterNot { it.id == id }))
|
||||||
|
SoundtrackCollectionArt.clear(context, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun add(context: Context, id: Int, tracks: List<TrackRef>) {
|
||||||
|
load(context)
|
||||||
|
val s = snapshot
|
||||||
|
if (id == FAVORITES_ID) commit(context, Snapshot(merged(s.favorites, tracks), s.collections))
|
||||||
|
else commit(context, Snapshot(s.favorites, s.collections.map { if (it.id == id) Collection(id, it.name, merged(it.tracks, tracks)) else it }))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun remove(context: Context, id: Int, paths: Set<String>) {
|
||||||
|
load(context)
|
||||||
|
val s = snapshot
|
||||||
|
if (id == FAVORITES_ID) commit(context, Snapshot(s.favorites.filterNot { it.path in paths }, s.collections))
|
||||||
|
else commit(context, Snapshot(s.favorites, s.collections.map { if (it.id == id) Collection(id, it.name, it.tracks.filterNot { t -> t.path in paths }) else it }))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun reorder(context: Context, id: Int, ordered: List<String>) {
|
||||||
|
load(context)
|
||||||
|
val s = snapshot
|
||||||
|
fun arrange(list: List<TrackRef>): List<TrackRef> {
|
||||||
|
val byPath = list.associateBy { it.path }
|
||||||
|
val placed = ordered.mapNotNull { byPath[it] }
|
||||||
|
val named = ordered.toSet()
|
||||||
|
val rest = list.filter { it.path !in named }
|
||||||
|
return placed + rest
|
||||||
|
}
|
||||||
|
if (id == FAVORITES_ID) commit(context, Snapshot(arrange(s.favorites), s.collections))
|
||||||
|
else commit(context, Snapshot(s.favorites, s.collections.map { if (it.id == id) Collection(id, it.name, arrange(it.tracks)) else it }))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun refresh() {
|
||||||
|
state.value = Snapshot(state.value.favorites, state.value.collections)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun autoCover(id: Int): File? = coverOf(tracksOf(id))
|
||||||
|
|
||||||
|
private fun coverOf(tracks: List<TrackRef>): File? =
|
||||||
|
tracks.firstNotNullOfOrNull { t -> t.cover.takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile } }
|
||||||
|
|
||||||
|
private fun game(context: Context, id: Int, name: String, tracks: List<TrackRef>): Library.SteamGame = Library.SteamGame(
|
||||||
|
appId = id, name = name, art = SoundtrackCollectionArt.chosen(context, id) ?: coverOf(tracks), library = Library.ADDED, gameId = id.toLong(),
|
||||||
|
source = Library.SOURCE_COLLECTION, soundtrack = true,
|
||||||
|
)
|
||||||
|
|
||||||
|
fun games(context: Context, favoritesLabel: String): List<Library.SteamGame> {
|
||||||
|
val s = snapshot
|
||||||
|
return listOf(game(context, FAVORITES_ID, favoritesLabel, s.favorites)) + s.collections.map { game(context, it.id, it.name, it.tracks) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun album(context: Context, id: Int): Soundtrack.Album {
|
||||||
|
val tracks = tracksOf(id).filter { File(it.path).isFile }.mapIndexed { i, t ->
|
||||||
|
Soundtrack.Track(File(t.path), t.title, 1, i + 1, t.durationMs, t.artist)
|
||||||
|
}
|
||||||
|
return Soundtrack.Album(mapOf(1 to tracks), "", SoundtrackCollectionArt.chosen(context, id))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package com.droiddeck.launcher.frontend
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
|
||||||
|
object SoundtrackIndex {
|
||||||
|
class Hit(val ref: SoundtrackCollections.TrackRef, val game: Library.SteamGame)
|
||||||
|
|
||||||
|
private var cacheKey = ""
|
||||||
|
private var cache: List<Hit> = emptyList()
|
||||||
|
|
||||||
|
private fun fingerprint(dir: java.io.File?): Long =
|
||||||
|
if (dir == null) 0L else Soundtrack.audioFiles(dir).fold(17L) { h, f -> 31 * (31 * (31 * h + f.path.hashCode()) + f.length()) + f.lastModified() }
|
||||||
|
|
||||||
|
fun build(context: Context, games: List<Library.SteamGame>): List<Hit> {
|
||||||
|
val roots = games.filter { it.gameFiles != null }
|
||||||
|
val key = roots.joinToString("|") { "${it.appId}:${it.gameFiles?.path}:${it.art?.path}:${fingerprint(it.gameFiles)}" }
|
||||||
|
synchronized(this) { if (key == cacheKey) return cache }
|
||||||
|
val hits = roots.flatMap { g ->
|
||||||
|
val dir = g.gameFiles ?: return@flatMap emptyList()
|
||||||
|
val album = Soundtrack.load(context, dir, g.art)
|
||||||
|
val cover = (g.art ?: album.cover)?.path.orEmpty()
|
||||||
|
album.tracks.map { t ->
|
||||||
|
Hit(SoundtrackCollections.TrackRef(t.file.path, t.title, t.artist.ifBlank { album.artist }, g.name, t.durationMs, cover), g)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
synchronized(this) {
|
||||||
|
cacheKey = key
|
||||||
|
cache = hits
|
||||||
|
}
|
||||||
|
return hits
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package com.droiddeck.launcher.frontend
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.compose.runtime.mutableIntStateOf
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.File
|
||||||
|
import java.util.concurrent.Executors
|
||||||
|
|
||||||
|
object SoundtrackOrder {
|
||||||
|
private val changes = mutableIntStateOf(0)
|
||||||
|
private var cache: Map<String, List<String>>? = null
|
||||||
|
private val writer = Executors.newSingleThreadExecutor { r -> Thread(r, "soundtrack-order").apply { isDaemon = true } }
|
||||||
|
|
||||||
|
val version: Int get() = changes.intValue
|
||||||
|
|
||||||
|
private fun file(context: Context) = File(context.filesDir, "soundtrack-order.json")
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
private fun read(context: Context): Map<String, List<String>> {
|
||||||
|
cache?.let { return it }
|
||||||
|
val out = HashMap<String, List<String>>()
|
||||||
|
val f = file(context)
|
||||||
|
if (f.isFile) runCatching {
|
||||||
|
val json = JSONObject(f.readText())
|
||||||
|
for (key in json.keys()) {
|
||||||
|
val array = json.getJSONArray(key)
|
||||||
|
out[key] = List(array.length()) { array.getString(it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cache = out
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun set(context: Context, root: File, paths: List<String>) {
|
||||||
|
val next = HashMap(read(context))
|
||||||
|
next[root.path] = paths
|
||||||
|
cache = next
|
||||||
|
val body = JSONObject().also { json -> next.forEach { (k, v) -> json.put(k, JSONArray(v)) } }.toString()
|
||||||
|
val target = file(context)
|
||||||
|
writer.execute {
|
||||||
|
val tmp = File(target.path + ".tmp")
|
||||||
|
runCatching {
|
||||||
|
tmp.writeText(body)
|
||||||
|
if (!tmp.renameTo(target)) tmp.delete()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
changes.intValue++
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun ordered(disc: Map<Int, List<Soundtrack.Track>>, order: List<String>): Map<Int, List<Soundtrack.Track>> {
|
||||||
|
if (order.isEmpty()) return disc
|
||||||
|
val index = HashMap<String, Int>()
|
||||||
|
order.forEachIndexed { i, p -> index.putIfAbsent(p, i) }
|
||||||
|
return disc.mapValues { (_, list) ->
|
||||||
|
list.sortedBy { index[it.file.path] ?: Int.MAX_VALUE }.mapIndexed { i, t ->
|
||||||
|
Soundtrack.Track(t.file, t.title, t.disc, i + 1, t.durationMs, t.artist, t.discLabel)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun apply(context: Context, root: File, disc: Map<Int, List<Soundtrack.Track>>): Map<Int, List<Soundtrack.Track>> {
|
||||||
|
val order = read(context)[root.path] ?: return disc
|
||||||
|
return ordered(disc, order)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package com.droiddeck.launcher.frontend
|
||||||
|
|
||||||
|
import android.app.Activity
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.pm.ShortcutInfo
|
||||||
|
import android.content.pm.ShortcutManager
|
||||||
|
import android.graphics.drawable.Icon
|
||||||
|
import android.net.Uri
|
||||||
|
import android.widget.Toast
|
||||||
|
import com.droiddeck.launcher.FrontEndActivity
|
||||||
|
import com.droiddeck.launcher.LauncherIcon
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
|
|
||||||
|
object SoundtrackShortcuts {
|
||||||
|
private val linkPattern = Regex("droiddeck://soundtrack/(-?[0-9]{1,11})")
|
||||||
|
|
||||||
|
fun uri(appId: Int): String = "droiddeck://soundtrack/$appId"
|
||||||
|
|
||||||
|
fun parse(link: String?): Int? = link?.let { linkPattern.matchEntire(it)?.groupValues?.get(1)?.toIntOrNull() }
|
||||||
|
|
||||||
|
fun read(intent: Intent): Int? = if (intent.action == Intent.ACTION_VIEW) parse(intent.dataString) else null
|
||||||
|
|
||||||
|
private fun info(context: Context, game: Library.SteamGame): ShortcutInfo {
|
||||||
|
val name = game.name.ifBlank { context.getString(R.string.app_name) }
|
||||||
|
val icon = GameShortcuts.iconBitmap(game)?.let(Icon::createWithBitmap) ?: Icon.createWithResource(context, R.mipmap.ic_launcher)
|
||||||
|
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uri(game.appId)), context, FrontEndActivity::class.java)
|
||||||
|
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||||
|
return ShortcutInfo.Builder(context, "soundtrack:${game.appId}")
|
||||||
|
.setActivity(LauncherIcon.activity(context))
|
||||||
|
.setShortLabel(name.take(40)).setLongLabel(name).setIcon(icon).setIntent(intent).build()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun pin(activity: Activity, game: Library.SteamGame) {
|
||||||
|
val manager = activity.getSystemService(ShortcutManager::class.java)
|
||||||
|
val requested = runCatching {
|
||||||
|
manager.isRequestPinShortcutSupported && manager.requestPinShortcut(info(activity, game), null)
|
||||||
|
}.getOrDefault(false)
|
||||||
|
if (!requested) Toast.makeText(activity, R.string.game_shortcut_unsupported, Toast.LENGTH_LONG).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package com.droiddeck.launcher.frontend
|
||||||
|
|
||||||
|
object SoundtrackTracks {
|
||||||
|
enum class Sort { DEFAULT, TITLE_ASC, TITLE_DESC, LONGEST, SHORTEST }
|
||||||
|
|
||||||
|
fun <T> sort(items: List<T>, sort: Sort, title: (T) -> String, duration: (T) -> Long): List<T> = when (sort) {
|
||||||
|
Sort.DEFAULT -> items
|
||||||
|
Sort.TITLE_ASC -> items.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER, title))
|
||||||
|
Sort.TITLE_DESC -> items.sortedWith(compareByDescending(String.CASE_INSENSITIVE_ORDER, title))
|
||||||
|
Sort.LONGEST -> items.sortedByDescending(duration)
|
||||||
|
Sort.SHORTEST -> items.sortedBy(duration)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun matches(query: String, vararg fields: String): Boolean {
|
||||||
|
val words = query.trim().lowercase().split(' ').filter { it.isNotEmpty() }
|
||||||
|
if (words.isEmpty()) return true
|
||||||
|
val haystack = fields.map { it.lowercase() }
|
||||||
|
return words.all { word -> haystack.any { it.contains(word) } }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun rank(query: String, title: String): Int {
|
||||||
|
val q = query.trim().lowercase()
|
||||||
|
val t = title.lowercase()
|
||||||
|
return when {
|
||||||
|
t == q -> 0
|
||||||
|
t.startsWith(q) -> 1
|
||||||
|
else -> 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -24,11 +24,7 @@ object SteamGameArt {
|
|||||||
val icon = chosenFile(context, game.appId, AddedGameArt.Slot.ICON)
|
val icon = chosenFile(context, game.appId, AddedGameArt.Slot.ICON)
|
||||||
val logo = chosenFile(context, game.appId, AddedGameArt.Slot.LOGO)
|
val logo = chosenFile(context, game.appId, AddedGameArt.Slot.LOGO)
|
||||||
if (cover == null && hero == null && icon == null && logo == null) return game
|
if (cover == null && hero == null && icon == null && logo == null) return game
|
||||||
return Library.SteamGame(
|
return game.withArt(cover ?: game.art, hero ?: game.hero, icon ?: game.icon, logo ?: game.logo)
|
||||||
game.appId, game.name, cover ?: game.art, game.library, game.gameId,
|
|
||||||
hero ?: game.hero, game.lastPlayed, game.gameFiles, game.protonPrefix, icon ?: game.icon, game.source, game.storeId,
|
|
||||||
logo ?: game.logo,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun chosenSource(context: Context, appId: Int, slot: AddedGameArt.Slot): Pair<String, String> {
|
fun chosenSource(context: Context, appId: Int, slot: AddedGameArt.Slot): Pair<String, String> {
|
||||||
|
|||||||
@@ -563,7 +563,7 @@ object Glasses {
|
|||||||
val device = selected?.first
|
val device = selected?.first
|
||||||
val m = selected?.second
|
val m = selected?.second
|
||||||
val controllable = m?.let(::canOpenModel) == true
|
val controllable = m?.let(::canOpenModel) == true
|
||||||
val permitted = controllable && device != null && (m === XrealModel || usb.hasPermission(device))
|
val permitted = controllable && device != null && (m is XrealModel || usb.hasPermission(device))
|
||||||
val identity = device?.let {
|
val identity = device?.let {
|
||||||
GlassesModeState.Device(it.productId, if (permitted) runCatching { it.serialNumber }.getOrNull() else null)
|
GlassesModeState.Device(it.productId, if (permitted) runCatching { it.serialNumber }.getOrNull() else null)
|
||||||
}
|
}
|
||||||
@@ -614,9 +614,9 @@ object Glasses {
|
|||||||
sbs = sbsByDisplay,
|
sbs = sbsByDisplay,
|
||||||
switching3d = modeState.pendingStereo,
|
switching3d = modeState.pendingStereo,
|
||||||
brightnessMax = m?.brightnessMax ?: 8, volumeMax = m?.volumeMax ?: 8,
|
brightnessMax = m?.brightnessMax ?: 8, volumeMax = m?.volumeMax ?: 8,
|
||||||
sunblock = if (m === XrealModel) it.sunblock else _settings.value.sunblock ?: it.sunblock,
|
sunblock = if (m is XrealModel) it.sunblock else _settings.value.sunblock ?: it.sunblock,
|
||||||
hardwareControls = m?.hardwareControls == true &&
|
hardwareControls = m?.hardwareControls == true &&
|
||||||
(device?.vendorId == VitureProtocol.VENDOR_ID || m === XrealModel || m is RokidModel),
|
(device?.vendorId == VitureProtocol.VENDOR_ID || m is XrealModel || m is RokidModel),
|
||||||
supportsDisplayModeControl = m?.supportsDisplayModeControl == true,
|
supportsDisplayModeControl = m?.supportsDisplayModeControl == true,
|
||||||
hasSunblock = m?.hasSunblock == true,
|
hasSunblock = m?.hasSunblock == true,
|
||||||
diagonalFovDeg = m?.diagonalFovDeg ?: 46f,
|
diagonalFovDeg = m?.diagonalFovDeg ?: 46f,
|
||||||
@@ -624,7 +624,7 @@ object Glasses {
|
|||||||
noSignal = noSignal,
|
noSignal = noSignal,
|
||||||
sbs90 = m?.sbs90 == true,
|
sbs90 = m?.sbs90 == true,
|
||||||
rates2d = m?.rates2d ?: listOf(60, 90, 120),
|
rates2d = m?.rates2d ?: listOf(60, 90, 120),
|
||||||
experimental = m === XrealModel || (m is VitureProtocol.Model && m.family == VitureProtocol.Family.PRO2 && !m.needsSdk),
|
experimental = m is XrealModel || (m is VitureProtocol.Model && m.family == VitureProtocol.Family.PRO2 && !m.needsSdk),
|
||||||
supportsScreen3dof = link?.hasImu == true,
|
supportsScreen3dof = link?.hasImu == true,
|
||||||
supports30Hz = display?.let(::supports30Hz) == true,
|
supports30Hz = display?.let(::supports30Hz) == true,
|
||||||
supportsSpatial = (link as? VitureSdkLink)?.isCarina == true,
|
supportsSpatial = (link as? VitureSdkLink)?.isCarina == true,
|
||||||
@@ -660,8 +660,8 @@ object Glasses {
|
|||||||
else VitureSdk.marketName(device.productId)?.let(VitureProtocol::sdkModel)
|
else VitureSdk.marketName(device.productId)?.let(VitureProtocol::sdkModel)
|
||||||
?: VitureProtocol.model(device.productId, name)
|
?: VitureProtocol.model(device.productId, name)
|
||||||
}
|
}
|
||||||
else if (XrealModel.matches(device.vendorId, device.productId)) XrealModel
|
else XrealModel.model(device.vendorId, device.productId)
|
||||||
else RokidModel.model(device.vendorId, device.productId, name)
|
?: RokidModel.model(device.vendorId, device.productId, name)
|
||||||
?: RayNeoModel.model(device.vendorId, device.productId, name)
|
?: RayNeoModel.model(device.vendorId, device.productId, name)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -729,8 +729,8 @@ object Glasses {
|
|||||||
VitureSdkLink.open(usb, device, File(app.noBackupFilesDir, "viture"), sdkListener(generation),
|
VitureSdkLink.open(usb, device, File(app.noBackupFilesDir, "viture"), sdkListener(generation),
|
||||||
(model as? VitureProtocol.Model)?.family, spatial)
|
(model as? VitureProtocol.Model)?.family, spatial)
|
||||||
} else VitureLink.open(usb, device, linkListener(generation))
|
} else VitureLink.open(usb, device, linkListener(generation))
|
||||||
} else if (model === XrealModel) {
|
} else if (model is XrealModel) {
|
||||||
XrealLink.open(app, xrealListener(generation))
|
XrealLink.open(app, model as XrealModel, xrealListener(generation))
|
||||||
} else if (model is RokidModel) {
|
} else if (model is RokidModel) {
|
||||||
RokidLink.open(usb, device, rokidListener(generation))
|
RokidLink.open(usb, device, rokidListener(generation))
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import java.util.concurrent.atomic.AtomicReference
|
|||||||
internal class XrealLink internal constructor(
|
internal class XrealLink internal constructor(
|
||||||
private val connector: XrealConnector,
|
private val connector: XrealConnector,
|
||||||
private val listener: Listener,
|
private val listener: Listener,
|
||||||
|
private val model: XrealModel = XrealModel.ONE_S,
|
||||||
) : GlassesLink {
|
) : GlassesLink {
|
||||||
interface Listener {
|
interface Listener {
|
||||||
fun onReady()
|
fun onReady()
|
||||||
@@ -29,7 +30,8 @@ internal class XrealLink internal constructor(
|
|||||||
private val worker = Thread(::run, "xreal-control").apply { isDaemon = true; start() }
|
private val worker = Thread(::run, "xreal-control").apply { isDaemon = true; start() }
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
fun open(context: Context, listener: Listener) = XrealLink(AndroidXrealConnector(context), listener)
|
fun open(context: Context, model: XrealModel, listener: Listener) =
|
||||||
|
XrealLink(AndroidXrealConnector(context), listener, model)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun send(msgId: Int, payload: ByteArray): Boolean {
|
override fun send(msgId: Int, payload: ByteArray): Boolean {
|
||||||
@@ -43,9 +45,10 @@ internal class XrealLink internal constructor(
|
|||||||
if (msgId == VitureProtocol.MSG_GET_IMU) return true
|
if (msgId == VitureProtocol.MSG_GET_IMU) return true
|
||||||
val valid = when (msgId) {
|
val valid = when (msgId) {
|
||||||
VitureProtocol.MSG_GET_DISPLAY -> true
|
VitureProtocol.MSG_GET_DISPLAY -> true
|
||||||
VitureProtocol.MSG_DISPLAY -> value in 2..5 || value == XrealModel.NATIVE_60HZ
|
VitureProtocol.MSG_DISPLAY -> if (model.stereoOnlyControl) value == 5 || value == XrealModel.NATIVE_60HZ
|
||||||
VitureProtocol.MSG_BRIGHTNESS -> value in 0..9
|
else value in 2..5 || value == XrealModel.NATIVE_60HZ
|
||||||
VitureProtocol.MSG_FILM -> value in 0..1
|
VitureProtocol.MSG_BRIGHTNESS -> !model.stereoOnlyControl && value in 0..9
|
||||||
|
VitureProtocol.MSG_FILM -> !model.stereoOnlyControl && value in 0..1
|
||||||
else -> false
|
else -> false
|
||||||
}
|
}
|
||||||
return valid && commands.offer(Command(msgId, value))
|
return valid && commands.offer(Command(msgId, value))
|
||||||
@@ -61,12 +64,12 @@ internal class XrealLink internal constructor(
|
|||||||
channels = connector.connect()
|
channels = connector.connect()
|
||||||
connection.set(channels)
|
connection.set(channels)
|
||||||
if (!running) break
|
if (!running) break
|
||||||
val control = XrealControl(channels)
|
val control = XrealControl(channels, stereoOnly = model.stereoOnlyControl)
|
||||||
listener.onValue(VitureProtocol.MSG_GET_DISPLAY, control.display())
|
listener.onValue(VitureProtocol.MSG_GET_DISPLAY, control.display())
|
||||||
val current = channels
|
val current = channels
|
||||||
reports = Thread({
|
reports = Thread({
|
||||||
try {
|
try {
|
||||||
var filter = XrealOrientationFilter()
|
var filter = XrealOrientationFilter(model.flipsYz)
|
||||||
var wasTracking = false
|
var wasTracking = false
|
||||||
var lastSensor = System.nanoTime()
|
var lastSensor = System.nanoTime()
|
||||||
while (running && connection.get() === current) {
|
while (running && connection.get() === current) {
|
||||||
@@ -75,7 +78,7 @@ internal class XrealLink internal constructor(
|
|||||||
if (sample != null) {
|
if (sample != null) {
|
||||||
lastSensor = System.nanoTime()
|
lastSensor = System.nanoTime()
|
||||||
val enabled = tracking
|
val enabled = tracking
|
||||||
if (enabled && !wasTracking) filter = XrealOrientationFilter()
|
if (enabled && !wasTracking) filter = XrealOrientationFilter(model.flipsYz)
|
||||||
wasTracking = enabled
|
wasTracking = enabled
|
||||||
if (enabled) filter.update(sample)?.let {
|
if (enabled) filter.update(sample)?.let {
|
||||||
if (running && ready && tracking && connection.get() === current)
|
if (running && ready && tracking && connection.get() === current)
|
||||||
@@ -149,7 +152,11 @@ internal class XrealLink internal constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal class XrealControl(private val channels: XrealChannels, private val settleDelayMs: Long = 150) {
|
internal class XrealControl(
|
||||||
|
private val channels: XrealChannels,
|
||||||
|
private val settleDelayMs: Long = 150,
|
||||||
|
private val stereoOnly: Boolean = false,
|
||||||
|
) {
|
||||||
private var transaction = 0
|
private var transaction = 0
|
||||||
private fun exchange(command: Int, value: Int? = null): ByteArray {
|
private fun exchange(command: Int, value: Int? = null): ByteArray {
|
||||||
transaction = if (transaction == Int.MAX_VALUE) 1 else transaction + 1
|
transaction = if (transaction == Int.MAX_VALUE) 1 else transaction + 1
|
||||||
@@ -163,26 +170,42 @@ internal class XrealControl(private val channels: XrealChannels, private val set
|
|||||||
throw IOException("XREAL control response was not received")
|
throw IOException("XREAL control response was not received")
|
||||||
}
|
}
|
||||||
fun display(): Int {
|
fun display(): Int {
|
||||||
|
if (stereoOnly) return stereoDisplay()
|
||||||
val reply = exchange(XrealProtocol.GET_DISPLAY)
|
val reply = exchange(XrealProtocol.GET_DISPLAY)
|
||||||
return XrealProtocol.numeric(reply)?.takeIf { it in 2..5 || it == XrealModel.NATIVE_60HZ }
|
return XrealProtocol.numeric(reply)?.takeIf { it in 2..5 || it == XrealModel.NATIVE_60HZ }
|
||||||
?: throw IOException("Unsupported XREAL display response: ${reply.take(32).joinToString("") { "%02x".format(it) }}")
|
?: throw IOException("Unsupported XREAL display response: ${reply.take(32).joinToString("") { "%02x".format(it) }}")
|
||||||
}
|
}
|
||||||
|
private fun stereoDisplay(): Int {
|
||||||
|
val reply = exchange(XrealProtocol.GET_INPUT)
|
||||||
|
return when {
|
||||||
|
XrealProtocol.acknowledged(reply) -> XrealModel.NATIVE_60HZ
|
||||||
|
else -> when (XrealProtocol.numeric(reply)) {
|
||||||
|
0 -> XrealModel.NATIVE_60HZ
|
||||||
|
1 -> 5
|
||||||
|
else -> throw IOException("Unsupported XREAL stereo response: ${reply.take(32).joinToString("") { "%02x".format(it) }}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
fun changeDisplay(mode: Int): Int {
|
fun changeDisplay(mode: Int): Int {
|
||||||
val stereo = mode == 5
|
val stereo = mode == 5
|
||||||
set(XrealProtocol.SET_INPUT, if (stereo) 1 else 0)
|
set(XrealProtocol.SET_INPUT, if (stereo) 1 else 0)
|
||||||
val current = awaitDisplay { (it == 5) == stereo }
|
val current = awaitDisplay { (it == 5) == stereo }
|
||||||
if (current == mode) return current
|
if (current == mode || stereoOnly) return current
|
||||||
set(XrealProtocol.SET_DISPLAY, mode)
|
set(XrealProtocol.SET_DISPLAY, mode)
|
||||||
return awaitDisplay { it == mode }
|
return awaitDisplay { it == mode }
|
||||||
}
|
}
|
||||||
private fun awaitDisplay(matches: (Int) -> Boolean): Int {
|
private fun awaitDisplay(matches: (Int) -> Boolean): Int {
|
||||||
val deadline = System.nanoTime() + 8_000_000_000L
|
val deadline = System.nanoTime() + 8_000_000_000L
|
||||||
repeat(40) {
|
repeat(40) {
|
||||||
val reply = exchange(XrealProtocol.GET_DISPLAY)
|
if (stereoOnly) {
|
||||||
val value = XrealProtocol.numeric(reply)
|
stereoDisplay().let { if (matches(it)) return it }
|
||||||
if (value != null && matches(value)) return value
|
} else {
|
||||||
if (value == null && !XrealProtocol.acknowledged(reply))
|
val reply = exchange(XrealProtocol.GET_DISPLAY)
|
||||||
throw IOException("Invalid XREAL display transition response")
|
val value = XrealProtocol.numeric(reply)
|
||||||
|
if (value != null && matches(value)) return value
|
||||||
|
if (value == null && !XrealProtocol.acknowledged(reply))
|
||||||
|
throw IOException("Invalid XREAL display transition response")
|
||||||
|
}
|
||||||
if (System.nanoTime() > deadline) throw IOException("XREAL display transition timed out")
|
if (System.nanoTime() > deadline) throw IOException("XREAL display transition timed out")
|
||||||
Thread.sleep(settleDelayMs)
|
Thread.sleep(settleDelayMs)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,25 +1,63 @@
|
|||||||
package com.droiddeck.launcher.glasses
|
package com.droiddeck.launcher.glasses
|
||||||
|
|
||||||
object XrealModel : GlassesModel {
|
internal class XrealModel private constructor(
|
||||||
const val VENDOR_ID = 0x3318
|
override val name: String,
|
||||||
const val PRODUCT_1S = 0x043e
|
val family: Family,
|
||||||
const val NATIVE_60HZ = 29
|
override val diagonalFovDeg: Float,
|
||||||
override val name = "XREAL 1S"
|
) : GlassesModel {
|
||||||
|
enum class Family {
|
||||||
|
ONE_S,
|
||||||
|
ONE,
|
||||||
|
AURA,
|
||||||
|
}
|
||||||
|
|
||||||
override val controllable = true
|
override val controllable = true
|
||||||
override val brightnessMax = 9
|
override val brightnessMax = 9
|
||||||
override val volumeMax = 0
|
override val volumeMax = 0
|
||||||
override val hasSunblock = true
|
override val hasSunblock get() = family == Family.ONE_S
|
||||||
override val diagonalFovDeg = 52f
|
override val hardwareControls get() = family == Family.ONE_S
|
||||||
override val sbs90 = false
|
override val sbs90 = false
|
||||||
|
override val rates2d get() = if (family == Family.ONE_S) super.rates2d else listOf(60)
|
||||||
|
|
||||||
fun matches(vid: Int, pid: Int) = vid == VENDOR_ID && pid == PRODUCT_1S
|
// Only the 1S has been exercised with SET_DISPLAY; the Aura is known to reboot on an unexpected index.
|
||||||
fun isDisplay(name: String) = name.contains("XREAL", ignoreCase = true)
|
val stereoOnlyControl get() = family != Family.ONE_S
|
||||||
|
|
||||||
|
// The Aura reports x right, y up, z back; the rest of the One family is a half turn about x from it.
|
||||||
|
val flipsYz get() = family != Family.AURA
|
||||||
|
|
||||||
override fun mode(hz: Int, sbs: Boolean) = when {
|
override fun mode(hz: Int, sbs: Boolean) = when {
|
||||||
sbs -> 5
|
sbs -> 5
|
||||||
|
stereoOnlyControl -> NATIVE_60HZ
|
||||||
hz >= 120 -> 4
|
hz >= 120 -> 4
|
||||||
hz >= 90 -> 3
|
hz >= 90 -> 3
|
||||||
else -> NATIVE_60HZ
|
else -> NATIVE_60HZ
|
||||||
}
|
}
|
||||||
override fun modeForStep(step: Int): Int? = null
|
override fun modeForStep(step: Int): Int? = null
|
||||||
|
|
||||||
|
override fun toString() = name
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val VENDOR_ID = 0x3318
|
||||||
|
const val PRODUCT_1S = 0x043e
|
||||||
|
const val NATIVE_60HZ = 29
|
||||||
|
|
||||||
|
val ONE_S = XrealModel("XREAL 1S", Family.ONE_S, 52f)
|
||||||
|
val ONE = XrealModel("XREAL One", Family.ONE, 50f)
|
||||||
|
val ONE_PRO = XrealModel("XREAL One Pro", Family.ONE, 57f)
|
||||||
|
val ONE_PRO_PLUS = XrealModel("XREAL One Pro+", Family.ONE, 57f)
|
||||||
|
val AURA = XrealModel("XREAL Aura", Family.AURA, 70f)
|
||||||
|
|
||||||
|
// The odd product ids one below these are the glasses' recovery mode.
|
||||||
|
private val products = mapOf(
|
||||||
|
PRODUCT_1S to ONE_S,
|
||||||
|
0x0438 to ONE,
|
||||||
|
0x0436 to ONE_PRO,
|
||||||
|
0x0444 to ONE_PRO_PLUS,
|
||||||
|
0x043a to AURA,
|
||||||
|
)
|
||||||
|
|
||||||
|
fun model(vid: Int, pid: Int): XrealModel? = if (vid == VENDOR_ID) products[pid] else null
|
||||||
|
fun matches(vid: Int, pid: Int) = model(vid, pid) != null
|
||||||
|
fun isDisplay(name: String) = name.contains("XREAL", ignoreCase = true)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -2,12 +2,13 @@ package com.droiddeck.launcher.glasses
|
|||||||
|
|
||||||
import kotlin.math.abs
|
import kotlin.math.abs
|
||||||
|
|
||||||
internal class XrealOrientationFilter {
|
internal class XrealOrientationFilter(private val flipYz: Boolean = true) {
|
||||||
private val fusion = ImuFusion()
|
private val fusion = ImuFusion()
|
||||||
|
|
||||||
fun update(sample: XrealProtocol.Sample): FloatArray? = fusion.update(sample.timeNs,
|
fun update(sample: XrealProtocol.Sample): FloatArray? = fusion.update(sample.timeNs,
|
||||||
Vec3(sample.accel.x, -sample.accel.y, -sample.accel.z),
|
sample.accel.headAxes(), sample.gyro.headAxes())
|
||||||
Vec3(sample.gyro.x, -sample.gyro.y, -sample.gyro.z))
|
|
||||||
|
private fun Vec3.headAxes() = if (flipYz) Vec3(x, -y, -z) else this
|
||||||
}
|
}
|
||||||
|
|
||||||
internal class ImuFusion {
|
internal class ImuFusion {
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ internal object XrealProtocol {
|
|||||||
const val REPORT = 0x2836
|
const val REPORT = 0x2836
|
||||||
const val GET_DISPLAY = 0x275e
|
const val GET_DISPLAY = 0x275e
|
||||||
const val SET_DISPLAY = 0x275f
|
const val SET_DISPLAY = 0x275f
|
||||||
|
const val GET_INPUT = 0x2821
|
||||||
const val SET_INPUT = 0x2822
|
const val SET_INPUT = 0x2822
|
||||||
const val SET_BRIGHTNESS = 0x271c
|
const val SET_BRIGHTNESS = 0x271c
|
||||||
const val SET_DIMMER = 0x2727
|
const val SET_DIMMER = 0x2727
|
||||||
|
|||||||
@@ -145,16 +145,22 @@ object DeviceInfo {
|
|||||||
private fun drivers(context: Context, gpu: GpuInfo) = Section("Drivers DroidDeck uses", buildList<Pair<String, String>> {
|
private fun drivers(context: Context, gpu: GpuInfo) = Section("Drivers DroidDeck uses", buildList<Pair<String, String>> {
|
||||||
add("Driver mode", SessionPrefs.gpuDriverMode(context))
|
add("Driver mode", SessionPrefs.gpuDriverMode(context))
|
||||||
val turnip = TurnipDriver(context)
|
val turnip = TurnipDriver(context)
|
||||||
val choice = SessionPrefs.androidDriver(context).ifEmpty { turnip.autoId() }
|
val choice = turnip.effectiveId()
|
||||||
val powerVr = gpu.family == GpuInfo.Family.POWERVR
|
val powerVr = gpu.family == GpuInfo.Family.POWERVR
|
||||||
add("Display driver", if (choice == "system") builtinDriverLabel(powerVr, runtime = false)
|
add("Display driver", if (choice == "system") builtinDriverLabel(powerVr, runtime = false)
|
||||||
else "${turnip.displayName(choice)} ${turnip.driverVersion(choice)}".trim())
|
else "${turnip.displayName(choice)} ${turnip.driverVersion(choice)}".trim())
|
||||||
val linux = LinuxVulkanDriverManager(context)
|
val linux = LinuxVulkanDriverManager(context)
|
||||||
val id = SessionPrefs.linuxDriver(context)
|
val id = SessionPrefs.linuxDriver(context)
|
||||||
add("Game driver", if (id.isEmpty()) builtinDriverLabel(powerVr, runtime = true) else "${linux.getDriverName(id)} ${linux.getDriverVersion(id)}".trim())
|
add("Game driver", hostRoute(context) ?: if (id.isEmpty()) builtinDriverLabel(powerVr, runtime = true) else "${linux.getDriverName(id)} ${linux.getDriverVersion(id)}".trim())
|
||||||
if (gpu.oneUi8Gen2) add("Note", "One UI on an 8 Gen 2: needs the OneUI Turnip build")
|
if (gpu.oneUi8Gen2) add("Note", "One UI on an 8 Gen 2: needs the OneUI Turnip build")
|
||||||
})
|
})
|
||||||
|
|
||||||
|
internal fun hostRoute(context: Context): String? = when {
|
||||||
|
com.droiddeck.launcher.session.VenusComponent.wanted(context) -> "Mali (Venus)"
|
||||||
|
com.droiddeck.launcher.core.DeviceSupport.vkBridge(context) -> "the Mali bridge"
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
|
||||||
/** Shared by the device card and the session report, which are written in English. */
|
/** Shared by the device card and the session report, which are written in English. */
|
||||||
internal fun builtinDriverLabel(powerVr: Boolean, runtime: Boolean): String = when {
|
internal fun builtinDriverLabel(powerVr: Boolean, runtime: Boolean): String = when {
|
||||||
powerVr -> "System PowerVR"
|
powerVr -> "System PowerVR"
|
||||||
|
|||||||
@@ -28,12 +28,38 @@ object FrameGen {
|
|||||||
|
|
||||||
fun engine(context: Context): String = mode(context).engine
|
fun engine(context: Context): String = mode(context).engine
|
||||||
|
|
||||||
fun mode(context: Context): Mode {
|
fun mode(context: Context): Mode = mode(context, null)
|
||||||
|
|
||||||
|
fun mode(context: Context, appId: String?): Mode {
|
||||||
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||||
val engine = prefs.getString("engine", ENGINE_OFF).let { if (it == LEGACY_ENGINE_WINFG) ENGINE_DDFG else it ?: ENGINE_OFF }
|
val gamePrefix = appId?.takeIf { it.isNotBlank() }?.let { "game.$it." }
|
||||||
val target = prefs.getInt("target", 0)
|
?.takeIf { prefs.contains(it + "engine") } ?: ""
|
||||||
|
val engine = prefs.getString(gamePrefix + "engine", ENGINE_OFF)
|
||||||
|
.let { if (it == LEGACY_ENGINE_WINFG) ENGINE_DDFG else it ?: ENGINE_OFF }
|
||||||
|
val target = prefs.getInt(gamePrefix + "target", 0)
|
||||||
if (engine == ENGINE_LSFG && target in ADAPTIVE_TARGETS) return Mode(engine, target = target)
|
if (engine == ENGINE_LSFG && target in ADAPTIVE_TARGETS) return Mode(engine, target = target)
|
||||||
return Mode(engine, prefs.getInt("multiplier", 2).coerceIn(2, 4))
|
return Mode(engine, prefs.getInt(gamePrefix + "multiplier", 2).coerceIn(2, 4))
|
||||||
|
}
|
||||||
|
|
||||||
|
fun hasGameOverride(context: Context, appId: String): Boolean =
|
||||||
|
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).contains("game.$appId.engine")
|
||||||
|
|
||||||
|
fun setForGame(context: Context, appId: String, mode: Mode) {
|
||||||
|
val prefix = "game.$appId."
|
||||||
|
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
|
||||||
|
.putString(prefix + "engine", mode.engine)
|
||||||
|
.putInt(prefix + "multiplier", mode.multiplier)
|
||||||
|
.putInt(prefix + "target", mode.target)
|
||||||
|
.apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clearGame(context: Context, appId: String) {
|
||||||
|
val prefix = "game.$appId."
|
||||||
|
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
|
||||||
|
.remove(prefix + "engine")
|
||||||
|
.remove(prefix + "multiplier")
|
||||||
|
.remove(prefix + "target")
|
||||||
|
.apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun set(context: Context, mode: Mode) {
|
fun set(context: Context, mode: Mode) {
|
||||||
@@ -41,6 +67,11 @@ object FrameGen {
|
|||||||
.putString("engine", mode.engine).putInt("multiplier", mode.multiplier).putInt("target", mode.target).apply()
|
.putString("engine", mode.engine).putInt("multiplier", mode.multiplier).putInt("target", mode.target).apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun clearGlobal(context: Context) {
|
||||||
|
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
|
||||||
|
.remove("engine").remove("multiplier").remove("target").apply()
|
||||||
|
}
|
||||||
|
|
||||||
fun label(context: Context): String = label(context, mode(context))
|
fun label(context: Context): String = label(context, mode(context))
|
||||||
|
|
||||||
fun label(context: Context, mode: Mode): String = when {
|
fun label(context: Context, mode: Mode): String = when {
|
||||||
@@ -50,14 +81,32 @@ object FrameGen {
|
|||||||
else -> context.getString(R.string.frame_gen_off)
|
else -> context.getString(R.string.frame_gen_off)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun apply(context: Context, refreshHz: Float): String? = apply(context, mode(context), refreshHz)
|
data class PreparedApply internal constructor(
|
||||||
|
val mode: Mode,
|
||||||
|
internal val lsfgStatus: Int? = null,
|
||||||
|
internal val lsfgCachePath: String? = null,
|
||||||
|
)
|
||||||
|
|
||||||
fun apply(context: Context, mode: Mode, refreshHz: Float): String? {
|
fun prepareApply(context: Context, mode: Mode): PreparedApply {
|
||||||
|
if (mode.engine != ENGINE_LSFG) return PreparedApply(mode)
|
||||||
|
val status = Lossless.sync(context)
|
||||||
|
val cachePath = Lossless.cacheFile(context)?.absolutePath
|
||||||
|
return PreparedApply(mode, status, cachePath)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun apply(context: Context, refreshHz: Float): String? =
|
||||||
|
apply(context, mode(context), refreshHz)
|
||||||
|
|
||||||
|
fun apply(context: Context, mode: Mode, refreshHz: Float): String? =
|
||||||
|
applyPrepared(context, prepareApply(context, mode), refreshHz)
|
||||||
|
|
||||||
|
fun applyPrepared(context: Context, prepared: PreparedApply, refreshHz: Float): String? {
|
||||||
|
val mode = prepared.mode
|
||||||
when (mode.engine) {
|
when (mode.engine) {
|
||||||
ENGINE_LSFG -> {
|
ENGINE_LSFG -> {
|
||||||
val status = Lossless.sync(context)
|
val status = prepared.lsfgStatus ?: LsfgNative.STATUS_NOT_INSTALLED
|
||||||
val cache = Lossless.cacheFile(context)
|
val cachePath = prepared.lsfgCachePath
|
||||||
if (status != LsfgNative.STATUS_OK || cache == null) {
|
if (status != LsfgNative.STATUS_OK || cachePath == null) {
|
||||||
WaylandCompositor.nativeSetFrameGenArmed(false, 0, 0)
|
WaylandCompositor.nativeSetFrameGenArmed(false, 0, 0)
|
||||||
val problem = context.getString(
|
val problem = context.getString(
|
||||||
if (status == LsfgNative.STATUS_NOT_INSTALLED) R.string.lsfg_problem_missing else R.string.lsfg_problem_failed,
|
if (status == LsfgNative.STATUS_NOT_INSTALLED) R.string.lsfg_problem_missing else R.string.lsfg_problem_failed,
|
||||||
@@ -66,7 +115,7 @@ object FrameGen {
|
|||||||
return problem
|
return problem
|
||||||
}
|
}
|
||||||
WaylandCompositor.nativeSetFrameGenEngine(WaylandCompositor.FG_ENGINE_LSFG)
|
WaylandCompositor.nativeSetFrameGenEngine(WaylandCompositor.FG_ENGINE_LSFG)
|
||||||
WaylandCompositor.nativeSetLsfgCachePath(cache.absolutePath)
|
WaylandCompositor.nativeSetLsfgCachePath(cachePath)
|
||||||
WaylandCompositor.nativeSetFrameGenTuning(FLOW_SCALE_LSFG, refreshHz)
|
WaylandCompositor.nativeSetFrameGenTuning(FLOW_SCALE_LSFG, refreshHz)
|
||||||
WaylandCompositor.nativeSetFrameGenArmed(true, mode.multiplier, mode.target)
|
WaylandCompositor.nativeSetFrameGenArmed(true, mode.multiplier, mode.target)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,6 +34,8 @@ public final class TurnipDriver {
|
|||||||
public static final List<String> BUNDLED = Collections.unmodifiableList(Arrays.asList(
|
public static final List<String> BUNDLED = Collections.unmodifiableList(Arrays.asList(
|
||||||
DRIVER_A7XX, DRIVER_A8XX, com.droiddeck.launcher.session.QuestExperimental.DRIVER,
|
DRIVER_A7XX, DRIVER_A8XX, com.droiddeck.launcher.session.QuestExperimental.DRIVER,
|
||||||
DRIVER_A6XX, com.droiddeck.launcher.session.QuestExperimental.DRIVER_A6XX));
|
DRIVER_A6XX, com.droiddeck.launcher.session.QuestExperimental.DRIVER_A6XX));
|
||||||
|
private static final String KGSL_NODE = "/dev/kgsl-3d0";
|
||||||
|
private static final String KGSL_SYSFS = "/sys/class/kgsl/kgsl-3d0";
|
||||||
private static final String OVERRIDE_FILE = "Download/droiddeck-driver";
|
private static final String OVERRIDE_FILE = "Download/droiddeck-driver";
|
||||||
private static final String PREFS = "graphics_driver";
|
private static final String PREFS = "graphics_driver";
|
||||||
private static final String KEY_HIDDEN = "hiddenBundled";
|
private static final String KEY_HIDDEN = "hiddenBundled";
|
||||||
@@ -140,6 +142,25 @@ public final class TurnipDriver {
|
|||||||
return id == null ? "system" : id;
|
return id == null ? "system" : id;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String effectiveId() {
|
||||||
|
String id = choose();
|
||||||
|
return id == null || !reachesGpu(id) ? "system" : id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean reachesGpu(String driverId) {
|
||||||
|
String library = libraryName(driverId);
|
||||||
|
return library == null || !needsMissingKgsl(new File(new File(contentDir, driverId), library),
|
||||||
|
kgslPresent(new File(KGSL_NODE), new File(KGSL_SYSFS)));
|
||||||
|
}
|
||||||
|
|
||||||
|
static boolean kgslPresent(File node, File sysfs) {
|
||||||
|
return node.exists() || sysfs.exists();
|
||||||
|
}
|
||||||
|
|
||||||
|
static boolean needsMissingKgsl(File library, boolean kgsl) {
|
||||||
|
return !kgsl && library.isFile() && LinuxVulkanDriverManager.containsAscii(library, KGSL_NODE);
|
||||||
|
}
|
||||||
|
|
||||||
public void remove(String driverId) {
|
public void remove(String driverId) {
|
||||||
if (driverId == null || driverId.isEmpty() || BUNDLED.contains(driverId)
|
if (driverId == null || driverId.isEmpty() || BUNDLED.contains(driverId)
|
||||||
|| driverId.contains("/") || driverId.contains("..")) return;
|
|| driverId.contains("/") || driverId.contains("..")) return;
|
||||||
@@ -257,6 +278,11 @@ public final class TurnipDriver {
|
|||||||
Log.e(TAG, id + " unpacked without " + library);
|
Log.e(TAG, id + " unpacked without " + library);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
if (!reachesGpu(id)) {
|
||||||
|
Log.w(TAG, id + " needs " + KGSL_NODE + ", which this GPU does not have; display on the system Vulkan loader");
|
||||||
|
DriverSetupLog.write(context, "install.no-kgsl driver=" + id);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
Log.i(TAG, "graphics driver " + id + " (" + library + ")");
|
Log.i(TAG, "graphics driver " + id + " (" + library + ")");
|
||||||
DriverSetupLog.write(context, "install.ready driver=" + id + " library=" + library);
|
DriverSetupLog.write(context, "install.ready driver=" + id + " library=" + library);
|
||||||
return id;
|
return id;
|
||||||
@@ -282,6 +308,12 @@ public final class TurnipDriver {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (chosen != null && !chosen.isEmpty()) {
|
if (chosen != null && !chosen.isEmpty()) {
|
||||||
|
if (SessionPrefs.GPU_DRIVERS_AUTO.equals(SessionPrefs.INSTANCE.gpuDriverMode(context))
|
||||||
|
&& SessionPrefs.INSTANCE.gpuAutoInstalled(context).contains(chosen)
|
||||||
|
&& gpuDetector.get().getFamily() == GpuInfo.Family.A7XX_LOW) {
|
||||||
|
Log.i(TAG, "Auto-selected display driver does not cover Adreno 710/720/722; leaving the display driver to the system");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
if (BUNDLED.contains(chosen)) {
|
if (BUNDLED.contains(chosen)) {
|
||||||
Log.i(TAG, "driver pinned by the user: " + chosen);
|
Log.i(TAG, "driver pinned by the user: " + chosen);
|
||||||
return chosen;
|
return chosen;
|
||||||
@@ -318,6 +350,10 @@ public final class TurnipDriver {
|
|||||||
Log.i(TAG, "not an Adreno GPU; leaving the display driver to the system");
|
Log.i(TAG, "not an Adreno GPU; leaving the display driver to the system");
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
if (gpu.getFamily() == GpuInfo.Family.A7XX_LOW) {
|
||||||
|
Log.i(TAG, "no bundled display driver covers Adreno 710/720/722; leaving the display driver to the system");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
int model = gpu.getModel();
|
int model = gpu.getModel();
|
||||||
Log.i(TAG, "gpu model: " + (model == 0 ? "unknown" : model));
|
Log.i(TAG, "gpu model: " + (model == 0 ? "unknown" : model));
|
||||||
return chooseByModel(model, android.os.Build.VERSION.SDK_INT);
|
return chooseByModel(model, android.os.Build.VERSION.SDK_INT);
|
||||||
|
|||||||
@@ -7,15 +7,21 @@ internal object DroidDeckHudConfig {
|
|||||||
val DEFAULTS: Map<String, String> = linkedMapOf(
|
val DEFAULTS: Map<String, String> = linkedMapOf(
|
||||||
"hudSize" to "minimal", "hudLocked" to "1", "hudSnap" to "1", "hudScale" to "100", "hudDock" to "none", "hudOpacity" to "80", "hudColor" to "mid",
|
"hudSize" to "minimal", "hudLocked" to "1", "hudSnap" to "1", "hudScale" to "100", "hudDock" to "none", "hudOpacity" to "80", "hudColor" to "mid",
|
||||||
"hudOutline" to "40", "hudOutlineAccent" to "1",
|
"hudOutline" to "40", "hudOutlineAccent" to "1",
|
||||||
"showFPS" to "1", "showFPSGraph" to "1", "showCPUUsage" to "1", "showCPULoad" to "1", "showGPULoad" to "1",
|
"showGpuModel" to "1", "showGPULoad" to "1", "showCPUUsage" to "1", "showCPULoad" to "1",
|
||||||
"showVram" to "1", "showRAM" to "1", "showPower" to "1", "showTemp" to "1", "showBatteryTemp" to "1",
|
"showPerCore" to "1", "showTemp" to "1", "showBatteryTemp" to "1", "showGpuTemp" to "0",
|
||||||
"showGpuTemp" to "0", "showBattery" to "0", "showLow1" to "1", "showLow01" to "1", "showLow001" to "1", "fpsDecimal" to "1", "showPerCore" to "1",
|
"showVram" to "1", "showRAM" to "1", "showSwap" to "1", "showBattery" to "0", "showBatteryTime" to "0", "showPower" to "1",
|
||||||
"showSwap" to "1", "showNet" to "1", "showResolution" to "1", "showProton" to "1", "showSession" to "1",
|
"showFPS" to "1", "showFPSGraph" to "1", "fpsDecimal" to "1",
|
||||||
"showClock" to "1", "showEngine" to "1", "showRenderer" to "1", "showGpuModel" to "1",
|
"showLatency" to "1", "showAvg" to "1", "showLow1" to "1", "showLow01" to "1", "showLow001" to "1",
|
||||||
|
"showEngine" to "1", "showRenderer" to "1",
|
||||||
|
"showDisplay" to "1", "showHdr" to "1", "showNet" to "1", "showResolution" to "1",
|
||||||
|
"showProton" to "1", "showSession" to "1", "showClock" to "1", "hudOrder" to "",
|
||||||
"tempUnit" to "c", "tempBands" to "1", "tempAuto" to "1", "tempRedCpu" to "90", "tempRedGpu" to "90", "tempRedBat" to "48",
|
"tempUnit" to "c", "tempBands" to "1", "tempAuto" to "1", "tempRedCpu" to "90", "tempRedGpu" to "90", "tempRedBat" to "48",
|
||||||
)
|
)
|
||||||
|
|
||||||
private val TWINS = mapOf("showCPUUsage" to "showCPULoad", "showTemp" to "showBatteryTemp", "showEngine" to "showRenderer")
|
private val NOT_READINGS = setOf("showCPULoad", "showRenderer", "fpsDecimal")
|
||||||
|
|
||||||
|
/** Orders saved before the GPU switch was named after the alias the HUD actually reads. */
|
||||||
|
private val RENAMED = mapOf("showGPU" to "showGPULoad")
|
||||||
|
|
||||||
fun load(context: Context): MutableMap<String, String> {
|
fun load(context: Context): MutableMap<String, String> {
|
||||||
val values = LinkedHashMap(DEFAULTS)
|
val values = LinkedHashMap(DEFAULTS)
|
||||||
@@ -36,7 +42,31 @@ internal object DroidDeckHudConfig {
|
|||||||
val values = load(context)
|
val values = load(context)
|
||||||
if (key !in DEFAULTS) return values
|
if (key !in DEFAULTS) return values
|
||||||
values[key] = value
|
values[key] = value
|
||||||
TWINS[key]?.let { values[it] = value }
|
SessionPrefs.setDroidDeckHudConfig(context, encode(values))
|
||||||
|
return values
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Writes several switches and the row order in one go, so the HUD is rebuilt once. */
|
||||||
|
fun choose(context: Context, switches: Map<String, Boolean>, order: List<String>): Map<String, String> {
|
||||||
|
val values = load(context)
|
||||||
|
for ((key, on) in switches) if (key in DEFAULTS) {
|
||||||
|
values[key] = flag(on)
|
||||||
|
}
|
||||||
|
val size = DroidDeckHudSize.from(values["hudSize"])
|
||||||
|
val groups = sizeOrders(values).toMutableMap()
|
||||||
|
if (groups.isEmpty()) {
|
||||||
|
val legacy = legacyOrder(values)
|
||||||
|
if (legacy.isNotEmpty()) for (each in DroidDeckHudSize.values()) groups[each] = legacy.filter { it in each.rows }
|
||||||
|
}
|
||||||
|
groups[size] = order.filter { it in ORDER }
|
||||||
|
values["hudOrder"] = encodeOrders(groups)
|
||||||
|
SessionPrefs.setDroidDeckHudConfig(context, encode(values))
|
||||||
|
return values
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clearOrder(context: Context): Map<String, String> {
|
||||||
|
val values = load(context)
|
||||||
|
values["hudOrder"] = ""
|
||||||
SessionPrefs.setDroidDeckHudConfig(context, encode(values))
|
SessionPrefs.setDroidDeckHudConfig(context, encode(values))
|
||||||
return values
|
return values
|
||||||
}
|
}
|
||||||
@@ -46,5 +76,37 @@ internal object DroidDeckHudConfig {
|
|||||||
return DEFAULTS
|
return DEFAULTS
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Every metric switch, in the order the HUD lists them before the user moves any. Derived from
|
||||||
|
* [DEFAULTS], so a switch added there shows up here without a second list to keep in step. */
|
||||||
|
val ORDER: List<String> = DEFAULTS.keys.filter { it.startsWith("show") && it !in NOT_READINGS }
|
||||||
|
|
||||||
|
/** Only the rows the user moved for [size], in the order they left them. */
|
||||||
|
fun storedOrder(values: Map<String, String>, size: DroidDeckHudSize): List<String> =
|
||||||
|
sizeOrders(values)[size] ?: legacyOrder(values)
|
||||||
|
|
||||||
|
/** Orders saved before each size kept its own: one list, applied to every size. */
|
||||||
|
private fun legacyOrder(values: Map<String, String>): List<String> {
|
||||||
|
val raw = values["hudOrder"].orEmpty()
|
||||||
|
if (raw.isBlank() || raw.contains(':')) return emptyList()
|
||||||
|
return raw.split('|').map { RENAMED[it] ?: it }.filter { it in ORDER }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sizeOrders(values: Map<String, String>): Map<DroidDeckHudSize, List<String>> {
|
||||||
|
val raw = values["hudOrder"].orEmpty()
|
||||||
|
if (raw.isBlank()) return emptyMap()
|
||||||
|
val groups = LinkedHashMap<DroidDeckHudSize, List<String>>()
|
||||||
|
for (group in raw.split(';')) {
|
||||||
|
val colon = group.indexOf(':')
|
||||||
|
if (colon <= 0) continue
|
||||||
|
val size = DroidDeckHudSize.values().firstOrNull { it.token == group.substring(0, colon) } ?: continue
|
||||||
|
groups[size] = group.substring(colon + 1).split('|').map { RENAMED[it] ?: it }.filter { it in ORDER }
|
||||||
|
}
|
||||||
|
return groups
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun encodeOrders(groups: Map<DroidDeckHudSize, List<String>>): String =
|
||||||
|
groups.entries.filter { it.value.isNotEmpty() }
|
||||||
|
.joinToString(";") { "${it.key.token}:${it.value.joinToString("|")}" }
|
||||||
|
|
||||||
private fun flag(on: Boolean) = if (on) "1" else "0"
|
private fun flag(on: Boolean) = if (on) "1" else "0"
|
||||||
}
|
}
|
||||||
@@ -10,11 +10,9 @@ import android.view.View
|
|||||||
import android.view.animation.PathInterpolator
|
import android.view.animation.PathInterpolator
|
||||||
import android.view.ViewGroup
|
import android.view.ViewGroup
|
||||||
import android.widget.FrameLayout
|
import android.widget.FrameLayout
|
||||||
import com.droiddeck.launcher.gpu.FrameGen
|
|
||||||
import com.droiddeck.launcher.gpu.GpuInfo
|
import com.droiddeck.launcher.gpu.GpuInfo
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
import com.droiddeck.launcher.session.SessionPrefs
|
||||||
import com.droiddeck.launcher.session.SessionService
|
|
||||||
import com.droiddeck.launcher.session.SessionState
|
import com.droiddeck.launcher.session.SessionState
|
||||||
import com.droiddeck.launcher.ui.Motion
|
import com.droiddeck.launcher.ui.Motion
|
||||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||||
@@ -24,7 +22,7 @@ import kotlin.math.roundToInt
|
|||||||
class DroidDeckHudHost(context: Context) {
|
class DroidDeckHudHost(context: Context) {
|
||||||
private val context = context.applicationContext
|
private val context = context.applicationContext
|
||||||
private val handler = Handler(Looper.getMainLooper())
|
private val handler = Handler(Looper.getMainLooper())
|
||||||
private val feed = GameFrameFeed(File(LinuxRuntime.rootDir(this.context), HudFrames.PATH))
|
private val feed = GameFrameFeed.forRoot(LinuxRuntime.rootDir(this.context))
|
||||||
private val readings = MangoReadings(File(this.context.filesDir, "session"), LinuxRuntime.rootDir(this.context))
|
private val readings = MangoReadings(File(this.context.filesDir, "session"), LinuxRuntime.rootDir(this.context))
|
||||||
private var view: DroidDeckHudView? = null
|
private var view: DroidDeckHudView? = null
|
||||||
private var parent: ViewGroup? = null
|
private var parent: ViewGroup? = null
|
||||||
@@ -39,6 +37,8 @@ class DroidDeckHudHost(context: Context) {
|
|||||||
private var snapping = false
|
private var snapping = false
|
||||||
private var previewFade: ValueAnimator? = null
|
private var previewFade: ValueAnimator? = null
|
||||||
private var flingX = 0f
|
private var flingX = 0f
|
||||||
|
private var flingY = 0f
|
||||||
|
private var throwSpring: com.droiddeck.launcher.ui.FlingSpring? = null
|
||||||
private var engine = ""
|
private var engine = ""
|
||||||
private var gpuName = ""
|
private var gpuName = ""
|
||||||
private var protonPid = 0
|
private var protonPid = 0
|
||||||
@@ -95,18 +95,22 @@ class DroidDeckHudHost(context: Context) {
|
|||||||
stopMotion(hud)
|
stopMotion(hud)
|
||||||
shrinkPastEdge(hud, rawX, rawY)
|
shrinkPastEdge(hud, rawX, rawY)
|
||||||
}
|
}
|
||||||
hud.setOnFlungListener { vx, _ -> flingX = vx }
|
hud.setOnFlungListener { vx, vy -> flingX = vx; flingY = vy }
|
||||||
hud.setOnTabDraggedListener { x, y -> dragTab(hud, x, y) }
|
hud.setOnTabDraggedListener { x, y -> dragTab(hud, x, y) }
|
||||||
hud.setOnTabDroppedListener { dropTab(hud) }
|
hud.setOnTabDroppedListener { dropTab(hud) }
|
||||||
hud.setOnTabDragCancelledListener { snapping = false; keepOnScreen(hud) }
|
hud.setOnTabDragCancelledListener { snapping = false; keepOnScreen(hud) }
|
||||||
hud.setOnMovedListener { x, y ->
|
hud.setOnMovedListener { x, y ->
|
||||||
wantX = x; wantY = y
|
wantX = x; wantY = y
|
||||||
val vx = flingX
|
val vx = flingX
|
||||||
|
val vy = flingY
|
||||||
flingX = 0f
|
flingX = 0f
|
||||||
dockEdgeFor(hud)?.let { edge -> setDock(hud, edge); return@setOnMovedListener }
|
flingY = 0f
|
||||||
|
// A throw only carries the strip into its tab; a floating HUD flung across goes to the other side.
|
||||||
|
val coast = hud.isStrip
|
||||||
|
dockEdgeFor(hud, if (coast) vx else 0f, if (coast) vy else 0f)?.let { edge -> setDock(hud, edge); return@setOnMovedListener }
|
||||||
stopMotion(hud)
|
stopMotion(hud)
|
||||||
fadeDockPreview(hud)
|
fadeDockPreview(hud)
|
||||||
if (snaps && !hud.isStrip) { snapToAnchor(hud, vx); return@setOnMovedListener }
|
if (snaps && !hud.isStrip) { snapToAnchor(hud, vx, vy); return@setOnMovedListener }
|
||||||
val fromX = hud.x; val fromY = hud.y
|
val fromX = hud.x; val fromY = hud.y
|
||||||
keepOnScreen(hud)
|
keepOnScreen(hud)
|
||||||
wantX = hud.x; wantY = hud.y
|
wantX = hud.x; wantY = hud.y
|
||||||
@@ -179,9 +183,8 @@ class DroidDeckHudHost(context: Context) {
|
|||||||
private fun applyShown() {
|
private fun applyShown() {
|
||||||
if (!running) return
|
if (!running) return
|
||||||
val show = !hidden && !backgrounded
|
val show = !hidden && !backgrounded
|
||||||
val visible = show && SessionState.mode != SessionService.MODE_DESKTOP
|
view?.visibility = if (show) View.VISIBLE else View.GONE
|
||||||
view?.visibility = if (visible) View.VISIBLE else View.GONE
|
showing = show
|
||||||
showing = visible
|
|
||||||
if (show != polling) {
|
if (show != polling) {
|
||||||
polling = show
|
polling = show
|
||||||
if (show) Choreographer.getInstance().postFrameCallback(frameCallback)
|
if (show) Choreographer.getInstance().postFrameCallback(frameCallback)
|
||||||
@@ -238,28 +241,36 @@ class DroidDeckHudHost(context: Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun presentedFps(): Float {
|
private fun presentedFps(): Float {
|
||||||
if (FrameGen.mode(context).engine == FrameGen.ENGINE_OFF) return 0f
|
if (!runCatching { WaylandCompositor.nativeFrameGenActive() }
|
||||||
val stats = runCatching { WaylandCompositor.nativeFrameGenStats() }.getOrNull() ?: return 0f
|
.getOrDefault(false)) return 0f
|
||||||
|
|
||||||
|
val stats = runCatching {
|
||||||
|
WaylandCompositor.nativeFrameGenStats()
|
||||||
|
}.getOrNull() ?: return 0f
|
||||||
|
|
||||||
return if (stats.size > 3 && stats[3] > 1f) stats[3] else 0f
|
return if (stats.size > 3 && stats[3] > 1f) stats[3] else 0f
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun dockEdgeFor(v: View): DroidDeckHudDock? {
|
/** The edge the HUD tucks into: one it hangs far enough over, or would once a throw at [vx], [vy] coasts out. */
|
||||||
val over = overhang(v) ?: return null
|
private fun dockEdgeFor(v: View, vx: Float = 0f, vy: Float = 0f): DroidDeckHudDock? {
|
||||||
|
val over = overhang(v, vx * com.droiddeck.launcher.ui.EdgeFling.COAST_S, vy * com.droiddeck.launcher.ui.EdgeFling.COAST_S) ?: return null
|
||||||
return over.key.takeIf { over.value >= DOCK_OVERHANG }
|
return over.key.takeIf { over.value >= DOCK_OVERHANG }
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun overhang(v: View): Map.Entry<DroidDeckHudDock, Float>? {
|
private fun overhang(v: View, dx: Float = 0f, dy: Float = 0f): Map.Entry<DroidDeckHudDock, Float>? {
|
||||||
val p = v.parent as? View ?: return null
|
val p = v.parent as? View ?: return null
|
||||||
if (p.width <= 0 || p.height <= 0 || v.width <= 0 || v.height <= 0) return null
|
if (p.width <= 0 || p.height <= 0 || v.width <= 0 || v.height <= 0) return null
|
||||||
val strip = (v as? DroidDeckHudView)?.isStrip == true
|
val strip = (v as? DroidDeckHudView)?.isStrip == true
|
||||||
val density = v.resources.displayMetrics.density
|
val density = v.resources.displayMetrics.density
|
||||||
val w = if (strip) minOf(v.width.toFloat(), STRIP_PULL_ACROSS_DP * density) else v.width.toFloat()
|
val w = if (strip) minOf(v.width.toFloat(), STRIP_PULL_ACROSS_DP * density) else v.width.toFloat()
|
||||||
val h = if (strip) maxOf(v.height.toFloat(), STRIP_PULL_OFF_DP * density) else v.height.toFloat()
|
val h = if (strip) maxOf(v.height.toFloat(), STRIP_PULL_OFF_DP * density) else v.height.toFloat()
|
||||||
|
val x = v.x + dx
|
||||||
|
val y = v.y + dy
|
||||||
return mapOf(
|
return mapOf(
|
||||||
DroidDeckHudDock.LEFT to -v.x / w,
|
DroidDeckHudDock.LEFT to -x / w,
|
||||||
DroidDeckHudDock.RIGHT to (v.x + v.width - p.width) / w,
|
DroidDeckHudDock.RIGHT to (x + v.width - p.width) / w,
|
||||||
DroidDeckHudDock.TOP to -v.y / h,
|
DroidDeckHudDock.TOP to -y / h,
|
||||||
DroidDeckHudDock.BOTTOM to (v.y + v.height - p.height) / h,
|
DroidDeckHudDock.BOTTOM to (y + v.height - p.height) / h,
|
||||||
).maxByOrNull { it.value }
|
).maxByOrNull { it.value }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -294,6 +305,7 @@ class DroidDeckHudHost(context: Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun stopMotion(hud: DroidDeckHudView) {
|
private fun stopMotion(hud: DroidDeckHudView) {
|
||||||
|
throwSpring?.cancel()
|
||||||
hud.animate().setUpdateListener(null)
|
hud.animate().setUpdateListener(null)
|
||||||
hud.animate().cancel()
|
hud.animate().cancel()
|
||||||
}
|
}
|
||||||
@@ -323,23 +335,21 @@ class DroidDeckHudHost(context: Context) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun snapToAnchor(hud: DroidDeckHudView, vx: Float) {
|
/** Sends the HUD to a side the way a chat head goes: by where the throw would carry it, springing on from its speed. */
|
||||||
|
private fun snapToAnchor(hud: DroidDeckHudView, vx: Float, vy: Float) {
|
||||||
val p = hud.parent as? View ?: return
|
val p = hud.parent as? View ?: return
|
||||||
val maxX = (p.width - hud.width).toFloat().coerceAtLeast(0f)
|
val maxX = (p.width - hud.width).toFloat().coerceAtLeast(0f)
|
||||||
val maxY = (p.height - hud.height).toFloat().coerceAtLeast(0f)
|
val maxY = (p.height - hud.height).toFloat().coerceAtLeast(0f)
|
||||||
anchorX = if (hud.x + vx * FLING_REACH_S < maxX / 2f) 0f else 1f
|
val right = com.droiddeck.launcher.ui.EdgeFling.toRight(hud.x + hud.width / 2f, p.width.toFloat(), vx, context.resources.displayMetrics.density)
|
||||||
|
anchorX = if (right) 1f else 0f
|
||||||
wantX = anchorX * maxX
|
wantX = anchorX * maxX
|
||||||
wantY = hud.y.coerceIn(0f, maxY)
|
wantY = com.droiddeck.launcher.ui.EdgeFling.restY(hud.y, vy, 0f, maxY)
|
||||||
SessionPrefs.setDroidDeckHudPosition(context, wantX, wantY)
|
SessionPrefs.setDroidDeckHudPosition(context, wantX, wantY)
|
||||||
stopMotion(hud)
|
stopMotion(hud)
|
||||||
if (Motion.scale == 0f) {
|
hud.scaleX = 1f; hud.scaleY = 1f
|
||||||
hud.scaleX = 1f; hud.scaleY = 1f
|
|
||||||
hud.x = wantX; hud.y = wantY
|
|
||||||
return
|
|
||||||
}
|
|
||||||
snapping = true
|
snapping = true
|
||||||
hud.animate().x(wantX).y(wantY).scaleX(1f).scaleY(1f).setDuration(Motion.ms(260).toLong()).setInterpolator(EASE)
|
val spring = throwSpring ?: com.droiddeck.launcher.ui.FlingSpring { sx, sy -> hud.x = sx; hud.y = sy }.also { throwSpring = it }
|
||||||
.withEndAction { snapping = false; keepOnScreen(hud) }.start()
|
spring.start(hud.x, hud.y, vx, vy, wantX, wantY) { snapping = false; keepOnScreen(hud) }
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun shrinkPastEdge(hud: DroidDeckHudView, rawX: Float, rawY: Float) {
|
private fun shrinkPastEdge(hud: DroidDeckHudView, rawX: Float, rawY: Float) {
|
||||||
@@ -496,10 +506,9 @@ class DroidDeckHudHost(context: Context) {
|
|||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
private const val DOCK_OVERHANG = 0.4f
|
private const val DOCK_OVERHANG = 0.4f
|
||||||
private const val FLING_REACH_S = 0.18f
|
|
||||||
private const val PREVIEW_FROM = 0.55f
|
private const val PREVIEW_FROM = 0.55f
|
||||||
private const val STRIP_PULL_ACROSS_DP = 600f
|
private const val STRIP_PULL_ACROSS_DP = 360f
|
||||||
private const val STRIP_PULL_OFF_DP = 150f
|
private const val STRIP_PULL_OFF_DP = 100f
|
||||||
private const val EXPAND_FADE = 0.5f
|
private const val EXPAND_FADE = 0.5f
|
||||||
private val EASE = PathInterpolator(0.2f, 0.8f, 0.2f, 1f)
|
private val EASE = PathInterpolator(0.2f, 0.8f, 0.2f, 1f)
|
||||||
|
|
||||||
|
|||||||
@@ -13,6 +13,27 @@
|
|||||||
|
|
||||||
package com.droiddeck.launcher.hud
|
package com.droiddeck.launcher.hud
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Size modes for the DroidDeck HUD (the 4th selectable in-game overlay style). One shared color-coded
|
||||||
|
* visual language, four amounts of detail — see the approved mockup. The config value is the lower-case
|
||||||
|
* token stored under the `hudSize` key; the label is the user-facing string.
|
||||||
|
*/
|
||||||
|
/** The text sizes and spacing a [DroidDeckHudSize] lays its rows out with, in sp. */
|
||||||
|
data class DroidDeckHudStyle(
|
||||||
|
val row: Float,
|
||||||
|
val unit: Float,
|
||||||
|
val pad: Float,
|
||||||
|
val lineGap: Float,
|
||||||
|
val labelGap: Float,
|
||||||
|
val key: Float = 0f,
|
||||||
|
val sub: Float = 0f,
|
||||||
|
val foot: Float = 0f,
|
||||||
|
val band: Float = 0f,
|
||||||
|
val gutter: Float = 0f,
|
||||||
|
val tileGap: Float = 0f,
|
||||||
|
val innerPad: Float = 0f,
|
||||||
|
)
|
||||||
|
|
||||||
enum class DroidDeckHudSize(val token: String, val label: String) {
|
enum class DroidDeckHudSize(val token: String, val label: String) {
|
||||||
FULL("full", "Full"),
|
FULL("full", "Full"),
|
||||||
TILES("tiles", "Tiles"),
|
TILES("tiles", "Tiles"),
|
||||||
@@ -26,27 +47,73 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
|
|||||||
return all[(ordinal + 1) % all.size]
|
return all[(ordinal + 1) % all.size]
|
||||||
}
|
}
|
||||||
|
|
||||||
fun supportedChips(): Set<String> = when (this) {
|
/**
|
||||||
MINIMAL -> MINIMAL_CHIPS
|
* The rows this size draws, in the order it draws them before the user moves any. This is the single
|
||||||
PILL -> PILL_CHIPS
|
* source of truth for both surfaces: [DroidDeckHudView] draws exactly these and the settings screen
|
||||||
FULL, TILES, STRIP -> STANDARD_CHIPS
|
* offers exactly these. A switch outside the set is ignored by the size, so the two cannot drift.
|
||||||
MEGA -> MEGA_CHIPS
|
*/
|
||||||
}
|
val rows: List<String> get() = ROWS.getValue(this)
|
||||||
|
|
||||||
|
/** This size's rows: the ones the user moved first, then the rest in the order [rows] lists them. */
|
||||||
|
fun rowsIn(stored: List<String>): List<String> =
|
||||||
|
stored.filter { it in rows } + rows.filter { it !in stored }
|
||||||
|
/**
|
||||||
|
* The numbers each size sets its text in, in sp. One table so a size's scale can be read (and changed)
|
||||||
|
* in one place instead of hunting the `sp(...)` literals scattered through its builder.
|
||||||
|
*/
|
||||||
|
val style: DroidDeckHudStyle get() = STYLE.getValue(this)
|
||||||
|
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
fun from(token: String?): DroidDeckHudSize =
|
fun from(token: String?): DroidDeckHudSize =
|
||||||
values().firstOrNull { it.token.equals(token, ignoreCase = true) } ?: FULL
|
values().firstOrNull { it.token.equals(token, ignoreCase = true) } ?: FULL
|
||||||
|
|
||||||
val MINIMAL_CHIPS = setOf("FPS", "FPS graph", "1% low", "0.1% low", "0.01% low", "FPS .1", "Engine", "Clock")
|
private val EXTRAS = setOf("showClock")
|
||||||
val PILL_CHIPS = setOf("FPS", "FPS graph", "GPU", "CPU", "VRAM", "RAM", "Battery", "GPU model", "FPS .1", "Engine", "Clock")
|
|
||||||
val STANDARD_CHIPS = setOf(
|
val ROWS: Map<DroidDeckHudSize, List<String>> = mapOf(
|
||||||
"FPS", "FPS graph", "GPU", "GPU temp", "CPU", "VRAM", "RAM", "Power", "Temp",
|
FULL to listOf(
|
||||||
"Battery", "GPU model", "Engine", "1% low", "0.1% low", "0.01% low", "FPS .1", "Clock",
|
"showFPS", "showFPSGraph", "showGpuModel", "showDisplay", "showHdr", "showGPULoad", "showGpuTemp",
|
||||||
|
"showCPUUsage", "showTemp", "showVram", "showRAM", "showBattery", "showBatteryTemp", "showBatteryTime",
|
||||||
|
"showPower", "showLatency", "showAvg", "showLow1", "showLow01", "showLow001",
|
||||||
|
),
|
||||||
|
TILES to listOf(
|
||||||
|
"showFPS", "showFPSGraph", "showLatency", "showGPULoad", "showGpuTemp", "showCPUUsage", "showTemp",
|
||||||
|
"showVram", "showRAM", "showEngine", "showDisplay", "showHdr", "showAvg", "showLow1",
|
||||||
|
"showLow01", "showLow001", "showGpuModel", "showBattery", "showBatteryTemp", "showBatteryTime", "showPower",
|
||||||
|
),
|
||||||
|
PILL to listOf(
|
||||||
|
"showFPS", "showFPSGraph", "showGpuModel", "showGPULoad", "showGpuTemp", "showCPUUsage", "showTemp",
|
||||||
|
"showRAM", "showBattery", "showBatteryTemp", "showBatteryTime", "showPower", "showLatency", "showDisplay",
|
||||||
|
"showVram", "showHdr",
|
||||||
|
),
|
||||||
|
MINIMAL to listOf(
|
||||||
|
"showFPS", "showBatteryTime", "showFPSGraph", "showLow1", "showLow01", "showLow001", "showAvg", "showLatency",
|
||||||
|
"showEngine", "showDisplay", "showHdr",
|
||||||
|
),
|
||||||
|
MEGA to DroidDeckHudConfig.ORDER.filter { it !in EXTRAS },
|
||||||
|
STRIP to listOf(
|
||||||
|
"showFPS", "showFPSGraph", "showLow1", "showLow01", "showLow001", "showGPULoad", "showGpuTemp",
|
||||||
|
"showCPUUsage", "showTemp", "showVram", "showRAM", "showBattery", "showBatteryTemp", "showBatteryTime",
|
||||||
|
"showPower", "showDisplay", "showHdr", "showGpuModel",
|
||||||
|
),
|
||||||
)
|
)
|
||||||
val MEGA_ONLY = setOf(
|
|
||||||
"Per-core", "Swap", "Network", "Resolution", "Proton", "Wrapper", "DX ver", "Session",
|
|
||||||
|
val STYLE: Map<DroidDeckHudSize, DroidDeckHudStyle> = mapOf(
|
||||||
|
FULL to DroidDeckHudStyle(row = 12f, unit = 12f * 0.62f, pad = 10f, lineGap = 4f, labelGap = 8f),
|
||||||
|
TILES to DroidDeckHudStyle(row = 18f, unit = 11f, pad = 9f, lineGap = 4f, labelGap = 8f,
|
||||||
|
key = 10f, sub = 10f, tileGap = 6f, innerPad = 8f),
|
||||||
|
PILL to DroidDeckHudStyle(row = 30f, unit = 30f * 0.36f, pad = 10f, lineGap = 3f, labelGap = 12f,
|
||||||
|
sub = 11.5f),
|
||||||
|
MINIMAL to DroidDeckHudStyle(row = 34f, unit = 34f * 0.32f, pad = 10f, lineGap = 4f, labelGap = 8f,
|
||||||
|
sub = 11.5f, foot = 9.5f),
|
||||||
|
MEGA to DroidDeckHudStyle(row = 11.5f, unit = 11.5f * 0.62f, pad = 10f, lineGap = 3.5f, labelGap = 7f,
|
||||||
|
band = 9.5f, gutter = 16f),
|
||||||
|
STRIP to DroidDeckHudStyle(row = 11.5f, unit = 11.5f * 0.8f, pad = 10f, lineGap = 0f, labelGap = 13f),
|
||||||
)
|
)
|
||||||
val MEGA_CHIPS = STANDARD_CHIPS + MEGA_ONLY
|
|
||||||
|
fun rowsFor(size: DroidDeckHudSize, values: Map<String, String>): List<String> =
|
||||||
|
size.rowsIn(DroidDeckHudConfig.storedOrder(values, size))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -69,6 +69,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
|||||||
|
|
||||||
private val density = resources.displayMetrics.density
|
private val density = resources.displayMetrics.density
|
||||||
|
|
||||||
|
private var cfg: KeyValueSet = KeyValueSet()
|
||||||
private var size = DroidDeckHudSize.FULL
|
private var size = DroidDeckHudSize.FULL
|
||||||
private var scale = 1f
|
private var scale = 1f
|
||||||
private var bgOpacity = 0.8f
|
private var bgOpacity = 0.8f
|
||||||
@@ -95,13 +96,16 @@ class DroidDeckHudView(context: Context) : View(context) {
|
|||||||
private var showLow001 = true
|
private var showLow001 = true
|
||||||
private var fpsDecimal = true
|
private var fpsDecimal = true
|
||||||
private var showClockTime = true
|
private var showClockTime = true
|
||||||
|
private var showLatency = true
|
||||||
|
private var showAvg = true
|
||||||
|
private var showDisplay = true
|
||||||
|
private var showHdr = true
|
||||||
|
private var storedOrder: List<String> = emptyList()
|
||||||
private var showPerCore = true
|
private var showPerCore = true
|
||||||
private var showSwap = true
|
private var showSwap = true
|
||||||
private var showNet = true
|
private var showNet = true
|
||||||
private var showResolution = true
|
private var showResolution = true
|
||||||
private var showProton = true
|
private var showProton = true
|
||||||
private var showWrapper = true
|
|
||||||
private var showDxVer = true
|
|
||||||
private var showSession = true
|
private var showSession = true
|
||||||
|
|
||||||
private var engineLabel = ""
|
private var engineLabel = ""
|
||||||
@@ -177,7 +181,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
|||||||
fun moved(dx: Float, dy: Float) = Glyph(x + dx, baseline + dy, text, color, sizePx, glow)
|
fun moved(dx: Float, dy: Float) = Glyph(x + dx, baseline + dy, text, color, sizePx, glow)
|
||||||
}
|
}
|
||||||
private class Span(val text: String, val color: Int, val sizePx: Float, val glow: Boolean = false)
|
private class Span(val text: String, val color: Int, val sizePx: Float, val glow: Boolean = false)
|
||||||
private class HudRow(val label: Span, val vals: List<Span>, val inline: Boolean = false)
|
private class HudRow(val key: String, val label: Span, val vals: List<Span>, val inline: Boolean = false)
|
||||||
private val glyphs = ArrayList<Glyph>()
|
private val glyphs = ArrayList<Glyph>()
|
||||||
private val tileRects = ArrayList<RectF>()
|
private val tileRects = ArrayList<RectF>()
|
||||||
private var graphRect: RectF? = null
|
private var graphRect: RectF? = null
|
||||||
@@ -289,41 +293,52 @@ class DroidDeckHudView(context: Context) : View(context) {
|
|||||||
|
|
||||||
private fun cycleSize() {
|
private fun cycleSize() {
|
||||||
size = size.next()
|
size = size.next()
|
||||||
|
refreshOrder()
|
||||||
onSizeCycledListener?.accept(size.token)
|
onSizeCycledListener?.accept(size.token)
|
||||||
rebuildAndInvalidate()
|
rebuildAndInvalidate()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun refreshOrder() {
|
||||||
|
storedOrder = DroidDeckHudConfig.storedOrder(mapOf("hudOrder" to cfg.get("hudOrder", "")), size)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun switchOn(key: String): Boolean =
|
||||||
|
cfg.get(key, DroidDeckHudConfig.DEFAULTS[key] ?: "1") == "1"
|
||||||
|
|
||||||
fun applyConfig(configString: String?) {
|
fun applyConfig(configString: String?) {
|
||||||
if (configString.isNullOrEmpty()) return
|
if (configString.isNullOrEmpty()) return
|
||||||
val cfg = KeyValueSet(configString)
|
cfg = KeyValueSet(configString)
|
||||||
|
|
||||||
size = DroidDeckHudSize.from(cfg.get("hudSize", "minimal"))
|
size = DroidDeckHudSize.from(cfg.get("hudSize", "minimal"))
|
||||||
showFPS = cfg.get("showFPS", "1") == "1"
|
showFPS = switchOn("showFPS")
|
||||||
showEngine = cfg.get("showEngine", "1") == "1"
|
showEngine = switchOn("showEngine")
|
||||||
showGpuModel = cfg.get("showGpuModel", "1") == "1"
|
showGpuModel = switchOn("showGpuModel")
|
||||||
showCPU = cfg.get("showCPUUsage", cfg.get("showCPULoad", "1")) == "1"
|
showCPU = switchOn("showCPUUsage")
|
||||||
showGPU = cfg.get("showGPULoad", "1") == "1"
|
showGPU = switchOn("showGPULoad")
|
||||||
showCpuTemp = cfg.get("showTemp", "1") == "1"
|
showCpuTemp = switchOn("showTemp")
|
||||||
showGpuTemp = cfg.get("showGpuTemp", "0") == "1"
|
showGpuTemp = switchOn("showGpuTemp")
|
||||||
showVram = cfg.get("showVram", "1") == "1"
|
showVram = switchOn("showVram")
|
||||||
showRAM = cfg.get("showRAM", "1") == "1"
|
showRAM = switchOn("showRAM")
|
||||||
showBattery = cfg.get("showBattery", "1") == "1"
|
showBattery = switchOn("showBattery")
|
||||||
showPower = cfg.get("showPower", "1") == "1"
|
showPower = switchOn("showPower")
|
||||||
showBatteryTemp = cfg.get("showBatteryTemp", "0") == "1"
|
showBatteryTemp = switchOn("showBatteryTemp")
|
||||||
showGraph = cfg.get("showFPSGraph", "0") == "1"
|
showGraph = switchOn("showFPSGraph")
|
||||||
showLow1 = cfg.get("showLow1", "1") == "1"
|
showLow001 = switchOn("showLow001")
|
||||||
showLow01 = cfg.get("showLow01", "1") == "1"
|
|
||||||
showLow001 = cfg.get("showLow001", "1") == "1"
|
|
||||||
fpsDecimal = cfg.get("fpsDecimal", "1") == "1"
|
fpsDecimal = cfg.get("fpsDecimal", "1") == "1"
|
||||||
showClockTime = cfg.get("showClock", "1") == "1"
|
showClockTime = switchOn("showClock")
|
||||||
showPerCore = cfg.get("showPerCore", "1") == "1"
|
showLatency = switchOn("showLatency")
|
||||||
showSwap = cfg.get("showSwap", "1") == "1"
|
showAvg = switchOn("showAvg")
|
||||||
showNet = cfg.get("showNet", "1") == "1"
|
showLow1 = switchOn("showLow1")
|
||||||
showResolution = cfg.get("showResolution", "1") == "1"
|
showLow01 = switchOn("showLow01")
|
||||||
showProton = cfg.get("showProton", "1") == "1"
|
showDisplay = switchOn("showDisplay")
|
||||||
showWrapper = cfg.get("showWrapper", "1") == "1"
|
showHdr = switchOn("showHdr")
|
||||||
showDxVer = cfg.get("showDxVer", "1") == "1"
|
refreshOrder()
|
||||||
showSession = cfg.get("showSession", "1") == "1"
|
showPerCore = switchOn("showPerCore")
|
||||||
|
showSwap = switchOn("showSwap")
|
||||||
|
showNet = switchOn("showNet")
|
||||||
|
showResolution = switchOn("showResolution")
|
||||||
|
showProton = switchOn("showProton")
|
||||||
|
showSession = switchOn("showSession")
|
||||||
tempDisplay = HudMetrics.TempDisplay.from(cfg)
|
tempDisplay = HudMetrics.TempDisplay.from(cfg)
|
||||||
lockController.setLocked(cfg.get("hudLocked", "1") == "1")
|
lockController.setLocked(cfg.get("hudLocked", "1") == "1")
|
||||||
dock = DroidDeckHudDock.from(cfg.get("hudDock", "none"))
|
dock = DroidDeckHudDock.from(cfg.get("hudDock", "none"))
|
||||||
@@ -458,6 +473,8 @@ class DroidDeckHudView(context: Context) : View(context) {
|
|||||||
return w
|
return w
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun showHdrLine(): Boolean = showHdr && hdrState != DroidDeckHudHdr.NONE
|
||||||
|
|
||||||
private fun placeRun(startX: Float, baseline: Float, spans: List<Span>, glow: Boolean = false): Float {
|
private fun placeRun(startX: Float, baseline: Float, spans: List<Span>, glow: Boolean = false): Float {
|
||||||
var x = startX
|
var x = startX
|
||||||
for (s in spans) {
|
for (s in spans) {
|
||||||
@@ -539,13 +556,15 @@ class DroidDeckHudView(context: Context) : View(context) {
|
|||||||
val s = snap
|
val s = snap
|
||||||
if (s == null) { contentW = 0f; contentH = 0f; return }
|
if (s == null) { contentW = 0f; contentH = 0f; return }
|
||||||
if (dock != DroidDeckHudDock.NONE) { buildDockTab(); return }
|
if (dock != DroidDeckHudDock.NONE) { buildDockTab(); return }
|
||||||
|
if (size == DroidDeckHudSize.STRIP) { buildStrip(s); return }
|
||||||
|
buildRows(s)
|
||||||
|
if (contentW <= 0f || contentH <= 0f) return
|
||||||
|
if (size == DroidDeckHudSize.PILL) addSubtleClock(sp(10f), leftAligned = true)
|
||||||
|
val pad = sp(size.style.pad)
|
||||||
when (size) {
|
when (size) {
|
||||||
DroidDeckHudSize.FULL -> { buildFull(s); intoPanel(sp(10f), header = true) }
|
DroidDeckHudSize.MINIMAL -> intoPanel(pad, header = true, halfRound = true)
|
||||||
DroidDeckHudSize.TILES -> { buildTiles(s); intoPanel(sp(9f), header = true) }
|
DroidDeckHudSize.PILL -> intoPanel(pad, header = false)
|
||||||
DroidDeckHudSize.PILL -> { buildPill(s); intoPanel(sp(10f), header = false) }
|
else -> intoPanel(pad, header = true)
|
||||||
DroidDeckHudSize.MINIMAL -> buildMinimal(s)
|
|
||||||
DroidDeckHudSize.MEGA -> { buildMega(s); intoPanel(sp(10f), header = true) }
|
|
||||||
DroidDeckHudSize.STRIP -> buildStrip(s)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -615,7 +634,12 @@ class DroidDeckHudView(context: Context) : View(context) {
|
|||||||
return Pair(dDividerTop + max(1f, density), x)
|
return Pair(dDividerTop + max(1f, density), x)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun intoPanel(pad: Float, header: Boolean) {
|
/**
|
||||||
|
* Moves a size's content, laid out from [pad] at the origin, into the panel: under the header, or after
|
||||||
|
* the logo chip on the Pill. Lines that start on the content's left edge are lined up by their ink, so
|
||||||
|
* the logo, labels and numbers share one edge.
|
||||||
|
*/
|
||||||
|
private fun intoPanel(pad: Float, header: Boolean, halfRound: Boolean = !header) {
|
||||||
if (contentW <= 0f || contentH <= 0f) return
|
if (contentW <= 0f || contentH <= 0f) return
|
||||||
for (i in glyphs.indices) {
|
for (i in glyphs.indices) {
|
||||||
val g = glyphs[i]
|
val g = glyphs[i]
|
||||||
@@ -641,7 +665,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
|||||||
val panel = RectF(panelLeft(), panelInset(), max(contentW - pad + dx, headerRight) + sp(18f),
|
val panel = RectF(panelLeft(), panelInset(), max(contentW - pad + dx, headerRight) + sp(18f),
|
||||||
contentH - pad + dy + sp(10f) + stroke)
|
contentH - pad + dy + sp(10f) + stroke)
|
||||||
chipRect?.let { it.offsetTo(it.left, panel.centerY() - it.height() / 2f) }
|
chipRect?.let { it.offsetTo(it.left, panel.centerY() - it.height() / 2f) }
|
||||||
finishPanel(panel, halfRound = !header)
|
finishPanel(panel, halfRound = halfRound)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun finishPanel(panel: RectF, halfRound: Boolean) {
|
private fun finishPanel(panel: RectF, halfRound: Boolean) {
|
||||||
@@ -712,316 +736,188 @@ class DroidDeckHudView(context: Context) : View(context) {
|
|||||||
contentW = max(contentW, pad + w + pad)
|
contentW = max(contentW, pad + w + pad)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun hasGpuStats(s: HudMetrics.Snapshot): Boolean =
|
private fun switchLabel(key: String): Pair<String, Int> = when (key) {
|
||||||
s.gpuPercent != null || s.gpuTempC != null || s.gpuClockMhz != null
|
"showGpuModel" -> "MODEL" to colGpu
|
||||||
|
"showGPULoad" -> "GPU" to colGpu
|
||||||
private fun buildFull(s: HudMetrics.Snapshot) {
|
"showGpuTemp" -> "GPU.T" to colGpu
|
||||||
val rowPx = sp(12f); val unitPx = rowPx * 0.62f
|
"showCPUUsage" -> "CPU" to colCpu
|
||||||
val pad = sp(10f); val lineGap = sp(4f); val lvGap = sp(8f)
|
"showTemp" -> "CPU.T" to colCpu
|
||||||
val rows = ArrayList<HudRow>()
|
"showBatteryTemp" -> "BAT.T" to colBat
|
||||||
|
"showPower" -> "PWR" to colBat
|
||||||
if (showGpuModel && gpuNameText().isNotBlank())
|
"showBattery" -> "BAT" to colBat
|
||||||
rows.add(HudRow(Span("GPU", colGpu, rowPx), gpuModelSpans(rowPx, colValue)))
|
"showBatteryTime" -> "BAT TIME" to colBat
|
||||||
if (displayServer.isNotBlank())
|
"showVram" -> "VRAM" to colVram
|
||||||
rows.add(HudRow(Span("DISP", colDisp, rowPx), listOf(Span(displayServer, colValue, rowPx))))
|
"showRAM" -> "RAM" to colRam
|
||||||
if (hdrState != DroidDeckHudHdr.NONE)
|
"showSwap" -> "SWP" to colRam
|
||||||
rows.add(HudRow(Span("HDR", colHdr, rowPx), hdrValue(rowPx)))
|
"showNet" -> "NET" to colFps
|
||||||
if (showGPU && hasGpuStats(s)) {
|
"showPerCore" -> "CORE" to colCpu
|
||||||
val v = ArrayList<Span>()
|
"showFPS" -> "FPS" to colFps
|
||||||
v += numUnit(s.gpuPercent?.toString(), "%", rowPx, unitPx)
|
"showLatency" -> "MS" to colDim
|
||||||
if (showGpuTemp) tempSpans(s.gpuTempC, HudMetrics.TempSensor.GPU, rowPx, unitPx)
|
"showAvg" -> "AVG" to colLo
|
||||||
.let { if (it.isNotEmpty()) { v += gap(unitPx); v += it } }
|
"showLow1" -> "1%" to colLo
|
||||||
v += gap(unitPx); v += numUnit(s.gpuClockMhz?.toString(), "MHz", rowPx, unitPx)
|
"showLow01" -> "0.1%" to colLo
|
||||||
rows.add(HudRow(Span("GPU", colGpu, rowPx), v))
|
"showLow001" -> "0.01%" to colLo
|
||||||
}
|
"showEngine" -> "API" to colFps
|
||||||
if (showCPU) {
|
"showDisplay" -> "DISP" to colDisp
|
||||||
val v = ArrayList<Span>()
|
"showHdr" -> "HDR" to colHdr
|
||||||
v += numUnit(s.cpuPercent?.toString(), "%", rowPx, unitPx)
|
"showResolution" -> "RES" to colDim
|
||||||
v += gap(unitPx); v += numUnit(s.cpuClockMhz?.toString(), "MHz", rowPx, unitPx)
|
"showProton" -> "PROTON" to colVram
|
||||||
if (showCpuTemp) tempSpans(s.cpuTempC, HudMetrics.TempSensor.CPU, rowPx, unitPx)
|
"showSession" -> "TIME" to colDim
|
||||||
.let { if (it.isNotEmpty()) { v += gap(unitPx); v += it } }
|
else -> key.removePrefix("show") to colDim
|
||||||
rows.add(HudRow(Span("CPU", colCpu, rowPx), v))
|
|
||||||
}
|
|
||||||
if (showVram && s.vramText() != null)
|
|
||||||
rows.add(HudRow(Span("VRAM", colVram, rowPx), valueUnit(s.vramText()!!, rowPx, unitPx)))
|
|
||||||
if (showRAM) {
|
|
||||||
val v = ArrayList<Span>()
|
|
||||||
v += valueUnit(s.ramUsedText(), rowPx, unitPx)
|
|
||||||
v += gap(unitPx); v += numUnit(s.ramPercent.roundToInt().toString(), "%", rowPx, unitPx)
|
|
||||||
rows.add(HudRow(Span("RAM", colRam, rowPx), v))
|
|
||||||
}
|
|
||||||
if (showBattery || showPower || showBatteryTemp) {
|
|
||||||
val v = ArrayList<Span>(); var any = false
|
|
||||||
if (showBattery && s.battery.percent != null) { v += numUnit(s.battery.percent.toString(), "%", rowPx, unitPx); any = true }
|
|
||||||
if (showBatteryTemp) tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, rowPx, unitPx)
|
|
||||||
.let { if (it.isNotEmpty()) { if (any) v += gap(unitPx); v += it; any = true } }
|
|
||||||
if (showPower && s.battery.watts > 0f) { if (any) v += gap(unitPx); v += numUnit(fmt1(s.battery.watts), "W", rowPx, unitPx); any = true }
|
|
||||||
if (any) rows.add(HudRow(Span("BAT", colBat, rowPx), v))
|
|
||||||
}
|
|
||||||
if (showFPS) {
|
|
||||||
val v = ArrayList<Span>()
|
|
||||||
v += glowing(numUnit(fpsText(fpsNow), "FPS", rowPx, unitPx))
|
|
||||||
v += gap(unitPx); v += numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", rowPx, unitPx)
|
|
||||||
rows.add(HudRow(Span(apiLabel(), colFps, rowPx), v))
|
|
||||||
rows.add(HudRow(Span("AVG", colLo, rowPx), numUnit(fmt1(fpsAvg), "FPS", rowPx, unitPx)))
|
|
||||||
if (showLow1)
|
|
||||||
rows.add(HudRow(Span("1%", colLo, rowPx), numUnit(lowText(lows.low1Fps), "FPS", rowPx, unitPx)))
|
|
||||||
if (showLow01)
|
|
||||||
rows.add(HudRow(Span("0.1%", colLo, rowPx), numUnit(lowText(lows.low01Fps), "FPS", rowPx, unitPx)))
|
|
||||||
if (showLow001)
|
|
||||||
rows.add(HudRow(Span("0.01%", colLo, rowPx), numUnit(lowText(lows.low001Fps), "FPS", rowPx, unitPx)))
|
|
||||||
}
|
|
||||||
|
|
||||||
var labelCol = 0f
|
|
||||||
for (r in rows) if (!r.inline) labelCol = max(labelCol, measure(r.label.text, rowPx))
|
|
||||||
val h = lineH(rowPx); val asc = ascent(rowPx)
|
|
||||||
var y = pad; var maxRight = pad
|
|
||||||
for (r in rows) {
|
|
||||||
val baseline = y - asc
|
|
||||||
placeRun(pad, baseline, listOf(r.label))
|
|
||||||
val valX = if (r.inline) pad + measure(r.label.text, rowPx) + lvGap
|
|
||||||
else pad + labelCol + lvGap
|
|
||||||
val end = placeRun(valX, baseline, r.vals)
|
|
||||||
maxRight = max(maxRight, end)
|
|
||||||
y += h + lineGap
|
|
||||||
}
|
|
||||||
|
|
||||||
if (showFPS && showGraph) {
|
|
||||||
val ftPx = unitPx * 1.15f
|
|
||||||
val baseline = y - asc
|
|
||||||
placeRun(pad, baseline, listOf(Span("Frametime", colFps, ftPx)))
|
|
||||||
val stat = "min:${fmt1(graphMinMs)} max:${fmt1(graphMaxMs)}"
|
|
||||||
val statX = pad + max(labelCol, measure("Frametime", ftPx)) + lvGap
|
|
||||||
val end = placeRun(statX, baseline, listOf(Span(stat, colDim, unitPx)))
|
|
||||||
maxRight = max(maxRight, end)
|
|
||||||
y += h + lineGap
|
|
||||||
val gh = sp(22f)
|
|
||||||
val right = max(maxRight, pad + sp(160f))
|
|
||||||
graphRect = RectF(pad, y, right, y + gh)
|
|
||||||
maxRight = max(maxRight, right)
|
|
||||||
y += gh
|
|
||||||
}
|
|
||||||
|
|
||||||
contentW = maxRight + pad
|
|
||||||
contentH = y + pad
|
|
||||||
addSubtleClock(pad)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun buildTiles(s: HudMetrics.Snapshot) {
|
private fun reading(key: String, s: HudMetrics.Snapshot, labelPx: Float, valuePx: Float, unitPx: Float): HudRow {
|
||||||
val keyPx = sp(10f); val valPx = sp(18f); val subPx = sp(10f); val unitPx = sp(11f)
|
if (key == "showFPSGraph") return HudRow(key, Span("", colDim, 0f), emptyList())
|
||||||
val pad = sp(9f); val innerPad = sp(8f); val tileGap = sp(6f); val lineGap = sp(4f)
|
val (label, color) = switchLabel(key)
|
||||||
|
val values: List<Span> = when (key) {
|
||||||
class Tile(val key: String, val keyColor: Int, val value: List<Span>, val sub: String?, val wide: Boolean)
|
"showGpuModel" -> if (gpuNameText().isBlank()) numUnit(null, "", valuePx, unitPx)
|
||||||
val tiles = ArrayList<Tile>()
|
else gpuModelSpans(valuePx, colValue)
|
||||||
|
"showGPULoad" -> numUnit(s.gpuPercent?.toString(), "%", valuePx, unitPx)
|
||||||
if (showFPS) tiles.add(Tile("FPS", colFps, listOf(Span(fpsText(fpsNow), colValue, valPx, glow = true)),
|
"showGpuTemp" -> tempSpans(s.gpuTempC, HudMetrics.TempSensor.GPU, valuePx, unitPx)
|
||||||
"${fmt1(fpsAvg)} avg" + (if (showLow1) " · ${lowText(lows.low1Fps) ?: "—"} 1%" else ""), false))
|
"showCPUUsage" -> numUnit(s.cpuPercent?.toString(), "%", valuePx, unitPx)
|
||||||
if (showFPS) tiles.add(Tile("FRAME", colDim, numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", valPx, unitPx),
|
"showTemp" -> tempSpans(s.cpuTempC, HudMetrics.TempSensor.CPU, valuePx, unitPx)
|
||||||
"${fmt1(graphMinMs)} – ${fmt1(graphMaxMs)}", false))
|
"showBatteryTemp" -> tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, valuePx, unitPx)
|
||||||
if (showGPU && hasGpuStats(s)) tiles.add(Tile("GPU", colGpu, numUnit(s.gpuPercent?.toString(), "%", valPx, unitPx),
|
"showPower" -> numUnit(if (s.battery.watts > 0f) fmt1(s.battery.watts) else null, "W", valuePx, unitPx)
|
||||||
if (showGpuTemp && s.gpuTempC != null) HudMetrics.formatTemp(s.gpuTempC.toFloat(), tempDisplay, false)
|
"showBattery" -> numUnit(s.battery.percent?.toString(), "%", valuePx, unitPx)
|
||||||
else s.gpuClockMhz?.let { "${it}MHz" }, false))
|
"showBatteryTime" -> valueUnit(s.battery.runtimeText ?: "—", valuePx, unitPx)
|
||||||
if (showCPU) tiles.add(Tile("CPU", colCpu, numUnit(s.cpuPercent?.toString(), "%", valPx, unitPx),
|
"showVram" -> valueUnit(s.vramText() ?: "—", valuePx, unitPx)
|
||||||
listOfNotNull(s.cpuClockMhz?.let { "${it}MHz" },
|
"showRAM" -> numUnit(s.ramPercent.roundToInt().toString(), "%", valuePx, unitPx)
|
||||||
if (showCpuTemp) s.cpuTempC?.let { HudMetrics.formatTemp(it.toFloat(), tempDisplay, false) } else null)
|
"showSwap" -> valueUnit(s.swapUsedText() ?: "—", valuePx, unitPx)
|
||||||
.joinToString(" · ").ifBlank { null }, false))
|
"showNet" -> listOf(
|
||||||
if (showVram && s.vramText() != null) tiles.add(Tile("VRAM", colVram, valueUnit(s.vramText()!!, valPx, unitPx), null, false))
|
Span("↓", colDim, unitPx), Span(((s.netDownBps ?: 0L) / 1024L).toString(), colValue, valuePx),
|
||||||
if (showRAM) tiles.add(Tile("RAM", colRam, numUnit(s.ramPercent.roundToInt().toString(), "%", valPx, unitPx),
|
Span(" ↑", colDim, unitPx), Span(((s.netUpBps ?: 0L) / 1024L).toString(), colValue, valuePx),
|
||||||
"${s.ramUsedText()} / ${s.ramTotalText()}", false))
|
)
|
||||||
if (showEngine && engineLabel.isNotBlank())
|
"showPerCore" -> listOf(Span(s.perCorePercent.size.toString(), colValue, valuePx))
|
||||||
tiles.add(Tile("API", colFps, listOf(Span(engineLabel, colValue, valPx)),
|
"showFPS" -> glowing(numUnit(fpsText(fpsNow), "", valuePx, unitPx))
|
||||||
dxVersion().ifBlank { null }, false))
|
"showLatency" -> numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", valuePx, unitPx)
|
||||||
if (displayServer.isNotBlank())
|
"showAvg" -> numUnit(fmt1(fpsAvg), "", valuePx, unitPx)
|
||||||
tiles.add(Tile("DISPLAY", colDisp, listOf(Span(displayServer, colValue, valPx)),
|
"showLow1" -> numUnit(lowText(lows.low1Fps), "", valuePx, unitPx)
|
||||||
if (hdrState != DroidDeckHudHdr.NONE) hdrText() else null, false))
|
"showLow01" -> numUnit(lowText(lows.low01Fps), "", valuePx, unitPx)
|
||||||
if (showGpuModel && gpuNameText().isNotBlank())
|
"showLow001" -> numUnit(lowText(lows.low001Fps), "", valuePx, unitPx)
|
||||||
tiles.add(Tile("GPU", colGpu, gpuModelSpans(valPx, colValue), null, true))
|
"showEngine" -> listOf(Span(engineLabel.ifBlank { "—" }, colValue, valuePx))
|
||||||
if (showBattery || showPower || showBatteryTemp) {
|
"showDisplay" -> listOf(Span(displayServer.ifBlank { "—" }, colDisp, valuePx))
|
||||||
val parts = ArrayList<Span>(); var any = false
|
"showHdr" -> if (showHdrLine()) hdrValue(valuePx) else listOf(Span("off", colDim, valuePx))
|
||||||
if (showBattery && s.battery.percent != null) { parts += numUnit(s.battery.percent.toString(), "%", valPx, unitPx); any = true }
|
"showResolution" -> listOf(Span(resolutionString(), colValue, valuePx))
|
||||||
if (showBatteryTemp && s.battery.tempC != null) { if (any) parts += Span(" · ", colDim, subPx); parts += tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, valPx, unitPx); any = true }
|
"showProton" -> listOf(Span(wineVersion.ifBlank { "—" }, colVram, valuePx))
|
||||||
if (showPower && s.battery.watts > 0f) { if (any) parts += Span(" · ", colDim, subPx); parts += numUnit(fmt1(s.battery.watts), "W", valPx, unitPx); any = true }
|
"showSession" -> listOf(Span(elapsedString(), colValue, valuePx))
|
||||||
if (any) tiles.add(Tile("BAT", colBat, parts, null, true))
|
else -> listOf(Span("—", colDim, valuePx))
|
||||||
}
|
}
|
||||||
if (tiles.isEmpty()) { contentW = 0f; contentH = 0f; return }
|
return HudRow(key, Span(label, color, labelPx), values.ifEmpty { listOf(Span("—", colDim, valuePx)) })
|
||||||
|
|
||||||
val keyH = lineH(keyPx); val valH = lineH(valPx); val subH = lineH(subPx)
|
|
||||||
fun tileW(t: Tile) = max(max(measure(t.key, keyPx), runWidth(t.value)),
|
|
||||||
t.sub?.let { measure(it, subPx) } ?: 0f) + innerPad * 2
|
|
||||||
var normalW = 0f
|
|
||||||
for (t in tiles) if (!t.wide) normalW = max(normalW, tileW(t))
|
|
||||||
if (normalW == 0f) for (t in tiles) normalW = max(normalW, tileW(t) / 2f)
|
|
||||||
val tileH = innerPad * 2 + keyH + lineGap + valH + lineGap + subH
|
|
||||||
val fullW = normalW * 2 + tileGap
|
|
||||||
|
|
||||||
var x = pad; var y = pad; var col = 0
|
|
||||||
fun place(t: Tile, tx: Float, ty: Float, tw: Float) {
|
|
||||||
tileRects.add(RectF(tx, ty, tx + tw, ty + tileH))
|
|
||||||
var by = ty + innerPad - ascent(keyPx)
|
|
||||||
placeRun(tx + innerPad, by, listOf(Span(t.key, t.keyColor, keyPx)))
|
|
||||||
by = ty + innerPad + keyH + lineGap - ascent(valPx)
|
|
||||||
placeRun(tx + innerPad, by, t.value)
|
|
||||||
if (t.sub != null) {
|
|
||||||
by = ty + innerPad + keyH + lineGap + valH + lineGap - ascent(subPx)
|
|
||||||
placeRun(tx + innerPad, by, listOf(Span(t.sub, colDim, subPx)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (t in tiles) {
|
|
||||||
if (t.wide) {
|
|
||||||
if (col != 0) { y += tileH + tileGap; col = 0; x = pad }
|
|
||||||
place(t, pad, y, fullW)
|
|
||||||
y += tileH + tileGap; col = 0; x = pad
|
|
||||||
} else {
|
|
||||||
place(t, x, y, normalW)
|
|
||||||
col++; x += normalW + tileGap
|
|
||||||
if (col == 2) { col = 0; x = pad; y += tileH + tileGap }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (col != 0) y += tileH + tileGap
|
|
||||||
if (showFPS && showGraph) {
|
|
||||||
graphRect = RectF(pad, y, pad + fullW, y + sp(22f))
|
|
||||||
y += sp(22f) + tileGap
|
|
||||||
}
|
|
||||||
contentW = pad + fullW + pad
|
|
||||||
contentH = y + (pad - tileGap)
|
|
||||||
addSubtleClock(pad)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun buildPill(s: HudMetrics.Snapshot) {
|
private fun buildRows(s: HudMetrics.Snapshot) {
|
||||||
val bigPx = sp(30f); val bigUnitPx = bigPx * 0.36f; val stkPx = sp(11.5f)
|
val st = size.style
|
||||||
val pad = sp(10f); val midGap = sp(12f); val stkLineGap = sp(3f)
|
val pad = sp(st.pad); val lineGap = sp(st.lineGap); val lvGap = sp(st.labelGap)
|
||||||
|
val gutter = sp(if (st.gutter > 0f) st.gutter else 14f)
|
||||||
|
val unitPx = sp(if (st.unit > 0f) st.unit else st.row * 0.62f)
|
||||||
|
val basePx = sp(if (st.sub > 0f) st.sub else st.row)
|
||||||
|
|
||||||
val left = ArrayList<Span>()
|
val keys = size.rowsIn(storedOrder).filter { switchOn(it) }
|
||||||
val generating = differs(fpsNow)
|
if (keys.isEmpty()) { contentW = 0f; contentH = 0f; return }
|
||||||
val fpsPx = if (generating) bigPx * 0.55f else bigPx
|
val hero = (size == DroidDeckHudSize.PILL || size == DroidDeckHudSize.MINIMAL) && keys.firstOrNull() == "showFPS"
|
||||||
left += Span(fpsText(fpsNow), colValue, fpsPx, glow = true)
|
val tiles = size == DroidDeckHudSize.TILES
|
||||||
left += Span("fps", colDim, if (generating) bigUnitPx * 0.8f else bigUnitPx)
|
val bigPx = sp(st.row); val bigUnitPx = sp(st.unit)
|
||||||
|
val heroSpans = listOf(
|
||||||
val stack = ArrayList<List<Span>>()
|
Span(fpsText(fpsNow), colValue, bigPx, glow = true),
|
||||||
val gpuName = if (showGpuModel && gpuNameText().isNotBlank()) gpuModelSpans(stkPx, colDim, compact = true) else null
|
Span("fps", colDim, bigUnitPx),
|
||||||
run {
|
)
|
||||||
val l = ArrayList<Span>()
|
val listed = keys.filter { !hero || it != "showFPS" }.flatMap { key ->
|
||||||
if (showGPU && s.gpuPercent != null) { l += Span("GPU ${s.gpuPercent}%", colGpu, stkPx) }
|
val labelPx = if (tiles) sp(st.key) else basePx
|
||||||
if (showCPU) { if (l.isNotEmpty()) l += Span(" · ", colDim, stkPx); l += Span("CPU ${s.cpuPercent ?: "—"}%", colCpu, stkPx) }
|
val valuePx = if (tiles) sp(st.row) else basePx
|
||||||
if (l.isNotEmpty()) stack.add(l)
|
if (key == "showPerCore" && size == DroidDeckHudSize.MEGA)
|
||||||
|
perCoreRows(s, labelPx, valuePx, unitPx)
|
||||||
|
else listOf(reading(key, s, labelPx, valuePx, unitPx))
|
||||||
}
|
}
|
||||||
if (showRAM) stack.add(listOf(Span("RAM ${s.ramPercent.roundToInt()}%", colRam, stkPx)))
|
val maxCols = if (size == DroidDeckHudSize.MEGA) 3 else 2
|
||||||
if (showBattery || showPower || showBatteryTemp) {
|
val cols = when {
|
||||||
val l = ArrayList<Span>()
|
listed.size >= 9 -> maxCols
|
||||||
fun part(spans: List<Span>) {
|
listed.size >= 4 -> minOf(2, maxCols)
|
||||||
l += if (l.isEmpty()) Span("BAT ", colBat, stkPx) else Span(" · ", colDim, stkPx)
|
else -> 1
|
||||||
l += spans
|
}
|
||||||
|
|
||||||
|
if (tiles) {
|
||||||
|
val innerPad = sp(st.innerPad); val tileGap = sp(st.tileGap)
|
||||||
|
val keyH = lineH(sp(st.key)); val valH = lineH(sp(st.row))
|
||||||
|
val cellW = listed.maxOf { max(measure(it.label.text, it.label.sizePx), runWidth(it.vals)) } + innerPad * 2f
|
||||||
|
val graphMin = if (listed.any { it.key == "showFPSGraph" }) sp(GRAPH_MIN_WIDTH_SP) else 0f
|
||||||
|
val cellMin = graphMin + innerPad * 2f
|
||||||
|
val cellH = innerPad * 2f + keyH + lineGap + valH
|
||||||
|
for ((i, r) in listed.withIndex()) {
|
||||||
|
val x = pad + (i % cols) * (cellW + tileGap)
|
||||||
|
val y = pad + (i / cols) * (cellH + tileGap)
|
||||||
|
tileRects.add(RectF(x, y, x + cellW, y + cellH))
|
||||||
|
if (r.key == "showFPSGraph") {
|
||||||
|
graphRect = RectF(x + innerPad, y + innerPad, x + max(cellW, cellMin) - innerPad, y + cellH - innerPad)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
placeRun(x + innerPad, y + innerPad - ascent(r.label.sizePx), listOf(r.label))
|
||||||
|
placeRun(x + innerPad, y + innerPad + keyH + lineGap - ascent(sp(st.row)), r.vals)
|
||||||
}
|
}
|
||||||
if (showBattery && s.battery.percent != null) part(listOf(Span("${s.battery.percent}%", colBat, stkPx)))
|
val lines = (listed.size + cols - 1) / cols
|
||||||
if (showBatteryTemp && s.battery.tempC != null)
|
contentW = pad + cols * (cellW + tileGap) - tileGap + pad
|
||||||
part(tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, stkPx, stkPx * 0.62f))
|
contentH = pad + lines * (cellH + tileGap) - tileGap + pad
|
||||||
if (showPower && s.battery.watts > 0f) part(listOf(Span("${fmt1(s.battery.watts)}W", colDim, stkPx)))
|
} else {
|
||||||
if (l.isNotEmpty()) stack.add(l)
|
val columns = (0 until cols).map { c -> listed.filterIndexed { i, _ -> i % cols == c } }
|
||||||
}
|
val labelW = columns.map { col -> col.maxOfOrNull { measure(it.label.text, it.label.sizePx) } ?: 0f }
|
||||||
run {
|
val colW = columns.mapIndexed { c, col ->
|
||||||
val l = ArrayList<Span>()
|
val body = if (col.isEmpty()) 0f else labelW[c] + lvGap + (col.maxOfOrNull { runWidth(it.vals) } ?: 0f)
|
||||||
l += Span("${fmt1(1000f / max(fpsNow, 1f))}ms", colDim, stkPx)
|
val graph = if (col.any { it.key == "showFPSGraph" }) sp(GRAPH_MIN_WIDTH_SP) + labelW[c] + lvGap else 0f
|
||||||
if (displayServer.isNotBlank()) { l += Span(" · ", colDim, stkPx); l += Span(displayServer, colDisp, stkPx) }
|
max(body, graph)
|
||||||
if (showVram && s.vramText() != null) { l += Span(" · ", colDim, stkPx); l += Span("${s.vramText()} vram", colDim, stkPx) }
|
}
|
||||||
stack.add(l)
|
val gaps = (0 until cols).count { columns[it].isNotEmpty() }.coerceAtLeast(1) - 1
|
||||||
}
|
val bodyW = colW.sum() + gutter * gaps
|
||||||
if (hdrState != DroidDeckHudHdr.NONE) stack.add(hdrLine(stkPx))
|
var bodyH = 0f
|
||||||
|
for (col in columns) {
|
||||||
var statsW = 0f
|
var y = 0f
|
||||||
for (l in stack) statsW = max(statsW, runWidth(l))
|
for (r in col) y += rowHeight(r) + lineGap
|
||||||
val nameOnTop = gpuName != null && runWidth(gpuName) > statsW
|
if (col.isNotEmpty()) bodyH = max(bodyH, y - lineGap)
|
||||||
if (gpuName != null && !nameOnTop) stack.add(0, gpuName)
|
}
|
||||||
|
val heroW = if (hero) runWidth(heroSpans) else 0f
|
||||||
val apiStr = apiLabel()
|
val heroH = if (hero) lineH(bigPx) else 0f
|
||||||
val hasApi = apiStr != "FPS"
|
val x0 = pad + if (hero && listed.isNotEmpty()) heroW + gutter else 0f
|
||||||
val apiH = if (hasApi) lineH(stkPx) else 0f
|
val top = pad + (max(bodyH, heroH) - bodyH) / 2f
|
||||||
val apiGap = if (hasApi) stkLineGap else 0f
|
var x = x0
|
||||||
|
for (c in 0 until cols) {
|
||||||
val leftW = runWidth(left); val leftH = lineH(bigPx)
|
if (columns[c].isEmpty()) continue
|
||||||
val apiW = if (hasApi) measure(apiStr, stkPx) else 0f
|
var y = top
|
||||||
val leftBlockW = max(leftW, apiW)
|
for (r in columns[c]) {
|
||||||
val leftColH = apiH + apiGap + leftH
|
if (r.key == "showFPSGraph") {
|
||||||
val stkH = lineH(stkPx)
|
val left = x + labelW[c] + lvGap
|
||||||
var stackW = 0f
|
graphRect = RectF(left, y, max(x + colW[c], left + sp(GRAPH_MIN_WIDTH_SP)), y + sp(GRAPH_HEIGHT_SP))
|
||||||
for (l in stack) stackW = max(stackW, runWidth(l))
|
y += sp(GRAPH_HEIGHT_SP) + lineGap
|
||||||
val stackTotalH = stack.size * stkH + (stack.size - 1).coerceAtLeast(0) * stkLineGap
|
continue
|
||||||
val innerH = max(leftColH, stackTotalH)
|
}
|
||||||
val topLineH = if (nameOnTop) stkH + stkLineGap else 0f
|
val px = maxOf(r.label.sizePx, r.vals.maxOfOrNull { it.sizePx } ?: 0f)
|
||||||
contentW = pad + leftBlockW + midGap + stackW + pad
|
val baseline = y - ascent(px)
|
||||||
contentH = pad + topLineH + innerH + pad
|
placeRun(x, baseline, listOf(r.label))
|
||||||
|
placeRun(x + labelW[c] + lvGap, baseline, r.vals)
|
||||||
var ly = pad + topLineH + (innerH - leftColH) / 2f
|
y += lineH(px) + lineGap
|
||||||
if (hasApi) {
|
}
|
||||||
placeRun(pad, ly - ascent(stkPx), listOf(Span(apiStr, colFps, stkPx)))
|
x += colW[c] + gutter
|
||||||
ly += apiH + apiGap
|
}
|
||||||
}
|
if (hero) {
|
||||||
placeRun(pad, ly - ascent(bigPx), left)
|
val baseline = pad + (max(bodyH, heroH) - heroH) / 2f - ascent(bigPx)
|
||||||
var sy = pad + topLineH + (innerH - stackTotalH) / 2f
|
placeRun(pad, baseline, heroSpans, glow = true)
|
||||||
for (l in stack) {
|
}
|
||||||
placeRun(pad + leftBlockW + midGap, sy - ascent(stkPx), l)
|
contentW = max(x0 + bodyW, pad + heroW) + pad
|
||||||
sy += stkH + stkLineGap
|
contentH = pad + max(bodyH, heroH) + pad
|
||||||
}
|
|
||||||
addSubtleClock(pad, leftAligned = true)
|
|
||||||
if (nameOnTop && gpuName != null) {
|
|
||||||
val end = placeRun(pad, pad - ascent(stkPx), gpuName)
|
|
||||||
contentW = max(contentW, end + pad)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun buildMinimal(s: HudMetrics.Snapshot) {
|
private fun rowHeight(r: HudRow): Float =
|
||||||
val bigPx = sp(34f); val bigUnitPx = bigPx * 0.32f; val subPx = sp(11.5f); val footPx = sp(9.5f)
|
if (r.key == "showFPSGraph") sp(GRAPH_HEIGHT_SP)
|
||||||
val stroke = outlineWidth()
|
else lineH(maxOf(r.label.sizePx, r.vals.maxOfOrNull { it.sizePx } ?: 0f))
|
||||||
val left = contentLeft()
|
|
||||||
val inner = panelInset() + stroke
|
|
||||||
|
|
||||||
val minGenerating = differs(fpsNow)
|
private fun perCoreRows(s: HudMetrics.Snapshot, labelPx: Float, valuePx: Float, unitPx: Float): List<HudRow> {
|
||||||
val big = listOf(
|
val pct = s.perCorePercent
|
||||||
Span(fpsText(fpsNow), colValue, if (minGenerating) bigPx * 0.55f else bigPx),
|
val clk = s.perCoreClockMhz
|
||||||
Span("fps", colDim, if (minGenerating) bigUnitPx * 0.8f else bigUnitPx))
|
return (0 until max(pct.size, clk.size)).map { i ->
|
||||||
val sub = ArrayList<Span>()
|
val vals = ArrayList<Span>()
|
||||||
fun low(label: String, value: Float) {
|
vals += numUnit(if (i < pct.size && pct[i] >= 0) pct[i].toString() else null, "%", valuePx, unitPx)
|
||||||
if (sub.isNotEmpty()) sub += Span(" · ", colDim, subPx)
|
vals += Span(" ", colDim, unitPx)
|
||||||
sub += Span("$label ", colDim, subPx)
|
vals += numUnit(if (i < clk.size && clk[i] > 0) clk[i].toString() else null, "MHz", valuePx, unitPx)
|
||||||
sub += Span(lowText(value) ?: "—", colFps, subPx)
|
HudRow("showPerCore", Span("C$i", colCpu, labelPx), vals)
|
||||||
}
|
}
|
||||||
if (showLow1) low("1%", lows.low1Fps)
|
|
||||||
if (showLow01) low("0.1%", lows.low01Fps)
|
|
||||||
if (showLow001) low("0.01%", lows.low001Fps)
|
|
||||||
val footerLabel = listOf(if (showEngine) engineLabel else "", displayServer)
|
|
||||||
.filter { it.isNotBlank() }.joinToString(" · ")
|
|
||||||
val hdr = if (hdrState != DroidDeckHudHdr.NONE) hdrLine(footPx) else emptyList()
|
|
||||||
|
|
||||||
val (headerBottom, headerRight) = addPanelHeader(left, inner)
|
|
||||||
val x = headerRight
|
|
||||||
|
|
||||||
val colW = maxOf(runWidth(big), runWidth(sub), x - left,
|
|
||||||
max(measure(footerLabel, footPx), runWidth(hdr)), if (showGraph) sp(120f) else 0f)
|
|
||||||
val bigBase = headerBottom + sp(8f) + capHeight(big[0].sizePx)
|
|
||||||
placeRun(left - inkLeft(big[0].text, big[0].sizePx), bigBase, big, glow = true)
|
|
||||||
var last = bigBase
|
|
||||||
if (sub.isNotEmpty()) {
|
|
||||||
last += sp(10f) + capHeight(subPx)
|
|
||||||
placeRun(left - inkLeft(sub[0].text, subPx), last, sub)
|
|
||||||
}
|
|
||||||
if (showGraph) {
|
|
||||||
val top = last + sp(9f)
|
|
||||||
graphRect = RectF(left, top, left + colW, top + sp(24f))
|
|
||||||
last = top + sp(24f)
|
|
||||||
}
|
|
||||||
if (footerLabel.isNotBlank()) {
|
|
||||||
val base = last + sp(8f) + capHeight(footPx)
|
|
||||||
glyphs.add(Glyph(left - inkLeft(footerLabel, footPx), base, footerLabel, blend(colDim), footPx))
|
|
||||||
last = base
|
|
||||||
}
|
|
||||||
if (hdr.isNotEmpty()) {
|
|
||||||
val base = last + sp(6f) + capHeight(footPx)
|
|
||||||
placeRun(left - inkLeft(hdr[0].text, footPx), base, hdr)
|
|
||||||
last = base
|
|
||||||
}
|
|
||||||
measurePaint.textSize = footPx
|
|
||||||
val panel = RectF(panelLeft(), panelInset(), left + colW + sp(34f), last + measurePaint.fontMetrics.descent + sp(9f) + stroke)
|
|
||||||
|
|
||||||
finishPanel(panel, halfRound = true)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun buildStrip(s: HudMetrics.Snapshot) {
|
private fun buildStrip(s: HudMetrics.Snapshot) {
|
||||||
@@ -1046,66 +942,27 @@ class DroidDeckHudView(context: Context) : View(context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
val generating = differs(fpsNow)
|
val generating = differs(fpsNow)
|
||||||
val fps = ArrayList<Span>()
|
for (key in size.rowsIn(storedOrder)) {
|
||||||
if (apiLabel() != "FPS") fps += Span("${apiLabel()} ", colDim, rowPx)
|
if (!switchOn(key)) continue
|
||||||
fps += Span(fpsText(fpsNow), colValue, if (generating) fpsPx * 0.8f else fpsPx, glow = true)
|
if (key == "showFPSGraph") {
|
||||||
fps += Span("fps", colDim, unitPx)
|
val gw = sp(72f); val gh = h * 0.55f
|
||||||
x = placeRun(x, baseline, fps) + groupGap
|
if (x + gw > right) break
|
||||||
|
|
||||||
if (showGraph) {
|
|
||||||
val gw = sp(72f); val gh = h * 0.55f
|
|
||||||
if (x + gw <= right) {
|
|
||||||
graphRect = RectF(x, mid - gh / 2f, x + gw, mid + gh / 2f)
|
graphRect = RectF(x, mid - gh / 2f, x + gw, mid + gh / 2f)
|
||||||
x += gw + groupGap
|
x += gw + groupGap
|
||||||
|
continue
|
||||||
}
|
}
|
||||||
}
|
val spans = if (key == "showFPS") {
|
||||||
|
val fps = ArrayList<Span>()
|
||||||
val groups = ArrayList<List<Span>>()
|
if (apiLabel() != "FPS") fps += Span("${apiLabel()} ", colDim, rowPx)
|
||||||
run {
|
fps += Span(fpsText(fpsNow), colValue, if (generating) fpsPx * 0.8f else fpsPx, glow = true)
|
||||||
val l = ArrayList<Span>()
|
fps += Span("fps", colDim, unitPx)
|
||||||
fun low(label: String, value: Float) {
|
fps
|
||||||
if (l.isNotEmpty()) l += Span(" ", colDim, rowPx)
|
} else {
|
||||||
l += Span("$label ", colDim, rowPx)
|
val row = reading(key, s, rowPx, rowPx, unitPx)
|
||||||
l += Span(lowText(value) ?: "—", colFps, rowPx)
|
listOf(row.label, Span(" ", colDim, rowPx)) + row.vals
|
||||||
}
|
}
|
||||||
if (showLow1) low("1%", lows.low1Fps)
|
if (x + runWidth(spans) > right) break
|
||||||
if (showLow01) low("0.1%", lows.low01Fps)
|
x = placeRun(x, baseline, spans) + groupGap
|
||||||
if (showLow001) low("0.01%", lows.low001Fps)
|
|
||||||
if (l.isNotEmpty()) groups += l
|
|
||||||
}
|
|
||||||
if (showGPU || showGpuTemp) {
|
|
||||||
val l = arrayListOf(Span("GPU", colGpu, rowPx))
|
|
||||||
if (showGPU) l += Span(" ${s.gpuPercent ?: "—"}%", colGpu, rowPx)
|
|
||||||
if (showGpuTemp && s.gpuTempC != null) { l += Span(" ", colDim, rowPx); l += tempSpans(s.gpuTempC, HudMetrics.TempSensor.GPU, rowPx, unitPx) }
|
|
||||||
groups += l
|
|
||||||
}
|
|
||||||
if (showCPU || showCpuTemp) {
|
|
||||||
val l = arrayListOf(Span("CPU", colCpu, rowPx))
|
|
||||||
if (showCPU) l += Span(" ${s.cpuPercent ?: "—"}%", colCpu, rowPx)
|
|
||||||
if (showCpuTemp && s.cpuTempC != null) { l += Span(" ", colDim, rowPx); l += tempSpans(s.cpuTempC, HudMetrics.TempSensor.CPU, rowPx, unitPx) }
|
|
||||||
groups += l
|
|
||||||
}
|
|
||||||
if (showVram) s.vramText()?.let { groups += listOf(Span("VRAM $it", colVram, rowPx)) }
|
|
||||||
if (showRAM) groups += listOf(Span("RAM ${s.ramPercent.roundToInt()}%", colRam, rowPx))
|
|
||||||
if (showBattery || showPower || showBatteryTemp) {
|
|
||||||
val l = ArrayList<Span>()
|
|
||||||
fun part(spans: List<Span>) {
|
|
||||||
l += if (l.isEmpty()) Span("BAT ", colBat, rowPx) else Span(" ", colDim, rowPx)
|
|
||||||
l += spans
|
|
||||||
}
|
|
||||||
if (showBattery && s.battery.percent != null) part(listOf(Span("${s.battery.percent}%", colBat, rowPx)))
|
|
||||||
if (showBatteryTemp && s.battery.tempC != null)
|
|
||||||
part(tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, rowPx, unitPx))
|
|
||||||
if (showPower && s.battery.watts > 0f) part(listOf(Span("${fmt1(s.battery.watts)}W", colDim, rowPx)))
|
|
||||||
if (l.isNotEmpty()) groups += l
|
|
||||||
}
|
|
||||||
if (displayServer.isNotBlank()) groups += listOf(Span(displayServer, colDisp, rowPx))
|
|
||||||
if (hdrState != DroidDeckHudHdr.NONE) groups += hdrLine(rowPx)
|
|
||||||
if (showGpuModel && gpuNameText().isNotBlank()) groups += gpuModelSpans(rowPx, colDim, compact = true)
|
|
||||||
|
|
||||||
for (g in groups) {
|
|
||||||
if (x + runWidth(g) > right) break
|
|
||||||
x = placeRun(x, baseline, g) + groupGap
|
|
||||||
}
|
}
|
||||||
|
|
||||||
stripRect = RectF(0f, 0f, w, h)
|
stripRect = RectF(0f, 0f, w, h)
|
||||||
@@ -1125,168 +982,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
|||||||
return inkRect.left.toFloat()
|
return inkRect.left.toFloat()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun layoutColumn(rows: List<HudRow>, x: Float, y0: Float,
|
|
||||||
rowPx: Float, lineGap: Float, lvGap: Float): Pair<Float, Float> {
|
|
||||||
if (rows.isEmpty()) return Pair(y0, x)
|
|
||||||
var labelCol = 0f
|
|
||||||
for (r in rows) if (!r.inline) labelCol = max(labelCol, measure(r.label.text, rowPx))
|
|
||||||
val h = lineH(rowPx); val asc = ascent(rowPx)
|
|
||||||
var y = y0; var right = x
|
|
||||||
for (r in rows) {
|
|
||||||
val baseline = y - asc
|
|
||||||
placeRun(x, baseline, listOf(r.label))
|
|
||||||
val valX = if (r.inline) x + measure(r.label.text, rowPx) + lvGap
|
|
||||||
else x + labelCol + lvGap
|
|
||||||
val end = placeRun(valX, baseline, r.vals)
|
|
||||||
right = max(right, end)
|
|
||||||
y += h + lineGap
|
|
||||||
}
|
|
||||||
return Pair(y - lineGap, right)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun layoutWrap(fragments: List<List<Span>>, x: Float, y0: Float, maxWidth: Float,
|
|
||||||
px: Float, lineGap: Float): Pair<Float, Float> {
|
|
||||||
if (fragments.isEmpty()) return Pair(y0, x)
|
|
||||||
val h = lineH(px); val asc = ascent(px)
|
|
||||||
val sepW = measure(" · ", px)
|
|
||||||
var cx = x; var y = y0; var right = x; var firstOnLine = true
|
|
||||||
for (frag in fragments) {
|
|
||||||
val w = runWidth(frag)
|
|
||||||
if (!firstOnLine && (cx + sepW + w - x) > maxWidth) { y += h + lineGap; cx = x; firstOnLine = true }
|
|
||||||
if (!firstOnLine) { placeRun(cx, y - asc, listOf(Span(" · ", colDim, px))); cx += sepW }
|
|
||||||
val end = placeRun(cx, y - asc, frag)
|
|
||||||
cx = end; right = max(right, end); firstOnLine = false
|
|
||||||
}
|
|
||||||
return Pair(y + h, right)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun buildMega(s: HudMetrics.Snapshot) {
|
|
||||||
val rowPx = sp(11.5f); val unitPx = rowPx * 0.62f; val bandPx = sp(9.5f)
|
|
||||||
val pad = sp(10f); val lineGap = sp(3.5f); val lvGap = sp(7f); val gutter = sp(16f)
|
|
||||||
|
|
||||||
val left = ArrayList<HudRow>()
|
|
||||||
if (showGpuModel && gpuNameText().isNotBlank())
|
|
||||||
left.add(HudRow(Span("GPU", colGpu, rowPx), gpuModelSpans(rowPx, colValue)))
|
|
||||||
if (showGPU && hasGpuStats(s)) {
|
|
||||||
val v = ArrayList<Span>()
|
|
||||||
v += numUnit(s.gpuPercent?.toString(), "%", rowPx, unitPx)
|
|
||||||
if (showGpuTemp) tempSpans(s.gpuTempC, HudMetrics.TempSensor.GPU, rowPx, unitPx)
|
|
||||||
.let { if (it.isNotEmpty()) { v += gap(unitPx); v += it } }
|
|
||||||
v += gap(unitPx); v += numUnit(s.gpuClockMhz?.toString(), "MHz", rowPx, unitPx)
|
|
||||||
left.add(HudRow(Span("GPU", colGpu, rowPx), v))
|
|
||||||
}
|
|
||||||
if (showCPU) {
|
|
||||||
val v = ArrayList<Span>()
|
|
||||||
v += numUnit(s.cpuPercent?.toString(), "%", rowPx, unitPx)
|
|
||||||
v += gap(unitPx); v += numUnit(s.cpuClockMhz?.toString(), "MHz", rowPx, unitPx)
|
|
||||||
if (showCpuTemp) tempSpans(s.cpuTempC, HudMetrics.TempSensor.CPU, rowPx, unitPx)
|
|
||||||
.let { if (it.isNotEmpty()) { v += gap(unitPx); v += it } }
|
|
||||||
left.add(HudRow(Span("CPU", colCpu, rowPx), v))
|
|
||||||
}
|
|
||||||
if (showPerCore) {
|
|
||||||
val pct = s.perCorePercent; val clk = s.perCoreClockMhz
|
|
||||||
val n = max(pct.size, clk.size)
|
|
||||||
for (i in 0 until n) {
|
|
||||||
val v = ArrayList<Span>()
|
|
||||||
v += numUnit(if (i < pct.size && pct[i] >= 0) pct[i].toString() else null, "%", rowPx, unitPx)
|
|
||||||
v += gap(unitPx)
|
|
||||||
v += numUnit(if (i < clk.size && clk[i] > 0) clk[i].toString() else null, "MHz", rowPx, unitPx)
|
|
||||||
left.add(HudRow(Span("C$i", colCpu, rowPx), v))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
val right = ArrayList<HudRow>()
|
|
||||||
if (showVram && s.vramText() != null)
|
|
||||||
right.add(HudRow(Span("VRAM", colVram, rowPx), valueUnit(s.vramText()!!, rowPx, unitPx)))
|
|
||||||
if (showRAM) {
|
|
||||||
val v = ArrayList<Span>()
|
|
||||||
v += valueUnit(s.ramUsedText(), rowPx, unitPx)
|
|
||||||
v += Span("/", colDim, unitPx); v += valueUnit(s.ramTotalText(), rowPx, unitPx)
|
|
||||||
v += gap(unitPx); v += numUnit(s.ramPercent.roundToInt().toString(), "%", rowPx, unitPx)
|
|
||||||
right.add(HudRow(Span("RAM", colRam, rowPx), v))
|
|
||||||
}
|
|
||||||
if (showSwap && s.swapUsedText() != null) {
|
|
||||||
val v = ArrayList<Span>()
|
|
||||||
v += valueUnit(s.swapUsedText()!!, rowPx, unitPx)
|
|
||||||
s.swapTotalText()?.let { v += Span("/", colDim, unitPx); v += valueUnit(it, rowPx, unitPx) }
|
|
||||||
right.add(HudRow(Span("SWP", colRam, rowPx), v))
|
|
||||||
}
|
|
||||||
if (showNet && s.netDownBps != null) {
|
|
||||||
val d = (s.netDownBps ?: 0L) / 1024L
|
|
||||||
val u = (s.netUpBps ?: 0L) / 1024L
|
|
||||||
val v = ArrayList<Span>()
|
|
||||||
v += Span("↓", colDim, unitPx); v += Span(d.toString(), colValue, rowPx)
|
|
||||||
v += Span(" ↑", colDim, unitPx); v += Span(u.toString(), colValue, rowPx)
|
|
||||||
v += Span("KB/s", colDim, unitPx)
|
|
||||||
right.add(HudRow(Span("NET", colFps, rowPx), v))
|
|
||||||
}
|
|
||||||
if (showBattery || showPower || showBatteryTemp) {
|
|
||||||
val v = ArrayList<Span>(); var any = false
|
|
||||||
if (showBattery && s.battery.percent != null) { v += numUnit(s.battery.percent.toString(), "%", rowPx, unitPx); any = true }
|
|
||||||
if (showBatteryTemp) tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, rowPx, unitPx)
|
|
||||||
.let { if (it.isNotEmpty()) { if (any) v += gap(unitPx); v += it; any = true } }
|
|
||||||
if (showPower && s.battery.watts > 0f) { if (any) v += gap(unitPx); v += numUnit(fmt1(s.battery.watts), "W", rowPx, unitPx); any = true }
|
|
||||||
if (any) right.add(HudRow(Span("BAT", colBat, rowPx), v))
|
|
||||||
}
|
|
||||||
if (showFPS) {
|
|
||||||
val v = ArrayList<Span>()
|
|
||||||
v += glowing(numUnit(fpsText(fpsNow), "FPS", rowPx, unitPx))
|
|
||||||
v += gap(unitPx); v += numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", rowPx, unitPx)
|
|
||||||
right.add(HudRow(Span(apiLabel(), colFps, rowPx), v))
|
|
||||||
right.add(HudRow(Span("AVG", colLo, rowPx), numUnit(fmt1(fpsAvg), "FPS", rowPx, unitPx)))
|
|
||||||
if (showLow1)
|
|
||||||
right.add(HudRow(Span("1%", colLo, rowPx), numUnit(lowText(lows.low1Fps), "FPS", rowPx, unitPx)))
|
|
||||||
if (showLow01)
|
|
||||||
right.add(HudRow(Span("0.1%", colLo, rowPx), numUnit(lowText(lows.low01Fps), "FPS", rowPx, unitPx)))
|
|
||||||
if (showLow001)
|
|
||||||
right.add(HudRow(Span("0.01%", colLo, rowPx), numUnit(lowText(lows.low001Fps), "FPS", rowPx, unitPx)))
|
|
||||||
}
|
|
||||||
|
|
||||||
val (leftBottom, leftRight) = layoutColumn(left, pad, pad, rowPx, lineGap, lvGap)
|
|
||||||
val rightX = (if (left.isEmpty()) pad else leftRight + gutter)
|
|
||||||
val (rightBottom, rightRight) = layoutColumn(right, rightX, pad, rowPx, lineGap, lvGap)
|
|
||||||
var y = max(leftBottom, rightBottom)
|
|
||||||
var maxRight = max(leftRight, rightRight)
|
|
||||||
|
|
||||||
val band = ArrayList<List<Span>>()
|
|
||||||
if (showResolution) band.add(listOf(Span("RES ", colDim, bandPx), Span(resolutionString(), colValue, bandPx)))
|
|
||||||
if (displayServer.isNotBlank()) band.add(listOf(Span("DISP ", colDim, bandPx), Span(displayServer, colDisp, bandPx)))
|
|
||||||
if (hdrState != DroidDeckHudHdr.NONE) band.add(listOf(Span("HDR ", colDim, bandPx)) + hdrValue(bandPx))
|
|
||||||
if (showProton && wineVersion.isNotBlank()) band.add(listOf(Span(wineVersion, colVram, bandPx)))
|
|
||||||
if (showSession) band.add(listOf(Span("elapsed ", colDim, bandPx), Span(elapsedString(), colValue, bandPx)))
|
|
||||||
if (band.isNotEmpty()) {
|
|
||||||
y += sp(4f)
|
|
||||||
val (bBottom, bRight) = layoutWrap(band, pad, y, max(maxRight - pad, sp(180f)), bandPx, lineGap)
|
|
||||||
y = bBottom; maxRight = max(maxRight, bRight)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (showGraph) {
|
|
||||||
y += sp(3f)
|
|
||||||
val gh = sp(22f)
|
|
||||||
val gr = max(maxRight, pad + sp(220f))
|
|
||||||
graphRect = RectF(pad, y, gr, y + gh)
|
|
||||||
maxRight = max(maxRight, gr)
|
|
||||||
y += gh
|
|
||||||
}
|
|
||||||
|
|
||||||
val dxLine = dxVersionLabeled()
|
|
||||||
val hasDx = showDxVer && dxLine.isNotBlank()
|
|
||||||
if (hasDx) {
|
|
||||||
y += sp(4f)
|
|
||||||
maxRight = max(maxRight, placeRun(pad, y - ascent(bandPx), listOf(Span(dxLine, colDim, bandPx))))
|
|
||||||
y += lineH(bandPx)
|
|
||||||
}
|
|
||||||
if (showWrapper && graphicsWrapper.isNotBlank()) {
|
|
||||||
y += if (hasDx) sp(1f) else sp(4f)
|
|
||||||
maxRight = max(maxRight, placeRun(pad, y - ascent(bandPx), listOf(Span(graphicsWrapper, colDim, bandPx))))
|
|
||||||
y += lineH(bandPx)
|
|
||||||
}
|
|
||||||
|
|
||||||
contentW = maxRight + pad
|
|
||||||
contentH = y + pad
|
|
||||||
addSubtleClock(pad)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
|
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
|
||||||
if (stripRect != null) { setMeasuredDimension(contentW.roundToInt(), resolveSize(contentH.roundToInt(), heightMeasureSpec)); return }
|
if (stripRect != null) { setMeasuredDimension(contentW.roundToInt(), resolveSize(contentH.roundToInt(), heightMeasureSpec)); return }
|
||||||
setMeasuredDimension(
|
setMeasuredDimension(
|
||||||
@@ -1567,6 +1262,8 @@ class DroidDeckHudView(context: Context) : View(context) {
|
|||||||
const val MIN_SCALE = 0.5f
|
const val MIN_SCALE = 0.5f
|
||||||
const val MAX_SCALE = 2f
|
const val MAX_SCALE = 2f
|
||||||
const val GRAPH_CLIP_MS = 49.9f
|
const val GRAPH_CLIP_MS = 49.9f
|
||||||
|
const val GRAPH_HEIGHT_SP = 22f
|
||||||
|
const val GRAPH_MIN_WIDTH_SP = 160f
|
||||||
|
|
||||||
fun parseIntOr(s: String?, d: Int): Int = try { s?.trim()?.toInt() ?: d } catch (e: Exception) { d }
|
fun parseIntOr(s: String?, d: Int): Int = try { s?.trim()?.toInt() ?: d } catch (e: Exception) { d }
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.droiddeck.launcher.hud
|
package com.droiddeck.launcher.hud
|
||||||
|
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
import java.io.RandomAccessFile
|
||||||
import kotlin.math.roundToInt
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
internal class FrameStats {
|
internal class FrameStats {
|
||||||
@@ -159,7 +160,11 @@ internal class FrameStats {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal class GameFrameFeed(private val file: File, val stats: FrameStats = FrameStats()) {
|
internal class GameFrameFeed(
|
||||||
|
private val file: File,
|
||||||
|
val stats: FrameStats = FrameStats(),
|
||||||
|
private val clockControl: File? = null,
|
||||||
|
) {
|
||||||
private var handle = 0L
|
private var handle = 0L
|
||||||
private var nextOpenNs = 0L
|
private var nextOpenNs = 0L
|
||||||
private var lastRingFrameNs = 0L
|
private var lastRingFrameNs = 0L
|
||||||
@@ -171,6 +176,8 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
|
|||||||
private var lastCompositorNs = 0L
|
private var lastCompositorNs = 0L
|
||||||
@Volatile private var compositorFrames = 0L
|
@Volatile private var compositorFrames = 0L
|
||||||
private var seenCompositorFrames = 0L
|
private var seenCompositorFrames = 0L
|
||||||
|
private var clockShiftNs = 0L
|
||||||
|
private var clockShiftReadNs = Long.MIN_VALUE
|
||||||
|
|
||||||
@Volatile var engine = ""
|
@Volatile var engine = ""
|
||||||
private set
|
private set
|
||||||
@@ -199,6 +206,9 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
|
|||||||
}
|
}
|
||||||
val n = HudFrames.nativePoll(handle, frametimes, times)
|
val n = HudFrames.nativePoll(handle, frametimes, times)
|
||||||
if (n > 0) {
|
if (n > 0) {
|
||||||
|
var shift = guestClockShift(nowNs, SHIFT_NS)
|
||||||
|
if (nowNs - (times[n - 1] + shift) > LIVE_NS) shift = guestClockShift(nowNs, SHIFT_RECHECK_NS)
|
||||||
|
for (i in 0 until n) times[i] += shift
|
||||||
if (!fromGamescope) {
|
if (!fromGamescope) {
|
||||||
stats.reset()
|
stats.reset()
|
||||||
fromGamescope = true
|
fromGamescope = true
|
||||||
@@ -216,6 +226,16 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
|
|||||||
return n > 0 || compositorAdded
|
return n > 0 || compositorAdded
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal fun guestClockShift(nowNs: Long, maxAgeNs: Long): Long {
|
||||||
|
val control = clockControl ?: return 0L
|
||||||
|
if (clockShiftReadNs != Long.MIN_VALUE && nowNs - clockShiftReadNs < maxAgeNs) return clockShiftNs
|
||||||
|
clockShiftReadNs = nowNs
|
||||||
|
clockShiftNs = runCatching {
|
||||||
|
RandomAccessFile(control, "r").use { if (it.length() < Long.SIZE_BYTES) 0L else java.lang.Long.reverseBytes(it.readLong()) }
|
||||||
|
}.getOrDefault(0L).coerceAtLeast(0L)
|
||||||
|
return clockShiftNs
|
||||||
|
}
|
||||||
|
|
||||||
fun onCompositorFrame(nowNs: Long) {
|
fun onCompositorFrame(nowNs: Long) {
|
||||||
if (fromGamescope) {
|
if (fromGamescope) {
|
||||||
lastCompositorNs = 0L
|
lastCompositorNs = 0L
|
||||||
@@ -253,6 +273,11 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
|
|||||||
private const val LIVE_NS = 2_000_000_000L
|
private const val LIVE_NS = 2_000_000_000L
|
||||||
private const val STALE_NS = 5_000_000_000L
|
private const val STALE_NS = 5_000_000_000L
|
||||||
private const val INFO_NS = 500_000_000L
|
private const val INFO_NS = 500_000_000L
|
||||||
|
private const val SHIFT_NS = 1_000_000_000L
|
||||||
|
private const val SHIFT_RECHECK_NS = 100_000_000L
|
||||||
|
private const val CLOCK_CONTROL_PATH = "tmp/.bl-clock"
|
||||||
|
|
||||||
|
fun forRoot(root: File) = GameFrameFeed(File(root, HudFrames.PATH), clockControl = File(root, CLOCK_CONTROL_PATH))
|
||||||
|
|
||||||
fun engineLabel(name: String): String = when (name) {
|
fun engineLabel(name: String): String = when (name) {
|
||||||
"DXVK" -> "DXVK"
|
"DXVK" -> "DXVK"
|
||||||
|
|||||||
@@ -50,6 +50,7 @@ public class HudLockController {
|
|||||||
private final Callbacks cb;
|
private final Callbacks cb;
|
||||||
private final GestureDetector detector;
|
private final GestureDetector detector;
|
||||||
private final ScaleGestureDetector scaleDetector;
|
private final ScaleGestureDetector scaleDetector;
|
||||||
|
private final android.view.VelocityTracker velocity = android.view.VelocityTracker.obtain();
|
||||||
|
|
||||||
private boolean locked = false;
|
private boolean locked = false;
|
||||||
|
|
||||||
@@ -86,8 +87,18 @@ public class HudLockController {
|
|||||||
public boolean onTouchEvent(MotionEvent event) {
|
public boolean onTouchEvent(MotionEvent event) {
|
||||||
scaleDetector.onTouchEvent(event);
|
scaleDetector.onTouchEvent(event);
|
||||||
detector.onTouchEvent(event);
|
detector.onTouchEvent(event);
|
||||||
|
// The HUD moves under the finger, so the throw is measured on the screen, not in the HUD.
|
||||||
|
MotionEvent onScreen = MotionEvent.obtain(event);
|
||||||
|
onScreen.setLocation(event.getRawX(), event.getRawY());
|
||||||
|
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) velocity.clear();
|
||||||
|
velocity.addMovement(onScreen);
|
||||||
|
onScreen.recycle();
|
||||||
int action = event.getActionMasked();
|
int action = event.getActionMasked();
|
||||||
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
|
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
|
||||||
|
if (dragging && !locked && !pinched && action == MotionEvent.ACTION_UP) {
|
||||||
|
velocity.computeCurrentVelocity(1000);
|
||||||
|
cb.onFlung(velocity.getXVelocity(), velocity.getYVelocity());
|
||||||
|
}
|
||||||
if (dragging && !locked) cb.onMoved(view.getX(), view.getY());
|
if (dragging && !locked) cb.onMoved(view.getX(), view.getY());
|
||||||
dragging = false;
|
dragging = false;
|
||||||
}
|
}
|
||||||
@@ -124,12 +135,6 @@ public class HudLockController {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
|
|
||||||
if (dragging && !locked && !pinched) cb.onFlung(velocityX, velocityY);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
|
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
|
||||||
if (pinched) return true;
|
if (pinched) return true;
|
||||||
|
|||||||
@@ -14,6 +14,8 @@
|
|||||||
|
|
||||||
package com.droiddeck.launcher.hud;
|
package com.droiddeck.launcher.hud;
|
||||||
|
|
||||||
|
import com.droiddeck.launcher.session.BatteryRuntimeEstimator;
|
||||||
|
|
||||||
import android.app.ActivityManager;
|
import android.app.ActivityManager;
|
||||||
import android.content.Context;
|
import android.content.Context;
|
||||||
import android.content.Intent;
|
import android.content.Intent;
|
||||||
@@ -560,10 +562,9 @@ public class HudMetrics {
|
|||||||
return sawSignal;
|
return sawSignal;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Double smoothedBatteryRuntimeHours = null;
|
private final BatteryRuntimeEstimator batteryRuntimeEstimator = new BatteryRuntimeEstimator();
|
||||||
private static final double MAX_RUNTIME_HOURS = 72.0;
|
private Boolean lastBatteryDischarging = null;
|
||||||
private static final double RUNTIME_SMOOTHING_OLD_WEIGHT = 0.65;
|
private Boolean lastBatteryCharging = null;
|
||||||
private static final double RUNTIME_SMOOTHING_NEW_WEIGHT = 0.35;
|
|
||||||
|
|
||||||
public Battery collectBattery() {
|
public Battery collectBattery() {
|
||||||
BatteryManager bm = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
|
BatteryManager bm = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
|
||||||
@@ -581,11 +582,22 @@ public class HudMetrics {
|
|||||||
|
|
||||||
int st = status.getIntExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_UNKNOWN);
|
int st = status.getIntExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_UNKNOWN);
|
||||||
boolean charging = st == BatteryManager.BATTERY_STATUS_CHARGING || st == BatteryManager.BATTERY_STATUS_FULL;
|
boolean charging = st == BatteryManager.BATTERY_STATUS_CHARGING || st == BatteryManager.BATTERY_STATUS_FULL;
|
||||||
|
boolean discharging = st == BatteryManager.BATTERY_STATUS_DISCHARGING
|
||||||
|
|| st == BatteryManager.BATTERY_STATUS_NOT_CHARGING;
|
||||||
|
if (lastBatteryDischarging != null && lastBatteryDischarging.booleanValue() != discharging) {
|
||||||
|
batteryRuntimeEstimator.reset();
|
||||||
|
}
|
||||||
|
lastBatteryDischarging = discharging;
|
||||||
if (st == BatteryManager.BATTERY_STATUS_UNKNOWN) {
|
if (st == BatteryManager.BATTERY_STATUS_UNKNOWN) {
|
||||||
Boolean sysCharging = readChargingFromPowerSupply();
|
Boolean sysCharging = readChargingFromPowerSupply();
|
||||||
if (sysCharging != null) charging = sysCharging;
|
if (sysCharging != null) charging = sysCharging;
|
||||||
}
|
}
|
||||||
long currentMicroAmps = Math.abs(bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW));
|
if (lastBatteryCharging != null
|
||||||
|
&& lastBatteryCharging.booleanValue() != charging) {
|
||||||
|
batteryRuntimeEstimator.reset();
|
||||||
|
}
|
||||||
|
lastBatteryCharging = charging;
|
||||||
|
long currentMicroAmps = BatteryRuntimeEstimator.toMicroamps(bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW));
|
||||||
long chargeCounter = bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER);
|
long chargeCounter = bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER);
|
||||||
int voltageMv = status.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);
|
int voltageMv = status.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);
|
||||||
|
|
||||||
@@ -606,36 +618,16 @@ public class HudMetrics {
|
|||||||
if (uw != null && uw != 0L) watts = (float) (Math.abs(uw) / 1_000_000.0);
|
if (uw != null && uw != 0L) watts = (float) (Math.abs(uw) / 1_000_000.0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Double runtimeHours = !charging
|
||||||
|
? batteryRuntimeEstimator.estimateHours(chargeCounter, Math.abs((double) currentMicroAmps))
|
||||||
|
: null;
|
||||||
String runtimeText;
|
String runtimeText;
|
||||||
if (charging) {
|
if (st == BatteryManager.BATTERY_STATUS_FULL || (percent != null && percent >= 100)) runtimeText = "Full";
|
||||||
smoothedBatteryRuntimeHours = null;
|
else if (charging) runtimeText = "Charging";
|
||||||
runtimeText = "LEFT CHG";
|
else runtimeText = BatteryRuntimeEstimator.formatDuration(runtimeHours);
|
||||||
} else if (currentMicroAmps <= 0L || chargeCounter <= 0L) {
|
|
||||||
runtimeText = null;
|
|
||||||
} else {
|
|
||||||
double rawHours = (double) chargeCounter / (double) currentMicroAmps;
|
|
||||||
if (!Double.isFinite(rawHours) || rawHours <= 0.0 || rawHours > MAX_RUNTIME_HOURS) {
|
|
||||||
runtimeText = null;
|
|
||||||
} else {
|
|
||||||
double smoothed = smoothedBatteryRuntimeHours == null ? rawHours
|
|
||||||
: (smoothedBatteryRuntimeHours * RUNTIME_SMOOTHING_OLD_WEIGHT)
|
|
||||||
+ (rawHours * RUNTIME_SMOOTHING_NEW_WEIGHT);
|
|
||||||
smoothedBatteryRuntimeHours = smoothed;
|
|
||||||
runtimeText = "LEFT " + formatRuntimeHours(smoothed);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return new Battery(watts, charging, percent, tempC, runtimeText);
|
return new Battery(watts, charging, percent, tempC, runtimeText);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String formatRuntimeHours(double hours) {
|
|
||||||
int totalMinutes = Math.max(1, (int) Math.round(hours * 60.0));
|
|
||||||
int wholeHours = totalMinutes / 60;
|
|
||||||
int minutes = totalMinutes % 60;
|
|
||||||
if (wholeHours > 0 && minutes > 0) return wholeHours + "h " + minutes + "m";
|
|
||||||
if (wholeHours > 0) return wholeHours + "h";
|
|
||||||
return minutes + "m";
|
|
||||||
}
|
|
||||||
|
|
||||||
private static float currentRawToAmps(long raw) {
|
private static float currentRawToAmps(long raw) {
|
||||||
if (raw == 0L || raw == Long.MIN_VALUE) return 0f;
|
if (raw == 0L || raw == Long.MIN_VALUE) return 0f;
|
||||||
long a = Math.abs(raw);
|
long a = Math.abs(raw);
|
||||||
@@ -651,15 +643,10 @@ public class HudMetrics {
|
|||||||
return currentRawToAmps(raw);
|
return currentRawToAmps(raw);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Integer getCpuClockMhz() {
|
static Integer fastestCoreMhz(int[] perCoreMhz) {
|
||||||
int cores = Runtime.getRuntime().availableProcessors();
|
int max = 0;
|
||||||
long maxKhz = 0;
|
for (int mhz : perCoreMhz) max = Math.max(max, mhz);
|
||||||
for (int i = 0; i < cores; i++) {
|
return max > 0 ? max : null;
|
||||||
Long cur = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/scaling_cur_freq");
|
|
||||||
if (cur != null && cur > maxKhz) maxKhz = cur;
|
|
||||||
}
|
|
||||||
if (maxKhz <= 0) return null;
|
|
||||||
return (int) (maxKhz / 1000L);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<String> gpuClockPathsCache = null;
|
private List<String> gpuClockPathsCache = null;
|
||||||
@@ -809,7 +796,8 @@ public class HudMetrics {
|
|||||||
if (mango != null) return mangoSnapshot(mango);
|
if (mango != null) return mangoSnapshot(mango);
|
||||||
Integer cpu = getCpuUsagePercent();
|
Integer cpu = getCpuUsagePercent();
|
||||||
Integer gpu = getGpuUsagePercent();
|
Integer gpu = getGpuUsagePercent();
|
||||||
Integer cpuClk = getCpuClockMhz();
|
int[] perCoreClk = getPerCoreClockMhz();
|
||||||
|
Integer cpuClk = fastestCoreMhz(perCoreClk);
|
||||||
Integer gpuClk = getGpuClockMhz();
|
Integer gpuClk = getGpuClockMhz();
|
||||||
Integer cpuTemp = getCpuTempC();
|
Integer cpuTemp = getCpuTempC();
|
||||||
Integer gpuTemp = getGpuTempC();
|
Integer gpuTemp = getGpuTempC();
|
||||||
@@ -829,7 +817,6 @@ public class HudMetrics {
|
|||||||
Battery battery = collectBattery();
|
Battery battery = collectBattery();
|
||||||
|
|
||||||
int[] perCorePct = readPerCorePercent();
|
int[] perCorePct = readPerCorePercent();
|
||||||
int[] perCoreClk = getPerCoreClockMhz();
|
|
||||||
long[] swap = getSwapBytes();
|
long[] swap = getSwapBytes();
|
||||||
long[] net = readNetRateBps();
|
long[] net = readNetRateBps();
|
||||||
|
|
||||||
@@ -848,26 +835,65 @@ public class HudMetrics {
|
|||||||
Battery android = collectBattery();
|
Battery android = collectBattery();
|
||||||
MangoReadings.Battery bat = m.battery();
|
MangoReadings.Battery bat = m.battery();
|
||||||
Battery battery = bat == null ? android : new Battery(bat.getWatts(), bat.getCharging(),
|
Battery battery = bat == null ? android : new Battery(bat.getWatts(), bat.getCharging(),
|
||||||
bat.getPercent() != null ? bat.getPercent() : android.percent, android.tempC, android.runtimeText);
|
bat.getPercent() != null ? bat.getPercent() : android.percent, android.tempC, bat.getRuntimeText());
|
||||||
long[] net = readNetRateBps();
|
long[] net = readNetRateBps();
|
||||||
return new Snapshot(cpu != null ? cpu.getPercent() : null, m.gpuPercent(), getCpuClockMhz(), m.gpuClockMhz(),
|
int[] perCoreClk = getPerCoreClockMhz();
|
||||||
|
return new Snapshot(cpu != null ? cpu.getPercent() : null, m.gpuPercent(), fastestCoreMhz(perCoreClk), m.gpuClockMhz(),
|
||||||
m.cpuTempC(), m.gpuTempC(), used, total, total > 0 ? used * 100f / total : 0f, m.vramBytes(), battery,
|
m.cpuTempC(), m.gpuTempC(), used, total, total > 0 ? used * 100f / total : 0f, m.vramBytes(), battery,
|
||||||
cpu != null ? cpu.getPerCore() : new int[0], getPerCoreClockMhz(),
|
cpu != null ? cpu.getPerCore() : new int[0], perCoreClk,
|
||||||
mem != null && mem.getSwapTotalBytes() > 0 ? mem.getSwapUsedBytes() : null,
|
mem != null && mem.getSwapTotalBytes() > 0 ? mem.getSwapUsedBytes() : null,
|
||||||
mem != null && mem.getSwapTotalBytes() > 0 ? mem.getSwapTotalBytes() : null,
|
mem != null && mem.getSwapTotalBytes() > 0 ? mem.getSwapTotalBytes() : null,
|
||||||
net == null ? null : net[0], net == null ? null : net[1]);
|
net == null ? null : net[0], net == null ? null : net[1]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public int[] getPerCoreClockMhz() {
|
private final java.util.Map<Integer, long[][]> lastTimeInState = new java.util.HashMap<>();
|
||||||
|
|
||||||
|
public synchronized int[] getPerCoreClockMhz() {
|
||||||
int cores = Runtime.getRuntime().availableProcessors();
|
int cores = Runtime.getRuntime().availableProcessors();
|
||||||
int[] out = new int[Math.max(0, cores)];
|
int[] out = new int[Math.max(0, cores)];
|
||||||
for (int i = 0; i < out.length; i++) {
|
for (int i = 0; i < out.length; i++) {
|
||||||
Long cur = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/scaling_cur_freq");
|
long[][] table = readTimeInState("/sys/devices/system/cpu/cpu" + i + "/cpufreq/stats/time_in_state");
|
||||||
out[i] = (cur != null && cur > 0) ? (int) (cur / 1000L) : 0;
|
long khz = table == null ? -1L : averageKhz(lastTimeInState.put(i, table), table);
|
||||||
|
if (khz <= 0L) {
|
||||||
|
Long cur = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/scaling_cur_freq");
|
||||||
|
khz = cur != null ? cur : 0L;
|
||||||
|
}
|
||||||
|
out[i] = khz > 0L ? (int) (khz / 1000L) : 0;
|
||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static long averageKhz(long[][] before, long[][] after) {
|
||||||
|
if (before == null || after == null || !java.util.Arrays.equals(before[0], after[0])) return -1L;
|
||||||
|
long weighted = 0L, time = 0L;
|
||||||
|
for (int i = 0; i < after[0].length; i++) {
|
||||||
|
long dt = after[1][i] - before[1][i];
|
||||||
|
if (dt <= 0L) continue;
|
||||||
|
weighted += after[0][i] * dt;
|
||||||
|
time += dt;
|
||||||
|
}
|
||||||
|
return time > 0L ? weighted / time : -1L;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static long[][] readTimeInState(String path) {
|
||||||
|
List<long[]> rows = new ArrayList<>();
|
||||||
|
try (BufferedReader r = new BufferedReader(new FileReader(path))) {
|
||||||
|
String line;
|
||||||
|
while ((line = r.readLine()) != null) {
|
||||||
|
String[] parts = line.trim().split("\\s+");
|
||||||
|
if (parts.length < 2) continue;
|
||||||
|
try { rows.add(new long[] { Long.parseLong(parts[0]), Long.parseLong(parts[1]) }); }
|
||||||
|
catch (NumberFormatException ignored) {}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (rows.isEmpty()) return null;
|
||||||
|
long[][] table = new long[2][rows.size()];
|
||||||
|
for (int i = 0; i < rows.size(); i++) { table[0][i] = rows.get(i)[0]; table[1][i] = rows.get(i)[1]; }
|
||||||
|
return table;
|
||||||
|
}
|
||||||
|
|
||||||
private long[] lastCoreTotal = null;
|
private long[] lastCoreTotal = null;
|
||||||
private long[] lastCoreIdle = null;
|
private long[] lastCoreIdle = null;
|
||||||
private static final int PER_CORE_STAT = 1, PER_CORE_ESTIMATE = 2;
|
private static final int PER_CORE_STAT = 1, PER_CORE_ESTIMATE = 2;
|
||||||
|
|||||||
@@ -2,13 +2,18 @@ package com.droiddeck.launcher.hud
|
|||||||
|
|
||||||
import android.os.Environment
|
import android.os.Environment
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
|
import com.droiddeck.launcher.session.BatteryRuntimeEstimator
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
import kotlin.math.abs
|
||||||
import kotlin.math.roundToInt
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
internal class MangoReadings(private val sessionDir: File, private val rootDir: File) {
|
internal class MangoReadings(private val sessionDir: File, private val rootDir: File) {
|
||||||
class Cpu(val percent: Int, val perCore: IntArray)
|
class Cpu(val percent: Int, val perCore: IntArray)
|
||||||
class Memory(val usedBytes: Long, val totalBytes: Long, val swapUsedBytes: Long, val swapTotalBytes: Long)
|
class Memory(val usedBytes: Long, val totalBytes: Long, val swapUsedBytes: Long, val swapTotalBytes: Long)
|
||||||
class Battery(val percent: Int?, val watts: Float, val charging: Boolean)
|
class Battery(val percent: Int?, val watts: Float, val charging: Boolean, val runtimeText: String?)
|
||||||
|
|
||||||
|
private val batteryRuntimeEstimator = BatteryRuntimeEstimator()
|
||||||
|
private var lastBatteryDischarging: Boolean? = null
|
||||||
|
|
||||||
private val cpuTimes = HashMap<String, LongArray>()
|
private val cpuTimes = HashMap<String, LongArray>()
|
||||||
private val cpuPercents = HashMap<String, Int>()
|
private val cpuPercents = HashMap<String, Int>()
|
||||||
@@ -106,32 +111,113 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
|
|||||||
fun vramBytes(): Long? = fresh(File(rootDir, VRAM_FILE), VRAM_FRESH_MS)?.let(::readLong)?.takeIf { it > 0 }
|
fun vramBytes(): Long? = fresh(File(rootDir, VRAM_FILE), VRAM_FRESH_MS)?.let(::readLong)?.takeIf { it > 0 }
|
||||||
|
|
||||||
fun battery(): Battery? {
|
fun battery(): Battery? {
|
||||||
val dirs = File(sessionDir, "sys/power_supply").listFiles { f -> f.name.contains("BAT") }?.sortedBy { it.name }
|
val dirs = File(sessionDir, "sys/power_supply").listFiles { f -> f.name.contains("BAT") }?.sortedBy { it.name }?.take(2)
|
||||||
if (dirs.isNullOrEmpty()) return null
|
if (dirs.isNullOrEmpty()) return null
|
||||||
var chargeNow = 0f
|
|
||||||
var chargeFull = 0f
|
var weightedChargeNow = 0.0
|
||||||
var watts = 0f
|
var weightedChargeFull = 0.0
|
||||||
var charging = false
|
var allHaveWeightedCharge = true
|
||||||
|
val perBatteryPercents = ArrayList<Int>()
|
||||||
|
var runtimeChargeUah = 0.0
|
||||||
|
var runtimeChargeComplete = true
|
||||||
|
var aggregateCurrentUa = 0.0
|
||||||
|
var currentComplete = true
|
||||||
|
var watts = 0.0
|
||||||
|
var anyDischarging = false
|
||||||
|
var anyChargingStatus = false
|
||||||
|
var allFull = true
|
||||||
|
var suppliedRuntimeSeconds: Long? = null
|
||||||
|
|
||||||
for (dir in dirs) {
|
for (dir in dirs) {
|
||||||
val status = runCatching { File(dir, "status").readLines().firstOrNull() }.getOrNull()
|
val status = runCatching { File(dir, "status").readLines().firstOrNull() }.getOrNull()
|
||||||
if (status == "Charging" || status == "Unknown" || status == "Full") charging = true
|
val isDischarging = status == "Discharging" || status == "Not charging"
|
||||||
val now = File(dir, "charge_now").takeIf { it.exists() } ?: File(dir, "energy_now")
|
if (isDischarging) anyDischarging = true
|
||||||
val full = File(dir, "charge_full").takeIf { it.exists() } ?: File(dir, "energy_full")
|
if (status == "Charging" || status == "Unknown") anyChargingStatus = true
|
||||||
if (now.exists()) {
|
if (status != "Full") allFull = false
|
||||||
chargeNow += (readFloat(now) ?: 0f) / 1_000_000f
|
|
||||||
chargeFull += (readFloat(full) ?: 0f) / 1_000_000f
|
val chargeNowFile = File(dir, "charge_now")
|
||||||
} else {
|
val chargeFullFile = File(dir, "charge_full")
|
||||||
chargeNow += (readFloat(File(dir, "capacity")) ?: 0f) / 100f
|
val energyNowFile = File(dir, "energy_now")
|
||||||
chargeFull = dirs.size.toFloat()
|
val energyFullFile = File(dir, "energy_full")
|
||||||
|
val voltageFile = File(dir, "voltage_now")
|
||||||
|
val chargeNow = if (chargeNowFile.isFile) readFloat(chargeNowFile)?.toDouble() else null
|
||||||
|
val chargeFull = if (chargeFullFile.isFile) readFloat(chargeFullFile)?.toDouble() else null
|
||||||
|
val energyNow = if (energyNowFile.isFile) readFloat(energyNowFile)?.toDouble() else null
|
||||||
|
val energyFull = if (energyFullFile.isFile) readFloat(energyFullFile)?.toDouble() else null
|
||||||
|
val voltageUv = if (voltageFile.isFile) readFloat(voltageFile)?.toDouble() else null
|
||||||
|
|
||||||
|
val nowForPercent: Double? = when {
|
||||||
|
chargeNow != null && chargeNow >= 0.0 -> chargeNow
|
||||||
|
energyNow != null && voltageUv != null -> BatteryRuntimeEstimator.chargeMicroampHoursFromEnergy(energyNow, voltageUv)
|
||||||
|
else -> null
|
||||||
}
|
}
|
||||||
if (!charging) {
|
val fullForPercent: Double? = when {
|
||||||
val power = File(dir, "power_now")
|
chargeFull != null && chargeFull > 0.0 -> chargeFull
|
||||||
watts += if (power.exists()) kotlin.math.abs(readFloat(power) ?: 0f) / 1_000_000f
|
energyFull != null && voltageUv != null -> BatteryRuntimeEstimator.chargeMicroampHoursFromEnergy(energyFull, voltageUv)
|
||||||
else kotlin.math.abs((readFloat(File(dir, "current_now")) ?: 0f) * (readFloat(File(dir, "voltage_now")) ?: 0f)) / 1e12f
|
else -> null
|
||||||
|
}
|
||||||
|
if (nowForPercent != null && fullForPercent != null && fullForPercent > 0.0) {
|
||||||
|
weightedChargeNow += nowForPercent
|
||||||
|
weightedChargeFull += fullForPercent
|
||||||
|
perBatteryPercents += (nowForPercent * 100.0 / fullForPercent).roundToInt().coerceIn(0, 100)
|
||||||
|
} else {
|
||||||
|
allHaveWeightedCharge = false
|
||||||
|
readFloat(File(dir, "capacity"))?.roundToInt()?.coerceIn(0, 100)?.let { perBatteryPercents += it }
|
||||||
|
}
|
||||||
|
|
||||||
|
when {
|
||||||
|
chargeNow != null && chargeNow >= 0.0 -> runtimeChargeUah += chargeNow
|
||||||
|
energyNow != null && voltageUv != null ->
|
||||||
|
BatteryRuntimeEstimator.chargeMicroampHoursFromEnergy(energyNow, voltageUv)?.let { runtimeChargeUah += it }
|
||||||
|
?: run { runtimeChargeComplete = false }
|
||||||
|
else -> runtimeChargeComplete = false
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dirs.size == 1) {
|
||||||
|
suppliedRuntimeSeconds = readLong(File(dir, "time_to_empty_avg"))?.takeIf { it > 0L }
|
||||||
|
?: readLong(File(dir, "time_to_empty_now"))?.takeIf { it > 0L }
|
||||||
|
?: suppliedRuntimeSeconds
|
||||||
|
}
|
||||||
|
|
||||||
|
val currentFile = File(dir, "current_now")
|
||||||
|
val powerFile = File(dir, "power_now")
|
||||||
|
val currentNow = if (currentFile.isFile) readFloat(currentFile)?.toDouble() else null
|
||||||
|
val currentForEta = when {
|
||||||
|
currentNow != null -> abs(currentNow)
|
||||||
|
powerFile.isFile && voltageUv != null -> readFloat(powerFile)?.toDouble()?.let {
|
||||||
|
BatteryRuntimeEstimator.currentMicroampsFromPower(it, voltageUv)
|
||||||
|
}
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
if (currentForEta == null) currentComplete = false else aggregateCurrentUa += currentForEta
|
||||||
|
|
||||||
|
if (isDischarging) {
|
||||||
|
val power = if (powerFile.isFile) readFloat(powerFile)?.toDouble() else null
|
||||||
|
if (power != null) watts += abs(power) / 1_000_000.0
|
||||||
|
else if (currentNow != null && voltageUv != null) watts += abs(currentNow * voltageUv) / 1_000_000_000_000.0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
val percent = if (chargeFull > 0f) Math.round(chargeNow / chargeFull * 100f) else null
|
|
||||||
return Battery(percent, if (charging) 0f else watts, charging)
|
val percent = when {
|
||||||
|
allHaveWeightedCharge && weightedChargeFull > 0.0 -> (weightedChargeNow * 100.0 / weightedChargeFull).roundToInt().coerceIn(0, 100)
|
||||||
|
perBatteryPercents.isNotEmpty() -> perBatteryPercents.average().roundToInt().coerceIn(0, 100)
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
if (lastBatteryDischarging != null && lastBatteryDischarging != anyDischarging) {
|
||||||
|
batteryRuntimeEstimator.reset()
|
||||||
|
}
|
||||||
|
lastBatteryDischarging = anyDischarging
|
||||||
|
val estimatedHours = if (anyDischarging && runtimeChargeComplete && currentComplete)
|
||||||
|
batteryRuntimeEstimator.estimateHours(runtimeChargeUah, aggregateCurrentUa) else null
|
||||||
|
val runtimeHours = suppliedRuntimeSeconds?.let { it / 3600.0 } ?: estimatedHours
|
||||||
|
val charging = !anyDischarging && anyChargingStatus
|
||||||
|
val runtimeText = when {
|
||||||
|
anyDischarging -> BatteryRuntimeEstimator.formatDuration(runtimeHours)
|
||||||
|
charging -> "Charging"
|
||||||
|
allFull -> "Full"
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
return Battery(percent, if (anyDischarging) watts.toFloat() else 0f, charging, runtimeText)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun fresh(file: File, maxAgeMs: Long = FEED_FRESH_MS): File? =
|
private fun fresh(file: File, maxAgeMs: Long = FEED_FRESH_MS): File? =
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
package com.droiddeck.launcher.input
|
package com.droiddeck.launcher.input
|
||||||
|
|
||||||
import android.accessibilityservice.AccessibilityService
|
import android.content.Context
|
||||||
import android.accessibilityservice.AccessibilityServiceInfo
|
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.content.pm.PackageManager
|
import android.content.pm.PackageManager
|
||||||
import android.graphics.Rect
|
|
||||||
import android.hardware.display.DisplayManager
|
import android.hardware.display.DisplayManager
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.Handler
|
import android.os.Handler
|
||||||
@@ -12,9 +10,9 @@ import android.os.HandlerThread
|
|||||||
import android.os.SystemClock
|
import android.os.SystemClock
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import android.view.Display
|
import android.view.Display
|
||||||
import android.view.accessibility.AccessibilityEvent
|
|
||||||
import android.view.accessibility.AccessibilityWindowInfo
|
import android.view.accessibility.AccessibilityWindowInfo
|
||||||
import android.view.inputmethod.InputMethodManager
|
import android.view.inputmethod.InputMethodManager
|
||||||
|
import com.droiddeck.shortcuts.Relay
|
||||||
import java.util.concurrent.ConcurrentHashMap
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
|
|
||||||
object BottomScreenGuests {
|
object BottomScreenGuests {
|
||||||
@@ -45,7 +43,7 @@ object BottomScreenGuests {
|
|||||||
sdk >= 33 && DualScreen.yieldsBottom(model)
|
sdk >= 33 && DualScreen.yieldsBottom(model)
|
||||||
}
|
}
|
||||||
|
|
||||||
class BottomScreenWatch(private val service: AccessibilityService) {
|
class BottomScreenWatch(private val service: Context) {
|
||||||
private class Arrival(val pkg: String, val at: Long)
|
private class Arrival(val pkg: String, val at: Long)
|
||||||
|
|
||||||
private val thread = HandlerThread("bottom-screen").apply { start() }
|
private val thread = HandlerThread("bottom-screen").apply { start() }
|
||||||
@@ -57,33 +55,22 @@ class BottomScreenWatch(private val service: AccessibilityService) {
|
|||||||
private var holders: Map<Int, String?> = emptyMap()
|
private var holders: Map<Int, String?> = emptyMap()
|
||||||
private var ownWindows: Map<Int, Set<Int>> = emptyMap()
|
private var ownWindows: Map<Int, Set<Int>> = emptyMap()
|
||||||
private val ownShownAt = mutableMapOf<Int, Long>()
|
private val ownShownAt = mutableMapOf<Int, Long>()
|
||||||
private val check = Runnable { evaluate() }
|
|
||||||
|
|
||||||
fun start() {
|
fun start() {
|
||||||
current = this
|
current = this
|
||||||
service.serviceInfo = service.serviceInfo?.apply {
|
|
||||||
eventTypes = eventTypes or AccessibilityEvent.TYPE_WINDOWS_CHANGED or AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
|
|
||||||
flags = flags or AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS
|
|
||||||
}
|
|
||||||
handler.post {
|
handler.post {
|
||||||
homes = homePackages()
|
homes = homePackages()
|
||||||
keyboards = keyboardPackages()
|
keyboards = keyboardPackages()
|
||||||
evaluate()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onEvent(event: AccessibilityEvent) {
|
fun onArrival(displayId: Int, pkg: String, at: Long) {
|
||||||
when (event.eventType) {
|
if (displayId == Display.DEFAULT_DISPLAY || pkg == own || pkg == SYSTEM_UI) return
|
||||||
AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED -> {
|
arrivals[displayId] = Arrival(pkg, at)
|
||||||
val pkg = event.packageName?.toString() ?: return
|
}
|
||||||
if (event.displayId == Display.DEFAULT_DISPLAY || pkg == own || pkg == SYSTEM_UI) return
|
|
||||||
arrivals[event.displayId] = Arrival(pkg, event.eventTime)
|
fun onWindows(all: Map<Int, List<Relay.Window>>) {
|
||||||
}
|
handler.post { evaluate(all) }
|
||||||
AccessibilityEvent.TYPE_WINDOWS_CHANGED -> Unit
|
|
||||||
else -> return
|
|
||||||
}
|
|
||||||
handler.removeCallbacks(check)
|
|
||||||
handler.postDelayed(check, 150)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun stop() {
|
fun stop() {
|
||||||
@@ -97,25 +84,22 @@ class BottomScreenWatch(private val service: AccessibilityService) {
|
|||||||
thread.quitSafely()
|
thread.quitSafely()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun evaluate() {
|
private fun evaluate(all: Map<Int, List<Relay.Window>>) {
|
||||||
val seen = HashMap(arrivals)
|
val seen = HashMap(arrivals)
|
||||||
val all = runCatching { service.windowsOnAllDisplays }.getOrNull() ?: return
|
|
||||||
val displays = service.getSystemService(DisplayManager::class.java) ?: return
|
val displays = service.getSystemService(DisplayManager::class.java) ?: return
|
||||||
val taken = mutableMapOf<Int, String?>()
|
val taken = mutableMapOf<Int, String?>()
|
||||||
val shown = mutableMapOf<Int, Set<Int>>()
|
val shown = mutableMapOf<Int, Set<Int>>()
|
||||||
val now = SystemClock.uptimeMillis()
|
val now = SystemClock.uptimeMillis()
|
||||||
for (i in 0 until all.size()) {
|
for ((id, list) in all) {
|
||||||
val id = all.keyAt(i)
|
|
||||||
if (id == Display.DEFAULT_DISPLAY) continue
|
if (id == Display.DEFAULT_DISPLAY) continue
|
||||||
val display = displays.getDisplay(id)?.takeIf(DualScreen::builtIn) ?: continue
|
val display = displays.getDisplay(id)?.takeIf(DualScreen::builtIn) ?: continue
|
||||||
val windows = all.valueAt(i)
|
val windows = list
|
||||||
.filter { !BottomScreenGuests.ignorable(it.type) && cover(it, display) >= BottomScreenGuests.MIN_COVER }
|
.filter { !BottomScreenGuests.ignorable(it.type) && cover(it, display) >= BottomScreenGuests.MIN_COVER }
|
||||||
.sortedByDescending { it.layer }
|
.sortedByDescending { it.layer }
|
||||||
.map { it to packageOf(it) }
|
val ours = windows.filter { it.pkg == own }.map { it.id }.toSet()
|
||||||
val ours = windows.filter { it.second == own }.map { it.first.id }.toSet()
|
|
||||||
if (!ownWindows[id].orEmpty().containsAll(ours)) ownShownAt[id] = now
|
if (!ownWindows[id].orEmpty().containsAll(ours)) ownShownAt[id] = now
|
||||||
shown[id] = ours
|
shown[id] = ours
|
||||||
val topPkg = windows.firstNotNullOfOrNull { it.second?.takeUnless { pkg -> pkg == own } }
|
val topPkg = windows.firstNotNullOfOrNull { it.pkg?.takeUnless { pkg -> pkg == own } }
|
||||||
val arrival = seen[id]?.takeIf { BottomScreenGuests.current(it.at, ownShownAt[id]) }
|
val arrival = seen[id]?.takeIf { BottomScreenGuests.current(it.at, ownShownAt[id]) }
|
||||||
seen[id]?.takeIf { topPkg != null || arrival == null }?.let { arrivals.remove(id, it) }
|
seen[id]?.takeIf { topPkg != null || arrival == null }?.let { arrivals.remove(id, it) }
|
||||||
BottomScreenGuests.holder(topPkg, arrival?.pkg?.takeUnless { it in keyboards }, homes)?.let { taken[id] = it }
|
BottomScreenGuests.holder(topPkg, arrival?.pkg?.takeUnless { it in keyboards }, homes)?.let { taken[id] = it }
|
||||||
@@ -127,15 +111,11 @@ class BottomScreenWatch(private val service: AccessibilityService) {
|
|||||||
DualScreen.setTaken(taken.keys)
|
DualScreen.setTaken(taken.keys)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun cover(window: AccessibilityWindowInfo, display: Display): Float {
|
private fun cover(window: Relay.Window, display: Display): Float {
|
||||||
val bounds = Rect().also(window::getBoundsInScreen)
|
|
||||||
val area = display.mode.physicalWidth.toFloat() * display.mode.physicalHeight
|
val area = display.mode.physicalWidth.toFloat() * display.mode.physicalHeight
|
||||||
return if (area <= 0f) 0f else bounds.width().toFloat() * bounds.height() / area
|
return if (area <= 0f) 0f else window.bounds.width().toFloat() * window.bounds.height() / area
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun packageOf(window: AccessibilityWindowInfo): String? =
|
|
||||||
runCatching { window.getRoot(0)?.packageName?.toString() }.getOrNull()
|
|
||||||
|
|
||||||
private fun homePackages(): Set<String> {
|
private fun homePackages(): Set<String> {
|
||||||
val pm = service.packageManager
|
val pm = service.packageManager
|
||||||
return listOf(Intent.CATEGORY_HOME, Intent.CATEGORY_SECONDARY_HOME).flatMap { category ->
|
return listOf(Intent.CATEGORY_HOME, Intent.CATEGORY_SECONDARY_HOME).flatMap { category ->
|
||||||
@@ -154,6 +134,7 @@ class BottomScreenWatch(private val service: AccessibilityService) {
|
|||||||
|
|
||||||
private companion object {
|
private companion object {
|
||||||
@Volatile var current: BottomScreenWatch? = null
|
@Volatile var current: BottomScreenWatch? = null
|
||||||
|
|
||||||
const val TAG = "BottomScreen"
|
const val TAG = "BottomScreen"
|
||||||
const val SYSTEM_UI = "com.android.systemui"
|
const val SYSTEM_UI = "com.android.systemui"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -138,6 +138,15 @@ object ControllerPrefs {
|
|||||||
prefs(context).edit().putBoolean("joyConVr", on).apply()
|
prefs(context).edit().putBoolean("joyConVr", on).apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun nintendoLayout(context: Context, game: String?): Boolean =
|
||||||
|
game != null && prefs(context).getBoolean("nintendo.$game", false)
|
||||||
|
|
||||||
|
fun setNintendoLayout(context: Context, game: String, on: Boolean) {
|
||||||
|
val edit = prefs(context).edit()
|
||||||
|
if (on) edit.putBoolean("nintendo.$game", true) else edit.remove("nintendo.$game")
|
||||||
|
edit.apply()
|
||||||
|
}
|
||||||
|
|
||||||
fun snap(context: Context): Boolean = prefs(context).getBoolean("snap", true)
|
fun snap(context: Context): Boolean = prefs(context).getBoolean("snap", true)
|
||||||
|
|
||||||
fun setSnap(context: Context, on: Boolean) {
|
fun setSnap(context: Context, on: Boolean) {
|
||||||
|
|||||||
@@ -82,6 +82,8 @@ public class FakeInputWriter {
|
|||||||
private static final int PAD_TYPE_OFFSET = IMU_OFFSET + 44;
|
private static final int PAD_TYPE_OFFSET = IMU_OFFSET + 44;
|
||||||
private static final int PAD_TYPE_SET = 0x80000000;
|
private static final int PAD_TYPE_SET = 0x80000000;
|
||||||
private static final int LATENCY_OFFSET = IMU_OFFSET + 48;
|
private static final int LATENCY_OFFSET = IMU_OFFSET + 48;
|
||||||
|
private static final int REMOTE_IMU_MODE_OFFSET = IMU_OFFSET + 52;
|
||||||
|
private static final int REMOTE_IMU_PID_OFFSET = IMU_OFFSET + 56;
|
||||||
public static final int LATENCY_CONTROLLER = 1;
|
public static final int LATENCY_CONTROLLER = 1;
|
||||||
public static final int LATENCY_TOUCH = 2;
|
public static final int LATENCY_TOUCH = 2;
|
||||||
private static volatile int latency = 0;
|
private static volatile int latency = 0;
|
||||||
@@ -231,6 +233,8 @@ public class FakeInputWriter {
|
|||||||
}
|
}
|
||||||
data.putInt(IMU_OFFSET, 0);
|
data.putInt(IMU_OFFSET, 0);
|
||||||
data.putInt(IMU_MODE_OFFSET, 0);
|
data.putInt(IMU_MODE_OFFSET, 0);
|
||||||
|
data.putInt(REMOTE_IMU_MODE_OFFSET, 0);
|
||||||
|
data.putInt(REMOTE_IMU_PID_OFFSET, 0);
|
||||||
data.putLong(IMU_SEQ_OFFSET, 0L);
|
data.putLong(IMU_SEQ_OFFSET, 0L);
|
||||||
for (int i = 0; i < 12; i++) {
|
for (int i = 0; i < 12; i++) {
|
||||||
data.putShort(IMU_ACCEL_OFFSET + (i * 2), (short) 0);
|
data.putShort(IMU_ACCEL_OFFSET + (i * 2), (short) 0);
|
||||||
@@ -494,8 +498,11 @@ public class FakeInputWriter {
|
|||||||
if (ringSlot == null) return -1;
|
if (ringSlot == null) return -1;
|
||||||
synchronized (ringSlot) {
|
synchronized (ringSlot) {
|
||||||
ByteBuffer ring = ringSlot.data;
|
ByteBuffer ring = ringSlot.data;
|
||||||
int value = ring == null ? 0 : ring.getInt(IMU_MODE_OFFSET);
|
if (ring == null) return 0;
|
||||||
return value < 0 ? value & 0xffff : -1;
|
int remote = ring.getInt(REMOTE_IMU_MODE_OFFSET);
|
||||||
|
int pid = ring.getInt(REMOTE_IMU_PID_OFFSET);
|
||||||
|
return ImuModes.combine(ring.getInt(IMU_MODE_OFFSET), remote,
|
||||||
|
remote < 0 && pid > 0 && new File("/proc/" + pid).exists());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,158 @@
|
|||||||
|
package com.droiddeck.launcher.input
|
||||||
|
|
||||||
|
/** Where a USB mouse's input report keeps its buttons, motion and wheel, as its HID report descriptor lays them out. */
|
||||||
|
class HidMouseReport(
|
||||||
|
val reportId: Int,
|
||||||
|
private val buttons: List<Field?>,
|
||||||
|
private val x: Field,
|
||||||
|
private val y: Field,
|
||||||
|
private val wheel: Field?,
|
||||||
|
) {
|
||||||
|
class Field(private val bit: Int, private val size: Int, private val signed: Boolean) {
|
||||||
|
fun read(report: ByteArray, length: Int, base: Int): Int {
|
||||||
|
var value = 0
|
||||||
|
for (i in 0 until minOf(size, 32)) {
|
||||||
|
val at = base + bit + i
|
||||||
|
if (at / 8 >= length) break
|
||||||
|
if ((report[at / 8].toInt() shr (at % 8)) and 1 != 0) value = value or (1 shl i)
|
||||||
|
}
|
||||||
|
return if (signed && size in 1..31 && value and (1 shl (size - 1)) != 0) value - (1 shl size) else value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** [buttons] has bit 0 set for the first button. */
|
||||||
|
data class State(val buttons: Int, val dx: Int, val dy: Int, val wheel: Int)
|
||||||
|
|
||||||
|
/** Returns null for reports with another ID, such as a receiver's media keys. */
|
||||||
|
fun decode(report: ByteArray, length: Int): State? {
|
||||||
|
val base = if (reportId == 0) 0 else {
|
||||||
|
if (length < 1 || (report[0].toInt() and 0xff) != reportId) return null
|
||||||
|
8
|
||||||
|
}
|
||||||
|
var pressed = 0
|
||||||
|
buttons.forEachIndexed { i, field -> if (field != null && field.read(report, length, base) != 0) pressed = pressed or (1 shl i) }
|
||||||
|
return State(pressed, x.read(report, length, base), y.read(report, length, base), wheel?.read(report, length, base) ?: 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
/** The report every boot mouse sends after SET_PROTOCOL(boot): three buttons, then X and Y as signed bytes. */
|
||||||
|
val BOOT = HidMouseReport(0, List(3) { Field(it, 1, false) }, Field(8, 8, true), Field(16, 8, true), null)
|
||||||
|
|
||||||
|
private const val BUTTON_PAGE = 0x09
|
||||||
|
private const val MOUSE = 0x00010002
|
||||||
|
private const val X = 0x00010030
|
||||||
|
private const val Y = 0x00010031
|
||||||
|
private const val WHEEL = 0x00010038
|
||||||
|
private const val MAX_BUTTONS = 8
|
||||||
|
private const val MAX_FIELD_BITS = 32
|
||||||
|
private const val MAX_REPORT_COUNT = 4096
|
||||||
|
|
||||||
|
private class Global(var usagePage: Int = 0, var logicalMin: Int = 0, var reportSize: Int = 0,
|
||||||
|
var reportCount: Int = 0, var reportId: Int = 0) {
|
||||||
|
fun copy() = Global(usagePage, logicalMin, reportSize, reportCount, reportId)
|
||||||
|
}
|
||||||
|
|
||||||
|
private class Placed(val reportId: Int, val field: Field)
|
||||||
|
|
||||||
|
/** Returns null if [descriptor] has no mouse collection with X and Y in one report. */
|
||||||
|
fun parse(descriptor: ByteArray): HidMouseReport? {
|
||||||
|
var global = Global()
|
||||||
|
val pushed = ArrayDeque<Global>()
|
||||||
|
val usages = mutableListOf<Int>()
|
||||||
|
var usageMin = -1
|
||||||
|
var usageMax = -1
|
||||||
|
val offsets = HashMap<Int, Int>()
|
||||||
|
var depth = 0
|
||||||
|
var mouseDepth = -1
|
||||||
|
var mouseDone = false
|
||||||
|
val placed = HashMap<Int, Placed>()
|
||||||
|
|
||||||
|
fun usage(index: Int): Int = when {
|
||||||
|
usages.isNotEmpty() -> usages.getOrElse(index) { usages.last() }
|
||||||
|
usageMin >= 0 && usageMax >= usageMin -> minOf(usageMin + index, usageMax)
|
||||||
|
else -> -1
|
||||||
|
}
|
||||||
|
|
||||||
|
var i = 0
|
||||||
|
while (i < descriptor.size) {
|
||||||
|
val prefix = descriptor[i].toInt() and 0xff
|
||||||
|
if (prefix == 0xfe) {
|
||||||
|
if (i + 1 >= descriptor.size) break
|
||||||
|
i += 3 + (descriptor[i + 1].toInt() and 0xff)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
val size = intArrayOf(0, 1, 2, 4)[prefix and 3]
|
||||||
|
if (i + 1 + size > descriptor.size) break
|
||||||
|
var data = 0
|
||||||
|
for (b in 0 until size) data = data or ((descriptor[i + 1 + b].toInt() and 0xff) shl (8 * b))
|
||||||
|
val signedData = when (size) {
|
||||||
|
1 -> data.toByte().toInt()
|
||||||
|
2 -> data.toShort().toInt()
|
||||||
|
else -> data
|
||||||
|
}
|
||||||
|
val tag = prefix shr 4
|
||||||
|
when ((prefix shr 2) and 3) {
|
||||||
|
0 -> {
|
||||||
|
when (tag) {
|
||||||
|
0x8 -> {
|
||||||
|
if (global.reportSize !in 0..MAX_FIELD_BITS || global.reportCount !in 0..MAX_REPORT_COUNT) return null
|
||||||
|
val start = offsets[global.reportId] ?: 0
|
||||||
|
val isData = data and 1 == 0
|
||||||
|
val isVariable = data and 2 != 0
|
||||||
|
if (mouseDepth >= 0 && !mouseDone && isData && isVariable) {
|
||||||
|
for (n in 0 until global.reportCount) {
|
||||||
|
val u = usage(n)
|
||||||
|
if (u < 0) break
|
||||||
|
val field = Placed(global.reportId, Field(start + n * global.reportSize, global.reportSize, global.logicalMin < 0))
|
||||||
|
val button = if (u ushr 16 == BUTTON_PAGE) u and 0xffff else 0
|
||||||
|
when {
|
||||||
|
u == X || u == Y || u == WHEEL -> placed.putIfAbsent(u, field)
|
||||||
|
button in 1..MAX_BUTTONS -> placed.putIfAbsent(u, field)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
offsets[global.reportId] = start + global.reportSize * global.reportCount
|
||||||
|
}
|
||||||
|
0xa -> {
|
||||||
|
depth++
|
||||||
|
if (mouseDepth < 0 && data == 1 && usage(0) == MOUSE) mouseDepth = depth
|
||||||
|
}
|
||||||
|
0xc -> {
|
||||||
|
if (depth == mouseDepth) mouseDone = true
|
||||||
|
depth--
|
||||||
|
}
|
||||||
|
}
|
||||||
|
usages.clear()
|
||||||
|
usageMin = -1
|
||||||
|
usageMax = -1
|
||||||
|
}
|
||||||
|
1 -> when (tag) {
|
||||||
|
0x0 -> global.usagePage = data
|
||||||
|
0x1 -> global.logicalMin = signedData
|
||||||
|
0x7 -> global.reportSize = data
|
||||||
|
0x8 -> global.reportId = data
|
||||||
|
0x9 -> global.reportCount = data
|
||||||
|
0xa -> pushed.addLast(global.copy())
|
||||||
|
0xb -> global = pushed.removeLastOrNull() ?: global
|
||||||
|
}
|
||||||
|
2 -> {
|
||||||
|
val full = if (size == 4) data else (global.usagePage shl 16) or data
|
||||||
|
when (tag) {
|
||||||
|
0x0 -> usages += full
|
||||||
|
0x1 -> usageMin = full
|
||||||
|
0x2 -> usageMax = full
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
i += 1 + size
|
||||||
|
}
|
||||||
|
|
||||||
|
val x = placed[X] ?: return null
|
||||||
|
val y = placed[Y]?.takeIf { it.reportId == x.reportId } ?: return null
|
||||||
|
val id = x.reportId
|
||||||
|
val buttons = (1..MAX_BUTTONS).map { n -> placed[(BUTTON_PAGE shl 16) or n]?.takeIf { it.reportId == id }?.field }
|
||||||
|
return HidMouseReport(id, buttons.dropLastWhile { it == null }, x.field, y.field,
|
||||||
|
placed[WHEEL]?.takeIf { it.reportId == id }?.field)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package com.droiddeck.launcher.input;
|
||||||
|
|
||||||
|
final class ImuModes {
|
||||||
|
private ImuModes() {}
|
||||||
|
|
||||||
|
// Steam and its Remote Play client each keep their own mode word, with the top bit set once written. Motion is
|
||||||
|
// read while either process wants it, and a word that has not been set leaves the choice to the other one.
|
||||||
|
// -1 means neither has set a mode yet.
|
||||||
|
static int combine(int steam, int remote, boolean remoteRunning) {
|
||||||
|
boolean remoteSet = remote < 0 && remoteRunning;
|
||||||
|
if (steam >= 0 && !remoteSet) return -1;
|
||||||
|
return ((steam < 0 ? steam : 0) | (remoteSet ? remote : 0)) & 0xffff;
|
||||||
|
}
|
||||||
|
}
|
||||||
Loaded 100 of 589 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user