mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 04:55:44 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
24af194f45 |
No files matched your search
@@ -127,7 +127,6 @@ jobs:
|
||||
name: xbox-arm64
|
||||
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-xbox
|
||||
retention-days: 14
|
||||
overwrite: true
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: xbox-corresponding-source
|
||||
@@ -136,7 +135,6 @@ jobs:
|
||||
app/build/xbox/runtime/*-source.tar.xz
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
overwrite: true
|
||||
|
||||
components-runner:
|
||||
needs: source
|
||||
@@ -332,7 +330,6 @@ jobs:
|
||||
if-no-files-found: error
|
||||
compression-level: 0
|
||||
retention-days: 14
|
||||
overwrite: true
|
||||
|
||||
build-runner:
|
||||
needs: [components]
|
||||
@@ -667,7 +664,6 @@ jobs:
|
||||
name: stores-cargo-lock
|
||||
path: app/src/main/rust/stores/Cargo.lock
|
||||
if-no-files-found: ignore
|
||||
overwrite: true
|
||||
|
||||
- name: Unit tests
|
||||
id: unit-tests
|
||||
@@ -691,7 +687,6 @@ jobs:
|
||||
app/build/reports/tests/testReleaseUnitTest/
|
||||
if-no-files-found: ignore
|
||||
retention-days: 14
|
||||
overwrite: true
|
||||
|
||||
- name: Sign with the testkey (v1 + v2 + v3)
|
||||
run: |
|
||||
@@ -729,7 +724,6 @@ jobs:
|
||||
if-no-files-found: error
|
||||
retention-days: 30
|
||||
compression-level: 0
|
||||
overwrite: true
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
@@ -738,7 +732,6 @@ jobs:
|
||||
if-no-files-found: error
|
||||
retention-days: 30
|
||||
compression-level: 0
|
||||
overwrite: true
|
||||
|
||||
- name: Report on the pull request
|
||||
if: always() && github.event_name == 'pull_request'
|
||||
@@ -937,7 +930,7 @@ jobs:
|
||||
pull-requests: read
|
||||
env:
|
||||
CI_REPO: Droid-Deck/DroidDeck-CI
|
||||
KEEP_DAYS: 14
|
||||
KEEP: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
|
||||
@@ -1,141 +0,0 @@
|
||||
name: PR Rebuild On Version Bump
|
||||
run-name: rebuild test builds below versionCode on main
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths: [app/build.gradle]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
actions: write
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: read
|
||||
|
||||
concurrency:
|
||||
group: pr-rebuild-on-version
|
||||
cancel-in-progress: false
|
||||
queue: max
|
||||
|
||||
jobs:
|
||||
rebuild:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 180
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: main
|
||||
fetch-depth: 2
|
||||
persist-credentials: false
|
||||
- name: Rebuild open PRs whose test build Android would refuse over main
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
BEFORE: ${{ github.event.before }}
|
||||
PUSHED_AT: ${{ github.event.repository.pushed_at }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
code() { sed -n 's/^[[:space:]]*versionCode[[:space:]][[:space:]]*\([0-9][0-9]*\)[[:space:]]*$/\1/p'; }
|
||||
now=$(code < app/build.gradle)
|
||||
[[ "$now" =~ ^[0-9]+$ ]] || { echo "::error::No numeric versionCode on main"; exit 1; }
|
||||
if [ "$EVENT_NAME" = push ]; then
|
||||
was=$(git show "$BEFORE:app/build.gradle" 2>/dev/null | code || true)
|
||||
if [[ "$was" =~ ^[0-9]+$ ]] && [ "$was" -ge "$now" ]; then
|
||||
echo "versionCode stayed at $now"
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
# This run is created right after the push, so a PR build that started earlier may have pinned the old main.
|
||||
bumped=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" --jq .created_at)
|
||||
# A build can finish between the push and this run's creation; the push event carries the push time.
|
||||
if [[ "${PUSHED_AT:-}" =~ ^[0-9]+$ ]]; then
|
||||
pushed=$(date -u -d "@$PUSHED_AT" +%Y-%m-%dT%H:%M:%SZ)
|
||||
[[ "$pushed" < "$bumped" ]] && bumped=$pushed
|
||||
else
|
||||
pushed=$(date -u -d "$bumped - 10 minutes" +%Y-%m-%dT%H:%M:%SZ)
|
||||
fi
|
||||
note() {
|
||||
local number=$1
|
||||
local marker="<!-- droiddeck-rebuild-$now -->"
|
||||
gh api "repos/$GITHUB_REPOSITORY/issues/$number/comments?per_page=100" --jq '.[].body' | grep -qF "$marker" && return 0
|
||||
gh api -X POST "repos/$GITHUB_REPOSITORY/issues/$number/comments" -f body="$marker
|
||||
Main is now at versionCode $now, so this PR's test build no longer installs over current DroidDeck, and its last build is too old for GitHub to re-run. Push a commit or merge main to get a new test build." >/dev/null
|
||||
}
|
||||
latest() {
|
||||
gh api "repos/$GITHUB_REPOSITORY/actions/workflows/build.yml/runs?event=pull_request&head_sha=$1&per_page=20" \
|
||||
--jq '[.workflow_runs[] | select(.head_sha == "'"$1"'")] | sort_by(.created_at) | last // empty | [.id, .status, (.run_started_at // .created_at), .created_at, .updated_at] | @tsv'
|
||||
}
|
||||
consider() {
|
||||
local number=$1 head=$2 built=$3 id status started created updated
|
||||
IFS=$'\t' read -r id status started created updated <<<"$4"
|
||||
if [[ "$started" > "$bumped" ]]; then
|
||||
echo "PR #$number: build $id started after the bump"
|
||||
elif ! gh api "repos/$GITHUB_REPOSITORY/pulls/$number" |
|
||||
jq -e --arg head "$head" '.state == "open" and .draft == false and .base.ref == "main" and .head.sha == $head' >/dev/null; then
|
||||
echo "PR #$number: moved on since the scan, its own build covers it"
|
||||
elif gh run rerun "$id" -R "$GITHUB_REPOSITORY"; then
|
||||
echo "PR #$number: rebuilding ${head:0:7} on main (versionCode $built -> $now)"
|
||||
else
|
||||
echo "::warning::PR #$number: could not rerun build $id"
|
||||
# GitHub only re-runs a workflow within 30 days of its first run.
|
||||
if [[ "$created" < "$(date -u -d '-30 days' +%Y-%m-%dT%H:%M:%SZ)" ]]; then
|
||||
note "$number" || echo "::warning::PR #$number: could not leave a note"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
pending=()
|
||||
declare -A seen=()
|
||||
candidates() {
|
||||
gh api --paginate "repos/Droid-Deck/DroidDeck-CI/releases?per_page=100" \
|
||||
--jq '.[] | select(.tag_name | test("^pr-[0-9]+$")) | [(.tag_name | ltrimstr("pr-")), ((.body // "") | capture("(?m)^VersionCode: (?<v>[0-9]+)").v // "0")] | @tsv'
|
||||
# The latest build of every open PR: one that started before the bump and was still running at it
|
||||
# may have pinned the old main. This also covers a PR's first build and fork builds.
|
||||
gh api --paginate -X GET "repos/$GITHUB_REPOSITORY/pulls" -f state=open -f base=main -f per_page=100 \
|
||||
--jq '.[] | select(.draft | not) | [(.number | tostring), .head.sha] | @tsv' |
|
||||
while IFS=$'\t' read -r number sha; do
|
||||
run=$(latest "$sha")
|
||||
[ -n "$run" ] || continue
|
||||
IFS=$'\t' read -r _ status started _ updated <<<"$run"
|
||||
if [[ "$started" < "$bumped" ]] && { [ "$status" != completed ] || [[ ! "$updated" < "$pushed" ]]; }; then
|
||||
printf '%s\t?\n' "$number"
|
||||
fi
|
||||
done
|
||||
}
|
||||
found=$(mktemp)
|
||||
candidates > "$found"
|
||||
while IFS=$'\t' read -r number built; do
|
||||
[ "$built" = "?" ] || [ "$built" -lt "$now" ] || continue
|
||||
[ -z "${seen[$number]:-}" ] || continue
|
||||
seen[$number]=1
|
||||
pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$number") || continue
|
||||
jq -e '.state == "open" and .draft == false and .base.ref == "main"' <<<"$pr" >/dev/null || continue
|
||||
head=$(jq -r .head.sha <<<"$pr")
|
||||
run=$(latest "$head")
|
||||
if [ -z "$run" ]; then
|
||||
echo "PR #$number: no build of ${head:0:7} to rerun"
|
||||
elif [ "$(cut -f2 <<<"$run")" = completed ]; then
|
||||
consider "$number" "$head" "$built" "$run"
|
||||
else
|
||||
pending+=("$number $head $built")
|
||||
fi
|
||||
done < "$found"
|
||||
# Builds still running are polled together so one slow build cannot hold up the rest.
|
||||
deadline=$((SECONDS + 150 * 60))
|
||||
while [ ${#pending[@]} -gt 0 ] && [ "$SECONDS" -lt "$deadline" ]; do
|
||||
sleep 60
|
||||
left=()
|
||||
for item in "${pending[@]}"; do
|
||||
read -r number head built <<<"$item"
|
||||
run=$(latest "$head")
|
||||
if [ -n "$run" ] && [ "$(cut -f2 <<<"$run")" = completed ]; then
|
||||
consider "$number" "$head" "$built" "$run"
|
||||
else
|
||||
left+=("$item")
|
||||
fi
|
||||
done
|
||||
pending=(${left[@]+"${left[@]}"})
|
||||
done
|
||||
for item in ${pending[@]+"${pending[@]}"}; do
|
||||
echo "::warning::PR #${item%% *}: its build did not finish in time"
|
||||
done
|
||||
@@ -55,9 +55,3 @@ jobs:
|
||||
fi
|
||||
done
|
||||
exit "$failed"
|
||||
|
||||
catalog:
|
||||
needs: sweep
|
||||
if: ${{ always() }}
|
||||
uses: ./.github/workflows/update-catalog.yml
|
||||
secrets: inherit
|
||||
@@ -25,7 +25,7 @@ DroidDeck brings the SteamOS experience to Android: Steam Gaming Mode, full Linu
|
||||
|
||||
<p align="center"><img src="docs/media/steam-to-desktop.gif" width="100%" alt="On a Retroid Pocket Duo: Play Steam from the DroidDeck launcher, open Pac-Man in Steam Big Picture and play it, exit the game, then Switch to Desktop from the Power menu"></p>
|
||||
|
||||
> The official website is [droid-deck.dev](https://droid-deck.dev). Only download DroidDeck from this repository's [Releases](https://github.com/Droid-Deck/DroidDeck/releases).
|
||||
> DroidDeck has no website. Only download it from this repository's [Releases](https://github.com/Droid-Deck/DroidDeck/releases).
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/releases/media/0.6.7/library.gif" width="49%" alt="The Library switching source chips, changing the card size and opening the Filter menu">
|
||||
@@ -92,7 +92,6 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
|
||||
|
||||
- Epic Games and GOG build on [Phobos](https://github.com/phobos665)'s adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl). GOG install script registry entries are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher) (GPL-3.0) reads them.
|
||||
- Epic's official Linux launcher preview runs through FEX. That setup is outside Epic's listed Linux support.
|
||||
- The launcher's .deb gets the WebKitGTK and GTK 3 libraries it needs from unmodified [Debian](https://www.debian.org) 13 packages, following [@zooluis](https://github.com/zooluis)'s research in [#2268](https://github.com/Droid-Deck/DroidDeck/pull/2268).
|
||||
- Battle.net is by [@kayakyakr](https://github.com/kayakyakr). It runs Blizzard's own client in Proton (downloaded from Blizzard, not included) and shows key art from the [Battle.net Shop](https://shop.battle.net). Without Steam, its games see the pad as an Xbox 360 controller via `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`.
|
||||
- The EA store follows the EA app's protocols as documented by [ArmchairDevelopers](https://github.com/ArmchairDevelopers)' [Maxima](https://github.com/ArmchairDevelopers/Maxima) (GPL-3.0): sign-in, the GraphQL queries (included verbatim, since EA matches them by hash), build archives, online activation licences and the LSX game endpoint. The code is DroidDeck's own.
|
||||
- Battle.net installs drive Blizzard's Agent the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) does, with requests from [wowdev.wiki](https://wowdev.wiki/Agent). Read without taking code: [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader.
|
||||
|
||||
@@ -141,7 +141,6 @@ android {
|
||||
buildConfigField "boolean", "CI_BUILD", "${ciBuild}"
|
||||
buildConfigField "String", "RELEASE_SIGNER", "\"${releaseSigner}\""
|
||||
buildConfigField "long", "COMMIT_TIME", "${commitTime}L * 1000L"
|
||||
buildConfigField "String", "UPDATE_CATALOG_BRANCH", "\"${(System.getenv("DROIDDECK_UPDATE_CATALOG_BRANCH") ?: "main").with { it ==~ /[A-Za-z0-9._-]+/ ? it : "main" }}\""
|
||||
buildConfigField "String", "VARIANT_SUFFIXES", "\"${variantSuffixes}\""
|
||||
buildConfigField "String", "SGDB_API_KEY", "\"${System.getenv("SGDB_API_KEY") ?: project.findProperty("sgdbApiKey") ?: ""}\""
|
||||
buildConfigField "String", "DESKTOP_KDE_TAG", "\"${desktopKde.DESKTOP_KDE_TAG}\""
|
||||
@@ -401,8 +400,6 @@ dependencies {
|
||||
exclude group: 'com.google.auto.value', module: 'auto-value'
|
||||
}
|
||||
implementation 'com.google.zxing:core:3.5.3'
|
||||
implementation 'androidx.media3:media3-exoplayer:1.3.1'
|
||||
implementation 'androidx.media3:media3-session:1.3.1'
|
||||
|
||||
testImplementation 'junit:junit:4.13.2'
|
||||
testImplementation 'org.robolectric:robolectric:4.16.1'
|
||||
|
||||
@@ -118,17 +118,6 @@
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".DeviceCodeActivity"
|
||||
android:exported="false"
|
||||
android:launchMode="singleTask"
|
||||
android:taskAffinity="${applicationId}.devicecode"
|
||||
android:excludeFromRecents="true"
|
||||
android:supportsPictureInPicture="true"
|
||||
android:resizeableActivity="true"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density|keyboard|keyboardHidden|navigation"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
<activity
|
||||
android:name=".PairingGuideActivity"
|
||||
android:exported="false"
|
||||
@@ -152,7 +141,6 @@
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
<category android:name="android.intent.category.CAR_LAUNCHER" />
|
||||
<data android:scheme="droiddeck" android:host="game" />
|
||||
<data android:scheme="droiddeck" android:host="soundtrack" />
|
||||
</intent-filter>
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.CREATE_SHORTCUT" />
|
||||
@@ -323,10 +311,6 @@
|
||||
android:theme="@style/SessionTheme" />
|
||||
|
||||
<service android:name=".agent.AgentHostService" android:exported="false" />
|
||||
<service
|
||||
android:name=".update.UpdateWatch"
|
||||
android:permission="android.permission.BIND_JOB_SERVICE"
|
||||
android:exported="false" />
|
||||
<service
|
||||
android:name=".session.SessionService"
|
||||
android:exported="false"
|
||||
@@ -350,14 +334,6 @@
|
||||
android:name=".sync.SyncthingService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="dataSync" />
|
||||
<service
|
||||
android:name=".playback.SoundtrackService"
|
||||
android:exported="true"
|
||||
android:foregroundServiceType="mediaPlayback">
|
||||
<intent-filter>
|
||||
<action android:name="androidx.media3.session.MediaSessionService" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="${applicationId}.logs"
|
||||
|
||||
@@ -1,52 +1,27 @@
|
||||
#!/bin/bash
|
||||
# Starts GitHub's device login, floats its code over Android's browser and opens the approval page.
|
||||
url=https://github.com/login/device
|
||||
inbox=${DD_AGENT_INBOX:-}
|
||||
|
||||
# DroidDeck takes $inbox/device-code within a few seconds when it can float the code.
|
||||
float_code() {
|
||||
[ -n "$inbox" ] && [ -d "$inbox" ] || return 1
|
||||
rm -f "$inbox/device-code.result"
|
||||
printf '%s %s\n' "$1" "$url" > "$inbox/device-code.part" && mv -f "$inbox/device-code.part" "$inbox/device-code" || return 1
|
||||
i=0
|
||||
while [ $i -lt 40 ] && [ -e "$inbox/device-code" ]; do
|
||||
sleep 0.2
|
||||
i=$((i + 1))
|
||||
done
|
||||
if [ -e "$inbox/device-code" ]; then
|
||||
rm -f "$inbox/device-code"
|
||||
return 1
|
||||
fi
|
||||
# DroidDeck writes "ok" or "failed" once it has tried to open the page; no answer counts as failed.
|
||||
i=0
|
||||
while [ $i -lt 50 ] && [ ! -e "$inbox/device-code.result" ]; do
|
||||
sleep 0.2
|
||||
i=$((i + 1))
|
||||
done
|
||||
result=$(cat "$inbox/device-code.result" 2>/dev/null)
|
||||
rm -f "$inbox/device-code.result"
|
||||
[ "$result" = ok ]
|
||||
}
|
||||
|
||||
# GitHub sign-in through Android's browser, with the one-time code typed in for the person.
|
||||
serial=${ADB_SERIAL:-127.0.0.1:5555}
|
||||
display=${DD_BROWSER_DISPLAY:-0}
|
||||
adb connect "$serial" >/dev/null 2>&1
|
||||
coproc GH { BROWSER=true gh auth login --hostname github.com --git-protocol https --web 2>&1; }
|
||||
gh_pid=$GH_PID
|
||||
# bash drops GH and GH_PID once gh exits, which can be before the loop reads its last line.
|
||||
ghpid=$GH_PID
|
||||
exec {ghout}<&"${GH[0]}" {ghin}>&"${GH[1]}"
|
||||
shown=
|
||||
typed=
|
||||
while IFS= read -r line <&"$ghout"; do
|
||||
printf '%s\n' "$line"
|
||||
code=$(grep -oE '[A-Z0-9]{4}-[A-Z0-9]{4}' <<<"$line" | head -1)
|
||||
# gh's own prompts would push the code out of the one line the setup card shows.
|
||||
case "$line" in
|
||||
*"one-time code"* | *"Press Enter"* | *"Open this URL"*) ;;
|
||||
*) printf '%s\n' "$line" ;;
|
||||
esac
|
||||
if [ -n "$code" ] && [ -z "$shown" ]; then
|
||||
shown=1
|
||||
if [ -n "$code" ] && [ -z "$typed" ]; then
|
||||
typed=1
|
||||
echo >&"$ghin"
|
||||
printf 'GitHub device code: %s · github.com/login/device\n' "$code"
|
||||
float_code "$code" || android-open "$url"
|
||||
adb -s "$serial" shell "am start --display $display -a android.intent.action.VIEW -d https://github.com/login/device" >/dev/null 2>&1
|
||||
# Chrome drops characters from `input text` and from fast key events on this page.
|
||||
keys=
|
||||
for ((i = 0; i < ${#code}; i++)); do
|
||||
c=${code:i:1}
|
||||
[ "$c" = - ] || keys+="input -d $display keyevent KEYCODE_$c; sleep 0.4; "
|
||||
done
|
||||
(sleep 7; adb -s "$serial" shell "$keys" >/dev/null 2>&1) &
|
||||
fi
|
||||
done
|
||||
wait "$gh_pid"
|
||||
status=$?
|
||||
[ -n "$shown" ] && [ -n "$inbox" ] && [ -d "$inbox" ] && : > "$inbox/device-code"
|
||||
exit $status
|
||||
wait "$ghpid"
|
||||
Binary file not shown.
@@ -44,7 +44,6 @@ class App : Application() {
|
||||
CrashHandler.install(this)
|
||||
com.droiddeck.launcher.agent.AgentHost.refresh(this)
|
||||
com.droiddeck.launcher.agent.AgentTab.load(this)
|
||||
com.droiddeck.launcher.ui.NavTabs.load(this)
|
||||
com.droiddeck.launcher.ui.AgentPet.install(this)
|
||||
if (com.droiddeck.launcher.agent.AgentTab.visible) com.droiddeck.launcher.lab.LabNotice.openOnInstall = "agent"
|
||||
com.droiddeck.launcher.lab.LabNotice.started(this)
|
||||
@@ -53,7 +52,6 @@ class App : Application() {
|
||||
com.droiddeck.launcher.session.SessionPrefs.applyNtsyncDefault(this)
|
||||
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
|
||||
com.droiddeck.launcher.update.AppUpdates.init(this)
|
||||
com.droiddeck.launcher.update.UpdateWatch.sync(this, com.droiddeck.launcher.update.AppUpdates.follow(this, null))
|
||||
com.droiddeck.launcher.core.DownloadSource.init(this)
|
||||
prefetchAddonPacks()
|
||||
GpuClockPin.clearLeftover(this)
|
||||
|
||||
@@ -1,167 +0,0 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.app.ActivityOptions
|
||||
import android.app.PictureInPictureParams
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.res.Configuration
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import android.util.Rational
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.core.AppLanguage
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
import com.droiddeck.launcher.ui.FitText
|
||||
import com.droiddeck.launcher.ui.LocalPalette
|
||||
import com.droiddeck.launcher.ui.PrimaryButton
|
||||
import com.droiddeck.launcher.ui.SecondaryButton
|
||||
import java.lang.ref.WeakReference
|
||||
|
||||
/** Floats a sign-in code over the browser page that asks for it. */
|
||||
class DeviceCodeActivity : ComponentActivity() {
|
||||
private var code by mutableStateOf("")
|
||||
private var url = ""
|
||||
private var display: Int? = null
|
||||
private var inPip by mutableStateOf(false)
|
||||
private var openPending = false
|
||||
|
||||
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
current = WeakReference(this)
|
||||
read(intent)
|
||||
openPending = savedInstanceState == null
|
||||
setContent { DroidDeckTheme { Float() } }
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
setIntent(intent)
|
||||
read(intent)
|
||||
openPending = true
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
if (current?.get() === this) current = null
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
if (!openPending) return
|
||||
if (isInPictureInPictureMode) {
|
||||
openPage()
|
||||
return
|
||||
}
|
||||
enterPip()
|
||||
if (!inPip) {
|
||||
openPage()
|
||||
finish()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) {
|
||||
super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig)
|
||||
inPip = isInPictureInPictureMode
|
||||
if (isInPictureInPictureMode && openPending) openPage()
|
||||
}
|
||||
|
||||
private fun read(intent: Intent) {
|
||||
code = intent.getStringExtra(EXTRA_CODE).orEmpty()
|
||||
url = intent.getStringExtra(EXTRA_URL).orEmpty()
|
||||
display = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it > 0 }
|
||||
copy()
|
||||
}
|
||||
|
||||
private fun copy() {
|
||||
runCatching { getSystemService(ClipboardManager::class.java)?.setPrimaryClip(ClipData.newPlainText("GitHub", code)) }
|
||||
}
|
||||
|
||||
private fun enterPip() {
|
||||
inPip = runCatching {
|
||||
enterPictureInPictureMode(PictureInPictureParams.Builder().setAspectRatio(Rational(16, 9)).build())
|
||||
}.getOrDefault(false)
|
||||
}
|
||||
|
||||
private fun openPage() {
|
||||
openPending = false
|
||||
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
val at = display
|
||||
val opened = runCatching {
|
||||
if (at == null) startActivity(intent)
|
||||
else startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(at).toBundle())
|
||||
}.recoverCatching { startActivity(intent) }.isSuccess
|
||||
com.droiddeck.launcher.agent.AgentHost.deviceCodeOpened(applicationContext, opened)
|
||||
}
|
||||
|
||||
@androidx.compose.runtime.Composable
|
||||
private fun Float() {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val accent = LocalPalette.current.signal
|
||||
BackHandler(enabled = !inPip) { enterPip() }
|
||||
Box(Modifier.fillMaxSize().background(colors.background), contentAlignment = Alignment.Center) {
|
||||
Column(
|
||||
Modifier.widthIn(max = 520.dp).fillMaxWidth().padding(if (inPip) 8.dp else 24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(if (inPip) 2.dp else 16.dp),
|
||||
) {
|
||||
Text(stringResource(R.string.agent_step_github), style = MaterialTheme.typography.labelLarge, color = colors.onSurfaceVariant)
|
||||
FitText(code, maxSize = if (inPip) 40.sp else 56.sp, fontWeight = FontWeight.Bold, color = accent,
|
||||
modifier = Modifier.fillMaxWidth())
|
||||
Text(Uri.parse(url).let { it.host + it.path }, style = MaterialTheme.typography.labelMedium, color = colors.onSurfaceVariant, maxLines = 1)
|
||||
if (!inPip) Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
PrimaryButton(stringResource(R.string.fm_copy), onClick = ::copy)
|
||||
SecondaryButton(stringResource(R.string.common_close), onClick = ::finish)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val EXTRA_CODE = "code"
|
||||
private const val EXTRA_URL = "url"
|
||||
private const val EXTRA_DISPLAY = "display"
|
||||
private var current: WeakReference<DeviceCodeActivity>? = null
|
||||
|
||||
/** False when this device cannot float a window, so the caller opens the page itself. */
|
||||
fun show(context: Context, code: String, url: String, display: Int): Boolean {
|
||||
if (!PairingGuideActivity.canFloat(context)) return false
|
||||
val intent = Intent(context, DeviceCodeActivity::class.java)
|
||||
.putExtra(EXTRA_CODE, code).putExtra(EXTRA_URL, url).putExtra(EXTRA_DISPLAY, display)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
return runCatching {
|
||||
if (display > 0) context.startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(display).toBundle())
|
||||
else context.startActivity(intent)
|
||||
}.isSuccess
|
||||
}
|
||||
|
||||
fun close() {
|
||||
current?.get()?.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -179,7 +179,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
private var syncFallback by mutableStateOf(true)
|
||||
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 vramCapMb by mutableStateOf(0)
|
||||
@@ -207,10 +206,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
private var lowStorageWarning by mutableStateOf(true)
|
||||
private var launcherIcon by mutableStateOf(LauncherIcon.DARK)
|
||||
private var gameStoresEnabled by mutableStateOf(true)
|
||||
private var soundtracksEnabled by mutableStateOf(true)
|
||||
private var soundtracksIngame by mutableStateOf(false)
|
||||
private var soundtracks by mutableStateOf<List<Library.SteamGame>>(emptyList())
|
||||
private var soundtracksLoaded by mutableStateOf(false)
|
||||
private var gameStoresSpeedTier by mutableStateOf("fast")
|
||||
private var navRequest by mutableStateOf<String?>(null)
|
||||
private val gameLaunchRequest = java.util.concurrent.atomic.AtomicLong()
|
||||
@@ -790,11 +785,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
private var shortcutPicker by mutableStateOf(false)
|
||||
private var shortcutLibraryScanning by mutableStateOf(false)
|
||||
@Volatile private var libraryScanGeneration = 0
|
||||
private class SoundtrackRemoval(val op: Int, var scan: Int, var settled: Boolean)
|
||||
private val soundtrackRemovals = HashMap<String, SoundtrackRemoval>()
|
||||
private var soundtrackOp = 0
|
||||
private var soundtrackAddScan = -1
|
||||
private val soundtrackWork = java.util.concurrent.Executors.newSingleThreadExecutor { r -> Thread(r, "soundtrack-work").apply { isDaemon = true } }
|
||||
@Volatile private var lastComponentRestore = 0L
|
||||
@Volatile private var componentRestoreRetry = false
|
||||
private val componentRestoreLock = Any()
|
||||
@@ -857,15 +847,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
pendingGameLink = null
|
||||
gameLinkReading = false
|
||||
gameLinkTried = false
|
||||
soundtrackLaunch = false
|
||||
val soundtrackId = com.droiddeck.launcher.frontend.SoundtrackShortcuts.read(request)
|
||||
if (soundtrackId != null) {
|
||||
soundtrackLaunch = true
|
||||
navRequest = if (SessionPrefs.soundtracksEnabled(this)) "sound:$soundtrackId" else "app:$soundtrackId"
|
||||
request.data = null
|
||||
request.action = Intent.ACTION_MAIN
|
||||
return
|
||||
}
|
||||
if (GameLaunchIntent.accepts(request.action)) {
|
||||
gameLinkReading = true
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
|
||||
@@ -889,15 +870,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
}
|
||||
|
||||
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false, onHandled: () -> Unit = {}): Boolean {
|
||||
if (!SessionPrefs.soundtracksIngame(this)) com.droiddeck.launcher.playback.SoundtrackController.pause(this)
|
||||
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false): Boolean {
|
||||
if (pkgStage != null) {
|
||||
onHandled()
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return false
|
||||
}
|
||||
if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome, onHandled)
|
||||
onHandled()
|
||||
if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome)
|
||||
if (SessionState.running) {
|
||||
if (SessionState.mode != SessionService.MODE_STEAM || SessionState.stopRequested) {
|
||||
android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show()
|
||||
@@ -941,13 +919,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
.apply { if (returnHome) putExtra(SessionActivity.EXTRA_LINK_TASK, task) }
|
||||
}
|
||||
|
||||
private fun launchWithoutSteam(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit = {}): Boolean {
|
||||
private fun launchWithoutSteam(game: Library.SteamGame, returnHome: Boolean): Boolean {
|
||||
val app = applicationContext
|
||||
Thread({
|
||||
val added = if (com.droiddeck.launcher.session.NoSteamLaunch.needsAddedGame(game)) runCatching { com.droiddeck.launcher.session.NoSteamLaunch.addedGame(app, game) }.getOrNull() else null
|
||||
val added = if (game.library == Library.ADDED) runCatching { com.droiddeck.launcher.session.NoSteamLaunch.addedGame(app, game) }.getOrNull() else null
|
||||
val command = com.droiddeck.launcher.session.NoSteamLaunch.command(game, added)
|
||||
ui.post {
|
||||
onHandled()
|
||||
if (isDestroyed) return@post
|
||||
if (command == null) {
|
||||
android.widget.Toast.makeText(this, R.string.game_link_failed, android.widget.Toast.LENGTH_LONG).show()
|
||||
@@ -1167,8 +1144,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
LauncherIcon.repair(this, intent?.component)
|
||||
launcherIcon = LauncherIcon.current(this)
|
||||
gameStoresEnabled = SessionPrefs.gameStoresEnabled(this)
|
||||
soundtracksEnabled = SessionPrefs.soundtracksEnabled(this)
|
||||
soundtracksIngame = SessionPrefs.soundtracksIngame(this)
|
||||
gameStoresSpeedTier = SessionPrefs.gameStoresSpeedTier(this)
|
||||
storesShowMature = SessionPrefs.storesShowMature(this)
|
||||
storesSort = SessionPrefs.storesSort(this)
|
||||
@@ -1264,10 +1239,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
lowStorageWarning = lowStorageWarning,
|
||||
launcherIcon = launcherIcon,
|
||||
gameStoresEnabled = gameStoresEnabled,
|
||||
soundtracksEnabled = soundtracksEnabled,
|
||||
soundtracksIngame = soundtracksIngame,
|
||||
soundtracks = soundtracks,
|
||||
soundtracksLoaded = soundtracksLoaded,
|
||||
gameStoresSpeedTier = gameStoresSpeedTier,
|
||||
navigate = navRequest,
|
||||
addedGamesArt = addedGamesArt,
|
||||
@@ -1316,10 +1287,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
},
|
||||
onEpicLauncher = { openEpicLauncher() },
|
||||
onUninstallEpicLauncher = { uninstallEpicLauncher() },
|
||||
onGameShortcut = { g ->
|
||||
if (g.soundtrack) com.droiddeck.launcher.frontend.SoundtrackShortcuts.pin(this, g)
|
||||
else com.droiddeck.launcher.frontend.GameShortcuts.pin(this, g)
|
||||
},
|
||||
onGameShortcut = { g -> com.droiddeck.launcher.frontend.GameShortcuts.pin(this, g) },
|
||||
onExportGameFile = { g -> pickGameExport(g) },
|
||||
onSyncGameFiles = { pickGameExport(null) },
|
||||
onAddGameExe = { path -> addGameExe(path) },
|
||||
@@ -1344,9 +1312,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}, "game-file-stop-sync").start()
|
||||
},
|
||||
onCopyGameLink = { g ->
|
||||
val link = if (g.soundtrack) com.droiddeck.launcher.frontend.SoundtrackShortcuts.uri(g.appId)
|
||||
else com.droiddeck.launcher.frontend.GameLaunchLink.uri(g.gameIdString)
|
||||
(getSystemService(CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(ClipData.newPlainText(g.name, link))
|
||||
(getSystemService(CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(
|
||||
ClipData.newPlainText(g.name, com.droiddeck.launcher.frontend.GameLaunchLink.uri(g.gameIdString)))
|
||||
android.widget.Toast.makeText(this, R.string.game_link_copied, android.widget.Toast.LENGTH_SHORT).show()
|
||||
},
|
||||
onDesktop = {
|
||||
@@ -1371,7 +1338,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
},
|
||||
onRom = { g ->
|
||||
val e = emulatorList.first { it.id == g.emulatorId }
|
||||
if (!SessionPrefs.soundtracksIngame(this)) com.droiddeck.launcher.playback.SoundtrackController.pause(this)
|
||||
startActivity(Intent(this, SessionActivity::class.java)
|
||||
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN)
|
||||
.putExtra(SessionService.EXTRA_PROGRAM, e.program)
|
||||
@@ -1540,15 +1506,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
},
|
||||
onPageBack = { showPerformance = false; showComponents = false; showMapping = false },
|
||||
onGameStoresEnabled = { on -> SessionPrefs.setGameStoresEnabled(this, on); gameStoresEnabled = on },
|
||||
onSoundtracksEnabled = { on -> SessionPrefs.setSoundtracksEnabled(this, on); soundtracksEnabled = on },
|
||||
onSoundtracksIngame = { on ->
|
||||
SessionPrefs.setSoundtracksIngame(this, on)
|
||||
soundtracksIngame = on
|
||||
com.droiddeck.launcher.playback.SoundtrackController.setIngame(this, on)
|
||||
},
|
||||
onSoundtrackAdded = { folder -> addSoundtrack(folder) },
|
||||
onSoundtracksChanged = { refreshAddedSoundtracks() },
|
||||
onSoundtrackRemoved = { g -> removeSoundtrack(g) },
|
||||
onTheme = { id -> SessionPrefs.setTheme(this, id); theme = id },
|
||||
onLauncherIcon = { style -> switchLauncherIcon(style) },
|
||||
onLanguage = { tag ->
|
||||
@@ -1842,10 +1799,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
startSteamAtStartupIfEnabled()
|
||||
}
|
||||
|
||||
private var soundtrackLaunch = false
|
||||
|
||||
private fun startSteamAtStartupIfEnabled(cold: Boolean = false) {
|
||||
if (soundtrackLaunch) return
|
||||
if (intent.action != Intent.ACTION_MAIN && !(cold && intent.action == null)) return
|
||||
if (isFinishing || isDestroyed) return
|
||||
when (SessionPrefs.startupSession(this)) {
|
||||
@@ -2073,8 +2027,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g, onBlocked = done) {
|
||||
if (request != gameLaunchRequest.get() || isFinishing || isDestroyed) { done(); return@beforeLaunch }
|
||||
com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) {
|
||||
if (request == gameLaunchRequest.get() && !isFinishing && !isDestroyed) launchGame(g, onHandled = done)
|
||||
else done()
|
||||
done()
|
||||
if (request == gameLaunchRequest.get() && !isFinishing && !isDestroyed) launchGame(g)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2625,7 +2579,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
private fun PerformanceHost() {
|
||||
PerformancePage(
|
||||
cores = CpuCores.all.map { c -> CoreRow(c, "cpu$c" + (CpuCores.maxGhz(c)?.let { String.format(java.util.Locale.US, " · %.1f GHz", it) } ?: "")) },
|
||||
clientOverride = clientOverride, clientCores = clientCores, gameCores = gameCores, paceCores = paceCores,
|
||||
clientOverride = clientOverride, clientCores = clientCores, gameCores = gameCores,
|
||||
tuSysmem = tuSysmem, zinkLazy = zinkLazy, glThread = glThread, noGlError = noGlError, noXalia = noXalia,
|
||||
fastSync = fastSync,
|
||||
syncFallback = syncFallback,
|
||||
@@ -2639,7 +2593,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, cursorComposite = cursorComposite,
|
||||
guestHostname = guestHostname, phantomWarning = phantomWarning,
|
||||
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
|
||||
onPaceCores = { on -> SessionPrefs.setPaceCores(this, on); paceCores = on },
|
||||
onTuSysmem = { on -> SessionPrefs.setTuSysmem(this, on); tuSysmem = on },
|
||||
onZinkLazy = { on -> SessionPrefs.setZinkLazy(this, on); zinkLazy = on },
|
||||
onGlThread = { on -> SessionPrefs.setGlThread(this, on); glThread = on },
|
||||
@@ -2691,89 +2644,15 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
val version = (steamArtRefreshes[appId] ?: 0) + 1
|
||||
steamArtRefreshes[appId] = version
|
||||
Thread({
|
||||
val fresh = com.droiddeck.launcher.frontend.Library.steamGames(this, soundtracks = true).firstOrNull { it.appId == appId } ?: return@Thread
|
||||
val fresh = com.droiddeck.launcher.frontend.Library.steamGames(this).firstOrNull { it.appId == appId } ?: return@Thread
|
||||
ui.post {
|
||||
if (steamArtRefreshes[appId] != version) return@post
|
||||
if (fresh.soundtrack) soundtracks = soundtracks.map { if (it.appId == appId && it.library != Library.ADDED) fresh else it }
|
||||
else steamGames = steamGames.map { if (it.appId == appId && it.library != Library.ADDED) fresh else it }
|
||||
steamGames = steamGames.map { if (it.appId == appId && it.library != Library.ADDED) fresh else it }
|
||||
}
|
||||
}, "steam-art-update").start()
|
||||
}
|
||||
|
||||
private fun addSoundtrack(folder: java.io.File) {
|
||||
val op = ++soundtrackOp
|
||||
soundtrackAddScan = libraryScanGeneration
|
||||
soundtrackWork.execute {
|
||||
val added = com.droiddeck.launcher.frontend.AddedSoundtracks.add(this, folder)
|
||||
val list = com.droiddeck.launcher.frontend.AddedSoundtracks.games(this)
|
||||
ui.post {
|
||||
if (added) {
|
||||
soundtrackRemovals[folder.path]?.takeIf { it.op < op }?.let {
|
||||
soundtrackRemovals.remove(folder.path)
|
||||
com.droiddeck.launcher.playback.SoundtrackController.allow(listOf(folder.path))
|
||||
}
|
||||
val visible = list.filterNot { s -> s.gameFiles?.path?.let { soundtrackRemovals[it] }?.let { it.op > op } == true }
|
||||
soundtracks = soundtracks.filter { it.library != Library.ADDED } + visible
|
||||
} else android.widget.Toast.makeText(this, R.string.soundtracks_add_empty, android.widget.Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun refreshAddedSoundtracks() {
|
||||
val op = soundtrackOp
|
||||
soundtrackWork.execute {
|
||||
val list = com.droiddeck.launcher.frontend.AddedSoundtracks.games(this)
|
||||
ui.post {
|
||||
if (op != soundtrackOp) return@post
|
||||
val visible = list.filterNot { s -> s.gameFiles?.path?.let { soundtrackRemovals[it] } != null }
|
||||
soundtracks = soundtracks.filter { it.library != Library.ADDED } + visible
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun removeSoundtrack(g: Library.SteamGame) {
|
||||
val path = g.gameFiles?.path
|
||||
val added = g.library == Library.ADDED
|
||||
val target = if (added) null else com.droiddeck.launcher.frontend.GameRemoval.steamFiles(g) ?: return
|
||||
com.droiddeck.launcher.playback.SoundtrackController.stopIf(this, g.gameFiles)
|
||||
val marker = SoundtrackRemoval(++soundtrackOp, libraryScanGeneration, added)
|
||||
path?.let { soundtrackRemovals[it] = marker }
|
||||
if (target == null) {
|
||||
soundtracks = soundtracks.filterNot { it.appId == g.appId && it.library == Library.ADDED }
|
||||
soundtrackWork.execute {
|
||||
val removed = com.droiddeck.launcher.frontend.AddedSoundtracks.remove(this, path.orEmpty())
|
||||
val list = if (removed) emptyList() else com.droiddeck.launcher.frontend.AddedSoundtracks.games(this)
|
||||
if (!removed) ui.post {
|
||||
if (path != null && soundtrackRemovals[path] === marker) {
|
||||
soundtrackRemovals.remove(path)
|
||||
com.droiddeck.launcher.playback.SoundtrackController.allow(listOf(path))
|
||||
}
|
||||
soundtracks = soundtracks.filter { it.library != Library.ADDED } + list.filterNot { s -> s.gameFiles?.path?.let { soundtrackRemovals[it] } != null }
|
||||
android.widget.Toast.makeText(this, getString(R.string.gfiles_remove_failed, g.name), android.widget.Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
soundtrackWork.execute {
|
||||
val deleted = com.droiddeck.launcher.frontend.GameRemoval.delete(target)
|
||||
ui.post {
|
||||
if (deleted) {
|
||||
marker.scan = libraryScanGeneration
|
||||
marker.settled = true
|
||||
} else {
|
||||
if (path != null && soundtrackRemovals[path] === marker) {
|
||||
soundtrackRemovals.remove(path)
|
||||
com.droiddeck.launcher.playback.SoundtrackController.allow(listOf(path))
|
||||
}
|
||||
android.widget.Toast.makeText(this, getString(R.string.gfiles_remove_failed, g.name), android.widget.Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun removeGame(g: Library.SteamGame) {
|
||||
if (g.soundtrack) { removeSoundtrack(g); return }
|
||||
val folder = g.gameFiles ?: return
|
||||
when (com.droiddeck.launcher.frontend.GameRemoval.kind(g)) {
|
||||
com.droiddeck.launcher.frontend.GameRemoval.Kind.LAUNCHER -> Unit
|
||||
@@ -2946,7 +2825,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
syncFallback = SessionPrefs.syncFallback(this)
|
||||
fsyncFirst = SessionPrefs.fsyncFirst(this)
|
||||
gamescopeRealtime = SessionPrefs.gamescopeRealtime(this)
|
||||
paceCores = SessionPrefs.paceCores(this)
|
||||
ramCapMb = SessionPrefs.ramCapMb(this)
|
||||
zramClient = SessionPrefs.zramClient(this)
|
||||
vramCapMb = SessionPrefs.vramCapMb(this)
|
||||
@@ -3058,19 +2936,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
val scannedArch = SessionPrefs.activeSteamClientArch(this)
|
||||
val scannedX64 = scannedArch == "x86_64"
|
||||
val scannedSoundtracks = runCatching {
|
||||
(if (ready || com.droiddeck.launcher.runtime.LinuxRuntime.hasRootfs(this)) Library.soundtracks(this, scannedArch) else emptyList()) +
|
||||
com.droiddeck.launcher.frontend.AddedSoundtracks.games(this)
|
||||
}.getOrDefault(emptyList())
|
||||
ui.post {
|
||||
if (scanGeneration == libraryScanGeneration) {
|
||||
val scanned = if (scanGeneration <= soundtrackAddScan) scannedSoundtracks + soundtracks.filter { cur -> cur.library == Library.ADDED && scannedSoundtracks.none { it.library == Library.ADDED && it.appId == cur.appId } } else scannedSoundtracks
|
||||
val kept = scanned.filterNot { s -> s.gameFiles?.path?.let { p -> soundtrackRemovals[p]?.let { m -> !m.settled || s.library == Library.ADDED || scanGeneration <= m.scan } } == true }
|
||||
com.droiddeck.launcher.playback.SoundtrackController.allow(kept.mapNotNull { it.gameFiles?.path })
|
||||
soundtracks = kept
|
||||
soundtracksLoaded = true
|
||||
}
|
||||
}
|
||||
val games = if (ready || com.droiddeck.launcher.runtime.LinuxRuntime.hasRootfs(this)) Library.launchableGames(this, arch = scannedArch) else emptyList()
|
||||
val all = games.distinctBy { it.gameId }
|
||||
if (ready && scanGeneration == libraryScanGeneration) com.droiddeck.launcher.frontend.LibraryCache.save(this, all, scannedX64)
|
||||
@@ -3213,7 +3078,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
if (!ok) android.widget.Toast.makeText(this, R.string.setup_reset_settings_partial, android.widget.Toast.LENGTH_LONG).show()
|
||||
com.droiddeck.launcher.ui.Motion.refresh(this)
|
||||
com.droiddeck.launcher.agent.AgentTab.load(this)
|
||||
com.droiddeck.launcher.ui.NavTabs.load(this)
|
||||
if (!switchLauncherIcon(LauncherIcon.DARK)) recreate()
|
||||
}
|
||||
}, "reset-settings").start()
|
||||
|
||||
@@ -4,7 +4,6 @@ import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
|
||||
class HomeActivity : Activity() {
|
||||
override fun attachBaseContext(newBase: android.content.Context) {
|
||||
@@ -19,7 +18,7 @@ class HomeActivity : Activity() {
|
||||
}
|
||||
|
||||
private fun routeHome() {
|
||||
val destination = if (HomeApp.isActiveSteamSession() && !SessionState.pipActive) {
|
||||
val destination = if (HomeApp.isActiveSteamSession()) {
|
||||
Intent(this, SessionActivity::class.java)
|
||||
.setAction(SessionService.ACTION_HOME_GUIDE)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||
@@ -33,8 +32,7 @@ class HomeActivity : Activity() {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (SessionState.pipActive && destination.component?.className == FrontEndActivity::class.java.name) HomeApp.showFrontEnd(this, destination)
|
||||
else startActivity(destination)
|
||||
startActivity(destination)
|
||||
finish()
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,6 @@ import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import androidx.core.graphics.drawable.toBitmap
|
||||
import com.droiddeck.launcher.core.AppUiPrefs
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import kotlin.math.roundToInt
|
||||
@@ -197,10 +196,7 @@ object HomeApp {
|
||||
}
|
||||
|
||||
private fun syncRecents(activity: android.app.Activity) =
|
||||
keepOutOfRecents(
|
||||
activity,
|
||||
activity is FrontEndActivity && !SessionState.running && isDefault(activity) && AppUiPrefs.hideHomeFromRecents(activity),
|
||||
)
|
||||
keepOutOfRecents(activity, activity is FrontEndActivity && !SessionState.running && isDefault(activity))
|
||||
|
||||
internal enum class RecentsStep { HIDE, SHOW, FORGET, NONE }
|
||||
|
||||
@@ -262,19 +258,6 @@ object HomeApp {
|
||||
fun isActiveSteamSession(): Boolean =
|
||||
SessionState.running && SessionState.mode == SessionService.MODE_STEAM
|
||||
|
||||
fun showFrontEnd(context: Context, intent: Intent = Intent(context, FrontEndActivity::class.java)) {
|
||||
val frontEnd = FrontEndActivity::class.java.name
|
||||
val tasks = runCatching { context.getSystemService(android.app.ActivityManager::class.java)?.appTasks }.getOrNull().orEmpty()
|
||||
val own = tasks.firstOrNull { task ->
|
||||
runCatching { task.taskInfo.let { it.baseIntent.component?.className == frontEnd && it.topActivity?.className == frontEnd } }
|
||||
.getOrDefault(false)
|
||||
}
|
||||
val launch = Intent(intent).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||
if (own != null && runCatching { own.startActivity(context, launch, null) }.isSuccess) return
|
||||
// The session task shares the front end's affinity, so without MULTIPLE_TASK the front end lands inside the session's PiP window.
|
||||
context.startActivity(launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK))
|
||||
}
|
||||
|
||||
fun openSystemHomeSettings(context: Context) {
|
||||
try {
|
||||
context.startActivity(settingsIntent())
|
||||
|
||||
@@ -1330,9 +1330,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
selectedSecondScreenDisplay = selectedSecondScreenDisplay,
|
||||
onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() },
|
||||
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() },
|
||||
onHudOrderReset = { hudConfig = DroidDeckHudConfig.clearOrder(this@SessionActivity); hud.applyConfig() },
|
||||
onHudExport = { exportHudDiagnostics() },
|
||||
onUpscaler = { m ->
|
||||
SessionPrefs.setUpscaler(this@SessionActivity, m); upscaler = m
|
||||
@@ -2235,16 +2233,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
|
||||
private fun installRuntime(): String? {
|
||||
val release = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.fetchRelease()
|
||||
if (release == null) {
|
||||
SessionEvents.record("runtime.failed", mapOf("step" to "catalog", "reason" to com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.catalogError()))
|
||||
return getString(R.string.session_runtime_catalog_unreachable)
|
||||
}
|
||||
?: return getString(R.string.session_runtime_catalog_unreachable)
|
||||
runCatching { com.droiddeck.launcher.runtime.RuntimeInstallService.start(this, release) }
|
||||
val ok = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.install(this, release,
|
||||
progressFor(RUNTIME_LINES, release.size / 1_000_000))
|
||||
if (ok) return null
|
||||
SessionEvents.record("runtime.failed", mapOf("step" to "install", "reason" to com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.installError()))
|
||||
return getString(R.string.session_runtime_install_failed)
|
||||
return if (ok) null else getString(R.string.session_runtime_install_failed)
|
||||
}
|
||||
|
||||
private fun installDesktop(): String? {
|
||||
|
||||
@@ -17,7 +17,6 @@ import com.droiddeck.launcher.ui.UpdatesActions
|
||||
import com.droiddeck.launcher.ui.UpdatesState
|
||||
import com.droiddeck.launcher.update.AppUpdates
|
||||
import com.droiddeck.launcher.update.SelfInstaller
|
||||
import com.droiddeck.launcher.update.UpdateWatch
|
||||
|
||||
internal class UpdatesMenu(private val activity: Activity, private val ui: Handler) {
|
||||
var catalog by mutableStateOf<AppUpdates.Catalog?>(null)
|
||||
@@ -44,7 +43,6 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
|
||||
.onFailure { error = activity.getString(R.string.upd_unknown_apps_failed); pending = null }
|
||||
},
|
||||
onDismissPermission = { askPermission = false; pending = null },
|
||||
onSeen = { r -> UpdateWatch.seen(activity, r) },
|
||||
)
|
||||
|
||||
val hasUpdate: Boolean get() = AppUpdates.hasUpdate(catalog, follow)
|
||||
@@ -79,7 +77,6 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
|
||||
|
||||
private fun choose(f: AppUpdates.Follow) {
|
||||
AppUpdates.setFollow(activity, f)
|
||||
UpdateWatch.sync(activity, f, catalog?.let { AppUpdates.release(it, f) })
|
||||
follow = f
|
||||
error = null
|
||||
}
|
||||
|
||||
@@ -52,7 +52,6 @@ object AgentHost {
|
||||
|
||||
private const val TAG = "AgentHost"
|
||||
private const val WORKSPACE = "/root/DroidDeck"
|
||||
internal const val GUEST_PATH = "/root/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
|
||||
private const val TICK_MS = 1_000L
|
||||
private const val IDLE_TICK_MS = 5_000L
|
||||
|
||||
@@ -378,11 +377,11 @@ object AgentHost {
|
||||
* proot over the installed rootfs, without a session. Loopback adb is connected first so
|
||||
* droiddeckctl reaches the app.
|
||||
*/
|
||||
fun guest(app: Context, command: List<String>, workdir: String = "/root", connectAdb: Boolean = true, fakeRoot: Boolean = false): ProcessBuilder {
|
||||
fun guest(app: Context, command: List<String>, workdir: String = "/root", connectAdb: Boolean = true): ProcessBuilder {
|
||||
val adb = AgentAdb.prepare(app)
|
||||
val env = listOf(
|
||||
"/usr/bin/env", "HOME=/root", "PATH=$GUEST_PATH", "LANG=C.UTF-8",
|
||||
"ADB_SERIAL=${adb.serial}", "ADB_VENDOR_KEYS=${adb.vendorKeys}", "DROIDDECK_PACKAGE=${app.packageName}",
|
||||
"/usr/bin/env", "HOME=/root", "PATH=/root/.local/bin:/usr/local/bin:/usr/bin:/bin", "LANG=C.UTF-8",
|
||||
"ADB_SERIAL=${adb.serial}", "ADB_VENDOR_KEYS=${adb.vendorKeys}",
|
||||
"DD_AGENT=1", "DD_AGENT_INBOX=${File(app.filesDir, "agent").path}", "BROWSER=/root/.local/bin/android-open", "DD_BROWSER_DISPLAY=${AgentAdb.browserDisplay}",
|
||||
)
|
||||
val shell = listOf(
|
||||
@@ -391,7 +390,7 @@ object AgentHost {
|
||||
(if (connectAdb) "adb start-server >/dev/null 2>&1; adb connect \"\$ADB_SERIAL\" >/dev/null 2>&1; " else "") +
|
||||
"cd \"$1\" 2>/dev/null; shift; exec \"$@\"", "sh", workdir,
|
||||
)
|
||||
val proot = LinuxRuntime.command(app, null, null, Environment.getExternalStorageDirectory(), null, env + shell + command, fakeRoot)
|
||||
val proot = LinuxRuntime.command(app, null, null, Environment.getExternalStorageDirectory(), env + shell + command)
|
||||
return ProcessBuilder(proot).redirectErrorStream(true).apply {
|
||||
environment().apply {
|
||||
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
|
||||
@@ -508,7 +507,6 @@ object AgentHost {
|
||||
appContext?.let { app ->
|
||||
claimLabRequest(app)
|
||||
claimOpenUrl(app)
|
||||
claimDeviceCode(app)
|
||||
// proot comes from an add-on pack fetched after the app starts, so the runtime can become usable later.
|
||||
if (!available && state != State.WORKING) available = LinuxRuntime.hasRootfs(app)
|
||||
lab = LabProgress.read(LinuxRuntime.rootDir(app))
|
||||
@@ -530,43 +528,15 @@ object AgentHost {
|
||||
val url = runCatching { claimed.readText().trim() }.getOrNull()
|
||||
claimed.delete()
|
||||
if (url == null || !(url.startsWith("https://") || url.startsWith("http://"))) return
|
||||
if (!openUrl(app, url)) runCatching { File(app.filesDir, "$OPEN_URL.failed").writeText("") }
|
||||
}
|
||||
|
||||
/** dd-gh-login leaves "<code> <url>" here to float the code over the page, and an empty file when it ends. */
|
||||
private fun claimDeviceCode(app: Context) {
|
||||
val request = File(app.filesDir, DEVICE_CODE)
|
||||
if (!request.isFile) return
|
||||
val claimed = File(app.filesDir, "$DEVICE_CODE.claimed")
|
||||
if (!request.renameTo(claimed)) return
|
||||
val parts = runCatching { claimed.readText().trim() }.getOrDefault("").split(' ', limit = 2)
|
||||
claimed.delete()
|
||||
val code = parts[0]
|
||||
val url = parts.getOrNull(1)?.takeIf { it.startsWith("https://") }
|
||||
if (code.isEmpty() || url == null) {
|
||||
com.droiddeck.launcher.DeviceCodeActivity.close()
|
||||
return
|
||||
}
|
||||
if (!com.droiddeck.launcher.DeviceCodeActivity.show(app, code, url, AgentAdb.browserDisplay)) deviceCodeOpened(app, openUrl(app, url))
|
||||
}
|
||||
|
||||
/** Tells dd-gh-login whether the device page opened, so it can fall back to android-open. */
|
||||
fun deviceCodeOpened(app: Context, opened: Boolean) {
|
||||
runCatching {
|
||||
val part = File(app.filesDir, "$DEVICE_CODE.result.part")
|
||||
part.writeText(if (opened) "ok" else "failed")
|
||||
part.renameTo(File(app.filesDir, "$DEVICE_CODE.result"))
|
||||
}
|
||||
}
|
||||
|
||||
private fun openUrl(app: Context, url: String): Boolean {
|
||||
val intent = android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(url))
|
||||
.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
val options = android.app.ActivityOptions.makeBasic().setLaunchDisplayId(AgentAdb.browserDisplay).toBundle()
|
||||
return runCatching { app.startActivity(intent, options) }
|
||||
runCatching { app.startActivity(intent, options) }
|
||||
.recoverCatching { app.startActivity(intent) }
|
||||
.onFailure { Log.w(TAG, "could not open a sign-in link: ${it.javaClass.simpleName}") }
|
||||
.isSuccess
|
||||
.onFailure {
|
||||
Log.w(TAG, "could not open a sign-in link: ${it.javaClass.simpleName}")
|
||||
runCatching { File(app.filesDir, "$OPEN_URL.failed").writeText("") }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -622,7 +592,6 @@ object AgentHost {
|
||||
private const val RESUME = "agent/resume"
|
||||
private const val LAB_REQUEST = "agent/lab-request"
|
||||
private const val OPEN_URL = "agent/open-url"
|
||||
private const val DEVICE_CODE = "agent/device-code"
|
||||
private const val LAB_CHAT_KEY = "lab_chat"
|
||||
/** The raw output of the latest turn, for working out what a CLI did when the chat shows nothing. */
|
||||
private const val TURN_LOG = "agent/turn.log"
|
||||
|
||||
@@ -77,9 +77,6 @@ class AgentHostService : Service() {
|
||||
private fun describe(context: Context): String {
|
||||
val lab = AgentHost.lab?.takeIf { it.running }
|
||||
if (lab != null) return context.getString(R.string.agent_lab_progress, lab.permille / 10, minutes(lab.etaSeconds.toLong().coerceAtLeast(0)))
|
||||
AgentSetup.detail[AgentSetup.Step.GITHUB]?.takeIf {
|
||||
AgentSetup.status[AgentSetup.Step.GITHUB] == AgentSetup.Status.WORKING && it.startsWith("GitHub device code:")
|
||||
}?.let { return it }
|
||||
if (AgentHost.state != AgentHost.State.WORKING) return context.getString(R.string.agent_setting_up)
|
||||
val tool = AgentHost.running()
|
||||
val elapsed = minutes((SystemClock.elapsedRealtime() - AgentHost.turnStarted) / 1000)
|
||||
|
||||
@@ -73,8 +73,6 @@ object AgentSetup {
|
||||
Thread({ for ((step, command) in probes) probe(app, harness, step, command) }, "agent-checks").start()
|
||||
}
|
||||
|
||||
fun runsAsRoot(step: Step) = step == Step.INSTALL
|
||||
|
||||
/** Runs [step]'s action. [CONNECTION] is the app's own pairing flow, so the caller opens it. */
|
||||
fun run(context: Context, step: Step) {
|
||||
val app = context.applicationContext
|
||||
@@ -83,7 +81,7 @@ object AgentSetup {
|
||||
Step.CONNECTION -> return
|
||||
Step.INSTALL -> {
|
||||
listOf("sh", "-c", "set -e; export DEBIAN_FRONTEND=noninteractive; " +
|
||||
"dpkg --configure -a; apt-get update || echo 'Some package sources could not be refreshed; continuing'; apt-get -f install -y; " +
|
||||
"dpkg --configure -a; apt-get update; apt-get -f install -y; " +
|
||||
"apt-get install -y --no-install-recommends git gh adb curl ca-certificates python3; ${harness.install}")
|
||||
}
|
||||
Step.SIGN_IN -> harness.signIn
|
||||
@@ -99,7 +97,7 @@ object AgentSetup {
|
||||
val result = runCatching {
|
||||
installHelpers(app)
|
||||
runCatching { harness.prepare(LinuxRuntime.rootDir(app)) }
|
||||
val child = AgentHost.guest(app, command, fakeRoot = runsAsRoot(step)).start()
|
||||
val child = AgentHost.guest(app, command).start()
|
||||
val pid = AgentProcesses.pidOf(child)
|
||||
OrphanReaper.keep(pid)
|
||||
try {
|
||||
@@ -108,10 +106,7 @@ object AgentSetup {
|
||||
child.inputStream.bufferedReader().forEachLine { line ->
|
||||
log.appendLine(line)
|
||||
val text = line.trim()
|
||||
if (text.isNotEmpty() && !noise(text)) main.post {
|
||||
detail[step] = text.take(160)
|
||||
if (step == Step.GITHUB && text.startsWith("GitHub device code:")) AgentHostService.update(app)
|
||||
}
|
||||
if (text.isNotEmpty() && !noise(text)) main.post { detail[step] = text.take(160) }
|
||||
}
|
||||
child.waitFor().also { log.appendLine("exit $it") }
|
||||
}
|
||||
@@ -191,14 +186,6 @@ object AgentSetup {
|
||||
for (name in HELPERS) copyAsset(app, "agent/$name", File(bin, name))
|
||||
val ctl = File(root, CTL.removePrefix("/")).apply { mkdirs() }
|
||||
for (name in app.assets.list("agent/ctl").orEmpty()) copyAsset(app, "agent/ctl/$name", File(ctl, name))
|
||||
unpinAdbSerial(File(root, "root/.bashrc"))
|
||||
}
|
||||
|
||||
/** Older tools/agent/setup pinned the adb port in .bashrc, which overrides the live port DroidDeck passes. */
|
||||
internal fun unpinAdbSerial(bashrc: File) {
|
||||
val text = runCatching { bashrc.readText() }.getOrNull() ?: return
|
||||
val fixed = text.replace("ADB_SERIAL=127.0.0.1:5555 ", "ADB_SERIAL=\"\${ADB_SERIAL:-127.0.0.1:5555}\" ")
|
||||
if (fixed != text) runCatching { bashrc.writeText(fixed) }
|
||||
}
|
||||
|
||||
private fun copyAsset(app: Context, asset: String, target: File) {
|
||||
|
||||
@@ -7,7 +7,7 @@ import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
|
||||
object AgentTab {
|
||||
var shown by mutableStateOf(true)
|
||||
var shown by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
val visible: Boolean get() = shown && AgentHost.available
|
||||
|
||||
@@ -31,9 +31,6 @@ internal class AddonPack(
|
||||
val state: StateFlow<State> = mutableState.asStateFlow()
|
||||
private val lock = Any()
|
||||
|
||||
@Volatile var failure: String? = null
|
||||
private set
|
||||
|
||||
val available: Boolean get() = sha256.isNotEmpty()
|
||||
private val tag get() = "pack-$name-${sha256.take(16)}"
|
||||
private val urls get() = listOfNotNull(
|
||||
@@ -70,13 +67,9 @@ internal class AddonPack(
|
||||
if (installed(app)) { mutableState.value = State.Ready; return }
|
||||
if (mutableState.value is State.Downloading) return
|
||||
mutableState.value = State.Downloading(0f)
|
||||
failure = null
|
||||
}
|
||||
scope.launch {
|
||||
val ok = runCatching { install(app) }.onFailure {
|
||||
Log.w(TAG, "$name: install failed", it)
|
||||
failure = it.toString()
|
||||
}.getOrDefault(false)
|
||||
val ok = runCatching { install(app) }.onFailure { Log.w(TAG, "$name: install failed", it) }.getOrDefault(false)
|
||||
mutableState.value = if (ok) State.Ready else State.Failed
|
||||
if (ok) onReady(app)
|
||||
}
|
||||
@@ -100,28 +93,20 @@ internal class AddonPack(
|
||||
|
||||
private fun install(context: Context): Boolean {
|
||||
if (!available) {
|
||||
failure = if (reuseDeviceCopy) "this build has no pack and none is installed" else "this build has no pack"
|
||||
Log.w(TAG, "$name: $failure")
|
||||
Log.w(TAG, if (reuseDeviceCopy) "$name: this build has no pack and none is installed" else "$name: this build has no pack")
|
||||
return false
|
||||
}
|
||||
val root = root(context).apply { mkdirs() }
|
||||
val archive = File(root, "$sha256.tar.zst")
|
||||
val problems = mutableListOf<String>()
|
||||
val downloaded = bundled(context, archive) || urls.any { url ->
|
||||
Downloader.downloadFile(url, archive, true, sha256) { p -> mutableState.value = State.Downloading(p.coerceIn(0f, 1f)) }
|
||||
.also { if (!it) { archive.delete(); Downloader.lastFailure()?.let(problems::add) } }
|
||||
}
|
||||
if (!downloaded) {
|
||||
failure = problems.joinToString("; ").ifEmpty { "download failed" }
|
||||
return false
|
||||
.also { if (!it) archive.delete() }
|
||||
}
|
||||
if (!downloaded) return false
|
||||
val staging = File(root, "$sha256.partial")
|
||||
staging.deleteRecursively()
|
||||
try {
|
||||
if (!FileInputStream(archive).use { TarZst.extract(it, staging) }) {
|
||||
failure = "could not unpack the pack"
|
||||
return false
|
||||
}
|
||||
if (!FileInputStream(archive).use { TarZst.extract(it, staging) }) return false
|
||||
check(required.all { File(staging, it).isFile }) { "$name pack is incomplete" }
|
||||
File(staging, COMPLETE).writeText(sha256)
|
||||
val target = dir(context)
|
||||
|
||||
@@ -46,13 +46,6 @@ object AppUiPrefs {
|
||||
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putString("home-page", value).apply()
|
||||
}
|
||||
|
||||
fun hideHomeFromRecents(context: Context): Boolean =
|
||||
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).getBoolean("hide-home-from-recents", false)
|
||||
|
||||
fun setHideHomeFromRecents(context: Context, hidden: Boolean) {
|
||||
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putBoolean("hide-home-from-recents", hidden).apply()
|
||||
}
|
||||
|
||||
internal fun normalizeScale(percent: Int): Int = percent.takeIf { it in scales } ?: DEFAULT_SCALE
|
||||
|
||||
fun scale(context: Context): Int = normalizeScale(
|
||||
|
||||
@@ -274,7 +274,6 @@ object DeviceReport {
|
||||
EsyncPacks.status(LinuxRuntime.rootDir(context)).let { k("droiddeck-esync packs", "${it.installed} installed, ${it.wanted} wanted") }
|
||||
k("Linux x86 (FEX)", if (com.droiddeck.launcher.runtime.LinuxFex.ready(context)) "ready" else "not set up")
|
||||
k("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" })
|
||||
|
||||
@@ -31,26 +31,8 @@ public final class Downloader {
|
||||
return thread;
|
||||
});
|
||||
|
||||
private static final ThreadLocal<String> LAST_FAILURE = new ThreadLocal<>();
|
||||
|
||||
private Downloader() {}
|
||||
|
||||
public static String lastFailure() {
|
||||
return LAST_FAILURE.get();
|
||||
}
|
||||
|
||||
private static void failed(String url, String reason) {
|
||||
String host;
|
||||
try { host = new java.net.URI(url).getHost(); } catch (java.net.URISyntaxException e) { host = null; }
|
||||
String entry = (host == null ? url : host) + ": " + reason;
|
||||
String earlier = LAST_FAILURE.get();
|
||||
LAST_FAILURE.set(earlier == null ? entry : earlier + "; " + entry);
|
||||
}
|
||||
|
||||
private static String describe(Exception e) {
|
||||
return e.getMessage() == null ? e.getClass().getSimpleName() : e.getClass().getSimpleName() + ": " + e.getMessage();
|
||||
}
|
||||
|
||||
public static final class Cancellation implements java.util.function.BooleanSupplier {
|
||||
private final AtomicBoolean cancelled = new AtomicBoolean();
|
||||
private final AtomicReference<HttpURLConnection> connection = new AtomicReference<>();
|
||||
@@ -105,14 +87,12 @@ public final class Downloader {
|
||||
|
||||
public static String downloadString(String url, java.util.function.BooleanSupplier cancelled) {
|
||||
List<String> sources = DownloadSource.INSTANCE.candidates(url);
|
||||
LAST_FAILURE.remove();
|
||||
for (int i = 0; i < sources.size(); i++) {
|
||||
if (isCancelled(cancelled)) return null;
|
||||
if (i > 0) Log.i(TAG, "retrying " + url + " via " + sources.get(i));
|
||||
Fetch fetch = fetch(sources.get(i), cancelled);
|
||||
if (isCancelled(cancelled)) return null;
|
||||
if (fetch.body != null) {
|
||||
LAST_FAILURE.remove();
|
||||
DownloadSource.INSTANCE.succeeded(sources.get(i));
|
||||
return fetch.body;
|
||||
}
|
||||
@@ -123,7 +103,6 @@ public final class Downloader {
|
||||
}
|
||||
|
||||
public static String downloadDirect(String url) {
|
||||
LAST_FAILURE.remove();
|
||||
return fetch(url).body;
|
||||
}
|
||||
|
||||
@@ -159,7 +138,6 @@ public final class Downloader {
|
||||
String expectedSha256, java.util.function.BooleanSupplier cancelled,
|
||||
java.util.function.Consumer<Float> progress) {
|
||||
Identity identity = loadIdentity(destination, resume, expectedSha256);
|
||||
LAST_FAILURE.remove();
|
||||
for (int i = 0; i < sources.size(); i++) {
|
||||
String source = sources.get(i);
|
||||
if (isCancelled(cancelled)) return false;
|
||||
@@ -172,14 +150,12 @@ public final class Downloader {
|
||||
if (isCancelled(cancelled)) return false;
|
||||
if (!expectedSha256.equalsIgnoreCase(actualSha256)) {
|
||||
Log.w(TAG, "checksum mismatch from " + source + "; trying another source");
|
||||
failed(source, "checksum mismatch");
|
||||
if (!discardPartial(destination, identity)) return false;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (isCancelled(cancelled)) return false;
|
||||
resumeFile(destination).delete();
|
||||
LAST_FAILURE.remove();
|
||||
DownloadSource.INSTANCE.succeeded(source);
|
||||
if (progress != null) progress.accept(1f);
|
||||
return true;
|
||||
@@ -284,7 +260,6 @@ public final class Downloader {
|
||||
}
|
||||
if (code / 100 != 2) {
|
||||
Log.w(TAG, url + " -> HTTP " + code);
|
||||
failed(url, "HTTP " + code);
|
||||
return code == HttpURLConnection.HTTP_NOT_FOUND || code == HttpURLConnection.HTTP_GONE
|
||||
? Outcome.FATAL : Outcome.RETRY;
|
||||
}
|
||||
@@ -333,15 +308,11 @@ public final class Downloader {
|
||||
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).detach(input);
|
||||
}
|
||||
if (isCancelled(cancelled)) return Outcome.CANCELLED;
|
||||
if (total > 0 && written < total) {
|
||||
failed(url, "connection closed after " + written + " of " + total + " bytes");
|
||||
return Outcome.RETRY;
|
||||
}
|
||||
if (total > 0 && written < total) return Outcome.RETRY;
|
||||
return Outcome.DONE;
|
||||
} catch (Exception e) {
|
||||
if (isCancelled(cancelled)) return Outcome.CANCELLED;
|
||||
Log.w(TAG, "download " + url, e);
|
||||
failed(url, describe(e));
|
||||
return Outcome.RETRY;
|
||||
} finally {
|
||||
if (connection != null) {
|
||||
@@ -386,7 +357,6 @@ public final class Downloader {
|
||||
int code = connection.getResponseCode();
|
||||
if (code / 100 != 2) {
|
||||
Log.w(TAG, url + " -> HTTP " + code);
|
||||
failed(url, "HTTP " + code);
|
||||
return new Fetch(null, code == HttpURLConnection.HTTP_NOT_FOUND || code == HttpURLConnection.HTTP_GONE);
|
||||
}
|
||||
try (InputStream in = connection.getInputStream();
|
||||
@@ -397,7 +367,6 @@ public final class Downloader {
|
||||
} catch (Exception e) {
|
||||
if (isCancelled(cancelled)) return new Fetch(null, false);
|
||||
Log.w(TAG, "GET " + url, e);
|
||||
failed(url, describe(e));
|
||||
return new Fetch(null, false);
|
||||
} finally {
|
||||
if (connection != null) {
|
||||
|
||||
@@ -49,16 +49,6 @@ object GameEnvironment {
|
||||
return withScopeValue(config, scope, NO_STEAM, if (on) "1" else null)
|
||||
}
|
||||
|
||||
const val GAME_RESOLUTION = "DROIDDECK_GAME_RESOLUTION"
|
||||
|
||||
fun gameResolution(config: Config, scope: String): GameResolution.Choice? =
|
||||
if (scope.isEmpty()) null else GameResolution.parse(config.games[scope]?.get(GAME_RESOLUTION))
|
||||
|
||||
fun withGameResolution(config: Config, scope: String, choice: GameResolution.Choice?): Config {
|
||||
require(scope.isNotEmpty() && validScope(scope))
|
||||
return withScopeValue(config, scope, GAME_RESOLUTION, choice?.let(GameResolution::format))
|
||||
}
|
||||
|
||||
fun effective(config: Config, preset: String, scope: String, forceSsbs: Boolean = false): Map<String, String?> =
|
||||
defaults(preset, forceSsbs) + config.shared + if (scope.isEmpty()) emptyMap() else config.games[scope].orEmpty()
|
||||
|
||||
|
||||
@@ -1,70 +0,0 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
object GameResolution {
|
||||
sealed interface Choice
|
||||
data class Fixed(val width: Int, val height: Int) : Choice
|
||||
data class Scaled(val scale: Float) : Choice
|
||||
|
||||
data class Aspect(val label: String, val sizes: List<Fixed>)
|
||||
|
||||
val aspects = listOf(
|
||||
Aspect("16:9", listOf(Fixed(960, 540), Fixed(1280, 720), Fixed(1600, 900), Fixed(1920, 1080), Fixed(2560, 1440))),
|
||||
Aspect("16:10", listOf(Fixed(1280, 800), Fixed(1440, 900), Fixed(1680, 1050), Fixed(1920, 1200), Fixed(2560, 1600))),
|
||||
Aspect("4:3", listOf(Fixed(640, 480), Fixed(800, 600), Fixed(1024, 768), Fixed(1280, 960), Fixed(1440, 1080))),
|
||||
)
|
||||
|
||||
val scales = listOf(1.5f, 2f, 3f)
|
||||
|
||||
const val MIN_WIDTH = 320
|
||||
const val MIN_HEIGHT = 240
|
||||
const val MAX_SIDE = 7680
|
||||
private const val SCALED_PREFIX = "/"
|
||||
|
||||
fun parse(value: String?): Choice? {
|
||||
val text = value?.trim().orEmpty()
|
||||
if (text.startsWith(SCALED_PREFIX)) {
|
||||
return text.removePrefix(SCALED_PREFIX).toFloatOrNull()?.takeIf { it > 1f && it <= 8f }?.let(::Scaled)
|
||||
}
|
||||
val parts = text.split('x', 'X', '×').map { it.trim().toIntOrNull() }
|
||||
if (parts.size != 2) return null
|
||||
val (w, h) = parts
|
||||
return if (w != null && h != null && valid(w, h)) Fixed(w and 1.inv(), h and 1.inv()) else null
|
||||
}
|
||||
|
||||
fun valid(width: Int, height: Int) = width in MIN_WIDTH..MAX_SIDE && height in MIN_HEIGHT..MAX_SIDE
|
||||
|
||||
fun format(choice: Choice): String = when (choice) {
|
||||
is Fixed -> "${choice.width}x${choice.height}"
|
||||
is Scaled -> SCALED_PREFIX + formatScale(choice.scale)
|
||||
}
|
||||
|
||||
fun formatScale(scale: Float): String =
|
||||
(Math.round(scale * 10) / 10f).let { if (it % 1f == 0f) it.toInt().toString() else it.toString() }
|
||||
|
||||
fun resolve(choice: Choice, output: Pair<Int, Int>): Pair<Int, Int> = when (choice) {
|
||||
is Fixed -> choice.width to choice.height
|
||||
is Scaled -> (Math.round(output.first / choice.scale).coerceAtLeast(MIN_WIDTH) and 1.inv()) to
|
||||
(Math.round(output.second / choice.scale).coerceAtLeast(MIN_HEIGHT) and 1.inv())
|
||||
}
|
||||
|
||||
fun aspectLabel(width: Int, height: Int): String {
|
||||
if (width <= 0 || height <= 0) return ""
|
||||
val ratio = width.toFloat() / height
|
||||
aspects.firstOrNull { a ->
|
||||
val (w, h) = a.label.split(':').map(String::toFloat)
|
||||
kotlin.math.abs(ratio - w / h) < 0.02f
|
||||
}?.let { return it.label }
|
||||
if (kotlin.math.abs(ratio - 64f / 27f) < 0.04f || kotlin.math.abs(ratio - 21f / 9f) < 0.04f) return "21:9"
|
||||
val g = gcd(width, height)
|
||||
return if (width / g <= 32) "${width / g}:${height / g}" else String.format(java.util.Locale.ROOT, "%.2f:1", ratio)
|
||||
}
|
||||
|
||||
fun sizesFor(aspect: Aspect, panel: Pair<Int, Int>): List<Fixed> {
|
||||
val long = maxOf(panel.first, panel.second)
|
||||
val short = minOf(panel.first, panel.second)
|
||||
val fit = aspect.sizes.filter { it.width <= long && it.height <= short }
|
||||
return fit.ifEmpty { aspect.sizes.take(1) }
|
||||
}
|
||||
|
||||
private tailrec fun gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
|
||||
}
|
||||
@@ -100,13 +100,12 @@ object AddedGames {
|
||||
fun candidates(folder: File, reuse: Boolean = false): List<File> = rank(folder, reuse).exes
|
||||
|
||||
fun rank(folder: File, reuse: Boolean = false): GameExePicker.Ranking {
|
||||
val declared = declaredExes(folder)
|
||||
val stamp = declared.fold(0L) { hash, exe -> hash * 31 + exe.path.hashCode() }
|
||||
val key = "${folder.path}|${folder.lastModified()}|$stamp"
|
||||
val key = "${folder.path}|${folder.lastModified()}"
|
||||
val now = System.currentTimeMillis()
|
||||
ranked[key]?.takeIf { now - it.first < RANK_FRESH_MS }?.let { return it.second }
|
||||
if (reuse) kept?.rank(folder, stamp)?.let { return it }
|
||||
if (reuse) kept?.rank(folder)?.let { return it }
|
||||
val guessed = GameExePicker.rank(folder) { !skipExe(it.name) }
|
||||
val declared = declaredExes(folder)
|
||||
val preferred = declared.map { it.path }.toSet()
|
||||
val result = if (declared.isEmpty()) guessed else GameExePicker.Ranking(
|
||||
declared + guessed.exes.filter { it.path !in preferred },
|
||||
@@ -116,7 +115,7 @@ object AddedGames {
|
||||
)
|
||||
if (ranked.size > 256) ranked.clear()
|
||||
ranked[key] = now to result
|
||||
kept?.keepRank(folder, result, stamp)
|
||||
kept?.keepRank(folder, result)
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -201,7 +200,8 @@ object AddedGames {
|
||||
private val scanning = Any()
|
||||
|
||||
fun scan(context: Context): List<Game> = synchronized(scanning) {
|
||||
val cache = cache(context)
|
||||
val file = File(context.filesDir, AddedGamesCache.FILE)
|
||||
val cache = kept?.takeIf { it.file == file } ?: AddedGamesCache(file).also { kept = it }
|
||||
try {
|
||||
scanAll(context)
|
||||
} finally {
|
||||
@@ -209,13 +209,6 @@ object AddedGames {
|
||||
}
|
||||
}
|
||||
|
||||
private val keeping = Any()
|
||||
|
||||
private fun cache(context: Context): AddedGamesCache = synchronized(keeping) {
|
||||
val file = File(context.filesDir, AddedGamesCache.FILE)
|
||||
kept?.takeIf { it.file == file } ?: AddedGamesCache(file).also { kept = it }
|
||||
}
|
||||
|
||||
private fun scanAll(context: Context): List<Game> {
|
||||
val out = ArrayList<Game>()
|
||||
GamesFolderMigration.run(context)
|
||||
@@ -248,17 +241,11 @@ object AddedGames {
|
||||
return out.distinctBy { it.folder.canonicalPath }
|
||||
}
|
||||
|
||||
fun single(context: Context, folderPath: String, reuse: Boolean = false): Game? {
|
||||
fun single(context: Context, folderPath: String): Game? {
|
||||
val folder = File(folderPath)
|
||||
if (!folder.isDirectory || folderPath in SessionPrefs.removedAddedGames(context)) return null
|
||||
val out = ArrayList<Game>(1)
|
||||
val entry = AddedExes.list(context).firstOrNull { it.folder == folderPath }
|
||||
val cache = if (reuse) cache(context) else null
|
||||
try {
|
||||
scanGame(context, folder, out, single = entry, reuse = reuse)
|
||||
} finally {
|
||||
cache?.save()
|
||||
}
|
||||
scanGame(context, folder, out, single = AddedExes.list(context).firstOrNull { it.folder == folderPath })
|
||||
return out.firstOrNull()
|
||||
}
|
||||
|
||||
@@ -431,7 +418,7 @@ object AddedGames {
|
||||
private fun scanGame(context: Context, folder: File, out: MutableList<Game>, single: AddedExes.Entry? = null, reuse: Boolean = false) {
|
||||
run {
|
||||
val sidecar = StoreGameSidecar.read(folder)?.let { com.droiddeck.launcher.stores.StoreLaunch.adopt(folder, it) }
|
||||
if (sidecar?.store == Store.ROCKSTAR && sidecar.launcher != com.droiddeck.launcher.stores.StoreLaunch.LAUNCHER) return
|
||||
if (sidecar?.store == Store.ROCKSTAR && (!com.droiddeck.launcher.stores.rockstar.RockstarLaunch.supports(sidecar.id) || sidecar.launcher != com.droiddeck.launcher.stores.StoreLaunch.LAUNCHER)) return
|
||||
sidecar?.takeIf { it.id.isNotEmpty() }?.let { SessionPrefs.followStoreGame(context, "${it.store.id}:${it.id}", folder.path) { old -> !File(old).exists() } }
|
||||
val ranking = rank(folder, reuse)
|
||||
val candidates = ranking.exes
|
||||
@@ -542,17 +529,6 @@ object AddedGames {
|
||||
}
|
||||
}
|
||||
|
||||
class Listed(val appId: Long, val name: String, val launchOptions: String)
|
||||
|
||||
fun listed(context: Context): List<Listed>? = runCatching {
|
||||
val file = File(context.filesDir, "session/added-games.json")
|
||||
if (!file.isFile) return null
|
||||
val entries = org.json.JSONArray(file.readText())
|
||||
(0 until entries.length()).mapNotNull { i ->
|
||||
entries.optJSONObject(i)?.takeIf { it.has("appid") }?.let { Listed(it.optLong("appid") and 0xFFFFFFFFL, it.optString("name"), it.optString("launch")) }
|
||||
}
|
||||
}.getOrNull()
|
||||
|
||||
fun writeListing(context: Context, games: List<Game>,
|
||||
extra: List<JSONObject> = listOfNotNull(com.droiddeck.launcher.stores.epic.EpicClient.steamListing(context))): File {
|
||||
val file = File(context.filesDir, "session/added-games.json").apply { parentFile?.mkdirs() }
|
||||
|
||||
@@ -7,7 +7,7 @@ import java.io.File
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
internal class AddedGamesCache(val file: File) {
|
||||
private class Rank(val modified: Long, val declared: Long, val at: Long, val ranking: GameExePicker.Ranking)
|
||||
private class Rank(val modified: Long, val at: Long, val ranking: GameExePicker.Ranking)
|
||||
private class Name(val name: String, val at: Long)
|
||||
|
||||
private val ranks = ConcurrentHashMap<String, Rank>()
|
||||
@@ -22,7 +22,7 @@ internal class AddedGamesCache(val file: File) {
|
||||
val exes = o.getJSONArray("exes")
|
||||
val scores = o.getJSONArray("scores")
|
||||
require(exes.length() > 0 && exes.length() == scores.length())
|
||||
ranks[path] = Rank(o.getLong("modified"), o.optLong("declared"), o.getLong("at"), GameExePicker.Ranking(
|
||||
ranks[path] = Rank(o.getLong("modified"), o.getLong("at"), GameExePicker.Ranking(
|
||||
List(exes.length()) { File(exes.getString(it)) }, List(scores.length()) { scores.getInt(it) }, o.optBoolean("uncertain"),
|
||||
))
|
||||
}
|
||||
@@ -32,19 +32,19 @@ internal class AddedGamesCache(val file: File) {
|
||||
}
|
||||
}
|
||||
|
||||
fun rank(folder: File, declared: Long = 0): GameExePicker.Ranking? {
|
||||
fun rank(folder: File): GameExePicker.Ranking? {
|
||||
val kept = ranks[folder.path] ?: return null
|
||||
val age = System.currentTimeMillis() - kept.at
|
||||
val top = kept.ranking.exes.first()
|
||||
return kept.ranking.takeIf { kept.modified == folder.lastModified() && kept.declared == declared && age in 0 until KEEP_MS && top.isFile }
|
||||
return kept.ranking.takeIf { kept.modified == folder.lastModified() && age in 0 until KEEP_MS && top.isFile }
|
||||
}
|
||||
|
||||
fun keepRank(folder: File, ranking: GameExePicker.Ranking, declared: Long = 0) {
|
||||
fun keepRank(folder: File, ranking: GameExePicker.Ranking) {
|
||||
if (ranking.exes.isEmpty()) {
|
||||
if (ranks.remove(folder.path) != null) changed = true
|
||||
return
|
||||
}
|
||||
ranks[folder.path] = Rank(folder.lastModified(), declared, System.currentTimeMillis(), ranking)
|
||||
ranks[folder.path] = Rank(folder.lastModified(), System.currentTimeMillis(), ranking)
|
||||
changed = true
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ internal class AddedGamesCache(val file: File) {
|
||||
val oldest = System.currentTimeMillis() - KEEP_MS
|
||||
val keptRanks = JSONObject()
|
||||
ranks.forEach { (path, r) ->
|
||||
if (r.at >= oldest) keptRanks.put(path, JSONObject().put("modified", r.modified).put("declared", r.declared).put("at", r.at)
|
||||
if (r.at >= oldest) keptRanks.put(path, JSONObject().put("modified", r.modified).put("at", r.at)
|
||||
.put("exes", JSONArray(r.ranking.exes.map { it.path })).put("scores", JSONArray(r.ranking.scores))
|
||||
.put("uncertain", r.ranking.uncertain))
|
||||
}
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import android.content.Context
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
object AddedSoundtracks {
|
||||
private fun file(context: Context) = File(context.filesDir, "added-soundtracks.json")
|
||||
|
||||
class Entry(val path: String, val name: String, val id: Int = 0)
|
||||
|
||||
internal fun assignIds(list: List<Entry>): List<Entry> {
|
||||
val used = list.filter { it.id != 0 }.map { it.id }.toMutableSet()
|
||||
return list.map { e ->
|
||||
if (e.id != 0) e else {
|
||||
var id = idOf(e.path)
|
||||
while (id == 0 || !used.add(id)) id = (id + 1) or Int.MIN_VALUE
|
||||
Entry(e.path, e.name, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun entries(context: Context): List<Entry> = runCatching {
|
||||
val f = file(context).takeIf { it.isFile } ?: return emptyList()
|
||||
val array = JSONArray(f.readText())
|
||||
val raw = List(array.length()) { i -> array.getJSONObject(i).let { Entry(it.getString("path"), it.getString("name"), it.optInt("id", 0)) } }
|
||||
val ready = assignIds(raw)
|
||||
if (raw.any { it.id == 0 }) save(context, ready)
|
||||
ready
|
||||
}.getOrDefault(emptyList())
|
||||
|
||||
@Synchronized
|
||||
private fun save(context: Context, list: List<Entry>): Boolean =
|
||||
runCatching {
|
||||
val array = JSONArray()
|
||||
list.forEach { array.put(JSONObject().put("path", it.path).put("name", it.name).put("id", it.id)) }
|
||||
val f = file(context)
|
||||
val tmp = File(f.path + ".tmp")
|
||||
tmp.writeText(array.toString())
|
||||
if (tmp.renameTo(f)) true else { tmp.delete(); false }
|
||||
}.getOrDefault(false)
|
||||
|
||||
fun add(context: Context, folder: File): Boolean {
|
||||
if (!folder.isDirectory || Soundtrack.audioFiles(folder).isEmpty()) return false
|
||||
return synchronized(this) {
|
||||
val list = entries(context)
|
||||
list.any { it.path == folder.path } || save(context, assignIds(list + Entry(folder.path, folder.name)))
|
||||
}
|
||||
}
|
||||
|
||||
fun remove(context: Context, path: String): Boolean =
|
||||
synchronized(this) { save(context, entries(context).filterNot { it.path == path }) }
|
||||
|
||||
internal fun idOf(path: String): Int = path.hashCode() or Int.MIN_VALUE
|
||||
|
||||
fun games(context: Context): List<Library.SteamGame> = entries(context).mapNotNull { e ->
|
||||
val dir = File(e.path).takeIf { it.isDirectory } ?: return@mapNotNull null
|
||||
game(context, e, dir, e.id)
|
||||
}
|
||||
|
||||
private fun game(context: Context, e: Entry, dir: File, id: Int): Library.SteamGame {
|
||||
return Library.SteamGame(
|
||||
appId = id, name = e.name, art = SoundtrackCollectionArt.chosen(context, id) ?: Soundtrack.firstCover(context, dir), library = Library.ADDED, gameId = id.toLong() and 0xFFFFFFFFL,
|
||||
gameFiles = dir, source = Library.ADDED, soundtrack = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ object GameRemoval {
|
||||
fun steamFiles(game: Library.SteamGame): SteamFiles? {
|
||||
val dir = game.gameFiles ?: return null
|
||||
val common = dir.parentFile ?: return null
|
||||
if (common.name != (if (game.soundtrack) "music" else "common")) return null
|
||||
if (common.name != "common") return null
|
||||
val steamapps = common.parentFile ?: return null
|
||||
if (steamapps.name != "steamapps") return null
|
||||
val manifest = File(steamapps, "appmanifest_${game.appId}.acf")
|
||||
|
||||
@@ -19,10 +19,9 @@ object Library {
|
||||
val storeId: String? = null,
|
||||
val logo: File? = null,
|
||||
val installedAt: Long = 0L,
|
||||
val soundtrack: Boolean = false,
|
||||
) {
|
||||
fun withArt(art: File?, hero: File?, icon: File?, logo: File? = this.logo) =
|
||||
SteamGame(appId, name, art, library, gameId, hero, lastPlayed, gameFiles, protonPrefix, icon, source, storeId, logo, installedAt, soundtrack)
|
||||
SteamGame(appId, name, art, library, gameId, hero, lastPlayed, gameFiles, protonPrefix, icon, source, storeId, logo, installedAt)
|
||||
|
||||
val gameIdString: String get() = java.lang.Long.toUnsignedString(gameId)
|
||||
val launchKey: String get() = if (storeId != null) "$source:$storeId" else gameIdString
|
||||
@@ -39,7 +38,6 @@ object Library {
|
||||
const val BATTLENET_LAUNCHER = "battlenet-launcher"
|
||||
const val XBOX_CLOUD = "xbox-cloud"
|
||||
const val SOURCE_STEAM = "steam"
|
||||
const val SOURCE_COLLECTION = "collection"
|
||||
|
||||
class Rom(val name: String, val hostPath: File, val guestPath: String, val emulatorId: String, val art: File? = null)
|
||||
class Emulator(val id: String, val name: String, val system: String, val program: String, val installed: Boolean, val games: List<Rom>) {
|
||||
@@ -125,12 +123,9 @@ object Library {
|
||||
.distinctBy { runCatching { it.canonicalPath }.getOrDefault(it.absolutePath) }
|
||||
}
|
||||
|
||||
fun soundtracks(context: Context, arch: String = SessionPrefs.activeSteamClientArch(context)): List<SteamGame> =
|
||||
steamGames(context, arch = arch, withShared = false, soundtracks = true, soundtracksOnly = true)
|
||||
|
||||
fun steamGames(
|
||||
context: Context, strictRead: Boolean = false, arch: String = SessionPrefs.activeSteamClientArch(context),
|
||||
withShared: Boolean = true, soundtracks: Boolean = false, soundtracksOnly: Boolean = false,
|
||||
withShared: Boolean = true,
|
||||
onlyAppIds: Set<Int>? = null,
|
||||
): List<SteamGame> {
|
||||
val root = SessionPrefs.steamRoot(context, arch)
|
||||
@@ -151,19 +146,16 @@ object Library {
|
||||
val name = NAME.find(text)?.groupValues?.get(1)?.trim().orEmpty()
|
||||
val flags = STATE.find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0
|
||||
if (name.isEmpty() || flags and 4 == 0) return@forEach
|
||||
val installDir = INSTALL_DIR.find(text)?.groupValues?.get(1)?.trim()
|
||||
?.takeIf { it.isNotEmpty() && it != "." && it != ".." && '/' !in it && '\\' !in it }
|
||||
val gameFiles = installDir?.let { File(steamapps, "common/$it").takeIf(File::isDirectory) }
|
||||
val musicFiles = if (gameFiles == null) installDir?.let { File(steamapps, "music/$it").takeIf(File::isDirectory) } else null
|
||||
if (musicFiles != null && !soundtracks) return@forEach
|
||||
if (soundtracksOnly && musicFiles == null) return@forEach
|
||||
val images = SteamCacheImages(File(cache, appId.toString()))
|
||||
val art = images.find(STEAM_CAPSULES)
|
||||
val hero = images.find(STEAM_HEROES)
|
||||
val lastPlayed = LAST_PLAYED.find(text)?.groupValues?.get(1)?.toLongOrNull() ?: 0L
|
||||
val installDir = INSTALL_DIR.find(text)?.groupValues?.get(1)?.trim()
|
||||
?.takeIf { it.isNotEmpty() && it != "." && it != ".." && '/' !in it && '\\' !in it }
|
||||
val gameFiles = installDir?.let { File(steamapps, "common/$it").takeIf(File::isDirectory) }
|
||||
out[appId] = SteamGameArt.withOverrides(context, SteamGame(
|
||||
appId, name, art ?: musicFiles?.let { Soundtrack.firstCover(context, it) }, label, hero = hero, lastPlayed = lastPlayed,
|
||||
gameFiles = gameFiles ?: musicFiles, soundtrack = musicFiles != null,
|
||||
appId, name, art, label, hero = hero, lastPlayed = lastPlayed,
|
||||
gameFiles = gameFiles,
|
||||
protonPrefix = protonPrefix(context, appId.toLong(), library, roots),
|
||||
icon = images.icon(),
|
||||
logo = images.find(STEAM_LOGOS),
|
||||
@@ -185,7 +177,6 @@ object Library {
|
||||
strictRead = strictRead,
|
||||
arch = other,
|
||||
withShared = false,
|
||||
soundtracks = soundtracks,
|
||||
onlyAppIds = shared,
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
|
||||
@@ -1,308 +0,0 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import android.content.Context
|
||||
import android.media.MediaMetadataRetriever
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
object Soundtrack {
|
||||
class Track(
|
||||
val file: File, val title: String, val disc: Int, val number: Int, val durationMs: Long, val artist: String = "",
|
||||
val discLabel: String = disc.toString(),
|
||||
) {
|
||||
val id: String get() = file.path
|
||||
}
|
||||
|
||||
class Album(val disc: Map<Int, List<Track>>, val artist: String, val cover: File?) {
|
||||
val tracks: List<Track> get() = disc.values.flatten()
|
||||
val discs: List<Int> get() = disc.keys.toList()
|
||||
val multiDisc: Boolean get() = disc.size > 1
|
||||
val totalMs: Long get() = tracks.sumOf { it.durationMs }
|
||||
}
|
||||
|
||||
class Raw(
|
||||
val file: File, val folder: String, val tagDisc: Int?, val tagTrack: Int?, val tagTitle: String?, val tagArtist: String?,
|
||||
val durationMs: Long, val size: Long = file.length(),
|
||||
)
|
||||
|
||||
val EXTENSIONS = setOf("mp3", "flac", "ogg", "oga", "opus", "wav", "m4a", "aac")
|
||||
private val LOSSLESS = setOf("flac", "wav")
|
||||
private val COVERS = listOf("AlbumArtwork", "albumartwork", "cover", "Cover", "folder", "Folder", "front", "Front", "artwork", "Artwork")
|
||||
internal val COVER_EXT = listOf("png", "jpg", "jpeg", "webp")
|
||||
private val LEADING = Regex("^\\s*\\d+\\s*[.\\-_)]*\\s+")
|
||||
private val DIGITS = Regex("^\\s*(\\d+)")
|
||||
|
||||
fun isAudio(file: File): Boolean = file.isFile && file.extension.lowercase() in EXTENSIONS
|
||||
|
||||
fun cleanTitle(fileName: String): String {
|
||||
val base = fileName.substringBeforeLast('.', fileName).trim()
|
||||
val tail = if (" - " in base) base.substringAfterLast(" - ") else base
|
||||
val stripped = tail.replace(LEADING, "").trim()
|
||||
return stripped.ifEmpty { tail.ifEmpty { base } }
|
||||
}
|
||||
|
||||
internal fun leadingNumber(fileName: String): Int? = DIGITS.find(fileName.substringAfterLast(" - "))?.groupValues?.get(1)?.toIntOrNull()
|
||||
|
||||
private fun identity(r: Raw): String {
|
||||
val d = r.tagDisc
|
||||
val t = r.tagTrack
|
||||
if (d != null && t != null) return "n:$d:$t"
|
||||
val title = (r.tagTitle?.takeIf { it.isNotBlank() } ?: cleanTitle(r.file.name)).lowercase().filter { it.isLetterOrDigit() }
|
||||
return "t:$title:${leadingNumber(r.file.name)}"
|
||||
}
|
||||
|
||||
private fun better(a: Raw, b: Raw): Raw {
|
||||
val la = a.file.extension.lowercase() in LOSSLESS
|
||||
val lb = b.file.extension.lowercase() in LOSSLESS
|
||||
return when {
|
||||
la != lb -> if (la) a else b
|
||||
a.size != b.size -> if (a.size > b.size) a else b
|
||||
else -> if (a.file.path <= b.file.path) a else b
|
||||
}
|
||||
}
|
||||
|
||||
fun group(raws: List<Raw>): Map<Int, List<Track>> {
|
||||
if (raws.isEmpty()) return emptyMap()
|
||||
val unique = LinkedHashMap<String, Raw>()
|
||||
val home = HashMap<String, String>()
|
||||
val disc = HashMap<String, Int>()
|
||||
val track = HashMap<String, Int>()
|
||||
val title = HashMap<String, String>()
|
||||
for (r in raws) {
|
||||
val id = identity(r)
|
||||
unique[id] = unique[id]?.let { better(it, r) } ?: r
|
||||
if (r.folder.isNotEmpty() && home[id].isNullOrEmpty()) home[id] = r.folder
|
||||
r.tagDisc?.let { disc.putIfAbsent(id, it) }
|
||||
r.tagTrack?.let { track.putIfAbsent(id, it) }
|
||||
r.tagTitle?.takeIf { it.isNotBlank() }?.let { title.putIfAbsent(id, it) }
|
||||
}
|
||||
val kept = unique.map { (id, r) ->
|
||||
Raw(
|
||||
r.file, home[id] ?: r.folder, disc[id] ?: r.tagDisc, track[id] ?: r.tagTrack, title[id] ?: r.tagTitle, r.tagArtist,
|
||||
r.durationMs, r.size,
|
||||
)
|
||||
}
|
||||
val folders = kept.filter { it.tagDisc == null }.map { it.folder }.distinct().sortedWith(naturalOrder)
|
||||
val discs = kept.groupBy { r ->
|
||||
r.tagDisc ?: if (folders.size <= 1 && kept.none { it.tagDisc != null }) 0 else folders.indexOf(r.folder) + 1
|
||||
}
|
||||
return discs.toSortedMap().mapValues { (disc, list) ->
|
||||
list.sortedWith(
|
||||
compareBy<Raw>({ leadingNumber(it.file.name) ?: it.tagTrack ?: Int.MAX_VALUE }, { it.tagTrack ?: Int.MAX_VALUE }, { it.file.name.lowercase() }),
|
||||
).mapIndexed { i, r ->
|
||||
Track(
|
||||
r.file, r.tagTitle?.takeIf { it.isNotBlank() } ?: cleanTitle(r.file.name), disc, i + 1,
|
||||
r.durationMs, r.tagArtist.orEmpty(), labelOf(r, disc),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private val FOLDER_LABEL = Regex("[0-9][0-9 +&,.\\-]*")
|
||||
|
||||
private fun labelOf(r: Raw, disc: Int): String {
|
||||
if (r.tagDisc != null) return disc.toString()
|
||||
val name = r.folder.substringAfterLast('/')
|
||||
return if (FOLDER_LABEL.matches(name)) name else disc.toString()
|
||||
}
|
||||
|
||||
private val naturalOrder = Comparator<String> { a, b ->
|
||||
val x = Regex("\\d+|\\D+").findAll(a.lowercase()).map { it.value }.toList()
|
||||
val y = Regex("\\d+|\\D+").findAll(b.lowercase()).map { it.value }.toList()
|
||||
var i = 0
|
||||
var out = 0
|
||||
while (out == 0 && i < minOf(x.size, y.size)) {
|
||||
val nx = x[i].toBigIntegerOrNull()
|
||||
val ny = y[i].toBigIntegerOrNull()
|
||||
out = if (nx != null && ny != null) nx.compareTo(ny) else x[i].compareTo(y[i])
|
||||
i++
|
||||
}
|
||||
if (out != 0) out else x.size.compareTo(y.size)
|
||||
}
|
||||
|
||||
fun cover(dir: File): File? {
|
||||
for (name in COVERS) for (ext in COVER_EXT) File(dir, "$name.$ext").takeIf { it.isFile }?.let { return it }
|
||||
return dir.listFiles()?.filter { it.isFile && it.extension.lowercase() in COVER_EXT }?.minByOrNull { it.name.lowercase() }
|
||||
}
|
||||
|
||||
private fun parseNumber(value: String?): Int? = value?.substringBefore('/')?.trim()?.toIntOrNull()
|
||||
|
||||
private fun read(file: File, root: File): Raw {
|
||||
val folder = file.parentFile?.let { parent ->
|
||||
if (parent.path == root.path) "" else parent.path.removePrefix(root.path).trimStart('/')
|
||||
}.orEmpty()
|
||||
val retriever = MediaMetadataRetriever()
|
||||
return try {
|
||||
retriever.setDataSource(file.path)
|
||||
Raw(
|
||||
file, folder,
|
||||
parseNumber(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DISC_NUMBER)),
|
||||
parseNumber(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CD_TRACK_NUMBER)),
|
||||
retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE),
|
||||
retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST)
|
||||
?: retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST),
|
||||
retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull() ?: 0L,
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
Raw(file, folder, null, null, null, null, 0L)
|
||||
} finally {
|
||||
runCatching { retriever.release() }
|
||||
}
|
||||
}
|
||||
|
||||
private fun cacheFile(context: Context, root: File) = File(context.filesDir, "soundtrack-index/${root.path.hashCode().toUInt()}.json")
|
||||
|
||||
private fun fromCache(context: Context, root: File, files: List<File>): List<Raw>? = runCatching {
|
||||
val f = cacheFile(context, root).takeIf { it.isFile } ?: return null
|
||||
val json = JSONObject(f.readText())
|
||||
if (json.optString("root") != root.path) return null
|
||||
val rows = json.getJSONArray("rows")
|
||||
val byPath = HashMap<String, JSONObject>()
|
||||
for (i in 0 until rows.length()) rows.getJSONObject(i).let { byPath[it.getString("p")] = it }
|
||||
if (byPath.size != files.size) return null
|
||||
files.map { file ->
|
||||
val row = byPath[file.path] ?: return null
|
||||
if (row.getLong("s") != file.length() || row.getLong("m") != file.lastModified()) return null
|
||||
Raw(
|
||||
file, row.getString("f"), row.optInt("d", -1).takeIf { it >= 0 }, row.optInt("n", -1).takeIf { it >= 0 },
|
||||
row.optString("t").takeIf { it.isNotEmpty() }, row.optString("a").takeIf { it.isNotEmpty() }, row.optLong("l"),
|
||||
)
|
||||
}
|
||||
}.getOrNull()
|
||||
|
||||
private fun toCache(context: Context, root: File, raws: List<Raw>) {
|
||||
runCatching {
|
||||
val rows = JSONArray()
|
||||
for (r in raws) rows.put(
|
||||
JSONObject().put("p", r.file.path).put("s", r.file.length()).put("m", r.file.lastModified()).put("f", r.folder)
|
||||
.put("d", r.tagDisc ?: -1).put("n", r.tagTrack ?: -1).put("t", r.tagTitle.orEmpty()).put("a", r.tagArtist.orEmpty())
|
||||
.put("l", r.durationMs),
|
||||
)
|
||||
val f = cacheFile(context, root)
|
||||
f.parentFile?.mkdirs()
|
||||
val tmp = File(f.path + ".tmp")
|
||||
tmp.writeText(JSONObject().put("root", root.path).put("rows", rows).toString())
|
||||
if (!tmp.renameTo(f)) tmp.delete()
|
||||
}
|
||||
}
|
||||
|
||||
fun audioFiles(root: File): List<File> {
|
||||
val out = ArrayList<File>()
|
||||
fun walk(dir: File, depth: Int) {
|
||||
val children = dir.listFiles() ?: return
|
||||
for (c in children.sortedBy { it.name.lowercase() }) {
|
||||
if (c.isDirectory) { if (depth < 4) walk(c, depth + 1) } else if (isAudio(c)) out += c
|
||||
}
|
||||
}
|
||||
walk(root, 0)
|
||||
return out
|
||||
}
|
||||
|
||||
private fun coverCache(context: Context, root: File): File {
|
||||
val digest = java.security.MessageDigest.getInstance("SHA-256").digest(root.path.toByteArray(Charsets.UTF_8))
|
||||
val key = digest.take(16).joinToString("") { "%02x".format(it) }
|
||||
return File(context.filesDir, "soundtrack-index/cover-$key.jpg")
|
||||
}
|
||||
|
||||
fun cachedCover(context: Context, root: File): File? = coverCache(context, root).takeIf { it.isFile && it.length() > 0L }
|
||||
|
||||
private fun embeddedBytes(file: File): ByteArray? = runCatching {
|
||||
val retriever = MediaMetadataRetriever()
|
||||
try {
|
||||
retriever.setDataSource(file.path)
|
||||
retriever.embeddedPicture
|
||||
} finally {
|
||||
runCatching { retriever.release() }
|
||||
}
|
||||
}.getOrNull()?.takeIf { it.isNotEmpty() }
|
||||
|
||||
private fun hashOf(bytes: ByteArray): String =
|
||||
java.security.MessageDigest.getInstance("SHA-256").digest(bytes).take(16).joinToString("") { "%02x".format(it) }
|
||||
|
||||
private fun embeddedCover(context: Context, root: File, files: List<File>): File? {
|
||||
cachedCover(context, root)?.let { return it }
|
||||
val miss = File(coverCache(context, root).path + ".none")
|
||||
val probed = files.take(8)
|
||||
val signature = hashOf(probed.joinToString("\n") { "${it.path}|${it.length()}|${it.lastModified()}" }.toByteArray(Charsets.UTF_8))
|
||||
if (runCatching { miss.isFile && miss.readText().trim() == signature }.getOrDefault(false)) return null
|
||||
for (file in probed) {
|
||||
val bytes = embeddedBytes(file) ?: continue
|
||||
val out = coverCache(context, root)
|
||||
runCatching {
|
||||
out.parentFile?.mkdirs()
|
||||
out.writeBytes(bytes)
|
||||
}.onSuccess { return out }
|
||||
}
|
||||
runCatching {
|
||||
miss.parentFile?.mkdirs()
|
||||
miss.writeText(signature)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
fun firstCover(context: Context, root: File): File? = cover(root) ?: embeddedCover(context, root, audioFiles(root))
|
||||
|
||||
@Synchronized
|
||||
fun trackCover(context: Context, file: File): File? {
|
||||
val dir = File(context.filesDir, "soundtrack-index/track-covers")
|
||||
val marker = File(dir, "t-" + hashOf("${file.path}|${file.length()}|${file.lastModified()}".toByteArray(Charsets.UTF_8)))
|
||||
if (marker.isFile) {
|
||||
val name = runCatching { marker.readText().trim() }.getOrDefault("")
|
||||
if (name.isEmpty()) return null
|
||||
File(dir, name).takeIf { it.isFile && it.length() > 0L }?.let {
|
||||
val now = System.currentTimeMillis()
|
||||
marker.setLastModified(now)
|
||||
it.setLastModified(now)
|
||||
return it
|
||||
}
|
||||
}
|
||||
val bytes = embeddedBytes(file)
|
||||
return runCatching {
|
||||
dir.mkdirs()
|
||||
if (bytes == null) {
|
||||
marker.writeText("")
|
||||
prune(dir, setOf(marker.name))
|
||||
null
|
||||
} else {
|
||||
val out = File(dir, "c-" + hashOf(bytes) + ".jpg")
|
||||
if (!out.isFile || out.length() == 0L) out.writeBytes(bytes)
|
||||
marker.writeText(out.name)
|
||||
prune(dir, setOf(marker.name, out.name))
|
||||
out
|
||||
}
|
||||
}.getOrNull()
|
||||
}
|
||||
|
||||
private const val TRACK_COVER_BYTES = 64L * 1024 * 1024
|
||||
private const val TRACK_COVER_FILES = 2000
|
||||
|
||||
private fun prune(dir: File, keep: Set<String>) {
|
||||
val all = dir.listFiles()?.filter { it.isFile } ?: return
|
||||
var bytes = all.sumOf { it.length() }
|
||||
var count = all.size
|
||||
for (f in all.sortedBy { it.lastModified() }) {
|
||||
if (bytes <= TRACK_COVER_BYTES && count <= TRACK_COVER_FILES) break
|
||||
if (f.name in keep) continue
|
||||
bytes -= f.length()
|
||||
count--
|
||||
f.delete()
|
||||
}
|
||||
}
|
||||
|
||||
fun load(context: Context, root: File, coverHint: File? = null): Album {
|
||||
val files = audioFiles(root)
|
||||
val raws = fromCache(context, root, files) ?: files.map { read(it, root) }.also { toCache(context, root, it) }
|
||||
val disc = SoundtrackOrder.apply(context, root, group(raws))
|
||||
val artist = disc.values.flatten().map { it.artist }.filter { it.isNotBlank() }.groupingBy { it }.eachCount().maxByOrNull { it.value }?.key.orEmpty()
|
||||
return Album(disc, artist, coverHint ?: cover(root) ?: embeddedCover(context, root, files))
|
||||
}
|
||||
|
||||
fun formatLength(ms: Long): String {
|
||||
val total = ms / 1000
|
||||
val h = total / 3600
|
||||
val m = (total % 3600) / 60
|
||||
val s = total % 60
|
||||
return if (h > 0) "%d:%02d:%02d".format(h, m, s) else "%d:%02d".format(m, s)
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import android.content.Context
|
||||
import java.io.File
|
||||
|
||||
object SoundtrackCollectionArt {
|
||||
internal fun dir(context: Context, id: Int) = File(context.filesDir, "soundtrack-art/$id")
|
||||
|
||||
private fun sourceFile(context: Context, id: Int) = File(dir(context, id), "source")
|
||||
|
||||
fun chosen(context: Context, id: Int): File? = dir(context, id).takeIf { it.isDirectory }?.let { AddedGameArt.chosen(it, AddedGameArt.Slot.COVER) }
|
||||
|
||||
fun source(context: Context, id: Int): String =
|
||||
sourceFile(context, id).takeIf { it.isFile }?.readText()?.trim().orEmpty().substringAfter('|', "")
|
||||
|
||||
fun options(context: Context, id: Int, root: File?): List<AddedGameArt.Option> {
|
||||
val paths = if (root != null) {
|
||||
val images = root.listFiles()?.filter { it.isFile && it.extension.lowercase() in Soundtrack.COVER_EXT }?.sortedBy { it.name.lowercase() }.orEmpty()
|
||||
(images + listOfNotNull(Soundtrack.firstCover(context, root))).map { it.path }
|
||||
} else SoundtrackCollections.tracksOf(id).map { it.cover }
|
||||
return paths.filter { it.isNotEmpty() && File(it).isFile }.distinct().map { AddedGameArt.Option(AddedGameArt.FOLDER, it, it) }
|
||||
}
|
||||
|
||||
fun choose(context: Context, id: Int, option: AddedGameArt.Option): Boolean {
|
||||
val folder = dir(context, id)
|
||||
val fresh = AddedGameArt.storeNew(folder, AddedGameArt.Slot.COVER, option) ?: return false
|
||||
AddedGameArt.dropOlder(folder, AddedGameArt.Slot.COVER, fresh)
|
||||
sourceFile(context, id).writeText(option.group + "|" + option.full)
|
||||
return true
|
||||
}
|
||||
|
||||
fun reset(context: Context, id: Int) {
|
||||
chosen(context, id)?.delete()
|
||||
sourceFile(context, id).delete()
|
||||
}
|
||||
|
||||
fun describe(context: Context, id: Int, root: File? = null): List<AddedGameArt.SlotState> {
|
||||
val own = chosen(context, id)
|
||||
val state = if (own != null) AddedGameArt.SlotState(AddedGameArt.Slot.COVER, own, AddedGameArt.FILE, true)
|
||||
else {
|
||||
val auto = if (root != null) Soundtrack.firstCover(context, root) else SoundtrackCollections.autoCover(id)
|
||||
AddedGameArt.SlotState(AddedGameArt.Slot.COVER, auto, if (auto != null) AddedGameArt.FOLDER else AddedGameArt.AUTO, false)
|
||||
}
|
||||
return listOf(state)
|
||||
}
|
||||
|
||||
fun clear(context: Context, id: Int) {
|
||||
dir(context, id).deleteRecursively()
|
||||
}
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
object SoundtrackCollections {
|
||||
const val FAVORITES_ID = 2_000_000_000
|
||||
|
||||
class TrackRef(val path: String, val title: String, val artist: String, val album: String, val durationMs: Long, val cover: String = "")
|
||||
class Collection(val id: Int, val name: String, val tracks: List<TrackRef>)
|
||||
class Snapshot(val favorites: List<TrackRef>, val collections: List<Collection>)
|
||||
|
||||
private val state = mutableStateOf(Snapshot(emptyList(), emptyList()))
|
||||
private var loaded = false
|
||||
private val writer = Executors.newSingleThreadExecutor { r -> Thread(r, "soundtrack-collections").apply { isDaemon = true } }
|
||||
|
||||
val snapshot: Snapshot get() = state.value
|
||||
|
||||
private fun file(context: Context) = File(context.filesDir, "soundtrack-collections.json")
|
||||
|
||||
internal fun toggled(list: List<TrackRef>, ref: TrackRef): List<TrackRef> =
|
||||
if (list.any { it.path == ref.path }) list.filterNot { it.path == ref.path } else list + ref
|
||||
|
||||
internal fun merged(list: List<TrackRef>, add: List<TrackRef>): List<TrackRef> {
|
||||
val have = list.mapTo(HashSet()) { it.path }
|
||||
return list + add.filter { have.add(it.path) }
|
||||
}
|
||||
|
||||
internal fun cleanName(raw: String): String = raw.trim().replace(Regex("\\s+"), " ")
|
||||
|
||||
internal fun nameTaken(collections: List<Collection>, name: String, except: Int? = null): Boolean =
|
||||
collections.any { it.id != except && it.name.equals(name, ignoreCase = true) }
|
||||
|
||||
internal fun nextId(collections: List<Collection>): Int =
|
||||
(collections.maxOfOrNull { it.id } ?: FAVORITES_ID).coerceAtLeast(FAVORITES_ID) + 1
|
||||
|
||||
private fun encode(s: Snapshot): String {
|
||||
fun refs(list: List<TrackRef>) = JSONArray().also { array ->
|
||||
list.forEach {
|
||||
array.put(
|
||||
JSONObject().put("path", it.path).put("title", it.title).put("artist", it.artist).put("album", it.album)
|
||||
.put("duration", it.durationMs).put("cover", it.cover),
|
||||
)
|
||||
}
|
||||
}
|
||||
val collections = JSONArray()
|
||||
s.collections.forEach { collections.put(JSONObject().put("id", it.id).put("name", it.name).put("tracks", refs(it.tracks))) }
|
||||
return JSONObject().put("favorites", refs(s.favorites)).put("collections", collections).toString()
|
||||
}
|
||||
|
||||
private fun decode(text: String): Snapshot {
|
||||
fun refs(array: JSONArray?): List<TrackRef> = if (array == null) emptyList() else List(array.length()) { i ->
|
||||
array.getJSONObject(i).let {
|
||||
TrackRef(it.getString("path"), it.optString("title"), it.optString("artist"), it.optString("album"), it.optLong("duration"), it.optString("cover"))
|
||||
}
|
||||
}
|
||||
val root = JSONObject(text)
|
||||
val collections = root.optJSONArray("collections")
|
||||
return Snapshot(
|
||||
refs(root.optJSONArray("favorites")),
|
||||
if (collections == null) emptyList() else List(collections.length()) { i ->
|
||||
collections.getJSONObject(i).let { Collection(it.getInt("id"), it.getString("name"), refs(it.optJSONArray("tracks"))) }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun load(context: Context) {
|
||||
if (loaded) return
|
||||
loaded = true
|
||||
val f = file(context)
|
||||
if (f.isFile) runCatching { state.value = decode(f.readText()) }
|
||||
}
|
||||
|
||||
private fun commit(context: Context, next: Snapshot) {
|
||||
state.value = next
|
||||
val f = file(context)
|
||||
val json = encode(next)
|
||||
writer.execute {
|
||||
runCatching {
|
||||
val tmp = File(f.path + ".tmp")
|
||||
tmp.writeText(json)
|
||||
if (!tmp.renameTo(f)) tmp.delete()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun tracksOf(id: Int): List<TrackRef> =
|
||||
if (id == FAVORITES_ID) snapshot.favorites else snapshot.collections.firstOrNull { it.id == id }?.tracks.orEmpty()
|
||||
|
||||
fun isFavorite(path: String): Boolean = snapshot.favorites.any { it.path == path }
|
||||
|
||||
@Synchronized
|
||||
fun toggleFavorite(context: Context, ref: TrackRef) {
|
||||
load(context)
|
||||
val s = snapshot
|
||||
commit(context, Snapshot(toggled(s.favorites, ref), s.collections))
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun create(context: Context, rawName: String, tracks: List<TrackRef>): Int? {
|
||||
load(context)
|
||||
val s = snapshot
|
||||
val name = cleanName(rawName)
|
||||
if (name.isEmpty() || nameTaken(s.collections, name)) return null
|
||||
val id = nextId(s.collections)
|
||||
commit(context, Snapshot(s.favorites, s.collections + Collection(id, name, merged(emptyList(), tracks))))
|
||||
return id
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun rename(context: Context, id: Int, rawName: String): Boolean {
|
||||
load(context)
|
||||
val s = snapshot
|
||||
val name = cleanName(rawName)
|
||||
if (id == FAVORITES_ID || name.isEmpty() || nameTaken(s.collections, name, id)) return false
|
||||
commit(context, Snapshot(s.favorites, s.collections.map { if (it.id == id) Collection(id, name, it.tracks) else it }))
|
||||
return true
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun delete(context: Context, id: Int) {
|
||||
load(context)
|
||||
val s = snapshot
|
||||
if (id == FAVORITES_ID) return
|
||||
commit(context, Snapshot(s.favorites, s.collections.filterNot { it.id == id }))
|
||||
SoundtrackCollectionArt.clear(context, id)
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun add(context: Context, id: Int, tracks: List<TrackRef>) {
|
||||
load(context)
|
||||
val s = snapshot
|
||||
if (id == FAVORITES_ID) commit(context, Snapshot(merged(s.favorites, tracks), s.collections))
|
||||
else commit(context, Snapshot(s.favorites, s.collections.map { if (it.id == id) Collection(id, it.name, merged(it.tracks, tracks)) else it }))
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun remove(context: Context, id: Int, paths: Set<String>) {
|
||||
load(context)
|
||||
val s = snapshot
|
||||
if (id == FAVORITES_ID) commit(context, Snapshot(s.favorites.filterNot { it.path in paths }, s.collections))
|
||||
else commit(context, Snapshot(s.favorites, s.collections.map { if (it.id == id) Collection(id, it.name, it.tracks.filterNot { t -> t.path in paths }) else it }))
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun reorder(context: Context, id: Int, ordered: List<String>) {
|
||||
load(context)
|
||||
val s = snapshot
|
||||
fun arrange(list: List<TrackRef>): List<TrackRef> {
|
||||
val byPath = list.associateBy { it.path }
|
||||
val placed = ordered.mapNotNull { byPath[it] }
|
||||
val named = ordered.toSet()
|
||||
val rest = list.filter { it.path !in named }
|
||||
return placed + rest
|
||||
}
|
||||
if (id == FAVORITES_ID) commit(context, Snapshot(arrange(s.favorites), s.collections))
|
||||
else commit(context, Snapshot(s.favorites, s.collections.map { if (it.id == id) Collection(id, it.name, arrange(it.tracks)) else it }))
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun refresh() {
|
||||
state.value = Snapshot(state.value.favorites, state.value.collections)
|
||||
}
|
||||
|
||||
internal fun autoCover(id: Int): File? = coverOf(tracksOf(id))
|
||||
|
||||
private fun coverOf(tracks: List<TrackRef>): File? =
|
||||
tracks.firstNotNullOfOrNull { t -> t.cover.takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile } }
|
||||
|
||||
private fun game(context: Context, id: Int, name: String, tracks: List<TrackRef>): Library.SteamGame = Library.SteamGame(
|
||||
appId = id, name = name, art = SoundtrackCollectionArt.chosen(context, id) ?: coverOf(tracks), library = Library.ADDED, gameId = id.toLong(),
|
||||
source = Library.SOURCE_COLLECTION, soundtrack = true,
|
||||
)
|
||||
|
||||
fun games(context: Context, favoritesLabel: String): List<Library.SteamGame> {
|
||||
val s = snapshot
|
||||
return listOf(game(context, FAVORITES_ID, favoritesLabel, s.favorites)) + s.collections.map { game(context, it.id, it.name, it.tracks) }
|
||||
}
|
||||
|
||||
fun album(context: Context, id: Int): Soundtrack.Album {
|
||||
val tracks = tracksOf(id).filter { File(it.path).isFile }.mapIndexed { i, t ->
|
||||
Soundtrack.Track(File(t.path), t.title, 1, i + 1, t.durationMs, t.artist)
|
||||
}
|
||||
return Soundtrack.Album(mapOf(1 to tracks), "", SoundtrackCollectionArt.chosen(context, id))
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import android.content.Context
|
||||
|
||||
object SoundtrackIndex {
|
||||
class Hit(val ref: SoundtrackCollections.TrackRef, val game: Library.SteamGame)
|
||||
|
||||
private var cacheKey = ""
|
||||
private var cache: List<Hit> = emptyList()
|
||||
|
||||
private fun fingerprint(dir: java.io.File?): Long =
|
||||
if (dir == null) 0L else Soundtrack.audioFiles(dir).fold(17L) { h, f -> 31 * (31 * (31 * h + f.path.hashCode()) + f.length()) + f.lastModified() }
|
||||
|
||||
fun build(context: Context, games: List<Library.SteamGame>): List<Hit> {
|
||||
val roots = games.filter { it.gameFiles != null }
|
||||
val key = roots.joinToString("|") { "${it.appId}:${it.gameFiles?.path}:${it.art?.path}:${fingerprint(it.gameFiles)}" }
|
||||
synchronized(this) { if (key == cacheKey) return cache }
|
||||
val hits = roots.flatMap { g ->
|
||||
val dir = g.gameFiles ?: return@flatMap emptyList()
|
||||
val album = Soundtrack.load(context, dir, g.art)
|
||||
val cover = (g.art ?: album.cover)?.path.orEmpty()
|
||||
album.tracks.map { t ->
|
||||
Hit(SoundtrackCollections.TrackRef(t.file.path, t.title, t.artist.ifBlank { album.artist }, g.name, t.durationMs, cover), g)
|
||||
}
|
||||
}
|
||||
synchronized(this) {
|
||||
cacheKey = key
|
||||
cache = hits
|
||||
}
|
||||
return hits
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
object SoundtrackOrder {
|
||||
private val changes = mutableIntStateOf(0)
|
||||
private var cache: Map<String, List<String>>? = null
|
||||
private val writer = Executors.newSingleThreadExecutor { r -> Thread(r, "soundtrack-order").apply { isDaemon = true } }
|
||||
|
||||
val version: Int get() = changes.intValue
|
||||
|
||||
private fun file(context: Context) = File(context.filesDir, "soundtrack-order.json")
|
||||
|
||||
@Synchronized
|
||||
private fun read(context: Context): Map<String, List<String>> {
|
||||
cache?.let { return it }
|
||||
val out = HashMap<String, List<String>>()
|
||||
val f = file(context)
|
||||
if (f.isFile) runCatching {
|
||||
val json = JSONObject(f.readText())
|
||||
for (key in json.keys()) {
|
||||
val array = json.getJSONArray(key)
|
||||
out[key] = List(array.length()) { array.getString(it) }
|
||||
}
|
||||
}
|
||||
cache = out
|
||||
return out
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun set(context: Context, root: File, paths: List<String>) {
|
||||
val next = HashMap(read(context))
|
||||
next[root.path] = paths
|
||||
cache = next
|
||||
val body = JSONObject().also { json -> next.forEach { (k, v) -> json.put(k, JSONArray(v)) } }.toString()
|
||||
val target = file(context)
|
||||
writer.execute {
|
||||
val tmp = File(target.path + ".tmp")
|
||||
runCatching {
|
||||
tmp.writeText(body)
|
||||
if (!tmp.renameTo(target)) tmp.delete()
|
||||
}
|
||||
}
|
||||
changes.intValue++
|
||||
}
|
||||
|
||||
internal fun ordered(disc: Map<Int, List<Soundtrack.Track>>, order: List<String>): Map<Int, List<Soundtrack.Track>> {
|
||||
if (order.isEmpty()) return disc
|
||||
val index = HashMap<String, Int>()
|
||||
order.forEachIndexed { i, p -> index.putIfAbsent(p, i) }
|
||||
return disc.mapValues { (_, list) ->
|
||||
list.sortedBy { index[it.file.path] ?: Int.MAX_VALUE }.mapIndexed { i, t ->
|
||||
Soundtrack.Track(t.file, t.title, t.disc, i + 1, t.durationMs, t.artist, t.discLabel)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun apply(context: Context, root: File, disc: Map<Int, List<Soundtrack.Track>>): Map<Int, List<Soundtrack.Track>> {
|
||||
val order = read(context)[root.path] ?: return disc
|
||||
return ordered(disc, order)
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.ShortcutInfo
|
||||
import android.content.pm.ShortcutManager
|
||||
import android.graphics.drawable.Icon
|
||||
import android.net.Uri
|
||||
import android.widget.Toast
|
||||
import com.droiddeck.launcher.FrontEndActivity
|
||||
import com.droiddeck.launcher.LauncherIcon
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
object SoundtrackShortcuts {
|
||||
private val linkPattern = Regex("droiddeck://soundtrack/(-?[0-9]{1,11})")
|
||||
|
||||
fun uri(appId: Int): String = "droiddeck://soundtrack/$appId"
|
||||
|
||||
fun parse(link: String?): Int? = link?.let { linkPattern.matchEntire(it)?.groupValues?.get(1)?.toIntOrNull() }
|
||||
|
||||
fun read(intent: Intent): Int? = if (intent.action == Intent.ACTION_VIEW) parse(intent.dataString) else null
|
||||
|
||||
private fun info(context: Context, game: Library.SteamGame): ShortcutInfo {
|
||||
val name = game.name.ifBlank { context.getString(R.string.app_name) }
|
||||
val icon = GameShortcuts.iconBitmap(game)?.let(Icon::createWithBitmap) ?: Icon.createWithResource(context, R.mipmap.ic_launcher)
|
||||
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uri(game.appId)), context, FrontEndActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||
return ShortcutInfo.Builder(context, "soundtrack:${game.appId}")
|
||||
.setActivity(LauncherIcon.activity(context))
|
||||
.setShortLabel(name.take(40)).setLongLabel(name).setIcon(icon).setIntent(intent).build()
|
||||
}
|
||||
|
||||
fun pin(activity: Activity, game: Library.SteamGame) {
|
||||
val manager = activity.getSystemService(ShortcutManager::class.java)
|
||||
val requested = runCatching {
|
||||
manager.isRequestPinShortcutSupported && manager.requestPinShortcut(info(activity, game), null)
|
||||
}.getOrDefault(false)
|
||||
if (!requested) Toast.makeText(activity, R.string.game_shortcut_unsupported, Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
object SoundtrackTracks {
|
||||
enum class Sort { DEFAULT, TITLE_ASC, TITLE_DESC, LONGEST, SHORTEST }
|
||||
|
||||
fun <T> sort(items: List<T>, sort: Sort, title: (T) -> String, duration: (T) -> Long): List<T> = when (sort) {
|
||||
Sort.DEFAULT -> items
|
||||
Sort.TITLE_ASC -> items.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER, title))
|
||||
Sort.TITLE_DESC -> items.sortedWith(compareByDescending(String.CASE_INSENSITIVE_ORDER, title))
|
||||
Sort.LONGEST -> items.sortedByDescending(duration)
|
||||
Sort.SHORTEST -> items.sortedBy(duration)
|
||||
}
|
||||
|
||||
fun matches(query: String, vararg fields: String): Boolean {
|
||||
val words = query.trim().lowercase().split(' ').filter { it.isNotEmpty() }
|
||||
if (words.isEmpty()) return true
|
||||
val haystack = fields.map { it.lowercase() }
|
||||
return words.all { word -> haystack.any { it.contains(word) } }
|
||||
}
|
||||
|
||||
fun rank(query: String, title: String): Int {
|
||||
val q = query.trim().lowercase()
|
||||
val t = title.lowercase()
|
||||
return when {
|
||||
t == q -> 0
|
||||
t.startsWith(q) -> 1
|
||||
else -> 2
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,11 @@ object SteamGameArt {
|
||||
val icon = chosenFile(context, game.appId, AddedGameArt.Slot.ICON)
|
||||
val logo = chosenFile(context, game.appId, AddedGameArt.Slot.LOGO)
|
||||
if (cover == null && hero == null && icon == null && logo == null) return game
|
||||
return game.withArt(cover ?: game.art, hero ?: game.hero, icon ?: game.icon, logo ?: game.logo)
|
||||
return Library.SteamGame(
|
||||
game.appId, game.name, cover ?: game.art, game.library, game.gameId,
|
||||
hero ?: game.hero, game.lastPlayed, game.gameFiles, game.protonPrefix, icon ?: game.icon, game.source, game.storeId,
|
||||
logo ?: game.logo,
|
||||
)
|
||||
}
|
||||
|
||||
fun chosenSource(context: Context, appId: Int, slot: AddedGameArt.Slot): Pair<String, String> {
|
||||
|
||||
@@ -7,21 +7,15 @@ internal object DroidDeckHudConfig {
|
||||
val DEFAULTS: Map<String, String> = linkedMapOf(
|
||||
"hudSize" to "minimal", "hudLocked" to "1", "hudSnap" to "1", "hudScale" to "100", "hudDock" to "none", "hudOpacity" to "80", "hudColor" to "mid",
|
||||
"hudOutline" to "40", "hudOutlineAccent" to "1",
|
||||
"showGpuModel" to "1", "showGPULoad" to "1", "showCPUUsage" to "1", "showCPULoad" to "1",
|
||||
"showPerCore" to "1", "showTemp" to "1", "showBatteryTemp" to "1", "showGpuTemp" to "0",
|
||||
"showVram" to "1", "showRAM" to "1", "showSwap" to "1", "showBattery" to "0", "showBatteryTime" to "0", "showPower" to "1",
|
||||
"showFPS" to "1", "showFPSGraph" to "1", "fpsDecimal" to "1",
|
||||
"showLatency" to "1", "showAvg" to "1", "showLow1" to "1", "showLow01" to "1", "showLow001" to "1",
|
||||
"showEngine" to "1", "showRenderer" to "1",
|
||||
"showDisplay" to "1", "showHdr" to "1", "showNet" to "1", "showResolution" to "1",
|
||||
"showProton" to "1", "showSession" to "1", "showClock" to "1", "hudOrder" to "",
|
||||
"showFPS" to "1", "showFPSGraph" to "1", "showCPUUsage" to "1", "showCPULoad" to "1", "showGPULoad" to "1",
|
||||
"showVram" to "1", "showRAM" to "1", "showPower" to "1", "showTemp" to "1", "showBatteryTemp" to "1",
|
||||
"showGpuTemp" to "0", "showBattery" to "0", "showLow1" to "1", "showLow01" to "1", "showLow001" to "1", "fpsDecimal" to "1", "showPerCore" to "1",
|
||||
"showSwap" to "1", "showNet" to "1", "showResolution" to "1", "showProton" to "1", "showSession" to "1",
|
||||
"showClock" to "1", "showEngine" to "1", "showRenderer" to "1", "showGpuModel" to "1",
|
||||
"tempUnit" to "c", "tempBands" to "1", "tempAuto" to "1", "tempRedCpu" to "90", "tempRedGpu" to "90", "tempRedBat" to "48",
|
||||
)
|
||||
|
||||
private val NOT_READINGS = setOf("showCPULoad", "showRenderer", "fpsDecimal")
|
||||
|
||||
/** Orders saved before the GPU switch was named after the alias the HUD actually reads. */
|
||||
private val RENAMED = mapOf("showGPU" to "showGPULoad")
|
||||
private val TWINS = mapOf("showCPUUsage" to "showCPULoad", "showTemp" to "showBatteryTemp", "showEngine" to "showRenderer")
|
||||
|
||||
fun load(context: Context): MutableMap<String, String> {
|
||||
val values = LinkedHashMap(DEFAULTS)
|
||||
@@ -42,31 +36,7 @@ internal object DroidDeckHudConfig {
|
||||
val values = load(context)
|
||||
if (key !in DEFAULTS) return values
|
||||
values[key] = value
|
||||
SessionPrefs.setDroidDeckHudConfig(context, encode(values))
|
||||
return values
|
||||
}
|
||||
|
||||
/** Writes several switches and the row order in one go, so the HUD is rebuilt once. */
|
||||
fun choose(context: Context, switches: Map<String, Boolean>, order: List<String>): Map<String, String> {
|
||||
val values = load(context)
|
||||
for ((key, on) in switches) if (key in DEFAULTS) {
|
||||
values[key] = flag(on)
|
||||
}
|
||||
val size = DroidDeckHudSize.from(values["hudSize"])
|
||||
val groups = sizeOrders(values).toMutableMap()
|
||||
if (groups.isEmpty()) {
|
||||
val legacy = legacyOrder(values)
|
||||
if (legacy.isNotEmpty()) for (each in DroidDeckHudSize.values()) groups[each] = legacy.filter { it in each.rows }
|
||||
}
|
||||
groups[size] = order.filter { it in ORDER }
|
||||
values["hudOrder"] = encodeOrders(groups)
|
||||
SessionPrefs.setDroidDeckHudConfig(context, encode(values))
|
||||
return values
|
||||
}
|
||||
|
||||
fun clearOrder(context: Context): Map<String, String> {
|
||||
val values = load(context)
|
||||
values["hudOrder"] = ""
|
||||
TWINS[key]?.let { values[it] = value }
|
||||
SessionPrefs.setDroidDeckHudConfig(context, encode(values))
|
||||
return values
|
||||
}
|
||||
@@ -76,37 +46,5 @@ internal object DroidDeckHudConfig {
|
||||
return DEFAULTS
|
||||
}
|
||||
|
||||
/** Every metric switch, in the order the HUD lists them before the user moves any. Derived from
|
||||
* [DEFAULTS], so a switch added there shows up here without a second list to keep in step. */
|
||||
val ORDER: List<String> = DEFAULTS.keys.filter { it.startsWith("show") && it !in NOT_READINGS }
|
||||
|
||||
/** Only the rows the user moved for [size], in the order they left them. */
|
||||
fun storedOrder(values: Map<String, String>, size: DroidDeckHudSize): List<String> =
|
||||
sizeOrders(values)[size] ?: legacyOrder(values)
|
||||
|
||||
/** Orders saved before each size kept its own: one list, applied to every size. */
|
||||
private fun legacyOrder(values: Map<String, String>): List<String> {
|
||||
val raw = values["hudOrder"].orEmpty()
|
||||
if (raw.isBlank() || raw.contains(':')) return emptyList()
|
||||
return raw.split('|').map { RENAMED[it] ?: it }.filter { it in ORDER }
|
||||
}
|
||||
|
||||
private fun sizeOrders(values: Map<String, String>): Map<DroidDeckHudSize, List<String>> {
|
||||
val raw = values["hudOrder"].orEmpty()
|
||||
if (raw.isBlank()) return emptyMap()
|
||||
val groups = LinkedHashMap<DroidDeckHudSize, List<String>>()
|
||||
for (group in raw.split(';')) {
|
||||
val colon = group.indexOf(':')
|
||||
if (colon <= 0) continue
|
||||
val size = DroidDeckHudSize.values().firstOrNull { it.token == group.substring(0, colon) } ?: continue
|
||||
groups[size] = group.substring(colon + 1).split('|').map { RENAMED[it] ?: it }.filter { it in ORDER }
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
private fun encodeOrders(groups: Map<DroidDeckHudSize, List<String>>): String =
|
||||
groups.entries.filter { it.value.isNotEmpty() }
|
||||
.joinToString(";") { "${it.key.token}:${it.value.joinToString("|")}" }
|
||||
|
||||
private fun flag(on: Boolean) = if (on) "1" else "0"
|
||||
}
|
||||
@@ -22,7 +22,7 @@ import kotlin.math.roundToInt
|
||||
class DroidDeckHudHost(context: Context) {
|
||||
private val context = context.applicationContext
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val feed = GameFrameFeed.forRoot(LinuxRuntime.rootDir(this.context))
|
||||
private val feed = GameFrameFeed(File(LinuxRuntime.rootDir(this.context), HudFrames.PATH))
|
||||
private val readings = MangoReadings(File(this.context.filesDir, "session"), LinuxRuntime.rootDir(this.context))
|
||||
private var view: DroidDeckHudView? = null
|
||||
private var parent: ViewGroup? = null
|
||||
|
||||
@@ -13,27 +13,6 @@
|
||||
|
||||
package com.droiddeck.launcher.hud
|
||||
|
||||
/**
|
||||
* Size modes for the DroidDeck HUD (the 4th selectable in-game overlay style). One shared color-coded
|
||||
* visual language, four amounts of detail — see the approved mockup. The config value is the lower-case
|
||||
* token stored under the `hudSize` key; the label is the user-facing string.
|
||||
*/
|
||||
/** The text sizes and spacing a [DroidDeckHudSize] lays its rows out with, in sp. */
|
||||
data class DroidDeckHudStyle(
|
||||
val row: Float,
|
||||
val unit: Float,
|
||||
val pad: Float,
|
||||
val lineGap: Float,
|
||||
val labelGap: Float,
|
||||
val key: Float = 0f,
|
||||
val sub: Float = 0f,
|
||||
val foot: Float = 0f,
|
||||
val band: Float = 0f,
|
||||
val gutter: Float = 0f,
|
||||
val tileGap: Float = 0f,
|
||||
val innerPad: Float = 0f,
|
||||
)
|
||||
|
||||
enum class DroidDeckHudSize(val token: String, val label: String) {
|
||||
FULL("full", "Full"),
|
||||
TILES("tiles", "Tiles"),
|
||||
@@ -47,73 +26,27 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
|
||||
return all[(ordinal + 1) % all.size]
|
||||
}
|
||||
|
||||
/**
|
||||
* The rows this size draws, in the order it draws them before the user moves any. This is the single
|
||||
* source of truth for both surfaces: [DroidDeckHudView] draws exactly these and the settings screen
|
||||
* offers exactly these. A switch outside the set is ignored by the size, so the two cannot drift.
|
||||
*/
|
||||
val rows: List<String> get() = ROWS.getValue(this)
|
||||
|
||||
/** This size's rows: the ones the user moved first, then the rest in the order [rows] lists them. */
|
||||
fun rowsIn(stored: List<String>): List<String> =
|
||||
stored.filter { it in rows } + rows.filter { it !in stored }
|
||||
/**
|
||||
* The numbers each size sets its text in, in sp. One table so a size's scale can be read (and changed)
|
||||
* in one place instead of hunting the `sp(...)` literals scattered through its builder.
|
||||
*/
|
||||
val style: DroidDeckHudStyle get() = STYLE.getValue(this)
|
||||
|
||||
fun supportedChips(): Set<String> = when (this) {
|
||||
MINIMAL -> MINIMAL_CHIPS
|
||||
PILL -> PILL_CHIPS
|
||||
FULL, TILES, STRIP -> STANDARD_CHIPS
|
||||
MEGA -> MEGA_CHIPS
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun from(token: String?): DroidDeckHudSize =
|
||||
values().firstOrNull { it.token.equals(token, ignoreCase = true) } ?: FULL
|
||||
|
||||
private val EXTRAS = setOf("showClock")
|
||||
|
||||
val ROWS: Map<DroidDeckHudSize, List<String>> = mapOf(
|
||||
FULL to listOf(
|
||||
"showFPS", "showFPSGraph", "showGpuModel", "showDisplay", "showHdr", "showGPULoad", "showGpuTemp",
|
||||
"showCPUUsage", "showTemp", "showVram", "showRAM", "showBattery", "showBatteryTemp", "showBatteryTime",
|
||||
"showPower", "showLatency", "showAvg", "showLow1", "showLow01", "showLow001",
|
||||
),
|
||||
TILES to listOf(
|
||||
"showFPS", "showFPSGraph", "showLatency", "showGPULoad", "showGpuTemp", "showCPUUsage", "showTemp",
|
||||
"showVram", "showRAM", "showEngine", "showDisplay", "showHdr", "showAvg", "showLow1",
|
||||
"showLow01", "showLow001", "showGpuModel", "showBattery", "showBatteryTemp", "showBatteryTime", "showPower",
|
||||
),
|
||||
PILL to listOf(
|
||||
"showFPS", "showFPSGraph", "showGpuModel", "showGPULoad", "showGpuTemp", "showCPUUsage", "showTemp",
|
||||
"showRAM", "showBattery", "showBatteryTemp", "showBatteryTime", "showPower", "showLatency", "showDisplay",
|
||||
"showVram", "showHdr",
|
||||
),
|
||||
MINIMAL to listOf(
|
||||
"showFPS", "showBatteryTime", "showFPSGraph", "showLow1", "showLow01", "showLow001", "showAvg", "showLatency",
|
||||
"showEngine", "showDisplay", "showHdr",
|
||||
),
|
||||
MEGA to DroidDeckHudConfig.ORDER.filter { it !in EXTRAS },
|
||||
STRIP to listOf(
|
||||
"showFPS", "showFPSGraph", "showLow1", "showLow01", "showLow001", "showGPULoad", "showGpuTemp",
|
||||
"showCPUUsage", "showTemp", "showVram", "showRAM", "showBattery", "showBatteryTemp", "showBatteryTime",
|
||||
"showPower", "showDisplay", "showHdr", "showGpuModel",
|
||||
),
|
||||
val MINIMAL_CHIPS = setOf("FPS", "FPS graph", "1% low", "0.1% low", "0.01% low", "FPS .1", "Engine", "Clock")
|
||||
val PILL_CHIPS = setOf("FPS", "FPS graph", "GPU", "CPU", "VRAM", "RAM", "Battery", "GPU model", "FPS .1", "Engine", "Clock")
|
||||
val STANDARD_CHIPS = setOf(
|
||||
"FPS", "FPS graph", "GPU", "GPU temp", "CPU", "VRAM", "RAM", "Power", "Temp",
|
||||
"Battery", "GPU model", "Engine", "1% low", "0.1% low", "0.01% low", "FPS .1", "Clock",
|
||||
)
|
||||
|
||||
|
||||
val STYLE: Map<DroidDeckHudSize, DroidDeckHudStyle> = mapOf(
|
||||
FULL to DroidDeckHudStyle(row = 12f, unit = 12f * 0.62f, pad = 10f, lineGap = 4f, labelGap = 8f),
|
||||
TILES to DroidDeckHudStyle(row = 18f, unit = 11f, pad = 9f, lineGap = 4f, labelGap = 8f,
|
||||
key = 10f, sub = 10f, tileGap = 6f, innerPad = 8f),
|
||||
PILL to DroidDeckHudStyle(row = 30f, unit = 30f * 0.36f, pad = 10f, lineGap = 3f, labelGap = 12f,
|
||||
sub = 11.5f),
|
||||
MINIMAL to DroidDeckHudStyle(row = 34f, unit = 34f * 0.32f, pad = 10f, lineGap = 4f, labelGap = 8f,
|
||||
sub = 11.5f, foot = 9.5f),
|
||||
MEGA to DroidDeckHudStyle(row = 11.5f, unit = 11.5f * 0.62f, pad = 10f, lineGap = 3.5f, labelGap = 7f,
|
||||
band = 9.5f, gutter = 16f),
|
||||
STRIP to DroidDeckHudStyle(row = 11.5f, unit = 11.5f * 0.8f, pad = 10f, lineGap = 0f, labelGap = 13f),
|
||||
val MEGA_ONLY = setOf(
|
||||
"Per-core", "Swap", "Network", "Resolution", "Proton", "Wrapper", "DX ver", "Session",
|
||||
)
|
||||
|
||||
fun rowsFor(size: DroidDeckHudSize, values: Map<String, String>): List<String> =
|
||||
size.rowsIn(DroidDeckHudConfig.storedOrder(values, size))
|
||||
val MEGA_CHIPS = STANDARD_CHIPS + MEGA_ONLY
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -69,7 +69,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
|
||||
private val density = resources.displayMetrics.density
|
||||
|
||||
private var cfg: KeyValueSet = KeyValueSet()
|
||||
private var size = DroidDeckHudSize.FULL
|
||||
private var scale = 1f
|
||||
private var bgOpacity = 0.8f
|
||||
@@ -96,16 +95,13 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
private var showLow001 = true
|
||||
private var fpsDecimal = true
|
||||
private var showClockTime = true
|
||||
private var showLatency = true
|
||||
private var showAvg = true
|
||||
private var showDisplay = true
|
||||
private var showHdr = true
|
||||
private var storedOrder: List<String> = emptyList()
|
||||
private var showPerCore = true
|
||||
private var showSwap = true
|
||||
private var showNet = true
|
||||
private var showResolution = true
|
||||
private var showProton = true
|
||||
private var showWrapper = true
|
||||
private var showDxVer = true
|
||||
private var showSession = true
|
||||
|
||||
private var engineLabel = ""
|
||||
@@ -181,7 +177,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
fun moved(dx: Float, dy: Float) = Glyph(x + dx, baseline + dy, text, color, sizePx, glow)
|
||||
}
|
||||
private class Span(val text: String, val color: Int, val sizePx: Float, val glow: Boolean = false)
|
||||
private class HudRow(val key: String, val label: Span, val vals: List<Span>, val inline: Boolean = false)
|
||||
private class HudRow(val label: Span, val vals: List<Span>, val inline: Boolean = false)
|
||||
private val glyphs = ArrayList<Glyph>()
|
||||
private val tileRects = ArrayList<RectF>()
|
||||
private var graphRect: RectF? = null
|
||||
@@ -293,52 +289,41 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
|
||||
private fun cycleSize() {
|
||||
size = size.next()
|
||||
refreshOrder()
|
||||
onSizeCycledListener?.accept(size.token)
|
||||
rebuildAndInvalidate()
|
||||
}
|
||||
|
||||
private fun refreshOrder() {
|
||||
storedOrder = DroidDeckHudConfig.storedOrder(mapOf("hudOrder" to cfg.get("hudOrder", "")), size)
|
||||
}
|
||||
|
||||
private fun switchOn(key: String): Boolean =
|
||||
cfg.get(key, DroidDeckHudConfig.DEFAULTS[key] ?: "1") == "1"
|
||||
|
||||
fun applyConfig(configString: String?) {
|
||||
if (configString.isNullOrEmpty()) return
|
||||
cfg = KeyValueSet(configString)
|
||||
val cfg = KeyValueSet(configString)
|
||||
|
||||
size = DroidDeckHudSize.from(cfg.get("hudSize", "minimal"))
|
||||
showFPS = switchOn("showFPS")
|
||||
showEngine = switchOn("showEngine")
|
||||
showGpuModel = switchOn("showGpuModel")
|
||||
showCPU = switchOn("showCPUUsage")
|
||||
showGPU = switchOn("showGPULoad")
|
||||
showCpuTemp = switchOn("showTemp")
|
||||
showGpuTemp = switchOn("showGpuTemp")
|
||||
showVram = switchOn("showVram")
|
||||
showRAM = switchOn("showRAM")
|
||||
showBattery = switchOn("showBattery")
|
||||
showPower = switchOn("showPower")
|
||||
showBatteryTemp = switchOn("showBatteryTemp")
|
||||
showGraph = switchOn("showFPSGraph")
|
||||
showLow001 = switchOn("showLow001")
|
||||
showFPS = cfg.get("showFPS", "1") == "1"
|
||||
showEngine = cfg.get("showEngine", "1") == "1"
|
||||
showGpuModel = cfg.get("showGpuModel", "1") == "1"
|
||||
showCPU = cfg.get("showCPUUsage", cfg.get("showCPULoad", "1")) == "1"
|
||||
showGPU = cfg.get("showGPULoad", "1") == "1"
|
||||
showCpuTemp = cfg.get("showTemp", "1") == "1"
|
||||
showGpuTemp = cfg.get("showGpuTemp", "0") == "1"
|
||||
showVram = cfg.get("showVram", "1") == "1"
|
||||
showRAM = cfg.get("showRAM", "1") == "1"
|
||||
showBattery = cfg.get("showBattery", "1") == "1"
|
||||
showPower = cfg.get("showPower", "1") == "1"
|
||||
showBatteryTemp = cfg.get("showBatteryTemp", "0") == "1"
|
||||
showGraph = cfg.get("showFPSGraph", "0") == "1"
|
||||
showLow1 = cfg.get("showLow1", "1") == "1"
|
||||
showLow01 = cfg.get("showLow01", "1") == "1"
|
||||
showLow001 = cfg.get("showLow001", "1") == "1"
|
||||
fpsDecimal = cfg.get("fpsDecimal", "1") == "1"
|
||||
showClockTime = switchOn("showClock")
|
||||
showLatency = switchOn("showLatency")
|
||||
showAvg = switchOn("showAvg")
|
||||
showLow1 = switchOn("showLow1")
|
||||
showLow01 = switchOn("showLow01")
|
||||
showDisplay = switchOn("showDisplay")
|
||||
showHdr = switchOn("showHdr")
|
||||
refreshOrder()
|
||||
showPerCore = switchOn("showPerCore")
|
||||
showSwap = switchOn("showSwap")
|
||||
showNet = switchOn("showNet")
|
||||
showResolution = switchOn("showResolution")
|
||||
showProton = switchOn("showProton")
|
||||
showSession = switchOn("showSession")
|
||||
showClockTime = cfg.get("showClock", "1") == "1"
|
||||
showPerCore = cfg.get("showPerCore", "1") == "1"
|
||||
showSwap = cfg.get("showSwap", "1") == "1"
|
||||
showNet = cfg.get("showNet", "1") == "1"
|
||||
showResolution = cfg.get("showResolution", "1") == "1"
|
||||
showProton = cfg.get("showProton", "1") == "1"
|
||||
showWrapper = cfg.get("showWrapper", "1") == "1"
|
||||
showDxVer = cfg.get("showDxVer", "1") == "1"
|
||||
showSession = cfg.get("showSession", "1") == "1"
|
||||
tempDisplay = HudMetrics.TempDisplay.from(cfg)
|
||||
lockController.setLocked(cfg.get("hudLocked", "1") == "1")
|
||||
dock = DroidDeckHudDock.from(cfg.get("hudDock", "none"))
|
||||
@@ -473,8 +458,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
return w
|
||||
}
|
||||
|
||||
private fun showHdrLine(): Boolean = showHdr && hdrState != DroidDeckHudHdr.NONE
|
||||
|
||||
private fun placeRun(startX: Float, baseline: Float, spans: List<Span>, glow: Boolean = false): Float {
|
||||
var x = startX
|
||||
for (s in spans) {
|
||||
@@ -556,15 +539,13 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
val s = snap
|
||||
if (s == null) { contentW = 0f; contentH = 0f; return }
|
||||
if (dock != DroidDeckHudDock.NONE) { buildDockTab(); return }
|
||||
if (size == DroidDeckHudSize.STRIP) { buildStrip(s); return }
|
||||
buildRows(s)
|
||||
if (contentW <= 0f || contentH <= 0f) return
|
||||
if (size == DroidDeckHudSize.PILL) addSubtleClock(sp(10f), leftAligned = true)
|
||||
val pad = sp(size.style.pad)
|
||||
when (size) {
|
||||
DroidDeckHudSize.MINIMAL -> intoPanel(pad, header = true, halfRound = true)
|
||||
DroidDeckHudSize.PILL -> intoPanel(pad, header = false)
|
||||
else -> intoPanel(pad, header = true)
|
||||
DroidDeckHudSize.FULL -> { buildFull(s); intoPanel(sp(10f), header = true) }
|
||||
DroidDeckHudSize.TILES -> { buildTiles(s); intoPanel(sp(9f), header = true) }
|
||||
DroidDeckHudSize.PILL -> { buildPill(s); intoPanel(sp(10f), header = false) }
|
||||
DroidDeckHudSize.MINIMAL -> buildMinimal(s)
|
||||
DroidDeckHudSize.MEGA -> { buildMega(s); intoPanel(sp(10f), header = true) }
|
||||
DroidDeckHudSize.STRIP -> buildStrip(s)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -634,12 +615,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
return Pair(dDividerTop + max(1f, density), x)
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves a size's content, laid out from [pad] at the origin, into the panel: under the header, or after
|
||||
* the logo chip on the Pill. Lines that start on the content's left edge are lined up by their ink, so
|
||||
* the logo, labels and numbers share one edge.
|
||||
*/
|
||||
private fun intoPanel(pad: Float, header: Boolean, halfRound: Boolean = !header) {
|
||||
private fun intoPanel(pad: Float, header: Boolean) {
|
||||
if (contentW <= 0f || contentH <= 0f) return
|
||||
for (i in glyphs.indices) {
|
||||
val g = glyphs[i]
|
||||
@@ -665,7 +641,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
val panel = RectF(panelLeft(), panelInset(), max(contentW - pad + dx, headerRight) + sp(18f),
|
||||
contentH - pad + dy + sp(10f) + stroke)
|
||||
chipRect?.let { it.offsetTo(it.left, panel.centerY() - it.height() / 2f) }
|
||||
finishPanel(panel, halfRound = halfRound)
|
||||
finishPanel(panel, halfRound = !header)
|
||||
}
|
||||
|
||||
private fun finishPanel(panel: RectF, halfRound: Boolean) {
|
||||
@@ -736,188 +712,316 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
contentW = max(contentW, pad + w + pad)
|
||||
}
|
||||
|
||||
private fun switchLabel(key: String): Pair<String, Int> = when (key) {
|
||||
"showGpuModel" -> "MODEL" to colGpu
|
||||
"showGPULoad" -> "GPU" to colGpu
|
||||
"showGpuTemp" -> "GPU.T" to colGpu
|
||||
"showCPUUsage" -> "CPU" to colCpu
|
||||
"showTemp" -> "CPU.T" to colCpu
|
||||
"showBatteryTemp" -> "BAT.T" to colBat
|
||||
"showPower" -> "PWR" to colBat
|
||||
"showBattery" -> "BAT" to colBat
|
||||
"showBatteryTime" -> "BAT TIME" to colBat
|
||||
"showVram" -> "VRAM" to colVram
|
||||
"showRAM" -> "RAM" to colRam
|
||||
"showSwap" -> "SWP" to colRam
|
||||
"showNet" -> "NET" to colFps
|
||||
"showPerCore" -> "CORE" to colCpu
|
||||
"showFPS" -> "FPS" to colFps
|
||||
"showLatency" -> "MS" to colDim
|
||||
"showAvg" -> "AVG" to colLo
|
||||
"showLow1" -> "1%" to colLo
|
||||
"showLow01" -> "0.1%" to colLo
|
||||
"showLow001" -> "0.01%" to colLo
|
||||
"showEngine" -> "API" to colFps
|
||||
"showDisplay" -> "DISP" to colDisp
|
||||
"showHdr" -> "HDR" to colHdr
|
||||
"showResolution" -> "RES" to colDim
|
||||
"showProton" -> "PROTON" to colVram
|
||||
"showSession" -> "TIME" to colDim
|
||||
else -> key.removePrefix("show") to colDim
|
||||
private fun hasGpuStats(s: HudMetrics.Snapshot): Boolean =
|
||||
s.gpuPercent != null || s.gpuTempC != null || s.gpuClockMhz != null
|
||||
|
||||
private fun buildFull(s: HudMetrics.Snapshot) {
|
||||
val rowPx = sp(12f); val unitPx = rowPx * 0.62f
|
||||
val pad = sp(10f); val lineGap = sp(4f); val lvGap = sp(8f)
|
||||
val rows = ArrayList<HudRow>()
|
||||
|
||||
if (showGpuModel && gpuNameText().isNotBlank())
|
||||
rows.add(HudRow(Span("GPU", colGpu, rowPx), gpuModelSpans(rowPx, colValue)))
|
||||
if (displayServer.isNotBlank())
|
||||
rows.add(HudRow(Span("DISP", colDisp, rowPx), listOf(Span(displayServer, colValue, rowPx))))
|
||||
if (hdrState != DroidDeckHudHdr.NONE)
|
||||
rows.add(HudRow(Span("HDR", colHdr, rowPx), hdrValue(rowPx)))
|
||||
if (showGPU && hasGpuStats(s)) {
|
||||
val v = ArrayList<Span>()
|
||||
v += numUnit(s.gpuPercent?.toString(), "%", rowPx, unitPx)
|
||||
if (showGpuTemp) tempSpans(s.gpuTempC, HudMetrics.TempSensor.GPU, rowPx, unitPx)
|
||||
.let { if (it.isNotEmpty()) { v += gap(unitPx); v += it } }
|
||||
v += gap(unitPx); v += numUnit(s.gpuClockMhz?.toString(), "MHz", rowPx, unitPx)
|
||||
rows.add(HudRow(Span("GPU", colGpu, rowPx), v))
|
||||
}
|
||||
if (showCPU) {
|
||||
val v = ArrayList<Span>()
|
||||
v += numUnit(s.cpuPercent?.toString(), "%", rowPx, unitPx)
|
||||
v += gap(unitPx); v += numUnit(s.cpuClockMhz?.toString(), "MHz", rowPx, unitPx)
|
||||
if (showCpuTemp) tempSpans(s.cpuTempC, HudMetrics.TempSensor.CPU, rowPx, unitPx)
|
||||
.let { if (it.isNotEmpty()) { v += gap(unitPx); v += it } }
|
||||
rows.add(HudRow(Span("CPU", colCpu, rowPx), v))
|
||||
}
|
||||
if (showVram && s.vramText() != null)
|
||||
rows.add(HudRow(Span("VRAM", colVram, rowPx), valueUnit(s.vramText()!!, rowPx, unitPx)))
|
||||
if (showRAM) {
|
||||
val v = ArrayList<Span>()
|
||||
v += valueUnit(s.ramUsedText(), rowPx, unitPx)
|
||||
v += gap(unitPx); v += numUnit(s.ramPercent.roundToInt().toString(), "%", rowPx, unitPx)
|
||||
rows.add(HudRow(Span("RAM", colRam, rowPx), v))
|
||||
}
|
||||
if (showBattery || showPower || showBatteryTemp) {
|
||||
val v = ArrayList<Span>(); var any = false
|
||||
if (showBattery && s.battery.percent != null) { v += numUnit(s.battery.percent.toString(), "%", rowPx, unitPx); any = true }
|
||||
if (showBatteryTemp) tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, rowPx, unitPx)
|
||||
.let { if (it.isNotEmpty()) { if (any) v += gap(unitPx); v += it; any = true } }
|
||||
if (showPower && s.battery.watts > 0f) { if (any) v += gap(unitPx); v += numUnit(fmt1(s.battery.watts), "W", rowPx, unitPx); any = true }
|
||||
if (any) rows.add(HudRow(Span("BAT", colBat, rowPx), v))
|
||||
}
|
||||
if (showFPS) {
|
||||
val v = ArrayList<Span>()
|
||||
v += glowing(numUnit(fpsText(fpsNow), "FPS", rowPx, unitPx))
|
||||
v += gap(unitPx); v += numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", rowPx, unitPx)
|
||||
rows.add(HudRow(Span(apiLabel(), colFps, rowPx), v))
|
||||
rows.add(HudRow(Span("AVG", colLo, rowPx), numUnit(fmt1(fpsAvg), "FPS", rowPx, unitPx)))
|
||||
if (showLow1)
|
||||
rows.add(HudRow(Span("1%", colLo, rowPx), numUnit(lowText(lows.low1Fps), "FPS", rowPx, unitPx)))
|
||||
if (showLow01)
|
||||
rows.add(HudRow(Span("0.1%", colLo, rowPx), numUnit(lowText(lows.low01Fps), "FPS", rowPx, unitPx)))
|
||||
if (showLow001)
|
||||
rows.add(HudRow(Span("0.01%", colLo, rowPx), numUnit(lowText(lows.low001Fps), "FPS", rowPx, unitPx)))
|
||||
}
|
||||
|
||||
var labelCol = 0f
|
||||
for (r in rows) if (!r.inline) labelCol = max(labelCol, measure(r.label.text, rowPx))
|
||||
val h = lineH(rowPx); val asc = ascent(rowPx)
|
||||
var y = pad; var maxRight = pad
|
||||
for (r in rows) {
|
||||
val baseline = y - asc
|
||||
placeRun(pad, baseline, listOf(r.label))
|
||||
val valX = if (r.inline) pad + measure(r.label.text, rowPx) + lvGap
|
||||
else pad + labelCol + lvGap
|
||||
val end = placeRun(valX, baseline, r.vals)
|
||||
maxRight = max(maxRight, end)
|
||||
y += h + lineGap
|
||||
}
|
||||
|
||||
if (showFPS && showGraph) {
|
||||
val ftPx = unitPx * 1.15f
|
||||
val baseline = y - asc
|
||||
placeRun(pad, baseline, listOf(Span("Frametime", colFps, ftPx)))
|
||||
val stat = "min:${fmt1(graphMinMs)} max:${fmt1(graphMaxMs)}"
|
||||
val statX = pad + max(labelCol, measure("Frametime", ftPx)) + lvGap
|
||||
val end = placeRun(statX, baseline, listOf(Span(stat, colDim, unitPx)))
|
||||
maxRight = max(maxRight, end)
|
||||
y += h + lineGap
|
||||
val gh = sp(22f)
|
||||
val right = max(maxRight, pad + sp(160f))
|
||||
graphRect = RectF(pad, y, right, y + gh)
|
||||
maxRight = max(maxRight, right)
|
||||
y += gh
|
||||
}
|
||||
|
||||
contentW = maxRight + pad
|
||||
contentH = y + pad
|
||||
addSubtleClock(pad)
|
||||
}
|
||||
|
||||
private fun reading(key: String, s: HudMetrics.Snapshot, labelPx: Float, valuePx: Float, unitPx: Float): HudRow {
|
||||
if (key == "showFPSGraph") return HudRow(key, Span("", colDim, 0f), emptyList())
|
||||
val (label, color) = switchLabel(key)
|
||||
val values: List<Span> = when (key) {
|
||||
"showGpuModel" -> if (gpuNameText().isBlank()) numUnit(null, "", valuePx, unitPx)
|
||||
else gpuModelSpans(valuePx, colValue)
|
||||
"showGPULoad" -> numUnit(s.gpuPercent?.toString(), "%", valuePx, unitPx)
|
||||
"showGpuTemp" -> tempSpans(s.gpuTempC, HudMetrics.TempSensor.GPU, valuePx, unitPx)
|
||||
"showCPUUsage" -> numUnit(s.cpuPercent?.toString(), "%", valuePx, unitPx)
|
||||
"showTemp" -> tempSpans(s.cpuTempC, HudMetrics.TempSensor.CPU, valuePx, unitPx)
|
||||
"showBatteryTemp" -> tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, valuePx, unitPx)
|
||||
"showPower" -> numUnit(if (s.battery.watts > 0f) fmt1(s.battery.watts) else null, "W", valuePx, unitPx)
|
||||
"showBattery" -> numUnit(s.battery.percent?.toString(), "%", valuePx, unitPx)
|
||||
"showBatteryTime" -> valueUnit(s.battery.runtimeText ?: "—", valuePx, unitPx)
|
||||
"showVram" -> valueUnit(s.vramText() ?: "—", valuePx, unitPx)
|
||||
"showRAM" -> numUnit(s.ramPercent.roundToInt().toString(), "%", valuePx, unitPx)
|
||||
"showSwap" -> valueUnit(s.swapUsedText() ?: "—", valuePx, unitPx)
|
||||
"showNet" -> listOf(
|
||||
Span("↓", colDim, unitPx), Span(((s.netDownBps ?: 0L) / 1024L).toString(), colValue, valuePx),
|
||||
Span(" ↑", colDim, unitPx), Span(((s.netUpBps ?: 0L) / 1024L).toString(), colValue, valuePx),
|
||||
)
|
||||
"showPerCore" -> listOf(Span(s.perCorePercent.size.toString(), colValue, valuePx))
|
||||
"showFPS" -> glowing(numUnit(fpsText(fpsNow), "", valuePx, unitPx))
|
||||
"showLatency" -> numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", valuePx, unitPx)
|
||||
"showAvg" -> numUnit(fmt1(fpsAvg), "", valuePx, unitPx)
|
||||
"showLow1" -> numUnit(lowText(lows.low1Fps), "", valuePx, unitPx)
|
||||
"showLow01" -> numUnit(lowText(lows.low01Fps), "", valuePx, unitPx)
|
||||
"showLow001" -> numUnit(lowText(lows.low001Fps), "", valuePx, unitPx)
|
||||
"showEngine" -> listOf(Span(engineLabel.ifBlank { "—" }, colValue, valuePx))
|
||||
"showDisplay" -> listOf(Span(displayServer.ifBlank { "—" }, colDisp, valuePx))
|
||||
"showHdr" -> if (showHdrLine()) hdrValue(valuePx) else listOf(Span("off", colDim, valuePx))
|
||||
"showResolution" -> listOf(Span(resolutionString(), colValue, valuePx))
|
||||
"showProton" -> listOf(Span(wineVersion.ifBlank { "—" }, colVram, valuePx))
|
||||
"showSession" -> listOf(Span(elapsedString(), colValue, valuePx))
|
||||
else -> listOf(Span("—", colDim, valuePx))
|
||||
private fun buildTiles(s: HudMetrics.Snapshot) {
|
||||
val keyPx = sp(10f); val valPx = sp(18f); val subPx = sp(10f); val unitPx = sp(11f)
|
||||
val pad = sp(9f); val innerPad = sp(8f); val tileGap = sp(6f); val lineGap = sp(4f)
|
||||
|
||||
class Tile(val key: String, val keyColor: Int, val value: List<Span>, val sub: String?, val wide: Boolean)
|
||||
val tiles = ArrayList<Tile>()
|
||||
|
||||
if (showFPS) tiles.add(Tile("FPS", colFps, listOf(Span(fpsText(fpsNow), colValue, valPx, glow = true)),
|
||||
"${fmt1(fpsAvg)} avg" + (if (showLow1) " · ${lowText(lows.low1Fps) ?: "—"} 1%" else ""), false))
|
||||
if (showFPS) tiles.add(Tile("FRAME", colDim, numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", valPx, unitPx),
|
||||
"${fmt1(graphMinMs)} – ${fmt1(graphMaxMs)}", false))
|
||||
if (showGPU && hasGpuStats(s)) tiles.add(Tile("GPU", colGpu, numUnit(s.gpuPercent?.toString(), "%", valPx, unitPx),
|
||||
if (showGpuTemp && s.gpuTempC != null) HudMetrics.formatTemp(s.gpuTempC.toFloat(), tempDisplay, false)
|
||||
else s.gpuClockMhz?.let { "${it}MHz" }, false))
|
||||
if (showCPU) tiles.add(Tile("CPU", colCpu, numUnit(s.cpuPercent?.toString(), "%", valPx, unitPx),
|
||||
listOfNotNull(s.cpuClockMhz?.let { "${it}MHz" },
|
||||
if (showCpuTemp) s.cpuTempC?.let { HudMetrics.formatTemp(it.toFloat(), tempDisplay, false) } else null)
|
||||
.joinToString(" · ").ifBlank { null }, false))
|
||||
if (showVram && s.vramText() != null) tiles.add(Tile("VRAM", colVram, valueUnit(s.vramText()!!, valPx, unitPx), null, false))
|
||||
if (showRAM) tiles.add(Tile("RAM", colRam, numUnit(s.ramPercent.roundToInt().toString(), "%", valPx, unitPx),
|
||||
"${s.ramUsedText()} / ${s.ramTotalText()}", false))
|
||||
if (showEngine && engineLabel.isNotBlank())
|
||||
tiles.add(Tile("API", colFps, listOf(Span(engineLabel, colValue, valPx)),
|
||||
dxVersion().ifBlank { null }, false))
|
||||
if (displayServer.isNotBlank())
|
||||
tiles.add(Tile("DISPLAY", colDisp, listOf(Span(displayServer, colValue, valPx)),
|
||||
if (hdrState != DroidDeckHudHdr.NONE) hdrText() else null, false))
|
||||
if (showGpuModel && gpuNameText().isNotBlank())
|
||||
tiles.add(Tile("GPU", colGpu, gpuModelSpans(valPx, colValue), null, true))
|
||||
if (showBattery || showPower || showBatteryTemp) {
|
||||
val parts = ArrayList<Span>(); var any = false
|
||||
if (showBattery && s.battery.percent != null) { parts += numUnit(s.battery.percent.toString(), "%", valPx, unitPx); any = true }
|
||||
if (showBatteryTemp && s.battery.tempC != null) { if (any) parts += Span(" · ", colDim, subPx); parts += tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, valPx, unitPx); any = true }
|
||||
if (showPower && s.battery.watts > 0f) { if (any) parts += Span(" · ", colDim, subPx); parts += numUnit(fmt1(s.battery.watts), "W", valPx, unitPx); any = true }
|
||||
if (any) tiles.add(Tile("BAT", colBat, parts, null, true))
|
||||
}
|
||||
return HudRow(key, Span(label, color, labelPx), values.ifEmpty { listOf(Span("—", colDim, valuePx)) })
|
||||
if (tiles.isEmpty()) { contentW = 0f; contentH = 0f; return }
|
||||
|
||||
val keyH = lineH(keyPx); val valH = lineH(valPx); val subH = lineH(subPx)
|
||||
fun tileW(t: Tile) = max(max(measure(t.key, keyPx), runWidth(t.value)),
|
||||
t.sub?.let { measure(it, subPx) } ?: 0f) + innerPad * 2
|
||||
var normalW = 0f
|
||||
for (t in tiles) if (!t.wide) normalW = max(normalW, tileW(t))
|
||||
if (normalW == 0f) for (t in tiles) normalW = max(normalW, tileW(t) / 2f)
|
||||
val tileH = innerPad * 2 + keyH + lineGap + valH + lineGap + subH
|
||||
val fullW = normalW * 2 + tileGap
|
||||
|
||||
var x = pad; var y = pad; var col = 0
|
||||
fun place(t: Tile, tx: Float, ty: Float, tw: Float) {
|
||||
tileRects.add(RectF(tx, ty, tx + tw, ty + tileH))
|
||||
var by = ty + innerPad - ascent(keyPx)
|
||||
placeRun(tx + innerPad, by, listOf(Span(t.key, t.keyColor, keyPx)))
|
||||
by = ty + innerPad + keyH + lineGap - ascent(valPx)
|
||||
placeRun(tx + innerPad, by, t.value)
|
||||
if (t.sub != null) {
|
||||
by = ty + innerPad + keyH + lineGap + valH + lineGap - ascent(subPx)
|
||||
placeRun(tx + innerPad, by, listOf(Span(t.sub, colDim, subPx)))
|
||||
}
|
||||
}
|
||||
for (t in tiles) {
|
||||
if (t.wide) {
|
||||
if (col != 0) { y += tileH + tileGap; col = 0; x = pad }
|
||||
place(t, pad, y, fullW)
|
||||
y += tileH + tileGap; col = 0; x = pad
|
||||
} else {
|
||||
place(t, x, y, normalW)
|
||||
col++; x += normalW + tileGap
|
||||
if (col == 2) { col = 0; x = pad; y += tileH + tileGap }
|
||||
}
|
||||
}
|
||||
if (col != 0) y += tileH + tileGap
|
||||
if (showFPS && showGraph) {
|
||||
graphRect = RectF(pad, y, pad + fullW, y + sp(22f))
|
||||
y += sp(22f) + tileGap
|
||||
}
|
||||
contentW = pad + fullW + pad
|
||||
contentH = y + (pad - tileGap)
|
||||
addSubtleClock(pad)
|
||||
}
|
||||
|
||||
private fun buildRows(s: HudMetrics.Snapshot) {
|
||||
val st = size.style
|
||||
val pad = sp(st.pad); val lineGap = sp(st.lineGap); val lvGap = sp(st.labelGap)
|
||||
val gutter = sp(if (st.gutter > 0f) st.gutter else 14f)
|
||||
val unitPx = sp(if (st.unit > 0f) st.unit else st.row * 0.62f)
|
||||
val basePx = sp(if (st.sub > 0f) st.sub else st.row)
|
||||
private fun buildPill(s: HudMetrics.Snapshot) {
|
||||
val bigPx = sp(30f); val bigUnitPx = bigPx * 0.36f; val stkPx = sp(11.5f)
|
||||
val pad = sp(10f); val midGap = sp(12f); val stkLineGap = sp(3f)
|
||||
|
||||
val keys = size.rowsIn(storedOrder).filter { switchOn(it) }
|
||||
if (keys.isEmpty()) { contentW = 0f; contentH = 0f; return }
|
||||
val hero = (size == DroidDeckHudSize.PILL || size == DroidDeckHudSize.MINIMAL) && keys.firstOrNull() == "showFPS"
|
||||
val tiles = size == DroidDeckHudSize.TILES
|
||||
val bigPx = sp(st.row); val bigUnitPx = sp(st.unit)
|
||||
val heroSpans = listOf(
|
||||
Span(fpsText(fpsNow), colValue, bigPx, glow = true),
|
||||
Span("fps", colDim, bigUnitPx),
|
||||
)
|
||||
val listed = keys.filter { !hero || it != "showFPS" }.flatMap { key ->
|
||||
val labelPx = if (tiles) sp(st.key) else basePx
|
||||
val valuePx = if (tiles) sp(st.row) else basePx
|
||||
if (key == "showPerCore" && size == DroidDeckHudSize.MEGA)
|
||||
perCoreRows(s, labelPx, valuePx, unitPx)
|
||||
else listOf(reading(key, s, labelPx, valuePx, unitPx))
|
||||
}
|
||||
val maxCols = if (size == DroidDeckHudSize.MEGA) 3 else 2
|
||||
val cols = when {
|
||||
listed.size >= 9 -> maxCols
|
||||
listed.size >= 4 -> minOf(2, maxCols)
|
||||
else -> 1
|
||||
}
|
||||
val left = ArrayList<Span>()
|
||||
val generating = differs(fpsNow)
|
||||
val fpsPx = if (generating) bigPx * 0.55f else bigPx
|
||||
left += Span(fpsText(fpsNow), colValue, fpsPx, glow = true)
|
||||
left += Span("fps", colDim, if (generating) bigUnitPx * 0.8f else bigUnitPx)
|
||||
|
||||
if (tiles) {
|
||||
val innerPad = sp(st.innerPad); val tileGap = sp(st.tileGap)
|
||||
val keyH = lineH(sp(st.key)); val valH = lineH(sp(st.row))
|
||||
val cellW = listed.maxOf { max(measure(it.label.text, it.label.sizePx), runWidth(it.vals)) } + innerPad * 2f
|
||||
val graphMin = if (listed.any { it.key == "showFPSGraph" }) sp(GRAPH_MIN_WIDTH_SP) else 0f
|
||||
val cellMin = graphMin + innerPad * 2f
|
||||
val cellH = innerPad * 2f + keyH + lineGap + valH
|
||||
for ((i, r) in listed.withIndex()) {
|
||||
val x = pad + (i % cols) * (cellW + tileGap)
|
||||
val y = pad + (i / cols) * (cellH + tileGap)
|
||||
tileRects.add(RectF(x, y, x + cellW, y + cellH))
|
||||
if (r.key == "showFPSGraph") {
|
||||
graphRect = RectF(x + innerPad, y + innerPad, x + max(cellW, cellMin) - innerPad, y + cellH - innerPad)
|
||||
continue
|
||||
}
|
||||
placeRun(x + innerPad, y + innerPad - ascent(r.label.sizePx), listOf(r.label))
|
||||
placeRun(x + innerPad, y + innerPad + keyH + lineGap - ascent(sp(st.row)), r.vals)
|
||||
val stack = ArrayList<List<Span>>()
|
||||
val gpuName = if (showGpuModel && gpuNameText().isNotBlank()) gpuModelSpans(stkPx, colDim, compact = true) else null
|
||||
run {
|
||||
val l = ArrayList<Span>()
|
||||
if (showGPU && s.gpuPercent != null) { l += Span("GPU ${s.gpuPercent}%", colGpu, stkPx) }
|
||||
if (showCPU) { if (l.isNotEmpty()) l += Span(" · ", colDim, stkPx); l += Span("CPU ${s.cpuPercent ?: "—"}%", colCpu, stkPx) }
|
||||
if (l.isNotEmpty()) stack.add(l)
|
||||
}
|
||||
if (showRAM) stack.add(listOf(Span("RAM ${s.ramPercent.roundToInt()}%", colRam, stkPx)))
|
||||
if (showBattery || showPower || showBatteryTemp) {
|
||||
val l = ArrayList<Span>()
|
||||
fun part(spans: List<Span>) {
|
||||
l += if (l.isEmpty()) Span("BAT ", colBat, stkPx) else Span(" · ", colDim, stkPx)
|
||||
l += spans
|
||||
}
|
||||
val lines = (listed.size + cols - 1) / cols
|
||||
contentW = pad + cols * (cellW + tileGap) - tileGap + pad
|
||||
contentH = pad + lines * (cellH + tileGap) - tileGap + pad
|
||||
} else {
|
||||
val columns = (0 until cols).map { c -> listed.filterIndexed { i, _ -> i % cols == c } }
|
||||
val labelW = columns.map { col -> col.maxOfOrNull { measure(it.label.text, it.label.sizePx) } ?: 0f }
|
||||
val colW = columns.mapIndexed { c, col ->
|
||||
val body = if (col.isEmpty()) 0f else labelW[c] + lvGap + (col.maxOfOrNull { runWidth(it.vals) } ?: 0f)
|
||||
val graph = if (col.any { it.key == "showFPSGraph" }) sp(GRAPH_MIN_WIDTH_SP) + labelW[c] + lvGap else 0f
|
||||
max(body, graph)
|
||||
}
|
||||
val gaps = (0 until cols).count { columns[it].isNotEmpty() }.coerceAtLeast(1) - 1
|
||||
val bodyW = colW.sum() + gutter * gaps
|
||||
var bodyH = 0f
|
||||
for (col in columns) {
|
||||
var y = 0f
|
||||
for (r in col) y += rowHeight(r) + lineGap
|
||||
if (col.isNotEmpty()) bodyH = max(bodyH, y - lineGap)
|
||||
}
|
||||
val heroW = if (hero) runWidth(heroSpans) else 0f
|
||||
val heroH = if (hero) lineH(bigPx) else 0f
|
||||
val x0 = pad + if (hero && listed.isNotEmpty()) heroW + gutter else 0f
|
||||
val top = pad + (max(bodyH, heroH) - bodyH) / 2f
|
||||
var x = x0
|
||||
for (c in 0 until cols) {
|
||||
if (columns[c].isEmpty()) continue
|
||||
var y = top
|
||||
for (r in columns[c]) {
|
||||
if (r.key == "showFPSGraph") {
|
||||
val left = x + labelW[c] + lvGap
|
||||
graphRect = RectF(left, y, max(x + colW[c], left + sp(GRAPH_MIN_WIDTH_SP)), y + sp(GRAPH_HEIGHT_SP))
|
||||
y += sp(GRAPH_HEIGHT_SP) + lineGap
|
||||
continue
|
||||
}
|
||||
val px = maxOf(r.label.sizePx, r.vals.maxOfOrNull { it.sizePx } ?: 0f)
|
||||
val baseline = y - ascent(px)
|
||||
placeRun(x, baseline, listOf(r.label))
|
||||
placeRun(x + labelW[c] + lvGap, baseline, r.vals)
|
||||
y += lineH(px) + lineGap
|
||||
}
|
||||
x += colW[c] + gutter
|
||||
}
|
||||
if (hero) {
|
||||
val baseline = pad + (max(bodyH, heroH) - heroH) / 2f - ascent(bigPx)
|
||||
placeRun(pad, baseline, heroSpans, glow = true)
|
||||
}
|
||||
contentW = max(x0 + bodyW, pad + heroW) + pad
|
||||
contentH = pad + max(bodyH, heroH) + pad
|
||||
if (showBattery && s.battery.percent != null) part(listOf(Span("${s.battery.percent}%", colBat, stkPx)))
|
||||
if (showBatteryTemp && s.battery.tempC != null)
|
||||
part(tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, stkPx, stkPx * 0.62f))
|
||||
if (showPower && s.battery.watts > 0f) part(listOf(Span("${fmt1(s.battery.watts)}W", colDim, stkPx)))
|
||||
if (l.isNotEmpty()) stack.add(l)
|
||||
}
|
||||
run {
|
||||
val l = ArrayList<Span>()
|
||||
l += Span("${fmt1(1000f / max(fpsNow, 1f))}ms", colDim, stkPx)
|
||||
if (displayServer.isNotBlank()) { l += Span(" · ", colDim, stkPx); l += Span(displayServer, colDisp, stkPx) }
|
||||
if (showVram && s.vramText() != null) { l += Span(" · ", colDim, stkPx); l += Span("${s.vramText()} vram", colDim, stkPx) }
|
||||
stack.add(l)
|
||||
}
|
||||
if (hdrState != DroidDeckHudHdr.NONE) stack.add(hdrLine(stkPx))
|
||||
|
||||
var statsW = 0f
|
||||
for (l in stack) statsW = max(statsW, runWidth(l))
|
||||
val nameOnTop = gpuName != null && runWidth(gpuName) > statsW
|
||||
if (gpuName != null && !nameOnTop) stack.add(0, gpuName)
|
||||
|
||||
val apiStr = apiLabel()
|
||||
val hasApi = apiStr != "FPS"
|
||||
val apiH = if (hasApi) lineH(stkPx) else 0f
|
||||
val apiGap = if (hasApi) stkLineGap else 0f
|
||||
|
||||
val leftW = runWidth(left); val leftH = lineH(bigPx)
|
||||
val apiW = if (hasApi) measure(apiStr, stkPx) else 0f
|
||||
val leftBlockW = max(leftW, apiW)
|
||||
val leftColH = apiH + apiGap + leftH
|
||||
val stkH = lineH(stkPx)
|
||||
var stackW = 0f
|
||||
for (l in stack) stackW = max(stackW, runWidth(l))
|
||||
val stackTotalH = stack.size * stkH + (stack.size - 1).coerceAtLeast(0) * stkLineGap
|
||||
val innerH = max(leftColH, stackTotalH)
|
||||
val topLineH = if (nameOnTop) stkH + stkLineGap else 0f
|
||||
contentW = pad + leftBlockW + midGap + stackW + pad
|
||||
contentH = pad + topLineH + innerH + pad
|
||||
|
||||
var ly = pad + topLineH + (innerH - leftColH) / 2f
|
||||
if (hasApi) {
|
||||
placeRun(pad, ly - ascent(stkPx), listOf(Span(apiStr, colFps, stkPx)))
|
||||
ly += apiH + apiGap
|
||||
}
|
||||
placeRun(pad, ly - ascent(bigPx), left)
|
||||
var sy = pad + topLineH + (innerH - stackTotalH) / 2f
|
||||
for (l in stack) {
|
||||
placeRun(pad + leftBlockW + midGap, sy - ascent(stkPx), l)
|
||||
sy += stkH + stkLineGap
|
||||
}
|
||||
addSubtleClock(pad, leftAligned = true)
|
||||
if (nameOnTop && gpuName != null) {
|
||||
val end = placeRun(pad, pad - ascent(stkPx), gpuName)
|
||||
contentW = max(contentW, end + pad)
|
||||
}
|
||||
}
|
||||
|
||||
private fun rowHeight(r: HudRow): Float =
|
||||
if (r.key == "showFPSGraph") sp(GRAPH_HEIGHT_SP)
|
||||
else lineH(maxOf(r.label.sizePx, r.vals.maxOfOrNull { it.sizePx } ?: 0f))
|
||||
private fun buildMinimal(s: HudMetrics.Snapshot) {
|
||||
val bigPx = sp(34f); val bigUnitPx = bigPx * 0.32f; val subPx = sp(11.5f); val footPx = sp(9.5f)
|
||||
val stroke = outlineWidth()
|
||||
val left = contentLeft()
|
||||
val inner = panelInset() + stroke
|
||||
|
||||
private fun perCoreRows(s: HudMetrics.Snapshot, labelPx: Float, valuePx: Float, unitPx: Float): List<HudRow> {
|
||||
val pct = s.perCorePercent
|
||||
val clk = s.perCoreClockMhz
|
||||
return (0 until max(pct.size, clk.size)).map { i ->
|
||||
val vals = ArrayList<Span>()
|
||||
vals += numUnit(if (i < pct.size && pct[i] >= 0) pct[i].toString() else null, "%", valuePx, unitPx)
|
||||
vals += Span(" ", colDim, unitPx)
|
||||
vals += numUnit(if (i < clk.size && clk[i] > 0) clk[i].toString() else null, "MHz", valuePx, unitPx)
|
||||
HudRow("showPerCore", Span("C$i", colCpu, labelPx), vals)
|
||||
val minGenerating = differs(fpsNow)
|
||||
val big = listOf(
|
||||
Span(fpsText(fpsNow), colValue, if (minGenerating) bigPx * 0.55f else bigPx),
|
||||
Span("fps", colDim, if (minGenerating) bigUnitPx * 0.8f else bigUnitPx))
|
||||
val sub = ArrayList<Span>()
|
||||
fun low(label: String, value: Float) {
|
||||
if (sub.isNotEmpty()) sub += Span(" · ", colDim, subPx)
|
||||
sub += Span("$label ", colDim, subPx)
|
||||
sub += Span(lowText(value) ?: "—", colFps, subPx)
|
||||
}
|
||||
if (showLow1) low("1%", lows.low1Fps)
|
||||
if (showLow01) low("0.1%", lows.low01Fps)
|
||||
if (showLow001) low("0.01%", lows.low001Fps)
|
||||
val footerLabel = listOf(if (showEngine) engineLabel else "", displayServer)
|
||||
.filter { it.isNotBlank() }.joinToString(" · ")
|
||||
val hdr = if (hdrState != DroidDeckHudHdr.NONE) hdrLine(footPx) else emptyList()
|
||||
|
||||
val (headerBottom, headerRight) = addPanelHeader(left, inner)
|
||||
val x = headerRight
|
||||
|
||||
val colW = maxOf(runWidth(big), runWidth(sub), x - left,
|
||||
max(measure(footerLabel, footPx), runWidth(hdr)), if (showGraph) sp(120f) else 0f)
|
||||
val bigBase = headerBottom + sp(8f) + capHeight(big[0].sizePx)
|
||||
placeRun(left - inkLeft(big[0].text, big[0].sizePx), bigBase, big, glow = true)
|
||||
var last = bigBase
|
||||
if (sub.isNotEmpty()) {
|
||||
last += sp(10f) + capHeight(subPx)
|
||||
placeRun(left - inkLeft(sub[0].text, subPx), last, sub)
|
||||
}
|
||||
if (showGraph) {
|
||||
val top = last + sp(9f)
|
||||
graphRect = RectF(left, top, left + colW, top + sp(24f))
|
||||
last = top + sp(24f)
|
||||
}
|
||||
if (footerLabel.isNotBlank()) {
|
||||
val base = last + sp(8f) + capHeight(footPx)
|
||||
glyphs.add(Glyph(left - inkLeft(footerLabel, footPx), base, footerLabel, blend(colDim), footPx))
|
||||
last = base
|
||||
}
|
||||
if (hdr.isNotEmpty()) {
|
||||
val base = last + sp(6f) + capHeight(footPx)
|
||||
placeRun(left - inkLeft(hdr[0].text, footPx), base, hdr)
|
||||
last = base
|
||||
}
|
||||
measurePaint.textSize = footPx
|
||||
val panel = RectF(panelLeft(), panelInset(), left + colW + sp(34f), last + measurePaint.fontMetrics.descent + sp(9f) + stroke)
|
||||
|
||||
finishPanel(panel, halfRound = true)
|
||||
}
|
||||
|
||||
private fun buildStrip(s: HudMetrics.Snapshot) {
|
||||
@@ -942,27 +1046,66 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
}
|
||||
|
||||
val generating = differs(fpsNow)
|
||||
for (key in size.rowsIn(storedOrder)) {
|
||||
if (!switchOn(key)) continue
|
||||
if (key == "showFPSGraph") {
|
||||
val gw = sp(72f); val gh = h * 0.55f
|
||||
if (x + gw > right) break
|
||||
val fps = ArrayList<Span>()
|
||||
if (apiLabel() != "FPS") fps += Span("${apiLabel()} ", colDim, rowPx)
|
||||
fps += Span(fpsText(fpsNow), colValue, if (generating) fpsPx * 0.8f else fpsPx, glow = true)
|
||||
fps += Span("fps", colDim, unitPx)
|
||||
x = placeRun(x, baseline, fps) + groupGap
|
||||
|
||||
if (showGraph) {
|
||||
val gw = sp(72f); val gh = h * 0.55f
|
||||
if (x + gw <= right) {
|
||||
graphRect = RectF(x, mid - gh / 2f, x + gw, mid + gh / 2f)
|
||||
x += gw + groupGap
|
||||
continue
|
||||
}
|
||||
val spans = if (key == "showFPS") {
|
||||
val fps = ArrayList<Span>()
|
||||
if (apiLabel() != "FPS") fps += Span("${apiLabel()} ", colDim, rowPx)
|
||||
fps += Span(fpsText(fpsNow), colValue, if (generating) fpsPx * 0.8f else fpsPx, glow = true)
|
||||
fps += Span("fps", colDim, unitPx)
|
||||
fps
|
||||
} else {
|
||||
val row = reading(key, s, rowPx, rowPx, unitPx)
|
||||
listOf(row.label, Span(" ", colDim, rowPx)) + row.vals
|
||||
}
|
||||
|
||||
val groups = ArrayList<List<Span>>()
|
||||
run {
|
||||
val l = ArrayList<Span>()
|
||||
fun low(label: String, value: Float) {
|
||||
if (l.isNotEmpty()) l += Span(" ", colDim, rowPx)
|
||||
l += Span("$label ", colDim, rowPx)
|
||||
l += Span(lowText(value) ?: "—", colFps, rowPx)
|
||||
}
|
||||
if (x + runWidth(spans) > right) break
|
||||
x = placeRun(x, baseline, spans) + groupGap
|
||||
if (showLow1) low("1%", lows.low1Fps)
|
||||
if (showLow01) low("0.1%", lows.low01Fps)
|
||||
if (showLow001) low("0.01%", lows.low001Fps)
|
||||
if (l.isNotEmpty()) groups += l
|
||||
}
|
||||
if (showGPU || showGpuTemp) {
|
||||
val l = arrayListOf(Span("GPU", colGpu, rowPx))
|
||||
if (showGPU) l += Span(" ${s.gpuPercent ?: "—"}%", colGpu, rowPx)
|
||||
if (showGpuTemp && s.gpuTempC != null) { l += Span(" ", colDim, rowPx); l += tempSpans(s.gpuTempC, HudMetrics.TempSensor.GPU, rowPx, unitPx) }
|
||||
groups += l
|
||||
}
|
||||
if (showCPU || showCpuTemp) {
|
||||
val l = arrayListOf(Span("CPU", colCpu, rowPx))
|
||||
if (showCPU) l += Span(" ${s.cpuPercent ?: "—"}%", colCpu, rowPx)
|
||||
if (showCpuTemp && s.cpuTempC != null) { l += Span(" ", colDim, rowPx); l += tempSpans(s.cpuTempC, HudMetrics.TempSensor.CPU, rowPx, unitPx) }
|
||||
groups += l
|
||||
}
|
||||
if (showVram) s.vramText()?.let { groups += listOf(Span("VRAM $it", colVram, rowPx)) }
|
||||
if (showRAM) groups += listOf(Span("RAM ${s.ramPercent.roundToInt()}%", colRam, rowPx))
|
||||
if (showBattery || showPower || showBatteryTemp) {
|
||||
val l = ArrayList<Span>()
|
||||
fun part(spans: List<Span>) {
|
||||
l += if (l.isEmpty()) Span("BAT ", colBat, rowPx) else Span(" ", colDim, rowPx)
|
||||
l += spans
|
||||
}
|
||||
if (showBattery && s.battery.percent != null) part(listOf(Span("${s.battery.percent}%", colBat, rowPx)))
|
||||
if (showBatteryTemp && s.battery.tempC != null)
|
||||
part(tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, rowPx, unitPx))
|
||||
if (showPower && s.battery.watts > 0f) part(listOf(Span("${fmt1(s.battery.watts)}W", colDim, rowPx)))
|
||||
if (l.isNotEmpty()) groups += l
|
||||
}
|
||||
if (displayServer.isNotBlank()) groups += listOf(Span(displayServer, colDisp, rowPx))
|
||||
if (hdrState != DroidDeckHudHdr.NONE) groups += hdrLine(rowPx)
|
||||
if (showGpuModel && gpuNameText().isNotBlank()) groups += gpuModelSpans(rowPx, colDim, compact = true)
|
||||
|
||||
for (g in groups) {
|
||||
if (x + runWidth(g) > right) break
|
||||
x = placeRun(x, baseline, g) + groupGap
|
||||
}
|
||||
|
||||
stripRect = RectF(0f, 0f, w, h)
|
||||
@@ -982,6 +1125,168 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
return inkRect.left.toFloat()
|
||||
}
|
||||
|
||||
private fun layoutColumn(rows: List<HudRow>, x: Float, y0: Float,
|
||||
rowPx: Float, lineGap: Float, lvGap: Float): Pair<Float, Float> {
|
||||
if (rows.isEmpty()) return Pair(y0, x)
|
||||
var labelCol = 0f
|
||||
for (r in rows) if (!r.inline) labelCol = max(labelCol, measure(r.label.text, rowPx))
|
||||
val h = lineH(rowPx); val asc = ascent(rowPx)
|
||||
var y = y0; var right = x
|
||||
for (r in rows) {
|
||||
val baseline = y - asc
|
||||
placeRun(x, baseline, listOf(r.label))
|
||||
val valX = if (r.inline) x + measure(r.label.text, rowPx) + lvGap
|
||||
else x + labelCol + lvGap
|
||||
val end = placeRun(valX, baseline, r.vals)
|
||||
right = max(right, end)
|
||||
y += h + lineGap
|
||||
}
|
||||
return Pair(y - lineGap, right)
|
||||
}
|
||||
|
||||
private fun layoutWrap(fragments: List<List<Span>>, x: Float, y0: Float, maxWidth: Float,
|
||||
px: Float, lineGap: Float): Pair<Float, Float> {
|
||||
if (fragments.isEmpty()) return Pair(y0, x)
|
||||
val h = lineH(px); val asc = ascent(px)
|
||||
val sepW = measure(" · ", px)
|
||||
var cx = x; var y = y0; var right = x; var firstOnLine = true
|
||||
for (frag in fragments) {
|
||||
val w = runWidth(frag)
|
||||
if (!firstOnLine && (cx + sepW + w - x) > maxWidth) { y += h + lineGap; cx = x; firstOnLine = true }
|
||||
if (!firstOnLine) { placeRun(cx, y - asc, listOf(Span(" · ", colDim, px))); cx += sepW }
|
||||
val end = placeRun(cx, y - asc, frag)
|
||||
cx = end; right = max(right, end); firstOnLine = false
|
||||
}
|
||||
return Pair(y + h, right)
|
||||
}
|
||||
|
||||
private fun buildMega(s: HudMetrics.Snapshot) {
|
||||
val rowPx = sp(11.5f); val unitPx = rowPx * 0.62f; val bandPx = sp(9.5f)
|
||||
val pad = sp(10f); val lineGap = sp(3.5f); val lvGap = sp(7f); val gutter = sp(16f)
|
||||
|
||||
val left = ArrayList<HudRow>()
|
||||
if (showGpuModel && gpuNameText().isNotBlank())
|
||||
left.add(HudRow(Span("GPU", colGpu, rowPx), gpuModelSpans(rowPx, colValue)))
|
||||
if (showGPU && hasGpuStats(s)) {
|
||||
val v = ArrayList<Span>()
|
||||
v += numUnit(s.gpuPercent?.toString(), "%", rowPx, unitPx)
|
||||
if (showGpuTemp) tempSpans(s.gpuTempC, HudMetrics.TempSensor.GPU, rowPx, unitPx)
|
||||
.let { if (it.isNotEmpty()) { v += gap(unitPx); v += it } }
|
||||
v += gap(unitPx); v += numUnit(s.gpuClockMhz?.toString(), "MHz", rowPx, unitPx)
|
||||
left.add(HudRow(Span("GPU", colGpu, rowPx), v))
|
||||
}
|
||||
if (showCPU) {
|
||||
val v = ArrayList<Span>()
|
||||
v += numUnit(s.cpuPercent?.toString(), "%", rowPx, unitPx)
|
||||
v += gap(unitPx); v += numUnit(s.cpuClockMhz?.toString(), "MHz", rowPx, unitPx)
|
||||
if (showCpuTemp) tempSpans(s.cpuTempC, HudMetrics.TempSensor.CPU, rowPx, unitPx)
|
||||
.let { if (it.isNotEmpty()) { v += gap(unitPx); v += it } }
|
||||
left.add(HudRow(Span("CPU", colCpu, rowPx), v))
|
||||
}
|
||||
if (showPerCore) {
|
||||
val pct = s.perCorePercent; val clk = s.perCoreClockMhz
|
||||
val n = max(pct.size, clk.size)
|
||||
for (i in 0 until n) {
|
||||
val v = ArrayList<Span>()
|
||||
v += numUnit(if (i < pct.size && pct[i] >= 0) pct[i].toString() else null, "%", rowPx, unitPx)
|
||||
v += gap(unitPx)
|
||||
v += numUnit(if (i < clk.size && clk[i] > 0) clk[i].toString() else null, "MHz", rowPx, unitPx)
|
||||
left.add(HudRow(Span("C$i", colCpu, rowPx), v))
|
||||
}
|
||||
}
|
||||
|
||||
val right = ArrayList<HudRow>()
|
||||
if (showVram && s.vramText() != null)
|
||||
right.add(HudRow(Span("VRAM", colVram, rowPx), valueUnit(s.vramText()!!, rowPx, unitPx)))
|
||||
if (showRAM) {
|
||||
val v = ArrayList<Span>()
|
||||
v += valueUnit(s.ramUsedText(), rowPx, unitPx)
|
||||
v += Span("/", colDim, unitPx); v += valueUnit(s.ramTotalText(), rowPx, unitPx)
|
||||
v += gap(unitPx); v += numUnit(s.ramPercent.roundToInt().toString(), "%", rowPx, unitPx)
|
||||
right.add(HudRow(Span("RAM", colRam, rowPx), v))
|
||||
}
|
||||
if (showSwap && s.swapUsedText() != null) {
|
||||
val v = ArrayList<Span>()
|
||||
v += valueUnit(s.swapUsedText()!!, rowPx, unitPx)
|
||||
s.swapTotalText()?.let { v += Span("/", colDim, unitPx); v += valueUnit(it, rowPx, unitPx) }
|
||||
right.add(HudRow(Span("SWP", colRam, rowPx), v))
|
||||
}
|
||||
if (showNet && s.netDownBps != null) {
|
||||
val d = (s.netDownBps ?: 0L) / 1024L
|
||||
val u = (s.netUpBps ?: 0L) / 1024L
|
||||
val v = ArrayList<Span>()
|
||||
v += Span("↓", colDim, unitPx); v += Span(d.toString(), colValue, rowPx)
|
||||
v += Span(" ↑", colDim, unitPx); v += Span(u.toString(), colValue, rowPx)
|
||||
v += Span("KB/s", colDim, unitPx)
|
||||
right.add(HudRow(Span("NET", colFps, rowPx), v))
|
||||
}
|
||||
if (showBattery || showPower || showBatteryTemp) {
|
||||
val v = ArrayList<Span>(); var any = false
|
||||
if (showBattery && s.battery.percent != null) { v += numUnit(s.battery.percent.toString(), "%", rowPx, unitPx); any = true }
|
||||
if (showBatteryTemp) tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, rowPx, unitPx)
|
||||
.let { if (it.isNotEmpty()) { if (any) v += gap(unitPx); v += it; any = true } }
|
||||
if (showPower && s.battery.watts > 0f) { if (any) v += gap(unitPx); v += numUnit(fmt1(s.battery.watts), "W", rowPx, unitPx); any = true }
|
||||
if (any) right.add(HudRow(Span("BAT", colBat, rowPx), v))
|
||||
}
|
||||
if (showFPS) {
|
||||
val v = ArrayList<Span>()
|
||||
v += glowing(numUnit(fpsText(fpsNow), "FPS", rowPx, unitPx))
|
||||
v += gap(unitPx); v += numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", rowPx, unitPx)
|
||||
right.add(HudRow(Span(apiLabel(), colFps, rowPx), v))
|
||||
right.add(HudRow(Span("AVG", colLo, rowPx), numUnit(fmt1(fpsAvg), "FPS", rowPx, unitPx)))
|
||||
if (showLow1)
|
||||
right.add(HudRow(Span("1%", colLo, rowPx), numUnit(lowText(lows.low1Fps), "FPS", rowPx, unitPx)))
|
||||
if (showLow01)
|
||||
right.add(HudRow(Span("0.1%", colLo, rowPx), numUnit(lowText(lows.low01Fps), "FPS", rowPx, unitPx)))
|
||||
if (showLow001)
|
||||
right.add(HudRow(Span("0.01%", colLo, rowPx), numUnit(lowText(lows.low001Fps), "FPS", rowPx, unitPx)))
|
||||
}
|
||||
|
||||
val (leftBottom, leftRight) = layoutColumn(left, pad, pad, rowPx, lineGap, lvGap)
|
||||
val rightX = (if (left.isEmpty()) pad else leftRight + gutter)
|
||||
val (rightBottom, rightRight) = layoutColumn(right, rightX, pad, rowPx, lineGap, lvGap)
|
||||
var y = max(leftBottom, rightBottom)
|
||||
var maxRight = max(leftRight, rightRight)
|
||||
|
||||
val band = ArrayList<List<Span>>()
|
||||
if (showResolution) band.add(listOf(Span("RES ", colDim, bandPx), Span(resolutionString(), colValue, bandPx)))
|
||||
if (displayServer.isNotBlank()) band.add(listOf(Span("DISP ", colDim, bandPx), Span(displayServer, colDisp, bandPx)))
|
||||
if (hdrState != DroidDeckHudHdr.NONE) band.add(listOf(Span("HDR ", colDim, bandPx)) + hdrValue(bandPx))
|
||||
if (showProton && wineVersion.isNotBlank()) band.add(listOf(Span(wineVersion, colVram, bandPx)))
|
||||
if (showSession) band.add(listOf(Span("elapsed ", colDim, bandPx), Span(elapsedString(), colValue, bandPx)))
|
||||
if (band.isNotEmpty()) {
|
||||
y += sp(4f)
|
||||
val (bBottom, bRight) = layoutWrap(band, pad, y, max(maxRight - pad, sp(180f)), bandPx, lineGap)
|
||||
y = bBottom; maxRight = max(maxRight, bRight)
|
||||
}
|
||||
|
||||
if (showGraph) {
|
||||
y += sp(3f)
|
||||
val gh = sp(22f)
|
||||
val gr = max(maxRight, pad + sp(220f))
|
||||
graphRect = RectF(pad, y, gr, y + gh)
|
||||
maxRight = max(maxRight, gr)
|
||||
y += gh
|
||||
}
|
||||
|
||||
val dxLine = dxVersionLabeled()
|
||||
val hasDx = showDxVer && dxLine.isNotBlank()
|
||||
if (hasDx) {
|
||||
y += sp(4f)
|
||||
maxRight = max(maxRight, placeRun(pad, y - ascent(bandPx), listOf(Span(dxLine, colDim, bandPx))))
|
||||
y += lineH(bandPx)
|
||||
}
|
||||
if (showWrapper && graphicsWrapper.isNotBlank()) {
|
||||
y += if (hasDx) sp(1f) else sp(4f)
|
||||
maxRight = max(maxRight, placeRun(pad, y - ascent(bandPx), listOf(Span(graphicsWrapper, colDim, bandPx))))
|
||||
y += lineH(bandPx)
|
||||
}
|
||||
|
||||
contentW = maxRight + pad
|
||||
contentH = y + pad
|
||||
addSubtleClock(pad)
|
||||
}
|
||||
|
||||
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
|
||||
if (stripRect != null) { setMeasuredDimension(contentW.roundToInt(), resolveSize(contentH.roundToInt(), heightMeasureSpec)); return }
|
||||
setMeasuredDimension(
|
||||
@@ -1262,8 +1567,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
const val MIN_SCALE = 0.5f
|
||||
const val MAX_SCALE = 2f
|
||||
const val GRAPH_CLIP_MS = 49.9f
|
||||
const val GRAPH_HEIGHT_SP = 22f
|
||||
const val GRAPH_MIN_WIDTH_SP = 160f
|
||||
|
||||
fun parseIntOr(s: String?, d: Int): Int = try { s?.trim()?.toInt() ?: d } catch (e: Exception) { d }
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package com.droiddeck.launcher.hud
|
||||
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
internal class FrameStats {
|
||||
@@ -67,6 +66,15 @@ internal class FrameStats {
|
||||
count++
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun addIfNew(frametimeNs: Long, timeNs: Long, rebase: Boolean): Boolean {
|
||||
if (timeNs <= lastPresentNs) return false
|
||||
val elapsedNs = if (rebase && lastPresentNs != 0L) timeNs - lastPresentNs else frametimeNs
|
||||
if (elapsedNs <= 0L) return false
|
||||
add(elapsedNs, timeNs)
|
||||
return true
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun reset() {
|
||||
graph.fill(0f)
|
||||
@@ -160,11 +168,7 @@ internal class FrameStats {
|
||||
}
|
||||
}
|
||||
|
||||
internal class GameFrameFeed(
|
||||
private val file: File,
|
||||
val stats: FrameStats = FrameStats(),
|
||||
private val clockControl: File? = null,
|
||||
) {
|
||||
internal class GameFrameFeed(private val file: File, val stats: FrameStats = FrameStats()) {
|
||||
private var handle = 0L
|
||||
private var nextOpenNs = 0L
|
||||
private var lastRingFrameNs = 0L
|
||||
@@ -176,8 +180,6 @@ internal class GameFrameFeed(
|
||||
private var lastCompositorNs = 0L
|
||||
@Volatile private var compositorFrames = 0L
|
||||
private var seenCompositorFrames = 0L
|
||||
private var clockShiftNs = 0L
|
||||
private var clockShiftReadNs = Long.MIN_VALUE
|
||||
|
||||
@Volatile var engine = ""
|
||||
private set
|
||||
@@ -206,14 +208,11 @@ internal class GameFrameFeed(
|
||||
}
|
||||
val n = HudFrames.nativePoll(handle, frametimes, times)
|
||||
if (n > 0) {
|
||||
var shift = guestClockShift(nowNs, SHIFT_NS)
|
||||
if (nowNs - (times[n - 1] + shift) > LIVE_NS) shift = guestClockShift(nowNs, SHIFT_RECHECK_NS)
|
||||
for (i in 0 until n) times[i] += shift
|
||||
if (!fromGamescope) {
|
||||
stats.reset()
|
||||
fromGamescope = true
|
||||
var rebase = !fromGamescope
|
||||
fromGamescope = true
|
||||
for (i in 0 until n) {
|
||||
if (stats.addIfNew(frametimes[i], times[i], rebase)) rebase = false
|
||||
}
|
||||
for (i in 0 until n) stats.add(frametimes[i], times[i])
|
||||
lastRingFrameNs = times[n - 1]
|
||||
} else if (lastRingFrameNs != 0L && nowNs - lastRingFrameNs > LIVE_NS) {
|
||||
fromGamescope = false
|
||||
@@ -226,16 +225,6 @@ internal class GameFrameFeed(
|
||||
return n > 0 || compositorAdded
|
||||
}
|
||||
|
||||
internal fun guestClockShift(nowNs: Long, maxAgeNs: Long): Long {
|
||||
val control = clockControl ?: return 0L
|
||||
if (clockShiftReadNs != Long.MIN_VALUE && nowNs - clockShiftReadNs < maxAgeNs) return clockShiftNs
|
||||
clockShiftReadNs = nowNs
|
||||
clockShiftNs = runCatching {
|
||||
RandomAccessFile(control, "r").use { if (it.length() < Long.SIZE_BYTES) 0L else java.lang.Long.reverseBytes(it.readLong()) }
|
||||
}.getOrDefault(0L).coerceAtLeast(0L)
|
||||
return clockShiftNs
|
||||
}
|
||||
|
||||
fun onCompositorFrame(nowNs: Long) {
|
||||
if (fromGamescope) {
|
||||
lastCompositorNs = 0L
|
||||
@@ -273,11 +262,6 @@ internal class GameFrameFeed(
|
||||
private const val LIVE_NS = 2_000_000_000L
|
||||
private const val STALE_NS = 5_000_000_000L
|
||||
private const val INFO_NS = 500_000_000L
|
||||
private const val SHIFT_NS = 1_000_000_000L
|
||||
private const val SHIFT_RECHECK_NS = 100_000_000L
|
||||
private const val CLOCK_CONTROL_PATH = "tmp/.bl-clock"
|
||||
|
||||
fun forRoot(root: File) = GameFrameFeed(File(root, HudFrames.PATH), clockControl = File(root, CLOCK_CONTROL_PATH))
|
||||
|
||||
fun engineLabel(name: String): String = when (name) {
|
||||
"DXVK" -> "DXVK"
|
||||
|
||||
@@ -14,8 +14,6 @@
|
||||
|
||||
package com.droiddeck.launcher.hud;
|
||||
|
||||
import com.droiddeck.launcher.session.BatteryRuntimeEstimator;
|
||||
|
||||
import android.app.ActivityManager;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
@@ -562,9 +560,10 @@ public class HudMetrics {
|
||||
return sawSignal;
|
||||
}
|
||||
|
||||
private final BatteryRuntimeEstimator batteryRuntimeEstimator = new BatteryRuntimeEstimator();
|
||||
private Boolean lastBatteryDischarging = null;
|
||||
private Boolean lastBatteryCharging = null;
|
||||
private Double smoothedBatteryRuntimeHours = null;
|
||||
private static final double MAX_RUNTIME_HOURS = 72.0;
|
||||
private static final double RUNTIME_SMOOTHING_OLD_WEIGHT = 0.65;
|
||||
private static final double RUNTIME_SMOOTHING_NEW_WEIGHT = 0.35;
|
||||
|
||||
public Battery collectBattery() {
|
||||
BatteryManager bm = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
|
||||
@@ -582,22 +581,11 @@ public class HudMetrics {
|
||||
|
||||
int st = status.getIntExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_UNKNOWN);
|
||||
boolean charging = st == BatteryManager.BATTERY_STATUS_CHARGING || st == BatteryManager.BATTERY_STATUS_FULL;
|
||||
boolean discharging = st == BatteryManager.BATTERY_STATUS_DISCHARGING
|
||||
|| st == BatteryManager.BATTERY_STATUS_NOT_CHARGING;
|
||||
if (lastBatteryDischarging != null && lastBatteryDischarging.booleanValue() != discharging) {
|
||||
batteryRuntimeEstimator.reset();
|
||||
}
|
||||
lastBatteryDischarging = discharging;
|
||||
if (st == BatteryManager.BATTERY_STATUS_UNKNOWN) {
|
||||
Boolean sysCharging = readChargingFromPowerSupply();
|
||||
if (sysCharging != null) charging = sysCharging;
|
||||
}
|
||||
if (lastBatteryCharging != null
|
||||
&& lastBatteryCharging.booleanValue() != charging) {
|
||||
batteryRuntimeEstimator.reset();
|
||||
}
|
||||
lastBatteryCharging = charging;
|
||||
long currentMicroAmps = BatteryRuntimeEstimator.toMicroamps(bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW));
|
||||
long currentMicroAmps = Math.abs(bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW));
|
||||
long chargeCounter = bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER);
|
||||
int voltageMv = status.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);
|
||||
|
||||
@@ -618,16 +606,36 @@ public class HudMetrics {
|
||||
if (uw != null && uw != 0L) watts = (float) (Math.abs(uw) / 1_000_000.0);
|
||||
}
|
||||
|
||||
Double runtimeHours = !charging
|
||||
? batteryRuntimeEstimator.estimateHours(chargeCounter, Math.abs((double) currentMicroAmps))
|
||||
: null;
|
||||
String runtimeText;
|
||||
if (st == BatteryManager.BATTERY_STATUS_FULL || (percent != null && percent >= 100)) runtimeText = "Full";
|
||||
else if (charging) runtimeText = "Charging";
|
||||
else runtimeText = BatteryRuntimeEstimator.formatDuration(runtimeHours);
|
||||
if (charging) {
|
||||
smoothedBatteryRuntimeHours = null;
|
||||
runtimeText = "LEFT CHG";
|
||||
} else if (currentMicroAmps <= 0L || chargeCounter <= 0L) {
|
||||
runtimeText = null;
|
||||
} else {
|
||||
double rawHours = (double) chargeCounter / (double) currentMicroAmps;
|
||||
if (!Double.isFinite(rawHours) || rawHours <= 0.0 || rawHours > MAX_RUNTIME_HOURS) {
|
||||
runtimeText = null;
|
||||
} else {
|
||||
double smoothed = smoothedBatteryRuntimeHours == null ? rawHours
|
||||
: (smoothedBatteryRuntimeHours * RUNTIME_SMOOTHING_OLD_WEIGHT)
|
||||
+ (rawHours * RUNTIME_SMOOTHING_NEW_WEIGHT);
|
||||
smoothedBatteryRuntimeHours = smoothed;
|
||||
runtimeText = "LEFT " + formatRuntimeHours(smoothed);
|
||||
}
|
||||
}
|
||||
return new Battery(watts, charging, percent, tempC, runtimeText);
|
||||
}
|
||||
|
||||
private static String formatRuntimeHours(double hours) {
|
||||
int totalMinutes = Math.max(1, (int) Math.round(hours * 60.0));
|
||||
int wholeHours = totalMinutes / 60;
|
||||
int minutes = totalMinutes % 60;
|
||||
if (wholeHours > 0 && minutes > 0) return wholeHours + "h " + minutes + "m";
|
||||
if (wholeHours > 0) return wholeHours + "h";
|
||||
return minutes + "m";
|
||||
}
|
||||
|
||||
private static float currentRawToAmps(long raw) {
|
||||
if (raw == 0L || raw == Long.MIN_VALUE) return 0f;
|
||||
long a = Math.abs(raw);
|
||||
@@ -643,10 +651,15 @@ public class HudMetrics {
|
||||
return currentRawToAmps(raw);
|
||||
}
|
||||
|
||||
static Integer fastestCoreMhz(int[] perCoreMhz) {
|
||||
int max = 0;
|
||||
for (int mhz : perCoreMhz) max = Math.max(max, mhz);
|
||||
return max > 0 ? max : null;
|
||||
public Integer getCpuClockMhz() {
|
||||
int cores = Runtime.getRuntime().availableProcessors();
|
||||
long maxKhz = 0;
|
||||
for (int i = 0; i < cores; i++) {
|
||||
Long cur = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/scaling_cur_freq");
|
||||
if (cur != null && cur > maxKhz) maxKhz = cur;
|
||||
}
|
||||
if (maxKhz <= 0) return null;
|
||||
return (int) (maxKhz / 1000L);
|
||||
}
|
||||
|
||||
private List<String> gpuClockPathsCache = null;
|
||||
@@ -796,8 +809,7 @@ public class HudMetrics {
|
||||
if (mango != null) return mangoSnapshot(mango);
|
||||
Integer cpu = getCpuUsagePercent();
|
||||
Integer gpu = getGpuUsagePercent();
|
||||
int[] perCoreClk = getPerCoreClockMhz();
|
||||
Integer cpuClk = fastestCoreMhz(perCoreClk);
|
||||
Integer cpuClk = getCpuClockMhz();
|
||||
Integer gpuClk = getGpuClockMhz();
|
||||
Integer cpuTemp = getCpuTempC();
|
||||
Integer gpuTemp = getGpuTempC();
|
||||
@@ -817,6 +829,7 @@ public class HudMetrics {
|
||||
Battery battery = collectBattery();
|
||||
|
||||
int[] perCorePct = readPerCorePercent();
|
||||
int[] perCoreClk = getPerCoreClockMhz();
|
||||
long[] swap = getSwapBytes();
|
||||
long[] net = readNetRateBps();
|
||||
|
||||
@@ -835,65 +848,26 @@ public class HudMetrics {
|
||||
Battery android = collectBattery();
|
||||
MangoReadings.Battery bat = m.battery();
|
||||
Battery battery = bat == null ? android : new Battery(bat.getWatts(), bat.getCharging(),
|
||||
bat.getPercent() != null ? bat.getPercent() : android.percent, android.tempC, bat.getRuntimeText());
|
||||
bat.getPercent() != null ? bat.getPercent() : android.percent, android.tempC, android.runtimeText);
|
||||
long[] net = readNetRateBps();
|
||||
int[] perCoreClk = getPerCoreClockMhz();
|
||||
return new Snapshot(cpu != null ? cpu.getPercent() : null, m.gpuPercent(), fastestCoreMhz(perCoreClk), m.gpuClockMhz(),
|
||||
return new Snapshot(cpu != null ? cpu.getPercent() : null, m.gpuPercent(), getCpuClockMhz(), m.gpuClockMhz(),
|
||||
m.cpuTempC(), m.gpuTempC(), used, total, total > 0 ? used * 100f / total : 0f, m.vramBytes(), battery,
|
||||
cpu != null ? cpu.getPerCore() : new int[0], perCoreClk,
|
||||
cpu != null ? cpu.getPerCore() : new int[0], getPerCoreClockMhz(),
|
||||
mem != null && mem.getSwapTotalBytes() > 0 ? mem.getSwapUsedBytes() : null,
|
||||
mem != null && mem.getSwapTotalBytes() > 0 ? mem.getSwapTotalBytes() : null,
|
||||
net == null ? null : net[0], net == null ? null : net[1]);
|
||||
}
|
||||
|
||||
private final java.util.Map<Integer, long[][]> lastTimeInState = new java.util.HashMap<>();
|
||||
|
||||
public synchronized int[] getPerCoreClockMhz() {
|
||||
public int[] getPerCoreClockMhz() {
|
||||
int cores = Runtime.getRuntime().availableProcessors();
|
||||
int[] out = new int[Math.max(0, cores)];
|
||||
for (int i = 0; i < out.length; i++) {
|
||||
long[][] table = readTimeInState("/sys/devices/system/cpu/cpu" + i + "/cpufreq/stats/time_in_state");
|
||||
long khz = table == null ? -1L : averageKhz(lastTimeInState.put(i, table), table);
|
||||
if (khz <= 0L) {
|
||||
Long cur = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/scaling_cur_freq");
|
||||
khz = cur != null ? cur : 0L;
|
||||
}
|
||||
out[i] = khz > 0L ? (int) (khz / 1000L) : 0;
|
||||
Long cur = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/scaling_cur_freq");
|
||||
out[i] = (cur != null && cur > 0) ? (int) (cur / 1000L) : 0;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
static long averageKhz(long[][] before, long[][] after) {
|
||||
if (before == null || after == null || !java.util.Arrays.equals(before[0], after[0])) return -1L;
|
||||
long weighted = 0L, time = 0L;
|
||||
for (int i = 0; i < after[0].length; i++) {
|
||||
long dt = after[1][i] - before[1][i];
|
||||
if (dt <= 0L) continue;
|
||||
weighted += after[0][i] * dt;
|
||||
time += dt;
|
||||
}
|
||||
return time > 0L ? weighted / time : -1L;
|
||||
}
|
||||
|
||||
private static long[][] readTimeInState(String path) {
|
||||
List<long[]> rows = new ArrayList<>();
|
||||
try (BufferedReader r = new BufferedReader(new FileReader(path))) {
|
||||
String line;
|
||||
while ((line = r.readLine()) != null) {
|
||||
String[] parts = line.trim().split("\\s+");
|
||||
if (parts.length < 2) continue;
|
||||
try { rows.add(new long[] { Long.parseLong(parts[0]), Long.parseLong(parts[1]) }); }
|
||||
catch (NumberFormatException ignored) {}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
if (rows.isEmpty()) return null;
|
||||
long[][] table = new long[2][rows.size()];
|
||||
for (int i = 0; i < rows.size(); i++) { table[0][i] = rows.get(i)[0]; table[1][i] = rows.get(i)[1]; }
|
||||
return table;
|
||||
}
|
||||
|
||||
private long[] lastCoreTotal = null;
|
||||
private long[] lastCoreIdle = null;
|
||||
private static final int PER_CORE_STAT = 1, PER_CORE_ESTIMATE = 2;
|
||||
|
||||
@@ -2,18 +2,13 @@ package com.droiddeck.launcher.hud
|
||||
|
||||
import android.os.Environment
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.BatteryRuntimeEstimator
|
||||
import java.io.File
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
internal class MangoReadings(private val sessionDir: File, private val rootDir: File) {
|
||||
class Cpu(val percent: Int, val perCore: IntArray)
|
||||
class Memory(val usedBytes: Long, val totalBytes: Long, val swapUsedBytes: Long, val swapTotalBytes: Long)
|
||||
class Battery(val percent: Int?, val watts: Float, val charging: Boolean, val runtimeText: String?)
|
||||
|
||||
private val batteryRuntimeEstimator = BatteryRuntimeEstimator()
|
||||
private var lastBatteryDischarging: Boolean? = null
|
||||
class Battery(val percent: Int?, val watts: Float, val charging: Boolean)
|
||||
|
||||
private val cpuTimes = HashMap<String, LongArray>()
|
||||
private val cpuPercents = HashMap<String, Int>()
|
||||
@@ -111,113 +106,32 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
|
||||
fun vramBytes(): Long? = fresh(File(rootDir, VRAM_FILE), VRAM_FRESH_MS)?.let(::readLong)?.takeIf { it > 0 }
|
||||
|
||||
fun battery(): Battery? {
|
||||
val dirs = File(sessionDir, "sys/power_supply").listFiles { f -> f.name.contains("BAT") }?.sortedBy { it.name }?.take(2)
|
||||
val dirs = File(sessionDir, "sys/power_supply").listFiles { f -> f.name.contains("BAT") }?.sortedBy { it.name }
|
||||
if (dirs.isNullOrEmpty()) return null
|
||||
|
||||
var weightedChargeNow = 0.0
|
||||
var weightedChargeFull = 0.0
|
||||
var allHaveWeightedCharge = true
|
||||
val perBatteryPercents = ArrayList<Int>()
|
||||
var runtimeChargeUah = 0.0
|
||||
var runtimeChargeComplete = true
|
||||
var aggregateCurrentUa = 0.0
|
||||
var currentComplete = true
|
||||
var watts = 0.0
|
||||
var anyDischarging = false
|
||||
var anyChargingStatus = false
|
||||
var allFull = true
|
||||
var suppliedRuntimeSeconds: Long? = null
|
||||
|
||||
var chargeNow = 0f
|
||||
var chargeFull = 0f
|
||||
var watts = 0f
|
||||
var charging = false
|
||||
for (dir in dirs) {
|
||||
val status = runCatching { File(dir, "status").readLines().firstOrNull() }.getOrNull()
|
||||
val isDischarging = status == "Discharging" || status == "Not charging"
|
||||
if (isDischarging) anyDischarging = true
|
||||
if (status == "Charging" || status == "Unknown") anyChargingStatus = true
|
||||
if (status != "Full") allFull = false
|
||||
|
||||
val chargeNowFile = File(dir, "charge_now")
|
||||
val chargeFullFile = File(dir, "charge_full")
|
||||
val energyNowFile = File(dir, "energy_now")
|
||||
val energyFullFile = File(dir, "energy_full")
|
||||
val voltageFile = File(dir, "voltage_now")
|
||||
val chargeNow = if (chargeNowFile.isFile) readFloat(chargeNowFile)?.toDouble() else null
|
||||
val chargeFull = if (chargeFullFile.isFile) readFloat(chargeFullFile)?.toDouble() else null
|
||||
val energyNow = if (energyNowFile.isFile) readFloat(energyNowFile)?.toDouble() else null
|
||||
val energyFull = if (energyFullFile.isFile) readFloat(energyFullFile)?.toDouble() else null
|
||||
val voltageUv = if (voltageFile.isFile) readFloat(voltageFile)?.toDouble() else null
|
||||
|
||||
val nowForPercent: Double? = when {
|
||||
chargeNow != null && chargeNow >= 0.0 -> chargeNow
|
||||
energyNow != null && voltageUv != null -> BatteryRuntimeEstimator.chargeMicroampHoursFromEnergy(energyNow, voltageUv)
|
||||
else -> null
|
||||
}
|
||||
val fullForPercent: Double? = when {
|
||||
chargeFull != null && chargeFull > 0.0 -> chargeFull
|
||||
energyFull != null && voltageUv != null -> BatteryRuntimeEstimator.chargeMicroampHoursFromEnergy(energyFull, voltageUv)
|
||||
else -> null
|
||||
}
|
||||
if (nowForPercent != null && fullForPercent != null && fullForPercent > 0.0) {
|
||||
weightedChargeNow += nowForPercent
|
||||
weightedChargeFull += fullForPercent
|
||||
perBatteryPercents += (nowForPercent * 100.0 / fullForPercent).roundToInt().coerceIn(0, 100)
|
||||
if (status == "Charging" || status == "Unknown" || status == "Full") charging = true
|
||||
val now = File(dir, "charge_now").takeIf { it.exists() } ?: File(dir, "energy_now")
|
||||
val full = File(dir, "charge_full").takeIf { it.exists() } ?: File(dir, "energy_full")
|
||||
if (now.exists()) {
|
||||
chargeNow += (readFloat(now) ?: 0f) / 1_000_000f
|
||||
chargeFull += (readFloat(full) ?: 0f) / 1_000_000f
|
||||
} else {
|
||||
allHaveWeightedCharge = false
|
||||
readFloat(File(dir, "capacity"))?.roundToInt()?.coerceIn(0, 100)?.let { perBatteryPercents += it }
|
||||
chargeNow += (readFloat(File(dir, "capacity")) ?: 0f) / 100f
|
||||
chargeFull = dirs.size.toFloat()
|
||||
}
|
||||
|
||||
when {
|
||||
chargeNow != null && chargeNow >= 0.0 -> runtimeChargeUah += chargeNow
|
||||
energyNow != null && voltageUv != null ->
|
||||
BatteryRuntimeEstimator.chargeMicroampHoursFromEnergy(energyNow, voltageUv)?.let { runtimeChargeUah += it }
|
||||
?: run { runtimeChargeComplete = false }
|
||||
else -> runtimeChargeComplete = false
|
||||
}
|
||||
|
||||
if (dirs.size == 1) {
|
||||
suppliedRuntimeSeconds = readLong(File(dir, "time_to_empty_avg"))?.takeIf { it > 0L }
|
||||
?: readLong(File(dir, "time_to_empty_now"))?.takeIf { it > 0L }
|
||||
?: suppliedRuntimeSeconds
|
||||
}
|
||||
|
||||
val currentFile = File(dir, "current_now")
|
||||
val powerFile = File(dir, "power_now")
|
||||
val currentNow = if (currentFile.isFile) readFloat(currentFile)?.toDouble() else null
|
||||
val currentForEta = when {
|
||||
currentNow != null -> abs(currentNow)
|
||||
powerFile.isFile && voltageUv != null -> readFloat(powerFile)?.toDouble()?.let {
|
||||
BatteryRuntimeEstimator.currentMicroampsFromPower(it, voltageUv)
|
||||
}
|
||||
else -> null
|
||||
}
|
||||
if (currentForEta == null) currentComplete = false else aggregateCurrentUa += currentForEta
|
||||
|
||||
if (isDischarging) {
|
||||
val power = if (powerFile.isFile) readFloat(powerFile)?.toDouble() else null
|
||||
if (power != null) watts += abs(power) / 1_000_000.0
|
||||
else if (currentNow != null && voltageUv != null) watts += abs(currentNow * voltageUv) / 1_000_000_000_000.0
|
||||
if (!charging) {
|
||||
val power = File(dir, "power_now")
|
||||
watts += if (power.exists()) kotlin.math.abs(readFloat(power) ?: 0f) / 1_000_000f
|
||||
else kotlin.math.abs((readFloat(File(dir, "current_now")) ?: 0f) * (readFloat(File(dir, "voltage_now")) ?: 0f)) / 1e12f
|
||||
}
|
||||
}
|
||||
|
||||
val percent = when {
|
||||
allHaveWeightedCharge && weightedChargeFull > 0.0 -> (weightedChargeNow * 100.0 / weightedChargeFull).roundToInt().coerceIn(0, 100)
|
||||
perBatteryPercents.isNotEmpty() -> perBatteryPercents.average().roundToInt().coerceIn(0, 100)
|
||||
else -> null
|
||||
}
|
||||
if (lastBatteryDischarging != null && lastBatteryDischarging != anyDischarging) {
|
||||
batteryRuntimeEstimator.reset()
|
||||
}
|
||||
lastBatteryDischarging = anyDischarging
|
||||
val estimatedHours = if (anyDischarging && runtimeChargeComplete && currentComplete)
|
||||
batteryRuntimeEstimator.estimateHours(runtimeChargeUah, aggregateCurrentUa) else null
|
||||
val runtimeHours = suppliedRuntimeSeconds?.let { it / 3600.0 } ?: estimatedHours
|
||||
val charging = !anyDischarging && anyChargingStatus
|
||||
val runtimeText = when {
|
||||
anyDischarging -> BatteryRuntimeEstimator.formatDuration(runtimeHours)
|
||||
charging -> "Charging"
|
||||
allFull -> "Full"
|
||||
else -> null
|
||||
}
|
||||
return Battery(percent, if (anyDischarging) watts.toFloat() else 0f, charging, runtimeText)
|
||||
val percent = if (chargeFull > 0f) Math.round(chargeNow / chargeFull * 100f) else null
|
||||
return Battery(percent, if (charging) 0f else watts, charging)
|
||||
}
|
||||
|
||||
private fun fresh(file: File, maxAgeMs: Long = FEED_FRESH_MS): File? =
|
||||
|
||||
@@ -390,8 +390,7 @@ object SteamTouchConfig {
|
||||
options: Options? = null,
|
||||
): File? {
|
||||
val dir = configDir(context) ?: return null
|
||||
val base = config.text ?: if (config.file == null && bindings.isEmpty()) "\"controller_mappings\"\n{\n\t\"controller_type\"\t\t\"controller_mobile_touch\"\n}\n" else return null
|
||||
val source = bindings.entries.fold(base) { text, (ref, change) ->
|
||||
val source = bindings.entries.fold(config.text ?: return null) { text, (ref, change) ->
|
||||
SteamTouchBindings.rewrite(text, ref, change) ?: text
|
||||
}
|
||||
val key = steamKey(context, appId)
|
||||
|
||||
@@ -1,288 +0,0 @@
|
||||
package com.droiddeck.launcher.playback
|
||||
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.os.Bundle
|
||||
import android.net.Uri
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableLongStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.media3.common.MediaItem
|
||||
import androidx.media3.common.MediaMetadata
|
||||
import androidx.media3.common.PlaybackParameters
|
||||
import androidx.media3.common.Player
|
||||
import androidx.media3.session.MediaController
|
||||
import androidx.media3.session.SessionToken
|
||||
import com.droiddeck.launcher.frontend.Soundtrack
|
||||
import com.google.common.util.concurrent.ListenableFuture
|
||||
import java.io.File
|
||||
|
||||
object SoundtrackController {
|
||||
var playing by mutableStateOf(false)
|
||||
private set
|
||||
var currentId by mutableStateOf<String?>(null)
|
||||
private set
|
||||
var title by mutableStateOf("")
|
||||
private set
|
||||
var shuffle by mutableStateOf(false)
|
||||
private set
|
||||
var repeat by mutableStateOf(Player.REPEAT_MODE_OFF)
|
||||
private set
|
||||
var durationMs by mutableStateOf(0L)
|
||||
private set
|
||||
var buffering by mutableStateOf(false)
|
||||
private set
|
||||
var volume by mutableStateOf(1f)
|
||||
private set
|
||||
|
||||
var activeCollection by mutableStateOf<Int?>(null)
|
||||
private set
|
||||
|
||||
var sleepEndsAt by mutableLongStateOf(0L)
|
||||
private set
|
||||
var sleepTrackEnd by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
private var app: Context? = null
|
||||
private val removed: MutableSet<String> = java.util.Collections.synchronizedSet(HashSet())
|
||||
private var activeRoot: String? = null
|
||||
private var savedId: String? = null
|
||||
private var future: ListenableFuture<MediaController>? = null
|
||||
private var controller: MediaController? = null
|
||||
private val pending = ArrayList<(MediaController) -> Unit>()
|
||||
|
||||
private val listener = object : Player.Listener {
|
||||
override fun onEvents(player: Player, events: Player.Events) = sync(player)
|
||||
}
|
||||
|
||||
private val disconnect = object : MediaController.Listener {
|
||||
override fun onDisconnected(controller: MediaController) {
|
||||
if (this@SoundtrackController.controller === controller) {
|
||||
this@SoundtrackController.controller = null
|
||||
future = null
|
||||
reset()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun reset() {
|
||||
playing = false
|
||||
currentId = null
|
||||
title = ""
|
||||
durationMs = 0L
|
||||
buffering = false
|
||||
volume = 1f
|
||||
activeCollection = null
|
||||
}
|
||||
|
||||
private fun sync(player: Player) {
|
||||
playing = player.isPlaying
|
||||
buffering = player.playbackState == Player.STATE_BUFFERING
|
||||
currentId = player.currentMediaItem?.mediaId?.takeIf { player.mediaItemCount > 0 }
|
||||
title = player.mediaMetadata.title?.toString().orEmpty()
|
||||
shuffle = player.shuffleModeEnabled
|
||||
repeat = player.repeatMode
|
||||
durationMs = player.duration.takeIf { it > 0 } ?: 0L
|
||||
volume = player.volume
|
||||
if (!player.playWhenReady) sleepTrackEnd = false
|
||||
persistResume(player)
|
||||
}
|
||||
|
||||
private fun persistResume(player: Player) {
|
||||
val context = app ?: return
|
||||
val id = currentId ?: return
|
||||
if (activeCollection != null) return
|
||||
val root = activeRoot ?: SoundtrackSettings.resume(context)?.root?.takeIf { id.startsWith("$it/") }?.also { activeRoot = it } ?: return
|
||||
if (id != savedId || !player.isPlaying) {
|
||||
savedId = id
|
||||
SoundtrackSettings.saveResume(context, root, id, if (player.playbackState == Player.STATE_ENDED) 0L else player.currentPosition)
|
||||
}
|
||||
}
|
||||
|
||||
private fun applySettings(c: MediaController) {
|
||||
val context = app ?: return
|
||||
SoundtrackSettings.load(context)
|
||||
c.setPlaybackParameters(PlaybackParameters(SoundtrackSettings.speed, SoundtrackSettings.pitch))
|
||||
c.sendCustomCommand(SoundtrackService.SKIP_SILENCE, Bundle().apply { putBoolean(SoundtrackService.ARG_ON, SoundtrackSettings.skipSilence) })
|
||||
sendEqualizer(c)
|
||||
c.sendCustomCommand(SoundtrackService.INGAME, Bundle().apply { putBoolean(SoundtrackService.ARG_ON, com.droiddeck.launcher.session.SessionPrefs.soundtracksIngame(context)) })
|
||||
}
|
||||
|
||||
private fun sendEqualizer(c: MediaController) {
|
||||
c.sendCustomCommand(
|
||||
SoundtrackService.EQUALIZER,
|
||||
Bundle().apply {
|
||||
putBoolean(SoundtrackService.ARG_ON, SoundtrackSettings.eqOn)
|
||||
putIntArray(SoundtrackService.ARG_BANDS, SoundtrackSettings.bands.toIntArray())
|
||||
putInt(SoundtrackService.ARG_BASS, SoundtrackSettings.bass)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
private fun run(context: Context, block: (MediaController) -> Unit) {
|
||||
app = context.applicationContext
|
||||
val live = controller
|
||||
if (live != null) { block(live); return }
|
||||
pending += block
|
||||
if (future != null) return
|
||||
val app = context.applicationContext
|
||||
val token = SessionToken(app, ComponentName(app, SoundtrackService::class.java))
|
||||
val built = MediaController.Builder(app, token).setListener(disconnect)
|
||||
.setConnectionHints(Bundle().apply { putBoolean(SoundtrackService.HINT_OWNER, true) }).buildAsync()
|
||||
future = built
|
||||
built.addListener({
|
||||
val ready = runCatching { built.get() }.getOrNull()
|
||||
if (ready == null) {
|
||||
future = null
|
||||
pending.clear()
|
||||
return@addListener
|
||||
}
|
||||
controller = ready
|
||||
ready.addListener(listener)
|
||||
applySettings(ready)
|
||||
sync(ready)
|
||||
val queued = pending.toList()
|
||||
pending.clear()
|
||||
queued.forEach { it(ready) }
|
||||
}, ContextCompat.getMainExecutor(app))
|
||||
}
|
||||
|
||||
fun connect(context: Context) = run(context) { }
|
||||
|
||||
fun position(): Long = controller?.currentPosition ?: 0L
|
||||
|
||||
fun belongsCollection(id: Int): Boolean = activeCollection == id && currentId != null
|
||||
|
||||
fun belongs(root: File?): Boolean {
|
||||
if (activeCollection != null) return false
|
||||
val id = currentId ?: return false
|
||||
return root != null && id.startsWith(root.path + "/")
|
||||
}
|
||||
|
||||
private fun items(album: Soundtrack.Album, albumTitle: String): List<MediaItem> {
|
||||
val cover = album.cover?.let { Uri.fromFile(it) }
|
||||
return album.tracks.map { t ->
|
||||
MediaItem.Builder()
|
||||
.setMediaId(t.file.path)
|
||||
.setMediaMetadata(
|
||||
MediaMetadata.Builder()
|
||||
.setTitle(t.title)
|
||||
.setArtist(t.artist.ifBlank { album.artist }.ifBlank { null })
|
||||
.setAlbumTitle(albumTitle)
|
||||
.setTrackNumber(t.number)
|
||||
.setDiscNumber(t.disc.takeIf { it > 0 })
|
||||
.setArtworkUri(cover)
|
||||
.setIsPlayable(true)
|
||||
.build(),
|
||||
)
|
||||
.build()
|
||||
}
|
||||
}
|
||||
|
||||
fun play(
|
||||
context: Context, album: Soundtrack.Album, albumTitle: String, startId: String?, shuffled: Boolean? = null,
|
||||
root: File? = null, startMs: Long = 0L, collection: Int? = null,
|
||||
) {
|
||||
val list = items(album, albumTitle)
|
||||
if (list.isEmpty()) return
|
||||
run(context) { c ->
|
||||
if (root != null && root.path in removed) return@run
|
||||
val start = list.indexOfFirst { it.mediaId == startId }.coerceAtLeast(0)
|
||||
root?.let { activeRoot = it.path }
|
||||
activeCollection = collection
|
||||
c.setMediaItems(list, start, startMs)
|
||||
shuffled?.let { c.shuffleModeEnabled = it }
|
||||
c.prepare()
|
||||
c.play()
|
||||
}
|
||||
}
|
||||
|
||||
fun allow(paths: Collection<String>) {
|
||||
removed.removeAll(paths.toSet())
|
||||
}
|
||||
|
||||
fun toggle(context: Context, album: Soundtrack.Album, albumTitle: String, root: File?, collection: Int? = null) {
|
||||
run(context) { c ->
|
||||
if (root != null && root.path in removed) return@run
|
||||
val mine = if (collection != null) belongsCollection(collection) else belongs(root)
|
||||
if (mine && c.mediaItemCount > 0) {
|
||||
if (c.isPlaying) c.pause() else {
|
||||
if (c.playbackState == Player.STATE_ENDED) c.seekToDefaultPosition(0)
|
||||
c.play()
|
||||
}
|
||||
} else {
|
||||
val saved = if (collection != null) null else root?.let { r -> SoundtrackSettings.resume(context)?.takeIf { it.root == r.path && album.tracks.any { t -> t.id == it.id } } }
|
||||
play(context, album, albumTitle, saved?.id ?: album.tracks.firstOrNull()?.id, root = root, startMs = saved?.positionMs ?: 0L, collection = collection)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun pause(context: Context) {
|
||||
val live = controller
|
||||
if (live != null) live.pause() else if (future != null) pending += { it.pause() }
|
||||
}
|
||||
|
||||
fun next(context: Context) = run(context) { it.seekToNext() }
|
||||
fun previous(context: Context) = run(context) { c -> if (c.currentPosition > 3000L) c.seekTo(0) else c.seekToPrevious() }
|
||||
fun seekTo(context: Context, ms: Long) = run(context) { it.seekTo(ms) }
|
||||
fun setShuffle(context: Context, on: Boolean) = run(context) { it.shuffleModeEnabled = on }
|
||||
fun cycleRepeat(context: Context) = run(context) {
|
||||
it.repeatMode = when (it.repeatMode) {
|
||||
Player.REPEAT_MODE_OFF -> Player.REPEAT_MODE_ALL
|
||||
Player.REPEAT_MODE_ALL -> Player.REPEAT_MODE_ONE
|
||||
else -> Player.REPEAT_MODE_OFF
|
||||
}
|
||||
}
|
||||
fun setVolume(context: Context, volume: Float) = run(context) { it.volume = volume.coerceIn(0f, 1f) }
|
||||
|
||||
fun setSpeed(context: Context, value: Float) {
|
||||
SoundtrackSettings.load(context)
|
||||
SoundtrackSettings.setSpeed(context, value)
|
||||
run(context) { it.setPlaybackParameters(PlaybackParameters(SoundtrackSettings.speed, SoundtrackSettings.pitch)) }
|
||||
}
|
||||
|
||||
fun setPitch(context: Context, value: Float) {
|
||||
SoundtrackSettings.load(context)
|
||||
SoundtrackSettings.setPitch(context, value)
|
||||
run(context) { it.setPlaybackParameters(PlaybackParameters(SoundtrackSettings.speed, SoundtrackSettings.pitch)) }
|
||||
}
|
||||
|
||||
fun setSkipSilence(context: Context, on: Boolean) {
|
||||
SoundtrackSettings.load(context)
|
||||
SoundtrackSettings.setSkipSilence(context, on)
|
||||
run(context) { it.sendCustomCommand(SoundtrackService.SKIP_SILENCE, Bundle().apply { putBoolean(SoundtrackService.ARG_ON, on) }) }
|
||||
}
|
||||
|
||||
fun setEqualizer(context: Context, on: Boolean, bands: List<Int>, bass: Int) {
|
||||
SoundtrackSettings.load(context)
|
||||
SoundtrackSettings.setEqualizer(context, on, bands, bass)
|
||||
run(context) { sendEqualizer(it) }
|
||||
}
|
||||
|
||||
fun setIngame(context: Context, on: Boolean) {
|
||||
run(context) { it.sendCustomCommand(SoundtrackService.INGAME, Bundle().apply { putBoolean(SoundtrackService.ARG_ON, on) }) }
|
||||
}
|
||||
|
||||
fun setSleep(context: Context, minutes: Int) {
|
||||
sleepEndsAt = if (minutes > 0) System.currentTimeMillis() + minutes * 60_000L else 0L
|
||||
sleepTrackEnd = minutes < 0
|
||||
run(context) { it.sendCustomCommand(SoundtrackService.SLEEP, Bundle().apply { putInt(SoundtrackService.ARG_MINUTES, minutes) }) }
|
||||
}
|
||||
|
||||
fun sleepRemainingMs(): Long {
|
||||
val left = sleepEndsAt - System.currentTimeMillis()
|
||||
if (sleepEndsAt > 0L && left <= 0L) sleepEndsAt = 0L
|
||||
return left.coerceAtLeast(0L)
|
||||
}
|
||||
|
||||
fun stopIf(context: Context, root: File?) {
|
||||
root?.let { removed.add(it.path) }
|
||||
if (root == null || currentId?.startsWith(root.path + "/") != true) return
|
||||
run(context) { c ->
|
||||
c.stop()
|
||||
c.clearMediaItems()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,282 +0,0 @@
|
||||
package com.droiddeck.launcher.playback
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.media.audiofx.BassBoost
|
||||
import android.media.audiofx.Equalizer
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.Process
|
||||
import androidx.media3.common.AudioAttributes
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.MediaItem
|
||||
import androidx.media3.common.Player
|
||||
import androidx.media3.exoplayer.ExoPlayer
|
||||
import androidx.media3.session.CommandButton
|
||||
import androidx.media3.session.DefaultMediaNotificationProvider
|
||||
import androidx.media3.session.MediaSession
|
||||
import androidx.media3.session.MediaSessionService
|
||||
import androidx.media3.session.SessionCommand
|
||||
import androidx.media3.session.SessionResult
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.frontend.Soundtrack
|
||||
import com.google.common.collect.ImmutableList
|
||||
import com.google.common.util.concurrent.Futures
|
||||
import com.google.common.util.concurrent.ListenableFuture
|
||||
import java.io.File
|
||||
|
||||
private class EdgeButtonsProvider(context: Context) : DefaultMediaNotificationProvider(context) {
|
||||
override fun getMediaButtons(
|
||||
session: MediaSession, playerCommands: Player.Commands, customLayout: ImmutableList<CommandButton>, showPauseButton: Boolean,
|
||||
): ImmutableList<CommandButton> {
|
||||
val all = super.getMediaButtons(session, playerCommands, customLayout, showPauseButton)
|
||||
val custom = all.filter { it.sessionCommand != null }
|
||||
if (custom.size < 2) return all
|
||||
return ImmutableList.builder<CommandButton>()
|
||||
.add(custom.first())
|
||||
.addAll(all.filter { it.sessionCommand == null })
|
||||
.addAll(custom.drop(1))
|
||||
.build()
|
||||
}
|
||||
}
|
||||
|
||||
class SoundtrackService : MediaSessionService() {
|
||||
private var session: MediaSession? = null
|
||||
private var exo: ExoPlayer? = null
|
||||
private var equalizer: Equalizer? = null
|
||||
private var bassBoost: BassBoost? = null
|
||||
private var effectsSession = C.AUDIO_SESSION_ID_UNSET
|
||||
private var eqOn = false
|
||||
private var eqBands = IntArray(0)
|
||||
private var eqBass = 0
|
||||
private var sleepAtTrackEnd = false
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val sleepRunnable = Runnable { session?.player?.pause() }
|
||||
private val covers = java.util.concurrent.Executors.newSingleThreadExecutor { r -> Thread(r, "soundtrack-cover").apply { isDaemon = true } }
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
val player = ExoPlayer.Builder(this)
|
||||
.setAudioAttributes(mediaAttributes(), !com.droiddeck.launcher.session.SessionPrefs.soundtracksIngame(this))
|
||||
.setHandleAudioBecomingNoisy(true)
|
||||
.setWakeMode(androidx.media3.common.C.WAKE_MODE_LOCAL)
|
||||
.build()
|
||||
exo = player
|
||||
val sessionIntent = packageManager.getLaunchIntentForPackage(packageName)?.let {
|
||||
PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
|
||||
}
|
||||
player.addListener(object : Player.Listener {
|
||||
override fun onShuffleModeEnabledChanged(shuffleModeEnabled: Boolean) = refreshButtons()
|
||||
override fun onRepeatModeChanged(repeatMode: Int) = refreshButtons()
|
||||
override fun onAudioSessionIdChanged(audioSessionId: Int) = applyEffects()
|
||||
override fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int) {
|
||||
if (!playWhenReady) sleepAtTrackEnd = false
|
||||
}
|
||||
override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
|
||||
refreshTrackCover(mediaItem)
|
||||
val ended = reason == Player.MEDIA_ITEM_TRANSITION_REASON_AUTO || reason == Player.MEDIA_ITEM_TRANSITION_REASON_REPEAT
|
||||
if (sleepAtTrackEnd && ended) {
|
||||
sleepAtTrackEnd = false
|
||||
player.pause()
|
||||
}
|
||||
}
|
||||
})
|
||||
session = MediaSession.Builder(this, player).setCallback(Resolver()).apply { sessionIntent?.let { setSessionActivity(it) } }.build()
|
||||
setMediaNotificationProvider(EdgeButtonsProvider(this).apply { setSmallIcon(R.drawable.ic_soundtrack) })
|
||||
}
|
||||
|
||||
private fun mediaAttributes(): AudioAttributes =
|
||||
AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MUSIC).build()
|
||||
|
||||
private fun buttons(player: Player): ImmutableList<CommandButton> = ImmutableList.of(
|
||||
CommandButton.Builder()
|
||||
.setDisplayName(getString(R.string.soundtracks_shuffle))
|
||||
.setIconResId(if (player.shuffleModeEnabled) R.drawable.ic_shuffle_on else R.drawable.ic_shuffle_off)
|
||||
.setSessionCommand(SHUFFLE)
|
||||
.build(),
|
||||
CommandButton.Builder()
|
||||
.setDisplayName(
|
||||
getString(
|
||||
when (player.repeatMode) {
|
||||
Player.REPEAT_MODE_ALL -> R.string.soundtracks_repeat_all
|
||||
Player.REPEAT_MODE_ONE -> R.string.soundtracks_repeat_one
|
||||
else -> R.string.soundtracks_repeat_off
|
||||
},
|
||||
),
|
||||
)
|
||||
.setIconResId(
|
||||
when (player.repeatMode) {
|
||||
Player.REPEAT_MODE_ALL -> R.drawable.ic_repeat_all
|
||||
Player.REPEAT_MODE_ONE -> R.drawable.ic_repeat_one
|
||||
else -> R.drawable.ic_repeat_off
|
||||
},
|
||||
)
|
||||
.setSessionCommand(REPEAT)
|
||||
.build(),
|
||||
)
|
||||
|
||||
private fun hasPinnedArt(item: MediaItem): Boolean =
|
||||
item.mediaMetadata.artworkUri?.path.orEmpty().let { it.contains("/steam-art/") || it.contains("/soundtrack-art/") }
|
||||
|
||||
private fun refreshTrackCover(item: MediaItem?) {
|
||||
val current = item ?: return
|
||||
if (hasPinnedArt(current)) return
|
||||
val file = File(current.mediaId)
|
||||
covers.execute {
|
||||
val art = Soundtrack.trackCover(this, file) ?: return@execute
|
||||
handler.post {
|
||||
val player = exo ?: return@post
|
||||
val live = player.currentMediaItem ?: return@post
|
||||
val uri = Uri.fromFile(art)
|
||||
if (live.mediaId != current.mediaId || live.mediaMetadata.artworkUri == uri || hasPinnedArt(live)) return@post
|
||||
player.replaceMediaItem(
|
||||
player.currentMediaItemIndex,
|
||||
live.buildUpon().setMediaMetadata(live.mediaMetadata.buildUpon().setArtworkUri(uri).build()).build(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun releaseEffects() {
|
||||
runCatching { equalizer?.release() }
|
||||
runCatching { bassBoost?.release() }
|
||||
equalizer = null
|
||||
bassBoost = null
|
||||
effectsSession = C.AUDIO_SESSION_ID_UNSET
|
||||
}
|
||||
|
||||
private fun applyEffects() {
|
||||
val id = exo?.audioSessionId ?: C.AUDIO_SESSION_ID_UNSET
|
||||
if (!eqOn || id == C.AUDIO_SESSION_ID_UNSET) {
|
||||
releaseEffects()
|
||||
return
|
||||
}
|
||||
if (id != effectsSession) {
|
||||
releaseEffects()
|
||||
effectsSession = id
|
||||
equalizer = runCatching { Equalizer(0, id) }.getOrNull()
|
||||
bassBoost = runCatching { BassBoost(0, id) }.getOrNull()
|
||||
}
|
||||
runCatching {
|
||||
equalizer?.let { eq ->
|
||||
val range = eq.bandLevelRange
|
||||
for (band in 0 until minOf(eq.numberOfBands.toInt(), eqBands.size)) {
|
||||
eq.setBandLevel(band.toShort(), eqBands[band].coerceIn(range[0].toInt(), range[1].toInt()).toShort())
|
||||
}
|
||||
eq.enabled = true
|
||||
}
|
||||
}
|
||||
runCatching {
|
||||
bassBoost?.let { boost ->
|
||||
if (boost.strengthSupported) boost.setStrength(eqBass.coerceIn(0, 1000).toShort())
|
||||
boost.enabled = eqBass > 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun setSleep(minutes: Int) {
|
||||
handler.removeCallbacks(sleepRunnable)
|
||||
sleepAtTrackEnd = false
|
||||
if (minutes > 0) handler.postDelayed(sleepRunnable, minutes * 60_000L)
|
||||
else if (minutes < 0) sleepAtTrackEnd = true
|
||||
}
|
||||
|
||||
private fun refreshButtons() {
|
||||
val live = session ?: return
|
||||
live.setCustomLayout(buttons(live.player))
|
||||
}
|
||||
|
||||
override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? = session
|
||||
|
||||
override fun onTaskRemoved(rootIntent: Intent?) {
|
||||
val player = session?.player
|
||||
if (player == null || !player.playWhenReady || player.mediaItemCount == 0 || player.playbackState == Player.STATE_ENDED) stopSelf()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
handler.removeCallbacks(sleepRunnable)
|
||||
covers.shutdownNow()
|
||||
releaseEffects()
|
||||
session?.let {
|
||||
it.player.release()
|
||||
it.release()
|
||||
}
|
||||
session = null
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val HINT_OWNER = "droiddeck.owner"
|
||||
private val SHUFFLE = SessionCommand("droiddeck.shuffle", Bundle.EMPTY)
|
||||
private val REPEAT = SessionCommand("droiddeck.repeat", Bundle.EMPTY)
|
||||
val SKIP_SILENCE = SessionCommand("droiddeck.skipsilence", Bundle.EMPTY)
|
||||
val EQUALIZER = SessionCommand("droiddeck.equalizer", Bundle.EMPTY)
|
||||
val SLEEP = SessionCommand("droiddeck.sleep", Bundle.EMPTY)
|
||||
val INGAME = SessionCommand("droiddeck.ingame", Bundle.EMPTY)
|
||||
const val ARG_ON = "on"
|
||||
const val ARG_BANDS = "bands"
|
||||
const val ARG_BASS = "bass"
|
||||
const val ARG_MINUTES = "minutes"
|
||||
}
|
||||
|
||||
private inner class Resolver : MediaSession.Callback {
|
||||
private fun isOwner(controller: MediaSession.ControllerInfo) =
|
||||
controller.uid == Process.myUid() && controller.connectionHints.getBoolean(HINT_OWNER, false)
|
||||
|
||||
override fun onConnect(session: MediaSession, controller: MediaSession.ControllerInfo): MediaSession.ConnectionResult =
|
||||
if (controller.uid == Process.myUid() || controller.isTrusted) {
|
||||
MediaSession.ConnectionResult.AcceptedResultBuilder(session)
|
||||
.setAvailableSessionCommands(
|
||||
MediaSession.ConnectionResult.DEFAULT_SESSION_COMMANDS.buildUpon().add(SHUFFLE).add(REPEAT).add(SKIP_SILENCE).add(EQUALIZER).add(SLEEP).add(INGAME).build(),
|
||||
)
|
||||
.setCustomLayout(buttons(session.player))
|
||||
.build()
|
||||
} else {
|
||||
MediaSession.ConnectionResult.reject()
|
||||
}
|
||||
|
||||
override fun onCustomCommand(
|
||||
session: MediaSession, controller: MediaSession.ControllerInfo, customCommand: SessionCommand, args: Bundle,
|
||||
): ListenableFuture<SessionResult> {
|
||||
val player = session.player
|
||||
when (customCommand.customAction) {
|
||||
SHUFFLE.customAction -> player.shuffleModeEnabled = !player.shuffleModeEnabled
|
||||
REPEAT.customAction -> player.repeatMode = when (player.repeatMode) {
|
||||
Player.REPEAT_MODE_OFF -> Player.REPEAT_MODE_ALL
|
||||
Player.REPEAT_MODE_ALL -> Player.REPEAT_MODE_ONE
|
||||
else -> Player.REPEAT_MODE_OFF
|
||||
}
|
||||
SKIP_SILENCE.customAction, EQUALIZER.customAction, SLEEP.customAction, INGAME.customAction -> {
|
||||
if (!isOwner(controller)) return Futures.immediateFuture(SessionResult(SessionResult.RESULT_ERROR_PERMISSION_DENIED))
|
||||
when (customCommand.customAction) {
|
||||
SKIP_SILENCE.customAction -> exo?.skipSilenceEnabled = args.getBoolean(ARG_ON)
|
||||
INGAME.customAction -> exo?.setAudioAttributes(mediaAttributes(), !args.getBoolean(ARG_ON))
|
||||
EQUALIZER.customAction -> {
|
||||
eqOn = args.getBoolean(ARG_ON)
|
||||
eqBands = args.getIntArray(ARG_BANDS) ?: IntArray(0)
|
||||
eqBass = args.getInt(ARG_BASS)
|
||||
applyEffects()
|
||||
}
|
||||
else -> setSleep(args.getInt(ARG_MINUTES))
|
||||
}
|
||||
}
|
||||
else -> return Futures.immediateFuture(SessionResult(SessionResult.RESULT_ERROR_NOT_SUPPORTED))
|
||||
}
|
||||
return Futures.immediateFuture(SessionResult(SessionResult.RESULT_SUCCESS))
|
||||
}
|
||||
|
||||
override fun onAddMediaItems(
|
||||
mediaSession: MediaSession, controller: MediaSession.ControllerInfo, mediaItems: MutableList<MediaItem>,
|
||||
): ListenableFuture<MutableList<MediaItem>> {
|
||||
if (!isOwner(controller)) return Futures.immediateFailedFuture(SecurityException("Only DroidDeck can queue soundtrack files"))
|
||||
val resolved = mediaItems.mapNotNull { item ->
|
||||
val file = File(item.mediaId)
|
||||
if (Soundtrack.isAudio(file)) item.buildUpon().setUri(Uri.fromFile(file)).build() else null
|
||||
}.toMutableList()
|
||||
return Futures.immediateFuture(resolved)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
package com.droiddeck.launcher.playback
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableFloatStateOf
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
|
||||
object SoundtrackSettings {
|
||||
const val MIN_RATE = 0.5f
|
||||
const val MAX_RATE = 2f
|
||||
|
||||
var speed by mutableFloatStateOf(1f)
|
||||
private set
|
||||
var pitch by mutableFloatStateOf(1f)
|
||||
private set
|
||||
var skipSilence by mutableStateOf(false)
|
||||
private set
|
||||
var eqOn by mutableStateOf(false)
|
||||
private set
|
||||
var bands by mutableStateOf<List<Int>>(emptyList())
|
||||
private set
|
||||
var bass by mutableIntStateOf(0)
|
||||
private set
|
||||
|
||||
class Resume(val root: String, val id: String, val positionMs: Long)
|
||||
|
||||
private var loaded = false
|
||||
|
||||
private fun prefs(context: Context) = context.applicationContext.getSharedPreferences("soundtrack_settings", Context.MODE_PRIVATE)
|
||||
|
||||
@Synchronized
|
||||
fun load(context: Context) {
|
||||
if (loaded) return
|
||||
loaded = true
|
||||
val p = prefs(context)
|
||||
speed = p.getFloat("speed", 1f).coerceIn(MIN_RATE, MAX_RATE)
|
||||
pitch = p.getFloat("pitch", 1f).coerceIn(MIN_RATE, MAX_RATE)
|
||||
skipSilence = p.getBoolean("skipSilence", false)
|
||||
eqOn = p.getBoolean("eqOn", false)
|
||||
bands = p.getString("bands", "").orEmpty().split(',').mapNotNull { it.trim().toIntOrNull() }
|
||||
bass = p.getInt("bass", 0).coerceIn(0, 1000)
|
||||
}
|
||||
|
||||
fun setSpeed(context: Context, value: Float) {
|
||||
speed = value.coerceIn(MIN_RATE, MAX_RATE)
|
||||
prefs(context).edit().putFloat("speed", speed).apply()
|
||||
}
|
||||
|
||||
fun setPitch(context: Context, value: Float) {
|
||||
pitch = value.coerceIn(MIN_RATE, MAX_RATE)
|
||||
prefs(context).edit().putFloat("pitch", pitch).apply()
|
||||
}
|
||||
|
||||
fun setSkipSilence(context: Context, on: Boolean) {
|
||||
skipSilence = on
|
||||
prefs(context).edit().putBoolean("skipSilence", on).apply()
|
||||
}
|
||||
|
||||
fun setEqualizer(context: Context, on: Boolean, levels: List<Int>, bassStrength: Int) {
|
||||
eqOn = on
|
||||
bands = levels
|
||||
bass = bassStrength.coerceIn(0, 1000)
|
||||
prefs(context).edit().putBoolean("eqOn", on).putString("bands", levels.joinToString(",")).putInt("bass", bass).apply()
|
||||
}
|
||||
|
||||
fun resume(context: Context): Resume? {
|
||||
val p = prefs(context)
|
||||
val root = p.getString("resumeRoot", null) ?: return null
|
||||
val id = p.getString("resumeId", null) ?: return null
|
||||
return Resume(root, id, p.getLong("resumePosition", 0L))
|
||||
}
|
||||
|
||||
fun saveResume(context: Context, root: String, id: String, positionMs: Long) {
|
||||
prefs(context).edit().putString("resumeRoot", root).putString("resumeId", id).putLong("resumePosition", positionMs.coerceAtLeast(0L)).apply()
|
||||
}
|
||||
}
|
||||
@@ -139,26 +139,15 @@ public final class LinuxRuntime {
|
||||
public static List<String> command(Context context, File sessionRoot, File runtimeDir,
|
||||
File externalStorage, List<String> extraBinds,
|
||||
List<String> guestCommand) {
|
||||
return command(context, sessionRoot, runtimeDir, externalStorage, extraBinds, guestCommand, false);
|
||||
}
|
||||
|
||||
public static List<String> command(Context context, File sessionRoot, File runtimeDir,
|
||||
File externalStorage, List<String> extraBinds,
|
||||
List<String> guestCommand, boolean fakeRoot) {
|
||||
File root = rootDir(context);
|
||||
List<String> binds = binds(context, sessionRoot, runtimeDir, externalStorage, extraBinds);
|
||||
if (sessionRoot != null) lastBinds = binds;
|
||||
return commandWithBinds(context, root, binds, guestCommand, fakeRoot);
|
||||
return commandWithBinds(context, root, binds, guestCommand);
|
||||
}
|
||||
|
||||
public static List<String> commandWithBinds(Context context, File root, List<String> binds,
|
||||
List<String> guestCommand) {
|
||||
return commandWithBinds(context, root, binds, guestCommand, false);
|
||||
}
|
||||
|
||||
public static List<String> commandWithBinds(Context context, File root, List<String> binds,
|
||||
List<String> guestCommand, boolean fakeRoot) {
|
||||
List<String> cmd = fakeRoot ? rootPrefix(context, root, "/root") : prootPrefix(context, root, "/root");
|
||||
List<String> cmd = prootPrefix(context, root, "/root");
|
||||
for (String spec : binds) bind(cmd, spec);
|
||||
cmd.addAll(guestCommand);
|
||||
return cmd;
|
||||
@@ -181,12 +170,6 @@ public final class LinuxRuntime {
|
||||
return prootPrefix(context, root, cwd, false);
|
||||
}
|
||||
|
||||
public static List<String> rootPrefix(Context context, File root, String cwd) {
|
||||
List<String> cmd = prootPrefix(context, root, cwd, true);
|
||||
cmd.add(1, "--link2symlink");
|
||||
return cmd;
|
||||
}
|
||||
|
||||
public static List<String> prootPrefix(Context context, File root, String cwd, boolean fakeRoot) {
|
||||
List<String> cmd = new ArrayList<>();
|
||||
cmd.add(prootBinary(context).getPath());
|
||||
|
||||
@@ -70,7 +70,6 @@ public final class LinuxRuntimeInstaller {
|
||||
volatile Step step = Step.OTHER;
|
||||
volatile int percent = -1;
|
||||
volatile boolean ok;
|
||||
volatile String failure;
|
||||
final boolean removal;
|
||||
boolean maintenance;
|
||||
Job(boolean removal, String stage) { this.removal = removal; this.stage = stage; }
|
||||
@@ -79,9 +78,6 @@ public final class LinuxRuntimeInstaller {
|
||||
private static final Object JOB_LOCK = new Object();
|
||||
private static Job running;
|
||||
private static volatile String removalError;
|
||||
private static final ThreadLocal<Job> LAST_INSTALL = new ThreadLocal<>();
|
||||
private static final ThreadLocal<Job> CURRENT_INSTALL = new ThreadLocal<>();
|
||||
private static final ThreadLocal<String> CATALOG_ERROR = new ThreadLocal<>();
|
||||
|
||||
private LinuxRuntimeInstaller() {}
|
||||
|
||||
@@ -109,66 +105,34 @@ public final class LinuxRuntimeInstaller {
|
||||
}
|
||||
|
||||
public static Release fetchRelease() {
|
||||
return fetchRelease(catalogUrl());
|
||||
}
|
||||
|
||||
public static String catalogError() { return CATALOG_ERROR.get(); }
|
||||
|
||||
static Release fetchRelease(String catalogUrl) {
|
||||
CATALOG_ERROR.remove();
|
||||
String body = Downloader.downloadString(catalogUrl);
|
||||
if (body == null) return catalogFailed(Downloader.lastFailure());
|
||||
if (body.isEmpty()) return catalogFailed("empty catalog");
|
||||
String body = Downloader.downloadString(catalogUrl());
|
||||
if (body == null || body.isEmpty()) return null;
|
||||
try {
|
||||
JSONObject json = new JSONObject(body);
|
||||
String version = json.optString("version", "");
|
||||
String url = json.optString("url", "");
|
||||
String sha256 = json.optString("sha256", "");
|
||||
if (version.isEmpty() || url.isEmpty() || sha256.isEmpty()) {
|
||||
return catalogFailed("catalog lacks version, url or sha256");
|
||||
}
|
||||
if (version.isEmpty() || url.isEmpty() || sha256.isEmpty()) return null;
|
||||
return new Release(version, url, sha256, json.optLong("size", 0L));
|
||||
} catch (Exception e) {
|
||||
return catalogFailed("invalid catalog: " + e);
|
||||
Log.w(TAG, "catalog: " + e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static Release catalogFailed(String reason) {
|
||||
CATALOG_ERROR.set(reason);
|
||||
Log.w(TAG, "catalog: " + reason);
|
||||
return null;
|
||||
}
|
||||
|
||||
private static final String USER_DATA = "root";
|
||||
|
||||
public static boolean install(Context context, Release release, ProgressListener listener) {
|
||||
Job job;
|
||||
boolean owner;
|
||||
synchronized (JOB_LOCK) {
|
||||
if (running != null && (running.removal || running.maintenance)) {
|
||||
Job rejected = new Job(false, null);
|
||||
rejected.failure = running.removal ? "Runtime busy: removal in progress" : "Runtime busy: maintenance in progress";
|
||||
Log.w(TAG, rejected.failure);
|
||||
LAST_INSTALL.set(rejected);
|
||||
return false;
|
||||
}
|
||||
if (running != null && (running.removal || running.maintenance)) return false;
|
||||
owner = running == null;
|
||||
if (owner) { running = new Job(false, context.getString(R.string.user_apps_starting)); removalError = null; }
|
||||
job = running;
|
||||
if (listener != null) job.listeners.add(listener);
|
||||
}
|
||||
if (!owner) {
|
||||
Boolean ok = await(job, listener);
|
||||
if (ok != null) {
|
||||
LAST_INSTALL.set(job);
|
||||
return ok;
|
||||
}
|
||||
Job interrupted = new Job(false, null);
|
||||
interrupted.failure = "Runtime install interrupted while waiting for the running install";
|
||||
LAST_INSTALL.set(interrupted);
|
||||
return false;
|
||||
}
|
||||
CURRENT_INSTALL.set(job);
|
||||
if (!owner) return join(job, listener);
|
||||
try {
|
||||
Context app = context.getApplicationContext();
|
||||
ProgressListener progress = new ProgressListener() {
|
||||
@@ -192,10 +156,9 @@ public final class LinuxRuntimeInstaller {
|
||||
if (job.ok && desktop) keepDesktop(app, progress);
|
||||
return job.ok;
|
||||
} finally {
|
||||
CURRENT_INSTALL.remove();
|
||||
LAST_INSTALL.set(job);
|
||||
synchronized (JOB_LOCK) { running = null; }
|
||||
if (listener != null) job.listeners.remove(listener);
|
||||
synchronized (JOB_LOCK) {
|
||||
running = null;
|
||||
}
|
||||
job.done.countDown();
|
||||
}
|
||||
}
|
||||
@@ -284,21 +247,6 @@ public final class LinuxRuntimeInstaller {
|
||||
|
||||
public static String removalError() { return removalError; }
|
||||
|
||||
public static String installError() {
|
||||
Job job = LAST_INSTALL.get();
|
||||
return job == null ? null : job.failure;
|
||||
}
|
||||
|
||||
private static boolean fail(String step, String detail) {
|
||||
String reason = detail == null || detail.isEmpty() ? step : step + ": " + detail;
|
||||
Job job = CURRENT_INSTALL.get();
|
||||
if (job != null) job.failure = reason;
|
||||
Log.w(TAG, reason);
|
||||
return false;
|
||||
}
|
||||
|
||||
private static final String SWAP_FAILED = "Cannot replace the previous runtime";
|
||||
|
||||
public static boolean hasRemovalPending(Context context) {
|
||||
return removalDirectory(LinuxRuntime.rootDir(context)).exists();
|
||||
}
|
||||
@@ -318,17 +266,13 @@ public final class LinuxRuntimeInstaller {
|
||||
}
|
||||
|
||||
private static boolean join(Job job, ProgressListener listener) {
|
||||
return Boolean.TRUE.equals(await(job, listener));
|
||||
}
|
||||
|
||||
private static Boolean await(Job job, ProgressListener listener) {
|
||||
try {
|
||||
if (listener != null) listener.onProgress(job.step, job.stage, job.percent);
|
||||
job.done.await();
|
||||
return job.ok;
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return null;
|
||||
return false;
|
||||
} finally {
|
||||
if (listener != null) job.listeners.remove(listener);
|
||||
}
|
||||
@@ -385,9 +329,8 @@ public final class LinuxRuntimeInstaller {
|
||||
if (listener != null) listener.onProgress(Step.DOWNLOADING, downloading, 0);
|
||||
if (!LinuxRuntime.patchedProot(context) && !AddonPack.PROOT.await(context, () -> true, packProgress(listener, downloading))
|
||||
&& !SessionPrefs.allowStockProot(context))
|
||||
return fail("Cannot download proot", AddonPack.PROOT.getFailure());
|
||||
if (!AddonPack.DIRECTAUDIO.await(context, () -> true, packProgress(listener, downloading)))
|
||||
return fail("Cannot download DirectAudio", AddonPack.DIRECTAUDIO.getFailure());
|
||||
throw new IOException("Cannot download proot");
|
||||
if (!AddonPack.DIRECTAUDIO.await(context, () -> true, packProgress(listener, downloading))) throw new IOException("Cannot download DirectAudio");
|
||||
boolean ok = Downloader.downloadFile(release.url, archive, true, release.sha256, (fraction) -> {
|
||||
if (listener != null) {
|
||||
listener.onProgress(Step.DOWNLOADING, downloading,
|
||||
@@ -395,36 +338,39 @@ public final class LinuxRuntimeInstaller {
|
||||
}
|
||||
});
|
||||
if (!ok) {
|
||||
Log.w(TAG, "download failed");
|
||||
keepPartial = true;
|
||||
return fail("Cannot download the runtime", Downloader.lastFailure());
|
||||
return false;
|
||||
}
|
||||
|
||||
if (listener != null) listener.onProgress(Step.VERIFYING, context.getString(R.string.rtinst_verifying), -1);
|
||||
String actual = Hashes.sha256(archive);
|
||||
if (!release.sha256.equalsIgnoreCase(actual))
|
||||
return fail("Runtime checksum mismatch", "wanted " + release.sha256 + ", got " + actual);
|
||||
if (!release.sha256.equalsIgnoreCase(actual)) {
|
||||
Log.w(TAG, "checksum mismatch: wanted " + release.sha256 + ", got " + actual);
|
||||
return false;
|
||||
}
|
||||
|
||||
File root = LinuxRuntime.rootDir(context);
|
||||
File staging = new File(root.getParentFile(), LinuxRuntime.DIR + ".new");
|
||||
File old = new File(root.getParentFile(), LinuxRuntime.DIR + ".old");
|
||||
recoverInterruptedSwap(root, staging, old);
|
||||
if (!discard(staging, null) || !staging.mkdirs()) return fail("Cannot prepare " + staging.getName(), null);
|
||||
if (!discard(staging, null) || !staging.mkdirs()) return false;
|
||||
if (listener != null) listener.onProgress(context.getString(R.string.rtinst_extracting), -1);
|
||||
if (!extract(context, archive, staging, root, listener)) {
|
||||
RuntimeFileTree.delete(staging, null);
|
||||
return fail("Cannot unpack the runtime", null);
|
||||
return false;
|
||||
}
|
||||
FileUtils.writeString(new File(staging, VERSION_FILE), release.version);
|
||||
|
||||
if (!discard(old, null)) {
|
||||
discard(staging, null);
|
||||
return fail(SWAP_FAILED, null);
|
||||
return false;
|
||||
}
|
||||
java.util.List<String> carryPaths = root.isDirectory()
|
||||
? RuntimeFileTree.existingUserPaths(root, staging) : java.util.Collections.emptyList();
|
||||
if (root.isDirectory() && !root.renameTo(old)) {
|
||||
RuntimeFileTree.delete(staging, null);
|
||||
return fail(SWAP_FAILED, null);
|
||||
return false;
|
||||
}
|
||||
File carryMarker = new File(staging, CARRY_MARKER);
|
||||
java.util.List<String> encodedPaths = new java.util.ArrayList<>();
|
||||
@@ -433,7 +379,7 @@ public final class LinuxRuntimeInstaller {
|
||||
if (old.isDirectory() && !old.renameTo(root))
|
||||
Log.w(TAG, "could not restore the previous runtime; retained at " + old);
|
||||
discard(staging, null);
|
||||
return fail(SWAP_FAILED, null);
|
||||
return false;
|
||||
}
|
||||
|
||||
java.util.List<String> carried;
|
||||
@@ -450,7 +396,7 @@ public final class LinuxRuntimeInstaller {
|
||||
} else {
|
||||
Log.w(TAG, "incomplete rollback; retaining user data in " + staging);
|
||||
}
|
||||
return fail("Cannot carry user data into the new runtime", e.getMessage());
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!staging.renameTo(root)) {
|
||||
@@ -461,7 +407,7 @@ public final class LinuxRuntimeInstaller {
|
||||
} catch (IOException e) { Log.w(TAG, "could not move all user data back after a failed swap", e); }
|
||||
old.renameTo(root);
|
||||
}
|
||||
return fail(SWAP_FAILED, null);
|
||||
return false;
|
||||
}
|
||||
new File(root, CARRY_MARKER).delete();
|
||||
try { RuntimeFileTree.dropStaleState(root); }
|
||||
@@ -469,10 +415,10 @@ public final class LinuxRuntimeInstaller {
|
||||
discard(old, null);
|
||||
try { com.droiddeck.launcher.session.SessionFiles.INSTANCE.stage(context, root, false); }
|
||||
catch (Exception e) { Log.w(TAG, "could not stage the session files into the new runtime", e); }
|
||||
return LinuxRuntime.isInstalled(context) || fail("The runtime is incomplete after unpacking", null);
|
||||
return LinuxRuntime.isInstalled(context);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "install", e);
|
||||
return fail("Install stopped", e.toString());
|
||||
return false;
|
||||
} finally {
|
||||
if (!keepPartial) archive.delete();
|
||||
}
|
||||
|
||||
@@ -120,7 +120,8 @@ object RootSpawner {
|
||||
val builder = if (NativeGuest.forSession(context)) {
|
||||
NativeGuest.processBuilder(context, root, binds, guest, cwd)
|
||||
} else {
|
||||
val cmd = LinuxRuntime.rootPrefix(context, root, cwd)
|
||||
val cmd = LinuxRuntime.prootPrefix(context, root, cwd, true)
|
||||
cmd.add(1, "--link2symlink")
|
||||
binds.forEach { cmd.add("-b"); cmd.add(it) }
|
||||
cmd.addAll(guest)
|
||||
ProcessBuilder(cmd).directory(root).also { b ->
|
||||
|
||||
@@ -11,8 +11,6 @@ import kotlin.math.abs
|
||||
class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart() {
|
||||
@Volatile private var running = false
|
||||
private var thread: Thread? = null
|
||||
private val runtimeEstimator = BatteryRuntimeEstimator()
|
||||
private var lastDischarging: Boolean? = null
|
||||
|
||||
override fun start() {
|
||||
File(dir, "BAT0").deleteRecursively()
|
||||
@@ -51,17 +49,11 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
|
||||
val currentAvgUa = toMicroamps(bm?.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_AVERAGE)?.takeIf { it != Long.MIN_VALUE && it != 0L } ?: 0L)
|
||||
.takeIf { it != 0L } ?: currentNowUa
|
||||
val discharging = status == BatteryManager.BATTERY_STATUS_DISCHARGING || status == BatteryManager.BATTERY_STATUS_NOT_CHARGING
|
||||
if (lastDischarging != null && lastDischarging != discharging) runtimeEstimator.reset()
|
||||
lastDischarging = discharging
|
||||
val currentForRuntimeUa = currentNowUa.takeIf { it != 0L } ?: currentAvgUa
|
||||
val chargeFullUah = if (chargeNowUah > 0 && pct > 0) chargeNowUah * 100 / pct else 0L
|
||||
val energyNowUwh = chargeNowUah * voltageUv / 1_000_000L
|
||||
val energyFullUwh = chargeFullUah * voltageUv / 1_000_000L
|
||||
val powerNowUw = abs(currentNowUa) * voltageUv / 1_000_000L
|
||||
val runtimeHours = if (discharging)
|
||||
runtimeEstimator.estimateHours(chargeNowUah.toDouble(), currentForRuntimeUa.toDouble())
|
||||
else null
|
||||
val timeToEmptyS = BatteryRuntimeEstimator.secondsFromHours(runtimeHours)
|
||||
val timeToEmptyS = if (discharging && chargeNowUah > 0 && abs(currentAvgUa) > 0) chargeNowUah * 3600L / abs(currentAvgUa) else 0L
|
||||
val charging = status == BatteryManager.BATTERY_STATUS_CHARGING
|
||||
val timeToFullS = if (charging && chargeFullUah > chargeNowUah && abs(currentAvgUa) > 0) (chargeFullUah - chargeNowUah) * 3600L / abs(currentAvgUa) else 0L
|
||||
val statusText = when (status) {
|
||||
@@ -134,7 +126,9 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SessionService"
|
||||
internal fun toMicroamps(raw: Long): Long = BatteryRuntimeEstimator.toMicroamps(raw)
|
||||
private const val MILLIAMP_CEILING = 10_000L
|
||||
|
||||
internal fun toMicroamps(raw: Long): Long = if (abs(raw) < MILLIAMP_CEILING) raw * 1000L else raw
|
||||
private const val PERIOD_MS = 5_000L
|
||||
private val VPOWER_FILES = listOf(
|
||||
"ac_status", "battery_percent", "battery_status",
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.util.ArrayDeque
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.roundToLong
|
||||
|
||||
class BatteryRuntimeEstimator {
|
||||
private val currentSamples = ArrayDeque<Double>()
|
||||
|
||||
@Synchronized
|
||||
fun reset() {
|
||||
currentSamples.clear()
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun estimateHours(chargeNowUah: Double, currentSampleUa: Double): Double? {
|
||||
if (currentSampleUa.isFinite() && currentSampleUa != 0.0) {
|
||||
currentSamples.addLast(abs(currentSampleUa))
|
||||
while (currentSamples.size > MAX_SAMPLES) currentSamples.removeFirst()
|
||||
}
|
||||
if (!chargeNowUah.isFinite() || chargeNowUah <= 0.0 || currentSamples.isEmpty()) return null
|
||||
var sum = 0.0
|
||||
for (sample in currentSamples) sum += sample
|
||||
val averageCurrentUa = sum / currentSamples.size
|
||||
if (!averageCurrentUa.isFinite() || averageCurrentUa <= 0.0) return null
|
||||
val hours = chargeNowUah / averageCurrentUa
|
||||
return hours.takeIf { it.isFinite() && it > 0.0 }
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val MAX_SAMPLES = 25
|
||||
private const val MILLIAMP_CEILING = 10_000L
|
||||
|
||||
@JvmStatic
|
||||
fun toMicroamps(raw: Long): Long {
|
||||
if (raw == Long.MIN_VALUE) return 0L
|
||||
return if (abs(raw) < MILLIAMP_CEILING) raw * 1_000L else raw
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun chargeMicroampHoursFromEnergy(energyUwh: Double, voltageUv: Double): Double? {
|
||||
if (!energyUwh.isFinite() || energyUwh <= 0.0 || !voltageUv.isFinite() || voltageUv <= 0.0) return null
|
||||
return (energyUwh * 1_000_000.0 / voltageUv).takeIf { it.isFinite() && it > 0.0 }
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun currentMicroampsFromPower(powerUw: Double, voltageUv: Double): Double? {
|
||||
if (!powerUw.isFinite() || voltageUv <= 0.0 || !voltageUv.isFinite()) return null
|
||||
return (abs(powerUw) * 1_000_000.0 / voltageUv).takeIf { it.isFinite() && it > 0.0 }
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun secondsFromHours(hours: Double?): Long {
|
||||
if (hours == null || !hours.isFinite() || hours <= 0.0) return 0L
|
||||
val seconds = hours * 3_600.0
|
||||
return if (seconds.isFinite() && seconds < Long.MAX_VALUE.toDouble()) seconds.toLong() else 0L
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun formatDuration(hours: Double?): String? {
|
||||
if (hours == null || !hours.isFinite() || hours <= 0.0) return null
|
||||
val totalMinutes = (hours * 60.0).roundToLong().coerceAtLeast(1L)
|
||||
val wholeHours = totalMinutes / 60L
|
||||
val minutes = totalMinutes % 60L
|
||||
val hourUnit = if (wholeHours == 1L) "hr" else "hrs"
|
||||
val minuteUnit = if (minutes == 1L) "min" else "mins"
|
||||
return when {
|
||||
wholeHours > 0L && minutes > 0L -> "$wholeHours $hourUnit $minutes $minuteUnit"
|
||||
wholeHours > 0L -> "$wholeHours $hourUnit"
|
||||
else -> "$minutes $minuteUnit"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,6 @@ object BootMovie {
|
||||
const val DROIDDECK_30 = "dd30"
|
||||
const val DROIDDECK_60 = "dd60"
|
||||
const val CUSTOM = "custom"
|
||||
private const val SKIP = "skip"
|
||||
const val MAX_BYTES = 50L shl 20
|
||||
const val MAX_CONVERT_SECONDS = 60
|
||||
val PICKER_EXTENSIONS = listOf("webm", "mkv", "mp4", "mov", "m4v", "3gp")
|
||||
@@ -23,7 +22,6 @@ object BootMovie {
|
||||
private val ASSETS = mapOf(
|
||||
DROIDDECK_30 to "droiddeck-startup.webm",
|
||||
DROIDDECK_60 to "droiddeck-startup-60.webm",
|
||||
SKIP to "skip-startup.webm",
|
||||
)
|
||||
|
||||
internal val VIDEO_CODECS = setOf(MediaFormat.MIMETYPE_VIDEO_VP8, MediaFormat.MIMETYPE_VIDEO_VP9, MediaFormat.MIMETYPE_VIDEO_AV1)
|
||||
@@ -76,7 +74,6 @@ object BootMovie {
|
||||
|
||||
fun prepare(context: Context): File? {
|
||||
BootMovieLibrary.restore(context)
|
||||
if (SessionPrefs.skipBootMovie(context)) return assetFile(context, SKIP)
|
||||
val source = sourceOf(context, choice(context)) ?: return null
|
||||
return variant(context, source)
|
||||
}
|
||||
|
||||
@@ -67,7 +67,7 @@ object BootMovieReport {
|
||||
line("== DroidDeck state")
|
||||
line("choice=${BootMovie.choice(context)} saved choice=${SessionPrefs.bootMovie(context)} pending pick=${SessionPrefs.bootMovieApplyNext(context)}")
|
||||
line("last Steam path seen=${SessionPrefs.bootMovieSteamSeen(context)}")
|
||||
line("sound=${SessionPrefs.bootMovieSound(context)} volume=${SessionPrefs.bootMovieVolume(context)} seconds=${SessionPrefs.bootMovieSeconds(context)} skip=${SessionPrefs.skipBootMovie(context)}")
|
||||
line("sound=${SessionPrefs.bootMovieSound(context)} volume=${SessionPrefs.bootMovieVolume(context)} seconds=${SessionPrefs.bootMovieSeconds(context)}")
|
||||
line("session running=${SessionState.running}")
|
||||
line()
|
||||
line("== The movie list as shown")
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
internal class BrowserHandoff(private val timeoutMs: Long) {
|
||||
private var startedAt = -1L
|
||||
private var sessionLeft = false
|
||||
|
||||
fun begin(now: Long) {
|
||||
startedAt = now
|
||||
sessionLeft = false
|
||||
}
|
||||
|
||||
fun sessionHidden() {
|
||||
if (startedAt >= 0) sessionLeft = true
|
||||
}
|
||||
|
||||
fun sessionShown() {
|
||||
if (sessionLeft) clear()
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
startedAt = -1L
|
||||
sessionLeft = false
|
||||
}
|
||||
|
||||
fun active(now: Long): Boolean = startedAt >= 0 && now - startedAt < timeoutMs
|
||||
}
|
||||
@@ -79,13 +79,6 @@ object GameEnvironmentStore {
|
||||
return config
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun setGameResolution(context: Context, scope: String, choice: com.droiddeck.launcher.core.GameResolution.Choice?): GameEnvironment.Config {
|
||||
val config = GameEnvironment.withGameResolution(read(context), scope, choice)
|
||||
save(context, config)
|
||||
return config
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun setDefault(context: Context, scope: String, name: String, value: String): Boolean {
|
||||
val config = read(context)
|
||||
|
||||
@@ -30,33 +30,9 @@ object NoSteamLaunch {
|
||||
GameEnvironment.gameNoSteam(GameEnvironmentStore.read(context), (appId and 0xFFFFFFFFL).toString())
|
||||
}.getOrDefault(false)
|
||||
|
||||
fun scopeOf(program: String?, args: List<String>, battleNetTitle: (String) -> String? = { null }): String? = when (program) {
|
||||
EPIC -> EpicClient.shortcutAppId.toString()
|
||||
BATTLENET -> args.getOrNull(args.indexOf("launch") + 1)?.takeIf { args.contains("launch") }?.let(battleNetTitle)
|
||||
?: com.droiddeck.launcher.runtime.BattleNet.APP_ID.toString()
|
||||
PROTON_RUN -> args.getOrNull(args.indexOf("--app") + 1)?.takeIf { args.contains("--app") }
|
||||
else -> null
|
||||
}?.takeIf { it.isNotEmpty() && GameEnvironment.validScope(it) }
|
||||
|
||||
fun battleNetTitleScope(context: Context, code: String): String? =
|
||||
AddedGames.scan(context).firstOrNull { game ->
|
||||
game.source == com.droiddeck.launcher.stores.Store.BATTLENET.id &&
|
||||
game.storeId?.let(com.droiddeck.launcher.runtime.BattleNet::title)?.code == code
|
||||
}?.let { settingsId(it).toString() }
|
||||
|
||||
fun resolution(config: GameEnvironment.Config, scope: String?, output: Pair<Int, Int>): Pair<Int, Int>? {
|
||||
val choice = scope?.let { GameEnvironment.gameResolution(config, it) } ?: return null
|
||||
return com.droiddeck.launcher.core.GameResolution.resolve(choice, output)
|
||||
}
|
||||
|
||||
fun needsAddedGame(game: Library.SteamGame): Boolean = game.library == Library.ADDED && !viaBattleNet(game)
|
||||
|
||||
private fun viaBattleNet(game: Library.SteamGame): Boolean =
|
||||
game.library == Library.ADDED && game.source == com.droiddeck.launcher.stores.Store.BATTLENET.id
|
||||
|
||||
fun command(game: Library.SteamGame, added: AddedGames.Game?): Command? = when {
|
||||
game.library == Library.EPIC_LAUNCHER -> Command(EPIC, listOf("run"), game.name)
|
||||
viaBattleNet(game) ->
|
||||
game.library == Library.ADDED && game.source == com.droiddeck.launcher.stores.Store.BATTLENET.id ->
|
||||
game.storeId?.let(com.droiddeck.launcher.runtime.BattleNet::title)?.let { Command(BATTLENET, listOf("launch", it.code), game.name) }
|
||||
game.library == Library.ADDED -> added?.let { a -> a.steamAppId?.let { Command(PROTON_RUN, listOf("--app", it.toString()), a.name) } ?: addedCommand(a) }
|
||||
game.appId > 0 -> Command(PROTON_RUN, listOf("--app", game.appId.toString()), game.name)
|
||||
@@ -75,7 +51,7 @@ object NoSteamLaunch {
|
||||
|
||||
fun addedGame(context: Context, game: Library.SteamGame): AddedGames.Game? {
|
||||
val id = game.appId.toLong() and 0xFFFFFFFFL
|
||||
val one = game.gameFiles?.let { AddedGames.single(context, it.path, reuse = true) }
|
||||
val one = game.gameFiles?.let { AddedGames.single(context, it.path) }
|
||||
return one?.takeIf { settingsId(it) == id } ?: AddedGames.scan(context).firstOrNull { settingsId(it) == id }
|
||||
}
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ data class SelectedGameProfile(
|
||||
)
|
||||
}
|
||||
val otherEnvironment = environment.games[game.profileKey].orEmpty().keys - FexPreset.environmentKeys -
|
||||
GameEnvironment.NO_STEAM - GameEnvironment.GAME_RESOLUTION
|
||||
GameEnvironment.NO_STEAM
|
||||
return SelectedGameProfile(
|
||||
appId = selectedAppId,
|
||||
name = game.name,
|
||||
|
||||
@@ -104,7 +104,6 @@ object SessionFiles {
|
||||
"usr/local/bin/droiddeck-steam-share" to "usr/local/bin/droiddeck-steam-share",
|
||||
"usr/local/bin/droiddeck-seed-redists" to "usr/local/bin/droiddeck-seed-redists",
|
||||
"usr/local/bin/droiddeck-launcher-cores" to "usr/local/bin/droiddeck-launcher-cores",
|
||||
"usr/local/bin/droiddeck-pace-cores" to "usr/local/bin/droiddeck-pace-cores",
|
||||
"usr/local/bin/droiddeck-proton-extra" to "usr/local/bin/droiddeck-proton-extra",
|
||||
"usr/local/bin/droiddeck-netmanager" to "usr/local/bin/droiddeck-netmanager",
|
||||
"usr/local/bin/droiddeck-login1" to "usr/local/bin/droiddeck-login1",
|
||||
@@ -355,10 +354,7 @@ object SessionFiles {
|
||||
"stage session=$startsSession pending=$force choice=${SessionPrefs.bootMovie(context)} movie=${startupMovie?.path} " +
|
||||
"staged=$bigPictureMovieInstalled done=$done steam=${home.path} config: $before -> ${startupMoviePath(config)}",
|
||||
)
|
||||
if (startsSession) {
|
||||
disableIdleSleep(home)
|
||||
seedUserDefaults(home)
|
||||
}
|
||||
if (startsSession) disableIdleSleep(home)
|
||||
if (!done) allDone = false
|
||||
if (!bigPictureMovieInstalled) allInstalled = false
|
||||
if (done && home.path.contains(".droiddeck-x64") == activeIsX64) seen = if (bigPictureMovieInstalled) BOOT_MOVIE_PATH else ""
|
||||
@@ -578,85 +574,6 @@ object SessionFiles {
|
||||
}
|
||||
}
|
||||
|
||||
private const val USER_DEFAULTS_MARKER = "droiddeck-user-defaults-initialized"
|
||||
private const val BATTERY_PREFERENCES = "CachedBatteryPreferences"
|
||||
private const val UI_STATE = "UIStoreLocalSteamUIState"
|
||||
private const val SORT_RECENT_OFF = "\\\"bSortedByRecent\\\":false"
|
||||
private const val SORT_RECENT_ON = "\\\"bSortedByRecent\\\":true"
|
||||
private const val BATTERY_PERCENT_ON = "{\\\"bShowBatteryPercentage\\\":true}"
|
||||
|
||||
/**
|
||||
* Seeds opinionated first-run defaults into each Steam account's localconfig.vdf: battery percentage shown and
|
||||
* download speeds in bytes rather than bits, and the library sorted by recently played. A value is written once per account and only when the key is
|
||||
* absent, so a later choice made in Steam is never overridden. Runs while Steam is stopped, as it keeps the
|
||||
* file in memory and rewrites it.
|
||||
*/
|
||||
internal fun seedUserDefaults(steamHome: File) {
|
||||
val users = File(steamHome, "userdata").listFiles { f -> f.isDirectory && f.name.all(Char::isDigit) && f.name != "0" } ?: return
|
||||
for (user in users) {
|
||||
val configDir = File(user, "config")
|
||||
val marker = File(configDir, USER_DEFAULTS_MARKER)
|
||||
val file = File(configDir, "localconfig.vdf")
|
||||
if (marker.exists() || !file.isFile) continue
|
||||
try {
|
||||
val text = file.readText()
|
||||
val updated = withUserDefaults(text) ?: continue
|
||||
if (updated != text) {
|
||||
val staged = File(configDir, file.name + ".staged")
|
||||
staged.writeText(updated)
|
||||
if (!staged.renameTo(file)) { staged.delete(); continue }
|
||||
}
|
||||
marker.writeText("1\n")
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not seed Steam user defaults", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun withUserDefaults(text: String): String? {
|
||||
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
|
||||
val root = findObject(text, "UserLocalConfigStore", 0, text.length) ?: return null
|
||||
var out = text
|
||||
val system = findObject(out, "system", root.open + 1, root.close)
|
||||
if (system == null) {
|
||||
out = insertInto(out, root, listOf("\"system\"", "{", "\t\"displayratesasbits\"\t\t\"0\"", "}"), newline)
|
||||
} else if (!hasKey(out.substring(system.keyStart, system.close + 1), "displayratesasbits")) {
|
||||
val block = out.substring(system.keyStart, system.close + 1)
|
||||
out = out.replaceRange(system.keyStart, system.close + 1, setScalar(block, "displayratesasbits", "0", newline))
|
||||
}
|
||||
val reroot = findObject(out, "UserLocalConfigStore", 0, out.length) ?: return out
|
||||
val web = findObject(out, "WebStorage", reroot.open + 1, reroot.close)
|
||||
if (web == null) {
|
||||
out = insertInto(out, reroot, listOf("\"WebStorage\"", "{", "\t\"$BATTERY_PREFERENCES\"\t\t\"$BATTERY_PERCENT_ON\"", "}"), newline)
|
||||
} else if (!hasKey(out.substring(web.keyStart, web.close + 1), BATTERY_PREFERENCES)) {
|
||||
val block = out.substring(web.keyStart, web.close + 1)
|
||||
out = out.replaceRange(web.keyStart, web.close + 1, setScalar(block, BATTERY_PREFERENCES, BATTERY_PERCENT_ON, newline))
|
||||
}
|
||||
return seedRecentSort(out, newline)
|
||||
}
|
||||
|
||||
// The library sort lives inside a JSON string; Steam writes bSortedByRecent:false until the player picks a sort,
|
||||
// so the first seed flips it once and the marker file keeps a later choice.
|
||||
private fun seedRecentSort(text: String, newline: String): String {
|
||||
val root = findObject(text, "UserLocalConfigStore", 0, text.length) ?: return text
|
||||
val web = findObject(text, "WebStorage", root.open + 1, root.close) ?: return text
|
||||
val block = text.substring(web.keyStart, web.close + 1)
|
||||
if (!hasKey(block, UI_STATE)) {
|
||||
return text.replaceRange(web.keyStart, web.close + 1,
|
||||
setScalar(block, UI_STATE, "{\\\"nVersion\\\":1,$SORT_RECENT_ON}", newline))
|
||||
}
|
||||
return text.replaceRange(web.keyStart, web.close + 1, block.replace(SORT_RECENT_OFF, SORT_RECENT_ON))
|
||||
}
|
||||
|
||||
private fun hasKey(block: String, key: String) = Regex("(?m)^[\\t ]*\"${Regex.escape(key)}\"[\\t ]").containsMatchIn(block)
|
||||
|
||||
private fun insertInto(text: String, parent: VdfBlock, lines: List<String>, newline: String): String {
|
||||
val lineStart = text.lastIndexOf('\n', parent.close).let { if (it < 0) 0 else it + 1 }
|
||||
val indent = text.substring(lineStart, parent.close).takeWhile { it == '\t' || it == ' ' } + "\t"
|
||||
val section = lines.joinToString(newline) { indent + it } + newline
|
||||
return text.substring(0, lineStart) + section + text.substring(lineStart)
|
||||
}
|
||||
|
||||
private val IDLE_SLEEP_TIMERS = listOf("IdleSuspendBatterySeconds", "IdleSuspendACSeconds")
|
||||
|
||||
internal fun disableIdleSleep(steamHome: File): Boolean {
|
||||
|
||||
@@ -21,7 +21,6 @@ class SessionPipController(
|
||||
private set
|
||||
private var suppressAuto = false
|
||||
private var visit = false
|
||||
private var requested = false
|
||||
private var lastParams = ""
|
||||
val floating get() = transitioning || activity.isInPictureInPictureMode
|
||||
|
||||
@@ -48,7 +47,7 @@ class SessionPipController(
|
||||
return builder.build()
|
||||
}
|
||||
|
||||
fun enter(explicit: Boolean = true) {
|
||||
fun enter() {
|
||||
if (!eligible()) {
|
||||
Toast.makeText(activity, R.string.pip_not_ready, Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
@@ -60,10 +59,8 @@ class SessionPipController(
|
||||
return
|
||||
}
|
||||
prepare()
|
||||
requested = explicit
|
||||
val entered = runCatching { activity.enterPictureInPictureMode(params(bounds())) }.getOrDefault(false)
|
||||
if (!entered) {
|
||||
requested = false
|
||||
restore()
|
||||
Toast.makeText(activity, R.string.pip_unavailable, Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
@@ -71,7 +68,7 @@ class SessionPipController(
|
||||
|
||||
fun leaving() {
|
||||
if (!automatic() || !allowed()) return
|
||||
if (Build.VERSION.SDK_INT < 31) enter(explicit = false) else prepare()
|
||||
if (Build.VERSION.SDK_INT < 31) enter() else prepare()
|
||||
}
|
||||
|
||||
private fun prepare() {
|
||||
@@ -88,8 +85,6 @@ class SessionPipController(
|
||||
showPipUi(true)
|
||||
SessionService.beginPip(activity)
|
||||
SessionService.setActivityVisible(activity, true)
|
||||
if (requested) runCatching { com.droiddeck.launcher.HomeApp.showFrontEnd(activity) }
|
||||
requested = false
|
||||
} else restore()
|
||||
refresh(true)
|
||||
}
|
||||
|
||||
@@ -201,18 +201,6 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("gameStoresEnabled", on).apply()
|
||||
}
|
||||
|
||||
fun soundtracksEnabled(context: Context): Boolean = prefs(context).getBoolean("soundtracksEnabled", true)
|
||||
|
||||
fun setSoundtracksEnabled(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("soundtracksEnabled", on).apply()
|
||||
}
|
||||
|
||||
fun soundtracksIngame(context: Context): Boolean = prefs(context).getBoolean("soundtracksIngame", false)
|
||||
|
||||
fun setSoundtracksIngame(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("soundtracksIngame", on).apply()
|
||||
}
|
||||
|
||||
fun gameStoresSpeedTier(context: Context): String = prefs(context).getString("gameStoresSpeedTier", "fast") ?: "fast"
|
||||
|
||||
fun setGameStoresSpeedTier(context: Context, tier: String) {
|
||||
@@ -265,7 +253,7 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("railLabels", show).apply()
|
||||
}
|
||||
|
||||
fun agentTab(context: Context): Boolean = prefs(context).getBoolean("agentTab", true)
|
||||
fun agentTab(context: Context): Boolean = prefs(context).getBoolean("agentTab", false)
|
||||
|
||||
fun setAgentTab(context: Context, show: Boolean) {
|
||||
prefs(context).edit().putBoolean("agentTab", show).apply()
|
||||
@@ -277,12 +265,6 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("libraryShowUninstalled", show).apply()
|
||||
}
|
||||
|
||||
fun libraryFavorites(context: Context): Set<String> = prefs(context).getStringSet("libraryFavorites", null)?.toSet().orEmpty()
|
||||
|
||||
fun setLibraryFavorites(context: Context, keys: Set<String>) {
|
||||
prefs(context).edit().putStringSet("libraryFavorites", keys.toSet()).apply()
|
||||
}
|
||||
|
||||
fun storesTabOrder(context: Context): List<String> = idList(prefs(context).getString("storesTabOrder", null))
|
||||
|
||||
fun setStoresTabOrder(context: Context, order: List<String>) {
|
||||
@@ -295,24 +277,6 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("storesTabHidden", hidden.joinToString(",")).apply()
|
||||
}
|
||||
|
||||
fun navTabOrder(context: Context): List<String> = idList(prefs(context).getString("navTabOrder", null))
|
||||
|
||||
fun setNavTabOrder(context: Context, order: List<String>) {
|
||||
prefs(context).edit().putString("navTabOrder", order.joinToString(",")).apply()
|
||||
}
|
||||
|
||||
fun navTabShelved(context: Context): Set<String> = idList(prefs(context).getString("navTabShelved", "soundtracks,agent")).toSet()
|
||||
|
||||
fun setNavTabShelved(context: Context, keys: Set<String>) {
|
||||
prefs(context).edit().putString("navTabShelved", keys.joinToString(",")).apply()
|
||||
}
|
||||
|
||||
fun navTabHidden(context: Context): Set<String> = idList(prefs(context).getString("navTabHidden", null)).toSet()
|
||||
|
||||
fun setNavTabHidden(context: Context, keys: Set<String>) {
|
||||
prefs(context).edit().putString("navTabHidden", keys.joinToString(",")).apply()
|
||||
}
|
||||
|
||||
private fun idList(raw: String?): List<String> = raw.orEmpty().split(',').map { it.trim() }.filter { it.isNotEmpty() }
|
||||
|
||||
val STORES_SORTS = listOf("lastPlayed", "recentlyInstalled", "titleAsc", "titleDesc", "sizeDesc", "sizeAsc", "releaseDateDesc")
|
||||
@@ -756,12 +720,6 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("syncFallback", on).apply()
|
||||
}
|
||||
|
||||
fun paceCores(context: Context): Boolean = prefs(context).getBoolean("paceCores", true)
|
||||
|
||||
fun setPaceCores(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("paceCores", on).apply()
|
||||
}
|
||||
|
||||
fun gamescopeRealtime(context: Context): Boolean = prefs(context).getBoolean("gamescopeRealtime", false)
|
||||
|
||||
fun setGamescopeRealtime(context: Context, on: Boolean) {
|
||||
@@ -1176,11 +1134,6 @@ object SessionPrefs {
|
||||
fun setBootMovieVolume(context: Context, percent: Int) { prefs(context).edit().putInt("bootMovieVolume", percent.coerceIn(0, 100)).apply() }
|
||||
fun bootMovieSeconds(context: Context): Int = prefs(context).getInt("bootMovieSeconds", 0).coerceAtLeast(0)
|
||||
fun setBootMovieSeconds(context: Context, seconds: Int) { prefs(context).edit().putInt("bootMovieSeconds", seconds.coerceAtLeast(0)).apply() }
|
||||
fun skipBootMovie(context: Context): Boolean = prefs(context).getBoolean("skipBootMovie", false)
|
||||
fun setSkipBootMovie(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("skipBootMovie", on).apply()
|
||||
setBootMovieApplyNext(context, true)
|
||||
}
|
||||
fun bootMovieApplyNext(context: Context): Boolean = prefs(context).getBoolean("bootMovieApplyNext", false)
|
||||
fun setBootMovieApplyNext(context: Context, on: Boolean) { prefs(context).edit().putBoolean("bootMovieApplyNext", on).apply() }
|
||||
fun bootMovieSteamSeen(context: Context): String? = prefs(context).getString("bootMovieSteamSeen", null)
|
||||
@@ -1298,11 +1251,6 @@ object SessionPrefs {
|
||||
fun addedGameStoredAppId(context: Context, folderPath: String): Long? =
|
||||
prefs(context).getLong("addedAppId:$folderPath", 0L).takeIf { it != 0L }
|
||||
|
||||
fun addedGameFolders(context: Context): Map<Long, String> = prefs(context).all.mapNotNull { (key, value) ->
|
||||
val id = (value as? Long)?.takeIf { key.startsWith("addedAppId:") && it != 0L } ?: return@mapNotNull null
|
||||
(id and 0xFFFFFFFFL) to key.removePrefix("addedAppId:")
|
||||
}.toMap()
|
||||
|
||||
fun followStoreGame(context: Context, key: String, folderPath: String, gone: (String) -> Boolean) = synchronized(addedGameLock) {
|
||||
val p = prefs(context)
|
||||
val previous = p.getString("storeFolder:$key", null)
|
||||
|
||||
@@ -23,7 +23,6 @@ import android.os.IBinder
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.PowerManager
|
||||
import android.os.SystemClock
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.view.Display
|
||||
import android.util.Log
|
||||
@@ -86,12 +85,7 @@ class SessionService : Service() {
|
||||
private var activityDisplayId = Display.DEFAULT_DISPLAY
|
||||
private var xrActivityVisible = false
|
||||
private var signInHold = false
|
||||
private val browserHandoff = BrowserHandoff(BROWSER_HANDOFF_TIMEOUT_MS)
|
||||
private val browserHandoffExpired = Runnable {
|
||||
suspendAttemptFailed = false
|
||||
updateSuspendPolicy()
|
||||
}
|
||||
private val hasVisibleSurface get() = browserHandoff.active(SystemClock.elapsedRealtime()) || !SessionVisibilityPolicy.isHidden(
|
||||
private val hasVisibleSurface get() = !SessionVisibilityPolicy.isHidden(
|
||||
activityStarted = activityVisible || signInHold,
|
||||
defaultDisplayOn = (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: screenOn,
|
||||
activityOnDefaultDisplay = activityDisplayId == Display.DEFAULT_DISPLAY,
|
||||
@@ -241,7 +235,6 @@ class SessionService : Service() {
|
||||
ACTION_ACTIVITY_VISIBLE -> {
|
||||
if (!SessionState.pipActive) pipTask = false
|
||||
activityVisible = true
|
||||
browserHandoff.sessionShown()
|
||||
activityDisplayId = intent.getIntExtra(EXTRA_ACTIVITY_DISPLAY_ID, activityDisplayId)
|
||||
sessionDisplayId = intent.getIntExtra(EXTRA_DISPLAY_ID, sessionDisplayId)
|
||||
screenOn = readScreenOn()
|
||||
@@ -265,7 +258,6 @@ class SessionService : Service() {
|
||||
}
|
||||
ACTION_ACTIVITY_HIDDEN -> {
|
||||
activityVisible = false
|
||||
browserHandoff.sessionHidden()
|
||||
activityDisplayId = intent.getIntExtra(EXTRA_ACTIVITY_DISPLAY_ID, activityDisplayId)
|
||||
suspendAttemptFailed = false
|
||||
updateSuspendPolicy()
|
||||
@@ -295,17 +287,6 @@ class SessionService : Service() {
|
||||
updateSuspendPolicy()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
ACTION_BROWSER_HANDOFF -> {
|
||||
if (!SessionState.running) return START_NOT_STICKY
|
||||
browserHandoff.begin(SystemClock.elapsedRealtime())
|
||||
if (!activityVisible) browserHandoff.sessionHidden()
|
||||
mainHandler.removeCallbacks(browserHandoffExpired)
|
||||
mainHandler.postDelayed(browserHandoffExpired, BROWSER_HANDOFF_TIMEOUT_MS)
|
||||
if (!manualHold) manualPauseRequested = false
|
||||
suspendAttemptFailed = false
|
||||
updateSuspendPolicy()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
ACTION_MIC_CHANGED -> {
|
||||
if (SessionState.running && SessionState.micAvailable && !SessionState.suspended) {
|
||||
val enabled = intent.getBooleanExtra("enabled", false)
|
||||
@@ -362,8 +343,6 @@ class SessionService : Service() {
|
||||
activityVisible = true
|
||||
xrActivityVisible = false
|
||||
signInHold = false
|
||||
browserHandoff.clear()
|
||||
mainHandler.removeCallbacks(browserHandoffExpired)
|
||||
sessionDisplayId = intent?.getIntExtra(EXTRA_DISPLAY_ID, Display.DEFAULT_DISPLAY) ?: Display.DEFAULT_DISPLAY
|
||||
activityDisplayId = intent?.getIntExtra(EXTRA_ACTIVITY_DISPLAY_ID, sessionDisplayId) ?: sessionDisplayId
|
||||
screenOn = readScreenOn()
|
||||
@@ -609,14 +588,6 @@ class SessionService : Service() {
|
||||
|
||||
guest.add("BL_WIDTH=" + size.first)
|
||||
guest.add("BL_HEIGHT=" + size.second)
|
||||
if (noSteamGame()) runCatching {
|
||||
val scope = NoSteamLaunch.scopeOf(SessionState.program, SessionState.programArgs) { NoSteamLaunch.battleNetTitleScope(this, it) }
|
||||
NoSteamLaunch.resolution(GameEnvironmentStore.read(this), scope, size)
|
||||
}.onFailure { Log.w(TAG, "game resolution", it) }.getOrNull()?.let { (w, h) ->
|
||||
guest.add("BL_GAME_WIDTH=$w")
|
||||
guest.add("BL_GAME_HEIGHT=$h")
|
||||
Log.i(TAG, "game resolution: ${w}x$h on a ${size.first}x${size.second} output")
|
||||
}
|
||||
if (SessionState.followScreen || size.first < size.second ||
|
||||
SessionPrefs.orientation(this) == android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
|
||||
guest.add("BL_FOLLOW_OUTPUT=1")
|
||||
@@ -1006,7 +977,6 @@ class SessionService : Service() {
|
||||
guest.add("BL_SYNC=" + (if (SessionPrefs.fastSync(this)) "1" else "0"))
|
||||
guest.add("BL_SYNC_FALLBACK=" + (if (SessionPrefs.syncFallback(this)) "1" else "0"))
|
||||
guest.add("BL_FSYNC_FIRST=" + (if (SessionPrefs.fsyncFirst(this)) "1" else "0"))
|
||||
guest.add("BL_PACE_CORES=" + (if (SessionPrefs.paceCores(this)) "1" else "0"))
|
||||
guest.add("BL_GAMESCOPE_REALTIME=" + (if (SessionPrefs.gamescopeRealtime(this)) "1" else "0"))
|
||||
if (SessionPrefs.cursorComposite(this)) guest.add("BL_CURSOR_COMPOSITE=1")
|
||||
relativeMouseForSession().takeIf { it != 0 }?.let { guest.add("gamescope_relative_mouse=$it") }
|
||||
@@ -1018,9 +988,7 @@ class SessionService : Service() {
|
||||
SessionPrefs.vramCapMb(this).takeIf { it > 0 }?.let { guest.add("BL_VRAM_MB=$it") }
|
||||
guest.add("AUDIO_DIRECT_DECAY=0")
|
||||
val extra = extraEnv() + agentEnvironment
|
||||
mapOf("TU_DEBUG" to (tuOverride ?: if (tuDriver) "sysmem" else ""), "MESA_NO_ERROR" to "").forEach { (name, game) ->
|
||||
if (extra.none { it.startsWith("$name=") }) guest.add("$GAME_PREFIX$name=$game")
|
||||
}
|
||||
if (extra.none { it.startsWith("TU_DEBUG=") }) guest.add("$GAME_TU_DEBUG=" + (tuOverride ?: if (tuDriver) "sysmem" else ""))
|
||||
extra.forEach { guest.add(it) }
|
||||
com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice(this)?.let { guest.add("${com.droiddeck.launcher.gpu.TpUbwcHint.ENV}=$it") }
|
||||
val clientPinned = steamHere && SessionPrefs.clientCpusOverride(this)
|
||||
@@ -2400,7 +2368,7 @@ class SessionService : Service() {
|
||||
private const val TRACER_NICE = -6
|
||||
private const val MIC_RELEASE_TIMEOUT_MS = 5_000L
|
||||
private const val TU_DEBUG_SWITCH = "Download/droiddeck-tu-debug"
|
||||
private const val GAME_PREFIX = "DROIDDECK_GAME_"
|
||||
private const val GAME_TU_DEBUG = "DROIDDECK_GAME_TU_DEBUG"
|
||||
private const val LEGACY_ENV_SWITCH = "Download/droiddeck-env"
|
||||
private const val ENV_SWITCH_NAME = "droiddeck-env"
|
||||
|
||||
@@ -2430,8 +2398,6 @@ class SessionService : Service() {
|
||||
private const val ACTION_XR_ACTIVITY_HIDDEN = "com.droiddeck.launcher.XR_ACTIVITY_HIDDEN"
|
||||
private const val ACTION_SIGN_IN_HOLD = "com.droiddeck.launcher.SIGN_IN_HOLD"
|
||||
private const val EXTRA_HOLD = "hold"
|
||||
private const val ACTION_BROWSER_HANDOFF = "com.droiddeck.launcher.BROWSER_HANDOFF"
|
||||
private const val BROWSER_HANDOFF_TIMEOUT_MS = 10 * 60_000L
|
||||
private const val ACTION_TRACK_AUXILIARY = "com.droiddeck.launcher.TRACK_AUXILIARY"
|
||||
private const val ACTION_STOP_AUXILIARY = "com.droiddeck.launcher.STOP_AUXILIARY"
|
||||
private const val ACTION_AUXILIARY_EXITED = "com.droiddeck.launcher.AUXILIARY_EXITED"
|
||||
@@ -2534,11 +2500,6 @@ class SessionService : Service() {
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_SIGN_IN_HOLD).putExtra(EXTRA_HOLD, hold))
|
||||
}
|
||||
|
||||
fun holdForBrowserHandoff(context: Context) {
|
||||
if (!SessionState.running) return
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_BROWSER_HANDOFF))
|
||||
}
|
||||
|
||||
fun pause(context: Context) {
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_PAUSE_NOW))
|
||||
}
|
||||
|
||||
@@ -14,18 +14,18 @@ object SettingsReset {
|
||||
internal val SESSION_KEYS = setOf(
|
||||
"orientation", "launcherFullscreen", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt",
|
||||
"dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard",
|
||||
"gameStoresEnabled", "soundtracksEnabled", "soundtracksIngame", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
|
||||
"gameStoresEnabled", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
|
||||
"storesInstallLanguage",
|
||||
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "backActionsInverted", "backDoubleTapMs", "touch", "osc", "shape", "steamController",
|
||||
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
|
||||
"stretch16x9", "picturePosition", "railLabels", "agentTab", "navTabOrder", "navTabShelved", "navTabHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
|
||||
"stretch16x9", "picturePosition", "railLabels", "agentTab", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
|
||||
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
|
||||
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores", "ramCapMb", "vramCapMb", "zramClient",
|
||||
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "ramCapMb", "vramCapMb", "zramClient",
|
||||
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
|
||||
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "nativeUserland", "cursorComposite",
|
||||
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics", "buildWatermark",
|
||||
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
|
||||
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds", "skipBootMovie",
|
||||
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds",
|
||||
"bootMovieApplyNext", "bootMovieSteamSeen",
|
||||
"questDefaultsV1", "telemetryAuto", "telemetryOff", "statsStrip", "statsHud", "bottomHud", "bottomStripMetrics", "bottomStripTabs", "statsDash", "statsSpeedUnit",
|
||||
)
|
||||
|
||||
@@ -155,42 +155,6 @@ object SteamStorage {
|
||||
|
||||
fun leftoverId(name: String): Int? = name.toLongOrNull()?.takeIf { it in 1 until (1L shl 31) }?.toInt()
|
||||
|
||||
fun shortcutId(name: String): Long? = name.toLongOrNull()
|
||||
?.takeIf { it in Int.MIN_VALUE until 0 || it in (1L shl 31) until (1L shl 32) }?.and(0xFFFFFFFFL)
|
||||
|
||||
private val COMPAT_PATH = Regex("""STEAM_COMPAT_DATA_PATH=(?:"([^"]*)"|'([^']*)'|(\S+))""")
|
||||
private val COMPAT_ID = Regex("""/compatdata/(-?\d+)/*$""")
|
||||
|
||||
fun sharedPrefixId(launchOptions: String): Long? {
|
||||
val path = COMPAT_PATH.find(launchOptions)?.groupValues?.drop(1)?.firstOrNull { it.isNotEmpty() } ?: return null
|
||||
return COMPAT_ID.find(path.trim())?.groupValues?.get(1)?.let(::shortcutId)
|
||||
}
|
||||
|
||||
private val GAME_FOLDER = Regex("""Z:\\\\(?:[^"\\]+\\\\)*?(?:steamapps\\\\common|Games\\\\Stores\\\\[^"\\]+)\\\\([^"\\]+)""")
|
||||
|
||||
fun gameFolderHint(prefix: File): String? = runCatching {
|
||||
listOf("pfx/system.reg", "pfx/user.reg").map { File(prefix, it) }.filter { it.isFile && it.length() < 64L * 1024 * 1024 }
|
||||
.flatMap { f -> f.useLines { lines -> lines.flatMap { GAME_FOLDER.findAll(it).map { m -> m.groupValues[1] } }.toList() } }
|
||||
.groupingBy { it }.eachCount().maxByOrNull { it.value }?.key
|
||||
}.getOrNull()
|
||||
|
||||
class Shortcut(val name: String, val launchOptions: List<String>)
|
||||
|
||||
fun shortcuts(root: File): Map<Long, Shortcut>? = runCatching {
|
||||
val userdata = File(root, "userdata")
|
||||
val users = if (userdata.exists()) userdata.listFiles() ?: return null else emptyArray()
|
||||
users.mapNotNull { File(it, "config/shortcuts.vdf").takeIf(File::isFile) }.flatMap { file ->
|
||||
val vdf = com.droiddeck.launcher.frontend.SteamAppInfo.readMap(java.nio.ByteBuffer.wrap(file.readBytes()).order(java.nio.ByteOrder.LITTLE_ENDIAN), null)
|
||||
(vdf["shortcuts"] as? Map<*, *>)?.values?.filterIsInstance<Map<*, *>>()?.mapNotNull { s ->
|
||||
fun value(key: String) = s.entries.firstOrNull { (it.key as? String).equals(key, ignoreCase = true) }?.value as? String
|
||||
val id = value("appid")?.toLongOrNull()?.and(0xFFFFFFFFL) ?: return@mapNotNull null
|
||||
id to Shortcut(value("AppName") ?: "", listOfNotNull(value("LaunchOptions")))
|
||||
}.orEmpty()
|
||||
}.groupBy({ it.first }, { it.second }).mapValues { (_, all) ->
|
||||
Shortcut(all.firstOrNull { it.name.isNotEmpty() }?.name.orEmpty(), all.flatMap { it.launchOptions })
|
||||
}
|
||||
}.getOrNull()
|
||||
|
||||
fun isStubPrefix(prefix: File): Boolean = prefix.walkTopDown().onEnter { !java.nio.file.Files.isSymbolicLink(it.toPath()) }
|
||||
.none { it.isFile && it.name != "steam_autocloud.vdf" && !java.nio.file.Files.isSymbolicLink(it.toPath()) }
|
||||
}
|
||||
@@ -18,7 +18,7 @@ enum class Bucket { GAMES, GAME_DATA, TOOLS, COMPONENTS, STORES, DESKTOP, SYSTEM
|
||||
|
||||
class GameUsage(
|
||||
val appId: Int, val name: String, val art: File?, val library: String, val internal: Boolean, val lastPlayed: Long,
|
||||
val game: Long, val prefix: Long, val shaders: Long, val workshop: Long, val shaderDirs: List<File>,
|
||||
val game: Long, val prefix: Long, val shaders: Long, val workshop: Long, val shaderDir: File?,
|
||||
val x64: Boolean = false, val prefixDir: File? = null,
|
||||
) {
|
||||
val data: Long get() = prefix + shaders + workshop
|
||||
@@ -33,16 +33,7 @@ class ToolUsage(
|
||||
val games: Int, val isDefault: Boolean, val manifests: List<File>, val dirs: List<File>,
|
||||
)
|
||||
|
||||
class Leftover(val appId: Long, val prefix: File?, val shaders: File?, val bytes: Long, val safe: Boolean, val shortcut: Boolean = false, val name: String? = null, val prefixBytes: Long = 0)
|
||||
|
||||
enum class PrefixOwner { SHARED, LAUNCHER, GAME, UNKNOWN }
|
||||
|
||||
class KeptPrefix(
|
||||
val dir: File, val owner: PrefixOwner, val name: String?, val bytes: Long, val library: String, val x64: Boolean, val users: List<String> = emptyList(),
|
||||
val shaders: File? = null, val shaderBytes: Long = 0,
|
||||
)
|
||||
|
||||
class StoreGameUsage(val game: com.droiddeck.launcher.stores.InstalledStoreGame, val bytes: Long, val internal: Boolean)
|
||||
class Leftover(val appId: Int, val prefix: File?, val shaders: File?, val bytes: Long, val safe: Boolean)
|
||||
|
||||
class ComponentUsage(
|
||||
val comp: String, val version: String, val bytes: Long, val inUse: Boolean,
|
||||
@@ -68,11 +59,9 @@ class StorageReport(
|
||||
val components: List<ComponentUsage>,
|
||||
val flatpakApps: List<FlatpakUsage>,
|
||||
val flatpakRuntimes: Long,
|
||||
val kept: List<KeptPrefix>,
|
||||
val otherPrefixes: Long,
|
||||
val leftoversChecked: Boolean,
|
||||
val storeGames: List<StoreGameUsage> = emptyList(),
|
||||
) {
|
||||
val otherPrefixes: Long get() = kept.sumOf { it.bytes }
|
||||
val droiddeck: Long get() = buckets.values.sum()
|
||||
val installedShaders: Long get() = games.sumOf { it.shaders }
|
||||
val unusedTools: List<ToolUsage> get() = tools.filter { it.state == ToolState.UNUSED }
|
||||
@@ -102,16 +91,7 @@ object StorageScan {
|
||||
|
||||
fun steamRoot(context: Context) = SessionPrefs.steamRoot(context, "arm64")
|
||||
|
||||
fun measure(file: File): Long = Walker().measure(file)
|
||||
|
||||
fun scan(context: Context): StorageReport {
|
||||
val phases = ArrayList<String>()
|
||||
var mark = android.os.SystemClock.elapsedRealtime()
|
||||
fun phase(name: String) {
|
||||
val now = android.os.SystemClock.elapsedRealtime()
|
||||
phases.add("$name ${now - mark}")
|
||||
mark = now
|
||||
}
|
||||
val walker = Walker()
|
||||
val files = context.filesDir
|
||||
val rootfs = LinuxRuntime.rootDir(context)
|
||||
@@ -119,7 +99,6 @@ object StorageScan {
|
||||
val x64Root = SessionPrefs.steamRoot(context, "x86_64").takeIf { SteamStorage.x64ClientPresent(it) }
|
||||
val clients = listOfNotNull("arm64", "x86_64".takeIf { x64Root != null })
|
||||
fun canonical(f: File) = runCatching { f.canonicalPath }.getOrDefault(f.path)
|
||||
phase("setup")
|
||||
val art = clients.associate { arch ->
|
||||
(arch == "x86_64") to runCatching { Library.steamGames(context, arch = arch) }.getOrDefault(emptyList()).associateBy { it.appId }
|
||||
}
|
||||
@@ -127,7 +106,6 @@ object StorageScan {
|
||||
class Lib(val root: File, val label: String, val internal: Boolean, val data: File, val listing: SteamStorage.Listing?, val x64: Boolean) {
|
||||
val manifests: List<SteamStorage.Manifest>? get() = listing?.manifests
|
||||
}
|
||||
phase("steam games")
|
||||
val libs = clients.flatMap { arch ->
|
||||
val x64 = arch == "x86_64"
|
||||
val primary = canonical(SessionPrefs.steamRoot(context, arch))
|
||||
@@ -145,7 +123,6 @@ object StorageScan {
|
||||
val clientIds = libs.groupBy { it.x64 }.mapValues { (_, own) -> own.flatMap { it.listing?.ids.orEmpty() }.toSet() }
|
||||
fun installedGames(x64: Boolean) = libs.filter { it.x64 == x64 }.flatMap { it.manifests.orEmpty() }
|
||||
.filter { !SteamStorage.isTool(it) && it.installed }.map { it.appId.toString() }.toSet()
|
||||
phase("libraries")
|
||||
val armUse = runCatching { SteamStorage.compatMappings(File(steamRoot, "config/config.vdf").readText()) }.getOrNull()
|
||||
?.let { SteamStorage.ToolUse(it, installedGames(false)) }
|
||||
val x64Vdf = x64Root?.let { File(it, "config/config.vdf") }
|
||||
@@ -155,10 +132,8 @@ object StorageScan {
|
||||
val uses = listOfNotNull(armUse, x64Use)
|
||||
fun gamesOn(tool: String) = uses.sumOf { it.games(tool) }
|
||||
|
||||
val libraryDataRoots = File(files, "steam-libraries").listFiles().orEmpty().filter { it.isDirectory }
|
||||
val tools = LinkedHashMap<String, ToolUsage>()
|
||||
val games = ArrayList<GameUsage>()
|
||||
val countedShaders = HashSet<String>()
|
||||
for (lib in libs) {
|
||||
for (m in lib.manifests.orEmpty()) {
|
||||
val dir = m.installDir
|
||||
@@ -201,19 +176,17 @@ object StorageScan {
|
||||
val compatRoot = File(lib.data, "steamapps/compatdata").takeIf { it.isDirectory } ?: File(lib.root, "steamapps/compatdata")
|
||||
val prefixDir = File(compatRoot, m.appId.toString()).takeIf { it.isDirectory }
|
||||
val prefix = prefixDir?.let { walker.measure(it) } ?: 0
|
||||
val shaderDirs = ((listOf(lib) + libs.filter { it !== lib && it.x64 == lib.x64 }).map { it.data } + libraryDataRoots)
|
||||
.map { File(it, "steamapps/shadercache/${m.appId}") }.filter { it.isDirectory }.distinctBy { canonical(it) }
|
||||
val shaders = shaderDirs.filter { countedShaders.add(canonical(it)) }.sumOf { walker.measure(it) }
|
||||
val shaderDir = File(lib.data, "steamapps/shadercache/${m.appId}").takeIf { it.isDirectory }
|
||||
val shaders = shaderDir?.let { walker.measure(it) } ?: 0
|
||||
val workshop = File(lib.root, "steamapps/workshop/content/${m.appId}").takeIf { it.isDirectory }?.let { walker.measure(it) } ?: 0
|
||||
val known = art[lib.x64]?.get(m.appId)
|
||||
games.add(GameUsage(
|
||||
m.appId, known?.name ?: m.name, known?.art, lib.label, lib.internal, m.lastPlayed,
|
||||
gameBytes, prefix, shaders, workshop, shaderDirs, lib.x64, prefixDir,
|
||||
gameBytes, prefix, shaders, workshop, shaderDir, lib.x64, prefixDir,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
phase("manifests and games")
|
||||
File(steamRoot, "compatibilitytools.d").listFiles()?.sortedBy { it.name }?.forEach { dir ->
|
||||
if (!dir.isDirectory) return@forEach
|
||||
val bytes = walker.measure(dir)
|
||||
@@ -233,7 +206,6 @@ object StorageScan {
|
||||
)
|
||||
}
|
||||
|
||||
phase("compat tools")
|
||||
val leftovers = ArrayList<Leftover>()
|
||||
for (lib in libs) {
|
||||
if (!everyLibraryRead) break
|
||||
@@ -245,22 +217,16 @@ object StorageScan {
|
||||
for (id in (prefixes.keys + caches.keys).sorted()) {
|
||||
val prefix = prefixes[id]
|
||||
val cache = caches[id]
|
||||
val prefixBytes = prefix?.let { walker.measure(it) } ?: 0
|
||||
val bytes = prefixBytes + (cache?.let { walker.measure(it) } ?: 0)
|
||||
val bytes = (prefix?.let { walker.measure(it) } ?: 0) + (cache?.let { walker.measure(it) } ?: 0)
|
||||
val safe = prefix == null || SteamStorage.isStubPrefix(prefix)
|
||||
val name = if (safe) null else runCatching {
|
||||
com.droiddeck.launcher.frontend.SteamAppInfo.info(context, id, File(if (lib.x64) x64Root ?: steamRoot else steamRoot, "appcache/appinfo.vdf"))?.name
|
||||
}.getOrNull()?.ifEmpty { null }
|
||||
leftovers.add(Leftover(id.toLong(), prefix, cache, bytes, safe, name = name, prefixBytes = prefixBytes))
|
||||
leftovers.add(Leftover(id, prefix, cache, bytes, safe))
|
||||
}
|
||||
}
|
||||
|
||||
phase("leftovers")
|
||||
val logs = SessionPaths.sessionFolders(context).filter { it != SessionPaths.current() } +
|
||||
listOf(File(LinuxRuntime.logDir(context), SessionPaths.TOOLS_DIR)).filter { it.exists() }
|
||||
val logBytes = logs.sumOf { walker.measure(it) }
|
||||
|
||||
phase("logs")
|
||||
val flatpakDir = File(rootfs, "root/.local/share/flatpak")
|
||||
val flatpakNames = runCatching { FlatpakManager.installedApps(context) }.getOrDefault(emptyList()).associate { it.id to it.name }
|
||||
val flatpakApps = File(flatpakDir, "app").listFiles().orEmpty().filter { it.isDirectory }.map { dir ->
|
||||
@@ -268,7 +234,6 @@ object StorageScan {
|
||||
}.sortedByDescending { it.bytes }
|
||||
val flatpakRuntimes = File(flatpakDir, "runtime").takeIf { it.isDirectory }?.let { walker.measure(it) } ?: 0
|
||||
|
||||
phase("flatpak")
|
||||
val componentsDir = File(files, "components")
|
||||
val stored = runCatching { ComponentsManager.stored(context) }.onFailure { Log.w("StorageScan", "components", it) }.getOrNull()
|
||||
val components = stored?.let { st ->
|
||||
@@ -276,70 +241,10 @@ object StorageScan {
|
||||
st.originals.map { ComponentUsage(it.comp, it.protonVersion, it.size, it.kept, protonId = it.protonId, protonName = it.protonName) }
|
||||
}.orEmpty()
|
||||
|
||||
phase("components")
|
||||
val added = com.droiddeck.launcher.frontend.AddedGames.listed(context)
|
||||
val shortcuts = listOfNotNull(steamRoot, x64Root).map { SteamStorage.shortcuts(it) }
|
||||
val ownersRead = added != null && shortcuts.all { it != null }
|
||||
val live = HashMap<Long, String>()
|
||||
shortcuts.forEach { it?.forEach { (id, s) -> live[id] = s.name } }
|
||||
added?.forEach { live[it.appId] = it.name }
|
||||
val folders = SessionPrefs.addedGameFolders(context)
|
||||
val removedFolders = SessionPrefs.removedAddedGames(context).toSet()
|
||||
folders.forEach { (id, path) -> if (id !in live && path !in removedFolders && File(path).exists()) live[id] = File(path).name }
|
||||
val launchers = mapOf(
|
||||
com.droiddeck.launcher.runtime.BattleNet.APP_ID to com.droiddeck.launcher.stores.Store.BATTLENET.label,
|
||||
com.droiddeck.launcher.stores.ubisoft.UbisoftConnect.APP_ID to com.droiddeck.launcher.stores.Store.UBISOFT.label,
|
||||
com.droiddeck.launcher.stores.epic.EpicClient.shortcutAppId to Library.EPIC_LAUNCHER_NAME,
|
||||
)
|
||||
val users = HashMap<Long, MutableSet<String>>()
|
||||
fun shares(own: Long, name: String, launchOptions: String) {
|
||||
SteamStorage.sharedPrefixId(launchOptions)?.takeIf { it != own }?.let { users.getOrPut(it) { LinkedHashSet() }.add(name) }
|
||||
}
|
||||
added?.forEach { shares(it.appId, it.name, it.launchOptions) }
|
||||
shortcuts.forEach { it?.forEach { (id, s) -> s.launchOptions.forEach { shares(id, s.name, it) } } }
|
||||
phase("added games and shortcuts")
|
||||
val kept = ArrayList<KeptPrefix>()
|
||||
for (lib in libs) {
|
||||
val dirs = File(lib.data, "steamapps/compatdata").listFiles().orEmpty().filter { it.isDirectory && SteamStorage.leftoverId(it.name) == null }
|
||||
val caches = File(lib.data, "steamapps/shadercache").listFiles().orEmpty()
|
||||
.mapNotNull { f -> SteamStorage.shortcutId(f.name)?.takeIf { f.isDirectory }?.let { it to f } }.toMap()
|
||||
for (dir in dirs) {
|
||||
val bytes = walker.measure(dir)
|
||||
val id = SteamStorage.shortcutId(dir.name)
|
||||
val cache = id?.let { caches[it] }
|
||||
val cacheBytes = cache?.let { walker.measure(it) } ?: 0
|
||||
when {
|
||||
dir.name == "0" -> kept.add(KeptPrefix(dir, PrefixOwner.SHARED, null, bytes, lib.label, lib.x64))
|
||||
id != null && (id in launchers || id in users) -> kept.add(KeptPrefix(dir, PrefixOwner.LAUNCHER,
|
||||
launchers[id] ?: live[id]?.ifEmpty { null }, bytes, lib.label, lib.x64, users[id].orEmpty().toList(), cache, cacheBytes))
|
||||
id != null && id in live -> kept.add(KeptPrefix(dir, PrefixOwner.GAME, live[id]?.ifEmpty { null }, bytes, lib.label, lib.x64, shaders = cache, shaderBytes = cacheBytes))
|
||||
id != null && ownersRead -> {
|
||||
leftovers.add(Leftover(id, dir, cache, bytes + cacheBytes, SteamStorage.isStubPrefix(dir),
|
||||
shortcut = true, name = folders[id]?.let { File(it).name } ?: SteamStorage.gameFolderHint(dir), prefixBytes = bytes))
|
||||
}
|
||||
else -> kept.add(KeptPrefix(dir, PrefixOwner.UNKNOWN, id?.toString() ?: dir.name, bytes, lib.label, lib.x64))
|
||||
}
|
||||
}
|
||||
if (!ownersRead) continue
|
||||
val prefixIds = dirs.mapNotNullTo(HashSet()) { SteamStorage.shortcutId(it.name) }
|
||||
for ((id, cache) in caches) {
|
||||
if (id in prefixIds || id in live || id in launchers || id in users) continue
|
||||
leftovers.add(Leftover(id, null, cache, walker.measure(cache), true, shortcut = true, name = folders[id]?.let { File(it).name }))
|
||||
}
|
||||
}
|
||||
val otherPrefixes = libs.flatMap { lib ->
|
||||
File(lib.data, "steamapps/compatdata").listFiles().orEmpty().filter { it.isDirectory && SteamStorage.leftoverId(it.name) == null }
|
||||
}.sumOf { walker.measure(it) }
|
||||
|
||||
phase("kept prefixes")
|
||||
val storeGames = (com.droiddeck.launcher.stores.StoreInstallRoot.gameFolders(context).mapNotNull { folder ->
|
||||
com.droiddeck.launcher.stores.StoreGameSidecar.read(folder)
|
||||
?.takeIf { it.isInstalled || it.state == com.droiddeck.launcher.stores.StoreGameSidecar.STATE_UPDATING }
|
||||
?.let { com.droiddeck.launcher.stores.InstalledStoreGame(it, folder) }
|
||||
} + runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetBackend.installedGames(context) }.getOrDefault(emptyList()))
|
||||
.map { g ->
|
||||
val internal = g.folder.path.startsWith(files.path + "/")
|
||||
StoreGameUsage(g, if (internal) walker.measure(g.folder) else -1L, internal)
|
||||
}.sortedByDescending { it.bytes }
|
||||
|
||||
phase("store games")
|
||||
val clientRoots = listOfNotNull(steamRoot, x64Root)
|
||||
val apps = clientRoots.map { File(it, "steamapps") }
|
||||
val privateRoots = File(files, "steam-libraries").listFiles().orEmpty().filter { it.isDirectory }
|
||||
@@ -364,8 +269,6 @@ object StorageScan {
|
||||
val componentBytes = m(componentsDir)
|
||||
val droiddeck = m(files) + m(context.cacheDir) - rootfsBytes - privateBytes - componentBytes +
|
||||
(privateBytes - toolsPrivate - privatePrefixes - privateShaders)
|
||||
phase("totals")
|
||||
Log.i("StorageScan", "scan ms: " + phases.joinToString(", "))
|
||||
val stat = StatFs(files.path)
|
||||
return StorageReport(
|
||||
System.currentTimeMillis(), stat.totalBytes, stat.availableBytes,
|
||||
@@ -381,7 +284,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, otherPrefixes, everyLibraryRead,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,6 @@ import com.droiddeck.launcher.files.FileOps
|
||||
import com.droiddeck.launcher.runtime.FlatpakManager
|
||||
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 }
|
||||
|
||||
@@ -28,45 +27,6 @@ object StorageState {
|
||||
private set
|
||||
var cleaning by mutableStateOf(false)
|
||||
private set
|
||||
var storeBatch by mutableStateOf(false)
|
||||
private set
|
||||
val busy: Boolean get() = cleaning || storeBatch
|
||||
private var refreshAgain = false
|
||||
val storeSizes = androidx.compose.runtime.mutableStateMapOf<String, Long>()
|
||||
private var measuringStores = false
|
||||
|
||||
private fun sizeKey(usage: StoreGameUsage): String = with(usage.game) {
|
||||
"${folder.path}|${sidecar.installVersion}|${sidecar.installedAt}|${StoreGameSidecar.file(folder).lastModified()}"
|
||||
}
|
||||
|
||||
fun storeBytes(usage: StoreGameUsage): Long = if (usage.bytes >= 0) usage.bytes else storeSizes[sizeKey(usage)] ?: -1L
|
||||
|
||||
private fun measureStoreGames(app: Context) {
|
||||
val current = report ?: return
|
||||
if (measuringStores) return
|
||||
val wanted = current.storeGames.filter { it.bytes < 0 && sizeKey(it) !in storeSizes }.map { sizeKey(it) to it.game.folder }
|
||||
if (wanted.isEmpty()) return
|
||||
measuringStores = true
|
||||
Thread({
|
||||
val started = android.os.SystemClock.elapsedRealtime()
|
||||
for ((key, folder) in wanted) {
|
||||
val bytes = runCatching { StorageScan.measure(folder) }.getOrDefault(0L)
|
||||
main.post { storeSizes[key] = bytes }
|
||||
}
|
||||
Log.i(TAG, "measured ${wanted.size} store games on removable storage in ${android.os.SystemClock.elapsedRealtime() - started} ms")
|
||||
main.post {
|
||||
measuringStores = false
|
||||
measureStoreGames(app)
|
||||
}
|
||||
}, "storage-store-sizes").start()
|
||||
}
|
||||
|
||||
private fun publish(app: Context, result: StorageReport) {
|
||||
report = result
|
||||
val live = result.storeGames.mapTo(HashSet()) { sizeKey(it) }
|
||||
storeSizes.keys.retainAll(live)
|
||||
measureStoreGames(app)
|
||||
}
|
||||
var lastFreed by mutableStateOf<Long?>(null)
|
||||
var progress by mutableStateOf<String?>(null)
|
||||
private set
|
||||
@@ -88,21 +48,16 @@ object StorageState {
|
||||
|
||||
fun refresh(context: Context, force: Boolean = false) {
|
||||
val current = report
|
||||
if (scanning || cleaning) {
|
||||
if (force) refreshAgain = true
|
||||
return
|
||||
}
|
||||
if (scanning || cleaning) return
|
||||
if (!force && current != null && System.currentTimeMillis() - current.at < FRESH_MS) return
|
||||
refreshAgain = false
|
||||
val app = context.applicationContext
|
||||
scanning = true
|
||||
Thread({
|
||||
val result = runCatching { StorageScan.scan(app) }
|
||||
.onFailure { Log.w(TAG, "storage scan failed", it) }.getOrNull()
|
||||
main.post {
|
||||
if (result != null) publish(app, result)
|
||||
if (result != null) report = result
|
||||
scanning = false
|
||||
if (refreshAgain) refresh(app, force = true)
|
||||
}
|
||||
}, "storage-scan").start()
|
||||
}
|
||||
@@ -129,7 +84,7 @@ object StorageState {
|
||||
fun safeBytes(report: StorageReport): Long = SAFE.sumOf { bytes(report, it) }
|
||||
|
||||
fun clean(context: Context, items: Set<CleanItem>, onDone: (Long?) -> Unit) {
|
||||
if (busy || SessionState.running) { onDone(null); return }
|
||||
if (cleaning || SessionState.running) { onDone(null); return }
|
||||
val app = context.applicationContext
|
||||
appContext = app
|
||||
cleaning = true
|
||||
@@ -146,7 +101,7 @@ object StorageState {
|
||||
}
|
||||
|
||||
fun removeTool(context: Context, tool: ToolUsage, onDone: (Long?) -> Unit) {
|
||||
if (tool.state != ToolState.UNUSED || busy || SessionState.running) { onDone(null); return }
|
||||
if (tool.state != ToolState.UNUSED || cleaning || SessionState.running) { onDone(null); return }
|
||||
val app = context.applicationContext
|
||||
cleaning = true
|
||||
Thread({
|
||||
@@ -164,7 +119,7 @@ object StorageState {
|
||||
}
|
||||
|
||||
private fun act(context: Context, name: String, action: (Context, StorageReport) -> Boolean, onDone: (Long?) -> Unit = {}) {
|
||||
if (busy || SessionState.running) { onDone(null); return }
|
||||
if (cleaning || SessionState.running) { onDone(null); return }
|
||||
val app = context.applicationContext
|
||||
appContext = app
|
||||
cleaning = true
|
||||
@@ -182,8 +137,8 @@ object StorageState {
|
||||
}
|
||||
|
||||
fun clearShaders(context: Context, appId: Int, x64: Boolean = false) = act(context, "shaders-$appId", { _, fresh ->
|
||||
val dirs = fresh.games.firstOrNull { it.appId == appId && it.x64 == x64 }?.shaderDirs.orEmpty()
|
||||
dirs.isNotEmpty() && dirs.map { FileOps.delete(it) }.all { it }
|
||||
val dir = fresh.games.firstOrNull { it.appId == appId && it.x64 == x64 }?.shaderDir ?: return@act false
|
||||
FileOps.delete(dir)
|
||||
})
|
||||
|
||||
fun resetPrefix(context: Context, game: GameUsage) = act(context, "prefix-${game.appId}", { _, fresh ->
|
||||
@@ -200,41 +155,6 @@ object StorageState {
|
||||
true
|
||||
})
|
||||
|
||||
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" }
|
||||
true
|
||||
})
|
||||
|
||||
fun uninstallStoreGames(context: Context, games: List<StoreGameUsage>) {
|
||||
if (busy || SessionState.running || games.isEmpty()) return
|
||||
storeBatch = true
|
||||
uninstallNext(context.applicationContext, games)
|
||||
}
|
||||
|
||||
private fun uninstallNext(app: Context, games: List<StoreGameUsage>) {
|
||||
val rest = games.dropWhile { com.droiddeck.launcher.stores.download.DownloadQueue.isActive(it.game.key) }
|
||||
val next = rest.firstOrNull()
|
||||
if (next == null || SessionState.running) {
|
||||
storeBatch = false
|
||||
com.droiddeck.launcher.stores.StoresState.notifyLibraryChanged(app)
|
||||
refresh(app, force = true)
|
||||
return
|
||||
}
|
||||
com.droiddeck.launcher.stores.StoresState.uninstall(app, next.game) { uninstallNext(app, rest.drop(1)) }
|
||||
}
|
||||
|
||||
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 }
|
||||
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")
|
||||
targets.forEach { check(FileOps.delete(it)) { "cannot delete $it" } }
|
||||
targets.isNotEmpty()
|
||||
})
|
||||
|
||||
fun removeComponent(context: Context, usage: ComponentUsage) = act(context, "component", { app, fresh ->
|
||||
val current = fresh.components.firstOrNull { it.packageFile == usage.packageFile && it.protonId == usage.protonId &&
|
||||
it.comp == usage.comp && it.version == usage.version } ?: return@act false
|
||||
@@ -266,11 +186,10 @@ object StorageState {
|
||||
private fun finish(app: Context, freed: Long?, onDone: (Long?) -> Unit) {
|
||||
val rescanned = runCatching { StorageScan.scan(app) }.getOrNull()
|
||||
main.post {
|
||||
if (rescanned != null) publish(app, rescanned)
|
||||
if (rescanned != null) report = rescanned
|
||||
cleaning = false
|
||||
lastFreed = freed
|
||||
onDone(freed)
|
||||
if (refreshAgain) refresh(app, force = true)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -282,7 +201,7 @@ object StorageState {
|
||||
CleanItem.LEFTOVERS -> report.leftovers.filter { it.safe }.forEach(::deleteLeftover)
|
||||
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.SHADERS -> report.games.mapNotNull { it.shaderDir }.forEach { FileOps.delete(it) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -89,62 +89,16 @@ object StoreInstalls {
|
||||
StoresState.logLine("uninstalled \"${game.sidecar.title}\"")
|
||||
}
|
||||
|
||||
private val discarding = HashMap<String, Int>()
|
||||
|
||||
fun isDiscarding(folder: File): Boolean = synchronized(discarding) { folder.absolutePath in discarding }
|
||||
|
||||
internal fun beginDiscard(folder: File) { synchronized(discarding) { discarding.merge(folder.absolutePath, 1, Int::plus) } }
|
||||
|
||||
internal fun endDiscard(folder: File) {
|
||||
synchronized(discarding) {
|
||||
discarding.computeIfPresent(folder.absolutePath) { _, n -> (n - 1).takeIf { it > 0 } }
|
||||
(discarding as Object).notifyAll()
|
||||
}
|
||||
}
|
||||
|
||||
fun awaitDiscard(folder: File) {
|
||||
synchronized(discarding) { while (folder.absolutePath in discarding) (discarding as Object).wait() }
|
||||
}
|
||||
|
||||
private val started = ThreadLocal<MutableList<Thread>?>()
|
||||
|
||||
fun collectingDiscards(into: MutableList<Thread> = ArrayList(), block: () -> Unit): List<Thread> {
|
||||
val previous = started.get()
|
||||
started.set(into)
|
||||
try {
|
||||
block()
|
||||
} finally {
|
||||
started.set(previous)
|
||||
previous?.addAll(into)
|
||||
}
|
||||
return into
|
||||
}
|
||||
|
||||
fun discard(context: Context, folder: File, caches: List<File>) {
|
||||
val app = context.applicationContext
|
||||
beginDiscard(folder)
|
||||
val worker = Thread({
|
||||
try {
|
||||
discardNow(app, folder, caches)
|
||||
} finally {
|
||||
endDiscard(folder)
|
||||
}
|
||||
}, "store-cancel-clean")
|
||||
started.get()?.add(worker)
|
||||
worker.start()
|
||||
}
|
||||
|
||||
@androidx.annotation.VisibleForTesting
|
||||
internal var beforeDiscard: (File) -> Unit = {}
|
||||
|
||||
private fun discardNow(app: Context, folder: File, caches: List<File>) {
|
||||
beforeDiscard(folder)
|
||||
val sidecar = StoreGameSidecar.read(folder)
|
||||
val keep = sidecar?.isInstalled == true || sidecar?.state == StoreGameSidecar.STATE_UPDATING
|
||||
caches.forEach { deleteTree(it) }
|
||||
if (!keep) deleteTree(folder)
|
||||
StoresState.logLine(if (keep) "removed update caches for ${folder.name}; verified file swaps are retained" else "removed ${folder.name}")
|
||||
StoresState.notifyLibraryChanged(app)
|
||||
Thread({
|
||||
val sidecar = StoreGameSidecar.read(folder)
|
||||
val keep = sidecar?.isInstalled == true || sidecar?.state == StoreGameSidecar.STATE_UPDATING
|
||||
caches.forEach { deleteTree(it) }
|
||||
if (!keep) deleteTree(folder)
|
||||
StoresState.logLine(if (keep) "removed update caches for ${folder.name}; verified file swaps are retained" else "removed ${folder.name}")
|
||||
StoresState.notifyLibraryChanged(app)
|
||||
}, "store-cancel-clean").start()
|
||||
}
|
||||
|
||||
fun deleteTree(dir: File) {
|
||||
|
||||
@@ -21,6 +21,10 @@ object StoreLaunch {
|
||||
val needs = sidecar.args.isNotEmpty() || sidecar.env.isNotEmpty() || sidecar.store == Store.EPIC || sidecar.store == Store.EA || sidecar.store == Store.UBISOFT || sidecar.store == Store.ROCKSTAR
|
||||
val file = File(folder, LAUNCHER)
|
||||
if (sidecar.store == Store.ROCKSTAR && java.nio.file.Files.isSymbolicLink(file.toPath())) return sidecar.copy(launcher = null)
|
||||
if (sidecar.store == Store.ROCKSTAR && !com.droiddeck.launcher.stores.rockstar.RockstarLaunch.supports(sidecar.id)) {
|
||||
file.delete()
|
||||
return sidecar.copy(launcher = null)
|
||||
}
|
||||
if (!needs) { file.delete(); return sidecar.copy(launcher = null) }
|
||||
file.writeText(launcherText(sidecar))
|
||||
return sidecar.copy(launcher = LAUNCHER)
|
||||
@@ -32,11 +36,11 @@ object StoreLaunch {
|
||||
?: exe.substringBeforeLast('\\', "")
|
||||
val lines = ArrayList<String>()
|
||||
lines += "@echo off"
|
||||
lines += if (sidecar.store == Store.ROCKSTAR) "setlocal DisableDelayedExpansion" else "setlocal"
|
||||
lines += "setlocal"
|
||||
if (sidecar.store != Store.ROCKSTAR) lines += "rem Written by DroidDeck for ${sidecar.store.label}: ${sidecar.title}. Steam's shortcut runs this file."
|
||||
lines += "cd /d \"%~dp0$dir\""
|
||||
for ((k, v) in sidecar.env) if (ENV_NAME.matches(k)) lines += "set \"$k=${v.replace("\"", "")}\""
|
||||
val args = sidecar.args.joinToString(" ") { if (sidecar.store == Store.ROCKSTAR) batchArg(it) else quoteArg(it) }
|
||||
val args = sidecar.args.joinToString(" ") { quoteArg(it) }
|
||||
val run = "\"%~dp0$exe\"" + (if (args.isNotEmpty()) " $args" else "")
|
||||
if (sidecar.store == Store.EPIC) {
|
||||
lines += "if exist \"%~dp0$EPIC_ARGS\" goto client"
|
||||
@@ -56,11 +60,8 @@ object StoreLaunch {
|
||||
lines += "if exist \"%~dp0$EPIC_CODE\" del \"%~dp0$EPIC_CODE\""
|
||||
lines += "set \"$CLIENT_VAR=\" & \"%~dp0$exe\" %$CLIENT_VAR%"
|
||||
} else if (sidecar.store == Store.ROCKSTAR) {
|
||||
lines += "if not exist \"C:\\Program Files\\Rockstar Games\\Launcher\\launch.json\" goto direct"
|
||||
lines += "\"C:\\Program Files\\Rockstar Games\\Launcher\\Launcher.exe\""
|
||||
lines += "exit /b %errorlevel%"
|
||||
lines += ":direct"
|
||||
lines += run
|
||||
} else if (sidecar.store == Store.UBISOFT) {
|
||||
lines += "if not exist \"%~dp0$UBISOFT_LAUNCH\" goto direct"
|
||||
lines += "if not exist \"$UBISOFT_SERVICE\" goto direct"
|
||||
@@ -84,22 +85,6 @@ object StoreLaunch {
|
||||
|
||||
private val ENV_NAME = Regex("[A-Za-z_][A-Za-z0-9_]*")
|
||||
|
||||
private fun batchArg(arg: String): String {
|
||||
val quoted = StringBuilder("\"")
|
||||
var slashes = 0
|
||||
for (c in arg.filter { it >= ' ' && it != '\u007f' }) {
|
||||
if (c == '\\') { slashes++; continue }
|
||||
quoted.append("\\".repeat(if (c == '"') slashes * 2 + 1 else slashes)).append(c)
|
||||
slashes = 0
|
||||
}
|
||||
quoted.append("\\".repeat(slashes * 2)).append('"')
|
||||
return quoted.toString().map { c -> when (c) {
|
||||
'%' -> "%%"
|
||||
in "^&|<>()\"" -> "^$c"
|
||||
else -> c.toString()
|
||||
} }.joinToString("")
|
||||
}
|
||||
|
||||
fun quoteArg(arg: String): String {
|
||||
val clean = arg.filter { it >= ' ' && it != '\u007f' }
|
||||
return if (' ' in clean && !clean.contains('"')) "\"$clean\"" else clean
|
||||
@@ -118,12 +103,11 @@ object StoreLaunch {
|
||||
|
||||
fun adopt(folder: File, sidecar: StoreGameSidecar): StoreGameSidecar {
|
||||
if (sidecar.store !in listOf(Store.UBISOFT, Store.ROCKSTAR) || !sidecar.isInstalled) return sidecar
|
||||
if (sidecar.store == Store.ROCKSTAR && !com.droiddeck.launcher.stores.rockstar.RockstarLaunch.supports(sidecar.id)) return sidecar
|
||||
if (sidecar.store == Store.ROCKSTAR && java.nio.file.Files.isSymbolicLink(File(folder, LAUNCHER).toPath())) return sidecar.copy(launcher = null)
|
||||
val wrongExe = !sidecar.exeFile(folder).isFile || sidecar.exe.contains("installer", ignoreCase = true) || sidecar.exe.contains("autorun", ignoreCase = true)
|
||||
if (sidecar.store == Store.UBISOFT && sidecar.launcher == LAUNCHER && !wrongExe) return sidecar
|
||||
val metadataExe = if (sidecar.store == Store.ROCKSTAR) com.droiddeck.launcher.stores.rockstar.RockstarMetadata.find(folder)?.exe
|
||||
?.takeIf { File(folder, it).isFile && File(folder, it).canonicalPath.startsWith(folder.canonicalPath + File.separator) } else null
|
||||
val exe = metadataExe ?: if (wrongExe) StoreExe.pick(folder, null, sidecar.title).ifEmpty { sidecar.exe } else sidecar.exe
|
||||
val exe = if (wrongExe) StoreExe.pick(folder, null, sidecar.title).ifEmpty { sidecar.exe } else sidecar.exe
|
||||
if (exe == sidecar.exe && sidecar.launcher == LAUNCHER &&
|
||||
runCatching { File(folder, LAUNCHER).readText() }.getOrNull() == launcherText(sidecar)) return sidecar
|
||||
return runCatching { writeLauncher(folder, sidecar.copy(exe = exe)).also { it.write(folder) } }.getOrDefault(sidecar)
|
||||
|
||||
@@ -114,7 +114,6 @@ object StoreLaunchRequests {
|
||||
if (!(url.startsWith("https://") || url.startsWith("http://"))) JSONObject().put("ok", false).put("reason", "not-http")
|
||||
else try {
|
||||
app.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(url)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
com.droiddeck.launcher.session.SessionService.holdForBrowserHandoff(app)
|
||||
Log.i(TAG, "open-url: " + StoreLog.redactUrl(url))
|
||||
JSONObject().put("ok", true)
|
||||
} catch (e: Exception) {
|
||||
|
||||
@@ -314,37 +314,23 @@ object StoresState {
|
||||
val key = "${game.sidecar.store.id}:${game.sidecar.id}"
|
||||
uninstalling[key] = 0f
|
||||
background("stores-uninstall", onFailure = { main.post { uninstalling.remove(key); onDone() } }) {
|
||||
if (!com.droiddeck.launcher.stores.download.DownloadQueue.holdForRemovalWhenFree(key)) {
|
||||
logLine("kept \"${game.sidecar.title}\": its download or update is still running")
|
||||
runCatching { backends[game.sidecar.store]?.uninstall(app, game) }
|
||||
if (game.sidecar.store == Store.BATTLENET && com.droiddeck.launcher.runtime.BattleNet.games(app).any { it.folder.absolutePath == game.folder.absolutePath }) {
|
||||
main.post { uninstalling.remove(key); onDone() }
|
||||
return@background
|
||||
}
|
||||
try {
|
||||
StoreInstalls.awaitDiscard(game.folder)
|
||||
uninstallHeld(app, game, key, onDone)
|
||||
} finally {
|
||||
com.droiddeck.launcher.stores.download.DownloadQueue.releaseRemoval(key)
|
||||
}
|
||||
StoreInstalls.uninstall(app, game, progress = { f -> main.post { if (key in uninstalling) uninstalling[key] = f } }, removed = {
|
||||
main.post {
|
||||
installed = installed.filterNot { it.folder.absolutePath == game.folder.absolutePath }
|
||||
uninstalling.remove(key)
|
||||
if (game.sidecar.store == Store.ITCH) com.droiddeck.launcher.stores.itch.ItchUpdates.applied(app, key)
|
||||
if (game.sidecar.store == Store.GAMEJOLT) com.droiddeck.launcher.stores.gamejolt.GameJoltUpdates.applied(app, key)
|
||||
}
|
||||
})
|
||||
main.post(onDone)
|
||||
}
|
||||
}
|
||||
|
||||
private fun uninstallHeld(app: Context, game: InstalledStoreGame, key: String, onDone: () -> Unit) {
|
||||
runCatching { backends[game.sidecar.store]?.uninstall(app, game) }
|
||||
if (game.sidecar.store == Store.BATTLENET && com.droiddeck.launcher.runtime.BattleNet.games(app).any { it.folder.absolutePath == game.folder.absolutePath }) {
|
||||
main.post { uninstalling.remove(key); onDone() }
|
||||
return
|
||||
}
|
||||
StoreInstalls.uninstall(app, game, progress = { f -> main.post { if (key in uninstalling) uninstalling[key] = f } }, removed = {
|
||||
main.post {
|
||||
installed = installed.filterNot { it.folder.absolutePath == game.folder.absolutePath }
|
||||
uninstalling.remove(key)
|
||||
if (game.sidecar.store == Store.ITCH) com.droiddeck.launcher.stores.itch.ItchUpdates.applied(app, key)
|
||||
if (game.sidecar.store == Store.GAMEJOLT) com.droiddeck.launcher.stores.gamejolt.GameJoltUpdates.applied(app, key)
|
||||
}
|
||||
})
|
||||
main.post(onDone)
|
||||
}
|
||||
|
||||
@Volatile var libraryListener: (() -> Unit)? = null
|
||||
|
||||
fun notifyLibraryChanged(context: Context) {
|
||||
|
||||
@@ -111,22 +111,16 @@ object BattleNetInstall {
|
||||
fun update(context: Context, game: InstalledStoreGame) {
|
||||
val app = context.applicationContext
|
||||
Thread({
|
||||
val item = updateItem(game, installUid(app, game))
|
||||
val item = CatalogItem(
|
||||
Store.BATTLENET, game.sidecar.id, game.sidecar.title, game.sidecar.hero, tallImageUrl = game.sidecar.cover, owned = true,
|
||||
extra = mapOf(INSTALL_UID to installUid(app, game)),
|
||||
)
|
||||
game.folder.parentFile?.parentFile?.let { com.droiddeck.launcher.stores.download.SavedQueue.remember(app, item, it) }
|
||||
enqueue(app, item, game.folder, update = true)
|
||||
}, "battlenet-update").start()
|
||||
}
|
||||
|
||||
internal fun updateItem(game: InstalledStoreGame, uid: String) = CatalogItem(
|
||||
Store.BATTLENET, game.sidecar.id, game.sidecar.title, game.sidecar.hero, tallImageUrl = game.sidecar.cover, owned = true,
|
||||
extra = mapOf(INSTALL_UID to uid, UPDATE_FOLDER to game.folder.absolutePath),
|
||||
)
|
||||
|
||||
internal fun updateFolder(item: CatalogItem): File? = item.extra[UPDATE_FOLDER]?.let(::File)
|
||||
|
||||
internal const val INSTALL_UID = "installUid"
|
||||
internal const val UPDATE_FOLDER = "updateFolder"
|
||||
internal const val STALLED = "stalled"
|
||||
|
||||
internal fun installUid(context: Context, game: InstalledStoreGame): String =
|
||||
runCatching { BattleNet.games(context).firstOrNull { it.uid == game.sidecar.id }?.installUid }.getOrNull() ?: game.sidecar.id
|
||||
@@ -225,7 +219,6 @@ object BattleNetInstall {
|
||||
val detail = when {
|
||||
reason == null -> "exit $code"
|
||||
reason == "client" -> return context.getString(R.string.bnet_dl_client_first)
|
||||
reason == STALLED -> return context.getString(R.string.bnet_dl_stalled)
|
||||
reason.startsWith("agent ") -> context.getString(R.string.bnet_dl_agent_error, reason.removePrefix("agent "))
|
||||
else -> reason.removePrefix("stopped ")
|
||||
}
|
||||
|
||||
@@ -192,7 +192,6 @@ object BattleNetBackend : StoreBackend {
|
||||
override fun install(context: Context, item: CatalogItem, root: File) {
|
||||
if (!BattleNetInstall.headless(item)) return BattleNetClient.installGame(context, item.id, root)
|
||||
val app = context.applicationContext
|
||||
BattleNetInstall.updateFolder(item)?.let { return BattleNetInstall.enqueue(app, item, it, update = true) }
|
||||
BattleNetInstall.enqueue(app, item, StoreInstallRoot.folderFor(app, store, item.id, item.title, root))
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.stores.download
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.stores.StoreInstalls
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
@@ -103,55 +102,6 @@ object DownloadQueue {
|
||||
private val lock = Any()
|
||||
private val items = LinkedHashMap<String, Item>()
|
||||
private val heldPaused = HashSet<String>()
|
||||
private val removing = HashSet<String>()
|
||||
private val cleaningUp = HashMap<String, Int>()
|
||||
|
||||
fun holdForRemoval(key: String): Boolean = synchronized(lock) {
|
||||
val item = items[key]
|
||||
if (item?.entry?.isActive == true || item?.job != null || key in cleaningUp || key in removing) return@synchronized false
|
||||
removing.add(key)
|
||||
true
|
||||
}
|
||||
|
||||
fun releaseRemoval(key: String) { synchronized(lock) { removing.remove(key); (lock as Object).notifyAll() } }
|
||||
|
||||
fun holdForRemovalWhenFree(key: String): Boolean = synchronized(lock) {
|
||||
while (true) {
|
||||
val item = items[key]
|
||||
if (item?.entry?.isActive == true || item?.job != null) return@synchronized false
|
||||
if (key !in cleaningUp && key !in removing) break
|
||||
(lock as Object).wait()
|
||||
}
|
||||
removing.add(key)
|
||||
true
|
||||
}
|
||||
|
||||
private fun beginCleanup(key: String): Boolean = synchronized(lock) {
|
||||
if (key in removing) return@synchronized false
|
||||
cleaningUp.merge(key, 1, Int::plus)
|
||||
true
|
||||
}
|
||||
|
||||
private fun holdCleanup(key: String) { synchronized(lock) { cleaningUp.merge(key, 1, Int::plus) } }
|
||||
|
||||
private fun endCleanup(key: String) {
|
||||
synchronized(lock) {
|
||||
cleaningUp.computeIfPresent(key) { _, n -> (n - 1).takeIf { it > 0 } }
|
||||
(lock as Object).notifyAll()
|
||||
}
|
||||
}
|
||||
|
||||
private fun cleanUpLater(context: Context, key: String, name: String, work: () -> Unit) {
|
||||
Thread({
|
||||
try {
|
||||
val deleting = ArrayList<Thread>()
|
||||
try { StoreInstalls.collectingDiscards(deleting, work) } finally { deleting.forEach { it.join() } }
|
||||
} finally {
|
||||
endCleanup(key)
|
||||
advance(context)
|
||||
}
|
||||
}, name).start()
|
||||
}
|
||||
|
||||
fun holdPaused(key: String) = synchronized(lock) { heldPaused.add(key) }
|
||||
private var running = 0
|
||||
@@ -181,7 +131,6 @@ object DownloadQueue {
|
||||
fun enqueue(context: Context, entry: DownloadEntry, factory: () -> DownloadJob) {
|
||||
val app = context.applicationContext
|
||||
synchronized(lock) {
|
||||
if (entry.key in removing) { Log.i(TAG, "${entry.key}: being uninstalled"); return }
|
||||
items[entry.key]?.let { if (it.entry.isActive) { Log.i(TAG, "${entry.key}: already queued"); return } }
|
||||
items.remove(entry.key)
|
||||
val state = if (heldPaused.remove(entry.key)) DownloadState.PAUSED else DownloadState.QUEUED
|
||||
@@ -236,7 +185,6 @@ object DownloadQueue {
|
||||
val retry: (() -> Unit)?
|
||||
synchronized(lock) {
|
||||
val item = items[key] ?: return
|
||||
if (key in removing) return
|
||||
if (item.entry.state != DownloadState.PAUSED && item.entry.state != DownloadState.FAILED) return
|
||||
retry = item.retry
|
||||
if (retry == null && item.factory == null) return
|
||||
@@ -258,28 +206,23 @@ object DownloadQueue {
|
||||
val app = context.applicationContext
|
||||
val item: Item
|
||||
val wasRunning: Boolean
|
||||
var cleanup = false
|
||||
var awaitDeletion: List<Thread> = emptyList()
|
||||
synchronized(lock) {
|
||||
item = items[key] ?: return
|
||||
if (!item.entry.interruptible) return
|
||||
wasRunning = item.entry.state == DownloadState.RUNNING
|
||||
if (wasRunning) {
|
||||
item.cancelled.set(true)
|
||||
val deleting = StoreInstalls.collectingDiscards { runCatching { item.job?.cancel(deleteFiles = true) } }
|
||||
if (deleting.isNotEmpty()) { holdCleanup(key); awaitDeletion = deleting }
|
||||
item.job?.cancel(deleteFiles = true)
|
||||
}
|
||||
if (!wasRunning) {
|
||||
cleanup = beginCleanup(key)
|
||||
item.entry = item.entry.copy(state = DownloadState.CANCELLED, queuePosition = 0, finishedAt = System.currentTimeMillis())
|
||||
renumber()
|
||||
publishLocked()
|
||||
}
|
||||
}
|
||||
if (cleanup) {
|
||||
cleanUpLater(app, key, "store-dl-cancel") { runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) } }
|
||||
if (!wasRunning) {
|
||||
Thread({ runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) } }, "store-dl-cancel").start()
|
||||
}
|
||||
if (awaitDeletion.isNotEmpty()) cleanUpLater(app, key, "store-dl-cancel-wait") { awaitDeletion.forEach { it.join() } }
|
||||
StoresState.logLine("cancelled \"${item.entry.name}\"")
|
||||
StoreDownloadService.finish(app, key)
|
||||
advance(app)
|
||||
@@ -287,16 +230,12 @@ object DownloadQueue {
|
||||
}
|
||||
|
||||
fun clear(context: Context, key: String) {
|
||||
val item: Item
|
||||
val cleanup: Boolean
|
||||
synchronized(lock) {
|
||||
item = items[key] ?: return
|
||||
if (item.entry.state == DownloadState.RUNNING || item.entry.state == DownloadState.QUEUED) return
|
||||
cleanup = (item.entry.state == DownloadState.FAILED || item.entry.state == DownloadState.PAUSED) && beginCleanup(key)
|
||||
items.remove(key)
|
||||
publishLocked()
|
||||
val item = synchronized(lock) { items[key] } ?: return
|
||||
if (item.entry.state == DownloadState.RUNNING || item.entry.state == DownloadState.QUEUED) return
|
||||
if (item.entry.state == DownloadState.FAILED || item.entry.state == DownloadState.PAUSED) {
|
||||
Thread({ runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) } }, "store-dl-clear").start()
|
||||
}
|
||||
if (cleanup) cleanUpLater(context.applicationContext, key, "store-dl-clear") { runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) } }
|
||||
synchronized(lock) { items.remove(key); publishLocked() }
|
||||
StoreDownloadService.finish(context.applicationContext, key)
|
||||
}
|
||||
|
||||
@@ -359,7 +298,7 @@ object DownloadQueue {
|
||||
val next: Item
|
||||
synchronized(lock) {
|
||||
if (running >= parallel(context)) return
|
||||
next = items.values.firstOrNull { it.entry.state == DownloadState.QUEUED && it.entry.key !in cleaningUp } ?: return
|
||||
next = items.values.firstOrNull { it.entry.state == DownloadState.QUEUED } ?: return
|
||||
running++
|
||||
next.entry = next.entry.copy(state = DownloadState.RUNNING, stage = DownloadStage.MANIFEST, queuePosition = 0)
|
||||
renumber()
|
||||
@@ -379,15 +318,7 @@ object DownloadQueue {
|
||||
val job = checkNotNull(item.factory).invoke()
|
||||
synchronized(lock) { item.job = job }
|
||||
StoresState.logLine("${item.entry.store.label}: fetching manifest for \"${item.entry.name}\"")
|
||||
val deleting = ArrayList<Thread>()
|
||||
try {
|
||||
StoreInstalls.collectingDiscards(deleting) { result = job.run(handle) }
|
||||
} finally {
|
||||
if (deleting.isNotEmpty()) {
|
||||
holdCleanup(item.entry.key)
|
||||
cleanUpLater(context, item.entry.key, "store-dl-run-discard") { deleting.forEach { it.join() } }
|
||||
}
|
||||
}
|
||||
result = job.run(handle)
|
||||
if (result == null && !item.cancelled.get()) error = "install failed"
|
||||
} catch (t: Throwable) {
|
||||
error = t.message ?: t.javaClass.simpleName
|
||||
|
||||
@@ -21,61 +21,19 @@ import java.security.MessageDigest
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
internal object EpicClientSources {
|
||||
const val LAUNCHER_URL = "https://launcher-public-service-prod06.ol.epicgames.com/launcher/api/installer/download/EpicGamesLauncher-x86_64.deb"
|
||||
const val LAUNCHER_FILE = "EpicGamesLauncher-x86_64.deb"
|
||||
const val LAUNCHER_URL = "https://launcher-public-service-prod06.ol.epicgames.com/launcher/api/installer/download/EpicGamesLauncher-x86_64.AppImage"
|
||||
const val LAUNCHER_FILE = "EpicGamesLauncher-x86_64.AppImage"
|
||||
const val RUNTIME_BASE = "https://repo.steampowered.com/steamrt4/images/"
|
||||
const val RUNTIME_FILE = "com.valvesoftware.SteamRuntime.Platform-amd64,i386-steamrt4-runtime.tar.gz"
|
||||
const val GLES_URL = "https://deb.debian.org/debian/pool/main/libg/libglvnd/libgles2_1.7.0-1+b2_amd64.deb"
|
||||
const val GLES_FILE = "libgles2_1.7.0-1+b2_amd64.deb"
|
||||
const val GLES_SHA256 = "e12c18aa77939d122ee1dea520ba0440b97dc19200b7396e03dff03a3ece74c1"
|
||||
const val DEBIAN = "https://deb.debian.org/debian/"
|
||||
const val SNAPSHOT = "https://snapshot.debian.org/archive/debian/20261101T000000Z/"
|
||||
const val USER_AGENT = "DroidDeck"
|
||||
private val VERSION = Regex("[A-Za-z0-9._+-]{1,64}")
|
||||
private val SUM = Regex("^([0-9a-fA-F]{64})\\s+\\*?(.+)$")
|
||||
|
||||
class Source(val url: String, val version: String, val sha256: String? = null)
|
||||
|
||||
class Package(val path: String, val sha256: String, val size: Long) {
|
||||
val file: String get() = path.substringAfterLast('/')
|
||||
val urls: List<String> get() = listOf(DEBIAN + path, SNAPSHOT + path)
|
||||
}
|
||||
|
||||
val DESKTOP = listOf(
|
||||
Package("pool/main/a/abseil/libabsl20240722_20240722.0-4_amd64.deb", "78c6d7692890990a27cb1d5bbd95b7bfe47a4183ffafec5b30f689f9b58ec6f7", 491548L),
|
||||
Package("pool/main/a/aom/libaom3_3.12.1-1+deb13u1_amd64.deb", "743eec7c94ae30295bc557ebac3dfae948e7390e89a2743c585d56297e9d312e", 1871712L),
|
||||
Package("pool/main/a/aspell/libaspell15_0.60.8.1-4_amd64.deb", "8be22785198a4e5de1e2c3a157e8cd99ec7d5843c8ac96a174ec701ba4ac28e2", 337684L),
|
||||
Package("pool/main/a/at-spi2-core/libatk-bridge2.0-0t64_2.56.2-1+deb13u2_amd64.deb", "c0fe87ea1bdca2f938eaa8286af5ad38ecd15cf18c6cfb5961d7d46ac3192325", 68516L),
|
||||
Package("pool/main/a/at-spi2-core/libatspi2.0-0t64_2.56.2-1+deb13u2_amd64.deb", "65e9c9ecbd820fba2d04104cddd0bad33d256cbdfe0d1cb5365f10e363df2315", 81056L),
|
||||
Package("pool/main/liba/libavif/libavif16_1.2.1-1.2_amd64.deb", "ba6c334454d3562560ad583fbe2c998e203b0fc5a0e0e91112ddcd3cff4704bb", 133120L),
|
||||
Package("pool/main/libc/libcloudproviders/libcloudproviders0_0.3.6-2_amd64.deb", "a626bb23ed9ebc4bc3ce446b552048de63d76768bf0fb492754965c5ee28a7e4", 29232L),
|
||||
Package("pool/main/c/colord/libcolord2_1.4.7-3_amd64.deb", "f11fd3b492781122edf0790f1e1fe24c51a41c67d4bb76cff84a9426c5654fa7", 139204L),
|
||||
Package("pool/main/e/enchant-2/libenchant-2-2_2.8.2+dfsg1-3_amd64.deb", "83f208d89db1c48e6ede8a23e8ffa2bcddd4f99427bfd1279201247bbf27ca58", 56756L),
|
||||
Package("pool/main/libe/libepoxy/libepoxy0_1.5.10-2_amd64.deb", "4c4c8024f2175086de65bca9fdc3fbb967f2863ebf249d489c66d0c8103dd3a3", 192728L),
|
||||
Package("pool/main/libe/libevdev/libevdev2_1.13.4+dfsg-1_amd64.deb", "02e85fb9461b85b23f775d5fcf5a31c55d37bec40b63fd98ca5d3a2763714ae7", 32372L),
|
||||
Package("pool/main/f/flite/libflite1_2.2-7_amd64.deb", "5945190970be7d4a1f71fb6f7e3e340ba2675e770605df0754051d617a6c5ee6", 12811404L),
|
||||
Package("pool/main/libg/libgav1/libgav1-1_0.19.0-3+b1_amd64.deb", "94010041e59c7a8d2d3d1f5e62afd523f002b7b1caa3189419160b66d71c0195", 352956L),
|
||||
Package("pool/main/g/gst-plugins-base1.0/libgstreamer-gl1.0-0_1.26.2-1+deb13u1_amd64.deb", "efacc61acbd44a6a067612e4592b9fe81efdc5011ed4c6cf7afd8ed83c5f834a", 269984L),
|
||||
Package("pool/main/g/gst-plugins-base1.0/libgstreamer-plugins-base1.0-0_1.26.2-1+deb13u1_amd64.deb", "a20aedb3f89c162b4859cec37076f4eba54b0bcc7e5cb254a26cc4a877a88a1e", 997404L),
|
||||
Package("pool/main/g/gstreamer1.0/libgstreamer1.0-0_1.26.2-2_amd64.deb", "08b463307fbde5496a346b1bb300b465cd22bd326f6f4634f482bf441af28a9b", 1421116L),
|
||||
Package("pool/main/g/gtk+3.0/libgtk-3-0t64_3.24.49-3_amd64.deb", "4aa8828f01365f937f3bf69f812c8107ee4c8a2b208ffdd7656e8de5de81d98f", 2768812L),
|
||||
Package("pool/main/h/hidapi/libhidapi-hidraw0_0.14.0-1+b2_amd64.deb", "89c546cb55be403ce63fe668baff2515979100a30fa07e2b97de186b9c07f01e", 12664L),
|
||||
Package("pool/main/h/hunspell/libhunspell-1.7-0_1.7.2+really1.7.2-10+b4_amd64.deb", "a9427e5220e71f8c04c6c0f87826c6fef98e2bab6994a87d6d82e8a120790ecf", 236980L),
|
||||
Package("pool/main/h/highway/libhwy1t64_1.2.0-2+b2_amd64.deb", "540c4ff28255fbfa89468061b722dfc2b773b0c1ecf163a063202482dea5b119", 676044L),
|
||||
Package("pool/main/h/hyphen/libhyphen0_2.8.8-7+b2_amd64.deb", "fa9dca7b8cf1381fd52800c44a385c5725a78a88bd705f7c39b1046a5293435e", 30664L),
|
||||
Package("pool/main/w/webkit2gtk/libjavascriptcoregtk-4.1-0_2.52.6-1~deb13u1_amd64.deb", "3383ebb3e13f31225c65f41112420be58493a3de112b5993cf5c417cfedc47c8", 7511632L),
|
||||
Package("pool/main/j/jpeg-xl/libjxl0.11_0.11.2-0.1~deb13u2_amd64.deb", "cd1ca3a52cb0d8fdce1d994bcbf0663de28c64add1cfe8096639ae8fa9808824", 1133312L),
|
||||
Package("pool/main/l/lcms2/liblcms2-2_2.16-2+deb13u2_amd64.deb", "32e53c2002ccea8c60c02779bea0ba49ac132fef702988a30d64af79b6617806", 160264L),
|
||||
Package("pool/main/libm/libmanette/libmanette-0.2-0_0.2.12-1_amd64.deb", "98841a467692c46fd1870275113235691ebbfe71a3524f6b2a0fa7e9c33c6e56", 43752L),
|
||||
Package("pool/main/o/orc/liborc-0.4-0t64_0.4.41-1_amd64.deb", "5b9afe78be0dd71399c0d4d7e5f26beb6ddf207279997942d8280be1b20bd58c", 189604L),
|
||||
Package("pool/main/r/rust-rav1e/librav1e0.7_0.7.1-9+b2_amd64.deb", "d5b1373a8d6905ee4523faf1db7a626dc660e03836ec91b616e57ba386f47eb6", 946396L),
|
||||
Package("pool/main/libs/libsecret/libsecret-1-0_0.21.7-1_amd64.deb", "949c5428cd3427486ac6c4dfc6d9400ce786c504c02334acc903c873aa52d14f", 111224L),
|
||||
Package("pool/main/s/svt-av1/libsvtav1enc2_2.3.0+dfsg-1_amd64.deb", "cdaf961c3cc4fe78a19ff18c17d83d813f78a378fdcc4c86ccbb9b54e84ae599", 2489492L),
|
||||
Package("pool/main/w/webkit2gtk/libwebkit2gtk-4.1-0_2.52.6-1~deb13u1_amd64.deb", "6471d989a61a56a7801e88e420789aa6b0eaba630a9787365bba8b9576b7ba1c", 24163372L),
|
||||
Package("pool/main/libx/libxslt/libxslt1.1_1.1.35-1.2+deb13u3_amd64.deb", "c8e5a745ca3afaa079b01e0c00d80a241101d1ab840407fcd4bb423de3326160", 233128L),
|
||||
Package("pool/main/liby/libyuv/libyuv0_0.0.1904.20250204-1_amd64.deb", "1a6827fe94fa5572a032332df7313ed408e9c0ad78f3a1248391bddc6d920ef2", 173700L),
|
||||
)
|
||||
|
||||
fun launcher(): Source? {
|
||||
val location = redirect(LAUNCHER_URL) ?: return null
|
||||
val version = launcherVersion(location) ?: return null
|
||||
@@ -184,13 +142,12 @@ internal object EpicClientSources {
|
||||
|
||||
private fun hex(bytes: ByteArray): String = bytes.joinToString("") { "%02x".format(it) }
|
||||
|
||||
private val DEB_MAGIC = "!<arch>\ndebian-binary".toByteArray(Charsets.US_ASCII)
|
||||
|
||||
fun isDeb(file: File): Boolean = runCatching {
|
||||
fun isAppImage(file: File): Boolean = runCatching {
|
||||
RandomAccessFile(file, "r").use { raf ->
|
||||
val head = ByteArray(DEB_MAGIC.size)
|
||||
val head = ByteArray(11)
|
||||
raf.readFully(head)
|
||||
head.contentEquals(DEB_MAGIC)
|
||||
head[0] == 0x7f.toByte() && head[1] == 'E'.code.toByte() && head[2] == 'L'.code.toByte() && head[3] == 'F'.code.toByte() &&
|
||||
head[8] == 'A'.code.toByte() && head[9] == 'I'.code.toByte() && head[10] == 2.toByte()
|
||||
}
|
||||
}.getOrDefault(false)
|
||||
}
|
||||
@@ -199,10 +156,9 @@ internal class EpicClientInstaller(private val app: Context) : DownloadQueue.Dow
|
||||
private val cancelled = AtomicBoolean(false)
|
||||
@Volatile private var connection: HttpURLConnection? = null
|
||||
|
||||
private class Part(val urls: List<String>, val file: File, val sha256: String?, val launcher: Boolean, var size: Long = -1L) {
|
||||
var mirror = 0
|
||||
private class Part(val url: String, val file: File, val sha256: String?, val appImage: Boolean) {
|
||||
var size = -1L
|
||||
var mismatch: String? = null
|
||||
val url: String get() = urls[mirror]
|
||||
}
|
||||
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||
@@ -217,15 +173,17 @@ internal class EpicClientInstaller(private val app: Context) : DownloadQueue.Dow
|
||||
val needRuntime = !(before.runtimeVersion == runtime.version && File(state, "runtime/${runtime.version}/.droiddeck-ready").isFile)
|
||||
val dir = EpicClient.downloadsDir(app).apply { mkdirs() }
|
||||
val gles = EpicClientSources.gles()
|
||||
val appPart = if (needApp) Part(listOf(launcher.url), File(dir, "${launcher.version}-${EpicClientSources.LAUNCHER_FILE}"), null, true) else null
|
||||
val desktopParts = if (needApp) EpicClientSources.DESKTOP.map { Part(it.urls, File(dir, it.file), it.sha256, false, it.size) } else emptyList()
|
||||
val runtimePart = if (needRuntime) Part(listOf(runtime.url), File(dir, "steamrt4-${runtime.version}.tar.gz"), runtime.sha256, false) else null
|
||||
val glesPart = if (needRuntime) Part(listOf(gles.url), File(dir, EpicClientSources.GLES_FILE), gles.sha256, false) else null
|
||||
val parts = listOfNotNull(appPart) + desktopParts + listOfNotNull(runtimePart, glesPart)
|
||||
val parts = buildList {
|
||||
if (needApp) add(Part(launcher.url, File(dir, "${launcher.version}-${EpicClientSources.LAUNCHER_FILE}"), null, true))
|
||||
if (needRuntime) {
|
||||
add(Part(runtime.url, File(dir, "steamrt4-${runtime.version}.tar.gz"), runtime.sha256, false))
|
||||
add(Part(gles.url, File(dir, EpicClientSources.GLES_FILE), gles.sha256, false))
|
||||
}
|
||||
}
|
||||
val keep = parts.flatMap { listOf(it.file.name, it.file.name + PARTIAL, it.file.name + TAG) }.toSet()
|
||||
dir.listFiles()?.forEach { if (it.name !in keep) it.deleteRecursively() }
|
||||
if (parts.isNotEmpty()) {
|
||||
parts.forEach { if (it.size <= 0) it.size = length(it.url) }
|
||||
parts.forEach { it.size = length(it.url) }
|
||||
val total = parts.sumOf { it.size.coerceAtLeast(0L) }
|
||||
val have = parts.sumOf { p -> if (p.file.isFile) p.file.length() else File(p.file.path + PARTIAL).length() }
|
||||
val needed = (total - have).coerceAtLeast(0L) + (if (needApp) APP_ROOM else 0L) + (if (needRuntime) RUNTIME_ROOM else 0L)
|
||||
@@ -244,9 +202,8 @@ internal class EpicClientInstaller(private val app: Context) : DownloadQueue.Dow
|
||||
handle.stage(DownloadStage.INSTALL, app.getString(R.string.epic_client_unpacking))
|
||||
val argv = mutableListOf(EpicClient.PROGRAM, "install", "--app-version", launcher.version, "--runtime-version", runtime.version)
|
||||
fun guest(file: File) = EpicClient.guestPath(app, file) ?: throw IllegalStateException(app.getString(R.string.epic_client_unpack_failed, file.name))
|
||||
appPart?.let { argv += listOf("--app", guest(it.file)) }
|
||||
desktopParts.forEach { argv += listOf("--desktop", guest(it.file)) }
|
||||
if (runtimePart != null && glesPart != null) argv += listOf("--runtime", guest(runtimePart.file), "--gles", guest(glesPart.file))
|
||||
if (needApp) argv += listOf("--app", guest(parts[0].file))
|
||||
if (needRuntime) argv += listOf("--runtime", guest(parts[parts.size - 2].file), "--gles", guest(parts[parts.size - 1].file))
|
||||
var answer: JSONObject? = null
|
||||
val code = GuestCommand.run(app, argv, fakeRoot = true, logName = "epic-client") { line ->
|
||||
if (line.startsWith("{")) runCatching { JSONObject(line) }.getOrNull()?.let { answer = it }
|
||||
@@ -341,10 +298,6 @@ internal class EpicClientInstaller(private val app: Context) : DownloadQueue.Dow
|
||||
}
|
||||
200 -> false
|
||||
416 -> { partial.delete(); tag.delete(); throw IOException("HTTP 416") }
|
||||
404, 410 -> {
|
||||
if (part.mirror + 1 < part.urls.size) { part.mirror++; tag.delete() }
|
||||
throw IOException("HTTP $code")
|
||||
}
|
||||
else -> throw IOException("HTTP $code")
|
||||
}
|
||||
val served = conn.getHeaderField("ETag")?.takeIf { it.isNotBlank() }
|
||||
@@ -381,8 +334,8 @@ internal class EpicClientInstaller(private val app: Context) : DownloadQueue.Dow
|
||||
part.sha256?.let { want ->
|
||||
if (EpicClientSources.sha256(file) != want) { file.delete(); throw IOException("checksum mismatch") }
|
||||
}
|
||||
if (part.launcher) {
|
||||
if (!EpicClientSources.isDeb(file)) { file.delete(); throw IOException("not a Debian package") }
|
||||
if (part.appImage) {
|
||||
if (!EpicClientSources.isAppImage(file)) { file.delete(); throw IOException("not an AppImage") }
|
||||
if (EpicClientSources.etagMatches(file, etag) == false) {
|
||||
val seen = EpicClientSources.sha256(file)
|
||||
if (part.mismatch != seen) {
|
||||
@@ -398,7 +351,7 @@ internal class EpicClientInstaller(private val app: Context) : DownloadQueue.Dow
|
||||
const val PARTIAL = ".part"
|
||||
const val TAG = ".etag"
|
||||
const val ATTEMPTS = 6
|
||||
const val APP_ROOM = 700L shl 20
|
||||
const val APP_ROOM = 600L shl 20
|
||||
const val RUNTIME_ROOM = 560L shl 20
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,7 @@ object RockstarAuth {
|
||||
private const val TICKET_MARGIN_MS = 15 * 60 * 1000L
|
||||
private val lock = Any()
|
||||
|
||||
class Ticket(val ticket: String, val sessionKey: String, val sessionTicket: String, val rockstarId: String, val nickname: String, val expiresAt: Long, val email: String = "", val sdkTicket: String = "")
|
||||
class Ticket(val ticket: String, val sessionKey: String, val sessionTicket: String, val rockstarId: String, val nickname: String, val expiresAt: Long)
|
||||
|
||||
internal fun fingerprint(context: Context): JSONObject {
|
||||
val p = context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
@@ -159,7 +159,7 @@ object RockstarAuth {
|
||||
|
||||
private fun stored(o: JSONObject): Ticket? {
|
||||
val t = o.optString("ticket").takeIf { it.isNotEmpty() } ?: return null
|
||||
return Ticket(t, o.optString("session_key"), o.optString("session_ticket"), o.optString("rockstar_id"), o.optString("display_name"), o.optLong("ticket_expires_at"), o.optString("email"), o.optString("sdk_ticket").takeIf { o.optInt("sdk_ticket_version") == 1 }.orEmpty())
|
||||
return Ticket(t, o.optString("session_key"), o.optString("session_ticket"), o.optString("rockstar_id"), o.optString("display_name"), o.optLong("ticket_expires_at"))
|
||||
}
|
||||
|
||||
private fun mint(context: Context): Ticket {
|
||||
@@ -176,7 +176,7 @@ object RockstarAuth {
|
||||
}
|
||||
val t = parseTicket(root) ?: throw IllegalStateException("no ticket in the answer")
|
||||
o.put("ticket", t.ticket).put("session_key", t.sessionKey).put("session_ticket", t.sessionTicket)
|
||||
.put("rockstar_id", t.rockstarId).put("ticket_expires_at", t.expiresAt).put("email", t.email).put("sdk_ticket", t.sdkTicket).put("sdk_ticket_version", 1)
|
||||
.put("rockstar_id", t.rockstarId).put("ticket_expires_at", t.expiresAt)
|
||||
if (t.nickname.isNotEmpty()) o.put("display_name", t.nickname)
|
||||
StoreAccounts.write(app, Store.ROCKSTAR, o)
|
||||
return t
|
||||
@@ -191,49 +191,8 @@ object RockstarAuth {
|
||||
(account?.let { RockstarRos.text(it, "RockstarId") } ?: RockstarRos.text(root, "RockstarId")).orEmpty(),
|
||||
account?.let { RockstarRos.text(it, "Nickname") }.orEmpty(),
|
||||
now + secs * 1000L,
|
||||
account?.let { RockstarRos.text(it, "Email") }.orEmpty(),
|
||||
sdkTicket(root),
|
||||
)
|
||||
}
|
||||
|
||||
internal fun sdkTicket(root: org.w3c.dom.Element): String {
|
||||
val document = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument()
|
||||
val response = document.createElement("Response").also { document.appendChild(it) }
|
||||
val fields = setOf("Status", "Ticket", "SessionKey", "SessionTicket", "SecsUntilExpiration", "PlayerAccountId", "PlayerAccountRuid",
|
||||
"Region", "Privileges", "Privs", "Services", "SslServices", "Hosts", "DisabledSecurityFlags", "SessionId", "CloudKey", "PublicIp", "PosixTime", "IsSubAccount")
|
||||
val blocked = setOf("scauthtoken", "accesstoken", "refreshtoken", "rememberedmachinetoken", "loginguid", "password")
|
||||
fun copy(source: org.w3c.dom.Element): org.w3c.dom.Element {
|
||||
val target = document.createElement(source.tagName)
|
||||
for (i in 0 until source.attributes.length) {
|
||||
val attribute = source.attributes.item(i)
|
||||
if (attribute.nodeName.lowercase() !in blocked) target.setAttribute(attribute.nodeName, attribute.nodeValue)
|
||||
}
|
||||
var child = source.firstChild
|
||||
while (child != null) {
|
||||
if (child is org.w3c.dom.Element) {
|
||||
if (child.tagName.lowercase() !in blocked) target.appendChild(copy(child))
|
||||
} else if (child.nodeType == org.w3c.dom.Node.TEXT_NODE || child.nodeType == org.w3c.dom.Node.CDATA_SECTION_NODE) {
|
||||
target.appendChild(document.createTextNode(child.nodeValue))
|
||||
}
|
||||
child = child.nextSibling
|
||||
}
|
||||
return target
|
||||
}
|
||||
for (field in fields) RockstarRos.first(root, field)?.let { response.appendChild(copy(it)) }
|
||||
RockstarRos.first(root, "RockstarAccount")?.let { account ->
|
||||
val target = document.createElement("RockstarAccount")
|
||||
for (field in setOf("RockstarId", "Nickname", "Email", "Age", "CountryCode", "LanguageCode", "AvatarUrl", "ZipCode", "Ruid")) {
|
||||
RockstarRos.first(account, field)?.let { target.appendChild(copy(it)) }
|
||||
}
|
||||
response.appendChild(target)
|
||||
}
|
||||
val output = java.io.StringWriter()
|
||||
javax.xml.transform.TransformerFactory.newInstance().newTransformer().apply {
|
||||
setOutputProperty(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes")
|
||||
transform(javax.xml.transform.dom.DOMSource(document), javax.xml.transform.stream.StreamResult(output))
|
||||
}
|
||||
return output.toString()
|
||||
}
|
||||
|
||||
fun signOut(context: Context) = synchronized(lock) { StoreAccounts.clear(context.applicationContext, Store.ROCKSTAR) }
|
||||
}
|
||||
@@ -147,9 +147,6 @@ object RockstarLibrary {
|
||||
internal fun owned(account: RockstarAccountApps): List<RockstarTitle> =
|
||||
account.packages.filter { !it.featured }.flatMap { RockstarTitles.forName(it.title) }.distinct()
|
||||
|
||||
internal fun owns(account: RockstarAccountApps, rosId: Int, id: String): Boolean =
|
||||
owned(account).any { it.rosTitleId == rosId } || account.packages.any { !it.featured && it.title == id }
|
||||
|
||||
internal fun games(account: RockstarAccountApps): List<CatalogItem> = owned(account).mapNotNull { t ->
|
||||
RockstarApps.deliverer(account.apps, t)?.let { RockstarTitles.item(t, owned = true, extra = mapOf("app" to it.name, "appId" to it.id)) }
|
||||
}.sortedBy { it.title.lowercase() }
|
||||
|
||||
@@ -10,9 +10,9 @@ import java.security.MessageDigest
|
||||
import java.util.Base64
|
||||
|
||||
object RockstarLaunch {
|
||||
internal val pipes = mapOf("gta3" to "GTA3_Pipe", "gtavc" to "GTA-VC_Pipe", "gtasa" to "GTA_SA_Pipe", "gta4" to "GTAIV_Pipe", "lanoire" to "LANOIRE_Pipe")
|
||||
internal val pipes = mapOf("gta3" to "GTA3_Pipe", "gtavc" to "GTA-VC_Pipe", "gtasa" to "GTA_SA_Pipe")
|
||||
|
||||
fun usesClassicLauncher(id: String) = id in pipes
|
||||
fun supports(id: String?) = id != null && id in pipes
|
||||
|
||||
fun applyDefaults(app: Context, id: String, appId: Long) {
|
||||
val scope = (appId and 0xffffffffL).toString()
|
||||
@@ -23,22 +23,16 @@ object RockstarLaunch {
|
||||
}
|
||||
|
||||
fun prepare(app: Context, id: String): JSONObject {
|
||||
val pipe = pipes[id] ?: return failure("unsupported-title")
|
||||
val title = RockstarTitles.byId(id) ?: return failure("unknown-title")
|
||||
val folder = StoreInstallRoot.gameFolders(app).firstOrNull { folder ->
|
||||
StoreGameSidecar.read(folder)?.let { it.store == Store.ROCKSTAR && it.id == id && it.isInstalled } == true
|
||||
} ?: return failure("not-installed")
|
||||
val installed = StoreGameSidecar.read(folder) ?: return failure("not-installed")
|
||||
val exe = installed.exeFile(folder).canonicalFile
|
||||
if (!exe.path.startsWith(folder.canonicalPath + java.io.File.separator) || !exe.isFile) return failure("missing-game-files")
|
||||
val metadata = RockstarMetadata.find(folder)
|
||||
val pipe = pipes[id]
|
||||
val sdk = (pipe == null && metadata != null) || id in setOf("gta4", "lanoire") || listOf(folder, exe.parentFile).any { dir ->
|
||||
dir.listFiles().orEmpty().any { it.isFile && it.name.lowercase() in setOf("socialclub.dll", "socialclub64.dll") }
|
||||
}
|
||||
if (pipe == null && !sdk) return failure("no-launcher-protocol")
|
||||
if (pipe != null && !listOf(folder, exe.parentFile).any { java.io.File(it, "MTLX.dll").isFile }) return failure("missing-game-files")
|
||||
val rosId = metadata?.rosId ?: RockstarTitles.byId(id)?.rosTitleId ?: return failure("missing-title-metadata")
|
||||
if (!exe.path.startsWith(folder.canonicalPath + java.io.File.separator) || !exe.isFile ||
|
||||
!java.io.File(folder, "MTLX.dll").isFile) return failure("missing-game-files")
|
||||
var ticket = RockstarAuth.ticket(app) ?: RockstarAuth.ticket(app, fresh = true) ?: return failure("signed-out")
|
||||
if (sdk && ticket.sdkTicket.isEmpty()) ticket = RockstarAuth.ticket(app, fresh = true) ?: return failure("signed-out")
|
||||
val account = try {
|
||||
RockstarApps.fetch(ticket.ticket) {}
|
||||
} catch (e: RockstarRos.RosException) {
|
||||
@@ -46,23 +40,16 @@ object RockstarLaunch {
|
||||
ticket = RockstarAuth.ticket(app, fresh = true) ?: return failure("signed-out")
|
||||
RockstarApps.fetch(ticket.ticket) {}
|
||||
}
|
||||
if (metadata != null && account.apps.none { it.titleId.toIntOrNull() == rosId && (it.name == metadata.id || it.name.startsWith(metadata.id + "_")) }) return failure("title-metadata-mismatch")
|
||||
val tokenRoot = RockstarRos.result("app.asmx/GetTitleAccessToken2", listOf("ticket" to ticket.ticket, "titleId" to rosId.toString(), "platformId" to "8"))
|
||||
if (RockstarLibrary.owned(account).none { it.id == id } || RockstarApps.deliverer(account.apps, title) == null) return failure("not-owned")
|
||||
val tokenRoot = RockstarRos.result("app.asmx/GetTitleAccessToken2", listOf("ticket" to ticket.ticket, "titleId" to title.rosTitleId.toString(), "platformId" to "8"))
|
||||
val token = RockstarRos.text(tokenRoot, "Result")?.takeIf { it.isNotEmpty() } ?: return failure("no-title-token")
|
||||
val result = JSONObject().put("ok", true).put("expiresAt", System.currentTimeMillis() + 90_000)
|
||||
if (sdk) {
|
||||
val session = JSONObject().put("accountId", ticket.rockstarId).put("identity", ticket.email.ifEmpty { ticket.nickname }).put("ticket", ticket.sdkTicket)
|
||||
if (RockstarLibrary.owns(account, rosId, metadata?.id ?: id)) session.put("titleId", metadata?.id ?: id)
|
||||
result.put("session", session)
|
||||
}
|
||||
if (pipe == null) return result
|
||||
val hash = MessageDigest.getInstance("SHA-256").digest(RockstarAuth.fingerprint(app).toString().toByteArray()).copyOf(16)
|
||||
val launch = RockstarRos.result("app.asmx/GetTitleLaunchData", listOf("ticket" to ticket.ticket, "titleAccessToken" to token,
|
||||
"machineHash" to Base64.getEncoder().encodeToString(hash)))
|
||||
val encoded = RockstarRos.text(launch, "Data") ?: return failure("no-launch-data")
|
||||
val iv = RockstarRos.text(launch, "EndpointIV") ?: return failure("no-launch-iv")
|
||||
val material = RockstarLaunchCipher.decode(encoded, iv)
|
||||
return result.put("pipe", pipe).put("material", material)
|
||||
return JSONObject().put("ok", true).put("pipe", pipe).put("material", material).put("expiresAt", System.currentTimeMillis() + 90_000)
|
||||
}
|
||||
|
||||
private fun failure(reason: String) = JSONObject().put("ok", false).put("reason", reason)
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
package com.droiddeck.launcher.stores.rockstar
|
||||
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import java.nio.charset.CodingErrorAction
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.spec.IvParameterSpec
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
internal object RockstarMetadata {
|
||||
data class Title(val id: String, val rosId: Int, val exe: String)
|
||||
|
||||
fun find(folder: File): Title? {
|
||||
val root = folder.canonicalFile
|
||||
var level = listOf(root)
|
||||
repeat(4) {
|
||||
val entries = level.map { it.listFiles().orEmpty() }
|
||||
val metadata = entries.flatMap { files -> files.filter { it.name.equals("title.rgl", true) } }
|
||||
for (file in metadata.filter { it.isFile && !java.nio.file.Files.isSymbolicLink(it.toPath()) && it.canonicalPath.startsWith(root.path + File.separator) }) {
|
||||
if (file.length() in 112..1_048_576) runCatching { decode(file.readBytes()) }.getOrNull()?.let {
|
||||
return it.copy(exe = File(file.parentFile, it.exe).relativeTo(root).invariantSeparatorsPath)
|
||||
}
|
||||
}
|
||||
level = entries.flatMap { files -> files.asSequence().filter {
|
||||
it.isDirectory && !java.nio.file.Files.isSymbolicLink(it.toPath()) && it.canonicalPath.startsWith(root.path + File.separator)
|
||||
}.take(256).toList() }.take(256)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
fun decode(bytes: ByteArray): Title? = runCatching {
|
||||
require(bytes.size in 112..1_048_576 && bytes.copyOfRange(0, 4).contentEquals(byteArrayOf(82, 71, 76, 77)))
|
||||
val header = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
|
||||
require(header.getInt(4) == 1 && header.getInt(8) == bytes.size - 80 && (bytes.size - 80) % 16 == 0)
|
||||
val cipher = Cipher.getInstance("AES/CBC/NoPadding")
|
||||
cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(ByteArray(32), "AES"), IvParameterSpec(bytes.copyOfRange(80, 96)))
|
||||
val clear = cipher.doFinal(bytes, 96, bytes.size - 96)
|
||||
val pad = clear.last().toInt() and 255
|
||||
val size = if (pad in 1..16 && clear.takeLast(pad).all { (it.toInt() and 255) == pad }) clear.size - pad
|
||||
else clear.indexOfLast { it != 0.toByte() } + 1
|
||||
val text = Charsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(clear, 0, size)).toString().removePrefix("\uFEFF")
|
||||
val json = JSONObject(text)
|
||||
val id = json.getString("titleId")
|
||||
val rosId = json.get("rosTitleId").toString().takeIf { Regex("[1-9][0-9]{0,4}").matches(it) }?.toInt() ?: return null
|
||||
val exe = json.getString("principalFileName").replace('\\', '/')
|
||||
require(Regex("[a-z][a-z0-9_]{0,63}").matches(id) && rosId in 1..65535)
|
||||
require(exe.isNotEmpty() && !exe.startsWith('/') && ':' !in exe && '\u0000' !in exe && exe.split('/').none { it == ".." })
|
||||
Title(id, rosId, exe)
|
||||
}.getOrNull()
|
||||
}
|
||||
@@ -301,9 +301,6 @@ internal fun rememberShown(onDismiss: () -> Unit): MutableTransitionState<Boolea
|
||||
return shown
|
||||
}
|
||||
|
||||
private val DIALOG_MARGIN = 12.dp
|
||||
private val SIDE_GAP = 24.dp
|
||||
|
||||
@Composable
|
||||
internal fun AppDialog(
|
||||
shown: MutableTransitionState<Boolean>, close: () -> Unit, label: String, wide: Boolean,
|
||||
@@ -312,23 +309,17 @@ internal fun AppDialog(
|
||||
back: (() -> Unit)? = null,
|
||||
scrollable: Boolean = true,
|
||||
scrollState: androidx.compose.foundation.ScrollState = rememberScrollState(),
|
||||
side: (@Composable () -> Unit)? = null,
|
||||
sideRoom: Dp = 0.dp,
|
||||
content: @Composable ColumnScope.() -> Unit,
|
||||
) {
|
||||
val pal = LocalPalette.current
|
||||
val panelCap = maxWidth ?: if (wide) 860.dp else 560.dp
|
||||
VeilRing()
|
||||
Dialog(onDismissRequest = back ?: close, properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false)) {
|
||||
CompositionLocalProvider(LocalFrontFocus provides null) {
|
||||
BoxWithConstraints(
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.fillMaxSize().imePadding()
|
||||
.tapOutside(close),
|
||||
) {
|
||||
val panel = (this.maxWidth - DIALOG_MARGIN * 2).coerceAtMost(panelCap)
|
||||
val free = (this.maxWidth - panel) / 2 - SIDE_GAP
|
||||
val beside = side != null && free >= sideRoom
|
||||
AnimatedVisibility(
|
||||
visibleState = shown,
|
||||
enter = fadeIn(Motion.tw(180)) + scaleIn(Motion.sp(0.7f), initialScale = 0.94f),
|
||||
@@ -338,8 +329,8 @@ internal fun AppDialog(
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||
modifier = Modifier
|
||||
.padding(DIALOG_MARGIN)
|
||||
.widthIn(max = panelCap)
|
||||
.padding(12.dp)
|
||||
.widthIn(max = maxWidth ?: if (wide) 860.dp else 560.dp)
|
||||
.then(
|
||||
when {
|
||||
width != null -> Modifier.width(width)
|
||||
@@ -357,21 +348,8 @@ internal fun AppDialog(
|
||||
.then(modifier)
|
||||
.then(if (scrollable) Modifier.verticalScroll(scrollState) else Modifier)
|
||||
.padding(horizontal = 18.dp, vertical = 16.dp),
|
||||
) {
|
||||
content()
|
||||
if (side != null && !beside) side()
|
||||
}
|
||||
}
|
||||
if (side != null && beside) {
|
||||
AnimatedVisibility(
|
||||
visibleState = shown,
|
||||
enter = fadeIn(Motion.tw(180)),
|
||||
exit = fadeOut(Motion.tw(140)),
|
||||
modifier = Modifier.align(Alignment.CenterEnd).padding(end = SIDE_GAP),
|
||||
label = "$label-side",
|
||||
) {
|
||||
Box(Modifier.widthIn(max = free).blockTouches()) { side() }
|
||||
}
|
||||
content = content,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,7 +70,6 @@ import com.droiddeck.launcher.frontend.AddedGameArt
|
||||
import com.droiddeck.launcher.frontend.AddedGameEdits
|
||||
import com.droiddeck.launcher.frontend.AddedGames
|
||||
import com.droiddeck.launcher.frontend.LogoPosition
|
||||
import com.droiddeck.launcher.frontend.SoundtrackCollectionArt
|
||||
import com.droiddeck.launcher.frontend.SteamGameArt
|
||||
import com.droiddeck.launcher.frontend.SteamGridDb
|
||||
import com.droiddeck.launcher.frontend.SteamLaunchOptions
|
||||
@@ -180,16 +179,6 @@ internal class ArtTarget(
|
||||
{ c, value -> AddedGameEdits.setLogoPosition(c, game.folder.path, value) },
|
||||
)
|
||||
|
||||
fun ofCollection(id: Int, name: String, root: java.io.File? = null) = ArtTarget(
|
||||
name,
|
||||
{ c, _ -> SoundtrackCollectionArt.source(c, id) },
|
||||
{ c, _ -> AddedGameArt.Choices(SoundtrackCollectionArt.options(c, id, root), SteamGridDb.Status.OK) },
|
||||
{ c, _, option -> SoundtrackCollectionArt.choose(c, id, option) },
|
||||
{ c, _ -> SoundtrackCollectionArt.reset(c, id) },
|
||||
{ _ -> null },
|
||||
{ _, _ -> false },
|
||||
)
|
||||
|
||||
fun of(game: com.droiddeck.launcher.frontend.Library.SteamGame) = ArtTarget(
|
||||
game.name,
|
||||
{ c, slot -> SteamGameArt.chosenSource(c, game.appId, slot).second },
|
||||
@@ -210,12 +199,6 @@ internal fun SteamGameArtEditor(
|
||||
ArtOnlyEditor(game.name, target, game, { SteamGameArt.describe(it, game) }, onClose, onChanged)
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun CollectionArtEditor(id: Int, name: String, root: java.io.File? = null, onClose: () -> Unit, onChanged: () -> Unit) {
|
||||
val target = remember(id, root) { ArtTarget.ofCollection(id, name, root) }
|
||||
ArtOnlyEditor(name, target, id, { SoundtrackCollectionArt.describe(it, id, root) }, onClose, onChanged, listOf(AddedGameArt.Slot.COVER))
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun StoreGameArtEditor(folder: String, name: String, onClose: () -> Unit, onChanged: () -> Unit) {
|
||||
val app = LocalContext.current.applicationContext
|
||||
@@ -229,7 +212,7 @@ internal fun StoreGameArtEditor(folder: String, name: String, onClose: () -> Uni
|
||||
@Composable
|
||||
private fun ArtOnlyEditor(
|
||||
name: String, target: ArtTarget?, refresh: Any?, describe: (Context) -> List<AddedGameArt.SlotState>,
|
||||
onClose: () -> Unit, onChanged: () -> Unit, slots: List<AddedGameArt.Slot> = AddedGameArt.Slot.values().toList(),
|
||||
onClose: () -> Unit, onChanged: () -> Unit,
|
||||
) {
|
||||
val app = LocalContext.current.applicationContext
|
||||
val shown = rememberShown(onClose)
|
||||
@@ -250,7 +233,7 @@ private fun ArtOnlyEditor(
|
||||
modifier = Modifier.fillMaxWidth().heightIn(max = maxHeight).verticalScroll(rememberScrollState()),
|
||||
) {
|
||||
Text(stringResource(R.string.edit_artwork), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(start = 4.dp, top = 2.dp))
|
||||
for (slot in slots) key(slot) {
|
||||
for (slot in AddedGameArt.Slot.values()) key(slot) {
|
||||
val state = arts.firstOrNull { it.slot == slot }
|
||||
FieldRow(slot.label(), focus = if (slot == AddedGameArt.Slot.COVER) first else null, onClick = { if (target != null) artSlot = slot }) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
@@ -259,7 +242,7 @@ private fun ArtOnlyEditor(
|
||||
}
|
||||
}
|
||||
}
|
||||
if (AddedGameArt.Slot.LOGO in slots) PickerRow(Icons.Outlined.Tune, stringResource(R.string.art_adjust_logo), logoPositionSummary(position?.value), enabled = target != null && position != null) { logoOpen = true }
|
||||
PickerRow(Icons.Outlined.Tune, stringResource(R.string.art_adjust_logo), logoPositionSummary(position?.value), enabled = target != null && position != null) { logoOpen = true }
|
||||
}
|
||||
}
|
||||
val chosen = target ?: return
|
||||
|
||||
@@ -9,8 +9,6 @@ import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.animation.expandVertically
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.shrinkHorizontally
|
||||
import androidx.compose.animation.expandHorizontally
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.shrinkVertically
|
||||
import androidx.compose.foundation.Canvas
|
||||
@@ -131,19 +129,6 @@ private const val COMPOSER_SLIDE_MS = 350L
|
||||
@Composable
|
||||
internal fun AgentPage(
|
||||
modifier: Modifier, inputModifier: Modifier = Modifier, visible: Boolean = true, startTyping: Boolean = true, hidesPet: Boolean = true,
|
||||
menuSlot: AgentMenuSlot? = null,
|
||||
) = AgentPageContent(modifier, inputModifier, visible, startTyping, hidesPet, showControlsWithoutKeyboard = false, menuSlot)
|
||||
|
||||
@Composable
|
||||
internal fun AgentPageWithControls(
|
||||
modifier: Modifier, inputModifier: Modifier = Modifier, visible: Boolean = true, startTyping: Boolean = true,
|
||||
showControlsWithoutKeyboard: Boolean,
|
||||
) = AgentPageContent(modifier, inputModifier, visible, startTyping, hidesPet = true, showControlsWithoutKeyboard = showControlsWithoutKeyboard)
|
||||
|
||||
@Composable
|
||||
private fun AgentPageContent(
|
||||
modifier: Modifier, inputModifier: Modifier, visible: Boolean, startTyping: Boolean, hidesPet: Boolean,
|
||||
showControlsWithoutKeyboard: Boolean, menuSlot: AgentMenuSlot? = null,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val view = LocalView.current
|
||||
@@ -175,16 +160,6 @@ private fun AgentPageContent(
|
||||
val composer = remember { ComposerState(startTyping && AgentHost.entries.isEmpty()) }
|
||||
val focusManager = LocalFocusManager.current
|
||||
val togglePanel: (AgentPanel) -> Unit = { panel = if (panel == it) AgentPanel.NONE else it }
|
||||
var menuOpen by rememberSaveable { mutableStateOf(false) }
|
||||
val menu: @Composable () -> Unit = {
|
||||
AgentMenu(menuOpen, { menuOpen = it }, onPanel = { panel = it }, onSetup = { setup = true })
|
||||
}
|
||||
// A host with a title bar shows the menu there; otherwise it floats over the conversation's top corner.
|
||||
val inSlot = menuSlot != null && panel != AgentPanel.HISTORY && panel != AgentPanel.PROCESSES
|
||||
if (menuSlot != null) DisposableEffect(menuSlot, inSlot) {
|
||||
menuSlot.content = if (inSlot) menu else null
|
||||
onDispose { menuSlot.content = null }
|
||||
}
|
||||
// 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 }
|
||||
@@ -250,10 +225,9 @@ private fun AgentPageContent(
|
||||
) {
|
||||
AgentJumpPill(toLatest)
|
||||
}
|
||||
if (menuSlot == null) Box(Modifier.align(Alignment.TopEnd).padding(top = 4.dp)) { menu() }
|
||||
}
|
||||
androidx.compose.animation.AnimatedVisibility(!hidden, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) {
|
||||
AgentComposer(composer, draft, inputModifier, panel, togglePanel, showControlsWithoutKeyboard)
|
||||
AgentComposer(composer, draft, inputModifier, panel, togglePanel) { setup = true }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -266,7 +240,6 @@ private class ComposerState(typing: Boolean) {
|
||||
var typing by mutableStateOf(typing)
|
||||
var focusRequests by mutableIntStateOf(0)
|
||||
private set
|
||||
private var consumedFocusRequests by mutableIntStateOf(0)
|
||||
/** Opened and waiting for the text field to take focus; focus passes through nothing on the way. */
|
||||
var opening = false
|
||||
|
||||
@@ -275,52 +248,6 @@ private class ComposerState(typing: Boolean) {
|
||||
opening = true
|
||||
focusRequests++
|
||||
}
|
||||
|
||||
fun hasUnconsumedFocusRequest() = focusRequests > consumedFocusRequests
|
||||
|
||||
fun consumeFocusRequest() {
|
||||
consumedFocusRequests = focusRequests
|
||||
}
|
||||
}
|
||||
|
||||
/** Where a host with its own title bar shows the conversation's menu. */
|
||||
@Stable
|
||||
internal class AgentMenuSlot {
|
||||
var content by mutableStateOf<(@Composable () -> Unit)?>(null)
|
||||
}
|
||||
|
||||
/** History, processes, a new conversation, the pet and setup, folded behind one button. */
|
||||
@Composable
|
||||
private fun AgentMenu(open: Boolean, onOpen: (Boolean) -> Unit, onPanel: (AgentPanel) -> Unit, onSetup: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val working = AgentHost.state == AgentHost.State.WORKING
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.clip(Shape16).background(colors.surface.copy(alpha = if (open) 0.97f else 0.88f))
|
||||
.border(1.dp, pal.line, Shape16).padding(end = 2.dp),
|
||||
) {
|
||||
androidx.compose.animation.AnimatedVisibility(open, enter = expandHorizontally(expandFrom = Alignment.End) + fadeIn(),
|
||||
exit = shrinkHorizontally(shrinkTowards = Alignment.End) + fadeOut()) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
HeaderAction(Icons.Outlined.History, stringResource(R.string.agent_history), size = 36.dp, tag = "agent-history") { onOpen(false); onPanel(AgentPanel.HISTORY) }
|
||||
HeaderAction(Icons.Outlined.Memory, stringResource(R.string.agent_processes), size = 36.dp, tag = "agent-processes") { onOpen(false); onPanel(AgentPanel.PROCESSES) }
|
||||
HeaderAction(Icons.Outlined.Add, stringResource(R.string.agent_new), enabled = !working && AgentHost.entries.isNotEmpty(), size = 36.dp, tag = "agent-new") {
|
||||
onOpen(false)
|
||||
AgentHost.forget(context)
|
||||
}
|
||||
HeaderAction(Icons.Outlined.Pets, stringResource(R.string.setup_agent_pet), selected = AgentPet.enabled, size = 36.dp, tag = "agent-pet-toggle") {
|
||||
AgentPet.set(context, !AgentPet.enabled)
|
||||
}
|
||||
HeaderAction(Icons.Outlined.Settings, stringResource(R.string.agent_setup_title), enabled = !working, size = 36.dp, tag = "agent-settings") {
|
||||
onOpen(false)
|
||||
onSetup()
|
||||
}
|
||||
}
|
||||
}
|
||||
HeaderAction(Icons.Outlined.MoreHoriz, stringResource(R.string.agent_more), selected = open, size = 36.dp, tag = "agent-menu") { onOpen(!open) }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -565,8 +492,7 @@ internal fun liveUsed(limit: AgentHost.Limit) = if (limit.resetsAt > 0 && limit.
|
||||
|
||||
@Composable
|
||||
private fun AgentComposer(
|
||||
composer: ComposerState, draftState: MutableState<String>, inputModifier: Modifier, panel: AgentPanel, onPanel: (AgentPanel) -> Unit,
|
||||
showControlsWithoutKeyboard: Boolean,
|
||||
composer: ComposerState, draftState: MutableState<String>, inputModifier: Modifier, panel: AgentPanel, onPanel: (AgentPanel) -> Unit, onSetup: () -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
var draft by draftState
|
||||
@@ -612,23 +538,15 @@ private fun AgentComposer(
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.padding(top = 8.dp).fillMaxWidth().horizontalScroll(rememberScrollState()),
|
||||
) { AgentActivity(labOpen) { labOpen = !labOpen } }
|
||||
AgentEditor(composer, draftState, inputModifier, panel, onPanel, highlightControls = showControlsWithoutKeyboard, send = send)
|
||||
} else AgentReadingBar(
|
||||
composer, draft, inputModifier, labOpen, onLab = { labOpen = !labOpen }, onUsage = { onPanel(AgentPanel.USAGE) },
|
||||
) {
|
||||
// The session drawer is driven by a controller, so its editor opens without raising the keyboard.
|
||||
if (showControlsWithoutKeyboard) {
|
||||
composer.typing = true
|
||||
composer.opening = true
|
||||
} else composer.open()
|
||||
}
|
||||
AgentEditor(composer, draftState, inputModifier, panel, onPanel, onSetup, send)
|
||||
} else AgentReadingBar(composer, draft, inputModifier, labOpen, onLab = { labOpen = !labOpen }) { onPanel(AgentPanel.USAGE) }
|
||||
}
|
||||
}
|
||||
|
||||
/** The composer while reading: one line holding what is going on, opened by a press or by Y. */
|
||||
@Composable
|
||||
private fun AgentReadingBar(
|
||||
composer: ComposerState, draft: String, inputModifier: Modifier, labOpen: Boolean, onLab: () -> Unit, onUsage: () -> Unit, onOpen: () -> Unit,
|
||||
composer: ComposerState, draft: String, inputModifier: Modifier, labOpen: Boolean, onLab: () -> Unit, onUsage: () -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
@@ -639,7 +557,7 @@ private fun AgentReadingBar(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 8.dp).height(44.dp).clip(Shape16).background(colors.surface)
|
||||
.border(if (focused) 2.dp else 1.dp, if (focused) pal.primary else pal.line, Shape16)
|
||||
.then(inputModifier).onFocusChanged { focused = it.isFocused }.clickable(onClick = onOpen).testTag("agent-composer-bar")
|
||||
.then(inputModifier).onFocusChanged { focused = it.isFocused }.clickable { composer.open() }.testTag("agent-composer-bar")
|
||||
.padding(start = 14.dp, end = 4.dp),
|
||||
) {
|
||||
Text(
|
||||
@@ -664,7 +582,7 @@ private fun AgentReadingBar(
|
||||
@Composable
|
||||
private fun AgentEditor(
|
||||
composer: ComposerState, draftState: MutableState<String>, inputModifier: Modifier, panel: AgentPanel, onPanel: (AgentPanel) -> Unit,
|
||||
highlightControls: Boolean = false, send: () -> Unit,
|
||||
onSetup: () -> Unit, send: () -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
@@ -690,11 +608,12 @@ private fun AgentEditor(
|
||||
for (path in AgentAttachments.pending.toList()) AttachmentChip(path) { AgentAttachments.pending.remove(path) }
|
||||
}
|
||||
var focused by remember { mutableStateOf(false) }
|
||||
var menu by rememberSaveable { mutableStateOf(false) }
|
||||
val field = remember { FocusRequester() }
|
||||
LaunchedEffect(composer.focusRequests) { if (composer.hasUnconsumedFocusRequest()) runCatching { field.requestFocus() } }
|
||||
LaunchedEffect(composer.focusRequests) { if (composer.focusRequests > 0) runCatching { field.requestFocus() } }
|
||||
Column(
|
||||
Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape16).background(colors.surface)
|
||||
.border(if (focused || highlightControls) 2.dp else 1.dp, if (focused || highlightControls) pal.primary else pal.line, Shape16).padding(6.dp),
|
||||
.border(1.dp, if (focused) pal.primary else pal.line, Shape16).padding(6.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().height(36.dp)) {
|
||||
val model = AgentHost.models(context).firstOrNull { it.id == AgentHost.model }?.label ?: AgentHost.model ?: stringResource(R.string.agent_model_default)
|
||||
@@ -711,6 +630,22 @@ private fun AgentEditor(
|
||||
}
|
||||
ContextRing("agent-usage", onClick = { onPanel(AgentPanel.USAGE) })
|
||||
}
|
||||
if (menu) {
|
||||
HeaderAction(Icons.Outlined.History, stringResource(R.string.agent_history), size = 32.dp, tag = "agent-history") { menu = false; onPanel(AgentPanel.HISTORY) }
|
||||
HeaderAction(Icons.Outlined.Memory, stringResource(R.string.agent_processes), size = 32.dp, tag = "agent-processes") { menu = false; onPanel(AgentPanel.PROCESSES) }
|
||||
HeaderAction(Icons.Outlined.Add, stringResource(R.string.agent_new), enabled = !working && AgentHost.entries.isNotEmpty(), size = 32.dp, tag = "agent-new") {
|
||||
menu = false
|
||||
AgentHost.forget(context)
|
||||
}
|
||||
HeaderAction(Icons.Outlined.Pets, stringResource(R.string.setup_agent_pet), selected = AgentPet.enabled, size = 32.dp, tag = "agent-pet-toggle") {
|
||||
AgentPet.set(context, !AgentPet.enabled)
|
||||
}
|
||||
HeaderAction(Icons.Outlined.Settings, stringResource(R.string.agent_setup_title), enabled = !working, size = 32.dp, tag = "agent-settings") {
|
||||
menu = false
|
||||
onSetup()
|
||||
}
|
||||
}
|
||||
HeaderAction(if (menu) Icons.Outlined.Close else Icons.Outlined.MoreHoriz, stringResource(R.string.agent_more), size = 32.dp, tag = "agent-menu") { menu = !menu }
|
||||
}
|
||||
Row(verticalAlignment = Alignment.Bottom) {
|
||||
if (LocalActivityResultRegistryOwner.current != null) AttachButton()
|
||||
@@ -723,10 +658,7 @@ private fun AgentEditor(
|
||||
draft, { draft = it },
|
||||
Modifier.fillMaxWidth().focusRequester(field).onFocusChanged {
|
||||
focused = it.isFocused
|
||||
if (it.isFocused) {
|
||||
composer.consumeFocusRequest()
|
||||
composer.opening = false
|
||||
}
|
||||
if (it.isFocused) composer.opening = false
|
||||
}.testTag("agent-input").then(inputModifier),
|
||||
textStyle = TextStyle(fontSize = 16.sp, color = colors.onSurface),
|
||||
cursorBrush = SolidColor(pal.primary),
|
||||
|
||||
@@ -116,10 +116,6 @@ internal object AgentPet {
|
||||
fun set(context: Context, on: Boolean) {
|
||||
enabled = on
|
||||
AgentHost.prefs(context).edit().putBoolean(KEY, on).apply()
|
||||
if (on) {
|
||||
allowed = PetWindows.allowed(context)
|
||||
if (!allowed) requestFloating(context)
|
||||
}
|
||||
}
|
||||
|
||||
/** Opens the system page where the user lets DroidDeck draw over other apps. */
|
||||
|
||||
@@ -110,11 +110,7 @@ internal class PetMotion(private val context: Context) {
|
||||
private val margin = 6 * density
|
||||
private val inset = 24 * density
|
||||
private var settle: ValueAnimator? = null
|
||||
// A fling's overshoot may carry the pet past the edge it settles on, but never so far that it leaves the screen.
|
||||
private val spring = FlingSpring { sx, sy ->
|
||||
x = sx.coerceIn(-size / 2, (width - size / 2).coerceAtLeast(-size / 2))
|
||||
y = sy.coerceIn(0f, (height - size).coerceAtLeast(0f))
|
||||
}
|
||||
private val spring = FlingSpring { sx, sy -> x = sx; y = sy }
|
||||
|
||||
val dockX get() = width - size - margin
|
||||
|
||||
@@ -337,24 +333,11 @@ internal class PetWindows(private val context: Context) {
|
||||
gravity = Gravity.TOP or Gravity.START
|
||||
if (full) softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
|
||||
noMoveAnimation(this)
|
||||
}
|
||||
if (onSize != null) compose.addOnLayoutChangeListener { v, _, _, _, _, _, _, _, _ -> onSize(v.width, v.height) }
|
||||
return Window(frame, params, touchable)
|
||||
}
|
||||
|
||||
/**
|
||||
* The system otherwise eases a moved overlay from where it last placed it, so the pet trails behind
|
||||
* the finger, lags the chat as it opens, or flashes at an old spot. setCanPlayMoveAnimation sets the
|
||||
* same flag but makes some ROMs refuse the window, so the flag is set directly.
|
||||
*/
|
||||
private fun noMoveAnimation(params: WindowManager.LayoutParams) {
|
||||
runCatching {
|
||||
val field = WindowManager.LayoutParams::class.java.getField("privateFlags")
|
||||
field.setInt(params, field.getInt(params) or PRIVATE_FLAG_NO_MOVE_ANIMATION)
|
||||
}
|
||||
}
|
||||
|
||||
/** A hidden overlay window still owns its frame, which the system can stretch over the screen, so it also stops taking touches. */
|
||||
private fun setVisible(window: Window, shown: Boolean) {
|
||||
window.view.visibility = if (shown) View.VISIBLE else View.GONE
|
||||
@@ -484,7 +467,6 @@ internal class PetWindows(private val context: Context) {
|
||||
|
||||
companion object {
|
||||
private const val OFFSCREEN = 10_000
|
||||
private const val PRIVATE_FLAG_NO_MOVE_ANIMATION = 0x40
|
||||
fun allowed(context: Context) = Settings.canDrawOverlays(context)
|
||||
}
|
||||
}
|
||||
@@ -519,7 +501,6 @@ internal fun PetChat(open: Boolean, motion: PetMotion, onClose: () -> Unit, onCl
|
||||
} else {
|
||||
Rect(margin, motion.dockY + motion.size + gap, w - margin, h - margin)
|
||||
}
|
||||
val menuSlot = remember { AgentMenuSlot() }
|
||||
val grow = remember { Animatable(0f) }
|
||||
val fade = remember { Animatable(0f) }
|
||||
LaunchedEffect(open) {
|
||||
@@ -560,10 +541,9 @@ internal fun PetChat(open: Boolean, motion: PetMotion, onClose: () -> Unit, onCl
|
||||
Text(stringResource(R.string.agent_pet_name), fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
|
||||
modifier = Modifier.padding(start = 4.dp))
|
||||
Spacer(Modifier.weight(1f))
|
||||
menuSlot.content?.invoke()
|
||||
HeaderAction(Icons.Outlined.Close, stringResource(R.string.agent_close), size = 34.dp, tag = "agent-pet-close", onClick = onClose)
|
||||
}
|
||||
AgentPage(Modifier.weight(1f).fillMaxWidth(), visible = open, startTyping = AgentHost.entries.isEmpty(), hidesPet = false, menuSlot = menuSlot)
|
||||
AgentPage(Modifier.weight(1f).fillMaxWidth(), visible = open, startTyping = AgentHost.entries.isEmpty(), hidesPet = false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,29 +142,18 @@ private fun TabChip(label: String, selected: Boolean, modifier: Modifier = Modif
|
||||
@Composable
|
||||
internal fun BootMovieGroup(s: ModeSettings, a: ModeSettingsActions, host: MenuHost) {
|
||||
var tab by rememberSaveable { mutableStateOf(MovieTab.INSTALLED) }
|
||||
val app = LocalContext.current.applicationContext
|
||||
var skipBootMovie by remember { mutableStateOf(SessionPrefs.skipBootMovie(app)) }
|
||||
SettingsGroup(stringResource(R.string.boot_movie)) {
|
||||
ToggleRow(
|
||||
host, "boot-movie-skip", stringResource(R.string.boot_movie_skip),
|
||||
stringResource(R.string.boot_movie_skip_hint), skipBootMovie,
|
||||
) { enabled ->
|
||||
skipBootMovie = enabled
|
||||
SessionPrefs.setSkipBootMovie(app, enabled)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 10.dp)) {
|
||||
TabChip(stringResource(R.string.boot_movie_tab_installed), tab == MovieTab.INSTALLED, Modifier.weight(1f)) { tab = MovieTab.INSTALLED }
|
||||
TabChip(stringResource(R.string.boot_movie_tab_import), tab == MovieTab.IMPORT, Modifier.weight(1f)) { tab = MovieTab.IMPORT }
|
||||
TabChip(stringResource(R.string.boot_movie_tab_repo), tab == MovieTab.REPO, Modifier.weight(1f)) { tab = MovieTab.REPO }
|
||||
TabChip(stringResource(R.string.boot_movie_tab_sound), tab == MovieTab.SOUND, Modifier.weight(1f)) { tab = MovieTab.SOUND }
|
||||
}
|
||||
if (!skipBootMovie) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 10.dp)) {
|
||||
TabChip(stringResource(R.string.boot_movie_tab_installed), tab == MovieTab.INSTALLED, Modifier.weight(1f)) { tab = MovieTab.INSTALLED }
|
||||
TabChip(stringResource(R.string.boot_movie_tab_import), tab == MovieTab.IMPORT, Modifier.weight(1f)) { tab = MovieTab.IMPORT }
|
||||
TabChip(stringResource(R.string.boot_movie_tab_repo), tab == MovieTab.REPO, Modifier.weight(1f)) { tab = MovieTab.REPO }
|
||||
TabChip(stringResource(R.string.boot_movie_tab_sound), tab == MovieTab.SOUND, Modifier.weight(1f)) { tab = MovieTab.SOUND }
|
||||
}
|
||||
when (tab) {
|
||||
MovieTab.INSTALLED -> InstalledTab(a)
|
||||
MovieTab.IMPORT -> ImportTab(s, a)
|
||||
MovieTab.REPO -> RepoTab(a)
|
||||
MovieTab.SOUND -> SoundTab(s, a, host)
|
||||
}
|
||||
when (tab) {
|
||||
MovieTab.INSTALLED -> InstalledTab(a)
|
||||
MovieTab.IMPORT -> ImportTab(s, a)
|
||||
MovieTab.REPO -> RepoTab(a)
|
||||
MovieTab.SOUND -> SoundTab(s, a, host)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import androidx.compose.ui.platform.LocalContext
|
||||
import com.droiddeck.launcher.hud.DroidDeckHudConfig
|
||||
import com.droiddeck.launcher.hud.FrameStats
|
||||
import com.droiddeck.launcher.hud.GameFrameFeed
|
||||
import com.droiddeck.launcher.hud.HudFrames
|
||||
import com.droiddeck.launcher.hud.HudMetrics
|
||||
import com.droiddeck.launcher.hud.KeyValueSet
|
||||
import com.droiddeck.launcher.hud.MangoReadings
|
||||
@@ -33,7 +34,7 @@ private const val STRIP_TEMP_PLAIN = 0xFFF2F5F9.toInt()
|
||||
@Composable
|
||||
internal fun SessionBottomStrip(pageId: String?, fps: () -> Float?) {
|
||||
val context = LocalContext.current
|
||||
val frames = remember { GameFrameFeed.forRoot(LinuxRuntime.rootDir(context)) }
|
||||
val frames = remember { GameFrameFeed(File(LinuxRuntime.rootDir(context), HudFrames.PATH)) }
|
||||
DisposableEffect(frames) { onDispose { frames.close() } }
|
||||
val page by rememberUpdatedState(pageId)
|
||||
var frameTick by remember { mutableIntStateOf(0) }
|
||||
|
||||
@@ -55,6 +55,7 @@ import com.droiddeck.launcher.hud.DroidDeckHudConfig
|
||||
import com.droiddeck.launcher.hud.DroidDeckHudHost
|
||||
import com.droiddeck.launcher.hud.FrameStats
|
||||
import com.droiddeck.launcher.hud.GameFrameFeed
|
||||
import com.droiddeck.launcher.hud.HudFrames
|
||||
import com.droiddeck.launcher.hud.HudMetrics
|
||||
import com.droiddeck.launcher.hud.KeyValueSet
|
||||
import com.droiddeck.launcher.hud.MangoReadings
|
||||
@@ -143,7 +144,7 @@ fun BottomTelemetryPage(fps: () -> Float?, runningGame: () -> String? = { null }
|
||||
var perfTick by remember { mutableIntStateOf(0) }
|
||||
var traceTick by remember { mutableIntStateOf(0) }
|
||||
var clock by remember { mutableStateOf("") }
|
||||
val frames = remember { GameFrameFeed.forRoot(LinuxRuntime.rootDir(context)) }
|
||||
val frames = remember { GameFrameFeed(File(LinuxRuntime.rootDir(context), HudFrames.PATH)) }
|
||||
DisposableEffect(frames) { onDispose { frames.close() } }
|
||||
val currentFps = { if (frames.live) frames.stats.fps else fps() }
|
||||
var hud by remember { mutableStateOf(StatsHud.from(SessionPrefs.statsHud(context))) }
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
@@ -10,9 +8,7 @@ import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
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.SessionPrefs
|
||||
import com.droiddeck.launcher.session.StripMetric
|
||||
@@ -59,34 +55,20 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
|
||||
ChoiceRow(host, "hud-outline-color", stringResource(R.string.hud_outline_color), null,
|
||||
listOf("0" to stringResource(R.string.hud_outline_gray), "1" to stringResource(R.string.hud_outline_theme)),
|
||||
if (cfg["hudOutlineAccent"] == "0") "0" else "1", chipModifier = track("hud-outline-color")) { a.onHudSetting("hudOutlineAccent", it) }
|
||||
ToggleRow(host, "hud-fps-decimal", stringResource(R.string.hud_metric_decimal), null, on("fpsDecimal"),
|
||||
chipModifier = track("hud-fps-decimal")) { a.onHudSetting("fpsDecimal", flag(it)) }
|
||||
ToggleRow(host, "hud-clock", stringResource(R.string.hud_metric_clock), null, on("showClock"),
|
||||
chipModifier = track("hud-clock")) { a.onHudSetting("showClock", flag(it)) }
|
||||
ToggleRow(host, "hud-graph", stringResource(R.string.hud_metric_graph), null, on("showFPSGraph"),
|
||||
chipModifier = track("hud-graph")) { a.onHudSetting("showFPSGraph", flag(it)) }
|
||||
}
|
||||
|
||||
var editing by remember { mutableStateOf(false) }
|
||||
val size = DroidDeckHudSize.from(cfg["hudSize"])
|
||||
val chips = size.supportedChips() + EXTRA[size].orEmpty()
|
||||
SettingsGroup(stringResource(R.string.hud_group_metrics)) {
|
||||
ActionRow(stringResource(R.string.hud_group_metrics), null, stringResource(R.string.common_edit),
|
||||
onClick = { editing = true }, modifier = track("hud-readings"))
|
||||
val rows = DroidDeckHudSize.rowsFor(DroidDeckHudSize.from(cfg["hudSize"]), cfg)
|
||||
SettingsRow(stringResource(R.string.hud_readings_shown), null) {
|
||||
Text(stringResource(R.string.hud_readings_count, rows.count { on(it) }, rows.size),
|
||||
fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
for (metric in METRICS) {
|
||||
if (metric.chip !in chips || metric.chip in HIDDEN[size].orEmpty()) continue
|
||||
ToggleRow(host, "hud-${metric.key}", stringResource(metric.label), null, on(metric.key),
|
||||
chipModifier = track("hud-${metric.key}")) { a.onHudSetting(metric.key, flag(it)) }
|
||||
}
|
||||
if (editing) HudReadingsDialog(
|
||||
visible = rows,
|
||||
initialOrder = rows,
|
||||
initialOn = rows.associateWith { on(it) },
|
||||
onDismiss = { editing = false },
|
||||
onSave = { switches, order -> a.onHudOrder(switches, order) },
|
||||
onReset = a.onHudOrderReset,
|
||||
)
|
||||
}
|
||||
|
||||
if (on("showTemp") || on("showGpuTemp") || on("showBatteryTemp")) SettingsGroup(stringResource(R.string.hud_group_temps)) {
|
||||
val tempsShown = ("Temp" in chips && on("showTemp")) || ("GPU temp" in chips && on("showGpuTemp"))
|
||||
if (tempsShown) SettingsGroup(stringResource(R.string.hud_group_temps)) {
|
||||
ChoiceRow(host, "hud-temp-unit", stringResource(R.string.hud_temp_unit), null,
|
||||
listOf("c" to "°C", "f" to "°F"), if (cfg["tempUnit"].equals("f", true)) "f" else "c",
|
||||
chipModifier = track("hud-temp-unit")) { a.onHudSetting("tempUnit", it) }
|
||||
@@ -163,39 +145,39 @@ private val BOTTOM_STRIP_ROWS = listOf(
|
||||
StripMetric.CLOCK to R.string.hud_metric_clock,
|
||||
)
|
||||
|
||||
private class HudMetric(val key: String, val label: Int)
|
||||
private val EXTRA = mapOf(DroidDeckHudSize.PILL to setOf("Temp", "Power"))
|
||||
|
||||
private class HudMetric(val chip: String, val key: String, val label: Int)
|
||||
|
||||
// Wrapper and DX version have nothing to show in DroidDeck.
|
||||
private val METRICS = listOf(
|
||||
HudMetric("showGpuModel", R.string.hud_metric_gpu_model),
|
||||
HudMetric("showGPULoad", R.string.hud_metric_gpu),
|
||||
HudMetric("showCPUUsage", R.string.hud_metric_cpu),
|
||||
HudMetric("showPerCore", R.string.hud_metric_per_core),
|
||||
HudMetric("showTemp", R.string.hud_metric_temp),
|
||||
HudMetric("showBatteryTemp", R.string.drawer_hud_battery),
|
||||
HudMetric("showGpuTemp", R.string.hud_metric_gpu_temp),
|
||||
HudMetric("showVram", R.string.hud_metric_vram),
|
||||
HudMetric("showRAM", R.string.hud_metric_ram),
|
||||
HudMetric("showSwap", R.string.hud_metric_swap),
|
||||
HudMetric("showBattery", R.string.hud_metric_battery),
|
||||
HudMetric("showBatteryTime", R.string.hud_metric_battery_time),
|
||||
HudMetric("showPower", R.string.hud_metric_power),
|
||||
HudMetric("showFPS", R.string.drawer_hud_fps),
|
||||
HudMetric("showFPSGraph", R.string.hud_metric_graph),
|
||||
HudMetric("showLatency", R.string.hud_metric_latency),
|
||||
HudMetric("showAvg", R.string.hud_metric_avg),
|
||||
HudMetric("showLow1", R.string.hud_metric_low1),
|
||||
HudMetric("showLow01", R.string.hud_metric_low01),
|
||||
HudMetric("showLow001", R.string.hud_metric_low001),
|
||||
HudMetric("showEngine", R.string.hud_metric_engine),
|
||||
HudMetric("showDisplay", R.string.hud_metric_display),
|
||||
HudMetric("showHdr", R.string.hud_metric_hdr),
|
||||
HudMetric("showNet", R.string.hud_metric_network),
|
||||
HudMetric("showResolution", R.string.hud_metric_resolution),
|
||||
HudMetric("showProton", R.string.hud_metric_proton),
|
||||
HudMetric("showSession", R.string.hud_metric_session),
|
||||
HudMetric("showClock", R.string.hud_metric_clock),
|
||||
HudMetric("FPS", "showFPS", R.string.drawer_hud_fps),
|
||||
HudMetric("FPS graph", "showFPSGraph", R.string.hud_metric_graph),
|
||||
HudMetric("FPS .1", "fpsDecimal", R.string.hud_metric_decimal),
|
||||
HudMetric("1% low", "showLow1", R.string.hud_metric_low1),
|
||||
HudMetric("0.1% low", "showLow01", R.string.hud_metric_low01),
|
||||
HudMetric("0.01% low", "showLow001", R.string.hud_metric_low001),
|
||||
HudMetric("Engine", "showEngine", R.string.hud_metric_engine),
|
||||
HudMetric("GPU model", "showGpuModel", R.string.hud_metric_gpu_model),
|
||||
HudMetric("GPU", "showGPULoad", R.string.hud_metric_gpu),
|
||||
HudMetric("GPU temp", "showGpuTemp", R.string.hud_metric_gpu_temp),
|
||||
HudMetric("CPU", "showCPUUsage", R.string.hud_metric_cpu),
|
||||
HudMetric("Per-core", "showPerCore", R.string.hud_metric_per_core),
|
||||
HudMetric("Temp", "showTemp", R.string.hud_metric_temp),
|
||||
HudMetric("RAM", "showRAM", R.string.hud_metric_ram),
|
||||
HudMetric("VRAM", "showVram", R.string.hud_metric_vram),
|
||||
HudMetric("Swap", "showSwap", R.string.hud_metric_swap),
|
||||
HudMetric("Battery", "showBattery", R.string.hud_metric_battery),
|
||||
HudMetric("Power", "showPower", R.string.hud_metric_power),
|
||||
HudMetric("Network", "showNet", R.string.hud_metric_network),
|
||||
HudMetric("Resolution", "showResolution", R.string.hud_metric_resolution),
|
||||
HudMetric("Proton", "showProton", R.string.hud_metric_proton),
|
||||
HudMetric("Session", "showSession", R.string.hud_metric_session),
|
||||
HudMetric("Clock", "showClock", R.string.hud_metric_clock),
|
||||
)
|
||||
|
||||
internal fun hudMetricLabel(key: String): Int? =
|
||||
METRICS.firstOrNull { it.key == key }?.label
|
||||
private val HIDDEN = mapOf(
|
||||
DroidDeckHudSize.PILL to setOf("FPS", "FPS graph"),
|
||||
DroidDeckHudSize.MINIMAL to setOf("FPS"),
|
||||
DroidDeckHudSize.TILES to setOf("FPS graph", "0.1% low", "0.01% low"),
|
||||
DroidDeckHudSize.STRIP to setOf("FPS"),
|
||||
)
|
||||
@@ -59,8 +59,6 @@ class DualPanelModel(
|
||||
val appScale: Int,
|
||||
val onSelect: (String) -> Unit,
|
||||
val onResume: () -> Unit,
|
||||
val title: String = selected,
|
||||
val moreDownloads: Int = 0,
|
||||
)
|
||||
|
||||
object DualScreenPanel {
|
||||
@@ -324,7 +322,7 @@ internal fun DualPanelContent(model: DualPanelModel) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(stringResource(R.string.app_name), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = pal.signal)
|
||||
Spacer(Modifier.size(12.dp))
|
||||
val (label, _) = railLabelIcon(model.title)
|
||||
val (label, _) = railLabelIcon(model.selected)
|
||||
Text(stringResource(label), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
|
||||
modifier = Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
PanelClock()
|
||||
@@ -338,7 +336,7 @@ internal fun DualPanelContent(model: DualPanelModel) {
|
||||
for (row in model.keys.chunked(columns)) {
|
||||
Row(Modifier.fillMaxWidth().height(tileHeight), horizontalArrangement = Arrangement.spacedBy(gap)) {
|
||||
for (key in row) PanelTile(key, key == model.selected, key in model.badges,
|
||||
if (key == "stores") model.storeDownloads else if (key == NavTabs.MORE) model.moreDownloads else 0, Modifier.weight(1f)) { model.onSelect(key) }
|
||||
if (key == "stores") model.storeDownloads else 0, Modifier.weight(1f)) { model.onSelect(key) }
|
||||
repeat(columns - row.size) { Spacer(Modifier.weight(1f)) }
|
||||
}
|
||||
}
|
||||
@@ -402,10 +400,12 @@ private fun PanelClock() {
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun DualPanelPublisher(s: FrontEndState, selected: String, title: String, onSelect: (String) -> Unit, a: FrontEndActions) {
|
||||
val keys = navigationKeys(s)
|
||||
val badges = keys.filter { railBadge(s, it) }.toSet()
|
||||
val model = DualPanelModel(keys, selected, badges, s.storeDownloadsActive, s.running, s.theme, s.appScale, onSelect, a.onResume, title, railCount(s, NavTabs.MORE))
|
||||
internal fun DualPanelPublisher(s: FrontEndState, selected: String, onSelect: (String) -> Unit, a: FrontEndActions) {
|
||||
val badges = buildSet {
|
||||
if (setupNeedsAttention(s)) add("setup")
|
||||
if (s.updates.hasUpdate) add("updates")
|
||||
}
|
||||
val model = DualPanelModel(navigationKeys(s), selected, badges, s.storeDownloadsActive, s.running, s.theme, s.appScale, onSelect, a.onResume)
|
||||
androidx.compose.runtime.SideEffect { DualScreenPanel.model = model }
|
||||
androidx.compose.runtime.DisposableEffect(Unit) { onDispose { DualScreenPanel.model = null } }
|
||||
}
|
||||
|
||||
@@ -115,7 +115,6 @@ internal fun Pane(
|
||||
s.pageKey != null && page != null -> null
|
||||
selected.startsWith("app:") -> s.steamGames.firstOrNull { "app:${it.appId}" == selected }?.art
|
||||
selected == "games" -> s.steamGames.maxByOrNull { it.lastPlayed }?.art
|
||||
selected.startsWith("sound:") -> s.soundtracks.firstOrNull { "sound:${it.appId}" == selected }?.let { it.hero ?: it.art }
|
||||
selected.startsWith("rom:") -> romFor(s, selected)?.second?.art
|
||||
else -> null
|
||||
}
|
||||
@@ -125,12 +124,10 @@ internal fun Pane(
|
||||
val origins = remember { HashMap<String, Origin>() }
|
||||
val paneAt = remember { arrayOf(Offset.Zero) }
|
||||
val livePage by rememberUpdatedState(s.pageKey)
|
||||
val railContent = if (selected.startsWith("app:")) "games" else if (selected.startsWith("sound:")) "soundtracks" else selected
|
||||
val railContent = if (selected.startsWith("app:")) "games" else selected
|
||||
val target = if (page != null && s.pageKey != null) s.pageKey else railContent
|
||||
val gameShown = remember { arrayOf("games") }
|
||||
if (selected == "games" || selected.startsWith("app:")) gameShown[0] = selected
|
||||
val soundShown = remember { arrayOf("soundtracks") }
|
||||
if (selected == "soundtracks" || selected.startsWith("sound:")) soundShown[0] = selected
|
||||
val before = remember { arrayOf(target) }
|
||||
if (page != null && s.pageKey != null) {
|
||||
pages[s.pageKey] = page
|
||||
@@ -174,7 +171,7 @@ internal fun Pane(
|
||||
label = "pane",
|
||||
) { key ->
|
||||
val drawn = (if (page != null && key == s.pageKey) page else pages[key])
|
||||
?: { Content(s, if (key == "games") gameShown[0] else if (key == "soundtracks") soundShown[0] else key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb, onPairWirelessDebugging) }
|
||||
?: { Content(s, if (key == "games") gameShown[0] else key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb, onPairWirelessDebugging) }
|
||||
val hopSink by androidx.compose.animation.core.animateFloatAsState(
|
||||
if (Hops.sinking == key) 1f else 0f, Motion.tw(260), label = "hopSink",
|
||||
)
|
||||
@@ -265,7 +262,7 @@ private fun Content(
|
||||
StoresPage(s, a, modifier)
|
||||
return
|
||||
}
|
||||
if (selected == "games" || selected.startsWith("app:") || selected == "soundtracks" || selected.startsWith("sound:")) {
|
||||
if (selected == "games" || selected.startsWith("app:")) {
|
||||
LibraryPage(s, a, selected, onSelect, modifier)
|
||||
return
|
||||
}
|
||||
@@ -273,10 +270,6 @@ private fun Content(
|
||||
DesktopPage(s, a, modifier, onSelect)
|
||||
return
|
||||
}
|
||||
if (selected == NavTabs.MORE) {
|
||||
MorePage(s, a, onSelect, modifier.padding(horizontal = padH).padding(top = padV))
|
||||
return
|
||||
}
|
||||
if (selected == "agent") {
|
||||
AgentPage(modifier.padding(horizontal = padH).padding(top = padV))
|
||||
return
|
||||
|
||||
@@ -51,7 +51,6 @@ import androidx.compose.material.icons.outlined.AutoAwesome
|
||||
import androidx.compose.material.icons.outlined.DesktopWindows
|
||||
import androidx.compose.material.icons.outlined.Layers
|
||||
import androidx.compose.material.icons.outlined.LocalMall
|
||||
import androidx.compose.material.icons.outlined.MoreHoriz
|
||||
import androidx.compose.material.icons.outlined.SportsEsports
|
||||
import androidx.compose.material.icons.outlined.Storefront
|
||||
import androidx.compose.material.icons.outlined.SystemUpdate
|
||||
@@ -106,16 +105,13 @@ internal fun BottomBar(
|
||||
val bounds = remember { androidx.compose.runtime.mutableStateMapOf<String, androidx.compose.ui.geometry.Rect>() }
|
||||
val tint = androidx.compose.runtime.rememberUpdatedState(LocalPalette.current.signal)
|
||||
val content = remember { arrayOfNulls<LayoutCoordinates>(1) }
|
||||
val barContext = LocalContext.current
|
||||
remember { RailLabels.load(barContext) }
|
||||
val iconOnly = !RailLabels.shown
|
||||
Row(modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surface), verticalAlignment = Alignment.CenterVertically) {
|
||||
BoxWithConstraints(Modifier.weight(1f)) {
|
||||
val itemWidth = (maxWidth / keys.size).coerceIn(56.dp, 88.dp)
|
||||
Box(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).onPlaced { content[0] = it }) {
|
||||
if (shown in keys) ChipGlide(keys.indexOf(shown), bounds[shown], tint, GlideAxis.Horizontal, corner = 14.dp, fill = 0.14f, outline = 0f)
|
||||
Row(Modifier.selectableGroup().padding(vertical = 4.dp), horizontalArrangement = Arrangement.Center) {
|
||||
NavigationItems(s, shown, compact = true, iconOnly = iconOnly, height = if (iconOnly) 48.dp else 56.dp, width = itemWidth,
|
||||
NavigationItems(s, shown, compact = true, iconOnly = false, height = 56.dp, width = itemWidth,
|
||||
place = { key -> Modifier.onGloballyPositioned { item -> content[0]?.let { bounds[key] = it.localBoundingBoxOf(item) }; Hops.railBounds[key] = item.boundsInRoot() } },
|
||||
onSelect = onSelect, onFocusSelect = onFocusSelect)
|
||||
}
|
||||
@@ -125,7 +121,15 @@ internal fun BottomBar(
|
||||
}
|
||||
}
|
||||
|
||||
internal fun navigationKeys(s: FrontEndState) = NavTabs.bar(s)
|
||||
internal fun navigationKeys(s: FrontEndState) = buildList {
|
||||
add("steam"); add("games")
|
||||
if (s.gameStoresEnabled) add("stores")
|
||||
add("desktop")
|
||||
if (com.droiddeck.launcher.agent.AgentTab.visible) add("agent")
|
||||
add("components")
|
||||
if (s.isHomeApp) add("android-apps")
|
||||
add("setup"); add("updates")
|
||||
}
|
||||
|
||||
internal object RailLabels {
|
||||
var shown by mutableStateOf(true)
|
||||
@@ -193,33 +197,18 @@ 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
|
||||
"soundtracks" -> R.string.rail_music to SoundtrackIcon
|
||||
"stores" -> R.string.rail_stores to Icons.Outlined.LocalMall
|
||||
"desktop" -> R.string.rail_desktop to Icons.Outlined.DesktopWindows
|
||||
"components" -> R.string.rail_components to Icons.Outlined.Layers
|
||||
"agent" -> R.string.rail_agent to Icons.Outlined.AutoAwesome
|
||||
"android-apps" -> R.string.rail_apps to Icons.Outlined.Apps
|
||||
"setup" -> R.string.rail_setup to Icons.Outlined.Tune
|
||||
NavTabs.MORE -> R.string.rail_more to Icons.Outlined.MoreHoriz
|
||||
else -> R.string.rail_updates to Icons.Outlined.SystemUpdate
|
||||
}
|
||||
|
||||
internal fun setupNeedsAttention(s: FrontEndState): Boolean = !s.ready || (s.available != null && s.available != s.installed) ||
|
||||
PhantomProcessLimit.blocksSteam(s.phantomProcessStatus) || com.droiddeck.launcher.sync.Syncthing.needsAttention
|
||||
|
||||
internal fun railBadge(s: FrontEndState, key: String, setupNeedsAttention: Boolean = setupNeedsAttention(s)): Boolean = when (key) {
|
||||
"setup" -> setupNeedsAttention
|
||||
"updates" -> s.updates.hasUpdate
|
||||
NavTabs.MORE -> NavTabs.more(s).any { it != NavTabs.MORE && railBadge(s, it, setupNeedsAttention) }
|
||||
else -> false
|
||||
}
|
||||
|
||||
internal fun railCount(s: FrontEndState, key: String): Int = when (key) {
|
||||
"stores" -> s.storeDownloadsActive
|
||||
NavTabs.MORE -> if ("stores" in NavTabs.more(s)) s.storeDownloadsActive else 0
|
||||
else -> 0
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun NavigationItems(
|
||||
s: FrontEndState, shown: String, compact: Boolean, iconOnly: Boolean, height: Dp, width: Dp,
|
||||
@@ -230,8 +219,8 @@ private fun NavigationItems(
|
||||
val (label, icon) = railLabelIcon(key)
|
||||
key(key) {
|
||||
RailItem(stringResource(label), icon, key, shown == key, compact, iconOnly, height, width,
|
||||
badge = railBadge(s, key, setupNeedsAttention),
|
||||
count = railCount(s, key),
|
||||
badge = (key == "setup" && setupNeedsAttention) || (key == "updates" && s.updates.hasUpdate),
|
||||
count = if (key == "stores") s.storeDownloadsActive else 0,
|
||||
place = place, onFocus = { onFocusSelect(key) }) { onSelect(key) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,10 +181,6 @@ class FrontEndState(
|
||||
val lowStorageWarning: Boolean = true,
|
||||
val launcherIcon: String = com.droiddeck.launcher.LauncherIcon.DARK,
|
||||
val gameStoresEnabled: Boolean = true,
|
||||
val soundtracksEnabled: Boolean = true,
|
||||
val soundtracksIngame: Boolean = false,
|
||||
val soundtracks: List<Library.SteamGame> = emptyList(),
|
||||
val soundtracksLoaded: Boolean = true,
|
||||
val gameStoresSpeedTier: String = "fast",
|
||||
val navigate: String? = null,
|
||||
val addedGamesArt: Boolean = true,
|
||||
@@ -289,11 +285,6 @@ class FrontEndActions(
|
||||
val onDownloadPrefix: (String) -> Unit = {},
|
||||
val onDownloadProxy: (String) -> Unit = {},
|
||||
val onGameStoresEnabled: (Boolean) -> Unit = {},
|
||||
val onSoundtracksEnabled: (Boolean) -> Unit = {},
|
||||
val onSoundtracksIngame: (Boolean) -> Unit = {},
|
||||
val onSoundtrackAdded: (java.io.File) -> Unit = {},
|
||||
val onSoundtracksChanged: () -> Unit = {},
|
||||
val onSoundtrackRemoved: (Library.SteamGame) -> Unit = {},
|
||||
val onGameStoresSpeedTier: (String) -> Unit = {},
|
||||
val onNavigated: () -> Unit = {},
|
||||
val onStoresShowMature: (Boolean) -> Unit = {},
|
||||
@@ -468,9 +459,7 @@ fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () -
|
||||
@OptIn(ExperimentalComposeUiApi::class)
|
||||
@Composable
|
||||
private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)?, frontFocus: FrontFocus) {
|
||||
var selected by rememberSaveable {
|
||||
mutableStateOf(if (s.shortcutPicker) "games" else if (NavTabs.place(s, "steam") == TabPlace.HIDDEN) navigationKeys(s).first { it != "components" } else "steam")
|
||||
}
|
||||
var selected by rememberSaveable { mutableStateOf(if (s.shortcutPicker) "games" else "steam") }
|
||||
LaunchedEffect(s.shortcutPicker) { if (s.shortcutPicker) selected = "games" }
|
||||
LaunchedEffect(s.navigate) {
|
||||
val target = s.navigate ?: return@LaunchedEffect
|
||||
@@ -577,32 +566,20 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
) {
|
||||
selected = if (selected.startsWith("rom:")) "emu:" + selected.removePrefix("rom:").substringBefore(':') else "desktop"
|
||||
}
|
||||
val backToMore = s.pageKey == null && Hops.origin == null && selected in NavTabs.more(s)
|
||||
BackHandler(enabled = !processSettingsPageVisible && backToMore) {
|
||||
selected = NavTabs.MORE
|
||||
}
|
||||
LaunchedEffect(s.isHomeApp) { if (!s.isHomeApp && selected == "android-apps") selected = "steam" }
|
||||
LaunchedEffect(s.soundtracksEnabled) {
|
||||
if (!s.soundtracksEnabled && (selected == "soundtracks" || selected.startsWith("sound:"))) selected = "games"
|
||||
}
|
||||
LaunchedEffect(s.steamGames.isEmpty(), s.soundtracks, s.soundtracksLoaded) {
|
||||
if (s.steamGames.isEmpty() && selected.startsWith("app:")) {
|
||||
val id = GameRef.parse(selected).appId
|
||||
if (id != null && s.soundtracks.none { it.appId == id } && s.soundtracksLoaded) selected = "games"
|
||||
}
|
||||
LaunchedEffect(s.steamGames.isEmpty()) {
|
||||
if (s.steamGames.isEmpty() && selected.startsWith("app:") && GameRef.parse(selected).appId != null) selected = "games"
|
||||
}
|
||||
remember { Motion.refresh(ctx); true }
|
||||
|
||||
val openTab = when {
|
||||
val railSelection = when {
|
||||
Hops.origin != null && s.pageKey == Hops.origin?.page -> Hops.origin!!.dest
|
||||
s.pageKey == "performance" -> "steam"
|
||||
s.pageKey == "controller-mapping" -> "setup"
|
||||
selected.startsWith("app:") -> "games"
|
||||
selected.startsWith("sound:") -> "soundtracks"
|
||||
selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:") || selected == "store" -> "desktop"
|
||||
else -> s.pageKey ?: selected
|
||||
}
|
||||
val railSelection = if (openTab in NavTabs.more(s)) NavTabs.MORE else openTab
|
||||
val railSelectionNow = androidx.compose.runtime.rememberUpdatedState(railSelection)
|
||||
var railPicks by remember { mutableStateOf(0) }
|
||||
val showRailPage: (String, Boolean) -> Unit = { key, focusContent ->
|
||||
@@ -711,14 +688,14 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
val r = Hops.restore ?: return@LaunchedEffect
|
||||
if (r.surface == HOP_SURFACE_SHEET) return@LaunchedEffect
|
||||
Hops.restore = null
|
||||
if (r.rail != selected && !(r.rail == "games" && selected.startsWith("app:")) && !(r.rail == "soundtracks" && selected.startsWith("sound:"))) selected = r.rail
|
||||
if (r.rail != selected && !(r.rail == "games" && selected.startsWith("app:"))) selected = r.rail
|
||||
kotlinx.coroutines.delay(Motion.ms(PAGE_EXIT_MS).toLong())
|
||||
if (inputModeManager.inputMode != InputMode.Keyboard) return@LaunchedEffect
|
||||
frontFocus.last = r.control
|
||||
focusWithinFrames({ frontFocus.last == r.control && anyFocused }) { frontFocus.items[r.control] ?: frontFocus.paneEntry() }
|
||||
}
|
||||
var screenAt by remember { mutableStateOf(Offset.Zero) }
|
||||
if (s.dualScreen) DualPanelPublisher(s, railSelection, openTab, { key ->
|
||||
if (s.dualScreen) DualPanelPublisher(s, railSelection, { key ->
|
||||
if (processSettingsPageVisible) return@DualPanelPublisher
|
||||
if (inputModeManager.inputMode != InputMode.Keyboard) inputModeManager.requestInputMode(InputMode.Keyboard)
|
||||
focusManager.clearFocus(force = true)
|
||||
@@ -841,7 +818,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
)
|
||||
}
|
||||
}
|
||||
val hasBackTarget = backToMore || (s.pageKey != null && page != null) ||
|
||||
val hasBackTarget = (s.pageKey != null && page != null) ||
|
||||
(s.pageKey == null && Hops.origin?.page == selected) ||
|
||||
((s.pageKey == null || page == null) &&
|
||||
(selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:") || selected == "store"))
|
||||
|
||||
@@ -91,7 +91,6 @@ private const val LAUNCHER_TAB = 2
|
||||
|
||||
internal object SetupTabs {
|
||||
var openLauncher = false
|
||||
var focusTabs = false
|
||||
var openOverview = false
|
||||
}
|
||||
private const val GLASSES_TAB = 6
|
||||
@@ -147,7 +146,6 @@ internal fun SetupPanel(
|
||||
) {
|
||||
val host = rememberMenuHost()
|
||||
val ctx = LocalContext.current
|
||||
var hideHomeFromRecents by remember { mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.hideHomeFromRecents(ctx)) }
|
||||
var processLimitBusy by remember { mutableStateOf(false) }
|
||||
var processLimitMessage by remember { mutableStateOf<String?>(null) }
|
||||
val setProcessLimit: (Boolean) -> Unit = { enabled ->
|
||||
@@ -458,9 +456,8 @@ internal fun SetupPanel(
|
||||
remember { RailLabels.load(railContext) }
|
||||
ToggleRow(host, "rail-labels", stringResource(R.string.setup_rail_labels), stringResource(R.string.setup_rail_labels_hint), RailLabels.shown) { RailLabels.set(railContext, it) }
|
||||
LanguageRow(host, s.language, a.onLanguage)
|
||||
if (s.soundtracksEnabled) ToggleRow(host, "soundtracks-ingame", stringResource(R.string.setup_soundtracks_ingame), stringResource(R.string.setup_soundtracks_ingame_hint), s.soundtracksIngame, onChange = a.onSoundtracksIngame)
|
||||
ToggleRow(host, "show-stores", stringResource(R.string.setup_stores), null, s.gameStoresEnabled, onChange = a.onGameStoresEnabled)
|
||||
}
|
||||
TabsSettingsGroup(host, s, a)
|
||||
}
|
||||
val device: @Composable () -> Unit = {
|
||||
SettingsGroup(stringResource(R.string.setup_group_device)) {
|
||||
@@ -471,13 +468,6 @@ internal fun SetupPanel(
|
||||
) { a.onHomeScreen(it) }
|
||||
if (s.homeScreenEnabled) {
|
||||
ActionRow(stringResource(R.string.setup_default_home), s.defaultHomeLabel ?: stringResource(R.string.setup_choose_home), stringResource(R.string.setup_choose), a.onHomeApp)
|
||||
ToggleRow(
|
||||
host, "hide-home-from-recents", stringResource(R.string.setup_hide_home_from_recents),
|
||||
stringResource(R.string.setup_hide_home_from_recents_hint), hideHomeFromRecents,
|
||||
) { hidden ->
|
||||
hideHomeFromRecents = hidden
|
||||
com.droiddeck.launcher.core.AppUiPrefs.setHideHomeFromRecents(ctx, hidden)
|
||||
}
|
||||
ChoiceRow(
|
||||
host, "home-page", stringResource(R.string.setup_home_page), stringResource(R.string.setup_home_page_hint),
|
||||
com.droiddeck.launcher.core.AppUiPrefs.homePageOptions.map { (value, label) -> value to stringResource(label) },
|
||||
@@ -606,6 +596,9 @@ internal fun SetupPanel(
|
||||
ToggleRow(host, "agent-commands", stringResource(R.string.setup_agent_commands), null, s.agentCommands) { a.onAgentCommands() }
|
||||
if (com.droiddeck.launcher.agent.AgentHost.available) {
|
||||
val agentContext = androidx.compose.ui.platform.LocalContext.current
|
||||
ToggleRow(host, "agent-tab", stringResource(R.string.setup_agent_tab), null, com.droiddeck.launcher.agent.AgentTab.shown) {
|
||||
com.droiddeck.launcher.agent.AgentTab.set(agentContext, it)
|
||||
}
|
||||
ToggleRow(host, "agent-pet", stringResource(R.string.setup_agent_pet), stringResource(R.string.setup_agent_pet_hint), AgentPet.enabled) {
|
||||
AgentPet.set(agentContext, it)
|
||||
}
|
||||
@@ -925,37 +918,12 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron
|
||||
val custom = stringResource(R.string.comp_game_fex_custom)
|
||||
val customSync = stringResource(R.string.game_sync_custom)
|
||||
val resetDone = stringResource(R.string.comp_game_reset_done, game.name)
|
||||
val resKey = "game-settings-res"
|
||||
val resolution = current?.let { com.droiddeck.launcher.core.GameEnvironment.gameResolution(it, scope) }
|
||||
val screen = remember { com.droiddeck.launcher.session.SessionDisplay.screenSize(com.droiddeck.launcher.session.SessionDisplay.panelSize(appContext)) }
|
||||
val matchScreen = stringResource(R.string.display_match_screen, screen.first, screen.second)
|
||||
val scaledLabels = com.droiddeck.launcher.core.GameResolution.scales.associateWith {
|
||||
stringResource(R.string.display_follow_screen_scaled, com.droiddeck.launcher.core.GameResolution.formatScale(it))
|
||||
}
|
||||
fun sizeLabel(size: Pair<Int, Int>) = "${size.first}×${size.second} · ${com.droiddeck.launcher.core.GameResolution.aspectLabel(size.first, size.second)}"
|
||||
fun resolutionLabel(choice: com.droiddeck.launcher.core.GameResolution.Choice?): String = when (choice) {
|
||||
null -> matchScreen
|
||||
is com.droiddeck.launcher.core.GameResolution.Scaled -> (scaledLabels[choice.scale]
|
||||
?: "÷" + com.droiddeck.launcher.core.GameResolution.formatScale(choice.scale)) +
|
||||
" · " + sizeLabel(com.droiddeck.launcher.core.GameResolution.resolve(choice, screen))
|
||||
is com.droiddeck.launcher.core.GameResolution.Fixed -> sizeLabel(choice.width to choice.height)
|
||||
}
|
||||
fun pickResolution(choice: com.droiddeck.launcher.core.GameResolution.Choice?) {
|
||||
host.open = key
|
||||
save { com.droiddeck.launcher.session.GameEnvironmentStore.setGameResolution(it, scope, choice) }
|
||||
}
|
||||
var editResolution by remember(scope) { mutableStateOf(false) }
|
||||
AnchoredMenu(host.open == key, onDismiss = { if (host.open == key) host.open = null }, title = stringResource(R.string.game_settings_menu_title, game.name)) { first ->
|
||||
MenuItem(stringResource(R.string.game_no_steam_title), checked = noSteam, enabled = ready,
|
||||
detail = stringResource(R.string.game_no_steam_detail), focusRequester = first) {
|
||||
val on = !noSteam
|
||||
save { com.droiddeck.launcher.session.GameEnvironmentStore.setGameNoSteam(it, scope, on) }
|
||||
}
|
||||
if (noSteam) MenuItem(
|
||||
stringResource(R.string.game_res_title), checked = false, enabled = ready,
|
||||
detail = resolutionLabel(resolution),
|
||||
trailing = { Text("›", fontSize = 16.sp, color = colors.onSurfaceVariant) },
|
||||
) { host.open = resKey }
|
||||
if (!launcher) {
|
||||
val chosen = com.droiddeck.launcher.core.FexPreset.all.firstOrNull { it.id == fex }
|
||||
MenuItem(
|
||||
@@ -992,45 +960,6 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron
|
||||
}
|
||||
}
|
||||
}
|
||||
AnchoredMenu(host.open == resKey, onDismiss = { if (host.open == resKey) host.open = null }, title = stringResource(R.string.game_res_title)) { first ->
|
||||
MenuItem(matchScreen, checked = resolution == null, enabled = ready, focusRequester = first) { pickResolution(null) }
|
||||
com.droiddeck.launcher.core.GameResolution.scales.forEach { scale ->
|
||||
val choice = com.droiddeck.launcher.core.GameResolution.Scaled(scale)
|
||||
MenuItem(scaledLabels.getValue(scale), checked = resolution == choice, enabled = ready,
|
||||
detail = sizeLabel(com.droiddeck.launcher.core.GameResolution.resolve(choice, screen))) { pickResolution(choice) }
|
||||
}
|
||||
com.droiddeck.launcher.core.GameResolution.aspects.forEach { aspect ->
|
||||
val sizes = com.droiddeck.launcher.core.GameResolution.sizesFor(aspect, screen)
|
||||
MenuItem(aspect.label, checked = resolution in aspect.sizes, enabled = ready,
|
||||
detail = sizes.joinToString(" · ") { "${it.width}×${it.height}" },
|
||||
trailing = { Text("›", fontSize = 16.sp, color = colors.onSurfaceVariant) },
|
||||
) { host.open = "$resKey-${aspect.label}" }
|
||||
}
|
||||
val fixed = resolution as? com.droiddeck.launcher.core.GameResolution.Fixed
|
||||
val customValue = fixed?.takeIf { f -> com.droiddeck.launcher.core.GameResolution.aspects.none { f in it.sizes } }
|
||||
MenuItem(
|
||||
if (customValue == null) stringResource(R.string.mode_res_custom) else stringResource(R.string.mode_res_custom_value, customValue.width, customValue.height),
|
||||
checked = customValue != null, enabled = ready,
|
||||
detail = customValue?.let { com.droiddeck.launcher.core.GameResolution.aspectLabel(it.width, it.height) },
|
||||
) { editResolution = true }
|
||||
}
|
||||
com.droiddeck.launcher.core.GameResolution.aspects.forEach { aspect ->
|
||||
val aspectKey = "$resKey-${aspect.label}"
|
||||
AnchoredMenu(host.open == aspectKey, onDismiss = { if (host.open == aspectKey) host.open = null }, title = aspect.label) { first ->
|
||||
com.droiddeck.launcher.core.GameResolution.sizesFor(aspect, screen).forEachIndexed { index, size ->
|
||||
MenuItem("${size.width}×${size.height}", checked = resolution == size, enabled = ready,
|
||||
focusRequester = if (index == 0) first else null) { pickResolution(size) }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (editResolution) CustomResolutionDialog(
|
||||
(resolution as? com.droiddeck.launcher.core.GameResolution.Fixed)?.let { it.width to it.height },
|
||||
onSave = { value ->
|
||||
editResolution = false
|
||||
pickResolution(com.droiddeck.launcher.core.GameResolution.Fixed(value.first, value.second))
|
||||
},
|
||||
onDismiss = { editResolution = false },
|
||||
)
|
||||
AnchoredMenu(host.open == fexKey, onDismiss = { if (host.open == fexKey) host.open = null }, title = stringResource(R.string.fex_preset_title)) { first ->
|
||||
MenuItem(useDefault, checked = fex == null, enabled = ready, detail = stringResource(generalFex.label), focusRequester = first) {
|
||||
host.open = key
|
||||
|
||||
@@ -35,8 +35,6 @@ import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Favorite
|
||||
import androidx.compose.material.icons.filled.FavoriteBorder
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material.icons.outlined.Delete
|
||||
import androidx.compose.material.icons.outlined.Edit
|
||||
@@ -150,7 +148,7 @@ internal fun GameDetail(
|
||||
val narrow = LocalNarrowPane.current
|
||||
val stacked = narrow || LocalConfiguration.current.screenWidthDp < 700
|
||||
val ref = remember(key) { GameRef.parse(key) }
|
||||
val games = s.steamGames + rememberXboxCloudRows(s) + if (s.soundtracksEnabled) emptyList() else s.soundtracks
|
||||
val games = s.steamGames + rememberXboxCloudRows(s)
|
||||
val found = ref.game(games)
|
||||
val known = remember(key) { arrayOfNulls<Pair<Store, String>>(1) }
|
||||
val store = ref.store ?: Store.byId(found?.source) ?: known[0]?.first
|
||||
@@ -167,7 +165,6 @@ internal fun GameDetail(
|
||||
if (nothing) return
|
||||
val source = game?.source ?: store?.id ?: Library.SOURCE_STEAM
|
||||
val title = game?.name ?: item?.title ?: installed?.sidecar?.title ?: id.orEmpty()
|
||||
val favoriteKey = if (store != null && id != null) "${store.id}:$id" else game?.let { GameRef.key(it) } ?: key
|
||||
val scores = if (source != Library.ADDED) rememberGameScores(title.takeIf { it.isNotBlank() && it != id }) else null
|
||||
val achievements = remember(store, id, item?.accessible, installed) {
|
||||
when {
|
||||
@@ -228,7 +225,6 @@ internal fun GameDetail(
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
if (installed != null && installed.sidecar.store == Store.ITCH) ItchCheckButton(installed)
|
||||
if (installed != null && installed.sidecar.store == Store.GAMEJOLT) GameJoltCheckButton(installed)
|
||||
FavoriteButton(favoriteKey)
|
||||
RemoveButton(title, game, installed, a)
|
||||
}
|
||||
}
|
||||
@@ -284,7 +280,7 @@ internal fun GameDetail(
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SourceBadge(source: String) {
|
||||
private fun SourceBadge(source: String) {
|
||||
val c = sourceColours(source)
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(7.dp),
|
||||
@@ -404,6 +400,7 @@ internal fun GameActions(
|
||||
val failed = rawDownload?.takeIf { it.state == DownloadState.FAILED }
|
||||
val cloud = game?.library == Library.XBOX_CLOUD && installed == null
|
||||
val downloadBytes = catalogSize(item)
|
||||
val launchSupported = store != Store.ROCKSTAR || com.droiddeck.launcher.stores.rockstar.RockstarLaunch.supports(id)
|
||||
Actions {
|
||||
when {
|
||||
s.shortcutPicker && game != null -> {
|
||||
@@ -415,8 +412,8 @@ internal fun GameActions(
|
||||
val xboxBusy = store == Store.XBOX && id != null && XboxContent.busy(id)
|
||||
val preparing = (game?.launchKey ?: storeKey)?.let { it in s.preparingGames } == true
|
||||
PrimaryButton(
|
||||
stringResource(if (preparing) R.string.store_starting else R.string.stores_play),
|
||||
enabled = !s.busy && !preparing && gone == null && download == null && !xboxBusy && (store != Store.GOG || installed?.sidecar?.isInstalled != false),
|
||||
stringResource(if (!launchSupported) R.string.stores_rockstar_launch_unavailable else if (preparing) R.string.store_starting else R.string.stores_play),
|
||||
enabled = launchSupported && !s.busy && !preparing && gone == null && download == null && !xboxBusy && (store != Store.GOG || installed?.sidecar?.isInstalled != false),
|
||||
main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn,
|
||||
) {
|
||||
if (game != null) a.onSteamGame(game) else if (store != null && id != null) launchStoreGame(store, id, s, a)
|
||||
@@ -578,13 +575,13 @@ private fun buyLabel(item: CatalogItem): String = when {
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun FileButtons(game: Library.SteamGame, a: FrontEndActions) {
|
||||
private fun FileButtons(game: Library.SteamGame, a: FrontEndActions) {
|
||||
game.gameFiles?.takeIf { it.isDirectory }?.let { dir -> SecondaryButton(stringResource(R.string.games_files), compact = true) { a.onBrowseFiles(dir) } }
|
||||
game.protonPrefix?.takeIf { it.isDirectory }?.let { dir -> SecondaryButton(stringResource(R.string.games_prefix), compact = true) { a.onBrowseFiles(dir) } }
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun GameShortcutMenu(g: Library.SteamGame, a: FrontEndActions) {
|
||||
private fun GameShortcutMenu(g: Library.SteamGame, a: FrontEndActions) {
|
||||
var open by remember(g.gameId) { mutableStateOf(false) }
|
||||
Box {
|
||||
SecondaryButton(stringResource(R.string.game_shortcut), compact = true) { open = !open }
|
||||
@@ -597,7 +594,7 @@ internal fun GameShortcutMenu(g: Library.SteamGame, a: FrontEndActions) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun rememberEditArt(g: Library.SteamGame): (() -> Unit)? {
|
||||
private fun rememberEditArt(g: Library.SteamGame): (() -> Unit)? {
|
||||
val ctx = LocalContext.current
|
||||
val folder = g.gameFiles
|
||||
return when {
|
||||
@@ -611,7 +608,7 @@ internal fun rememberEditArt(g: Library.SteamGame): (() -> Unit)? {
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun EditArtButton(g: Library.SteamGame) {
|
||||
private fun EditArtButton(g: Library.SteamGame) {
|
||||
val open = rememberEditArt(g) ?: return
|
||||
IconAction(Icons.Outlined.Edit, stringResource(R.string.game_edit_art), "game:edit", onClick = open)
|
||||
}
|
||||
@@ -636,7 +633,7 @@ private fun GameMoreMenu(g: Library.SteamGame, a: FrontEndActions) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun IconAction(icon: androidx.compose.ui.graphics.vector.ImageVector, label: String, id: String, danger: Boolean = false, enabled: Boolean = true, frosted: Boolean = false, tint: Color? = null, onClick: () -> Unit) {
|
||||
internal fun IconAction(icon: androidx.compose.ui.graphics.vector.ImageVector, label: String, id: String, danger: Boolean = false, enabled: Boolean = true, frosted: Boolean = false, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pill = LocalPillButtons.current
|
||||
val shape = if (pill) CircleShape else Shape12
|
||||
@@ -661,26 +658,14 @@ internal fun IconAction(icon: androidx.compose.ui.graphics.vector.ImageVector, l
|
||||
.controllerConfirm(enabled = enabled, onClick = onClick)
|
||||
.semantics { contentDescription = label },
|
||||
) {
|
||||
Icon(icon, contentDescription = null, tint = tint ?: if (danger && hot) colors.error else if (danger && !pill) Color.White else colors.onBackground, modifier = Modifier.size(18.dp))
|
||||
Icon(icon, contentDescription = null, tint = if (danger && hot) colors.error else if (danger && !pill) Color.White else colors.onBackground, modifier = Modifier.size(18.dp))
|
||||
}
|
||||
}
|
||||
if (frosted) Box(Modifier.glass(CircleShape)) { button() } else button()
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun FavoriteButton(key: String) {
|
||||
val ctx = LocalContext.current
|
||||
remember { LibraryFavorites.load(ctx) }
|
||||
val on = key in LibraryFavorites.keys
|
||||
IconAction(
|
||||
if (on) Icons.Filled.Favorite else Icons.Filled.FavoriteBorder,
|
||||
stringResource(if (on) R.string.fm_favorite_remove else R.string.fm_favorite_add),
|
||||
"game:favorite", frosted = true, tint = if (on) FavoritesColours.dot else null,
|
||||
) { LibraryFavorites.toggle(ctx, key) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun RemoveButton(title: String, game: Library.SteamGame?, installed: InstalledStoreGame?, a: FrontEndActions) {
|
||||
private fun RemoveButton(title: String, game: Library.SteamGame?, installed: InstalledStoreGame?, a: FrontEndActions) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
if ((installed?.sidecar?.store?.id ?: game?.source) == Store.BATTLENET.id && installed?.sidecar?.id?.let(BattleNetInstall::product) == null) return
|
||||
|
||||
@@ -38,7 +38,6 @@ import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
|
||||
import androidx.compose.ui.graphics.drawscope.DrawScope
|
||||
import androidx.compose.ui.graphics.drawscope.clipRect
|
||||
import androidx.compose.ui.graphics.drawscope.translate
|
||||
import androidx.compose.ui.draw.blur
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.graphics.luminance
|
||||
import androidx.compose.ui.graphics.painter.Painter
|
||||
@@ -148,7 +147,6 @@ internal fun GameBackdrop(
|
||||
fadeTop: Boolean,
|
||||
modifier: Modifier = Modifier,
|
||||
onArtPlaced: (androidx.compose.ui.geometry.Rect?) -> Unit = {},
|
||||
artBlur: androidx.compose.ui.unit.Dp = 0.dp,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
val ctx = LocalContext.current
|
||||
@@ -180,13 +178,13 @@ internal fun GameBackdrop(
|
||||
glass.fadeBottom(this, size)
|
||||
},
|
||||
)
|
||||
if (art != null) ArtLayer(art, ambient ?: art, fadeTop, artBlur, onArtPlaced)
|
||||
if (art != null) ArtLayer(art, ambient ?: art, fadeTop, onArtPlaced)
|
||||
CompositionLocalProvider(LocalGlass provides glass) { content() }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ArtLayer(model: Any?, sample: Any?, fadeTop: Boolean, blur: androidx.compose.ui.unit.Dp, onPlaced: (androidx.compose.ui.geometry.Rect?) -> Unit) {
|
||||
private fun ArtLayer(model: Any?, sample: Any?, fadeTop: Boolean, onPlaced: (androidx.compose.ui.geometry.Rect?) -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val light = colors.background.luminance() > 0.5f
|
||||
val pale = ((rememberArtBrightness(sample) - 0.28f) / 0.5f).coerceIn(0f, 1f)
|
||||
@@ -210,7 +208,7 @@ private fun ArtLayer(model: Any?, sample: Any?, fadeTop: Boolean, blur: androidx
|
||||
model = model, contentDescription = null, contentScale = ContentScale.Crop,
|
||||
alignment = BiasAlignment(0.45f, -0.35f),
|
||||
colorFilter = artFilter,
|
||||
modifier = Modifier.matchParentSize().then(if (blur > 0.dp) Modifier.blur(blur) else Modifier),
|
||||
modifier = Modifier.matchParentSize(),
|
||||
)
|
||||
Box(
|
||||
Modifier.matchParentSize().drawBehind {
|
||||
|
||||
@@ -1,389 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.view.KeyEvent
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.animation.core.LinearEasing
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.gestures.awaitEachGesture
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.gestures.awaitFirstDown
|
||||
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.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.DragHandle
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableFloatStateOf
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.withFrameNanos
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusProperties
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.input.InputMode
|
||||
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||
import androidx.compose.ui.input.pointer.PointerEventPass
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.material3.LocalTextStyle
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalInputModeManager
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.PlatformTextStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.zIndex
|
||||
import com.droiddeck.launcher.R
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
private val ROW_HEIGHT = 44.dp
|
||||
private val HANDLE_WIDTH = 40.dp
|
||||
private const val RESET_HOLD_MS = 5_000
|
||||
private const val TAP_HOLD_MS = 400
|
||||
private val HINT_LABEL_WIDTH = 92.dp
|
||||
private val HINT_KEY_SIZE = 18.dp
|
||||
private val HINT_GAP = 8.dp
|
||||
private val HINT_LABEL_MIN = 24.dp
|
||||
private val HINT_ROOM = HINT_LABEL_MIN + HINT_KEY_SIZE + HINT_GAP
|
||||
|
||||
@Composable
|
||||
internal fun ResetHold(held: Boolean, onFire: () -> Unit): Float {
|
||||
val fill by animateFloatAsState(
|
||||
if (held) 1f else 0f,
|
||||
if (held) tween(RESET_HOLD_MS, easing = LinearEasing) else tween(120),
|
||||
label = "resetHold",
|
||||
)
|
||||
LaunchedEffect(held) {
|
||||
if (!held) return@LaunchedEffect
|
||||
delay(RESET_HOLD_MS.toLong())
|
||||
onFire()
|
||||
}
|
||||
return fill
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun HudKeyHints(grabbed: String?, resetFill: Float) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.End,
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
KeyHint("X", stringResource(R.string.hud_hint_reset), resetFill)
|
||||
KeyHint("Y", stringResource(if (grabbed != null) R.string.hud_hint_drop else R.string.hud_hint_grab))
|
||||
KeyHint("B", stringResource(R.string.hud_hint_save))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun KeyHint(key: String, label: String, fill: Float = 0f) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(HINT_GAP),
|
||||
) {
|
||||
Text(
|
||||
label,
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 14.sp,
|
||||
textAlign = TextAlign.End,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 2,
|
||||
modifier = Modifier.widthIn(max = HINT_LABEL_WIDTH),
|
||||
)
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.size(HINT_KEY_SIZE).clip(RoundedCornerShape(5.dp))
|
||||
.background(
|
||||
if (fill > 0f) MaterialTheme.colorScheme.primary.copy(alpha = 0.15f + 0.55f * fill)
|
||||
else MaterialTheme.colorScheme.surfaceVariant,
|
||||
)
|
||||
.border(1.dp, MaterialTheme.colorScheme.outline, RoundedCornerShape(5.dp)),
|
||||
) {
|
||||
Text(
|
||||
key,
|
||||
fontSize = 10.sp,
|
||||
lineHeight = 10.sp,
|
||||
textAlign = TextAlign.Center,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
style = LocalTextStyle.current.copy(
|
||||
platformStyle = PlatformTextStyle(includeFontPadding = false),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
internal fun HudReadingsDialog(
|
||||
visible: List<String>,
|
||||
initialOrder: List<String>,
|
||||
initialOn: Map<String, Boolean>,
|
||||
onDismiss: () -> Unit,
|
||||
onSave: (Map<String, Boolean>, List<String>) -> Unit,
|
||||
onReset: () -> Unit,
|
||||
controller: Boolean = LocalInputModeManager.current.inputMode == InputMode.Keyboard,
|
||||
) {
|
||||
val order = remember { mutableStateListOf<String>().apply { addAll(initialOrder.filter { it in visible }) } }
|
||||
val enabled = remember { mutableStateMapOf<String, Boolean>() }
|
||||
remember(initialOn) { for (key in initialOrder) enabled[key] = initialOn[key] == true; true }
|
||||
val merged = {
|
||||
val moved = order.toList()
|
||||
var i = 0
|
||||
initialOrder.map { if (it in visible) moved[i++] else it }
|
||||
}
|
||||
val shown = rememberShown { onDismiss() }
|
||||
val close = { shown.targetState = false }
|
||||
val save = { onSave(enabled.toMap(), merged()); close() }
|
||||
val restore = { onReset(); close() }
|
||||
val rowPx = with(LocalDensity.current) { ROW_HEIGHT.toPx() }
|
||||
var pad by remember { mutableStateOf(controller) }
|
||||
var yHeld by remember { mutableStateOf(false) }
|
||||
var yLong by remember { mutableStateOf(false) }
|
||||
var yStartedGrab by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(yHeld) {
|
||||
if (!yHeld) return@LaunchedEffect
|
||||
delay(TAP_HOLD_MS.toLong())
|
||||
yLong = true
|
||||
}
|
||||
|
||||
var resetHeld by remember { mutableStateOf(false) }
|
||||
val resetFill = ResetHold(resetHeld, restore)
|
||||
|
||||
var dragging by remember { mutableStateOf(-1) }
|
||||
var dragOffset by remember { mutableFloatStateOf(0f) }
|
||||
|
||||
val panelFocus = remember { FocusRequester() }
|
||||
val firstKey = remember { order.firstOrNull() }
|
||||
val firstFocus = remember { FocusRequester() }
|
||||
LaunchedEffect(Unit) {
|
||||
runCatching { panelFocus.requestFocus() }
|
||||
repeat(30) {
|
||||
if (runCatching { firstFocus.requestFocus() }.isSuccess) return@LaunchedEffect
|
||||
withFrameNanos { }
|
||||
}
|
||||
}
|
||||
var focusedKey by remember { mutableStateOf<String?>(null) }
|
||||
var grabbed by remember { mutableStateOf<String?>(null) }
|
||||
val before = remember { mutableStateListOf<String>() }
|
||||
val grab = {
|
||||
val target = focusedKey ?: order.firstOrNull()
|
||||
if (target != null && grabbed == null && dragging < 0) {
|
||||
before.clear()
|
||||
before.addAll(order)
|
||||
grabbed = target
|
||||
}
|
||||
}
|
||||
val cancel = {
|
||||
val held = grabbed
|
||||
if (held != null) {
|
||||
order.clear()
|
||||
order.addAll(before)
|
||||
grabbed = null
|
||||
}
|
||||
}
|
||||
|
||||
AppDialog(
|
||||
shown, close, "hudReadings", wide = false, scrollable = false,
|
||||
modifier = Modifier.fillMaxHeight(),
|
||||
back = { if (grabbed != null) cancel() else if (pad) save() else close() },
|
||||
side = if (pad) {
|
||||
{ HudKeyHints(grabbed, resetFill) }
|
||||
} else {
|
||||
null
|
||||
},
|
||||
sideRoom = HINT_ROOM,
|
||||
) {
|
||||
val state = rememberLazyListState()
|
||||
val scope = rememberCoroutineScope()
|
||||
val handlePx = with(LocalDensity.current) { HANDLE_WIDTH.toPx() }
|
||||
Column(
|
||||
Modifier.fillMaxWidth().weight(1f).focusRequester(panelFocus).focusable()
|
||||
.onPreviewKeyEvent { event ->
|
||||
val key = event.nativeKeyEvent
|
||||
val down = key.action == KeyEvent.ACTION_DOWN
|
||||
if (down) pad = true
|
||||
val first = down && key.repeatCount == 0
|
||||
val held = grabbed
|
||||
when {
|
||||
key.keyCode == KeyEvent.KEYCODE_BUTTON_Y -> {
|
||||
when {
|
||||
down && first -> {
|
||||
yHeld = true
|
||||
yLong = key.flags and KeyEvent.FLAG_LONG_PRESS != 0
|
||||
yStartedGrab = grabbed == null
|
||||
if (yStartedGrab) grab()
|
||||
}
|
||||
down -> if (key.repeatCount > 0) yLong = true
|
||||
else -> {
|
||||
val drop = grabbed != null && (!yStartedGrab || yLong)
|
||||
yHeld = false
|
||||
if (drop) grabbed = null
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
key.keyCode == KeyEvent.KEYCODE_BUTTON_X && pad -> {
|
||||
resetHeld = down
|
||||
true
|
||||
}
|
||||
key.keyCode == KeyEvent.KEYCODE_BUTTON_A ||
|
||||
key.keyCode == KeyEvent.KEYCODE_ENTER ||
|
||||
key.keyCode == KeyEvent.KEYCODE_SPACE -> {
|
||||
val target = focusedKey
|
||||
when {
|
||||
held != null -> {
|
||||
if (first) grabbed = null
|
||||
true
|
||||
}
|
||||
target == null -> false
|
||||
else -> {
|
||||
if (first) enabled[target] = !(enabled[target] == true)
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
held == null -> false
|
||||
key.keyCode == KeyEvent.KEYCODE_DPAD_UP || key.keyCode == KeyEvent.KEYCODE_DPAD_DOWN -> {
|
||||
if (down) {
|
||||
val from = order.indexOf(held)
|
||||
val step = if (key.keyCode == KeyEvent.KEYCODE_DPAD_UP) -1 else 1
|
||||
val to = (from + step).coerceIn(0, order.lastIndex)
|
||||
if (to != from) {
|
||||
order.add(to, order.removeAt(from))
|
||||
val visible = state.layoutInfo.visibleItemsInfo
|
||||
if (visible.isNotEmpty()) {
|
||||
val first = visible.first().index
|
||||
val last = visible.last().index
|
||||
val target = when {
|
||||
to <= first -> to
|
||||
to > last -> (to - visible.size + 1).coerceAtLeast(0)
|
||||
else -> null
|
||||
}
|
||||
if (target != null) scope.launch { state.animateScrollToItem(target) }
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
else -> false
|
||||
}
|
||||
},
|
||||
) {
|
||||
val list = @Composable { m: Modifier ->
|
||||
LazyColumn(state = state, modifier = m.pointerInput(Unit) {
|
||||
awaitEachGesture {
|
||||
val down = awaitFirstDown(requireUnconsumed = false)
|
||||
val item = state.layoutInfo.visibleItemsInfo.firstOrNull {
|
||||
it.offset <= down.position.y && down.position.y < it.offset + it.size
|
||||
}
|
||||
if (item == null || down.position.x > handlePx || grabbed != null) return@awaitEachGesture
|
||||
val start = item.index
|
||||
dragging = start
|
||||
dragOffset = 0f
|
||||
while (true) {
|
||||
val change = awaitPointerEvent(PointerEventPass.Initial).changes.firstOrNull { it.id == down.id } ?: break
|
||||
val travel = change.position.y - down.position.y
|
||||
change.consume()
|
||||
if (!change.pressed) break
|
||||
val target = (start + (travel / rowPx).roundToInt()).coerceIn(0, order.lastIndex)
|
||||
while (target != dragging) {
|
||||
val step = if (target > dragging) 1 else -1
|
||||
order.add(dragging + step, order.removeAt(dragging))
|
||||
dragging += step
|
||||
}
|
||||
dragOffset = travel - (dragging - start) * rowPx
|
||||
}
|
||||
dragging = -1
|
||||
dragOffset = 0f
|
||||
}
|
||||
}) {
|
||||
itemsIndexed(order, key = { _, key -> key }) { index, key ->
|
||||
val held = index == dragging || key == grabbed
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().height(ROW_HEIGHT).testTag("hud-row-$key")
|
||||
.then(if (key == firstKey) Modifier.focusRequester(firstFocus) else Modifier)
|
||||
.onFocusChanged { if (it.isFocused) focusedKey = key else if (focusedKey == key) focusedKey = null }
|
||||
.zIndex(if (held) 1f else 0f)
|
||||
.graphicsLayer { translationY = if (index == dragging) dragOffset else 0f }
|
||||
.clip(Shape12)
|
||||
.background(
|
||||
if (held) MaterialTheme.colorScheme.surfaceVariant
|
||||
else MaterialTheme.colorScheme.surface,
|
||||
)
|
||||
.then(
|
||||
if (key == focusedKey) Modifier.border(2.dp, LocalPalette.current.signal, Shape12)
|
||||
else Modifier,
|
||||
)
|
||||
.focusable()
|
||||
.padding(start = 4.dp, end = 6.dp),
|
||||
) {
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.size(width = HANDLE_WIDTH, height = ROW_HEIGHT).testTag("hud-handle-$key"),
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.DragHandle, null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
val label = hudMetricLabel(key)
|
||||
Text(
|
||||
if (label != null) stringResource(label) else key,
|
||||
fontSize = 14.sp, color = MaterialTheme.colorScheme.onBackground, maxLines = 1,
|
||||
modifier = Modifier.weight(1f).padding(start = 2.dp),
|
||||
)
|
||||
ToggleSwitch(
|
||||
enabled[key] == true, true, null,
|
||||
modifier = Modifier.testTag("hud-switch-$key").focusProperties { canFocus = false },
|
||||
) { enabled[key] = !(enabled[key] == true) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
list(Modifier.weight(1f).fillMaxWidth())
|
||||
if (!pad) {
|
||||
Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Box(Modifier.weight(1f))
|
||||
PrimaryButton(stringResource(R.string.common_ok), compact = true, onClick = save)
|
||||
SecondaryButton(stringResource(R.string.hud_reset_button), compact = true, onClick = restore)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
|
||||
internal const val LIBRARY_FAVORITES = "favorites"
|
||||
|
||||
internal object LibraryFavorites {
|
||||
var keys by mutableStateOf<Set<String>>(emptySet())
|
||||
private set
|
||||
private var loaded = false
|
||||
|
||||
fun load(context: Context) {
|
||||
if (loaded) return
|
||||
loaded = true
|
||||
keys = SessionPrefs.libraryFavorites(context)
|
||||
}
|
||||
|
||||
fun toggle(context: Context, key: String) {
|
||||
load(context)
|
||||
keys = toggled(keys, key)
|
||||
SessionPrefs.setLibraryFavorites(context, keys)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun toggled(keys: Set<String>, key: String): Set<String> = if (key in keys) keys - key else keys + key
|
||||
|
||||
internal fun inLibrarySource(source: String, entry: LibraryEntry, favorites: Set<String>): Boolean = when (source) {
|
||||
LIBRARY_ALL -> true
|
||||
LIBRARY_FAVORITES -> entry.favoriteKey in favorites
|
||||
else -> entry.source == source
|
||||
}
|
||||
@@ -42,7 +42,6 @@ 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.BookmarkBorder
|
||||
import androidx.compose.material.icons.filled.FilterAlt
|
||||
import androidx.compose.material.icons.filled.GridView
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
@@ -62,7 +61,6 @@ import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
@@ -94,11 +92,6 @@ import androidx.compose.ui.unit.sp
|
||||
import coil.compose.AsyncImage
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.frontend.Soundtrack
|
||||
import com.droiddeck.launcher.frontend.SoundtrackCollections
|
||||
import com.droiddeck.launcher.frontend.SoundtrackIndex
|
||||
import com.droiddeck.launcher.frontend.SoundtrackTracks
|
||||
import com.droiddeck.launcher.playback.SoundtrackController
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
@@ -126,7 +119,6 @@ internal class LibraryEntry(
|
||||
val game: Library.SteamGame?, val item: CatalogItem?, val installed: Boolean,
|
||||
) {
|
||||
val storeKey: String? get() = item?.key ?: game?.storeId?.let { "${game.source}:$it" }
|
||||
val favoriteKey: String get() = storeKey ?: key
|
||||
}
|
||||
|
||||
internal fun libraryEntries(
|
||||
@@ -163,12 +155,9 @@ internal fun collectionEntries(all: List<LibraryEntry>, items: List<CatalogItem>
|
||||
internal fun installedFirst(entries: List<LibraryEntry>): List<LibraryEntry> = entries.partition { it.installed }.let { (on, off) -> on + off }
|
||||
|
||||
internal const val LIBRARY_ALL = "all"
|
||||
internal fun librarySources(entries: List<LibraryEntry>, order: List<String>, always: Set<String> = emptySet(), favorites: Set<String> = emptySet()): List<String> =
|
||||
(listOf(LIBRARY_FAVORITES, Library.SOURCE_STEAM) + arrangeStoreTabs(order, emptySet()).map { it.store.id } + Library.ADDED + Library.SOURCE_COLLECTION)
|
||||
.filter { source ->
|
||||
if (source == LIBRARY_FAVORITES) entries.any { it.favoriteKey in favorites }
|
||||
else source in always || entries.any { it.source == source }
|
||||
}
|
||||
internal fun librarySources(entries: List<LibraryEntry>, order: List<String>, always: Set<String> = emptySet()): List<String> =
|
||||
(listOf(Library.SOURCE_STEAM) + arrangeStoreTabs(order, emptySet()).map { it.store.id } + Library.ADDED)
|
||||
.filter { source -> source in always || entries.any { it.source == source } }
|
||||
|
||||
internal object LibraryDisplay {
|
||||
val scales = listOf(0.75f, 0.875f, 1f, 1.2f, 1.45f)
|
||||
@@ -226,26 +215,14 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
|
||||
val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current
|
||||
LaunchedEffect(Unit) { StoresState.refresh(ctx) }
|
||||
remember { LibraryDisplay.load(ctx) }
|
||||
remember { LibraryFavorites.load(ctx) }
|
||||
val soundMode = selected == "soundtracks" || selected.startsWith("sound:")
|
||||
val favorites = if (soundMode) emptySet() else LibraryFavorites.keys
|
||||
val stores = s.gameStoresEnabled && !s.shortcutPicker && !soundMode
|
||||
val stores = s.gameStoresEnabled && !s.shortcutPicker
|
||||
val signedIn = Store.entries.filter { StoresState.isSignedIn(it) }
|
||||
LaunchedEffect(stores, signedIn) { if (stores) signedIn.forEach { StoresState.loadLibrary(ctx, it) } }
|
||||
val owned = if (stores) signedIn.associateWith { StoresState.library[it].orEmpty() } else emptyMap()
|
||||
val installedStore = StoresState.installed.map { it.key }.toSet()
|
||||
val syncing = if (stores) signedIn.mapNotNull { st -> StoresState.status[st]?.let { st to it } } else emptyList()
|
||||
val cloudRows = rememberXboxCloudRows(s)
|
||||
remember { SoundtrackCollections.load(ctx) }
|
||||
val savedSnapshot = SoundtrackCollections.snapshot
|
||||
val favoritesLabel = stringResource(R.string.soundtracks_favorites)
|
||||
val all = remember(soundMode, s.steamGames, s.soundtracks, s.soundtracksEnabled, cloudRows, owned, installedStore, savedSnapshot, favoritesLabel) {
|
||||
if (soundMode) s.soundtracks.map { LibraryEntry("sound:${it.appId}", it.source, it.name, it, null, true) } +
|
||||
(if (s.soundtracks.isEmpty() && savedSnapshot.favorites.isEmpty() && savedSnapshot.collections.isEmpty()) emptyList() else SoundtrackCollections.games(ctx, favoritesLabel))
|
||||
.map { LibraryEntry("sound:${it.appId}", it.source, it.name, it, null, true) }
|
||||
else libraryEntries(s.steamGames + cloudRows + if (s.soundtracksEnabled) emptyList() else s.soundtracks.filter { it.library != Library.ADDED }, owned, installedStore)
|
||||
}
|
||||
var addingSoundtrack by remember { mutableStateOf(false) }
|
||||
val all = remember(s.steamGames, cloudRows, owned, installedStore) { libraryEntries(s.steamGames + cloudRows, owned, installedStore) }
|
||||
LaunchedEffect(Unit) { XboxLibraryFilter.load(ctx) }
|
||||
var showUninstalled by remember(LibraryView.ownedRequest) { mutableStateOf(SessionPrefs.libraryShowUninstalled(ctx)) }
|
||||
var collectionShows by remember { mutableStateOf<Pair<String, Boolean>?>(null) }
|
||||
@@ -263,11 +240,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
|
||||
}
|
||||
val itchSignedIn = owned.containsKey(Store.ITCH)
|
||||
val gameJoltSignedIn = owned.containsKey(Store.GAMEJOLT)
|
||||
val sources = librarySources(
|
||||
all, SessionPrefs.storesTabOrder(ctx),
|
||||
listOfNotNull(Store.ITCH.id.takeIf { itchSignedIn && !soundMode }, Store.GAMEJOLT.id.takeIf { gameJoltSignedIn && !soundMode }, Library.SOURCE_COLLECTION.takeIf { soundMode }).toSet(),
|
||||
favorites,
|
||||
)
|
||||
val sources = librarySources(all, SessionPrefs.storesTabOrder(ctx), listOfNotNull(Store.ITCH.id.takeIf { itchSignedIn }, Store.GAMEJOLT.id.takeIf { gameJoltSignedIn }).toSet())
|
||||
val source = LibraryView.source.takeIf { it == LIBRARY_ALL || it in sources } ?: LIBRARY_ALL
|
||||
val q = LibraryView.query.trim().lowercase()
|
||||
val xboxFilter = if (source == Store.XBOX.id) XboxLibraryFilter.current else XboxLibraryFilter.ALL
|
||||
@@ -289,33 +262,9 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
|
||||
val collectionItems = collectionId?.let { if (source == Store.GAMEJOLT.id) GameJoltCollections.gamesOf(it) else ItchCollections.gamesOf(it) }
|
||||
val pool = if (collectionId == null) all else collectionEntries(all, collectionItems.orEmpty(), Store.byId(source) ?: Store.ITCH)
|
||||
val matching = pool.filter {
|
||||
inLibrarySource(source, it, favorites) && (q.isEmpty() || it.title.lowercase().contains(q)) && keepsXbox(xboxFilter, it)
|
||||
(source == LIBRARY_ALL || it.source == source) && (q.isEmpty() || it.title.lowercase().contains(q)) && keepsXbox(xboxFilter, it)
|
||||
}
|
||||
val listUninstalled = if (collectionId == null) showUninstalled else collectionShows?.takeIf { it.first == collectionId }?.second ?: true
|
||||
val trackHits by produceState<List<SoundtrackIndex.Hit>>(emptyList(), soundMode, q, source, s.soundtracks) {
|
||||
if (!soundMode || q.isEmpty()) {
|
||||
value = emptyList()
|
||||
return@produceState
|
||||
}
|
||||
kotlinx.coroutines.delay(150)
|
||||
value = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
|
||||
SoundtrackIndex.build(ctx, s.soundtracks)
|
||||
.filter { (source == LIBRARY_ALL || it.game.source == source) && SoundtrackTracks.matches(q, it.ref.title, it.ref.artist, it.ref.album) }
|
||||
.distinctBy { it.ref.path }
|
||||
.sortedWith(compareBy({ SoundtrackTracks.rank(q, it.ref.title) }, { it.ref.title.lowercase() }))
|
||||
.take(100)
|
||||
}
|
||||
}
|
||||
val shownHits = trackHits.filter { source == LIBRARY_ALL || it.game.source == source }
|
||||
val hitScope = rememberCoroutineScope()
|
||||
val playHit: (SoundtrackIndex.Hit) -> Unit = { hit ->
|
||||
val dir = hit.game.gameFiles
|
||||
if (dir != null) hitScope.launch {
|
||||
val album = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { Soundtrack.load(ctx, dir, hit.game.art) }
|
||||
SoundtrackController.play(ctx, album, hit.game.name, hit.ref.path, root = dir)
|
||||
}
|
||||
}
|
||||
var savedDialog by remember { mutableStateOf(false) }
|
||||
val candidates = if (listUninstalled) matching else matching.filter { it.installed }
|
||||
val hiddenUninstalled = if (listUninstalled) 0 else matching.count { !it.installed }
|
||||
val sort = s.storesSort
|
||||
@@ -355,20 +304,18 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
|
||||
var stable by remember { mutableStateOf(emptyList<LibraryEntry>()) }
|
||||
val ordered = if (sizesPending) retainOrder(candidates, stable) { it.key } else sorted
|
||||
SideEffect { if (!sizesPending) stable = sorted }
|
||||
val visible = installedFirst(ordered).let { list ->
|
||||
if (soundMode && source == Library.SOURCE_COLLECTION) list.sortedBy { if (it.game?.appId == SoundtrackCollections.FAVORITES_ID) 0 else 1 } else list
|
||||
}
|
||||
val visible = installedFirst(ordered)
|
||||
val split = visible.count { it.installed }.takeIf { it in 1 until visible.size } ?: 0
|
||||
|
||||
val open = selected.takeIf { it.startsWith(if (soundMode) "sound:" else "app:") }
|
||||
val back = { onSelect(if (soundMode) "soundtracks" else "games") }
|
||||
val open = selected.takeIf { it.startsWith("app:") }
|
||||
val back = { onSelect("games") }
|
||||
BackHandler(enabled = open == null && LibraryView.query.isNotEmpty()) { LibraryView.query = "" }
|
||||
BackHandler(enabled = open != null) { back() }
|
||||
val lead = remember { FocusRequester() }
|
||||
var detailFocused by remember { mutableStateOf(false) }
|
||||
var lastOpened by remember { mutableStateOf<String?>(null) }
|
||||
val wasOpen = remember { booleanArrayOf(false) }
|
||||
val backLabel = stringResource(if (soundMode) R.string.rail_soundtracks else R.string.rail_games)
|
||||
val backLabel = stringResource(R.string.rail_games)
|
||||
LaunchedEffect(open) {
|
||||
val closing = open == null && wasOpen[0]
|
||||
wasOpen[0] = open != null
|
||||
@@ -402,7 +349,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
|
||||
kotlinx.coroutines.delay(Motion.ms(240).toLong())
|
||||
focusWithinFrames({ ff.last?.startsWith("card:") == true }) { if (ff.firstTileAttached > 0) ff.firstTile else FocusRequester.Default }
|
||||
}
|
||||
if (!soundMode && all.isEmpty() && open == null && !itchSignedIn && !gameJoltSignedIn) {
|
||||
if (all.isEmpty() && open == null && !itchSignedIn && !gameJoltSignedIn) {
|
||||
LibraryEmpty(s, a, modifier)
|
||||
return
|
||||
}
|
||||
@@ -438,26 +385,9 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
|
||||
onOpen = { focusManager.clearFocus(force = true); onSelect(it) },
|
||||
searchCleared = open != null,
|
||||
onFocus = { gridFocused = it },
|
||||
soundMode = soundMode,
|
||||
emptyText = when {
|
||||
soundMode && all.isEmpty() -> R.string.soundtracks_empty
|
||||
soundMode && source == Library.SOURCE_COLLECTION && q.isEmpty() -> R.string.soundtracks_collections_empty
|
||||
else -> R.string.stores_nothing_matches
|
||||
},
|
||||
onAddSoundtrack = { addingSoundtrack = true },
|
||||
onCollections = { savedDialog = true },
|
||||
trackHits = shownHits, onPlayHit = playHit,
|
||||
)
|
||||
},
|
||||
) { key ->
|
||||
if (soundMode || (!s.soundtracksEnabled && s.soundtracks.any { GameRef.key(it) == key })) SoundtrackDetail(key, s, a, lead, backLabel, onBack = back)
|
||||
else GameDetail(key, s, a, lead, backLabel, hopRail = "games", onBack = back)
|
||||
}
|
||||
if (savedDialog) SavedDialog(emptyList(), onOpen = { id -> onSelect("sound:$id") }) { savedDialog = false }
|
||||
if (addingSoundtrack) SyncFolderPicker(stringResource(R.string.soundtracks_add_title), null, onDismiss = { addingSoundtrack = false }) { dir ->
|
||||
addingSoundtrack = false
|
||||
a.onSoundtrackAdded(dir)
|
||||
}
|
||||
) { key -> GameDetail(key, s, a, lead, backLabel, hopRail = "games", onBack = back) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -486,8 +416,6 @@ private fun LibraryGrid(
|
||||
sources: List<String>, source: String, sizesPending: Boolean, syncing: List<Pair<Store, String>>,
|
||||
showUninstalled: Boolean?, onShowUninstalled: (Boolean) -> Unit, hiddenUninstalled: Int,
|
||||
onSource: (String) -> Unit, onCycle: (Int) -> Unit, onOpen: (String) -> Unit, onFocus: (Boolean) -> Unit, searchCleared: Boolean,
|
||||
soundMode: Boolean = false, emptyText: Int = R.string.stores_nothing_matches, onAddSoundtrack: () -> Unit = {},
|
||||
onCollections: () -> Unit = {}, trackHits: List<SoundtrackIndex.Hit> = emptyList(), onPlayHit: (SoundtrackIndex.Hit) -> Unit = {},
|
||||
) {
|
||||
val listMode = s.storesView == "list"
|
||||
val capsules = s.storesView == "capsules"
|
||||
@@ -510,7 +438,7 @@ private fun LibraryGrid(
|
||||
val next = storeGridNeighbor(index, visible.size, if (listMode) 1 else columns, direction, split)
|
||||
when {
|
||||
direction == 0 || index < 0 -> false
|
||||
next == null -> direction > 0 && trackHits.isEmpty()
|
||||
next == null -> direction > 0
|
||||
else -> {
|
||||
if (key.action == KeyEvent.ACTION_DOWN) {
|
||||
val target = "card:${visible[next].key}"
|
||||
@@ -529,7 +457,7 @@ private fun LibraryGrid(
|
||||
}
|
||||
val picker = s.shortcutPicker && e.game != null
|
||||
val choose = if (picker) ({ a.onSteamGame(e.game!!) }) else null
|
||||
if (listMode) LibraryRow(e, first, navigation, choose, onOpen) else LibraryTile(e, capsules, first, navigation, choose, onOpen, showSource = source == LIBRARY_ALL || source == LIBRARY_FAVORITES)
|
||||
if (listMode) LibraryRow(e, first, navigation, choose, onOpen) else LibraryTile(e, capsules, first, navigation, choose, onOpen, showSource = source == LIBRARY_ALL)
|
||||
}
|
||||
LazyVerticalGrid(
|
||||
columns = if (listMode) GridCells.Fixed(1) else GridCells.Adaptive(tileWidth), state = grid,
|
||||
@@ -542,7 +470,7 @@ private fun LibraryGrid(
|
||||
contentPadding = PaddingValues(top = 4.dp, bottom = 16.dp),
|
||||
) {
|
||||
item(key = "header", span = { GridItemSpan(maxLineSpan) }) {
|
||||
Rise(0) { LibraryHeader(s, a, total, searchCleared, source == Store.XBOX.id, showUninstalled, onShowUninstalled, collections = Store.byId(source)?.takeIf { it == Store.ITCH || it == Store.GAMEJOLT }, soundMode = soundMode, onAddSoundtrack = onAddSoundtrack, onCollections = onCollections) }
|
||||
Rise(0) { LibraryHeader(s, a, total, searchCleared, source == Store.XBOX.id, showUninstalled, onShowUninstalled, collections = Store.byId(source)?.takeIf { it == Store.ITCH || it == Store.GAMEJOLT }) }
|
||||
}
|
||||
item(key = "filters", span = { GridItemSpan(maxLineSpan) }) {
|
||||
Rise(1) { LibraryFilters(sources, source, onSource) }
|
||||
@@ -560,7 +488,7 @@ private fun LibraryGrid(
|
||||
Text(stringResource(R.string.store_section_loading), fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
val empty = emptyText
|
||||
val empty = R.string.stores_nothing_matches
|
||||
if (visible.isEmpty() && hiddenUninstalled > 0) item(key = "browse-owned", span = { GridItemSpan(maxLineSpan) }) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.fillMaxWidth().padding(vertical = 32.dp)) {
|
||||
Text(stringResource(R.string.library_no_installed_matches), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
@@ -574,40 +502,6 @@ private fun LibraryGrid(
|
||||
item(key = "not-installed-label", span = { GridItemSpan(maxLineSpan) }) { SectionLabel(stringResource(R.string.stores_section_not_installed)) }
|
||||
libraryGrid(visible.drop(split), empty, tile)
|
||||
}
|
||||
if (trackHits.isNotEmpty()) {
|
||||
item(key = "tracks-label", span = { GridItemSpan(maxLineSpan) }) { SectionLabel(stringResource(R.string.soundtracks_tracks_heading)) }
|
||||
items(trackHits, key = { "track:${it.ref.path}" }, span = { GridItemSpan(maxLineSpan) }, contentType = { "track" }) { hit -> TrackHitRow(hit, onPlayHit) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TrackHitRow(hit: SoundtrackIndex.Hit, onPlay: (SoundtrackIndex.Hit) -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
val shape = RoundedCornerShape(10.dp)
|
||||
val cover = hit.ref.cover.takeIf { it.isNotEmpty() }?.let { java.io.File(it) }?.takeIf { it.isFile }
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 56.dp).paneItem("trackhit:${hit.ref.path}").testTag("track-hit")
|
||||
.clip(shape).glideBorder(hot, shape, pal.signal, pal.line)
|
||||
.hoverable(src).clickable(role = Role.Button, interactionSource = src, indication = LocalIndication.current) { onPlay(hit) }
|
||||
.controllerConfirm { onPlay(hit) }
|
||||
.padding(horizontal = 10.dp, vertical = 6.dp),
|
||||
) {
|
||||
Box(Modifier.size(44.dp).clip(RoundedCornerShape(8.dp)).background(artBrush(hueOf(hit.ref.album)))) {
|
||||
if (cover != null) AsyncImage(model = cover, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize())
|
||||
}
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(hit.ref.title, fontSize = 14.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
listOf(hit.ref.album, hit.ref.artist).filter { it.isNotBlank() }.joinToString(" · "),
|
||||
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
if (hit.ref.durationMs > 0) Text(Soundtrack.formatLength(hit.ref.durationMs), fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -638,31 +532,28 @@ private fun LazyGridScope.libraryGrid(entries: List<LibraryEntry>, empty: Int, t
|
||||
private fun LibraryHeader(
|
||||
s: FrontEndState, a: FrontEndActions, total: Int, searchCleared: Boolean, xbox: Boolean,
|
||||
showUninstalled: Boolean?, onShowUninstalled: (Boolean) -> Unit, collections: Store?,
|
||||
soundMode: Boolean = false, onAddSoundtrack: () -> Unit = {}, onCollections: () -> Unit = {},
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val narrow = LocalNarrowPane.current
|
||||
val heading = stringResource(if (soundMode) R.string.rail_soundtracks else R.string.rail_games)
|
||||
ModeHeader(
|
||||
heading, LibraryView.query, { LibraryView.query = it },
|
||||
placeholder = stringResource(if (soundMode) R.string.soundtracks_search else R.string.stores_search_library),
|
||||
stringResource(R.string.rail_games), LibraryView.query, { LibraryView.query = it },
|
||||
placeholder = stringResource(R.string.stores_search_library),
|
||||
clearSearchFocus = searchCleared, inlineWhenStacked = true,
|
||||
lead = {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(start = 2.dp, end = 4.dp)) {
|
||||
Text(heading, fontSize = if (narrow) 20.sp else 24.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1)
|
||||
Text(if (soundMode) total.toString() else pluralStringResource(R.plurals.mode_added_count, total, total), fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1)
|
||||
Text(stringResource(R.string.rail_games), fontSize = if (narrow) 20.sp else 24.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1)
|
||||
Text(pluralStringResource(R.plurals.mode_added_count, total, total), fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1)
|
||||
if (s.steamGamesX64 && !narrow) ClientTag()
|
||||
}
|
||||
},
|
||||
) {
|
||||
if (soundMode) HeaderIconButton(stringResource(R.string.soundtracks_saved), Icons.Filled.BookmarkBorder, "collections", onCollections)
|
||||
DisplayButton()
|
||||
if (!soundMode && (showUninstalled != null || xbox)) LibraryFilterButton(showUninstalled, onShowUninstalled, xbox)
|
||||
if (showUninstalled != null || xbox) LibraryFilterButton(showUninstalled, onShowUninstalled, xbox)
|
||||
if (collections != null) CollectionsButton(collections)
|
||||
SortButton(s, a)
|
||||
ViewButton(s, a)
|
||||
if (!soundMode) GameFileFolderActions(s, a)
|
||||
if (!s.shortcutPicker) AddGameButton { if (soundMode) onAddSoundtrack() else GamesDialogState.adding = true }
|
||||
GameFileFolderActions(s, a)
|
||||
if (!s.shortcutPicker) AddGameButton { GamesDialogState.adding = true }
|
||||
}
|
||||
if (s.steamGamesX64 && narrow) Box(Modifier.padding(top = 4.dp)) { ClientTag() }
|
||||
}
|
||||
@@ -679,19 +570,10 @@ private fun LibraryFilters(sources: List<String>, source: String, onSource: (Str
|
||||
val store = Store.byId(src)
|
||||
val dot = when {
|
||||
store != null -> sourceColours(src).dot.copy(alpha = if (StoresState.isSignedIn(store) && StoresState.expired[store] != true) 1f else 0.35f)
|
||||
src == LIBRARY_FAVORITES -> FavoritesColours.dot
|
||||
src == Library.SOURCE_STEAM || src == Library.ADDED || src == Library.SOURCE_COLLECTION -> sourceColours(src).dot
|
||||
src == Library.SOURCE_STEAM -> sourceColours(src).dot
|
||||
else -> null
|
||||
}
|
||||
SourceFilterChip(
|
||||
src,
|
||||
when (src) {
|
||||
Library.ADDED -> stringResource(R.string.library_filter_added)
|
||||
LIBRARY_FAVORITES -> stringResource(R.string.soundtracks_favorites)
|
||||
else -> store?.shortLabel ?: sourceLabel(src)
|
||||
},
|
||||
source == src, dot,
|
||||
) { onSource(src) }
|
||||
SourceFilterChip(src, if (src == Library.ADDED) stringResource(R.string.library_filter_added) else store?.shortLabel ?: sourceLabel(src), source == src, dot) { onSource(src) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -767,7 +649,7 @@ private fun LibraryArt(e: LibraryEntry, wide: Any?, tall: Any?, download: Downlo
|
||||
}
|
||||
ArtCard(
|
||||
e.title, wide, tall, download, hot, capsule, chip,
|
||||
badge = if (showSource) ({ SourceChip(e.source, small = true, modifier = Modifier.align(Alignment.TopStart).padding(6.dp), label = favoritesBadge(e), colours = favoritesColours(e)) }) else null,
|
||||
badge = if (showSource) ({ SourceChip(e.source, small = true, modifier = Modifier.align(Alignment.TopStart).padding(6.dp)) }) else null,
|
||||
) { LibrarySize(e) }
|
||||
}
|
||||
|
||||
@@ -904,7 +786,7 @@ private fun LibraryRow(e: LibraryEntry, first: Boolean, navigation: Modifier, ch
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
Text(e.title, fontSize = 14.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
SourceChip(e.source, small = true, label = favoritesBadge(e), colours = favoritesColours(e))
|
||||
SourceChip(e.source, small = true)
|
||||
Text(meta.joinToString(" · "), fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
@@ -1122,10 +1004,3 @@ private fun ViewButton(s: FrontEndState, a: FrontEndActions) {
|
||||
"view",
|
||||
) { a.onStoresView(next) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun favoritesBadge(e: LibraryEntry): String? =
|
||||
if (e.game?.appId == SoundtrackCollections.FAVORITES_ID && e.source == Library.SOURCE_COLLECTION) stringResource(R.string.soundtracks_favorites) else null
|
||||
|
||||
private fun favoritesColours(e: LibraryEntry): SourceColours? =
|
||||
if (e.game?.appId == SoundtrackCollections.FAVORITES_ID && e.source == Library.SOURCE_COLLECTION) FavoritesColours else null
|
||||
@@ -1,98 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.LocalIndication
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.hoverable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
@Composable
|
||||
internal fun MorePage(s: FrontEndState, a: FrontEndActions, onSelect: (String) -> Unit, modifier: Modifier) {
|
||||
val keys = NavTabs.more(s)
|
||||
val open: (String) -> Unit = { key -> if (key == "components") a.onComponents(true) else onSelect(key) }
|
||||
Column(modifier.verticalScroll(rememberScrollState())) {
|
||||
PageHeader(stringResource(R.string.rail_more)) {
|
||||
Spacer(Modifier.weight(1f))
|
||||
SecondaryButton(stringResource(R.string.more_edit_tabs), compact = true) {
|
||||
SetupTabs.openLauncher = true
|
||||
SetupTabs.focusTabs = true
|
||||
onSelect("setup")
|
||||
}
|
||||
}
|
||||
BoxWithConstraints(Modifier.fillMaxWidth()) {
|
||||
val gap = 12.dp
|
||||
val columns = ((maxWidth + gap) / (160.dp + gap)).toInt().coerceIn(2, 5)
|
||||
Column(verticalArrangement = Arrangement.spacedBy(gap)) {
|
||||
keys.chunked(columns).forEachIndexed { r, row ->
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(gap)) {
|
||||
row.forEachIndexed { c, key ->
|
||||
MoreTile(s, key, first = r == 0 && c == 0, Modifier.weight(1f)) { open(key) }
|
||||
}
|
||||
repeat(columns - row.size) { Spacer(Modifier.weight(1f)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MoreTile(s: FrontEndState, key: String, first: Boolean, modifier: Modifier, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val (label, icon) = railLabelIcon(key)
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
val shape = RoundedCornerShape(18.dp)
|
||||
val count = railCount(s, key)
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = modifier
|
||||
.then(if (first) Modifier.paneEntry() else Modifier.paneItem("more:$key"))
|
||||
.testTag("more-$key")
|
||||
.height(112.dp).clip(shape)
|
||||
.background(if (hot) pal.signal.copy(alpha = 0.12f) else colors.surface)
|
||||
.glideBorder(hot, shape, pal.signal, pal.line)
|
||||
.hoverable(src)
|
||||
.clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick)
|
||||
.controllerConfirm(onClick = onClick),
|
||||
) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Icon(icon, contentDescription = null, tint = if (hot) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(30.dp))
|
||||
Text(stringResource(label), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
|
||||
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(horizontal = 8.dp))
|
||||
}
|
||||
if (railBadge(s, key)) Box(Modifier.align(Alignment.TopEnd).padding(12.dp).size(9.dp).clip(CircleShape).background(AttentionAmber))
|
||||
if (count > 0) Box(Modifier.align(Alignment.TopEnd).padding(10.dp)) { CountPill(count) }
|
||||
}
|
||||
}
|
||||
Loaded 100 of 293 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user