chore: merge main into feat/bt-controller-trinket

This commit is contained in:
Kurt Himebauch committed 2026-11-19 15:02:05 -05:00
commit 0a6060d409
259 files changed
+19673 -4249

No files matched your search

+1
View File
@@ -1,5 +1,6 @@
ASEbrahim
FX192
FryMcNugget
K11MCH1
KeegantheVeganat0r
kingokksa
+4 -5
View File
@@ -291,7 +291,7 @@ jobs:
- name: Build the non-Adreno test additions (Mali bridge client, Venus GL probe, Xclipse layer)
run: |
set -euo pipefail
bash tools/ci/install-ubuntu-packages.sh gcc-aarch64-linux-gnu libvulkan-dev
bash tools/ci/install-ubuntu-packages.sh gcc-aarch64-linux-gnu libc6-dev-arm64-cross libvulkan-dev
D=app/src/main/assets/linuxfs
mkdir -p "$D/usr/local/bin" "$D/usr/local/lib/droiddeck-xclipse"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wextra -Wno-unused-parameter -fvisibility=hidden -pthread \
@@ -765,7 +765,6 @@ jobs:
if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
runs-on: ubuntu-24.04
timeout-minutes: 15
continue-on-error: true
permissions:
contents: read
actions: read
@@ -811,7 +810,6 @@ jobs:
stores-host-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust.outputs.rustc }}-
- name: Store engines host unit tests
timeout-minutes: 10
continue-on-error: true
run: |
set -o pipefail
cd app/src/main/rust/stores
@@ -900,7 +898,7 @@ jobs:
checks:
name: Compile and test APK
needs: [build, python-tests]
needs: [build, python-tests, store-tests]
if: ${{ !cancelled() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) }}
runs-on: ubuntu-24.04
timeout-minutes: 5
@@ -909,7 +907,8 @@ jobs:
env:
BUILD_RESULT: ${{ needs.build.result }}
PYTHON_RESULT: ${{ needs.python-tests.result }}
run: test "$BUILD_RESULT" = success && test "$PYTHON_RESULT" = success
STORE_RESULT: ${{ needs.store-tests.result }}
run: test "$BUILD_RESULT" = success && test "$PYTHON_RESULT" = success && test "$STORE_RESULT" = success
sign:
needs: [build, checks]
+1 -1
View File
@@ -47,7 +47,7 @@ Help, Preview builds and device reports are on [Discord](https://discord.gg/JRGA
## Build
Needs Docker, Java 17, the Android SDK and NDK, Rust via rustup, GitHub CLI, Python 3 and `zstd`.
Needs Docker, Java 17, the Android SDK and NDK, Rust via rustup, Go, a host C compiler, the x86_64 and i686 MinGW-w64 compilers (i686 with DWARF-2 exceptions, as Debian and Ubuntu ship it; SJLJ builds such as Homebrew's cannot link Rust's `i686-pc-windows-gnu`), GitHub CLI, Python 3 and `zstd`. On x86_64 Linux, Docker also needs an arm64 binfmt handler (`docker run --privileged --rm tonistiigi/binfmt --install arm64`).
```bash
tools/build_local.sh
+3
View File
@@ -4,6 +4,9 @@
<queries>
<package android:name="cn.nubia.gamelauncher" />
<intent>
<action android:name="android.speech.RecognitionService" />
</intent>
<intent>
<action android:name="android.content.pm.action.CONFIRM_INSTALL" />
</intent>
+6 -7
View File
@@ -85,17 +85,16 @@ void main() {
float crossingPattern = smoothstep(threshold, threshold * 2.5, crossingContrast);
float areaWeight = 0.38 * crossingPattern * clamp(span / 4.0, 0.0, 1.0);
float diagonalContrast = max(abs(nw - se), abs(ne - sw));
float cornerFactor = 1.0 - 0.18 * smoothstep(threshold, threshold * 3.0, diagonalContrast);
float cornerFactor = 1.0 - 0.35 * smoothstep(threshold, threshold * 3.0, diagonalContrast);
float baseWeight = areaWeight * endpointArea * edgeConfidence * cornerFactor;
float diagonalStrength = abs(abs(nw - se) - abs(ne - sw));
float diagonalStrength = min(vertical, horizontal);
float diagonalPattern = smoothstep(threshold, threshold * 2.5, diagonalStrength);
float diagonalFallback = 0.16 * diagonalPattern * edgeConfidence * cornerFactor;
float diagonalContinuity = smoothstep(1.0, 3.0, span);
float diagonalFallback = 0.16 * diagonalPattern * edgeConfidence
* cornerFactor * diagonalContinuity * crossingPattern;
float weight = clamp(
baseWeight <= 0.0001 ? diagonalFallback : baseWeight,
0.0, 0.42
);
float weight = clamp(max(baseWeight, diagonalFallback), 0.0, 0.42);
vec3 across = texture(InputTexture, uv + normal * px).rgb;
outColor = vec4(mix(center.rgb, across, weight), center.a);
}
+388 -388
View File
@@ -2,7 +2,7 @@
#include <stdint.h>
static const uint32_t smaa_code[] = {
0x07230203u, 0x00010000u, 0x0008000bu, 0x00000254u, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu,
0x07230203u, 0x00010000u, 0x0008000bu, 0x00000251u, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu,
0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u,
0x0007000fu, 0x00000004u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00000072u, 0x000000f6u, 0x00030010u,
0x00000004u, 0x00000007u, 0x00030003u, 0x00000002u, 0x000001c2u, 0x00040005u, 0x00000004u, 0x6e69616du,
@@ -53,391 +53,391 @@ static const uint32_t smaa_code[] = {
0x00000200u, 0x67616964u, 0x6c616e6fu, 0x746e6f43u, 0x74736172u, 0x00000000u, 0x00060005u, 0x0000020au,
0x6e726f63u, 0x61467265u, 0x726f7463u, 0x00000000u, 0x00050005u, 0x00000214u, 0x65736162u, 0x67696557u,
0x00007468u, 0x00070005u, 0x0000021cu, 0x67616964u, 0x6c616e6fu, 0x65727453u, 0x6874676eu, 0x00000000u,
0x00060005u, 0x00000227u, 0x67616964u, 0x6c616e6fu, 0x74746150u, 0x006e7265u, 0x00070005u, 0x0000022du,
0x67616964u, 0x6c616e6fu, 0x6c6c6146u, 0x6b636162u, 0x00000000u, 0x00040005u, 0x00000235u, 0x67696577u,
0x00007468u, 0x00040005u, 0x0000023eu, 0x6f726361u, 0x00007373u, 0x00040047u, 0x00000025u, 0x00000021u,
0x00000000u, 0x00040047u, 0x00000025u, 0x00000022u, 0x00000000u, 0x00030047u, 0x00000064u, 0x00000002u,
0x00050048u, 0x00000064u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00050048u, 0x00000064u, 0x00000001u,
0x00000023u, 0x00000010u, 0x00050048u, 0x00000064u, 0x00000002u, 0x00000023u, 0x00000018u, 0x00050048u,
0x00000064u, 0x00000003u, 0x00000023u, 0x0000001cu, 0x00040047u, 0x00000072u, 0x0000001eu, 0x00000000u,
0x00040047u, 0x000000f6u, 0x0000001eu, 0x00000000u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u,
0x00000002u, 0x00030016u, 0x00000006u, 0x00000020u, 0x00040017u, 0x00000007u, 0x00000006u, 0x00000003u,
0x00040020u, 0x00000008u, 0x00000007u, 0x00000007u, 0x00040021u, 0x00000009u, 0x00000006u, 0x00000008u,
0x00040017u, 0x0000000du, 0x00000006u, 0x00000002u, 0x00040020u, 0x0000000eu, 0x00000007u, 0x0000000du,
0x00050021u, 0x0000000fu, 0x00000006u, 0x0000000eu, 0x0000000eu, 0x0004002bu, 0x00000006u, 0x00000019u,
0x3e59b3d0u, 0x0004002bu, 0x00000006u, 0x0000001au, 0x3f371759u, 0x0004002bu, 0x00000006u, 0x0000001bu,
0x3d93dd98u, 0x0006002cu, 0x00000007u, 0x0000001cu, 0x00000019u, 0x0000001au, 0x0000001bu, 0x00040020u,
0x00000020u, 0x00000007u, 0x00000006u, 0x00090019u, 0x00000022u, 0x00000006u, 0x00000001u, 0x00000000u,
0x00000000u, 0x00000000u, 0x00000001u, 0x00000000u, 0x0003001bu, 0x00000023u, 0x00000022u, 0x00040020u,
0x00000024u, 0x00000000u, 0x00000023u, 0x0004003bu, 0x00000024u, 0x00000025u, 0x00000000u, 0x00040015u,
0x00000028u, 0x00000020u, 0x00000000u, 0x0004002bu, 0x00000028u, 0x00000029u, 0x00000000u, 0x0004002bu,
0x00000006u, 0x0000002cu, 0x00000000u, 0x00040017u, 0x0000002fu, 0x00000006u, 0x00000004u, 0x0004002bu,
0x00000028u, 0x00000048u, 0x00000001u, 0x0004002bu, 0x00000006u, 0x00000063u, 0x3f800000u, 0x0006001eu,
0x00000064u, 0x0000002fu, 0x0000000du, 0x00000006u, 0x00000006u, 0x00040020u, 0x00000065u, 0x00000009u,
0x00000064u, 0x0004003bu, 0x00000065u, 0x00000066u, 0x00000009u, 0x00040015u, 0x00000067u, 0x00000020u,
0x00000001u, 0x0004002bu, 0x00000067u, 0x00000068u, 0x00000001u, 0x00040020u, 0x00000069u, 0x00000009u,
0x0000000du, 0x0005002cu, 0x0000000du, 0x0000006cu, 0x00000063u, 0x00000063u, 0x00040020u, 0x00000071u,
0x00000001u, 0x0000000du, 0x0004003bu, 0x00000071u, 0x00000072u, 0x00000001u, 0x0004002bu, 0x00000006u,
0x00000075u, 0x3f000000u, 0x00040020u, 0x0000007bu, 0x00000007u, 0x0000002fu, 0x0004002bu, 0x00000006u,
0x000000deu, 0x3d3851ecu, 0x0004002bu, 0x00000006u, 0x000000e0u, 0x3da3d70au, 0x00020014u, 0x000000f1u,
0x00040020u, 0x000000f5u, 0x00000003u, 0x0000002fu, 0x0004003bu, 0x000000f5u, 0x000000f6u, 0x00000003u,
0x00040020u, 0x000000f9u, 0x00000007u, 0x000000f1u, 0x0004002bu, 0x00000006u, 0x00000113u, 0xbf800000u,
0x00040020u, 0x0000011fu, 0x00000007u, 0x00000067u, 0x0004002bu, 0x00000067u, 0x00000127u, 0x00000006u,
0x0004002bu, 0x00000006u, 0x00000161u, 0x3f266666u, 0x0004002bu, 0x00000006u, 0x00000182u, 0x40200000u,
0x0004002bu, 0x00000006u, 0x000001cau, 0x3d6147aeu, 0x0004002bu, 0x00000006u, 0x000001f8u, 0x3ec28f5cu,
0x0004002bu, 0x00000006u, 0x000001fcu, 0x40800000u, 0x0004002bu, 0x00000006u, 0x0000020bu, 0x3e3851ecu,
0x0004002bu, 0x00000006u, 0x0000020eu, 0x40400000u, 0x0004002bu, 0x00000006u, 0x0000022eu, 0x3e23d70au,
0x0004002bu, 0x00000006u, 0x00000237u, 0x38d1b717u, 0x0004002bu, 0x00000006u, 0x0000023cu, 0x3ed70a3du,
0x0004002bu, 0x00000028u, 0x0000024du, 0x00000003u, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u,
0x00000003u, 0x000200f8u, 0x00000005u, 0x0004003bu, 0x0000000eu, 0x00000062u, 0x00000007u, 0x0004003bu,
0x0000000eu, 0x00000070u, 0x00000007u, 0x0004003bu, 0x0000007bu, 0x0000007cu, 0x00000007u, 0x0004003bu,
0x00000020u, 0x00000080u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x00000081u, 0x00000007u, 0x0004003bu,
0x00000020u, 0x00000085u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x0000008du, 0x00000007u, 0x0004003bu,
0x00000020u, 0x00000090u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x00000098u, 0x00000007u, 0x0004003bu,
0x00000020u, 0x0000009bu, 0x00000007u, 0x0004003bu, 0x00000008u, 0x000000a3u, 0x00000007u, 0x0004003bu,
0x00000020u, 0x000000a6u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x000000aeu, 0x00000007u, 0x0004003bu,
0x00000020u, 0x000000b1u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000b6u, 0x00000007u, 0x0004003bu,
0x00000020u, 0x000000bbu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000c0u, 0x00000007u, 0x0004003bu,
0x00000020u, 0x000000c5u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000cfu, 0x00000007u, 0x0004003bu,
0x00000020u, 0x000000d9u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000ddu, 0x00000007u, 0x0004003bu,
0x00000020u, 0x000000e3u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000e7u, 0x00000007u, 0x0004003bu,
0x00000020u, 0x000000ebu, 0x00000007u, 0x0004003bu, 0x000000f9u, 0x000000fau, 0x00000007u, 0x0004003bu,
0x0000000eu, 0x000000feu, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x00000100u, 0x00000007u, 0x0004003bu,
0x0000000eu, 0x0000010bu, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x0000010du, 0x00000007u, 0x0004003bu,
0x00000020u, 0x0000011du, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000011eu, 0x00000007u, 0x0004003bu,
0x0000011fu, 0x00000120u, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x00000129u, 0x00000007u, 0x0004003bu,
0x00000020u, 0x0000012eu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000130u, 0x00000007u, 0x0004003bu,
0x0000000eu, 0x00000136u, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x00000137u, 0x00000007u, 0x0004003bu,
0x0000000eu, 0x0000013eu, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x0000013fu, 0x00000007u, 0x0004003bu,
0x00000020u, 0x00000143u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000145u, 0x00000007u, 0x0004003bu,
0x0000000eu, 0x0000014bu, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x0000014cu, 0x00000007u, 0x0004003bu,
0x0000000eu, 0x00000153u, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x00000154u, 0x00000007u, 0x0004003bu,
0x00000020u, 0x0000017bu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000017fu, 0x00000007u, 0x0004003bu,
0x00000020u, 0x00000186u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x00000192u, 0x00000007u, 0x0004003bu,
0x00000020u, 0x00000195u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x000001a0u, 0x00000007u, 0x0004003bu,
0x00000020u, 0x000001a3u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x000001aeu, 0x00000007u, 0x0004003bu,
0x00000020u, 0x000001b1u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x000001bbu, 0x00000007u, 0x0004003bu,
0x00000020u, 0x000001beu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001c7u, 0x00000007u, 0x0004003bu,
0x00000020u, 0x000001ceu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001d0u, 0x00000007u, 0x0004003bu,
0x00000020u, 0x000001ddu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001dfu, 0x00000007u, 0x0004003bu,
0x00000020u, 0x000001ecu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001f1u, 0x00000007u, 0x0004003bu,
0x00000020u, 0x000001f7u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000200u, 0x00000007u, 0x0004003bu,
0x00000020u, 0x0000020au, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000214u, 0x00000007u, 0x0004003bu,
0x00000020u, 0x0000021cu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000227u, 0x00000007u, 0x0004003bu,
0x00000020u, 0x0000022du, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000235u, 0x00000007u, 0x0004003bu,
0x00000008u, 0x0000023eu, 0x00000007u, 0x00050041u, 0x00000069u, 0x0000006au, 0x00000066u, 0x00000068u,
0x0004003du, 0x0000000du, 0x0000006bu, 0x0000006au, 0x0007000cu, 0x0000000du, 0x0000006du, 0x00000001u,
0x00000028u, 0x0000006bu, 0x0000006cu, 0x00050050u, 0x0000000du, 0x0000006eu, 0x00000063u, 0x00000063u,
0x00050088u, 0x0000000du, 0x0000006fu, 0x0000006eu, 0x0000006du, 0x0003003eu, 0x00000062u, 0x0000006fu,
0x0004003du, 0x0000000du, 0x00000073u, 0x00000072u, 0x0004003du, 0x0000000du, 0x00000074u, 0x00000062u,
0x0005008eu, 0x0000000du, 0x00000076u, 0x00000074u, 0x00000075u, 0x0004003du, 0x0000000du, 0x00000077u,
0x00000062u, 0x0005008eu, 0x0000000du, 0x00000078u, 0x00000077u, 0x00000075u, 0x00050083u, 0x0000000du,
0x00000079u, 0x0000006cu, 0x00000078u, 0x0008000cu, 0x0000000du, 0x0000007au, 0x00000001u, 0x0000002bu,
0x00000073u, 0x00000076u, 0x00000079u, 0x0003003eu, 0x00000070u, 0x0000007au, 0x0004003du, 0x00000023u,
0x0000007du, 0x00000025u, 0x0004003du, 0x0000000du, 0x0000007eu, 0x00000070u, 0x00050057u, 0x0000002fu,
0x0000007fu, 0x0000007du, 0x0000007eu, 0x0003003eu, 0x0000007cu, 0x0000007fu, 0x0004003du, 0x0000002fu,
0x00000082u, 0x0000007cu, 0x0008004fu, 0x00000007u, 0x00000083u, 0x00000082u, 0x00000082u, 0x00000000u,
0x00000001u, 0x00000002u, 0x0003003eu, 0x00000081u, 0x00000083u, 0x00050039u, 0x00000006u, 0x00000084u,
0x0000000bu, 0x00000081u, 0x0003003eu, 0x00000080u, 0x00000084u, 0x0004003du, 0x00000023u, 0x00000086u,
0x00000025u, 0x0004003du, 0x0000000du, 0x00000087u, 0x00000070u, 0x00050041u, 0x00000020u, 0x00000088u,
0x00000062u, 0x00000029u, 0x0004003du, 0x00000006u, 0x00000089u, 0x00000088u, 0x00050050u, 0x0000000du,
0x0000008au, 0x00000089u, 0x0000002cu, 0x00050083u, 0x0000000du, 0x0000008bu, 0x00000087u, 0x0000008au,
0x00050057u, 0x0000002fu, 0x0000008cu, 0x00000086u, 0x0000008bu, 0x0008004fu, 0x00000007u, 0x0000008eu,
0x0000008cu, 0x0000008cu, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x0000008du, 0x0000008eu,
0x00050039u, 0x00000006u, 0x0000008fu, 0x0000000bu, 0x0000008du, 0x0003003eu, 0x00000085u, 0x0000008fu,
0x0004003du, 0x00000023u, 0x00000091u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000092u, 0x00000070u,
0x00050041u, 0x00000020u, 0x00000093u, 0x00000062u, 0x00000029u, 0x0004003du, 0x00000006u, 0x00000094u,
0x00000093u, 0x00050050u, 0x0000000du, 0x00000095u, 0x00000094u, 0x0000002cu, 0x00050081u, 0x0000000du,
0x00000096u, 0x00000092u, 0x00000095u, 0x00050057u, 0x0000002fu, 0x00000097u, 0x00000091u, 0x00000096u,
0x0008004fu, 0x00000007u, 0x00000099u, 0x00000097u, 0x00000097u, 0x00000000u, 0x00000001u, 0x00000002u,
0x0003003eu, 0x00000098u, 0x00000099u, 0x00050039u, 0x00000006u, 0x0000009au, 0x0000000bu, 0x00000098u,
0x0003003eu, 0x00000090u, 0x0000009au, 0x0004003du, 0x00000023u, 0x0000009cu, 0x00000025u, 0x0004003du,
0x0000000du, 0x0000009du, 0x00000070u, 0x00050041u, 0x00000020u, 0x0000009eu, 0x00000062u, 0x00000048u,
0x0004003du, 0x00000006u, 0x0000009fu, 0x0000009eu, 0x00050050u, 0x0000000du, 0x000000a0u, 0x0000002cu,
0x0000009fu, 0x00050083u, 0x0000000du, 0x000000a1u, 0x0000009du, 0x000000a0u, 0x00050057u, 0x0000002fu,
0x000000a2u, 0x0000009cu, 0x000000a1u, 0x0008004fu, 0x00000007u, 0x000000a4u, 0x000000a2u, 0x000000a2u,
0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x000000a3u, 0x000000a4u, 0x00050039u, 0x00000006u,
0x000000a5u, 0x0000000bu, 0x000000a3u, 0x0003003eu, 0x0000009bu, 0x000000a5u, 0x0004003du, 0x00000023u,
0x000000a7u, 0x00000025u, 0x0004003du, 0x0000000du, 0x000000a8u, 0x00000070u, 0x00050041u, 0x00000020u,
0x000000a9u, 0x00000062u, 0x00000048u, 0x0004003du, 0x00000006u, 0x000000aau, 0x000000a9u, 0x00050050u,
0x0000000du, 0x000000abu, 0x0000002cu, 0x000000aau, 0x00050081u, 0x0000000du, 0x000000acu, 0x000000a8u,
0x000000abu, 0x00050057u, 0x0000002fu, 0x000000adu, 0x000000a7u, 0x000000acu, 0x0008004fu, 0x00000007u,
0x000000afu, 0x000000adu, 0x000000adu, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x000000aeu,
0x000000afu, 0x00050039u, 0x00000006u, 0x000000b0u, 0x0000000bu, 0x000000aeu, 0x0003003eu, 0x000000a6u,
0x000000b0u, 0x0004003du, 0x00000006u, 0x000000b2u, 0x00000080u, 0x0004003du, 0x00000006u, 0x000000b3u,
0x00000085u, 0x00050083u, 0x00000006u, 0x000000b4u, 0x000000b2u, 0x000000b3u, 0x0006000cu, 0x00000006u,
0x000000b5u, 0x00000001u, 0x00000004u, 0x000000b4u, 0x0003003eu, 0x000000b1u, 0x000000b5u, 0x0004003du,
0x00000006u, 0x000000b7u, 0x00000080u, 0x0004003du, 0x00000006u, 0x000000b8u, 0x00000090u, 0x00050083u,
0x00000006u, 0x000000b9u, 0x000000b7u, 0x000000b8u, 0x0006000cu, 0x00000006u, 0x000000bau, 0x00000001u,
0x00000004u, 0x000000b9u, 0x0003003eu, 0x000000b6u, 0x000000bau, 0x0004003du, 0x00000006u, 0x000000bcu,
0x00000080u, 0x0004003du, 0x00000006u, 0x000000bdu, 0x0000009bu, 0x00050083u, 0x00000006u, 0x000000beu,
0x000000bcu, 0x000000bdu, 0x0006000cu, 0x00000006u, 0x000000bfu, 0x00000001u, 0x00000004u, 0x000000beu,
0x0003003eu, 0x000000bbu, 0x000000bfu, 0x0004003du, 0x00000006u, 0x000000c1u, 0x00000080u, 0x0004003du,
0x00000006u, 0x000000c2u, 0x000000a6u, 0x00050083u, 0x00000006u, 0x000000c3u, 0x000000c1u, 0x000000c2u,
0x0006000cu, 0x00000006u, 0x000000c4u, 0x00000001u, 0x00000004u, 0x000000c3u, 0x0003003eu, 0x000000c0u,
0x000000c4u, 0x0004003du, 0x00000006u, 0x000000c6u, 0x00000080u, 0x0004003du, 0x00000006u, 0x000000c7u,
0x00000085u, 0x0004003du, 0x00000006u, 0x000000c8u, 0x00000090u, 0x0007000cu, 0x00000006u, 0x000000c9u,
0x00000001u, 0x00000025u, 0x000000c7u, 0x000000c8u, 0x0004003du, 0x00000006u, 0x000000cau, 0x0000009bu,
0x0004003du, 0x00000006u, 0x000000cbu, 0x000000a6u, 0x0007000cu, 0x00000006u, 0x000000ccu, 0x00000001u,
0x00000025u, 0x000000cau, 0x000000cbu, 0x0007000cu, 0x00000006u, 0x000000cdu, 0x00000001u, 0x00000025u,
0x000000c9u, 0x000000ccu, 0x0007000cu, 0x00000006u, 0x000000ceu, 0x00000001u, 0x00000025u, 0x000000c6u,
0x000000cdu, 0x0003003eu, 0x000000c5u, 0x000000ceu, 0x0004003du, 0x00000006u, 0x000000d0u, 0x00000080u,
0x0004003du, 0x00000006u, 0x000000d1u, 0x00000085u, 0x0004003du, 0x00000006u, 0x000000d2u, 0x00000090u,
0x0007000cu, 0x00000006u, 0x000000d3u, 0x00000001u, 0x00000028u, 0x000000d1u, 0x000000d2u, 0x0004003du,
0x00000006u, 0x000000d4u, 0x0000009bu, 0x0004003du, 0x00000006u, 0x000000d5u, 0x000000a6u, 0x0007000cu,
0x00000006u, 0x000000d6u, 0x00000001u, 0x00000028u, 0x000000d4u, 0x000000d5u, 0x0007000cu, 0x00000006u,
0x000000d7u, 0x00000001u, 0x00000028u, 0x000000d3u, 0x000000d6u, 0x0007000cu, 0x00000006u, 0x000000d8u,
0x00000001u, 0x00000028u, 0x000000d0u, 0x000000d7u, 0x0003003eu, 0x000000cfu, 0x000000d8u, 0x0004003du,
0x00000006u, 0x000000dau, 0x000000cfu, 0x0004003du, 0x00000006u, 0x000000dbu, 0x000000c5u, 0x00050083u,
0x00000006u, 0x000000dcu, 0x000000dau, 0x000000dbu, 0x0003003eu, 0x000000d9u, 0x000000dcu, 0x0004003du,
0x00000006u, 0x000000dfu, 0x000000d9u, 0x00050085u, 0x00000006u, 0x000000e1u, 0x000000dfu, 0x000000e0u,
0x0007000cu, 0x00000006u, 0x000000e2u, 0x00000001u, 0x00000028u, 0x000000deu, 0x000000e1u, 0x0003003eu,
0x000000ddu, 0x000000e2u, 0x0004003du, 0x00000006u, 0x000000e4u, 0x000000b1u, 0x0004003du, 0x00000006u,
0x000000e5u, 0x000000b6u, 0x0007000cu, 0x00000006u, 0x000000e6u, 0x00000001u, 0x00000028u, 0x000000e4u,
0x000000e5u, 0x0003003eu, 0x000000e3u, 0x000000e6u, 0x0004003du, 0x00000006u, 0x000000e8u, 0x000000bbu,
0x0004003du, 0x00000006u, 0x000000e9u, 0x000000c0u, 0x0007000cu, 0x00000006u, 0x000000eau, 0x00000001u,
0x00000028u, 0x000000e8u, 0x000000e9u, 0x0003003eu, 0x000000e7u, 0x000000eau, 0x0004003du, 0x00000006u,
0x000000ecu, 0x000000e3u, 0x0004003du, 0x00000006u, 0x000000edu, 0x000000e7u, 0x0007000cu, 0x00000006u,
0x000000eeu, 0x00000001u, 0x00000028u, 0x000000ecu, 0x000000edu, 0x0003003eu, 0x000000ebu, 0x000000eeu,
0x0004003du, 0x00000006u, 0x000000efu, 0x000000ebu, 0x0004003du, 0x00000006u, 0x000000f0u, 0x000000ddu,
0x000500bcu, 0x000000f1u, 0x000000f2u, 0x000000efu, 0x000000f0u, 0x000300f7u, 0x000000f4u, 0x00000000u,
0x000400fau, 0x000000f2u, 0x000000f3u, 0x000000f4u, 0x000200f8u, 0x000000f3u, 0x0004003du, 0x0000002fu,
0x000000f7u, 0x0000007cu, 0x0003003eu, 0x000000f6u, 0x000000f7u, 0x000100fdu, 0x000200f8u, 0x000000f4u,
0x0004003du, 0x00000006u, 0x000000fbu, 0x000000e3u, 0x0004003du, 0x00000006u, 0x000000fcu, 0x000000e7u,
0x000500beu, 0x000000f1u, 0x000000fdu, 0x000000fbu, 0x000000fcu, 0x0003003eu, 0x000000fau, 0x000000fdu,
0x0004003du, 0x000000f1u, 0x000000ffu, 0x000000fau, 0x000300f7u, 0x00000102u, 0x00000000u, 0x000400fau,
0x000000ffu, 0x00000101u, 0x00000106u, 0x000200f8u, 0x00000101u, 0x00050041u, 0x00000020u, 0x00000103u,
0x00000062u, 0x00000048u, 0x0004003du, 0x00000006u, 0x00000104u, 0x00000103u, 0x00050050u, 0x0000000du,
0x00000105u, 0x0000002cu, 0x00000104u, 0x0003003eu, 0x00000100u, 0x00000105u, 0x000200f9u, 0x00000102u,
0x000200f8u, 0x00000106u, 0x00050041u, 0x00000020u, 0x00000107u, 0x00000062u, 0x00000029u, 0x0004003du,
0x00000006u, 0x00000108u, 0x00000107u, 0x00050050u, 0x0000000du, 0x00000109u, 0x00000108u, 0x0000002cu,
0x0003003eu, 0x00000100u, 0x00000109u, 0x000200f9u, 0x00000102u, 0x000200f8u, 0x00000102u, 0x0004003du,
0x0000000du, 0x0000010au, 0x00000100u, 0x0003003eu, 0x000000feu, 0x0000010au, 0x0004003du, 0x000000f1u,
0x0000010cu, 0x000000fau, 0x000300f7u, 0x0000010fu, 0x00000000u, 0x000400fau, 0x0000010cu, 0x0000010eu,
0x00000116u, 0x000200f8u, 0x0000010eu, 0x0004003du, 0x00000006u, 0x00000110u, 0x000000b1u, 0x0004003du,
0x00000006u, 0x00000111u, 0x000000b6u, 0x000500beu, 0x000000f1u, 0x00000112u, 0x00000110u, 0x00000111u,
0x000600a9u, 0x00000006u, 0x00000114u, 0x00000112u, 0x00000113u, 0x00000063u, 0x00050050u, 0x0000000du,
0x00000115u, 0x00000114u, 0x0000002cu, 0x0003003eu, 0x0000010du, 0x00000115u, 0x000200f9u, 0x0000010fu,
0x000200f8u, 0x00000116u, 0x0004003du, 0x00000006u, 0x00000117u, 0x000000bbu, 0x0004003du, 0x00000006u,
0x00000118u, 0x000000c0u, 0x000500beu, 0x000000f1u, 0x00000119u, 0x00000117u, 0x00000118u, 0x000600a9u,
0x00000006u, 0x0000011au, 0x00000119u, 0x00000113u, 0x00000063u, 0x00050050u, 0x0000000du, 0x0000011bu,
0x0000002cu, 0x0000011au, 0x0003003eu, 0x0000010du, 0x0000011bu, 0x000200f9u, 0x0000010fu, 0x000200f8u,
0x0000010fu, 0x0004003du, 0x0000000du, 0x0000011cu, 0x0000010du, 0x0003003eu, 0x0000010bu, 0x0000011cu,
0x0003003eu, 0x0000011du, 0x0000002cu, 0x0003003eu, 0x0000011eu, 0x0000002cu, 0x0003003eu, 0x00000120u,
0x00000068u, 0x000200f9u, 0x00000121u, 0x000200f8u, 0x00000121u, 0x000400f6u, 0x00000123u, 0x00000124u,
0x00000000u, 0x000200f9u, 0x00000125u, 0x000200f8u, 0x00000125u, 0x0004003du, 0x00000067u, 0x00000126u,
0x00000120u, 0x000500b3u, 0x000000f1u, 0x00000128u, 0x00000126u, 0x00000127u, 0x000400fau, 0x00000128u,
0x00000122u, 0x00000123u, 0x000200f8u, 0x00000122u, 0x0004003du, 0x0000000du, 0x0000012au, 0x000000feu,
0x0004003du, 0x00000067u, 0x0000012bu, 0x00000120u, 0x0004006fu, 0x00000006u, 0x0000012cu, 0x0000012bu,
0x0005008eu, 0x0000000du, 0x0000012du, 0x0000012au, 0x0000012cu, 0x0003003eu, 0x00000129u, 0x0000012du,
0x0004003du, 0x000000f1u, 0x0000012fu, 0x000000fau, 0x000300f7u, 0x00000132u, 0x00000000u, 0x000400fau,
0x0000012fu, 0x00000131u, 0x0000013au, 0x000200f8u, 0x00000131u, 0x0004003du, 0x0000000du, 0x00000133u,
0x00000070u, 0x0004003du, 0x0000000du, 0x00000134u, 0x00000129u, 0x00050083u, 0x0000000du, 0x00000135u,
0x00000133u, 0x00000134u, 0x0003003eu, 0x00000136u, 0x00000135u, 0x0004003du, 0x0000000du, 0x00000138u,
0x00000062u, 0x0003003eu, 0x00000137u, 0x00000138u, 0x00060039u, 0x00000006u, 0x00000139u, 0x00000012u,
0x00000136u, 0x00000137u, 0x0003003eu, 0x00000130u, 0x00000139u, 0x000200f9u, 0x00000132u, 0x000200f8u,
0x0000013au, 0x0004003du, 0x0000000du, 0x0000013bu, 0x00000070u, 0x0004003du, 0x0000000du, 0x0000013cu,
0x00000129u, 0x00050083u, 0x0000000du, 0x0000013du, 0x0000013bu, 0x0000013cu, 0x0003003eu, 0x0000013eu,
0x0000013du, 0x0004003du, 0x0000000du, 0x00000140u, 0x00000062u, 0x0003003eu, 0x0000013fu, 0x00000140u,
0x00060039u, 0x00000006u, 0x00000141u, 0x00000016u, 0x0000013eu, 0x0000013fu, 0x0003003eu, 0x00000130u,
0x00000141u, 0x000200f9u, 0x00000132u, 0x000200f8u, 0x00000132u, 0x0004003du, 0x00000006u, 0x00000142u,
0x00000130u, 0x0003003eu, 0x0000012eu, 0x00000142u, 0x0004003du, 0x000000f1u, 0x00000144u, 0x000000fau,
0x000300f7u, 0x00000147u, 0x00000000u, 0x000400fau, 0x00000144u, 0x00000146u, 0x0000014fu, 0x000200f8u,
0x00000146u, 0x0004003du, 0x0000000du, 0x00000148u, 0x00000070u, 0x0004003du, 0x0000000du, 0x00000149u,
0x00000129u, 0x00050081u, 0x0000000du, 0x0000014au, 0x00000148u, 0x00000149u, 0x0003003eu, 0x0000014bu,
0x0000014au, 0x0004003du, 0x0000000du, 0x0000014du, 0x00000062u, 0x0003003eu, 0x0000014cu, 0x0000014du,
0x00060039u, 0x00000006u, 0x0000014eu, 0x00000012u, 0x0000014bu, 0x0000014cu, 0x0003003eu, 0x00000145u,
0x0000014eu, 0x000200f9u, 0x00000147u, 0x000200f8u, 0x0000014fu, 0x0004003du, 0x0000000du, 0x00000150u,
0x00000070u, 0x0004003du, 0x0000000du, 0x00000151u, 0x00000129u, 0x00050081u, 0x0000000du, 0x00000152u,
0x00000150u, 0x00000151u, 0x0003003eu, 0x00000153u, 0x00000152u, 0x0004003du, 0x0000000du, 0x00000155u,
0x00000062u, 0x0003003eu, 0x00000154u, 0x00000155u, 0x00060039u, 0x00000006u, 0x00000156u, 0x00000016u,
0x00000153u, 0x00000154u, 0x0003003eu, 0x00000145u, 0x00000156u, 0x000200f9u, 0x00000147u, 0x000200f8u,
0x00000147u, 0x0004003du, 0x00000006u, 0x00000157u, 0x00000145u, 0x0003003eu, 0x00000143u, 0x00000157u,
0x0004003du, 0x00000006u, 0x00000158u, 0x0000011du, 0x0004003du, 0x00000067u, 0x00000159u, 0x00000120u,
0x00050082u, 0x00000067u, 0x0000015au, 0x00000159u, 0x00000068u, 0x0004006fu, 0x00000006u, 0x0000015bu,
0x0000015au, 0x000500b4u, 0x000000f1u, 0x0000015cu, 0x00000158u, 0x0000015bu, 0x000300f7u, 0x0000015eu,
0x00000000u, 0x000400fau, 0x0000015cu, 0x0000015du, 0x0000015eu, 0x000200f8u, 0x0000015du, 0x0004003du,
0x00000006u, 0x0000015fu, 0x0000012eu, 0x0004003du, 0x00000006u, 0x00000160u, 0x000000ddu, 0x00050085u,
0x00000006u, 0x00000162u, 0x00000160u, 0x00000161u, 0x000500bau, 0x000000f1u, 0x00000163u, 0x0000015fu,
0x00000162u, 0x000200f9u, 0x0000015eu, 0x000200f8u, 0x0000015eu, 0x000700f5u, 0x000000f1u, 0x00000164u,
0x0000015cu, 0x00000147u, 0x00000163u, 0x0000015du, 0x000300f7u, 0x00000166u, 0x00000000u, 0x000400fau,
0x00000164u, 0x00000165u, 0x00000166u, 0x000200f8u, 0x00000165u, 0x0004003du, 0x00000067u, 0x00000167u,
0x00000120u, 0x0004006fu, 0x00000006u, 0x00000168u, 0x00000167u, 0x0003003eu, 0x0000011du, 0x00000168u,
0x000200f9u, 0x00000166u, 0x000200f8u, 0x00000166u, 0x0004003du, 0x00000006u, 0x00000169u, 0x0000011eu,
0x0004003du, 0x00000067u, 0x0000016au, 0x00000120u, 0x00050082u, 0x00000067u, 0x0000016bu, 0x0000016au,
0x00000068u, 0x0004006fu, 0x00000006u, 0x0000016cu, 0x0000016bu, 0x000500b4u, 0x000000f1u, 0x0000016du,
0x00000169u, 0x0000016cu, 0x000300f7u, 0x0000016fu, 0x00000000u, 0x000400fau, 0x0000016du, 0x0000016eu,
0x0000016fu, 0x000200f8u, 0x0000016eu, 0x0004003du, 0x00000006u, 0x00000170u, 0x00000143u, 0x0004003du,
0x00000006u, 0x00000171u, 0x000000ddu, 0x00050085u, 0x00000006u, 0x00000172u, 0x00000171u, 0x00000161u,
0x000500bau, 0x000000f1u, 0x00000173u, 0x00000170u, 0x00000172u, 0x000200f9u, 0x0000016fu, 0x000200f8u,
0x0000016fu, 0x000700f5u, 0x000000f1u, 0x00000174u, 0x0000016du, 0x00000166u, 0x00000173u, 0x0000016eu,
0x000300f7u, 0x00000176u, 0x00000000u, 0x000400fau, 0x00000174u, 0x00000175u, 0x00000176u, 0x000200f8u,
0x00000175u, 0x0004003du, 0x00000067u, 0x00000177u, 0x00000120u, 0x0004006fu, 0x00000006u, 0x00000178u,
0x00000177u, 0x0003003eu, 0x0000011eu, 0x00000178u, 0x000200f9u, 0x00000176u, 0x000200f8u, 0x00000176u,
0x000200f9u, 0x00000124u, 0x000200f8u, 0x00000124u, 0x0004003du, 0x00000067u, 0x00000179u, 0x00000120u,
0x00050080u, 0x00000067u, 0x0000017au, 0x00000179u, 0x00000068u, 0x0003003eu, 0x00000120u, 0x0000017au,
0x000200f9u, 0x00000121u, 0x000200f8u, 0x00000123u, 0x0004003du, 0x00000006u, 0x0000017cu, 0x0000011du,
0x0004003du, 0x00000006u, 0x0000017du, 0x0000011eu, 0x00050081u, 0x00000006u, 0x0000017eu, 0x0000017cu,
0x0000017du, 0x0003003eu, 0x0000017bu, 0x0000017eu, 0x0004003du, 0x00000006u, 0x00000180u, 0x000000ddu,
0x0004003du, 0x00000006u, 0x00000181u, 0x000000ddu, 0x00050085u, 0x00000006u, 0x00000183u, 0x00000181u,
0x00000182u, 0x0004003du, 0x00000006u, 0x00000184u, 0x000000ebu, 0x0008000cu, 0x00000006u, 0x00000185u,
0x00000001u, 0x00000031u, 0x00000180u, 0x00000183u, 0x00000184u, 0x0003003eu, 0x0000017fu, 0x00000185u,
0x0004003du, 0x00000023u, 0x00000187u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000188u, 0x00000070u,
0x00050041u, 0x00000020u, 0x00000189u, 0x00000062u, 0x00000029u, 0x0004003du, 0x00000006u, 0x0000018au,
0x00000189u, 0x0004007fu, 0x00000006u, 0x0000018bu, 0x0000018au, 0x00050041u, 0x00000020u, 0x0000018cu,
0x00000062u, 0x00000048u, 0x0004003du, 0x00000006u, 0x0000018du, 0x0000018cu, 0x0004007fu, 0x00000006u,
0x0000018eu, 0x0000018du, 0x00050050u, 0x0000000du, 0x0000018fu, 0x0000018bu, 0x0000018eu, 0x00050081u,
0x0000000du, 0x00000190u, 0x00000188u, 0x0000018fu, 0x00050057u, 0x0000002fu, 0x00000191u, 0x00000187u,
0x00000190u, 0x0008004fu, 0x00000007u, 0x00000193u, 0x00000191u, 0x00000191u, 0x00000000u, 0x00000001u,
0x00000002u, 0x0003003eu, 0x00000192u, 0x00000193u, 0x00050039u, 0x00000006u, 0x00000194u, 0x0000000bu,
0x00000192u, 0x0003003eu, 0x00000186u, 0x00000194u, 0x0004003du, 0x00000023u, 0x00000196u, 0x00000025u,
0x0004003du, 0x0000000du, 0x00000197u, 0x00000070u, 0x00050041u, 0x00000020u, 0x00000198u, 0x00000062u,
0x00000029u, 0x0004003du, 0x00000006u, 0x00000199u, 0x00000198u, 0x00050041u, 0x00000020u, 0x0000019au,
0x00000062u, 0x00000048u, 0x0004003du, 0x00000006u, 0x0000019bu, 0x0000019au, 0x0004007fu, 0x00000006u,
0x0000019cu, 0x0000019bu, 0x00050050u, 0x0000000du, 0x0000019du, 0x00000199u, 0x0000019cu, 0x00050081u,
0x0000000du, 0x0000019eu, 0x00000197u, 0x0000019du, 0x00050057u, 0x0000002fu, 0x0000019fu, 0x00000196u,
0x0000019eu, 0x0008004fu, 0x00000007u, 0x000001a1u, 0x0000019fu, 0x0000019fu, 0x00000000u, 0x00000001u,
0x00000002u, 0x0003003eu, 0x000001a0u, 0x000001a1u, 0x00050039u, 0x00000006u, 0x000001a2u, 0x0000000bu,
0x000001a0u, 0x0003003eu, 0x00000195u, 0x000001a2u, 0x0004003du, 0x00000023u, 0x000001a4u, 0x00000025u,
0x0004003du, 0x0000000du, 0x000001a5u, 0x00000070u, 0x00050041u, 0x00000020u, 0x000001a6u, 0x00000062u,
0x00000029u, 0x0004003du, 0x00000006u, 0x000001a7u, 0x000001a6u, 0x0004007fu, 0x00000006u, 0x000001a8u,
0x000001a7u, 0x00050041u, 0x00000020u, 0x000001a9u, 0x00000062u, 0x00000048u, 0x0004003du, 0x00000006u,
0x000001aau, 0x000001a9u, 0x00050050u, 0x0000000du, 0x000001abu, 0x000001a8u, 0x000001aau, 0x00050081u,
0x0000000du, 0x000001acu, 0x000001a5u, 0x000001abu, 0x00050057u, 0x0000002fu, 0x000001adu, 0x000001a4u,
0x000001acu, 0x0008004fu, 0x00000007u, 0x000001afu, 0x000001adu, 0x000001adu, 0x00000000u, 0x00000001u,
0x00000002u, 0x0003003eu, 0x000001aeu, 0x000001afu, 0x00050039u, 0x00000006u, 0x000001b0u, 0x0000000bu,
0x000001aeu, 0x0003003eu, 0x000001a3u, 0x000001b0u, 0x0004003du, 0x00000023u, 0x000001b2u, 0x00000025u,
0x0004003du, 0x0000000du, 0x000001b3u, 0x00000070u, 0x00050041u, 0x00000020u, 0x000001b4u, 0x00000062u,
0x00000029u, 0x0004003du, 0x00000006u, 0x000001b5u, 0x000001b4u, 0x00050041u, 0x00000020u, 0x000001b6u,
0x00000062u, 0x00000048u, 0x0004003du, 0x00000006u, 0x000001b7u, 0x000001b6u, 0x00050050u, 0x0000000du,
0x000001b8u, 0x000001b5u, 0x000001b7u, 0x00050081u, 0x0000000du, 0x000001b9u, 0x000001b3u, 0x000001b8u,
0x00050057u, 0x0000002fu, 0x000001bau, 0x000001b2u, 0x000001b9u, 0x0008004fu, 0x00000007u, 0x000001bcu,
0x000001bau, 0x000001bau, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x000001bbu, 0x000001bcu,
0x00050039u, 0x00000006u, 0x000001bdu, 0x0000000bu, 0x000001bbu, 0x0003003eu, 0x000001b1u, 0x000001bdu,
0x0004003du, 0x00000006u, 0x000001bfu, 0x0000011du, 0x0004003du, 0x00000006u, 0x000001c0u, 0x0000011eu,
0x00050083u, 0x00000006u, 0x000001c1u, 0x000001bfu, 0x000001c0u, 0x0006000cu, 0x00000006u, 0x000001c2u,
0x00000001u, 0x00000004u, 0x000001c1u, 0x0004003du, 0x00000006u, 0x000001c3u, 0x0000017bu, 0x0007000cu,
0x00000006u, 0x000001c4u, 0x00000001u, 0x00000028u, 0x000001c3u, 0x00000063u, 0x00050088u, 0x00000006u,
0x000001c5u, 0x000001c2u, 0x000001c4u, 0x0008000cu, 0x00000006u, 0x000001c6u, 0x00000001u, 0x0000002bu,
0x000001c5u, 0x0000002cu, 0x00000063u, 0x0003003eu, 0x000001beu, 0x000001c6u, 0x0004003du, 0x00000006u,
0x000001c8u, 0x000001beu, 0x0004003du, 0x00000006u, 0x000001c9u, 0x0000017bu, 0x00050085u, 0x00000006u,
0x000001cbu, 0x000001c9u, 0x000001cau, 0x00050081u, 0x00000006u, 0x000001ccu, 0x00000063u, 0x000001cbu,
0x00050088u, 0x00000006u, 0x000001cdu, 0x000001c8u, 0x000001ccu, 0x0003003eu, 0x000001c7u, 0x000001cdu,
0x0004003du, 0x000000f1u, 0x000001cfu, 0x000000fau, 0x000300f7u, 0x000001d2u, 0x00000000u, 0x000400fau,
0x000001cfu, 0x000001d1u, 0x000001d7u, 0x000200f8u, 0x000001d1u, 0x0004003du, 0x00000006u, 0x000001d3u,
0x00000186u, 0x0004003du, 0x00000006u, 0x000001d4u, 0x00000195u, 0x00050083u, 0x00000006u, 0x000001d5u,
0x000001d3u, 0x000001d4u, 0x0006000cu, 0x00000006u, 0x000001d6u, 0x00000001u, 0x00000004u, 0x000001d5u,
0x0003003eu, 0x000001d0u, 0x000001d6u, 0x000200f9u, 0x000001d2u, 0x000200f8u, 0x000001d7u, 0x0004003du,
0x00000006u, 0x000001d8u, 0x00000186u, 0x0004003du, 0x00000006u, 0x000001d9u, 0x000001a3u, 0x00050083u,
0x00000006u, 0x000001dau, 0x000001d8u, 0x000001d9u, 0x0006000cu, 0x00000006u, 0x000001dbu, 0x00000001u,
0x00000004u, 0x000001dau, 0x0003003eu, 0x000001d0u, 0x000001dbu, 0x000200f9u, 0x000001d2u, 0x000200f8u,
0x000001d2u, 0x0004003du, 0x00000006u, 0x000001dcu, 0x000001d0u, 0x0003003eu, 0x000001ceu, 0x000001dcu,
0x0004003du, 0x000000f1u, 0x000001deu, 0x000000fau, 0x000300f7u, 0x000001e1u, 0x00000000u, 0x000400fau,
0x000001deu, 0x000001e0u, 0x000001e6u, 0x000200f8u, 0x000001e0u, 0x0004003du, 0x00000006u, 0x000001e2u,
0x000001a3u, 0x0004003du, 0x00000006u, 0x000001e3u, 0x000001b1u, 0x00050083u, 0x00000006u, 0x000001e4u,
0x000001e2u, 0x000001e3u, 0x0006000cu, 0x00000006u, 0x000001e5u, 0x00000001u, 0x00000004u, 0x000001e4u,
0x0003003eu, 0x000001dfu, 0x000001e5u, 0x000200f9u, 0x000001e1u, 0x000200f8u, 0x000001e6u, 0x0004003du,
0x00000006u, 0x000001e7u, 0x00000195u, 0x0004003du, 0x00000006u, 0x000001e8u, 0x000001b1u, 0x00050083u,
0x00000006u, 0x000001e9u, 0x000001e7u, 0x000001e8u, 0x0006000cu, 0x00000006u, 0x000001eau, 0x00000001u,
0x00000004u, 0x000001e9u, 0x0003003eu, 0x000001dfu, 0x000001eau, 0x000200f9u, 0x000001e1u, 0x000200f8u,
0x000001e1u, 0x0004003du, 0x00000006u, 0x000001ebu, 0x000001dfu, 0x0003003eu, 0x000001ddu, 0x000001ebu,
0x0004003du, 0x00000006u, 0x000001edu, 0x000001ceu, 0x0004003du, 0x00000006u, 0x000001eeu, 0x000001ddu,
0x00050083u, 0x00000006u, 0x000001efu, 0x000001edu, 0x000001eeu, 0x0006000cu, 0x00000006u, 0x000001f0u,
0x00000001u, 0x00000004u, 0x000001efu, 0x0003003eu, 0x000001ecu, 0x000001f0u, 0x0004003du, 0x00000006u,
0x000001f2u, 0x000000ddu, 0x0004003du, 0x00000006u, 0x000001f3u, 0x000000ddu, 0x00050085u, 0x00000006u,
0x000001f4u, 0x000001f3u, 0x00000182u, 0x0004003du, 0x00000006u, 0x000001f5u, 0x000001ecu, 0x0008000cu,
0x00000006u, 0x000001f6u, 0x00000001u, 0x00000031u, 0x000001f2u, 0x000001f4u, 0x000001f5u, 0x0003003eu,
0x000001f1u, 0x000001f6u, 0x0004003du, 0x00000006u, 0x000001f9u, 0x000001f1u, 0x00050085u, 0x00000006u,
0x000001fau, 0x000001f8u, 0x000001f9u, 0x0004003du, 0x00000006u, 0x000001fbu, 0x0000017bu, 0x00050088u,
0x00000006u, 0x000001fdu, 0x000001fbu, 0x000001fcu, 0x0008000cu, 0x00000006u, 0x000001feu, 0x00000001u,
0x0000002bu, 0x000001fdu, 0x0000002cu, 0x00000063u, 0x00050085u, 0x00000006u, 0x000001ffu, 0x000001fau,
0x000001feu, 0x0003003eu, 0x000001f7u, 0x000001ffu, 0x0004003du, 0x00000006u, 0x00000201u, 0x00000186u,
0x0004003du, 0x00000006u, 0x00000202u, 0x000001b1u, 0x00050083u, 0x00000006u, 0x00000203u, 0x00000201u,
0x00000202u, 0x0006000cu, 0x00000006u, 0x00000204u, 0x00000001u, 0x00000004u, 0x00000203u, 0x0004003du,
0x00000006u, 0x00000205u, 0x00000195u, 0x0004003du, 0x00000006u, 0x00000206u, 0x000001a3u, 0x00050083u,
0x00000006u, 0x00000207u, 0x00000205u, 0x00000206u, 0x0006000cu, 0x00000006u, 0x00000208u, 0x00000001u,
0x00000004u, 0x00000207u, 0x0007000cu, 0x00000006u, 0x00000209u, 0x00000001u, 0x00000028u, 0x00000204u,
0x00000208u, 0x0003003eu, 0x00000200u, 0x00000209u, 0x0004003du, 0x00000006u, 0x0000020cu, 0x000000ddu,
0x0004003du, 0x00000006u, 0x0000020du, 0x000000ddu, 0x00050085u, 0x00000006u, 0x0000020fu, 0x0000020du,
0x0000020eu, 0x0004003du, 0x00000006u, 0x00000210u, 0x00000200u, 0x0008000cu, 0x00000006u, 0x00000211u,
0x00000001u, 0x00000031u, 0x0000020cu, 0x0000020fu, 0x00000210u, 0x00050085u, 0x00000006u, 0x00000212u,
0x0000020bu, 0x00000211u, 0x00050083u, 0x00000006u, 0x00000213u, 0x00000063u, 0x00000212u, 0x0003003eu,
0x0000020au, 0x00000213u, 0x0004003du, 0x00000006u, 0x00000215u, 0x000001f7u, 0x0004003du, 0x00000006u,
0x00000216u, 0x000001c7u, 0x00050085u, 0x00000006u, 0x00000217u, 0x00000215u, 0x00000216u, 0x0004003du,
0x00000006u, 0x00000218u, 0x0000017fu, 0x00050085u, 0x00000006u, 0x00000219u, 0x00000217u, 0x00000218u,
0x0004003du, 0x00000006u, 0x0000021au, 0x0000020au, 0x00050085u, 0x00000006u, 0x0000021bu, 0x00000219u,
0x0000021au, 0x0003003eu, 0x00000214u, 0x0000021bu, 0x0004003du, 0x00000006u, 0x0000021du, 0x00000186u,
0x0004003du, 0x00000006u, 0x0000021eu, 0x000001b1u, 0x00050083u, 0x00000006u, 0x0000021fu, 0x0000021du,
0x0000021eu, 0x0006000cu, 0x00000006u, 0x00000220u, 0x00000001u, 0x00000004u, 0x0000021fu, 0x0004003du,
0x00000006u, 0x00000221u, 0x00000195u, 0x0004003du, 0x00000006u, 0x00000222u, 0x000001a3u, 0x00050083u,
0x00000006u, 0x00000223u, 0x00000221u, 0x00000222u, 0x0006000cu, 0x00000006u, 0x00000224u, 0x00000001u,
0x00000004u, 0x00000223u, 0x00050083u, 0x00000006u, 0x00000225u, 0x00000220u, 0x00000224u, 0x0006000cu,
0x00000006u, 0x00000226u, 0x00000001u, 0x00000004u, 0x00000225u, 0x0003003eu, 0x0000021cu, 0x00000226u,
0x0004003du, 0x00000006u, 0x00000228u, 0x000000ddu, 0x0004003du, 0x00000006u, 0x00000229u, 0x000000ddu,
0x00050085u, 0x00000006u, 0x0000022au, 0x00000229u, 0x00000182u, 0x0004003du, 0x00000006u, 0x0000022bu,
0x0000021cu, 0x0008000cu, 0x00000006u, 0x0000022cu, 0x00000001u, 0x00000031u, 0x00000228u, 0x0000022au,
0x0000022bu, 0x0003003eu, 0x00000227u, 0x0000022cu, 0x0004003du, 0x00000006u, 0x0000022fu, 0x00000227u,
0x00050085u, 0x00000006u, 0x00000230u, 0x0000022eu, 0x0000022fu, 0x0004003du, 0x00000006u, 0x00000231u,
0x0000017fu, 0x00050085u, 0x00000006u, 0x00000232u, 0x00000230u, 0x00000231u, 0x0004003du, 0x00000006u,
0x00000233u, 0x0000020au, 0x00050085u, 0x00000006u, 0x00000234u, 0x00000232u, 0x00000233u, 0x0003003eu,
0x0000022du, 0x00000234u, 0x0004003du, 0x00000006u, 0x00000236u, 0x00000214u, 0x000500bcu, 0x000000f1u,
0x00000238u, 0x00000236u, 0x00000237u, 0x0004003du, 0x00000006u, 0x00000239u, 0x0000022du, 0x0004003du,
0x00000006u, 0x0000023au, 0x00000214u, 0x000600a9u, 0x00000006u, 0x0000023bu, 0x00000238u, 0x00000239u,
0x0000023au, 0x0008000cu, 0x00000006u, 0x0000023du, 0x00000001u, 0x0000002bu, 0x0000023bu, 0x0000002cu,
0x0000023cu, 0x0003003eu, 0x00000235u, 0x0000023du, 0x0004003du, 0x00000023u, 0x0000023fu, 0x00000025u,
0x0004003du, 0x0000000du, 0x00000240u, 0x00000070u, 0x0004003du, 0x0000000du, 0x00000241u, 0x0000010bu,
0x0004003du, 0x0000000du, 0x00000242u, 0x00000062u, 0x00050085u, 0x0000000du, 0x00000243u, 0x00000241u,
0x00000242u, 0x00050081u, 0x0000000du, 0x00000244u, 0x00000240u, 0x00000243u, 0x00050057u, 0x0000002fu,
0x00000245u, 0x0000023fu, 0x00000244u, 0x0008004fu, 0x00000007u, 0x00000246u, 0x00000245u, 0x00000245u,
0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x0000023eu, 0x00000246u, 0x0004003du, 0x0000002fu,
0x00000247u, 0x0000007cu, 0x0008004fu, 0x00000007u, 0x00000248u, 0x00000247u, 0x00000247u, 0x00000000u,
0x00000001u, 0x00000002u, 0x0004003du, 0x00000007u, 0x00000249u, 0x0000023eu, 0x0004003du, 0x00000006u,
0x0000024au, 0x00000235u, 0x00060050u, 0x00000007u, 0x0000024bu, 0x0000024au, 0x0000024au, 0x0000024au,
0x0008000cu, 0x00000007u, 0x0000024cu, 0x00000001u, 0x0000002eu, 0x00000248u, 0x00000249u, 0x0000024bu,
0x00050041u, 0x00000020u, 0x0000024eu, 0x0000007cu, 0x0000024du, 0x0004003du, 0x00000006u, 0x0000024fu,
0x0000024eu, 0x00050051u, 0x00000006u, 0x00000250u, 0x0000024cu, 0x00000000u, 0x00050051u, 0x00000006u,
0x00000251u, 0x0000024cu, 0x00000001u, 0x00050051u, 0x00000006u, 0x00000252u, 0x0000024cu, 0x00000002u,
0x00070050u, 0x0000002fu, 0x00000253u, 0x00000250u, 0x00000251u, 0x00000252u, 0x0000024fu, 0x0003003eu,
0x000000f6u, 0x00000253u, 0x000100fdu, 0x00010038u, 0x00050036u, 0x00000006u, 0x0000000bu, 0x00000000u,
0x00000009u, 0x00030037u, 0x00000008u, 0x0000000au, 0x000200f8u, 0x0000000cu, 0x0004003du, 0x00000007u,
0x00000018u, 0x0000000au, 0x00050094u, 0x00000006u, 0x0000001du, 0x00000018u, 0x0000001cu, 0x000200feu,
0x0000001du, 0x00010038u, 0x00050036u, 0x00000006u, 0x00000012u, 0x00000000u, 0x0000000fu, 0x00030037u,
0x0000000eu, 0x00000010u, 0x00030037u, 0x0000000eu, 0x00000011u, 0x000200f8u, 0x00000013u, 0x0004003bu,
0x00000020u, 0x00000021u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x00000031u, 0x00000007u, 0x0004003bu,
0x00000020u, 0x00000034u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x0000003cu, 0x00000007u, 0x0004003du,
0x00000023u, 0x00000026u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000027u, 0x00000010u, 0x00050041u,
0x00000020u, 0x0000002au, 0x00000011u, 0x00000029u, 0x0004003du, 0x00000006u, 0x0000002bu, 0x0000002au,
0x00050050u, 0x0000000du, 0x0000002du, 0x0000002bu, 0x0000002cu, 0x00050083u, 0x0000000du, 0x0000002eu,
0x00000027u, 0x0000002du, 0x00050057u, 0x0000002fu, 0x00000030u, 0x00000026u, 0x0000002eu, 0x0008004fu,
0x00000007u, 0x00000032u, 0x00000030u, 0x00000030u, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu,
0x00000031u, 0x00000032u, 0x00050039u, 0x00000006u, 0x00000033u, 0x0000000bu, 0x00000031u, 0x0003003eu,
0x00000021u, 0x00000033u, 0x0004003du, 0x00000023u, 0x00000035u, 0x00000025u, 0x0004003du, 0x0000000du,
0x00000036u, 0x00000010u, 0x00050041u, 0x00000020u, 0x00000037u, 0x00000011u, 0x00000029u, 0x0004003du,
0x00000006u, 0x00000038u, 0x00000037u, 0x00050050u, 0x0000000du, 0x00000039u, 0x00000038u, 0x0000002cu,
0x00050081u, 0x0000000du, 0x0000003au, 0x00000036u, 0x00000039u, 0x00050057u, 0x0000002fu, 0x0000003bu,
0x00000035u, 0x0000003au, 0x0008004fu, 0x00000007u, 0x0000003du, 0x0000003bu, 0x0000003bu, 0x00000000u,
0x00000001u, 0x00000002u, 0x0003003eu, 0x0000003cu, 0x0000003du, 0x00050039u, 0x00000006u, 0x0000003eu,
0x0000000bu, 0x0000003cu, 0x0003003eu, 0x00000034u, 0x0000003eu, 0x0004003du, 0x00000006u, 0x0000003fu,
0x00000021u, 0x0004003du, 0x00000006u, 0x00000040u, 0x00000034u, 0x00050083u, 0x00000006u, 0x00000041u,
0x0000003fu, 0x00000040u, 0x0006000cu, 0x00000006u, 0x00000042u, 0x00000001u, 0x00000004u, 0x00000041u,
0x000200feu, 0x00000042u, 0x00010038u, 0x00050036u, 0x00000006u, 0x00000016u, 0x00000000u, 0x0000000fu,
0x00030037u, 0x0000000eu, 0x00000014u, 0x00030037u, 0x0000000eu, 0x00000015u, 0x000200f8u, 0x00000017u,
0x0004003bu, 0x00000020u, 0x00000045u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x0000004eu, 0x00000007u,
0x0004003bu, 0x00000020u, 0x00000051u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x00000059u, 0x00000007u,
0x0004003du, 0x00000023u, 0x00000046u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000047u, 0x00000014u,
0x00050041u, 0x00000020u, 0x00000049u, 0x00000015u, 0x00000048u, 0x0004003du, 0x00000006u, 0x0000004au,
0x00000049u, 0x00050050u, 0x0000000du, 0x0000004bu, 0x0000002cu, 0x0000004au, 0x00050083u, 0x0000000du,
0x0000004cu, 0x00000047u, 0x0000004bu, 0x00050057u, 0x0000002fu, 0x0000004du, 0x00000046u, 0x0000004cu,
0x0008004fu, 0x00000007u, 0x0000004fu, 0x0000004du, 0x0000004du, 0x00000000u, 0x00000001u, 0x00000002u,
0x0003003eu, 0x0000004eu, 0x0000004fu, 0x00050039u, 0x00000006u, 0x00000050u, 0x0000000bu, 0x0000004eu,
0x0003003eu, 0x00000045u, 0x00000050u, 0x0004003du, 0x00000023u, 0x00000052u, 0x00000025u, 0x0004003du,
0x0000000du, 0x00000053u, 0x00000014u, 0x00050041u, 0x00000020u, 0x00000054u, 0x00000015u, 0x00000048u,
0x0004003du, 0x00000006u, 0x00000055u, 0x00000054u, 0x00050050u, 0x0000000du, 0x00000056u, 0x0000002cu,
0x00000055u, 0x00050081u, 0x0000000du, 0x00000057u, 0x00000053u, 0x00000056u, 0x00050057u, 0x0000002fu,
0x00000058u, 0x00000052u, 0x00000057u, 0x0008004fu, 0x00000007u, 0x0000005au, 0x00000058u, 0x00000058u,
0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x00000059u, 0x0000005au, 0x00050039u, 0x00000006u,
0x0000005bu, 0x0000000bu, 0x00000059u, 0x0003003eu, 0x00000051u, 0x0000005bu, 0x0004003du, 0x00000006u,
0x0000005cu, 0x00000045u, 0x0004003du, 0x00000006u, 0x0000005du, 0x00000051u, 0x00050083u, 0x00000006u,
0x0000005eu, 0x0000005cu, 0x0000005du, 0x0006000cu, 0x00000006u, 0x0000005fu, 0x00000001u, 0x00000004u,
0x0000005eu, 0x000200feu, 0x0000005fu, 0x00010038u,
0x00060005u, 0x00000220u, 0x67616964u, 0x6c616e6fu, 0x74746150u, 0x006e7265u, 0x00070005u, 0x00000226u,
0x67616964u, 0x6c616e6fu, 0x746e6f43u, 0x69756e69u, 0x00007974u, 0x00070005u, 0x00000229u, 0x67616964u,
0x6c616e6fu, 0x6c6c6146u, 0x6b636162u, 0x00000000u, 0x00040005u, 0x00000235u, 0x67696577u, 0x00007468u,
0x00040005u, 0x0000023bu, 0x6f726361u, 0x00007373u, 0x00040047u, 0x00000025u, 0x00000021u, 0x00000000u,
0x00040047u, 0x00000025u, 0x00000022u, 0x00000000u, 0x00030047u, 0x00000064u, 0x00000002u, 0x00050048u,
0x00000064u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00050048u, 0x00000064u, 0x00000001u, 0x00000023u,
0x00000010u, 0x00050048u, 0x00000064u, 0x00000002u, 0x00000023u, 0x00000018u, 0x00050048u, 0x00000064u,
0x00000003u, 0x00000023u, 0x0000001cu, 0x00040047u, 0x00000072u, 0x0000001eu, 0x00000000u, 0x00040047u,
0x000000f6u, 0x0000001eu, 0x00000000u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u,
0x00030016u, 0x00000006u, 0x00000020u, 0x00040017u, 0x00000007u, 0x00000006u, 0x00000003u, 0x00040020u,
0x00000008u, 0x00000007u, 0x00000007u, 0x00040021u, 0x00000009u, 0x00000006u, 0x00000008u, 0x00040017u,
0x0000000du, 0x00000006u, 0x00000002u, 0x00040020u, 0x0000000eu, 0x00000007u, 0x0000000du, 0x00050021u,
0x0000000fu, 0x00000006u, 0x0000000eu, 0x0000000eu, 0x0004002bu, 0x00000006u, 0x00000019u, 0x3e59b3d0u,
0x0004002bu, 0x00000006u, 0x0000001au, 0x3f371759u, 0x0004002bu, 0x00000006u, 0x0000001bu, 0x3d93dd98u,
0x0006002cu, 0x00000007u, 0x0000001cu, 0x00000019u, 0x0000001au, 0x0000001bu, 0x00040020u, 0x00000020u,
0x00000007u, 0x00000006u, 0x00090019u, 0x00000022u, 0x00000006u, 0x00000001u, 0x00000000u, 0x00000000u,
0x00000000u, 0x00000001u, 0x00000000u, 0x0003001bu, 0x00000023u, 0x00000022u, 0x00040020u, 0x00000024u,
0x00000000u, 0x00000023u, 0x0004003bu, 0x00000024u, 0x00000025u, 0x00000000u, 0x00040015u, 0x00000028u,
0x00000020u, 0x00000000u, 0x0004002bu, 0x00000028u, 0x00000029u, 0x00000000u, 0x0004002bu, 0x00000006u,
0x0000002cu, 0x00000000u, 0x00040017u, 0x0000002fu, 0x00000006u, 0x00000004u, 0x0004002bu, 0x00000028u,
0x00000048u, 0x00000001u, 0x0004002bu, 0x00000006u, 0x00000063u, 0x3f800000u, 0x0006001eu, 0x00000064u,
0x0000002fu, 0x0000000du, 0x00000006u, 0x00000006u, 0x00040020u, 0x00000065u, 0x00000009u, 0x00000064u,
0x0004003bu, 0x00000065u, 0x00000066u, 0x00000009u, 0x00040015u, 0x00000067u, 0x00000020u, 0x00000001u,
0x0004002bu, 0x00000067u, 0x00000068u, 0x00000001u, 0x00040020u, 0x00000069u, 0x00000009u, 0x0000000du,
0x0005002cu, 0x0000000du, 0x0000006cu, 0x00000063u, 0x00000063u, 0x00040020u, 0x00000071u, 0x00000001u,
0x0000000du, 0x0004003bu, 0x00000071u, 0x00000072u, 0x00000001u, 0x0004002bu, 0x00000006u, 0x00000075u,
0x3f000000u, 0x00040020u, 0x0000007bu, 0x00000007u, 0x0000002fu, 0x0004002bu, 0x00000006u, 0x000000deu,
0x3d3851ecu, 0x0004002bu, 0x00000006u, 0x000000e0u, 0x3da3d70au, 0x00020014u, 0x000000f1u, 0x00040020u,
0x000000f5u, 0x00000003u, 0x0000002fu, 0x0004003bu, 0x000000f5u, 0x000000f6u, 0x00000003u, 0x00040020u,
0x000000f9u, 0x00000007u, 0x000000f1u, 0x0004002bu, 0x00000006u, 0x00000113u, 0xbf800000u, 0x00040020u,
0x0000011fu, 0x00000007u, 0x00000067u, 0x0004002bu, 0x00000067u, 0x00000127u, 0x00000006u, 0x0004002bu,
0x00000006u, 0x00000161u, 0x3f266666u, 0x0004002bu, 0x00000006u, 0x00000182u, 0x40200000u, 0x0004002bu,
0x00000006u, 0x000001cau, 0x3d6147aeu, 0x0004002bu, 0x00000006u, 0x000001f8u, 0x3ec28f5cu, 0x0004002bu,
0x00000006u, 0x000001fcu, 0x40800000u, 0x0004002bu, 0x00000006u, 0x0000020bu, 0x3eb33333u, 0x0004002bu,
0x00000006u, 0x0000020eu, 0x40400000u, 0x0004002bu, 0x00000006u, 0x0000022au, 0x3e23d70au, 0x0004002bu,
0x00000006u, 0x00000239u, 0x3ed70a3du, 0x0004002bu, 0x00000028u, 0x0000024au, 0x00000003u, 0x00050036u,
0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u, 0x0004003bu, 0x0000000eu,
0x00000062u, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x00000070u, 0x00000007u, 0x0004003bu, 0x0000007bu,
0x0000007cu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000080u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x00000081u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000085u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x0000008du, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000090u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x00000098u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000009bu, 0x00000007u, 0x0004003bu, 0x00000008u,
0x000000a3u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000a6u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x000000aeu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000b1u, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000000b6u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000bbu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000000c0u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000c5u, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000000cfu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000d9u, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000000ddu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000e3u, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000000e7u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000ebu, 0x00000007u, 0x0004003bu, 0x000000f9u,
0x000000fau, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x000000feu, 0x00000007u, 0x0004003bu, 0x0000000eu,
0x00000100u, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x0000010bu, 0x00000007u, 0x0004003bu, 0x0000000eu,
0x0000010du, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000011du, 0x00000007u, 0x0004003bu, 0x00000020u,
0x0000011eu, 0x00000007u, 0x0004003bu, 0x0000011fu, 0x00000120u, 0x00000007u, 0x0004003bu, 0x0000000eu,
0x00000129u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000012eu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x00000130u, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x00000136u, 0x00000007u, 0x0004003bu, 0x0000000eu,
0x00000137u, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x0000013eu, 0x00000007u, 0x0004003bu, 0x0000000eu,
0x0000013fu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000143u, 0x00000007u, 0x0004003bu, 0x00000020u,
0x00000145u, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x0000014bu, 0x00000007u, 0x0004003bu, 0x0000000eu,
0x0000014cu, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x00000153u, 0x00000007u, 0x0004003bu, 0x0000000eu,
0x00000154u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000017bu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x0000017fu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000186u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x00000192u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000195u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x000001a0u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001a3u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x000001aeu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001b1u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x000001bbu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001beu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000001c7u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001ceu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000001d0u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001ddu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000001dfu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001ecu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000001f1u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001f7u, 0x00000007u, 0x0004003bu, 0x00000020u,
0x00000200u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000020au, 0x00000007u, 0x0004003bu, 0x00000020u,
0x00000214u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000021cu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x00000220u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000226u, 0x00000007u, 0x0004003bu, 0x00000020u,
0x00000229u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000235u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x0000023bu, 0x00000007u, 0x00050041u, 0x00000069u, 0x0000006au, 0x00000066u, 0x00000068u, 0x0004003du,
0x0000000du, 0x0000006bu, 0x0000006au, 0x0007000cu, 0x0000000du, 0x0000006du, 0x00000001u, 0x00000028u,
0x0000006bu, 0x0000006cu, 0x00050050u, 0x0000000du, 0x0000006eu, 0x00000063u, 0x00000063u, 0x00050088u,
0x0000000du, 0x0000006fu, 0x0000006eu, 0x0000006du, 0x0003003eu, 0x00000062u, 0x0000006fu, 0x0004003du,
0x0000000du, 0x00000073u, 0x00000072u, 0x0004003du, 0x0000000du, 0x00000074u, 0x00000062u, 0x0005008eu,
0x0000000du, 0x00000076u, 0x00000074u, 0x00000075u, 0x0004003du, 0x0000000du, 0x00000077u, 0x00000062u,
0x0005008eu, 0x0000000du, 0x00000078u, 0x00000077u, 0x00000075u, 0x00050083u, 0x0000000du, 0x00000079u,
0x0000006cu, 0x00000078u, 0x0008000cu, 0x0000000du, 0x0000007au, 0x00000001u, 0x0000002bu, 0x00000073u,
0x00000076u, 0x00000079u, 0x0003003eu, 0x00000070u, 0x0000007au, 0x0004003du, 0x00000023u, 0x0000007du,
0x00000025u, 0x0004003du, 0x0000000du, 0x0000007eu, 0x00000070u, 0x00050057u, 0x0000002fu, 0x0000007fu,
0x0000007du, 0x0000007eu, 0x0003003eu, 0x0000007cu, 0x0000007fu, 0x0004003du, 0x0000002fu, 0x00000082u,
0x0000007cu, 0x0008004fu, 0x00000007u, 0x00000083u, 0x00000082u, 0x00000082u, 0x00000000u, 0x00000001u,
0x00000002u, 0x0003003eu, 0x00000081u, 0x00000083u, 0x00050039u, 0x00000006u, 0x00000084u, 0x0000000bu,
0x00000081u, 0x0003003eu, 0x00000080u, 0x00000084u, 0x0004003du, 0x00000023u, 0x00000086u, 0x00000025u,
0x0004003du, 0x0000000du, 0x00000087u, 0x00000070u, 0x00050041u, 0x00000020u, 0x00000088u, 0x00000062u,
0x00000029u, 0x0004003du, 0x00000006u, 0x00000089u, 0x00000088u, 0x00050050u, 0x0000000du, 0x0000008au,
0x00000089u, 0x0000002cu, 0x00050083u, 0x0000000du, 0x0000008bu, 0x00000087u, 0x0000008au, 0x00050057u,
0x0000002fu, 0x0000008cu, 0x00000086u, 0x0000008bu, 0x0008004fu, 0x00000007u, 0x0000008eu, 0x0000008cu,
0x0000008cu, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x0000008du, 0x0000008eu, 0x00050039u,
0x00000006u, 0x0000008fu, 0x0000000bu, 0x0000008du, 0x0003003eu, 0x00000085u, 0x0000008fu, 0x0004003du,
0x00000023u, 0x00000091u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000092u, 0x00000070u, 0x00050041u,
0x00000020u, 0x00000093u, 0x00000062u, 0x00000029u, 0x0004003du, 0x00000006u, 0x00000094u, 0x00000093u,
0x00050050u, 0x0000000du, 0x00000095u, 0x00000094u, 0x0000002cu, 0x00050081u, 0x0000000du, 0x00000096u,
0x00000092u, 0x00000095u, 0x00050057u, 0x0000002fu, 0x00000097u, 0x00000091u, 0x00000096u, 0x0008004fu,
0x00000007u, 0x00000099u, 0x00000097u, 0x00000097u, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu,
0x00000098u, 0x00000099u, 0x00050039u, 0x00000006u, 0x0000009au, 0x0000000bu, 0x00000098u, 0x0003003eu,
0x00000090u, 0x0000009au, 0x0004003du, 0x00000023u, 0x0000009cu, 0x00000025u, 0x0004003du, 0x0000000du,
0x0000009du, 0x00000070u, 0x00050041u, 0x00000020u, 0x0000009eu, 0x00000062u, 0x00000048u, 0x0004003du,
0x00000006u, 0x0000009fu, 0x0000009eu, 0x00050050u, 0x0000000du, 0x000000a0u, 0x0000002cu, 0x0000009fu,
0x00050083u, 0x0000000du, 0x000000a1u, 0x0000009du, 0x000000a0u, 0x00050057u, 0x0000002fu, 0x000000a2u,
0x0000009cu, 0x000000a1u, 0x0008004fu, 0x00000007u, 0x000000a4u, 0x000000a2u, 0x000000a2u, 0x00000000u,
0x00000001u, 0x00000002u, 0x0003003eu, 0x000000a3u, 0x000000a4u, 0x00050039u, 0x00000006u, 0x000000a5u,
0x0000000bu, 0x000000a3u, 0x0003003eu, 0x0000009bu, 0x000000a5u, 0x0004003du, 0x00000023u, 0x000000a7u,
0x00000025u, 0x0004003du, 0x0000000du, 0x000000a8u, 0x00000070u, 0x00050041u, 0x00000020u, 0x000000a9u,
0x00000062u, 0x00000048u, 0x0004003du, 0x00000006u, 0x000000aau, 0x000000a9u, 0x00050050u, 0x0000000du,
0x000000abu, 0x0000002cu, 0x000000aau, 0x00050081u, 0x0000000du, 0x000000acu, 0x000000a8u, 0x000000abu,
0x00050057u, 0x0000002fu, 0x000000adu, 0x000000a7u, 0x000000acu, 0x0008004fu, 0x00000007u, 0x000000afu,
0x000000adu, 0x000000adu, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x000000aeu, 0x000000afu,
0x00050039u, 0x00000006u, 0x000000b0u, 0x0000000bu, 0x000000aeu, 0x0003003eu, 0x000000a6u, 0x000000b0u,
0x0004003du, 0x00000006u, 0x000000b2u, 0x00000080u, 0x0004003du, 0x00000006u, 0x000000b3u, 0x00000085u,
0x00050083u, 0x00000006u, 0x000000b4u, 0x000000b2u, 0x000000b3u, 0x0006000cu, 0x00000006u, 0x000000b5u,
0x00000001u, 0x00000004u, 0x000000b4u, 0x0003003eu, 0x000000b1u, 0x000000b5u, 0x0004003du, 0x00000006u,
0x000000b7u, 0x00000080u, 0x0004003du, 0x00000006u, 0x000000b8u, 0x00000090u, 0x00050083u, 0x00000006u,
0x000000b9u, 0x000000b7u, 0x000000b8u, 0x0006000cu, 0x00000006u, 0x000000bau, 0x00000001u, 0x00000004u,
0x000000b9u, 0x0003003eu, 0x000000b6u, 0x000000bau, 0x0004003du, 0x00000006u, 0x000000bcu, 0x00000080u,
0x0004003du, 0x00000006u, 0x000000bdu, 0x0000009bu, 0x00050083u, 0x00000006u, 0x000000beu, 0x000000bcu,
0x000000bdu, 0x0006000cu, 0x00000006u, 0x000000bfu, 0x00000001u, 0x00000004u, 0x000000beu, 0x0003003eu,
0x000000bbu, 0x000000bfu, 0x0004003du, 0x00000006u, 0x000000c1u, 0x00000080u, 0x0004003du, 0x00000006u,
0x000000c2u, 0x000000a6u, 0x00050083u, 0x00000006u, 0x000000c3u, 0x000000c1u, 0x000000c2u, 0x0006000cu,
0x00000006u, 0x000000c4u, 0x00000001u, 0x00000004u, 0x000000c3u, 0x0003003eu, 0x000000c0u, 0x000000c4u,
0x0004003du, 0x00000006u, 0x000000c6u, 0x00000080u, 0x0004003du, 0x00000006u, 0x000000c7u, 0x00000085u,
0x0004003du, 0x00000006u, 0x000000c8u, 0x00000090u, 0x0007000cu, 0x00000006u, 0x000000c9u, 0x00000001u,
0x00000025u, 0x000000c7u, 0x000000c8u, 0x0004003du, 0x00000006u, 0x000000cau, 0x0000009bu, 0x0004003du,
0x00000006u, 0x000000cbu, 0x000000a6u, 0x0007000cu, 0x00000006u, 0x000000ccu, 0x00000001u, 0x00000025u,
0x000000cau, 0x000000cbu, 0x0007000cu, 0x00000006u, 0x000000cdu, 0x00000001u, 0x00000025u, 0x000000c9u,
0x000000ccu, 0x0007000cu, 0x00000006u, 0x000000ceu, 0x00000001u, 0x00000025u, 0x000000c6u, 0x000000cdu,
0x0003003eu, 0x000000c5u, 0x000000ceu, 0x0004003du, 0x00000006u, 0x000000d0u, 0x00000080u, 0x0004003du,
0x00000006u, 0x000000d1u, 0x00000085u, 0x0004003du, 0x00000006u, 0x000000d2u, 0x00000090u, 0x0007000cu,
0x00000006u, 0x000000d3u, 0x00000001u, 0x00000028u, 0x000000d1u, 0x000000d2u, 0x0004003du, 0x00000006u,
0x000000d4u, 0x0000009bu, 0x0004003du, 0x00000006u, 0x000000d5u, 0x000000a6u, 0x0007000cu, 0x00000006u,
0x000000d6u, 0x00000001u, 0x00000028u, 0x000000d4u, 0x000000d5u, 0x0007000cu, 0x00000006u, 0x000000d7u,
0x00000001u, 0x00000028u, 0x000000d3u, 0x000000d6u, 0x0007000cu, 0x00000006u, 0x000000d8u, 0x00000001u,
0x00000028u, 0x000000d0u, 0x000000d7u, 0x0003003eu, 0x000000cfu, 0x000000d8u, 0x0004003du, 0x00000006u,
0x000000dau, 0x000000cfu, 0x0004003du, 0x00000006u, 0x000000dbu, 0x000000c5u, 0x00050083u, 0x00000006u,
0x000000dcu, 0x000000dau, 0x000000dbu, 0x0003003eu, 0x000000d9u, 0x000000dcu, 0x0004003du, 0x00000006u,
0x000000dfu, 0x000000d9u, 0x00050085u, 0x00000006u, 0x000000e1u, 0x000000dfu, 0x000000e0u, 0x0007000cu,
0x00000006u, 0x000000e2u, 0x00000001u, 0x00000028u, 0x000000deu, 0x000000e1u, 0x0003003eu, 0x000000ddu,
0x000000e2u, 0x0004003du, 0x00000006u, 0x000000e4u, 0x000000b1u, 0x0004003du, 0x00000006u, 0x000000e5u,
0x000000b6u, 0x0007000cu, 0x00000006u, 0x000000e6u, 0x00000001u, 0x00000028u, 0x000000e4u, 0x000000e5u,
0x0003003eu, 0x000000e3u, 0x000000e6u, 0x0004003du, 0x00000006u, 0x000000e8u, 0x000000bbu, 0x0004003du,
0x00000006u, 0x000000e9u, 0x000000c0u, 0x0007000cu, 0x00000006u, 0x000000eau, 0x00000001u, 0x00000028u,
0x000000e8u, 0x000000e9u, 0x0003003eu, 0x000000e7u, 0x000000eau, 0x0004003du, 0x00000006u, 0x000000ecu,
0x000000e3u, 0x0004003du, 0x00000006u, 0x000000edu, 0x000000e7u, 0x0007000cu, 0x00000006u, 0x000000eeu,
0x00000001u, 0x00000028u, 0x000000ecu, 0x000000edu, 0x0003003eu, 0x000000ebu, 0x000000eeu, 0x0004003du,
0x00000006u, 0x000000efu, 0x000000ebu, 0x0004003du, 0x00000006u, 0x000000f0u, 0x000000ddu, 0x000500bcu,
0x000000f1u, 0x000000f2u, 0x000000efu, 0x000000f0u, 0x000300f7u, 0x000000f4u, 0x00000000u, 0x000400fau,
0x000000f2u, 0x000000f3u, 0x000000f4u, 0x000200f8u, 0x000000f3u, 0x0004003du, 0x0000002fu, 0x000000f7u,
0x0000007cu, 0x0003003eu, 0x000000f6u, 0x000000f7u, 0x000100fdu, 0x000200f8u, 0x000000f4u, 0x0004003du,
0x00000006u, 0x000000fbu, 0x000000e3u, 0x0004003du, 0x00000006u, 0x000000fcu, 0x000000e7u, 0x000500beu,
0x000000f1u, 0x000000fdu, 0x000000fbu, 0x000000fcu, 0x0003003eu, 0x000000fau, 0x000000fdu, 0x0004003du,
0x000000f1u, 0x000000ffu, 0x000000fau, 0x000300f7u, 0x00000102u, 0x00000000u, 0x000400fau, 0x000000ffu,
0x00000101u, 0x00000106u, 0x000200f8u, 0x00000101u, 0x00050041u, 0x00000020u, 0x00000103u, 0x00000062u,
0x00000048u, 0x0004003du, 0x00000006u, 0x00000104u, 0x00000103u, 0x00050050u, 0x0000000du, 0x00000105u,
0x0000002cu, 0x00000104u, 0x0003003eu, 0x00000100u, 0x00000105u, 0x000200f9u, 0x00000102u, 0x000200f8u,
0x00000106u, 0x00050041u, 0x00000020u, 0x00000107u, 0x00000062u, 0x00000029u, 0x0004003du, 0x00000006u,
0x00000108u, 0x00000107u, 0x00050050u, 0x0000000du, 0x00000109u, 0x00000108u, 0x0000002cu, 0x0003003eu,
0x00000100u, 0x00000109u, 0x000200f9u, 0x00000102u, 0x000200f8u, 0x00000102u, 0x0004003du, 0x0000000du,
0x0000010au, 0x00000100u, 0x0003003eu, 0x000000feu, 0x0000010au, 0x0004003du, 0x000000f1u, 0x0000010cu,
0x000000fau, 0x000300f7u, 0x0000010fu, 0x00000000u, 0x000400fau, 0x0000010cu, 0x0000010eu, 0x00000116u,
0x000200f8u, 0x0000010eu, 0x0004003du, 0x00000006u, 0x00000110u, 0x000000b1u, 0x0004003du, 0x00000006u,
0x00000111u, 0x000000b6u, 0x000500beu, 0x000000f1u, 0x00000112u, 0x00000110u, 0x00000111u, 0x000600a9u,
0x00000006u, 0x00000114u, 0x00000112u, 0x00000113u, 0x00000063u, 0x00050050u, 0x0000000du, 0x00000115u,
0x00000114u, 0x0000002cu, 0x0003003eu, 0x0000010du, 0x00000115u, 0x000200f9u, 0x0000010fu, 0x000200f8u,
0x00000116u, 0x0004003du, 0x00000006u, 0x00000117u, 0x000000bbu, 0x0004003du, 0x00000006u, 0x00000118u,
0x000000c0u, 0x000500beu, 0x000000f1u, 0x00000119u, 0x00000117u, 0x00000118u, 0x000600a9u, 0x00000006u,
0x0000011au, 0x00000119u, 0x00000113u, 0x00000063u, 0x00050050u, 0x0000000du, 0x0000011bu, 0x0000002cu,
0x0000011au, 0x0003003eu, 0x0000010du, 0x0000011bu, 0x000200f9u, 0x0000010fu, 0x000200f8u, 0x0000010fu,
0x0004003du, 0x0000000du, 0x0000011cu, 0x0000010du, 0x0003003eu, 0x0000010bu, 0x0000011cu, 0x0003003eu,
0x0000011du, 0x0000002cu, 0x0003003eu, 0x0000011eu, 0x0000002cu, 0x0003003eu, 0x00000120u, 0x00000068u,
0x000200f9u, 0x00000121u, 0x000200f8u, 0x00000121u, 0x000400f6u, 0x00000123u, 0x00000124u, 0x00000000u,
0x000200f9u, 0x00000125u, 0x000200f8u, 0x00000125u, 0x0004003du, 0x00000067u, 0x00000126u, 0x00000120u,
0x000500b3u, 0x000000f1u, 0x00000128u, 0x00000126u, 0x00000127u, 0x000400fau, 0x00000128u, 0x00000122u,
0x00000123u, 0x000200f8u, 0x00000122u, 0x0004003du, 0x0000000du, 0x0000012au, 0x000000feu, 0x0004003du,
0x00000067u, 0x0000012bu, 0x00000120u, 0x0004006fu, 0x00000006u, 0x0000012cu, 0x0000012bu, 0x0005008eu,
0x0000000du, 0x0000012du, 0x0000012au, 0x0000012cu, 0x0003003eu, 0x00000129u, 0x0000012du, 0x0004003du,
0x000000f1u, 0x0000012fu, 0x000000fau, 0x000300f7u, 0x00000132u, 0x00000000u, 0x000400fau, 0x0000012fu,
0x00000131u, 0x0000013au, 0x000200f8u, 0x00000131u, 0x0004003du, 0x0000000du, 0x00000133u, 0x00000070u,
0x0004003du, 0x0000000du, 0x00000134u, 0x00000129u, 0x00050083u, 0x0000000du, 0x00000135u, 0x00000133u,
0x00000134u, 0x0003003eu, 0x00000136u, 0x00000135u, 0x0004003du, 0x0000000du, 0x00000138u, 0x00000062u,
0x0003003eu, 0x00000137u, 0x00000138u, 0x00060039u, 0x00000006u, 0x00000139u, 0x00000012u, 0x00000136u,
0x00000137u, 0x0003003eu, 0x00000130u, 0x00000139u, 0x000200f9u, 0x00000132u, 0x000200f8u, 0x0000013au,
0x0004003du, 0x0000000du, 0x0000013bu, 0x00000070u, 0x0004003du, 0x0000000du, 0x0000013cu, 0x00000129u,
0x00050083u, 0x0000000du, 0x0000013du, 0x0000013bu, 0x0000013cu, 0x0003003eu, 0x0000013eu, 0x0000013du,
0x0004003du, 0x0000000du, 0x00000140u, 0x00000062u, 0x0003003eu, 0x0000013fu, 0x00000140u, 0x00060039u,
0x00000006u, 0x00000141u, 0x00000016u, 0x0000013eu, 0x0000013fu, 0x0003003eu, 0x00000130u, 0x00000141u,
0x000200f9u, 0x00000132u, 0x000200f8u, 0x00000132u, 0x0004003du, 0x00000006u, 0x00000142u, 0x00000130u,
0x0003003eu, 0x0000012eu, 0x00000142u, 0x0004003du, 0x000000f1u, 0x00000144u, 0x000000fau, 0x000300f7u,
0x00000147u, 0x00000000u, 0x000400fau, 0x00000144u, 0x00000146u, 0x0000014fu, 0x000200f8u, 0x00000146u,
0x0004003du, 0x0000000du, 0x00000148u, 0x00000070u, 0x0004003du, 0x0000000du, 0x00000149u, 0x00000129u,
0x00050081u, 0x0000000du, 0x0000014au, 0x00000148u, 0x00000149u, 0x0003003eu, 0x0000014bu, 0x0000014au,
0x0004003du, 0x0000000du, 0x0000014du, 0x00000062u, 0x0003003eu, 0x0000014cu, 0x0000014du, 0x00060039u,
0x00000006u, 0x0000014eu, 0x00000012u, 0x0000014bu, 0x0000014cu, 0x0003003eu, 0x00000145u, 0x0000014eu,
0x000200f9u, 0x00000147u, 0x000200f8u, 0x0000014fu, 0x0004003du, 0x0000000du, 0x00000150u, 0x00000070u,
0x0004003du, 0x0000000du, 0x00000151u, 0x00000129u, 0x00050081u, 0x0000000du, 0x00000152u, 0x00000150u,
0x00000151u, 0x0003003eu, 0x00000153u, 0x00000152u, 0x0004003du, 0x0000000du, 0x00000155u, 0x00000062u,
0x0003003eu, 0x00000154u, 0x00000155u, 0x00060039u, 0x00000006u, 0x00000156u, 0x00000016u, 0x00000153u,
0x00000154u, 0x0003003eu, 0x00000145u, 0x00000156u, 0x000200f9u, 0x00000147u, 0x000200f8u, 0x00000147u,
0x0004003du, 0x00000006u, 0x00000157u, 0x00000145u, 0x0003003eu, 0x00000143u, 0x00000157u, 0x0004003du,
0x00000006u, 0x00000158u, 0x0000011du, 0x0004003du, 0x00000067u, 0x00000159u, 0x00000120u, 0x00050082u,
0x00000067u, 0x0000015au, 0x00000159u, 0x00000068u, 0x0004006fu, 0x00000006u, 0x0000015bu, 0x0000015au,
0x000500b4u, 0x000000f1u, 0x0000015cu, 0x00000158u, 0x0000015bu, 0x000300f7u, 0x0000015eu, 0x00000000u,
0x000400fau, 0x0000015cu, 0x0000015du, 0x0000015eu, 0x000200f8u, 0x0000015du, 0x0004003du, 0x00000006u,
0x0000015fu, 0x0000012eu, 0x0004003du, 0x00000006u, 0x00000160u, 0x000000ddu, 0x00050085u, 0x00000006u,
0x00000162u, 0x00000160u, 0x00000161u, 0x000500bau, 0x000000f1u, 0x00000163u, 0x0000015fu, 0x00000162u,
0x000200f9u, 0x0000015eu, 0x000200f8u, 0x0000015eu, 0x000700f5u, 0x000000f1u, 0x00000164u, 0x0000015cu,
0x00000147u, 0x00000163u, 0x0000015du, 0x000300f7u, 0x00000166u, 0x00000000u, 0x000400fau, 0x00000164u,
0x00000165u, 0x00000166u, 0x000200f8u, 0x00000165u, 0x0004003du, 0x00000067u, 0x00000167u, 0x00000120u,
0x0004006fu, 0x00000006u, 0x00000168u, 0x00000167u, 0x0003003eu, 0x0000011du, 0x00000168u, 0x000200f9u,
0x00000166u, 0x000200f8u, 0x00000166u, 0x0004003du, 0x00000006u, 0x00000169u, 0x0000011eu, 0x0004003du,
0x00000067u, 0x0000016au, 0x00000120u, 0x00050082u, 0x00000067u, 0x0000016bu, 0x0000016au, 0x00000068u,
0x0004006fu, 0x00000006u, 0x0000016cu, 0x0000016bu, 0x000500b4u, 0x000000f1u, 0x0000016du, 0x00000169u,
0x0000016cu, 0x000300f7u, 0x0000016fu, 0x00000000u, 0x000400fau, 0x0000016du, 0x0000016eu, 0x0000016fu,
0x000200f8u, 0x0000016eu, 0x0004003du, 0x00000006u, 0x00000170u, 0x00000143u, 0x0004003du, 0x00000006u,
0x00000171u, 0x000000ddu, 0x00050085u, 0x00000006u, 0x00000172u, 0x00000171u, 0x00000161u, 0x000500bau,
0x000000f1u, 0x00000173u, 0x00000170u, 0x00000172u, 0x000200f9u, 0x0000016fu, 0x000200f8u, 0x0000016fu,
0x000700f5u, 0x000000f1u, 0x00000174u, 0x0000016du, 0x00000166u, 0x00000173u, 0x0000016eu, 0x000300f7u,
0x00000176u, 0x00000000u, 0x000400fau, 0x00000174u, 0x00000175u, 0x00000176u, 0x000200f8u, 0x00000175u,
0x0004003du, 0x00000067u, 0x00000177u, 0x00000120u, 0x0004006fu, 0x00000006u, 0x00000178u, 0x00000177u,
0x0003003eu, 0x0000011eu, 0x00000178u, 0x000200f9u, 0x00000176u, 0x000200f8u, 0x00000176u, 0x000200f9u,
0x00000124u, 0x000200f8u, 0x00000124u, 0x0004003du, 0x00000067u, 0x00000179u, 0x00000120u, 0x00050080u,
0x00000067u, 0x0000017au, 0x00000179u, 0x00000068u, 0x0003003eu, 0x00000120u, 0x0000017au, 0x000200f9u,
0x00000121u, 0x000200f8u, 0x00000123u, 0x0004003du, 0x00000006u, 0x0000017cu, 0x0000011du, 0x0004003du,
0x00000006u, 0x0000017du, 0x0000011eu, 0x00050081u, 0x00000006u, 0x0000017eu, 0x0000017cu, 0x0000017du,
0x0003003eu, 0x0000017bu, 0x0000017eu, 0x0004003du, 0x00000006u, 0x00000180u, 0x000000ddu, 0x0004003du,
0x00000006u, 0x00000181u, 0x000000ddu, 0x00050085u, 0x00000006u, 0x00000183u, 0x00000181u, 0x00000182u,
0x0004003du, 0x00000006u, 0x00000184u, 0x000000ebu, 0x0008000cu, 0x00000006u, 0x00000185u, 0x00000001u,
0x00000031u, 0x00000180u, 0x00000183u, 0x00000184u, 0x0003003eu, 0x0000017fu, 0x00000185u, 0x0004003du,
0x00000023u, 0x00000187u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000188u, 0x00000070u, 0x00050041u,
0x00000020u, 0x00000189u, 0x00000062u, 0x00000029u, 0x0004003du, 0x00000006u, 0x0000018au, 0x00000189u,
0x0004007fu, 0x00000006u, 0x0000018bu, 0x0000018au, 0x00050041u, 0x00000020u, 0x0000018cu, 0x00000062u,
0x00000048u, 0x0004003du, 0x00000006u, 0x0000018du, 0x0000018cu, 0x0004007fu, 0x00000006u, 0x0000018eu,
0x0000018du, 0x00050050u, 0x0000000du, 0x0000018fu, 0x0000018bu, 0x0000018eu, 0x00050081u, 0x0000000du,
0x00000190u, 0x00000188u, 0x0000018fu, 0x00050057u, 0x0000002fu, 0x00000191u, 0x00000187u, 0x00000190u,
0x0008004fu, 0x00000007u, 0x00000193u, 0x00000191u, 0x00000191u, 0x00000000u, 0x00000001u, 0x00000002u,
0x0003003eu, 0x00000192u, 0x00000193u, 0x00050039u, 0x00000006u, 0x00000194u, 0x0000000bu, 0x00000192u,
0x0003003eu, 0x00000186u, 0x00000194u, 0x0004003du, 0x00000023u, 0x00000196u, 0x00000025u, 0x0004003du,
0x0000000du, 0x00000197u, 0x00000070u, 0x00050041u, 0x00000020u, 0x00000198u, 0x00000062u, 0x00000029u,
0x0004003du, 0x00000006u, 0x00000199u, 0x00000198u, 0x00050041u, 0x00000020u, 0x0000019au, 0x00000062u,
0x00000048u, 0x0004003du, 0x00000006u, 0x0000019bu, 0x0000019au, 0x0004007fu, 0x00000006u, 0x0000019cu,
0x0000019bu, 0x00050050u, 0x0000000du, 0x0000019du, 0x00000199u, 0x0000019cu, 0x00050081u, 0x0000000du,
0x0000019eu, 0x00000197u, 0x0000019du, 0x00050057u, 0x0000002fu, 0x0000019fu, 0x00000196u, 0x0000019eu,
0x0008004fu, 0x00000007u, 0x000001a1u, 0x0000019fu, 0x0000019fu, 0x00000000u, 0x00000001u, 0x00000002u,
0x0003003eu, 0x000001a0u, 0x000001a1u, 0x00050039u, 0x00000006u, 0x000001a2u, 0x0000000bu, 0x000001a0u,
0x0003003eu, 0x00000195u, 0x000001a2u, 0x0004003du, 0x00000023u, 0x000001a4u, 0x00000025u, 0x0004003du,
0x0000000du, 0x000001a5u, 0x00000070u, 0x00050041u, 0x00000020u, 0x000001a6u, 0x00000062u, 0x00000029u,
0x0004003du, 0x00000006u, 0x000001a7u, 0x000001a6u, 0x0004007fu, 0x00000006u, 0x000001a8u, 0x000001a7u,
0x00050041u, 0x00000020u, 0x000001a9u, 0x00000062u, 0x00000048u, 0x0004003du, 0x00000006u, 0x000001aau,
0x000001a9u, 0x00050050u, 0x0000000du, 0x000001abu, 0x000001a8u, 0x000001aau, 0x00050081u, 0x0000000du,
0x000001acu, 0x000001a5u, 0x000001abu, 0x00050057u, 0x0000002fu, 0x000001adu, 0x000001a4u, 0x000001acu,
0x0008004fu, 0x00000007u, 0x000001afu, 0x000001adu, 0x000001adu, 0x00000000u, 0x00000001u, 0x00000002u,
0x0003003eu, 0x000001aeu, 0x000001afu, 0x00050039u, 0x00000006u, 0x000001b0u, 0x0000000bu, 0x000001aeu,
0x0003003eu, 0x000001a3u, 0x000001b0u, 0x0004003du, 0x00000023u, 0x000001b2u, 0x00000025u, 0x0004003du,
0x0000000du, 0x000001b3u, 0x00000070u, 0x00050041u, 0x00000020u, 0x000001b4u, 0x00000062u, 0x00000029u,
0x0004003du, 0x00000006u, 0x000001b5u, 0x000001b4u, 0x00050041u, 0x00000020u, 0x000001b6u, 0x00000062u,
0x00000048u, 0x0004003du, 0x00000006u, 0x000001b7u, 0x000001b6u, 0x00050050u, 0x0000000du, 0x000001b8u,
0x000001b5u, 0x000001b7u, 0x00050081u, 0x0000000du, 0x000001b9u, 0x000001b3u, 0x000001b8u, 0x00050057u,
0x0000002fu, 0x000001bau, 0x000001b2u, 0x000001b9u, 0x0008004fu, 0x00000007u, 0x000001bcu, 0x000001bau,
0x000001bau, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x000001bbu, 0x000001bcu, 0x00050039u,
0x00000006u, 0x000001bdu, 0x0000000bu, 0x000001bbu, 0x0003003eu, 0x000001b1u, 0x000001bdu, 0x0004003du,
0x00000006u, 0x000001bfu, 0x0000011du, 0x0004003du, 0x00000006u, 0x000001c0u, 0x0000011eu, 0x00050083u,
0x00000006u, 0x000001c1u, 0x000001bfu, 0x000001c0u, 0x0006000cu, 0x00000006u, 0x000001c2u, 0x00000001u,
0x00000004u, 0x000001c1u, 0x0004003du, 0x00000006u, 0x000001c3u, 0x0000017bu, 0x0007000cu, 0x00000006u,
0x000001c4u, 0x00000001u, 0x00000028u, 0x000001c3u, 0x00000063u, 0x00050088u, 0x00000006u, 0x000001c5u,
0x000001c2u, 0x000001c4u, 0x0008000cu, 0x00000006u, 0x000001c6u, 0x00000001u, 0x0000002bu, 0x000001c5u,
0x0000002cu, 0x00000063u, 0x0003003eu, 0x000001beu, 0x000001c6u, 0x0004003du, 0x00000006u, 0x000001c8u,
0x000001beu, 0x0004003du, 0x00000006u, 0x000001c9u, 0x0000017bu, 0x00050085u, 0x00000006u, 0x000001cbu,
0x000001c9u, 0x000001cau, 0x00050081u, 0x00000006u, 0x000001ccu, 0x00000063u, 0x000001cbu, 0x00050088u,
0x00000006u, 0x000001cdu, 0x000001c8u, 0x000001ccu, 0x0003003eu, 0x000001c7u, 0x000001cdu, 0x0004003du,
0x000000f1u, 0x000001cfu, 0x000000fau, 0x000300f7u, 0x000001d2u, 0x00000000u, 0x000400fau, 0x000001cfu,
0x000001d1u, 0x000001d7u, 0x000200f8u, 0x000001d1u, 0x0004003du, 0x00000006u, 0x000001d3u, 0x00000186u,
0x0004003du, 0x00000006u, 0x000001d4u, 0x00000195u, 0x00050083u, 0x00000006u, 0x000001d5u, 0x000001d3u,
0x000001d4u, 0x0006000cu, 0x00000006u, 0x000001d6u, 0x00000001u, 0x00000004u, 0x000001d5u, 0x0003003eu,
0x000001d0u, 0x000001d6u, 0x000200f9u, 0x000001d2u, 0x000200f8u, 0x000001d7u, 0x0004003du, 0x00000006u,
0x000001d8u, 0x00000186u, 0x0004003du, 0x00000006u, 0x000001d9u, 0x000001a3u, 0x00050083u, 0x00000006u,
0x000001dau, 0x000001d8u, 0x000001d9u, 0x0006000cu, 0x00000006u, 0x000001dbu, 0x00000001u, 0x00000004u,
0x000001dau, 0x0003003eu, 0x000001d0u, 0x000001dbu, 0x000200f9u, 0x000001d2u, 0x000200f8u, 0x000001d2u,
0x0004003du, 0x00000006u, 0x000001dcu, 0x000001d0u, 0x0003003eu, 0x000001ceu, 0x000001dcu, 0x0004003du,
0x000000f1u, 0x000001deu, 0x000000fau, 0x000300f7u, 0x000001e1u, 0x00000000u, 0x000400fau, 0x000001deu,
0x000001e0u, 0x000001e6u, 0x000200f8u, 0x000001e0u, 0x0004003du, 0x00000006u, 0x000001e2u, 0x000001a3u,
0x0004003du, 0x00000006u, 0x000001e3u, 0x000001b1u, 0x00050083u, 0x00000006u, 0x000001e4u, 0x000001e2u,
0x000001e3u, 0x0006000cu, 0x00000006u, 0x000001e5u, 0x00000001u, 0x00000004u, 0x000001e4u, 0x0003003eu,
0x000001dfu, 0x000001e5u, 0x000200f9u, 0x000001e1u, 0x000200f8u, 0x000001e6u, 0x0004003du, 0x00000006u,
0x000001e7u, 0x00000195u, 0x0004003du, 0x00000006u, 0x000001e8u, 0x000001b1u, 0x00050083u, 0x00000006u,
0x000001e9u, 0x000001e7u, 0x000001e8u, 0x0006000cu, 0x00000006u, 0x000001eau, 0x00000001u, 0x00000004u,
0x000001e9u, 0x0003003eu, 0x000001dfu, 0x000001eau, 0x000200f9u, 0x000001e1u, 0x000200f8u, 0x000001e1u,
0x0004003du, 0x00000006u, 0x000001ebu, 0x000001dfu, 0x0003003eu, 0x000001ddu, 0x000001ebu, 0x0004003du,
0x00000006u, 0x000001edu, 0x000001ceu, 0x0004003du, 0x00000006u, 0x000001eeu, 0x000001ddu, 0x00050083u,
0x00000006u, 0x000001efu, 0x000001edu, 0x000001eeu, 0x0006000cu, 0x00000006u, 0x000001f0u, 0x00000001u,
0x00000004u, 0x000001efu, 0x0003003eu, 0x000001ecu, 0x000001f0u, 0x0004003du, 0x00000006u, 0x000001f2u,
0x000000ddu, 0x0004003du, 0x00000006u, 0x000001f3u, 0x000000ddu, 0x00050085u, 0x00000006u, 0x000001f4u,
0x000001f3u, 0x00000182u, 0x0004003du, 0x00000006u, 0x000001f5u, 0x000001ecu, 0x0008000cu, 0x00000006u,
0x000001f6u, 0x00000001u, 0x00000031u, 0x000001f2u, 0x000001f4u, 0x000001f5u, 0x0003003eu, 0x000001f1u,
0x000001f6u, 0x0004003du, 0x00000006u, 0x000001f9u, 0x000001f1u, 0x00050085u, 0x00000006u, 0x000001fau,
0x000001f8u, 0x000001f9u, 0x0004003du, 0x00000006u, 0x000001fbu, 0x0000017bu, 0x00050088u, 0x00000006u,
0x000001fdu, 0x000001fbu, 0x000001fcu, 0x0008000cu, 0x00000006u, 0x000001feu, 0x00000001u, 0x0000002bu,
0x000001fdu, 0x0000002cu, 0x00000063u, 0x00050085u, 0x00000006u, 0x000001ffu, 0x000001fau, 0x000001feu,
0x0003003eu, 0x000001f7u, 0x000001ffu, 0x0004003du, 0x00000006u, 0x00000201u, 0x00000186u, 0x0004003du,
0x00000006u, 0x00000202u, 0x000001b1u, 0x00050083u, 0x00000006u, 0x00000203u, 0x00000201u, 0x00000202u,
0x0006000cu, 0x00000006u, 0x00000204u, 0x00000001u, 0x00000004u, 0x00000203u, 0x0004003du, 0x00000006u,
0x00000205u, 0x00000195u, 0x0004003du, 0x00000006u, 0x00000206u, 0x000001a3u, 0x00050083u, 0x00000006u,
0x00000207u, 0x00000205u, 0x00000206u, 0x0006000cu, 0x00000006u, 0x00000208u, 0x00000001u, 0x00000004u,
0x00000207u, 0x0007000cu, 0x00000006u, 0x00000209u, 0x00000001u, 0x00000028u, 0x00000204u, 0x00000208u,
0x0003003eu, 0x00000200u, 0x00000209u, 0x0004003du, 0x00000006u, 0x0000020cu, 0x000000ddu, 0x0004003du,
0x00000006u, 0x0000020du, 0x000000ddu, 0x00050085u, 0x00000006u, 0x0000020fu, 0x0000020du, 0x0000020eu,
0x0004003du, 0x00000006u, 0x00000210u, 0x00000200u, 0x0008000cu, 0x00000006u, 0x00000211u, 0x00000001u,
0x00000031u, 0x0000020cu, 0x0000020fu, 0x00000210u, 0x00050085u, 0x00000006u, 0x00000212u, 0x0000020bu,
0x00000211u, 0x00050083u, 0x00000006u, 0x00000213u, 0x00000063u, 0x00000212u, 0x0003003eu, 0x0000020au,
0x00000213u, 0x0004003du, 0x00000006u, 0x00000215u, 0x000001f7u, 0x0004003du, 0x00000006u, 0x00000216u,
0x000001c7u, 0x00050085u, 0x00000006u, 0x00000217u, 0x00000215u, 0x00000216u, 0x0004003du, 0x00000006u,
0x00000218u, 0x0000017fu, 0x00050085u, 0x00000006u, 0x00000219u, 0x00000217u, 0x00000218u, 0x0004003du,
0x00000006u, 0x0000021au, 0x0000020au, 0x00050085u, 0x00000006u, 0x0000021bu, 0x00000219u, 0x0000021au,
0x0003003eu, 0x00000214u, 0x0000021bu, 0x0004003du, 0x00000006u, 0x0000021du, 0x000000e3u, 0x0004003du,
0x00000006u, 0x0000021eu, 0x000000e7u, 0x0007000cu, 0x00000006u, 0x0000021fu, 0x00000001u, 0x00000025u,
0x0000021du, 0x0000021eu, 0x0003003eu, 0x0000021cu, 0x0000021fu, 0x0004003du, 0x00000006u, 0x00000221u,
0x000000ddu, 0x0004003du, 0x00000006u, 0x00000222u, 0x000000ddu, 0x00050085u, 0x00000006u, 0x00000223u,
0x00000222u, 0x00000182u, 0x0004003du, 0x00000006u, 0x00000224u, 0x0000021cu, 0x0008000cu, 0x00000006u,
0x00000225u, 0x00000001u, 0x00000031u, 0x00000221u, 0x00000223u, 0x00000224u, 0x0003003eu, 0x00000220u,
0x00000225u, 0x0004003du, 0x00000006u, 0x00000227u, 0x0000017bu, 0x0008000cu, 0x00000006u, 0x00000228u,
0x00000001u, 0x00000031u, 0x00000063u, 0x0000020eu, 0x00000227u, 0x0003003eu, 0x00000226u, 0x00000228u,
0x0004003du, 0x00000006u, 0x0000022bu, 0x00000220u, 0x00050085u, 0x00000006u, 0x0000022cu, 0x0000022au,
0x0000022bu, 0x0004003du, 0x00000006u, 0x0000022du, 0x0000017fu, 0x00050085u, 0x00000006u, 0x0000022eu,
0x0000022cu, 0x0000022du, 0x0004003du, 0x00000006u, 0x0000022fu, 0x0000020au, 0x00050085u, 0x00000006u,
0x00000230u, 0x0000022eu, 0x0000022fu, 0x0004003du, 0x00000006u, 0x00000231u, 0x00000226u, 0x00050085u,
0x00000006u, 0x00000232u, 0x00000230u, 0x00000231u, 0x0004003du, 0x00000006u, 0x00000233u, 0x000001f1u,
0x00050085u, 0x00000006u, 0x00000234u, 0x00000232u, 0x00000233u, 0x0003003eu, 0x00000229u, 0x00000234u,
0x0004003du, 0x00000006u, 0x00000236u, 0x00000214u, 0x0004003du, 0x00000006u, 0x00000237u, 0x00000229u,
0x0007000cu, 0x00000006u, 0x00000238u, 0x00000001u, 0x00000028u, 0x00000236u, 0x00000237u, 0x0008000cu,
0x00000006u, 0x0000023au, 0x00000001u, 0x0000002bu, 0x00000238u, 0x0000002cu, 0x00000239u, 0x0003003eu,
0x00000235u, 0x0000023au, 0x0004003du, 0x00000023u, 0x0000023cu, 0x00000025u, 0x0004003du, 0x0000000du,
0x0000023du, 0x00000070u, 0x0004003du, 0x0000000du, 0x0000023eu, 0x0000010bu, 0x0004003du, 0x0000000du,
0x0000023fu, 0x00000062u, 0x00050085u, 0x0000000du, 0x00000240u, 0x0000023eu, 0x0000023fu, 0x00050081u,
0x0000000du, 0x00000241u, 0x0000023du, 0x00000240u, 0x00050057u, 0x0000002fu, 0x00000242u, 0x0000023cu,
0x00000241u, 0x0008004fu, 0x00000007u, 0x00000243u, 0x00000242u, 0x00000242u, 0x00000000u, 0x00000001u,
0x00000002u, 0x0003003eu, 0x0000023bu, 0x00000243u, 0x0004003du, 0x0000002fu, 0x00000244u, 0x0000007cu,
0x0008004fu, 0x00000007u, 0x00000245u, 0x00000244u, 0x00000244u, 0x00000000u, 0x00000001u, 0x00000002u,
0x0004003du, 0x00000007u, 0x00000246u, 0x0000023bu, 0x0004003du, 0x00000006u, 0x00000247u, 0x00000235u,
0x00060050u, 0x00000007u, 0x00000248u, 0x00000247u, 0x00000247u, 0x00000247u, 0x0008000cu, 0x00000007u,
0x00000249u, 0x00000001u, 0x0000002eu, 0x00000245u, 0x00000246u, 0x00000248u, 0x00050041u, 0x00000020u,
0x0000024bu, 0x0000007cu, 0x0000024au, 0x0004003du, 0x00000006u, 0x0000024cu, 0x0000024bu, 0x00050051u,
0x00000006u, 0x0000024du, 0x00000249u, 0x00000000u, 0x00050051u, 0x00000006u, 0x0000024eu, 0x00000249u,
0x00000001u, 0x00050051u, 0x00000006u, 0x0000024fu, 0x00000249u, 0x00000002u, 0x00070050u, 0x0000002fu,
0x00000250u, 0x0000024du, 0x0000024eu, 0x0000024fu, 0x0000024cu, 0x0003003eu, 0x000000f6u, 0x00000250u,
0x000100fdu, 0x00010038u, 0x00050036u, 0x00000006u, 0x0000000bu, 0x00000000u, 0x00000009u, 0x00030037u,
0x00000008u, 0x0000000au, 0x000200f8u, 0x0000000cu, 0x0004003du, 0x00000007u, 0x00000018u, 0x0000000au,
0x00050094u, 0x00000006u, 0x0000001du, 0x00000018u, 0x0000001cu, 0x000200feu, 0x0000001du, 0x00010038u,
0x00050036u, 0x00000006u, 0x00000012u, 0x00000000u, 0x0000000fu, 0x00030037u, 0x0000000eu, 0x00000010u,
0x00030037u, 0x0000000eu, 0x00000011u, 0x000200f8u, 0x00000013u, 0x0004003bu, 0x00000020u, 0x00000021u,
0x00000007u, 0x0004003bu, 0x00000008u, 0x00000031u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000034u,
0x00000007u, 0x0004003bu, 0x00000008u, 0x0000003cu, 0x00000007u, 0x0004003du, 0x00000023u, 0x00000026u,
0x00000025u, 0x0004003du, 0x0000000du, 0x00000027u, 0x00000010u, 0x00050041u, 0x00000020u, 0x0000002au,
0x00000011u, 0x00000029u, 0x0004003du, 0x00000006u, 0x0000002bu, 0x0000002au, 0x00050050u, 0x0000000du,
0x0000002du, 0x0000002bu, 0x0000002cu, 0x00050083u, 0x0000000du, 0x0000002eu, 0x00000027u, 0x0000002du,
0x00050057u, 0x0000002fu, 0x00000030u, 0x00000026u, 0x0000002eu, 0x0008004fu, 0x00000007u, 0x00000032u,
0x00000030u, 0x00000030u, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x00000031u, 0x00000032u,
0x00050039u, 0x00000006u, 0x00000033u, 0x0000000bu, 0x00000031u, 0x0003003eu, 0x00000021u, 0x00000033u,
0x0004003du, 0x00000023u, 0x00000035u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000036u, 0x00000010u,
0x00050041u, 0x00000020u, 0x00000037u, 0x00000011u, 0x00000029u, 0x0004003du, 0x00000006u, 0x00000038u,
0x00000037u, 0x00050050u, 0x0000000du, 0x00000039u, 0x00000038u, 0x0000002cu, 0x00050081u, 0x0000000du,
0x0000003au, 0x00000036u, 0x00000039u, 0x00050057u, 0x0000002fu, 0x0000003bu, 0x00000035u, 0x0000003au,
0x0008004fu, 0x00000007u, 0x0000003du, 0x0000003bu, 0x0000003bu, 0x00000000u, 0x00000001u, 0x00000002u,
0x0003003eu, 0x0000003cu, 0x0000003du, 0x00050039u, 0x00000006u, 0x0000003eu, 0x0000000bu, 0x0000003cu,
0x0003003eu, 0x00000034u, 0x0000003eu, 0x0004003du, 0x00000006u, 0x0000003fu, 0x00000021u, 0x0004003du,
0x00000006u, 0x00000040u, 0x00000034u, 0x00050083u, 0x00000006u, 0x00000041u, 0x0000003fu, 0x00000040u,
0x0006000cu, 0x00000006u, 0x00000042u, 0x00000001u, 0x00000004u, 0x00000041u, 0x000200feu, 0x00000042u,
0x00010038u, 0x00050036u, 0x00000006u, 0x00000016u, 0x00000000u, 0x0000000fu, 0x00030037u, 0x0000000eu,
0x00000014u, 0x00030037u, 0x0000000eu, 0x00000015u, 0x000200f8u, 0x00000017u, 0x0004003bu, 0x00000020u,
0x00000045u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x0000004eu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x00000051u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x00000059u, 0x00000007u, 0x0004003du, 0x00000023u,
0x00000046u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000047u, 0x00000014u, 0x00050041u, 0x00000020u,
0x00000049u, 0x00000015u, 0x00000048u, 0x0004003du, 0x00000006u, 0x0000004au, 0x00000049u, 0x00050050u,
0x0000000du, 0x0000004bu, 0x0000002cu, 0x0000004au, 0x00050083u, 0x0000000du, 0x0000004cu, 0x00000047u,
0x0000004bu, 0x00050057u, 0x0000002fu, 0x0000004du, 0x00000046u, 0x0000004cu, 0x0008004fu, 0x00000007u,
0x0000004fu, 0x0000004du, 0x0000004du, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x0000004eu,
0x0000004fu, 0x00050039u, 0x00000006u, 0x00000050u, 0x0000000bu, 0x0000004eu, 0x0003003eu, 0x00000045u,
0x00000050u, 0x0004003du, 0x00000023u, 0x00000052u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000053u,
0x00000014u, 0x00050041u, 0x00000020u, 0x00000054u, 0x00000015u, 0x00000048u, 0x0004003du, 0x00000006u,
0x00000055u, 0x00000054u, 0x00050050u, 0x0000000du, 0x00000056u, 0x0000002cu, 0x00000055u, 0x00050081u,
0x0000000du, 0x00000057u, 0x00000053u, 0x00000056u, 0x00050057u, 0x0000002fu, 0x00000058u, 0x00000052u,
0x00000057u, 0x0008004fu, 0x00000007u, 0x0000005au, 0x00000058u, 0x00000058u, 0x00000000u, 0x00000001u,
0x00000002u, 0x0003003eu, 0x00000059u, 0x0000005au, 0x00050039u, 0x00000006u, 0x0000005bu, 0x0000000bu,
0x00000059u, 0x0003003eu, 0x00000051u, 0x0000005bu, 0x0004003du, 0x00000006u, 0x0000005cu, 0x00000045u,
0x0004003du, 0x00000006u, 0x0000005du, 0x00000051u, 0x00050083u, 0x00000006u, 0x0000005eu, 0x0000005cu,
0x0000005du, 0x0006000cu, 0x00000006u, 0x0000005fu, 0x00000001u, 0x00000004u, 0x0000005eu, 0x000200feu,
0x0000005fu, 0x00010038u,
};
+82 -18
View File
@@ -256,6 +256,7 @@ struct surface {
struct wl_list child_link;
int sub_x, sub_y, sub_pending_x, sub_pending_y, sub_pending;
int below_parent;
int sub_desync;
int fullscreen;
int toplevel_committed;
@@ -332,6 +333,7 @@ struct pending_release {
struct wl_resource *buffer;
struct wl_listener destroy;
struct surface *surface;
struct surface *held_by;
int64_t at_ns;
int64_t since_ns;
struct wl_list link;
@@ -434,10 +436,54 @@ static void pending_release_free(struct pending_release *pr) {
free(pr);
}
static void release_due_buffers(void);
static void arm_release_timer(void);
static void pending_releases_forget_surface(struct surface *s) {
struct pending_release *pr;
wl_list_for_each(pr, &g_pending_releases, link)
int unheld = 0;
wl_list_for_each(pr, &g_pending_releases, link) {
if (pr->surface == s) pr->surface = NULL;
if (pr->held_by == s) { pr->held_by = NULL; unheld = 1; }
}
if (unheld) { release_due_buffers(); arm_release_timer(); }
}
static void pending_releases_cancel(struct wl_resource *buffer) {
struct pending_release *pr, *tmp;
wl_list_for_each_safe(pr, tmp, &g_pending_releases, link)
if (pr->buffer == buffer) pending_release_free(pr);
}
static void pending_releases_apply(struct surface *holder) {
struct pending_release *pr;
int unheld = 0;
wl_list_for_each(pr, &g_pending_releases, link)
if (pr->held_by == holder) { pr->held_by = NULL; unheld = 1; }
if (unheld) { release_due_buffers(); arm_release_timer(); }
}
static struct surface *sync_holder(struct surface *s) {
struct surface *holder = NULL;
for (int depth = 0; s && s->role == ROLE_SUBSURFACE && s->parent && depth < 8; depth++) {
if (!s->sub_desync) holder = s->parent;
s = s->parent;
}
return holder;
}
static void pending_releases_rehold(struct surface *changed) {
struct pending_release *pr;
int unheld = 0;
wl_list_for_each(pr, &g_pending_releases, link) {
if (!pr->held_by || !pr->surface) continue;
struct surface *s = pr->surface;
for (int depth = 0; s && s != changed && depth < 8; depth++) s = s->parent;
if (s != changed) continue;
pr->held_by = sync_holder(pr->surface);
if (!pr->held_by) unheld = 1;
}
if (unheld) { release_due_buffers(); arm_release_timer(); }
}
static void on_pending_release_buffer_destroyed(struct wl_listener *l, void *data) {
@@ -450,20 +496,18 @@ static void arm_release_timer(void) {
int64_t earliest = 0;
if (g_release_timer_fd < 0) return;
wl_list_for_each(pr, &g_pending_releases, link)
if (!buffer_release_blocked(pr->buffer) && (!earliest || pr->at_ns < earliest))
if (!pr->held_by && !buffer_release_blocked(pr->buffer) && (!earliest || pr->at_ns < earliest))
earliest = pr->at_ns;
struct itimerspec its = {0};
if (earliest) { its.it_value.tv_sec = earliest / 1000000000LL; its.it_value.tv_nsec = earliest % 1000000000LL; }
timerfd_settime(g_release_timer_fd, TFD_TIMER_ABSTIME, &its, NULL);
}
static int on_release_timer(int fd, uint32_t mask, void *data) {
static void release_due_buffers(void) {
struct pending_release *pr, *tmp;
uint64_t expirations;
int64_t now = now_ns() + 300000;
if (read(fd, &expirations, sizeof(expirations)) < 0 && errno != EAGAIN) return 0;
wl_list_for_each_safe(pr, tmp, &g_pending_releases, link) {
if (pr->at_ns <= now && !buffer_release_blocked(pr->buffer)) {
if (!pr->held_by && pr->at_ns <= now && !buffer_release_blocked(pr->buffer)) {
/* Attached again since (to its surface or another): that surface releases it later. */
if (buffer_shown_elsewhere(pr->buffer, NULL)) {
pending_release_free(pr);
@@ -474,28 +518,39 @@ static int on_release_timer(int fd, uint32_t mask, void *data) {
pending_release_free(pr);
}
}
}
static int on_release_timer(int fd, uint32_t mask, void *data) {
uint64_t expirations;
if (read(fd, &expirations, sizeof(expirations)) < 0 && errno != EAGAIN) return 0;
release_due_buffers();
wl_display_flush_clients(g_display);
arm_release_timer();
return 0;
}
static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_t since_ns) {
static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_t since_ns, struct surface *holder) {
/* No allocation or immediate-release fallback is allowed for a quarantined
* DMA-BUF. Existing queued releases stay held; their timer is disarmed. */
if (buffer_release_blocked(buffer)) return;
const int limit = g_fps_limit;
const int64_t interval = limit > 0 ? 1000000000LL / limit : g_refresh_ns;
if (g_release_unpaced || interval <= 0 || g_release_timer_fd < 0) { send_buffer_release(buffer); perf_note_release(since_ns); return; }
const int paced = !g_release_unpaced && interval > 0 && g_release_timer_fd >= 0;
if (!paced && !holder) { send_buffer_release(buffer); perf_note_release(since_ns); return; }
int64_t now = now_ns();
int64_t at = s->next_release_ns + interval;
int64_t latest = now + interval * (int64_t)(s->releases_pending + 1);
if (at < now) at = now;
if (at > latest) at = latest;
s->next_release_ns = at;
int64_t at = now;
if (paced) {
int64_t latest = now + interval * (int64_t)(s->releases_pending + 1);
at = s->next_release_ns + interval;
if (at < now) at = now;
if (at > latest) at = latest;
s->next_release_ns = at;
}
struct pending_release *pr = calloc(1, sizeof(*pr));
if (!pr) { send_buffer_release(buffer); perf_note_release(since_ns); return; }
pr->buffer = buffer;
pr->surface = s;
pr->held_by = holder;
pr->at_ns = at;
pr->since_ns = since_ns;
pr->destroy.notify = on_pending_release_buffer_destroyed;
@@ -721,7 +776,7 @@ static void drop_dmabuf(struct surface *s, int paced) {
wl_list_remove(&s->dmabuf_destroy.link);
if (buffer_shown_elsewhere(s->dmabuf, s)) {
} else if (!ahb_swapchain_defer_release(s->dmabuf_buf, s->dmabuf, s, paced)) {
if (paced) release_buffer(s, s->dmabuf, now_ns());
if (paced) release_buffer(s, s->dmabuf, now_ns(), sync_holder(s));
else send_buffer_release(s->dmabuf);
}
s->dmabuf = NULL;
@@ -887,6 +942,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
s->last_dmabuf = buffer;
pace_note_buffer(buffer);
drop_dmabuf(s, 1);
pending_releases_cancel(buffer);
s->dmabuf = buffer;
s->dmabuf_buf = b;
b->refs++;
@@ -977,7 +1033,7 @@ void droiddeck_dmabuf_ref(struct dmabuf_buffer *b) { b->refs++; }
void droiddeck_dmabuf_unref(struct dmabuf_buffer *b) { dmabuf_buffer_unref(b); }
void droiddeck_release_buffer(struct surface *s, struct wl_resource *buffer, int paced, int64_t since_ns) {
if (buffer_release_blocked(buffer)) return;
if (paced && s) release_buffer(s, buffer, since_ns);
if (paced && s) release_buffer(s, buffer, since_ns, NULL);
else { send_buffer_release(buffer); perf_note_release(since_ns); }
}
void droiddeck_surface_describe(const struct surface *s, char *out, size_t size) { describe(s, out, size); }
@@ -1265,6 +1321,7 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
s->pending_attach = 0;
surface_drop_idle(s);
buf_trace_attach(buffer);
if (s->role == ROLE_CURSOR) {
if (!buffer) {
cursor_publish_hidden();
@@ -1275,7 +1332,6 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
} else if (s->role == ROLE_NONE) {
if (buffer) surface_hold_idle(s, buffer);
} else if (db) {
buf_trace_attach(buffer);
take_dmabuf(s, db, buffer);
} else if (shm) {
drop_dmabuf(s, 1);
@@ -1289,6 +1345,7 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
if (buffer) send_buffer_release(buffer);
}
}
pending_releases_apply(s);
wl_list_for_each(child, &s->children, child_link) {
if (child->sub_pending) {
@@ -1486,8 +1543,14 @@ static void subsurface_place_below(struct wl_client *c, struct wl_resource *r,
struct wl_resource *sibling) {
restack_child(wl_resource_get_user_data(r), wl_resource_get_user_data(sibling), 0);
}
static void subsurface_set_sync(struct wl_client *c, struct wl_resource *r) {}
static void subsurface_set_desync(struct wl_client *c, struct wl_resource *r) {}
static void subsurface_set_sync(struct wl_client *c, struct wl_resource *r) {
struct surface *s = wl_resource_get_user_data(r);
if (s) s->sub_desync = 0;
}
static void subsurface_set_desync(struct wl_client *c, struct wl_resource *r) {
struct surface *s = wl_resource_get_user_data(r);
if (s) { s->sub_desync = 1; pending_releases_rehold(s); }
}
static const struct wl_subsurface_interface subsurface_impl = {
.destroy = subsurface_destroy,
.set_position = subsurface_set_position,
@@ -1521,6 +1584,7 @@ static void subcompositor_get_subsurface(struct wl_client *c, struct wl_resource
s->subsurface = sub;
s->parent = p;
s->below_parent = 0;
s->sub_desync = 0;
s->sub_x = s->sub_y = 0;
wl_list_insert(p->children.prev, &s->child_link);
}
@@ -155,6 +155,10 @@ int vkp_effects_upscaling(void) {
return spatial_mode(g_cur.scaling) && g_cur.scaling != 6;
}
int vkp_effects_sharpening(void) {
return vkp_effects_upscaling() || cas_active(&g_cur);
}
int vkp_effects_postprocessing(void) {
vkp_effects_sync();
return effect_count(&g_cur) > 0;
@@ -11,6 +11,7 @@ int vkp_effects_sync(void);
int vkp_effects_active(void);
int vkp_effects_upscaling(void);
int vkp_effects_sharpening(void);
int vkp_effects_postprocessing(void);
VkFilter vkp_effects_blit_filter(void);
@@ -2179,7 +2179,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
VkImageLayout result_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
if (fx) {
int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f);
if (fg) { mapped_w = scene_w; mapped_h = scene_h; }
if (fg && !vkp_effects_sharpening()) { mapped_w = scene_w; mapped_h = scene_h; }
vkp_effects_set_formats(scene_fmt, scene_fmt);
result = vkp_effects_run(cmd, scene_img, input_w, input_h, mapped_w, mapped_h, &rw, &rh);
effects_overlay_draws(cmd, result, rw, rh, scene_w, scene_h,
@@ -45,14 +45,15 @@ class App : Application() {
CrashHandler.install(this)
com.droiddeck.launcher.input.ShortcutsRelay.Holder.install(this)
com.droiddeck.launcher.agent.AgentHost.refresh(this)
com.droiddeck.launcher.ui.DeveloperTools.load(this)
com.droiddeck.launcher.ui.NavTabs.load(this)
com.droiddeck.launcher.ui.DeveloperTools.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.session.QuestExperimental.initialize(this)
com.droiddeck.launcher.session.SessionPrefs.applyNtsyncDefault(this)
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
com.droiddeck.launcher.session.SessionPrefs.settleStoresTabOrder(this, com.droiddeck.launcher.stores.Store.entries.map { it.id })
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)
@@ -319,7 +319,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
refreshDrivers()
return
}
if (gpu.family.mali && DriverPairs.recommendedKey(gpu, emptyList()) == null &&
if (gpu.family.mali && !DriverPairs.autoEligible(gpu) &&
com.droiddeck.launcher.gpu.VulkanInfo.cachedOrNull() == null) {
releaseChecking = true
autoStatus = activity.getString(R.string.drivers_checking_latest)
@@ -335,14 +335,14 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
}, "gpu-name").start()
return
}
Log.i(TAG, "auto: ${gpu.name} (${gpu.family}) -> " + (DriverPairs.recommendedKey(gpu, emptyList()) ?: "no pair"))
if (gpu.family.mali && DriverPairs.recommendedKey(gpu, emptyList()) == null) {
Log.i(TAG, "auto: ${gpu.name} (${gpu.family}) eligible=${DriverPairs.autoEligible(gpu)}")
if (gpu.family.mali && !DriverPairs.autoEligible(gpu)) {
// No PanVK build covers this Mali (e.g. the G1 series, arch v14): the phone's own driver.
autoStatus = useMaliFallback(null)
refreshDrivers()
return
}
if (DriverPairs.recommendedKey(gpu, emptyList()) == null) {
if (!DriverPairs.autoEligible(gpu)) {
autoStatus = activity.getString(R.string.drivers_none_to_set, gpu.supportText(activity, com.droiddeck.launcher.core.DeviceSupport.vkBridge(activity)).lowercase())
return
}
@@ -372,7 +372,11 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
}
gpu.family == GpuInfo.Family.POWERVR && (pair == null || !pair.complete) -> {
// RADV is not published right now: the Xclipse falls back to the system route.
SessionPrefs.ensurePowerVrAutoDrivers(activity)
if (gpu.name.contains("Xclipse", ignoreCase = true) && DriverPairs.xclipseNeedsUpstream(gpu.name)) {
if (!SessionState.running) SessionPrefs.ensurePowerVrAutoDrivers(activity, powerVr = true, autoOwnedOnly = true)
} else {
SessionPrefs.ensurePowerVrAutoDrivers(activity)
}
autoStatus = activity.getString(R.string.drivers_powervr_builtin)
refreshDrivers()
}
@@ -99,6 +99,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
this, ui,
idle = { !busy && flood == null && compatLaunch == null && pkgStage == null && components.compBusy == null },
onInstalled = { if (!OfflineMode.enabled(this)) components.checkComponentUpdates(force = false) },
onRemoved = { components.refreshComponents() },
)
private var installed by mutableStateOf<String?>(null)
@@ -180,10 +181,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var fsyncFirst by mutableStateOf(false)
private var gamescopeRealtime by mutableStateOf(false)
private var paceCores by mutableStateOf(true)
private var ramCapMb by mutableStateOf(0)
private var zramClient by mutableStateOf(true)
private var zramIdle by mutableStateOf(true)
private var vramCapMb by mutableStateOf(0)
private var gpuClockPin by mutableStateOf(false)
private var prootNoSeccomp by mutableStateOf(false)
private var prootFastPath by mutableStateOf(true)
@@ -279,6 +276,11 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private val pickAnyDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { drivers.importDriver(it, linux = null) }
}
private val pickExperimentalProton = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { zip ->
protons.installExperimental { progress -> com.droiddeck.launcher.session.ExperimentalProtons.installFromFile(this, zip, progress) }
}
}
private val pickLossless = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) }
}
@@ -963,13 +965,36 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
}
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false, onHandled: () -> Unit = {}): Boolean {
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false, onHandled: () -> Unit = {}, onSettled: () -> Unit = {}) {
val request = gameLaunchRequest.incrementAndGet()
if (!SessionPrefs.soundtracksIngame(this)) com.droiddeck.launcher.playback.SoundtrackController.pause(this)
if (pkgStage != null) {
onHandled()
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
return false
return
}
val files = game.gameFiles
if (game.source != com.droiddeck.launcher.stores.Store.XBOX.id || files == null) {
if (startGame(game, returnHome, onHandled)) onSettled()
return
}
Thread({
val refused = com.droiddeck.launcher.stores.xbox.XboxManifest.needsAppModel(files)
ui.post {
when {
request != gameLaunchRequest.get() || isFinishing || isDestroyed -> onHandled()
refused -> {
onHandled()
android.widget.Toast.makeText(this, getString(R.string.game_needs_app_model, game.name), android.widget.Toast.LENGTH_LONG).show()
onSettled()
}
startGame(game, returnHome, onHandled) -> onSettled()
}
}
}, "xbox-app-model").start()
}
private fun startGame(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit): Boolean {
if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome, onHandled)
onHandled()
if (SessionState.running) {
@@ -1184,19 +1209,19 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
if (!isDestroyed && lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) syncDualPanel()
}, LINK_PANEL_MS)
val game = games.firstOrNull { it.gameIdString == id }
if (game == null) {
val link = intent
fun consume() {
if (intent !== link || pendingGameLink != id) return
pendingGameLink = null
intent.data = null
intent.action = Intent.ACTION_MAIN
intent.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
link.data = null
link.action = Intent.ACTION_MAIN
link.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
}
if (game == null) {
consume()
syncDualPanel()
android.widget.Toast.makeText(this, R.string.game_link_missing, android.widget.Toast.LENGTH_LONG).show()
} else if (launchGame(game, returnHome = true)) {
pendingGameLink = null
intent.data = null
intent.action = Intent.ACTION_MAIN
intent.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
}
} else launchGame(game, returnHome = true, onSettled = ::consume)
}
private fun chooseGameShortcut(game: Library.SteamGame) {
@@ -1490,7 +1515,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onComponents = { focusContent -> openComponents(focusContent) },
onGameComponents = { game -> openComponents(gameKey = game.profileKey) },
onComponentsTab = { tab -> openComponents(focusContent = true, tab = tab) },
onSaveImport = { sg -> importSaves(sg.name) { GameSaves.game(sg) } },
onSaveImport = { sg -> importSaves(sg.name) { GameSaves.game(this@FrontEndActivity, sg) } },
onAddonImport = { sg, target -> importAddons(sg.name, target) },
onAddonDelete = { target, name ->
saveAction(getString(R.string.main_addons_deleting, name)) {
@@ -1498,7 +1523,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
getString(R.string.main_addons_deleted, name)
}
},
onSaveExport = { sg, layout -> exportSaves(sg.name, layout) { GameSaves.game(sg) } },
onSaveExport = { sg, layout -> exportSaves(sg.name, layout) { GameSaves.game(this@FrontEndActivity, sg) } },
onPerformance = { refreshCores(); showComponents = false; showMapping = false; showPerformance = true },
performancePanel = { PerformanceHost(embedded = true) },
onRoms = { showRoms = true },
@@ -1914,6 +1939,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
gameLaunchRequest.incrementAndGet()
if (intent.action == SteamIntegration.ACTION_SETUP) {
gameLinkReading = false
pendingGameLink = null
@@ -2407,13 +2433,20 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
),
protons = com.droiddeck.launcher.ui.ProtonsState(
rows = protons.protonRows, busyId = protons.protonBusyId, stage = protons.protonStage, percent = protons.protonPercent,
runtimeReady = ready && !busy, sessionRunning = SessionState.running,
runtimeReady = ready && !busy, sessionRunning = SessionState.running, experimental = protons.experimentalDirs,
experimentalReleases = protons.experimentalReleases,
),
protonActions = com.droiddeck.launcher.ui.ProtonsActions(
onInstall = { id -> protons.installProton(id) },
onCancel = { id -> ProtonExtras.tools.firstOrNull { it.id == id }?.let { ProtonExtras.unqueue(this, it) }; protons.refreshProtons() },
onRemove = { id, dir -> protons.removeProton(id, dir) },
onRemoveOlder = { id -> protons.removeProton(id, older = true) },
onExperimentalFile = {
pickExperimentalProton.launch(InAppFilePicker.buildIntent(this, EXPERIMENTAL_PROTON_EXT, getString(R.string.xproton_install_file),
android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).path))
},
onExperimentalRelease = { release -> protons.installExperimentalRelease(release) },
onRemoveExperimental = { dir -> protons.removeExperimental(dir) },
),
protonOptions = {
com.droiddeck.launcher.ui.ProtonOptions(
@@ -2721,10 +2754,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
fsyncFirst = fsyncFirst,
gamescopeRealtime = gamescopeRealtime,
gpuClockPin = gpuClockPin,
ramCapMb = ramCapMb, vramCapMb = vramCapMb, zramClient = zramClient, zramIdle = zramIdle,
deviceRamMb = (android.app.ActivityManager.MemoryInfo()
.also((getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)::getMemoryInfo).totalMem / (1024 * 1024)).toInt(),
ramCapAvailable = com.droiddeck.launcher.core.ZramSupport.supported(),
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, cursorComposite = cursorComposite,
guestHostname = guestHostname, phantomWarning = phantomWarning,
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
@@ -2739,10 +2768,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onFsyncFirst = { on -> SessionPrefs.setFsyncFirst(this, on); fsyncFirst = on },
onGamescopeRealtime = { on -> SessionPrefs.setGamescopeRealtime(this, on); gamescopeRealtime = on },
onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on },
onRamCapMb = { mb -> SessionPrefs.setRamCapMb(this, mb); ramCapMb = mb },
onZramClient = { on -> SessionPrefs.setZramClient(this, on); zramClient = on },
onZramIdle = { on -> SessionPrefs.setZramIdle(this, on); zramIdle = on },
onVramCapMb = { mb -> SessionPrefs.setVramCapMb(this, mb); vramCapMb = mb },
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
onNativeUserland = { on -> SessionPrefs.setNativeUserland(this, on); nativeUserland = on },
@@ -3041,10 +3066,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
fsyncFirst = SessionPrefs.fsyncFirst(this)
gamescopeRealtime = SessionPrefs.gamescopeRealtime(this)
paceCores = SessionPrefs.paceCores(this)
ramCapMb = SessionPrefs.ramCapMb(this)
zramClient = SessionPrefs.zramClient(this)
zramIdle = SessionPrefs.zramIdle(this)
vramCapMb = SessionPrefs.vramCapMb(this)
gpuClockPin = SessionPrefs.gpuClockPin(this)
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
prootFastPath = SessionPrefs.prootFastPath(this)
@@ -3101,6 +3122,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
installed = LinuxRuntimeInstaller.installedVersion(this)
ready = LinuxRuntime.isInstalled(this)
vkBridge = SessionPrefs.vkBridge(this)
venus = SessionPrefs.venus(this)
venusHostVulkan = com.droiddeck.launcher.session.VenusComponent.hostVulkanTooOld(this)
vkBridgeSafe = SessionPrefs.vkBridgeSafe(this)
bridgeProtonDxvk = SessionPrefs.bridgeProtonDxvk(this)
removalPending = LinuxRuntimeInstaller.hasRemovalPending(this)
@@ -3392,6 +3415,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private const val KEY_SWITCH_DEADLINE = "switch_deadline"
private val SESSION_ENDED = setOf(SessionPhase.IDLE, SessionPhase.FAILED)
private val ZIP_EXT = listOf("zip")
private val EXPERIMENTAL_PROTON_EXT = listOf("zip", "7z", "tar", "gz", "xz", "zst", "bz2", "tgz", "txz", "tbz2", "tzst")
private val WCP_EXT = listOf("wcp")
}
}
@@ -7,6 +7,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.session.ExperimentalProtons
import com.droiddeck.launcher.session.ProtonExtras
import com.droiddeck.launcher.ui.ProtonRow
import com.droiddeck.launcher.session.SessionState
@@ -19,6 +20,7 @@ internal class ProtonMenu(
private val activity: android.app.Activity,
private val ui: Handler,
private val onInstalled: () -> Unit = {},
private val onRemoved: () -> Unit = {},
private val idle: () -> Boolean = { true },
) {
private object Operation {
@@ -27,13 +29,23 @@ internal class ProtonMenu(
val stage = mutableStateOf<String?>(null)
val percent = mutableIntStateOf(-1)
val problem = mutableStateOf<String?>(null)
val experimental = mutableStateOf<List<String>>(emptyList())
val experimentalReleases = mutableStateOf<List<ExperimentalProtons.Release>>(emptyList())
var fetchedReleases = emptyList<ExperimentalProtons.Release>()
val checking = java.util.concurrent.atomic.AtomicBoolean(false)
}
var protonRows by Operation.rows
var protonBusyId by Operation.busyId
var protonStage by Operation.stage
var protonPercent by Operation.percent
var protonProblem by Operation.problem
private val checking = java.util.concurrent.atomic.AtomicBoolean(false)
var experimentalDirs by Operation.experimental
var experimentalReleases by Operation.experimentalReleases
companion object {
const val EXPERIMENTAL = "experimental"
}
@VisibleForTesting internal var latestCheck: (Boolean) -> Boolean = { force -> ProtonExtras.checkLatest(activity, force) }
@VisibleForTesting internal var experimentalRefresh: () -> List<ExperimentalProtons.Release>? = { ExperimentalProtons.refresh(activity) }
@VisibleForTesting internal var installer: (ProtonExtras.Tool, (String, Int) -> Unit) -> String? =
{ tool, progress -> ProtonExtras.install(activity, tool, progress) }
@@ -86,7 +98,57 @@ internal class ProtonMenu(
}, "remove-proton-$id").start()
}
fun installExperimental(work: ((String, Int) -> Unit) -> String?) {
if (protonBusyId != null || ProtonExtras.installInProgress || SessionState.running) return
protonBusyId = EXPERIMENTAL
protonProblem = null
protonStage = activity.getString(R.string.store_starting)
protonPercent = -1
Thread({
val problem = runCatching {
work { label, value -> ui.post { protonStage = label; protonPercent = value } }
}.getOrElse { it.message ?: it.javaClass.simpleName }
ui.post {
protonProblem = problem
protonBusyId = null
protonStage = null
protonPercent = -1
refreshProtons()
android.widget.Toast.makeText(activity, problem ?: activity.getString(R.string.xproton_installed), android.widget.Toast.LENGTH_LONG).show()
if (problem == null) onInstalled()
}
}, "install-proton-experimental").start()
}
fun installExperimentalRelease(release: ExperimentalProtons.Release) {
installExperimental { progress -> ExperimentalProtons.installRelease(activity, release, progress) }
}
fun removeExperimental(dir: String) {
if (protonBusyId != null || SessionState.running) return
protonBusyId = EXPERIMENTAL
protonProblem = null
protonStage = activity.getString(R.string.main_removing_named, dir)
protonPercent = -1
Thread({
val removed = runCatching { ExperimentalProtons.remove(activity, dir) }.getOrDefault(false)
ui.post {
protonBusyId = null
protonStage = null
refreshProtons()
if (!removed) android.widget.Toast.makeText(activity, activity.getString(R.string.xproton_remove_failed, dir), android.widget.Toast.LENGTH_LONG).show()
}
}, "remove-proton-experimental").start()
}
private fun refreshExperimental() {
val installed = ExperimentalProtons.installed(activity)
experimentalDirs = installed.map { it.dir }
experimentalReleases = ExperimentalProtons.available(Operation.fetchedReleases, installed)
}
fun refreshProtons() {
refreshExperimental()
protonRows = ProtonExtras.tools.map {
val all = ProtonExtras.installedAll(activity, it)
ProtonRow(it.id, it.name, all.lastOrNull(), ProtonExtras.queued(activity, it), all, ProtonExtras.update(activity, it))
@@ -94,13 +156,22 @@ internal class ProtonMenu(
}
fun checkUpdates(force: Boolean = false) {
if (!checking.compareAndSet(false, true)) return
if (!Operation.checking.compareAndSet(false, true)) return
Thread({
val asked = try { ProtonExtras.checkLatest(activity, force) } catch (_: Throwable) { false } finally { checking.set(false) }
ui.post {
if (asked) refreshProtons()
val asked = runCatching { latestCheck(force) }.getOrDefault(false)
val experimental = runCatching { experimentalRefresh() }.getOrNull()
val published = ui.post {
try {
val before = experimentalDirs
Operation.fetchedReleases = experimental ?: emptyList()
if (asked) refreshProtons() else refreshExperimental()
if (!experimentalDirs.containsAll(before)) onRemoved()
} finally {
Operation.checking.set(false)
}
ensureAutoUpdates()
}
if (!published) Operation.checking.set(false)
}, "proton-updates").start()
}
@@ -115,6 +115,7 @@ import com.droiddeck.launcher.hud.DroidDeckHudHost
import com.droiddeck.launcher.session.PerfMode
import com.droiddeck.launcher.session.SteamRepair
import com.droiddeck.launcher.session.GameEnvironmentStore
import com.droiddeck.launcher.session.GpuClockPin
import com.droiddeck.launcher.session.GameProfileFollowState
import com.droiddeck.launcher.session.GameProfileInventoryCache
import com.droiddeck.launcher.session.GameProfileRefreshState
@@ -488,7 +489,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
drawerLayerOpen = false
drawerPinned = false
if (value) drawerDocked = dockDrawer() && openDockedMenu()
if (value) {
releaseHeldKeys()
drawerDocked = dockDrawer() && openDockedMenu()
}
drawerOpenState = value
if (!value && drawerDocked) closeDockedMenu()
}
@@ -550,6 +554,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var achievementsInFront by mutableStateOf<AchievementsInFront?>(null)
private var achievementsOpen by mutableStateOf(false)
private var hudOn by mutableStateOf(true)
private var gpuClockPin by mutableStateOf(false)
private var hudConfig by mutableStateOf<Map<String, String>>(emptyMap())
private var hudColor by mutableStateOf(SessionPrefs.HUD_COLOR_MINT)
private var hudOpacity by mutableStateOf(SessionPrefs.HUD_OPACITY_DEFAULT)
@@ -825,7 +830,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
pointerCaptureRefused = false
if (usbMouse.active) updatePointerCapture()
} else {
releaseHeldGuestInput()
releaseHeldInputOnCaptureLoss()
uiHandler.postDelayed(::updatePointerCapture, 250)
}
}
@@ -1404,6 +1409,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
androidApps = androidApps,
hudOn = hudOn,
hudConfig = hudConfig,
gpuClockPin = gpuClockPin,
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
effects = effects,
screenEffectsTarget = screenEffectsTarget,
@@ -1461,6 +1467,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
secondScreenDisplays = secondScreenDisplays,
selectedSecondScreenDisplay = selectedSecondScreenDisplay,
onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() },
onGpuClockPin = { on ->
SessionPrefs.setGpuClockPin(this@SessionActivity, on)
gpuClockPin = on
Thread {
synchronized(GpuClockPin) { GpuClockPin.sync(applicationContext)?.let { Log.i(TAG, it) } }
runOnUiThread { gpuClockPin = gpuClockHeld() }
}.start()
},
onHudSetting = { key, value -> hudConfig = DroidDeckHudConfig.set(this@SessionActivity, key, value); hud.applyConfig() },
onHudOrder = { switches, order -> hudConfig = DroidDeckHudConfig.choose(this@SessionActivity, switches, order); hud.applyConfig() },
onHudReset = { hudConfig = DroidDeckHudConfig.reset(this@SessionActivity); hud.applyConfig() },
@@ -2468,6 +2482,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
.show()
}
private fun gpuClockHeld() = SessionPrefs.gpuClockPin(this) && !GpuClockPin.failed
private fun readPrefs() {
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
unfoldedControls = SessionPrefs.unfoldedControls(this)
@@ -2475,6 +2491,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
picturePosition = SessionPrefs.picturePosition(this)
integerScaling = SessionPrefs.integerScaling(this)
hudOn = SessionPrefs.hudEnabled(this)
gpuClockPin = gpuClockHeld()
blackFrameInsertion = SessionPrefs.blackFrameInsertion(this)
hudConfig = DroidDeckHudConfig.load(this)
hudColor = SessionPrefs.hudColor(this)
@@ -3301,8 +3318,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
}
private fun prootFailureHint(): EndHint? {
if (SessionState.failureCode != "PROOT_MISSING") return null
private fun startFailureHint(): EndHint? {
val code = SessionState.failureCode ?: return null
if (code == "GUEST_EXIT") return null
val message = SessionState.failureMessage ?: return null
return EndHint(message)
}
@@ -3312,7 +3330,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun sessionExitHint(status: Int): EndHint? = if (status == 0) presentationFaultHint()
else runtimeDamageHint() ?: sessionEndHint(SessionState.logFile) ?: prootFailureHint()
else runtimeDamageHint() ?: sessionEndHint(SessionState.logFile) ?: startFailureHint()
private fun sessionEndHint(log: File?): EndHint? {
presentationFaultHint()?.let { return it }
@@ -5118,10 +5136,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun relativeMouseAttached(): Boolean = !isInMultiWindowMode && !glassesOutputActive && mouseAttached()
private fun sessionOwnsInput() =
resumed && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !inputSettingsOpen &&
!pipUi && !bottomOutputActive && !touchEditorOpen && !wowChatOnTop
private fun updatePointerCapture() {
if (!::surfaceView.isInitialized) return
val view = window.decorView
val want = (pointerLocked || relativeMouseAttached()) && resumed && hasWindowFocus() && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !inputSettingsOpen && !pipUi && !bottomOutputActive && !touchEditorOpen && !wowChatOnTop && mouseAttached()
val want = (pointerLocked || relativeMouseAttached()) && sessionOwnsInput() && hasWindowFocus() && mouseAttached()
releaseDesktopMouseGrab()
updateUsbMouse(want)
if (want == view.hasPointerCapture()) return
@@ -5444,14 +5466,26 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun keyboardCoversPad() =
SessionState.mode == SessionService.MODE_STEAM && AgentGuest.steamKeyboard
private fun releaseHeldGuestInput() {
private fun releaseHeldInputOnCaptureLoss() {
if (sessionOwnsInput()) releaseHeldPointerInput() else releaseHeldGuestInput()
}
private fun releaseHeldPointerInput() {
mouseBackInput.cancel()
cancelPen(releaseKey = true)
heldButtons.release(1 or 2 or 8 or 16)
}
private fun releaseHeldKeys() {
guestKeysDown.toList().forEach { sendGuestKey(it, false) }
heldKeys.release(8 or 16 or 32)
}
private fun releaseHeldGuestInput() {
releaseHeldPointerInput()
releaseHeldKeys()
}
private fun sendGuestKey(key: Int, down: Boolean, owner: Int = 1) {
if (down && pipUi) return
val code = if (key == KEY_RIGHTCTRL && SessionState.mode == SessionService.MODE_DESKTOP) KEY_LEFTCTRL else key
@@ -76,6 +76,9 @@ class AgentBridgeProvider : ContentProvider() {
"stop" -> stop(context)
"resume" -> resume(context)
"launch" -> launch(context, request)
"library" -> AgentStores.library(context, request)
"xodus" -> AgentStores.xodus(context, request)
"cloud" -> AgentStores.cloud(context, request)
"focus" -> guest(context, JSONObject().put("kind", "focus"), 15_000)
"quit" -> guest(context, JSONObject().put("kind", "quit").put("appId", request.opt("appId"))
.put("timeout", request.optDouble("timeout", 15.0)), timeoutMs(request, 15.0, 30_000))
@@ -0,0 +1,27 @@
package com.droiddeck.launcher.agent
import android.content.Context
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
/** The text typed in the Agent tab and not yet sent, kept across leaving the tab and restarts. */
object AgentDraft {
private const val KEY = "draft"
private var state: MutableState<String>? = null
fun state(context: Context): MutableState<String> = state ?: run {
val prefs = AgentHost.prefs(context.applicationContext)
val backing = mutableStateOf(prefs.getString(KEY, "") ?: "")
object : MutableState<String> {
override var value: String
get() = backing.value
set(text) {
if (text == backing.value) return
backing.value = text
prefs.edit().apply { if (text.isEmpty()) remove(KEY) else putString(KEY, text) }.apply()
}
override fun component1() = value
override fun component2(): (String) -> Unit = { value = it }
}.also { state = it }
}
}
File diff suppressed because it is too large. Load diff
@@ -21,8 +21,8 @@ import java.nio.file.Files
/**
* The launcher's agent: a coding agent CLI ([AgentHarness]) from the Linux userland, run headless
* outside any game or desktop session: one process per turn, or for a CLI that takes its messages over
* stdin one process kept open between turns, so background work can start a turn of its own. Conversations are kept on disk
* outside any game or desktop session as one process that takes its messages over stdin and stays open
* between turns, so background work can start a turn of its own. Conversations are kept on disk
* ([AgentChats]), so a restart (a Lab build, a crash) continues the same one.
*/
object AgentHost {
@@ -56,6 +56,9 @@ object AgentHost {
/** A message typed while the agent was working, sent when the turn ends. */
data class Queued(val text: String, val files: List<String>)
/** A tool call the CLI waits on the user to allow; [payload] is what its protocol needs to answer. */
data class Approval(val id: String, val tool: String, val detail: String, val input: String, val payload: String = "")
enum class State { MISSING, IDLE, WORKING }
private const val TAG = "AgentHost"
@@ -94,6 +97,12 @@ object AgentHost {
private set
var plan by mutableStateOf(false)
private set
/** The chosen [AgentHarness.Permission] of [harness]; asking first until the user picks another. */
var permission by mutableStateOf(AgentHarness.ASK)
private set
/** Tool calls of the running turn that wait for the user, oldest first. */
val approvals = mutableStateListOf<Approval>()
private var approvalNoticed = false
var chat by mutableStateOf<String?>(null)
private set
/** A reply finished since the conversation was last on screen. */
@@ -123,7 +132,9 @@ object AgentHost {
var lab by mutableStateOf<LabProgress?>(null)
private set
private class Turn(val process: Process, val pid: Int, val stdin: java.io.OutputStream? = null) {
private class Turn(val process: Process, val pid: Int, val protocol: AgentProtocol, val stdin: java.io.OutputStream) {
fun write(lines: List<String>) = synchronized(this) { stdin.apply { lines.forEach { write((it + "\n").toByteArray()) }; flush() } }
var writingGeneration: Int? = null
var exitStatus: Int? = null
var costs: AgentCostTracker? = null
@@ -171,6 +182,8 @@ object AgentHost {
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)
permission = prefs(app).getString(permissionKey(harness), null)?.takeIf { id -> harness.permissions.any { it.id == id } }
?: harness.permissions.first().id
limits = decodeLimits(prefs(app).getString(limitsKey(harness), null))
available = LinuxRuntime.hasRootfs(app)
installed = harness.files.all { guestFileExists(app, it) }
@@ -273,6 +286,42 @@ object AgentHost {
prefs(context).edit().putBoolean(PLAN_KEY, on).apply()
}
/** Kept per CLI, for every conversation; the CLI process restarts with it on the next message. */
fun choosePermission(context: Context, id: String) {
if (harness.permissions.none { it.id == id }) return
permission = id
prefs(context).edit().putString(permissionKey(harness), id).apply()
}
/** Lets the CLI run [approval]'s tool call, or tells it the user said no. */
fun answer(context: Context, approval: Approval, allow: Boolean) {
if (!approvals.remove(approval)) return
val running = turn ?: session ?: return
val line = running.protocol.answer(approval, allow)
val app = context.applicationContext
val current = harness
Thread({ runCatching { running.write(listOf(line)) }.onFailure { lost(app, running, current, it) } }, "agent-approval").start()
approvalsChanged(app)
}
/** The approval notice goes once nothing waits on the user any more. */
private fun approvalsChanged(app: Context) {
if (approvals.isNotEmpty() || !approvalNoticed) return
approvalNoticed = false
AgentNotice.clear(app)
}
/**
* A line the CLI waits for could not be written, so it would wait forever: its process ends, which ends
* the turn, and the chat says why. A request that may have reached it is not sent again.
*/
private fun lost(app: Context, from: Turn, current: AgentHarness, error: Throwable) {
Log.w(TAG, "could not write to ${current.name}", error)
main.post { if (turn === from || session === from) record(app, Entry.Notice("Could not write to ${current.name}: ${error.message ?: error.javaClass.simpleName}")) }
AgentProcesses.killTree(from.pid)
from.process.destroy()
}
fun models(context: Context) = harness.models(LinuxRuntime.rootDir(context.applicationContext))
/** Sends [text] now, or after the current turn when the agent is working. */
@@ -303,19 +352,20 @@ object AgentHost {
val current = harness
val prompt = AgentAttachments.prompt(message, attached)
turnPlanned = plan && current.plans
val options = AgentHarness.Options(model, turnPlanned, BRIEF, effort)
val command = current.turn(prompt, conversation, options)
val line = current.input(prompt)
val key = "${current.id}|$id|$model|$turnPlanned|$effort"
val options = AgentHarness.Options(model, turnPlanned, BRIEF, effort, permission, workspace(app))
val key = "${current.id}|$id|$model|$turnPlanned|$effort|$permission"
val resumed = conversation
background = false
approvals.clear()
approvalsChanged(app)
val kept = session
if (kept != null && line != null && sessionKey == key && kept.process.isAlive) {
if (kept != null && sessionKey == key && kept.process.isAlive) {
main.removeCallbacks(reap)
turn = kept
kept.writingGeneration = gen
kept.clearingCosts = prompt == "/clear"
Thread({
val written = runCatching { synchronized(kept) { kept.stdin?.apply { write((line + "\n").toByteArray()); flush() } != null } }.getOrDefault(false)
val written = runCatching { kept.write(kept.protocol.input(prompt, resumed, options, started = false)) }.isSuccess
// The process died between turns: the same message goes to a new one, which resumes the conversation.
main.post {
if (kept.writingGeneration == gen) kept.writingGeneration = null
@@ -323,7 +373,7 @@ object AgentHost {
if (!written) {
dropSession()
turn = null
spawn(app, gen, current, current.turn(prompt, conversation, options), line, key)
spawn(app, gen, current, prompt, resumed, options, key)
} else kept.exitStatus?.let { processExited(app, kept, current, it) }
}
}
@@ -331,12 +381,14 @@ object AgentHost {
return
}
dropSession()
spawn(app, gen, current, command, line, key)
spawn(app, gen, current, prompt, resumed, options, key)
}
private fun spawn(app: Context, gen: Int, current: AgentHarness, command: List<String>, line: String?, key: String) {
val workdir = workspace(app)
var threadConversation = conversation
private fun spawn(app: Context, gen: Int, current: AgentHarness, prompt: String, resumed: String?, options: AgentHarness.Options, key: String) {
val workdir = options.workdir
val command = current.turn(prompt, resumed, options)
val protocol = current.protocol()
var threadConversation = resumed
Thread({
runCatching { current.prepare(LinuxRuntime.rootDir(app)) }
runCatching { AgentSetup.installHelpers(app) }
@@ -349,17 +401,18 @@ object AgentHost {
main.post { if (generation == gen) finish(app, e.message ?: "could not start") }
return@Thread
}
val started = Turn(child, AgentProcesses.pidOf(child), if (line != null) child.outputStream else null).apply {
if (current === ClaudeCode && line != null) costs = AgentCostTracker()
val started = Turn(child, AgentProcesses.pidOf(child), protocol, child.outputStream).apply {
if (current === ClaudeCode) costs = AgentCostTracker()
}
OrphanReaper.keep(started.pid)
main.post {
if (generation == gen && state == State.WORKING && turn == null) {
turn = started
if (line != null) { session = started; sessionKey = key }
session = started
sessionKey = key
} else AgentProcesses.killTree(started.pid)
}
if (line != null) runCatching { child.outputStream.apply { write((line + "\n").toByteArray()); flush() } } else child.outputStream.close()
runCatching { started.write(protocol.input(prompt, resumed, options, started = true)) }.onFailure { lost(app, started, current, it) }
val raw = runCatching {
val log = File(app.filesDir, TURN_LOG).apply { parentFile?.mkdirs() }
log.renameTo(File(app.filesDir, "$TURN_LOG.1"))
@@ -368,7 +421,8 @@ object AgentHost {
runCatching {
child.inputStream.bufferedReader().forEachLine { output ->
runCatching { raw?.apply { write(output); newLine(); flush() } }
val parsed = current.parse(output) ?: return@forEachLine
val parsed = protocol.parse(output) ?: return@forEachLine
if (parsed.reply.isNotEmpty()) runCatching { started.write(parsed.reply) }.onFailure { lost(app, started, current, it) }
parsed.conversation?.let { threadConversation = it }
val done = parsed.entries.any { it is Entry.Finished }
val event = if (!done) parsed else runCatching { current.usage(LinuxRuntime.rootDir(app), threadConversation) }.getOrNull()
@@ -410,7 +464,7 @@ object AgentHost {
if (background && state == State.WORKING) finish(app, event.backgroundError, usage = event.usage?.let { from.costs?.perTurn(it) ?: it })
return
}
val content = event.text != null || event.thinking != null || event.entries.any { it !is Entry.Finished }
val content = event.text != null || event.thinking != null || event.approval != null || event.entries.any { it !is Entry.Finished }
if (content && state == State.IDLE && session === from) {
main.removeCallbacks(reap)
background = true
@@ -428,10 +482,17 @@ object AgentHost {
from.clearingCosts = false
}
val applied = if (finished != null && state == State.WORKING && event.usage != null)
event.copy(usage = from.costs?.perTurn(event.usage) ?: event.usage) else event
event.copy(usage = turnCost(from.costs?.perTurn(event.usage) ?: event.usage)) else event
apply(app, applied)
}
/** A CLI that reports the conversation's whole cost spent what this chat has not recorded yet. */
private fun turnCost(usage: Usage): Usage {
if (!harness.sessionCost) return usage
val recorded = entries.sumOf { (it as? Entry.Finished)?.usage?.costUsd ?: 0.0 }
return usage.copy(costUsd = (usage.costUsd - recorded).coerceAtLeast(0.0))
}
/** Ends the CLI process kept between turns, and with it whatever it still runs in the background. */
private fun dropSession() {
main.removeCallbacks(reap)
@@ -529,6 +590,15 @@ object AgentHost {
}
event.text?.let { live += it }
event.thinking?.let { liveThinking += it }
event.resolved?.let { id ->
approvals.removeAll { it.id == id }
approvalsChanged(app)
}
event.approval?.takeIf { a -> state == State.WORKING && approvals.none { it.id == a.id } }?.let {
approvals += it
approvalNoticed = true
AgentNotice.post(app, AgentNotice.Kind.APPROVAL, listOf(it.tool, it.detail).filter { s -> s.isNotEmpty() }.joinToString(": "))
}
event.context?.let { context = it }
event.window?.let { window = it }
event.limits?.let { reported ->
@@ -549,6 +619,8 @@ object AgentHost {
private fun finish(app: Context, error: String?, stopped: Boolean = false, usage: Usage? = null) {
if (state != State.WORKING) return
turn = null
approvals.clear()
approvalsChanged(app)
val answeredTask = background
background = false
main.removeCallbacks(reap)
@@ -762,6 +834,7 @@ object AgentHost {
private const val LINGER_MS = 20 * 60_000L
private fun modelKey(harness: AgentHarness) = "model_${harness.id}"
private fun permissionKey(harness: AgentHarness) = "permission_${harness.id}"
private fun limitsKey(harness: AgentHarness) = "limits_${harness.id}"
@VisibleForTesting
@@ -16,10 +16,10 @@ internal object AgentNotice {
private const val CHANNEL_ID = "agent_done"
private const val NOTIFICATION_ID = 4108
enum class Kind { DONE, FAILED, QUESTION }
enum class Kind { DONE, FAILED, QUESTION, APPROVAL }
fun post(context: Context, kind: Kind, text: String) {
if (onScreen(context)) return
if (onScreen(context, kind)) 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,
@@ -31,6 +31,7 @@ internal object AgentNotice {
Kind.DONE -> R.string.agent_done
Kind.FAILED -> R.string.agent_done_failed
Kind.QUESTION -> R.string.agent_done_question
Kind.APPROVAL -> R.string.agent_done_approval
})
runCatching {
manager.notify(NOTIFICATION_ID, Notification.Builder(context, CHANNEL_ID)
@@ -49,9 +50,9 @@ internal object AgentNotice {
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
/** The chat in a DroidDeck window in front, or the pet, which shows the reply in its own bubble but has no way to answer an approval. */
private fun onScreen(context: Context, kind: Kind): Boolean {
if (AgentPet.floating && kind != Kind.APPROVAL) return true
val state = ActivityManager.RunningAppProcessInfo().also { ActivityManager.getMyMemoryState(it) }
return AgentPet.agentOnScreen > 0 && state.importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
}
@@ -27,25 +27,52 @@ object AgentSetup {
val detail = mutableStateMapOf<Step, String>()
var runtimeInstalled by mutableStateOf(true)
private set
/** The harness has a key from its [AgentHarness.keyPage] saved; signed in without one means its free models. */
var keySaved by mutableStateOf(false)
/** Ids of the harness's [AgentHarness.providers] with a key saved; signed in without one means its free models. */
var keys by mutableStateOf(emptySet<String>())
private set
/** The provider and custom server picked in the key field, kept while a save is checked. */
var provider by mutableStateOf<String?>(null)
var server by mutableStateOf("")
/** Saves a pasted key for a harness that signs in with one, then checks the sign-in again. */
fun saveKey(context: Context, key: String) = signInLocally(context) { harness, root -> harness.saveKey(root, key) }
fun saveKey(context: Context, provider: AgentHarness.Provider, key: String, endpoint: String? = null) = signInLocally(context) { harness, root ->
harness.saveKey(root, provider, key, endpoint) { url, token -> fetch(context.applicationContext, url, token) }
}
fun removeKey(context: Context, provider: AgentHarness.Provider) = signInLocally(context) { harness, root -> harness.removeKey(root, provider) }
/** A GET from the userland, which reaches the LAN servers the app's own cleartext policy does not. */
private fun fetch(app: Context, url: String, token: String?): String {
// The key goes in on stdin, so it is never in a command line.
val process = AgentHost.guest(app, listOf("curl", "-fsSL", "--max-time", "20", "-H", "@-", url), connectAdb = false).start()
process.outputStream.bufferedWriter().use { if (token != null) it.write("Authorization: Bearer $token\n") }
val output = process.inputStream.bufferedReader().readText()
check(process.waitFor(30, TimeUnit.SECONDS) && process.exitValue() == 0) { output.trim().lines().lastOrNull()?.takeIf { it.isNotEmpty() } ?: "Cannot reach $url" }
return output
}
fun useFree(context: Context) = signInLocally(context) { harness, root -> harness.useFree(root) }
private val signInLock = Any()
private fun signInLocally(context: Context, write: (AgentHarness, File) -> Unit) {
val app = context.applicationContext
val harness = AgentHost.harness
set(Step.SIGN_IN, Status.WORKING)
Thread({
val result = runCatching { write(harness, LinuxRuntime.rootDir(app)) }
// Each write reads the files the one before it left, including across a save's model request.
val result = synchronized(signInLock) { runCatching { write(harness, LinuxRuntime.rootDir(app)) } }
main.post {
status[Step.SIGN_IN] = Status.UNKNOWN
result.exceptionOrNull()?.let { detail[Step.SIGN_IN] = it.message ?: "failed" }
check(app)
// A failure stays on the row with the key field open, since the next check would clear it.
val error = result.exceptionOrNull()
if (error != null) {
status[Step.SIGN_IN] = Status.FAILED
detail[Step.SIGN_IN] = error.message ?: "failed"
} else {
status[Step.SIGN_IN] = Status.UNKNOWN
detail.remove(Step.SIGN_IN)
check(app)
}
}
}, "agent-sign-in").start()
}
@@ -75,7 +102,7 @@ object AgentSetup {
if (!runtimeInstalled) return
AgentHost.refresh(app)
val harness = AgentHost.harness
keySaved = harness.hasKey(LinuxRuntime.rootDir(app))
keys = harness.keys(LinuxRuntime.rootDir(app))
val probes = mutableListOf<Pair<Step, List<String>>>()
for (step in Step.entries) if (status[step] != Status.WORKING) {
when (step) {
@@ -102,10 +129,15 @@ object AgentSetup {
fun runsAsRoot(step: Step) = step == Step.INSTALL
/** 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) = run(context, step, null)
/** Opens the page where a provider's key is made, as the sign-in of a harness that takes pasted keys. */
fun openKeyPage(context: Context, page: String) = run(context, Step.SIGN_IN, listOf("/root/.local/bin/android-open", page))
private fun run(context: Context, step: Step, override: List<String>?) {
val app = context.applicationContext
val harness = AgentHost.harness
val command = when (step) {
val command = override ?: when (step) {
Step.CONNECTION -> return
Step.INSTALL -> {
listOf("sh", "-c", "set -e; export DEBIAN_FRONTEND=noninteractive; " +
@@ -0,0 +1,91 @@
package com.droiddeck.launcher.agent
import android.content.Context
import com.droiddeck.launcher.frontend.LibraryCache
import com.droiddeck.launcher.stores.CloudSaves
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.xbox.Xodus
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.util.concurrent.TimeUnit
import org.json.JSONArray
import org.json.JSONObject
internal object AgentStores {
private const val OUTPUT_CAP = 160 * 1024
fun library(context: Context, request: JSONObject): JSONObject {
val query = request.optString("query").trim()
val source = request.optString("source").trim()
val games = JSONArray()
LibraryCache.load(context)
.filter { (query.isEmpty() || it.name.contains(query, ignoreCase = true)) && (source.isEmpty() || it.source.equals(source, ignoreCase = true)) }
.forEach {
games.put(JSONObject().put("id", it.gameIdString).put("name", it.name).put("source", it.source)
.put("storeId", it.storeId ?: JSONObject.NULL).put("folder", it.gameFiles?.path ?: JSONObject.NULL))
}
return JSONObject().put("ok", true).put("command", "library").put("games", games)
}
fun xodus(context: Context, request: JSONObject): JSONObject {
AgentAccess.requireCommands(context)
val list = request.optJSONArray("args")
val args = if (list == null) emptyList() else List(list.length()) { list.optString(it) }
if (args.isEmpty() || args.any { it.isEmpty() }) throw AgentException("INVALID_REQUEST", "xodus needs its arguments")
val timeoutMs = (request.optDouble("timeout", 120.0) * 1000).toLong().coerceIn(1_000L, 900_000L)
return Xodus.start(context.applicationContext, args).use { child ->
val out = Tail(child.process.inputStream)
val err = Tail(child.process.errorStream)
val finished = child.process.waitFor(timeoutMs, TimeUnit.MILLISECONDS)
if (!finished) child.close()
JSONObject().put("ok", true).put("command", "xodus").put("timedOut", !finished)
.put("exit", if (finished) child.process.exitValue() else JSONObject.NULL)
.put("stdout", out.text()).put("stderr", err.text())
}
}
fun cloud(context: Context, request: JSONObject): JSONObject {
AgentAccess.requireCommands(context)
val store = Store.byId(request.optString("store"))?.takeIf(CloudSaves::supports)
?: throw AgentException("INVALID_REQUEST", "store must be one with cloud saves")
val id = request.optString("id").ifEmpty { throw AgentException("INVALID_REQUEST", "cloud needs a game id") }
val force = request.optBoolean("force")
val result = when (val direction = request.optString("direction")) {
"down" -> CloudSaves.download(context.applicationContext, store, id, force)
"up" -> CloudSaves.upload(context.applicationContext, store, id, force)
else -> throw AgentException("INVALID_REQUEST", "direction '$direction' is not down or up")
}
return JSONObject().put("ok", true).put("command", "cloud").put("result", result.result).put("files", result.files)
.put("bytes", result.bytes).put("reason", result.reason).put("conflicts", result.conflicts).put("detail", result.detail)
}
private class Tail(stream: InputStream) {
private val kept = ByteArrayOutputStream()
private var dropped = false
private val reader = Thread({
val buffer = ByteArray(8192)
stream.use { input ->
while (true) {
val n = runCatching { input.read(buffer) }.getOrDefault(-1)
if (n < 0) break
synchronized(kept) {
kept.write(buffer, 0, n)
if (kept.size() > OUTPUT_CAP * 2) {
val bytes = kept.toByteArray()
kept.reset()
kept.write(bytes, bytes.size - OUTPUT_CAP, OUTPUT_CAP)
dropped = true
}
}
}
}
}, "agent-xodus-output").apply { isDaemon = true; start() }
fun text(): String {
reader.join(2_000)
val bytes = synchronized(kept) { kept.toByteArray() }
val tail = if (bytes.size > OUTPUT_CAP) bytes.copyOfRange(bytes.size - OUTPUT_CAP, bytes.size) else bytes
return (if (dropped || bytes.size > OUTPUT_CAP) "...\n" else "") + String(tail, Charsets.UTF_8)
}
}
}
@@ -16,8 +16,10 @@ import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.IntConsumer;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
public class PulseAudioComponent extends SessionPart {
private static final String TAG = "PulseAudio";
@@ -38,6 +40,7 @@ public class PulseAudioComponent extends SessionPart {
private long generation;
private long launches;
private final IntConsumer terminate;
final ReentrantReadWriteLock commands = new ReentrantReadWriteLock();
HostLifecycle(IntConsumer terminate) {
this.terminate = terminate;
@@ -54,11 +57,27 @@ public class PulseAudioComponent extends SessionPart {
pid = -1;
}
synchronized boolean launch(long expected, IntSupplier launch) {
if (expected != generation) return false;
launches++;
pid = launch.getAsInt();
return true;
boolean launch(long expected, IntSupplier launch) {
commands.writeLock().lock();
try {
synchronized (this) {
if (expected != generation) return false;
launches++;
pid = launch.getAsInt();
return true;
}
} finally {
commands.writeLock().unlock();
}
}
<T> T command(long token, Supplier<T> command) {
commands.readLock().lock();
try {
return live(token) ? command.get() : null;
} finally {
commands.readLock().unlock();
}
}
synchronized boolean current(long expected) {
@@ -218,13 +237,13 @@ public class PulseAudioComponent extends SessionPart {
String loadedAs = null;
for (int attempt = 1; attempt <= 5 && loadedAs == null && host.live(token); attempt++) {
try { Thread.sleep(2000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
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
&& pactlFor(token, "set-default-sink", "DirectAudio") != null) {
if (pactlOk(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)
&& pactlOk(token, "set-default-sink", "DirectAudio")) {
loadedAs = "DirectAudio on attempt " + attempt;
} 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
&& pactlFor(token, "set-default-sink", "AAudioSink") != null) {
} else if (pactlOk(token, "load-module", "module-aaudio-sink", "sink_name=AAudioSink",
"performance_mode=" + (attempt == 1 ? "1" : "0"), "adaptive=1", "volume=1.0", "control_dir=" + deviceControls)
&& pactlOk(token, "set-default-sink", "AAudioSink")) {
loadedAs = "the plain AAudio sink (AAudioSink) on attempt " + attempt;
}
}
@@ -248,14 +267,24 @@ public class PulseAudioComponent extends SessionPart {
}
private String pactlFor(long token, String... args) {
return host.live(token) ? pactl(args) : null;
return host.command(token, () -> pactl(true, args));
}
/** Runs pactl against this daemon; its stdout, or null when it failed or timed out. */
private String pactl(String... args) {
private boolean pactlOk(long token, String... args) {
return host.command(token, () -> pactl(false, args)) != null;
}
private static void reap(java.lang.Process process) throws InterruptedException {
process.destroyForcibly();
process.waitFor(2, TimeUnit.SECONDS);
}
/** Runs pactl against this daemon; its stdout when captured (empty otherwise), or null when it failed or timed out. */
private String pactl(boolean capture, String... args) {
File pactl = new File(workingDir, "pactl");
if (!pactl.isFile() || host.pid <= 1) return null;
java.lang.Process process = null;
File output = null;
try {
File modules = new File(workingDir, "modules/arm64");
ArrayList<String> cmd = new ArrayList<>();
@@ -268,29 +297,33 @@ public class PulseAudioComponent extends SessionPart {
builder.environment().put("HOME", workingDir.getAbsolutePath());
builder.environment().put("TMPDIR", workingDir.getAbsolutePath());
builder.environment().put("PULSE_SERVER", "unix:" + socket().getAbsolutePath());
process = builder.start();
String output;
try (InputStream in = process.getInputStream();
java.io.ByteArrayOutputStream outStream = new java.io.ByteArrayOutputStream()) {
byte[] buf = new byte[4096];
int n;
while ((n = in.read(buf)) != -1) {
outStream.write(buf, 0, n);
}
output = outStream.toString(java.nio.charset.StandardCharsets.UTF_8.name());
if (capture) {
output = File.createTempFile("pactl", ".out", workingDir);
builder.redirectOutput(output);
} else {
builder.redirectOutput(new File("/dev/null"));
}
process = builder.start();
if (!process.waitFor(5, TimeUnit.SECONDS)) {
process.destroyForcibly();
reap(process);
return null;
}
return process.exitValue() == 0 ? output : null;
if (process.exitValue() != 0) return null;
return capture ? new String(Files.readAllBytes(output.toPath()), java.nio.charset.StandardCharsets.UTF_8) : "";
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return null;
} catch (Throwable t) {
return null;
} finally {
if (process != null && process.isAlive()) process.destroyForcibly();
if (process != null && process.isAlive()) {
try {
reap(process);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
if (output != null) output.delete();
}
}
@@ -281,9 +281,6 @@ object DeviceReport {
k("Linux x86 (FEX)", if (com.droiddeck.launcher.runtime.LinuxFex.ready(context)) "ready" else "not set up")
k("gamescope realtime", SessionPrefs.gamescopeRealtime(context))
k("pace cores", SessionPrefs.paceCores(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("VRAM cap", SessionPrefs.vramCapMb(context).let { if (it > 0) "$it MB" else "driver default" })
k("proot without seccomp", SessionPrefs.prootNoSeccomp(context))
k("native userland (no proot)", SessionPrefs.nativeUserland(context))
k("proot fast path", SessionPrefs.prootFastPath(context))
@@ -122,6 +122,12 @@ public final class Downloader {
return null;
}
public static Boolean gone(String url) {
Fetch fetch = fetch(url);
if (fetch.body != null) return Boolean.FALSE;
return fetch.fatal ? Boolean.TRUE : null;
}
public static String downloadDirect(String url) {
LAST_FAILURE.remove();
return fetch(url).body;
@@ -235,6 +235,17 @@ object WirelessAdbFix {
fun hasSavedPairing(context: Context): Boolean = savedConnection(context.applicationContext) != null
fun savedPairingIsLocal(context: Context): Boolean = savedConnection(context.applicationContext)?.host
?.let { host ->
// Unlike isLocalAddress, an address that cannot be matched to this device's own counts as remote.
runCatching {
val address = InetAddress.getByName(host)
address.isLoopbackAddress || NetworkInterface.getNetworkInterfaces().toList().any { network ->
network.inetAddresses.toList().any { it.address.contentEquals(address.address) }
}
}.getOrDefault(false)
} == true
fun clearCachedApps(context: Context) {
shell(context, "am kill-all")
}
@@ -13,6 +13,7 @@ import android.provider.DocumentsContract.Root
import android.provider.DocumentsProvider
import android.webkit.MimeTypeMap
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
@@ -26,11 +27,21 @@ import java.nio.file.attribute.BasicFileAttributes
class AppFilesProvider : DocumentsProvider() {
private lateinit var base: File
private lateinit var baseCanonical: String
private lateinit var privatePaths: List<String>
override fun attachInfo(context: Context, info: ProviderInfo) {
super.attachInfo(context, info)
base = context.dataDir
baseCanonical = base.canonicalPath
// The wireless ADB pairing identity, preferences, store logins and Steam's saved login stay app-only.
privatePaths = listOf(
context.noBackupFilesDir,
File(base, "shared_prefs"),
context.getDatabasePath("x").parentFile!!,
File(context.filesDir, "stores"),
File(SessionPrefs.steamRoot(context, "arm64"), "config"),
File(SessionPrefs.steamRoot(context, "x86_64"), "config"),
).flatMap { listOf(it.absoluteFile.normalize().path, runCatching { it.canonicalPath }.getOrDefault(it.path)) }.distinct()
}
override fun onCreate() = true
@@ -74,6 +85,7 @@ class AppFilesProvider : DocumentsProvider() {
var file = File(parent, name)
var n = 2
while (file.exists()) file = File(parent, "$name (${n++})")
if (isPrivate(file)) throw FileNotFoundException("could not create ${file.path}")
val made = try {
if (mimeType == Document.MIME_TYPE_DIR) file.mkdir() else file.createNewFile()
} catch (e: IOException) {
@@ -85,7 +97,7 @@ class AppFilesProvider : DocumentsProvider() {
override fun deleteDocument(documentId: String) {
val file = fileFor(documentId)
if (file.canonicalPath == baseCanonical) throw FileNotFoundException("the app folder itself is not deleted")
if (file.canonicalPath == baseCanonical || holdsPrivate(file)) throw FileNotFoundException("$documentId holds the app's private files")
try {
deleteTree(file.toPath())
} catch (e: IOException) {
@@ -116,17 +128,19 @@ class AppFilesProvider : DocumentsProvider() {
override fun renameDocument(documentId: String, displayName: String): String {
val file = fileFor(documentId)
if (holdsPrivate(file)) throw FileNotFoundException("$documentId holds the app's private files")
val target = File(file.parentFile, displayName.substringAfterLast('/'))
if (target.exists() || !file.renameTo(target)) throw FileNotFoundException("could not rename $documentId")
if (target.exists() || isPrivate(target) || !file.renameTo(target)) throw FileNotFoundException("could not rename $documentId")
return target.absolutePath
}
override fun moveDocument(sourceDocumentId: String, sourceParentDocumentId: String, targetParentDocumentId: String): String {
val source = fileFor(sourceDocumentId)
if (holdsPrivate(source)) throw FileNotFoundException("$sourceDocumentId holds the app's private files")
val targetParent = fileFor(targetParentDocumentId)
if (!targetParent.isDirectory) throw FileNotFoundException("$targetParentDocumentId is not a folder")
val target = File(targetParent, source.name)
if (target.exists() || !source.renameTo(target)) throw FileNotFoundException("could not move $sourceDocumentId")
if (target.exists() || isPrivate(target) || !source.renameTo(target)) throw FileNotFoundException("could not move $sourceDocumentId")
return target.absolutePath
}
@@ -163,7 +177,19 @@ class AppFilesProvider : DocumentsProvider() {
val abs = f.absoluteFile.normalize().path
if (abs != base.absolutePath && !abs.startsWith(base.absolutePath + "/")) return false
val real = runCatching { f.canonicalPath }.getOrNull() ?: return false
return real == baseCanonical || real.startsWith("$baseCanonical/")
if (real != baseCanonical && !real.startsWith("$baseCanonical/")) return false
return !isPrivate(f)
}
private fun isPrivate(f: File): Boolean {
val real = runCatching { f.canonicalPath }.getOrNull() ?: return true
val paths = listOf(f.absoluteFile.normalize().path, real)
return privatePaths.any { p -> paths.any { it == p || it.startsWith("$p/") } }
}
private fun holdsPrivate(f: File): Boolean {
val paths = listOfNotNull(f.absoluteFile.normalize().path, runCatching { f.canonicalPath }.getOrNull())
return privatePaths.any { p -> paths.any { p.startsWith("$it/") } }
}
private fun addRow(result: MatrixCursor, file: File) {
@@ -173,7 +199,7 @@ class AppFilesProvider : DocumentsProvider() {
} else if (file.canWrite()) {
flags = flags or Document.FLAG_SUPPORTS_WRITE
}
if (file.absolutePath != base.absolutePath && file.parentFile?.canWrite() == true) {
if (file.absolutePath != base.absolutePath && file.parentFile?.canWrite() == true && !holdsPrivate(file)) {
flags = flags or Document.FLAG_SUPPORTS_DELETE or Document.FLAG_SUPPORTS_RENAME or
Document.FLAG_SUPPORTS_MOVE or Document.FLAG_SUPPORTS_REMOVE
}
@@ -40,12 +40,10 @@ import androidx.compose.material.icons.filled.ContentPaste
import androidx.compose.material.icons.filled.CreateNewFolder
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Folder
import androidx.compose.material.icons.filled.GridView
import androidx.compose.material.icons.filled.SdStorage
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Sort
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.ViewList
import androidx.compose.material.icons.filled.StarBorder
import androidx.compose.material.icons.filled.Storage
import androidx.compose.material.icons.filled.Smartphone
@@ -727,11 +725,15 @@ fun FileManagerScreen(
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.surfaceContainer)
.then(if (compactToolbar) Modifier.horizontalScroll(rememberScrollState()) else Modifier)
.padding(horizontal = 8.dp, vertical = 6.dp),
) {
IconButton(onClick = { requestNavigation(FileManagerNavigation.UP) }, enabled = canGoUp && !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) {
Icon(Icons.Filled.ArrowBack, stringResource(R.string.fm_back), tint = MaterialTheme.colorScheme.primary)
val upEnabled = canGoUp && !cancellingNavigation
IconButton(onClick = { requestNavigation(FileManagerNavigation.UP) }, enabled = upEnabled, modifier = Modifier.focusGlide(CircleShape)) {
Icon(
Icons.Filled.ArrowBack,
stringResource(R.string.fm_back),
tint = if (upEnabled) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f),
)
}
val currentDriveLabel = stringResource(describeLocation(currentDir).driveLabel)
@@ -794,113 +796,119 @@ fun FileManagerScreen(
Spacer(Modifier.width(4.dp))
if (showFavorites) {
Text(
text = stringResource(R.string.fm_favorites),
color = MaterialTheme.colorScheme.primary,
fontSize = 13.sp,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f),
)
} else if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT) {
if (!compactToolbar) Spacer(Modifier.weight(1f))
} else {
Text(
text = currentDir.name.ifBlank { currentDir.absolutePath },
color = MaterialTheme.colorScheme.onSurface,
fontSize = 14.sp,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f),
)
}
if (launchDir != null) {
IconButton(onClick = { requestNavigation(FileManagerNavigation.RETURN_TO_START) }, enabled = !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) {
Icon(Icons.AutoMirrored.Filled.KeyboardReturn, stringResource(R.string.fm_return_to_start), tint = MaterialTheme.colorScheme.primary)
}
if (LocalConfiguration.current.screenWidthDp >= 700) Spacer(Modifier.width(56.dp))
}
if (!showFavorites) {
if (!pickMode) {
OutlinedButton(
onClick = { showNewFolderDialog = true },
border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.6f)),
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 2.dp),
modifier = Modifier.height(32.dp).focusGlide(CircleShape),
) {
Icon(Icons.Filled.CreateNewFolder, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
Spacer(Modifier.width(5.dp))
Text(stringResource(R.string.fm_new_folder), color = MaterialTheme.colorScheme.onBackground, fontSize = 12.sp)
}
}
IconButton(onClick = {
gridView = !gridView
browsePrefs.edit().putBoolean("fmGridView", gridView).apply()
}, modifier = Modifier.focusGlide(CircleShape)) {
Icon(
if (gridView) Icons.Filled.ViewList else Icons.Filled.GridView,
if (gridView) stringResource(R.string.fm_list_view) else stringResource(R.string.fm_grid_view),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.weight(1f)
.then(if (compactToolbar) Modifier.horizontalScroll(rememberScrollState()) else Modifier),
) {
if (showFavorites) {
Text(
text = stringResource(R.string.fm_favorites),
color = MaterialTheme.colorScheme.primary,
fontSize = 13.sp,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f),
)
} else if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT) {
if (!compactToolbar) Spacer(Modifier.weight(1f))
} else {
Text(
text = currentDir.name.ifBlank { currentDir.absolutePath },
color = MaterialTheme.colorScheme.onSurface,
fontSize = 14.sp,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f),
)
}
IconButton(onClick = { showSearch = !showSearch; if (!showSearch) searchQuery = "" }, modifier = Modifier.focusGlide(CircleShape)) {
Icon(Icons.Filled.Search, stringResource(R.string.fm_search), tint = MaterialTheme.colorScheme.onSurfaceVariant)
}
Box {
IconButton(onClick = { showSortMenu = true }, modifier = Modifier.focusGlide(CircleShape)) {
Icon(Icons.Filled.Sort, stringResource(R.string.fm_sort), tint = MaterialTheme.colorScheme.onSurfaceVariant)
}
DropdownMenu(expanded = showSortMenu, onDismissRequest = { showSortMenu = false }) {
listOf("name" to stringResource(R.string.fm_sort_name), "date" to stringResource(R.string.fm_sort_date), "size" to stringResource(R.string.fm_prop_size))
.forEach { (key, label) ->
DropdownMenuItem(
text = {
Text(if (sortBy == key) "$label ${if (sortDesc) "↓" else "↑"}" else label)
},
onClick = {
if (sortBy == key) sortDesc = !sortDesc else { sortBy = key; sortDesc = false }
browsePrefs.edit().putString("fmSortBy", sortBy)
.putBoolean("fmSortDesc", sortDesc).apply()
showSortMenu = false
loadDirectory(currentDir, resetScroll = false)
},
modifier = Modifier.focusGlide(),
)
}
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
DropdownMenuItem(
text = { Text(if (compactRows) stringResource(R.string.fm_rows_comfortable) else stringResource(R.string.fm_rows_compact)) },
onClick = {
compactRows = !compactRows
browsePrefs.edit().putBoolean("fmCompactRows", compactRows).apply()
showSortMenu = false
},
modifier = Modifier.focusGlide(),
)
DropdownMenuItem(
text = { Text(if (showHidden) stringResource(R.string.fm_hide_hidden) else stringResource(R.string.fm_show_hidden)) },
onClick = {
showHidden = !showHidden
browsePrefs.edit().putBoolean("fmShowHidden", showHidden).apply()
showSortMenu = false
loadDirectory(currentDir, resetScroll = false)
},
modifier = Modifier.focusGlide(),
)
}
}
}
IconButton(onClick = { showFavorites = !showFavorites }, modifier = Modifier.focusGlide(CircleShape)) {
if (showFavorites) {
Icon(Icons.Filled.Star, stringResource(R.string.fm_hide_favorites), tint = MaterialTheme.colorScheme.primary)
} else {
Icon(Icons.Filled.StarBorder, stringResource(R.string.fm_show_favorites), tint = MaterialTheme.colorScheme.onSurfaceVariant)
if (launchDir != null) {
IconButton(onClick = { requestNavigation(FileManagerNavigation.RETURN_TO_START) }, enabled = !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) {
Icon(Icons.AutoMirrored.Filled.KeyboardReturn, stringResource(R.string.fm_return_to_start), tint = MaterialTheme.colorScheme.primary)
}
if (LocalConfiguration.current.screenWidthDp >= 700) Spacer(Modifier.width(56.dp))
}
if (!showFavorites) {
if (!pickMode) {
OutlinedButton(
onClick = { showNewFolderDialog = true },
border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.6f)),
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 2.dp),
modifier = Modifier.height(32.dp).focusGlide(CircleShape),
) {
Icon(Icons.Filled.CreateNewFolder, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
Spacer(Modifier.width(5.dp))
Text(stringResource(R.string.fm_new_folder), color = MaterialTheme.colorScheme.onBackground, fontSize = 12.sp)
}
}
IconButton(onClick = { showSearch = !showSearch; if (!showSearch) searchQuery = "" }, modifier = Modifier.focusGlide(CircleShape)) {
Icon(Icons.Filled.Search, stringResource(R.string.fm_search), tint = MaterialTheme.colorScheme.onSurfaceVariant)
}
Box {
IconButton(onClick = { showSortMenu = true }, modifier = Modifier.focusGlide(CircleShape)) {
Icon(Icons.Filled.Sort, stringResource(R.string.fm_sort), tint = MaterialTheme.colorScheme.onSurfaceVariant)
}
DropdownMenu(expanded = showSortMenu, onDismissRequest = { showSortMenu = false }) {
listOf("name" to stringResource(R.string.fm_sort_name), "date" to stringResource(R.string.fm_sort_date), "size" to stringResource(R.string.fm_prop_size))
.forEach { (key, label) ->
DropdownMenuItem(
text = {
Text(if (sortBy == key) "$label ${if (sortDesc) "↓" else "↑"}" else label)
},
onClick = {
if (sortBy == key) sortDesc = !sortDesc else { sortBy = key; sortDesc = false }
browsePrefs.edit().putString("fmSortBy", sortBy)
.putBoolean("fmSortDesc", sortDesc).apply()
showSortMenu = false
loadDirectory(currentDir, resetScroll = false)
},
modifier = Modifier.focusGlide(),
)
}
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
DropdownMenuItem(
text = { Text(if (gridView) stringResource(R.string.fm_list_view) else stringResource(R.string.fm_grid_view)) },
onClick = {
gridView = !gridView
browsePrefs.edit().putBoolean("fmGridView", gridView).apply()
showSortMenu = false
},
modifier = Modifier.focusGlide(),
)
DropdownMenuItem(
text = { Text(if (compactRows) stringResource(R.string.fm_rows_comfortable) else stringResource(R.string.fm_rows_compact)) },
onClick = {
compactRows = !compactRows
browsePrefs.edit().putBoolean("fmCompactRows", compactRows).apply()
showSortMenu = false
},
modifier = Modifier.focusGlide(),
)
DropdownMenuItem(
text = { Text(if (showHidden) stringResource(R.string.fm_hide_hidden) else stringResource(R.string.fm_show_hidden)) },
onClick = {
showHidden = !showHidden
browsePrefs.edit().putBoolean("fmShowHidden", showHidden).apply()
showSortMenu = false
loadDirectory(currentDir, resetScroll = false)
},
modifier = Modifier.focusGlide(),
)
}
}
}
IconButton(onClick = { showFavorites = !showFavorites }, modifier = Modifier.focusGlide(CircleShape)) {
if (showFavorites) {
Icon(Icons.Filled.Star, stringResource(R.string.fm_hide_favorites), tint = MaterialTheme.colorScheme.primary)
} else {
Icon(Icons.Filled.StarBorder, stringResource(R.string.fm_show_favorites), tint = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
}
if (!pickMode && onExit != null) {
@@ -222,16 +222,7 @@ object Library {
internal fun concealedSteamApps(root: File): Set<Long> {
val config = AddedGames.accountConfig(root) ?: return emptySet()
val hidden = runCatching {
val entries = org.json.JSONArray(File(config, "cloudstorage/cloud-storage-namespace-1.json").readText())
val entry = (0 until entries.length()).map { entries.getJSONArray(it) }
.firstOrNull { it.optString(0) == "user-collections.hidden" }?.optJSONObject(1)
if (entry == null || entry.optBoolean("is_deleted")) emptySet() else {
val collection = org.json.JSONObject(entry.optString("value"))
fun ids(key: String) = collection.optJSONArray(key)?.let { a -> (0 until a.length()).map { a.optLong(it) } }.orEmpty()
ids("added").toSet() - ids("removed").toSet()
}
}.getOrDefault(emptySet())
val hidden = SteamHidden.read(root)
val private = runCatching {
PRIVATE_APPS.find(File(config, "localconfig.vdf").readText())?.groupValues?.get(1)
?.split(',')?.mapNotNull { it.trim().toLongOrNull() }?.toSet()
@@ -302,6 +293,7 @@ object Library {
g.steamAppId ?: g.appId.toInt(), g.name, art.portrait ?: art.header, ADDED, g.gameId,
hero = art.hero ?: art.header, lastPlayed = maxOf(lastPlayed, recordedPlay(context, g.gameId)), gameFiles = g.folder,
protonPrefix = if (g.source == com.droiddeck.launcher.stores.Store.BATTLENET.id) File(com.droiddeck.launcher.runtime.BattleNet.prefix(context), "pfx").takeIf { it.isDirectory }
else if (g.source == com.droiddeck.launcher.stores.Store.UBISOFT.id) File(com.droiddeck.launcher.stores.ubisoft.UbisoftConnect.prefix(context), "pfx").takeIf { it.isDirectory }
else protonPrefix(context, g.steamAppId?.toLong() ?: g.appId, libraries = roots),
icon = art.icon?.takeIf { it.extension.lowercase() != "ico" },
source = g.source, storeId = g.storeId,
@@ -177,9 +177,10 @@ object SoundtrackCollections {
source = Library.SOURCE_COLLECTION, soundtrack = true,
)
fun games(context: Context, favoritesLabel: String): List<Library.SteamGame> {
fun games(context: Context, favoritesLabel: String, skipEmptyFavorites: Boolean = false): 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) }
val favorites = if (skipEmptyFavorites && s.favorites.isEmpty()) emptyList() else listOf(game(context, FAVORITES_ID, favoritesLabel, s.favorites))
return favorites + s.collections.map { game(context, it.id, it.name, it.tracks) }
}
fun album(context: Context, id: Int): Soundtrack.Album {
@@ -0,0 +1,78 @@
package com.droiddeck.launcher.frontend
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
internal object SteamHidden {
private const val KEY = "user-collections.hidden"
private fun file(root: File): File? = AddedGames.accountConfig(root)?.let { File(it, "cloudstorage/cloud-storage-namespace-1.json") }
class Saved(val hidden: Set<Long>, val queued: Boolean)
private fun id(member: Any?): Long? = when (member) {
is Int -> member.toLong()
is Long -> member
is String -> member.toLongOrNull()
else -> null
}
private fun ids(collection: JSONObject, key: String, strict: Boolean): List<Long> {
if (!collection.has(key)) return emptyList()
val array = collection.optJSONArray(key) ?: throw IllegalStateException(key)
return (0 until array.length()).mapNotNull { index ->
id(array.get(index)) ?: if (strict) throw IllegalStateException(key) else null
}
}
fun read(root: File): Set<Long> = readOrNull(root).orEmpty()
fun readOrNull(root: File): Set<Long>? = runCatching {
val entries = JSONArray(file(root)?.readText() ?: return null)
val slot = (0 until entries.length()).map { entries.getJSONArray(it) }.firstOrNull { it.optString(0) == KEY }
val entry = slot?.optJSONObject(1)
if (slot != null && entry == null) return null
if (entry == null || entry.optBoolean("is_deleted")) emptySet() else {
val collection = JSONObject(entry.optString("value"))
ids(collection, "added", false).toSet() - ids(collection, "removed", false).toSet()
}
}.getOrNull()
fun write(root: File, appId: Long, hidden: Boolean, now: Long = System.currentTimeMillis() / 1000): Saved? = runCatching {
val target = file(root) ?: return null
val entries = JSONArray(target.readText())
val slot = (0 until entries.length()).firstOrNull { entries.getJSONArray(it).optString(0) == KEY }
val entry = if (slot == null) JSONObject().put("key", KEY) else entries.getJSONArray(slot).optJSONObject(1) ?: return null
val live = !entry.optBoolean("is_deleted")
val collection = if (live && entry.has("value")) JSONObject(entry.optString("value")) else JSONObject().put("id", "hidden")
val added = ids(collection, "added", true).filter { it != appId }
val removed = ids(collection, "removed", true).filter { it != appId }
collection.put("added", JSONArray(if (hidden) added + appId else added))
collection.put("removed", JSONArray(if (hidden) removed else removed + appId))
entry.put("value", collection.toString())
entry.put("timestamp", now)
entry.put("is_deleted", false)
entry.opt("version")?.toString()?.toLongOrNull()?.let { entry.put("version", (it + 1).toString()) }
if (slot == null) entries.put(JSONArray().put(KEY).put(entry))
val temp = File(target.parentFile, target.name + ".tmp")
temp.writeText(entries.toString())
if (!temp.renameTo(target)) {
temp.delete()
return null
}
Saved(ids(collection, "added", true).toSet() - ids(collection, "removed", true).toSet(), markModified(File(target.parentFile, "cloud-storage-namespace-1.modified.json")))
}.getOrNull()
private fun markModified(file: File): Boolean {
val pending = if (file.exists()) runCatching { JSONArray(file.readText()) }.getOrNull() ?: return false else JSONArray()
if ((0 until pending.length()).any { pending.optString(it) == KEY }) return true
val temp = File(file.parentFile, file.name + ".tmp")
val saved = runCatching {
temp.writeText(pending.put(KEY).toString())
temp.renameTo(file)
}.getOrDefault(false)
if (!saved) temp.delete()
return saved
}
}
@@ -37,22 +37,22 @@ class ClockLogComponent(private val logFile: File) : SessionPart() {
?.sortedBy { it.name.removePrefix("policy").toIntOrNull() ?: 0 } ?: emptyList()
val gpuCandidates = gpuSources()
val gpu = gpuCandidates.firstOrNull { !it.startsWith("/proc/") && firstNumber(it) != null }
val stepSources = GpuLimits.stepSources()
val maxSources = GpuLimits.maxSources()
val minSources = GpuLimits.minSources()
val steps = GpuLimits.first(stepSources)
var ceiling = ceilingSource(maxSources)
val power = app().getSystemService(Context.POWER_SERVICE) as? PowerManager
val time = SimpleDateFormat("HH:mm:ss", Locale.US)
try {
FileWriter(logFile, true).use { w ->
w.write("== clocks: ${Build.MANUFACTURER} ${Build.MODEL} (${Build.HARDWARE}), every ${PERIOD_MS / 1000}s\n")
w.write("cpu policies: ${policies.joinToString { p -> p.name + " " + (File(p, "related_cpus").readTextOrNull()?.trim() ?: "?") }}\n")
for (source in gpuCandidates) {
val f = File(source)
val state = when {
!f.exists() -> continue
firstNumber(source) != null -> "readable"
else -> "refused"
}
w.write("gpu source $source: $state\n")
}
probeLines("gpu source", gpuCandidates).forEach { w.write(it + "\n") }
w.write("gpu clock from: ${gpu ?: "nothing readable"}\n")
(probeLines("gpu limit", stepSources, ::firstStep) + probeLines("gpu limit", maxSources, ::limit) +
probeLines("gpu limit", minSources, ::firstStep)).distinct().forEach { w.write(it + "\n") }
limitLines(steps, ceiling, GpuLimits.first(minSources)).forEach { w.write(it + "\n") }
w.flush()
while (running && logFile.length() < MAX_BYTES) {
val line = StringBuilder(time.format(Date()))
@@ -63,7 +63,8 @@ class ClockLogComponent(private val logFile: File) : SessionPart() {
line.append(" ${p.name.removePrefix("policy").let { "p$it" }} ${mhz(cur)}/${mhz(max)}")
if (hw != null && max != null && max < hw) line.append("(of ${mhz(hw)})")
}
gpu?.let { line.append(" | gpu ${mhz(firstNumber(it))} MHz") }
if (ceiling == null) ceiling = ceilingSource(maxSources)?.also { w.write("gpu ceiling from: $it\n") }
line.append(gpuField(gpu, ceiling, steps?.mhz?.last()))
if (power != null && Build.VERSION.SDK_INT >= 29) {
line.append(" | thermal ${power.currentThermalStatus}")
if (Build.VERSION.SDK_INT >= 30) {
@@ -109,16 +110,41 @@ class ClockLogComponent(private val logFile: File) : SessionPart() {
return list.distinct()
}
internal fun probeLines(label: String, sources: List<String>, read: (String) -> Long? = ::firstNumber): List<String> = sources.mapNotNull { source ->
when {
!File(source).exists() -> null
read(source) != null -> "$label $source: readable"
else -> "$label $source: refused"
}
}
internal fun limitLines(steps: GpuLimits.Found?, ceiling: String?, floor: GpuLimits.Found?): List<String> = listOf(
"gpu steps: " + (steps?.let { "${it.mhz.joinToString(" ")} MHz from ${it.path}" } ?: "nothing readable"),
"gpu ceiling from: " + (ceiling ?: "nothing readable"),
"gpu floor: " + (floor?.let { "${it.mhz.first()} MHz from ${it.path}" } ?: "nothing readable"),
)
internal fun gpuField(clock: String?, ceiling: String?, top: Long?): String {
if (clock == null && ceiling == null) return ""
val field = StringBuilder(" | gpu ").append(mhz(clock?.let(::firstNumber)))
ceiling?.let(::limit)?.let { max ->
field.append('/').append(mhz(max))
if (top != null && GpuLimits.mhz(max) < top) field.append("(of $top)")
}
return field.append(" MHz").toString()
}
private fun File.readTextOrNull(): String? = runCatching { readText() }.getOrNull()
private fun firstNumber(path: String): Long? =
runCatching { Regex("\\d+").find(File(path).readText())?.value?.toLong() }.getOrNull()
private fun mhz(raw: Long?): String = when {
raw == null -> "?"
raw > 10_000_000 -> (raw / 1_000_000).toString()
raw > 10_000 -> (raw / 1_000).toString()
else -> raw.toString()
}
internal fun limit(path: String): Long? = firstNumber(path)?.takeIf { it > 0 }
internal fun firstStep(path: String): Long? = GpuLimits.read(path).firstOrNull()
internal fun ceilingSource(sources: List<String>): String? = sources.firstOrNull { limit(it) != null }
private fun mhz(raw: Long?): String = raw?.let { GpuLimits.mhz(it).toString() } ?: "?"
}
}
@@ -87,20 +87,10 @@ object DeviceInfo {
private fun ghz(khz: Long) = String.format(Locale.US, "%.2f GHz", khz / 1e6)
private fun gpuRange(): String? {
fun mhz(hz: Long) = "${hz / 1_000_000} MHz"
val kgsl = read("/sys/class/kgsl/kgsl-3d0/gpu_available_frequencies")
?.split(Regex("\\s+"))?.mapNotNull { it.toLongOrNull() }?.filter { it > 0 }.orEmpty()
if (kgsl.isNotEmpty()) return "${mhz(kgsl.min())}–${mhz(kgsl.max())} (${kgsl.size} steps)"
read("/sys/class/kgsl/kgsl-3d0/max_gpuclk")?.toLongOrNull()?.let { return "up to ${mhz(it)}" }
val node = File("/sys/class/devfreq").listFiles()?.firstOrNull { f ->
val n = f.name.lowercase()
(n.contains("gpu") || n.contains("mali") || n.contains("kgsl-3d")) && listOf("bus", "bw", "memlat").none { n.contains(it) }
} ?: return null
val steps = read("${node.path}/available_frequencies")?.split(Regex("\\s+"))?.mapNotNull { it.toLongOrNull() }?.filter { it > 0 }.orEmpty()
if (steps.isNotEmpty()) return "${mhz(steps.min())}–${mhz(steps.max())} (${steps.size} steps)"
val min = read("${node.path}/min_freq")?.toLongOrNull()
val max = read("${node.path}/max_freq")?.toLongOrNull() ?: return null
return (if (min != null) "${mhz(min)}–" else "up to ") + mhz(max)
GpuLimits.first(GpuLimits.stepSources())?.mhz?.let { return "${it.first()} MHz–${it.last()} MHz (${it.size} steps)" }
val max = GpuLimits.first(GpuLimits.maxSources())?.mhz?.last() ?: return null
val min = GpuLimits.first(GpuLimits.minSources())?.mhz?.first()
return (if (min != null) "$min MHz–" else "up to ") + "$max MHz"
}
private fun memory(context: Context) = Section("Memory", buildList<Pair<String, String>> {
@@ -18,6 +18,7 @@ object DriverPairs {
/** RADV-Xclipse rebased on JimVulkan's upstream: a manual choice, never Auto. */
const val NAD_RADV_XCLIPSE_UPSTREAM = "nad:radv-xclipse-upstream"
private val XCLIPSE_MODEL = Regex("""(?i)xclipse\s*(\d{3})\b""")
private val SUPPORTED_XCLIPSE_MODELS = setOf("530", "920", "940")
const val NAD_MALI_JM = "nad:panvk-mali-jm"
const val NAD_MALI_G710 = "nad:panvk-mali-g710"
const val NAD_MALI_G615 = "nad:panvk-mali-g615"
@@ -112,9 +113,12 @@ object DriverPairs {
}
}
/** 950 and 960 panic on the older build; a name without a model number is treated the same way. */
private fun xclipseNeedsUpstream(name: String): Boolean =
XCLIPSE_MODEL.find(name)?.groupValues?.get(1).let { it == null || it == "950" || it == "960" }
internal fun xclipseNeedsUpstream(name: String): Boolean =
XCLIPSE_MODEL.find(name)?.groupValues?.get(1) !in SUPPORTED_XCLIPSE_MODELS
fun autoEligible(gpu: GpuInfo, sdk: Int = android.os.Build.VERSION.SDK_INT): Boolean =
recommendedKey(gpu, emptyList(), sdk = sdk) != null ||
(gpu.family == Family.POWERVR && gpu.name.contains("Xclipse", ignoreCase = true))
fun recommendedKey(
gpu: GpuInfo, pairs: List<DriverPair>,
@@ -125,6 +129,7 @@ object DriverPairs {
Family.POWERVR -> return when {
!gpu.name.contains("Xclipse", ignoreCase = true) -> null
xclipseNeedsUpstream(gpu.name) && pairs.any { it.key == NAD_RADV_XCLIPSE_UPSTREAM } -> NAD_RADV_XCLIPSE_UPSTREAM
xclipseNeedsUpstream(gpu.name) -> null
else -> NAD_RADV_XCLIPSE
}
Family.MALI_OTHER, Family.NOT_ADRENO -> return null
@@ -118,9 +118,7 @@ data class GpuInfo(
val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true)
return GpuInfo(
name = when {
family == Family.POWERVR -> SystemVulkanDriver.gpuName().let { gpu ->
VulkanInfo.cachedOrNull()?.get("device")?.takeIf { it.contains(gpu, ignoreCase = true) } ?: gpu
}
family == Family.POWERVR -> systemDriverName(SystemVulkanDriver.gpuName(), VulkanInfo.cachedOrNull())
mali != null && mali.isNotEmpty() -> mali
!adreno -> Build.HARDWARE.ifBlank { UNNAMED }
model > 0 -> "Adreno $model"
@@ -134,6 +132,9 @@ data class GpuInfo(
)
}
fun systemDriverName(gpu: String, vulkan: Map<String, String>?): String =
vulkan?.get("device")?.takeIf { it.contains(gpu, ignoreCase = true) } ?: gpu
internal fun verifiedOn(model: Int, device: String): Boolean =
model == 722 && device.equals("Retroid Pocket Duo", ignoreCase = true)
@@ -0,0 +1,41 @@
package com.droiddeck.launcher.gpu
import java.io.File
object GpuLimits {
class Found(val path: String, val mhz: List<Long>)
private const val KGSL = "/sys/class/kgsl/kgsl-3d0"
private const val QCOM_GPU = "/sys/kernel/gpu"
fun stepSources(): List<String> = listOf(
"$KGSL/gpu_available_frequencies", "$KGSL/freq_table_mhz", "$KGSL/devfreq/available_frequencies", "$QCOM_GPU/gpu_freq_table",
) + devfreq("available_frequencies")
fun maxSources(): List<String> = listOf(
"$KGSL/max_gpuclk", "$KGSL/max_clock_mhz", "$KGSL/devfreq/max_freq", "$QCOM_GPU/gpu_max_clock",
) + devfreq("max_freq")
fun minSources(): List<String> = listOf(
"$KGSL/min_clock_mhz", "$KGSL/devfreq/min_freq", "$QCOM_GPU/gpu_min_clock",
) + devfreq("min_freq")
fun first(sources: List<String>): Found? =
sources.firstNotNullOfOrNull { path -> read(path).takeIf { it.isNotEmpty() }?.let { Found(path, it) } }
fun read(path: String): List<Long> = runCatching {
Regex("\\d+").findAll(File(path).readText()).map { mhz(it.value.toLong()) }.filter { it > 0 }.distinct().sorted().toList()
}.getOrDefault(emptyList())
fun mhz(raw: Long): Long = when {
raw > 10_000_000 -> raw / 1_000_000
raw > 10_000 -> raw / 1_000
else -> raw
}
private fun devfreq(file: String): List<String> =
File("/sys/class/devfreq").listFiles()?.filter { f ->
val n = f.name.lowercase()
(n.contains("gpu") || n.contains("mali") || n.contains("kgsl-3d")) && listOf("bus", "bw", "memlat").none { n.contains(it) }
}?.sortedBy { it.name }?.map { "${it.path}/$file" }.orEmpty()
}
@@ -138,16 +138,16 @@ object InputLibraries {
update(context) { library -> library.layouts.firstOrNull { it.id == layoutId && it.editable }?.let { library.withLayout(it.withQuickButton(button, shown)) } ?: library }
}.isSuccess
fun defaultPositions(context: Context, library: InputLibrary, layout: SavedInputLayout): List<InputSurfaceElement>? {
fun defaultPositions(context: Context, library: InputLibrary, layout: SavedInputLayout): Pair<List<InputSurfaceElement>, Float>? {
val origin = layout.origin ?: layout.id
InputStockLayouts.layouts().firstOrNull { it.id == origin }?.let { return it.elements }
InputStockLayouts.layouts().firstOrNull { it.id == origin }?.let { return it.elements to it.aspect }
if (origin == OVERLAY || origin.startsWith("migrated.layout.")) {
val (surfaceContext, metrics) = primaryDisplay(context)
val size = if (origin == OVERLAY) listOf(metrics.widthPixels, metrics.heightPixels)
else origin.removePrefix("migrated.layout.").split('x').mapNotNull { it.toIntOrNull() }
return size.takeIf { it.size == 2 && it.all { side -> side > 0 } }?.let { LegacyGamepadLayout(surfaceContext, it[0], it[1]).elements() }
return size.takeIf { it.size == 2 && it.all { side -> side > 0 } }?.let { LegacyGamepadLayout(surfaceContext, it[0], it[1]).elements() to it[0].toFloat() / it[1] }
}
return library.layouts.firstOrNull { it.id == origin && it.id != layout.id }?.elements
return library.layouts.firstOrNull { it.id == origin && it.id != layout.id }?.let { it.elements to it.aspect }
}
@Suppress("DEPRECATION")
@@ -282,6 +282,8 @@ object ComponentsManager {
if (parts.size > 1) parts[1] else parts.firstOrNull()?.ifEmpty { null } ?: "unknown"
}.getOrDefault("unknown")
internal fun isProtonTree(dir: File): Boolean = File(dir, WINE).isDirectory && File(dir, "proton").isFile
fun protons(context: Context): List<Proton> {
val found = LinkedHashMap<String, Proton>()
val bases = listOf(File(steam(context), "compatibilitytools.d") to false) +
@@ -290,7 +292,7 @@ object ComponentsManager {
for ((base, valve) in bases) {
val entries = base.listFiles()?.sortedBy { it.name } ?: continue
for (dir in entries) {
if (!File(dir, WINE).isDirectory || !File(dir, "proton").isFile) continue
if (!isProtonTree(dir)) continue
val real = runCatching { dir.canonicalPath }.getOrDefault(dir.path)
if (found.containsKey(real)) continue
val guest = if (dir.absolutePath.startsWith(rootPath)) dir.absolutePath.removePrefix(rootPath) else dir.absolutePath
@@ -900,15 +902,26 @@ object ComponentsManager {
}
}
fun forgetProton(context: Context, dirName: String) {
synchronized(lock) {
val id = safeName(dirName)
if (protons(context).any { it.id == id }) return
val state = loadState(context)
val selected = listOf("active", "queued").map { state.sub(it).remove(id) != null }.any { it }
if (selected && runCatching { saveState(context, state) }.onFailure { Log.w(TAG, "forget $id", it) }.isFailure) return
File(originalsDir(context), id).deleteRecursively()
}
fun forgetProton(context: Context, dirName: String): Boolean = synchronized(lock) {
val id = safeName(dirName)
if (protons(context).any { it.id == id }) return true
val state = loadState(context)
val selected = listOf("active", "queued").map { state.sub(it).remove(id) != null }.any { it }
val published = File(launchDir(context), "desired.tsv")
val listed = published.takeIf { it.isFile }
?.useLines { rows -> rows.any { it.split('\t').getOrNull(1) == dirName } } == true
if ((selected || listed) && runCatching { saveState(context, state) }.onFailure { Log.w(TAG, "forget $id", it) }.isFailure) return false
val originals = File(originalsDir(context), id)
val store = File(launchDir(context), "store")
val used = published.takeIf { it.isFile }?.useLines { rows ->
rows.mapNotNull { it.substringAfterLast('\t').substringAfter("/store/", "").substringBefore('/').ifEmpty { null } }.toSet()
}.orEmpty()
val unpacked = originals.listFiles().orEmpty().flatMap { version ->
version.listFiles().orEmpty().map { File(store, "original-$id-${version.name}-${it.name.removeSuffix(".wcp")}") }
}.filter { it.name !in used }
if (unpacked.any { File(it, ".complete").delete(); !it.deleteRecursively() && it.exists() }) return false
originals.deleteRecursively()
true
}
private fun storePackage(context: Context, part: File, dest: File) {
@@ -708,10 +708,10 @@ internal object EnhancedSessionLogShare {
}
val logs = LinuxRuntime.logDir(context)
for ((name, root) in listOf(SessionLogShare.STORES_DIR to File(logs, SessionLogShare.STORES_DIR), SessionPaths.TOOLS_DIR to File(logs, SessionPaths.TOOLS_DIR))) {
val scan = directFiles(root, remaining(maxFiles, out.size))
val scan = directFiles(root, STORE_LOG_SCAN)
truncated = truncated || scan.truncated
partial = partial || scan.partial
scan.files.asSequence().filter { recent(it) }
scan.files.filter { recent(it) }.sortedByDescending { it.lastModified() }.take(remaining(maxFiles, out.size))
.forEach { add(it, root, "$name/${it.name}", name) }
}
if (legacy) {
@@ -965,6 +965,7 @@ internal object EnhancedSessionLogShare {
"events.jsonl", "memory.csv", "capture.json", "crash.log",
)
private const val RECENT_MILLIS = 7L * 24 * 60 * 60 * 1000
private const val STORE_LOG_SCAN = 512
private const val COPY_BUFFER_BYTES = 64 * 1024
private const val TRACE_SCAN_BYTES = 16L * 1024 * 1024
private const val LEGACY_LOG_MAX_BYTES = 8L * 1024 * 1024
@@ -0,0 +1,412 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.os.StatFs
import android.util.Log
import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.core.Hashes
import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.nio.file.Files
import java.nio.file.attribute.PosixFilePermission
import java.security.DigestOutputStream
import java.security.MessageDigest
import java.util.zip.ZipFile
import org.apache.commons.compress.archivers.sevenz.SevenZFile
import org.apache.commons.compress.archivers.zip.ZipFile as CommonsZipFile
import kotlin.io.path.ExperimentalPathApi
import kotlin.io.path.deleteRecursively
import org.json.JSONArray
import org.json.JSONObject
object ExperimentalProtons {
private const val TAG = "ExperimentalProtons"
const val PREFIX = "Experimental-"
private const val MARKER = ".droiddeck-experimental.json"
private const val STAGING = ".droiddeck-experimental"
private const val BACKUPS = ".droiddeck-experimental-old"
private const val INCOMING = ".droiddeck-experimental-new"
private const val REMOVED = ".droiddeck-experimental-gone"
private const val GUEST_TOOLS = "/root/.local/share/Steam/compatibilitytools.d"
private const val NEED_BYTES = 4L * 1024 * 1024 * 1024
private const val USER_SETTINGS = "user_settings.py"
internal val TARBALL = Regex("(?i)\\.tar(\\.(gz|xz|zst|bz2))?$")
internal val FOREIGN_ARCH = Regex("(?i)(^|[^a-z0-9])(x86|x64|amd64|i[3-6]86)([^a-z0-9]|$)")
private val DOWNLOAD_PREFIX = "droiddeck-"
data class Installed(val dir: String, val label: String, val source: String, val releaseTag: String? = null)
data class Release(val tag: String, val asset: String, val url: String, val sha512: String?, val size: Long, val name: String = tag)
enum class ArchiveType { ZIP, SEVEN_Z, TAR, UNKNOWN }
private fun toolsDir(context: Context) = File(LinuxRuntime.rootDir(context), GUEST_TOOLS.removePrefix("/"))
fun installed(context: Context): List<Installed> =
toolsDir(context).listFiles()
?.filter { it.isDirectory && File(it, MARKER).isFile }
?.map { dir ->
val info = runCatching { JSONObject(File(dir, MARKER).readText()) }.getOrDefault(JSONObject())
Installed(dir.name, info.optString("label").ifEmpty { dir.name }, info.optString("source"), info.optString("releaseTag").ifEmpty { null })
}
?.sortedBy { it.dir }
?: emptyList()
fun remove(context: Context, dir: String): Boolean {
val tools = toolsDir(context)
val target = File(tools, dir)
if (!File(target, MARKER).isFile) return false
val doomed = File(File(tools, REMOVED).apply { mkdirs() }, dir)
if (!deleteTree(doomed)) return false
val detached = synchronized(SessionState.startLock) { !SessionState.running && target.renameTo(doomed) }
if (!detached) return false
ComponentsManager.forgetProton(context, dir)
deleteTree(doomed)
deleteTree(File(File(tools, BACKUPS), dir))
deleteTree(File(File(tools, INCOMING), dir))
return true
}
internal fun dirName(tree: String, label: String?): String {
val base = ComponentsManager.safeName(tree)
val tag = label?.let(ComponentsManager::safeName)?.takeIf { it != "unnamed" && !base.contains(it, ignoreCase = true) }
return PREFIX + base + (tag?.let { "-$it" } ?: "")
}
fun refresh(context: Context): List<Release>? {
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
val fetched = ProtonExtras.releasesForRemoval(tool) ?: return null
val assets = ProtonExtras.assets(tool, fetched.releases, prerelease = true)
val rows = assets.map { Release(it.tag, it.name, it.url, it.sha512, it.size, it.releaseName) }.distinctBy { it.tag }
if (!SessionState.running) {
reconcile(context, fetched)
if (fetched.complete) removeStaleDownloads(context, fetched.releases.tags())
}
return rows
}
private fun JSONArray.tags(): Set<String> = (0 until length()).mapNotNull { optJSONObject(it)?.optString("tag_name")?.takeIf(String::isNotEmpty) }.toSet()
internal fun removeStaleDownloads(context: Context, availableTags: Set<String>) {
val downloads = File(context.filesDir, "proton-downloads")
downloads.listFiles()?.filter { file ->
file.isFile && file.name.startsWith(DOWNLOAD_PREFIX) && availableTags.none { tag -> file.name.startsWith("$DOWNLOAD_PREFIX${ComponentsManager.safeName(tag)}-") }
}?.forEach { it.delete() }
}
internal fun available(releases: List<Release>, installed: List<Installed>): List<Release> =
releases.filter { release -> installed.none { it.releaseTag == release.tag } }
internal fun shouldRemove(installedReleaseTag: String?, fetched: ProtonExtras.ReleaseFetch, gone: (String) -> Boolean): Boolean {
val tag = installedReleaseTag ?: return false
val release = (0 until fetched.releases.length()).asSequence()
.mapNotNull { fetched.releases.optJSONObject(it) }
.firstOrNull { it.optString("tag_name") == tag }
return if (release != null) !release.optBoolean("prerelease", false) else fetched.complete && gone(tag)
}
internal fun reconcile(
context: Context,
fetched: ProtonExtras.ReleaseFetch,
gone: (String) -> Boolean = { tag -> ProtonExtras.releaseGone(ProtonExtras.tools.first { it.id == ProtonExtras.OWN }, tag) },
) {
for (build in installed(context)) {
if (SessionState.running) return
if (shouldRemove(build.releaseTag, fetched, gone)) remove(context, build.dir)
}
}
internal fun compatVdf(name: String): String = """"compatibilitytools"
{
"compat_tools"
{
"$name"
{
"install_path" "."
"display_name" "$name"
"from_oslist" "windows"
"to_oslist" "linux"
}
}
}
"""
fun installFromFile(context: Context, file: File, onProgress: (String, Int) -> Unit): String? {
preflight(context)?.let { return it }
if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + file.length()) {
return context.getString(R.string.xproton_no_space)
}
return install(context, file, fileLabel(file.name), file.name, null, onProgress, false)
}
internal fun fileLabel(name: String): String =
if (TARBALL.containsMatchIn(name)) name.replace(TARBALL, "") else name.substringBeforeLast('.')
fun installRelease(context: Context, release: Release, onProgress: (String, Int) -> Unit): String? {
preflight(context)?.let { return it }
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
val archive = File(downloads, "droiddeck-${ComponentsManager.safeName(release.tag)}-${release.asset}")
if (release.size > 0 && archive.length() > release.size) archive.delete()
val missing = (release.size - archive.length()).coerceAtLeast(0L)
val copyBytes = if (sameFileStore(archive, toolsDir(context))) 0L else release.size
if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + missing + copyBytes) return context.getString(R.string.xproton_no_space)
val title = context.getString(R.string.pextra_downloading, "Proton", release.tag)
onProgress(title, 0)
if (!Downloader.downloadFile(release.url, archive, true) { fraction ->
onProgress(title, if (fraction < 0) -1 else (fraction * 100f).toInt().coerceIn(0, 100))
}) return context.getString(R.string.pextra_download_failed)
if (release.size > 0 && archive.length() != release.size) return context.getString(R.string.pextra_incomplete)
if (release.sha512 != null) {
val expected = Downloader.downloadDirect(release.sha512)?.let(::checksumIn)
?: return context.getString(R.string.pextra_checksum_unreadable)
if (!expected.equals(Hashes.sha512(archive), true)) {
archive.delete()
return context.getString(R.string.pextra_checksum_mismatch)
}
}
return try { install(context, archive, release.tag, release.tag, release.tag, onProgress, true) }
finally { archive.delete() }
}
private fun sameFileStore(file: File, directory: File): Boolean = runCatching {
directory.mkdirs()
Files.getFileStore((file.takeIf(File::exists) ?: file.parentFile).toPath()) == Files.getFileStore(directory.toPath())
}.getOrDefault(false)
private fun preflight(context: Context): String? = when {
SessionState.running -> context.getString(R.string.pextra_stop_session)
!LinuxRuntime.isInstalled(context) -> context.getString(R.string.user_apps_runtime_required)
else -> null
}
private fun install(context: Context, archive: File, label: String, source: String, releaseTag: String?, onProgress: (String, Int) -> Unit, downloaded: Boolean): String? {
val tools = toolsDir(context).apply { mkdirs() }
val staging = File(tools, STAGING)
val forget = { name: String -> ComponentsManager.forgetProton(context, name) }
restoreInterrupted(tools, forget)
deleteTree(staging)
staging.mkdirs()
try {
LinuxRuntime.writeAccounts(context)
SessionFiles.stage(context, LinuxRuntime.rootDir(context))
onProgress(context.getString(R.string.xproton_unpacking), -1)
val unpacked = File(staging, "unpacked").apply { mkdirs() }
val type = archiveType(archive)
if (SessionState.running) return context.getString(R.string.pextra_session_started)
onProgress(context.getString(R.string.xproton_unpacking), -1)
when (type) {
ArchiveType.ZIP -> {
val tarball = extractTarball(archive, staging)
if (tarball == null) {
extractDirect(archive, unpacked, ArchiveType.ZIP)
} else {
val status = runGuest(context, listOf("tar", "-xf", "$GUEST_TOOLS/$STAGING/${tarball.name}", "-C", "$GUEST_TOOLS/$STAGING/unpacked"))
tarball.delete()
if (status != 0) return context.getString(R.string.xproton_untar_failed, status)
}
}
ArchiveType.SEVEN_Z -> extractDirect(archive, unpacked, ArchiveType.SEVEN_Z)
ArchiveType.TAR -> {
val stagedArchive = File(staging, archive.name)
if (!archive.canonicalFile.equals(stagedArchive.canonicalFile) && !(downloaded && archive.renameTo(stagedArchive))) {
archive.copyTo(stagedArchive, overwrite = true)
}
val status = runGuest(context, listOf("tar", "-xf", "$GUEST_TOOLS/$STAGING/${stagedArchive.name}", "-C", "$GUEST_TOOLS/$STAGING/unpacked"))
if (status != 0) return context.getString(R.string.xproton_untar_failed, status)
}
ArchiveType.UNKNOWN -> return context.getString(R.string.xproton_archive_invalid)
}
val tree = buildTree(unpacked) ?: return context.getString(R.string.xproton_no_tree)
val name = dirName(tree.name, label)
ownFile(tree, "compatibilitytool.vdf").writeText(compatVdf(name))
ownFile(tree, MARKER).writeText(
JSONObject().put("label", name).put("source", source).putOpt("releaseTag", releaseTag).put("at", System.currentTimeMillis() / 1000).toString(),
)
val final = File(tools, name)
val settings = File(final, USER_SETTINGS)
if (Files.isRegularFile(settings.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS)) {
settings.copyTo(ownFile(tree, USER_SETTINGS))
}
if (!placeTree(tree, tools, name, forget)) return context.getString(R.string.xproton_place_failed)
onProgress(context.getString(R.string.pextra_installing, name), -1)
runGuest(context, listOf("steam-compatibility", "/root/.local/share/Steam"))
return null
} catch (e: Exception) {
Log.e(TAG, "install $source", e)
return if (e is UnsafeArchiveException) context.getString(R.string.xproton_archive_unsafe) else context.getString(R.string.xproton_archive_invalid)
} finally {
deleteTree(staging)
}
}
internal fun buildTree(unpacked: File): File? {
val root = unpacked.canonicalFile
return unpacked.listFiles()?.sortedBy { it.name }?.firstOrNull {
!Files.isSymbolicLink(it.toPath()) && it.isDirectory && it.canonicalFile.parentFile == root &&
Files.isRegularFile(File(it, "toolmanifest.vdf").toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS) &&
ComponentsManager.isProtonTree(it)
}
}
@OptIn(ExperimentalPathApi::class)
internal fun deleteTree(dir: File): Boolean =
runCatching { dir.toPath().deleteRecursively() }.onFailure { Log.w(TAG, "delete $dir", it) }.isSuccess && !Files.exists(dir.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS)
internal fun ownFile(tree: File, name: String): File {
val file = File(tree, name)
Files.deleteIfExists(file.toPath())
return file
}
internal fun placeTree(tree: File, tools: File, name: String, forget: (String) -> Boolean): Boolean {
val incoming = File(File(tools, INCOMING).apply { mkdirs() }, name)
if (!deleteTree(incoming) || !tree.renameTo(incoming)) return false
return finishPlacing(tools, name, forget)
}
private fun finishPlacing(tools: File, name: String, forget: (String) -> Boolean): Boolean {
val incoming = File(File(tools, INCOMING), name)
val final = File(tools, name)
val backup = File(File(tools, BACKUPS).apply { mkdirs() }, name)
val moved = !final.exists() || (deleteTree(backup) && final.renameTo(backup))
val placed = moved && (!backup.exists() || forget(name)) && incoming.renameTo(final)
if (!placed) {
if (!final.exists()) backup.renameTo(final)
deleteTree(incoming)
}
if (final.exists()) deleteTree(backup)
return placed
}
internal fun restoreInterrupted(tools: File, forget: (String) -> Boolean) {
deleteTree(File(tools, REMOVED))
File(tools, INCOMING).listFiles()?.forEach { finishPlacing(tools, it.name, forget) }
File(tools, BACKUPS).listFiles()?.forEach { if (File(tools, it.name).exists()) deleteTree(it) else it.renameTo(File(tools, it.name)) }
}
internal fun archiveType(file: File): ArchiveType {
val head = runCatching { file.inputStream().use { ByteArray(300).also { b -> it.read(b) } } }.getOrNull() ?: return ArchiveType.UNKNOWN
fun at(i: Int, vararg bytes: Int) = bytes.indices.all { head.getOrNull(i + it) == bytes[it].toByte() }
return when {
at(0, 0x50, 0x4B) -> ArchiveType.ZIP
at(0, 0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C) -> ArchiveType.SEVEN_Z
at(0, 0x1F, 0x8B) || at(0, 0x42, 0x5A, 0x68) || at(0, 0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00) || at(0, 0x28, 0xB5, 0x2F, 0xFD) || at(257, 0x75, 0x73, 0x74, 0x61, 0x72) -> ArchiveType.TAR
else -> ArchiveType.UNKNOWN
}
}
private fun extractTarball(zip: File, into: File): File? = ZipFile(zip).use { z ->
val entries = z.entries().toList().filter { !it.isDirectory }
val entry = entries.filter { TARBALL.containsMatchIn(it.name) }.maxByOrNull { it.size } ?: return null
val name = File(entry.name).name
val sums = checksumEntry(entries.map { it.name }, name)?.let { checksumName -> entries.first { it.name == checksumName } }
val expected = sums?.let { e ->
z.getInputStream(e).use { checksumIn(it.readBytes().decodeToString()) }
?: throw IllegalStateException("${File(e.name).name} holds no SHA-512 checksum")
}
val out = File(into, name)
val digest = MessageDigest.getInstance("SHA-512")
z.getInputStream(entry).use { input -> DigestOutputStream(FileOutputStream(out), digest).use { input.copyTo(it, 1 shl 16) } }
if (expected != null && !expected.equals(digest.digest().joinToString("") { "%02x".format(it) }, ignoreCase = true)) {
out.delete()
throw IllegalStateException("Checksum mismatch in $name")
}
out
}
internal class UnsafeArchiveException : Exception()
internal fun extractDirect(archive: File, into: File, type: ArchiveType) {
val root = into.toPath().toAbsolutePath().normalize()
fun target(name: String): File {
val clean = name.replace('\\', '/')
val parts = clean.split('/')
if (clean.startsWith('/') || parts.any { it == ".." }) throw UnsafeArchiveException()
val path = root.resolve(clean).normalize()
if (!path.startsWith(root)) throw UnsafeArchiveException()
var parent = path.parent
while (parent != null && parent.startsWith(root) && parent != root) {
if (Files.isSymbolicLink(parent)) throw UnsafeArchiveException()
parent = parent.parent
}
return path.toFile()
}
fun applyMode(file: File, mode: Int) {
val permissions = mutableSetOf<PosixFilePermission>()
if (mode and 0x100 != 0) permissions += PosixFilePermission.OWNER_READ
if (mode and 0x80 != 0) permissions += PosixFilePermission.OWNER_WRITE
if (mode and 0x40 != 0) permissions += PosixFilePermission.OWNER_EXECUTE
if (mode and 0x20 != 0) permissions += PosixFilePermission.GROUP_READ
if (mode and 0x10 != 0) permissions += PosixFilePermission.GROUP_WRITE
if (mode and 0x08 != 0) permissions += PosixFilePermission.GROUP_EXECUTE
if (mode and 0x04 != 0) permissions += PosixFilePermission.OTHERS_READ
if (mode and 0x02 != 0) permissions += PosixFilePermission.OTHERS_WRITE
if (mode and 0x01 != 0) permissions += PosixFilePermission.OTHERS_EXECUTE
if (permissions.isNotEmpty()) Files.setPosixFilePermissions(file.toPath(), permissions)
}
val directoryModes = mutableListOf<Pair<File, Int>>()
fun place(name: String, mode: Int, directory: Boolean, content: () -> InputStream) {
val file = target(name)
when {
mode and 0xF000 == 0xA000 -> {
val link = content().use { it.readBytes().decodeToString() }
val parent = file.parentFile ?: throw UnsafeArchiveException()
val climbsLater = link.split('/').filter { it != "." }.dropWhile { it == ".." }.any { it == ".." }
if (link.startsWith('/') || climbsLater || !parent.toPath().resolve(link).normalize().startsWith(root)) throw UnsafeArchiveException()
parent.mkdirs()
Files.deleteIfExists(file.toPath())
Files.createSymbolicLink(file.toPath(), java.nio.file.Paths.get(link))
}
directory -> {
file.mkdirs()
directoryModes += file to mode
}
else -> {
if (Files.isSymbolicLink(file.toPath())) throw UnsafeArchiveException()
file.parentFile?.mkdirs()
content().use { input -> file.outputStream().use { output -> input.copyTo(output, 1 shl 16) } }
applyMode(file, mode)
}
}
}
when (type) {
ArchiveType.ZIP -> CommonsZipFile.builder().setFile(archive).get().use { zip ->
for (entry in zip.entries) place(entry.name, entry.unixMode, entry.isDirectory) { zip.getInputStream(entry) }
}
ArchiveType.SEVEN_Z -> Files.newByteChannel(archive.toPath()).use { channel ->
SevenZFile.builder().setSeekableByteChannel(channel).get().use { seven ->
for (entry in seven.entries) {
val unix = entry.hasWindowsAttributes && entry.windowsAttributes and 0x8000 != 0
place(entry.name, if (unix) entry.windowsAttributes ushr 16 else 0, entry.isDirectory) { seven.getInputStream(entry) }
}
}
}
else -> error("Unsupported direct archive")
}
directoryModes.sortedByDescending { it.first.path.length }.forEach { (directory, mode) -> applyMode(directory, mode) }
}
internal fun checksumIn(text: String): String? = Regex("(?i)\\b[0-9a-f]{128}\\b").find(text)?.value
internal fun checksumEntry(entries: List<String>, tarball: String): String? {
val stem = tarball.substringBefore(".tar")
return entries.firstOrNull {
val name = File(it).name
!TARBALL.containsMatchIn(name) && (name.startsWith("$tarball.") || name.startsWith("$stem.")) && name.contains("sha512", true)
}
}
private fun runGuest(context: Context, command: List<String>): Int {
val guest = listOf(
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "PATH=/usr/local/bin:/usr/bin:/bin",
"LANG=C.UTF-8", "XDG_DATA_HOME=/root/.local/share",
) + command
val child = ProtonExtras.guestProcess(context, guest).start()
child.inputStream.bufferedReader().useLines { lines -> lines.forEach { Log.i(TAG, it) } }
return child.waitFor()
}
}
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.session
import android.content.Context
import android.util.AtomicFile
import android.util.Log
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.core.TextureFiltering
import com.droiddeck.launcher.runtime.LinuxRuntime
@@ -9,6 +10,7 @@ import org.json.JSONObject
import java.io.File
object GameEnvironmentStore {
private const val TAG = "GameEnvironmentStore"
private const val SETTINGS = "game-environment.json"
private const val GUEST_FILE = "root/.config/droiddeck/game-environment.json"
const val DXVK_CONFIG = "dxvkConfig"
@@ -19,7 +21,16 @@ object GameEnvironmentStore {
fun read(context: Context): GameEnvironment.Config {
val file = AtomicFile(File(context.filesDir, SETTINGS))
val bytes = try { file.readFully() } catch (_: java.io.FileNotFoundException) { return GameEnvironment.Config() }
return decode(JSONObject(bytes.toString(Charsets.UTF_8)))
return try {
decode(JSONObject(bytes.toString(Charsets.UTF_8)))
} catch (error: Exception) {
if (error !is org.json.JSONException && error !is IllegalArgumentException) throw error
val aside = File(context.filesDir, "$SETTINGS.unreadable")
Log.w(TAG, "game environment settings are unreadable, set aside as ${aside.name}", error)
aside.delete()
file.baseFile.renameTo(aside)
GameEnvironment.Config()
}
}
fun decode(json: JSONObject): GameEnvironment.Config {
@@ -25,7 +25,7 @@ object GameSaves {
fun label(context: Context): String = context.getString(R.string.saves_layout_zip, app)
}
data class Game(val game: Library.SteamGame, val prefix: File?, val saves: List<SaveDir>) {
data class Game(val game: Library.SteamGame, val prefix: File?, val saves: List<SaveDir>, val root: String? = null) {
val launched get() = prefix?.let { File(it, "drive_c").isDirectory } == true
}
@@ -36,7 +36,28 @@ object GameSaves {
fun savesDir(): File = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "DroidDeck/Saves")
private fun backupsDir(): File = File(savesDir(), "backups")
fun game(game: Library.SteamGame): Game = Game(game, game.protonPrefix, game.protonPrefix?.let { locate(it, game) } ?: emptyList())
fun game(context: Context, game: Library.SteamGame): Game {
val root = if (ubisoft(game)) ubisoftRoot(context, game) else null
val saves = game.protonPrefix?.let { prefix -> if (ubisoft(game)) root?.let { ubisoftSaves(prefix, it) }.orEmpty() else locate(prefix, game) }.orEmpty()
return Game(game, game.protonPrefix, saves, root)
}
fun saves(context: Context, prefix: File, game: Library.SteamGame): List<SaveDir> =
if (ubisoft(game)) ubisoftRoot(context, game)?.let { ubisoftSaves(prefix, it) }.orEmpty() else locate(prefix, game)
private fun ubisoftRoot(context: Context, game: Library.SteamGame): String? {
val product = game.gameFiles?.let { com.droiddeck.launcher.stores.StoreGameSidecar.read(it) }?.extra?.get("productId")?.toLongOrNull() ?: return null
val user = com.droiddeck.launcher.stores.ubisoft.UbisoftAuth.load(context)?.userId
if (user.isNullOrEmpty() || user.contains('/') || user.contains("..")) return null
return "Saved Games/Ubisoft/$user/$product"
}
private fun ubisoft(game: Library.SteamGame) = game.source == com.droiddeck.launcher.stores.Store.UBISOFT.id
private fun ubisoftSaves(prefix: File, rel: String): List<SaveDir> {
val files = File(profile(prefix), rel).walkTopDown().filter { it.isFile }.toList()
return if (files.isEmpty()) emptyList() else listOf(SaveDir(rel, files.size, files.sumOf { it.length() }))
}
private val SAVE_ROOTS = listOf("Documents/My Games", "Saved Games", "AppData/Roaming", "Documents", "AppData/Local", "AppData/LocalLow")
@@ -109,9 +130,11 @@ object GameSaves {
fun export(context: Context, game: Game, layout: Layout, dir: File): Pair<File, Int> {
val prefix = game.prefix ?: error(context.getString(R.string.saves_not_launched, game.game.name))
val roots = game.saves.map { it.relPath }
if (roots.isEmpty() && ubisoft(game.game)) error(context.getString(R.string.saves_none_found, game.game.name))
dir.mkdirs()
val out = File(dir, "${safe(game.game.name)}_${stamp()}.zip")
val count = zipProfile(profile(prefix), game.saves.map { it.relPath }.ifEmpty { null }, layout, out)
val count = zipProfile(profile(prefix), roots.ifEmpty { null }, layout, out)
if (count == 0) { out.delete(); error(context.getString(R.string.saves_none_found, game.game.name)) }
return out to count
}
@@ -142,12 +165,21 @@ object GameSaves {
if (!driveC.isDirectory) error(context.getString(R.string.saves_not_launched, game.game.name))
if (!looksLikeSaveZip(zip)) error(context.getString(R.string.saves_not_save_zip, zip.name))
val scoped = if (ubisoft(game.game)) game.root ?: error(context.getString(R.string.saves_none_found, game.game.name)) else null
if (scoped != null) {
val base = File(profile(prefix), scoped).canonicalFile
val eligible = ZipInputStream(BufferedInputStream(zip.inputStream())).use { zis ->
generateSequence { zis.nextEntry }.any { e -> !e.isDirectory && remap(e.name)?.let { File(driveC, it).canonicalFile.path.startsWith(base.path + File.separator) } == true }
}
if (!eligible) error(context.getString(R.string.saves_not_save_zip, zip.name))
}
backupsDir().mkdirs()
val backup = File(backupsDir(), "${safe(game.game.name)}_${stamp()}.zip")
val backedUp = zipProfile(profile(prefix), null, Layout.GAMEHUB, backup)
val backup = File(backupsDir(), "${safe(game.game.name)}_${stamp()}_${System.currentTimeMillis()}.zip")
val backedUp = if (scoped != null && File(profile(prefix), scoped).walkTopDown().none { it.isFile }) 0
else zipProfile(profile(prefix), scoped?.let(::listOf), Layout.GAMEHUB, backup)
if (backedUp == 0) backup.delete()
val base = driveC.canonicalFile
val base = (if (scoped != null) File(profile(prefix), scoped) else driveC).canonicalFile
var written = 0
ZipInputStream(BufferedInputStream(zip.inputStream())).use { zis ->
var e = zis.nextEntry
@@ -14,10 +14,22 @@ object GpuClockPin {
@Volatile
private var pinned = false
private val supported: Boolean by lazy { File(KGSL_NODE).exists() }
@Volatile
var failed = false
private set
val supported: Boolean by lazy { File(KGSL_NODE).exists() }
private var live = false
@Synchronized
fun start(context: Context): String {
live = true
return hold(context)
}
private fun hold(context: Context): String {
failed = false
if (!SessionPrefs.gpuClockPin(context)) return "gpu clock: governed"
if (!supported) return "gpu clock: no $KGSL_NODE, left governed"
return try {
@@ -28,12 +40,21 @@ object GpuClockPin {
} catch (t: Throwable) {
File(context.filesDir, MARKER).delete()
Log.w(TAG, "pin", t)
failed = true
"gpu clock: pin failed"
}
}
@Synchronized
fun sync(context: Context): String? {
if (!live) return null
if (!SessionPrefs.gpuClockPin(context) && pinned) clear(context)
return hold(context)
}
@Synchronized
fun stop(context: Context) {
live = false
if (pinned) clear(context)
}
@@ -9,13 +9,17 @@ import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.util.Locale
import org.json.JSONArray
import org.json.JSONObject
object ProtonExtras {
private const val TAG = "ProtonExtras"
private const val NEED_BYTES = 4L * 1024 * 1024 * 1024
private const val RELEASES = "https://api.github.com/repos/%s/releases?per_page=15"
private const val RELEASE_PAGE_SIZE = 15
private const val RELEASES = "https://api.github.com/repos/%s/releases?per_page=$RELEASE_PAGE_SIZE&page=%d"
private const val RELEASE_PAGES = 5
private const val RELEASE_TAG = "https://api.github.com/repos/%s/releases/tags/%s"
const val CHECK_EVERY_MS = 60L * 60 * 1000
@Volatile
var installInProgress = false
@@ -26,7 +30,8 @@ object ProtonExtras {
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex)
internal data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long,
val sha256: String? = null)
val sha256: String? = null, val releaseName: String = tag)
internal data class ReleaseFetch(val releases: JSONArray, val complete: Boolean)
const val OWN = "droiddeck"
@@ -120,22 +125,25 @@ object ProtonExtras {
if (due.isEmpty() || !force && (now - lastAttempt) in 0 until RETRY_MS) return false
lastAttempt = now
for (tool in due) {
val tag = findLatestAsset(tool)?.tag ?: continue
cache.put(tool.id, JSONObject().put("tag", tag).put("at", now))
updateLatest(cache, tool, releases(tool), now)
}
runCatching { file.writeText(cache.toString()) }
return true
}
}
internal fun recordLatest(latest: JSONObject, tool: Tool, tag: String, now: Long): Boolean {
val entry = latest.optJSONObject(tool.id)
val known = entry?.optString("tag")
if (!known.isNullOrEmpty() && compareVersions(tag, known) < 0) return false
latest.put(tool.id, JSONObject().put("tag", tag).put("at", now))
return true
}
private fun record(context: Context, tool: Tool, dir: String?, tag: String) {
runCatching {
val latest = readJson(latestFile(context))
val known = latest.optJSONObject(tool.id)?.optString("tag")
if (known.isNullOrEmpty() || compareVersions(tag, known) >= 0) {
latest.put(tool.id, JSONObject().put("tag", tag).put("at", System.currentTimeMillis()))
latestFile(context).writeText(latest.toString())
}
if (recordLatest(latest, tool, tag, System.currentTimeMillis())) latestFile(context).writeText(latest.toString())
if (dir != null) {
val releases = readJson(releasesFile(context))
val present = toolsDir(context).list()?.toSet() ?: emptySet()
@@ -218,7 +226,7 @@ object ProtonExtras {
if (SessionState.running) return context.getString(R.string.pextra_stop_session)
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
val asset = findLatestAsset(tool) ?: return context.getString(R.string.pextra_no_release, tool.name)
val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name)
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
val archive = File(downloads, "${tool.id}-${asset.name}")
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
@@ -277,26 +285,12 @@ object ProtonExtras {
val root = LinuxRuntime.rootDir(context)
LinuxRuntime.writeAccounts(context)
com.droiddeck.launcher.session.SessionFiles.stage(context, root)
val runtimeDir = File(context.filesDir, ".proton-install-rt").apply { mkdirs() }
val guest = listOf(
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "PATH=/usr/local/bin:/usr/bin:/bin",
"LANG=C.UTF-8", "XDG_DATA_HOME=/root/.local/share",
"/usr/local/bin/droiddeck-proton-extra", "/root/.local/share/Steam", archive.absolutePath,
)
val process = if (com.droiddeck.launcher.runtime.NativeGuest.enabled(context)) {
com.droiddeck.launcher.runtime.NativeGuest.processBuilder(context, root,
LinuxRuntime.binds(context, null, runtimeDir, null, null), guest).redirectErrorStream(true)
} else {
ProcessBuilder(LinuxRuntime.command(context, null, runtimeDir, null, guest))
.directory(root)
.redirectErrorStream(true)
.also { builder ->
val hostEnv = builder.environment()
hostEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(context).path
hostEnv["PROOT_TMP_DIR"] = LinuxRuntime.prootTempDir(context).path
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { hostEnv["LD_LIBRARY_PATH"] = it }
}
}
val process = guestProcess(context, guest)
val child = process.start()
var placed: String? = null
child.inputStream.bufferedReader().useLines { lines ->
@@ -331,36 +325,106 @@ object ProtonExtras {
}
}
private fun findLatestAsset(tool: Tool): Asset? {
val releases = Downloader.downloadString(RELEASES.format(tool.repo)) ?: return null
return try {
pickAsset(tool, JSONArray(releases))
} catch (e: Exception) {
Log.w(TAG, "release metadata for ${tool.id}", e)
null
internal fun guestProcess(context: Context, guest: List<String>): ProcessBuilder {
val root = LinuxRuntime.rootDir(context)
val runtimeDir = File(context.filesDir, ".proton-install-rt").apply { mkdirs() }
return if (com.droiddeck.launcher.runtime.NativeGuest.enabled(context)) {
com.droiddeck.launcher.runtime.NativeGuest.processBuilder(context, root,
LinuxRuntime.binds(context, null, runtimeDir, null, null), guest).redirectErrorStream(true)
} else {
ProcessBuilder(LinuxRuntime.command(context, null, runtimeDir, null, guest))
.directory(root)
.redirectErrorStream(true)
.also { builder ->
val hostEnv = builder.environment()
hostEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(context).path
hostEnv["PROOT_TMP_DIR"] = LinuxRuntime.prootTempDir(context).path
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { hostEnv["LD_LIBRARY_PATH"] = it }
}
}
}
internal fun releases(tool: Tool): JSONArray? = releases(tool) { page ->
Downloader.downloadString(RELEASES.format(Locale.ROOT, tool.repo, page))?.let { body ->
try {
JSONArray(body)
} catch (e: Exception) {
Log.w(TAG, "release metadata for ${tool.id}", e)
null
}
}
}
internal fun releases(tool: Tool, fetch: (Int) -> JSONArray?): JSONArray? {
return releasesResult(tool, fetch, stopAtStable = true)?.releases
}
internal fun releasesForRemoval(tool: Tool, fetch: (Int) -> JSONArray? = { page ->
Downloader.downloadString(RELEASES.format(Locale.ROOT, tool.repo, page))?.let { body ->
runCatching { JSONArray(body) }.getOrNull()
}
}): ReleaseFetch? = releasesResult(tool, fetch, stopAtStable = false)
internal fun releaseGone(tool: Tool, tag: String): Boolean =
Downloader.gone(RELEASE_TAG.format(Locale.ROOT, tool.repo, java.net.URLEncoder.encode(tag, "UTF-8").replace("+", "%20"))) == true
private fun releasesResult(tool: Tool, fetch: (Int) -> JSONArray?, stopAtStable: Boolean): ReleaseFetch? {
val all = fetch(1) ?: return null
var page = 1
var last = all.length()
var complete = last < RELEASE_PAGE_SIZE
while (!complete && page < RELEASE_PAGES && (!stopAtStable || pickAsset(tool, all) == null)) {
val next = fetch(++page) ?: return null
for (i in 0 until next.length()) all.put(next.opt(i))
last = next.length()
complete = last < RELEASE_PAGE_SIZE
}
return ReleaseFetch(all, complete)
}
internal fun assets(tool: Tool, array: JSONArray, prerelease: Boolean): List<Asset> {
val releases = (0 until array.length()).mapNotNull { array.optJSONObject(it) }.filter { !it.optBoolean("draft", false) }
val stableAt = releases.filter { !it.optBoolean("prerelease", false) }.maxOfOrNull { it.optString("published_at") }.orEmpty()
return releases
.filter { it.optBoolean("prerelease", false) == prerelease && (!prerelease || it.optString("published_at") > stableAt) }
.mapNotNull { assetOf(tool, it, experimental = prerelease) }
}
internal fun pickAsset(tool: Tool, array: JSONArray): Asset? {
for (i in 0 until array.length()) {
val release = array.getJSONObject(i)
if (release.optBoolean("draft", false) || release.optBoolean("prerelease", false)) continue
val assets = release.optJSONArray("assets") ?: continue
val entries = (0 until assets.length()).map { assets.getJSONObject(it) }
val archive = entries.sortedBy { it.optString("name") }.firstOrNull { tool.assetPattern.containsMatchIn(it.optString("name")) } ?: continue
val candidates = (0 until array.length()).asSequence()
.mapNotNull { array.optJSONObject(it) }
.filter { !it.optBoolean("draft", false) && !it.optBoolean("prerelease", false) }
return candidates.firstNotNullOfOrNull { assetOf(tool, it) }
}
internal fun updateLatest(cache: JSONObject, tool: Tool, array: JSONArray?, now: Long) {
if (array == null) return
val tag = pickAsset(tool, array)?.tag
if (tag == null) {
return
}
cache.put(tool.id, JSONObject().put("tag", tag).put("at", now))
}
internal fun assetOf(tool: Tool, release: JSONObject, requireChecksum: Boolean = false, experimental: Boolean = false): Asset? = try {
val assets = release.optJSONArray("assets")
val entries = assets?.let { list -> (0 until list.length()).mapNotNull { list.optJSONObject(it) } }.orEmpty()
entries.sortedBy { it.optString("name") }.filter {
val name = it.optString("name")
if (experimental && tool.id == OWN) name.startsWith(release.optString("tag_name")) && ExperimentalProtons.TARBALL.containsMatchIn(name) && !ExperimentalProtons.FOREIGN_ARCH.containsMatchIn(name) else tool.assetPattern.containsMatchIn(name)
}.mapNotNull { archive ->
val name = archive.optString("name")
val stem = name.substringBefore(".tar")
val checksum = entries.firstOrNull {
it.optString("name").startsWith(stem) && it.optString("name").contains("sha512", ignoreCase = true)
}?.optString("browser_download_url")?.takeIf { it.startsWith("http") }
return Asset(
release.optString("tag_name"), name,
archive.optString("browser_download_url").takeIf { it.startsWith("http") } ?: continue, checksum,
archive.optLong("size", 0L),
Hashes.githubSha256(archive.optString("digest")),
)
}
return null
archive.optString("browser_download_url").takeIf { it.startsWith("http") }?.let { url ->
Asset(release.optString("tag_name"), name, url, checksum, archive.optLong("size", 0L), Hashes.githubSha256(archive.optString("digest")), release.optString("name").ifEmpty { release.optString("tag_name") })
}
}.let { found -> if (requireChecksum) found.firstOrNull { it.sha256 != null || it.sha512 != null } else found.firstOrNull() }
} catch (e: Exception) {
Log.w(TAG, "release metadata for ${tool.id}", e)
null
}
private fun requestLines(context: Context): List<String> =
@@ -234,8 +234,6 @@ object SessionFiles {
val gpuLoad = listOf(
"usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so" to "usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so",
"usr/local/lib/droiddeck-gpuload/VK_LAYER_DROIDDECK_gpu_load.json" to "usr/share/vulkan/implicit_layer.d/droiddeck_gpu_load.json",
"usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_vramcap.so" to "usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_vramcap.so",
"usr/local/lib/droiddeck-gpuload/VK_LAYER_DROIDDECK_vram_cap.json" to "usr/share/vulkan/implicit_layer.d/droiddeck_vram_cap.json",
)
val fexPreloads = listOf("x86_64", "i386").flatMap { arch ->
listOf("libddsession.so", "libfakeinput.so", "libfaultreport.so").map { "$arch/$it" to "usr/local/lib/droiddeck-fex/$arch/$it" }
@@ -282,6 +280,8 @@ object SessionFiles {
if (installed) ledger.staged(relative, target) else Log.e(TAG, "$relative NOT staged")
}
File(root, "usr/local/bin/bannerlator-steam-compat").delete()
File(root, "usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_vramcap.so").delete()
File(root, "usr/share/vulkan/implicit_layer.d/droiddeck_vram_cap.json").delete()
LegacyNames.migrateRootfs(root)
ComponentsManager.migrateLaunchDir(context)
EsyncPacks.stageBundled(context, root)
@@ -255,6 +255,18 @@ object SessionPrefs {
prefs(context).edit().putBoolean("libraryShowSize", show).apply()
}
fun libraryShowHidden(context: Context): Boolean = prefs(context).getBoolean("libraryShowHidden", false)
fun setLibraryShowHidden(context: Context, show: Boolean) {
prefs(context).edit().putBoolean("libraryShowHidden", show).apply()
}
fun libraryHidden(context: Context): Set<String> = prefs(context).getStringSet("libraryHidden", null)?.toSet().orEmpty()
fun setLibraryHidden(context: Context, keys: Set<String>) {
prefs(context).edit().putStringSet("libraryHidden", keys.toSet()).apply()
}
fun railLabels(context: Context): Boolean = prefs(context).getBoolean("railLabels", false)
fun setRailLabels(context: Context, show: Boolean) {
@@ -306,8 +318,36 @@ object SessionPrefs {
prefs(context).edit().putStringSet("libraryFavorites", keys.toSet()).apply()
}
fun storesTabOrderCustomized(context: Context): Boolean =
prefs(context).getBoolean("storesTabOrderCustomized", false)
fun setStoresTabOrderCustomized(context: Context, customized: Boolean) {
prefs(context).edit().putBoolean("storesTabOrderCustomized", customized).apply()
}
fun storesTabOrder(context: Context): List<String> = idList(prefs(context).getString("storesTabOrder", null))
/** An order nobody arranged stays unsaved, so it keeps following the default. */
fun saveStoresTabs(context: Context, order: List<String>, hidden: Set<String>, arranged: Boolean) {
if (arranged) setStoresTabOrderCustomized(context, true)
if (storesTabOrderCustomized(context)) setStoresTabOrder(context, order)
setStoresTabHidden(context, hidden)
}
private val LEGACY_STORES_TAB_ORDER = listOf("gog", "epic", "amazon", "xbox", "itch", "gamejolt", "battlenet", "ubisoft", "ea", "rockstar")
/**
* Forgets an order the user never arranged, so the Stores tabs and Library pills follow whatever the default is now.
* Earlier versions saved the default of their day, which is why a saved order alone does not mean the user chose it.
*/
fun settleStoresTabOrder(context: Context, defaults: List<String>) {
if (storesTabOrderCustomized(context)) return
val saved = storesTabOrder(context)
if (saved.isEmpty()) return
if (saved == LEGACY_STORES_TAB_ORDER || saved == defaults) prefs(context).edit().remove("storesTabOrder").apply()
else setStoresTabOrderCustomized(context, true)
}
fun setStoresTabOrder(context: Context, order: List<String>) {
prefs(context).edit().putString("storesTabOrder", order.joinToString(",")).apply()
}
@@ -657,14 +697,42 @@ object SessionPrefs {
}
@JvmStatic
fun ensurePowerVrAutoDrivers(context: Context) {
if (com.droiddeck.launcher.core.DeviceSupport.openDriverActive(context)) return
ensurePowerVrAutoDrivers(context, SystemVulkanDriver.isPowerVr())
fun ensurePowerVrAutoDrivers(context: Context) = reconcilePowerVrAutoDrivers(
context, SystemVulkanDriver.isPowerVr(), SystemVulkanDriver.isXclipse(),
com.droiddeck.launcher.gpu.VulkanInfo::cachedOrNull,
)
fun ensurePowerVrAutoDriversAfterGpuQuery(context: Context) = reconcilePowerVrAutoDrivers(
context, SystemVulkanDriver.isPowerVr(), SystemVulkanDriver.isXclipse(),
com.droiddeck.launcher.gpu.VulkanInfo::query,
)
internal fun reconcilePowerVrAutoDrivers(
context: Context, powerVr: Boolean, xclipse: Boolean, vulkan: () -> Map<String, String>?,
) {
val device = if (xclipse) vulkan() ?: return else null
val unsupported = unsupportedXclipse(xclipse) {
com.droiddeck.launcher.gpu.GpuInfo.systemDriverName(SystemVulkanDriver.gpuName(), device)
}
val activeKey = com.droiddeck.launcher.gpu.DriverBundle.active(context)
?.id
?.let(com.droiddeck.launcher.gpu.DriverPairs::nonAdreno)
val upstreamBundle = activeKey == com.droiddeck.launcher.gpu.DriverPairs.NAD_RADV_XCLIPSE_UPSTREAM ||
(activeKey != null && activeKey.startsWith("${com.droiddeck.launcher.gpu.DriverPairs.NAD_RADV_XCLIPSE_UPSTREAM}-"))
if (com.droiddeck.launcher.core.DeviceSupport.openDriverActive(context) && (!unsupported || upstreamBundle)) return
ensurePowerVrAutoDrivers(context, powerVr, unsupported)
}
internal fun ensurePowerVrAutoDrivers(context: Context, powerVr: Boolean) {
internal fun unsupportedXclipse(xclipse: Boolean, gpuName: () -> String): Boolean =
xclipse && com.droiddeck.launcher.gpu.DriverPairs.xclipseNeedsUpstream(gpuName())
internal fun ensurePowerVrAutoDrivers(context: Context, powerVr: Boolean, autoOwnedOnly: Boolean = false) {
if (!powerVr || gpuDriverMode(context) != GPU_DRIVERS_AUTO) return
prefs(context).edit().putString("linuxDriver", "").putString("androidDriver", TurnipDriver.AUTO).apply()
val owned = gpuAutoInstalled(context)
val edit = prefs(context).edit()
if (!autoOwnedOnly || linuxDriver(context) in owned) edit.putString("linuxDriver", "")
if (!autoOwnedOnly || androidDriver(context) in owned) edit.putString("androidDriver", TurnipDriver.AUTO)
edit.apply()
}
fun gpuAutoInstalled(context: Context): Set<String> =
@@ -704,7 +772,7 @@ object SessionPrefs {
val prefs = prefs(context)
if (!prefs.contains("shaderPrecache")) {
if (steamConfig(context).exists()) return null
prefs.edit().putBoolean("shaderPrecache", false).apply()
prefs.edit().putBoolean("shaderPrecache", true).apply()
}
val on = prefs.getBoolean("shaderPrecache", true)
val applied = shaderPrecacheApplied(context)
@@ -864,29 +932,6 @@ object SessionPrefs {
prefs(context).edit().putBoolean("gamescopeRealtime", on).apply()
}
fun ramCapMb(context: Context): Int = prefs(context).getInt("ramCapMb", 0).coerceAtLeast(0)
fun setRamCapMb(context: Context, mb: Int) {
prefs(context).edit().putInt("ramCapMb", mb.coerceAtLeast(0)).apply()
}
fun zramClient(context: Context): Boolean = prefs(context).getBoolean("zramClient", true)
fun setZramClient(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("zramClient", on).apply()
}
fun zramIdle(context: Context): Boolean = prefs(context).getBoolean("zramIdle", true)
fun setZramIdle(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("zramIdle", on).apply()
}
fun vramCapMb(context: Context): Int = prefs(context).getInt("vramCapMb", 0).coerceAtLeast(0)
fun setVramCapMb(context: Context, mb: Int) {
prefs(context).edit().putInt("vramCapMb", mb.coerceAtLeast(0)).apply()
}
fun gpuClockPin(context: Context): Boolean = prefs(context).getBoolean("gpuClockPin", false)
@@ -1416,6 +1461,8 @@ object SessionPrefs {
(id and 0xFFFFFFFFL) to key.removePrefix("addedAppId:")
}.toMap()
fun storeGameFolder(context: Context, key: String): String? = prefs(context).getString("storeFolder:$key", null)
fun followStoreGame(context: Context, key: String, folderPath: String, gone: (String) -> Boolean) = synchronized(addedGameLock) {
val p = prefs(context)
val previous = p.getString("storeFolder:$key", null)
@@ -1487,6 +1534,45 @@ object SessionPrefs {
prefs(context).edit().putInt("gradientPrimary", primary).putInt("gradientSecondary", secondary).apply()
}
fun customThemeColors(context: Context): com.droiddeck.launcher.ui.CustomThemeColors =
prefs(context).let { p ->
val defaults = com.droiddeck.launcher.ui.CustomThemeColors()
com.droiddeck.launcher.ui.CustomThemeColors(
background = p.getInt("customThemeBackground", defaults.background),
surface = p.getInt("customThemeSurface", defaults.surface),
surfaceVariant = p.getInt("customThemeSurfaceVariant", defaults.surfaceVariant),
line = p.getInt("customThemeLine", defaults.line),
line2 = p.getInt("customThemeLine2", defaults.line2),
onBackground = p.getInt("customThemeOnBackground", defaults.onBackground),
onSurfaceVariant = p.getInt("customThemeOnSurfaceVariant", defaults.onSurfaceVariant),
primary = p.getInt("customThemePrimary", defaults.primary),
onPrimary = p.getInt("customThemeOnPrimary", defaults.onPrimary),
signal = p.getInt("customThemeSignal", defaults.signal),
good = p.getInt("customThemeGood", defaults.good),
error = p.getInt("customThemeError", defaults.error),
)
}
fun setCustomThemeColors(
context: Context,
colors: com.droiddeck.launcher.ui.CustomThemeColors,
) {
prefs(context).edit()
.putInt("customThemeBackground", colors.background)
.putInt("customThemeSurface", colors.surface)
.putInt("customThemeSurfaceVariant", colors.surfaceVariant)
.putInt("customThemeLine", colors.line)
.putInt("customThemeLine2", colors.line2)
.putInt("customThemeOnBackground", colors.onBackground)
.putInt("customThemeOnSurfaceVariant", colors.onSurfaceVariant)
.putInt("customThemePrimary", colors.primary)
.putInt("customThemeOnPrimary", colors.onPrimary)
.putInt("customThemeSignal", colors.signal)
.putInt("customThemeGood", colors.good)
.putInt("customThemeError", colors.error)
.apply()
}
fun trueBlackHighlight(context: Context): Int =
prefs(context).getInt("trueBlackHighlight", com.droiddeck.launcher.ui.Themes.DEFAULT_HIGHLIGHT)
@@ -1530,7 +1616,7 @@ object SessionPrefs {
}
val upscalerChoices = listOf(
0 to "Linear", 2 to "Nearest", 4 to "AMD FSR 1", 3 to "Snapdragon GSR",
2 to "Nearest", 0 to "Linear", 4 to "AMD FSR 1", 3 to "Snapdragon GSR",
8 to "Snapdragon GSR (quality)", 7 to "NVIDIA NIS", 6 to "Sharpen only",
)
@@ -1545,12 +1631,12 @@ object SessionPrefs {
fun canonicalUpscaler(mode: Int): Int = when (mode) {
1 -> 0
5 -> 4
else -> mode.takeIf { m -> upscalerChoices.any { it.first == m } } ?: 0
else -> mode.takeIf { m -> upscalerChoices.any { it.first == m } } ?: 2
}
fun upscalerHasSharpness(mode: Int): Boolean = canonicalUpscaler(mode) in 3..8
fun upscaler(context: Context): Int = canonicalUpscaler(prefs(context).getInt("upscaler", 0))
fun upscaler(context: Context): Int = canonicalUpscaler(prefs(context).getInt("upscaler", 2))
fun setUpscaler(context: Context, mode: Int) {
prefs(context).edit().putInt("upscaler", canonicalUpscaler(mode)).apply()
@@ -417,10 +417,12 @@ class SessionService : Service() {
SessionPrefs.screenEffectsProfileId(SessionState.mode, resolvedGameId, SessionState.program),
)
com.droiddeck.launcher.stores.battlenet.BattleNetClient.clearRequests(LinuxRuntime.sessionRoot(this))
val gen = synchronized(stopLock) {
SessionState.steamClientArch = null
SessionState.running = true
++sessionGen
val gen = synchronized(SessionState.startLock) {
synchronized(stopLock) {
SessionState.steamClientArch = null
SessionState.running = true
++sessionGen
}
}
if (SessionState.stopRequested) {
stopSession(0)
@@ -497,7 +499,7 @@ class SessionService : Service() {
private fun runSession(gen: Int) {
SessionPrefs.ensurePowerVrAutoDrivers(this)
SessionPrefs.ensurePowerVrAutoDriversAfterGpuQuery(this)
if (!com.droiddeck.launcher.core.DeviceSupport.adreno()) {
com.droiddeck.launcher.gpu.VulkanInfo.query()["api"]?.let { SessionPrefs.setHostVulkanApi(this, it) }
if (SessionPrefs.venus(this)) VenusComponent.hostVulkanTooOld(this)?.let {
@@ -566,10 +568,19 @@ class SessionService : Service() {
SessionFiles.stage(this, root, startsSession = true)
} catch (error: Exception) {
Log.e(TAG, "Could not prepare the session graphics runtime", error)
failSession(gen, "GRAPHICS_RUNTIME_FAILED", getString(R.string.session_graphics_runtime_failed), -1)
stopSession(-1, gen)
return
}
if (!stillStarting()) {
Log.i(TAG, "session stopped while its files were staging")
return
}
SessionArtifacts.awaitCollections()
if (!stillStarting()) {
Log.i(TAG, "session stopped while earlier session logs were being collected")
return
}
SessionArtifacts.finishAbandoned(this, beforeGuestStart = true)
VacDiagnostics.arm(this)
com.droiddeck.launcher.agent.AgentGuest.reset(this)
@@ -581,7 +592,9 @@ class SessionService : Service() {
SessionEvents.step("game-environment") { GameEnvironmentStore.publish(this) }
} catch (e: Exception) {
Log.e(TAG, "could not publish the game environment", e)
failSession(gen, "GAME_ENVIRONMENT_FAILED", getString(R.string.session_game_environment_failed), -1)
stopSession(-1, gen)
abandonStart(gen, sessionDir)
return
}
val sessionLog = File(sessionDir, "session.log")
@@ -610,6 +623,7 @@ class SessionService : Service() {
Log.e(TAG, "Could not resolve the selected Linux Vulkan driver", e)
failSession(gen, "VULKAN_DRIVER_UNAVAILABLE", e.message ?: "Selected Linux Vulkan driver is unavailable", -1)
stopSession(-1, gen)
abandonStart(gen, sessionDir)
return
}
if (steamHere) guest.add("DD_EPIC_APP_ID=" + com.droiddeck.launcher.stores.epic.EpicClient.shortcutAppId)
@@ -710,6 +724,7 @@ class SessionService : Service() {
if (program.isNullOrEmpty()) {
Log.e(TAG, "run mode without a program")
stopSession(65, gen)
abandonStart(gen, sessionDir)
return
}
guest.add(program)
@@ -805,15 +820,25 @@ class SessionService : Service() {
components.add(deviceControls)
if (gen != sessionGen || !SessionState.running) {
Log.i(TAG, "session stopped while it was starting; not launching it")
if (gen == sessionGen) components.clear()
abandonStart(gen, sessionDir)
return
}
val started = ArrayList<SessionPart>()
try {
components.forEach { it.start() }
for (part in components.toList()) {
if (!stillStarting()) {
Log.i(TAG, "session stopped while its components were starting; stopping the ${started.size} already started")
abandonStart(gen, sessionDir, started)
return
}
started.add(part)
part.start()
}
} catch (e: Exception) {
Log.e(TAG, "Could not start the session components", e)
failSession(gen, "COMPONENT_START_FAILED", e.message ?: "Session component could not be started", -1)
stopSession(-1, gen)
abandonStart(gen, sessionDir, started)
return
}
@@ -840,9 +865,8 @@ class SessionService : Service() {
launchWatcher = null
syncWatcher?.stopWatching()
syncWatcher = null
components.reversed().forEach { runCatching { it.stop() } }
components.clear()
}
abandonStart(gen, sessionDir, started)
if (pid > 1) Thread({ teardown(pid) }, "session-teardown").start()
return
}
@@ -854,6 +878,7 @@ class SessionService : Service() {
SessionEvents.record("guest.start_failed", mapOf("pid" to pid))
failSession(gen, "GUEST_START_FAILED", "The guest process could not be started", pid)
stopSession(-1, gen)
abandonStart(gen, sessionDir, started)
return
}
if (gen == sessionGen && SessionState.running) {
@@ -888,10 +913,9 @@ class SessionService : Service() {
))
}
},
readBackAllowed = { SessionPrefs.ramCapMb(this) == 0 },
pagedIn = { processes, swapKb, swapBeforeKb, availableKb, millis ->
if (processes == 0) {
Log.i(TAG, "left ${swapBeforeKb / 1024} MB in zram after resume (RAM cap, or ${availableKb / 1024} MB available is too little)")
Log.i(TAG, "left ${swapBeforeKb / 1024} MB in zram after resume (${availableKb / 1024} MB available is too little)")
} else {
Log.i(TAG, "read back $processes processes in $millis ms: zram ${swapBeforeKb / 1024} -> ${swapKb / 1024} MB")
}
@@ -908,6 +932,30 @@ class SessionService : Service() {
}
}
private fun abandonStart(gen: Int, sessionDir: File, started: List<SessionPart> = emptyList()) {
val (ended, endedArch) = synchronized(stopLock) {
if (gen != sessionGen || SessionState.running) return
components.clear()
GpuClockPin.stop(this)
GameThreadHints.stop()
com.droiddeck.launcher.stores.StoreLaunchRequests.stop()
MemoryLog.stop()
val ended = synchronized(SessionPaths) {
if (SessionPaths.current() == sessionDir) SessionPaths.take() else null
}
if (ended != null) SessionArtifacts.collectionStarted(ended)
ended to SessionState.steamClientArch
}
started.asReversed().forEach {
try {
it.stop()
} catch (e: Exception) {
Log.w(TAG, "stopping ${it.javaClass.simpleName}", e)
}
}
if (ended != null) Thread({ collectSessionArtifacts(ended, endedArch) }, "session-collect").start()
}
private fun openSessionFolder(): File {
val sessionDir = SessionPaths.beginOrCurrent(this)
val sessionLog = File(sessionDir, "session.log")
@@ -1038,11 +1086,7 @@ class SessionService : Service() {
relativeMouseForSession().takeIf { it != 0 }?.let { guest.add("gamescope_relative_mouse=$it") }
if (com.droiddeck.launcher.core.ZramSupport.supported()) {
guest.add("DD_ZRAM=1")
if (steamHere) SessionPrefs.ramCapMb(this).takeIf { it > 0 }?.let { guest.add("DD_RAM_CAP_MB=$it") }
if (!SessionPrefs.zramClient(this)) guest.add("DD_ZRAM_CLIENT=0")
if (!SessionPrefs.zramIdle(this)) guest.add("DD_ZRAM_IDLE=0")
}
SessionPrefs.vramCapMb(this).takeIf { it > 0 }?.let { guest.add("DD_VRAM_MB=$it") }
guest.add("AUDIO_DIRECT_DECAY=0")
val extra = extraEnv() + agentEnvironment
guest.addAll(TurnipEnvironment.gameEnvironment(tuOverride, tuDriver, SessionPrefs.tuSysmem(this), extra))
@@ -43,6 +43,8 @@ object SessionState {
@Volatile
var stopRequested = false
val startLock = Any()
@Volatile
var running = false
@Volatile
@@ -27,7 +27,6 @@ internal class SessionSuspendController(
private val nowNanos: () -> Long = System::nanoTime,
private val pagedOut: (processes: Int, unacknowledged: Int, residentKb: Long, swapKb: Long, swapBeforeKb: Long, millis: Long) -> Unit =
{ _, _, _, _, _, _ -> },
private val readBackAllowed: () -> Boolean = { true },
private val pagedIn: (processes: Int, swapKb: Long, swapBeforeKb: Long, availableKb: Long, millis: Long) -> Unit =
{ _, _, _, _, _ -> },
) {
@@ -278,12 +277,21 @@ internal class SessionSuspendController(
private fun pageOut(records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>) {
val control = zramControl?.takeIf { it.isFile } ?: return
val hold = holdFile(control)
try {
addSnapshot(records, root, helpers)
control.writeText("1")
hold.writeText(PAGE_OUT_REQUEST)
sleep(PAGE_OUT_POLL_MS)
pageOut(control, records, root, helpers)
} catch (_: IOException) {
return
} finally {
hold.delete()
}
}
private fun holdFile(control: File) = File(control.parentFile, "${control.name}.hold")
private fun pageOut(control: File, records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>) {
addSnapshot(records, root, helpers)
val targets = records.values.filter { record ->
try {
File(procRoot, "${record.pid}/maps").useLines { lines -> lines.any { it.endsWith("/libddsession.so") } }
@@ -301,16 +309,22 @@ internal class SessionSuspendController(
val waiting = targets.toMutableList()
while (!closing && !cancelled && nowMillis() - start < PAGE_OUT_TIMEOUT_MS) {
val started = nowMillis() - start >= PAGE_OUT_START_MS
waiting.removeAll { val ack = acks.getValue(it); ack.length() > 0 || (started && !ack.exists()) || isGone(it) }
waiting.removeAll { val ack = acks.getValue(it); pagedOut(ack) || (started && !ack.exists()) || isGone(it) }
if (waiting.isEmpty()) break
sleep(PAGE_OUT_POLL_MS)
}
val unacknowledged = targets.count { acks.getValue(it).length() == 0L && !isGone(it) }
val unacknowledged = targets.count { !pagedOut(acks.getValue(it)) && !isGone(it) }
acks.values.forEach { it.delete() }
val after = memoryKb(targets)
pagedOut(targets.size, unacknowledged, after.first, after.second, before.second, nowMillis() - start)
}
private fun pagedOut(ack: File): Boolean = try {
ack.readText().trim() == PAGE_OUT_ACK
} catch (_: IOException) {
false
}
private fun readBack() {
val targets = pagedOutTargets.filterNot { isGone(it) }
pagedOutTargets = emptyList()
@@ -318,13 +332,15 @@ internal class SessionSuspendController(
if (targets.isEmpty() || closing) return
val before = memoryKb(targets).second
val (total, available) = meminfoKb()
if (!readBackAllowed() || !canTake(before, total, available)) {
if (!canTake(before, total, available)) {
pagedIn(0, before, before, available, 0)
return
}
val hold = holdFile(control)
try {
control.writeText("0")
hold.writeText(READ_BACK_REQUEST)
} catch (_: IOException) {
hold.delete()
return
}
val start = nowMillis()
@@ -341,6 +357,8 @@ internal class SessionSuspendController(
}
} catch (_: InterruptedException) {
Thread.currentThread().interrupt()
} finally {
hold.delete()
}
pagedIn(targets.size, swap, before, available, nowMillis() - start)
}
@@ -456,6 +474,9 @@ internal class SessionSuspendController(
const val SIGSTOP = 19
const val SIGCONT = 18
const val SIGURG = 23
const val PAGE_OUT_ACK = "1"
const val PAGE_OUT_REQUEST = "1"
const val READ_BACK_REQUEST = "0"
const val PAGE_OUT_POLL_MS = 100L
const val PAGE_OUT_START_MS = 2_000L
const val PAGE_OUT_TIMEOUT_MS = 12_000L
@@ -18,9 +18,9 @@ object SettingsReset {
"storesInstallLanguage",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController",
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
"stretch16x9", "picturePosition", "integerScaling", "railLabels", "navTabOrder", "navTabShelved", "navTabHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"stretch16x9", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores", "ramCapMb", "vramCapMb", "zramClient", "zramIdle",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "nativeUserland", "cursorComposite",
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics", "buildWatermark",
@@ -40,8 +40,9 @@ object SteamGameProcess {
val appId = args.getOrNull(i + 1)
?.takeIf { it.startsWith("AppId=") }
?.removePrefix("AppId=")
val launchOptions = args.drop(i + 2).takeWhile { it != "--" }
if (appId == expectedAppId) return true
if (appId == expectedAppId && "Install=1" !in launchOptions) return true
}
if (args[i] == "-applaunch" &&
@@ -71,7 +71,10 @@ class StorageReport(
val kept: List<KeptPrefix>,
val leftoversChecked: Boolean,
val storeGames: List<StoreGameUsage> = emptyList(),
val systemCaches: List<SystemCacheUsage> = emptyList(),
val checkouts: List<CheckoutUsage> = emptyList(),
) {
val systemCacheBytes: Long get() = systemCaches.sumOf { it.bytes }
val otherPrefixes: Long get() = kept.sumOf { it.bytes }
val droiddeck: Long get() = buckets.values.sum()
val installedShaders: Long get() = games.sumOf { it.shaders }
@@ -358,6 +361,9 @@ object StorageScan {
val stores = m(File(rootfs, "root/Games"))
val flatpak = m(File(rootfs, "root/.local/share/flatpak"))
val rootfsBytes = m(rootfs)
val systemCaches = SystemCaches.find(rootfs, clientRoots, System.currentTimeMillis())
.map { (kind, found) -> SystemCacheUsage(kind, found, found.sumOf { walker.measure(it) }) }.filter { it.bytes > 0 }
val checkouts = SystemCaches.checkouts(rootfs).map { CheckoutUsage(it, walker.measure(it)) }.sortedByDescending { it.bytes }
val privateBytes = privateRoots.sumOf { m(it) }
val system = rootfsBytes - installs - inApps("compatdata") - inApps("shadercache") - workshop -
compatTools - stores - flatpak
@@ -381,7 +387,7 @@ object StorageScan {
),
prefixes, shaders, workshop, flatpak,
games.sortedByDescending { it.total }, tools.values.toList(), leftovers, logs, logBytes,
components, flatpakApps, flatpakRuntimes, kept, everyLibraryRead, storeGames,
components, flatpakApps, flatpakRuntimes, kept, everyLibraryRead, storeGames, systemCaches, checkouts,
)
}
}
@@ -15,7 +15,7 @@ import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.StoreGameSidecar
enum class CleanItem { OLD_TOOLS, LEFTOVERS, LEFTOVERS_UNSURE, LOGS, UNUSED_CUSTOM, UNUSED_COMPONENTS, SHADERS }
enum class CleanItem { OLD_TOOLS, LEFTOVERS, LEFTOVERS_UNSURE, LOGS, SYSTEM_CACHES, UNUSED_CUSTOM, UNUSED_COMPONENTS, SHADERS }
object StorageState {
private const val TAG = "StorageState"
@@ -61,8 +61,17 @@ object StorageState {
}, "storage-store-sizes").start()
}
/** The last scan's overview from disk, shown until this run's first scan lands. */
var saved by mutableStateOf<StorageSummary?>(null)
private set
private fun publish(app: Context, result: StorageReport) {
report = result
val summary = StorageSummary.of(result)
saved = summary
Thread({
runCatching { StorageSummary.file(app.filesDir).writeText(summary.toJson()) }.onFailure { Log.w(TAG, "could not keep the storage summary", it) }
}, "storage-summary").start()
val live = result.storeGames.mapTo(HashSet()) { sizeKey(it) }
storeSizes.keys.retainAll(live)
measureStoreGames(app)
@@ -88,6 +97,9 @@ object StorageState {
fun refresh(context: Context, force: Boolean = false) {
val current = report
if (current == null && saved == null) {
saved = runCatching { StorageSummary.fromJson(StorageSummary.file(context.applicationContext.filesDir).readText()) }.getOrNull()
}
if (scanning || cleaning) {
if (force) refreshAgain = true
return
@@ -122,9 +134,10 @@ object StorageState {
CleanItem.UNUSED_CUSTOM -> report.unusedTools.filter { it.reason == ToolReason.CUSTOM }.sumOf { it.bytes }
CleanItem.UNUSED_COMPONENTS -> report.unusedComponents.sumOf { it.bytes }
CleanItem.SHADERS -> report.installedShaders
CleanItem.SYSTEM_CACHES -> report.systemCacheBytes
}
val SAFE = setOf(CleanItem.OLD_TOOLS, CleanItem.LEFTOVERS, CleanItem.LOGS)
val SAFE = setOf(CleanItem.OLD_TOOLS, CleanItem.LEFTOVERS, CleanItem.LOGS, CleanItem.SYSTEM_CACHES)
fun safeBytes(report: StorageReport): Long = SAFE.sumOf { bytes(report, it) }
@@ -200,10 +213,19 @@ object StorageState {
true
})
/**
* Whether a kept prefix may be removed. A store app's prefix can go, as Wine makes a new one and the app can be set up
* again, but not while a store game is installed inside it, as Battle.net does on drive C, or while a download may write to it.
*/
internal fun keptRemovable(report: StorageReport, prefix: KeptPrefix): Boolean =
prefix.owner != PrefixOwner.LAUNCHER || (report.storeGames.none { it.game.folder.path.startsWith(prefix.dir.path + "/") } &&
!com.droiddeck.launcher.stores.download.DownloadQueue.anyActive())
fun resetKept(context: Context, prefix: KeptPrefix) = act(context, "kept-${prefix.dir.name}", { _, fresh ->
val dir = fresh.kept.firstOrNull { it.dir.path == prefix.dir.path && it.owner == prefix.owner }
?.takeIf { it.owner == PrefixOwner.SHARED || it.owner == PrefixOwner.GAME }?.dir ?: return@act false
check(FileOps.delete(dir)) { "cannot delete $dir" }
val kept = fresh.kept.firstOrNull { it.dir.path == prefix.dir.path && it.owner == prefix.owner }
?.takeIf { keptRemovable(fresh, it) } ?: return@act false
val reset = kept.owner == PrefixOwner.SHARED || kept.owner == PrefixOwner.GAME
(listOf(kept.dir) + listOfNotNull(kept.shaders?.takeUnless { reset })).forEach { check(FileOps.delete(it)) { "cannot delete $it" } }
true
})
@@ -225,9 +247,25 @@ object StorageState {
com.droiddeck.launcher.stores.StoresState.uninstall(app, next.game) { uninstallNext(app, rest.drop(1)) }
}
/** Clears one cache, as found by a fresh scan, so a file that became busy since stays. */
fun clearSystemCache(context: Context, kind: SystemCache) = act(context, "cache-$kind", { _, fresh ->
val files = fresh.systemCaches.firstOrNull { it.kind == kind }?.files.orEmpty()
files.forEach { FileOps.delete(it) }
files.isNotEmpty()
})
/** Deletes a checkout the fresh scan still lists, and the main repository's record of it if it was a worktree. */
fun removeCheckout(context: Context, dir: java.io.File) = act(context, "checkout-${dir.name}", { app, fresh ->
val checkout = fresh.checkouts.firstOrNull { it.dir.path == dir.path } ?: return@act false
val record = SystemCaches.worktreeRecord(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app), checkout.dir)
check(FileOps.delete(checkout.dir)) { "cannot delete ${checkout.dir}" }
record?.let { FileOps.delete(it) }
true
})
fun removeDirs(context: Context, dirs: List<java.io.File>) = act(context, "remove-${dirs.size}", { _, fresh ->
val allowed = (fresh.games.flatMap { it.shaderDirs + listOfNotNull(it.prefixDir) } + fresh.leftovers.flatMap { listOfNotNull(it.prefix, it.shaders) } +
fresh.kept.filter { it.owner == PrefixOwner.SHARED || it.owner == PrefixOwner.GAME }.flatMap { listOfNotNull(it.dir, it.shaders) }).mapTo(HashSet()) { it.path }
fresh.kept.filter { keptRemovable(fresh, it) }.flatMap { listOfNotNull(it.dir, it.shaders) }).mapTo(HashSet()) { it.path }
val wanted = dirs.distinctBy { it.path }
val targets = wanted.filter { it.path in allowed }
if (targets.size < wanted.size) Log.w(TAG, "kept ${wanted.size - targets.size} folders that are no longer safe to remove")
@@ -283,6 +321,7 @@ object StorageState {
CleanItem.LEFTOVERS_UNSURE -> report.leftovers.filter { !it.safe }.forEach(::deleteLeftover)
CleanItem.LOGS -> report.logs.forEach { FileOps.delete(it) }
CleanItem.SHADERS -> report.games.flatMap { it.shaderDirs }.forEach { FileOps.delete(it) }
CleanItem.SYSTEM_CACHES -> report.systemCaches.flatMap { it.files }.forEach { FileOps.delete(it) }
}
}
@@ -0,0 +1,54 @@
package com.droiddeck.launcher.storage
import org.json.JSONObject
import java.io.File
/**
* What the Storage overview shows, kept on disk so the page opens at once after DroidDeck restarts, as it does on
* every update, while a fresh scan of the whole userland runs behind it.
*/
class StorageSummary(
val at: Long, val total: Long, val free: Long, val buckets: Map<Bucket, Long>, val safe: Long,
val games: Int, val gamesOnSd: Int, val prefixes: Long, val workshop: Long, val shaders: Long,
val tools: Int, val unusedTools: Long, val components: Int, val unusedComponents: Long,
val storeGames: Int, val flatpakApps: Int, val flatpakShared: Long, val logBytes: Long, val systemClearable: Long,
) {
val droiddeck: Long get() = buckets.values.sum()
fun toJson(): String = JSONObject().apply {
put("v", VERSION)
put("at", at); put("total", total); put("free", free); put("safe", safe)
put("buckets", JSONObject().apply { buckets.forEach { (b, v) -> put(b.name, v) } })
put("games", games); put("gamesOnSd", gamesOnSd); put("prefixes", prefixes); put("workshop", workshop); put("shaders", shaders)
put("tools", tools); put("unusedTools", unusedTools); put("components", components); put("unusedComponents", unusedComponents)
put("storeGames", storeGames); put("flatpakApps", flatpakApps); put("flatpakShared", flatpakShared)
put("logBytes", logBytes); put("systemClearable", systemClearable)
}.toString()
companion object {
private const val VERSION = 1
fun of(r: StorageReport) = StorageSummary(
r.at, r.total, r.free, r.buckets, StorageState.safeBytes(r),
r.games.size, r.gamesOnSd, r.prefixes, r.workshop, r.shaders,
r.tools.size, r.unusedTools.sumOf { it.bytes }, r.components.size, r.unusedComponents.sumOf { it.bytes },
r.storeGames.size, r.flatpakApps.size, r.flatpakRuntimes + r.flatpakCache, r.logBytes,
r.systemCacheBytes + r.checkouts.sumOf { it.bytes },
)
/** A summary another version wrote, or a damaged file, reads as none, so the page measures as before. */
fun fromJson(text: String): StorageSummary? = runCatching {
val o = JSONObject(text)
if (o.optInt("v") != VERSION) return null
val b = o.getJSONObject("buckets")
StorageSummary(
o.getLong("at"), o.getLong("total"), o.getLong("free"), Bucket.entries.associateWith { b.optLong(it.name) }, o.getLong("safe"),
o.getInt("games"), o.getInt("gamesOnSd"), o.getLong("prefixes"), o.getLong("workshop"), o.getLong("shaders"),
o.getInt("tools"), o.getLong("unusedTools"), o.getInt("components"), o.getLong("unusedComponents"),
o.getInt("storeGames"), o.getInt("flatpakApps"), o.getLong("flatpakShared"), o.getLong("logBytes"), o.getLong("systemClearable"),
)
}.getOrNull()
fun file(filesDir: File) = File(filesDir, "storage-summary.json")
}
}
@@ -0,0 +1,58 @@
package com.droiddeck.launcher.storage
import java.io.File
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.attribute.BasicFileAttributes
/** Parts of the Linux userland that the system and Steam make again when needed, so clearing them loses nothing. */
enum class SystemCache { TEMP, PACKAGES, STEAM_WEB, STEAM_CORRUPT }
class SystemCacheUsage(val kind: SystemCache, val files: List<File>, val bytes: Long)
/** A git checkout in the home folder, such as one the agent made with `git worktree add`. */
class CheckoutUsage(val dir: File, val bytes: Long)
object SystemCaches {
/** Temporary files nothing has touched for a day belong to no program still running. */
const val TEMP_IDLE_MS = 24L * 60 * 60 * 1000
/**
* What each cache would delete. In /tmp, hidden entries (X11, ICE and other sockets' folders) stay, as does
* anything changed within [TEMP_IDLE_MS] or holding a socket or pipe. apt keeps only its downloaded packages
* here, and Steam's web cache and the download chunks it set aside as corrupt come back or are not needed.
*/
fun find(rootfs: File, steamRoots: List<File>, now: Long): Map<SystemCache, List<File>> = linkedMapOf(
SystemCache.TEMP to File(rootfs, "tmp").listFiles().orEmpty().filter { !it.name.startsWith(".") && idle(it, now) },
SystemCache.PACKAGES to File(rootfs, "var/cache/apt/archives").let { dir ->
dir.listFiles().orEmpty().filter { it.isFile && it.name.endsWith(".deb") } + File(dir, "partial").listFiles().orEmpty()
},
SystemCache.STEAM_WEB to steamRoots.map { File(it, "config/htmlcache") }.filter { it.isDirectory },
SystemCache.STEAM_CORRUPT to steamRoots.map { File(it, "steamapps/corrupt") }.filter { it.isDirectory },
)
/** The home folder's git checkouts but the DroidDeck source, which the Agent tab's own entry covers. */
fun checkouts(rootfs: File): List<File> = File(rootfs, "root").listFiles().orEmpty()
.filter { it.isDirectory && it.name != "DroidDeck" && File(it, ".git").exists() }
/**
* The main repository's record of a worktree, which `git worktree prune` would drop once the folder is gone.
* Only a path inside some `.git/worktrees/` under [rootfs] counts.
*/
fun worktreeRecord(rootfs: File, checkout: File): File? {
val link = File(checkout, ".git").takeIf { it.isFile } ?: return null
val path = runCatching { link.readText() }.getOrNull()?.lineSequence()?.firstOrNull { it.startsWith("gitdir:") }
?.removePrefix("gitdir:")?.trim()?.takeIf { it.startsWith("/") && "/.git/worktrees/" in it && "/../" !in it } ?: return null
return File(rootfs, path.removePrefix("/")).takeIf { it.isDirectory }
}
/** Nothing inside changed for [TEMP_IDLE_MS] and nothing is a socket or pipe; links are not followed. */
internal fun idle(file: File, now: Long): Boolean = runCatching {
Files.walk(file.toPath()).use { paths ->
paths.allMatch { p ->
val a = Files.readAttributes(p, BasicFileAttributes::class.java, LinkOption.NOFOLLOW_LINKS)
!a.isOther && now - a.lastModifiedTime().toMillis() >= TEMP_IDLE_MS
}
}
}.getOrDefault(false)
}
@@ -5,11 +5,20 @@ import android.content.SharedPreferences
import android.util.Log
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.stores.ea.EaAuth
import com.droiddeck.launcher.stores.ea.EaCloud
import com.droiddeck.launcher.stores.ea.EaLibrary
import com.droiddeck.launcher.stores.ea.EaPrefs
import com.droiddeck.launcher.stores.ea.EaSaveRules
import com.droiddeck.launcher.stores.epic.EpicApiClient
import com.droiddeck.launcher.stores.epic.EpicCredentialStore
import com.droiddeck.launcher.stores.epic.EpicPrefs
import com.droiddeck.launcher.stores.gog.GogAuth
import com.droiddeck.launcher.stores.gog.GogPrefs
import com.droiddeck.launcher.stores.ubisoft.UbisoftAuth
import com.droiddeck.launcher.stores.ubisoft.UbisoftCloud
import com.droiddeck.launcher.stores.ubisoft.UbisoftCloudTransport
import com.droiddeck.launcher.stores.ubisoft.UbisoftConnect
import java.io.File
import java.net.HttpURLConnection
import java.net.URL
@@ -32,19 +41,27 @@ object CloudSaves {
if (detail.isNotEmpty()) " detail=\"$detail\"" else ""
}
class Status(val supported: Boolean, val folder: File?, val lastSync: Long, val reason: String, val conflicts: List<String> = emptyList())
class Status(val supported: Boolean, val folder: File?, val lastSync: Long, val reason: String, val conflicts: List<String> = emptyList(), val signedIn: Boolean = true)
private fun game(context: Context, store: Store, id: String): Pair<File, StoreGameSidecar>? =
StoreInstallRoot.gameFolders(context).firstNotNullOfOrNull { f ->
StoreGameSidecar.read(f)?.takeIf { it.store == store && it.id == id && it.isInstalled }?.let { f to it }
}
private fun game(context: Context, store: Store, id: String): Pair<File, StoreGameSidecar>? {
fun match(f: File) = StoreGameSidecar.read(f)?.takeIf { it.store == store && it.id == id && it.isInstalled }?.let { f to it }
return StoreInstallRoot.gameFolders(context).firstNotNullOfOrNull(::match)
?: if (store != Store.UBISOFT) null
else com.droiddeck.launcher.session.SessionPrefs.storeGameFolder(context, "${store.id}:$id")?.let { match(File(it)) }
}
fun supports(store: Store?): Boolean = store == Store.GOG || store == Store.EPIC || store == Store.EA || store == Store.UBISOFT
fun prefix(context: Context, folder: File): File? {
val appId = AddedGames.scan(context).firstOrNull { it.folder.absolutePath == folder.absolutePath }?.appId ?: return null
return Library.protonPrefix(context, appId and 0xFFFFFFFFL)
}
private fun prefs(context: Context, store: Store) = if (store == Store.GOG) GogPrefs.get(context) else EpicPrefs.get(context)
private fun prefs(context: Context, store: Store) = when (store) {
Store.GOG -> GogPrefs.get(context)
Store.EA -> EaPrefs.get(context)
else -> EpicPrefs.get(context)
}
fun lastSync(context: Context, store: Store, id: String): Long = prefs(context, store).getLong("cloud_sync_$id", 0L)
@@ -52,6 +69,7 @@ object CloudSaves {
private const val TEMPLATE_NONE = "none"
private const val UBISOFT_TEMPLATE = "ubisoft"
internal const val TEMPLATE_NONE_TTL_MS = 24 * 60 * 60 * 1000L
internal fun noneTemplateIsCurrent(storedAtMs: Long, nowMs: Long) =
@@ -64,6 +82,10 @@ object CloudSaves {
fun template(context: Context, store: Store, id: String, folder: File, sidecar: StoreGameSidecar): String? {
val p = prefs(context, store)
if (store == Store.EA) eaRules(context, id)?.let { fresh ->
if (fresh.isEmpty()) rememberNoCloud(p, id) else p.edit().putString("cloud_template_$id", fresh).remove("cloud_template_at_$id").apply()
return fresh
}
var retryNone = false
if (p.contains("cloud_template_$id")) {
val cached = p.getString("cloud_template_$id", "") ?: ""
@@ -89,7 +111,9 @@ object CloudSaves {
val item = sidecar.extra["catalogItemId"].orEmpty()
if (ns.isEmpty() || item.isEmpty()) "" else EpicApiClient.getCustomAttribute(token, ns, item, "CloudSaveFolder")
}
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT, Store.ROCKSTAR -> ""
Store.UBISOFT -> UBISOFT_TEMPLATE
Store.EA -> eaRules(context, id) ?: return null
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.ROCKSTAR -> ""
} ?: return null
p.edit()
.putString("cloud_template_$id", fetched.ifEmpty { TEMPLATE_NONE })
@@ -146,18 +170,25 @@ object CloudSaves {
val (folder, sidecar) = game(context, store, id) ?: return null to "not-installed"
val template = template(context, store, id, folder, sidecar) ?: return null to "store-unreachable"
if (template.isEmpty()) return null to "no-cloud-saves"
if (store == Store.UBISOFT) {
val user = UbisoftAuth.load(context)?.userId?.takeIf { it.isNotEmpty() } ?: return null to "not-signed-in"
val product = sidecar.extra["productId"]?.toLongOrNull() ?: return null to "unresolved"
return File(UbisoftConnect.prefix(context), "pfx/drive_c/users/steamuser/Saved Games/Ubisoft/$user/$product") to "ok"
}
val pfx = prefix(context, folder) ?: return null to "no-prefix"
val dir = when (store) {
Store.GOG -> CloudSavePaths.gog(template, pfx, folder)
Store.EPIC -> CloudSavePaths.epic(template, pfx, folder, EpicCredentialStore.load(context)?.accountId.orEmpty(), id)
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT, Store.ROCKSTAR -> null
Store.EA -> if (sidecar.extra["masterTitleId"].isNullOrEmpty()) null
else EaSaveRules.parse(template)?.base()?.let(EaSaveRules::template)?.let { CloudSavePaths.gog(it, pfx, folder) }
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR -> null
}
return dir to (if (dir == null) "unresolved" else "ok")
}
fun status(context: Context, store: Store, id: String): Status {
val (dir, reason) = saveFolder(context, store, id)
return Status(reason != "no-cloud-saves" && reason != "not-installed", dir, lastSync(context, store, id), reason, conflicts(context, store, id))
return Status(reason != "no-cloud-saves" && reason != "not-installed", dir, lastSync(context, store, id), reason, conflicts(context, store, id, dir), signedIn(context, store))
}
@@ -175,7 +206,33 @@ object CloudSaves {
val account = EpicCredentialStore.load(context)?.accountId.orEmpty()
if (token == null || account.isEmpty()) null else EpicCloud(account, id, token)
}
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT, Store.ROCKSTAR -> null
Store.UBISOFT -> {
val session = UbisoftAuth.current(context)
val product = StoreGameSidecar.read(folder)?.extra?.get("productId")?.toLongOrNull()
if (session == null || product == null) null else UbisoftCloudTransport(UbisoftCloud(session, product), session.userId)
}
Store.EA -> {
val sidecar = StoreGameSidecar.read(folder)
val rules = sidecar?.let { template(context, store, id, folder, it) }?.let(EaSaveRules::parse)
val base = rules?.base()
val token = EaAuth.accessToken(context)
val uid = EaAuth.load(context)?.userId.orEmpty()
val master = sidecar?.extra?.get("masterTitleId").orEmpty()
if (rules == null || base == null || token == null || uid.isEmpty() || master.isEmpty()) null
else EaCloud(token, uid, EaCloud.keys(master, sidecar?.extra?.get("multiplayerId").orEmpty()), base, rules, saveFolder(context, store, id).first)
}
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.ROCKSTAR -> null
}
private fun signedIn(context: Context, store: Store): Boolean = when (store) {
Store.EA -> EaAuth.signedIn(context)
else -> true
}
private fun eaRules(context: Context, id: String): String? {
val games = EaLibrary.cached(context)
if (games.isEmpty()) return null
return games.firstOrNull { it.offerId == id }?.cloudSaves.orEmpty()
}
private fun gogScopedToken(context: Context, id: String, clientId: String): String? {
@@ -184,11 +241,15 @@ object CloudSaves {
}
private fun baseline(context: Context, store: Store, id: String): Map<String, CloudPlan.Entry>? =
CloudPlan.fromJson(prefs(context, store).getString("cloud_baseline_$id", null))
/** Ubisoft saves belong to an account and product, so their sync state is kept per save folder. */
internal fun scope(store: Store, id: String, dir: File): String =
if (store == Store.UBISOFT) "$id:${dir.parentFile?.name.orEmpty()}:${dir.name}" else id
private fun saveBaseline(context: Context, store: Store, id: String, b: Map<String, CloudPlan.Entry>) =
prefs(context, store).edit().putString("cloud_baseline_$id", CloudPlan.toJson(b)).apply()
internal fun baseline(context: Context, store: Store, key: String): Map<String, CloudPlan.Entry>? =
CloudPlan.fromJson(prefs(context, store).getString("cloud_baseline_$key", null))
private fun saveBaseline(context: Context, store: Store, key: String, b: Map<String, CloudPlan.Entry>) =
prefs(context, store).edit().putString("cloud_baseline_$key", CloudPlan.toJson(b)).apply()
internal class Migration(val baseline: Map<String, CloudPlan.Entry>, val moved: Int, val cleaned: Int, val failed: Int)
@@ -260,30 +321,45 @@ object CloudSaves {
if (result == null || result.failed == 0) p.edit().putInt("cloud_layout_$id", CLOUD_LAYOUT).apply()
}
fun conflicts(context: Context, store: Store, id: String): List<String> =
prefs(context, store).getString("cloud_conflicts_$id", "").orEmpty().split('\n').filter { it.isNotEmpty() }
fun conflicts(context: Context, store: Store, id: String, dir: File? = null): List<String> =
if (store == Store.UBISOFT && dir == null) emptyList() else savedConflicts(context, store, dir?.let { scope(store, id, it) } ?: id)
private fun saveConflicts(context: Context, store: Store, id: String, names: Collection<String>) =
prefs(context, store).edit().putString("cloud_conflicts_$id", names.joinToString("\n")).apply()
private fun savedConflicts(context: Context, store: Store, key: String): List<String> =
prefs(context, store).getString("cloud_conflicts_$key", "").orEmpty().split('\n').filter { it.isNotEmpty() }
fun download(context: Context, store: Store, id: String, force: Boolean = false): Result =
sync(context, store, id, "down") { dir, cloud -> downWith(context, store, id, dir, cloud, force) }
private fun saveConflicts(context: Context, store: Store, key: String, names: Collection<String>) =
prefs(context, store).edit().putString("cloud_conflicts_$key", names.joinToString("\n")).apply()
private fun alike(cloud: CloudTransport, conflicts: List<String>, local: Map<String, CloudPlan.Local>, remote: Map<String, CloudFile>): List<String> =
if (cloud.contentDigests) emptyList()
else conflicts.filter { name ->
val r = remote[name] ?: return@filter false
val l = local[name] ?: return@filter false
runCatching { md5(cloud.get(r).first) }.getOrNull()?.equals(l.md5, ignoreCase = true) == true
}
private fun settled(plan: CloudPlan.Plan, alike: List<String>): CloudPlan.Plan =
if (alike.isEmpty()) plan else CloudPlan.Plan(plan.transfer, plan.conflicts - alike.toSet(), plan.same + alike, plan.refused)
fun download(context: Context, store: Store, id: String, force: Boolean = false, claim: () -> Boolean = { true }): Result =
sync(context, store, id, "down") { dir, cloud -> downWith(context, store, id, dir, cloud, force, claim) }
fun upload(context: Context, store: Store, id: String, force: Boolean = false): Result =
sync(context, store, id, "up") { dir, cloud -> upWith(context, store, id, dir, cloud, force) }
fun downloadOrDefer(context: Context, store: Store, id: String): Result =
downloadOrDefer(context, store, id, Executor { Thread(it, "cloud-deferred").start() })
fun downloadOrDefer(context: Context, store: Store, id: String, claim: () -> Boolean): Result =
downloadOrDefer(context, store, id, Executor { Thread(it, "cloud-deferred").start() }, claim)
internal fun downloadOrDefer(context: Context, store: Store, id: String, executor: Executor): Result {
internal fun downloadOrDefer(context: Context, store: Store, id: String, executor: Executor, claim: () -> Boolean = { true }): Result {
val app = context.applicationContext
val g = game(app, store, id) ?: return done(store, id, "down", Result("skipped", 0, 0, "not-installed"))
if (!g.second.cloud) return done(store, id, "down", Result("skipped", 0, 0, "off"))
if (prefix(app, g.first)?.let { CloudSavePaths.profile(it).isDirectory } == true) return download(app, store, id)
val ready = { (if (store == Store.UBISOFT) File(UbisoftConnect.prefix(app), "pfx") else prefix(app, g.first))?.let { CloudSavePaths.profile(it).isDirectory } == true }
if (ready()) return download(app, store, id, claim = claim)
executor.execute {
val end = System.currentTimeMillis() + PREFIX_WAIT_MS
while (System.currentTimeMillis() < end) {
if (prefix(app, g.first)?.let { CloudSavePaths.profile(it).isDirectory } == true) { download(app, store, id); return@execute }
if (ready()) { download(app, store, id); return@execute }
Thread.sleep(2000)
}
done(store, id, "down", Result("skipped", 0, 0, "no-prefix"))
@@ -304,8 +380,12 @@ object CloudSaves {
if (dir != null && store == Store.GOG) migrateGogNested(context, id, g.first, dir)
val cloud = if (dir != null) transport(context, store, id, g.first) else null
when {
cloud is UbisoftCloudTransport && dir?.parentFile?.name != cloud.user -> Result("skipped", 0, 0, "account-changed")
dir == null -> Result("skipped", 0, 0, reason)
cloud == null && store == Store.EA && signedIn(context, store) -> Result("failed", 0, 0, "sign-in-unreachable")
cloud == null -> Result("skipped", 0, 0, "not-signed-in")
cloud is EaCloud && cloud.localDir?.canonicalPath != dir.canonicalPath -> Result("skipped", 0, 0, "rules-changed")
cloud is EaCloud && caseCollision(localFiles(dir).keys, cloud::wants) -> Result("failed", 0, 0, "case-collision")
else -> body(dir, cloud).also { if (it.result == "ok") markSynced(context, store, id) }
}
}
@@ -319,15 +399,32 @@ object CloudSaves {
return done(store, id, way, result)
}
internal fun caseCollision(names: Collection<String>, wants: (String) -> Boolean): Boolean =
names.filter(wants).groupBy { it.lowercase() }.any { it.value.size > 1 }
private fun done(store: Store, id: String, way: String, r: Result): Result {
Log.i(TAG, "cloud ${store.id} $id $way ${r.line}")
StoresState.logLine("cloud ${store.id} $id $way ${r.line}")
return r
}
private fun localFiles(dir: File): Map<String, File> =
if (!dir.isDirectory) emptyMap()
else dir.walkTopDown().filter { it.isFile }.associateBy { it.relativeTo(dir).path.replace(File.separatorChar, '/') }
private fun localFiles(dir: File): Map<String, File> {
if (!dir.isDirectory) return emptyMap()
val root = runCatching { dir.toPath().toRealPath() }.getOrNull() ?: return emptyMap()
val found = LinkedHashMap<String, File>()
fun walk(d: File, prefix: String, ancestry: Set<java.nio.file.Path>) {
for (child in d.listFiles().orEmpty()) {
val real = runCatching { child.toPath().toRealPath() }.getOrNull() ?: continue
if (!real.startsWith(root)) continue
val name = prefix + child.name
if (child.isDirectory) {
if (real !in ancestry) walk(child, "$name/", ancestry + real)
} else if (child.isFile) found[name] = child
}
}
walk(dir, "", setOf(root))
return found
}
internal fun md5(f: File): String = md5(f.readBytes())
@@ -341,46 +438,85 @@ object CloudSaves {
return files.associateBy { it.name }
}
internal fun downWith(context: Context, store: Store, id: String, dir: File, cloud: CloudTransport, force: Boolean): Result {
val files = localFiles(dir)
internal fun downWith(context: Context, store: Store, id: String, dir: File, cloud: CloudTransport, force: Boolean, claim: () -> Boolean = { true }): Result {
val files = localFiles(dir).filterKeys(cloud::wants)
val remote = remote(cloud) { it in files }
val local = files.mapValues { CloudPlan.Local(md5(it.value)) }
val base = baseline(context, store, id)
val plan = CloudPlan.down(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base)
val take = if (force) plan.transfer + plan.conflicts else plan.transfer
if (take.isNotEmpty() && files.isNotEmpty()) backup(context, store, id, dir, "local")
val key = scope(store, id, dir)
val base = baseline(context, store, key)
val planned = CloudPlan.down(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base)
val alike = alike(cloud, planned.conflicts, local, remote)
val plan = settled(planned, alike)
val saved = savedConflicts(context, store, key).filter { it in remote && it !in alike && it !in plan.same }
val take = if (force) (plan.transfer + plan.conflicts + saved).distinct() else plan.transfer
val next = HashMap(base.orEmpty())
var bytes = 0L
val written = HashSet<String>()
val changed = ArrayList<String>()
val blocked = ArrayList<String>()
val fetched = LinkedHashMap<String, Pair<CloudFile, Pair<ByteArray, Long>>>()
for (name in take) {
val f = remote[name] ?: continue
val (data, modified) = cloud.get(f)
if (!File(dir, name).canonicalPath.startsWith(dir.canonicalPath + File.separator)) { blocked += name; continue }
fetched[name] = f to cloud.get(f)
}
if (fetched.isNotEmpty() && !claim()) return Result("skipped", 0, 0, "launch-moved-on")
val replaced = fetched.keys.mapNotNull { name -> files[name] ?: File(dir, name).takeIf { it.isFile } }
if (!backupReplaced(context, store, id, dir, replaced)) return Result("failed", 0, 0, "backup-failed")
for ((name, got) in fetched) {
val (f, content) = got
val (data, modified) = content
val dest = File(dir, name)
if (!dest.canonicalPath.startsWith(dir.canonicalPath + File.separator)) continue
if ((if (dest.isFile) md5(dest) else null) != local[name]?.md5) { changed += name; continue }
dest.parentFile?.mkdirs()
dest.writeBytes(data)
if (modified > 0) dest.setLastModified(modified)
bytes += data.size
written += name
next[name] = CloudPlan.Entry(md5(data), f.md5, if (modified > 0) modified else f.modifiedMs)
}
for (name in plan.same) remote[name]?.let { r -> next[name] = CloudPlan.Entry(local.getValue(name).md5, r.md5, r.modifiedMs) }
saveBaseline(context, store, id, next)
val left = if (force) emptyList() else plan.conflicts
saveConflicts(context, store, id, left)
return Result("ok", take.size, bytes, if (take.isEmpty()) "up-to-date" else "downloaded", left.size)
saveBaseline(context, store, key, next)
val left = (if (force) take.filter { it !in written } else plan.conflicts + saved.filter { it !in written } + changed)
.filter { it !in blocked }.distinct()
saveConflicts(context, store, key, left)
val reason = when {
take.isEmpty() -> "up-to-date"
changed.isNotEmpty() -> "changed-locally"
blocked.isNotEmpty() -> "blocked-path"
else -> "downloaded"
}
val detail = listOfNotNull(
changed.takeIf { it.isNotEmpty() }?.joinToString(prefix = "changed locally: "),
blocked.takeIf { it.isNotEmpty() }?.joinToString(prefix = "outside the save folder: "),
).joinToString("; ")
return Result(if (written.size < take.size) "partial" else "ok", written.size, bytes, reason, left.size, detail)
}
internal fun upWith(context: Context, store: Store, id: String, dir: File, cloud: CloudTransport, force: Boolean): Result {
val base = baseline(context, store, id) ?: return Result("skipped", 0, 0, "no-baseline")
val files = localFiles(dir)
val key = scope(store, id, dir)
val base = baseline(context, store, key) ?: return Result("skipped", 0, 0, "no-baseline")
val files = localFiles(dir).filterKeys(cloud::wants).let { all -> if (cloud is UbisoftCloudTransport) all.filterValues(::markUbisoftSave) else all }
if (files.isEmpty()) return Result("skipped", 0, 0, "nothing-local")
val remote = remote(cloud) { it in files }
val local = files.mapValues { CloudPlan.Local(md5(it.value)) }
val plan = CloudPlan.up(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base)
val send = CloudPlan.upSend(plan, force, cloud is GogCloud, files.keys)
val planned = CloudPlan.up(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base)
val alike = alike(cloud, planned.conflicts, local, remote)
val plan = settled(planned, alike)
val saved = savedConflicts(context, store, key).filter { it !in alike && it !in plan.same }
var send = CloudPlan.upSend(plan, force, cloud is GogCloud, files.keys)
val next = HashMap(base)
for (name in plan.same) remote[name]?.let { r -> next[name] = CloudPlan.Entry(local.getValue(name).md5, r.md5, r.modifiedMs) }
var drifted = emptyList<String>()
var raced = emptyList<String>()
if (send.isNotEmpty()) {
val copies = backupCloud(context, store, id, cloud, send.mapNotNull { remote[it] })
if (cloud is UbisoftCloudTransport && !force) {
drifted = send.filter { name -> val synced = base[name]?.localMd5; synced != null && copies[name]?.let { it != synced } == true }
send = send - drifted.toSet()
}
}
if (send.isNotEmpty()) {
backupCloud(context, store, id, cloud, send.mapNotNull { remote[it] })
val stamped = HashMap<String, Long>()
val sentMd5 = HashMap<String, String>()
if (cloud is GogCloud) {
@@ -394,19 +530,40 @@ object CloudSaves {
} else {
val data = send.associateWith { files.getValue(it).readBytes() }
for ((name, bytes) in data) sentMd5[name] = md5(bytes)
stamped += cloud.put(data, send.associateWith { files.getValue(it).lastModified() })
stamped += try {
cloud.put(data, send.associateWith { files.getValue(it).lastModified() })
} catch (e: CloudChanged) {
raced = e.unsent
e.sent
} catch (e: Exception) {
val kept = send.mapNotNull { name -> cloud.committed(name)?.let { name to it } }
if (kept.isNotEmpty()) {
for ((name, r) in kept) next[name] = CloudPlan.Entry(sentMd5.getValue(name), r.md5, r.modifiedMs)
saveBaseline(context, store, key, next)
saveConflicts(context, store, key, saved - kept.map { it.first }.toSet())
}
throw e
}
send = send.filter { it in stamped }
for ((name, t) in stamped) if (t > 0) files[name]?.setLastModified(t)
}
val after = remote(cloud) { it in send }
val after = if (send.all { cloud.committed(it) != null }) emptyMap() else remote(cloud) { it in send && cloud.committed(it) == null }
for (name in send) {
val r = after[name]
val r = cloud.committed(name) ?: after[name]
next[name] = CloudPlan.Entry(sentMd5.getValue(name), r?.md5, r?.modifiedMs ?: stamped[name] ?: -1L)
}
}
saveBaseline(context, store, id, next)
val left = if (force) emptyList() else plan.conflicts
saveConflicts(context, store, id, left)
return Result("ok", send.size, send.sumOf { files.getValue(it).length() }, if (send.isEmpty()) "up-to-date" else "uploaded", left.size)
saveBaseline(context, store, key, next)
val left = (if (force) (plan.conflicts + saved).filter { it !in send } + raced
else plan.conflicts + drifted + raced + saved.filter { it !in send && it in files }).distinct()
saveConflicts(context, store, key, left)
val reason = when {
raced.isNotEmpty() -> "changed-in-cloud"
send.isEmpty() -> "up-to-date"
else -> "uploaded"
}
return Result(if (raced.isEmpty()) "ok" else "partial", send.size, send.sumOf { files.getValue(it).length() }, reason, left.size,
if (raced.isEmpty()) "" else raced.joinToString(prefix = "changed in the cloud: "))
}
@@ -441,23 +598,59 @@ object CloudSaves {
private fun backupRoot(context: Context, store: Store, id: String) =
File(context.filesDir, "stores/cloud-backups/${store.id}-${id.replace(Regex("[^A-Za-z0-9._-]"), "_")}")
private fun backup(context: Context, store: Store, id: String, dir: File, kind: String) {
val root = backupRoot(context, store, id)
runCatching { dir.copyRecursively(File(root, "$kind-${System.currentTimeMillis()}"), overwrite = true) }
prune(root, kind)
private fun markUbisoftSave(file: File): Boolean {
val head = ByteArray(40)
var filled = 0
file.inputStream().use { input ->
while (filled < head.size) {
val n = input.read(head, filled, head.size - filled)
if (n < 0) break
filled += n
}
}
if (filled < head.size) return false
if (UbisoftCloud.mark(head) != null) return true
if (head.copyOfRange(8, 40).any { it != 0.toByte() }) return false
java.io.RandomAccessFile(file, "rw").use { it.seek(8); it.write(UbisoftCloud.freshMark().toByteArray(Charsets.ISO_8859_1)) }
return true
}
private fun backupCloud(context: Context, store: Store, id: String, cloud: CloudTransport, files: List<CloudFile>) {
if (files.isEmpty()) return
private fun backupCloud(context: Context, store: Store, id: String, cloud: CloudTransport, files: List<CloudFile>): Map<String, String> {
if (files.isEmpty()) return emptyMap()
val root = backupRoot(context, store, id)
val target = File(root, "cloud-${System.currentTimeMillis()}")
val copies = HashMap<String, String>()
for (f in files) {
val dest = File(target, f.name)
if (!dest.canonicalPath.startsWith(target.canonicalPath + File.separator)) continue
dest.parentFile?.mkdirs()
dest.writeBytes(cloud.get(f).first)
val data = cloud.get(f).first
dest.writeBytes(data)
copies[f.name] = md5(data)
}
prune(root, "cloud")
return copies
}
private fun backupReplaced(context: Context, store: Store, id: String, dir: File, replaced: List<File>): Boolean {
if (replaced.isEmpty()) return true
val base = runCatching { dir.canonicalPath + File.separator }.getOrNull() ?: return false
val root = backupRoot(context, store, id)
val stamp = "${System.currentTimeMillis()}-${java.util.UUID.randomUUID().toString().take(8)}"
val staging = File(root, "staging-$stamp")
val copied = runCatching {
for (f in replaced) {
check(f.canonicalPath.startsWith(base))
f.copyTo(File(staging, f.relativeTo(dir).path), overwrite = true)
}
check(staging.renameTo(File(root, "local-$stamp")))
}.isSuccess
if (!copied) {
staging.deleteRecursively()
return false
}
prune(root, "local")
return true
}
private fun prune(root: File, kind: String) {
@@ -27,6 +27,10 @@ class CloudFile(val name: String, var modifiedMs: Long, var md5: String? = null,
class CloudPut(val modifiedMs: Long, val md5: String?)
interface CloudTransport {
/** False when [CloudFile.md5] is a version the service assigns rather than a digest of the content. */
val contentDigests: Boolean get() = true
fun committed(name: String): CloudFile? = null
fun wants(name: String): Boolean = true
fun list(): List<CloudFile>
fun details(file: CloudFile) {}
fun get(file: CloudFile): Pair<ByteArray, Long>
@@ -182,6 +186,8 @@ internal fun isoDate(s: String?): Long {
class NoCloudSaves : Exception("no cloud saves")
class CloudChanged(val sent: Map<String, Long>, val unsent: List<String>) : Exception("cloud saves changed since they were read")
internal fun splitGogName(name: String): Pair<String?, String> {
val slash = name.indexOf('/')
return if (slash <= 0 || slash == name.length - 1) null to name
@@ -1,16 +1,16 @@
package com.droiddeck.launcher.stores
enum class Store(val id: String, val label: String, val shortLabel: String) {
GOG("gog", "GOG", "GOG"),
EPIC("epic", "Epic Games", "Epic"),
AMAZON("amazon", "Amazon Games", "Amazon"),
XBOX("xbox", "Xbox", "Xbox"),
ITCH("itch", "Itch.io", "Itch.io"),
GAMEJOLT("gamejolt", "Game Jolt", "Game Jolt"),
BATTLENET("battlenet", "Battle.net", "Battle.net"),
UBISOFT("ubisoft", "Ubisoft Connect", "Ubisoft"),
EA("ea", "EA", "EA"),
ROCKSTAR("rockstar", "Rockstar Games", "Rockstar");
XBOX("xbox", "Xbox", "Xbox"),
GOG("gog", "GOG", "GOG"),
ROCKSTAR("rockstar", "Rockstar Games", "Rockstar"),
ITCH("itch", "Itch.io", "Itch.io"),
UBISOFT("ubisoft", "Ubisoft Connect", "Ubisoft"),
AMAZON("amazon", "Amazon Games", "Amazon"),
BATTLENET("battlenet", "Battle.net", "Battle.net"),
GAMEJOLT("gamejolt", "Game Jolt", "Game Jolt");
val folder: String get() = if (this == ITCH) "itch" else shortLabel
@@ -46,11 +46,18 @@ object StoreLaunchRequests {
}
private fun answer(app: Context, file: File) {
val resp = File(dir(app), "resp").apply { mkdirs() }
val rid = file.name.removeSuffix(".json")
val taken = File(resp, "$rid.taken")
val writing = File(resp, "$rid.writing")
if (!file.renameTo(taken)) return
val request = try {
JSONObject(file.readText()).also { file.delete() }
JSONObject(taken.readText())
} catch (e: Exception) {
taken.delete()
return
}
val claim = { taken.renameTo(writing) }
val reply = when (request.optString("op")) {
"xbox-released" -> {
com.droiddeck.launcher.stores.xbox.XboxRuntime.released(request.optString("lease"))
@@ -58,7 +65,10 @@ object StoreLaunchRequests {
}
"xbox-renew" -> JSONObject().put("ok", com.droiddeck.launcher.stores.xbox.XboxRuntime.renew(app, request.optString("id"), request.optString("lease")))
"xbox-prepare" -> runCatching { com.droiddeck.launcher.stores.xbox.XboxRuntime.prepare(app, request.getString("id")) }
.getOrElse { JSONObject().put("ok", false).put("reason", "Xbox account service is unavailable. Sign in again and retry.") }
.getOrElse {
StoresState.logLine("Xbox: launch prepare failed (${it.javaClass.simpleName}: ${it.message})")
JSONObject().put("ok", false).put("reason", reasonFor(it))
}
"ea-prepare" -> runCatching { lastLaunched = Store.EA to request.optString("id"); com.droiddeck.launcher.stores.ea.EaLaunch.prepare(app, request) }
.getOrElse { JSONObject().put("ok", false).put("reason", "error-" + it.javaClass.simpleName) }
"ea-exited" -> {
@@ -105,7 +115,7 @@ object StoreLaunchRequests {
else {
lastLaunched = store to id
CloudSaves.markDirty(app, store, id)
CloudSaves.downloadOrDefer(app, store, id).let { JSONObject().put("ok", it.ok).put("result", it.result).put("files", it.files).put("reason", it.reason) }
CloudSaves.downloadOrDefer(app, store, id, claim).let { JSONObject().put("ok", it.ok).put("result", it.result).put("files", it.files).put("reason", it.reason) }
}
}
"cloud-up" -> {
@@ -164,12 +174,31 @@ object StoreLaunchRequests {
else -> JSONObject().put("ok", false).put("reason", "unknown-op")
}
try {
val resp = File(dir(app), "resp").apply { mkdirs() }
val tmp = File(resp, file.name + ".tmp")
tmp.writeText(reply.toString())
tmp.renameTo(File(resp, file.name))
} catch (e: Exception) {
Log.w(TAG, "could not answer ${file.name}: ${e.message}")
} finally {
taken.delete()
writing.delete()
}
}
/// What the guest prints when a launch is refused.
///
/// The message is the only thing that separates a stale sign-in from a title
/// that is not installed, so it is kept, minus anything that could carry a
/// device path or a token: segments lookng like a path are dropped and the
/// rest is folded to plain text.
internal fun reasonFor(error: Throwable): String {
val text = error.message.orEmpty()
.split(' ')
.filterNot { it.contains('/') || it.startsWith("http") }
.joinToString(" ")
.filter { it.isLetterOrDigit() || it in " .,:;_-()'" }
.trim()
.take(160)
return if (text.isEmpty()) "Xbox account service is unavailable. Sign in again and retry." else text
}
}
@@ -46,6 +46,26 @@ data class DownloadEntry(
stageItemsTotal > 0 -> (stageItems.toFloat() / stageItemsTotal).coerceIn(0f, 1f)
else -> -1f
}
val downloadFraction: Float get() = if (bytesTotal > 0L) (bytesDone.toDouble() / bytesTotal).toFloat().coerceIn(0f, 1f) else -1f
val installFraction: Float get() = when {
stage != DownloadStage.DOWNLOAD && stage != DownloadStage.INSTALL -> -1f
stageTotal > 0L -> (stageDone.toDouble() / stageTotal).toFloat().coerceIn(0f, 1f)
stageItemsTotal > 0 -> (stageItems.toFloat() / stageItemsTotal).coerceIn(0f, 1f)
else -> -1f
}
val streaming: Boolean get() = state == DownloadState.RUNNING && bytesTotal > 0L && bytesDone < bytesTotal && installFraction >= 0f &&
(stage == DownloadStage.INSTALL || (stage == DownloadStage.DOWNLOAD && passed(DownloadStage.INSTALL)))
/** Whole job as one bar: downloading fills the first 90%, installing the rest, also when they run together. */
val overallFraction: Float get() {
if (state == DownloadState.INSTALLED || stage == DownloadStage.DONE) return 1f
val downloaded = when {
bytesTotal > 0L -> downloadFraction
passed(DownloadStage.DOWNLOAD) -> 1f
else -> 0f
}
val installed = if (stage == DownloadStage.INSTALL || (stage == DownloadStage.DOWNLOAD && passed(DownloadStage.INSTALL))) installFraction.coerceAtLeast(0f) else 0f
return (0.9f * downloaded + 0.1f * installed).coerceIn(0f, 1f)
}
val fraction: Float get() = stageFraction.coerceAtLeast(0f)
val percent: Int get() = (fraction * 100).toInt()
}
@@ -45,13 +45,18 @@ object DownloadQueue {
val e = item.entry
if (e.stage == stage) return
item.speedAt = 0L; item.speedBytes = 0L; item.speedEwma = 0.0
item.entry = e.copy(
stage = stage, stagesPassed = e.stagesPassed or (1 shl e.stage.ordinal), speedBps = 0, etaSeconds = -1,
val passed = e.stagesPassed or (1 shl e.stage.ordinal)
// Streaming installers (GOG) alternate between DOWNLOAD and INSTALL; the install count lives on across the swaps.
val streaming = e.stage in STREAMED && stage in STREAMED && (passed and (1 shl DownloadStage.INSTALL.ordinal)) != 0
item.entry = if (streaming) e.copy(stage = stage, stagesPassed = passed, speedBps = 0, etaSeconds = -1)
else e.copy(
stage = stage, stagesPassed = passed, speedBps = 0, etaSeconds = -1,
stageDone = 0, stageTotal = 0, stageItems = 0, stageItemsTotal = 0,
)
}
private const val SPEED_WINDOW_MS = 3000.0
private val STREAMED = setOf(DownloadStage.DOWNLOAD, DownloadStage.INSTALL)
private fun stageCount(key: String, done: Long, total: Long, files: Int, filesTotal: Int, bytes: Boolean) {
synchronized(lock) {
@@ -178,6 +183,8 @@ object DownloadQueue {
fun isActive(key: String): Boolean = entry(key)?.isActive == true
fun anyActive(): Boolean = synchronized(lock) { items.values.any { it.entry.isActive } }
fun enqueue(context: Context, entry: DownloadEntry, factory: () -> DownloadJob) {
val app = context.applicationContext
synchronized(lock) {
@@ -17,7 +17,7 @@ object EaAuth {
const val CLIENT_ID = "JUNO_PC_CLIENT"
private const val CLIENT_SECRET = "4mRLtYMb6vq9qglomWEaT4ChxsXWcyqbQpuBNfMPOYOiDmYYQmjuaBsF2Zp0RyVeWkfqhE9TuGgAw7te"
const val AUTH_URL = "https://accounts.ea.com/connect/auth"
private const val TOKEN_URL = "https://accounts.ea.com/connect/token"
internal var tokenUrl = "https://accounts.ea.com/connect/token"
const val REDIRECT = "qrc:///html/login_successful.html"
private const val REFRESH_MARGIN_MS = 5 * 60 * 1000L
private val refreshLock = Any()
@@ -41,8 +41,11 @@ object EaAuth {
val personaId: String,
val displayName: String,
val eaId: String,
val rejected: Boolean = false,
)
private class Rejected(message: String) : IllegalStateException(message)
class Pending(val url: String, val verifier: String)
internal fun fromJson(o: JSONObject): Account? {
@@ -55,6 +58,7 @@ object EaAuth {
personaId = o.optString("persona_id"),
displayName = o.optString("display_name"),
eaId = o.optString("ea_id"),
rejected = o.optBoolean("refresh_rejected"),
)
}
@@ -122,14 +126,15 @@ object EaAuth {
private fun tokenCall(values: List<Pair<String, String>>): JSONObject {
val reply = EaHttp.request(
TOKEN_URL, "POST",
tokenUrl, "POST",
mapOf("Content-Type" to "application/x-www-form-urlencoded"),
EaHttp.form(values + listOf("client_id" to CLIENT_ID, "client_secret" to CLIENT_SECRET)).toByteArray(),
follow = false,
)
val json = runCatching { JSONObject(reply.text) }.getOrNull()
if (!reply.ok || json == null || json.optString("access_token").isEmpty()) {
throw IllegalStateException("EA token request failed (${reply.status}): ${json?.optString("error_description")?.ifEmpty { json.optString("error") } ?: ""}")
val message = "EA token request failed (${reply.status}): ${json?.optString("error_description")?.ifEmpty { json.optString("error") } ?: ""}"
throw if (json?.optString("error") == "invalid_grant") Rejected(message) else IllegalStateException(message)
}
return json
}
@@ -162,6 +167,7 @@ object EaAuth {
tokenCall(listOf("grant_type" to "refresh_token", "refresh_token" to a.refreshToken))
} catch (e: Exception) {
Log.w(TAG, "refresh: ${e.message}")
if (e is Rejected) markRejected(context, a.refreshToken)
return null
}
val access = token.getString("access_token")
@@ -176,11 +182,24 @@ object EaAuth {
val record = StoreAccounts.read(app, Store.EA) ?: return false
record.put("access_token", access).put("expires_at", System.currentTimeMillis() + expiresIn * 1000)
refresh.takeIf { it.isNotEmpty() }?.let { record.put("refresh_token", it) }
record.remove("refresh_rejected")
player?.let { record.put("user_id", it.userId).put("persona_id", it.personaId).put("display_name", it.displayName).put("ea_id", it.eaId) }
StoreAccounts.write(app, Store.EA, record)
true
}
private fun markRejected(context: Context, refresh: String) = synchronized(refreshLock) {
val app = context.applicationContext
val record = StoreAccounts.read(app, Store.EA) ?: return@synchronized
if (record.optString("refresh_token") != refresh) return@synchronized
StoreAccounts.write(app, Store.EA, record.put("refresh_rejected", true))
}
fun signedIn(context: Context): Boolean {
val a = load(context) ?: return false
return a.userId.isNotEmpty() && !(a.rejected && a.expiresAt <= System.currentTimeMillis())
}
fun accessToken(context: Context): String? {
val current = load(context) ?: return null
if (fresh(current)) return current.accessToken
@@ -0,0 +1,265 @@
package com.droiddeck.launcher.stores.ea
import android.util.Base64
import android.util.Xml
import com.droiddeck.launcher.stores.CloudFile
import com.droiddeck.launcher.stores.CloudTransport
import java.io.File
import java.io.StringReader
import java.security.MessageDigest
import java.time.Instant
import org.xmlpull.v1.XmlPullParser
internal class EaCloud(
private val token: String,
private val uid: String,
private val keys: List<String>,
private val base: String,
private val rules: EaSaveRules,
val localDir: File? = null,
) : CloudTransport {
class Entry(val size: Long, val href: String, val md5: String, val created: String, val modified: String, val localName: String)
class Manifest(val lineage: String, val files: List<Entry>, val snapshots: List<String>)
private class Signed(val url: String, val headers: Map<String, String>)
private class Request(val verb: String, val resource: String, val md5: String? = null, val type: String? = null)
private var key: String? = null
private var found = false
private var listed: Map<String, String?>? = null
private val committed = HashMap<String, CloudFile>()
override fun wants(name: String): Boolean = rules.matches(base + name)
override fun committed(name: String): CloudFile? = committed[name]
override fun list(): List<CloudFile> {
val manifest = pick()
val files = manifest?.files.orEmpty().mapNotNull { e ->
val path = EaSaveRules.normalize(e.localName)
if (!path.startsWith(base, ignoreCase = true) || !rules.matches(path)) return@mapNotNull null
val md5 = hex(e.md5) ?: error("EA listed ${path.substring(base.length)} without a valid checksum")
CloudFile(localName(path.substring(base.length)), parseTime(e.modified), md5, readLink = e.href)
}
val twins = files.groupBy { it.name.lowercase() }.values.firstOrNull { it.size > 1 }
check(twins == null) { "EA lists more than one save named ${twins!!.first().name} in different cases" }
listed = files.associate { it.name.lowercase() to it.md5 }
return files
}
private fun localName(name: String): String {
var dir = localDir ?: return name
val parts = name.split('/')
val out = ArrayList<String>()
for (part in parts) {
val match = dir.listFiles()?.filter { it.name.equals(part, ignoreCase = true) }.orEmpty()
check(match.size <= 1) { "The save folder holds more than one file named $part in different cases" }
val pick = match.singleOrNull()
if (pick == null) return (out + parts.drop(out.size)).joinToString("/")
out += pick.name
dir = pick
}
return out.joinToString("/")
}
override fun get(file: CloudFile): Pair<ByteArray, Long> {
val href = file.readLink ?: error("EA has no data for ${file.name}")
return locked("read", key ?: keys.first()) { lock, _ ->
val signed = authorize(lock, listOf(Request("GET", href))).single()
val reply = EaHttp.request(signed.url, headers = signed.headers)
check(reply.ok) { "EA cloud save download answered ${reply.status}" }
val want = file.md5 ?: error("EA listed ${file.name} without a valid checksum")
check(hex(b64(md5(reply.body))) == want) { "EA cloud save ${file.name} failed its checksum" }
reply.body to file.modifiedMs
}
}
override fun put(files: Map<String, ByteArray>, modifiedMs: Map<String, Long>): Map<String, Long> {
if (key == null) pick()
check(found || keys.size == 1) { "EA has no cloud save record for this game yet; play it once in the EA app" }
val target = key ?: keys.first()
val seen = listed
return locked("write", target) { lock, body ->
val locked = manifestUrl(body)?.let { fetchManifest(it) }
check(locked != null || !found) { "EA's cloud save record disappeared" }
val current = locked ?: Manifest("{00000000-0000-0000-0000-000000000000}", emptyList(), emptyList())
if (seen != null) for (name in files.keys) {
val entry = current.files.firstOrNull { EaSaveRules.normalize(it.localName).equals(base + name, ignoreCase = true) }
val now = entry?.let { hex(it.md5) ?: error("EA lists $name without a valid checksum") }
check(now == seen[name.lowercase()]) { "EA's cloud saves changed since they were read" }
}
val now = System.currentTimeMillis()
val added = files.map { (name, data) ->
val sum = md5(data)
val stamp = stamp(modifiedMs[name]?.takeIf { it > 0 } ?: now)
val old = current.files.firstOrNull { EaSaveRules.normalize(it.localName).equals(base + name, ignoreCase = true) }
Entry(data.size.toLong(), "content/${data.size}-${hexOf(sum)}", b64(sum), old?.created ?: stamp, stamp, base + name) to data
}
val names = added.map { it.first.localName.lowercase() }.toSet()
val next = Manifest(current.lineage, current.files.filter { EaSaveRules.normalize(it.localName).lowercase() !in names } + added.map { it.first }, current.snapshots)
val xml = write(next).toByteArray()
val xmlMd5 = b64(md5(xml))
val requests = added.map { Request("PUT", it.first.href, it.first.md5, "application/octet-stream") } + Request("PUT", "manifest.xml", xmlMd5, "text/xml")
val signed = authorize(lock, requests)
for ((i, pair) in added.withIndex()) upload(signed[i], pair.second)
upload(signed.last(), xml)
found = true
for ((entry, _) in added) {
val name = entry.localName.substring(base.length)
committed[name] = CloudFile(name, parseTime(entry.modified), hex(entry.md5), readLink = entry.href)
}
listed = null
files.mapValues { (name, _) -> modifiedMs[name]?.takeIf { it > 0 } ?: now }
}
}
private fun pick(): Manifest? {
for (candidate in keys) {
val manifest = locked("read", candidate, missing = { null }) { _, body -> manifestUrl(body)?.let { fetchManifest(it) } }
if (manifest != null) {
key = candidate
found = true
return manifest
}
}
key = keys.first()
found = false
return null
}
private fun upload(signed: Signed, data: ByteArray) {
val reply = EaHttp.request(signed.url, "PUT", signed.headers, data)
check(reply.ok) { "EA cloud save upload answered ${reply.status}" }
}
private fun fetchManifest(url: String): Manifest? {
val reply = EaHttp.request(url)
if (reply.status == 404) return null
check(reply.ok) { "EA cloud save manifest answered ${reply.status}" }
return parse(reply.text)
}
private fun <T> locked(kind: String, key: String, missing: (() -> T)? = null, body: (String, String) -> T): T {
val reply = EaHttp.request("$HOST/lock/$kind/$uid/$key", "POST", mapOf(AUTH to token, "Content-Type" to "application/xml"), ByteArray(0))
if (reply.status == 404 && missing != null) return missing()
check(reply.ok) { "EA cloud saves answered ${reply.status}" }
val lock = reply.header(LOCK) ?: error("EA did not grant a cloud save lock")
try {
return body(lock, reply.text)
} finally {
runCatching { EaHttp.request("$HOST/lock/delete/$uid", "DELETE", mapOf(AUTH to token, LOCK to lock)) }
}
}
private fun authorize(lock: String, requests: List<Request>): List<Signed> {
val body = buildString {
append("<requests>")
for ((i, r) in requests.withIndex()) {
append("<request id=\"").append(i).append("\"><verb>").append(r.verb).append("</verb><resource>").append(escape(r.resource)).append("</resource>")
r.md5?.let { append("<md5>").append(it).append("</md5>") }
r.type?.let { append("<content-type>").append(it).append("</content-type>") }
append("</request>")
}
append("</requests>")
}
val reply = EaHttp.request("$HOST/lock/authorize/$uid", "PUT", mapOf(AUTH to token, LOCK to lock, "Content-Type" to "application/xml"), body.toByteArray())
check(reply.ok) { "EA cloud saves refused the transfer (${reply.status})" }
return signedRequests(reply.text, requests.size)
}
companion object {
private const val HOST = "https://cloudsync.juno.ea.com"
private const val AUTH = "X-Origin-AuthToken"
private const val LOCK = "X-Origin-Sync-Lock"
private val REQUEST = Regex("<request\\b[^>]*\\bid=\"(\\d+)\"[^>]*>(.*?)</request>", RegexOption.DOT_MATCHES_ALL)
private val HEADER = Regex("<header\\b([^>]*)/?>")
fun keys(masterTitleId: String, multiplayerId: String): List<String> =
if (multiplayerId.isNotEmpty()) listOf("${masterTitleId}_$multiplayerId") else listOf(masterTitleId, "${masterTitleId}_$masterTitleId")
fun manifestUrl(lockBody: String): String? = Regex("<manifest>([^<]+)</manifest>").find(lockBody)?.groupValues?.get(1)?.let(::unescape)
fun parse(xml: String): Manifest {
val p = Xml.newPullParser().apply { setInput(StringReader(xml)) }
var root: String? = null
var lineage: String? = null
var depth = 0
var closed = false
val files = ArrayList<Entry>()
val snapshots = ArrayList<String>()
var file: Array<String>? = null
var local: Entry? = null
runCatching {
while (p.next() != XmlPullParser.END_DOCUMENT) when (p.eventType) {
XmlPullParser.START_TAG -> {
depth++
val at = { name: String -> p.getAttributeValue(null, name).orEmpty() }
when {
root == null -> { root = p.name; lineage = p.getAttributeValue(null, "lineage") }
depth == 2 && p.name == "file" -> { file = arrayOf(at("size"), at("href"), at("md5")); local = null }
depth == 3 && p.name == "localName" && file != null -> {
val f = file!!
val created = at("created")
val modified = at("lastModified")
local = Entry(f[0].toLongOrNull() ?: 0, f[1], f[2], created, modified, p.nextText())
depth--
}
depth == 2 && p.name == "snapshot" -> { snapshots += p.nextText(); depth-- }
}
}
XmlPullParser.END_TAG -> {
if (depth == 2 && p.name == "file") { local?.let(files::add); file = null }
depth--
if (depth == 0) closed = true
}
}
}.onFailure { error("EA sent an incomplete cloud save manifest") }
check(root == "manifest" && depth == 0 && closed) { "EA sent an incomplete cloud save manifest" }
return Manifest(lineage ?: "{00000000-0000-0000-0000-000000000000}", files, snapshots)
}
fun write(m: Manifest): String = buildString {
append("<manifest xmlns=\"http://origin.com/cloudsaves/manifest\" lineage=\"").append(escape(m.lineage)).append("\">\n")
for (f in m.files) {
append(" <file size=\"").append(f.size).append("\" href=\"").append(escape(f.href)).append("\" md5=\"").append(escape(f.md5)).append("\">\n")
append(" <localName created=\"").append(escape(f.created)).append("\" lastModified=\"").append(escape(f.modified)).append("\">")
append(escape(f.localName)).append("</localName>\n </file>\n")
}
for (s in m.snapshots) append(" <snapshot>").append(escape(s)).append("</snapshot>\n")
append("</manifest>\n")
}
private fun signedRequests(xml: String, count: Int): List<Signed> {
val byId = REQUEST.findAll(xml).associate { m ->
val inner = m.groupValues[2]
val url = Regex("<url>([^<]+)</url>").find(inner)?.groupValues?.get(1)?.let(::unescape) ?: error("EA sent no transfer URL")
val headers = HEADER.findAll(inner).mapNotNull { h ->
val k = attr(h.groupValues[1], "key") ?: return@mapNotNull null
k to (attr(h.groupValues[1], "value") ?: "")
}.toMap()
m.groupValues[1].toInt() to Signed(url, headers)
}
return (0 until count).map { byId[it] ?: error("EA signed ${byId.size} of $count cloud save transfers") }
}
fun stamp(ms: Long): String = Instant.ofEpochMilli(ms / 1000 * 1000).toString() + "Z"
fun parseTime(s: String): Long = runCatching { Instant.parse(s.trimEnd('Z') + "Z").toEpochMilli() }.getOrDefault(-1L)
private fun attr(attrs: String, name: String): String? = Regex("\\b$name=\"([^\"]*)\"").find(attrs)?.groupValues?.get(1)?.let(::unescape)
private fun md5(data: ByteArray) = MessageDigest.getInstance("MD5").digest(data)
private fun b64(sum: ByteArray) = Base64.encodeToString(sum, Base64.NO_WRAP)
private fun hexOf(sum: ByteArray) = sum.joinToString("") { "%02x".format(it) }
fun hex(b64: String): String? = runCatching { hexOf(Base64.decode(b64, Base64.DEFAULT)) }.getOrNull()?.takeIf { it.length == 32 }
private fun escape(s: String) = s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;")
private fun unescape(s: String) = EaSaveRules.unescape(s)
}
}
@@ -0,0 +1,84 @@
package com.droiddeck.launcher.stores.ea
internal class EaSaveRules(private val rules: List<Pair<Boolean, String>>) {
val includes get() = rules.filter { it.first }.map { it.second }
val excludes get() = rules.filterNot { it.first }.map { it.second }
fun base(): String? {
val dirs = includes.filterNot(::bare).map { pattern ->
val wild = pattern.indexOfFirst { it == '*' || it == '?' }
val fixed = if (wild < 0) pattern else pattern.substring(0, wild)
if (fixed.endsWith('/')) fixed else fixed.substringBeforeLast('/', "") + "/"
}
val parts = dirs.map { it.trimEnd('/').split('/') }
if (parts.isEmpty()) return null
val common = ArrayList<String>()
for (i in parts.minOf { it.size }.let { 0 until it }) {
val seg = parts[0][i]
if (parts.all { it[i].equals(seg, ignoreCase = true) }) common += seg else break
}
if (common.isEmpty() || !VARIABLE.matches(common[0])) return null
return common.joinToString("/") + "/"
}
fun matches(path: String): Boolean {
val p = normalize(path)
val inside = base()?.let { p.startsWith(it, ignoreCase = true) } ?: false
return rules.firstOrNull { (_, pattern) -> if (bare(pattern)) inside && hit(pattern, p.substringAfterLast('/')) else hit(pattern, p) }?.first ?: false
}
private fun bare(pattern: String) = !pattern.startsWith('%') && '/' !in pattern
private fun hit(pattern: String, path: String): Boolean = when {
pattern.endsWith('/') -> path.startsWith(pattern, ignoreCase = true)
pattern.any { it == '*' || it == '?' } -> glob(pattern).matches(path)
else -> path.equals(pattern, ignoreCase = true)
}
private fun glob(pattern: String): Regex = Regex(
pattern.split('*').joinToString("[^/]*") { part -> part.split('?').joinToString("[^/]") { Regex.escape(it) } },
RegexOption.IGNORE_CASE,
)
companion object {
private val VARIABLE = Regex("%[A-Za-z]+%")
private val RULE = Regex("<(include|exclude)\\b([^>]*)>([^<]*)</\\1>", RegexOption.IGNORE_CASE)
private val ORDER = Regex("\\border\\s*=\\s*[\"']?(\\d+)")
private val TOKENS = mapOf(
"documents" to "%DOCUMENTS%", "savedgames" to "%SAVED_GAMES%", "appdata" to "%APPDATA%",
"localappdata" to "%LOCALAPPDATA%", "programdata" to "%PROGRAMDATA%", "userprofile" to "%USERPROFILE%",
"locallowappdata" to "%APPLICATION_DATA_LOCAL_LOW%", "installdir" to "%INSTALL%",
)
private val COMMENT = Regex("<!--.*?-->", RegexOption.DOT_MATCHES_ALL)
private val ENTITY = Regex("&(#x[0-9a-fA-F]+|#[0-9]+|lt|gt|quot|apos|amp);")
fun normalize(path: String) = path.replace('\\', '/')
fun parse(xml: String): EaSaveRules? {
val rules = RULE.findAll(COMMENT.replace(xml, "")).mapIndexed { index, rule ->
val order = ORDER.find(rule.groupValues[2])?.groupValues?.get(1)?.toIntOrNull() ?: index
Triple(order, rule.groupValues[1].equals("include", true), normalize(unescape(rule.groupValues[3]).trim()))
}.filter { it.third.isNotEmpty() }.sortedBy { it.first }.map { it.second to it.third }.toList()
if (rules.none { it.first }) return null
return EaSaveRules(rules)
}
fun template(base: String): String? {
val variable = VARIABLE.find(base)?.takeIf { it.range.first == 0 } ?: return null
val token = TOKENS[variable.value.trim('%').lowercase()] ?: return null
return token + base.substring(variable.value.length)
}
fun unescape(s: String): String = ENTITY.replace(s) { m ->
when (val e = m.groupValues[1]) {
"lt" -> "<"
"gt" -> ">"
"quot" -> "\""
"apos" -> "'"
"amp" -> "&"
else -> runCatching { String(Character.toChars(if (e.startsWith("#x")) e.substring(2).toInt(16) else e.substring(1).toInt())) }.getOrDefault(m.value)
}
}
}
}
@@ -15,23 +15,44 @@ object UbisoftActivation {
private const val POLL_MS = 250L
private const val IDLE_MS = 60_000L
private val watching = HashMap<Long, Long>()
private val owners = HashMap<Long, String>()
private const val INVALIDATE = "denuvo-invalidate"
fun bridge(context: Context, product: Long) = File(LinuxRuntime.rootDir(context), "root/.cache/droiddeck/ubisoft/bridge-$product")
/** Starts answering the product's activations; stale requests are cleared before this returns. */
fun watch(app: Context, product: Long) {
fun watch(app: Context, product: Long, owner: String?) {
val dir = bridge(app, product)
synchronized(watching) {
val running = watching.containsKey(product)
watching[product] = System.currentTimeMillis()
if (owner.isNullOrEmpty()) owners.remove(product) else owners[product] = owner
if (running) return
dir.mkdirs()
dir.listFiles()?.forEach { it.delete() }
dir.listFiles()?.forEach { if (it.name != INVALIDATE) it.delete() }
}
Thread({
var idleSince = 0L
while (true) {
runCatching { dir.listFiles { f -> f.name.startsWith("denuvo-") && f.name.endsWith(".req") }?.forEach { answer(app, product, it) } }
runCatching {
val marker = File(dir, INVALIDATE)
val (owner, requests) = synchronized(watching) {
owners[product] to dir.listFiles { f -> f.name.startsWith("denuvo-") && f.name.endsWith(".req") }.orEmpty()
}
if (marker.exists()) {
val named = runCatching { marker.readText().trim() }.getOrNull()?.takeIf { it.isNotEmpty() }
val issuer = named ?: owner
if (invalidate(app, product, issuer)) marker.delete()
else if (named == null && issuer != null) runCatching {
val part = File(dir, "$INVALIDATE.part")
part.writeText(issuer)
check(part.renameTo(marker))
}
}
val pending = marker.exists()
requests.forEach { answer(app, product, it, owner, pending) }
}
.onFailure { StoresState.logLine("Ubisoft: activation for $product: ${it.javaClass.simpleName}") }
val now = System.currentTimeMillis()
if (SessionState.running) idleSince = 0L
@@ -44,18 +65,31 @@ object UbisoftActivation {
}, "ubisoft-activation-$product").start()
}
private fun answer(app: Context, product: Long, request: File) {
private fun answer(app: Context, product: Long, request: File, owner: String?, pending: Boolean) {
val challenge = runCatching { request.readBytes() }.getOrNull() ?: return
request.delete()
val reply = File(request.parentFile, request.name.removeSuffix(".req") + ".rsp")
val token = activate(app, product, challenge)
val reply = File(request.parentFile, request.name.removeSuffix(".req").removeSuffix(".cache") + ".rsp")
val token = activate(app, product, challenge, owner, cached = request.name.endsWith(".cache.req") && !pending)
val part = File(reply.path + ".part")
part.writeBytes(token ?: ByteArray(0))
part.renameTo(reply)
}
private fun activate(app: Context, product: Long, challenge: ByteArray): ByteArray? {
private fun invalidate(app: Context, product: Long, owner: String?): Boolean {
val user = owner ?: return false
val gone = TokenCache(cacheDir(app)).drop(user, product)
if (gone) StoresState.logLine("Ubisoft: activation for $product: kept game token dropped")
return gone
}
private fun activate(app: Context, product: Long, challenge: ByteArray, owner: String?, cached: Boolean): ByteArray? {
val s = UbisoftAuth.current(app) ?: return null.also { StoresState.logLine("Ubisoft: activation for $product: signed out") }
if (owner == null || s.userId != owner) return null.also { StoresState.logLine("Ubisoft: activation for $product: the signed-in account changed") }
val cache = TokenCache(cacheDir(app))
if (cached) cache.get(s.userId, product)?.let {
StoresState.logLine("Ubisoft: activation for $product: kept ${it.size} B game token")
return it
}
val answer = UbisoftNative.call("denuvo", JSONObject().put("ticket", s.ticket).put("sessionId", s.sessionId)
.put("productId", product).put("challenge", hex(challenge)))
answer?.optString("error")?.takeIf { it.isNotEmpty() }?.let {
@@ -64,9 +98,28 @@ object UbisoftActivation {
}
val token = answer?.optString("token")?.takeIf { it.isNotEmpty() }?.let(::unhex)
StoresState.logLine("Ubisoft: activation for $product: ${token?.size ?: 0} B game token")
if (token != null && !cache.put(s.userId, product, token)) StoresState.logLine("Ubisoft: activation for $product: game token not kept")
return token
}
private fun cacheDir(app: Context) = File(app.filesDir, "ubisoft/denuvo")
internal class TokenCache(private val dir: File) {
private fun file(user: String, product: Long) = File(dir, "${user.filter { it.isLetterOrDigit() || it == '-' }}-$product.token")
fun get(user: String, product: Long): ByteArray? = runCatching { file(user, product).readBytes() }.getOrNull()?.takeIf { it.isNotEmpty() }
fun put(user: String, product: Long, token: ByteArray): Boolean = runCatching {
dir.mkdirs()
val target = file(user, product)
val part = File(target.path + ".part")
part.writeBytes(token)
check(part.renameTo(target))
}.isSuccess
fun drop(user: String, product: Long): Boolean = file(user, product).let { it.delete() || !it.exists() }
}
internal fun hex(b: ByteArray): String = b.joinToString("") { "%02x".format(it) }
internal fun unhex(s: String): ByteArray? =
@@ -168,14 +168,14 @@ object UbisoftLibrary {
internal fun assemble(listed: List<CatalogItem>, owned: JSONObject?): List<CatalogItem> {
val known = owned?.optJSONArray("games") != null && owned.optString("error").isEmpty()
val bySpace = ownedBySpace(owned)
val matched = listed.map { g -> bySpace[g.id]?.let { g.copy(extra = g.extra + download(it)) } ?: g }
val matched = listed.map { g -> bySpace[g.id]?.let { withArt(g.copy(extra = g.extra + download(it)), it) } ?: g }
.filter { !known || it.extra["productId"] != null }
.let { games -> games.filter { g -> g.extra["productId"] == null || games.first { it.extra["productId"] == g.extra["productId"] } === g } }
.let { games -> games.filter { g -> g.extra["productId"] != null || games.none { it !== g && it.title == g.title && it.extra["productId"] != null } } }
val products = matched.mapNotNull { it.extra["productId"] }.toSet()
val unlisted = bySpace.filterKeys { space -> listed.none { it.id == space } }.filterValues { it.optLong("productId").toString() !in products }.mapNotNull { (space, o) ->
val title = title(o.optString("configuration")) ?: return@mapNotNull null
CatalogItem(Store.UBISOFT, space, title, null, owned = true, extra = mapOf("spaceId" to space) + download(o))
withArt(CatalogItem(Store.UBISOFT, space, title, null, owned = true, extra = mapOf("spaceId" to space) + download(o)), o)
}
return (matched + unlisted).sortedBy { it.title.lowercase() }
}
@@ -184,12 +184,36 @@ object UbisoftLibrary {
private val NAME = Regex("""^\s{1,4}name:\s*['"]?(.+?)['"]?\s*$""", RegexOption.MULTILINE)
/** The default text of a localisation key such as `l1` or `THUMBIMAGE`. */
private fun localized(configuration: String, key: String): String? {
if (!Regex("""\w+""").matches(key)) return null
val local = configuration.indexOf("localizations:").takeIf { it >= 0 } ?: return null
return Regex("""^\s+${key}:\s*['"]?(.+?)['"]?\s*$""", RegexOption.MULTILINE).find(configuration, local)?.groupValues?.get(1)?.trim()
}
/** The product's name from its configuration, following a localisation key such as `l1` to its default text. */
internal fun title(configuration: String): String? {
val raw = NAME.find(configuration)?.groupValues?.get(1)?.trim()?.takeIf { it.isNotEmpty() } ?: return null
if (!Regex("""l\d+""").matches(raw)) return raw
val local = configuration.indexOf("localizations:").takeIf { it >= 0 } ?: return raw
return Regex("""^\s+${raw}:\s*['"]?(.+?)['"]?\s*$""", RegexOption.MULTILINE).find(configuration, local)?.groupValues?.get(1)?.trim() ?: raw
return localized(configuration, raw) ?: raw
}
private const val ASSETS = "https://static3.cdn.ubi.com/orbit/uplay_launcher_3_0/assets/"
private val ASSET = Regex("""[\w.-]+\.(?:jpe?g|png)""", RegexOption.IGNORE_CASE)
/** The URL of an image the configuration's `root` names, such as `thumb_image`, following a localisation key to its file. */
internal fun image(configuration: String, key: String): String? {
val raw = Regex("""^ {1,2}${key}:[ \t]*['"]?([^'"\r\n]+?)['"]?[ \t]*$""", RegexOption.MULTILINE).find(configuration)?.groupValues?.get(1)?.trim() ?: return null
val file = raw.takeIf { ASSET.matches(it) } ?: localized(configuration, raw)?.takeIf { ASSET.matches(it) } ?: return null
return ASSETS + file
}
/** Art the profile's game list lacks, from the product's configuration: games Connect owns but the list leaves out have none. */
private fun withArt(g: CatalogItem, owned: JSONObject): CatalogItem {
if (g.imageUrl != null && g.tallImageUrl != null) return g
val configuration = owned.optString("configuration")
val thumb = image(configuration, "thumb_image")
return g.copy(imageUrl = g.imageUrl ?: image(configuration, "background_image") ?: thumb, tallImageUrl = g.tallImageUrl ?: thumb)
}
/** The first launch path under `start_game` in a product's configuration. */
@@ -0,0 +1,220 @@
package com.droiddeck.launcher.stores.ubisoft
import android.os.Build
import android.util.Base64
import com.droiddeck.launcher.stores.CloudChanged
import com.droiddeck.launcher.stores.CloudFile
import com.droiddeck.launcher.stores.CloudTransport
import org.json.JSONArray
import org.json.JSONObject
import java.io.ByteArrayOutputStream
import java.net.HttpURLConnection
import java.net.URL
import java.security.MessageDigest
import java.time.Instant
import java.util.zip.Deflater
import java.util.zip.Inflater
internal interface UbisoftSlots {
fun entity(): UbisoftCloud.Entity?
fun upload(slot: String, data: ByteArray)
fun update(entity: UbisoftCloud.Entity, slots: JSONArray)
fun download(slot: String): ByteArray?
}
internal class UbisoftCloud(private val session: UbisoftAuth.Session, val product: Long) : UbisoftSlots {
class Slot(val id: Int, val filename: String, val hash: String, val size: Long, val modifiedMs: Long)
class Entity(val json: JSONObject) {
val id: String get() = json.optString("entityId")
val revision: Int get() = json.optInt("revision")
val slots: List<Slot> get() {
val list = json.optJSONObject("obj")?.optJSONArray("slots") ?: JSONArray()
return (0 until list.length()).mapNotNull { list.optJSONObject(it) }.map {
Slot(it.optInt("id"), it.optString("filename"), it.optString("hash"), it.optLong("size"), UbisoftAuth.parseTime(it.optString("lastModified")))
}
}
}
private val authorization get() = "ubi_v1 t=${session.ticket}"
override fun entity(): Entity? {
val url = "https://public-ubiservices.ubi.com/v1/profiles/${session.profileId}/entities?name=${entityName(product)}"
val reply = UbisoftAuth.request(url, authorization = authorization, sessionId = session.sessionId)
check(reply.ok) { "Ubisoft cloud saves answered ${reply.status}" }
val list = JSONObject(reply.body).optJSONArray("entities") ?: return null
return (0 until list.length()).mapNotNull { list.optJSONObject(it) }.firstOrNull { it.optString("name") == entityName(product) }?.let(::Entity)
}
override fun upload(slot: String, data: ByteArray) {
val packed = deflate(data)
val md5 = Base64.encodeToString(MessageDigest.getInstance("MD5").digest(packed), Base64.NO_WRAP)
val signed = signed("put", JSONArray().put(JSONObject().put("name", slot).put("size", packed.size).put("md5", md5))).single()
val c = URL(signed.getString("url")).openConnection() as HttpURLConnection
c.connectTimeout = 15_000
c.readTimeout = 60_000
c.requestMethod = "PUT"
c.doOutput = true
c.setFixedLengthStreamingMode(packed.size)
c.setRequestProperty("Content-MD5", md5)
try {
c.outputStream.use { it.write(packed) }
check(c.responseCode in 200..299) { "Ubisoft cloud save upload answered ${c.responseCode}" }
} finally {
c.disconnect()
}
}
override fun update(entity: Entity, slots: JSONArray) {
val obj = JSONObject(entity.json.optJSONObject("obj")?.toString() ?: "{}")
.put("slots", slots).put("timestamp", (System.currentTimeMillis() / 1000).toString()).put("pc_name", Build.MODEL ?: "Android")
val body = JSONObject().put("revision", entity.revision).put("name", entity.json.optString("name")).put("type", "cloudSave")
.put("spaceId", entity.json.optString("spaceId")).put("tags", entity.json.optJSONArray("tags") ?: JSONArray()).put("obj", obj)
val reply = UbisoftAuth.request("https://public-ubiservices.ubi.com/v1/profiles/entities/${entity.id}", "PUT",
authorization, session.sessionId, body.toString())
check(reply.ok) { "Ubisoft cloud save record answered ${reply.status}" }
}
override fun download(slot: String): ByteArray? {
val signed = signed("get", JSONArray().put(JSONObject().put("name", slot))).single()
val c = URL(signed.getString("url")).openConnection() as HttpURLConnection
c.connectTimeout = 15_000
c.readTimeout = 60_000
return try {
when (c.responseCode) {
404 -> null
in 200..299 -> c.inputStream.use(::inflate)
else -> error("Ubisoft cloud save download answered ${c.responseCode}")
}
} finally {
c.disconnect()
}
}
private fun signed(method: String, items: JSONArray): List<JSONObject> {
val answer = UbisoftNative.call("cloud-urls", JSONObject().put("ticket", session.ticket).put("sessionId", session.sessionId)
.put("productId", product).put("method", method).put("items", items)) ?: error("Ubisoft cloud saves are unavailable")
answer.optString("error").takeIf { it.isNotEmpty() }?.let { error(it) }
val requests = answer.getJSONArray("requests")
return (0 until requests.length()).map { requests.getJSONObject(it) }
}
companion object {
private const val MAX_SAVE = 256L * 1024 * 1024
fun entityName(product: Long) = "upcCloudSaveUplayId_$product"
private val MARK = Regex("[0-9a-f]{32}")
internal fun freshMark(): String = java.util.UUID.randomUUID().toString().replace("-", "")
internal fun mark(save: ByteArray): String? =
if (save.size < 40) null else String(save, 8, 32, Charsets.ISO_8859_1).takeIf { MARK.matches(it) }
internal fun deflate(data: ByteArray): ByteArray {
val deflater = Deflater(Deflater.BEST_COMPRESSION)
deflater.setInput(data)
deflater.finish()
val out = ByteArrayOutputStream(data.size / 2 + 64)
val buffer = ByteArray(64 * 1024)
try {
while (!deflater.finished()) out.write(buffer, 0, deflater.deflate(buffer))
} finally {
deflater.end()
}
return out.toByteArray()
}
internal fun inflate(data: ByteArray): ByteArray = inflate(data.inputStream())
internal fun inflate(input: java.io.InputStream): ByteArray {
val inflater = Inflater()
val out = ByteArrayOutputStream(64 * 1024)
val buffer = ByteArray(64 * 1024)
val chunk = ByteArray(64 * 1024)
try {
while (!inflater.finished()) {
if (inflater.needsInput()) {
val read = input.read(chunk)
if (read < 0) error("Ubisoft cloud save is truncated")
inflater.setInput(chunk, 0, read)
continue
}
if (inflater.needsDictionary()) error("Ubisoft cloud save is truncated")
val n = inflater.inflate(buffer)
check(out.size().toLong() + n <= MAX_SAVE) { "Ubisoft cloud save is too large" }
out.write(buffer, 0, n)
}
} finally {
inflater.end()
}
return out.toByteArray()
}
internal fun version(slot: Slot): String = "${slot.size}:${slot.modifiedMs}:${slot.hash}"
}
}
internal class UbisoftCloudTransport(private val cloud: UbisoftSlots, val user: String) : CloudTransport {
private var listed: UbisoftCloud.Entity? = null
private val committed = HashMap<String, CloudFile>()
override val contentDigests: Boolean get() = false
override fun committed(name: String): CloudFile? = committed[name]
override fun wants(name: String): Boolean = name.endsWith(SUFFIX) && !name.contains('/')
override fun list(): List<CloudFile> {
val entity = cloud.entity()
listed = entity
return entity?.slots.orEmpty().map { CloudFile(it.filename + SUFFIX, it.modifiedMs, UbisoftCloud.version(it)) }
}
override fun get(file: CloudFile): Pair<ByteArray, Long> {
val data = cloud.download(file.name.removeSuffix(SUFFIX)) ?: error("Ubisoft has no data for ${file.name}")
return data to file.modifiedMs
}
override fun put(files: Map<String, ByteArray>, modifiedMs: Map<String, Long>): Map<String, Long> {
var expected = listed ?: cloud.entity() ?: error("Ubisoft has no cloud save record for this game yet; play it once in Ubisoft Connect")
val marks = files.mapValues { (name, data) ->
check(name.endsWith(SUFFIX) && !name.contains('/')) { "$name is not a Ubisoft save slot" }
UbisoftCloud.mark(data) ?: error("$name has no save identifier for Ubisoft Connect")
}
val sent = LinkedHashMap<String, Long>()
try {
for ((name, data) in files) {
val slot = name.removeSuffix(SUFFIX)
val live = cloud.entity() ?: error("Ubisoft's cloud save record disappeared")
if (live.revision != expected.revision) throw CloudChanged(sent, files.keys.filter { it !in sent })
val now = System.currentTimeMillis()
cloud.upload(slot, data)
val slots = JSONArray(live.json.optJSONObject("obj")?.optJSONArray("slots")?.toString() ?: "[]")
val entry = (0 until slots.length()).map { slots.getJSONObject(it) }.firstOrNull { it.optString("filename") == slot }
?: JSONObject().put("filename", slot).also { if (slot.toIntOrNull() != null) it.put("id", slot.toInt()); slots.put(it) }
entry.put("hash", marks.getValue(name)).put("size", data.size).put("lastModified", Instant.ofEpochMilli(now).toString())
cloud.update(live, slots)
val after = cloud.entity()
val mine = after?.let { committedSlot(live, it, slot, marks.getValue(name), data.size.toLong()) }
?: throw CloudChanged(sent, files.keys.filter { it !in sent })
sent[name] = now
committed[name] = CloudFile(name, mine.modifiedMs, UbisoftCloud.version(mine))
expected = after
}
} finally {
listed = null
}
return sent
}
companion object {
const val SUFFIX = ".save"
internal fun committedSlot(before: UbisoftCloud.Entity, after: UbisoftCloud.Entity, filename: String, hash: String, size: Long): UbisoftCloud.Slot? {
fun others(e: UbisoftCloud.Entity) = e.slots.filter { it.filename != filename }.associate { it.filename to UbisoftCloud.version(it) }
if (others(before) != others(after)) return null
return after.slots.firstOrNull { it.filename == filename && it.hash == hash && it.size == size }
}
}
}
@@ -58,7 +58,7 @@ object UbisoftLaunch {
}
} ?: cached
setup?.let { StoresState.logLine("Ubisoft: setup for $product: ${it.toString().take(1500)}") }
UbisoftActivation.watch(app, product)
UbisoftActivation.watch(app, product, s.userId)
return JSONObject().put("ok", true)
.put("productId", product)
.put("ticket", native.optString("ticket"))
@@ -112,11 +112,21 @@ object XboxBackend : StoreBackend {
fun selectPackage(context: Context, choice: org.json.JSONObject) {
val pending = packageChoice ?: return
packageChoice = null
val item = pending.item.copy(extra = pending.item.extra + ("contentId" to choice.getString("contentId")))
val item = pending.item.chosen(choice)
com.droiddeck.launcher.stores.download.SavedQueue.remember(context, item, pending.root)
enqueue(context.applicationContext, item, pending.root)
}
/**
* The picker can offer a package in a different container format than the
* catalogue listed, and the installer dispatches on that format, so the
* choice decides it and the catalogue value only fills a missing one.
*/
private fun CatalogItem.chosen(choice: org.json.JSONObject): CatalogItem {
val format = choice.optString("packageFormat").takeIf { it.isNotBlank() } ?: extra["format"].orEmpty()
return copy(extra = extra + mapOf("contentId" to choice.getString("contentId"), "format" to format))
}
override fun install(context: Context, item: CatalogItem, root: File) {
val app = context.applicationContext
if (!item.extra["baseId"].isNullOrBlank()) { XboxContent.install(app, item); return }
@@ -128,7 +138,7 @@ object XboxBackend : StoreBackend {
val choices = XboxCatalog.objects(plan.getJSONArray("choices")).filter { it.optBoolean("supported") && it.optString("kind") == "Game" }
check(choices.isNotEmpty()) { "This offer has no supported PC package." }
if (plan.getString("status") == "ready" && choices.size == 1) {
val selected = item.copy(extra = item.extra + ("contentId" to choices.single().getString("contentId")))
val selected = item.chosen(choices.single())
com.droiddeck.launcher.stores.download.SavedQueue.remember(app, selected, root)
enqueue(app, selected, root)
} else StoresState.post { packageChoice = PackageChoice(item, root, choices) }
@@ -18,6 +18,14 @@ internal object XboxCatalog {
"CFQ7TTC10QFD" to "Xbox Game Pass (Starter Edition)",
)
/**
* The formats the installer can put on disk, so the catalogue never lists a
* title it cannot install. `MSIXVC` streams in place; an EAppx container is a
* legacy package that takes `legacy-install` instead.
*/
internal fun installableFormat(format: String): Boolean =
format.equals("MSIXVC", true) || format.equals("EAPPX", true) || format.equals("EAPPXBUNDLE", true)
fun access(json: JSONObject, account: String, market: String, now: Instant = Instant.now(), report: (String) -> Unit = {}): Map<String, String> {
require(json.getInt("schema") == 1 && json.getString("account") == account && json.getString("market") == market)
val age = java.time.Duration.between(timestamp(json.getString("checkedAt")), now).seconds
@@ -102,11 +110,15 @@ internal object XboxCatalog {
if (!productId.matches(id) || json.optString("ProductType") != "Game") return null
val localized = objects(json.optJSONArray("LocalizedProperties")).firstOrNull() ?: return null
val title = localized.optString("ProductTitle").takeIf { it.isNotBlank() } ?: return null
val packages = objects(json.optJSONArray("DisplaySkuAvailabilities")).flatMap {
objects(it.optJSONObject("Sku")?.optJSONObject("Properties")?.optJSONArray("Packages"))
}
val packages = objects(json.optJSONArray("DisplaySkuAvailabilities"))
.mapNotNull { it.optJSONObject("Sku")?.optJSONObject("Properties") }
.filter { it.opt("IsTrial") != true && it.opt("IsPreOrder") != true }
.flatMap { objects(it.optJSONArray("Packages")) }
val pc = packages.filter { pkg -> objects(pkg.optJSONArray("PlatformDependencies")).any { it.optString("PlatformName") == "Windows.Desktop" } }
val installable = pc.any { it.optString("PackageFormat").equals("MSIXVC", true) }
val installable = pc.any { installableFormat(it.optString("PackageFormat")) }
// The installer needs the format, not just the fact that one exists: a
// legacy container takes a different subcommand from a streamed package.
val format = pc.firstOrNull { installableFormat(it.optString("PackageFormat")) }?.optString("PackageFormat").orEmpty()
val streams = cloud?.streams(id, access[id].orEmpty()) == true
if (!installable && !streams) return null
val images = objects(localized.optJSONArray("Images"))
@@ -129,7 +141,8 @@ internal object XboxCatalog {
publisher = localized.optString("PublisherName"), developer = localized.optString("DeveloperName"),
description = localized.optString("ProductDescription"),
sizeBytes = if (installable) pc.maxOfOrNull { it.optLong("MaxDownloadSizeInBytes") } ?: 0L else 0L,
extra = mapOf("market" to Xodus.market(), "access" to kind.orEmpty(), "pc" to flag(installable), "cloud" to flag(streams)),
extra = mapOf("market" to Xodus.market(), "access" to kind.orEmpty(), "pc" to flag(installable),
"cloud" to flag(streams), "format" to format),
)
}
@@ -40,7 +40,8 @@ internal object XboxContent {
val item = CatalogItem(Store.XBOX, id, localized?.optString("ProductTitle")?.ifBlank { id } ?: id,
imageUrl = base.sidecar.cover, owned = access == "owned", subscription = access == "gamepass",
sizeBytes = pkg.optLong("MaxDownloadSizeInBytes"),
extra = mapOf("baseId" to base.sidecar.id, "contentId" to cid, "market" to market, "family" to pkg.getString("PackageFamilyName")))
extra = mapOf("baseId" to base.sidecar.id, "contentId" to cid, "market" to market,
"family" to pkg.getString("PackageFamilyName"), "format" to pkg.optString("PackageFormat")))
Offer(item, File(base.folder, ".xbox-content/$id/.droiddeck-content.json").isFile)
}
StoresState.post { plan = Plan(base, offers) }
@@ -51,7 +52,7 @@ internal object XboxContent {
private fun packages(product: JSONObject?): List<JSONObject> = XboxCatalog.objects(product?.optJSONArray("DisplaySkuAvailabilities"))
.filter { it.optJSONObject("Sku")?.optJSONObject("Properties")?.optBoolean("IsTrial", true) == false }
.flatMap { XboxCatalog.objects(it.optJSONObject("Sku")?.optJSONObject("Properties")?.optJSONArray("Packages")) }
.filter { pkg -> pkg.optString("PackageFormat") == "MSIXVC" &&
.filter { pkg -> XboxCatalog.installableFormat(pkg.optString("PackageFormat")) &&
XboxCatalog.objects(pkg.optJSONArray("PlatformDependencies")).any { it.optString("PlatformName") == "Windows.Desktop" } }
private val parents = java.util.concurrent.ConcurrentHashMap<String, String>()
@@ -249,10 +249,17 @@ internal class XboxCredentials(private val app: Context, expectedGeneration: Str
block(current)
}
fun invalidate(app: Context, revoked: () -> Unit = {}) = storage(app) {
java.io.File(StoreAccounts.dir(app, Store.XBOX), "generation").writeText(UUID.randomUUID().toString())
StoreAccounts.clear(app, Store.XBOX)
revoked()
try {
java.io.File(StoreAccounts.dir(app, Store.XBOX), "generation").writeText(UUID.randomUUID().toString())
val device = StoreAccounts.read(app, Store.XBOX)?.optJSONObject("slots")?.opt(DEVICE_SLOT)
val kept = device != null && runCatching { StoreAccounts.write(app, Store.XBOX, deviceOnly(device)) }.isSuccess
if (!kept) StoreAccounts.clear(app, Store.XBOX)
} finally {
revoked()
}
}
internal const val DEVICE_SLOT = "dev_license"
internal fun deviceOnly(device: Any): JSONObject = JSONObject().put("slots", JSONObject().put(DEVICE_SLOT, device))
fun <T> storage(app: Context, block: () -> T): T = synchronized(lock) {
java.io.RandomAccessFile(java.io.File(StoreAccounts.dir(app, Store.XBOX), "account.lock"), "rw").use { file ->
file.channel.lock().use { block() }
@@ -15,6 +15,10 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
private val paused = CountDownLatch(1)
@Volatile private var child: Xodus.Child? = null
@Volatile private var delete = false
/** A legacy container has no pause protocol: the downloader is killed instead. */
private val legacy = item.extra["format"]?.lowercase() in setOf("eappx", "eappxbundle")
/** Release builds hide logcat from adb, so the tail is reported in the failure itself. */
private val errors = java.util.concurrent.ConcurrentLinkedQueue<String>()
override fun run(handle: DownloadQueue.JobHandle): String? {
if (cancelled.get()) return null
@@ -41,13 +45,21 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
val source = if (content) selected else item.id
val guestFolder = StoreInstallRoot.guestPathForXodus(app, folder)
val selection = if (content) emptyList() else listOf("--selected-content-id", selected)
Xodus.start(app, listOf("streaming", source, guestFolder, "--market", market,
"--progress-json", "--control-stdin") + selection).use { process ->
// Streaming rejects a legacy container outright, so dispatch on the
// format the catalogue recorded rather than fail after a download.
val command = if (legacy) "legacy-install" else "streaming"
Xodus.start(app, if (legacy) {
listOf(command, source, guestFolder, "--market", market, "--progress-json", "--store-id", item.id) + selection
} else {
listOf(command, source, guestFolder, "--market", market, "--progress-json", "--control-stdin") + selection
}).use { process ->
child = process
val rejected = AtomicBoolean(false)
val rejectedLine = Regex(Xodus.SIGN_IN_REJECTED)
val diagnostics = Xodus.diagnostics(process) { line ->
StoresState.logLine("Xbox: $line")
errors.add(line)
while (errors.size > MAX_ERROR_LINES) errors.poll()
if (line.matches(rejectedLine)) rejected.set(true)
}
if (cancelled.get()) process.process.destroy()
@@ -60,7 +72,16 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
when (progress.getString("phase")) {
"complete" -> complete = true
"downloading", "download", "transfer" -> handle.progress(progress.getLong("completedBytes"), progress.optLong("totalBytes"))
"finalizing", "installing" -> handle.stage(DownloadStage.INSTALL)
// Unpacking reports files, not bytes: the frontend hands
// over one container and the backend counts what it has
// written, which is the only measure that moves while a
// single multi-gigabyte member is decrypted.
"installing" -> {
handle.stage(DownloadStage.INSTALL)
val total = progress.optLong("totalBytes")
if (total > 0L) handle.stageProgress(progress.getLong("completedBytes"), total)
}
"finalizing" -> handle.stage(DownloadStage.INSTALL)
else -> handle.stage(DownloadStage.MANIFEST)
}
}
@@ -69,7 +90,14 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
diagnostics.join(2000)
if (cancelled.get()) return null
check(!rejected.get()) { app.getString(com.droiddeck.launcher.R.string.stores_xbox_sign_in_again) }
check(process.process.exitValue() == 0 && complete) { "Xbox download did not complete. Resume to retry with fresh licenses." }
val exit = process.process.exitValue()
if (exit != 0 || !complete) {
val tail = errors.toList().takeLast(MAX_ERROR_LINES)
report(command, source, market, exit, tail)
licenseRefusal(tail)?.let { error(app.getString(it)) }
error("Xbox download did not complete. Resume to retry with fresh licenses." +
tail.takeLast(3).joinToString("") { "\n$it" })
}
}
if (content) {
XboxContent.complete(app, item, folder)
@@ -87,6 +115,21 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
}
}
/** Writes the backend's words beside the app, where adb can read them. */
private fun report(command: String, source: String, market: String, exit: Int, tail: List<String>) {
val text = buildString {
appendLine("command: $command $source --market $market")
appendLine("legacy: $legacy")
appendLine("exit: $exit")
appendLine("--- stderr (last ${tail.size} lines) ---")
tail.forEach { appendLine(it) }
}
runCatching {
app.getExternalFilesDir(null)?.let { File(it, "xbox-install.log").writeText(text) }
}
StoresState.logLine("Xbox install failed (exit $exit): ${tail.lastOrNull().orEmpty()}")
}
override fun cancel(deleteFiles: Boolean) {
cancelled.set(true)
delete = deleteFiles
@@ -98,14 +141,25 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
}
Thread({
runCatching {
process.send(JSONObject().put("schema", 1).put("command", "pause"))
paused.await(3, TimeUnit.SECONDS)
if (!legacy) {
process.send(JSONObject().put("schema", 1).put("command", "pause"))
paused.await(3, TimeUnit.SECONDS)
}
process.close()
}
process.close()
}, "xbox-download-stop").start()
}
companion object {
private const val MAX_ERROR_LINES = 40
const val DEVICES_URL = "https://account.microsoft.com/devices/content"
private const val LICENSE_DIAGNOSTIC = "NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 "
internal fun licenseRefusal(tail: List<String>): Int? = when (tail.lastOrNull { it.startsWith(LICENSE_DIAGNOSTIC) }
?.removePrefix(LICENSE_DIAGNOSTIC)?.substringBefore(' ')) {
"content-device-limit" -> com.droiddeck.launcher.R.string.stores_xbox_device_group_full
"content-device-name" -> com.droiddeck.launcher.R.string.stores_xbox_license_refused
else -> null
}
internal fun executable(folder: File): String = XboxManifest.executable(folder)
}
}
@@ -18,7 +18,8 @@ internal class XboxLaunchViews {
parent.listFiles()?.filter { it.name.startsWith("launch-") }?.forEach(::remove)
recovered.add(parent.path)
}
return Files.createTempDirectory(parent.toPath(), "launch-").toFile()
// The guest binds the files directory by the path Android reports, not its canonical one.
return File(files, "xbox-runtime/views/" + Files.createTempDirectory(parent.toPath(), "launch-").fileName)
}
companion object {
@@ -29,7 +29,10 @@ internal object XboxLibraryCache {
.put("image", game.imageUrl).put("poster", game.tallImageUrl).put("description", game.description)
.put("developer", game.developer).put("publisher", game.publisher).put("size", game.sizeBytes)
.put("access", if (game.subscription) "gamepass" else if (game.owned) "owned" else "none")
.put("pc", game.xboxPc).put("cloud", game.xboxCloud).put("cloudId", game.extra["cloudId"].orEmpty()))
.put("pc", game.xboxPc).put("cloud", game.xboxCloud).put("cloudId", game.extra["cloudId"].orEmpty())
// The installer picks its subcommand from this; without it a
// cached legacy game would fall back to streaming.
.put("format", game.extra["format"].orEmpty()))
}).toString()
internal fun decode(text: String?, account: String, market: String, now: Long = System.currentTimeMillis()): Snapshot? = runCatching {
@@ -46,13 +49,18 @@ internal object XboxLibraryCache {
val title = row.getString("title")
val access = row.getString("access")
val cloudId = row.optString("cloudId").takeIf { it.matches(Regex("[A-Z0-9]{12}")) }.orEmpty()
val format = row.optString("format").takeIf { XboxCatalog.installableFormat(it) }.orEmpty()
require(id.matches(Regex("[A-Z0-9]{12}")) && title.isNotBlank() && access in setOf("owned", "gamepass"))
// A title with no legacy format keeps the plain shape a cache written
// before formats existed has, so a restart round-trips unchanged.
val extra = linkedMapOf("market" to market, "access" to access,
"pc" to XboxCatalog.flag(row.getBoolean("pc")), "cloud" to XboxCatalog.flag(row.getBoolean("cloud")), "cloudId" to cloudId)
if (format.isNotEmpty()) extra["format"] = format
CatalogItem(Store.XBOX, id, title, row.optString("image").takeIf { it.isNotEmpty() },
tallImageUrl = row.optString("poster").takeIf { it.isNotEmpty() },
description = row.optString("description"), developer = row.optString("developer"), publisher = row.optString("publisher"),
sizeBytes = row.optLong("size"), owned = access == "owned", subscription = access == "gamepass",
storeUrl = "https://www.xbox.com/games/store/$id", extra = mapOf("market" to market, "access" to access,
"pc" to XboxCatalog.flag(row.getBoolean("pc")), "cloud" to XboxCatalog.flag(row.getBoolean("cloud")), "cloudId" to cloudId))
storeUrl = "https://www.xbox.com/games/store/$id", extra = extra)
}
require(games.map { it.id }.distinct().size == games.size)
Snapshot(games, savedAt)
@@ -5,12 +5,25 @@ import org.xmlpull.v1.XmlPullParser
internal object XboxManifest {
data class Info(val storeId: String, val name: String, val publisher: String, val version: String,
val dependency: String, val related: List<String>, val executables: List<String>)
val dependency: String, val related: List<String>, val executables: List<String>, val entryPoint: String,
val runtimeBehavior: String = "")
/** A GameCore title describes itself with the config; a legacy package does not. */
private const val GAME_CONFIG = "MicrosoftGame.config"
private const val APPX_MANIFEST = "AppxManifest.xml"
private const val FULL_TRUST = "Windows.FullTrustApplication"
private const val APP_MODEL = "windowsApp"
private val directBehaviors = setOf("packagedClassicApp", "win32App")
fun read(folder: File): Info {
val manifests = folder.listFiles().orEmpty().filter { it.name.equals("MicrosoftGame.config", true) && it.isFile }
require(manifests.size == 1) { "Missing or ambiguous MicrosoftGame.config." }
val manifest = manifests.single()
// Both manifests are read the same way: an identity, an executable path and,
// for a Store package, related content.
val files = folder.listFiles().orEmpty()
val config = files.filter { it.name.equals(GAME_CONFIG, true) && it.isFile }
val legacy = files.filter { it.name.equals(APPX_MANIFEST, true) && it.isFile }
require(config.size + legacy.size == 1) { "Missing or ambiguous game manifest." }
val manifest = (config + legacy).single()
val rootTag = if (config.isEmpty()) "Package" else "Game"
require(manifest.length() <= 1_048_576)
val parser = android.util.Xml.newPullParser().apply { setFeature(XmlPullParser.FEATURE_PROCESS_DOCDECL, false) }
val identities = ArrayList<List<String>>()
@@ -18,7 +31,11 @@ internal object XboxManifest {
val dependencies = ArrayList<String>()
val related = ArrayList<String>()
val entries = ArrayList<String>()
val entryPoints = ArrayList<String>()
val behaviors = ArrayList<String>()
fun attribute(name: String) = parser.getAttributeValue(null, name).orEmpty()
fun localAttribute(name: String) = (0 until parser.attributeCount)
.firstOrNull { parser.getAttributeName(it).substringAfterLast(':') == name }?.let(parser::getAttributeValue).orEmpty()
var root = false
var elements = 0
manifest.inputStream().use { input ->
@@ -29,16 +46,22 @@ internal object XboxManifest {
XmlPullParser.DOCDECL -> error("Xbox game manifests cannot contain a DTD.")
XmlPullParser.START_TAG -> {
require(++elements <= 10_000 && parser.depth <= 64) { "Xbox game manifest is too complex." }
if (parser.depth == 1) { require(!root && parser.name == "Game"); root = true }
if (parser.depth == 1) { require(!root && parser.name == rootTag); root = true }
when (parser.name) {
"Identity" -> identities.add(listOf(attribute("Name"), attribute("Publisher"), attribute("Version")))
"StoreId" -> storeIds.add(parser.nextText().trim())
"MainPackageDependency" -> dependencies.add(attribute("Name"))
"RelatedProduct" -> related.add(parser.nextText().trim())
"Executable" -> {
val path = attribute("Name").replace('\\', '/')
// Both carry the launch path: an attribute on the config's
// Executable, or on the AppxManifest's Application.
"Executable", "Application" -> {
val path = attribute("Name").ifEmpty { attribute("Executable") }.replace('\\', '/')
if (path.endsWith(".exe", true) && attribute("TargetDeviceFamily") in listOf("", "PC", "Windows.Desktop") &&
!attribute("IsDevOnly").equals("true", true)) entries.add(path)
if (parser.name == "Application") {
attribute("EntryPoint").takeIf { it.isNotEmpty() }?.let(entryPoints::add)
localAttribute("RuntimeBehavior").takeIf { it.isNotEmpty() }?.let(behaviors::add)
}
}
}
}
@@ -48,9 +71,25 @@ internal object XboxManifest {
require(root && identities.size <= 1 && storeIds.size <= 1 && dependencies.size <= 1) { "Invalid Xbox game manifest." }
val ids = related.distinct()
require(ids.size <= 128 && ids.all { it.matches(Regex("[A-Z0-9]{12}")) })
val entry = entryPoints.distinct()
val behavior = behaviors.distinct()
require(entry.size <= 1 && behavior.size <= 1) { "Invalid Xbox game manifest." }
val identity = identities.singleOrNull()
return Info(storeIds.singleOrNull().orEmpty(), identity?.get(0).orEmpty(), identity?.get(1).orEmpty(), identity?.get(2).orEmpty(),
dependencies.singleOrNull().orEmpty(), ids, entries)
dependencies.singleOrNull().orEmpty(), ids, entries, entry.singleOrNull().orEmpty(), behavior.singleOrNull().orEmpty())
}
/**
* A full trust package starts its executable directly. Anything else is activated
* through the Windows app model, which this runtime has no host for, so starting
* the executable would only crash.
*/
fun needsAppModel(folder: File): Boolean {
val info = runCatching { read(folder) }.getOrNull() ?: return false
val behavior = info.runtimeBehavior
if (behavior.equals(APP_MODEL, true)) return true
if (directBehaviors.any { it.equals(behavior, true) }) return false
return info.entryPoint.isNotEmpty() && !info.entryPoint.equals(FULL_TRUST, true)
}
fun executable(folder: File): String {
@@ -63,8 +102,29 @@ internal object XboxManifest {
file = matches.single()
}
require(file.canonicalPath.startsWith(folder.canonicalPath + File.separator))
if (file.isFile) return file.relativeTo(folder).invariantSeparatorsPath
if (file.isFile) return forwarded(folder, file) ?: file.relativeTo(folder).invariantSeparatorsPath
}
error("The Xbox package has no supported PC launch executable.")
}
private fun forwarded(folder: File, launcher: File): String? = try {
val arguments = File(launcher.parentFile, launcher.nameWithoutExtension + "LaunchArguments.txt")
if (!arguments.isFile || arguments.length() > 65_536) null
else arguments.readLines().firstNotNullOfOrNull { line ->
line.trim().takeIf { it.startsWith("exe=", ignoreCase = true) }?.substring(4)?.trim()
}?.takeIf { it.isNotEmpty() && !it.contains(':') }?.let { target -> located(folder.canonicalFile, launcher.parentFile.canonicalFile, target) }
} catch (_: java.io.IOException) {
null
}
private fun located(root: File, start: File, target: String): String? {
var file = start
for (part in target.split('/', '\\').filter { it.isNotEmpty() && it != "." }) {
file = if (part == "..") file.parentFile ?: return null
else file.listFiles().orEmpty().filter { it.name.equals(part, true) }.singleOrNull() ?: return null
}
val resolved = file.canonicalFile
if (!resolved.isFile || !resolved.path.startsWith(root.path + File.separator) || !resolved.extension.equals("exe", true)) return null
return resolved.relativeTo(root).invariantSeparatorsPath
}
}
@@ -155,10 +155,12 @@ internal object Xodus {
const val SIGN_IN_REJECTED = "Microsoft content licensing rejected sign-in \\(HTTP 401\\)\\. Sign in again in Settings\\."
internal val reportable = Regex("NEXUS_CREDENTIAL_ERROR_V1 [a-z-]{1,48}|NEXUS_LIBRARY_DIAGNOSTIC_V1 [a-z-]{1,48} [0-9]{1,3} [0-9]{1,6}|NEXUS_SESSION_DIAGNOSTIC_V1 [a-z-]{1,64}|Account library unavailable \\([a-z-]{1,64}\\); credentials and installed games are unchanged\\.|Account library timed out; installed games are unchanged\\.|Xbox profile is temporarily unavailable \\([a-z-]{1,48}\\); stored account is unchanged\\.|Xbox profile request timed out; stored account is unchanged\\.|NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 [a-z-]{1,48} [0-9]{1,3}|NEXUS_LEGACY_INSTALL_DIAGNOSTIC_V1 [a-z0-9-]{1,48}( [0-9]{1,6})?|NEXUS_LEGACY_INSTALL_DETAIL_V1 [A-Za-z0-9 .,;-]{1,220}|NEXUS_EXTRACT_DIAGNOSTIC_V1 [a-z-]{1,48}|NEXUS_EXTRACT_DETAIL_V1 [A-Za-z0-9 ._?-]{1,220}|$SIGN_IN_REJECTED")
fun diagnostics(child: Child, report: (String) -> Unit = { com.droiddeck.launcher.stores.StoresState.logLine("Xbox: $it") }): Thread = Thread({
runCatching {
child.process.errorStream.bufferedReader().useLines { lines -> lines.forEach { line ->
if (line.matches(Regex("NEXUS_CREDENTIAL_ERROR_V1 [a-z-]{1,48}|NEXUS_LIBRARY_DIAGNOSTIC_V1 [a-z-]{1,48} [0-9]{1,3} [0-9]{1,6}|NEXUS_SESSION_DIAGNOSTIC_V1 [a-z-]{1,64}|Account library unavailable \\([a-z-]{1,64}\\); credentials and installed games are unchanged\\.|Account library timed out; installed games are unchanged\\.|Xbox profile is temporarily unavailable \\([a-z-]{1,48}\\); stored account is unchanged\\.|Xbox profile request timed out; stored account is unchanged\\.|NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 [a-z-]{1,48} [0-9]{3}|$SIGN_IN_REJECTED")))
if (line.matches(reportable))
report(line)
} }
}
@@ -19,15 +19,18 @@ import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.waitForUpOrCancellation
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
@@ -37,6 +40,7 @@ import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
@@ -55,6 +59,7 @@ import androidx.compose.material.icons.outlined.Build
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.ExpandMore
import androidx.compose.material.icons.outlined.History
import androidx.compose.material.icons.outlined.Lock
import androidx.compose.material.icons.outlined.Memory
import androidx.compose.material.icons.outlined.MoreHoriz
import androidx.compose.material.icons.outlined.Pets
@@ -95,6 +100,7 @@ import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onGloballyPositioned
@@ -116,6 +122,7 @@ import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.DialogWindowProvider
import com.droiddeck.launcher.R
import com.droiddeck.launcher.agent.AgentAttachments
import com.droiddeck.launcher.agent.AgentDraft
import com.droiddeck.launcher.agent.AgentHost
import com.droiddeck.launcher.agent.AgentHost.Entry
import com.droiddeck.launcher.agent.AgentSetup
@@ -124,7 +131,7 @@ import kotlinx.coroutines.launch
internal enum class AgentPanel { NONE, MODEL, USAGE, HISTORY, PROCESSES, TOOLS }
/** Slash commands the app handles itself; others go to the CLI, which has its own. */
private val LOCAL_COMMANDS = listOf("/new", "/model", "/plan", "/history", "/processes", "/stop")
private val LOCAL_COMMANDS = listOf("/new", "/model", "/permissions", "/plan", "/history", "/processes", "/stop")
private val CLI_COMMANDS = listOf("/compact", "/cost", "/review", "/init")
/**
@@ -201,9 +208,9 @@ private fun AgentPageContent(
}
remember { AgentSetup.check(context) }
var setup by rememberSaveable { mutableStateOf(false) }
val draft = rememberSaveable { mutableStateOf("") }
val draft = remember { AgentDraft.state(context) }
if (setup || AgentHost.state == AgentHost.State.MISSING || !(AgentSetup.ready || AgentSetup.completed(context))) {
AgentSetupView(modifier, onDone = { setup = false })
AgentSetupView(modifier, firstControl = inputModifier, onDone = { setup = false })
return
}
var panel by rememberSaveable { mutableStateOf(AgentPanel.NONE) }
@@ -229,6 +236,10 @@ private fun AgentPageContent(
// The keyboard leaves too little height for a panel and the editor together, so typing closes the panel.
val keyboardOpen = WindowInsets.ime.getBottom(LocalDensity.current) > 0
LaunchedEffect(keyboardOpen) { if (keyboardOpen && (panel == AgentPanel.MODEL || panel == AgentPanel.USAGE)) panel = AgentPanel.NONE }
// History, processes and tools take the whole page, which would hide an approval the turn is waiting on.
LaunchedEffect(AgentHost.approvals.size, panel) {
if (AgentHost.approvals.isNotEmpty() && (panel == AgentPanel.HISTORY || panel == AgentPanel.PROCESSES || panel == AgentPanel.TOOLS)) panel = AgentPanel.NONE
}
Column(
modifier.fillMaxSize().imePadding().onPreviewKeyEvent { e ->
val k = e.nativeKeyEvent
@@ -275,7 +286,8 @@ private fun AgentPageContent(
readingBack = false
scope.launch { list.scrollToItem(maxOf(0, list.layoutInfo.totalItemsCount - 1), Int.MAX_VALUE / 2) }
}
val hidden = !composer.focused && !composer.hasUnconsumedFocusRequest() && readingBack && AgentHost.entries.isNotEmpty()
val hidden = !composer.focused && !composer.hasUnconsumedFocusRequest() && readingBack && AgentHost.entries.isNotEmpty() &&
AgentHost.approvals.isEmpty()
var listHeight by remember { mutableIntStateOf(0) }
Box(
Modifier.weight(1f).fillMaxWidth().clipToBounds().nestedScroll(dragBack).onGloballyPositioned {
@@ -292,7 +304,8 @@ private fun AgentPageContent(
awaitEachGesture {
awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)
if (panel == AgentPanel.MODEL || panel == AgentPanel.USAGE) panel = AgentPanel.NONE
if (composer.focused) focusManager.clearFocus()
// Forced: the unforced path walks the focus chain and throws ("ActiveParent with no focused child") when a tap lands while focus is moving.
if (composer.focused) focusManager.clearFocus(force = true)
}
},
list, following = !readingBack, onRevise = { composer.open() }, onSent = toLatest,
@@ -304,7 +317,7 @@ private fun AgentPageContent(
}
}
androidx.compose.animation.AnimatedVisibility(!hidden, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) {
AgentComposer(composer, draft, visible, inlineControls, onPanel = { panel = it }, onSent = toLatest)
AgentComposer(composer, draft, visible && started, inlineControls, onPanel = { panel = it }, onSent = toLatest)
}
}
}
@@ -349,7 +362,7 @@ private fun AgentTopBar(panel: AgentPanel, onPanel: (AgentPanel) -> Unit, firstC
}
}
/** The harness, model, effort and plan mode, opening the model picker; [compact] names only the model. */
/** The harness, model, effort, a permission mode other than asking first and plan mode, opening the model picker; [compact] names only the model. */
@Composable
private fun ModelChip(panel: AgentPanel, onPanel: (AgentPanel) -> Unit, firstControl: Modifier, modifier: Modifier = Modifier, compact: Boolean = false) {
val context = LocalContext.current
@@ -360,8 +373,12 @@ private fun ModelChip(panel: AgentPanel, onPanel: (AgentPanel) -> Unit, firstCon
modifier = modifier.then(if (compact) Modifier.widthIn(max = 120.dp) else Modifier).height(36.dp).clip(Shape12).then(firstControl)
.clickable { onPanel(AgentPanel.MODEL) }.padding(horizontal = 8.dp).testTag("agent-model"),
) {
val parts = if (compact) listOf(model)
else listOfNotNull(AgentHost.harness.name, model, AgentHost.effort, stringResource(R.string.agent_plan_short).takeIf { AgentHost.plan && AgentHost.harness.plans })
val mode = AgentHost.harness.permissions.drop(1).firstOrNull { it.id == AgentHost.permission }?.let { stringResource(it.label) }
val parts = if (compact) listOfNotNull(mode ?: model)
else listOfNotNull(
AgentHost.harness.name, model, AgentHost.effort, mode,
stringResource(R.string.agent_plan_short).takeIf { AgentHost.plan && AgentHost.harness.plans },
)
Text(parts.joinToString(" · "), fontSize = 13.sp, color = if (panel == AgentPanel.MODEL) pal.primary else pal.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
Icon(Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp))
@@ -518,6 +535,39 @@ internal fun clock(seconds: Long): String {
}
}
/** The oldest tool call that waits for the user; tapping its input shows all of it. */
@Composable
private fun AgentApprovalCard(approval: AgentHost.Approval, more: Int) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var open by remember(approval.id) { mutableStateOf(false) }
Column(
Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape14).background(colors.surface).border(1.dp, AttentionAmber, Shape14)
.padding(horizontal = 14.dp, vertical = 10.dp).testTag("agent-approval"),
) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Column(Modifier.weight(1f)) {
Text(stringResource(R.string.agent_approval_title, approval.tool), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
if (more > 0) Text(stringResource(R.string.agent_approval_more, more), fontSize = 12.5.sp, color = pal.onSurfaceVariant)
}
SecondaryButton(stringResource(R.string.agent_approval_deny), compact = true, modifier = Modifier.testTag("agent-approval-deny")) {
AgentHost.answer(context, approval, allow = false)
}
PrimaryButton(stringResource(R.string.agent_approval_allow), compact = true, modifier = Modifier.testTag("agent-approval-allow")) {
AgentHost.answer(context, approval, allow = true)
}
}
val body = approval.input.ifBlank { approval.detail }
val shown = Modifier.fillMaxWidth().padding(top = 6.dp)
.then(if (open) Modifier.heightIn(max = 280.dp).verticalScroll(rememberScrollState()) else Modifier).clickable { open = !open }
if (body.isNotBlank()) Text(
body, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant,
maxLines = if (open) Int.MAX_VALUE else 4, overflow = TextOverflow.Ellipsis, modifier = shown,
)
}
}
@Composable
private fun AgentLabCard() {
val context = LocalContext.current
@@ -670,7 +720,7 @@ private fun AgentComposer(
val text = draft.trim()
when (text.substringBefore(' ')) {
"/new" -> AgentHost.forget(context)
"/model" -> onPanel(AgentPanel.MODEL)
"/model", "/permissions" -> onPanel(AgentPanel.MODEL)
"/plan" -> AgentHost.choosePlan(context, !AgentHost.plan)
"/history" -> onPanel(AgentPanel.HISTORY)
"/processes" -> onPanel(AgentPanel.PROCESSES)
@@ -687,6 +737,7 @@ private fun AgentComposer(
val keyboardOpen = WindowInsets.ime.getBottom(LocalDensity.current) > 0
Column(Modifier.fillMaxWidth().padding(bottom = if (keyboardOpen) 4.dp else 8.dp)) {
if (labOpen) AgentLabCard()
AgentHost.approvals.firstOrNull()?.let { AgentApprovalCard(it, AgentHost.approvals.size - 1) }
if (hasActivity()) Row(
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(top = 8.dp).fillMaxWidth().horizontalScroll(rememberScrollState()),
@@ -703,9 +754,23 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String
val pal = LocalPalette.current
var draft by draftState
val voice = remember { AgentVoice(context.applicationContext, { draftState.value }) { draftState.value = it } }
val voiceAvailable = remember { AgentVoice.available(context) }
DisposableEffect(voice) { onDispose { voice.stop() } }
LaunchedEffect(visible) { if (!visible) voice.stop() }
DisposableEffect(voice) { onDispose { voice.settle() } }
var voiceSetup by remember { mutableStateOf(false) }
LaunchedEffect(voice.serviceMicBlocked) {
if (voice.serviceMicBlocked) {
voice.serviceMicBlocked = false
voiceSetup = true
}
}
LaunchedEffect(visible) { if (!visible) voice.settle() }
// Sends once dictation has written its last words; while a send already waits on them, there is nothing more to do.
val sendNow = {
when {
voice.listening -> voice.finish(send)
voice.finishing -> Unit
else -> send()
}
}
val working = AgentHost.state == AgentHost.State.WORKING
if (draft.startsWith("/") && !draft.contains(' ')) {
val matches = (LOCAL_COMMANDS + CLI_COMMANDS).filter { it.startsWith(draft) && it != draft }
@@ -725,23 +790,35 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String
) {
for (path in AgentAttachments.pending.toList()) AttachmentChip(path) { AgentAttachments.pending.remove(path) }
}
if (voiceSetup) AgentVoiceSetup(onReady = { voiceSetup = false }, onClose = { voiceSetup = false })
var focused by remember { mutableStateOf(false) }
val field = remember { FocusRequester() }
LaunchedEffect(composer.focusRequests) { if (composer.hasUnconsumedFocusRequest()) runCatching { field.requestFocus() } }
Column(
val attach = LocalActivityResultRegistryOwner.current != null
BoxWithConstraints(
Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape16).background(colors.surface)
.border(if (focused) 2.dp else 1.dp, if (focused) pal.primary else pal.line, Shape16).padding(6.dp),
) {
Row(verticalAlignment = Alignment.Bottom) {
if (LocalActivityResultRegistryOwner.current != null) AttachButton()
if (AgentAttachments.gameFrame != null) GameFrameButton()
Box(Modifier.weight(1f).padding(start = 8.dp, top = 10.dp, bottom = 10.dp)) {
// A narrow editor gives the buttons a row of their own so the text keeps room to be tapped.
val stacked = maxWidth < (if (controls != null) 560.dp else 320.dp)
val text: @Composable (Modifier) -> Unit = { modifier -> Box(modifier.padding(start = 8.dp, top = 10.dp, bottom = 10.dp)) {
if (draft.isEmpty()) Text(
stringResource(if (working) R.string.agent_hint_working else R.string.agent_hint), fontSize = 16.sp,
stringResource(
when {
voice.listening && !voice.locked -> R.string.agent_voice_hold
voice.listening -> R.string.agent_voice_listening
working -> R.string.agent_hint_working
else -> R.string.agent_hint
},
),
fontSize = 16.sp,
color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
BasicTextField(
draft, { draft = it },
draft, {
draft = it
if (voice.listening) voice.stop()
},
Modifier.fillMaxWidth().focusRequester(field).onFocusChanged {
focused = it.isFocused
composer.focused = it.isFocused
@@ -750,50 +827,132 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String
textStyle = TextStyle(fontSize = 16.sp, color = colors.onSurface),
cursorBrush = SolidColor(pal.primary),
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
keyboardActions = KeyboardActions(onSend = {
voice.stop()
send()
}),
keyboardActions = KeyboardActions(onSend = { sendNow() }),
minLines = 1,
maxLines = 8,
)
}
if (controls != null && !focused) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.height(42.dp)) { controls() }
} }
val actions: @Composable () -> Unit = {
if (working) RoundButton(Icons.Outlined.Stop, stringResource(R.string.agent_stop), pal.error.copy(alpha = 0.22f), colors.error, "agent-stop") {
AgentHost.stop(context)
}
val canSend = draft.isNotBlank() || AgentAttachments.pending.isNotEmpty()
// An empty message has nothing to send, so the button there dictates one instead.
if ((!canSend || voice.listening) && voiceAvailable) VoiceButton(voice) { voice.start(draft) }
else RoundButton(
if ((!canSend || voice.listening) && !voice.finishing) VoiceButton(voice, onStart = { voice.start(draft) }, onSend = send, onSetup = { voiceSetup = true })
if (voice.finishing || (voice.listening && voice.locked) || (canSend && !voice.listening)) RoundButton(
Icons.AutoMirrored.Outlined.Send, stringResource(if (working) R.string.agent_queue else R.string.agent_send),
if (canSend) pal.primary else pal.surfaceVariant, if (canSend) pal.onPrimary else pal.onSurfaceVariant, "agent-send", enabled = canSend,
) {
voice.stop()
send()
pal.primary, pal.onPrimary, "agent-send", enabled = !voice.finishing,
) { sendNow() }
}
if (stacked) Column {
text(Modifier.fillMaxWidth())
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
if (attach) AttachButton()
if (AgentAttachments.gameFrame != null) GameFrameButton()
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f).height(42.dp)) { if (controls != null && !focused) controls() }
actions()
}
} else Row(verticalAlignment = Alignment.Bottom) {
if (attach) AttachButton()
if (AgentAttachments.gameFrame != null) GameFrameButton()
text(Modifier.weight(1f))
if (controls != null && !focused) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.height(42.dp)) { controls() }
actions()
}
}
}
/**
* Held, it listens until let go and then sends; slid up, it keeps listening hands-free; slid left, it puts the text back.
* A tap or a controller press also listens hands-free.
*/
@Composable
private fun VoiceButton(voice: AgentVoice, onStart: () -> Unit) {
private fun VoiceButton(voice: AgentVoice, onStart: () -> Unit, onSend: () -> Unit, onSetup: () -> Unit) {
val context = LocalContext.current
val pal = LocalPalette.current
val ask = if (LocalActivityResultRegistryOwner.current != null) rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (granted) onStart() else android.widget.Toast.makeText(context, R.string.agent_voice_denied, android.widget.Toast.LENGTH_SHORT).show()
} else null
RoundButton(
if (voice.listening) Icons.Outlined.MicOff else Icons.Outlined.Mic, stringResource(if (voice.listening) R.string.agent_voice_stop else R.string.agent_voice),
if (voice.listening) pal.primary else pal.surfaceVariant, if (voice.listening) pal.onPrimary else pal.onBackground, "agent-voice",
) {
val start by rememberUpdatedState(onStart)
val send by rememberUpdatedState(onSend)
val setup by rememberUpdatedState(onSetup)
val handsFree = {
start()
if (voice.listening) voice.locked = true
}
val toggle = {
when {
voice.listening -> voice.finish()
context.checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) == android.content.pm.PackageManager.PERMISSION_GRANTED -> onStart()
ask != null -> ask.launch(android.Manifest.permission.RECORD_AUDIO)
else -> android.widget.Toast.makeText(context, R.string.agent_voice_denied, android.widget.Toast.LENGTH_SHORT).show()
!voiceReady(context) -> setup()
else -> handsFree()
}
}
val density = LocalDensity.current
val lockPx = with(density) { 56.dp.toPx() }
val cancelPx = with(density) { 72.dp.toPx() }
var drag by remember { mutableStateOf(Offset.Zero) }
val holding = voice.listening && !voice.locked
val icon = when {
voice.locked -> Icons.Outlined.MicOff
holding && -drag.x > cancelPx / 2 && -drag.x > -drag.y -> Icons.Outlined.Close
holding && -drag.y > lockPx / 2 -> Icons.Outlined.Lock
else -> Icons.Outlined.Mic
}
val scale = if (holding) 1.12f + 0.12f * voice.level else 1f
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.padding(start = 6.dp).size(42.dp).graphicsLayer {
scaleX = scale
scaleY = scale
}.clip(CircleShape).background(if (voice.listening) pal.primary else pal.surfaceVariant)
.pointerInput(voice) {
awaitEachGesture {
val down = awaitFirstDown(pass = PointerEventPass.Initial)
down.consume()
if (voice.listening || !voiceReady(context)) {
waitForUpOrCancellation(PointerEventPass.Initial)?.let {
it.consume()
toggle()
}
return@awaitEachGesture
}
start()
var resolved = !voice.listening
try {
while (!resolved) {
val change = awaitPointerEvent(PointerEventPass.Initial).changes.firstOrNull { it.id == down.id } ?: break
// Compose ends a cancelled touch stream with a lift that arrives already consumed; that is not a release.
if (!change.pressed && change.isConsumed) break
change.consume()
drag = change.position - down.position
when {
!voice.listening -> resolved = true
drag.y < -lockPx -> {
voice.locked = true
resolved = true
}
drag.x < -cancelPx -> {
voice.cancel()
resolved = true
}
!change.pressed -> {
val tap = change.uptimeMillis - down.uptimeMillis < viewConfiguration.longPressTimeoutMillis / 2 &&
drag.getDistance() < viewConfiguration.touchSlop
if (tap) voice.locked = true else voice.finish(send)
resolved = true
}
}
}
} finally {
drag = Offset.Zero
if (!resolved && voice.listening && !voice.locked) voice.finish()
}
}
}
.clickable(onClick = toggle).testTag("agent-voice"),
) {
Icon(
icon, stringResource(if (voice.listening) R.string.agent_voice_stop else R.string.agent_voice),
tint = if (voice.listening) pal.onPrimary else pal.onBackground, modifier = Modifier.size(21.dp),
)
}
}
/** Attaches what the running game shows, taken from its own surface so nothing drawn over it is in the picture. */
@@ -50,6 +50,11 @@ import androidx.compose.material3.Icon
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.relocation.bringIntoViewRequester
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.runtime.rememberCoroutineScope
import kotlinx.coroutines.launch
import com.droiddeck.launcher.agent.AgentTools
@@ -62,7 +67,7 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
/** The model, reasoning effort and plan mode for the next turns; a conversation keeps going with whatever is chosen. */
/** The model, reasoning effort, permissions and plan mode for the next turns; a conversation keeps going with whatever is chosen. */
@Composable
internal fun AgentModelPicker() {
val context = LocalContext.current
@@ -87,6 +92,20 @@ internal fun AgentModelPicker() {
}
}
}
val modes = AgentHost.harness.permissions
if (modes.size > 1) Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(stringResource(R.string.agent_permissions), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground, modifier = Modifier.padding(horizontal = 2.dp))
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.horizontalScroll(rememberScrollState())) {
for (mode in modes) {
val label = stringResource(mode.label)
if (mode.id == AgentHost.permission) PrimaryButton(label, compact = true, modifier = Modifier.testTag("agent-permission")) {}
else SecondaryButton(label, compact = true, modifier = Modifier.testTag("agent-permission")) { AgentHost.choosePermission(context, mode.id) }
}
}
modes.firstOrNull { it.id == AgentHost.permission }?.let {
Text(stringResource(it.hint), fontSize = 12.5.sp, color = pal.onSurfaceVariant, modifier = Modifier.padding(horizontal = 2.dp))
}
}
if (AgentHost.harness.plans) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp)) {
Column(Modifier.weight(1f)) {
Text(stringResource(R.string.agent_plan), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground)
@@ -416,14 +435,23 @@ private fun ToolsRow(title: String, detail: String, action: @Composable () -> Un
}
@Composable
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
internal fun ToolsField(value: String, onValue: (String) -> Unit, hint: String, tag: String) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Box(Modifier.fillMaxWidth().clip(Shape12).background(pal.surfaceVariant).padding(horizontal = 12.dp, vertical = 10.dp)) {
if (value.isEmpty()) Text(hint, fontSize = 14.sp, color = pal.onSurfaceVariant, maxLines = 1)
BasicTextField(
value, onValue, singleLine = true, textStyle = TextStyle(fontSize = 14.sp, fontFamily = FontFamily.Monospace, color = colors.onSurface),
cursorBrush = SolidColor(pal.primary), modifier = Modifier.fillMaxWidth().testTag(tag),
)
}
// The launcher's pane focus group sends a Compose text field's focus back to the last tile it remembers,
// so these fields use the EditText the rest of the launcher types into.
val view = remember { androidx.compose.foundation.relocation.BringIntoViewRequester() }
var focused by remember { mutableStateOf(false) }
val window = androidx.compose.ui.platform.LocalView.current
// An EditText's focus does not scroll its Compose parent, so the field follows the keyboard as it opens.
val keyboard = WindowInsets.ime.getBottom(androidx.compose.ui.platform.LocalDensity.current)
LaunchedEffect(focused, keyboard) { if (focused) view.bringIntoView() }
AdbTextField(
value = value, onValueChange = onValue, label = hint, keyboardType = KeyboardType.Text, imeAction = ImeAction.Done,
modifier = Modifier.bringIntoViewRequester(view).testTag(tag), placeholder = hint, compact = true, showLabel = false,
onFocusChange = { focused = it },
onDone = {
(window.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager)
?.hideSoftInputFromWindow(window.windowToken, 0)
},
)
}
@@ -397,11 +397,14 @@ internal class PetWindows(private val context: Context) {
/**
* The chat window is always drawn; closed, it waits off the screen and takes neither touches nor
* keys, so opening it is a move and not a first layout.
* keys, so opening it is a move and not a first layout. Only FLAG_LAYOUT_NO_LIMITS keeps it off the
* screen: without it the system moves the window back over the app below, where every touch reaches
* that app marked obscured, and apps that filter obscured touches, such as GitHub, ignore them all.
*/
private fun showChat(on: Boolean) {
chat.params.x = if (on) 0 else OFFSCREEN
val quiet = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
val quiet = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
chat.params.flags = if (on) chat.params.flags and quiet.inv() else chat.params.flags or quiet
if (added) runCatching { windows.updateViewLayout(chat.view, chat.params) }
}
@@ -4,6 +4,8 @@ import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
@@ -46,7 +48,7 @@ import com.droiddeck.launcher.agent.AgentSetup.Step
import com.droiddeck.launcher.core.WirelessAdbPairingService
@Composable
internal fun AgentSetupView(modifier: Modifier, onDone: () -> Unit = {}) {
internal fun AgentSetupView(modifier: Modifier, firstControl: Modifier = Modifier, onDone: () -> Unit = {}) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
@@ -76,7 +78,7 @@ internal fun AgentSetupView(modifier: Modifier, onDone: () -> Unit = {}) {
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
for (harness in AgentHarness.all) {
val chosen = harness == AgentHost.harness
if (chosen) PrimaryButton(harness.name, compact = true) {} else SecondaryButton(harness.name, enabled = !AgentSetup.busy, compact = true) { AgentHost.choose(context, harness) }
if (chosen) PrimaryButton(harness.name, compact = true, modifier = firstControl) {} else SecondaryButton(harness.name, enabled = !AgentSetup.busy, compact = true) { AgentHost.choose(context, harness) }
}
}
val steps = Step.entries
@@ -97,21 +99,21 @@ internal fun AgentSetupView(modifier: Modifier, onDone: () -> Unit = {}) {
steps.forEachIndexed { index, step ->
val status = AgentSetup.status[step] ?: Status.UNKNOWN
val harness = AgentHost.harness
// A harness that signs in with a pasted key: the sign-in opens its key page and this field takes the key.
val keyed = step == Step.SIGN_IN && harness.keyPage != null
// A harness that signs in with pasted keys: this row picks the provider and takes its key.
val keyed = step == Step.SIGN_IN && harness.providers.isNotEmpty()
var keyOpen by rememberSaveable(harness.id) { mutableStateOf(false) }
val (title, hint) = labels(step, harness.name, keyed)
val lab = AgentHost.lab?.takeIf { it.prepare && it.running }
val detail = when {
step == Step.PREPARE && lab != null ->
stringResource(R.string.agent_prepare_progress, lab.permille / 10, clock(lab.etaSeconds.toLong().coerceAtLeast(0)))
keyed && status == Status.DONE && !AgentSetup.keySaved -> stringResource(R.string.agent_step_free_models)
keyed && status == Status.DONE && AgentSetup.detail[step] == null ->
harness.providers.filter { it.id in AgentSetup.keys }.joinToString(" · ") { it.name }.ifEmpty { stringResource(R.string.agent_step_free_models) }
else -> AgentSetup.detail[step] ?: hint
}
// Shown while the sign-in is pending, so it is still there after a trip to the browser for the key.
val pending = (status == Status.TODO || status == Status.FAILED) && AgentSetup.status[Step.INSTALL] == Status.DONE
val showKey = keyed && (keyOpen || pending) && status != Status.WORKING
var key by remember(harness.id) { mutableStateOf("") }
CheckRow(
when (status) {
Status.DONE -> CheckState.OK
@@ -122,33 +124,17 @@ internal fun AgentSetupView(modifier: Modifier, onDone: () -> Unit = {}) {
) {
val blocked = (step in setOf(Step.SIGN_IN, Step.GITHUB, Step.BUILD_TOOLS) && AgentSetup.status[Step.INSTALL] != Status.DONE) ||
(step == Step.PREPARE && AgentSetup.status[Step.BUILD_TOOLS] != Status.DONE)
val openKey = {
keyOpen = true
AgentSetup.run(context, step)
}
if ((status == Status.TODO || status == Status.FAILED) && !blocked) {
if (keyed) {
if (pending && harness.free) SecondaryButton(stringResource(R.string.agent_action_free), compact = true) { AgentSetup.useFree(context) }
else if (status == Status.DONE) SecondaryButton(stringResource(if (keyOpen) R.string.common_hide else R.string.agent_action_add_key), compact = true) { keyOpen = !keyOpen }
} else if ((status == Status.TODO || status == Status.FAILED) && !blocked) {
val label = stringResource(if (status == Status.FAILED) R.string.agent_setup_retry else action(step))
val run = { if (step == Step.CONNECTION) pair(context) else if (keyed) openKey() else AgentSetup.run(context, step) }
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (keyed && harness.free) SecondaryButton(stringResource(R.string.agent_action_free), compact = true) { AgentSetup.useFree(context) }
if (step.required) PrimaryButton(label, compact = true, onClick = run) else SecondaryButton(label, compact = true, onClick = run)
}
} else if (keyed && status == Status.DONE && !AgentSetup.keySaved && !keyOpen) {
SecondaryButton(stringResource(R.string.agent_action_add_key), compact = true, onClick = openKey)
val run = { if (step == Step.CONNECTION) pair(context) else AgentSetup.run(context, step) }
if (step.required) PrimaryButton(label, compact = true, onClick = run) else SecondaryButton(label, compact = true, onClick = run)
}
}
if (showKey) {
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth().padding(start = 56.dp, end = 14.dp, bottom = 10.dp),
) {
Box(Modifier.weight(1f)) { ToolsField(key, { key = it.trim() }, stringResource(R.string.agent_key_hint), "agent-key") }
PrimaryButton(stringResource(R.string.agent_key_save), enabled = key.isNotBlank(), compact = true) {
keyOpen = false
AgentSetup.saveKey(context, key)
key = ""
}
}
KeyPanel(harness) { keyOpen = false }
if (index < steps.lastIndex) Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
}
@@ -167,6 +153,47 @@ internal fun AgentSetupView(modifier: Modifier, onDone: () -> Unit = {}) {
}
}
/** Picks one of [harness]'s providers and saves its key, or a custom server's address. */
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun KeyPanel(harness: AgentHarness, onSaved: () -> Unit) {
val context = LocalContext.current
val provider = harness.providers.firstOrNull { it.id == AgentSetup.provider } ?: harness.providers.first()
var key by remember(harness.id, provider.id) { mutableStateOf("") }
val saved = provider.id in AgentSetup.keys
Column(
verticalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth().padding(start = 56.dp, end = 14.dp, bottom = 12.dp),
) {
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
for (option in harness.providers) {
val name = if (option.id in AgentSetup.keys) "${option.name} ✓" else option.name
if (option == provider) PrimaryButton(name, compact = true) {} else SecondaryButton(name, compact = true) { AgentSetup.provider = option.id }
}
}
if (provider.custom) ToolsField(AgentSetup.server, { AgentSetup.server = it.trim() }, stringResource(R.string.agent_key_server_hint), "agent-key-server")
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Box(Modifier.weight(1f)) {
ToolsField(
key, { key = it.trim() },
if (provider.custom) stringResource(R.string.agent_key_optional_hint) else stringResource(R.string.agent_key_hint, provider.name),
"agent-key",
)
}
provider.keyPage?.let { page -> SecondaryButton(stringResource(R.string.agent_key_get), compact = true) { AgentSetup.openKeyPage(context, page) } }
if (saved) SecondaryButton(stringResource(R.string.agent_storage_remove), compact = true) { AgentSetup.removeKey(context, provider) }
PrimaryButton(
stringResource(R.string.agent_key_save), compact = true,
enabled = if (provider.custom) AgentSetup.server.isNotBlank() else key.isNotBlank(),
) {
AgentSetup.saveKey(context, provider, key, AgentSetup.server.takeIf { provider.custom })
key = ""
onSaved()
}
}
}
}
@Composable
private fun StorageCard() {
val context = LocalContext.current
@@ -193,9 +220,9 @@ private fun StorageCard() {
modifier = Modifier.fillMaxWidth().heightIn(min = 60.dp).padding(horizontal = 14.dp, vertical = 10.dp),
) {
Column(Modifier.weight(1f)) {
Text(stringResource(storageTitle(item)), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Text(stringResource(agentStorageTitle(item)), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Text(
if (armed) stringResource(storageWarning(item)) else Formatter.formatShortFileSize(context, AgentStorage.sizes[item] ?: 0L),
if (armed) stringResource(agentStorageWarning(item)) else Formatter.formatShortFileSize(context, AgentStorage.sizes[item] ?: 0L),
fontSize = 13.sp, color = if (armed) AttentionAmber else pal.onSurfaceVariant,
)
}
@@ -214,7 +241,7 @@ private fun StorageCard() {
}
}
private fun storageTitle(item: AgentStorage.Item) = when (item) {
internal fun agentStorageTitle(item: AgentStorage.Item) = when (item) {
AgentStorage.Item.CLAUDE_CODE -> R.string.agent_storage_claude
AgentStorage.Item.CODEX -> R.string.agent_storage_codex
AgentStorage.Item.OPENCODE -> R.string.agent_storage_opencode
@@ -223,7 +250,7 @@ private fun storageTitle(item: AgentStorage.Item) = when (item) {
AgentStorage.Item.CACHES -> R.string.agent_storage_caches
}
private fun storageWarning(item: AgentStorage.Item) = when (item) {
internal fun agentStorageWarning(item: AgentStorage.Item) = when (item) {
AgentStorage.Item.SOURCE -> R.string.agent_storage_source_warning
AgentStorage.Item.CACHES -> R.string.agent_storage_caches_warning
else -> R.string.agent_storage_reinstall_warning
@@ -1,44 +1,93 @@
package com.droiddeck.launcher.ui
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Build
import android.os.IBinder
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.speech.RecognitionListener
import android.speech.RecognitionService
import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
/** Dictation into the Agent editor: what is heard so far follows the text already typed, until the user edits the draft. */
/**
* Dictation into the Agent editor: what is heard so far follows the text already typed, until the user edits the draft.
* Listening carries on across pauses until [finish], which can send once the last words are written.
*/
internal class AgentVoice(private val context: Context, private val draft: () -> String, private val onText: (String) -> Unit) {
var listening by mutableStateOf(false)
private set
/** Whether listening goes on without the button held. */
var locked by mutableStateOf(false)
/** How loud the speech is, from 0 to 1. */
var level by mutableFloatStateOf(0f)
private set
/** Set when the speech service could not open the microphone, which a fresh install of Speech Services by Google cannot until allowed. */
var serviceMicBlocked by mutableStateOf(false)
private var recognizer: SpeechRecognizer? = null
private var typed = ""
private var base = ""
private var written = ""
/** Set between [finish] and the final result, while a send may still be waiting on the last words. */
var finishing by mutableStateOf(false)
private set
private var then: (() -> Unit)? = null
private val main = Handler(Looper.getMainLooper())
fun start(typed: String) {
stop()
val speech = runCatching { SpeechRecognizer.createSpeechRecognizer(context) }.getOrNull() ?: return
val service = component(context)
val speech = runCatching { SpeechRecognizer.createSpeechRecognizer(context, service) }.getOrNull() ?: return
recognizer = speech
base = typed.trimEnd().let { if (it.isEmpty()) it else "$it " }
if (service != null && !isDefault(context)) lend(service)
this.typed = typed
base = continued(typed)
written = typed
finishing = false
listening = true
speech.setRecognitionListener(object : RecognitionListener {
override fun onReadyForSpeech(params: Bundle?) { listening = true }
override fun onReadyForSpeech(params: Bundle?) {}
override fun onBeginningOfSpeech() {}
override fun onRmsChanged(rmsdB: Float) {}
override fun onRmsChanged(rmsdB: Float) { if (recognizer === speech) level = ((rmsdB + 2f) / 12f).coerceIn(0f, 1f) }
override fun onBufferReceived(buffer: ByteArray?) {}
override fun onEndOfSpeech() {}
override fun onError(error: Int) { if (recognizer === speech) stop() }
override fun onEndOfSpeech() { level = 0f }
override fun onError(error: Int) {
if (recognizer !== speech) return
// The recognizer gives up on a pause; the user is still talking until they let go or stop.
if (!finishing && (error == SpeechRecognizer.ERROR_NO_MATCH || error == SpeechRecognizer.ERROR_SPEECH_TIMEOUT)) {
base = continued(written)
relisten(speech)
} else {
done()
if (error == SpeechRecognizer.ERROR_AUDIO || error == SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS) serviceMicBlocked = true
}
}
override fun onResults(results: Bundle?) {
if (recognizer !== speech) return
heard(results)
stop()
if (recognizer !== speech) return
if (finishing) done() else {
base = continued(written)
relisten(speech)
}
}
override fun onPartialResults(partialResults: Bundle?) { if (recognizer === speech) heard(partialResults) }
override fun onEvent(eventType: Int, params: Bundle?) {}
})
listen(speech)
}
private fun continued(text: String) = text.trimEnd().let { if (it.isEmpty()) it else "$it " }
private fun listen(speech: SpeechRecognizer) {
val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)
@@ -46,22 +95,71 @@ internal class AgentVoice(private val context: Context, private val draft: () ->
runCatching { speech.startListening(intent) }.onFailure { stop() }
}
private fun relisten(speech: SpeechRecognizer) {
main.post { if (recognizer === speech && !finishing) listen(speech) }
}
private fun heard(results: Bundle?) {
val spoken = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull()?.takeIf { it.isNotBlank() } ?: return
if (draft() != written) return stop()
if (draft() != written) return if (finishing) done() else stop()
written = base + spoken
onText(written)
}
/** Ends listening but keeps the recognizer until its final result arrives. */
fun finish() {
/** Ends listening but keeps the recognizer until its final result arrives, then runs [then]. */
fun finish(then: (() -> Unit)? = null) {
val speech = recognizer ?: return
finishing = true
this.then = then
listening = false
runCatching { speech.stopListening() }.onFailure { stop() }
locked = false
level = 0f
runCatching { speech.stopListening() }.onFailure { done() }
// Some recognizers never answer a stop with nothing heard.
main.postDelayed({ if (recognizer === speech) done() }, FINAL_RESULT_TIMEOUT_MS)
}
private fun done() {
val next = then
stop()
next?.invoke()
}
/** Stops listening, but a send already waiting on the last words goes ahead with what was heard. */
fun settle() {
if (finishing) done() else stop()
}
/** Stops and puts back the text typed before listening began. */
fun cancel() {
val restore = draft() == written
stop()
if (restore) onText(typed)
}
private var lent: ServiceConnection? = null
// Android passes the microphone only to the default speech service on its own; any other one records silence unless
// the app in front binds it with its own capabilities for as long as it listens.
private fun lend(service: ComponentName) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return
val connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {}
override fun onServiceDisconnected(name: ComponentName?) {}
}
val intent = Intent(RecognitionService.SERVICE_INTERFACE).setComponent(service)
if (runCatching { context.bindService(intent, connection, Context.BIND_AUTO_CREATE or Context.BIND_INCLUDE_CAPABILITIES) }.getOrDefault(false)) lent = connection
else runCatching { context.unbindService(connection) }
}
fun stop() {
lent?.let { runCatching { context.unbindService(it) } }
lent = null
then = null
finishing = false
listening = false
locked = false
level = 0f
val speech = recognizer ?: return
recognizer = null
runCatching { speech.cancel() }
@@ -69,6 +167,38 @@ internal class AgentVoice(private val context: Context, private val draft: () ->
}
companion object {
private const val FINAL_RESULT_TIMEOUT_MS = 3000L
fun available(context: Context) = SpeechRecognizer.isRecognitionAvailable(context)
/** The package that turns speech into text, if one is installed. */
fun service(context: Context): String? = component(context)?.packageName
const val DEFAULT_SETTING = "voice_recognition_service"
private fun chosen(context: Context) = android.provider.Settings.Secure.getString(context.contentResolver, DEFAULT_SETTING)
?.takeIf { it.isNotBlank() }?.let(ComponentName::unflattenFromString)
private fun installed(context: Context) = context.packageManager.queryIntentServices(Intent(RecognitionService.SERVICE_INTERFACE), 0)
.map { ComponentName(it.serviceInfo.packageName, it.serviceInfo.name) }
// Installing a speech service does not always make it the system's choice, and without one Android refuses to listen.
fun component(context: Context): ComponentName? {
val chosen = chosen(context)
val installed = installed(context)
return installed.firstOrNull { it == chosen } ?: installed.firstOrNull()
}
/**
* Whether the installed service is the system's chosen one. Android only passes DroidDeck's right to the microphone on to that one;
* any other service hears silence once DroidDeck is in front.
*/
fun isDefault(context: Context): Boolean {
val chosen = chosen(context) ?: return false
return chosen in installed(context)
}
fun serviceHears(context: Context, service: String) =
context.packageManager.checkPermission(android.Manifest.permission.RECORD_AUDIO, service) == android.content.pm.PackageManager.PERMISSION_GRANTED
}
}
@@ -0,0 +1,160 @@
package com.droiddeck.launcher.ui
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.Settings
import androidx.activity.compose.LocalActivityResultRegistryOwner
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.platform.testTag
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 androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.WirelessAdbFix
private const val SPEECH_SERVICES = "com.google.android.tts"
/** Whether the mic can turn speech into text: a speech service is installed, and it and DroidDeck may both use the microphone. */
internal fun voiceReady(context: Context): Boolean {
val service = AgentVoice.service(context) ?: return false
return appHears(context) && AgentVoice.serviceHears(context, service)
}
/** Runs [command] over the saved Wireless debugging pairing off the main thread, then [done] on it with whether it worked. */
private fun adb(context: Context, command: String, done: (Boolean) -> Unit) {
val app = context.applicationContext
Thread({
// The pairing can be with another device, where the grant would land instead of here.
val ok = runCatching { WirelessAdbFix.savedPairingIsLocal(app) }.getOrDefault(false) && runCatching { WirelessAdbFix.shell(app, command) }.isSuccess
android.os.Handler(android.os.Looper.getMainLooper()).post { done(ok) }
}, "agent-voice-setup").start()
}
private fun appHears(context: Context) = context.checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
/** Opens [intent] over DroidDeck when it can, so Back comes straight back to the setup. */
private fun open(context: Context, intent: Intent): Boolean {
var base = context
while (base !is Activity && base is ContextWrapper) base = base.baseContext
return runCatching {
if (base is Activity) base.startActivity(intent) else context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}.isSuccess
}
private fun openAppInfo(context: Context, pkg: String) {
open(context, Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", pkg, null)))
}
private fun openStore(context: Context) {
if (!open(context, Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$SPEECH_SERVICES")))) {
open(context, Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=$SPEECH_SERVICES")))
}
}
/** What talking to the agent still needs, each step one button away, checked again whenever DroidDeck comes back. */
@Composable
internal fun AgentVoiceSetup(onReady: () -> Unit, onClose: () -> Unit) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var checks by remember { mutableIntStateOf(0) }
val owner = LocalLifecycleOwner.current
DisposableEffect(owner) {
val observer = LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_RESUME) checks++ }
owner.lifecycle.addObserver(observer)
onDispose { owner.lifecycle.removeObserver(observer) }
}
val service = remember(checks) { AgentVoice.service(context) }
val appMic = remember(checks) { appHears(context) }
val serviceMic = remember(checks, service) { service != null && AgentVoice.serviceHears(context, service) }
val paired = remember(checks) { WirelessAdbFix.hasSavedPairing(context) }
var working by remember { mutableStateOf(false) }
val shown = remember { booleanArrayOf(true) }
DisposableEffect(Unit) { onDispose { shown[0] = false } }
// A saved pairing does not mean Wireless debugging is on now, so a refusal falls back to doing it by hand.
val viaAdb: (String, () -> Unit) -> Unit = { command, byHand ->
working = true
adb(context, command) { ok ->
working = false
checks++
if (!ok && shown[0]) byHand()
}
}
LaunchedEffect(service, appMic, serviceMic) { if (service != null && appMic && serviceMic) onReady() }
val ask = if (LocalActivityResultRegistryOwner.current != null) rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
// Android stops asking after the user refuses twice; the switch is then only in App info.
if (granted) checks++ else openAppInfo(context, context.packageName)
} else null
Column(
Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14).testTag("agent-voice-setup"),
) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(start = 14.dp, end = 6.dp, top = 6.dp)) {
Text(
stringResource(R.string.agent_voice_setup), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
modifier = Modifier.weight(1f),
)
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(36.dp).clip(CircleShape).clickable(onClick = onClose)) {
Icon(Icons.Outlined.Close, stringResource(R.string.agent_voice_setup_close), tint = pal.onSurfaceVariant, modifier = Modifier.size(18.dp))
}
}
CheckRow(
if (service != null) CheckState.OK else CheckState.WARN, stringResource(R.string.agent_voice_setup_service),
if (service == null) stringResource(R.string.agent_voice_setup_service_detail) else null,
action = if (service == null) ({ SecondaryButton(stringResource(R.string.setup_install), compact = true) { openStore(context) } }) else null,
)
CheckRow(
if (appMic) CheckState.OK else CheckState.WARN, stringResource(R.string.agent_voice_setup_app_mic), null,
action = if (!appMic) ({
SecondaryButton(stringResource(R.string.libraries_access_allow), compact = true) {
if (ask != null) ask.launch(Manifest.permission.RECORD_AUDIO) else openAppInfo(context, context.packageName)
}
}) else null,
)
CheckRow(
if (serviceMic) CheckState.OK else CheckState.WARN, stringResource(R.string.agent_voice_setup_service_mic),
if (service != null && !serviceMic && !paired) stringResource(R.string.agent_voice_setup_service_mic_detail) else null, divider = false,
action = if (service != null && !serviceMic) ({
SecondaryButton(stringResource(R.string.libraries_access_allow), enabled = !working, compact = true) {
if (paired) viaAdb("pm grant $service ${Manifest.permission.RECORD_AUDIO}") { openAppInfo(context, service) } else openAppInfo(context, service)
}
}) else null,
)
}
}
@@ -848,13 +848,28 @@ private fun FolderSheet(
renaming = false
}
val firstApp = remember { FocusRequester() }
val title = remember { FocusRequester() }
var toTitle by remember { mutableStateOf(false) }
var titleFocused by remember { mutableStateOf(false) }
val sheetView = androidx.compose.ui.platform.LocalView.current
val leaveName = {
if (renaming) {
(ctx.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager)
?.hideSoftInputFromWindow(sheetView.windowToken, 0)
toTitle = true
commit()
}
}
val inputMode = LocalInputModeManager.current.inputMode
val ff = LocalFrontFocus.current
val grid = rememberLazyGridState()
var closing by remember { mutableStateOf(false) }
var inside by remember { mutableStateOf(false) }
LaunchedEffect(renaming, inputMode) {
if (!renaming && !closing && inputMode == InputMode.Keyboard && apps.isNotEmpty()) {
if (!renaming && !closing && toTitle) {
focusWithinFrames({ titleFocused || closing }) { title }
toTitle = false
} else if (!renaming && !closing && inputMode == InputMode.Keyboard && apps.isNotEmpty()) {
grid.scrollToItem(0)
androidx.compose.runtime.withFrameNanos { }
// After touch, focus starts outside the page and the first request is turned to the page's own entry, behind the sheet. Ask until it is in here.
@@ -885,6 +900,12 @@ private fun FolderSheet(
.clip(Shape16).background(pal.surfaceVariant.copy(alpha = 0.97f))
.glideBorder(false, Shape16, pal.signal, pal.signal.copy(alpha = 0.22f))
.pointerInput(Unit) { awaitEachGesture { awaitFirstDown(requireUnconsumed = false).consume() } }
.onPreviewKeyEvent { event ->
val k = event.nativeKeyEvent
if (!renaming || k.keyCode != KeyEvent.KEYCODE_BUTTON_B) return@onPreviewKeyEvent false
if (k.action == KeyEvent.ACTION_DOWN && k.repeatCount == 0) leaveName()
true
}
.controllerBack(close)
.onFocusChanged { inside = it.hasFocus }
.focusProperties {
@@ -901,7 +922,7 @@ private fun FolderSheet(
AdbTextField(
value = name, onValueChange = { name = it.take(40) }, label = stringResource(R.string.apps_folder_name),
keyboardType = KeyboardType.Text, imeAction = ImeAction.Done, compact = true, showLabel = false,
placeholder = folder.name, focusOnShow = true, onDone = { commit() },
placeholder = folder.name, focusOnShow = true, onDone = { commit() }, onBack = leaveName,
)
} else {
val src = remember { MutableInteractionSource() }
@@ -914,6 +935,8 @@ private fun FolderSheet(
modifier = Modifier.clip(Shape12)
.background(if (hot) pal.signal.copy(alpha = 0.12f) else colors.onBackground.copy(alpha = 0.07f))
.glideBorder(hot, Shape12, pal.signal)
.focusRequester(title)
.onFocusChanged { titleFocused = it.isFocused }
.hoverable(src)
.clickable(interactionSource = src, indication = LocalIndication.current, onClickLabel = stringResource(R.string.apps_folder_rename), role = Role.Button, onClick = rename)
.controllerConfirm(onClick = rename)
@@ -100,7 +100,7 @@ fun BottomDownloadsPage() {
formatSpeed(e.speedBps),
).filter { it.isNotEmpty() }.joinToString(" · ")
}
BottomDownloadRow(e.name, e.store.label, detail, e.stageFraction.takeIf { it >= 0f })
BottomDownloadRow(e.name, e.store.label, detail, steadyProgress(e))
}
}
}
@@ -10,13 +10,17 @@ import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
@@ -31,12 +35,14 @@ import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.R
import kotlin.math.atan2
@@ -77,33 +83,63 @@ internal fun ColorPickerDialog(title: String, initial: Int, onDismiss: () -> Uni
hue = h.coerceIn(0f, 360f); sat = s.coerceIn(0f, 1f); value = v.coerceIn(0f, 1f)
hexText = ThemeColors.hex(ThemeColors.fromHsv(hue, sat, value))
}
AppDialog(shown, close, "colorPicker", wide = false, maxWidth = 460.dp, scrollState = scroll) {
val screen = LocalConfiguration.current
val beside = screen.screenWidthDp > screen.screenHeightDp && screen.screenWidthDp >= 600
val wheelSize = if (beside) (screen.screenHeightDp - 176).coerceIn(160, 216).dp else 168.dp
val short = beside && wheelSize < 216.dp
AppDialog(shown, close, "colorPicker", wide = false, maxWidth = if (beside) 680.dp else 460.dp, scrollState = scroll) {
DialogTitleRow(title, close)
Row(horizontalArrangement = Arrangement.spacedBy(14.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
ColorWheel(hue, sat, value) { h, s -> picked(h = h, s = s) }
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Swatch(Color(initial))
Swatch(Color(current))
}
val wheel: @Composable () -> Unit = { ColorWheel(hue, sat, value, wheelSize) { h, s -> picked(h = h, s = s) } }
val track = if (short) 24.dp else 40.dp
val sliders: @Composable () -> Unit = {
ValueSlider(hue.toInt(), 0..360, step = 5, enabled = true, label = stringResource(R.string.theme_color_hue), format = { "$it°" },
modifier = Modifier.focusRequester(first), track = track) { picked(h = it.toFloat()) }
ValueSlider((sat * 100).toInt(), 0..100, step = 2, enabled = true, label = stringResource(R.string.theme_color_saturation), format = { "$it%" },
track = track) { picked(s = it / 100f) }
ValueSlider((value * 100).toInt(), 0..100, step = 2, enabled = true, label = stringResource(R.string.theme_color_brightness), format = { "$it%" },
track = track) { picked(v = it / 100f) }
}
ValueSlider(hue.toInt(), 0..360, step = 5, enabled = true, label = stringResource(R.string.theme_color_hue), format = { "$it°" },
modifier = Modifier.focusRequester(first)) { picked(h = it.toFloat()) }
ValueSlider((sat * 100).toInt(), 0..100, step = 2, enabled = true, label = stringResource(R.string.theme_color_saturation), format = { "$it%" }) { picked(s = it / 100f) }
ValueSlider((value * 100).toInt(), 0..100, step = 2, enabled = true, label = stringResource(R.string.theme_color_brightness), format = { "$it%" }) { picked(v = it / 100f) }
AdbTextField(
value = hexText,
onValueChange = { text ->
hexText = text
ThemeColors.parseHex(text)?.let { argb -> ThemeColors.toHsv(argb).let { hsv -> hue = hsv.h; sat = hsv.s; value = hsv.v } }
},
label = "", keyboardType = KeyboardType.Ascii, imeAction = ImeAction.Done, placeholder = stringResource(R.string.theme_color_hex),
onFocusChange = { typingHex = it },
onDone = { ThemeColors.parseHex(hexText)?.let { onApply(it); close() } },
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
SecondaryButton(stringResource(R.string.common_cancel), modifier = Modifier.weight(1f), onClick = close)
PrimaryButton(stringResource(R.string.common_ok), enabled = ThemeColors.parseHex(hexText) != null, modifier = Modifier.weight(1f)) {
ThemeColors.parseHex(hexText)?.let { onApply(it); close() }
val hex: @Composable (Modifier) -> Unit = { modifier ->
AdbTextField(
value = hexText,
onValueChange = { text ->
hexText = text
ThemeColors.parseHex(text)?.let { argb -> ThemeColors.toHsv(argb).let { hsv -> hue = hsv.h; sat = hsv.s; value = hsv.v } }
},
label = "", keyboardType = KeyboardType.Ascii, imeAction = ImeAction.Done, placeholder = stringResource(R.string.theme_color_hex),
showLabel = false, compact = beside, modifier = modifier,
onFocusChange = { typingHex = it },
onDone = { ThemeColors.parseHex(hexText)?.let { onApply(it); close() } },
)
}
val ok = { ThemeColors.parseHex(hexText)?.let { onApply(it); close() }; Unit }
val valid = ThemeColors.parseHex(hexText) != null
if (beside) {
Row(horizontalArrangement = Arrangement.spacedBy(20.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
wheel()
Column(verticalArrangement = Arrangement.spacedBy(if (short) 2.dp else 8.dp), modifier = Modifier.weight(1f)) {
CompositionLocalProvider(LocalCompactSettings provides true) { sliders() }
}
}
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
BeforeAfter(Color(initial), Color(current), Modifier.size(96.dp, 44.dp))
hex(Modifier.weight(1f))
SecondaryButton(stringResource(R.string.common_cancel), modifier = Modifier.width(128.dp), onClick = close)
PrimaryButton(stringResource(R.string.common_ok), enabled = valid, modifier = Modifier.width(128.dp), fill = true, onClick = ok)
}
} else {
Row(horizontalArrangement = Arrangement.spacedBy(14.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
wheel()
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Swatch(Color(initial))
Swatch(Color(current))
}
}
sliders()
hex(Modifier)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
SecondaryButton(stringResource(R.string.common_cancel), modifier = Modifier.weight(1f), onClick = close)
PrimaryButton(stringResource(R.string.common_ok), enabled = valid, modifier = Modifier.weight(1f), fill = true, onClick = ok)
}
}
}
@@ -116,9 +152,17 @@ private fun Swatch(color: Color) {
}
@Composable
private fun ColorWheel(hue: Float, sat: Float, value: Float, onPick: (hue: Float, sat: Float) -> Unit) {
private fun BeforeAfter(before: Color, after: Color, modifier: Modifier) {
val shape = RoundedCornerShape(10.dp)
Row(modifier.clip(shape).border(1.dp, LocalPalette.current.line2, shape)) {
Box(Modifier.weight(1f).fillMaxHeight().background(before))
Box(Modifier.weight(1f).fillMaxHeight().background(after))
}
}
@Composable
private fun ColorWheel(hue: Float, sat: Float, value: Float, size: Dp, onPick: (hue: Float, sat: Float) -> Unit) {
val rim = MaterialTheme.colorScheme.onBackground
val size = 168.dp
fun at(offset: Offset, side: Float) {
val center = side / 2f
val dx = offset.x - center
@@ -84,6 +84,7 @@ import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.ComponentUpdater
import com.droiddeck.launcher.session.ComponentUpdates
import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.session.ExperimentalProtons
import com.droiddeck.launcher.session.ComponentsManager.CatalogItem
import com.droiddeck.launcher.session.ComponentsManager.Snapshot
import kotlinx.coroutines.delay
@@ -524,7 +525,7 @@ fun ComponentsPage(
}
val availableTitle: @Composable (String) -> String = { l ->
when (l) {
PROTON_TAB -> stringResource(R.string.comp_available_count, protons.rows.count { it.installed == null || it.update != null })
PROTON_TAB -> stringResource(R.string.comp_available_count, protons.rows.count(ProtonRow::available))
else -> stringResource(R.string.comp_nightlies_count, availableRows(l, catalog, snapshot).size)
}
}
@@ -539,7 +540,8 @@ fun ComponentsPage(
val key = "proton:${v.proton.id}"
val swaps = v.components.values.count { it.activeFile != null }
val extra = protons.rows.firstOrNull { v.proton.dir.name in it.installedAll }
val removable = extra != null && protons.busyId == null && protons.runtimeReady && !protons.sessionRunning
val experimental = v.proton.dir.name in protons.experimental
val removable = (extra != null || experimental) && protons.busyId == null && protons.runtimeReady && !protons.sessionRunning
ChoiceLine(
v.proton.name,
(if (swaps > 0) stringResource(R.string.comp_swapped, v.proton.version, swaps) else stringResource(R.string.comp_all_original, v.proton.version))
@@ -548,7 +550,10 @@ fun ComponentsPage(
modifier = (if (i == 0 && !moded(l)) Modifier.focusRequester(firstRow) else Modifier).trackRow(key, rowsAt),
onSelect = { if (v.proton.id != view?.proton?.id) { onProton(v.proton.id); flyHome(key, PROTON_TAB) } },
onDelete = {
if (extra != null) ask(key, right, ctx.getString(R.string.proton_remove_title, v.proton.name), ctx.getString(R.string.proton_remove_body), ctx.getString(R.string.store_remove), true, v.proton.name) {
if (experimental) ask(key, right, ctx.getString(R.string.proton_remove_title, v.proton.name), ctx.getString(R.string.proton_remove_body), ctx.getString(R.string.store_remove), true, v.proton.name) {
protonActions.onRemoveExperimental(v.proton.dir.name)
}
else if (extra != null) ask(key, right, ctx.getString(R.string.proton_remove_title, v.proton.name), ctx.getString(R.string.proton_remove_body), ctx.getString(R.string.store_remove), true, v.proton.name) {
protonActions.onRemove(extra.id, v.proton.dir.name)
}
},
@@ -589,21 +594,24 @@ fun ComponentsPage(
val availableRows: @Composable ColumnScope.(String) -> Unit = { l ->
when (l) {
PROTON_TAB -> {
val rows = protons.rows.filter { it.installed == null || it.update != null }
val rows = protons.rows.filter(ProtonRow::available)
if (rows.isEmpty()) EmptyLine(stringResource(R.string.comp_nothing_new))
for (row in rows) GetLine(
row.name,
when {
row.update != null -> stringResource(R.string.proton_update_available, row.update)
row.queued -> stringResource(R.string.proton_queued)
else -> stringResource(R.string.proton_not_installed)
},
progress = if (protons.busyId == row.id) protons.percent else null,
stage = if (protons.busyId == row.id) protons.stage else null,
enabled = protons.busyId == null && protons.runtimeReady && !protons.sessionRunning,
onCancel = if (row.queued && protons.busyId == null && !protons.sessionRunning) ({ protonActions.onCancel(row.id) }) else null,
action = if (row.update != null) stringResource(R.string.common_update) else null,
) { protonActions.onInstall(row.id) }
for (row in rows) {
val idle = protons.busyId == null && protons.runtimeReady && !protons.sessionRunning
GetLine(
row.name,
when {
row.update != null -> stringResource(R.string.proton_update_available, row.update)
row.queued -> stringResource(R.string.proton_queued)
else -> stringResource(R.string.proton_not_installed)
},
progress = if (protons.busyId == row.id) protons.percent else null,
stage = if (protons.busyId == row.id) protons.stage else null,
enabled = idle,
onCancel = if (row.queued && protons.busyId == null && !protons.sessionRunning) ({ protonActions.onCancel(row.id) }) else null,
action = if (row.update != null) stringResource(R.string.common_update) else null,
) { protonActions.onInstall(row.id) }
}
}
else -> {
val available = availableRows(l, catalog, snapshot)
@@ -731,6 +739,8 @@ fun ComponentsPage(
}
}
if (l == PROTON_TAB) {
Spacer(Modifier.height(12.dp))
ExperimentalProtonGroup(protons, protonActions)
Spacer(Modifier.height(12.dp))
Note(stringResource(R.string.comp_about_text))
}
@@ -1528,12 +1538,12 @@ private fun GetLine(
}
@Composable
private fun ChannelToggle(nightly: Boolean, enabled: Boolean, onFlip: () -> Unit) {
private fun ChannelToggle(nightly: Boolean, enabled: Boolean, other: Int = R.string.comp_channel_nightly, onFlip: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src) && enabled
val state = stringResource(if (nightly) R.string.comp_channel_nightly else R.string.comp_channel_stable)
val state = stringResource(if (nightly) other else R.string.comp_channel_stable)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(2.dp),
modifier = Modifier.heightIn(min = 44.dp).clip(RoundedCornerShape(10.dp))
@@ -1544,12 +1554,12 @@ private fun ChannelToggle(nightly: Boolean, enabled: Boolean, onFlip: () -> Unit
.semantics { stateDescription = state }
.padding(4.dp),
) {
for ((label, on) in listOf(R.string.comp_channel_stable to !nightly, R.string.comp_channel_nightly to nightly)) {
for ((label, on) in listOf(R.string.comp_channel_stable to !nightly, other to nightly)) {
Text(
stringResource(label), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1,
color = if (!enabled) colors.onSurfaceVariant else if (on) (if (hot) pal.onSignal else pal.signal) else colors.onSurfaceVariant,
color = if (on) (if (hot) pal.onSignal else pal.signal) else colors.onSurfaceVariant,
modifier = Modifier.clip(RoundedCornerShape(7.dp))
.background(if (on && enabled) (if (hot) pal.signal else pal.signal.copy(alpha = 0.16f)) else Color.Transparent)
.background(if (on) (if (hot) pal.signal else pal.signal.copy(alpha = 0.16f)) else Color.Transparent)
.padding(horizontal = 10.dp, vertical = 6.dp),
)
}
@@ -1623,6 +1633,25 @@ private fun DeviceChip(s: GpuDriversState) {
) { face() }
}
@Composable
private fun ExperimentalProtonGroup(protons: ProtonsState, actions: ProtonsActions) {
val busy = protons.busyId == com.droiddeck.launcher.ProtonMenu.EXPERIMENTAL
val idle = protons.busyId == null && protons.runtimeReady && !protons.sessionRunning
RowGroup(stringResource(R.string.xproton_title)) {
if (busy) GetLine(stringResource(R.string.xproton_title), "", progress = protons.percent, enabled = false, stage = protons.stage) {}
else {
protons.experimentalReleases.forEach { release ->
GetLine(release.name, release.tag, progress = null, enabled = idle, action = stringResource(R.string.proton_install_now)) {
actions.onExperimentalRelease(release)
}
}
Row(horizontalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.padding(start = 14.dp, top = 4.dp, bottom = 8.dp)) {
SmallButton(stringResource(R.string.xproton_install_file), enabled = idle, onClick = actions.onExperimentalFile)
}
}
}
}
class ProtonsState(
val rows: List<ProtonRow> = emptyList(),
val busyId: String? = null,
@@ -1630,6 +1659,8 @@ class ProtonsState(
val percent: Int = -1,
val runtimeReady: Boolean = true,
val sessionRunning: Boolean = false,
val experimental: List<String> = emptyList(),
val experimentalReleases: List<ExperimentalProtons.Release> = emptyList(),
)
class ProtonsActions(
@@ -1637,12 +1668,17 @@ class ProtonsActions(
val onCancel: (String) -> Unit = {},
val onRemove: (String, String) -> Unit = { _, _ -> },
val onRemoveOlder: (String) -> Unit = {},
val onExperimentalFile: () -> Unit = {},
val onExperimentalRelease: (ExperimentalProtons.Release) -> Unit = {},
val onRemoveExperimental: (String) -> Unit = {},
)
class ProtonRow(
val id: String, val name: String, val installed: String?, val queued: Boolean,
val installedAll: List<String> = listOfNotNull(installed), val update: String? = null,
)
) {
val available: Boolean get() = installed == null || update != null
}
@Composable
private fun gpuCardValue(gpu: GpuDriversState, auto: String): String {
@@ -14,6 +14,7 @@ import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.hud.DroidDeckHudConfig
import com.droiddeck.launcher.hud.DroidDeckHudSize
import com.droiddeck.launcher.session.GpuClockPin
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.StripMetric
@@ -47,6 +48,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
ToggleRow(host, "hud-snap", stringResource(R.string.hud_snap), stringResource(R.string.hud_snap_hint), on("hudSnap"),
chipModifier = track("hud-snap")) { a.onHudSetting("hudSnap", flag(it)) }
}
if (GpuClockPin.supported) GpuClockGroup(host, a.gpuClockPin, track("gpuclock"), a.onGpuClockPin)
if (a.dashboardAvailable && a.secondScreenDisplays.isNotEmpty()) BottomStripSettings(host, track)
if (!a.hudOn) return
@@ -47,7 +47,7 @@ internal fun GameFileFolderActions(s: FrontEndState, a: FrontEndActions, labeled
var open by remember { androidx.compose.runtime.mutableStateOf(false) }
Box {
if (labeled) SecondaryButton(stringResource(R.string.game_frontend_files), compact = true) { open = !open }
else HeaderIconButton(stringResource(R.string.game_frontend_files), androidx.compose.material.icons.Icons.Outlined.Sync, "frontend-files") { open = !open }
else HeaderIconButton(stringResource(R.string.game_frontend_files), androidx.compose.material.icons.Icons.Outlined.Sync, "frontend-files", Modifier.downToFirstTile()) { open = !open }
AnchoredMenu(open, onDismiss = { open = false }, title = s.gameSyncFolder ?: stringResource(R.string.game_frontend_files)) { first ->
MenuItem(stringResource(R.string.game_file_sync), checked = false, focusRequester = first) {
open = false; a.onSyncGameFiles()
@@ -82,6 +82,12 @@ internal fun cloudMessage(context: android.content.Context, r: com.droiddeck.lau
r.files == 0 -> context.getString(R.string.cloud_up_to_date)
else -> context.getString(R.string.cloud_done, r.files)
}
"partial" -> when {
r.conflicts > 0 && r.detail.isNotEmpty() -> context.getString(R.string.cloud_conflict_files_detail, r.conflicts, r.detail)
r.conflicts > 0 -> context.getString(R.string.cloud_conflict_files, r.conflicts)
r.detail.isNotEmpty() -> context.getString(R.string.cloud_partial, r.detail)
else -> context.getString(R.string.cloud_not_synced)
}
"skipped" -> context.getString(when (r.reason) {
"not-signed-in" -> R.string.cloud_signed_out
"no-cloud-saves" -> R.string.cloud_none
@@ -61,7 +61,6 @@ import androidx.compose.material.icons.outlined.Storefront
import androidx.compose.material.icons.outlined.SystemUpdate
import androidx.compose.material.icons.outlined.Tune
import androidx.compose.material.icons.outlined.Toys
import androidx.compose.material.icons.outlined.VideoLibrary
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
@@ -197,7 +196,7 @@ internal fun SideRail(
internal fun railLabelIcon(key: String): Pair<Int, ImageVector> = when (key) {
"steam" -> R.string.rail_steam to Icons.Outlined.SportsEsports
"games" -> R.string.rail_games to Icons.Outlined.VideoLibrary
"games" -> R.string.rail_games to GameShelfIcon
"soundtracks" -> R.string.rail_music to SoundtrackIcon
"stores" -> R.string.rail_stores to Icons.Outlined.LocalMall
"downloads" -> R.string.stores_tab_downloads to Icons.Outlined.Download
@@ -754,11 +754,11 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
onRailSelect(key)
}, a)
CompositionLocalProvider(LocalShowSection provides { key -> selected = key }) {
val agentKeyboardOpen = railSelection == "agent" && WindowInsets.ime.getBottom(androidx.compose.ui.platform.LocalDensity.current) > 0
val agentKeyboardOpen = openTab == "agent" && WindowInsets.ime.getBottom(androidx.compose.ui.platform.LocalDensity.current) > 0
LauncherLayout(
bottomNavigation && !s.dualScreen, pal.line,
Modifier.fillMaxSize().onGloballyPositioned { screenAt = it.positionInRoot() }
.then(if (railSelection == "agent") Modifier.imePadding() else Modifier)
.then(if (openTab == "agent") Modifier.imePadding() else Modifier)
.then(if (s.dualScreen) Modifier.onKeyEvent { event ->
val step = dualPageStep(event.nativeKeyEvent) ?: return@onKeyEvent false
if (event.type == KeyEventType.KeyDown && !processSettingsPageVisible) {
@@ -437,6 +437,7 @@ internal fun SetupPanel(
}
if (s.theme == Themes.INNER_GAMER) RgbSpeedRow()
if (s.theme == Themes.GRADIENT) GradientColorRows()
if (s.theme == Themes.CUSTOM) CustomColorRows()
if (s.theme == Themes.TRUE_BLACK) HighlightColorRow()
ChoiceRow(
host, "app-scale", stringResource(R.string.setup_app_scale), stringResource(R.string.setup_app_scale_hint),
@@ -1212,3 +1213,42 @@ private fun GradientColorRows() {
if (picking == 1) Themes.setGradient(ctx, argb, secondary) else Themes.setGradient(ctx, primary, argb)
}
}
@Composable
private fun CustomColorRows() {
val ctx = androidx.compose.ui.platform.LocalContext.current.applicationContext
val colors = Themes.customColors
var picking by remember { mutableStateOf<String?>(null) }
val rows = listOf(
Triple("background", stringResource(R.string.theme_custom_background), colors.background),
Triple("surface", stringResource(R.string.theme_custom_surface), colors.surface),
Triple("surfaceVariant", stringResource(R.string.theme_custom_surface_variant), colors.surfaceVariant),
Triple("line", stringResource(R.string.theme_custom_line), colors.line),
Triple("line2", stringResource(R.string.theme_custom_line2), colors.line2),
Triple("onBackground", stringResource(R.string.theme_custom_on_background), colors.onBackground),
Triple("onSurfaceVariant", stringResource(R.string.theme_custom_on_surface_variant), colors.onSurfaceVariant),
Triple("primary", stringResource(R.string.theme_custom_primary), colors.primary),
Triple("onPrimary", stringResource(R.string.theme_custom_on_primary), colors.onPrimary),
Triple("signal", stringResource(R.string.theme_custom_signal), colors.signal),
Triple("good", stringResource(R.string.theme_custom_good), colors.good),
Triple("error", stringResource(R.string.theme_custom_error), colors.error),
)
rows.forEach { (key, label, argb) ->
SettingsRow(label, null) {
ColorCube(Color(argb), label) { picking = key }
}
}
val selected = rows.firstOrNull { it.first == picking }
if (selected != null) {
ColorPickerDialog(
selected.second,
selected.third,
onDismiss = { picking = null },
) { argb ->
Themes.setCustomColor(ctx, selected.first, argb)
}
}
}
@@ -27,6 +27,7 @@ import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
@@ -54,6 +55,7 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.focus.focusProperties
@@ -112,7 +114,8 @@ internal fun Actions(content: @Composable () -> Unit) = FlowRow(
) { content() }
@Composable
internal fun ActionChip(t: String, ok: Boolean) = Box(contentAlignment = Alignment.Center, modifier = Modifier.heightIn(min = 44.dp)) { Chip(t, ok) }
internal fun ActionChip(t: String, ok: Boolean, fraction: Float? = null, key: Any? = null, minWidth: androidx.compose.ui.unit.Dp = 0.dp) =
Box(contentAlignment = Alignment.Center, modifier = Modifier.heightIn(min = 44.dp)) { Chip(t, ok, fraction, key, minWidth) }
internal val Shape16 = RoundedCornerShape(16.dp)
@@ -139,13 +142,33 @@ internal fun BackLink(label: String, compact: Boolean = false, onClick: () -> Un
}
@Composable
internal fun Chip(t: String, ok: Boolean) {
internal fun Chip(t: String, ok: Boolean, fraction: Float? = null, key: Any? = null, minWidth: androidx.compose.ui.unit.Dp = 0.dp) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Text(
t, fontSize = 12.sp, color = if (ok) pal.good else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.clip(RoundedCornerShape(99.dp)).background(colors.surfaceVariant).border(1.dp, if (ok) pal.good.copy(alpha = 0.3f) else pal.line, RoundedCornerShape(99.dp)).padding(horizontal = 9.dp, vertical = 4.dp),
)
val shape = RoundedCornerShape(99.dp)
val ink = if (ok) pal.good else colors.onSurfaceVariant
Box(Modifier.widthIn(min = minWidth).clip(shape).background(colors.surfaceVariant).border(1.dp, if (ok) pal.good.copy(alpha = 0.3f) else pal.line, shape), contentAlignment = Alignment.CenterStart) {
if (fraction != null) ChipFill(fraction, key, pal.signal.copy(alpha = 0.3f))
Text(
t, fontSize = 12.sp, color = ink, maxLines = 1, overflow = TextOverflow.Ellipsis,
style = androidx.compose.ui.text.TextStyle(fontFeatureSettings = "tnum"),
modifier = Modifier.padding(horizontal = 9.dp, vertical = 4.dp),
)
}
}
@Composable
internal fun androidx.compose.foundation.layout.BoxScope.ChipFill(fraction: Float, key: Any?, color: Color) {
androidx.compose.runtime.key(key) {
val target = fraction.coerceIn(0f, 1f)
val shown = remember { Animatable(target) }
LaunchedEffect(target) { shown.animateTo(target, androidx.compose.animation.core.tween(250, easing = androidx.compose.animation.core.LinearEasing)) }
Box(
Modifier.matchParentSize().drawBehind {
drawRect(color, size = androidx.compose.ui.geometry.Size(size.width * shown.value, size.height))
},
)
}
}
@Composable
@@ -1,5 +1,8 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import android.widget.Toast
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.LocalIndication
import androidx.compose.ui.semantics.Role
@@ -78,6 +81,7 @@ import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
@@ -257,7 +261,7 @@ internal fun GameDetail(
stringResource(R.string.game_tab_achievements_count, stringResource(R.string.achievements_title), achievementState.done, list.size)
} ?: stringResource(R.string.achievements_title)
GameTab.LAUNCH -> stringResource(R.string.game_tab_launch)
GameTab.SAVES -> stringResource(if (Store.byId(source).let { it == Store.GOG || it == Store.EPIC }) R.string.game_tab_saves_cloud else R.string.games_saves)
GameTab.SAVES -> stringResource(if (CloudSaves.supports(Store.byId(source))) R.string.game_tab_saves_cloud else R.string.games_saves)
GameTab.ADDONS -> stringResource(R.string.game_tab_addons)
GameTab.INSTALL -> stringResource(R.string.game_tab_install)
}
@@ -358,7 +362,7 @@ private fun GameTabBar(
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(modifier.fillMaxWidth().glass(CircleShape).padding(4.dp), verticalAlignment = Alignment.CenterVertically) {
if (bumpers) BumperKey("LB", stringResource(R.string.widgets_prev_tab)) { onSelect((selected + tabs.size - 1) % tabs.size) }
if (bumpers) TabBarBumper("LB", stringResource(R.string.widgets_prev_tab), leading = true) { onSelect((selected + tabs.size - 1) % tabs.size) }
tabs.forEachIndexed { i, label ->
val on = i == selected
val src = remember { MutableInteractionSource() }
@@ -382,7 +386,30 @@ private fun GameTabBar(
)
}
}
if (bumpers) BumperKey("RB", stringResource(R.string.widgets_next_tab)) { onSelect((selected + 1) % tabs.size) }
if (bumpers) TabBarBumper("RB", stringResource(R.string.widgets_next_tab), leading = false) { onSelect((selected + 1) % tabs.size) }
}
}
@Composable
private fun TabBarBumper(label: String, description: String, leading: Boolean, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val round = 22.dp
val flat = 7.dp
val cap = if (leading) RoundedCornerShape(round, flat, flat, round) else RoundedCornerShape(flat, round, round, flat)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.padding(start = if (leading) 0.dp else 3.dp, end = if (leading) 3.dp else 0.dp)
.size(width = 46.dp, height = 44.dp)
.clip(cap).background(colors.surfaceVariant).border(1.dp, pal.line2, cap)
.focusProperties { canFocus = false }
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, role = Role.Button, onClick = onClick)
.semantics { contentDescription = description },
) {
Text(
label, fontSize = 12.sp, fontWeight = FontWeight.Bold, color = colors.onSurfaceVariant,
modifier = Modifier.padding(start = if (leading) 4.dp else 0.dp, end = if (leading) 0.dp else 4.dp),
)
}
}
@@ -457,7 +484,7 @@ internal fun GameActions(
if (installed != null && id != null) {
LaunchedEffect(id) { BattleNetInstall.checkUpdate(ctx, installed) }
if (download != null) {
ActionChip(downloadLabel(download), ok = false)
SteadyDownloadChip(download)
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(download.key) }
else SecondaryButton(stringResource(R.string.stores_dl_resume)) { DownloadQueue.resume(ctx, download.key) }
} else if (BattleNetInstall.updates[id] == true) {
@@ -466,10 +493,13 @@ internal fun GameActions(
}
SecondaryButton(stringResource(R.string.bnet_open)) { a.onBattleNet() }
}
if (game != null && !compactMenu) EditArtButton(game)
if (game != null && !compactMenu) {
HideButton(hideKey(game), game)
EditArtButton(game)
}
}
download != null -> {
ActionChip(downloadLabel(download), ok = false)
SteadyDownloadChip(download)
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause), modifier = leadOn) { DownloadQueue.pause(download.key) }
else PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) { DownloadQueue.resume(ctx, download.key) }
ConfirmButton(stringResource(R.string.stores_dl_cancel), stringResource(R.string.stores_dl_cancel_confirm)) { DownloadQueue.cancel(ctx, download.key) }
@@ -526,6 +556,8 @@ internal fun GameActions(
}
item != null -> PrimaryButton(buyLabel(item), main = true, modifier = leadOn) { openStoreUrl(ctx, item) }
}
val entryKey = game?.let(::hideKey) ?: storeKey
if (!s.shortcutPicker && entryKey != null && (game == null || cloud)) HideButton(entryKey, game)
if (cloud && (download != null || failed != null)) {
XboxStreamButton(game.storeId.orEmpty(), game.name)
XboxLibraryButton(game.storeId.orEmpty(), item)
@@ -618,6 +650,17 @@ internal fun rememberEditArt(g: Library.SteamGame): (() -> Unit)? {
}
}
internal fun hideKey(g: Library.SteamGame): String = g.storeId?.let { "${g.source}:$it" } ?: GameRef.key(g)
@Composable
internal fun HideButton(key: String, g: Library.SteamGame?) {
val ctx = LocalContext.current
rememberHiddenSync()
val hidden = LibraryHidden.isHidden(key, g)
val failed = stringResource(R.string.game_hide_failed)
SecondaryButton(stringResource(if (hidden) R.string.game_unhide else R.string.common_hide), compact = true) { if (!LibraryHidden.set(ctx, key, g, !hidden)) Toast.makeText(ctx, failed, Toast.LENGTH_LONG).show() }
}
@Composable
internal fun EditArtButton(g: Library.SteamGame) {
val open = rememberEditArt(g) ?: return
@@ -628,6 +671,10 @@ internal fun EditArtButton(g: Library.SteamGame) {
private fun GameMoreMenu(g: Library.SteamGame, a: FrontEndActions) {
var open by remember(g.gameId) { mutableStateOf(false) }
val edit = rememberEditArt(g)
val ctx = LocalContext.current
rememberHiddenSync()
val hidden = LibraryHidden.isHidden(hideKey(g), g)
val failed = stringResource(R.string.game_hide_failed)
Box {
SecondaryButton(stringResource(R.string.game_more)) { open = !open }
AnchoredMenu(open, onDismiss = { open = false }, title = stringResource(R.string.game_more), compact = true) { first ->
@@ -638,6 +685,8 @@ private fun GameMoreMenu(g: Library.SteamGame, a: FrontEndActions) {
MenuItem(stringResource(R.string.game_shortcut_add), checked = false, focusRequester = take()) { open = false; a.onGameShortcut(g) }
MenuItem(stringResource(R.string.game_file_export), checked = false) { open = false; a.onExportGameFile(g) }
MenuItem(stringResource(R.string.game_link_copy), checked = false) { open = false; a.onCopyGameLink(g) }
val hideKey = hideKey(g)
MenuItem(stringResource(if (hidden) R.string.game_unhide else R.string.common_hide), checked = false) { open = false; if (!LibraryHidden.set(ctx, hideKey, g, !hidden)) Toast.makeText(ctx, failed, Toast.LENGTH_LONG).show() }
edit?.let { run -> MenuItem(stringResource(R.string.game_edit_art), checked = false) { open = false; run() } }
}
}
@@ -869,8 +918,10 @@ private fun ShortcutFields(game: Library.SteamGame, folder: File) {
@Composable
private fun SavesTab(g: Library.SteamGame, prefix: File, a: FrontEndActions) {
val saves by produceState<List<GameSaves.SaveDir>?>(null, g.gameId) {
value = withContext(Dispatchers.IO) { runCatching { GameSaves.locate(prefix, g) }.getOrDefault(emptyList()) }
val context = LocalContext.current.applicationContext
var synced by remember(g.gameId) { mutableStateOf(0) }
val saves by produceState<List<GameSaves.SaveDir>?>(null, g.gameId, synced) {
value = withContext(Dispatchers.IO) { runCatching { GameSaves.saves(context, prefix, g) }.getOrDefault(emptyList()) }
}
val found = saves
val summary = when {
@@ -888,9 +939,9 @@ private fun SavesTab(g: Library.SteamGame, prefix: File, a: FrontEndActions) {
}
Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(summary, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(bottom = 6.dp).readable().padding(4.dp))
if (Store.byId(g.source).let { it == Store.GOG || it == Store.EPIC }) {
if (CloudSaves.supports(Store.byId(g.source))) {
SectionLabel(stringResource(R.string.store_cloud_saves))
CloudRows(g)
CloudRows(g) { synced++ }
SectionLabel(stringResource(R.string.games_saves))
}
MenuItem(stringResource(R.string.games_import_saves), checked = false) { a.onSaveImport(g) }
@@ -946,14 +997,16 @@ private fun AddonRow(name: String, target: WowAddons.Target, a: FrontEndActions)
}
@Composable
private fun CloudRows(g: Library.SteamGame) {
val store = Store.byId(g.source)?.takeIf { it != Store.AMAZON && it != Store.EA } ?: return
private fun CloudRows(g: Library.SteamGame, onSynced: () -> Unit = {}) {
val store = Store.byId(g.source)?.takeIf { it != Store.AMAZON } ?: return
val id = g.storeId ?: return
val context = LocalContext.current.applicationContext
var busy by remember(g.gameId) { mutableStateOf<String?>(null) }
var tick by remember(g.gameId) { mutableStateOf(0) }
var refreshing by remember(g.gameId) { mutableStateOf(false) }
val status by produceState<CloudSaves.Status?>(null, g.gameId, tick) {
value = withContext(Dispatchers.IO) { runCatching { CloudSaves.status(context, store, id) }.getOrNull() }
refreshing = false
}
val folder = g.gameFiles
var enabled by remember(g.gameId) { mutableStateOf(folder?.let { StoreGameSidecar.read(it)?.cloud } ?: true) }
@@ -965,7 +1018,7 @@ private fun CloudRows(g: Library.SteamGame) {
busy = if (up) "up" else "down"
Thread({
val r = if (up) CloudSaves.upload(context, store, id, force) else CloudSaves.download(context, store, id, force)
StoresState.post { busy = null; tick++; android.widget.Toast.makeText(context, cloudMessage(context, r), android.widget.Toast.LENGTH_SHORT).show() }
StoresState.post { refreshing = true; busy = null; tick++; onSynced(); android.widget.Toast.makeText(context, cloudMessage(context, r), android.widget.Toast.LENGTH_SHORT).show() }
}, "cloud-manual").start()
}
MenuItem(stringResource(R.string.store_cloud_saves), checked = enabled && supported, enabled = supported,
@@ -977,11 +1030,13 @@ private fun CloudRows(g: Library.SteamGame) {
StoresState.post { enabled = written?.cloud ?: enabled }
}, "cloud-switch").start()
}
val ready = st != null && supported && enabled && busy == null
val ready = st != null && supported && enabled && busy == null && !refreshing && st.folder != null && st.signedIn
val pending = stringResource(R.string.cloud_pending)
val summary = when {
st == null || busy != null -> pending
!supported -> stringResource(R.string.cloud_none)
!st.signedIn || st.reason == "not-signed-in" -> stringResource(R.string.cloud_signed_out)
st.folder == null -> stringResource(R.string.cloud_not_synced)
conflict -> stringResource(R.string.cloud_conflict_files, st.conflicts.size)
st.lastSync > 0 -> stringResource(R.string.cloud_last_sync, android.text.format.DateUtils.getRelativeTimeSpanString(st.lastSync).toString())
else -> stringResource(R.string.cloud_never)
@@ -1093,3 +1148,47 @@ internal object FolderSizes {
}, "folder-size").start()
}
}
@Composable
private fun SteadyDownloadChip(download: com.droiddeck.launcher.stores.download.DownloadEntry) {
val progress = steadyProgress(download)
val label = steadyLabel(download, progress)
val show = LocalShowSection.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val shape = if (LocalPillButtons.current) androidx.compose.foundation.shape.CircleShape else Shape12
val src = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }
val hot = rememberHot(src)
val pressed by src.collectIsPressedAsState()
val scale by androidx.compose.animation.core.animateFloatAsState(if (pressed) 0.955f else if (hot) 1.02f else 1f, Motion.sp(0.5f, androidx.compose.animation.core.Spring.StiffnessMedium), label = "dlScale")
val placed = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
val description = stringResource(R.string.stores_tab_downloads)
val open = {
placed[0]?.takeIf { it.isAttached }?.boundsInRoot()?.let { StoresMotion.fly(it) }
show("downloads")
}
Box(
contentAlignment = Alignment.CenterStart,
modifier = Modifier.paneItem("detail-download").testTag("detail-download")
.onGloballyPositioned { placed[0] = it }
.widthIn(min = 200.dp).heightIn(min = 48.dp)
.graphicsLayer { scaleX = scale; scaleY = scale }.clip(shape)
.background(Color.White.copy(alpha = 0.04f))
.glideBorder(hot, shape, pal.signal, pal.line2)
.hoverable(src)
.clickable(interactionSource = src, indication = androidx.compose.foundation.LocalIndication.current, role = androidx.compose.ui.semantics.Role.Button, onClickLabel = description, onClick = open)
.controllerConfirm(onClick = open),
) {
ChipFill(progress, download.key, pal.signal.copy(alpha = 0.42f))
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier.widthIn(min = 200.dp).padding(start = 16.dp, end = 10.dp),
) {
Text(
label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, color = colors.onBackground, maxLines = 1,
style = androidx.compose.ui.text.TextStyle(fontFeatureSettings = "tnum"), modifier = Modifier.padding(end = 8.dp),
)
Icon(androidx.compose.material.icons.Icons.AutoMirrored.Filled.KeyboardArrowRight, description, tint = if (hot) colors.onBackground else colors.onSurfaceVariant, modifier = Modifier.size(20.dp))
}
}
}
@@ -171,6 +171,10 @@ internal fun GameBackdrop(
},
) {
DisposableEffect(art == null) { onDispose { if (art == null) onArtPlaced(null) } }
if (art == null) androidx.compose.runtime.SideEffect {
StoresMotion.heroFadeTop = fadeTop
StoresMotion.heroDrift = { 0f }
}
Box(
Modifier.matchParentSize()
.graphicsLayer { compositingStrategy = CompositingStrategy.Offscreen }
@@ -217,6 +221,10 @@ private fun ArtLayer(model: Any?, sample: Any?, fadeTop: Boolean, blur: androidx
),
label = "heroDriftT",
)
androidx.compose.runtime.SideEffect {
StoresMotion.heroFadeTop = fadeTop
StoresMotion.heroDrift = { drift?.value ?: 0f }
}
AsyncImage(
model = model, contentDescription = null, contentScale = ContentScale.Crop,
alignment = BiasAlignment(0.45f, -0.35f),
@@ -224,12 +232,12 @@ private fun ArtLayer(model: Any?, sample: Any?, fadeTop: Boolean, blur: androidx
modifier = Modifier.matchParentSize()
.graphicsLayer {
val t = drift?.value ?: 0f
val zoom = 1f + 0.16f * t
val zoom = HeroDrift.zoom(t)
scaleX = zoom
scaleY = zoom
translationX = -size.width * 0.05f * t
translationY = size.height * 0.03f * t
transformOrigin = androidx.compose.ui.graphics.TransformOrigin(0.72f, 0.33f)
translationX = size.width * HeroDrift.DX * t
translationY = size.height * HeroDrift.DY * t
transformOrigin = androidx.compose.ui.graphics.TransformOrigin(HeroDrift.PX, HeroDrift.PY)
}
.then(if (blur > 0.dp) Modifier.blur(blur) else Modifier),
)
@@ -294,3 +302,11 @@ internal class HeroLook(brightness: Float, val light: Boolean, val background: C
)
}
}
internal object HeroDrift {
const val PX = 0.72f
const val PY = 0.33f
const val DX = -0.04f
const val DY = 0.03f
fun zoom(t: Float) = 1f + 0.16f * t
}
@@ -0,0 +1,17 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.addPathNodes
import androidx.compose.ui.unit.dp
internal val GameShelfIcon: ImageVector = ImageVector.Builder("GameShelf", 24.dp, 24.dp, 24f, 24f).apply {
for (d in listOf(
"M3,4H7V20H3ZM4.4,5.4V18.6H5.6V5.4Z",
"M8.5,4H12.5V20H8.5ZM9.9,5.4V18.6H11.1V5.4Z",
"M14.2,5.1L18.1,4.2L21.4,19.8L17.5,20.7ZM15.9,6.2L18.6,18.9L19.8,18.6L17.1,5.9Z",
"M2,21H22V22.5H2Z",
)) addPath(addPathNodes(d), fill = SolidColor(Color.Black), pathFillType = PathFillType.EvenOdd)
}.build()
@@ -68,7 +68,7 @@ internal fun GogMaintenanceActions(game: InstalledStoreGame) {
}
}
if (active) {
ActionChip(downloadLabel(download!!), ok = false)
ActionChip(downloadLabel(download!!), ok = false, fraction = download!!.stageFraction.takeIf { it >= 0f }, key = download!!.stage)
if (download.interruptible) {
SecondaryButton(stringResource(if (download.state == DownloadState.PAUSED) R.string.stores_dl_resume else R.string.stores_dl_pause)) {
if (download.state == DownloadState.PAUSED) DownloadQueue.resume(ctx, key) else DownloadQueue.pause(key)
@@ -1,6 +1,7 @@
package com.droiddeck.launcher.ui
import android.app.Presentation
import android.graphics.Rect
import android.hardware.display.DisplayManager
import android.os.Bundle
import android.os.Handler
@@ -37,6 +38,7 @@ import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import kotlin.math.abs
import kotlin.math.roundToInt
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.LocalContext
@@ -69,7 +71,8 @@ private class GamepadScaler(private val context: android.content.Context, privat
}
private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputBindings, val defaults: List<InputSurfaceElement>? = null,
private val gamepad: GamepadScaler? = null, snap: Boolean = true) {
private val defaultsFrame: Float = 0f, private var gamepad: GamepadScaler? = null, snap: Boolean = true) {
val hasGamepad get() = gamepad != null
var elements by mutableStateOf(layout.elements)
var actions by mutableStateOf(preset.elements)
var clicks by mutableStateOf(preset.clicks)
@@ -86,30 +89,37 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB
var aspect by mutableFloatStateOf(layout.aspect)
private var scaleBase by mutableStateOf<Triple<List<InputSurfaceElement>, List<InputSurfaceElement>, Float>?>(null)
private var scaleValue by mutableIntStateOf(100)
private val rescales get() = gamepad != null && elements.any { it.id in gamepad.ids }
private val rescales get() = gamepad?.let { pad -> elements.any { it.id in pad.ids } } == true
val scale get() = when {
scaleBase?.second == elements -> scaleValue
rescales -> (layoutScale * 100).roundToInt()
else -> 100
}
val positioned get() = (if (rescales) gamepad!!.reset(elements) else defaults?.let { elements.withPositionsOf(it) })
val positioned get() = (if (rescales) gamepad!!.reset(elements) else defaults?.let { elements.withPositionsOf(refit(it, defaultsFrame)) })
?.takeIf { it != elements || rescales && layoutScale != 1f }
private fun refit(placed: List<InputSurfaceElement>, from: Float): List<InputSurfaceElement> {
if (from <= 0f || aspect <= 0f || abs(from / aspect - 1f) < .01f) return placed
return OnScreenLayout.fit(placed, from, 1f, (aspect * 1000).roundToInt().coerceAtLeast(1), 1000, Rect())
}
val element get() = elements.firstOrNull { it.id == selected }
val dirty get() = elements != layout.elements || actions != preset.elements || clicks != preset.clicks || layoutScale != layout.scale || aspect != layout.aspect
fun checkpoint() { history = (history + SurfaceSnapshot(elements, actions, clicks, layoutScale, aspect)).takeLast(40) }
fun undo() { history.lastOrNull()?.let { elements = it.elements; actions = it.actions; clicks = it.clicks; layoutScale = it.scale; aspect = it.aspect; history = history.dropLast(1) } }
fun beginEdit(displayed: List<InputSurfaceElement>, aspect: Float) {
fun beginEdit(displayed: List<InputSurfaceElement>, aspect: Float, scaler: GamepadScaler? = gamepad) {
checkpoint()
elements = OnScreenLayout.editorFrame(layout.copy(elements = elements), displayed)
this.aspect = aspect
scaler?.let { gamepad = it }
}
fun scaleAll(percent: Int) {
val base = scaleBase?.takeIf { it.second == elements } ?: Triple(elements, elements, if (rescales) layoutScale else 0f).also { checkpoint() }
val factor = percent / 100f
elements = if (base.third > 0f && gamepad != null) {
val pad = gamepad
elements = if (base.third > 0f && pad != null) {
layoutScale = factor
val others = base.first.filterNot { it.id in gamepad.ids }.scaled(factor / base.third).associateBy { it.id }
gamepad.rescale(base.first, base.third, factor).map { others[it.id] ?: it }
val others = base.first.filterNot { it.id in pad.ids }.scaled(factor / base.third).associateBy { it.id }
pad.rescale(base.first, base.third, factor).map { others[it.id] ?: it }
} else base.first.scaled(factor)
scaleValue = percent; scaleBase = Triple(base.first, elements, base.third)
}
@@ -134,7 +144,8 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
val (w, h) = OnScreenLayout.generatedSize(context, savedLayout, metrics.widthPixels, metrics.heightPixels) ?: (metrics.widthPixels to metrics.heightPixels)
GamepadScaler(display, w, h)
}
SurfaceDraft(savedLayout, savedBindings, InputLibraries.defaultPositions(context, library, savedLayout), gamepad, ControllerPrefs.snap(context))
val defaults = InputLibraries.defaultPositions(context, library, savedLayout)
SurfaceDraft(savedLayout, savedBindings, defaults?.first, defaults?.second ?: 0f, gamepad, ControllerPrefs.snap(context))
}
val manager = remember { context.getSystemService(DisplayManager::class.java) }
var revision by remember { mutableIntStateOf(0) }
@@ -258,7 +269,7 @@ private fun SurfaceCanvas(draft: SurfaceDraft, transparent: Boolean = false) {
view.style = draft.layout.style.copy(hidden = emptySet()); view.sourceLayout = draft.layout; view.aspect = draft.aspect; view.elements = draft.elements; view.selected = draft.selected; view.snap = draft.snap
view.isEnabled = !draft.properties && !draft.adding
view.onSelect = { if (!draft.properties) draft.selected = it }
view.onBeginEdit = draft::beginEdit
view.onBeginEdit = { e, w, h -> draft.beginEdit(e, w.toFloat() / h, if (draft.hasGamepad) GamepadScaler(view.context, w, h) else null) }
view.onChange = { e -> if (!draft.properties) draft.elements = draft.elements.map { if (it.id == e.id) e else it } }
})
@@ -32,7 +32,7 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) {
var selected: String? = null
set(value) { field = value; invalidate() }
var onSelect: (String?) -> Unit = {}
var onBeginEdit: (List<InputSurfaceElement>, Float) -> Unit = { _, _ -> }
var onBeginEdit: (List<InputSurfaceElement>, Int, Int) -> Unit = { _, _, _ -> }
var onChange: (InputSurfaceElement) -> Unit = {}
private val preview = InputSurfaceView(context)
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.rgb(26, 159, 255); strokeWidth = 2 * resources.displayMetrics.density }
@@ -101,7 +101,7 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) {
MotionEvent.ACTION_MOVE -> {
val e = original ?: return true
if (!dragging && abs(event.x - downX) + abs(event.y - downY) > ViewConfiguration.get(context).scaledTouchSlop) {
dragging = true; onBeginEdit(visibleElements, width.toFloat() / height)
dragging = true; onBeginEdit(visibleElements, width, height)
}
if (!dragging) return true
val dx = (event.x - downX) / width; val dy = (event.y - downY) / height
@@ -19,7 +19,7 @@ import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ManageAccounts
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
@@ -66,7 +66,7 @@ internal fun StoreAccountsButton() {
placed[0]?.takeIf { it.isAttached }?.boundsInRoot()?.let { at ->
Steps.ask(StepAsk(
anchor = at, side = StepSide.Left, accent = pal.signal, items = storesWithSignIn().size + 1, pillCorner = 20.dp, maxWidth = 380.dp,
handle = { Icon(Icons.Filled.Add, null, tint = pal.signal, modifier = Modifier.size(20.dp)) },
handle = { Icon(Icons.Filled.ManageAccounts, null, tint = pal.signal, modifier = Modifier.size(20.dp)) },
) {
StoreAccountsStep(onSignIn = { store, row ->
Steps.fold()
@@ -92,7 +92,7 @@ internal fun StoreAccountsButton() {
.hoverable(src)
.clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClickLabel = label, onClick = open)
.controllerConfirm(onClick = open),
) { Icon(Icons.Filled.Add, label, tint = if (hot) colors.onBackground else colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) }
) { Icon(Icons.Filled.ManageAccounts, label, tint = if (hot) colors.onBackground else colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) }
}
}
Loaded 100 of 259 files, more files were not shown because too many files have changed in this diff. Show more