mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 20:45:43 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d584d2cadc | ||
|
|
486b1d3758 | ||
|
|
72a7c18797 |
No files matched your search
@@ -29,14 +29,11 @@ jobs:
|
||||
persist-credentials: false
|
||||
- name: Build in Arch Linux ARM
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
FEX_EXTRA_CXXFLAGS: ${{ inputs.cxxflags }}
|
||||
FEX_THUNKS: ${{ inputs.thunks == 'true' && '1' || '0' }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
FEX_VERSION=$(gh api repos/FEX-Emu/FEX/releases/latest --jq .tag_name)
|
||||
echo "Building $FEX_VERSION, FEX's latest release"
|
||||
docker run --rm -e FEX_VERSION="$FEX_VERSION" -e FEX_EXTRA_CXXFLAGS="$FEX_EXTRA_CXXFLAGS" -e FEX_THUNKS="$FEX_THUNKS" -v "$PWD:/work" -w /work menci/archlinuxarm:base-devel bash tools/fex/build-in-arch.sh
|
||||
docker run --rm -e FEX_EXTRA_CXXFLAGS="$FEX_EXTRA_CXXFLAGS" -e FEX_THUNKS="$FEX_THUNKS" -v "$PWD:/work" -w /work menci/archlinuxarm:base-devel bash tools/fex/build-in-arch.sh
|
||||
sudo chown -R "$(id -u):$(id -g)" .
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
|
||||
@@ -73,6 +73,8 @@ jobs:
|
||||
set -euo pipefail
|
||||
git fetch --no-tags origin main
|
||||
echo "base-sha=$(git rev-parse origin/main)" >> "$GITHUB_OUTPUT"
|
||||
- name: Verify checked-in binary provenance
|
||||
run: python3 tools/provenance/check.py
|
||||
- name: Record pinned source tree
|
||||
id: source
|
||||
run: echo "tree-sha=$(git rev-parse 'HEAD^{tree}')" >> "$GITHUB_OUTPUT"
|
||||
@@ -164,9 +166,6 @@ jobs:
|
||||
!/docs/releases/media/
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
- name: Clear scratch earlier runs left behind
|
||||
if: runner.environment == 'self-hosted'
|
||||
run: bash tools/ci/clear-runner-scratch.sh "$GITHUB_WORKSPACE"
|
||||
- name: Merge the pinned APK base
|
||||
if: github.event_name == 'pull_request'
|
||||
env:
|
||||
@@ -370,10 +369,6 @@ jobs:
|
||||
persist-credentials: false
|
||||
submodules: recursive
|
||||
|
||||
- name: Clear scratch earlier runs left behind
|
||||
if: runner.environment == 'self-hosted'
|
||||
run: bash tools/ci/clear-runner-scratch.sh "$GITHUB_WORKSPACE"
|
||||
|
||||
- name: Check human authorship
|
||||
env:
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
@@ -572,65 +567,23 @@ jobs:
|
||||
SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
|
||||
run: python3 tools/components/prepare.py unpack --tree "$SOURCE_TREE"
|
||||
|
||||
# A hosted runner needs over 20 minutes per launcher; rebuild only when its sources change, and save each
|
||||
# build as soon as it finishes so a later timeout cannot discard it.
|
||||
- name: Restore the Ubisoft launcher build
|
||||
id: ubisoft-cache
|
||||
uses: actions/cache/restore@v4
|
||||
with:
|
||||
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-ubisoft
|
||||
key: ubisoft-launcher-v1-${{ steps.rust.outputs.rustc }}-${{ hashFiles('tools/ubisoft-launcher/src/**', 'tools/ubisoft-launcher/Cargo.toml', 'tools/ubisoft-launcher/Cargo.lock', 'tools/ubisoft-launcher/build.sh', 'tools/ubisoft-launcher/build.rs', 'tools/ubisoft-launcher/.cargo/**') }}
|
||||
- name: Ubisoft launcher service (x86_64-pc-windows-gnu)
|
||||
if: steps.ubisoft-cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
command -v x86_64-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-x86-64; }
|
||||
bash tools/ubisoft-launcher/build.sh
|
||||
- name: Save the Ubisoft launcher build
|
||||
if: steps.ubisoft-cache.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/save@v4
|
||||
with:
|
||||
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-ubisoft
|
||||
key: ${{ steps.ubisoft-cache.outputs.cache-primary-key }}
|
||||
|
||||
- name: Restore the Rockstar launcher build
|
||||
id: rockstar-cache
|
||||
uses: actions/cache/restore@v4
|
||||
with:
|
||||
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-rockstar
|
||||
key: rockstar-launcher-v1-${{ steps.rust.outputs.rustc }}-${{ hashFiles('tools/rockstar-launcher/src/**', 'tools/rockstar-launcher/Cargo.toml', 'tools/rockstar-launcher/Cargo.lock', 'tools/rockstar-launcher/build.sh', 'tools/rockstar-launcher/build.rs', 'tools/rockstar-launcher/.cargo/**') }}
|
||||
- name: Rockstar launcher service (32-bit and 64-bit)
|
||||
if: steps.rockstar-cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
command -v i686-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-i686; }
|
||||
command -v x86_64-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-x86-64; }
|
||||
bash tools/rockstar-launcher/build.sh
|
||||
- name: Save the Rockstar launcher build
|
||||
if: steps.rockstar-cache.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/save@v4
|
||||
with:
|
||||
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-rockstar
|
||||
key: ${{ steps.rockstar-cache.outputs.cache-primary-key }}
|
||||
|
||||
- name: Restore the Epic launcher build
|
||||
id: epic-cache
|
||||
uses: actions/cache/restore@v4
|
||||
with:
|
||||
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-epic
|
||||
key: epic-launcher-v1-${{ steps.rust.outputs.rustc }}-${{ hashFiles('tools/epic-launcher/src/**', 'tools/epic-launcher/Cargo.toml', 'tools/epic-launcher/Cargo.lock', 'tools/epic-launcher/build.sh', 'tools/epic-launcher/build.rs', 'tools/epic-launcher/.cargo/**') }}
|
||||
- name: Epic Games Launcher parent stand-in (x86_64-pc-windows-gnu)
|
||||
if: steps.epic-cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
command -v x86_64-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-x86-64; }
|
||||
bash tools/epic-launcher/build.sh
|
||||
- name: Save the Epic launcher build
|
||||
if: steps.epic-cache.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/save@v4
|
||||
with:
|
||||
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-epic
|
||||
key: ${{ steps.epic-cache.outputs.cache-primary-key }}
|
||||
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
@@ -734,32 +687,6 @@ jobs:
|
||||
if-no-files-found: ignore
|
||||
overwrite: true
|
||||
|
||||
- name: Resolve the Robolectric version
|
||||
id: robolectric
|
||||
run: |
|
||||
echo "version=$(grep -o "org.robolectric:robolectric:[0-9.]*" app/build.gradle | cut -d: -f3)" >> "$GITHUB_OUTPUT"
|
||||
# Robolectric downloads these from Maven Central on first use without retrying, and 429s fail whole test classes.
|
||||
# The cache path sits beside the workspace because runner homes are at different depths from it, and
|
||||
# actions/cache stores paths relative to the workspace. Runners that keep their own ~/.m2 skip the cache.
|
||||
- name: Place Robolectric's Android jars beside the workspace
|
||||
id: robolectric-jars
|
||||
run: |
|
||||
set -euo pipefail
|
||||
jars="$GITHUB_WORKSPACE/../robolectric-jars"
|
||||
m2="$HOME/.m2/repository/org/robolectric/android-all-instrumented"
|
||||
if [ -d "$m2" ] && [ ! -L "$m2" ]; then
|
||||
echo "cache=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
mkdir -p "$jars" "$(dirname "$m2")"
|
||||
ln -sfn "$(cd "$jars" && pwd)" "$m2"
|
||||
echo "cache=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- name: Cache Robolectric's Android jars
|
||||
if: steps.robolectric-jars.outputs.cache == 'true'
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ../robolectric-jars
|
||||
key: robolectric-android-all-v2-${{ steps.robolectric.outputs.version }}
|
||||
- name: Unit tests
|
||||
id: unit-tests
|
||||
env:
|
||||
|
||||
@@ -2,42 +2,7 @@
|
||||
|
||||
- Comments should be rare, factual, and explain only non-obvious external constraints or business invariants.
|
||||
|
||||
# Building and testing
|
||||
|
||||
- For an install-and-look iteration, use `tools/quick_deploy.sh` (build without lint, sign, install, about 30 s). Run `tools/build_local.sh` once to prepare the runtime and again only before a PR. It is not a per-change step.
|
||||
- `tools/build_local.sh` reuses the components a main CI run prepared when every recipe identity matches the local tree (it prints `components: … reusing`). It builds them locally when no usable CI artifact matches (after you change their inputs, or when the lookup fails) or with `DROIDDECK_CI_COMPONENTS=0`.
|
||||
- Helper scripts (`tools/linuxfs/overlay`, `tools/linuxfs/desktop`) are staged on every Gradle build, so editing them needs no `build_local.sh`. After preloads or other runtime components change, the fast loop warns and reuses the old binaries; run `tools/build_local.sh` when those matter. "Missing or changed runtime input" means the prepared files themselves changed: run `tools/build_local.sh` once. Do not revert scripts or copy `app/build` between checkouts; `tools/seed_worktree.sh` seeds a new worktree from the main checkout.
|
||||
- Every build defaults to the NDK in `tools/ci/toolchains.env`, as CI does. CI runs `testReleaseUnitTest`; when a test fails only in CI, run the release variant locally.
|
||||
- Run the tests that cover what you changed, including unchanged tests of code you edited: `./gradlew -PskipRust=true :app:testDebugUnitTest --tests '<class>'` and `python3 -m unittest discover -s tools/tests -p 'test_<area>*.py'`. The full Python suite takes about 9 minutes, and some preload tests fail on any host without zram/ntsync. Leave full runs to CI.
|
||||
- For UI screenshots without a device, run `./gradlew -PskipRust=true :app:testDebugUnitTest --tests '*PreviewRenderTest'` and read `app/build/preview-renders/{handheld,portrait}/`. Add cases per `docs/compose-previews.md`. Check portrait, not just landscape.
|
||||
- After changing `SettingsIndex`, regenerate the doc: `UPDATE_SETTINGS_MAP=1 ./gradlew -PskipRust=true :app:testDebugUnitTest --tests '*SettingsMapTest*'`.
|
||||
- Compile errors in code you didn't touch, after switching branches, are usually stale incremental state. Rebuild once before you change anything.
|
||||
|
||||
# Worktrees and shared machines
|
||||
|
||||
- After `git worktree add`, run `git submodule update --init --recursive`. Without it, `buildVkBridgeServer` fails on missing `external/MaliBridge`. Do not commit the `tools/syncthing/syncthing-android` pointer the build dirties.
|
||||
- Other agents may be building on the same machine. Never run `./gradlew --stop` or kill Gradle/Kotlin daemons you did not start. If you need isolation, use `GRADLE_USER_HOME=<own dir> GRADLE_RO_DEP_CACHE=$HOME/.gradle/caches`.
|
||||
|
||||
# Driving the app and device
|
||||
|
||||
- Do it yourself with `tools/droiddeckctl` (see `docs/agent-control.md`) instead of asking the user: `cdp eval` for Steam's UI (`SteamClient.Apps.TerminateApp('<appid>', false)` quits a game, including on a Remote Play host), `input`, `quit`, `displays`, `screenshot --display <id>`.
|
||||
- A stream has started only when the session state reads `Streaming`. `SteamClient.Apps.StreamGame` alone can leave Steam on its menu, so open the game page and press Stream.
|
||||
- Test controller navigation with `tools/droiddeckctl input gamepad ...`, a real uinput pad. `adb shell input keyevent DPAD_*` does not arrive as a joystick event and hides d-pad/stick bugs.
|
||||
- A release-signed build installs over a release-signed install with `adb install -r`. Don't back up, uninstall or clear data to update. Scope `pm` and permission resets to `com.droiddeck.launcher`, never the whole device.
|
||||
|
||||
# CI
|
||||
|
||||
- Before pushing a PR, run `tools/pre_pr.sh`. It checks authorship and the merge onto `main`, then, when app sources change, compiles and runs lint as CI does. It picks tests by name: `<File>*Test` for changed Kotlin files, and `tools/tests` modules that mention a changed path. Add any other tests that cover your change, and leave the full suites to CI.
|
||||
- CI builds the PR merged onto `main`. Before pushing, merge or rebase onto `origin/main` and compile: most "works locally" Kotlin failures come from that merge.
|
||||
- Before a PR that touches strings or resources, run `./gradlew :app:lintVitalRelease`. The fast loop skips lint, and lint catches `ExtraTranslation` and missing-locale errors.
|
||||
- Commit messages and PR bodies must not carry `Co-Authored-By` or other bot trailers. `tools/release/check_authorship.py` fails the build on them.
|
||||
- `gh run view --log-failed` truncates the unit-test log, so the failing test may not show. Read the whole job log with `gh api repos/Droid-Deck/DroidDeck/actions/jobs/<job-id>/logs`, or `gh run download <run> -n unit-test-results`. Don't call a failure a runner problem until you have read it.
|
||||
- Only these are known flakes worth a `gh run rerun <run> --failed`: `ProtonMenuAutoTest` "Proton work did not finish", Robolectric `HTTP response code: 429` from Maven, `Gradle Test Executor N finished with non-zero exit value 2`, apt mirror and GitHub API rate-limit errors. Treat any other failure as real.
|
||||
- A workflow step that names a script your branch lacks means the branch predates a CI change. Rebase onto `main`.
|
||||
|
||||
# Agents running on the device (DroidDeck's in-app agent)
|
||||
|
||||
These apply only where `dd-lab-build` exists. Agents on a dev host use `tools/quick_deploy.sh` instead.
|
||||
# Working on the device
|
||||
|
||||
- `dd-lab-build` builds only committed work. Check `git status` and `gh api user` for the identity before committing; if `git config user.name` is empty, use the `gh` login's name and noreply email for this repo, never a guess.
|
||||
- Do not commit or start a build in the same step: a build started next to a failed commit fails too. Commit first, check it, then build.
|
||||
|
||||
@@ -70,7 +70,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
|
||||
|
||||
- Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05.
|
||||
- mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)).
|
||||
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122).
|
||||
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source.
|
||||
- x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence.
|
||||
- x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes.
|
||||
- `WriteProcessMemory` hooks fall back to `/proc/<pid>/mem` the way [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` did before Wine 11.
|
||||
|
||||
+6
-8
@@ -125,8 +125,7 @@ def variantSuffixes = rootProject.file('tools/release/variants.txt').readLines()
|
||||
android {
|
||||
namespace 'com.droiddeck.launcher'
|
||||
compileSdk 34
|
||||
ndkVersion project.findProperty('ndkVersion') ?: providers.fileContents(rootProject.layout.projectDirectory.file('tools/ci/toolchains.env'))
|
||||
.asText.get().readLines().find { it.startsWith('CI_ANDROID_NDK_VERSION=') }.split('=', 2)[1].trim()
|
||||
ndkVersion project.findProperty('ndkVersion') ?: '27.3.13750724'
|
||||
|
||||
defaultConfig {
|
||||
applicationId "com.droiddeck.launcher"
|
||||
@@ -233,9 +232,6 @@ android {
|
||||
}
|
||||
maxHeapSize = '2g'
|
||||
maxParallelForks = 2
|
||||
def jvmTemp = new File(temporaryDir, 'jvm')
|
||||
systemProperty 'java.io.tmpdir', jvmTemp.absolutePath
|
||||
doFirst { jvmTemp.mkdirs() }
|
||||
def logTarget = providers.systemProperty('robolectric.logging').orNull
|
||||
if (logTarget != null) systemProperty 'robolectric.logging', logTarget
|
||||
}
|
||||
@@ -265,9 +261,11 @@ if (vitureSdkDir) {
|
||||
tasks.named('preBuild').configure { dependsOn(stageVitureNotices) }
|
||||
}
|
||||
|
||||
def stageSessionScripts = tasks.register('stageSessionScripts', Exec) {
|
||||
workingDir rootProject.projectDir
|
||||
commandLine pythonExecutable, 'tools/release/check_session_assets.py', '--stage'
|
||||
def stageSessionScripts = tasks.register('stageSessionScripts', Copy) {
|
||||
from(rootProject.file('tools/linuxfs/overlay')) {
|
||||
include 'usr/local/bin/droiddeck-*', 'usr/local/bin/steam-compatibility', 'usr/bin/**'
|
||||
}
|
||||
into(layout.projectDirectory.dir('src/main/assets/linuxfs'))
|
||||
}
|
||||
tasks.named('preBuild').configure { dependsOn(stageSessionScripts) }
|
||||
|
||||
|
||||
@@ -15,7 +15,6 @@ private fun Launcher(tab: String, games: List<com.droiddeck.launcher.frontend.Li
|
||||
PreviewHost { FrontEndScreen(sampleState(games = games, navigate = tab, ready = ready), sampleActions) }
|
||||
|
||||
@DroidDeckPreviews @Composable private fun SteamTabPreview() = Launcher("steam")
|
||||
@DroidDeckPreviews @Composable private fun SteamEmptyPreview() = Launcher("steam", games = emptyList())
|
||||
@DroidDeckPreviews @Composable private fun LibraryPreview() = Launcher("games")
|
||||
@DroidDeckPreviews @Composable private fun LibraryEmptyPreview() = Launcher("games", games = emptyList())
|
||||
@DroidDeckPreviews @Composable private fun StoresPreview() = Launcher("stores")
|
||||
|
||||
@@ -61,7 +61,7 @@ internal val sampleActions: FrontEndActions = FrontEndActions(
|
||||
onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {},
|
||||
onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {},
|
||||
onFiles = {}, onLogs = {}, onOffline = {},
|
||||
onSetPhantomProcessLimit = { _, _ -> },
|
||||
onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, onSetPhantomProcessLimit = { _, _ -> },
|
||||
)
|
||||
|
||||
/** The in-game menu's actions with settled sample values; its switches do nothing. */
|
||||
|
||||
@@ -232,7 +232,6 @@
|
||||
android:exported="false"
|
||||
android:screenOrientation="user"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
||||
android:windowSoftInputMode="adjustResize"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
<activity
|
||||
|
||||
@@ -21,7 +21,6 @@
|
||||
#define SYS_munmap 215
|
||||
#define SYS_mmap 222
|
||||
#define SYS_mprotect 226
|
||||
#define SYS_getpid 172
|
||||
|
||||
#define AT_FDCWD_ (-100)
|
||||
#define O_RDONLY_ 0
|
||||
@@ -53,21 +52,6 @@ static size_t slen(const char *s) {
|
||||
return n;
|
||||
}
|
||||
|
||||
static int seq(const char *a, const char *b) {
|
||||
while (*a && *a == *b) a++, b++;
|
||||
return *a == *b;
|
||||
}
|
||||
|
||||
static const char *env_get(char **envp, const char *name) {
|
||||
size_t n = slen(name);
|
||||
for (; *envp; envp++) {
|
||||
size_t i = 0;
|
||||
while (i < n && (*envp)[i] == name[i]) i++;
|
||||
if (i == n && (*envp)[n] == '=') return *envp + n + 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void out(const char *s) { sys6(SYS_write, 2, (long)s, (long)slen(s), 0, 0, 0); }
|
||||
|
||||
static void out_num(long v) {
|
||||
@@ -128,43 +112,19 @@ static int prot_of(uint32_t flags) {
|
||||
|
||||
static void map_failed(const char *path, long r) { die("cannot map a segment", path, r); }
|
||||
|
||||
static void read_interp(int fd, const Elf64_Phdr *ph, int phnum, char *interp, size_t size, const char *path) {
|
||||
interp[0] = 0;
|
||||
for (int i = 0; i < phnum; i++) {
|
||||
if (ph[i].p_type != PT_INTERP) continue;
|
||||
if (ph[i].p_filesz == 0 || ph[i].p_filesz >= size) die("bad PT_INTERP", path, 0);
|
||||
if (xpread(fd, interp, ph[i].p_filesz, (long)ph[i].p_offset) != (long)ph[i].p_filesz)
|
||||
die("truncated PT_INTERP", path, 0);
|
||||
interp[ph[i].p_filesz] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
static int read_headers(const char *path, Elf64_Ehdr *eh, Elf64_Phdr *ph) {
|
||||
static void load(const char *path, struct image *im, uintptr_t page) {
|
||||
int fd = (int)sys6(SYS_openat, AT_FDCWD_, (long)path, O_RDONLY_ | O_CLOEXEC_, 0, 0, 0);
|
||||
if (fd < 0) die("cannot open", path, fd);
|
||||
if (xpread(fd, eh, sizeof(*eh), 0) != (long)sizeof(*eh)) die("not an ELF file", path, 0);
|
||||
if (eh->e_ident[EI_MAG0] != ELFMAG0 || eh->e_ident[EI_MAG1] != ELFMAG1 || eh->e_ident[EI_MAG2] != ELFMAG2 ||
|
||||
eh->e_ident[EI_MAG3] != ELFMAG3 || eh->e_ident[EI_CLASS] != ELFCLASS64 || eh->e_machine != EM_AARCH64 ||
|
||||
(eh->e_type != ET_EXEC && eh->e_type != ET_DYN) || eh->e_phentsize != sizeof(Elf64_Phdr) ||
|
||||
eh->e_phnum == 0 || eh->e_phnum > MAX_PHDRS)
|
||||
Elf64_Ehdr eh;
|
||||
if (xpread(fd, &eh, sizeof(eh), 0) != (long)sizeof(eh)) die("not an ELF file", path, 0);
|
||||
if (eh.e_ident[EI_MAG0] != ELFMAG0 || eh.e_ident[EI_MAG1] != ELFMAG1 || eh.e_ident[EI_MAG2] != ELFMAG2 ||
|
||||
eh.e_ident[EI_MAG3] != ELFMAG3 || eh.e_ident[EI_CLASS] != ELFCLASS64 || eh.e_machine != EM_AARCH64 ||
|
||||
(eh.e_type != ET_EXEC && eh.e_type != ET_DYN) || eh.e_phentsize != sizeof(Elf64_Phdr) ||
|
||||
eh.e_phnum == 0 || eh.e_phnum > MAX_PHDRS)
|
||||
die("not a 64-bit ARM ELF program", path, 0);
|
||||
long size = (long)eh->e_phnum * (long)sizeof(Elf64_Phdr);
|
||||
if (xpread(fd, ph, (size_t)size, (long)eh->e_phoff) != size) die("truncated program headers", path, 0);
|
||||
return fd;
|
||||
}
|
||||
|
||||
static void interp_of(const char *path, char *interp, size_t size) {
|
||||
Elf64_Ehdr eh;
|
||||
Elf64_Phdr ph[MAX_PHDRS];
|
||||
int fd = read_headers(path, &eh, ph);
|
||||
read_interp(fd, ph, eh.e_phnum, interp, size, path);
|
||||
sys6(SYS_close, fd, 0, 0, 0, 0, 0);
|
||||
}
|
||||
|
||||
static void load(const char *path, struct image *im, uintptr_t page) {
|
||||
Elf64_Ehdr eh;
|
||||
Elf64_Phdr ph[MAX_PHDRS];
|
||||
int fd = read_headers(path, &eh, ph);
|
||||
long size = (long)eh.e_phnum * (long)sizeof(Elf64_Phdr);
|
||||
if (xpread(fd, ph, (size_t)size, (long)eh.e_phoff) != size) die("truncated program headers", path, 0);
|
||||
|
||||
uintptr_t lo = UINTPTR_MAX, hi = 0;
|
||||
for (int i = 0; i < eh.e_phnum; i++) {
|
||||
@@ -213,9 +173,16 @@ static void load(const char *path, struct image *im, uintptr_t page) {
|
||||
im->phnum = eh.e_phnum;
|
||||
im->phent = eh.e_phentsize;
|
||||
im->phdr = 0;
|
||||
read_interp(fd, ph, eh.e_phnum, im->interp, sizeof(im->interp), path);
|
||||
for (int i = 0; i < eh.e_phnum; i++)
|
||||
im->interp[0] = 0;
|
||||
for (int i = 0; i < eh.e_phnum; i++) {
|
||||
if (ph[i].p_type == PT_PHDR) im->phdr = bias + ph[i].p_vaddr;
|
||||
if (ph[i].p_type == PT_INTERP) {
|
||||
if (ph[i].p_filesz == 0 || ph[i].p_filesz >= sizeof(im->interp)) die("bad PT_INTERP", path, 0);
|
||||
if (xpread(fd, im->interp, ph[i].p_filesz, (long)ph[i].p_offset) != (long)ph[i].p_filesz)
|
||||
die("truncated PT_INTERP", path, 0);
|
||||
im->interp[ph[i].p_filesz] = 0;
|
||||
}
|
||||
}
|
||||
if (!im->phdr) {
|
||||
for (int i = 0; i < eh.e_phnum; i++) {
|
||||
Elf64_Phdr *p = &ph[i];
|
||||
@@ -235,36 +202,6 @@ static unsigned long auxv_get(const uintptr_t *auxv, unsigned long type, unsigne
|
||||
return fallback;
|
||||
}
|
||||
|
||||
static int is_self_exe(const char *execfn) {
|
||||
if (!execfn) return 0;
|
||||
if (seq(execfn, "/proc/self/exe") || seq(execfn, "/proc/thread-self/exe")) return 1;
|
||||
const char *p = "/proc/";
|
||||
while (*p && *p == *execfn) p++, execfn++;
|
||||
if (*p) return 0;
|
||||
char num[24];
|
||||
int i = (int)sizeof(num) - 1;
|
||||
num[i] = 0;
|
||||
unsigned long pid = (unsigned long)sys6(SYS_getpid, 0, 0, 0, 0, 0, 0);
|
||||
do {
|
||||
num[--i] = (char)('0' + pid % 10);
|
||||
pid /= 10;
|
||||
} while (pid && i > 0);
|
||||
const char *d = num + i;
|
||||
while (*d && *d == *execfn) d++, execfn++;
|
||||
return !*d && seq(execfn, "/exe");
|
||||
}
|
||||
|
||||
static const char *guest_interp(char **envp, const char *interp, char *buf, size_t size) {
|
||||
const char *root = env_get(envp, "DDNATV_ROOT");
|
||||
if (!root || interp[0] != '/') return interp;
|
||||
size_t a = slen(root), b = slen(interp);
|
||||
if (a + b + 1 > size) return interp;
|
||||
for (size_t i = 0; i < a; i++) buf[i] = root[i];
|
||||
for (size_t i = 0; i <= b; i++) buf[a + i] = interp[i];
|
||||
if (sys6(SYS_faccessat, AT_FDCWD_, (long)buf, 0, 0, 0, 0) != 0) return interp;
|
||||
return buf;
|
||||
}
|
||||
|
||||
__attribute__((used, noreturn)) void ddexec_main(uintptr_t *sp) {
|
||||
long argc = (long)sp[0];
|
||||
char **argv = (char **)(sp + 1);
|
||||
@@ -274,66 +211,25 @@ __attribute__((used, noreturn)) void ddexec_main(uintptr_t *sp) {
|
||||
uintptr_t *auxv = (uintptr_t *)(envp + nenv + 1);
|
||||
long naux = 0;
|
||||
while (auxv[naux * 2] != AT_NULL) naux++;
|
||||
int reexec = is_self_exe((const char *)auxv_get(auxv, AT_EXECFN, 0));
|
||||
const char *path;
|
||||
char **args = argv + 2;
|
||||
long nargs = argc - 2;
|
||||
char interp_buf[4096];
|
||||
char hook_buf[4096];
|
||||
if (reexec) {
|
||||
path = env_get(envp, "DDNATV_REAL_EXE");
|
||||
if (!path || !path[0]) die("re-executed without DDNATV_REAL_EXE", 0, 0);
|
||||
args = argv;
|
||||
nargs = argc;
|
||||
const char *lib_path = env_get(envp, "DDNATV_LIBRARY_PATH");
|
||||
char prog_interp[256];
|
||||
interp_of(path, prog_interp, sizeof(prog_interp));
|
||||
if (prog_interp[0] && lib_path && lib_path[0]) {
|
||||
const char *ld_so = guest_interp(envp, prog_interp, interp_buf, sizeof(interp_buf));
|
||||
const char *hook = guest_interp(envp, "/usr/lib/libddnatv-hook.so", hook_buf, sizeof(hook_buf));
|
||||
if (hook != (const char *)hook_buf) hook = guest_interp(envp, "/lib/libddnatv-hook.so", hook_buf, sizeof(hook_buf));
|
||||
long n = argc > 1 ? argc - 1 : 0;
|
||||
char **v = (char **)__builtin_alloca((size_t)(n + 9) * sizeof(char *));
|
||||
long k = 0;
|
||||
v[k++] = (char *)ld_so;
|
||||
if (hook == (const char *)hook_buf) {
|
||||
v[k++] = (char *)"--preload";
|
||||
v[k++] = (char *)hook;
|
||||
}
|
||||
v[k++] = (char *)"--library-path";
|
||||
v[k++] = (char *)lib_path;
|
||||
v[k++] = (char *)"--argv0";
|
||||
v[k++] = argc > 0 ? argv[0] : (char *)path;
|
||||
v[k++] = (char *)path;
|
||||
for (long i = 0; i < n; i++) v[k++] = argv[1 + i];
|
||||
v[k] = 0;
|
||||
args = v;
|
||||
nargs = k;
|
||||
path = ld_so;
|
||||
}
|
||||
} else if (argc < 3) {
|
||||
die("usage: libddexec.so <file> <argv0> [args...]", 0, 0);
|
||||
} else {
|
||||
path = argv[1];
|
||||
}
|
||||
if (argc < 3) die("usage: libddexec.so <file> <argv0> [args...]", 0, 0);
|
||||
|
||||
uintptr_t page = auxv_get(auxv, AT_PAGESZ, 4096);
|
||||
const char *path = argv[1];
|
||||
struct image prog, interp;
|
||||
load(path, &prog, page);
|
||||
int has_interp = prog.interp[0] != 0;
|
||||
if (has_interp) load(reexec ? guest_interp(envp, prog.interp, interp_buf, sizeof(interp_buf)) : prog.interp, &interp, page);
|
||||
if (has_interp) load(prog.interp, &interp, page);
|
||||
|
||||
// The new stack: argc, argv, envp and auxv as the kernel lays them out, below the current one.
|
||||
// The strings stay where the kernel put them.
|
||||
static const unsigned long replaced[] = {AT_PHDR, AT_PHENT, AT_PHNUM, AT_BASE, AT_ENTRY, AT_EXECFN};
|
||||
long nreplaced = (long)(sizeof(replaced) / sizeof(replaced[0]));
|
||||
long new_argc = nargs;
|
||||
long new_argc = argc - 2;
|
||||
long words = 1 + (new_argc + 1) + (nenv + 1) + (naux + nreplaced + 1) * 2;
|
||||
uintptr_t top = (uintptr_t)args < (uintptr_t)sp ? (uintptr_t)args : (uintptr_t)sp;
|
||||
uintptr_t *nsp = (uintptr_t *)((top - STACK_GAP - (uintptr_t)words * sizeof(uintptr_t)) & ~(uintptr_t)15);
|
||||
uintptr_t *nsp = (uintptr_t *)(((uintptr_t)sp - STACK_GAP - (uintptr_t)words * sizeof(uintptr_t)) & ~(uintptr_t)15);
|
||||
uintptr_t *w = nsp;
|
||||
*w++ = (uintptr_t)new_argc;
|
||||
for (long i = 0; i < new_argc; i++) *w++ = (uintptr_t)args[i];
|
||||
for (long i = 0; i < new_argc; i++) *w++ = (uintptr_t)argv[i + 2];
|
||||
*w++ = 0;
|
||||
for (long i = 0; i < nenv; i++) *w++ = (uintptr_t)envp[i];
|
||||
*w++ = 0;
|
||||
|
||||
@@ -21,7 +21,6 @@ class App : Application() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
com.droiddeck.launcher.runtime.NativeGuest.init(this)
|
||||
com.droiddeck.launcher.session.Onboarding.attach(this)
|
||||
Thread({ runCatching { EnhancedSessionLogShare.cleanupAbandonedStages(this) } }, "diagnostic-stage-cleanup").start()
|
||||
com.droiddeck.launcher.ui.Themes.loadGradient(this)
|
||||
com.droiddeck.launcher.ui.BuildWatermark.install(this)
|
||||
|
||||
@@ -79,7 +79,7 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
|
||||
checkAgain = null
|
||||
checkComponentUpdates(again)
|
||||
}
|
||||
if (notes.isNotEmpty()) Log.i(TAG, notes.joinToString("; "))
|
||||
if (notes.isNotEmpty()) android.widget.Toast.makeText(activity, notes.joinToString("\n"), android.widget.Toast.LENGTH_LONG).show()
|
||||
refreshComponents()
|
||||
}
|
||||
}, "component-updates").start()
|
||||
|
||||
@@ -6,7 +6,6 @@ import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.runtime.DeckyManager
|
||||
import com.droiddeck.launcher.runtime.DeckyStore
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import java.io.File
|
||||
|
||||
@@ -22,59 +21,6 @@ internal class DeckyMenu(private val activity: android.app.Activity, private val
|
||||
var deckySupervisor by mutableStateOf(false)
|
||||
var deckyPendingZip by mutableStateOf<File?>(null)
|
||||
var deckyReleaseRequest = 0
|
||||
var deckyPlugins by mutableStateOf<List<DeckyStore.Installed>>(emptyList())
|
||||
var deckyStore by mutableStateOf<List<DeckyStore.Plugin>?>(null)
|
||||
var deckyStoreFailed by mutableStateOf(false)
|
||||
private var storeRequest = 0
|
||||
|
||||
fun refreshPlugins() {
|
||||
Thread({
|
||||
val found = DeckyStore.installed(activity)
|
||||
ui.post { deckyPlugins = found }
|
||||
}, "decky-plugins").start()
|
||||
}
|
||||
|
||||
fun refreshStore() {
|
||||
val request = ++storeRequest
|
||||
deckyStore = null; deckyStoreFailed = false
|
||||
Thread({
|
||||
val listing = DeckyStore.fetch()
|
||||
ui.post {
|
||||
if (request != storeRequest) return@post
|
||||
deckyStore = listing.orEmpty(); deckyStoreFailed = listing == null
|
||||
}
|
||||
}, "decky-store").start()
|
||||
}
|
||||
|
||||
fun installStorePlugin(plugin: DeckyStore.Plugin) {
|
||||
val version = plugin.latest ?: return
|
||||
if (deckyStage != null || SessionState.running || deckyInstalled == null) return
|
||||
deckyStage = activity.getString(R.string.decky_plugin_starting); deckyPercent = -1
|
||||
Thread({
|
||||
val problem = runCatching {
|
||||
DeckyStore.install(activity, plugin, version) { label, value ->
|
||||
val binary = DeckyManager.downloadingBinary
|
||||
ui.post { deckyStage = label; deckyPercent = value; deckyDownloadingBinary = binary }
|
||||
}
|
||||
}.getOrElse { error -> activity.getString(R.string.decky_plugin_failed, error.message ?: error.javaClass.simpleName) }
|
||||
ui.post {
|
||||
deckyStage = null; deckyPercent = -1; deckyDownloadingBinary = false
|
||||
android.widget.Toast.makeText(activity, problem ?: activity.getString(R.string.decky_plugin_installed), android.widget.Toast.LENGTH_LONG).show()
|
||||
refreshPlugins()
|
||||
}
|
||||
}, "install-decky-store").start()
|
||||
}
|
||||
|
||||
fun removePlugin(plugin: DeckyStore.Installed) {
|
||||
if (deckyStage != null || SessionState.running) return
|
||||
Thread({
|
||||
val problem = DeckyStore.remove(activity, plugin)
|
||||
ui.post {
|
||||
if (problem != null) android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show()
|
||||
refreshPlugins()
|
||||
}
|
||||
}, "remove-decky-plugin").start()
|
||||
}
|
||||
|
||||
fun refreshDecky() {
|
||||
val request = ++deckyReleaseRequest
|
||||
@@ -144,7 +90,6 @@ internal class DeckyMenu(private val activity: android.app.Activity, private val
|
||||
deckyStage = null; deckyPercent = -1; deckyDownloadingBinary = false
|
||||
val message = problem ?: activity.getString(R.string.decky_plugin_installed)
|
||||
android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_LONG).show()
|
||||
refreshPlugins()
|
||||
}
|
||||
}, "import-decky-plugin").start()
|
||||
}
|
||||
|
||||
@@ -17,11 +17,8 @@ import android.os.Looper
|
||||
import android.util.Log
|
||||
import android.view.Display
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.view.ViewConfiguration
|
||||
import android.view.WindowManager
|
||||
import android.widget.EditText
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
@@ -187,7 +184,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
private var gpuClockPin by mutableStateOf(false)
|
||||
private var prootNoSeccomp by mutableStateOf(false)
|
||||
private var prootFastPath by mutableStateOf(true)
|
||||
private var nativeUserland by mutableStateOf(true)
|
||||
private var nativeUserland by mutableStateOf(false)
|
||||
private var cursorComposite by mutableStateOf(false)
|
||||
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
|
||||
private var phantomWarning by mutableStateOf<String?>(null)
|
||||
@@ -254,12 +251,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, WifiDiscovery.permissionGranted(this))
|
||||
refreshWifiDiscovery()
|
||||
}
|
||||
private val bluetoothPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
if (!granted && !shouldShowRequestPermissionRationale(android.Manifest.permission.BLUETOOTH_CONNECT)) {
|
||||
integrationSettings(SteamIntegration.appInfo(this))
|
||||
}
|
||||
integrationState = readIntegration()
|
||||
}
|
||||
private val cameraPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
|
||||
com.droiddeck.launcher.handtracking.HandTracking.refreshPermission(this)
|
||||
}
|
||||
@@ -381,10 +372,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
SteamIntegration.Feature.SHORTCUTS -> {
|
||||
if (integrationState.shortcuts) openShortcutSettings() else installShortcuts()
|
||||
}
|
||||
SteamIntegration.Feature.BLUETOOTH -> {
|
||||
if (SteamIntegration.bluetoothAllowed(this)) integrationSettings(SteamIntegration.appInfo(this))
|
||||
else bluetoothPermission.launch(android.Manifest.permission.BLUETOOTH_CONNECT)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -717,7 +704,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
}
|
||||
private var secondScreenDisplays by mutableStateOf<List<SecondScreenDisplay>>(emptyList())
|
||||
private var ownScreen by mutableStateOf<SecondScreenDisplay?>(null)
|
||||
private var dualDisplayId by mutableStateOf(-1)
|
||||
private var dualScreenDevice by mutableStateOf(false)
|
||||
private var dualScreenMode by mutableStateOf(com.droiddeck.launcher.input.DualScreen.MODE_AUTO)
|
||||
@@ -932,7 +918,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
request.getStringExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV)?.let { navRequest = it; request.removeExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV) }
|
||||
request.data?.takeIf { it.scheme == "droiddeck" && it.host == "settings" }?.let { uri ->
|
||||
val section = uri.pathSegments.firstOrNull()
|
||||
navRequest = if (section in setOf("storage", "sync", "downloads", "decky", "boot-movies")) section
|
||||
navRequest = if (section in setOf("storage", "sync", "downloads")) section
|
||||
else "settings:" + (com.droiddeck.launcher.ui.SettingsSection.of(section) ?: com.droiddeck.launcher.ui.SettingsSection.OVERVIEW).key
|
||||
request.data = null
|
||||
gameLinkReading = false
|
||||
@@ -1255,10 +1241,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
drivers.restartBlocked = ::runtimeChangesBlocked
|
||||
drivers.loadTpUbwcMode()
|
||||
pendingSessionLogExport = savedInstanceState?.getString(KEY_PENDING_SESSION_LOG_EXPORT)?.let(::File)
|
||||
queuedLaunch.restore(
|
||||
savedInstanceState?.let { androidx.core.os.BundleCompat.getParcelable(it, STATE_PENDING_GATE_LAUNCH, Intent::class.java) },
|
||||
savedInstanceState?.getLong(STATE_PENDING_GATE_LAUNCH_AT, 0L) ?: 0L, System.currentTimeMillis(),
|
||||
)
|
||||
homeChoiceOpen = savedInstanceState?.getBoolean(STATE_HOME_CHOICE_OPEN) == true
|
||||
gameSpaceOffered = savedInstanceState?.getBoolean(STATE_GAME_SPACE_OFFERED) == true
|
||||
if (savedInstanceState == null) readIntegrationIntent(intent)
|
||||
@@ -1360,7 +1342,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
integrationFocus = integrationFocus,
|
||||
androidApps = androidApps,
|
||||
secondScreenDisplays = secondScreenDisplays,
|
||||
ownScreen = ownScreen,
|
||||
dualScreen = dualDisplayId >= 0 && com.droiddeck.launcher.ui.DualScreenPanel.available,
|
||||
dualScreenDevice = dualScreenDevice,
|
||||
dualScreenMode = dualScreenMode,
|
||||
@@ -1408,9 +1389,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
),
|
||||
FrontEndActions(
|
||||
onPlay = { playSteam() },
|
||||
onQueuePlaySteam = {
|
||||
queuedLaunch.queue(Intent(this, SessionActivity::class.java).putExtra(SessionActivity.EXTRA_STEAMVR, false), System.currentTimeMillis())
|
||||
},
|
||||
onPlaySteamVr = { playSteamVr() },
|
||||
onSteamUrl = { url ->
|
||||
if (!SessionState.running) startSession(
|
||||
@@ -1550,7 +1528,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
onAddonImport = { sg, target -> importAddons(sg.name, target) },
|
||||
onAddonDelete = { target, name ->
|
||||
saveAction(getString(R.string.main_addons_deleting, name)) {
|
||||
com.droiddeck.launcher.ui.deleteAddon(this, target, name)
|
||||
com.droiddeck.launcher.runtime.WowAddons.delete(target, name)
|
||||
getString(R.string.main_addons_deleted, name)
|
||||
}
|
||||
},
|
||||
@@ -1782,6 +1760,31 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
},
|
||||
onRefreshPhantomStatus = { refreshPhantomStatus() },
|
||||
onOpenDeveloperOptions = { displayId -> openDeveloperOptions(displayId) },
|
||||
onWirelessAdbPair = { host, port, code, complete ->
|
||||
Thread({
|
||||
val result = runCatching {
|
||||
kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@FrontEndActivity, host, port, code) }
|
||||
}
|
||||
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: getString(R.string.main_wadb_pair_failed) }
|
||||
ui.post { complete(error) }
|
||||
}, "wireless-adb-pair").start()
|
||||
},
|
||||
onFindWirelessAdbPort = { host, complete ->
|
||||
Thread({
|
||||
val port = WirelessAdbFix.findConnectPort(this@FrontEndActivity, host)
|
||||
ui.post { complete(port) }
|
||||
}, "wireless-adb-discovery").start()
|
||||
},
|
||||
onWirelessAdbApply = { host, port, enabled, complete ->
|
||||
Thread({
|
||||
val result = runCatching { WirelessAdbFix.setChildProcessLimit(this@FrontEndActivity, host, port, enabled) }
|
||||
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: getString(R.string.main_wadb_command_failed) }
|
||||
ui.post {
|
||||
if (error == null) refreshPhantomStatus()
|
||||
complete(error)
|
||||
}
|
||||
}, "wireless-adb-fix").start()
|
||||
},
|
||||
onSetPhantomProcessLimit = { enabled, complete ->
|
||||
Thread({
|
||||
val result = runCatching { WirelessAdbFix.setUsingSavedPairing(this@FrontEndActivity, enabled) }
|
||||
@@ -1798,14 +1801,18 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
)
|
||||
android.widget.Toast.makeText(this, R.string.main_adb_copied, android.widget.Toast.LENGTH_SHORT).show()
|
||||
},
|
||||
onDismissPhantomGate = { queuedLaunch.clear(); showPhantomGate = false },
|
||||
onDismissPhantomGate = { showPhantomGate = false },
|
||||
onShowPhantomGate = {
|
||||
refreshPhantomStatus()
|
||||
showPhantomGate = true
|
||||
},
|
||||
onStartWirelessAdbPairing = { enabled -> WirelessAdbPairingService.start(this, enabled) },
|
||||
onStartWirelessAdbPairing = { WirelessAdbPairingService.start(this) },
|
||||
onStartPairingGuide = { displayId, toggleOnly -> PairingGuideActivity.start(this, displayId, toggleOnly) },
|
||||
onEnsureNotifications = { done -> ensureNotifications(done) },
|
||||
onOpenNotificationSettings = {
|
||||
startActivity(Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS)
|
||||
.putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, packageName)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
},
|
||||
updates = updates.actions(),
|
||||
controller = ControllerActions(
|
||||
onMapping = { showPerformance = false; showComponents = false; showMapping = true },
|
||||
@@ -1985,7 +1992,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
|
||||
private fun startSteamSession(steamVr: Boolean = false) {
|
||||
startSession(Intent(this, SessionActivity::class.java).putExtra(SessionActivity.EXTRA_STEAMVR, steamVr), steamSession = true, queueIfBlocked = !steamVr)
|
||||
startSession(Intent(this, SessionActivity::class.java).putExtra(SessionActivity.EXTRA_STEAMVR, steamVr), steamSession = true)
|
||||
}
|
||||
|
||||
@Suppress("OVERRIDE_DEPRECATION")
|
||||
@@ -2006,7 +2013,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
if (!hasFocus) triggerKeys.cancel()
|
||||
if (hasFocus) {
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
|
||||
applyLauncherFullscreen()
|
||||
@@ -2036,36 +2042,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
}
|
||||
|
||||
private var touchDownX = 0f
|
||||
private var touchDownY = 0f
|
||||
private var touchDragged = false
|
||||
|
||||
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
com.droiddeck.launcher.ui.ScreenTaps.count++
|
||||
touchDownX = event.rawX
|
||||
touchDownY = event.rawY
|
||||
touchDragged = false
|
||||
}
|
||||
// A drag that wanders back to where it began is still a drag, not a tap.
|
||||
MotionEvent.ACTION_MOVE -> if (!touchDragged &&
|
||||
kotlin.math.hypot(event.rawX - touchDownX, event.rawY - touchDownY) > ViewConfiguration.get(this).scaledTouchSlop
|
||||
) touchDragged = true
|
||||
MotionEvent.ACTION_CANCEL -> touchDragged = true
|
||||
}
|
||||
val handled = super.dispatchTouchEvent(event)
|
||||
if (event.actionMasked == MotionEvent.ACTION_UP) leaveTextFieldOnOutsideTap(event)
|
||||
return handled
|
||||
}
|
||||
|
||||
private fun leaveTextFieldOnOutsideTap(event: MotionEvent) {
|
||||
val field = currentFocus as? EditText ?: return
|
||||
val slop = ViewConfiguration.get(this).scaledTouchSlop
|
||||
if (touchDragged || kotlin.math.hypot(event.rawX - touchDownX, event.rawY - touchDownY) > slop) return
|
||||
com.droiddeck.launcher.ui.releaseTextField(field, IntArray(2).also(field::getLocationOnScreen), event.rawX, event.rawY)
|
||||
}
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true
|
||||
if (compatLaunch != null) {
|
||||
@@ -2076,14 +2052,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
if (!compatLaunch!!.loading.ended && event.keyCode !in listOf(
|
||||
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE)) return true
|
||||
}
|
||||
if (!triggerKeys.synthesizing && triggerKeys.nativeKey(event)) return true
|
||||
val tabStep = com.droiddeck.launcher.ui.dualPageStep(event)
|
||||
val tabs = com.droiddeck.launcher.ui.MainTabSteps.handler
|
||||
if (tabStep != null && tabs != null) {
|
||||
if (controllerHaptics) com.droiddeck.launcher.ui.ControllerHaptics.onKey(this, event)
|
||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) tabs(tabStep)
|
||||
return true
|
||||
}
|
||||
if (controllerHaptics) com.droiddeck.launcher.ui.ControllerHaptics.onKey(this, event)
|
||||
if (event.keyCode == KeyEvent.KEYCODE_BUTTON_A) com.droiddeck.launcher.ui.HeldKeys.confirm = event.action == KeyEvent.ACTION_DOWN
|
||||
if (showComponents && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
|
||||
@@ -2101,12 +2069,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
}
|
||||
|
||||
private val triggerKeys = com.droiddeck.launcher.input.TriggerKeys { dispatchKeyEvent(it) }
|
||||
|
||||
override fun dispatchGenericMotionEvent(event: android.view.MotionEvent): Boolean {
|
||||
if (compatLaunch != null && !compatLaunch!!.loading.ended &&
|
||||
com.droiddeck.launcher.input.PadBridge.isControllerMotionEvent(event)) return true
|
||||
triggerKeys.onMotion(event)
|
||||
return super.dispatchGenericMotionEvent(event)
|
||||
}
|
||||
|
||||
@@ -2156,7 +2121,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
if (!OfflineMode.enabled(this)) {
|
||||
val updated = runCatching { ComponentUpdater.ensure(this, force = false) }
|
||||
.onFailure { android.util.Log.w("ComponentUpdater", "automatic component updates", it) }.getOrDefault(emptyList())
|
||||
if (updated.isNotEmpty()) android.util.Log.i("ComponentUpdater", updated.joinToString("; "))
|
||||
if (updated.isNotEmpty()) ui.post {
|
||||
android.widget.Toast.makeText(this, updated.joinToString("\n"), android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
ui.post {
|
||||
componentsQueueBusy = false
|
||||
@@ -2208,10 +2175,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
outState.putBoolean(STATE_HOME_CHOICE_OPEN, homeChoiceOpen)
|
||||
outState.putBoolean(STATE_GAME_SPACE_OFFERED, gameSpaceOffered)
|
||||
pendingSessionLogExport?.let { outState.putString(KEY_PENDING_SESSION_LOG_EXPORT, it.absolutePath) }
|
||||
queuedLaunch.launch?.let {
|
||||
outState.putParcelable(STATE_PENDING_GATE_LAUNCH, it)
|
||||
outState.putLong(STATE_PENDING_GATE_LAUNCH_AT, queuedLaunch.queuedAt)
|
||||
}
|
||||
if (slowUsbNever) SessionPrefs.setSlowUsbWarningOff(this)
|
||||
saveCompatLaunch(outState)
|
||||
pendingSwitch?.let { outState.putParcelable(KEY_PENDING_SWITCH, it) }
|
||||
@@ -2238,9 +2201,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
// The queued launch was saved before this; a restored activity keeps its copy, and this one must not start it too.
|
||||
queuedLaunchRunner.destroy()
|
||||
triggerKeys.cancel()
|
||||
gameLaunchRequest.incrementAndGet()
|
||||
cancelCompatLaunch()
|
||||
updates.unregister()
|
||||
@@ -2302,9 +2262,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
val ownDisplayId = if (android.os.Build.VERSION.SDK_INT >= 30) display?.displayId ?: android.view.Display.DEFAULT_DISPLAY else @Suppress("DEPRECATION") windowManager.defaultDisplay.displayId
|
||||
dualScreenMode = SessionPrefs.dualScreenMode(this)
|
||||
secondScreenDisplays = SecondScreenDisplays.available(displayManager, ownDisplayId)
|
||||
ownScreen = ownDisplayId.takeIf { it != Display.DEFAULT_DISPLAY }?.let { id ->
|
||||
displayManager.getDisplay(id)?.takeIf { it.isValid }?.let { SecondScreenDisplay(id, "${it.name} · ${it.mode.physicalWidth}×${it.mode.physicalHeight}") }
|
||||
}
|
||||
dualScreenDevice = com.droiddeck.launcher.input.DualScreen.anyDisplay(displayManager, ownDisplayId) != null
|
||||
dualScreenSessions = SessionPrefs.dualScreenSessionMode(this)
|
||||
dualScreenControls = SessionPrefs.dualScreenSessionControls(this)
|
||||
@@ -2325,24 +2282,17 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
private fun launchAndroidApp(app: HomeApp.LaunchableApp, displayId: Int?) {
|
||||
val onOwnScreen = displayId == null || displayId == (display?.displayId ?: Display.DEFAULT_DISPLAY)
|
||||
if (onOwnScreen) com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, true)
|
||||
val open = {
|
||||
try {
|
||||
HomeApp.launch(this, app, displayId)
|
||||
} catch (_: Exception) {
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
|
||||
val label = secondScreenDisplays.firstOrNull { it.id == displayId }?.label
|
||||
val message = when {
|
||||
displayId == null || displayId == Display.DEFAULT_DISPLAY -> getString(R.string.android_app_open_failed_primary, app.label)
|
||||
label != null -> getString(R.string.android_app_open_failed_on, app.label, label)
|
||||
else -> getString(R.string.android_app_open_failed_display, app.label, displayId)
|
||||
}
|
||||
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_SHORT).show()
|
||||
try {
|
||||
HomeApp.launch(this, app, displayId)
|
||||
} catch (_: Exception) {
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
|
||||
val label = secondScreenDisplays.firstOrNull { it.id == displayId }?.label
|
||||
val message = when {
|
||||
displayId == null || displayId == Display.DEFAULT_DISPLAY -> getString(R.string.android_app_open_failed_primary, app.label)
|
||||
label != null -> getString(R.string.android_app_open_failed_on, app.label, label)
|
||||
else -> getString(R.string.android_app_open_failed_display, app.label, displayId)
|
||||
}
|
||||
}
|
||||
if (displayId != null && displayId == com.droiddeck.launcher.ui.DualScreenPanel.shownOn) {
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.makeRoomForApp(this, displayId, open)
|
||||
} else {
|
||||
open()
|
||||
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2694,7 +2644,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
deckyChecking = decky.deckyChecking, deckyStage = decky.deckyStage, deckyPercent = decky.deckyPercent,
|
||||
deckyDownloadingBinary = decky.deckyDownloadingBinary,
|
||||
deckyEnabled = decky.deckySupervisor, deckySessionRunning = SessionState.running,
|
||||
deckyPlugins = decky.deckyPlugins, deckyStore = decky.deckyStore, deckyStoreFailed = decky.deckyStoreFailed,
|
||||
),
|
||||
ModeSettingsActions(
|
||||
onIntegration = ::configureIntegration,
|
||||
@@ -2805,9 +2754,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
decky.deckyInstalled = null
|
||||
decky.deckySupervisor = false
|
||||
},
|
||||
onDeckyStoreRefresh = { decky.refreshStore() },
|
||||
onDeckyStoreInstall = { plugin -> decky.installStorePlugin(plugin) },
|
||||
onDeckyRemove = { plugin -> decky.removePlugin(plugin) },
|
||||
onPickDeckyPluginZip = {
|
||||
pickDeckyPluginZip.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, getString(R.string.main_pick_decky_zip)))
|
||||
},
|
||||
@@ -3098,7 +3044,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
decky.deckyInstalled = deckyInstalled
|
||||
decky.deckySupervisor = deckySupervisor
|
||||
decky.refreshDecky()
|
||||
decky.refreshPlugins()
|
||||
}
|
||||
fetchAddedGameArt()
|
||||
}
|
||||
@@ -3213,7 +3158,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
bridgeProtonDxvk = SessionPrefs.bridgeProtonDxvk(this)
|
||||
removalPending = LinuxRuntimeInstaller.hasRemovalPending(this)
|
||||
ui.post { autoUpdateRuntime() }
|
||||
Thread({ com.droiddeck.launcher.session.Onboarding.recheck(this) }, "onboarding-recheck").start()
|
||||
frameGenLabel = FrameGen.label(this)
|
||||
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
|
||||
logsEnabled = SessionPrefs.logsEnabled(this)
|
||||
@@ -3339,7 +3283,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
install(release)
|
||||
}
|
||||
|
||||
private fun startSession(intent: Intent, steamSession: Boolean = false, queueIfBlocked: Boolean = false): Boolean {
|
||||
private fun startSession(intent: Intent, steamSession: Boolean = false): Boolean {
|
||||
if (busy || LinuxRuntimeInstaller.isBusy()) return false
|
||||
if (SessionState.installing != null && !SessionState.running) {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
|
||||
@@ -3351,7 +3295,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
refreshPhantomStatus()
|
||||
if (steamSession && PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
|
||||
if (queueIfBlocked) queuedLaunch.queue(intent, System.currentTimeMillis())
|
||||
showPhantomGate = true
|
||||
return false
|
||||
}
|
||||
@@ -3361,64 +3304,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
return true
|
||||
}
|
||||
|
||||
private var notificationsDone: ((Boolean) -> Unit)? = null
|
||||
|
||||
private fun ensureNotifications(done: (Boolean) -> Unit) {
|
||||
if (WirelessAdbPairingService.notificationsEnabled(this)) {
|
||||
done(true)
|
||||
return
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
|
||||
notificationsDone = done
|
||||
requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), REQUEST_NOTIFICATIONS)
|
||||
return
|
||||
}
|
||||
openNotificationSettings()
|
||||
done(false)
|
||||
}
|
||||
|
||||
private fun openNotificationSettings() {
|
||||
android.widget.Toast.makeText(this, R.string.gate_notifications_toast, android.widget.Toast.LENGTH_LONG).show()
|
||||
val appAllowed = getSystemService(android.app.NotificationManager::class.java)?.areNotificationsEnabled() != false
|
||||
val intent = if (appAllowed && WirelessAdbPairingService.channelBlocked(this)) {
|
||||
Intent(android.provider.Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS)
|
||||
.putExtra(android.provider.Settings.EXTRA_CHANNEL_ID, WirelessAdbPairingService.channelId())
|
||||
} else {
|
||||
Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS)
|
||||
}
|
||||
startActivity(intent.putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, packageName).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
}
|
||||
|
||||
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
|
||||
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
|
||||
if (requestCode != REQUEST_NOTIFICATIONS) return
|
||||
val done = notificationsDone ?: return
|
||||
notificationsDone = null
|
||||
val granted = WirelessAdbPairingService.notificationsEnabled(this)
|
||||
if (!granted) openNotificationSettings()
|
||||
done(granted)
|
||||
}
|
||||
|
||||
private val queuedLaunch = com.droiddeck.launcher.session.QueuedLaunch<Intent>(GATE_LAUNCH_MS)
|
||||
private val queuedLaunchRunner = com.droiddeck.launcher.session.QueuedLaunchRunner(
|
||||
queue = queuedLaunch,
|
||||
now = System::currentTimeMillis,
|
||||
blocked = { PhantomProcessLimit.blocksSteam(phantomProcessStatus) },
|
||||
busy = ::steamStartBusy,
|
||||
schedule = { delay, task -> if (delay <= 0L) ui.post(task) else ui.postDelayed(task, delay) },
|
||||
unschedule = ui::removeCallbacks,
|
||||
start = { launch -> startSession(launch, steamSession = true, queueIfBlocked = true) },
|
||||
retryMs = GATE_LAUNCH_RETRY_MS,
|
||||
)
|
||||
|
||||
/** The conditions under which a Steam start waits instead of being refused: setup, a runtime or desktop install, or a storage cleanup. */
|
||||
private fun steamStartBusy(): Boolean = busy || LinuxRuntimeInstaller.isBusy() || com.droiddeck.launcher.session.Onboarding.settling() ||
|
||||
(SessionState.installing != null && !SessionState.running) || com.droiddeck.launcher.storage.StorageState.cleaning
|
||||
|
||||
private fun refreshPhantomStatus() {
|
||||
phantomProcessStatus = PhantomProcessLimit.read(this)
|
||||
if (queuedLaunch.launch != null && !PhantomProcessLimit.blocksSteam(phantomProcessStatus)) showPhantomGate = false
|
||||
queuedLaunchRunner.poke()
|
||||
adbPaired = WirelessAdbFix.hasSavedPairing(this)
|
||||
phantomWarning = if (PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
|
||||
getString(
|
||||
@@ -3430,7 +3317,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
|
||||
private fun openDeveloperOptions(displayId: Int?) {
|
||||
val highlight = if (PhantomProcessLimit.hasDeveloperToggle() &&
|
||||
WirelessAdbPairingService.stage.value == WirelessAdbPairingService.Stage.Idle) "disable_phantom_process_monitor" else "toggle_adb_wireless"
|
||||
WirelessAdbPairingService.stage.value == WirelessAdbPairingService.Stage.Idle) null else "toggle_adb_wireless"
|
||||
val intent = Intent(android.provider.Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
.apply { if (highlight != null) putExtra(":settings:fragment_args_key", highlight) }
|
||||
@@ -3492,24 +3379,18 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
|
||||
private fun install(release: LinuxRuntimeInstaller.Release) {
|
||||
com.droiddeck.launcher.runtime.RuntimeInstallService.start(this, release)
|
||||
followRuntimeOperation(onboarding = true) { listener -> LinuxRuntimeInstaller.install(this, release, listener) }
|
||||
followRuntimeOperation { listener -> LinuxRuntimeInstaller.install(this, release, listener) }
|
||||
}
|
||||
|
||||
private fun followRuntimeOperation(onboarding: Boolean = false, run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) {
|
||||
private fun followRuntimeOperation(run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) {
|
||||
busy = true
|
||||
failed = false
|
||||
stage = getString(if (LinuxRuntimeInstaller.isMaintaining()) R.string.desktop_removing else if (LinuxRuntimeInstaller.isRemoving()) R.string.main_removing_runtime else R.string.store_starting)
|
||||
percent = -1
|
||||
Thread({
|
||||
val ok = run(LinuxRuntimeInstaller.ProgressListener { s, p ->
|
||||
if (onboarding) com.droiddeck.launcher.session.Onboarding.report(com.droiddeck.launcher.session.Onboarding.Step.RUNTIME, s, p)
|
||||
ui.post { stage = s; percent = p }
|
||||
})
|
||||
if (onboarding) {
|
||||
if (ok == false) com.droiddeck.launcher.session.Onboarding.fail(com.droiddeck.launcher.session.Onboarding.Step.RUNTIME, LinuxRuntimeInstaller.removalError() ?: "")
|
||||
else com.droiddeck.launcher.session.Onboarding.finish(com.droiddeck.launcher.session.Onboarding.Step.RUNTIME)
|
||||
}
|
||||
com.droiddeck.launcher.session.Onboarding.recheck(this)
|
||||
ui.post {
|
||||
busy = false
|
||||
if (ok != null) failed = !ok
|
||||
@@ -3518,7 +3399,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
refresh()
|
||||
com.droiddeck.launcher.agent.AgentHost.refresh(this)
|
||||
if (ok == true && LinuxRuntime.isInstalled(this)) { protons.checkUpdates(); protons.ensureSteamClient() }
|
||||
if (ok == true && LinuxRuntime.isInstalled(this)) protons.checkUpdates()
|
||||
}
|
||||
}, "runtime-operation").start()
|
||||
}
|
||||
@@ -3529,10 +3410,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
if (installed != null) com.droiddeck.launcher.runtime.RuntimeAutoUpdate.seed(this)
|
||||
if (release.version == installed) return
|
||||
if (installed == null && (OfflineMode.enabled(this) || !com.droiddeck.launcher.core.DeviceSupport.canDraw(this) ||
|
||||
!com.droiddeck.launcher.frontend.AutoComponents.online(this) || com.droiddeck.launcher.frontend.AutoComponents.firstRunHeldBack(this))) return
|
||||
!com.droiddeck.launcher.frontend.AutoComponents.online(this) || com.droiddeck.launcher.frontend.AutoComponents.unfavourable(this))) return
|
||||
if (com.droiddeck.launcher.runtime.RuntimeAutoUpdate.claim(this, installed, release.version)) {
|
||||
Log.i(TAG, "runtime: installing ${release.version} over ${installed ?: "nothing"} by itself")
|
||||
if (installed == null) protons.prefetchOwn()
|
||||
install(release)
|
||||
}
|
||||
}
|
||||
@@ -3549,12 +3429,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val REQUEST_NOTIFICATIONS = 7103
|
||||
private const val STATE_HOME_CHOICE_OPEN = "home_choice_open"
|
||||
private const val STATE_PENDING_GATE_LAUNCH = "pending_gate_launch"
|
||||
private const val STATE_PENDING_GATE_LAUNCH_AT = "pending_gate_launch_at"
|
||||
private const val GATE_LAUNCH_MS = 15 * 60_000L
|
||||
private const val GATE_LAUNCH_RETRY_MS = 2_000L
|
||||
private const val KEY_PENDING_SESSION_LOG_EXPORT = "pending_session_log_export"
|
||||
private const val STATE_GAME_SPACE_OFFERED = "game_space_offered"
|
||||
private const val TAG = "MainActivity"
|
||||
|
||||
@@ -93,14 +93,6 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
launchPending = true
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
val stage = WirelessAdbPairingService.stage.value
|
||||
if (isFinishing && (stage is WirelessAdbPairingService.Stage.Waiting || stage is WirelessAdbPairingService.Stage.CodeNeeded)) {
|
||||
WirelessAdbPairingService.cancel(this)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
if (!launchPending) return
|
||||
|
||||
@@ -8,9 +8,7 @@ import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.session.ExperimentalProtons
|
||||
import com.droiddeck.launcher.session.Onboarding
|
||||
import com.droiddeck.launcher.session.ProtonExtras
|
||||
import com.droiddeck.launcher.session.SteamClientPrefetch
|
||||
import com.droiddeck.launcher.ui.ProtonRow
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.session.SessionPhase
|
||||
@@ -62,15 +60,10 @@ internal class ProtonMenu(
|
||||
Thread({
|
||||
val problem = runCatching {
|
||||
installer(tool) { label, value ->
|
||||
if (tool.id == ProtonExtras.OWN) Onboarding.report(Onboarding.Step.PROTON, label, value)
|
||||
ui.post { protonStage = label; protonPercent = value }
|
||||
}
|
||||
}.getOrElse { it.message ?: it.javaClass.simpleName }
|
||||
if (problem == null && !automatic && tool.id == ProtonExtras.OWN) ProtonExtras.setDeclined(activity, false)
|
||||
if (tool.id == ProtonExtras.OWN) {
|
||||
if (problem == null) Onboarding.finish(Onboarding.Step.PROTON) else Onboarding.fail(Onboarding.Step.PROTON, problem)
|
||||
Onboarding.recheck(activity)
|
||||
}
|
||||
ui.post {
|
||||
protonProblem = problem
|
||||
protonBusyId = null
|
||||
@@ -177,46 +170,16 @@ internal class ProtonMenu(
|
||||
Operation.checking.set(false)
|
||||
}
|
||||
ensureAutoUpdates()
|
||||
ensureSteamClient()
|
||||
}
|
||||
if (!published) Operation.checking.set(false)
|
||||
}, "proton-updates").start()
|
||||
}
|
||||
|
||||
/** Downloads the DroidDeck Proton archive while the runtime installs; the install step later finds it whole. */
|
||||
fun prefetchOwn() {
|
||||
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
|
||||
if (ProtonExtras.declined(activity) || ProtonExtras.installedAll(activity, tool).isNotEmpty() ||
|
||||
ProtonExtras.installInProgress || !AutoComponents.online(activity) || AutoComponents.firstRunHeldBack(activity)) return
|
||||
Thread({
|
||||
val problem = runCatching {
|
||||
ProtonExtras.prefetch(activity, tool) { label, value -> Onboarding.report(Onboarding.Step.PROTON, label, value) }
|
||||
}.getOrElse { it.message ?: it.javaClass.simpleName }
|
||||
if (problem == null) Onboarding.finish(Onboarding.Step.PROTON) else Onboarding.fail(Onboarding.Step.PROTON, problem)
|
||||
Onboarding.recheck(activity)
|
||||
ui.post { ensureAutoUpdates() }
|
||||
}, "proton-prefetch").start()
|
||||
}
|
||||
|
||||
/** Fetches Steam's client in the background once the runtime exists, so the first Play does not wait for it. */
|
||||
fun ensureSteamClient() {
|
||||
if (activity.isFinishing || activity.isDestroyed || !idle() || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
|
||||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) || !LinuxRuntime.isInstalled(activity) ||
|
||||
!AutoComponents.online(activity) || AutoComponents.firstRunHeldBack(activity) || SteamClientPrefetch.running()) return
|
||||
SteamClientPrefetch.start(
|
||||
activity,
|
||||
{ mb -> activity.getString(if (mb > 0) R.string.onboarding_steam_downloading_mb else R.string.onboarding_steam_downloading, mb) },
|
||||
activity.getString(R.string.onboarding_steam_failed),
|
||||
)
|
||||
}
|
||||
|
||||
internal fun ensureAutoUpdates(now: Long = System.currentTimeMillis()) {
|
||||
if (activity.isFinishing || activity.isDestroyed || !idle() || protonBusyId != null ||
|
||||
ProtonExtras.installInProgress || ProtonExtras.prefetching || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
|
||||
ProtonExtras.installInProgress || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
|
||||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) ||
|
||||
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity)) return
|
||||
val firstInstall = !ProtonExtras.declined(activity) && ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).isEmpty()
|
||||
if (if (firstInstall) AutoComponents.firstRunHeldBack(activity) else AutoComponents.unfavourable(activity)) return
|
||||
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity) || AutoComponents.unfavourable(activity)) return
|
||||
if (ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size > 1) {
|
||||
protonBusyId = ProtonExtras.OWN
|
||||
protonProblem = null
|
||||
|
||||
@@ -154,8 +154,6 @@ import com.droiddeck.launcher.session.ComponentsManager
|
||||
import com.droiddeck.launcher.session.LatestRequestCoordinator
|
||||
import com.droiddeck.launcher.ui.SessionDrawerPage
|
||||
import com.droiddeck.launcher.ui.sessionDrawerPages
|
||||
import com.droiddeck.launcher.ui.strip
|
||||
import com.droiddeck.launcher.ui.tabFor
|
||||
import com.droiddeck.launcher.ui.step
|
||||
import kotlin.math.abs
|
||||
|
||||
@@ -596,7 +594,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
private var backHold by mutableStateOf(true)
|
||||
private var dockedMenuController by mutableStateOf(false)
|
||||
private var sessionOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
|
||||
private var dualScreenSessionMode by mutableStateOf(com.droiddeck.launcher.input.DualScreen.MODE_AUTO)
|
||||
private var backActionsInverted by mutableStateOf(false)
|
||||
private var backDoubleTapMs by mutableStateOf(500)
|
||||
private var lowLatency by mutableStateOf(true)
|
||||
@@ -850,8 +847,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
SessionState.bottomMenu = false
|
||||
SessionState.secondScreenProvisional = false
|
||||
SessionState.secondScreenAutomatic = false
|
||||
SessionState.gameOnBottom = SessionPrefs.dualScreenSessionMode(this) == com.droiddeck.launcher.input.DualScreen.MODE_SWAPPED
|
||||
gameOnBottom = SessionState.gameOnBottom
|
||||
SessionState.gameOnBottom = false
|
||||
gameOnBottom = false
|
||||
}
|
||||
if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) {
|
||||
SessionState.program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
|
||||
@@ -936,6 +933,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
SteamControllerBle.listener = { uiHandler.post { updatePadMotion(); refreshControls() } }
|
||||
steamController = SteamControllerBle(this, inputRouter).also { it.start() }
|
||||
if (Build.VERSION.SDK_INT >= 31 && checkSelfPermission(BLUETOOTH_CONNECT) != android.content.pm.PackageManager.PERMISSION_GRANTED &&
|
||||
!SessionPrefs.bluetoothAsked(this)) {
|
||||
SessionPrefs.setBluetoothAsked(this)
|
||||
requestPermissions(arrayOf(BLUETOOTH_CONNECT), REQUEST_BLUETOOTH)
|
||||
}
|
||||
padMotion = com.droiddeck.launcher.input.PadMotion(this) {
|
||||
@Suppress("DEPRECATION")
|
||||
(if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay)?.rotation ?: android.view.Surface.ROTATION_0
|
||||
@@ -1533,8 +1535,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
fexPreset = fexPreset,
|
||||
secondScreenMode = secondScreenMode,
|
||||
secondScreenNone = !bottomOutputActive && !dockDrawer(),
|
||||
dualScreenMode = dualScreenSessionMode,
|
||||
onDualScreenMode = ::chooseDualScreenSessionMode,
|
||||
gameOnBottom = bottomOutputActive,
|
||||
gameSwapAvailable = bottomSwapAvailable,
|
||||
gameSwapBuiltIn = !::displayManager.isInitialized || displayManager.getDisplay(selectedSecondScreenDisplay)
|
||||
@@ -2659,7 +2659,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
backHold = SessionPrefs.backHold(this)
|
||||
dockedMenuController = SessionPrefs.dockedMenuController(this)
|
||||
sessionOrientation = SessionPrefs.orientation(this)
|
||||
dualScreenSessionMode = SessionPrefs.dualScreenSessionMode(this)
|
||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||
physicalShortcuts.bindings = PhysicalShortcuts.read(this)
|
||||
backDoubleTapMs = SessionPrefs.backDoubleTapMs(this)
|
||||
@@ -3665,9 +3664,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
if (drawerOpen && (menuOwnsController || (!fromController && !(dockedTouchOnly && event.keyCode == KeyEvent.KEYCODE_BACK)))) {
|
||||
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
|
||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||
// The bumpers walk the tabs on the strip; a page kept inside More counts as the More tab.
|
||||
val pages = sessionDrawerPages(glasses.present)
|
||||
drawerPage = pages.strip().step(pages.tabFor(drawerPage), if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
|
||||
drawerPage = sessionDrawerPages(glasses.present)
|
||||
.step(drawerPage, if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
|
||||
releaseDrawerDirection()
|
||||
}
|
||||
return true
|
||||
@@ -4398,32 +4396,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
} else if (wanted != secondScreenMode) selectSecondScreenMode(wanted) else secondScreenPresentation?.retryTerminal()
|
||||
}
|
||||
|
||||
private fun chooseDualScreenSessionMode(mode: String) {
|
||||
if (mode !in com.droiddeck.launcher.input.DualScreen.modes || mode == dualScreenSessionMode) return
|
||||
SessionPrefs.setDualScreenSessionMode(this, mode)
|
||||
dualScreenSessionMode = mode
|
||||
SessionState.secondScreenAutoOpened = false
|
||||
val menuOnBottom = drawerDocked
|
||||
val menuOnTop = drawerOpenState && !drawerDocked
|
||||
if (mode == com.droiddeck.launcher.input.DualScreen.MODE_SWAPPED) {
|
||||
putGameOnBottom(true)
|
||||
} else if (gameOnBottom && mode != com.droiddeck.launcher.input.DualScreen.MODE_OFF) {
|
||||
putGameOnBottom(false)
|
||||
}
|
||||
if (mode == com.droiddeck.launcher.input.DualScreen.MODE_OFF) {
|
||||
if (gameOnBottom) putGameOnBottom(false)
|
||||
if (secondScreenMode != SecondScreenMode.NONE || menuOnBottom) closeSecondScreen(reset = true)
|
||||
if (menuOnBottom) drawerOpen = true
|
||||
} else if (menuOnTop) {
|
||||
// The menu moves to the second screen as the menu itself, not as one of the control panels.
|
||||
SessionState.secondScreenAutoOpened = true
|
||||
refreshSecondScreenDisplays()
|
||||
pinDockedMenu()
|
||||
return
|
||||
}
|
||||
refreshSecondScreenDisplays()
|
||||
}
|
||||
|
||||
private fun selectSecondScreenDisplay(displayId: Int) {
|
||||
if (secondScreenDisplays.none { it.id == displayId }) return
|
||||
selectedSecondScreenDisplay = displayId
|
||||
@@ -4504,7 +4476,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
private fun pickSecondScreenMode(mode: SecondScreenMode) {
|
||||
typingReturnMode = null
|
||||
automaticPanel = false
|
||||
SessionState.bottomMenu = false
|
||||
if (mode != SecondScreenMode.NONE) SessionPrefs.setSecondScreenPanel(this, desktopSession, mode.id)
|
||||
selectSecondScreenMode(mode)
|
||||
}
|
||||
@@ -5986,11 +5957,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
if (secondScreenPresentation == null) showSecondScreen(secondScreenMode)
|
||||
if (com.droiddeck.launcher.input.DualScreen.menuReturnsOnStart(openingPanel(), SessionState.bottomMenu, menuShownOnBottom())) pinDockedMenu()
|
||||
SessionState.bottomMenu = false
|
||||
} else {
|
||||
if (SessionState.bottomMenu && !menuShownOnBottom()) pinDockedMenu()
|
||||
SessionState.bottomMenu = false
|
||||
if (!menuShownOnBottom()) openDualScreenControls()
|
||||
}
|
||||
} else openDualScreenControls()
|
||||
startedScreens++
|
||||
SessionService.setActivityVisible(this, true, sessionActivityDisplayId)
|
||||
Glasses.rescan()
|
||||
|
||||
@@ -16,7 +16,7 @@ object SteamIntegration {
|
||||
const val EXTRA_FEATURE = "integration_feature"
|
||||
const val SHORTCUTS_STATUS = "com.droiddeck.launcher.SHORTCUTS_INSTALL_STATUS"
|
||||
private const val SHORTCUTS_ASSET = "shortcuts.apk"
|
||||
enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS, BLUETOOTH }
|
||||
enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS }
|
||||
|
||||
data class State(
|
||||
val wifi: Boolean = false,
|
||||
@@ -28,7 +28,6 @@ object SteamIntegration {
|
||||
val shortcuts: Boolean = false,
|
||||
val shortcutsRestricted: Boolean = false,
|
||||
val shortcutsTried: Boolean = false,
|
||||
val bluetooth: Boolean = false,
|
||||
val suggested: Boolean = true,
|
||||
)
|
||||
|
||||
@@ -40,16 +39,9 @@ object SteamIntegration {
|
||||
home = HomeApp.isDefault(context),
|
||||
shortcuts = shortcutsEnabled(context) && shortcutsCurrent(context),
|
||||
shortcutsRestricted = restrictedSettings(context),
|
||||
bluetooth = bluetoothAllowed(context),
|
||||
suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false),
|
||||
)
|
||||
|
||||
fun bluetoothAllowed(context: Context): Boolean =
|
||||
android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.S ||
|
||||
context.checkSelfPermission(android.Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
fun appInfo(context: Context) = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${context.packageName}"))
|
||||
|
||||
private fun restrictedSettings(context: Context): Boolean {
|
||||
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return false
|
||||
val mode = runCatching {
|
||||
|
||||
@@ -38,8 +38,6 @@ class WirelessAdbPairingService : Service() {
|
||||
private var pairingHost: String? = null
|
||||
private var pairingPort: Int? = null
|
||||
@Volatile private var working = false
|
||||
@Volatile private var limitEnabled = false
|
||||
@Volatile private var session = 0
|
||||
private val timeout = Runnable { finish(Stage.Failed(getString(R.string.adbpair_timed_out))) }
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
@@ -52,15 +50,12 @@ class WirelessAdbPairingService : Service() {
|
||||
onCode(code)
|
||||
}
|
||||
ACTION_CANCEL -> finish(Stage.Idle)
|
||||
else -> begin(intent?.getBooleanExtra(EXTRA_ENABLE_LIMIT, false) == true)
|
||||
else -> begin()
|
||||
}
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
private fun begin(enableLimit: Boolean) {
|
||||
if (working) return
|
||||
session++
|
||||
limitEnabled = enableLimit
|
||||
private fun begin() {
|
||||
pairingHost = null
|
||||
pairingPort = null
|
||||
working = false
|
||||
@@ -73,13 +68,12 @@ class WirelessAdbPairingService : Service() {
|
||||
|
||||
private fun startDiscovery() {
|
||||
stopDiscovery()
|
||||
val owner = session
|
||||
val manager = getSystemService(Context.NSD_SERVICE) as NsdManager
|
||||
val listener = object : NsdManager.DiscoveryListener {
|
||||
override fun onDiscoveryStarted(serviceType: String) = Unit
|
||||
override fun onServiceFound(serviceInfo: NsdServiceInfo) {
|
||||
if (serviceInfo.serviceType?.contains(PAIRING_TYPE) != true) return
|
||||
runCatching { manager.resolveService(serviceInfo, resolveListener(owner)) }
|
||||
runCatching { manager.resolveService(serviceInfo, resolveListener()) }
|
||||
}
|
||||
override fun onServiceLost(serviceInfo: NsdServiceInfo) = Unit
|
||||
override fun onDiscoveryStopped(serviceType: String) = Unit
|
||||
@@ -93,20 +87,18 @@ class WirelessAdbPairingService : Service() {
|
||||
.onFailure { finish(Stage.Failed(getString(R.string.adbpair_discovery_failed, it.localizedMessage.toString()))) }
|
||||
}
|
||||
|
||||
private fun resolveListener(owner: Int): NsdManager.ResolveListener {
|
||||
return object : NsdManager.ResolveListener {
|
||||
private fun resolveListener() = object : NsdManager.ResolveListener {
|
||||
override fun onResolveFailed(serviceInfo: NsdServiceInfo, errorCode: Int) = Unit
|
||||
override fun onServiceResolved(serviceInfo: NsdServiceInfo) {
|
||||
val address = serviceInfo.host ?: return
|
||||
if (!WirelessAdbFix.isLocalAddress(address)) return
|
||||
main.post {
|
||||
if (owner != session || working || current.value == Stage.Done) return@post
|
||||
if (working || current.value == Stage.Done) return@post
|
||||
pairingHost = address.hostAddress
|
||||
pairingPort = serviceInfo.port
|
||||
if (current.value !is Stage.CodeNeeded) show(Stage.CodeNeeded())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun onCode(code: String) {
|
||||
@@ -122,34 +114,29 @@ class WirelessAdbPairingService : Service() {
|
||||
return
|
||||
}
|
||||
working = true
|
||||
val owner = session
|
||||
val enable = limitEnabled
|
||||
show(Stage.Working(getString(R.string.adbpair_pairing)))
|
||||
Thread({
|
||||
val paired = runCatching { kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@WirelessAdbPairingService, WirelessAdbFix.LOOPBACK, port, code) } }
|
||||
if (paired.isFailure) {
|
||||
main.post {
|
||||
working = false
|
||||
if (owner != session) return@post
|
||||
pairingPort = null
|
||||
show(Stage.CodeNeeded(getString(R.string.adbpair_code_rejected)))
|
||||
}
|
||||
return@Thread
|
||||
}
|
||||
main.post {
|
||||
if (owner != session) return@post
|
||||
stopDiscovery()
|
||||
show(Stage.Working(getString(R.string.adbpair_connecting)))
|
||||
}
|
||||
val result = runCatching {
|
||||
val connectPort = WirelessAdbFix.localConnectPort(this)
|
||||
?: error(getString(R.string.adbpair_port_not_found))
|
||||
main.post { if (owner == session) show(Stage.Working(getString(R.string.adbpair_applying))) }
|
||||
WirelessAdbFix.setChildProcessLimit(this, WirelessAdbFix.LOOPBACK, connectPort, enable)
|
||||
main.post { show(Stage.Working(getString(R.string.adbpair_applying))) }
|
||||
WirelessAdbFix.setChildProcessLimit(this, WirelessAdbFix.LOOPBACK, connectPort, false)
|
||||
}
|
||||
main.post {
|
||||
working = false
|
||||
if (owner != session) return@post
|
||||
finish(result.exceptionOrNull()?.let { Stage.Failed(it.localizedMessage ?: getString(R.string.adbpair_command_failed)) } ?: Stage.Done)
|
||||
}
|
||||
}, "wireless-adb-pairing").start()
|
||||
@@ -161,7 +148,6 @@ class WirelessAdbPairingService : Service() {
|
||||
}
|
||||
|
||||
private fun finish(stage: Stage) {
|
||||
session++
|
||||
main.removeCallbacks(timeout)
|
||||
stopDiscovery()
|
||||
publish(stage)
|
||||
@@ -262,7 +248,6 @@ class WirelessAdbPairingService : Service() {
|
||||
private const val ACTION_CODE = "com.droiddeck.launcher.action.WIRELESS_ADB_CODE"
|
||||
private const val ACTION_CANCEL = "com.droiddeck.launcher.action.WIRELESS_ADB_CANCEL"
|
||||
private const val KEY_CODE = "code"
|
||||
private const val EXTRA_ENABLE_LIMIT = "enable_limit"
|
||||
private const val TIMEOUT_MS = 5 * 60_000L
|
||||
|
||||
private val current = MutableStateFlow<Stage>(Stage.Idle)
|
||||
@@ -270,10 +255,10 @@ class WirelessAdbPairingService : Service() {
|
||||
|
||||
private fun publish(stage: Stage) { current.value = stage }
|
||||
|
||||
fun start(context: Context, enableLimit: Boolean = false) {
|
||||
fun start(context: Context) {
|
||||
context.getSystemService(NotificationManager::class.java)?.cancel(NOTIFICATION_ID)
|
||||
publish(Stage.Waiting)
|
||||
val intent = Intent(context, WirelessAdbPairingService::class.java).putExtra(EXTRA_ENABLE_LIMIT, enableLimit)
|
||||
val intent = Intent(context, WirelessAdbPairingService::class.java)
|
||||
if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) else context.startService(intent)
|
||||
}
|
||||
|
||||
@@ -286,12 +271,6 @@ class WirelessAdbPairingService : Service() {
|
||||
}
|
||||
|
||||
fun notificationsEnabled(context: Context): Boolean =
|
||||
context.getSystemService(NotificationManager::class.java)?.areNotificationsEnabled() != false && !channelBlocked(context)
|
||||
|
||||
/** The code is typed into a notification on this channel; a channel the user switched off leaves pairing with nothing to type into. */
|
||||
fun channelBlocked(context: Context): Boolean =
|
||||
context.getSystemService(NotificationManager::class.java)?.getNotificationChannel(CHANNEL_ID)?.importance == NotificationManager.IMPORTANCE_NONE
|
||||
|
||||
fun channelId(): String = CHANNEL_ID
|
||||
context.getSystemService(NotificationManager::class.java)?.areNotificationsEnabled() != false
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,6 @@ import androidx.compose.material.icons.filled.ArrowUpward
|
||||
import androidx.compose.material.icons.filled.Checklist
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.FileCopy
|
||||
import androidx.compose.material.icons.filled.FileOpen
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.Info
|
||||
import androidx.compose.material.icons.filled.InsertDriveFile
|
||||
@@ -102,18 +101,8 @@ private fun FileContextMenuItems(
|
||||
onToggleFavorite: () -> Unit,
|
||||
onProperties: () -> Unit,
|
||||
onDismissMenu: () -> Unit,
|
||||
onOpen: () -> Unit,
|
||||
) {
|
||||
val isDir = file.isDirectory
|
||||
if (!isDir) {
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.fm_edit_open)) },
|
||||
leadingIcon = { Icon(Icons.Filled.FileOpen, null, tint = MaterialTheme.colorScheme.primary) },
|
||||
onClick = { onDismissMenu(); onOpen() },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
MenuItemDivider()
|
||||
}
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.fm_select)) },
|
||||
leadingIcon = { Icon(Icons.Filled.Checklist, null, tint = MaterialTheme.colorScheme.primary) },
|
||||
@@ -191,7 +180,6 @@ internal fun FileItemRow(
|
||||
onCut: () -> Unit,
|
||||
onDelete: () -> Unit,
|
||||
onRename: () -> Unit,
|
||||
onOpen: () -> Unit = {},
|
||||
isFavorite: Boolean = false,
|
||||
onToggleFavorite: () -> Unit = {},
|
||||
onProperties: () -> Unit = {},
|
||||
@@ -303,7 +291,6 @@ internal fun FileItemRow(
|
||||
file = file,
|
||||
isFavorite = isFavorite,
|
||||
onSelect = onSelect,
|
||||
onOpen = onOpen,
|
||||
onRename = onRename,
|
||||
onCopy = onCopy,
|
||||
onCut = onCut,
|
||||
@@ -530,7 +517,6 @@ internal fun FileGridTile(
|
||||
isFavorite: Boolean = false,
|
||||
onSelect: () -> Unit = {},
|
||||
onRename: () -> Unit = {},
|
||||
onOpen: () -> Unit = {},
|
||||
onCopy: () -> Unit = {},
|
||||
onCut: () -> Unit = {},
|
||||
onDelete: () -> Unit = {},
|
||||
@@ -619,7 +605,6 @@ internal fun FileGridTile(
|
||||
file = file,
|
||||
isFavorite = isFavorite,
|
||||
onSelect = onSelect,
|
||||
onOpen = onOpen,
|
||||
onRename = onRename,
|
||||
onCopy = onCopy,
|
||||
onCut = onCut,
|
||||
|
||||
@@ -191,7 +191,6 @@ fun FileManagerScreen(
|
||||
var compactRows by remember { mutableStateOf(browsePrefs.getBoolean("fmCompactRows", false)) }
|
||||
var showNewFolderDialog by remember { mutableStateOf(false) }
|
||||
var renameTarget by remember { mutableStateOf<File?>(null) }
|
||||
var editingTarget by remember { mutableStateOf<File?>(null) }
|
||||
var propertiesTarget by remember { mutableStateOf<File?>(null) }
|
||||
var isOperationRunning by remember { mutableStateOf(false) }
|
||||
var operationLabel by remember { mutableStateOf("") }
|
||||
@@ -295,7 +294,7 @@ fun FileManagerScreen(
|
||||
if (isOperationActive()) pendingNavigation = action else navigate(action)
|
||||
}
|
||||
|
||||
BackHandler(enabled = editingTarget == null && (operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot || history.isNotEmpty())) {
|
||||
BackHandler(enabled = operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot || history.isNotEmpty()) {
|
||||
requestNavigation(FileManagerNavigation.BACK)
|
||||
}
|
||||
|
||||
@@ -697,14 +696,6 @@ fun FileManagerScreen(
|
||||
|
||||
val compactToolbar = LocalConfiguration.current.screenWidthDp < 600
|
||||
Column(modifier = Modifier.fillMaxSize()) {
|
||||
editingTarget?.let { target ->
|
||||
TextEditorScreen(
|
||||
file = target,
|
||||
onExit = { editingTarget = null },
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
return@Column
|
||||
}
|
||||
if (pickMode && !pickerTitle.isNullOrEmpty()) {
|
||||
Text(
|
||||
text = pickerTitle,
|
||||
@@ -1203,8 +1194,6 @@ fun FileManagerScreen(
|
||||
pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply()
|
||||
onPick?.invoke(file)
|
||||
}
|
||||
} else {
|
||||
editingTarget = file
|
||||
}
|
||||
},
|
||||
onMenu = { showMenuFor = file },
|
||||
@@ -1216,7 +1205,6 @@ fun FileManagerScreen(
|
||||
selectedPaths = selectedPaths + file.absolutePath
|
||||
showMenuFor = null
|
||||
},
|
||||
onOpen = { editingTarget = file; showMenuFor = null },
|
||||
onRename = { renameTarget = file; showMenuFor = null },
|
||||
onCopy = { clipboardFiles = listOf(file); isCutOperation = false; showMenuFor = null },
|
||||
onCut = { clipboardFiles = listOf(file); isCutOperation = true; showMenuFor = null },
|
||||
@@ -1285,8 +1273,6 @@ fun FileManagerScreen(
|
||||
pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply()
|
||||
onPick?.invoke(file)
|
||||
}
|
||||
} else {
|
||||
editingTarget = file
|
||||
}
|
||||
},
|
||||
onMenu = { showMenuFor = file },
|
||||
@@ -1300,7 +1286,6 @@ fun FileManagerScreen(
|
||||
onCopy = { clipboardFiles = listOf(file); isCutOperation = false; showMenuFor = null },
|
||||
onCut = { clipboardFiles = listOf(file); isCutOperation = true; showMenuFor = null },
|
||||
onDelete = { selectedEntry = file; showMenuFor = null },
|
||||
onOpen = { editingTarget = file; showMenuFor = null },
|
||||
onRename = { renameTarget = file; showMenuFor = null },
|
||||
isFavorite = isFav,
|
||||
onToggleFavorite = {
|
||||
|
||||
@@ -1,726 +0,0 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.ScrollState
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.IntrinsicSize
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
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.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
||||
import androidx.compose.material.icons.filled.KeyboardArrowUp
|
||||
import androidx.compose.material.icons.filled.Save
|
||||
import androidx.compose.material.icons.filled.Search
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.TextRange
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardCapitalization
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.TextFieldValue
|
||||
import androidx.compose.ui.text.rememberTextMeasurer
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.ui.focusGlide
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.File
|
||||
import java.io.InputStream
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.charset.CharacterCodingException
|
||||
import java.nio.charset.Charset
|
||||
import java.nio.charset.CodingErrorAction
|
||||
import java.nio.file.Files
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
internal const val EDITOR_FONT_SIZE_SP = 13
|
||||
internal const val EDITOR_LINE_HEIGHT_SP = 18
|
||||
internal const val EDITOR_TAB_WIDTH = 4
|
||||
internal const val EDITOR_MAX_OPEN_BYTES = 4L * 1024 * 1024
|
||||
internal const val EDITOR_MAX_EDIT_BYTES = 512L * 1024
|
||||
|
||||
internal enum class EditorCharset(val label: String, private val charsetName: String) {
|
||||
UTF8("UTF-8", "UTF-8"),
|
||||
GB18030("GB18030", "GB18030"),
|
||||
;
|
||||
|
||||
val charset: Charset get() = Charset.forName(charsetName)
|
||||
}
|
||||
|
||||
internal enum class EditorLock { NONE, BINARY, TOO_LARGE, PERMISSION, LOSSY }
|
||||
|
||||
internal enum class EditorLoadState { LOADING, READY, TOO_LARGE, UNREADABLE }
|
||||
|
||||
internal data class DecodedEditorText(val text: String, val charset: EditorCharset, val lossy: Boolean)
|
||||
|
||||
internal fun editorIsBinary(bytes: ByteArray, sample: Int = 8192): Boolean {
|
||||
val limit = minOf(bytes.size, sample)
|
||||
for (i in 0 until limit) if (bytes[i].toInt() == 0) return true
|
||||
return false
|
||||
}
|
||||
|
||||
private fun strictDecode(bytes: ByteArray, charset: Charset): String? = try {
|
||||
charset.newDecoder()
|
||||
.onMalformedInput(CodingErrorAction.REPORT)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPORT)
|
||||
.decode(ByteBuffer.wrap(bytes))
|
||||
.toString()
|
||||
} catch (e: CharacterCodingException) {
|
||||
null
|
||||
}
|
||||
|
||||
internal fun decodeEditorText(bytes: ByteArray): DecodedEditorText {
|
||||
strictDecode(bytes, Charsets.UTF_8)?.let { return DecodedEditorText(it, EditorCharset.UTF8, false) }
|
||||
strictDecode(bytes, EditorCharset.GB18030.charset)?.let { return DecodedEditorText(it, EditorCharset.GB18030, false) }
|
||||
return DecodedEditorText(String(bytes, Charsets.UTF_8), EditorCharset.UTF8, true)
|
||||
}
|
||||
|
||||
internal fun resolveEditorSaveTarget(file: File): File {
|
||||
val isLink = runCatching { Files.isSymbolicLink(file.toPath()) }.getOrDefault(false)
|
||||
if (!isLink) return file
|
||||
// rename(2) replaces the link itself, so stage next to and rename onto the real target
|
||||
return runCatching { file.canonicalFile }.getOrDefault(file)
|
||||
}
|
||||
|
||||
internal fun readCapped(input: InputStream, limit: Long): ByteArray? {
|
||||
val out = ByteArrayOutputStream()
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
var total = 0L
|
||||
while (true) {
|
||||
val n = input.read(buffer)
|
||||
if (n < 0) return out.toByteArray()
|
||||
total += n
|
||||
if (total > limit) return null
|
||||
out.write(buffer, 0, n)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun expandEditorTabs(text: String, width: Int = EDITOR_TAB_WIDTH): String {
|
||||
if (text.indexOf('\t') < 0) return text
|
||||
val out = StringBuilder(text.length)
|
||||
var column = 0
|
||||
for (c in text) {
|
||||
when (c) {
|
||||
'\n' -> {
|
||||
out.append(c)
|
||||
column = 0
|
||||
}
|
||||
'\t' -> {
|
||||
val pad = width - (column % width)
|
||||
repeat(pad) { out.append(' ') }
|
||||
column += pad
|
||||
}
|
||||
else -> {
|
||||
out.append(c)
|
||||
column++
|
||||
}
|
||||
}
|
||||
}
|
||||
return out.toString()
|
||||
}
|
||||
|
||||
internal fun lineCountOf(text: String): Int {
|
||||
var lines = 1
|
||||
for (i in text.indices) if (text[i] == '\n') lines++
|
||||
return lines
|
||||
}
|
||||
|
||||
internal fun lineIndexOfOffset(text: String, offset: Int): Int {
|
||||
val end = offset.coerceIn(0, text.length)
|
||||
var line = 0
|
||||
var i = 0
|
||||
while (i < end) {
|
||||
if (text[i] == '\n') line++
|
||||
i++
|
||||
}
|
||||
return line
|
||||
}
|
||||
|
||||
internal fun columnOfOffset(text: String, offset: Int): Int {
|
||||
val end = offset.coerceIn(0, text.length)
|
||||
var start = end
|
||||
while (start > 0 && text[start - 1] != '\n') start--
|
||||
return end - start + 1
|
||||
}
|
||||
|
||||
internal fun findEditorMatches(
|
||||
text: String,
|
||||
query: String,
|
||||
matchCase: Boolean = false,
|
||||
limit: Int = 10000,
|
||||
): List<IntRange> {
|
||||
if (query.isEmpty()) return emptyList()
|
||||
val out = ArrayList<IntRange>()
|
||||
var at = 0
|
||||
while (out.size < limit) {
|
||||
val found = text.indexOf(query, at, ignoreCase = !matchCase)
|
||||
if (found < 0) break
|
||||
out.add(found until found + query.length)
|
||||
at = found + query.length
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
internal fun replaceEditorMatches(text: String, matches: List<IntRange>, replacement: String): String {
|
||||
if (matches.isEmpty()) return text
|
||||
val out = StringBuilder(text.length)
|
||||
var cursor = 0
|
||||
for (m in matches) {
|
||||
if (m.first < cursor || m.last >= text.length) continue
|
||||
out.append(text, cursor, m.first).append(replacement)
|
||||
cursor = m.last + 1
|
||||
}
|
||||
out.append(text, cursor, text.length)
|
||||
return out.toString()
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun TextEditorScreen(
|
||||
file: File,
|
||||
onExit: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val density = LocalDensity.current
|
||||
|
||||
var text by remember { mutableStateOf("") }
|
||||
var selection by remember { mutableStateOf(TextRange.Zero) }
|
||||
var composing by remember { mutableStateOf<TextRange?>(null) }
|
||||
var loadState by remember { mutableStateOf(EditorLoadState.LOADING) }
|
||||
var lock by remember { mutableStateOf(EditorLock.NONE) }
|
||||
var charset by remember { mutableStateOf(EditorCharset.UTF8) }
|
||||
var dirty by remember { mutableStateOf(false) }
|
||||
var saving by remember { mutableStateOf(false) }
|
||||
var showDiscard by remember { mutableStateOf(false) }
|
||||
var showSearch by remember { mutableStateOf(false) }
|
||||
var query by remember { mutableStateOf("") }
|
||||
var replacement by remember { mutableStateOf("") }
|
||||
var matchCase by remember { mutableStateOf(false) }
|
||||
var matchIndex by remember { mutableIntStateOf(0) }
|
||||
|
||||
val scrollState = rememberScrollState()
|
||||
val textHorizontalState = rememberScrollState()
|
||||
var viewportHeight by remember { mutableIntStateOf(0) }
|
||||
var viewportWidth by remember { mutableIntStateOf(0) }
|
||||
|
||||
val lineHeightDp = with(density) { EDITOR_LINE_HEIGHT_SP.sp.toDp() }
|
||||
val lineHeightPx = with(density) { lineHeightDp.toPx() }
|
||||
val totalLines = remember(text) { lineCountOf(text) }
|
||||
val cursorLine = lineIndexOfOffset(text, selection.end)
|
||||
val cursorColumn = columnOfOffset(text, selection.end)
|
||||
val matches = remember(text, query, matchCase) { findEditorMatches(text, query, matchCase) }
|
||||
val readOnly = lock != EditorLock.NONE
|
||||
val bodyStyle = TextStyle(
|
||||
fontFamily = FontFamily.Monospace,
|
||||
fontSize = EDITOR_FONT_SIZE_SP.sp,
|
||||
lineHeight = EDITOR_LINE_HEIGHT_SP.sp,
|
||||
color = MaterialTheme.colorScheme.onBackground,
|
||||
)
|
||||
val textMeasurer = rememberTextMeasurer()
|
||||
val charWidthPx = remember(bodyStyle) { textMeasurer.measure(text = "0", style = bodyStyle).size.width.toFloat() }
|
||||
|
||||
LaunchedEffect(file) {
|
||||
loadState = EditorLoadState.LOADING
|
||||
val size = withContext(Dispatchers.IO) { file.length() }
|
||||
if (size > EDITOR_MAX_OPEN_BYTES) {
|
||||
loadState = EditorLoadState.TOO_LARGE
|
||||
return@LaunchedEffect
|
||||
}
|
||||
val read = withContext(Dispatchers.IO) {
|
||||
runCatching { file.inputStream().use { readCapped(it, EDITOR_MAX_OPEN_BYTES) } }
|
||||
}
|
||||
val bytes = read.getOrNull()
|
||||
if (bytes == null) {
|
||||
loadState = if (read.isFailure) EditorLoadState.UNREADABLE else EditorLoadState.TOO_LARGE
|
||||
return@LaunchedEffect
|
||||
}
|
||||
val decoded = decodeEditorText(bytes)
|
||||
text = expandEditorTabs(decoded.text)
|
||||
charset = decoded.charset
|
||||
lock = when {
|
||||
editorIsBinary(bytes) -> EditorLock.BINARY
|
||||
decoded.lossy -> EditorLock.LOSSY
|
||||
bytes.size > EDITOR_MAX_EDIT_BYTES -> EditorLock.TOO_LARGE
|
||||
!file.canWrite() -> EditorLock.PERMISSION
|
||||
else -> EditorLock.NONE
|
||||
}
|
||||
selection = TextRange.Zero
|
||||
loadState = EditorLoadState.READY
|
||||
}
|
||||
|
||||
suspend fun revealLine(line: Int) {
|
||||
val current = scrollState.value
|
||||
val top = line * lineHeightPx
|
||||
val target = when {
|
||||
top < current -> top
|
||||
top + lineHeightPx > current + viewportHeight -> top + lineHeightPx - viewportHeight
|
||||
else -> return
|
||||
}
|
||||
val clamped = target.roundToInt().coerceIn(0, scrollState.maxValue)
|
||||
if (clamped != current) scrollState.scrollTo(clamped)
|
||||
}
|
||||
|
||||
LaunchedEffect(text, selection.end, viewportHeight, viewportWidth) {
|
||||
if (loadState != EditorLoadState.READY) return@LaunchedEffect
|
||||
revealLine(lineIndexOfOffset(text, selection.end))
|
||||
if (viewportWidth > 0 && charWidthPx > 0) {
|
||||
val x = (columnOfOffset(text, selection.end) - 1) * charWidthPx
|
||||
val current = textHorizontalState.value
|
||||
val target = when {
|
||||
x < current -> x
|
||||
x + charWidthPx > current + viewportWidth -> x + charWidthPx - viewportWidth
|
||||
else -> null
|
||||
}
|
||||
if (target != null) {
|
||||
val clamped = target.roundToInt().coerceIn(0, textHorizontalState.maxValue)
|
||||
if (clamped != current) textHorizontalState.scrollTo(clamped)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(query, matchCase) {
|
||||
if (query.isEmpty()) return@LaunchedEffect
|
||||
matchIndex = 0
|
||||
val first = matches.firstOrNull() ?: return@LaunchedEffect
|
||||
selection = TextRange(first.first, first.last + 1)
|
||||
composing = TextRange.Zero
|
||||
}
|
||||
|
||||
LaunchedEffect(text) { matchIndex = 0 }
|
||||
|
||||
fun gotoMatch(delta: Int) {
|
||||
if (matches.isEmpty()) return
|
||||
matchIndex = Math.floorMod(matchIndex + delta, matches.size)
|
||||
val m = matches[matchIndex]
|
||||
selection = TextRange(m.first, m.last + 1)
|
||||
composing = TextRange.Zero
|
||||
}
|
||||
|
||||
fun replaceCurrent() {
|
||||
if (readOnly) return
|
||||
val m = matches.getOrNull(matchIndex) ?: return
|
||||
text = text.replaceRange(m.first, m.last + 1, replacement)
|
||||
dirty = true
|
||||
matchIndex = 0
|
||||
selection = TextRange(m.first + replacement.length)
|
||||
composing = TextRange.Zero
|
||||
}
|
||||
|
||||
fun replaceAll() {
|
||||
if (readOnly || matches.isEmpty()) return
|
||||
val all = findEditorMatches(text, query, matchCase, limit = Int.MAX_VALUE)
|
||||
text = replaceEditorMatches(text, all, replacement)
|
||||
dirty = true
|
||||
matchIndex = 0
|
||||
selection = TextRange.Zero
|
||||
composing = TextRange.Zero
|
||||
}
|
||||
|
||||
fun save() {
|
||||
if (readOnly || saving || loadState != EditorLoadState.READY) return
|
||||
val snapshot = text
|
||||
val bytes = snapshot.toByteArray(charset.charset)
|
||||
saving = true
|
||||
scope.launch {
|
||||
val ok = withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
val target = resolveEditorSaveTarget(file)
|
||||
val parent = target.parentFile
|
||||
if (parent == null) {
|
||||
target.writeBytes(bytes)
|
||||
} else {
|
||||
val tmp = File.createTempFile(".${target.name}.", ".droiddeck-tmp", parent)
|
||||
try {
|
||||
tmp.writeBytes(bytes)
|
||||
runCatching {
|
||||
Files.setPosixFilePermissions(tmp.toPath(), Files.getPosixFilePermissions(target.toPath()))
|
||||
}
|
||||
if (!tmp.renameTo(target)) error("rename to ${target.name} failed")
|
||||
} finally {
|
||||
tmp.delete()
|
||||
}
|
||||
}
|
||||
}.isSuccess
|
||||
}
|
||||
saving = false
|
||||
if (ok) {
|
||||
if (text == snapshot) dirty = false
|
||||
} else {
|
||||
Toast.makeText(context, context.getString(R.string.fm_edit_save_failed, file.name), Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun tryExit() {
|
||||
if (saving) return
|
||||
if (dirty && !readOnly) showDiscard = true else onExit()
|
||||
}
|
||||
|
||||
BackHandler { tryExit() }
|
||||
|
||||
if (showDiscard) {
|
||||
OutlinedAlertDialog(
|
||||
onDismissRequest = { showDiscard = false },
|
||||
title = { Text(stringResource(R.string.fm_edit_discard_title)) },
|
||||
text = { Text(stringResource(R.string.fm_edit_discard_text, file.name)) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = onExit, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.fm_edit_discard))
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { showDiscard = false }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.common_cancel))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
Column(
|
||||
modifier = modifier
|
||||
.fillMaxSize()
|
||||
.background(MaterialTheme.colorScheme.background),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.background(MaterialTheme.colorScheme.surfaceContainer)
|
||||
.padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
) {
|
||||
IconButton(onClick = { tryExit() }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(
|
||||
Icons.Filled.ArrowBack,
|
||||
stringResource(R.string.fm_back),
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
Column(modifier = Modifier.weight(1f).padding(horizontal = 4.dp)) {
|
||||
Text(
|
||||
text = file.name,
|
||||
color = MaterialTheme.colorScheme.onBackground,
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (dirty) {
|
||||
Text(
|
||||
text = "\u2022 " + stringResource(R.string.fm_edit_modified),
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
fontSize = 11.sp,
|
||||
maxLines = 1,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (loadState == EditorLoadState.READY && lock != EditorLock.NONE) {
|
||||
Text(
|
||||
text = stringResource(
|
||||
if (lock == EditorLock.BINARY) R.string.fm_edit_binary else R.string.fm_edit_read_only,
|
||||
),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
fontSize = 10.sp,
|
||||
maxLines = 1,
|
||||
modifier = Modifier
|
||||
.background(MaterialTheme.colorScheme.surfaceVariant, MaterialTheme.shapes.small)
|
||||
.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
}
|
||||
IconButton(
|
||||
onClick = { showSearch = !showSearch },
|
||||
enabled = loadState == EditorLoadState.READY,
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.Search,
|
||||
stringResource(R.string.fm_edit_find),
|
||||
tint = if (showSearch) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
IconButton(
|
||||
onClick = { save() },
|
||||
enabled = loadState == EditorLoadState.READY && !readOnly && dirty && !saving,
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.Save,
|
||||
stringResource(R.string.fm_edit_save),
|
||||
tint = if (dirty) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (showSearch && loadState == EditorLoadState.READY) {
|
||||
Column(Modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surfaceContainer)) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().padding(start = 8.dp, end = 4.dp, top = 4.dp),
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = query,
|
||||
onValueChange = { query = it; matchIndex = 0 },
|
||||
singleLine = true,
|
||||
placeholder = { Text(stringResource(R.string.fm_edit_find), fontSize = 13.sp) },
|
||||
textStyle = MaterialTheme.typography.bodySmall,
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
|
||||
keyboardActions = KeyboardActions(onSearch = { gotoMatch(1) }),
|
||||
modifier = Modifier.weight(1f).focusGlide(),
|
||||
)
|
||||
Text(
|
||||
text = if (matches.isEmpty()) "0/${matches.size}" else "${matchIndex.coerceAtMost(matches.size - 1) + 1}/${matches.size}",
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
fontSize = 12.sp,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.padding(horizontal = 6.dp).widthIn(min = 44.dp, max = 80.dp),
|
||||
)
|
||||
IconButton(
|
||||
onClick = { gotoMatch(-1) },
|
||||
enabled = matches.isNotEmpty(),
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.KeyboardArrowUp,
|
||||
stringResource(R.string.fm_edit_find_previous),
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
IconButton(
|
||||
onClick = { gotoMatch(1) },
|
||||
enabled = matches.isNotEmpty(),
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.KeyboardArrowDown,
|
||||
stringResource(R.string.fm_edit_find_next),
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
TextButton(onClick = { matchCase = !matchCase }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(
|
||||
text = "Aa",
|
||||
color = if (matchCase) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
fontSize = 13.sp,
|
||||
)
|
||||
}
|
||||
IconButton(onClick = { showSearch = false }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(
|
||||
Icons.Filled.Close,
|
||||
stringResource(R.string.common_cancel),
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().padding(start = 8.dp, top = 2.dp, end = 4.dp, bottom = 2.dp),
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = replacement,
|
||||
onValueChange = { replacement = it },
|
||||
singleLine = true,
|
||||
placeholder = { Text(stringResource(R.string.fm_edit_replace), fontSize = 13.sp) },
|
||||
textStyle = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.weight(1f).focusGlide(),
|
||||
)
|
||||
TextButton(
|
||||
onClick = { replaceCurrent() },
|
||||
enabled = !readOnly && matches.isNotEmpty(),
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) {
|
||||
Text(stringResource(R.string.fm_edit_replace), fontSize = 13.sp)
|
||||
}
|
||||
TextButton(
|
||||
onClick = { replaceAll() },
|
||||
enabled = !readOnly && matches.isNotEmpty(),
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) {
|
||||
Text(stringResource(R.string.fm_edit_replace_all), fontSize = 13.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.fillMaxWidth()
|
||||
.onSizeChanged { viewportHeight = it.height },
|
||||
) {
|
||||
when (loadState) {
|
||||
EditorLoadState.LOADING -> CircularProgressIndicator(
|
||||
modifier = Modifier.align(Alignment.Center),
|
||||
)
|
||||
|
||||
EditorLoadState.TOO_LARGE, EditorLoadState.UNREADABLE -> Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = Modifier.align(Alignment.Center).padding(24.dp),
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(
|
||||
if (loadState == EditorLoadState.TOO_LARGE) R.string.fm_edit_too_large
|
||||
else R.string.fm_edit_open_failed,
|
||||
if (loadState == EditorLoadState.TOO_LARGE) FileOps.formatBytes(context, file.length())
|
||||
else file.name,
|
||||
),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
fontSize = 14.sp,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
|
||||
EditorLoadState.READY -> Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(scrollState),
|
||||
) {
|
||||
Row(modifier = Modifier.fillMaxWidth().height(lineHeightDp * totalLines.toFloat())) {
|
||||
LineNumbers(
|
||||
scrollState = scrollState,
|
||||
viewportHeight = viewportHeight,
|
||||
lineHeightDp = lineHeightDp,
|
||||
lineHeightPx = lineHeightPx,
|
||||
totalLines = totalLines,
|
||||
cursorLine = cursorLine,
|
||||
style = bodyStyle,
|
||||
mutedColor = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
cursorColor = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
Box(modifier = Modifier.weight(1f).onSizeChanged { viewportWidth = it.width }.horizontalScroll(textHorizontalState)) {
|
||||
BasicTextField(
|
||||
value = TextFieldValue(text = text, selection = selection, composition = composing),
|
||||
onValueChange = { next ->
|
||||
val changed = next.text != text
|
||||
text = next.text
|
||||
selection = next.selection
|
||||
composing = next.composition
|
||||
if (changed) dirty = true
|
||||
},
|
||||
readOnly = readOnly,
|
||||
textStyle = bodyStyle,
|
||||
cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Text,
|
||||
capitalization = KeyboardCapitalization.None,
|
||||
),
|
||||
modifier = Modifier.fillMaxHeight().focusGlide(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (loadState == EditorLoadState.READY) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.fm_edit_position, cursorLine + 1, cursorColumn),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
fontSize = 12.sp,
|
||||
maxLines = 1,
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(
|
||||
text = charset.label + " \u2022 " + FileOps.formatBytes(context, file.length()),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
fontSize = 12.sp,
|
||||
maxLines = 1,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LineNumbers(
|
||||
scrollState: ScrollState,
|
||||
viewportHeight: Int,
|
||||
lineHeightDp: Dp,
|
||||
lineHeightPx: Float,
|
||||
totalLines: Int,
|
||||
cursorLine: Int,
|
||||
style: TextStyle,
|
||||
mutedColor: Color,
|
||||
cursorColor: Color,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val firstLine = (scrollState.value / lineHeightPx).toInt().coerceIn(0, totalLines - 1)
|
||||
val lastLine = ((scrollState.value + viewportHeight) / lineHeightPx)
|
||||
.toInt()
|
||||
.coerceIn(firstLine, totalLines - 1)
|
||||
Column(
|
||||
horizontalAlignment = Alignment.End,
|
||||
modifier = modifier
|
||||
.width(IntrinsicSize.Min)
|
||||
.padding(top = lineHeightDp * firstLine.toFloat()),
|
||||
) {
|
||||
for (line in firstLine..lastLine) {
|
||||
Text(
|
||||
text = (line + 1).toString(),
|
||||
color = if (line == cursorLine) cursorColor else mutedColor,
|
||||
textAlign = TextAlign.End,
|
||||
maxLines = 1,
|
||||
style = style,
|
||||
modifier = Modifier.fillMaxWidth().height(lineHeightDp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,6 @@ object AutoComponents {
|
||||
{ c, comp, all, progress -> WinComponents.install(c, comp, all, progress) }
|
||||
@VisibleForTesting internal var sessionRunning: () -> Boolean = { SessionState.running }
|
||||
@VisibleForTesting internal var unfavourable: (Context) -> Boolean = { c -> constrained(c) }
|
||||
@VisibleForTesting internal var firstRunHeldBack: (Context) -> Boolean = { c -> powerSaveOrMetered(c) }
|
||||
@VisibleForTesting internal var online: (Context) -> Boolean = { c -> isOnline(c) }
|
||||
@VisibleForTesting @Volatile internal var runNow = false
|
||||
|
||||
@@ -534,10 +533,6 @@ object AutoComponents {
|
||||
caps.hasCapability(android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED)
|
||||
}
|
||||
|
||||
fun powerSaveOrMetered(context: Context): Boolean =
|
||||
context.getSystemService(PowerManager::class.java)?.isPowerSaveMode == true ||
|
||||
context.getSystemService(ConnectivityManager::class.java)?.isActiveNetworkMetered == true
|
||||
|
||||
fun constrained(context: Context): Boolean {
|
||||
val power = context.getSystemService(PowerManager::class.java)
|
||||
if (power?.isPowerSaveMode == true) return true
|
||||
|
||||
@@ -14,8 +14,7 @@ object DualScreen {
|
||||
const val MODE_AUTO = "auto"
|
||||
const val MODE_ON = "on"
|
||||
const val MODE_OFF = "off"
|
||||
const val MODE_SWAPPED = "swapped"
|
||||
val modes = listOf(MODE_AUTO, MODE_ON, MODE_SWAPPED, MODE_OFF)
|
||||
val modes = listOf(MODE_AUTO, MODE_ON, MODE_OFF)
|
||||
private const val TYPE_INTERNAL = 1
|
||||
private const val TYPE_EXTERNAL = 2
|
||||
private val knownModels = setOf("retroid pocket duo", "ayn thor")
|
||||
@@ -100,7 +99,7 @@ object DualScreen {
|
||||
fun display(context: Context, displayManager: DisplayManager, primaryDisplayId: Int, mode: String = SessionPrefs.dualScreenMode(context)): Display? =
|
||||
when (mode) {
|
||||
MODE_OFF -> null
|
||||
MODE_ON, MODE_SWAPPED -> internalDisplay(displayManager, primaryDisplayId) ?: anyDisplay(displayManager, primaryDisplayId)
|
||||
MODE_ON -> internalDisplay(displayManager, primaryDisplayId) ?: anyDisplay(displayManager, primaryDisplayId)
|
||||
else -> if (dockedToDisplay(displayManager, primaryDisplayId)) null else builtInDisplay(displayManager, primaryDisplayId)
|
||||
}?.takeUnless { taken(it.displayId) }
|
||||
|
||||
|
||||
@@ -31,20 +31,17 @@ object OnScreenLayout {
|
||||
private const val TOLERANCE = .01f
|
||||
private const val KEYBOARD_ID = "builtin:keyboard"
|
||||
private val REAR = setOf(InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5)
|
||||
private val BAR = setOf(InputControl.GUIDE, InputControl.QAM)
|
||||
|
||||
fun elements(context: Context, saved: SavedInputLayout?, width: Int, height: Int, safe: Rect,
|
||||
buttonsOnly: Boolean = false, dock: Dock? = null, rearButtons: Boolean? = null,
|
||||
trackpads: Boolean? = null): List<InputSurfaceElement> {
|
||||
if (saved == null) return emptyList()
|
||||
if (width <= 0 || height <= 0) return saved.elements
|
||||
val layout = oriented(saved, dock?.portrait ?: (height > width))
|
||||
val layout = oriented(saved, width, height)
|
||||
val stored = layout.elements
|
||||
val generator = LegacyGamepadLayout(context, width, height, safe, layout.scale)
|
||||
val (reference, matched) = reference(context, layout, width, height)
|
||||
if (buttonsOnly && dock == null) return generator.buttonsOnly(stored) + fit(stored.filter { it.alwaysShown }, reference.first, reference.second, width, height, safe)
|
||||
if (dock?.portrait == true && !dock.grips && !matched && layout.aspect > 0f && layout.aspect < 1f && stored.any(::isGamepad))
|
||||
return cluster(stored.filterNot { it.alwaysShown || isGamepad(it) && (it.id == KEYBOARD_ID || it.control in BAR) }, layout.aspect, width, height, safe)
|
||||
val generated = matched || PadKit.forOverlay(context, layout) != null && stored.any(::isGamepad) &&
|
||||
(dock != null || height > width && layout.aspect >= 1f || height <= width && layout.aspect > 0f && layout.aspect < 1f)
|
||||
val gamepad = if (generated) stored.filter(::isGamepad) else emptyList()
|
||||
@@ -73,9 +70,8 @@ object OnScreenLayout {
|
||||
.place(ordered, lowerShortcuts = generated, rearButtons = rearButtons, trackpads = trackpads)
|
||||
}
|
||||
|
||||
fun oriented(layout: SavedInputLayout, width: Int, height: Int): SavedInputLayout = oriented(layout, height > width)
|
||||
|
||||
private fun oriented(layout: SavedInputLayout, portrait: Boolean): SavedInputLayout {
|
||||
fun oriented(layout: SavedInputLayout, width: Int, height: Int): SavedInputLayout {
|
||||
val portrait = height > width
|
||||
if (layout.rotated.isEmpty() || layout.aspect <= 0f || (layout.aspect < 1f) == portrait || (layout.rotatedAspect < 1f) != portrait) return layout
|
||||
val rotated = layout.rotated.associateBy { it.id }
|
||||
return layout.copy(elements = layout.elements.map { e -> rotated[e.id]?.let { e.copy(x = it.x, y = it.y, width = it.width, height = it.height) } ?: e } +
|
||||
@@ -135,23 +131,6 @@ object OnScreenLayout {
|
||||
}
|
||||
}
|
||||
|
||||
private fun cluster(elements: List<InputSurfaceElement>, aspect: Float, width: Int, height: Int, safe: Rect): List<InputSurfaceElement> {
|
||||
if (elements.isEmpty()) return elements
|
||||
val left = elements.minOf { it.x } * aspect
|
||||
val top = elements.minOf { it.y }
|
||||
val spanX = (elements.maxOf { it.x + it.width } * aspect - left).coerceAtLeast(.0001f)
|
||||
val spanY = (elements.maxOf { it.y + it.height } - top).coerceAtLeast(.0001f)
|
||||
val w = (width - safe.left - safe.right).toFloat().coerceAtLeast(1f)
|
||||
val h = (height - safe.top - safe.bottom).toFloat().coerceAtLeast(1f)
|
||||
val scale = minOf(w / aspect, w / spanX, h / spanY)
|
||||
val originX = safe.left + (w - spanX * scale) / 2f - left * scale
|
||||
val originY = safe.top + (h - spanY * scale) / 2f - top * scale
|
||||
return elements.map { e ->
|
||||
e.copy(x = (originX + e.x * aspect * scale) / width, y = (originY + e.y * scale) / height,
|
||||
width = e.width * aspect * scale / width, height = e.height * scale / height)
|
||||
}
|
||||
}
|
||||
|
||||
private fun anchor(start: Float, size: Float, reference: Float, actual: Float, scale: Float): Float {
|
||||
val centre = start + size / 2f
|
||||
val scaled = size * reference * scale
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.view.InputDevice
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
|
||||
internal class TriggerKeys(private val dispatch: (KeyEvent) -> Unit) {
|
||||
private class Pull {
|
||||
val held = BooleanArray(2)
|
||||
val sent = BooleanArray(2)
|
||||
}
|
||||
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val keyed = HashSet<Int>()
|
||||
private val pulls = HashMap<Int, Pull>()
|
||||
var synthesizing = false
|
||||
private set
|
||||
|
||||
/** True when this real trigger key belongs to a pull that already went out as a synthetic press. */
|
||||
fun nativeKey(event: KeyEvent): Boolean {
|
||||
val i = index(event.keyCode) ?: return false
|
||||
keyed += event.deviceId
|
||||
val pull = pulls[event.deviceId] ?: return false
|
||||
if (!pull.sent[i]) return false
|
||||
if (event.action == KeyEvent.ACTION_UP) pull.sent[i] = false
|
||||
return true
|
||||
}
|
||||
|
||||
fun onMotion(event: MotionEvent) {
|
||||
if (event.source and InputDevice.SOURCE_JOYSTICK != InputDevice.SOURCE_JOYSTICK || event.action != MotionEvent.ACTION_MOVE) return
|
||||
val device = event.deviceId
|
||||
if (device in keyed) return
|
||||
val pull = pulls.getOrPut(device) { Pull() }
|
||||
update(pull, 0, maxOf(event.getAxisValue(MotionEvent.AXIS_LTRIGGER), event.getAxisValue(MotionEvent.AXIS_BRAKE)), event)
|
||||
update(pull, 1, maxOf(event.getAxisValue(MotionEvent.AXIS_RTRIGGER), event.getAxisValue(MotionEvent.AXIS_GAS)), event)
|
||||
}
|
||||
|
||||
fun cancel() {
|
||||
handler.removeCallbacksAndMessages(null)
|
||||
pulls.clear()
|
||||
}
|
||||
|
||||
private fun update(pull: Pull, i: Int, value: Float, event: MotionEvent) {
|
||||
if (!pull.held[i] && value >= PRESS) {
|
||||
pull.held[i] = true
|
||||
pull.sent[i] = false
|
||||
val device = event.deviceId
|
||||
val source = event.source
|
||||
// A pad that also sends trigger keys delivers them close to the axis; waiting lets that key win.
|
||||
handler.postDelayed({
|
||||
if (device !in keyed && pulls[device] === pull) {
|
||||
pull.sent[i] = true
|
||||
press(CODES[i], device, source)
|
||||
}
|
||||
}, KEY_WAIT_MS)
|
||||
} else if (pull.held[i] && value <= RELEASE) pull.held[i] = false
|
||||
}
|
||||
|
||||
private fun press(code: Int, device: Int, source: Int) {
|
||||
val now = SystemClock.uptimeMillis()
|
||||
synthesizing = true
|
||||
try {
|
||||
dispatch(KeyEvent(now, now, KeyEvent.ACTION_DOWN, code, 0, 0, device, 0, 0, source))
|
||||
dispatch(KeyEvent(now, now, KeyEvent.ACTION_UP, code, 0, 0, device, 0, 0, source))
|
||||
} finally {
|
||||
synthesizing = false
|
||||
}
|
||||
}
|
||||
|
||||
private fun index(code: Int): Int? = CODES.indexOf(code).takeIf { it >= 0 }
|
||||
|
||||
private companion object {
|
||||
val CODES = intArrayOf(KeyEvent.KEYCODE_BUTTON_L2, KeyEvent.KEYCODE_BUTTON_R2)
|
||||
const val PRESS = 0.6f
|
||||
const val RELEASE = 0.3f
|
||||
const val KEY_WAIT_MS = 40L
|
||||
}
|
||||
}
|
||||
@@ -56,7 +56,7 @@ object BattleNet {
|
||||
Title("aqua", "Avowed", "AQUA", 2457220, shop = "avowed", product = "aqua"),
|
||||
)
|
||||
|
||||
val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" }
|
||||
val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" && it.code != "WoWF" }
|
||||
|
||||
// Blizzard's China client installs some products under a CN uid; they are the same games and keep their store identity.
|
||||
private val CN_UIDS = mapOf("s2_cn" to "s2", "osic" to "osi", "anbs_cn" to "anbs")
|
||||
|
||||
@@ -1,303 +1,10 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.stores.battlenet.BattleNetInstall
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.time.Instant
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.LinkedBlockingQueue
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
object CurseForgeApp {
|
||||
const val NAME = "CurseForge"
|
||||
const val FEED = "https://curseforge.overwolf.com/electron/linux/latest-linux.yml"
|
||||
internal const val WOW = 1
|
||||
const val HELPER = "/usr/local/bin/droiddeck-curseforge"
|
||||
internal const val AGENT = "/usr/local/bin/droiddeck-agent"
|
||||
private const val READY_MS = 120_000L
|
||||
private const val INSTALL_MS = 300_000L
|
||||
private const val OUT_OF_DATE = 2
|
||||
|
||||
enum class Start { READY, BUSY, FAILED }
|
||||
|
||||
class Started(val state: Start, val inspector: String? = null)
|
||||
|
||||
class Project(val id: String, val installedModId: String, val folders: List<String>, val update: Boolean)
|
||||
|
||||
internal val INSPECTOR = Regex("ws://127\\.0\\.0\\.1:[0-9]{4,5}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
|
||||
|
||||
class Failure(message: String, val code: String? = null) : Exception(message) {
|
||||
val gone get() = code == "DEVTOOLS_UNREACHABLE"
|
||||
}
|
||||
|
||||
fun find(apps: List<UserApps.App>): UserApps.App? = apps.firstOrNull { it.feed == FEED }
|
||||
|
||||
fun request(): UserApps.Request = UserApps.Request(UserApps.Source.Feed(FEED), NAME, null)
|
||||
|
||||
internal fun dir(app: UserApps.App): String? = app.args.firstOrNull()?.takeIf { it.startsWith("/") }
|
||||
|
||||
internal fun helperArgv(command: String, dir: String): List<String> = listOf(HELPER, command, dir)
|
||||
|
||||
internal fun evalArgv(inspector: String, expression: String, timeoutMs: Long): List<String> =
|
||||
listOf(AGENT, "--cdp-inspector", inspector, (timeoutMs / 1000.0).toString(), expression)
|
||||
|
||||
internal fun lastJson(lines: List<String>): JSONObject? =
|
||||
lines.asReversed().firstNotNullOfOrNull { line -> runCatching { JSONObject(line.trim()) }.getOrNull() }
|
||||
|
||||
internal fun inspectorUrl(stdout: String): String? = stdout.lineSequence().map { it.trim() }.lastOrNull { INSPECTOR.matches(it) }
|
||||
|
||||
internal fun startState(exitCode: Int): Start = when (exitCode) {
|
||||
0 -> Start.READY
|
||||
3 -> Start.BUSY
|
||||
else -> Start.FAILED
|
||||
}
|
||||
|
||||
internal fun sortOf(sort: WowAddonCatalog.Sort): Pair<Int, Int> = when (sort) {
|
||||
WowAddonCatalog.Sort.POPULAR -> 8 to 2
|
||||
WowAddonCatalog.Sort.UPDATED -> 16 to 2
|
||||
WowAddonCatalog.Sort.NAME -> 1 to 1
|
||||
WowAddonCatalog.Sort.DOWNLOADS -> 7 to 2
|
||||
}
|
||||
|
||||
internal fun searchRequest(guid: String, text: String, sort: WowAddonCatalog.Sort, page: Int): JSONObject {
|
||||
val (column, order) = sortOf(sort)
|
||||
return JSONObject().put("gameId", WOW).put("searchText", text.trim()).put("page", page + 1)
|
||||
.put("sortColumn", column).put("sortOrder", order).put("gameInstanceGuid", guid)
|
||||
}
|
||||
|
||||
internal fun installRequest(guid: String, projectId: String): JSONObject =
|
||||
JSONObject().put("instanceId", guid).put("projectId", projectId.toLong()).put("categoryClassId", 1)
|
||||
.put("installLatestFile", true).put("installSource", 4)
|
||||
|
||||
private const val CACHE = "__droiddeckServices"
|
||||
|
||||
private const val SERVICES = """(() => {
|
||||
const seen = new Set(), out = {};
|
||||
const walk = (o, d) => {
|
||||
if (!o || typeof o !== 'object' || seen.has(o) || d > 4) return;
|
||||
seen.add(o);
|
||||
if (typeof o._nameOfService === 'string') { out[o._nameOfService] = o; return; }
|
||||
let keys; try { keys = Object.keys(o); } catch (e) { return; }
|
||||
for (const k of keys.slice(0, 4000)) {
|
||||
let v; try { v = o[k]; } catch (e) { continue; }
|
||||
if (v instanceof Map) { for (const x of v.values()) walk(x, d + 1); } else walk(v, d + 1);
|
||||
}
|
||||
};
|
||||
walk(window, 0);
|
||||
return out;
|
||||
})()"""
|
||||
|
||||
internal fun expression(service: String, method: String, args: JSONArray?, pick: String = "r => r"): String {
|
||||
val name = JSONObject.quote(method)
|
||||
val run = if (args == null) "true" else "($pick)(await s[$name](...$args))"
|
||||
val key = JSONObject.quote(service)
|
||||
val inner = "(async () => { let m = globalThis.$CACHE; if (!m || !m[$key]) m = globalThis.$CACHE = $SERVICES; const s = m[$key]; " +
|
||||
"if (!s || typeof s[$name] !== 'function') return { missing: true }; " +
|
||||
"return { value: $run }; })()"
|
||||
return "(() => { const w = require('electron').BrowserWindow.getAllWindows()" +
|
||||
".find(w => !w.isDestroyed() && w.webContents.getURL().includes('desktop.html')); " +
|
||||
"if (!w) return JSON.stringify({ missing: true }); " +
|
||||
"return w.webContents.executeJavaScript(${JSONObject.quote(inner)}).then(v => JSON.stringify(v)); })()"
|
||||
}
|
||||
|
||||
internal fun unwrap(answer: JSONObject): Any? {
|
||||
if (!answer.optBoolean("ok")) {
|
||||
val error = answer.optJSONObject("error")
|
||||
throw Failure(error?.optString("message")?.takeIf { it.isNotBlank() } ?: answer.toString(), error?.optString("code")?.takeIf { it.isNotBlank() })
|
||||
}
|
||||
val text = answer.opt("value") as? String ?: throw Failure("CurseForge gave no answer")
|
||||
val reply = JSONObject(text)
|
||||
if (reply.optBoolean("missing")) throw Failure("CurseForge is not ready")
|
||||
return reply.opt("value")
|
||||
}
|
||||
|
||||
internal fun parseSearch(value: Any?): WowAddonCatalog.Page {
|
||||
val reply = value as? JSONObject ?: throw Failure("CurseForge search failed")
|
||||
if (reply.has("success") && !reply.optBoolean("success")) throw Failure("CurseForge search failed")
|
||||
val mods = reply.optJSONArray("mods") ?: JSONArray()
|
||||
val items = (0 until mods.length()).mapNotNull { mods.optJSONObject(it) }.mapNotNull { mod ->
|
||||
val id = mod.optLong("id", 0L).takeIf { it > 0 } ?: return@mapNotNull null
|
||||
val name = mod.optString("name").takeIf { it.isNotBlank() } ?: return@mapNotNull null
|
||||
val author = mod.optJSONObject("primaryAuthor")?.optString("name")?.takeIf { it.isNotBlank() }
|
||||
?: mod.optJSONArray("authors")?.optJSONObject(0)?.optString("name").orEmpty()
|
||||
val date = mod.optJSONObject("updateVersion")?.optString("fileDate")?.takeIf { it.isNotBlank() }
|
||||
?: mod.optString("projectLatestReleaseDate")
|
||||
WowAddonCatalog.Addon(
|
||||
id.toString(), name, author, "", mod.optLong("downloads", 0L).coerceAtLeast(0L),
|
||||
runCatching { Instant.parse(date).toEpochMilli() }.getOrDefault(0L),
|
||||
mod.optString("thumbnailUrl").takeIf { WowAddonCatalog.isHttps(it) },
|
||||
)
|
||||
}
|
||||
val page = reply.optJSONObject("pagination")
|
||||
val more = page != null && page.optInt("index") + page.optInt("resultCount") < page.optInt("totalCount")
|
||||
return WowAddonCatalog.Page(items, more)
|
||||
}
|
||||
|
||||
internal fun samePath(a: String, b: String) = a.trimEnd('/') == b.trimEnd('/')
|
||||
|
||||
internal fun instanceFor(instances: Any?, flavorDir: String, detected: String?): String? {
|
||||
val list = instances as? JSONArray
|
||||
val match = list?.let { all ->
|
||||
(0 until all.length()).mapNotNull { all.optJSONObject(it) }
|
||||
.firstOrNull { samePath(it.optString("installPath"), flavorDir) }?.optString("guid")
|
||||
}
|
||||
if (list != null && list.length() > 0) return match?.takeIf { it.isNotBlank() }
|
||||
return detected?.takeIf { it.isNotBlank() }
|
||||
}
|
||||
|
||||
internal fun parseProjects(value: Any?): List<Project> {
|
||||
val list = value as? JSONArray ?: return emptyList()
|
||||
return (0 until list.length()).mapNotNull { list.optJSONObject(it) }.mapNotNull { p ->
|
||||
val id = p.optString("id").takeIf { it.isNotBlank() && it != "null" } ?: return@mapNotNull null
|
||||
val folders = p.optJSONArray("folders")?.let { f -> (0 until f.length()).mapNotNull { f.optString(it).takeIf(String::isNotBlank) } }.orEmpty()
|
||||
Project(id, p.optString("installedModId"), folders, p.optInt("status") == OUT_OF_DATE && !p.optBoolean("locked"))
|
||||
}
|
||||
}
|
||||
|
||||
internal fun owner(projects: List<Project>, folder: String): Project? =
|
||||
projects.firstOrNull { project -> project.folders.any { it.equals(folder, ignoreCase = true) } }
|
||||
|
||||
internal fun byFolder(projects: List<Project>): Map<String, Project> = projects.flatMap { project -> project.folders.map { it.lowercase() to project } }.toMap()
|
||||
|
||||
internal fun onDisk(projects: List<Project>, addOns: File): List<Project> {
|
||||
val names = addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }.map { it.name.lowercase() }.toSet()
|
||||
return projects.filter { project -> WowAddons.present(project.folders) { it.lowercase() in names } }
|
||||
}
|
||||
|
||||
internal var guest: (Context, List<String>, AtomicBoolean?, (String) -> Unit) -> Int = { context, argv, cancelled, onLine ->
|
||||
GuestCommand.run(context, argv, logName = "curseforge", extraBinds = BattleNetInstall.binds(context), fastPath = true,
|
||||
cancelled = cancelled, redact = INSPECTOR, onLine = onLine)
|
||||
}
|
||||
|
||||
private val holds = ConcurrentHashMap<String, AtomicBoolean>()
|
||||
private val connected = ConcurrentHashMap.newKeySet<String>()
|
||||
|
||||
private fun lines(context: Context, argv: List<String>): List<String> {
|
||||
val out = ArrayList<String>()
|
||||
guest(context, argv, null) { out += it }
|
||||
return out
|
||||
}
|
||||
|
||||
private fun call(context: Context, inspector: String, service: String, method: String, args: JSONArray?, timeoutMs: Long, pick: String = "r => r"): Any? =
|
||||
unwrap(lastJson(lines(context, evalArgv(inspector, expression(service, method, args, pick), timeoutMs))) ?: throw Failure("CurseForge gave no answer"))
|
||||
|
||||
private sealed class Launch {
|
||||
class Url(val inspector: String) : Launch()
|
||||
class Exit(val code: Int) : Launch()
|
||||
}
|
||||
|
||||
private fun launch(context: Context, dir: String, hold: AtomicBoolean): Launch? {
|
||||
val first = LinkedBlockingQueue<Launch>()
|
||||
Thread({
|
||||
val code = runCatching {
|
||||
guest(context, helperArgv("start", dir), hold) { line -> inspectorUrl(line)?.let { first.offer(Launch.Url(it)) } }
|
||||
}.getOrDefault(-1)
|
||||
first.offer(Launch.Exit(code))
|
||||
}, "curseforge-headless").apply { isDaemon = true; start() }
|
||||
return first.poll(READY_MS, TimeUnit.MILLISECONDS)
|
||||
}
|
||||
|
||||
fun start(context: Context, app: UserApps.App, hold: AtomicBoolean): Started {
|
||||
val dir = dir(app) ?: return Started(Start.FAILED)
|
||||
if (hold.get()) return Started(Start.FAILED)
|
||||
holds.put(dir, hold)?.takeIf { it !== hold }?.let {
|
||||
it.set(true)
|
||||
runCatching { lines(context, helperArgv("stop", dir)) }
|
||||
}
|
||||
val inspector = when (val first = launch(context, dir, hold)) {
|
||||
is Launch.Url -> first.inspector
|
||||
is Launch.Exit -> if (startState(first.code) == Start.BUSY) {
|
||||
holds.remove(dir, hold)
|
||||
return Started(Start.BUSY)
|
||||
} else null
|
||||
null -> null
|
||||
}
|
||||
if (inspector == null) {
|
||||
stop(context, app, null, hold)
|
||||
return Started(Start.FAILED)
|
||||
}
|
||||
val deadline = System.currentTimeMillis() + READY_MS
|
||||
while (System.currentTimeMillis() < deadline && !hold.get()) {
|
||||
if (runCatching { call(context, inspector, "InstalledProjectsAppService", "installAddon", null, 10_000) }.isSuccess) return Started(Start.READY, inspector)
|
||||
Thread.sleep(1_000)
|
||||
}
|
||||
stop(context, app, inspector, hold)
|
||||
return Started(Start.FAILED)
|
||||
}
|
||||
|
||||
fun stop(context: Context, app: UserApps.App, inspector: String?, hold: AtomicBoolean) {
|
||||
val dir = dir(app) ?: return
|
||||
if (holds[dir] !== hold) {
|
||||
hold.set(true)
|
||||
return
|
||||
}
|
||||
if (inspector != null) runCatching { call(context, inspector, "CoreService", "shutdown", JSONArray(), 30_000, "r => true") }
|
||||
hold.set(true)
|
||||
inspector?.let(connected::remove)
|
||||
if (holds.remove(dir, hold)) runCatching { lines(context, helperArgv("stop", dir)) }
|
||||
}
|
||||
|
||||
private fun connect(context: Context, inspector: String) {
|
||||
if (inspector in connected) return
|
||||
call(context, inspector, "CoreService", "connect", JSONArray(), 120_000, "r => true")
|
||||
connected += inspector
|
||||
}
|
||||
|
||||
private fun instances(context: Context, inspector: String): Any? =
|
||||
call(context, inspector, "GameAppService", "getGameInstances", JSONArray().put(WOW), 30_000,
|
||||
"r => (r || []).map(i => ({ guid: i.guid, installPath: i.installPath }))")
|
||||
|
||||
fun instance(context: Context, inspector: String, root: String, flavorDir: String): String {
|
||||
connect(context, inspector)
|
||||
instanceFor(instances(context, inspector), flavorDir, null)?.let { return it }
|
||||
val detected = call(context, inspector, "GameDetectionAppService", "detectGameFromPath", JSONArray().put(root).put(WOW), 60_000) as? JSONObject
|
||||
return instanceFor(instances(context, inspector), flavorDir, detected?.optString("gameInstanceGuid")) ?: throw Failure("CurseForge did not find $flavorDir")
|
||||
}
|
||||
|
||||
fun search(context: Context, inspector: String, guid: String, text: String, sort: WowAddonCatalog.Sort, page: Int): WowAddonCatalog.Page =
|
||||
parseSearch(call(context, inspector, "ProjectAppService", "search", JSONArray().put(searchRequest(guid, text, sort, page)), 60_000))
|
||||
|
||||
fun projects(context: Context, inspector: String, guid: String, rescan: Boolean = false): List<Project> {
|
||||
connect(context, inspector)
|
||||
if (rescan) call(context, inspector, "GameDetectionAppService", "scanGameInstance", JSONArray().put(guid), 120_000)
|
||||
return parseProjects(call(context, inspector, "InstalledProjectsAppService", "getProjects", JSONArray().put(guid), 30_000, PROJECTS))
|
||||
}
|
||||
|
||||
private const val PROJECTS = "r => (r || []).map(p => ({ id: String(p.id), installedModId: p.installedModId, status: p.status, " +
|
||||
"locked: !!(p.installedVersion && p.installedVersion.isLocked), " +
|
||||
"folders: ((p.installedVersion && p.installedVersion.addonFolders) || []).map(f => f.name) }))"
|
||||
|
||||
private fun settle(context: Context, inspector: String, guid: String, done: (List<Project>) -> Boolean): List<Project>? {
|
||||
val deadline = System.currentTimeMillis() + INSTALL_MS
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
val listed = runCatching { projects(context, inspector, guid) }
|
||||
val error = listed.exceptionOrNull()
|
||||
if (error is Failure && error.gone) throw error
|
||||
listed.getOrNull()?.let { if (done(it)) return it }
|
||||
Thread.sleep(1_000)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
fun install(context: Context, inspector: String, guid: String, projectId: String): List<Project>? {
|
||||
connect(context, inspector)
|
||||
if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return null
|
||||
return settle(context, inspector, guid) { list -> list.any { it.id == projectId } }
|
||||
}
|
||||
|
||||
fun update(context: Context, inspector: String, guid: String, projectId: String): List<Project>? {
|
||||
connect(context, inspector)
|
||||
if (call(context, inspector, "InstalledProjectsAppService", "updateMod", JSONArray().put(guid).put(projectId.toLong()), 300_000) != true) return null
|
||||
return settle(context, inspector, guid) { list -> list.any { it.id == projectId && !it.update } }
|
||||
}
|
||||
|
||||
fun uninstall(context: Context, inspector: String, guid: String, project: Project): List<Project>? {
|
||||
connect(context, inspector)
|
||||
val failed = call(context, inspector, "InstalledProjectsAppService", "deleteMods", JSONArray().put(guid).put(JSONArray().put(project.installedModId)), 120_000) as? JSONArray
|
||||
if (failed == null || failed.length() > 0) return null
|
||||
return settle(context, inspector, guid) { list -> list.none { it.id == project.id } }
|
||||
}
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.core.Downloader
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import java.io.File
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
object DeckyStore {
|
||||
private const val TAG = "DeckyStore"
|
||||
private const val LISTING = "https://plugins.deckbrew.xyz/plugins"
|
||||
private const val ARTIFACTS = "https://cdn.tzatzikiweeb.moe/file/steam-deck-homebrew/versions/"
|
||||
|
||||
data class Version(val name: String, val hash: String)
|
||||
data class Plugin(val name: String, val author: String, val description: String, val tags: List<String>, val downloads: Long, val imageUrl: String, val versions: List<Version>) {
|
||||
val latest: Version? get() = versions.firstOrNull()
|
||||
}
|
||||
data class Installed(val name: String, val folder: String, val author: String, val version: String)
|
||||
|
||||
fun parseListing(body: String): List<Plugin> {
|
||||
val array = JSONArray(body)
|
||||
return (0 until array.length()).mapNotNull { i ->
|
||||
val row = array.optJSONObject(i) ?: return@mapNotNull null
|
||||
val name = row.optString("name").takeIf { it.isNotBlank() } ?: return@mapNotNull null
|
||||
val versions = row.optJSONArray("versions")?.let { list ->
|
||||
(0 until list.length()).mapNotNull { v ->
|
||||
val version = list.optJSONObject(v) ?: return@mapNotNull null
|
||||
val hash = version.optString("hash")
|
||||
if (!hash.matches(Regex("(?i)[0-9a-f]{64}"))) null else Version(version.optString("name"), hash.lowercase())
|
||||
}
|
||||
}.orEmpty()
|
||||
if (versions.isEmpty()) return@mapNotNull null
|
||||
val tags = row.optJSONArray("tags")?.let { list -> (0 until list.length()).map { list.optString(it) } }.orEmpty()
|
||||
val downloads = row.optJSONArray("versions")?.let { list -> (0 until list.length()).sumOf { list.optJSONObject(it)?.optLong("downloads") ?: 0L } } ?: 0L
|
||||
val image = row.optString("image_url").takeIf { it.startsWith("https://") }.orEmpty()
|
||||
Plugin(name, row.optString("author"), row.optString("description"), tags, downloads, image, versions)
|
||||
}
|
||||
}
|
||||
|
||||
fun fetch(): List<Plugin>? {
|
||||
val body = Downloader.downloadString(LISTING) ?: return null
|
||||
return runCatching { parseListing(body) }.onFailure { Log.w(TAG, "store listing", it) }.getOrNull()
|
||||
}
|
||||
|
||||
fun pluginsDir(context: Context) = File(LinuxRuntime.rootDir(context), "root/homebrew/plugins")
|
||||
|
||||
fun installed(context: Context): List<Installed> =
|
||||
pluginsDir(context).listFiles().orEmpty()
|
||||
.filter { it.isDirectory && !it.name.startsWith(".droiddeck-") }
|
||||
.mapNotNull { folder ->
|
||||
runCatching {
|
||||
val meta = JSONObject(File(folder, "plugin.json").readText())
|
||||
val version = runCatching { JSONObject(File(folder, "package.json").readText()).optString("version") }.getOrDefault("")
|
||||
Installed(meta.getString("name"), folder.name, meta.optString("author"), version)
|
||||
}.getOrNull()
|
||||
}
|
||||
.sortedBy { it.name.lowercase() }
|
||||
|
||||
fun updateAvailable(installed: Installed, plugin: Plugin?): Boolean {
|
||||
val latest = plugin?.latest?.name ?: return false
|
||||
return installed.version.isNotEmpty() && latest != installed.version
|
||||
}
|
||||
|
||||
fun install(context: Context, plugin: Plugin, version: Version, progress: (String, Int) -> Unit): String? {
|
||||
if (SessionState.running) return context.getString(R.string.deckymgr_stop_session_plugin)
|
||||
if (DeckyManager.installed(context) == null) return context.getString(R.string.deckymgr_loader_required)
|
||||
val cache = File(context.cacheDir, "decky-store").apply { mkdirs() }
|
||||
val zip = File(cache, "${version.hash}.zip")
|
||||
try {
|
||||
val label = context.getString(R.string.decky_store_downloading, plugin.name)
|
||||
progress(label, -1)
|
||||
val ok = Downloader.downloadFile("$ARTIFACTS${version.hash}.zip", zip, true, version.hash) { fraction ->
|
||||
progress(label, if (fraction < 0) -1 else (fraction * 100).toInt().coerceIn(0, 100))
|
||||
}
|
||||
if (!ok) return context.getString(R.string.decky_store_download_failed, plugin.name)
|
||||
return DeckyManager.installPluginZip(context, zip, progress)
|
||||
} finally {
|
||||
zip.delete()
|
||||
}
|
||||
}
|
||||
|
||||
fun remove(context: Context, plugin: Installed): String? {
|
||||
if (SessionState.running) return context.getString(R.string.deckymgr_stop_session_plugin)
|
||||
val plugins = pluginsDir(context)
|
||||
val folder = File(plugins, plugin.folder)
|
||||
if (folder.parentFile?.canonicalFile != plugins.canonicalFile) return context.getString(R.string.decky_store_remove_failed)
|
||||
if (!folder.deleteRecursively()) return context.getString(R.string.decky_store_remove_failed)
|
||||
val settings = File(plugins.parentFile, "settings/loader.json")
|
||||
runCatching {
|
||||
val json = JSONObject(settings.readText())
|
||||
for (key in listOf("pluginOrder", "frozenPlugins", "hiddenPlugins", "disabled_plugins")) {
|
||||
val values = json.optJSONArray(key) ?: continue
|
||||
json.put(key, JSONArray((0 until values.length()).map { values.get(it) }.filter { it != plugin.name }))
|
||||
}
|
||||
settings.writeText(json.toString(4))
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -14,22 +14,20 @@ import java.util.concurrent.atomic.AtomicBoolean
|
||||
object GuestCommand {
|
||||
fun run(context: Context, argv: List<String>, fakeRoot: Boolean = false, logName: String? = null,
|
||||
linkDir: File? = null, extraBinds: List<String>? = null, fastPath: Boolean = false, cancelled: AtomicBoolean? = null,
|
||||
redact: Regex? = null, onLine: (String) -> Unit): Int {
|
||||
onLine: (String) -> Unit): Int {
|
||||
val log = logName?.let {
|
||||
try {
|
||||
File(File(LinuxRuntime.logDir(context), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter()
|
||||
} catch (e: Exception) { null }
|
||||
}
|
||||
log?.println("== ${java.util.Date()} ${redacted(argv.joinToString(" "), redact)}")
|
||||
log?.println("== ${java.util.Date()} ${argv.joinToString(" ")}")
|
||||
try {
|
||||
return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath, cancelled) { line -> log?.println(redacted(line, redact)); log?.flush(); onLine(line) }
|
||||
return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath, cancelled) { line -> log?.println(line); log?.flush(); onLine(line) }
|
||||
} finally {
|
||||
log?.close()
|
||||
}
|
||||
}
|
||||
|
||||
internal fun redacted(text: String, redact: Regex?): String = redact?.replace(text, "<redacted>") ?: text
|
||||
|
||||
private fun runLogged(context: Context, argv: List<String>, fakeRoot: Boolean, linkDir: File?, extraBinds: List<String>?,
|
||||
fastPath: Boolean, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
|
||||
@@ -275,15 +275,12 @@ class LinuxNetworkLinkComponent(
|
||||
* crash or power cut can keep the rename and lose the data, leaving a file of NUL bytes.
|
||||
*/
|
||||
private fun replace(file: File, text: String) {
|
||||
synchronized(WRITES) {
|
||||
if (runCatching { file.isFile && file.readText() == text }.getOrDefault(false)) return
|
||||
val staged = File(file.path + ".staged")
|
||||
java.io.FileOutputStream(staged).use { out ->
|
||||
out.write(text.toByteArray())
|
||||
out.fd.sync()
|
||||
}
|
||||
if (!staged.renameTo(file)) throw IOException("Could not replace $file")
|
||||
val staged = File(file.path + ".staged")
|
||||
java.io.FileOutputStream(staged).use { out ->
|
||||
out.write(text.toByteArray())
|
||||
out.fd.sync()
|
||||
}
|
||||
if (!staged.renameTo(file)) throw IOException("Could not replace $file")
|
||||
}
|
||||
|
||||
private fun writeResolver(properties: LinkProperties?) {
|
||||
@@ -336,8 +333,6 @@ class LinuxNetworkLinkComponent(
|
||||
seededMac { Settings.Secure.getString(appContext.contentResolver, Settings.Secure.ANDROID_ID) }
|
||||
|
||||
companion object {
|
||||
private val WRITES = Any()
|
||||
|
||||
internal fun gateways(properties: LinkProperties?, capabilities: NetworkCapabilities?): List<InetAddress> =
|
||||
listOf(Inet4Address::class.java, Inet6Address::class.java).mapNotNull { family ->
|
||||
properties?.routes.orEmpty()
|
||||
|
||||
@@ -76,6 +76,7 @@ object NativeGuest {
|
||||
fun environment(root: File, preload: List<String> = emptyList()): Map<String, String> = linkedMapOf(
|
||||
"DDNATV_ROOT" to root.path,
|
||||
"DDNATV_EXEC" to execLoader.orEmpty(),
|
||||
"LD_LIBRARY_PATH" to libraryPath(root),
|
||||
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
|
||||
).filterValues { it.isNotEmpty() }
|
||||
|
||||
@@ -83,10 +84,10 @@ object NativeGuest {
|
||||
* The host command line for the guest program at [program] (an absolute guest path to a real
|
||||
* file, not a symlink).
|
||||
*/
|
||||
fun command(root: File, program: String, args: List<String>, libraryPath: String = libraryPath(root)): List<String> {
|
||||
fun command(root: File, program: String, args: List<String>): List<String> {
|
||||
val loader = checkNotNull(loader(root)) { "no glibc loader in ${root.path}" }
|
||||
val host = File(root, program.removePrefix("/"))
|
||||
val launch = listOf(loader.path, "--library-path", libraryPath, "--argv0", host.name, host.path) + args
|
||||
val launch = listOf(loader.path, "--argv0", host.name, host.path) + args
|
||||
return simulator(root)?.let { it + launch } ?: (execPrefix(loader.path) + launch)
|
||||
}
|
||||
|
||||
@@ -99,6 +100,7 @@ object NativeGuest {
|
||||
"DDNATV_HOSTNAME" to hostname.orEmpty(),
|
||||
"DDNATV_BINDS" to binds.joinToString("|") { if (it.contains(':')) it else "$it:$it" },
|
||||
"DDNATV_PRELOAD" to preload.joinToString(":"),
|
||||
"LD_LIBRARY_PATH" to libraryPath(root),
|
||||
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
|
||||
).filterValues { it.isNotEmpty() }
|
||||
}
|
||||
@@ -271,9 +273,7 @@ object NativeGuest {
|
||||
|
||||
fun builder(root: File, cwd: String, argv: List<String>, env: Map<String, String>, preload: List<String> = emptyList()): ProcessBuilder {
|
||||
val program = argv.first()
|
||||
val callerDirs = env["LD_LIBRARY_PATH"]?.takeIf { it.isNotEmpty() }?.split(':').orEmpty()
|
||||
val rootDirs = libraryPath(root).split(':').filterNot { it in callerDirs }
|
||||
val cmd = command(root, program, argv.drop(1), (callerDirs + rootDirs).joinToString(":"))
|
||||
val cmd = command(root, program, argv.drop(1))
|
||||
val builder = ProcessBuilder(cmd).redirectErrorStream(false)
|
||||
builder.directory(File(root, cwd.removePrefix("/")).takeIf { it.isDirectory } ?: root)
|
||||
builder.environment().apply {
|
||||
|
||||
@@ -29,7 +29,6 @@ object WowAddonCatalog {
|
||||
val downloads: Long,
|
||||
val updated: Long,
|
||||
val thumb: String?,
|
||||
val folders: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
class Page(val items: List<Addon>, val more: Boolean)
|
||||
@@ -94,7 +93,8 @@ object WowAddonCatalog {
|
||||
Client(folder, version?.let(::flavorOf) ?: folderFamily(folder))
|
||||
|
||||
fun client(target: WowAddons.Target): Client {
|
||||
return client(target.flavor, WowAddons.flavorDir(target)?.let(::clientVersion))
|
||||
val dir = target.addOns.parentFile?.parentFile
|
||||
return client(target.flavor, dir?.let(::clientVersion))
|
||||
}
|
||||
|
||||
internal fun flavorMatches(flavors: Set<String>?, family: String?): Boolean =
|
||||
@@ -115,11 +115,9 @@ object WowAddonCatalog {
|
||||
}
|
||||
val thumbs = o.optJSONArray("UIIMG_Thumbs")
|
||||
val thumb = if (thumbs != null && thumbs.length() > 0) thumbs.optString(0).ifEmpty { null } else null
|
||||
val dirs = o.optJSONArray("UIDir")
|
||||
val folders = if (dirs == null) emptyList() else (0 until dirs.length()).map { dirs.optString(it).trim() }.filter { it.isNotEmpty() }
|
||||
val addon = Addon(
|
||||
id, o.optString("UIName"), o.optString("UIAuthorName"), o.optString("UIVersion"),
|
||||
o.optString("UIDownloadTotal").toLongOrNull() ?: 0L, o.optLong("UIDate"), thumb, folders,
|
||||
o.optString("UIDownloadTotal").toLongOrNull() ?: 0L, o.optLong("UIDate"), thumb,
|
||||
)
|
||||
out.add(Entry(addon, o.optString("UICATID"), flavors, o.optString("UIDownloadMonthly").toLongOrNull() ?: 0L))
|
||||
}
|
||||
@@ -244,32 +242,9 @@ object WowAddonCatalog {
|
||||
return details.version
|
||||
}
|
||||
|
||||
private fun normVersion(v: String) = v.trim().removePrefix("v").removePrefix("V").trim().lowercase()
|
||||
|
||||
internal fun sameVersion(a: String, b: String): Boolean = normVersion(a) == normVersion(b)
|
||||
|
||||
private val NUMERIC_VERSION = Regex("""^(\d+(?:\.\d+)*)(.*)$""")
|
||||
|
||||
private fun numericVersion(v: String): Pair<List<Long>, String>? {
|
||||
val match = NUMERIC_VERSION.matchEntire(normVersion(v)) ?: return null
|
||||
val parts = match.groupValues[1].split('.').map { it.toLongOrNull() ?: return null }
|
||||
return parts to match.groupValues[2]
|
||||
}
|
||||
|
||||
internal fun newer(have: String, latest: String): Boolean? {
|
||||
val (a, aRest) = numericVersion(have) ?: return null
|
||||
val (b, bRest) = numericVersion(latest) ?: return null
|
||||
for (i in 0 until maxOf(a.size, b.size)) {
|
||||
val x = a.getOrElse(i) { 0L }
|
||||
val y = b.getOrElse(i) { 0L }
|
||||
if (x != y) return y > x
|
||||
}
|
||||
return if (aRest == bRest) false else null
|
||||
}
|
||||
|
||||
internal fun offersUpdate(have: String?, latest: String, sameSource: Boolean): Boolean {
|
||||
if (have.isNullOrBlank() || latest.isBlank() || sameVersion(have, latest)) return false
|
||||
return newer(have, latest) ?: sameSource
|
||||
internal fun sameVersion(a: String, b: String): Boolean {
|
||||
fun norm(v: String) = v.trim().removePrefix("v").removePrefix("V").trim().lowercase()
|
||||
return norm(a) == norm(b)
|
||||
}
|
||||
|
||||
internal fun findUpdates(entries: List<Entry>, installed: List<WowAddons.Installed>): Map<String, Addon> {
|
||||
@@ -279,7 +254,7 @@ object WowAddonCatalog {
|
||||
val id = item.wowiId ?: return@mapNotNull null
|
||||
val version = item.version ?: return@mapNotNull null
|
||||
val latest = byId[id]?.addon?.takeIf { it.summary.isNotBlank() } ?: return@mapNotNull null
|
||||
if (!offersUpdate(version, latest.summary, sameSource = true) || !seen.add(id)) null else item.name to latest
|
||||
if (sameVersion(version, latest.summary) || !seen.add(id)) null else item.name to latest
|
||||
}.toMap()
|
||||
}
|
||||
|
||||
|
||||
@@ -28,27 +28,15 @@ object WowAddons {
|
||||
|
||||
class TooLarge : IOException()
|
||||
|
||||
fun changed() {
|
||||
imports++
|
||||
}
|
||||
|
||||
fun flavorDir(target: Target): File? = target.addOns.parentFile?.parentFile
|
||||
|
||||
fun root(target: Target): File? = flavorDir(target)?.parentFile
|
||||
|
||||
class Target(val flavor: String, val addOns: File)
|
||||
|
||||
class Addon(val name: String, val root: String)
|
||||
|
||||
class Installed(val name: String, val version: String?, val wowiId: String?, val curseId: String? = null)
|
||||
class Installed(val name: String, val version: String?, val wowiId: String?)
|
||||
|
||||
class Origin(val id: String, val version: String)
|
||||
|
||||
private const val ORIGINS = ".droiddeck-sources"
|
||||
private const val TOC_VERSION = "Version"
|
||||
private const val TOC_WOWI_ID = "X-WoWI-ID"
|
||||
private const val TOC_CURSE_ID = "X-Curse-Project-ID"
|
||||
private val TOC_KEYS = setOf(TOC_VERSION, TOC_WOWI_ID, TOC_CURSE_ID)
|
||||
|
||||
internal const val MAX_EXPANDED_BYTES = 4L * 1024 * 1024 * 1024
|
||||
|
||||
@@ -73,52 +61,33 @@ object WowAddons {
|
||||
target.addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }
|
||||
.map { it.name }.sortedBy { it.lowercase() }
|
||||
|
||||
fun present(folders: List<String>, exists: (String) -> Boolean): Boolean = folders.isNotEmpty() && folders.all(exists)
|
||||
|
||||
fun folder(addOns: File, name: String): File? {
|
||||
val dirs = addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }
|
||||
return dirs.firstOrNull { it.name == name } ?: dirs.firstOrNull { it.name.equals(name, ignoreCase = true) }
|
||||
}
|
||||
|
||||
fun details(target: Target): List<Installed> {
|
||||
val origins = origins(target)
|
||||
return installed(target).map { name ->
|
||||
val toc = toc(File(target.addOns, name))
|
||||
val origin = origins[name]
|
||||
Installed(name, origin?.version ?: toc[TOC_VERSION], origin?.id ?: toc[TOC_WOWI_ID], toc[TOC_CURSE_ID])
|
||||
Installed(name, origin?.version ?: toc["Version"], origin?.id ?: toc["X-WoWI-ID"])
|
||||
}
|
||||
}
|
||||
|
||||
internal fun tocFields(lines: Sequence<String>, keys: Set<String> = TOC_KEYS): Map<String, String> {
|
||||
internal fun tocFields(text: String): Map<String, String> {
|
||||
val out = LinkedHashMap<String, String>()
|
||||
for (raw in lines) {
|
||||
for (raw in text.lineSequence()) {
|
||||
val line = raw.trim().removePrefix("\uFEFF")
|
||||
if (!line.startsWith("##") || ':' !in line) continue
|
||||
val key = line.removePrefix("##").substringBefore(':').trim()
|
||||
if (key !in keys || key in out) continue
|
||||
val value = line.substringAfter(':').trim()
|
||||
if (value.isNotEmpty() && '@' !in value) out[key] = value
|
||||
if (out.size == keys.size) break
|
||||
if (key.isNotEmpty() && value.isNotEmpty() && '@' !in value) out.putIfAbsent(key, value)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private fun toc(folder: File): Map<String, String> {
|
||||
val tocs = folder.listFiles().orEmpty().filter { it.isFile && it.name.endsWith(".toc", ignoreCase = true) }.sortedWith(
|
||||
compareBy<File>(
|
||||
{ !it.name.dropLast(4).equals(folder.name, ignoreCase = true) },
|
||||
{ !it.name.dropLast(4).replace(SUFFIX, "").equals(folder.name, ignoreCase = true) },
|
||||
{ it.name.length },
|
||||
{ it.name },
|
||||
),
|
||||
)
|
||||
val out = LinkedHashMap<String, String>()
|
||||
for (file in tocs) {
|
||||
if (out.size == TOC_KEYS.size) break
|
||||
val missing = TOC_KEYS - out.keys
|
||||
runCatching { file.bufferedReader().useLines { tocFields(it, missing) } }.getOrNull()?.let(out::putAll)
|
||||
}
|
||||
return out
|
||||
val tocs = folder.listFiles().orEmpty().filter { it.isFile && it.name.endsWith(".toc", ignoreCase = true) }
|
||||
val main = tocs.firstOrNull { it.name.dropLast(4).equals(folder.name, ignoreCase = true) }
|
||||
?: tocs.firstOrNull { it.name.dropLast(4).replace(SUFFIX, "").equals(folder.name, ignoreCase = true) }
|
||||
?: tocs.minByOrNull { it.name.length } ?: return emptyMap()
|
||||
return runCatching { tocFields(main.readText()) }.getOrDefault(emptyMap())
|
||||
}
|
||||
|
||||
internal fun parseOrigins(text: String): Map<String, Origin> = text.lineSequence().mapNotNull { line ->
|
||||
|
||||
@@ -11,15 +11,7 @@ import java.io.RandomAccessFile
|
||||
import java.nio.charset.StandardCharsets
|
||||
|
||||
class LoadingState(context: Context, private val steam: Boolean = true) {
|
||||
private val prefs = context.getSharedPreferences("loading", Context.MODE_PRIVATE)
|
||||
private val firstRun = steam && !prefs.getBoolean(FIRST_DONE, false)
|
||||
private var shown by mutableStateOf(true)
|
||||
var visible: Boolean
|
||||
get() = shown
|
||||
set(value) {
|
||||
shown = value
|
||||
if (!value && steam) prefs.edit().putBoolean(FIRST_DONE, true).apply()
|
||||
}
|
||||
var visible by mutableStateOf(true)
|
||||
var step by mutableStateOf(context.getString(com.droiddeck.launcher.R.string.loadstate_starting))
|
||||
private set
|
||||
var topic by mutableStateOf(Topic.SESSION)
|
||||
@@ -41,7 +33,7 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
|
||||
fun tick() {
|
||||
val seconds = (SystemClock.elapsedRealtime() - startedAt) / 1000
|
||||
elapsed = res.getString(com.droiddeck.launcher.R.string.loadstate_elapsed, seconds / 60, seconds % 60)
|
||||
hint = if (firstRun) res.getString(com.droiddeck.launcher.R.string.loading_first_run) else hints[((seconds / 8) % hints.size).toInt()]
|
||||
hint = hints[((seconds / 8) % hints.size).toInt()]
|
||||
}
|
||||
|
||||
fun say(line: String, topic: Topic, readable: Boolean) {
|
||||
@@ -134,7 +126,6 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
|
||||
enum class Topic { RUNTIME, SESSION, DESKTOP, STEAM, STEAM_STARTING, OTHER }
|
||||
|
||||
companion object {
|
||||
private const val FIRST_DONE = "first_done"
|
||||
internal fun topicOf(scriptStep: String, steam: Boolean): Topic {
|
||||
val t = scriptStep.lowercase()
|
||||
return when {
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
|
||||
import com.droiddeck.launcher.runtime.RuntimeInstallService
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
|
||||
/** What first run installs by itself, in the order it is needed, and how far each part has got. */
|
||||
object Onboarding {
|
||||
enum class Step { RUNTIME, PROTON, STEAM }
|
||||
|
||||
data class Progress(val label: String, val percent: Int)
|
||||
|
||||
data class Facts(val runtime: Boolean = true, val proton: Boolean = true, val steam: Boolean = true)
|
||||
|
||||
enum class State { DONE, ACTIVE, WAITING, FAILED }
|
||||
|
||||
data class Row(val step: Step, val state: State, val label: String?, val percent: Int)
|
||||
|
||||
val active = MutableStateFlow<Map<Step, Progress>>(emptyMap())
|
||||
val failed = MutableStateFlow<Map<Step, String>>(emptyMap())
|
||||
val facts = MutableStateFlow(Facts())
|
||||
|
||||
@Volatile private var appContext: Context? = null
|
||||
private var hold: (() -> Unit)? = null
|
||||
|
||||
/** The setup screens belong to the first run; later runtime, Proton and Steam client updates keep the usual Play button. */
|
||||
val firstRun = MutableStateFlow(true)
|
||||
|
||||
fun attach(context: Context) {
|
||||
appContext = context.applicationContext
|
||||
val prefs = context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
var done = prefs.getBoolean(KEY_FIRST_RUN_DONE, false)
|
||||
if (!done && runCatching { installedAndReady(context) }.getOrDefault(false)) {
|
||||
done = true
|
||||
prefs.edit().putBoolean(KEY_FIRST_RUN_DONE, true).apply()
|
||||
}
|
||||
firstRun.value = !done
|
||||
}
|
||||
|
||||
/** Everything first run installs is in place, with the same Proton rule as [recheck]. */
|
||||
private fun installedAndReady(context: Context): Boolean {
|
||||
val own = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
|
||||
return LinuxRuntime.isInstalled(context) && !SteamClientPrefetch.pending(context) &&
|
||||
(ProtonExtras.declined(context) || ProtonExtras.installedAll(context, own).isNotEmpty())
|
||||
}
|
||||
|
||||
private const val PREFS = "onboarding"
|
||||
private const val KEY_FIRST_RUN_DONE = "first_run_done"
|
||||
|
||||
private fun markFirstRunDone() {
|
||||
val context = appContext ?: return
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(KEY_FIRST_RUN_DONE, true).apply()
|
||||
firstRun.value = false
|
||||
}
|
||||
|
||||
/** Keeps the process in the foreground, with one notification, while a step downloads and the runtime installer is not already doing so. */
|
||||
@Synchronized private fun keepAlive() {
|
||||
val context = appContext ?: return
|
||||
val running = active.value
|
||||
if (running.isNotEmpty() && !LinuxRuntimeInstaller.isBusy()) {
|
||||
if (hold == null) hold = RuntimeInstallService.holdForPackage(context, context.getString(R.string.onboarding_title))
|
||||
val rows = rows(running, failed.value, facts.value)
|
||||
RuntimeInstallService.packageProgress(running.values.first().label, overall(rows))
|
||||
} else {
|
||||
hold?.invoke()
|
||||
hold = null
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized fun recheck(context: Context) {
|
||||
val runtime = LinuxRuntime.isInstalled(context)
|
||||
val own = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
|
||||
facts.value = Facts(
|
||||
runtime = runtime,
|
||||
proton = ProtonExtras.declined(context) || ProtonExtras.installedAll(context, own).isNotEmpty(),
|
||||
steam = runtime && !SteamClientPrefetch.pending(context),
|
||||
)
|
||||
settle()
|
||||
}
|
||||
|
||||
/** A new attempt starts from zero once everything is ready, whichever screen is showing. */
|
||||
@Synchronized fun settle() {
|
||||
if (!pending(rows(active.value, failed.value, facts.value))) {
|
||||
resetProgress()
|
||||
markFirstRunDone()
|
||||
}
|
||||
}
|
||||
|
||||
fun report(step: Step, label: String, percent: Int) {
|
||||
failed.value = failed.value - step
|
||||
active.value = active.value + (step to Progress(label, percent))
|
||||
keepAlive()
|
||||
}
|
||||
|
||||
fun finish(step: Step) {
|
||||
active.value = active.value - step
|
||||
failed.value = failed.value - step
|
||||
keepAlive()
|
||||
}
|
||||
|
||||
fun fail(step: Step, message: String) {
|
||||
active.value = active.value - step
|
||||
failed.value = failed.value + (step to message)
|
||||
keepAlive()
|
||||
}
|
||||
|
||||
fun rows(active: Map<Step, Progress>, failed: Map<Step, String>, facts: Facts): List<Row> = Step.entries.map { step ->
|
||||
val ready = when (step) { Step.RUNTIME -> facts.runtime; Step.PROTON -> facts.proton; Step.STEAM -> facts.steam }
|
||||
val progress = active[step]
|
||||
when {
|
||||
progress != null -> Row(step, State.ACTIVE, progress.label, progress.percent)
|
||||
failed[step] != null -> Row(step, State.FAILED, failed[step], -1)
|
||||
ready -> Row(step, State.DONE, null, 100)
|
||||
else -> Row(step, State.WAITING, null, -1)
|
||||
}
|
||||
}
|
||||
|
||||
fun pending(rows: List<Row>): Boolean = rows.any { it.state != State.DONE }
|
||||
|
||||
/** Whether first-run downloads are under way, as the home screen decides it. */
|
||||
fun settling(): Boolean = firstRun.value && active.value.isNotEmpty() && pending(rows(active.value, failed.value, facts.value))
|
||||
|
||||
@Volatile private var highWater = 0
|
||||
|
||||
@Synchronized internal fun resetProgress() { highWater = 0 }
|
||||
|
||||
/**
|
||||
* The aggregate fraction of the whole first-run work, weighting each step by what it downloads: about 290 MB, 630 MB and 1,050 MB.
|
||||
* Steps download first and install later, restarting their own percent, so the figure only moves forward until everything is done.
|
||||
*/
|
||||
@Synchronized fun overall(rows: List<Row>): Int {
|
||||
val measured = measure(rows)
|
||||
if (!pending(rows)) {
|
||||
highWater = 0
|
||||
return measured
|
||||
}
|
||||
highWater = maxOf(highWater, measured)
|
||||
return highWater
|
||||
}
|
||||
|
||||
internal fun measure(rows: List<Row>): Int {
|
||||
val weights = mapOf(Step.RUNTIME to 20, Step.PROTON to 30, Step.STEAM to 50)
|
||||
val total = weights.values.sum()
|
||||
val got = rows.sumOf { row ->
|
||||
val w = weights.getValue(row.step)
|
||||
when (row.state) {
|
||||
State.DONE -> w
|
||||
State.ACTIVE -> if (row.percent >= 0) w * row.percent / 100 else 0
|
||||
else -> 0
|
||||
}
|
||||
}
|
||||
return got * 100 / total
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,6 @@ object ProtonExtras {
|
||||
const val CHECK_EVERY_MS = 60L * 60 * 1000
|
||||
@Volatile
|
||||
var installInProgress = false
|
||||
@Volatile var prefetching = false
|
||||
private set
|
||||
@Volatile
|
||||
private var replacing = false
|
||||
@@ -218,12 +217,24 @@ object ProtonExtras {
|
||||
|
||||
@Synchronized
|
||||
fun install(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||
if (installInProgress || prefetching) return context.getString(R.string.pextra_busy)
|
||||
if (installInProgress) return context.getString(R.string.pextra_busy)
|
||||
installInProgress = true
|
||||
return try { installNow(context, tool, onProgress) } finally { installInProgress = false }
|
||||
}
|
||||
|
||||
private fun fetchArchive(context: Context, tool: Tool, asset: Asset, archive: File, onProgress: (String, Int) -> Unit): String? {
|
||||
private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||
if (SessionState.running) return context.getString(R.string.pextra_stop_session)
|
||||
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
|
||||
|
||||
val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name)
|
||||
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
|
||||
val archive = File(downloads, "${tool.id}-${asset.name}")
|
||||
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
|
||||
val missing = (asset.size - archive.length()).coerceAtLeast(0L)
|
||||
if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + missing) {
|
||||
return context.getString(R.string.pextra_no_space, tool.name)
|
||||
}
|
||||
|
||||
val downloading = context.getString(R.string.pextra_downloading, tool.name, asset.tag)
|
||||
onProgress(downloading, 0)
|
||||
var downloaded = false
|
||||
@@ -241,41 +252,6 @@ object ProtonExtras {
|
||||
}
|
||||
}
|
||||
if (!downloaded) return context.getString(R.string.pextra_download_failed)
|
||||
return null
|
||||
}
|
||||
|
||||
/** Downloads the newest build of [tool] ahead of the runtime it installs into; [install] verifies and unpacks it later. */
|
||||
@Synchronized
|
||||
fun prefetch(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||
if (installInProgress) return context.getString(R.string.pextra_busy)
|
||||
prefetching = true
|
||||
try { return prefetchNow(context, tool, onProgress) } finally { prefetching = false }
|
||||
}
|
||||
|
||||
private fun prefetchNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||
val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name)
|
||||
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
|
||||
val archive = File(downloads, "${tool.id}-${asset.name}")
|
||||
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
|
||||
val missing = (asset.size - archive.length()).coerceAtLeast(0L)
|
||||
if (StatFs(context.filesDir.path).availableBytes < NEED_BYTES + missing) return context.getString(R.string.pextra_no_space, tool.name)
|
||||
return fetchArchive(context, tool, asset, archive, onProgress)
|
||||
}
|
||||
|
||||
private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||
if (SessionState.running) return context.getString(R.string.pextra_stop_session)
|
||||
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
|
||||
|
||||
val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name)
|
||||
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
|
||||
val archive = File(downloads, "${tool.id}-${asset.name}")
|
||||
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
|
||||
val missing = (asset.size - archive.length()).coerceAtLeast(0L)
|
||||
if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + missing) {
|
||||
return context.getString(R.string.pextra_no_space, tool.name)
|
||||
}
|
||||
|
||||
fetchArchive(context, tool, asset, archive, onProgress)?.let { return it }
|
||||
if (asset.size > 0 && archive.length() != asset.size) {
|
||||
if (archive.length() > asset.size) {
|
||||
archive.delete()
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
/** A launch the user asked for that waits for something else to finish first, and is forgotten if it waits too long. */
|
||||
class QueuedLaunch<T : Any>(private val lifetimeMs: Long = 15 * 60_000L) {
|
||||
var launch: T? = null
|
||||
private set
|
||||
var queuedAt: Long = 0L
|
||||
private set
|
||||
|
||||
fun queue(launch: T, now: Long) {
|
||||
this.launch = launch
|
||||
queuedAt = now
|
||||
}
|
||||
|
||||
/** Takes back a saved launch with the time it was first queued; one without a valid time or past its lifetime is dropped. */
|
||||
fun restore(launch: T?, queuedAt: Long, now: Long) {
|
||||
if (launch != null && fresh(queuedAt, now)) {
|
||||
this.launch = launch
|
||||
this.queuedAt = queuedAt
|
||||
} else {
|
||||
clear()
|
||||
}
|
||||
}
|
||||
|
||||
/** The launch if it is still wanted; an expired one is cleared. */
|
||||
fun current(now: Long): T? {
|
||||
val queued = launch ?: return null
|
||||
if (fresh(queuedAt, now)) return queued
|
||||
clear()
|
||||
return null
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
launch = null
|
||||
}
|
||||
|
||||
private fun fresh(queuedAt: Long, now: Long) = now - queuedAt in 0..lifetimeMs
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
/**
|
||||
* Starts a queued launch once nothing stands in its way and retries until it can or it expires. One runner belongs to one
|
||||
* activity: destroying it clears its queue and cancels its retry, so a restored activity is the only one that starts the launch.
|
||||
*/
|
||||
class QueuedLaunchRunner<T : Any>(
|
||||
private val queue: QueuedLaunch<T>,
|
||||
private val now: () -> Long,
|
||||
private val blocked: () -> Boolean,
|
||||
private val busy: () -> Boolean,
|
||||
private val schedule: (delayMs: Long, task: Runnable) -> Unit,
|
||||
private val unschedule: (Runnable) -> Unit,
|
||||
private val start: (T) -> Unit,
|
||||
private val retryMs: Long = 2_000L,
|
||||
) {
|
||||
private var posted = false
|
||||
private var retry: Runnable? = null
|
||||
private var destroyed = false
|
||||
|
||||
/** Call whenever the blocking setting may have changed. */
|
||||
fun poke() {
|
||||
if (destroyed || posted) return
|
||||
val launch = queue.current(now()) ?: return
|
||||
if (blocked()) return
|
||||
posted = true
|
||||
schedule(0L, Runnable {
|
||||
posted = false
|
||||
attempt(launch)
|
||||
})
|
||||
}
|
||||
|
||||
private fun attempt(launch: T) {
|
||||
if (destroyed || queue.current(now()) !== launch) return
|
||||
if (busy()) {
|
||||
val again = Runnable { if (!destroyed && queue.launch === launch) poke() }
|
||||
retry = again
|
||||
schedule(retryMs, again)
|
||||
return
|
||||
}
|
||||
queue.clear()
|
||||
start(launch)
|
||||
}
|
||||
|
||||
fun destroy() {
|
||||
destroyed = true
|
||||
queue.clear()
|
||||
retry?.let(unschedule)
|
||||
retry = null
|
||||
}
|
||||
}
|
||||
@@ -95,11 +95,7 @@ object SessionFiles {
|
||||
return all
|
||||
}
|
||||
|
||||
private val STAGE_LOCK = Any()
|
||||
|
||||
fun stage(context: Context, root: File, startsSession: Boolean = false) = synchronized(STAGE_LOCK) { stageNow(context, root, startsSession) }
|
||||
|
||||
private fun stageNow(context: Context, root: File, startsSession: Boolean) {
|
||||
fun stage(context: Context, root: File, startsSession: Boolean = false) {
|
||||
if (DesktopCatalog.desktopInstalled(root) && !DesktopCatalog.desktopFromPack(root)) try { DesktopCatalog.cleanLegacy(context) }
|
||||
catch (e: Exception) { Log.w(TAG, "LXQt cleanup will retry next session", e) }
|
||||
GameEnvironmentStore.publish(context)
|
||||
@@ -184,8 +180,6 @@ object SessionFiles {
|
||||
"usr/local/bin/droiddeck-flatpak-run" to "usr/local/bin/droiddeck-flatpak-run",
|
||||
"usr/local/bin/droiddeck-appimage-run" to "usr/local/bin/droiddeck-appimage-run",
|
||||
"usr/local/bin/droiddeck-appimage-exec" to "usr/local/bin/droiddeck-appimage-exec",
|
||||
"usr/local/bin/droiddeck-curseforge" to "usr/local/bin/droiddeck-curseforge",
|
||||
"usr/local/bin/droiddeck-headless" to "usr/local/bin/droiddeck-headless",
|
||||
"usr/local/bin/droiddeck-script-run" to "usr/local/bin/droiddeck-script-run",
|
||||
"usr/local/bin/droiddeck-open" to "usr/local/bin/droiddeck-open",
|
||||
"usr/local/bin/droiddeck-proton-run" to "usr/local/bin/droiddeck-proton-run",
|
||||
@@ -664,7 +658,6 @@ object SessionFiles {
|
||||
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 LIBRARY_BIG_ART = "LibraryHomeBigArt"
|
||||
private const val BATTERY_PERCENT_ON = "{\\\"bShowBatteryPercentage\\\":true}"
|
||||
|
||||
/**
|
||||
@@ -714,12 +707,7 @@ object SessionFiles {
|
||||
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))
|
||||
}
|
||||
out = seedRecentSort(out, newline)
|
||||
val last = findObject(out, "UserLocalConfigStore", 0, out.length) ?: return out
|
||||
if (!hasKey(out.substring(last.open + 1, last.close), LIBRARY_BIG_ART)) {
|
||||
out = insertInto(out, last, listOf("\"$LIBRARY_BIG_ART\"\t\t\"1\""), newline)
|
||||
}
|
||||
return out
|
||||
return seedRecentSort(out, newline)
|
||||
}
|
||||
|
||||
// The library sort lives inside a JSON string; Steam writes bSortedByRecent:false until the player picks a sort,
|
||||
@@ -739,11 +727,9 @@ object SessionFiles {
|
||||
|
||||
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 before = text.substring(lineStart, parent.close)
|
||||
val indent = before.takeWhile { it == '\t' || it == ' ' } + "\t"
|
||||
val indent = text.substring(lineStart, parent.close).takeWhile { it == '\t' || it == ' ' } + "\t"
|
||||
val section = lines.joinToString(newline) { indent + it } + newline
|
||||
if (before.isBlank()) return text.substring(0, lineStart) + section + text.substring(lineStart)
|
||||
return text.substring(0, parent.close) + newline + section + text.substring(parent.close)
|
||||
return text.substring(0, lineStart) + section + text.substring(lineStart)
|
||||
}
|
||||
|
||||
private val IDLE_SLEEP_TIMERS = listOf("IdleSuspendBatterySeconds", "IdleSuspendACSeconds")
|
||||
|
||||
@@ -63,13 +63,6 @@ object SessionPrefs {
|
||||
.takeIf { value -> orientationOptions.any { it.first == value } }
|
||||
?: ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
|
||||
|
||||
/** The session menu's width in dp the user dragged it to; null keeps the default. */
|
||||
fun drawerWidthDp(context: Context): Int? = prefs(context).getInt("drawerWidthDp", 0).takeIf { it > 0 }
|
||||
|
||||
fun setDrawerWidthDp(context: Context, dp: Int) {
|
||||
prefs(context).edit().putInt("drawerWidthDp", dp).apply()
|
||||
}
|
||||
|
||||
fun setOrientation(context: Context, orientation: Int) {
|
||||
require(orientationOptions.any { it.first == orientation })
|
||||
prefs(context).edit().putInt("orientation", orientation).apply()
|
||||
@@ -1018,7 +1011,7 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("prootNoSeccomp", on).apply()
|
||||
}
|
||||
|
||||
fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", true)
|
||||
fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", false)
|
||||
|
||||
fun setNativeUserland(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("nativeUserland", on).apply()
|
||||
|
||||
@@ -2705,7 +2705,6 @@ class SessionService : Service() {
|
||||
gameId: String? = null,
|
||||
displayId: Int = Display.DEFAULT_DISPLAY,
|
||||
) {
|
||||
SteamClientPrefetch.cancel()
|
||||
SessionState.activityDisplayId = displayId
|
||||
val intent = Intent(context, SessionService::class.java).putExtra(EXTRA_MODE, mode)
|
||||
.putExtra(EXTRA_DISPLAY_ID, displayId)
|
||||
|
||||
@@ -13,7 +13,7 @@ object SettingsReset {
|
||||
|
||||
internal val SESSION_KEYS = setOf(
|
||||
"orientation", "launcherFullscreen", "controllerHaptics", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt",
|
||||
"drawerWidthDp", "dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard",
|
||||
"dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard",
|
||||
"soundtracksIngame", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
|
||||
"storesInstallLanguage",
|
||||
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "dockedMenuController", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController",
|
||||
|
||||
@@ -1,105 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
import kotlinx.coroutines.flow.update
|
||||
|
||||
/**
|
||||
* Downloads Valve's Steam client while the session is stopped, so the first Play does not wait on it.
|
||||
* It runs the same droiddeck-steam-install the session runs, which keeps what arrived when it is cut
|
||||
* short and resumes from there.
|
||||
*/
|
||||
object SteamClientPrefetch {
|
||||
private const val TAG = "SteamClientPrefetch"
|
||||
private val DOWNLOADING = Regex("""downloading Steam: .*, (\d+) of (\d+) MB""")
|
||||
|
||||
private const val CANCELLED = "cancelled"
|
||||
private val lock = Any()
|
||||
private var process: Process? = null
|
||||
private var cancelled = false
|
||||
@Volatile private var thread: Thread? = null
|
||||
|
||||
internal fun parse(line: String): Pair<Int, Int>? {
|
||||
val match = DOWNLOADING.find(line) ?: return null
|
||||
val done = match.groupValues[1].toLongOrNull() ?: return null
|
||||
val total = match.groupValues[2].toLongOrNull()?.takeIf { it > 0 } ?: return null
|
||||
return (done * 100 / total).toInt().coerceIn(0, 100) to total.toInt()
|
||||
}
|
||||
|
||||
fun running(): Boolean = thread?.isAlive == true
|
||||
|
||||
private const val CACHED = "root/.local/share/Steam/package/droiddeck-cached"
|
||||
|
||||
fun installPending(context: Context): Boolean = SteamDownloadMonitor.clientInstallPending(LinuxRuntime.rootDir(context))
|
||||
|
||||
fun pending(context: Context): Boolean =
|
||||
installPending(context) || !File(LinuxRuntime.rootDir(context), CACHED).isFile
|
||||
|
||||
/** Stops a running download so a session can take over; the script resumes the partial files. */
|
||||
fun cancel() {
|
||||
synchronized(lock) {
|
||||
cancelled = true
|
||||
process?.destroy()
|
||||
}
|
||||
}
|
||||
|
||||
private fun isCancelled() = synchronized(lock) { cancelled }
|
||||
|
||||
@Synchronized
|
||||
fun start(context: Context, label: (Int) -> String, failedLabel: String) {
|
||||
if (running() || SessionState.running || !LinuxRuntime.isInstalled(context) || !pending(context)) return
|
||||
val app = context.applicationContext
|
||||
synchronized(lock) { cancelled = false }
|
||||
thread = Thread({
|
||||
Onboarding.report(Onboarding.Step.STEAM, label(-1), -1)
|
||||
val problem = runCatching { run(app, label) }.getOrElse { it.message ?: it.javaClass.simpleName }
|
||||
synchronized(lock) { process = null }
|
||||
if (problem == null && !pending(app)) Onboarding.finish(Onboarding.Step.STEAM)
|
||||
else if (SessionState.running || problem == CANCELLED || isCancelled()) Onboarding.finish(Onboarding.Step.STEAM)
|
||||
else Onboarding.fail(Onboarding.Step.STEAM, problem ?: failedLabel)
|
||||
val steamReady = !pending(app)
|
||||
Onboarding.facts.update { it.copy(steam = steamReady) }
|
||||
Onboarding.settle()
|
||||
}, "steam-client-prefetch").also { it.start() }
|
||||
}
|
||||
|
||||
private fun run(context: Context, label: (Int) -> String): String? {
|
||||
if (isCancelled()) return CANCELLED
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
LinuxRuntime.writeAccounts(context)
|
||||
SessionFiles.stage(context, root)
|
||||
val install = installPending(context)
|
||||
if (install) {
|
||||
val problem = script(context, emptyList(), label, 0, 35)
|
||||
if (problem != null) return problem
|
||||
}
|
||||
return script(context, listOf("--cache"), label, if (install) 35 else 0, 100)
|
||||
}
|
||||
|
||||
private fun script(context: Context, args: List<String>, label: (Int) -> String, from: Int, to: Int): String? {
|
||||
val guest = listOf(
|
||||
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "PATH=/usr/local/bin:/usr/bin:/bin",
|
||||
"LANG=C.UTF-8", "XDG_DATA_HOME=/root/.local/share", "/usr/local/bin/droiddeck-steam-install",
|
||||
) + args
|
||||
if (isCancelled()) return CANCELLED
|
||||
val child = ProtonExtras.guestProcess(context, guest).start()
|
||||
synchronized(lock) {
|
||||
if (cancelled) {
|
||||
child.destroy()
|
||||
return CANCELLED
|
||||
}
|
||||
process = child
|
||||
}
|
||||
child.inputStream.bufferedReader().useLines { lines ->
|
||||
lines.forEach { line ->
|
||||
Log.i(TAG, line)
|
||||
val progress = parse(line)
|
||||
if (progress != null) Onboarding.report(Onboarding.Step.STEAM, label(progress.second), from + progress.first * (to - from) / 100)
|
||||
}
|
||||
}
|
||||
val status = child.waitFor()
|
||||
return if (status == 0) null else "droiddeck-steam-install exited $status"
|
||||
}
|
||||
}
|
||||
@@ -330,7 +330,7 @@ public final class GogDownloadManager {
|
||||
rc = GuestCommand.INSTANCE.run(ctx, Arrays.asList(
|
||||
"/usr/local/bin/droiddeck-innoextract", "--gog", "--silent",
|
||||
"-d", guestDir, guestSetup),
|
||||
false, "gog-innoextract", null, null, false, cancelled, null,
|
||||
false, "gog-innoextract", null, null, false, cancelled,
|
||||
line -> { cb.onLog("gog innoextract: " + line); return kotlin.Unit.INSTANCE; });
|
||||
} catch (Exception e) {
|
||||
throw new InstallException("The installer could not be extracted: " + e.getClass().getSimpleName());
|
||||
|
||||
@@ -103,9 +103,7 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
|
||||
XboxContent.complete(app, item, folder)
|
||||
return folder.path
|
||||
}
|
||||
val exe = runCatching { executable(folder) }.onFailure {
|
||||
StoresState.logLine("Xbox: install folder holds ${folder.list().orEmpty().sorted().take(MAX_ERROR_LINES).joinToString()}")
|
||||
}.getOrThrow()
|
||||
val exe = executable(folder)
|
||||
StoreInstalls.complete(app, folder, StoreGameSidecar(Store.XBOX, item.id, item.title, exe,
|
||||
installVersion = XboxManifest.read(folder).version, installedAt = System.currentTimeMillis(), cover = item.tallImageUrl, hero = item.imageUrl,
|
||||
extra = item.extra + mapOf("contentId" to selected, "market" to market)))
|
||||
|
||||
@@ -21,9 +21,8 @@ internal object XboxManifest {
|
||||
val files = folder.listFiles().orEmpty()
|
||||
val config = files.filter { it.name.equals(GAME_CONFIG, true) && it.isFile }
|
||||
val legacy = files.filter { it.name.equals(APPX_MANIFEST, true) && it.isFile }
|
||||
val manifests = config.ifEmpty { legacy }
|
||||
require(manifests.size == 1) { "Missing or ambiguous game manifest." }
|
||||
val manifest = manifests.single()
|
||||
require(config.size + legacy.size == 1) { "Missing or ambiguous game manifest." }
|
||||
val manifest = (config + legacy).single()
|
||||
val rootTag = if (config.isEmpty()) "Package" else "Game"
|
||||
require(manifest.length() <= 1_048_576)
|
||||
val parser = android.util.Xml.newPullParser().apply { setFeature(XmlPullParser.FEATURE_PROCESS_DOCDECL, false) }
|
||||
|
||||
@@ -1,239 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import com.droiddeck.launcher.R
|
||||
import android.text.Editable
|
||||
import android.text.InputType
|
||||
import android.text.TextWatcher
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import android.widget.EditText
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
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.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.TextRange
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.ImeOptions
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.TextFieldValue
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import kotlin.math.min
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
@Composable
|
||||
internal fun AdbTextField(
|
||||
value: String,
|
||||
onValueChange: (String) -> Unit,
|
||||
label: String,
|
||||
keyboardType: KeyboardType,
|
||||
imeAction: ImeAction,
|
||||
modifier: Modifier = Modifier,
|
||||
placeholder: String? = null,
|
||||
compact: Boolean = false,
|
||||
onFocusChange: (Boolean) -> Unit = {},
|
||||
clearFocus: Boolean = false,
|
||||
onNext: (() -> Unit)? = null,
|
||||
onDone: (() -> Unit)? = null,
|
||||
focusOnShow: Boolean = false,
|
||||
showLabel: Boolean = true,
|
||||
focusAtTap: Int? = null,
|
||||
onBack: (() -> Unit)? = null,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val onBackLatest = rememberUpdatedState(onBack)
|
||||
val focusAsked = remember { booleanArrayOf(false) }
|
||||
val focusTapAsked = remember { arrayOfNulls<Int>(1) }
|
||||
val palette = LocalPalette.current
|
||||
val onValueChangeLatest = rememberUpdatedState(onValueChange)
|
||||
val onNextLatest = rememberUpdatedState(onNext)
|
||||
val onDoneLatest = rememberUpdatedState(onDone)
|
||||
val onFocusChangeLatest = rememberUpdatedState(onFocusChange)
|
||||
var focused by remember { mutableStateOf(false) }
|
||||
val shape = RoundedCornerShape(8.dp)
|
||||
val inputHeight = if (compact) 44.dp else 52.dp
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val bottomTyping = LocalBottomTyping.current
|
||||
val bottomTypingLatest = rememberUpdatedState(bottomTyping)
|
||||
val typingRequest = remember { arrayOfNulls<TypingRequest>(1) }
|
||||
|
||||
fun typeOnBottom(editText: EditText): Boolean {
|
||||
if (!bottomTypingLatest.value || !DualScreenPanel.attached) return false
|
||||
val text = editText.text.toString()
|
||||
lateinit var request: TypingRequest
|
||||
request = TypingRequest(
|
||||
TextFieldValue(text, TextRange(editText.selectionStart.coerceIn(0, text.length), editText.selectionEnd.coerceIn(0, text.length))),
|
||||
ImeOptions(singleLine = true, keyboardType = keyboardType, imeAction = imeAction),
|
||||
{ next ->
|
||||
if (editText.text.toString() != next.text) editText.setText(next.text)
|
||||
editText.setSelection(next.selection.start.coerceIn(0, next.text.length), next.selection.end.coerceIn(0, next.text.length))
|
||||
},
|
||||
{ action -> editText.onEditorAction(imeActionFlag(action)) },
|
||||
{ editText.post { if (typingRequest[0] === request) onBackLatest.value?.invoke() ?: editText.clearFocus() } },
|
||||
)
|
||||
typingRequest[0] = request
|
||||
DualScreenPanel.startTyping(request)
|
||||
return true
|
||||
}
|
||||
|
||||
DisposableEffect(Unit) {
|
||||
onDispose { typingRequest[0]?.let { DualScreenPanel.stopTyping(it) } }
|
||||
}
|
||||
|
||||
Column(modifier = modifier.fillMaxWidth()) {
|
||||
if (showLabel) Text(
|
||||
label,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = colors.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
)
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(inputHeight)
|
||||
.background(colors.surfaceVariant, shape)
|
||||
.glideBorder(focused, shape, palette.signal, palette.line2)
|
||||
.padding(horizontal = 10.dp),
|
||||
contentAlignment = Alignment.CenterStart,
|
||||
) {
|
||||
AndroidView(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
factory = { viewContext ->
|
||||
EditText(viewContext).apply {
|
||||
isSingleLine = true
|
||||
setHorizontallyScrolling(true)
|
||||
background = null
|
||||
setPadding((2 * context.resources.displayMetrics.density).roundToInt(), 0, 0, 0)
|
||||
setTextSize(android.util.TypedValue.COMPLEX_UNIT_SP, if (compact) 13f else 14f)
|
||||
setTextColor(colors.onBackground.toArgb())
|
||||
setHintTextColor(colors.onSurfaceVariant.toArgb())
|
||||
contentDescription = label
|
||||
inputType = if (keyboardType == KeyboardType.Number) {
|
||||
InputType.TYPE_CLASS_NUMBER
|
||||
} else {
|
||||
InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
|
||||
}
|
||||
imeOptions = imeActionFlag(imeAction) or EditorInfo.IME_FLAG_NO_FULLSCREEN or EditorInfo.IME_FLAG_NO_EXTRACT_UI
|
||||
hint = placeholder
|
||||
setOnEditorActionListener { _, actionId, event ->
|
||||
val isEnter = event?.keyCode == android.view.KeyEvent.KEYCODE_ENTER
|
||||
when {
|
||||
imeAction == ImeAction.Next && (actionId == EditorInfo.IME_ACTION_NEXT || isEnter) -> {
|
||||
onNextLatest.value?.invoke()
|
||||
true
|
||||
}
|
||||
imeAction == ImeAction.Done && (actionId == EditorInfo.IME_ACTION_DONE || isEnter) -> {
|
||||
onDoneLatest.value?.invoke()
|
||||
true
|
||||
}
|
||||
// Search and Go are terminal: leaving them unhandled
|
||||
// keeps focus in the field, so the keyboard would stay
|
||||
// up over the results it was used to find.
|
||||
imeAction in setOf(ImeAction.Search, ImeAction.Go) &&
|
||||
(actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_GO || isEnter) -> {
|
||||
onDoneLatest.value?.invoke()
|
||||
post {
|
||||
clearFocus()
|
||||
(context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE)
|
||||
as? android.view.inputmethod.InputMethodManager)
|
||||
?.hideSoftInputFromWindow(windowToken, 0)
|
||||
}
|
||||
true
|
||||
}
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
showSoftInputOnFocus = !bottomTyping
|
||||
// B on a controller puts the keyboard away first; with no keyboard up it goes back as usual.
|
||||
var hidingKeyboard = false
|
||||
setOnKeyListener { view, keyCode, event ->
|
||||
if (keyCode != android.view.KeyEvent.KEYCODE_BUTTON_B) return@setOnKeyListener false
|
||||
if (event.action == android.view.KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||
hidingKeyboard = androidx.core.view.ViewCompat.getRootWindowInsets(view)
|
||||
?.isVisible(androidx.core.view.WindowInsetsCompat.Type.ime()) == true
|
||||
if (hidingKeyboard) (view.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager)
|
||||
?.hideSoftInputFromWindow(view.windowToken, 0)
|
||||
onBackLatest.value?.let { hidingKeyboard = true; it() }
|
||||
}
|
||||
hidingKeyboard
|
||||
}
|
||||
setOnClickListener { if (hasFocus() && !typeOnBottom(this) && bottomTypingLatest.value) showKeyboardHere(this) }
|
||||
setOnFocusChangeListener { _, hasFocus ->
|
||||
focused = hasFocus
|
||||
if (hasFocus) { if (!typeOnBottom(this) && bottomTypingLatest.value) showKeyboardHere(this) }
|
||||
else typingRequest[0]?.let { DualScreenPanel.stopTyping(it) }
|
||||
onFocusChangeLatest.value(hasFocus)
|
||||
}
|
||||
addTextChangedListener(object : TextWatcher {
|
||||
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
|
||||
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit
|
||||
override fun afterTextChanged(s: Editable?) {
|
||||
onValueChangeLatest.value(s?.toString().orEmpty())
|
||||
}
|
||||
})
|
||||
}
|
||||
},
|
||||
update = { editText ->
|
||||
editText.showSoftInputOnFocus = !bottomTyping
|
||||
// A new tap may ask again: a field still on screen while it closes can be opened once more.
|
||||
val fresh = if (focusAtTap != null) focusTapAsked[0] != focusAtTap else !focusAsked[0]
|
||||
if (focusOnShow && fresh) {
|
||||
if (focusAtTap != null) focusTapAsked[0] = focusAtTap else focusAsked[0] = true
|
||||
editText.post {
|
||||
if (focusAtTap != null && focusAtTap != ScreenTaps.count) return@post
|
||||
editText.requestFocus()
|
||||
if (!bottomTypingLatest.value) (editText.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager)
|
||||
?.showSoftInput(editText, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT)
|
||||
}
|
||||
}
|
||||
if (clearFocus && editText.hasFocus()) {
|
||||
editText.clearFocus()
|
||||
(editText.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager)
|
||||
?.hideSoftInputFromWindow(editText.windowToken, 0)
|
||||
}
|
||||
editText.setTextColor(colors.onBackground.toArgb())
|
||||
editText.setHintTextColor(colors.onSurfaceVariant.toArgb())
|
||||
editText.hint = placeholder
|
||||
editText.contentDescription = label
|
||||
if (editText.text.toString() != value) {
|
||||
val cursor = if (editText.hasFocus()) editText.selectionStart.coerceAtLeast(0) else value.length
|
||||
editText.setText(value)
|
||||
editText.setSelection(min(cursor, value.length))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private fun showKeyboardHere(editText: EditText) {
|
||||
(editText.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager)
|
||||
?.showSoftInput(editText, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT)
|
||||
}
|
||||
|
||||
private fun imeActionFlag(action: ImeAction): Int = when (action) {
|
||||
ImeAction.Next -> EditorInfo.IME_ACTION_NEXT
|
||||
ImeAction.Done -> EditorInfo.IME_ACTION_DONE
|
||||
ImeAction.Go -> EditorInfo.IME_ACTION_GO
|
||||
ImeAction.Search -> EditorInfo.IME_ACTION_SEARCH
|
||||
else -> EditorInfo.IME_ACTION_UNSPECIFIED
|
||||
}
|
||||
@@ -360,7 +360,7 @@ internal fun AppDialog(
|
||||
.then(if (scrollable) Modifier.verticalScroll(scrollState) else Modifier)
|
||||
.padding(horizontal = 18.dp, vertical = 16.dp),
|
||||
) {
|
||||
androidx.compose.runtime.CompositionLocalProvider(LocalRevealChecked provides true) { content() }
|
||||
content()
|
||||
if (side != null && !beside) side()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.lazy.grid.GridCells
|
||||
import androidx.compose.foundation.lazy.grid.GridItemSpan
|
||||
import androidx.compose.foundation.lazy.grid.LazyGridState
|
||||
@@ -27,7 +28,6 @@ import androidx.compose.material3.Text
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
@@ -37,7 +37,6 @@ import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.withFrameNanos
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.snapshotFlow
|
||||
import androidx.compose.ui.Alignment
|
||||
@@ -54,7 +53,6 @@ import androidx.compose.ui.input.InputMode
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalInputModeManager
|
||||
import androidx.compose.ui.platform.LocalLifecycleOwner
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
@@ -62,28 +60,16 @@ import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import coil.compose.AsyncImage
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.frontend.AddedGames
|
||||
import com.droiddeck.launcher.runtime.CurseForgeApp
|
||||
import com.droiddeck.launcher.runtime.UserApps
|
||||
import com.droiddeck.launcher.runtime.WowAddonCatalog
|
||||
import com.droiddeck.launcher.runtime.WowAddons
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
private class AddonResults {
|
||||
val items = mutableStateListOf<WowAddonCatalog.Addon>()
|
||||
@@ -93,178 +79,12 @@ private class AddonResults {
|
||||
var more by mutableStateOf(false)
|
||||
}
|
||||
|
||||
internal enum class AddonStatus { INSTALL, UPDATE, INSTALLED }
|
||||
|
||||
private enum class AddonSource { WOWI, CURSE }
|
||||
|
||||
internal class CurseState(val notice: Int? = null) : Exception()
|
||||
|
||||
internal class CurseLink(val app: UserApps.App) {
|
||||
class Linked(val inspector: String, val guid: String)
|
||||
|
||||
private val lock = Object()
|
||||
private val work = SupervisorJob()
|
||||
@Volatile private var closed = false
|
||||
@Volatile private var hold: AtomicBoolean? = null
|
||||
@Volatile private var inspector: String? = null
|
||||
private val guids = HashMap<String, String>()
|
||||
private val scanLock = Object()
|
||||
private val scans = HashMap<String, Pair<Any, List<CurseForgeApp.Project>>>()
|
||||
private val settleLock = Object()
|
||||
private val settled = HashMap<String, Pair<Int, List<CurseForgeApp.Project>>>()
|
||||
private val turns = HashMap<String, Int>()
|
||||
var generation by mutableIntStateOf(0)
|
||||
private set
|
||||
|
||||
fun refresh() {
|
||||
generation++
|
||||
}
|
||||
|
||||
fun installed(context: Context, target: WowAddons.Target, key: Any): List<CurseForgeApp.Project> = CurseForgeApp.onDisk(
|
||||
synchronized(scanLock) {
|
||||
scans[target.addOns.path]?.takeIf { it.first == key }?.second
|
||||
?: (settledFor(target) ?: call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid, rescan = true) }).also {
|
||||
scans[target.addOns.path] = key to it
|
||||
report(target, it)
|
||||
}
|
||||
},
|
||||
target.addOns,
|
||||
)
|
||||
|
||||
fun marks(context: Context, target: WowAddons.Target, key: Any): Map<String, String?> =
|
||||
runCatching { installed(context, target, key).associate { it.id to curseMark(it) } }.getOrElse { lastReported(target) }
|
||||
|
||||
private fun settledFor(target: WowAddons.Target): List<CurseForgeApp.Project>? = synchronized(settleLock) {
|
||||
settled.remove(target.addOns.path)?.takeIf { it.first == generation }?.second
|
||||
}
|
||||
|
||||
fun change(context: Context, target: WowAddons.Target, launch: Boolean = true, block: (Linked) -> List<CurseForgeApp.Project>?): Boolean {
|
||||
val path = target.addOns.path
|
||||
val turn = synchronized(settleLock) {
|
||||
settled.remove(path)
|
||||
((turns[path] ?: 0) + 1).also { turns[path] = it }
|
||||
}
|
||||
val projects = call(context, target, launch, block) ?: return false
|
||||
synchronized(settleLock) {
|
||||
if (turns[path] == turn) {
|
||||
settled[path] = generation to projects
|
||||
report(target, projects)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
fun <T> call(context: Context, target: WowAddons.Target, launch: Boolean = true, block: (Linked) -> T): T {
|
||||
val linked = synchronized(lock) { link(context, target, launch) }
|
||||
try {
|
||||
return block(linked)
|
||||
} catch (e: CurseForgeApp.Failure) {
|
||||
if (e.gone) synchronized(lock) {
|
||||
if (inspector == linked.inspector) {
|
||||
inspector = null
|
||||
guids.clear()
|
||||
current.compareAndSet(this, null)
|
||||
}
|
||||
}
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
private fun link(context: Context, target: WowAddons.Target, launch: Boolean): Linked {
|
||||
if (closed) throw CurseState()
|
||||
val url = inspector ?: run {
|
||||
if (!launch) throw CurseState()
|
||||
val hold = AtomicBoolean(false)
|
||||
this.hold = hold
|
||||
if (closed) throw CurseState()
|
||||
val done = CurseForgeApp.start(context, app, hold)
|
||||
when (done.state) {
|
||||
CurseForgeApp.Start.READY -> {
|
||||
inspector = done.inspector
|
||||
if (!closed) current.set(this)
|
||||
done.inspector ?: throw CurseState()
|
||||
}
|
||||
CurseForgeApp.Start.BUSY -> throw CurseState(R.string.addons_curse_busy)
|
||||
else -> throw CurseState()
|
||||
}
|
||||
}
|
||||
if (closed) throw CurseState()
|
||||
guids[target.addOns.path]?.let { return Linked(url, it) }
|
||||
val root = WowAddons.root(target)?.let { AddedGames.guestPath(context, it) } ?: throw CurseState()
|
||||
val flavor = WowAddons.flavorDir(target)?.let { AddedGames.guestPath(context, it) } ?: throw CurseState()
|
||||
val guid = CurseForgeApp.instance(context, url, root, flavor)
|
||||
guids[target.addOns.path] = guid
|
||||
return Linked(url, guid)
|
||||
}
|
||||
|
||||
fun uninstall(context: Context, target: WowAddons.Target, folder: String): Boolean = change(context, target, launch = false) { linked ->
|
||||
val projects = CurseForgeApp.onDisk(CurseForgeApp.projects(context, linked.inspector, linked.guid), target.addOns)
|
||||
CurseForgeApp.owner(projects, folder)?.let { CurseForgeApp.uninstall(context, linked.inspector, linked.guid, it) ?: throw CurseState() }
|
||||
}
|
||||
|
||||
internal val stopped: Job get() = work
|
||||
|
||||
fun close(context: Context): Job {
|
||||
closed = true
|
||||
current.compareAndSet(this, null)
|
||||
val launch = hold
|
||||
return CoroutineScope(work + Dispatchers.IO).launch {
|
||||
if (launch != null) CurseForgeApp.stop(context, app, inspector, launch)
|
||||
synchronized(lock) {
|
||||
hold = null
|
||||
inspector = null
|
||||
}
|
||||
}.also { work.complete() }
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val current = AtomicReference<CurseLink?>()
|
||||
private val reported = ConcurrentHashMap<String, List<CurseForgeApp.Project>>()
|
||||
|
||||
fun lastReported(target: WowAddons.Target, disk: () -> List<WowAddons.Installed> = { WowAddons.details(target) }): Map<String, String?> {
|
||||
val last = reported[target.addOns.path] ?: return disk().mapNotNull { it.curseId }.associateWith { null }
|
||||
return CurseForgeApp.onDisk(last, target.addOns).associate { it.id to null }
|
||||
}
|
||||
|
||||
internal fun report(target: WowAddons.Target, projects: List<CurseForgeApp.Project>) {
|
||||
reported[target.addOns.path] = projects
|
||||
}
|
||||
|
||||
fun live(): CurseLink? = current.get()
|
||||
}
|
||||
}
|
||||
private enum class AddonStatus { INSTALL, UPDATE, INSTALLED }
|
||||
|
||||
private const val PAGES_AHEAD = 8
|
||||
private const val CURSE_UPDATE = "update"
|
||||
private const val UNINSTALLING = -1
|
||||
|
||||
private fun curseMark(project: CurseForgeApp.Project): String? = CURSE_UPDATE.takeIf { project.update }
|
||||
|
||||
private class Present(val curse: Map<String, String?> = emptyMap(), val disk: Map<String, WowAddons.Installed> = emptyMap())
|
||||
|
||||
@Composable
|
||||
internal fun rememberCurseLink(app: UserApps.App?, sessionRunning: Boolean): CurseLink? {
|
||||
val context = LocalContext.current.applicationContext
|
||||
val owner = LocalLifecycleOwner.current
|
||||
var visible by remember(owner) { mutableStateOf(owner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) }
|
||||
DisposableEffect(owner) {
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_START) visible = true
|
||||
if (event == Lifecycle.Event.ON_STOP) visible = false
|
||||
}
|
||||
owner.lifecycle.addObserver(observer)
|
||||
onDispose { owner.lifecycle.removeObserver(observer) }
|
||||
}
|
||||
val active = visible && !sessionRunning
|
||||
val link = remember(app?.key, active) { app?.takeIf { active }?.let(::CurseLink) }
|
||||
DisposableEffect(link) {
|
||||
onDispose { link?.close(context) }
|
||||
}
|
||||
return link
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAddons.Target, curseForge: UserApps.App?, link: CurseLink?, onDismiss: () -> Unit) {
|
||||
internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAddons.Target, onDismiss: () -> Unit) {
|
||||
val context = LocalContext.current.applicationContext
|
||||
val scope = rememberCoroutineScope()
|
||||
val shown = rememberShown(onDismiss)
|
||||
@@ -273,33 +93,20 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
||||
var text by remember { mutableStateOf("") }
|
||||
var category by remember { mutableStateOf<WowAddonCatalog.Category?>(null) }
|
||||
var sort by remember { mutableStateOf(WowAddonCatalog.Sort.POPULAR) }
|
||||
var source by remember { mutableStateOf(AddonSource.WOWI) }
|
||||
val curse = if (source == AddonSource.CURSE && link != null) curseForge else null
|
||||
LaunchedEffect(link) { link?.refresh() }
|
||||
var notice by remember { mutableStateOf<Int?>(null) }
|
||||
var curseInstalls by remember { mutableIntStateOf(0) }
|
||||
val results = remember(text, category, sort, target, curse) { AddonResults() }
|
||||
val results = remember(text, category, sort, target) { AddonResults() }
|
||||
val installing = remember { mutableStateMapOf<String, Int>() }
|
||||
val installed = remember { mutableStateMapOf<String, Pair<String, String>>() }
|
||||
val categories by produceState(emptyList<WowAddonCatalog.Category>()) {
|
||||
value = withContext(Dispatchers.IO) { runCatching { WowAddonCatalog.categories(context) }.getOrDefault(emptyList()) }
|
||||
}
|
||||
val presentKey = curse to target.addOns
|
||||
val scanKey = link?.generation to WowAddons.imports
|
||||
val snapshot by produceState(presentKey to Present(), target.addOns, scanKey, curse, curseInstalls, curse == null && results.items.isEmpty()) {
|
||||
val into = target
|
||||
val key = curse to into.addOns
|
||||
if (curse != null && link != null && value.first != key) value = key to withContext(Dispatchers.IO) { Present(curse = CurseLink.lastReported(into)) }
|
||||
value = key to withContext(Dispatchers.IO) {
|
||||
if (curse != null && link != null) Present(curse = link.marks(context, into, scanKey))
|
||||
else Present(disk = WowAddons.details(into).associateBy { it.name.lowercase() })
|
||||
}
|
||||
val present by produceState(emptyMap<String, String?>(), target.addOns, WowAddons.imports) {
|
||||
value = withContext(Dispatchers.IO) { WowAddons.details(target).mapNotNull { item -> item.wowiId?.let { it to item.version } }.toMap() }
|
||||
}
|
||||
val present = snapshot.second.takeIf { snapshot.first == presentKey } ?: Present()
|
||||
fun status(addon: WowAddonCatalog.Addon): AddonStatus {
|
||||
if (curse != null) return if (addon.id !in present.curse) AddonStatus.INSTALL else if (present.curse[addon.id] == CURSE_UPDATE) AddonStatus.UPDATE else AddonStatus.INSTALLED
|
||||
if (addon.id !in present) return AddonStatus.INSTALL
|
||||
val have = present[addon.id]
|
||||
val latest = installed[installKey(addon, target)]?.takeIf { it.first == addon.summary }?.second ?: addon.summary
|
||||
return diskStatus(addon.folders, present.disk, latest, addon.id)
|
||||
return if (have == null || latest.isBlank() || WowAddonCatalog.sameVersion(have, latest)) AddonStatus.INSTALLED else AddonStatus.UPDATE
|
||||
}
|
||||
fun load(page: Int) {
|
||||
if (results.loading) return
|
||||
@@ -309,16 +116,10 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
||||
val words = text
|
||||
val cat = category?.id
|
||||
val order = sort
|
||||
val via = link?.takeIf { curse != null }
|
||||
notice = null
|
||||
scope.launch {
|
||||
val got = withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
if (via != null) via.call(context, into) { CurseForgeApp.search(context, it.inspector, it.guid, words, order, page) }
|
||||
else WowAddonCatalog.search(context, WowAddonCatalog.Query(words, cat, WowAddonCatalog.client(into), order), page)
|
||||
}
|
||||
runCatching { WowAddonCatalog.search(context, WowAddonCatalog.Query(words, cat, WowAddonCatalog.client(into), order), page) }
|
||||
}
|
||||
if (results.items.isEmpty()) notice = (got.exceptionOrNull() as? CurseState)?.notice
|
||||
got.onSuccess {
|
||||
if (page == 0) results.items.clear()
|
||||
results.items.addAll(it.items.filter { addon -> results.items.none { seen -> seen.id == addon.id } })
|
||||
@@ -335,34 +136,6 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
||||
fun install(addon: WowAddonCatalog.Addon) {
|
||||
val key = installKey(addon, target)
|
||||
if (key in installing) return
|
||||
val via = link?.takeIf { curse != null }
|
||||
if (via != null) {
|
||||
val into = target
|
||||
val updating = status(addon) == AddonStatus.UPDATE
|
||||
installing[key] = 0
|
||||
scope.launch {
|
||||
val done = withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
via.change(context, into) {
|
||||
if (updating) CurseForgeApp.update(context, it.inspector, it.guid, addon.id)
|
||||
else CurseForgeApp.install(context, it.inspector, it.guid, addon.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
installing.remove(key)
|
||||
val ok = done.getOrNull() == true
|
||||
WowAddons.changed()
|
||||
curseInstalls++
|
||||
val message = when {
|
||||
ok && updating -> context.getString(R.string.user_apps_updated, addon.name)
|
||||
ok -> context.resources.getQuantityString(R.plurals.main_addons_imported, 1, 1, into.flavor)
|
||||
else -> (done.exceptionOrNull() as? CurseState)?.notice?.let(context::getString)
|
||||
?: context.getString(R.string.stores_dl_failed_reason, done.exceptionOrNull()?.message ?: addon.name)
|
||||
}
|
||||
Toast.makeText(context, message, Toast.LENGTH_LONG).show()
|
||||
}
|
||||
return
|
||||
}
|
||||
if (SessionState.running) {
|
||||
Toast.makeText(context, R.string.main_addons_close_session, Toast.LENGTH_LONG).show()
|
||||
return
|
||||
@@ -376,33 +149,7 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
||||
Toast.makeText(context, message.first, Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
fun uninstall(addon: WowAddonCatalog.Addon) {
|
||||
val key = installKey(addon, target)
|
||||
if (key in installing) return
|
||||
if (SessionState.running) {
|
||||
Toast.makeText(context, R.string.main_addons_close_session, Toast.LENGTH_LONG).show()
|
||||
return
|
||||
}
|
||||
val into = target
|
||||
val via = link?.takeIf { curse != null }
|
||||
installing[key] = UNINSTALLING
|
||||
scope.launch {
|
||||
val done = withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
val folders = if (via != null) curseFolders(into, addon.id, via.call(context, into) { linked ->
|
||||
CurseForgeApp.projects(context, linked.inspector, linked.guid).firstOrNull { it.id == addon.id }?.folders.orEmpty()
|
||||
}) else addon.folders
|
||||
deleteAddons(context, into, folders, link)
|
||||
}
|
||||
}
|
||||
installing.remove(key)
|
||||
installed.remove(key)
|
||||
WowAddons.changed()
|
||||
curseInstalls++
|
||||
if (done.isFailure) Toast.makeText(context, R.string.fm_delete_failed, Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
val sourceName = stringResource(if (curse != null) R.string.addons_source_curse else R.string.addons_source_wowi)
|
||||
val sourceName = stringResource(R.string.addons_source_wowi)
|
||||
val grid = rememberLazyGridState()
|
||||
LaunchedEffect(results, grid) {
|
||||
snapshotFlow { grid.layoutInfo.visibleItemsInfo.lastOrNull()?.index to grid.layoutInfo.totalItemsCount }.collect { (last, total) ->
|
||||
@@ -415,7 +162,7 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
||||
LaunchedEffect(results, results.items.isNotEmpty()) {
|
||||
if (results.items.isNotEmpty() && !searching && inputMode.inputMode == InputMode.Keyboard) focusSoon { firstAction }
|
||||
}
|
||||
AppDialog(shown, close, "addonBrowser", wide = true, maxWidth = 980.dp, scrollable = false, fillHeight = true, modifier = Modifier.releaseTextFieldOnTap()) {
|
||||
AppDialog(shown, close, "addonBrowser", wide = true, maxWidth = 980.dp, scrollable = false, fillHeight = true) {
|
||||
val sortChip: @Composable () -> Unit = {
|
||||
BrowseDropdown(sortLabel(sort)) { first, done ->
|
||||
WowAddonCatalog.Sort.entries.forEachIndexed { index, option ->
|
||||
@@ -423,14 +170,8 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
||||
}
|
||||
}
|
||||
}
|
||||
val sourceChip: @Composable () -> Unit = {
|
||||
if (curseForge != null) BrowseDropdown(sourceName) { first, done ->
|
||||
MenuItem(stringResource(R.string.addons_source_wowi), source == AddonSource.WOWI, focusRequester = first) { source = AddonSource.WOWI; done() }
|
||||
MenuItem(stringResource(R.string.addons_source_curse), source == AddonSource.CURSE) { source = AddonSource.CURSE; done() }
|
||||
}
|
||||
}
|
||||
val categoryChip: @Composable () -> Unit = {
|
||||
if (curse == null && categories.isNotEmpty()) BrowseDropdown(category?.name ?: stringResource(R.string.addons_category_all)) { first, done ->
|
||||
if (categories.isNotEmpty()) BrowseDropdown(category?.name ?: stringResource(R.string.addons_category_all)) { first, done ->
|
||||
MenuItem(stringResource(R.string.addons_category_all), category == null, focusRequester = first) { category = null; done() }
|
||||
categories.forEach { option -> MenuItem(option.name, category?.id == option.id) { category = option; done() } }
|
||||
}
|
||||
@@ -454,7 +195,6 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
||||
BoxWithConstraints(Modifier.fillMaxWidth()) {
|
||||
if (maxWidth >= 640.dp) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
search(Modifier.weight(1f))
|
||||
sourceChip()
|
||||
sortChip()
|
||||
categoryChip()
|
||||
flavorChip()
|
||||
@@ -468,7 +208,6 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
modifier = Modifier.horizontalScroll(rememberScrollState()),
|
||||
) {
|
||||
sourceChip()
|
||||
sortChip()
|
||||
categoryChip()
|
||||
flavorChip()
|
||||
@@ -483,16 +222,12 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
||||
) {
|
||||
items(results.items, key = { it.id }) { addon ->
|
||||
val key = installKey(addon, target)
|
||||
AddonRow(addon, status(addon), installing[key], if (addon.id == results.items.firstOrNull()?.id) Modifier.focusRequester(firstAction) else Modifier, { uninstall(addon) }) { install(addon) }
|
||||
AddonRow(addon, status(addon), installing[key], if (addon.id == results.items.firstOrNull()?.id) Modifier.focusRequester(firstAction) else Modifier) { install(addon) }
|
||||
}
|
||||
item(span = { GridItemSpan(maxLineSpan) }) {
|
||||
Column(Modifier.fillMaxWidth().padding(vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
when {
|
||||
results.loading -> LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||
results.failed != null && notice != null -> {
|
||||
Text(stringResource(notice!!), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
BrowseChip(stringResource(R.string.stores_dl_retry), false) { load(0) }
|
||||
}
|
||||
results.failed != null -> {
|
||||
Text(stringResource(R.string.addons_unreachable, sourceName), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
BrowseChip(stringResource(R.string.stores_dl_retry), false) { load(if (results.items.isEmpty()) 0 else results.page + 1) }
|
||||
@@ -506,22 +241,7 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progress: Int?, action: Modifier, onUninstall: () -> Unit, onInstall: () -> Unit) {
|
||||
var asking by remember(addon.id) { mutableStateOf(false) }
|
||||
val first = remember(addon.id) { FocusRequester() }
|
||||
var refocus by remember(addon.id) { mutableStateOf(false) }
|
||||
val inputMode = LocalInputModeManager.current
|
||||
LaunchedEffect(status, progress) {
|
||||
if (!refocus) return@LaunchedEffect
|
||||
withFrameNanos { }
|
||||
runCatching { first.requestFocus() }
|
||||
if (progress == null) refocus = false
|
||||
}
|
||||
fun act(block: () -> Unit) {
|
||||
refocus = inputMode.inputMode == InputMode.Keyboard
|
||||
block()
|
||||
}
|
||||
val lead = action.focusRequester(first)
|
||||
private fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progress: Int?, action: Modifier, onInstall: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Row(
|
||||
@@ -539,24 +259,13 @@ internal fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progres
|
||||
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
val uninstall = stringResource(R.string.common_uninstall)
|
||||
val size = Modifier.widthIn(min = 104.dp).then(action)
|
||||
when {
|
||||
progress == UNINSTALLING -> SecondaryButton(stringResource(R.string.stores_uninstalling), compact = true, modifier = lead) {}
|
||||
progress != null -> SecondaryButton(stringResource(R.string.store_installing), compact = true, modifier = lead, progress = progress / 100f, onClick = onInstall)
|
||||
status == AddonStatus.INSTALL -> PrimaryButton(stringResource(R.string.store_install), compact = true, modifier = lead) { act(onInstall) }
|
||||
else -> {
|
||||
if (status == AddonStatus.UPDATE) PrimaryButton(stringResource(R.string.common_update), compact = true, modifier = lead) { act(onInstall) }
|
||||
SecondaryButton(uninstall, compact = true, modifier = if (status == AddonStatus.UPDATE) Modifier else lead) { asking = true }
|
||||
}
|
||||
progress != null -> SecondaryButton(stringResource(R.string.store_installing), compact = true, modifier = size, progress = progress / 100f, onClick = onInstall)
|
||||
status == AddonStatus.INSTALLED -> SecondaryButton(stringResource(R.string.stores_installed_chip), enabled = false, compact = true, modifier = size) {}
|
||||
else -> PrimaryButton(stringResource(if (status == AddonStatus.UPDATE) R.string.common_update else R.string.store_install), compact = true, modifier = size, onClick = onInstall)
|
||||
}
|
||||
}
|
||||
if (asking) ConfirmDialog(
|
||||
title = stringResource(R.string.stores_uninstall_title, addon.name),
|
||||
text = stringResource(R.string.games_delete_addon_body),
|
||||
confirm = stringResource(R.string.common_uninstall),
|
||||
onConfirm = { asking = false; act(onUninstall) },
|
||||
onDismiss = { asking = false },
|
||||
)
|
||||
}
|
||||
|
||||
private fun Modifier.scrollThumb(state: LazyGridState, color: Color): Modifier = drawWithContent {
|
||||
@@ -605,25 +314,4 @@ internal fun installAddon(context: Context, addon: WowAddonCatalog.Addon, target
|
||||
}
|
||||
}
|
||||
|
||||
internal fun diskStatus(folders: List<String>, onDisk: Map<String, WowAddons.Installed>, latest: String, id: String): AddonStatus {
|
||||
if (!WowAddons.present(folders) { it.lowercase() in onDisk }) return AddonStatus.INSTALL
|
||||
val have = onDisk.getValue(folders.first().lowercase())
|
||||
return if (WowAddonCatalog.offersUpdate(have.version, latest, sameSource = have.wowiId == id)) AddonStatus.UPDATE else AddonStatus.INSTALLED
|
||||
}
|
||||
|
||||
internal fun curseFolders(target: WowAddons.Target, id: String, listed: List<String>): List<String> =
|
||||
listed.ifEmpty { WowAddons.details(target).filter { it.curseId == id }.map { it.name } }
|
||||
|
||||
internal fun deleteAddons(context: Context, target: WowAddons.Target, folders: List<String>, link: CurseLink?) {
|
||||
val found = folders.mapNotNull { WowAddons.folder(target.addOns, it) }
|
||||
if (found.isEmpty()) throw IOException("No addon folder to delete")
|
||||
found.forEach { deleteAddon(context, target, it.name, link) }
|
||||
}
|
||||
|
||||
internal fun deleteAddon(context: Context, target: WowAddons.Target, folder: String, link: CurseLink? = CurseLink.live()) {
|
||||
val managed = link?.let { runCatching { it.uninstall(context, target, folder) }.getOrDefault(false) } == true
|
||||
val left = WowAddons.folder(target.addOns, folder)
|
||||
if (managed || left == null) WowAddons.changed() else WowAddons.delete(target, left.name)
|
||||
}
|
||||
|
||||
private fun installKey(addon: WowAddonCatalog.Addon, target: WowAddons.Target) = addon.id + "|" + target.addOns.path
|
||||
@@ -2,7 +2,6 @@ package com.droiddeck.launcher.ui
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.ContextWrapper
|
||||
import android.os.Build
|
||||
import android.view.KeyEvent
|
||||
import android.view.WindowManager
|
||||
import androidx.activity.compose.LocalActivityResultRegistryOwner
|
||||
@@ -11,7 +10,6 @@ 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.AnimatedVisibility
|
||||
import androidx.compose.animation.expandHorizontally
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.shrinkVertically
|
||||
@@ -186,11 +184,7 @@ private fun AgentPageContent(
|
||||
?: generateSequence(view.context) { (it as? ContextWrapper)?.baseContext }
|
||||
.filterIsInstance<Activity>().firstOrNull()?.window
|
||||
val previousMode = window?.attributes?.softInputMode
|
||||
// A window fitted to the system bars with ADJUST_NOTHING reports no keyboard height to Compose.
|
||||
// It stays unfitted after the page leaves: fitting it again insets the other pages twice.
|
||||
val edgeToEdge = visible && hidesPet && !drawer && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R
|
||||
if (visible) window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING)
|
||||
if (edgeToEdge) window?.setDecorFitsSystemWindows(false)
|
||||
onDispose {
|
||||
if (visible && previousMode != null) window?.setSoftInputMode(previousMode)
|
||||
}
|
||||
@@ -229,14 +223,8 @@ private fun AgentPageContent(
|
||||
}
|
||||
val topBar: @Composable () -> Unit = { AgentTopBar(panel, togglePanel, inputModifier, menu) }
|
||||
val inlineControls: (@Composable () -> Unit)? = if (inline) ({
|
||||
// The open menu needs the row's width for its own buttons.
|
||||
androidx.compose.animation.AnimatedVisibility(!menuOpen, enter = expandHorizontally(expandFrom = Alignment.Start) + fadeIn(),
|
||||
exit = shrinkHorizontally(shrinkTowards = Alignment.Start) + fadeOut()) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
ModelChip(panel, togglePanel, inputModifier, compact = true)
|
||||
ContextRing("agent-usage", onClick = { togglePanel(AgentPanel.USAGE) })
|
||||
}
|
||||
}
|
||||
ModelChip(panel, togglePanel, inputModifier, compact = true)
|
||||
ContextRing("agent-usage", onClick = { togglePanel(AgentPanel.USAGE) })
|
||||
menu()
|
||||
}) else null
|
||||
// A host with a title bar shows the top bar there.
|
||||
@@ -252,11 +240,8 @@ private fun AgentPageContent(
|
||||
LaunchedEffect(AgentHost.approvals.size, panel) {
|
||||
if (AgentHost.approvals.isNotEmpty() && (panel == AgentPanel.HISTORY || panel == AgentPanel.PROCESSES || panel == AgentPanel.TOOLS)) panel = AgentPanel.NONE
|
||||
}
|
||||
androidx.compose.foundation.layout.BoxWithConstraints(modifier.fillMaxSize()) {
|
||||
// On a short page the picker would take it all and leave no conversation, so it scrolls within a share of the page.
|
||||
val panelMax = maxHeight * 0.5f
|
||||
Column(
|
||||
Modifier.fillMaxSize().imePadding().onPreviewKeyEvent { e ->
|
||||
modifier.fillMaxSize().imePadding().onPreviewKeyEvent { e ->
|
||||
val k = e.nativeKeyEvent
|
||||
if (k.keyCode != KeyEvent.KEYCODE_BUTTON_Y || composer.focused) return@onPreviewKeyEvent false
|
||||
if (k.action == KeyEvent.ACTION_UP) composer.open()
|
||||
@@ -279,8 +264,8 @@ private fun AgentPageContent(
|
||||
else -> {
|
||||
if (menuSlot == null && !inline) Box(Modifier.padding(bottom = 6.dp)) { topBar() }
|
||||
when (panel) {
|
||||
AgentPanel.MODEL -> Box(Modifier.heightIn(max = panelMax).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) { AgentModelPicker() }
|
||||
AgentPanel.USAGE -> Box(Modifier.heightIn(max = panelMax).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) { AgentUsage() }
|
||||
AgentPanel.MODEL -> Box(Modifier.padding(bottom = 8.dp)) { AgentModelPicker() }
|
||||
AgentPanel.USAGE -> Box(Modifier.padding(bottom = 8.dp)) { AgentUsage() }
|
||||
else -> Unit
|
||||
}
|
||||
val list = rememberLazyListState()
|
||||
@@ -332,12 +317,11 @@ private fun AgentPageContent(
|
||||
}
|
||||
}
|
||||
androidx.compose.animation.AnimatedVisibility(!hidden, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) {
|
||||
AgentComposer(composer, draft, visible && started, inlineControls, onPanel = { panel = it }, onSent = toLatest, hideAttach = inline && menuOpen)
|
||||
AgentComposer(composer, draft, visible && started, inlineControls, onPanel = { panel = it }, onSent = toLatest)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the editor has the cursor; [open] puts it there. */
|
||||
@@ -408,12 +392,10 @@ private fun AgentMenu(open: Boolean, onOpen: (Boolean) -> Unit, onPanel: (AgentP
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val working = AgentHost.state == AgentHost.State.WORKING
|
||||
// Closed, the outline sits flush against the lone button.
|
||||
val shape = if (open) Shape16 else Shape12
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.clip(shape).background(colors.surface.copy(alpha = if (open) 0.97f else 0.88f))
|
||||
.border(1.dp, pal.line, shape).then(if (open) Modifier.padding(top = 3.dp, bottom = 3.dp, end = 4.dp) else Modifier),
|
||||
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()) {
|
||||
@@ -436,7 +418,7 @@ private fun AgentMenu(open: Boolean, onOpen: (Boolean) -> Unit, onPanel: (AgentP
|
||||
}
|
||||
}
|
||||
}
|
||||
HeaderAction(Icons.Outlined.MoreHoriz, stringResource(R.string.agent_more), selected = open, size = 36.dp, tag = "agent-menu", startPadding = if (open) null else 0.dp) { onOpen(!open) }
|
||||
HeaderAction(Icons.Outlined.MoreHoriz, stringResource(R.string.agent_more), selected = open, size = 36.dp, tag = "agent-menu") { onOpen(!open) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -450,13 +432,12 @@ private fun AgentPanelBar(title: String, onClose: () -> Unit) {
|
||||
|
||||
@Composable
|
||||
internal fun HeaderAction(
|
||||
icon: ImageVector, label: String, enabled: Boolean = true, selected: Boolean = false, tag: String? = null, size: Dp = 44.dp,
|
||||
startPadding: Dp? = null, onClick: () -> Unit,
|
||||
icon: ImageVector, label: String, enabled: Boolean = true, selected: Boolean = false, tag: String? = null, size: Dp = 44.dp, onClick: () -> Unit,
|
||||
) {
|
||||
val pal = LocalPalette.current
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.padding(start = startPadding ?: if (size < 44.dp) 4.dp else 8.dp).size(size).clip(Shape12)
|
||||
modifier = Modifier.padding(start = if (size < 44.dp) 4.dp else 8.dp).size(size).clip(Shape12)
|
||||
.background(if (selected) pal.primary.copy(alpha = 0.2f) else pal.surfaceVariant)
|
||||
.clickable(enabled = enabled, onClick = onClick)
|
||||
.then(if (tag != null) Modifier.testTag(tag) else Modifier),
|
||||
@@ -729,7 +710,7 @@ internal fun liveUsed(limit: AgentHost.Limit) = if (limit.resetsAt > 0 && limit.
|
||||
@Composable
|
||||
private fun AgentComposer(
|
||||
composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?,
|
||||
onPanel: (AgentPanel) -> Unit, onSent: () -> Unit, hideAttach: Boolean = false,
|
||||
onPanel: (AgentPanel) -> Unit, onSent: () -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
var draft by draftState
|
||||
@@ -761,13 +742,13 @@ 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, visible, controls, send, hideAttach)
|
||||
AgentEditor(composer, draftState, visible, controls, send)
|
||||
}
|
||||
}
|
||||
|
||||
/** The text with attach, stop and send beside it, and [controls] while the text is not being typed in. */
|
||||
@Composable
|
||||
private fun AgentEditor(composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?, send: () -> Unit, hideAttach: Boolean = false) {
|
||||
private fun AgentEditor(composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?, send: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
@@ -866,14 +847,14 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String
|
||||
if (stacked) Column {
|
||||
text(Modifier.fillMaxWidth())
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
|
||||
AnimatedVisibility(attach && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton() }
|
||||
AnimatedVisibility(AgentAttachments.gameFrame != null && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { GameFrameButton() }
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f).height(42.dp).horizontalScroll(rememberScrollState(), reverseScrolling = true)) { if (controls != null && !focused) controls() }
|
||||
if (attach) AttachButton()
|
||||
if (AgentAttachments.gameFrame != null) GameFrameButton()
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f).height(42.dp)) { if (controls != null && !focused) controls() }
|
||||
actions()
|
||||
}
|
||||
} else Row(verticalAlignment = Alignment.Bottom) {
|
||||
AnimatedVisibility(attach && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton() }
|
||||
AnimatedVisibility(AgentAttachments.gameFrame != null && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { GameFrameButton() }
|
||||
if (attach) AttachButton()
|
||||
if (AgentAttachments.gameFrame != null) GameFrameButton()
|
||||
text(Modifier.weight(1f))
|
||||
if (controls != null && !focused) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.height(42.dp)) { controls() }
|
||||
actions()
|
||||
|
||||
@@ -117,7 +117,7 @@ private fun rememberMovies(refresh: Int, onSelectionChanged: () -> Unit): MovieS
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun TabChip(label: String, selected: Boolean, modifier: Modifier = Modifier, onClick: () -> Unit) {
|
||||
private fun TabChip(label: String, selected: Boolean, modifier: Modifier = Modifier, onClick: () -> Unit) {
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
|
||||
@@ -1629,7 +1629,7 @@ private fun DeviceChip(s: GpuDriversState) {
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.onGloballyPositioned { at = it.boundsInRoot() }.heightIn(min = 44.dp).paneItem("gpu-device").clip(shape)
|
||||
.background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.14f)) else Modifier)
|
||||
.background(if (hot) pal.signal.copy(alpha = 0.14f) else colors.surface)
|
||||
.glideBorder(hot, shape, pal.signal, pal.line)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Button, onClick = open)
|
||||
.controllerConfirm(onClick = open)
|
||||
|
||||
@@ -12,7 +12,6 @@ object ControllerHaptics {
|
||||
private val navKeys = setOf(
|
||||
KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT,
|
||||
KeyEvent.KEYCODE_BUTTON_A, KeyEvent.KEYCODE_BUTTON_L1, KeyEvent.KEYCODE_BUTTON_R1,
|
||||
KeyEvent.KEYCODE_BUTTON_L2, KeyEvent.KEYCODE_BUTTON_R2,
|
||||
)
|
||||
|
||||
fun onKey(context: Context, event: KeyEvent) {
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.graphics.vector.addPathNodes
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
internal val DeckyIcon: ImageVector = ImageVector.Builder("Decky", 24.dp, 24.dp, 24f, 24f).apply {
|
||||
for (d in listOf(
|
||||
"M8,2h2v6H8Z",
|
||||
"M14,2h2v6h-2Z",
|
||||
"M5,8h14v3a7,7 0 0 1 -5,6.7V19h-4v-1.3A7,7 0 0 1 5,11Z",
|
||||
"M11,19h2v3h-2Z",
|
||||
)) addPath(addPathNodes(d), fill = SolidColor(Color.Black))
|
||||
}.build()
|
||||
@@ -1,245 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import coil.compose.AsyncImage
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.size
|
||||
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.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Search
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
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.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.runtime.DeckyManager
|
||||
import com.droiddeck.launcher.runtime.DeckyStore
|
||||
|
||||
private enum class DeckyTab { INSTALLED, STORE, ZIP }
|
||||
|
||||
private const val STORE_PAGE = 30
|
||||
|
||||
internal fun deckyStoreMatches(plugins: List<DeckyStore.Plugin>, query: String): List<DeckyStore.Plugin> {
|
||||
val words = query.trim().lowercase().split(Regex("\\s+")).filter { it.isNotEmpty() }
|
||||
return plugins.filter { p ->
|
||||
val haystack = (p.name + " " + p.author + " " + p.description + " " + p.tags.joinToString(" ")).lowercase()
|
||||
words.all { it in haystack }
|
||||
}.sortedByDescending { it.downloads }
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun DeckyGroups(s: ModeSettings, a: ModeSettingsActions, host: MenuHost) {
|
||||
val idle = s.deckyStage == null && !s.deckySessionRunning
|
||||
SettingsGroup(stringResource(R.string.mode_decky_loader)) {
|
||||
val updateAvailable = s.deckyInstalled != null && s.deckyLatestRelease != null &&
|
||||
s.deckyInstalled != s.deckyLatestRelease.tag
|
||||
val status = when {
|
||||
s.deckyStage != null -> s.deckyStage
|
||||
s.deckyChecking -> stringResource(R.string.mode_decky_checking)
|
||||
s.deckyInstalled == null && s.deckyLatestRelease != null -> stringResource(R.string.mode_decky_ready, s.deckyLatestRelease.tag)
|
||||
s.deckyInstalled == null -> stringResource(R.string.mode_decky_none)
|
||||
s.deckyLatestRelease == null -> stringResource(R.string.mode_decky_installed, s.deckyInstalled)
|
||||
updateAvailable -> stringResource(R.string.mode_decky_update, s.deckyLatestRelease.tag)
|
||||
else -> stringResource(R.string.mode_decky_current, s.deckyInstalled)
|
||||
}
|
||||
SettingsRow(stringResource(R.string.decky_status), status) {
|
||||
val action = when {
|
||||
s.deckyStage != null -> stringResource(R.string.common_working)
|
||||
s.deckyChecking -> stringResource(R.string.common_checking)
|
||||
s.deckyInstalled == null && s.deckyLatestRelease != null -> stringResource(R.string.mode_decky_install_latest)
|
||||
s.deckyInstalled != null && updateAvailable -> stringResource(R.string.common_update)
|
||||
else -> stringResource(R.string.common_check)
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
SecondaryButton(action, enabled = s.deckyStage == null && !s.deckyChecking && !s.deckySessionRunning) {
|
||||
if (s.deckyLatestRelease == null || (s.deckyInstalled != null && !updateAvailable)) a.onDeckyCheck()
|
||||
else s.deckyLatestRelease?.let(a.onDeckyInstall)
|
||||
}
|
||||
if (s.deckyInstalled != null) DeckyUninstall(enabled = idle, onUninstall = a.onDeckyUninstall)
|
||||
}
|
||||
}
|
||||
if (s.deckyInstalled != null) ToggleRow(
|
||||
host, "decky-enabled", stringResource(R.string.decky_enable),
|
||||
null,
|
||||
s.deckyEnabled,
|
||||
enabled = idle,
|
||||
onChange = a.onDeckyEnabled,
|
||||
)
|
||||
ChoiceRow(
|
||||
host, "decky-channel", stringResource(R.string.decky_release_channel),
|
||||
null,
|
||||
listOf(
|
||||
DeckyManager.BRANCH_STABLE to stringResource(R.string.decky_channel_stable),
|
||||
DeckyManager.BRANCH_PRERELEASE to stringResource(R.string.decky_channel_prerelease),
|
||||
) + if (s.deckyBranch == DeckyManager.BRANCH_TESTING) listOf(
|
||||
DeckyManager.BRANCH_TESTING to stringResource(R.string.decky_channel_testing),
|
||||
) else emptyList(),
|
||||
s.deckyBranch,
|
||||
enabled = idle,
|
||||
onPick = a.onDeckyBranch,
|
||||
)
|
||||
if (s.deckyStage != null && s.deckyPercent >= 0) {
|
||||
LinearProgressIndicator(
|
||||
progress = { s.deckyPercent / 100f },
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (s.deckyInstalled == null) return
|
||||
var tab by rememberSaveable { mutableStateOf(DeckyTab.INSTALLED) }
|
||||
SettingsGroup(stringResource(R.string.mode_decky_plugins)) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 10.dp)) {
|
||||
TabChip(stringResource(R.string.decky_tab_installed, s.deckyPlugins.size), tab == DeckyTab.INSTALLED, Modifier.weight(1f)) { tab = DeckyTab.INSTALLED }
|
||||
TabChip(stringResource(R.string.decky_tab_store), tab == DeckyTab.STORE, Modifier.weight(1f)) { tab = DeckyTab.STORE }
|
||||
TabChip(stringResource(R.string.decky_tab_zip), tab == DeckyTab.ZIP, Modifier.weight(1f)) { tab = DeckyTab.ZIP }
|
||||
}
|
||||
LaunchedEffect(tab) { if (tab != DeckyTab.ZIP && s.deckyStore == null && !s.deckyStoreFailed) a.onDeckyStoreRefresh() }
|
||||
when (tab) {
|
||||
DeckyTab.INSTALLED -> InstalledPlugins(s, a, idle)
|
||||
DeckyTab.STORE -> PluginStore(s, a, idle)
|
||||
DeckyTab.ZIP -> SettingsRow(
|
||||
stringResource(R.string.decky_tab_zip),
|
||||
stringResource(R.string.mode_decky_plugins_hint),
|
||||
) {
|
||||
SecondaryButton(
|
||||
if (s.deckyStage != null && s.deckyDownloadingBinary) stringResource(R.string.mode_decky_plugin_downloading) else stringResource(R.string.mode_decky_plugin_install_zip),
|
||||
enabled = idle,
|
||||
modifier = Modifier.testTag("decky-install-zip"),
|
||||
onClick = a.onPickDeckyPluginZip,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InstalledPlugins(s: ModeSettings, a: ModeSettingsActions, idle: Boolean) {
|
||||
var removing by remember { mutableStateOf<DeckyStore.Installed?>(null) }
|
||||
if (s.deckyPlugins.isEmpty()) {
|
||||
Text(stringResource(R.string.decky_none_installed), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp))
|
||||
}
|
||||
for (plugin in s.deckyPlugins) {
|
||||
val listed = s.deckyStore?.firstOrNull { it.name == plugin.name }
|
||||
val update = listed?.takeIf { DeckyStore.updateAvailable(plugin, it) }
|
||||
PluginRow(
|
||||
plugin.name,
|
||||
listOf(plugin.version, plugin.author).filter { it.isNotBlank() }.joinToString(" · ") +
|
||||
(update?.latest?.let { " · " + stringResource(R.string.decky_update_to, it.name) } ?: ""),
|
||||
listed?.imageUrl.orEmpty(),
|
||||
) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
if (update != null) SecondaryButton(stringResource(R.string.common_update), enabled = idle, compact = true) { a.onDeckyStoreInstall(update) }
|
||||
SecondaryButton(stringResource(R.string.decky_remove), enabled = idle, compact = true, modifier = Modifier.testTag("decky-remove-${plugin.folder}")) { removing = plugin }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (s.deckyPlugins.isNotEmpty()) Text(stringResource(R.string.decky_changes_next_session), fontSize = 12.sp,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp))
|
||||
removing?.let { plugin ->
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { removing = null },
|
||||
title = { Text(stringResource(R.string.decky_remove_confirm, plugin.name)) },
|
||||
text = { Text(stringResource(R.string.decky_remove_confirm_body)) },
|
||||
confirmButton = { androidx.compose.material3.TextButton(onClick = { removing = null; a.onDeckyRemove(plugin) }) { Text(stringResource(R.string.decky_remove)) } },
|
||||
dismissButton = { androidx.compose.material3.TextButton(onClick = { removing = null }) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PluginStore(s: ModeSettings, a: ModeSettingsActions, idle: Boolean) {
|
||||
var query by rememberSaveable { mutableStateOf("") }
|
||||
var searching by remember { mutableStateOf(false) }
|
||||
var shown by rememberSaveable { mutableIntStateOf(STORE_PAGE) }
|
||||
val plugins = s.deckyStore
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp).padding(bottom = 12.dp)) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
Box(Modifier.weight(1f)) {
|
||||
ListRow(tall = true, onClick = { searching = true }) {
|
||||
androidx.compose.material3.Icon(Icons.Filled.Search, contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(18.dp))
|
||||
Text(
|
||||
query.ifEmpty { stringResource(R.string.decky_store_search) }, fontSize = 14.sp, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
color = if (query.isEmpty()) MaterialTheme.colorScheme.onSurfaceVariant else MaterialTheme.colorScheme.onBackground,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (query.isNotEmpty()) SecondaryButton(stringResource(R.string.boot_movie_repo_clear), compact = true) { query = ""; shown = STORE_PAGE }
|
||||
}
|
||||
when {
|
||||
plugins == null -> Text(stringResource(R.string.common_working), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(vertical = 12.dp))
|
||||
s.deckyStoreFailed -> Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(stringResource(R.string.decky_store_failed), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(1f))
|
||||
SecondaryButton(stringResource(R.string.boot_movie_repo_retry), compact = true) { a.onDeckyStoreRefresh() }
|
||||
}
|
||||
else -> {
|
||||
val matches = remember(plugins, query) { deckyStoreMatches(plugins, query) }
|
||||
if (matches.isEmpty()) Text(stringResource(R.string.decky_store_empty), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(vertical = 12.dp))
|
||||
for (plugin in matches.take(shown)) {
|
||||
val have = s.deckyPlugins.firstOrNull { it.name == plugin.name }
|
||||
val current = have != null && !DeckyStore.updateAvailable(have, plugin)
|
||||
PluginRow(
|
||||
plugin.name,
|
||||
listOf(plugin.latest?.name.orEmpty(), plugin.author, plugin.description).filter { it.isNotBlank() }.joinToString(" · "),
|
||||
plugin.imageUrl,
|
||||
) {
|
||||
SecondaryButton(
|
||||
stringResource(when { current -> R.string.setup_installed; have != null -> R.string.common_update; else -> R.string.boot_movie_repo_install }),
|
||||
enabled = idle && !current, compact = true,
|
||||
modifier = Modifier.testTag("decky-store-${plugin.name}"),
|
||||
) { a.onDeckyStoreInstall(plugin) }
|
||||
}
|
||||
}
|
||||
if (matches.size > shown) SecondaryButton(stringResource(R.string.decky_store_more, matches.size - shown), compact = true) { shown += STORE_PAGE }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (searching) TextEntryDialog(
|
||||
stringResource(R.string.decky_store_search), query, number = false, confirm = stringResource(R.string.stores_search_open),
|
||||
onSubmit = { query = it; shown = STORE_PAGE; searching = false }, onDismiss = { searching = false }, id = "decky-store-entry",
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PluginRow(name: String, detail: String, imageUrl: String, actions: @Composable () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp)) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = androidx.compose.ui.Alignment.CenterVertically) {
|
||||
val shape = RoundedCornerShape(8.dp)
|
||||
Box(Modifier.width(96.dp).aspectRatio(16f / 9f).clip(shape).background(Color(0xFF0E1218))) {
|
||||
if (imageUrl.isNotEmpty()) AsyncImage(model = imageUrl, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())
|
||||
}
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(name, fontSize = 15.sp, fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(detail, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) { actions() }
|
||||
}
|
||||
}
|
||||
@@ -309,7 +309,7 @@ private fun DesktopCard(
|
||||
Column(
|
||||
Modifier.width(width).paneItem("tile:desktop:$key").then(if (first) Modifier.firstTile() else Modifier)
|
||||
.graphicsLayer { scaleX = scale; scaleY = scale }
|
||||
.clip(shape).background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier)
|
||||
.clip(shape).background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)
|
||||
.glideBorder(hot, shape, pal.signal, pal.line)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button) { onClick(artAt) }
|
||||
.controllerConfirm { onClick(artAt) }
|
||||
|
||||
@@ -175,7 +175,7 @@ internal fun SessionDrawerPreview(secondScreens: List<SecondScreenDisplay>) {
|
||||
val code = e.nativeKeyEvent.keyCode
|
||||
if (code != android.view.KeyEvent.KEYCODE_BUTTON_L1 && code != android.view.KeyEvent.KEYCODE_BUTTON_R1) return@onPreviewKeyEvent false
|
||||
if (e.type == KeyEventType.KeyDown && e.nativeKeyEvent.repeatCount == 0) {
|
||||
page = sessionDrawerPages().let { it.strip().step(it.tabFor(page), if (code == android.view.KeyEvent.KEYCODE_BUTTON_R1) 1 else -1) }
|
||||
page = sessionDrawerPages().step(page, if (code == android.view.KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
@@ -148,61 +148,7 @@ object DualScreenPanel {
|
||||
}.onFailure { launching = false; displayId = -1 }
|
||||
}
|
||||
|
||||
/**
|
||||
* The panel on a presentation window sits above every activity on its screen, so an app launched there stays hidden behind it.
|
||||
* Swapping the panel for a task of its own puts the app above it, and closing the app shows the panel again.
|
||||
* Launches requested while the swap is under way wait for it and run in the order they were asked for.
|
||||
*/
|
||||
fun makeRoomForApp(context: Context, display: Int, launch: () -> Unit) {
|
||||
pendingLaunches?.let { it.add(launch); return }
|
||||
val shown = presentation
|
||||
if (shown == null || displayId != display) { launch(); return }
|
||||
pendingLaunches = mutableListOf(launch)
|
||||
val generation = ++handoffGeneration
|
||||
handoffWaited = 0
|
||||
presentation = null
|
||||
shown.dismiss()
|
||||
launching = true
|
||||
val intent = Intent(context, DualScreenActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION)
|
||||
.putExtra(EXTRA_HANDOFF, generation)
|
||||
val started = runCatching {
|
||||
context.startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(display).toBundle())
|
||||
}.isSuccess
|
||||
if (!started) { launching = false; displayId = -1; releaseLaunches(); return }
|
||||
handoffPoll.run()
|
||||
}
|
||||
|
||||
private var pendingLaunches: MutableList<() -> Unit>? = null
|
||||
private var handoffWaited = 0
|
||||
private var handoffGeneration = 0
|
||||
internal const val EXTRA_HANDOFF = "handoff"
|
||||
private val handoffHandler = android.os.Handler(android.os.Looper.getMainLooper())
|
||||
private val handoffPoll = object : Runnable {
|
||||
override fun run() {
|
||||
if (pendingLaunches == null) return
|
||||
if (activity != null || handoffWaited >= APP_WAIT_MS) releaseLaunches()
|
||||
else { handoffWaited += APP_POLL_MS; handoffHandler.postDelayed(this, APP_POLL_MS.toLong()) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun releaseLaunches() {
|
||||
val waiting = pendingLaunches ?: return
|
||||
pendingLaunches = null
|
||||
handoffHandler.removeCallbacks(handoffPoll)
|
||||
waiting.forEach { it() }
|
||||
}
|
||||
|
||||
private fun dropLaunches() {
|
||||
pendingLaunches = null
|
||||
handoffHandler.removeCallbacks(handoffPoll)
|
||||
}
|
||||
|
||||
private const val APP_POLL_MS = 100
|
||||
private const val APP_WAIT_MS = 2000
|
||||
|
||||
fun hide() {
|
||||
dropLaunches()
|
||||
stopTyping()
|
||||
launching = false
|
||||
displayId = -1
|
||||
@@ -223,9 +169,6 @@ object DualScreenPanel {
|
||||
if (activity !== host) activity?.finishAndRemoveTask()
|
||||
activity = host
|
||||
launching = false
|
||||
val waiting = pendingLaunches
|
||||
val generation = host.intent?.getIntExtra(EXTRA_HANDOFF, -1) ?: -1
|
||||
handoffHandler.post { if (pendingLaunches === waiting && generation == handoffGeneration) releaseLaunches() }
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@@ -33,9 +33,7 @@ import androidx.compose.ui.graphics.drawscope.translate
|
||||
import androidx.compose.ui.graphics.lerp
|
||||
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.layout.positionInRoot
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalHapticFeedback
|
||||
import androidx.compose.ui.unit.dp
|
||||
@@ -49,30 +47,21 @@ import kotlin.math.sin
|
||||
|
||||
@Composable
|
||||
internal fun EmptyLibrary(avoid: Rect?, wall: (@Composable () -> Unit)? = null, fade: @Composable () -> Unit) {
|
||||
var origin by remember { mutableStateOf(Offset.Zero) }
|
||||
val clock = rememberMarkClock(avoid?.translate(-origin.x, -origin.y))
|
||||
Box(
|
||||
Modifier.fillMaxSize()
|
||||
.onGloballyPositioned { origin = it.positionInRoot() }
|
||||
.onSizeChanged { clock.page = Size(it.width.toFloat(), it.height.toFloat()) },
|
||||
) {
|
||||
val clock = rememberMarkClock(avoid)
|
||||
Box(Modifier.fillMaxSize().onSizeChanged { clock.page = Size(it.width.toFloat(), it.height.toFloat()) }) {
|
||||
if (wall != null) wall() else EmptyWall(clock)
|
||||
fade()
|
||||
Mark(clock)
|
||||
}
|
||||
}
|
||||
|
||||
private const val TRACE_MS = 1250f
|
||||
private const val FILL_FROM = 450f
|
||||
private const val POP_FROM = 900f
|
||||
private const val IMPACT = 2200f
|
||||
private const val RIPPLE_MS = 1250f
|
||||
private const val HIT_MS = 900f
|
||||
private const val END = 3600f
|
||||
private const val REVEAL_MS = 2300f
|
||||
private const val TRACE_DRAW_MS = 900f
|
||||
private const val TRACE_FADE_MS = 500f
|
||||
private const val REVEAL_FILL_FROM = 600f
|
||||
private const val REVEAL_FILL_MS = 450f
|
||||
private const val REVEAL_FADE_FROM = 1700f
|
||||
private const val POKE = 880f
|
||||
private const val DRIFT_MS = 75_000f
|
||||
|
||||
@@ -93,7 +82,8 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock {
|
||||
val haptics = LocalHapticFeedback.current
|
||||
val keepOff by rememberUpdatedState(avoid)
|
||||
val speed = with(LocalDensity.current) { 64.dp.toPx() }
|
||||
val clearance = with(LocalDensity.current) { 4.dp.toPx() }
|
||||
val inset = with(LocalDensity.current) { 10.dp.toPx() }
|
||||
val clearance = with(LocalDensity.current) { 16.dp.toPx() }
|
||||
LaunchedEffect(clock) {
|
||||
var last = -1L
|
||||
var vx = speed * 0.8f
|
||||
@@ -119,28 +109,16 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock {
|
||||
|
||||
var x = clock.at.x + vx * dt / 1000f
|
||||
var y = clock.at.y + vy * dt / 1000f
|
||||
val hw = f.ball
|
||||
val hh = f.ball
|
||||
if (x - hw < 0f) { x = hw; vx = abs(vx) }
|
||||
if (x + hw > clock.page.width) { x = clock.page.width - hw; vx = -abs(vx) }
|
||||
if (y - hh < 0f) { y = hh; vy = abs(vy) }
|
||||
if (y + hh > clock.page.height) { y = clock.page.height - hh; vy = -abs(vy) }
|
||||
val hw = f.halfWidth
|
||||
val hh = f.halfHeight
|
||||
if (x - hw < inset) { x = inset + hw; vx = abs(vx) }
|
||||
if (x + hw > clock.page.width - inset) { x = clock.page.width - inset - hw; vx = -abs(vx) }
|
||||
if (y - hh < inset) { y = inset + hh; vy = abs(vy) }
|
||||
if (y + hh > clock.page.height - inset) { y = clock.page.height - inset - hh; vy = -abs(vy) }
|
||||
keepOff?.inflate(clearance)?.let { r ->
|
||||
val nearX = x.coerceIn(r.left, r.right)
|
||||
val nearY = y.coerceIn(r.top, r.bottom)
|
||||
val gapX = x - nearX
|
||||
val gapY = y - nearY
|
||||
val gap = hypot(gapX, gapY)
|
||||
if (gap in 0.0001f..f.ball) {
|
||||
val nx = gapX / gap
|
||||
val ny = gapY / gap
|
||||
x = nearX + nx * f.ball
|
||||
y = nearY + ny * f.ball
|
||||
val into = vx * nx + vy * ny
|
||||
if (into < 0f) { vx -= 2f * into * nx; vy -= 2f * into * ny }
|
||||
} else if (gap <= 0.0001f) {
|
||||
val outX = if (x < r.center.x) r.left - f.ball - x else r.right + f.ball - x
|
||||
val outY = if (y < r.center.y) r.top - f.ball - y else r.bottom + f.ball - y
|
||||
if (x + hw > r.left && x - hw < r.right && y + hh > r.top && y - hh < r.bottom) {
|
||||
val outX = if (x < r.center.x) r.left - (x + hw) else r.right - (x - hw)
|
||||
val outY = if (y < r.center.y) r.top - (y + hh) else r.bottom - (y - hh)
|
||||
if (abs(outX) < abs(outY)) { x += outX; vx = if (outX < 0) -abs(vx) else abs(vx) }
|
||||
else { y += outY; vy = if (outY < 0) -abs(vy) else abs(vy) }
|
||||
}
|
||||
@@ -316,33 +294,30 @@ private fun Mark(clock: MarkClock) {
|
||||
} else 0f
|
||||
|
||||
translate(0f, shake) {
|
||||
val since = t - IMPACT
|
||||
if (since in 0f..REVEAL_MS) {
|
||||
val fade = 1f - clamp01((since - REVEAL_FADE_FROM) / (REVEAL_MS - REVEAL_FADE_FROM))
|
||||
val fill = Out.transform(clamp01((since - REVEAL_FILL_FROM) / REVEAL_FILL_MS)) * fade
|
||||
if (fill > 0f) {
|
||||
val lift = 8f * k * (1f - fill / fade)
|
||||
val edge = 5f * f.s
|
||||
LogoShape.left(left, 0f) { x, y -> f.px(x, y) + Offset(0f, lift + edge) }
|
||||
LogoShape.right(right) { x, y -> f.px(x, y) + Offset(0f, lift + edge) }
|
||||
drawPath(left, slabEdge.copy(alpha = fill))
|
||||
drawPath(right, slabEdge.copy(alpha = fill))
|
||||
LogoShape.left(left, 0f) { x, y -> f.px(x, y) + Offset(0f, lift) }
|
||||
LogoShape.right(right) { x, y -> f.px(x, y) + Offset(0f, lift) }
|
||||
drawPath(left, ink.copy(alpha = fill))
|
||||
drawPath(right, ink.copy(alpha = fill))
|
||||
}
|
||||
val drawn = TraceEase.transform(clamp01(since / TRACE_DRAW_MS))
|
||||
val alpha = (if (since < TRACE_DRAW_MS) 1f else 1f - (since - TRACE_DRAW_MS) / TRACE_FADE_MS).coerceIn(0f, 1f) * fade
|
||||
if (alpha > 0f) {
|
||||
LogoShape.left(left, 0f, f::px)
|
||||
LogoShape.right(right, f::px)
|
||||
for (half in listOf(left, right)) {
|
||||
measure.setPath(half, false)
|
||||
piece.reset()
|
||||
measure.getSegment(0f, measure.length * drawn, piece, true)
|
||||
drawPath(piece, pal.signal.copy(alpha = alpha), style = Stroke(3f * f.s))
|
||||
}
|
||||
val fill = Out.transform(clamp01((intro - FILL_FROM) / 450f))
|
||||
if (fill > 0f) {
|
||||
val lift = 8f * k * (1f - fill)
|
||||
val edge = 5f * f.s
|
||||
LogoShape.left(left, 0f) { x, y -> f.px(x, y) + Offset(0f, lift + edge) }
|
||||
LogoShape.right(right) { x, y -> f.px(x, y) + Offset(0f, lift + edge) }
|
||||
drawPath(left, slabEdge.copy(alpha = fill))
|
||||
drawPath(right, slabEdge.copy(alpha = fill))
|
||||
LogoShape.left(left, 0f) { x, y -> f.px(x, y) + Offset(0f, lift) }
|
||||
LogoShape.right(right) { x, y -> f.px(x, y) + Offset(0f, lift) }
|
||||
drawPath(left, ink.copy(alpha = fill))
|
||||
drawPath(right, ink.copy(alpha = fill))
|
||||
}
|
||||
|
||||
if (intro < TRACE_MS) {
|
||||
val drawn = TraceEase.transform(clamp01(intro / 775f))
|
||||
val alpha = if (intro < 775f) 1f else 1f - (intro - 775f) / 475f
|
||||
LogoShape.left(left, 0f, f::px)
|
||||
LogoShape.right(right, f::px)
|
||||
for (half in listOf(left, right)) {
|
||||
measure.setPath(half, false)
|
||||
piece.reset()
|
||||
measure.getSegment(0f, measure.length * drawn, piece, true)
|
||||
drawPath(piece, pal.signal.copy(alpha = alpha), style = Stroke(2f * f.s))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -33,8 +33,6 @@ import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Outline
|
||||
import androidx.compose.ui.graphics.Shape
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
import androidx.compose.ui.graphics.Path
|
||||
import androidx.compose.ui.geometry.RoundRect
|
||||
import androidx.compose.ui.layout.LayoutCoordinates
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
@@ -111,21 +109,13 @@ internal fun VeilRing() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun cornersOf(shape: Shape, size: Size, dir: LayoutDirection, density: Density): FloatArray =
|
||||
private fun cornerOf(shape: Shape, size: Size, dir: LayoutDirection, density: Density): Float =
|
||||
when (val o = shape.createOutline(size, dir, density)) {
|
||||
is Outline.Rounded -> o.roundRect.run {
|
||||
floatArrayOf(topLeftCornerRadius.x, topRightCornerRadius.x, bottomRightCornerRadius.x, bottomLeftCornerRadius.x)
|
||||
}
|
||||
is Outline.Rectangle -> FloatArray(4)
|
||||
is Outline.Generic -> FloatArray(4) { minOf(size.width, size.height) / 2f }
|
||||
is Outline.Rounded -> o.roundRect.topLeftCornerRadius.x
|
||||
is Outline.Rectangle -> 0f
|
||||
is Outline.Generic -> minOf(size.width, size.height) / 2f
|
||||
}
|
||||
|
||||
private fun ringRect(l: Float, t: Float, w: Float, h: Float, radii: FloatArray, inset: Float): Path {
|
||||
// Radii are not capped one by one: the path scales corners whose neighbours overlap, as the outline does.
|
||||
fun r(i: Int) = CornerRadius((radii[i] - inset).coerceAtLeast(0f))
|
||||
return Path().apply { addRoundRect(RoundRect(Rect(l, t, l + w, t + h), r(0), r(1), r(2), r(3))) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun Modifier.glideBorder(
|
||||
hot: Boolean,
|
||||
@@ -200,7 +190,7 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
|
||||
val density = LocalDensity.current
|
||||
val dir = LocalLayoutDirection.current
|
||||
val edges = remember { List(4) { Animatable(0f) } }
|
||||
val corners = remember { List(4) { Animatable(0f) } }
|
||||
val corner = remember { Animatable(0f) }
|
||||
val solid = remember { Animatable(0f) }
|
||||
val alpha = remember { Animatable(0f) }
|
||||
val scope = rememberCoroutineScope()
|
||||
@@ -269,14 +259,14 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
|
||||
fun droplet(s: GlideSource, b: Rect) {
|
||||
jobs.forEach { it?.cancel() }
|
||||
val size = s.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size
|
||||
val endCorners = cornersOf(s.shape, size, dir, density)
|
||||
val endCorner = cornerOf(s.shape, size, dir, density)
|
||||
jobs[5] = scope.launch {
|
||||
val r = with(density) { 6.dp.toPx() }
|
||||
fun dot(c: Offset) = listOf(c.x - r, c.y - r, c.x + r, c.y + r)
|
||||
val here = Offset((edges[0].value + edges[2].value) / 2f, (edges[1].value + edges[3].value) / 2f)
|
||||
coroutineScope {
|
||||
launch { solid.animateTo(1f, Motion.tw(80)) }
|
||||
corners.forEach { c -> launch { c.animateTo(r, Motion.tw(90)) } }
|
||||
launch { corner.animateTo(r, Motion.tw(90)) }
|
||||
dot(here).forEachIndexed { i, v -> launch { edges[i].animateTo(v, Motion.tw(90)) } }
|
||||
}
|
||||
val distance = hypot(b.center.x - here.x, b.center.y - here.y) / density.density
|
||||
@@ -291,9 +281,7 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
|
||||
flight.cancel()
|
||||
val at = glide.boundsOf(s) ?: b
|
||||
launch { solid.animateTo(0f, Motion.tw(150)) }
|
||||
// The droplet job is cancelled by the next move, so the shape settles on the corner job instead.
|
||||
jobs[4]?.cancel()
|
||||
jobs[4] = scope.launch { corners.forEachIndexed { i, c -> launch { c.animateTo(endCorners[i], Motion.sp(0.8f, 600f)) } } }
|
||||
launch { corner.animateTo(endCorner, Motion.sp(0.8f, 600f)) }
|
||||
listOf(at.left, at.top, at.right, at.bottom).forEachIndexed { i, v ->
|
||||
jobs[i] = launch { edges[i].animateTo(v, Motion.sp(0.7f, 750f)) }
|
||||
}
|
||||
@@ -301,11 +289,9 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
|
||||
}
|
||||
fun cornerTo(s: GlideSource, b: Rect, snap: Boolean) {
|
||||
val size = s.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size
|
||||
val r = cornersOf(s.shape, size, dir, density)
|
||||
val r = cornerOf(s.shape, size, dir, density)
|
||||
jobs[4]?.cancel()
|
||||
jobs[4] = scope.launch {
|
||||
corners.forEachIndexed { i, c -> launch { if (snap) c.snapTo(r[i]) else c.animateTo(r[i], Motion.sp(0.8f, 500f)) } }
|
||||
}
|
||||
jobs[4] = scope.launch { if (snap) corner.snapTo(r) else corner.animateTo(r, Motion.sp(0.8f, 500f)) }
|
||||
}
|
||||
snapshotFlow { Triple(glide.current, glide.moves, glide.hidden || RingVeil.count > 0) }.collectLatest { (src, _, hidden) ->
|
||||
if (Motion.scale == 0f) {
|
||||
@@ -316,7 +302,7 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
|
||||
else {
|
||||
listOf(b.left, b.top, b.right, b.bottom).forEachIndexed { i, v -> edges[i].snapTo(v) }
|
||||
val size = src.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size
|
||||
cornersOf(src.shape, size, dir, density).forEachIndexed { i, v -> corners[i].snapTo(v) }
|
||||
corner.snapTo(cornerOf(src.shape, size, dir, density))
|
||||
alpha.snapTo(1f)
|
||||
}
|
||||
shown = src
|
||||
@@ -357,11 +343,10 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
|
||||
val out = with(density) { 3.dp.toPx() }
|
||||
val grown = listOf(b.left - out, b.top - out, b.right + out, b.bottom + out)
|
||||
jobs.forEach { it?.cancel() }
|
||||
// Set before the join: a move of the target restarts this block there, after shown is already set.
|
||||
cornerTo(src, b, snap = true)
|
||||
scope.launch { solid.snapTo(0f); edges.forEachIndexed { i, e -> e.snapTo(grown[i]) } }.join()
|
||||
dirSpecs = List(4) { Edge(0.6f, 700f) }
|
||||
delays = LongArray(4)
|
||||
cornerTo(src, b, snap = true)
|
||||
scope.launch { alpha.animateTo(1f, Motion.tw(140)) }
|
||||
} else {
|
||||
val dx = b.center.x - (edges[0].value + edges[2].value) / 2f
|
||||
@@ -409,13 +394,21 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
|
||||
val l = edges[0].value; val t = edges[1].value; val r = edges[2].value; val b = edges[3].value
|
||||
val sw = (r - l - w).coerceAtLeast(0f)
|
||||
val sh = (b - t - w).coerceAtLeast(0f)
|
||||
val radii = FloatArray(4) { corners[it].value }
|
||||
val rad = (corner.value - w / 2f).coerceIn(0f, minOf(sw, sh) / 2f)
|
||||
val f = solid.value
|
||||
if (f > 0.01f) drawPath(ringRect(l, t, r - l, b - t, radii, 0f), color, alpha = a * f)
|
||||
if (f > 0.01f) drawRoundRect(
|
||||
color, topLeft = Offset(l, t), size = Size(r - l, b - t),
|
||||
cornerRadius = CornerRadius(corner.value), alpha = a * f,
|
||||
)
|
||||
if (f < 0.99f) {
|
||||
val inner = ringRect(l + w / 2f, t + w / 2f, sw, sh, radii, w / 2f)
|
||||
drawPath(inner, color, alpha = a * (1f - f) * fillAlpha)
|
||||
drawPath(inner, color, style = Stroke(w), alpha = a)
|
||||
drawRoundRect(
|
||||
color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh),
|
||||
cornerRadius = CornerRadius(rad), alpha = a * (1f - f) * fillAlpha,
|
||||
)
|
||||
drawRoundRect(
|
||||
color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh),
|
||||
cornerRadius = CornerRadius(rad), style = Stroke(w), alpha = a,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -263,10 +263,6 @@ private fun Content(
|
||||
SyncTabPage(s, modifier.padding(horizontal = padH).padding(top = padV))
|
||||
return
|
||||
}
|
||||
if (selected == "decky" || selected == "boot-movies") {
|
||||
SteamTabPage(selected, a, modifier.padding(horizontal = padH).padding(top = padV))
|
||||
return
|
||||
}
|
||||
if (selected == "updates") {
|
||||
UpdatesPage(s, a, modifier.padding(horizontal = padH).padding(top = padV))
|
||||
return
|
||||
|
||||
@@ -56,9 +56,9 @@ import androidx.compose.material.icons.filled.Terminal
|
||||
import androidx.compose.material.icons.filled.Apps
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material.icons.filled.SdStorage
|
||||
import androidx.compose.material.icons.filled.Movie
|
||||
import androidx.compose.material.icons.filled.Sync
|
||||
import androidx.compose.material.icons.filled.MoreHoriz
|
||||
import androidx.compose.material.icons.filled.SystemUpdate
|
||||
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.material3.Icon
|
||||
@@ -207,10 +207,8 @@ internal fun railLabelIcon(key: String): Pair<Int, ImageVector> = when (key) {
|
||||
"setup" -> R.string.rail_setup to Icons.Filled.Settings
|
||||
"storage" -> R.string.rail_storage to Icons.Filled.SdStorage
|
||||
"sync" -> R.string.rail_sync to Icons.Filled.Sync
|
||||
"decky" -> R.string.rail_decky to DeckyIcon
|
||||
"boot-movies" -> R.string.rail_boot_movies to Icons.Filled.Movie
|
||||
NavTabs.MORE -> R.string.rail_more to Icons.Filled.MoreHoriz
|
||||
else -> R.string.rail_updates to updatesIcon(RunningBuild.kind())
|
||||
else -> R.string.rail_updates to Icons.Filled.SystemUpdate
|
||||
}
|
||||
|
||||
internal fun setupNeedsAttention(s: FrontEndState): Boolean = !s.ready || (s.available != null && s.available != s.installed) ||
|
||||
|
||||
@@ -143,7 +143,6 @@ class FrontEndState(
|
||||
val integrationFocus: com.droiddeck.launcher.core.SteamIntegration.Feature? = null,
|
||||
val androidApps: List<HomeApp.LaunchableApp> = emptyList(),
|
||||
val secondScreenDisplays: List<SecondScreenDisplay> = emptyList(),
|
||||
val ownScreen: SecondScreenDisplay? = null,
|
||||
val dualScreen: Boolean = false,
|
||||
val dualScreenDevice: Boolean = false,
|
||||
val dualScreenMode: String = com.droiddeck.launcher.input.DualScreen.MODE_AUTO,
|
||||
@@ -314,14 +313,16 @@ class FrontEndActions(
|
||||
val onBackActionsInverted: (Boolean) -> Unit = {},
|
||||
val onRefreshPhantomStatus: () -> Unit = {},
|
||||
val onOpenDeveloperOptions: (Int?) -> Unit = {},
|
||||
val onWirelessAdbPair: (String, Int, String, (String?) -> Unit) -> Unit,
|
||||
val onFindWirelessAdbPort: (String, (Int?) -> Unit) -> Unit = { _, done -> done(null) },
|
||||
val onWirelessAdbApply: (String, Int, Boolean, (String?) -> Unit) -> Unit,
|
||||
val onSetPhantomProcessLimit: (Boolean, (String?) -> Unit) -> Unit,
|
||||
val onCopyPhantomCommand: (Boolean) -> Unit = {},
|
||||
val onDismissPhantomGate: () -> Unit = {},
|
||||
val onStartWirelessAdbPairing: (Boolean) -> Unit = {},
|
||||
val onStartWirelessAdbPairing: () -> Unit = {},
|
||||
val onStartPairingGuide: (Int?, Boolean) -> Boolean = { _, _ -> false },
|
||||
val onShowPhantomGate: () -> Unit = {},
|
||||
val onQueuePlaySteam: () -> Unit = {},
|
||||
val onEnsureNotifications: ((Boolean) -> Unit) -> Unit = { it(true) },
|
||||
val onOpenNotificationSettings: () -> Unit = {},
|
||||
val controller: ControllerActions? = null,
|
||||
val updates: UpdatesActions = UpdatesActions(),
|
||||
)
|
||||
@@ -453,7 +454,6 @@ internal suspend fun focusSoon(target: () -> FocusRequester) {
|
||||
@Composable
|
||||
fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)? = null) {
|
||||
val frontFocus = remember { FrontFocus() }
|
||||
androidx.compose.runtime.SideEffect { RunningBuild.channel = s.updates.follow.channel }
|
||||
val textInput = androidx.compose.ui.platform.LocalTextInputService.current
|
||||
val bottomTextInput = remember(textInput) { textInput?.let { androidx.compose.ui.text.input.TextInputService(BottomScreenTextInput(it)) } }
|
||||
androidx.compose.foundation.layout.BoxWithConstraints(Modifier.fillMaxSize().pointerInput(Unit) {
|
||||
@@ -507,16 +507,17 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
LaunchedEffect(com.droiddeck.launcher.stores.StoresState.openGameRequest) {
|
||||
if (com.droiddeck.launcher.stores.StoresState.openGameRequest != null) selected = "stores"
|
||||
}
|
||||
var showWirelessAdbFix by rememberSaveable { mutableStateOf(false) }
|
||||
var showDeveloperDisplayChoice by rememberSaveable { mutableStateOf(false) }
|
||||
var developerChoiceGuided by rememberSaveable { mutableStateOf(false) }
|
||||
var developerChoiceToggle by rememberSaveable { mutableStateOf(false) }
|
||||
var guidedLimitEnabled by rememberSaveable { mutableStateOf(false) }
|
||||
var wirelessAdbDesiredEnabled by rememberSaveable { mutableStateOf(false) }
|
||||
var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) }
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val ctx = LocalContext.current
|
||||
val phantomGateVisible = s.showPhantomGate && PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
|
||||
val processSettingsPageVisible = phantomGateVisible || showDeveloperDisplayChoice
|
||||
val processSettingsPageVisible = phantomGateVisible || showWirelessAdbFix || showDeveloperDisplayChoice
|
||||
val requestDeveloperOptions = {
|
||||
developerChoiceGuided = false
|
||||
developerChoiceToggle = false
|
||||
@@ -524,7 +525,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
else showDeveloperDisplayChoice = true
|
||||
}
|
||||
val openDeveloperOptionsOn: (Int?) -> Unit = { displayId ->
|
||||
if (developerChoiceGuided) a.onStartWirelessAdbPairing(guidedLimitEnabled)
|
||||
if (developerChoiceGuided) a.onStartWirelessAdbPairing()
|
||||
val guided = developerChoiceGuided || developerChoiceToggle
|
||||
if (!guided || !a.onStartPairingGuide(displayId, developerChoiceToggle)) a.onOpenDeveloperOptions(displayId)
|
||||
developerChoiceGuided = false
|
||||
@@ -540,35 +541,31 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
else showDeveloperDisplayChoice = true
|
||||
}
|
||||
}
|
||||
val startGuidedPairing: (Boolean) -> Unit = { enabled ->
|
||||
a.onEnsureNotifications { granted ->
|
||||
if (granted) {
|
||||
guidedLimitEnabled = enabled
|
||||
developerChoiceGuided = true
|
||||
if (s.secondScreenDisplays.isEmpty()) openDeveloperOptionsOn(null)
|
||||
else showDeveloperDisplayChoice = true
|
||||
}
|
||||
val startGuidedPairing = {
|
||||
if (!com.droiddeck.launcher.core.WirelessAdbPairingService.notificationsEnabled(ctx)) {
|
||||
wirelessAdbDesiredEnabled = false
|
||||
showWirelessAdbFix = true
|
||||
} else {
|
||||
developerChoiceGuided = true
|
||||
if (s.secondScreenDisplays.isEmpty()) openDeveloperOptionsOn(null)
|
||||
else showDeveloperDisplayChoice = true
|
||||
}
|
||||
}
|
||||
val childProcessRequest = androidx.compose.runtime.rememberUpdatedState {
|
||||
if (PhantomProcessLimit.hasDeveloperToggle()) requestChildProcessToggle() else a.onShowPhantomGate()
|
||||
}
|
||||
DisposableEffect(Unit) {
|
||||
val handler: () -> Unit = { childProcessRequest.value() }
|
||||
ChildProcessSetup.request = handler
|
||||
onDispose { if (ChildProcessSetup.request === handler) ChildProcessSetup.request = null }
|
||||
}
|
||||
var applyingSavedPairing by remember { mutableStateOf(false) }
|
||||
val fixPhantomLimit = {
|
||||
if (!s.adbPaired || !com.droiddeck.launcher.core.GlobalSettings.wirelessDebuggingOn(ctx)) startGuidedPairing(false)
|
||||
if (!s.adbPaired || !com.droiddeck.launcher.core.GlobalSettings.wirelessDebuggingOn(ctx)) startGuidedPairing()
|
||||
else if (!applyingSavedPairing) {
|
||||
applyingSavedPairing = true
|
||||
a.onSetPhantomProcessLimit(false) { error ->
|
||||
applyingSavedPairing = false
|
||||
if (error != null) startGuidedPairing(false)
|
||||
if (error != null) startGuidedPairing()
|
||||
}
|
||||
}
|
||||
}
|
||||
val requestWirelessAdbFix: (Boolean) -> Unit = { enabled ->
|
||||
wirelessAdbDesiredEnabled = enabled
|
||||
showWirelessAdbFix = true
|
||||
}
|
||||
LaunchedEffect(s.showPhantomGate, s.phantomProcessStatus) {
|
||||
if (phantomGateVisible) {
|
||||
while (true) {
|
||||
@@ -764,20 +761,6 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
focusManager.clearFocus(force = true)
|
||||
onRailSelect(key)
|
||||
}, a)
|
||||
val tabStep = androidx.compose.runtime.rememberUpdatedState { step: Int ->
|
||||
if (!processSettingsPageVisible) {
|
||||
val keys = navigationKeys(s)
|
||||
keys.getOrNull(keys.indexOf(railSelectionNow.value) + step)?.let { key ->
|
||||
PageSwipe.direction = step
|
||||
onRailSelect(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
DisposableEffect(Unit) {
|
||||
val handler: (Int) -> Unit = { tabStep.value(it) }
|
||||
MainTabSteps.handler = handler
|
||||
onDispose { if (MainTabSteps.handler === handler) MainTabSteps.handler = null }
|
||||
}
|
||||
CompositionLocalProvider(LocalShowSection provides { key -> selected = key }) {
|
||||
val swipeContext = androidx.compose.ui.platform.LocalContext.current
|
||||
remember { com.droiddeck.launcher.core.AppUiPrefs.pageSwipe(swipeContext).also { PageSwipe.on = it } }
|
||||
@@ -785,7 +768,19 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
LauncherLayout(
|
||||
bottomNavigation && !s.dualScreen, pal.line,
|
||||
Modifier.fillMaxSize().onGloballyPositioned { screenAt = it.positionInRoot() }
|
||||
.then(if (openTab == "agent") Modifier.imePadding() else Modifier),
|
||||
.then(if (openTab == "agent") Modifier.imePadding() else Modifier)
|
||||
.then(if (s.dualScreen) Modifier.onKeyEvent { event ->
|
||||
val step = dualPageStep(event.nativeKeyEvent) ?: return@onKeyEvent false
|
||||
if (event.type == KeyEventType.KeyDown && !processSettingsPageVisible) {
|
||||
val keys = navigationKeys(s)
|
||||
val at = keys.indexOf(railSelectionNow.value)
|
||||
keys.getOrNull(at + step)?.let { key ->
|
||||
PageSwipe.direction = step
|
||||
onRailSelect(key)
|
||||
}
|
||||
}
|
||||
true
|
||||
} else Modifier),
|
||||
navigation = {
|
||||
if (s.dualScreen || (bottomNavigation && agentKeyboardOpen)) Unit
|
||||
else if (bottomNavigation) BottomBar(s, railSelection, onRailSelect, onRailFocus, a, railFocus)
|
||||
@@ -804,12 +799,12 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
},
|
||||
{ selected = it },
|
||||
onAndroidAppClick = { app ->
|
||||
if (s.secondScreenDisplays.isEmpty() && s.ownScreen == null) a.onAndroidApp(app, null)
|
||||
if (s.secondScreenDisplays.isEmpty()) a.onAndroidApp(app, null)
|
||||
else appToChooseDisplay = app
|
||||
},
|
||||
onOpenDeveloperOptions = requestChildProcessToggle,
|
||||
onPairWirelessDebugging = { startGuidedPairing(false) },
|
||||
onRequestWirelessAdb = startGuidedPairing,
|
||||
onRequestWirelessAdb = requestWirelessAdbFix,
|
||||
onPairWirelessDebugging = startGuidedPairing,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -825,7 +820,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
SessionDrawerPreview(s.secondScreenDisplays)
|
||||
|
||||
appToChooseDisplay?.let { app ->
|
||||
val secondaryDisplay = s.secondScreenDisplays.firstOrNull() ?: s.ownScreen
|
||||
val secondaryDisplay = s.secondScreenDisplays.firstOrNull()
|
||||
ChooseAppDisplayDialog(
|
||||
app = app,
|
||||
secondaryDisplay = secondaryDisplay,
|
||||
@@ -840,7 +835,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
onDismiss = { appToChooseDisplay = null },
|
||||
)
|
||||
}
|
||||
if (phantomGateVisible) {
|
||||
if (phantomGateVisible && !showWirelessAdbFix) {
|
||||
Box(Modifier.fillMaxSize().background(colors.background)) {
|
||||
PhantomProcessGatePage(
|
||||
status = s.phantomProcessStatus,
|
||||
@@ -848,7 +843,21 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
onOpenDeveloperOptions = requestChildProcessToggle,
|
||||
applyingSavedPairing = applyingSavedPairing,
|
||||
onFixWithWirelessDebugging = fixPhantomLimit,
|
||||
onEnterAddressManually = { requestWirelessAdbFix(false) },
|
||||
onCopyCommand = { a.onCopyPhantomCommand(false) },
|
||||
onOpenNotificationSettings = a.onOpenNotificationSettings,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (showWirelessAdbFix) {
|
||||
Box(Modifier.fillMaxSize().background(colors.background)) {
|
||||
WirelessAdbFixPage(
|
||||
onBack = { showWirelessAdbFix = false },
|
||||
desiredEnabled = wirelessAdbDesiredEnabled,
|
||||
onOpenDeveloperOptions = requestDeveloperOptions,
|
||||
onPair = a.onWirelessAdbPair,
|
||||
onFindConnectPort = a.onFindWirelessAdbPort,
|
||||
onApply = a.onWirelessAdbApply,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -893,11 +902,3 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal object ChildProcessSetup {
|
||||
@Volatile var request: (() -> Unit)? = null
|
||||
}
|
||||
|
||||
internal object MainTabSteps {
|
||||
@Volatile var handler: ((Int) -> Unit)? = null
|
||||
}
|
||||
@@ -51,7 +51,6 @@ import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
@@ -249,7 +248,6 @@ internal fun SetupPanel(
|
||||
if (listing) SettingsSearchResults(query) { section -> pick(section.ordinal) }
|
||||
else when (tab) {
|
||||
OVERVIEW_TAB -> {
|
||||
OnboardingCard(limitBlocks, a.onShowPhantomGate)
|
||||
// Setup's "Safe mode" row, under the GPU row while the bridge is on and can be used here.
|
||||
val bridgeModeRow = !s.adreno && s.vkBridge && com.droiddeck.launcher.core.DeviceSupport.bridgeUsable()
|
||||
val gpuCheck: @Composable (Boolean) -> Unit = { divider ->
|
||||
@@ -542,7 +540,7 @@ internal fun SetupPanel(
|
||||
)
|
||||
ChoiceRow(
|
||||
host, "dual-screen-sessions", stringResource(R.string.setup_dual_screen_sessions), stringResource(R.string.setup_dual_screen_sessions_hint),
|
||||
dualModes.take(2) + (com.droiddeck.launcher.input.DualScreen.MODE_SWAPPED to stringResource(R.string.setup_dual_screen_swapped)) + dualModes.drop(2), s.dualScreenSessions, onPick = a.onDualScreenSessions,
|
||||
dualModes, s.dualScreenSessions, onPick = a.onDualScreenSessions,
|
||||
)
|
||||
if (s.dualScreenSessions != com.droiddeck.launcher.input.DualScreen.MODE_OFF) {
|
||||
ToggleRow(host, "dual-screen-controls", stringResource(R.string.setup_dual_screen_controls),
|
||||
@@ -1168,7 +1166,7 @@ private fun SettingCard(label: String, value: String, id: String, modifier: Modi
|
||||
verticalArrangement = Arrangement.spacedBy(3.dp),
|
||||
modifier = modifier.paneItem(id)
|
||||
.graphicsLayer { scaleX = scale; scaleY = scale }
|
||||
.then(if (LocalGlass.current != null) Modifier.glass(Shape14, if (hot) 0.04f else 0f) else Modifier.clip(Shape14).background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier))
|
||||
.then(if (LocalGlass.current != null) Modifier.glass(Shape14, if (hot) 0.04f else 0f) else Modifier.clip(Shape14).background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface))
|
||||
.glideBorder(hot, Shape14, pal.signal, if (LocalGlass.current != null) Color.Transparent else pal.line2)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
|
||||
.controllerConfirm(onClick = onClick)
|
||||
@@ -1275,66 +1273,3 @@ private fun CustomColorRows() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun OnboardingCard(limitBlocks: Boolean = false, onSetUpLimit: () -> Unit = {}) {
|
||||
val active by com.droiddeck.launcher.session.Onboarding.active.collectAsState()
|
||||
val failed by com.droiddeck.launcher.session.Onboarding.failed.collectAsState()
|
||||
val facts by com.droiddeck.launcher.session.Onboarding.facts.collectAsState()
|
||||
val rows = com.droiddeck.launcher.session.Onboarding.rows(active, failed, facts)
|
||||
val firstRun by com.droiddeck.launcher.session.Onboarding.firstRun.collectAsState()
|
||||
val settling = firstRun && com.droiddeck.launcher.session.Onboarding.pending(rows)
|
||||
if (!settling) return
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val overall = com.droiddeck.launcher.session.Onboarding.overall(rows)
|
||||
Column(Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) {
|
||||
Column(Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 12.dp)) {
|
||||
Text(stringResource(R.string.onboarding_title), fontSize = 17.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
|
||||
Text(stringResource(R.string.onboarding_summary, overall), fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
LinearProgressIndicator(progress = { overall / 100f }, modifier = Modifier.fillMaxWidth().padding(top = 8.dp).height(4.dp))
|
||||
}
|
||||
rows.forEach { row ->
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp),
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
stringResource(when (row.step) {
|
||||
com.droiddeck.launcher.session.Onboarding.Step.RUNTIME -> R.string.onboarding_step_runtime
|
||||
com.droiddeck.launcher.session.Onboarding.Step.PROTON -> R.string.onboarding_step_proton
|
||||
com.droiddeck.launcher.session.Onboarding.Step.STEAM -> R.string.onboarding_step_steam
|
||||
}),
|
||||
fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
|
||||
)
|
||||
val detail = when (row.state) {
|
||||
com.droiddeck.launcher.session.Onboarding.State.ACTIVE -> row.label.orEmpty()
|
||||
com.droiddeck.launcher.session.Onboarding.State.FAILED -> stringResource(R.string.onboarding_failed)
|
||||
com.droiddeck.launcher.session.Onboarding.State.WAITING -> stringResource(R.string.onboarding_waiting)
|
||||
com.droiddeck.launcher.session.Onboarding.State.DONE -> stringResource(R.string.onboarding_done)
|
||||
}
|
||||
Text(detail, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
if (row.state == com.droiddeck.launcher.session.Onboarding.State.ACTIVE) {
|
||||
if (row.percent >= 0) LinearProgressIndicator(progress = { row.percent / 100f }, modifier = Modifier.fillMaxWidth().padding(top = 6.dp).height(3.dp))
|
||||
else LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(top = 6.dp).height(3.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (limitBlocks) {
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp),
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(stringResource(R.string.setup_limit), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||
Text(stringResource(R.string.onboarding_limit_reason), fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
PrimaryButton(stringResource(R.string.onboarding_limit_action), compact = true, onClick = onSetUpLimit)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -205,15 +205,12 @@ internal fun PrimaryButton(
|
||||
large: Boolean = false,
|
||||
icon: ImageVector? = null,
|
||||
fill: Boolean = false,
|
||||
progress: Float? = null,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val shownProgress by animateFloatAsState(progress?.coerceIn(0f, 1f) ?: 0f, Motion.tw(300), label = "btnProgress")
|
||||
val pillMode = LocalPillButtons.current
|
||||
val btnShape = if (pillMode) CircleShape else Shape12
|
||||
val outlined = LocalGradientOutline.current && enabled
|
||||
val frontFocus = if (main) LocalFrontFocus.current else null
|
||||
if (frontFocus != null) DisposableEffect(Unit) {
|
||||
frontFocus.primaryAttached++
|
||||
@@ -236,13 +233,7 @@ internal fun PrimaryButton(
|
||||
.graphicsLayer { alpha = if (LaunchOrigin.flooding === placed) 0f else 1f; scaleX = scale; scaleY = scale; shadowElevation = if (enabled) lift.dp.toPx() else 0f; shape = btnShape; clip = false; ambientShadowColor = pal.signal; spotShadowColor = pal.signal }
|
||||
.clip(btnShape)
|
||||
.background(if (enabled) Brush.linearGradient(listOf(colors.primary, pal.primary2)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surfaceVariant)))
|
||||
.then(if (progress != null) Modifier.drawBehind {
|
||||
val done = size.width * shownProgress
|
||||
if (enabled) drawRect(Color.Black.copy(alpha = 0.32f), topLeft = androidx.compose.ui.geometry.Offset(done, 0f), size = androidx.compose.ui.geometry.Size(size.width - done, size.height))
|
||||
else drawRect(pal.signal.copy(alpha = 0.4f), size = androidx.compose.ui.geometry.Size(done, size.height))
|
||||
} else Modifier)
|
||||
.then(if (enabled) Modifier else Modifier.border(1.dp, pal.line2, btnShape))
|
||||
.then(if (outlined) Modifier.border(2.dp, Brush.linearGradient(listOf(pal.primary2, colors.primary)), btnShape) else Modifier)
|
||||
.glideBorder(hot, btnShape, pal.signal, hotFillAlpha = 0f)
|
||||
.hoverable(src).clickable(role = Role.Button, interactionSource = src, indication = null, enabled = enabled) {
|
||||
placed[0]?.takeIf { it.isAttached }?.let { LaunchOrigin.mark(it.boundsInRoot(), placed) }
|
||||
|
||||
@@ -75,7 +75,6 @@ import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.layout.boundsInRoot
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.layout.positionInParent
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.layout.positionInRoot
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
@@ -132,9 +131,6 @@ import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.animation.core.Spring
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.foundation.layout.offset
|
||||
|
||||
internal class GameRef(val appId: Int?, val store: Store?, val storeId: String?) {
|
||||
fun game(games: List<Library.SteamGame>): Library.SteamGame? = when {
|
||||
@@ -258,18 +254,12 @@ internal fun GameDetail(
|
||||
color = MaterialTheme.colorScheme.error, maxLines = 3, overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Column {
|
||||
CompositionLocalProvider(LocalPillButtons provides true, LocalGradientOutline provides true) {
|
||||
GameActions(store, id, game, item, installed, s, a, Modifier.focusRequester(lead), compactMenu = stacked, inStore = inStore, part = ActionPart.LEAD)
|
||||
}
|
||||
Spacer(Modifier.height(LeadGap - ActionGap))
|
||||
GameCapsule(scores) { GameActions(store, id, game, item, installed, s, a, Modifier, compactMenu = stacked, inStore = inStore, part = ActionPart.REST) }
|
||||
}
|
||||
GameCapsule(scores) { GameActions(store, id, game, item, installed, s, a, Modifier.focusRequester(lead), compactMenu = stacked, inStore = inStore) }
|
||||
}
|
||||
}
|
||||
if (StoresMotion.heroLands) header() else Rise(1) { header() }
|
||||
if (tab != null) Rise(2) {
|
||||
Column(Modifier.fillMaxWidth().padding(top = ActionGap), verticalArrangement = Arrangement.spacedBy(ActionGap)) {
|
||||
Column(Modifier.fillMaxWidth().padding(top = 14.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
val labels = tabs.map { t ->
|
||||
when (t) {
|
||||
GameTab.ABOUT -> stringResource(R.string.game_tab_about)
|
||||
@@ -287,17 +277,15 @@ internal fun GameDetail(
|
||||
focusRequesters = tabs.map { tabFocus.getValue(it) }, bumpers = tabs.size > 1, compact = stacked,
|
||||
)
|
||||
Box(Modifier.fillMaxWidth().onFocusChanged { if (inPanel && !it.hasFocus) dropped++; inPanel = it.hasFocus }.testTag("game-tab-${tab.name.lowercase()}")) {
|
||||
CompositionLocalProvider(LocalRevealChecked provides false) {
|
||||
when (tab) {
|
||||
GameTab.ABOUT -> AboutTab(developer, publisher, releaseDate, description, scores, stacked) {
|
||||
if (!s.shortcutPicker) GameResourcesRow(title.takeUnless { it == id }.orEmpty(), game)
|
||||
}
|
||||
GameTab.ACHIEVEMENTS -> achievementState?.let { st -> AchievementsTab(StoreAchievements.forSource(store?.id)?.label.orEmpty(), st) }
|
||||
GameTab.LAUNCH -> if (game != null) LaunchTab(game, s, a, hopRail)
|
||||
GameTab.SAVES -> if (game != null && prefix != null) SavesTab(game, prefix, a)
|
||||
GameTab.ADDONS -> if (game != null) AddonsTab(game, addonTargets, s.sessionRunning, a)
|
||||
GameTab.INSTALL -> InstallTab(game, installed, item, store)
|
||||
when (tab) {
|
||||
GameTab.ABOUT -> AboutTab(developer, publisher, releaseDate, description, scores, stacked) {
|
||||
if (!s.shortcutPicker) GameResourcesRow(title.takeUnless { it == id }.orEmpty(), game)
|
||||
}
|
||||
GameTab.ACHIEVEMENTS -> achievementState?.let { st -> AchievementsTab(StoreAchievements.forSource(store?.id)?.label.orEmpty(), st) }
|
||||
GameTab.LAUNCH -> if (game != null) LaunchTab(game, s, a, hopRail)
|
||||
GameTab.SAVES -> if (game != null && prefix != null) SavesTab(game, prefix, a)
|
||||
GameTab.ADDONS -> if (game != null) AddonsTab(game, addonTargets, a)
|
||||
GameTab.INSTALL -> InstallTab(game, installed, item, store)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -360,22 +348,14 @@ private fun StatusChip(text: String, icon: androidx.compose.ui.graphics.vector.I
|
||||
}
|
||||
}
|
||||
|
||||
private val ActionGap = 12.dp
|
||||
private val LeadGap = 20.dp
|
||||
|
||||
@Composable
|
||||
private fun GameCapsule(scores: GameScores?, actions: @Composable () -> Unit) {
|
||||
var noActions by remember { mutableStateOf(false) }
|
||||
val shown = scores?.takeIf { it.metacritic != Lookup.None || it.hltb != Lookup.None }
|
||||
val empty = noActions && shown == null
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().then(if (empty) Modifier else Modifier.padding(top = ActionGap).glass(RoundedCornerShape(30.dp)).padding(6.dp)),
|
||||
modifier = Modifier.fillMaxWidth().glass(RoundedCornerShape(30.dp)).padding(6.dp),
|
||||
) {
|
||||
CompositionLocalProvider(LocalPillButtons provides true) {
|
||||
Box(Modifier.weight(1f).onSizeChanged { noActions = it.height == 0 }) { actions() }
|
||||
}
|
||||
shown?.let { CapsuleScores(it, Modifier.padding(start = 8.dp, end = 10.dp)) }
|
||||
CompositionLocalProvider(LocalPillButtons provides true) { Box(Modifier.weight(1f)) { actions() } }
|
||||
if (scores != null) CapsuleScores(scores, Modifier.padding(start = 8.dp, end = 10.dp))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -387,95 +367,41 @@ private fun GameTabBar(
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val scroll = rememberScrollState()
|
||||
val spans = remember(tabs.size) { androidx.compose.runtime.mutableStateListOf<IntRange?>(*arrayOfNulls<IntRange>(tabs.size)) }
|
||||
var tabHeight by remember { mutableStateOf(0) }
|
||||
var viewport by remember { mutableStateOf(0) }
|
||||
LaunchedEffect(selected, viewport) {
|
||||
val span = spans.getOrNull(selected) ?: return@LaunchedEffect
|
||||
if (viewport > 0) scroll.animateScrollTo((span.first + span.last) / 2 - viewport / 2)
|
||||
}
|
||||
Row(modifier.fillMaxWidth().glass(CircleShape).padding(4.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
if (bumpers) TabBarBumper("LB", stringResource(R.string.widgets_prev_tab), leading = true) { onSelect((selected + tabs.size - 1) % tabs.size) }
|
||||
androidx.compose.foundation.layout.BoxWithConstraints(Modifier.weight(1f).clip(if (bumpers) RoundedCornerShape(BumperFlat) else CircleShape).onSizeChanged { viewport = it.width }) {
|
||||
val share = maxWidth / tabs.size.coerceAtLeast(1)
|
||||
Box(Modifier.horizontalScroll(scroll)) {
|
||||
spans.getOrNull(selected)?.takeIf { tabHeight > 0 }?.let { span ->
|
||||
TabHighlight(span, tabHeight, flatStart = bumpers && selected == 0, flatEnd = bumpers && selected == tabs.lastIndex)
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
tabs.forEachIndexed { i, label ->
|
||||
val on = i == selected
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
val pick = { onSelect(i) }
|
||||
val shape = tabShape(flatStart = bumpers && i == 0, flatEnd = bumpers && i == tabs.lastIndex)
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.widthIn(min = share)
|
||||
.onGloballyPositioned { c -> val x = c.positionInParent().x.toInt(); val r = x..(x + c.size.width); if (spans[i] != r) spans[i] = r; tabHeight = c.size.height }
|
||||
.testTag("tab-$i")
|
||||
.then(focusRequesters?.getOrNull(i)?.let { Modifier.focusRequester(it) } ?: Modifier)
|
||||
.clip(shape)
|
||||
.background(if (hot && !on) pal.signal.copy(alpha = 0.14f) else Color.Transparent)
|
||||
.glideBorder(hot, shape, pal.signal)
|
||||
.hoverable(src).selectable(selected = on, interactionSource = src, indication = null, role = Role.Tab, onClick = pick)
|
||||
.controllerConfirm(onClick = pick)
|
||||
.padding(horizontal = 12.dp, vertical = if (compact) 8.dp else 10.dp),
|
||||
) {
|
||||
Text(
|
||||
label, fontSize = if (compact) 13.sp else 14.sp, fontWeight = if (on) FontWeight.Bold else FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
color = if (on || hot) colors.onBackground else colors.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
tabs.forEachIndexed { i, label ->
|
||||
val on = i == selected
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
val pick = { onSelect(i) }
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.weight(1f)
|
||||
.testTag("tab-$i")
|
||||
.then(focusRequesters?.getOrNull(i)?.let { Modifier.focusRequester(it) } ?: Modifier)
|
||||
.clip(CircleShape)
|
||||
.background(if (on) pal.signal.copy(alpha = 0.3f) else if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent)
|
||||
.glideBorder(hot, CircleShape, pal.signal, if (on) pal.signal.copy(alpha = 0.5f) else Color.Transparent)
|
||||
.hoverable(src).selectable(selected = on, interactionSource = src, indication = null, role = Role.Tab, onClick = pick)
|
||||
.controllerConfirm(onClick = pick)
|
||||
.padding(horizontal = 6.dp, vertical = if (compact) 8.dp else 10.dp),
|
||||
) {
|
||||
Text(
|
||||
label, fontSize = if (compact) 13.sp else 14.sp, fontWeight = if (on) FontWeight.Bold else FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
color = if (on || hot) colors.onBackground else colors.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (bumpers) TabBarBumper("RB", stringResource(R.string.widgets_next_tab), leading = false) { onSelect((selected + 1) % tabs.size) }
|
||||
}
|
||||
}
|
||||
|
||||
private val BumperFlat = 7.dp
|
||||
|
||||
@Composable
|
||||
private fun TabHighlight(span: IntRange, height: Int, flatStart: Boolean, flatEnd: Boolean) {
|
||||
val pal = LocalPalette.current
|
||||
val density = LocalDensity.current
|
||||
val spring = Motion.sp<Float>(0.8f, Spring.StiffnessMediumLow)
|
||||
val x by animateFloatAsState(span.first.toFloat(), spring, label = "tabX")
|
||||
val width by animateFloatAsState((span.last - span.first).toFloat(), spring, label = "tabWidth")
|
||||
val start by animateFloatAsState(if (flatStart) 1f else 0f, spring, label = "tabFlatStart")
|
||||
val end by animateFloatAsState(if (flatEnd) 1f else 0f, spring, label = "tabFlatEnd")
|
||||
with(density) {
|
||||
val round = (height / 2f).toDp()
|
||||
val shape = RoundedCornerShape(
|
||||
topStart = androidx.compose.ui.unit.lerp(round, BumperFlat, start), topEnd = androidx.compose.ui.unit.lerp(round, BumperFlat, end),
|
||||
bottomEnd = androidx.compose.ui.unit.lerp(round, BumperFlat, end), bottomStart = androidx.compose.ui.unit.lerp(round, BumperFlat, start),
|
||||
)
|
||||
Box(
|
||||
Modifier.offset { androidx.compose.ui.unit.IntOffset(x.toInt(), 0) }
|
||||
.size(width.toDp(), height.toDp())
|
||||
.clip(shape).background(pal.signal.copy(alpha = 0.3f)).border(1.dp, pal.signal.copy(alpha = 0.5f), shape),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun tabShape(flatStart: Boolean, flatEnd: Boolean): androidx.compose.ui.graphics.Shape {
|
||||
if (!flatStart && !flatEnd) return CircleShape
|
||||
val flat = androidx.compose.foundation.shape.CornerSize(BumperFlat)
|
||||
val round = androidx.compose.foundation.shape.CornerSize(50)
|
||||
val start = if (flatStart) flat else round
|
||||
val end = if (flatEnd) flat else round
|
||||
return RoundedCornerShape(topStart = start, topEnd = end, bottomEnd = end, bottomStart = start)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TabBarBumper(label: String, description: String, leading: Boolean, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val round = 22.dp
|
||||
val flat = BumperFlat
|
||||
val flat = 7.dp
|
||||
val cap = if (leading) RoundedCornerShape(round, flat, flat, round) else RoundedCornerShape(flat, round, round, flat)
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
@@ -507,17 +433,12 @@ private fun GameTitle(title: String, logo: Any?, titleSize: TextUnit) {
|
||||
)
|
||||
}
|
||||
|
||||
internal enum class ActionPart { ALL, LEAD, REST }
|
||||
|
||||
@Composable
|
||||
internal fun GameActions(
|
||||
store: Store?, id: String?, game: Library.SteamGame?, item: CatalogItem?, installed: InstalledStoreGame?,
|
||||
s: FrontEndState, a: FrontEndActions, leadOn: Modifier, compactMenu: Boolean = false, inStore: Boolean = false,
|
||||
part: ActionPart = ActionPart.ALL,
|
||||
) {
|
||||
val ctx = LocalContext.current
|
||||
val lead = part != ActionPart.REST
|
||||
val rest = part != ActionPart.LEAD
|
||||
val storeKey = if (store != null && id != null) "${store.id}:$id" else null
|
||||
val rawDownload = storeKey?.let { StoresState.download(it) }
|
||||
val download = rawDownload?.takeIf { it.isActive }
|
||||
@@ -527,133 +448,127 @@ internal fun GameActions(
|
||||
Actions {
|
||||
when {
|
||||
s.shortcutPicker && game != null -> {
|
||||
if (lead) PrimaryButton(stringResource(R.string.game_shortcut_choose), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn) { a.onSteamGame(game) }
|
||||
if (rest) FileButtons(game, a)
|
||||
PrimaryButton(stringResource(R.string.game_shortcut_choose), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn) { a.onSteamGame(game) }
|
||||
FileButtons(game, a)
|
||||
}
|
||||
!cloud && (game != null || installed != null) -> {
|
||||
val gone = storeKey?.let { StoresState.uninstalling[it] }
|
||||
val xboxBusy = store == Store.XBOX && id != null && XboxContent.busy(id)
|
||||
val preparing = (game?.launchKey ?: storeKey)?.let { it in s.preparingGames } == true
|
||||
if (lead) PrimaryButton(
|
||||
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),
|
||||
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)
|
||||
}
|
||||
if (rest) {
|
||||
if (game != null) {
|
||||
if (compactMenu) GameMoreMenu(game, a) else {
|
||||
FileButtons(game, a)
|
||||
GameShortcutMenu(game, a)
|
||||
if (game != null) {
|
||||
if (compactMenu) GameMoreMenu(game, a) else {
|
||||
FileButtons(game, a)
|
||||
GameShortcutMenu(game, a)
|
||||
}
|
||||
}
|
||||
if (store == Store.ITCH && installed != null) ItchUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
|
||||
if (store == Store.GAMEJOLT && installed != null) GameJoltUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
|
||||
if (store == Store.GAMEJOLT && installed != null) GameJoltVersionButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
|
||||
if (inStore && store == Store.GAMEJOLT && installed != null) {
|
||||
SecondaryButton(stringResource(R.string.stores_view_on, Store.GAMEJOLT.shortLabel)) {
|
||||
openUrl(ctx, item?.storeUrl.orEmpty().ifBlank { GameJoltApi.pageUrl("game", installed.sidecar.id) })
|
||||
}
|
||||
}
|
||||
if (store == Store.EA && installed != null) EaUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
|
||||
if (store == Store.GOG && installed != null) GogMaintenanceActions(installed)
|
||||
if (store == Store.XBOX && id != null) XboxInstalledStream(id, game?.name ?: item?.title.orEmpty(), item)
|
||||
if (store == Store.XBOX && installed != null && id != null) {
|
||||
SecondaryButton(stringResource(R.string.stores_xbox_update), enabled = download == null && !XboxRuntime.isActive(id)) {
|
||||
runCatching { XboxBackend.update(ctx, installed) }
|
||||
.onFailure { StoresState.problems[Store.XBOX] = it.message ?: ctx.getString(R.string.stores_xbox_close_first) }
|
||||
}
|
||||
SecondaryButton(stringResource(R.string.stores_xbox_manage), enabled = download == null) { XboxContent.manage(ctx, installed) }
|
||||
}
|
||||
if (store == Store.BATTLENET) {
|
||||
if (installed != null && id != null) {
|
||||
LaunchedEffect(id) { BattleNetInstall.checkUpdate(ctx, installed) }
|
||||
if (download != null) {
|
||||
SteadyDownloadChip(download)
|
||||
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(download.key) }
|
||||
else SecondaryButton(stringResource(R.string.stores_dl_resume)) { DownloadQueue.resume(ctx, download.key) }
|
||||
} else if (BattleNetInstall.updates[id] == true) {
|
||||
SecondaryButton(stringResource(R.string.bnet_update)) { BattleNetInstall.update(ctx, installed) }
|
||||
}
|
||||
}
|
||||
if (store == Store.ITCH && installed != null) ItchUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
|
||||
if (store == Store.GAMEJOLT && installed != null) GameJoltUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
|
||||
if (store == Store.GAMEJOLT && installed != null) GameJoltVersionButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
|
||||
if (inStore && store == Store.GAMEJOLT && installed != null) {
|
||||
SecondaryButton(stringResource(R.string.stores_view_on, Store.GAMEJOLT.shortLabel)) {
|
||||
openUrl(ctx, item?.storeUrl.orEmpty().ifBlank { GameJoltApi.pageUrl("game", installed.sidecar.id) })
|
||||
}
|
||||
}
|
||||
if (store == Store.EA && installed != null) EaUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
|
||||
if (store == Store.GOG && installed != null) GogMaintenanceActions(installed)
|
||||
if (store == Store.XBOX && id != null) XboxInstalledStream(id, game?.name ?: item?.title.orEmpty(), item)
|
||||
if (store == Store.XBOX && installed != null && id != null) {
|
||||
SecondaryButton(stringResource(R.string.stores_xbox_update), enabled = download == null && !XboxRuntime.isActive(id)) {
|
||||
runCatching { XboxBackend.update(ctx, installed) }
|
||||
.onFailure { StoresState.problems[Store.XBOX] = it.message ?: ctx.getString(R.string.stores_xbox_close_first) }
|
||||
}
|
||||
SecondaryButton(stringResource(R.string.stores_xbox_manage), enabled = download == null) { XboxContent.manage(ctx, installed) }
|
||||
}
|
||||
if (store == Store.BATTLENET) {
|
||||
if (installed != null && id != null) {
|
||||
LaunchedEffect(id) { BattleNetInstall.checkUpdate(ctx, installed) }
|
||||
if (download != null) {
|
||||
SteadyDownloadChip(download)
|
||||
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(download.key) }
|
||||
else SecondaryButton(stringResource(R.string.stores_dl_resume)) { DownloadQueue.resume(ctx, download.key) }
|
||||
} else if (BattleNetInstall.updates[id] == true) {
|
||||
SecondaryButton(stringResource(R.string.bnet_update)) { BattleNetInstall.update(ctx, installed) }
|
||||
}
|
||||
}
|
||||
SecondaryButton(stringResource(R.string.bnet_open)) { a.onBattleNet() }
|
||||
}
|
||||
if (game != null && !compactMenu) {
|
||||
HideButton(hideKey(game), game)
|
||||
EditArtButton(game)
|
||||
}
|
||||
SecondaryButton(stringResource(R.string.bnet_open)) { a.onBattleNet() }
|
||||
}
|
||||
if (game != null && !compactMenu) {
|
||||
HideButton(hideKey(game), game)
|
||||
EditArtButton(game)
|
||||
}
|
||||
}
|
||||
download != null -> {
|
||||
if (rest) SteadyDownloadChip(download)
|
||||
if (lead) {
|
||||
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause), modifier = leadOn) { DownloadQueue.pause(download.key) }
|
||||
else PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) { DownloadQueue.resume(ctx, download.key) }
|
||||
}
|
||||
if (rest) ConfirmButton(stringResource(R.string.stores_dl_cancel), stringResource(R.string.stores_dl_cancel_confirm)) { DownloadQueue.cancel(ctx, download.key) }
|
||||
SteadyDownloadChip(download)
|
||||
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause), modifier = leadOn) { DownloadQueue.pause(download.key) }
|
||||
else PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) { DownloadQueue.resume(ctx, download.key) }
|
||||
ConfirmButton(stringResource(R.string.stores_dl_cancel), stringResource(R.string.stores_dl_cancel_confirm)) { DownloadQueue.cancel(ctx, download.key) }
|
||||
}
|
||||
failed != null -> {
|
||||
if (rest) ActionChip(stringResource(R.string.stores_dl_failed), ok = false)
|
||||
if (lead) PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) {
|
||||
ActionChip(stringResource(R.string.stores_dl_failed), ok = false)
|
||||
PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) {
|
||||
if (item != null) StoresState.requestInstall(ctx, item) else DownloadQueue.retry(ctx, failed.key)
|
||||
}
|
||||
if (rest) ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { DownloadQueue.clear(ctx, failed.key) }
|
||||
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { DownloadQueue.clear(ctx, failed.key) }
|
||||
}
|
||||
cloud -> {
|
||||
val cloudId = game.storeId.orEmpty()
|
||||
if (lead) XboxStreamButton(cloudId, game.name, main = true, modifier = leadOn)
|
||||
if (rest && item?.installable == true && item.xboxPc) {
|
||||
XboxStreamButton(cloudId, game.name, main = true, modifier = leadOn)
|
||||
if (item?.installable == true && item.xboxPc) {
|
||||
SecondaryButton(
|
||||
if (StoresState.isUnfinished(item)) stringResource(R.string.stores_resume_install)
|
||||
else if (downloadBytes > 0) stringResource(R.string.stores_install_size, formatBytes(downloadBytes))
|
||||
else stringResource(R.string.stores_install),
|
||||
) { StoresState.requestInstall(ctx, item) }
|
||||
}
|
||||
if (rest && item != null && StoresState.isUnfinished(item)) ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) }
|
||||
if (rest) XboxLibraryButton(cloudId, item)
|
||||
if (item != null && StoresState.isUnfinished(item)) ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) }
|
||||
XboxLibraryButton(cloudId, item)
|
||||
}
|
||||
store == Store.BATTLENET && item != null -> if (lead) InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) }
|
||||
store == Store.BATTLENET && item != null -> InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) }
|
||||
store == Store.XBOX && item != null && !item.xboxPc && item.xboxCloud -> {
|
||||
if (lead) XboxStreamButton(item.id, item.title, main = true, modifier = leadOn)
|
||||
if (rest) XboxLibraryButton(item.id, item)
|
||||
XboxStreamButton(item.id, item.title, main = true, modifier = leadOn)
|
||||
XboxLibraryButton(item.id, item)
|
||||
}
|
||||
item?.installable == true && StoresState.isUnfinished(item) -> {
|
||||
if (lead) InstallButton(stringResource(R.string.stores_resume_install), leadOn) { StoresState.requestInstall(ctx, item) }
|
||||
if (rest) ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) }
|
||||
InstallButton(stringResource(R.string.stores_resume_install), leadOn) { StoresState.requestInstall(ctx, item) }
|
||||
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) }
|
||||
}
|
||||
item?.installable == true -> {
|
||||
if (lead) InstallButton(
|
||||
InstallButton(
|
||||
if (downloadBytes > 0) stringResource(R.string.stores_install_size, formatBytes(downloadBytes)) else stringResource(R.string.stores_install),
|
||||
leadOn,
|
||||
) { StoresState.requestInstall(ctx, item) }
|
||||
if (rest && store == Store.XBOX && item.xboxCloud) {
|
||||
if (store == Store.XBOX && item.xboxCloud) {
|
||||
XboxStreamButton(item.id, item.title)
|
||||
XboxLibraryButton(item.id, item)
|
||||
}
|
||||
if (rest && !item.accessible) SecondaryButton(buyLabel(item)) { openStoreUrl(ctx, item) }
|
||||
if (!item.accessible) SecondaryButton(buyLabel(item)) { openStoreUrl(ctx, item) }
|
||||
}
|
||||
item != null && (item.store == Store.ITCH || item.store == Store.GAMEJOLT) && item.isFree -> {
|
||||
if (lead) InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) }
|
||||
if (rest) SecondaryButton(stringResource(R.string.stores_view_on, item.store.shortLabel)) { openStoreUrl(ctx, item) }
|
||||
InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) }
|
||||
SecondaryButton(stringResource(R.string.stores_view_on, item.store.shortLabel)) { openStoreUrl(ctx, item) }
|
||||
}
|
||||
item != null && item.isFree -> if (lead) {
|
||||
item != null && item.isFree -> {
|
||||
val adding = StoresState.claiming[item.key] == true
|
||||
PrimaryButton(stringResource(if (adding) R.string.stores_claiming else R.string.stores_get_free), enabled = !adding, main = true, modifier = leadOn) {
|
||||
if (StoresState.canClaim(item)) StoresState.claim(ctx, item) { openStoreUrl(ctx, item) } else openStoreUrl(ctx, item)
|
||||
}
|
||||
}
|
||||
item != null -> if (lead) PrimaryButton(buyLabel(item), main = true, modifier = leadOn) { openStoreUrl(ctx, item) }
|
||||
item != null -> PrimaryButton(buyLabel(item), main = true, modifier = leadOn) { openStoreUrl(ctx, item) }
|
||||
}
|
||||
if (rest) {
|
||||
val entryKey = game?.let(::hideKey) ?: storeKey
|
||||
if (!s.shortcutPicker && entryKey != null && (game == null || cloud)) HideButton(entryKey, game)
|
||||
if (cloud && (download != null || failed != null)) {
|
||||
XboxStreamButton(game.storeId.orEmpty(), game.name)
|
||||
XboxLibraryButton(game.storeId.orEmpty(), item)
|
||||
}
|
||||
BusyChip(s)
|
||||
val entryKey = game?.let(::hideKey) ?: storeKey
|
||||
if (!s.shortcutPicker && entryKey != null && (game == null || cloud)) HideButton(entryKey, game)
|
||||
if (cloud && (download != null || failed != null)) {
|
||||
XboxStreamButton(game.storeId.orEmpty(), game.name)
|
||||
XboxLibraryButton(game.storeId.orEmpty(), item)
|
||||
}
|
||||
BusyChip(s)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1047,11 +962,9 @@ private fun SavesTab(g: Library.SteamGame, prefix: File, a: FrontEndActions) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, sessionRunning: Boolean, a: FrontEndActions) {
|
||||
private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, a: FrontEndActions) {
|
||||
var browsing by remember(g.gameId) { mutableStateOf<WowAddons.Target?>(null) }
|
||||
val curseForge = CurseForgeApp.find(UserAppsState.items)
|
||||
val link = rememberCurseLink(curseForge, sessionRunning)
|
||||
browsing?.let { AddonBrowserDialog(targets, it, curseForge, link) { browsing = null } }
|
||||
browsing?.let { AddonBrowserDialog(targets, it) { browsing = null } }
|
||||
Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
CurseForgeEntry(a)
|
||||
targets.forEach { target ->
|
||||
@@ -1062,12 +975,6 @@ private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, ses
|
||||
val updates by produceState(emptyMap<String, WowAddonCatalog.Addon>(), names) {
|
||||
value = withContext(Dispatchers.IO) { WowAddonCatalog.updates(context, names, target) }
|
||||
}
|
||||
val scanKey = link?.generation to WowAddons.imports
|
||||
val managed by produceState(emptyMap<String, CurseForgeApp.Project>(), link, target.addOns, scanKey) {
|
||||
value = if (link == null) emptyMap() else withContext(Dispatchers.IO) {
|
||||
runCatching { CurseForgeApp.byFolder(link.installed(context, target, scanKey)) }.getOrDefault(emptyMap())
|
||||
}
|
||||
}
|
||||
if (targets.size > 1) SectionLabel(target.flavor)
|
||||
MenuItem(stringResource(R.string.addons_download), checked = false) { browsing = target }
|
||||
MenuItem(
|
||||
@@ -1078,7 +985,7 @@ private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, ses
|
||||
target.addOns.mkdirs()
|
||||
a.onBrowseFiles(target.addOns)
|
||||
}
|
||||
names.forEach { item -> key(target.addOns, item.name) { AddonRow(item, updates[item.name], target, a, link?.let { l -> managed[item.name.lowercase()]?.let { it to l } }) } }
|
||||
names.forEach { item -> key(target.addOns, item.name) { AddonRow(item, updates[item.name], target, a) } }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1132,10 +1039,8 @@ private fun CurseForgeEntry(a: FrontEndActions) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun AddonRow(item: WowAddons.Installed, wowiUpdate: WowAddonCatalog.Addon?, target: WowAddons.Target, a: FrontEndActions, curse: Pair<CurseForgeApp.Project, CurseLink>? = null) {
|
||||
private fun AddonRow(item: WowAddons.Installed, update: WowAddonCatalog.Addon?, target: WowAddons.Target, a: FrontEndActions) {
|
||||
val name = item.name
|
||||
val update = wowiUpdate.takeIf { curse == null }
|
||||
val outdated = update != null || curse?.first?.update == true
|
||||
var asking by remember(target.addOns, name) { mutableStateOf(false) }
|
||||
var progress by remember(target.addOns, name) { mutableStateOf<Int?>(null) }
|
||||
val context = LocalContext.current
|
||||
@@ -1145,33 +1050,26 @@ internal fun AddonRow(item: WowAddons.Installed, wowiUpdate: WowAddonCatalog.Add
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(start = 16.dp, top = 2.dp, bottom = 2.dp)) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(name, fontSize = 14.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
val detail = listOfNotNull(item.version, if (outdated) stringResource(R.string.upd_available) else null).joinToString(" · ")
|
||||
val detail = listOfNotNull(item.version, update?.let { stringResource(R.string.upd_available) }).joinToString(" · ")
|
||||
if (detail.isNotEmpty()) Text(
|
||||
progress?.let { stringResource(R.string.ctrl_percent, it) } ?: detail, fontSize = 12.sp,
|
||||
color = if (outdated) LocalPalette.current.signal else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
color = if (update != null) LocalPalette.current.signal else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
if (outdated && !SessionState.running) IconAction(Icons.Outlined.Download, stringResource(R.string.common_update), "addon:update:${target.flavor}:$name", enabled = progress == null) {
|
||||
if (update != null && !SessionState.running) IconAction(Icons.Outlined.Download, stringResource(R.string.common_update), "addon:update:${target.flavor}:$name", enabled = progress == null) {
|
||||
progress = 0
|
||||
scope.launch {
|
||||
val message = withContext(Dispatchers.IO) {
|
||||
if (curse != null) {
|
||||
val (project, link) = curse
|
||||
val done = runCatching { link.change(context, target) { CurseForgeApp.update(context, it.inspector, it.guid, project.id) } }.getOrDefault(false)
|
||||
WowAddons.changed()
|
||||
if (done) context.getString(R.string.user_apps_updated, name) else context.getString(R.string.stores_dl_failed_reason, name)
|
||||
} else update?.let { installAddon(context, it, target) { pct -> scope.launch { progress = pct } }.first }
|
||||
}
|
||||
val message = withContext(Dispatchers.IO) { installAddon(context, update, target) { pct -> scope.launch { progress = pct } } }
|
||||
progress = null
|
||||
if (message != null) android.widget.Toast.makeText(context, message, android.widget.Toast.LENGTH_LONG).show()
|
||||
android.widget.Toast.makeText(context, message.first, android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
if (!SessionState.running) IconAction(Icons.Outlined.Delete, if (curse != null) stringResource(R.string.common_uninstall) else delete, "addon:delete:${target.flavor}:$name", danger = true) { asking = true }
|
||||
if (!SessionState.running) IconAction(Icons.Outlined.Delete, delete, "addon:delete:${target.flavor}:$name", danger = true) { asking = true }
|
||||
}
|
||||
if (asking) ConfirmDialog(
|
||||
title = if (curse != null) stringResource(R.string.stores_uninstall_title, name) else stringResource(R.string.games_delete_addon_title, name),
|
||||
title = stringResource(R.string.games_delete_addon_title, name),
|
||||
text = stringResource(R.string.games_delete_addon_body),
|
||||
confirm = if (curse != null) stringResource(R.string.common_uninstall) else delete,
|
||||
confirm = delete,
|
||||
onConfirm = { a.onAddonDelete(target, name) },
|
||||
onDismiss = { asking = false },
|
||||
)
|
||||
|
||||
@@ -58,7 +58,6 @@ import coil.size.Precision
|
||||
import kotlin.math.max
|
||||
|
||||
internal val LocalPillButtons = compositionLocalOf { false }
|
||||
internal val LocalGradientOutline = compositionLocalOf { false }
|
||||
|
||||
internal class GlassBackdrop {
|
||||
var painter: Painter? = null
|
||||
|
||||
@@ -60,7 +60,7 @@ internal fun gameResources(title: String, game: Library.SteamGame?): List<GameRe
|
||||
internal fun GameResourcesRow(title: String, game: Library.SteamGame?, modifier: Modifier = Modifier) {
|
||||
val links = remember(title, game) { gameResources(title, game) }
|
||||
if (links.isEmpty()) return
|
||||
FlowRow(modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
FlowRow(modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
links.forEach { ResourceLink(it) }
|
||||
}
|
||||
}
|
||||
@@ -79,14 +79,14 @@ private fun ResourceLink(link: GameResource) {
|
||||
val tint = if (hot) pal.signal else pal.onSurfaceVariant
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp),
|
||||
modifier = Modifier.paneItem("resource:${link.label}").heightIn(min = 34.dp).clip(shape)
|
||||
modifier = Modifier.paneItem("resource:${link.label}").heightIn(min = 44.dp).clip(shape)
|
||||
.background(if (hot) pal.signal.copy(alpha = 0.14f) else if (glass) Color.White.copy(alpha = 0.07f) else Color.Transparent)
|
||||
.glideBorder(hot, shape, pal.signal, restColor = if (glass) Color.White.copy(alpha = 0.12f) else Color.Transparent)
|
||||
.semantics { contentDescription = description }
|
||||
.hoverable(source).clickable(interactionSource = source, indication = LocalIndication.current, role = Role.Button, onClick = open)
|
||||
.controllerConfirm(onClick = open).padding(horizontal = if (glass) 11.dp else 8.dp),
|
||||
.controllerConfirm(onClick = open).padding(horizontal = if (glass) 14.dp else 8.dp),
|
||||
) {
|
||||
Text(label, fontSize = 12.sp, fontWeight = FontWeight.Medium, color = if (glass && !hot) MaterialTheme.colorScheme.onBackground else tint, maxLines = 1)
|
||||
Text(label, fontSize = if (glass) 13.sp else 12.sp, fontWeight = FontWeight.Medium, color = if (glass && !hot) MaterialTheme.colorScheme.onBackground else tint, maxLines = 1)
|
||||
Icon(Icons.AutoMirrored.Filled.OpenInNew, contentDescription = null, tint = tint.copy(alpha = 0.65f), modifier = Modifier.size(11.dp))
|
||||
}
|
||||
}
|
||||
@@ -267,6 +267,12 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
|
||||
}
|
||||
}
|
||||
InputPage.SOURCE -> {
|
||||
if (role == InputRole.PRIMARY) SettingsGroup(stringResource(R.string.input_screen_visibility)) {
|
||||
ChoiceRow(host, "controller-osc", stringResource(R.string.mode_osc), stringResource(R.string.input_visibility_shared),
|
||||
listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always),
|
||||
SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)),
|
||||
oscMode) { SessionPrefs.setOscMode(context, it); oscMode = it; onChanged() }
|
||||
}
|
||||
if (layout != null) SettingsGroup(stringResource(R.string.ctrl_layout)) {
|
||||
if (layout.editable) InputNavigationRow(stringResource(R.string.input_edit_layout), layout.name, Modifier.testTag("input-surface-${role.name.lowercase()}")) { surface = true }
|
||||
else InputHint(layout.name)
|
||||
@@ -282,12 +288,6 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
|
||||
}
|
||||
if (role == InputRole.SECONDARY) InputHint(stringResource(R.string.input_second_screen_enable))
|
||||
}
|
||||
if (role == InputRole.PRIMARY) SettingsGroup(stringResource(R.string.input_screen_visibility)) {
|
||||
ChoiceRow(host, "controller-osc", stringResource(R.string.mode_osc), stringResource(R.string.input_visibility_shared),
|
||||
listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always),
|
||||
SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)),
|
||||
oscMode) { SessionPrefs.setOscMode(context, it); oscMode = it; onChanged() }
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.input_assign_actions)) {
|
||||
val users = library.usersOfBindings(preset.id)
|
||||
if (users.size > 1) InputHint(stringResource(R.string.input_shared_with, users.filterNot { it.id == profileId }.joinToString { it.name }))
|
||||
|
||||
@@ -90,7 +90,6 @@ import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.layout.boundsInRoot
|
||||
import androidx.compose.ui.layout.layout
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
@@ -914,6 +913,7 @@ private fun LibraryFilters(sources: List<String>, source: String, onSource: (Str
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 2.dp),
|
||||
) {
|
||||
if (manage) ManageStoresChip()
|
||||
Box(Modifier.weight(1f).edgeFade(scroll).horizontalScroll(scroll)) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.focusGroup()) {
|
||||
for (id in keys) {
|
||||
@@ -945,7 +945,6 @@ private fun LibraryFilters(sources: List<String>, source: String, onSource: (Str
|
||||
}
|
||||
if (highlighted in keys) ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown)
|
||||
}
|
||||
if (manage) ManageStoresChip()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1122,22 +1121,14 @@ internal fun ArtCard(
|
||||
}
|
||||
val showName = LibraryDisplay.title || hot
|
||||
val showDetail = LibraryDisplay.size || hot
|
||||
if (showName || showDetail) {
|
||||
val top = with(androidx.compose.ui.platform.LocalDensity.current) { 20.dp.roundToPx() }
|
||||
val bottom = with(androidx.compose.ui.platform.LocalDensity.current) { (if (download != null) 14.dp else 6.dp).roundToPx() }
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(1.dp),
|
||||
modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth()
|
||||
.background(Brush.verticalGradient(0f to Color.Transparent, 0.6f to Color.Black.copy(alpha = 0.78f), 1f to Color.Black.copy(alpha = 0.92f)))
|
||||
.layout { measurable, constraints ->
|
||||
val inner = measurable.measure(constraints)
|
||||
if (inner.height == 0) layout(inner.width, 0) {} else layout(inner.width, inner.height + top + bottom) { inner.place(0, top) }
|
||||
}
|
||||
.padding(horizontal = 8.dp),
|
||||
) {
|
||||
if (showName) Text(title, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = if (hot) 2 else 1, overflow = TextOverflow.Ellipsis, lineHeight = 13.sp)
|
||||
if (showDetail) detail()
|
||||
}
|
||||
if (showName || showDetail) Column(
|
||||
verticalArrangement = Arrangement.spacedBy(1.dp),
|
||||
modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth()
|
||||
.background(Brush.verticalGradient(0f to Color.Transparent, 0.6f to Color.Black.copy(alpha = 0.78f), 1f to Color.Black.copy(alpha = 0.92f)))
|
||||
.padding(start = 8.dp, end = 8.dp, top = 20.dp, bottom = if (download != null) 14.dp else 6.dp),
|
||||
) {
|
||||
if (showName) Text(title, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = if (hot) 2 else 1, overflow = TextOverflow.Ellipsis, lineHeight = 13.sp)
|
||||
if (showDetail) detail()
|
||||
}
|
||||
if (download != null) Box(Modifier.align(Alignment.BottomCenter).padding(start = 6.dp, end = 6.dp, bottom = 5.dp)) {
|
||||
ProgressBarThin(download.fraction, paused = download.state == DownloadState.PAUSED, verify = download.stage == DownloadStage.VERIFY)
|
||||
|
||||
@@ -126,8 +126,6 @@ internal object SheetTab {
|
||||
const val LIBRARY = "library"
|
||||
const val STEAM = "steam"
|
||||
const val FILES = "files"
|
||||
const val DECKY = "decky"
|
||||
const val BOOT_MOVIES = "boot-movies"
|
||||
}
|
||||
|
||||
internal fun sheetTop(paneH: Float, buttonH: Float, minAbove: Float, ride: Float): Float =
|
||||
@@ -191,7 +189,6 @@ internal fun LiftHero(
|
||||
onOpenChange: (Boolean) -> Unit = {},
|
||||
start: Dp = 44.dp,
|
||||
bottom: Dp = 44.dp,
|
||||
onTextBounds: (Rect) -> Unit = {},
|
||||
drop: DropSheetState? = null,
|
||||
overlay: @Composable BoxWithConstraintsScope.(lifted: () -> Float) -> Unit = {},
|
||||
) {
|
||||
@@ -576,7 +573,7 @@ internal fun LiftHero(
|
||||
}
|
||||
}
|
||||
|
||||
Column(Modifier.align(Alignment.BottomStart).padding(start = start, bottom = bottom, end = 20.dp).onGloballyPositioned { onTextBounds(it.boundsInRoot()) }) {
|
||||
Column(Modifier.align(Alignment.BottomStart).padding(start = start, bottom = bottom, end = 20.dp)) {
|
||||
Box(Modifier.graphicsLayer { alpha = 1f - wallSink() }) { words() }
|
||||
Spacer(Modifier.height(18.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
|
||||
@@ -57,7 +57,7 @@ internal fun ManageDrawerPages(offeredNow: List<SessionDrawerPage>, modifier: Mo
|
||||
SortableRows(
|
||||
rows = { current.map { it.name } },
|
||||
commit = { names -> DrawerPages.rearrange(ctx, names.mapNotNull { n -> current.firstOrNull { it.name == n } }) },
|
||||
movable = { it != SessionDrawerPage.MORE.name },
|
||||
movable = { true },
|
||||
rowHeight = STORE_ROW, handleWidth = STORE_HANDLE,
|
||||
releaseSignal = releaseSignal,
|
||||
onGrab = { before -> DrawerPages.heldFrom = before?.mapNotNull { n -> current.firstOrNull { it.name == n } } },
|
||||
@@ -66,8 +66,6 @@ internal fun ManageDrawerPages(offeredNow: List<SessionDrawerPage>, modifier: Mo
|
||||
},
|
||||
) { name, held, offset, hint, rowModifier, onFocus ->
|
||||
val page = current.first { it.name == name }
|
||||
// The same divider the launcher's Edit tabs uses: pages above it are tabs, pages below it are kept in More.
|
||||
if (page == SessionDrawerPage.MORE) { MoreLine(STORE_ROW); return@SortableRows }
|
||||
val shown = page !in DrawerPages.hidden
|
||||
val pal = LocalPalette.current
|
||||
val label = stringResource(page.title)
|
||||
|
||||
@@ -202,7 +202,7 @@ internal fun SideSheet(open: Boolean, onClose: () -> Unit, returnFocus: FocusReq
|
||||
if (!pad) return@LaunchedEffect
|
||||
repeat(60) {
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
if (holds || !open || Steps.open) return@LaunchedEffect
|
||||
if (holds || !open) return@LaunchedEffect
|
||||
runCatching { inside.requestFocus() }
|
||||
}
|
||||
}
|
||||
@@ -210,7 +210,7 @@ internal fun SideSheet(open: Boolean, onClose: () -> Unit, returnFocus: FocusReq
|
||||
Modifier.width(width).fillMaxHeight()
|
||||
.onFocusChanged { holds = it.hasFocus }
|
||||
.focusRequester(inside)
|
||||
.focusProperties { exit = { if (open && !Steps.open) FocusRequester.Cancel else FocusRequester.Default } }
|
||||
.focusProperties { exit = { if (open) FocusRequester.Cancel else FocusRequester.Default } }
|
||||
.focusGroup()
|
||||
.background(MaterialTheme.colorScheme.background)
|
||||
.border(1.dp, pal.line).padding(horizontal = 18.dp, vertical = 16.dp).testTag(tag),
|
||||
|
||||
@@ -113,9 +113,6 @@ class ModeSettings(
|
||||
val deckyDownloadingBinary: Boolean = false,
|
||||
val deckyEnabled: Boolean = false,
|
||||
val deckySessionRunning: Boolean = false,
|
||||
val deckyPlugins: List<com.droiddeck.launcher.runtime.DeckyStore.Installed> = emptyList(),
|
||||
val deckyStore: List<com.droiddeck.launcher.runtime.DeckyStore.Plugin>? = null,
|
||||
val deckyStoreFailed: Boolean = false,
|
||||
)
|
||||
|
||||
class ModeSettingsActions(
|
||||
@@ -174,9 +171,6 @@ class ModeSettingsActions(
|
||||
val onDeckyEnabled: (Boolean) -> Unit = {},
|
||||
val onDeckyUninstall: () -> Unit = {},
|
||||
val onPickDeckyPluginZip: () -> Unit = {},
|
||||
val onDeckyStoreRefresh: () -> Unit = {},
|
||||
val onDeckyStoreInstall: (com.droiddeck.launcher.runtime.DeckyStore.Plugin) -> Unit = {},
|
||||
val onDeckyRemove: (com.droiddeck.launcher.runtime.DeckyStore.Installed) -> Unit = {},
|
||||
val onDismiss: () -> Unit,
|
||||
)
|
||||
|
||||
@@ -226,8 +220,6 @@ class SheetExtras(
|
||||
fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: SheetExtras = SheetExtras()) {
|
||||
val steam = s.mode == SessionService.MODE_STEAM
|
||||
val host = rememberMenuHost()
|
||||
if (tab == SheetTab.DECKY) { DeckyGroups(s, a, host); return }
|
||||
if (tab == SheetTab.BOOT_MOVIES) { if (s.bootMovie != null) BootMovieGroup(s, a, host); return }
|
||||
Text(
|
||||
stringResource(when (s.mode) {
|
||||
SessionService.MODE_STEAM -> R.string.sheet_scope_steam
|
||||
@@ -517,6 +509,75 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
}
|
||||
if (tab == SheetTab.STEAM && steam) {
|
||||
extras.account(host)
|
||||
SettingsGroup(stringResource(R.string.mode_decky)) {
|
||||
val updateAvailable = s.deckyInstalled != null && s.deckyLatestRelease != null &&
|
||||
s.deckyInstalled != s.deckyLatestRelease.tag
|
||||
val status = when {
|
||||
s.deckyStage != null -> s.deckyStage
|
||||
s.deckyChecking -> stringResource(R.string.mode_decky_checking)
|
||||
s.deckyInstalled == null && s.deckyLatestRelease != null -> stringResource(R.string.mode_decky_ready, s.deckyLatestRelease.tag)
|
||||
s.deckyInstalled == null -> stringResource(R.string.mode_decky_none)
|
||||
s.deckyLatestRelease == null -> stringResource(R.string.mode_decky_installed, s.deckyInstalled)
|
||||
updateAvailable -> stringResource(R.string.mode_decky_update, s.deckyLatestRelease.tag)
|
||||
else -> stringResource(R.string.mode_decky_current, s.deckyInstalled)
|
||||
}
|
||||
SettingsRow(stringResource(R.string.mode_decky_loader), status) {
|
||||
val action = when {
|
||||
s.deckyStage != null -> stringResource(R.string.common_working)
|
||||
s.deckyChecking -> stringResource(R.string.common_checking)
|
||||
s.deckyInstalled == null && s.deckyLatestRelease != null -> stringResource(R.string.mode_decky_install_latest)
|
||||
s.deckyInstalled != null && updateAvailable -> stringResource(R.string.common_update)
|
||||
else -> stringResource(R.string.common_check)
|
||||
}
|
||||
Row(horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(6.dp)) {
|
||||
SecondaryButton(
|
||||
action,
|
||||
enabled = s.deckyStage == null && !s.deckyChecking && !s.deckySessionRunning,
|
||||
) {
|
||||
if (s.deckyLatestRelease == null || (s.deckyInstalled != null && !updateAvailable)) a.onDeckyCheck()
|
||||
else s.deckyLatestRelease?.let(a.onDeckyInstall)
|
||||
}
|
||||
if (s.deckyInstalled != null) DeckyUninstall(enabled = s.deckyStage == null && !s.deckySessionRunning, onUninstall = a.onDeckyUninstall)
|
||||
}
|
||||
}
|
||||
ChoiceRow(
|
||||
host, "decky-channel", stringResource(R.string.decky_channel),
|
||||
stringResource(R.string.decky_channel_hint),
|
||||
listOf(
|
||||
DeckyManager.BRANCH_STABLE to stringResource(R.string.decky_channel_stable),
|
||||
DeckyManager.BRANCH_PRERELEASE to stringResource(R.string.decky_channel_prerelease),
|
||||
) + if (s.deckyBranch == DeckyManager.BRANCH_TESTING) listOf(
|
||||
DeckyManager.BRANCH_TESTING to stringResource(R.string.decky_channel_testing),
|
||||
) else emptyList(),
|
||||
s.deckyBranch,
|
||||
enabled = s.deckyStage == null && !s.deckySessionRunning,
|
||||
onPick = a.onDeckyBranch,
|
||||
)
|
||||
if (s.deckyInstalled != null) ToggleRow(
|
||||
host, "decky-enabled", stringResource(R.string.mode_decky),
|
||||
if (s.deckyEnabled) stringResource(R.string.mode_decky_on)
|
||||
else stringResource(R.string.mode_decky_off),
|
||||
s.deckyEnabled,
|
||||
enabled = !s.deckySessionRunning && s.deckyStage == null,
|
||||
onChange = a.onDeckyEnabled,
|
||||
)
|
||||
SettingsRow(
|
||||
stringResource(R.string.mode_decky_plugins),
|
||||
stringResource(R.string.mode_decky_plugins_hint),
|
||||
) {
|
||||
SecondaryButton(
|
||||
if (s.deckyStage != null && s.deckyDownloadingBinary) stringResource(R.string.mode_decky_plugin_downloading) else stringResource(R.string.mode_decky_plugin_install_zip),
|
||||
enabled = s.deckyInstalled != null && s.deckyStage == null && !s.deckySessionRunning,
|
||||
onClick = a.onPickDeckyPluginZip,
|
||||
)
|
||||
}
|
||||
if (s.deckyStage != null && s.deckyPercent >= 0) {
|
||||
LinearProgressIndicator(
|
||||
progress = { s.deckyPercent / 100f },
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.mode_client)) {
|
||||
ToggleRow(
|
||||
host, "mangoapp", stringResource(R.string.mode_mangoapp),
|
||||
@@ -546,6 +607,7 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
onPick = a.onSteamClientArch,
|
||||
)
|
||||
}
|
||||
if (s.bootMovie != null) BootMovieGroup(s, a, host)
|
||||
if (s.integration != null) SteamIntegrationGroup(s.integration,
|
||||
onFeature = a.onIntegration, onAppInfo = a.onIntegrationAppInfo, onLocation = a.onIntegrationLocation)
|
||||
}
|
||||
@@ -607,7 +669,7 @@ internal fun DeckyZipWarningDialog(onConfirm: () -> Unit, onCancel: () -> Unit)
|
||||
private const val DECKY_ZIP_WARNING_SECONDS = 5
|
||||
|
||||
@Composable
|
||||
internal fun DeckyUninstall(enabled: Boolean, onUninstall: () -> Unit) {
|
||||
private fun DeckyUninstall(enabled: Boolean, onUninstall: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val label = stringResource(R.string.common_uninstall)
|
||||
val title = stringResource(R.string.mode_decky_remove_title)
|
||||
|
||||
@@ -81,7 +81,7 @@ private fun MoreTile(s: FrontEndState, key: String, first: Boolean, modifier: Mo
|
||||
.then(if (first) Modifier.paneEntry() else Modifier.paneItem("more:$key"))
|
||||
.testTag("more-$key")
|
||||
.height(112.dp).clip(shape)
|
||||
.background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.12f)) else Modifier)
|
||||
.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)
|
||||
|
||||
@@ -26,10 +26,10 @@ internal object DeveloperTools {
|
||||
|
||||
internal object NavTabs {
|
||||
const val MORE = "more"
|
||||
val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent")
|
||||
val DEFAULT_SHELVED = setOf("soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent")
|
||||
val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", "components", "storage", "sync", "android-apps", "agent")
|
||||
val DEFAULT_SHELVED = setOf("stores", "soundtracks", "components", "storage", "sync", "android-apps", "agent")
|
||||
val DEFAULT_HIDDEN = setOf("android-apps", "agent")
|
||||
private val SHELVED_WHEN_NEW = setOf("storage", "sync", "decky", "boot-movies", "android-apps", "agent")
|
||||
private val SHELVED_WHEN_NEW = setOf("storage", "sync", "android-apps", "agent")
|
||||
private val OLD_ORDER = listOf("steam", "games", "soundtracks", "stores", "downloads", "desktop", "agent", "components", "android-apps", "storage", "sync", "setup", "updates")
|
||||
private val OLD_SHELVED = setOf("soundtracks", "agent", "storage", "sync")
|
||||
private const val LAYOUT_VERSION = 2
|
||||
|
||||
@@ -50,7 +50,9 @@ fun PhantomProcessGatePage(
|
||||
onDismiss: () -> Unit,
|
||||
onOpenDeveloperOptions: () -> Unit,
|
||||
onFixWithWirelessDebugging: () -> Unit,
|
||||
onEnterAddressManually: () -> Unit,
|
||||
onCopyCommand: () -> Unit,
|
||||
onOpenNotificationSettings: () -> Unit,
|
||||
) {
|
||||
BackHandler(onBack = onDismiss)
|
||||
val context = LocalContext.current
|
||||
@@ -80,11 +82,11 @@ fun PhantomProcessGatePage(
|
||||
val fix: @Composable ColumnScope.() -> Unit = {
|
||||
if (sideQuest) SideQuestGroup(compact, onCopyCommand)
|
||||
else FixGroup(hasToggle, stage, environment, compact, applyingSavedPairing, onOpenDeveloperOptions, onFixWithWirelessDebugging,
|
||||
onCancel = { WirelessAdbPairingService.cancel(context) })
|
||||
onOpenNotificationSettings, onCancel = { WirelessAdbPairingService.cancel(context) })
|
||||
}
|
||||
val side: @Composable ColumnScope.() -> Unit = {
|
||||
StatusGroup(status, compact)
|
||||
if (!sideQuest) OtherWays(hasToggle, compact, onOpenDeveloperOptions, onFixWithWirelessDebugging, onCopyCommand)
|
||||
if (!sideQuest) OtherWays(hasToggle, compact, onOpenDeveloperOptions, onFixWithWirelessDebugging, onEnterAddressManually, onCopyCommand)
|
||||
}
|
||||
if (wide) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.widthIn(max = 900.dp).fillMaxWidth()) {
|
||||
@@ -102,16 +104,15 @@ fun PhantomProcessGatePage(
|
||||
}
|
||||
}
|
||||
|
||||
private data class GateEnvironment(val onWifi: Boolean) {
|
||||
private data class GateEnvironment(val onWifi: Boolean, val notifications: Boolean) {
|
||||
companion object {
|
||||
fun read(context: Context): GateEnvironment {
|
||||
val connectivity = context.getSystemService(ConnectivityManager::class.java)
|
||||
val wifi = runCatching {
|
||||
connectivity?.allNetworks?.any { network ->
|
||||
connectivity.getNetworkCapabilities(network)?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true
|
||||
} == true
|
||||
connectivity?.getNetworkCapabilities(connectivity.activeNetwork)
|
||||
?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true
|
||||
}.getOrDefault(true)
|
||||
return GateEnvironment(wifi)
|
||||
return GateEnvironment(wifi, WirelessAdbPairingService.notificationsEnabled(context))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -125,6 +126,7 @@ private fun FixGroup(
|
||||
applyingSavedPairing: Boolean,
|
||||
onOpenDeveloperOptions: () -> Unit,
|
||||
onFixWithWirelessDebugging: () -> Unit,
|
||||
onOpenNotificationSettings: () -> Unit,
|
||||
onCancel: () -> Unit,
|
||||
) {
|
||||
val pairing = stage is Stage.Waiting || stage is Stage.CodeNeeded || stage is Stage.Working
|
||||
@@ -142,7 +144,6 @@ private fun FixGroup(
|
||||
hasToggle -> {
|
||||
Body(stringResource(R.string.gate_toggle_steps))
|
||||
PrimaryButton(stringResource(R.string.gate_open_dev), compact = compact, onClick = onOpenDeveloperOptions)
|
||||
SecondaryButton(stringResource(R.string.gate_use_wireless_instead), compact = compact, enabled = environment.onWifi, onClick = onFixWithWirelessDebugging)
|
||||
}
|
||||
else -> {
|
||||
Body(stringResource(R.string.gate_no_toggle))
|
||||
@@ -150,7 +151,7 @@ private fun FixGroup(
|
||||
PrimaryButton(
|
||||
if (stage is Stage.Failed) stringResource(R.string.store_try_again) else stringResource(R.string.gate_fix_for_me),
|
||||
compact = compact,
|
||||
enabled = environment.onWifi,
|
||||
enabled = environment.onWifi && environment.notifications,
|
||||
onClick = onFixWithWirelessDebugging,
|
||||
)
|
||||
}
|
||||
@@ -159,6 +160,10 @@ private fun FixGroup(
|
||||
if (!environment.onWifi) {
|
||||
Body(stringResource(R.string.gate_needs_wifi), warn = true)
|
||||
}
|
||||
if (!environment.notifications) {
|
||||
Body(stringResource(R.string.gate_needs_notifications), warn = true)
|
||||
SecondaryButton(stringResource(R.string.gate_allow_notifications), compact = compact, onClick = onOpenNotificationSettings)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -219,6 +224,7 @@ private fun OtherWays(
|
||||
compact: Boolean,
|
||||
onOpenDeveloperOptions: () -> Unit,
|
||||
onFixWithWirelessDebugging: () -> Unit,
|
||||
onEnterAddressManually: () -> Unit,
|
||||
onCopyCommand: () -> Unit,
|
||||
) {
|
||||
var open by rememberSaveable { mutableStateOf(false) }
|
||||
@@ -234,10 +240,14 @@ private fun OtherWays(
|
||||
modifier = Modifier.fillMaxWidth().padding(start = 14.dp, end = 14.dp, bottom = 14.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
if (!hasToggle) {
|
||||
if (hasToggle) {
|
||||
SecondaryButton(stringResource(R.string.gate_use_wireless_instead), compact = true, onClick = onFixWithWirelessDebugging)
|
||||
} else {
|
||||
Body(stringResource(R.string.gate_some_roms))
|
||||
SecondaryButton(stringResource(R.string.gate_open_dev), compact = true, onClick = onOpenDeveloperOptions)
|
||||
}
|
||||
Body(stringResource(R.string.gate_manual_hint))
|
||||
SecondaryButton(stringResource(R.string.gate_enter_manually), compact = true, onClick = onEnterAddressManually)
|
||||
Body(stringResource(R.string.gate_from_computer))
|
||||
AdbCommand()
|
||||
SecondaryButton(stringResource(R.string.gate_copy_command), compact = true, onClick = onCopyCommand)
|
||||
|
||||
@@ -75,19 +75,6 @@ internal fun SyncTabPage(s: FrontEndState, modifier: Modifier) {
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SteamTabPage(key: String, a: FrontEndActions, modifier: Modifier) {
|
||||
LaunchedEffect(Unit) { a.onSteamSettings() }
|
||||
Column(modifier.verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) {
|
||||
PageHeader(stringResource(if (key == "decky") R.string.rail_decky else R.string.rail_boot_movies))
|
||||
a.modeSheet(
|
||||
com.droiddeck.launcher.session.SessionService.MODE_STEAM,
|
||||
if (key == "decky") SheetTab.DECKY else SheetTab.BOOT_MOVIES,
|
||||
SheetExtras(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ResetTabsRow() {
|
||||
val ctx = androidx.compose.ui.platform.LocalContext.current
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.Context
|
||||
import android.view.inputmethod.InputMethodManager
|
||||
import android.widget.EditText
|
||||
import androidx.compose.foundation.gestures.awaitEachGesture
|
||||
import androidx.compose.foundation.gestures.awaitFirstDown
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.snapshotFlow
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.composed
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.input.pointer.PointerEventPass
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.layout.LayoutCoordinates
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
import kotlinx.coroutines.flow.first
|
||||
|
||||
internal object ScreenTaps {
|
||||
var count by mutableStateOf(0)
|
||||
}
|
||||
|
||||
/** A field that opens on a heavy page can take focus after the next tap has already finished. */
|
||||
@Composable
|
||||
internal fun CancelPendingFocus(pending: Boolean, askedAtTap: Int, focused: Boolean, cancel: () -> Unit) {
|
||||
val focusedNow by rememberUpdatedState(focused)
|
||||
val cancelNow by rememberUpdatedState(cancel)
|
||||
LaunchedEffect(pending, askedAtTap) {
|
||||
if (!pending) return@LaunchedEffect
|
||||
snapshotFlow { ScreenTaps.count }.first { it != askedAtTap }
|
||||
if (!focusedNow) cancelNow()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tapped controls do not take focus in touch mode, so a text field would otherwise keep it, and its highlight.
|
||||
* [x] and [y] share coordinates with [origin], the field's own position.
|
||||
*/
|
||||
internal fun releaseTextField(field: EditText, origin: IntArray, x: Float, y: Float) {
|
||||
val margin = 12 * field.resources.displayMetrics.density
|
||||
val insideX = x >= origin[0] - margin && x <= origin[0] + field.width + margin
|
||||
val insideY = y >= origin[1] - margin && y <= origin[1] + field.height + margin
|
||||
if (insideX && insideY) return
|
||||
field.clearFocus()
|
||||
(field.context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.hideSoftInputFromWindow(field.windowToken, 0)
|
||||
}
|
||||
|
||||
/** A dialog's touches never reach the activity, so a dialog holding a search field counts its taps and releases the field itself. */
|
||||
internal fun Modifier.releaseTextFieldOnTap(): Modifier = composed {
|
||||
val view = LocalView.current
|
||||
val placed = remember { arrayOfNulls<LayoutCoordinates>(1) }
|
||||
onGloballyPositioned { placed[0] = it }.pointerInput(view) {
|
||||
awaitEachGesture {
|
||||
val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)
|
||||
ScreenTaps.count++
|
||||
var up: Offset? = null
|
||||
while (true) {
|
||||
val change = awaitPointerEvent(PointerEventPass.Final).changes.firstOrNull { it.id == down.id } ?: break
|
||||
if ((change.position - down.position).getDistance() > viewConfiguration.touchSlop) break
|
||||
if (!change.pressed) { up = change.position; break }
|
||||
}
|
||||
val at = up?.let { placed[0]?.takeIf { c -> c.isAttached }?.localToWindow(it) } ?: return@awaitEachGesture
|
||||
view.post {
|
||||
val field = view.findFocus() as? EditText ?: return@post
|
||||
releaseTextField(field, IntArray(2).also(field::getLocationInWindow), at.x, at.y)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,11 +12,10 @@ internal enum class SessionDrawerPage(val firstControl: String) {
|
||||
DISPLAY("fg"),
|
||||
HUD("hud"),
|
||||
EFFECTS("look"),
|
||||
VR("steamvr"),
|
||||
GAMES("anisotropy"),
|
||||
AGENT("agent-input"),
|
||||
SESSION("suspend"),
|
||||
MORE("more-edit"),
|
||||
VR("steamvr"),
|
||||
}
|
||||
|
||||
internal object DrawerPages {
|
||||
@@ -28,7 +27,7 @@ internal object DrawerPages {
|
||||
/** The order captured when a page row was grabbed in Arrange pages; Back restores it. */
|
||||
var heldFrom: List<SessionDrawerPage>? = null
|
||||
|
||||
fun hideable(page: SessionDrawerPage) = page != SessionDrawerPage.SESSION && page != SessionDrawerPage.MORE
|
||||
fun hideable(page: SessionDrawerPage) = page != SessionDrawerPage.SESSION
|
||||
|
||||
fun load(context: Context) {
|
||||
order = arrange(SessionPrefs.drawerPageOrder(context))
|
||||
@@ -82,22 +81,6 @@ internal fun sessionDrawerPages(
|
||||
hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown,
|
||||
): List<SessionDrawerPage> = offeredDrawerPages(hasGlasses, hasAgent).filter { it !in DrawerPages.hidden }
|
||||
|
||||
/** The pages shown as tabs: everything up to and including the More tab. */
|
||||
internal fun List<SessionDrawerPage>.strip(): List<SessionDrawerPage> {
|
||||
val more = indexOf(SessionDrawerPage.MORE)
|
||||
return if (more < 0) this else subList(0, more + 1)
|
||||
}
|
||||
|
||||
/** The pages kept inside More: those after the More tab. */
|
||||
internal fun List<SessionDrawerPage>.inMore(): List<SessionDrawerPage> {
|
||||
val more = indexOf(SessionDrawerPage.MORE)
|
||||
return if (more < 0) emptyList() else subList(more + 1, size)
|
||||
}
|
||||
|
||||
/** The tab that stands for [page]: the More tab for a page kept inside More. */
|
||||
internal fun List<SessionDrawerPage>.tabFor(page: SessionDrawerPage): SessionDrawerPage =
|
||||
if (page in inMore()) SessionDrawerPage.MORE else page
|
||||
|
||||
internal fun List<SessionDrawerPage>.step(current: SessionDrawerPage, direction: Int): SessionDrawerPage {
|
||||
val index = indexOf(current).coerceAtLeast(0)
|
||||
return this[Math.floorMod(index + direction, size)]
|
||||
|
||||
@@ -39,7 +39,6 @@ import androidx.compose.material.icons.outlined.AutoFixHigh
|
||||
import androidx.compose.material.icons.outlined.ExpandMore
|
||||
import androidx.compose.material.icons.outlined.Home
|
||||
import androidx.compose.material.icons.outlined.MoreHoriz
|
||||
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
|
||||
import androidx.compose.material.icons.outlined.PowerSettingsNew
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.material.icons.outlined.DesktopWindows
|
||||
@@ -96,14 +95,6 @@ import androidx.compose.ui.ExperimentalComposeUiApi
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import android.view.KeyEvent
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.foundation.gestures.awaitEachGesture
|
||||
import androidx.compose.foundation.gestures.awaitFirstDown
|
||||
import androidx.compose.ui.layout.positionInRoot
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.HomeApp
|
||||
@@ -183,7 +174,6 @@ internal val SessionDrawerPage.title: Int get() = when (this) {
|
||||
SessionDrawerPage.GAMES -> R.string.game_settings_title
|
||||
SessionDrawerPage.AGENT -> R.string.rail_agent
|
||||
SessionDrawerPage.SESSION -> R.string.mode_session
|
||||
SessionDrawerPage.MORE -> R.string.drawer_page_more
|
||||
}
|
||||
|
||||
internal val SessionDrawerPage.icon get() = when (this) {
|
||||
@@ -196,7 +186,6 @@ internal val SessionDrawerPage.icon get() = when (this) {
|
||||
SessionDrawerPage.GAMES -> Icons.Outlined.Layers
|
||||
SessionDrawerPage.AGENT -> Icons.Outlined.Terminal
|
||||
SessionDrawerPage.SESSION -> Icons.Outlined.Settings
|
||||
SessionDrawerPage.MORE -> Icons.Outlined.MoreHoriz
|
||||
}
|
||||
|
||||
private class DrawerFocus {
|
||||
@@ -272,8 +261,6 @@ class DrawerActions(
|
||||
val textureLodBias: String? = TextureFiltering.LOD_BIAS_OFF,
|
||||
val secondScreenMode: SecondScreenMode,
|
||||
val secondScreenNone: Boolean = true,
|
||||
val dualScreenMode: String = com.droiddeck.launcher.input.DualScreen.MODE_AUTO,
|
||||
val onDualScreenMode: (String) -> Unit = {},
|
||||
val gameOnBottom: Boolean = false,
|
||||
val gameSwapAvailable: Boolean = false,
|
||||
val gameSwapBuiltIn: Boolean = true,
|
||||
@@ -431,8 +418,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) }
|
||||
var confirmStop by remember { mutableStateOf(false) }
|
||||
var sheetCoords by remember { mutableStateOf<LayoutCoordinates?>(null) }
|
||||
val widthContext = LocalContext.current
|
||||
var savedWidth by remember { mutableStateOf(SessionPrefs.drawerWidthDp(widthContext)) }
|
||||
var stopCoords by remember { mutableStateOf<LayoutCoordinates?>(null) }
|
||||
val pageScroll = remember { SessionDrawerPage.entries.associateWith { ScrollState(0) } }
|
||||
LaunchedEffect(glassesTab) {
|
||||
@@ -443,17 +428,11 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
val focus = remember { DrawerFocus() }
|
||||
val inputModeManager = LocalInputModeManager.current
|
||||
val focusManager = LocalFocusManager.current
|
||||
// A page kept inside More is one step deeper than the strip: back returns to More before it closes the menu.
|
||||
val insideMore = page in pages.inMore()
|
||||
BackHandler(enabled = open) {
|
||||
when {
|
||||
host.open != null -> host.open = null
|
||||
insideMore -> onPageChange(SessionDrawerPage.MORE)
|
||||
else -> a.onClose()
|
||||
}
|
||||
if (host.open != null) host.open = null else a.onClose()
|
||||
}
|
||||
BackHandler(enabled = open && confirmStop) { confirmStop = false }
|
||||
val layerOpen = open && (host.open != null || appToChooseDisplay != null || confirmStop || insideMore)
|
||||
val layerOpen = open && (host.open != null || appToChooseDisplay != null || confirmStop)
|
||||
LaunchedEffect(layerOpen) { onLayerChange(layerOpen) }
|
||||
var seenBackRequest by remember { mutableStateOf(backRequest) }
|
||||
LaunchedEffect(backRequest) {
|
||||
@@ -463,10 +442,9 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
confirmStop -> confirmStop = false
|
||||
appToChooseDisplay != null -> appToChooseDisplay = null
|
||||
host.open != null -> host.open = null
|
||||
insideMore -> onPageChange(SessionDrawerPage.MORE)
|
||||
}
|
||||
}
|
||||
LaunchedEffect(page) { host.open = null; appToChooseDisplay = null; managing = false }
|
||||
LaunchedEffect(page) { host.open = null; appToChooseDisplay = null }
|
||||
LaunchedEffect(a.selectedGameProfileId) {
|
||||
if (host.open == "fex") host.open = null
|
||||
}
|
||||
@@ -528,22 +506,17 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
}
|
||||
androidx.compose.foundation.layout.BoxWithConstraints(modifier = Modifier.fillMaxSize().exposeTestTags(), contentAlignment = Alignment.CenterEnd) {
|
||||
val short = maxHeight < 440.dp
|
||||
// The handle keeps a strip on the left free, so a sheet dragged wide can always be dragged back.
|
||||
val maxSheet = (maxWidth - DRAWER_EDGE_GAP).coerceAtLeast(0.dp)
|
||||
val minSheet = minOf(DRAWER_MIN_WIDTH, maxSheet)
|
||||
val defaultSheet = minOf(420.dp, maxWidth * 0.92f)
|
||||
val sheetWidth = if (docked) maxWidth else (savedWidth?.dp ?: defaultSheet).coerceIn(minSheet, maxSheet)
|
||||
val sheetWidth = if (docked) maxWidth else minOf(420.dp, maxWidth * 0.92f)
|
||||
val narrow = sheetWidth < 320.dp
|
||||
AnimatedVisibility(
|
||||
open,
|
||||
enter = if (docked) fadeIn(Motion.tw(160)) else slideInHorizontally(Motion.sp(0.8f, Spring.StiffnessLow)) { it } + fadeIn(Motion.tw(220)),
|
||||
exit = if (docked) fadeOut(Motion.tw(140)) else slideOutHorizontally(Motion.tw(240)) { it } + fadeOut(Motion.tw(200)),
|
||||
) {
|
||||
FocusGlideHost(Modifier.fillMaxHeight().width(if (docked) sheetWidth else sheetWidth + DRAWER_HANDLE_STRIP)) { Box(Modifier.fillMaxSize().onGloballyPositioned { sheetCoords = it }) {
|
||||
FocusGlideHost(Modifier.fillMaxHeight().width(sheetWidth)) { Box(Modifier.fillMaxSize().onGloballyPositioned { sheetCoords = it }) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(start = if (docked) 0.dp else DRAWER_HANDLE_STRIP)
|
||||
.background(if (docked) pal.background else pal.background.copy(alpha = 0.97f))
|
||||
.blockTouches()
|
||||
.focusGroup()
|
||||
@@ -554,7 +527,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
DrawerPages.rearrange(drawerContext, held)
|
||||
releaseSignal++
|
||||
} ?: run { managing = false }
|
||||
insideMore -> onPageChange(SessionDrawerPage.MORE)
|
||||
else -> a.onClose()
|
||||
}
|
||||
}
|
||||
@@ -632,14 +604,16 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 6.dp),
|
||||
) {
|
||||
DrawerBumper("LB", stringResource(R.string.drawer_prev_page), modifier = focus.track(page, "prev")) {
|
||||
host.open = null; onPageChange(pages.strip().step(pages.tabFor(page), -1))
|
||||
host.open = null; onPageChange(pages.step(page, -1))
|
||||
}
|
||||
DrawerPageTabs(page = pages.tabFor(page), pages = pages.strip(), compact = true, modifier = Modifier.weight(1f)) { index -> host.open = null; onPageChange(index) }
|
||||
DrawerPageTabs(page = page, pages = pages, compact = true, modifier = Modifier.weight(1f)) { index -> host.open = null; onPageChange(index) }
|
||||
DrawerBumper("RB", stringResource(R.string.drawer_next_page), modifier = focus.track(page, "next")) {
|
||||
host.open = null; onPageChange(pages.strip().step(pages.tabFor(page), 1))
|
||||
host.open = null; onPageChange(pages.step(page, 1))
|
||||
}
|
||||
SmallIconButton(
|
||||
Icons.Outlined.Tune, stringResource(R.string.drawer_manage_pages), colors.onSurfaceVariant,
|
||||
) { host.open = null; managing = !managing }
|
||||
}
|
||||
if (insideMore && !managing) DrawerMoreBack(stringResource(page.title), focus.track(page, "more-back")) { host.open = null; onPageChange(SessionDrawerPage.MORE) }
|
||||
if (managing) ManageDrawerPages(
|
||||
offeredDrawerPages(a.glassesPresent),
|
||||
Modifier.weight(1f).fillMaxWidth().padding(top = 8.dp, start = 14.dp, end = 14.dp),
|
||||
@@ -914,7 +888,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
)
|
||||
}
|
||||
SessionDrawerPage.AGENT -> Unit
|
||||
SessionDrawerPage.MORE -> DrawerMorePage(host, pages.inMore(), { host.open = null; onPageChange(it) }, { host.open = null; managing = true }) { key -> focus.track(page, key) }
|
||||
SessionDrawerPage.SESSION -> {
|
||||
SettingsGroup(stringResource(R.string.drawer_support)) {
|
||||
SettingsRow(stringResource(R.string.report_problem), stringResource(R.string.report_problem_hint)) {
|
||||
@@ -992,12 +965,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
} }
|
||||
}
|
||||
}
|
||||
if (!docked) DrawerResizeHandle(
|
||||
width = sheetWidth, min = minSheet, max = maxSheet,
|
||||
onWidth = { savedWidth = it.value.roundToInt() },
|
||||
onCommit = { savedWidth?.let { SessionPrefs.setDrawerWidthDp(widthContext, it) } },
|
||||
modifier = Modifier.align(Alignment.CenterStart).then(focus.track(page, "resize")),
|
||||
)
|
||||
StopConfirm(
|
||||
open = confirmStop,
|
||||
pill = sheetCoords?.let { sc -> stopCoords?.takeIf { it.isAttached && sc.isAttached }?.let { sc.localBoundingBoxOf(it, clipBounds = false) } },
|
||||
@@ -1185,70 +1152,6 @@ private fun DrawerPageTabs(page: SessionDrawerPage, pages: List<SessionDrawerPag
|
||||
|
||||
private const val LOOK_CUSTOM = "custom"
|
||||
|
||||
/** The row above a page kept inside More that goes back to the More list. */
|
||||
@Composable
|
||||
private fun DrawerMoreBack(title: String, modifier: Modifier, onBack: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val source = remember { MutableInteractionSource() }
|
||||
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
|
||||
val shape = RoundedCornerShape(12.dp)
|
||||
val label = stringResource(R.string.drawer_more_back, stringResource(R.string.drawer_page_more))
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
modifier = modifier.padding(top = 8.dp, start = 14.dp, end = 14.dp).fillMaxWidth().heightIn(min = 44.dp).clip(shape)
|
||||
.background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent)
|
||||
.glideBorder(hot, shape, pal.signal)
|
||||
.testTag("drawer-more-back")
|
||||
.hoverable(source)
|
||||
.clickable(interactionSource = source, indication = null, role = androidx.compose.ui.semantics.Role.Button, onClick = onBack)
|
||||
.controllerConfirm(onClick = onBack)
|
||||
.semantics { contentDescription = label }
|
||||
.padding(horizontal = 8.dp),
|
||||
) {
|
||||
Icon(Icons.AutoMirrored.Outlined.ArrowBack, null, tint = colors.onSurfaceVariant, modifier = Modifier.size(22.dp))
|
||||
Text(stringResource(R.string.drawer_page_more), fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
Text("·", fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
/** The pages kept inside More, and the way into arranging which pages sit on the strip and which here. */
|
||||
@Composable
|
||||
private fun DrawerMorePage(host: MenuHost, pages: List<SessionDrawerPage>, onOpen: (SessionDrawerPage) -> Unit, onEdit: () -> Unit, track: (String) -> Modifier) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
SettingsGroup(stringResource(R.string.drawer_page_more)) {
|
||||
if (pages.isEmpty()) Text(
|
||||
stringResource(R.string.drawer_more_empty), fontSize = 13.sp, color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||
)
|
||||
for (item in pages) {
|
||||
val source = remember { MutableInteractionSource() }
|
||||
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
|
||||
val shape = RoundedCornerShape(12.dp)
|
||||
val open = { onOpen(item) }
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp).clip(shape)
|
||||
.background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent)
|
||||
.glideBorder(hot, shape, pal.signal)
|
||||
.then(track("more-${item.name.lowercase()}"))
|
||||
.testTag("drawer-more-${item.name.lowercase()}")
|
||||
.hoverable(source)
|
||||
.clickable(interactionSource = source, indication = null, role = androidx.compose.ui.semantics.Role.Button, onClick = open)
|
||||
.controllerConfirm(onClick = open)
|
||||
.padding(horizontal = 14.dp),
|
||||
) {
|
||||
Icon(item.icon, null, tint = colors.onSurfaceVariant, modifier = Modifier.size(22.dp))
|
||||
Text(stringResource(item.title), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
DrawerOutlineButton(stringResource(R.string.drawer_manage_pages), modifier = track("more-edit").testTag("drawer-more-edit"), onClick = onEdit)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ScreenEffectsGroup(
|
||||
host: MenuHost, a: DrawerActions, advancedExpanded: Boolean, onAdvancedToggle: () -> Unit,
|
||||
@@ -1435,93 +1338,12 @@ internal fun secondScreenModes(none: Boolean, deckPad: Boolean, dashboard: Boole
|
||||
(if (dashboard) listOf(SecondScreenMode.DASHBOARD) else emptyList()) +
|
||||
(if (desktop) listOf(SecondScreenMode.DESKTOP) else emptyList())
|
||||
|
||||
private val DRAWER_MIN_WIDTH = 300.dp
|
||||
private val DRAWER_HANDLE_STRIP = 24.dp
|
||||
private val DRAWER_EDGE_GAP = 80.dp
|
||||
|
||||
/** A grip on the sheet's left edge: dragging it, or pressing left and right on a controller, resizes the sheet. */
|
||||
@Composable
|
||||
private fun DrawerResizeHandle(width: Dp, min: Dp, max: Dp, onWidth: (Dp) -> Unit, onCommit: () -> Unit, modifier: Modifier) {
|
||||
val pal = LocalPalette.current
|
||||
val density = LocalDensity.current
|
||||
val source = remember { MutableInteractionSource() }
|
||||
val focused by source.collectIsFocusedAsState()
|
||||
var dragging by remember { mutableStateOf(false) }
|
||||
var coords by remember { mutableStateOf<LayoutCoordinates?>(null) }
|
||||
val current by rememberUpdatedState(width)
|
||||
val lower by rememberUpdatedState(min)
|
||||
val upper by rememberUpdatedState(max)
|
||||
val change by rememberUpdatedState(onWidth)
|
||||
val commit by rememberUpdatedState(onCommit)
|
||||
val hot = focused || dragging
|
||||
val label = stringResource(R.string.drawer_resize)
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = modifier.width(24.dp).height(96.dp)
|
||||
.onGloballyPositioned { coords = it }
|
||||
.focusable(true, source)
|
||||
.onPreviewKeyEvent { event ->
|
||||
val key = event.nativeKeyEvent
|
||||
val wider = key.keyCode == KeyEvent.KEYCODE_DPAD_LEFT
|
||||
if (!wider && key.keyCode != KeyEvent.KEYCODE_DPAD_RIGHT) false
|
||||
else {
|
||||
if (key.action == KeyEvent.ACTION_DOWN) {
|
||||
change((current + if (wider) 24.dp else (-24).dp).coerceIn(lower, upper))
|
||||
commit()
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
// The handle moves with the finger as the sheet resizes, so the drag is measured on the screen.
|
||||
.pointerInput(Unit) {
|
||||
awaitEachGesture {
|
||||
val down = awaitFirstDown(requireUnconsumed = false)
|
||||
var last = (coords?.positionInRoot()?.x ?: 0f) + down.position.x
|
||||
// Several moves can arrive before the sheet recomposes, so the width is accumulated here.
|
||||
var live = current
|
||||
dragging = true
|
||||
do {
|
||||
val event = awaitPointerEvent()
|
||||
val pointer = event.changes.firstOrNull() ?: break
|
||||
val x = (coords?.positionInRoot()?.x ?: 0f) + pointer.position.x
|
||||
val delta = with(density) { (x - last).toDp() }
|
||||
last = x
|
||||
if (delta != 0.dp) {
|
||||
live = (live - delta).coerceIn(lower, upper)
|
||||
change(live)
|
||||
}
|
||||
pointer.consume()
|
||||
} while (event.changes.any { it.pressed })
|
||||
dragging = false
|
||||
commit()
|
||||
}
|
||||
}
|
||||
.semantics {
|
||||
contentDescription = label
|
||||
stateDescription = "${width.value.roundToInt()} dp"
|
||||
},
|
||||
) {
|
||||
Box(
|
||||
Modifier.width(if (hot) 6.dp else 4.dp).height(56.dp).clip(CircleShape)
|
||||
.background(if (hot) pal.signal else pal.onSurfaceVariant.copy(alpha = 0.55f)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
|
||||
val choosesDisplay = a.secondScreenDisplays.size > 1
|
||||
val swapsGame = a.gameSwapAvailable || a.gameOnBottom
|
||||
val hasSecondScreen = a.secondScreenDisplays.isNotEmpty()
|
||||
if (!hasSecondScreen && !choosesDisplay && !swapsGame) return
|
||||
if (!choosesDisplay && !swapsGame) return
|
||||
SettingsGroup(stringResource(R.string.drawer_second_screen)) {
|
||||
if (hasSecondScreen) ChoiceRow(host, "dual-screen-mode", stringResource(R.string.setup_dual_screen_sessions), null,
|
||||
listOf(
|
||||
com.droiddeck.launcher.input.DualScreen.MODE_AUTO to stringResource(R.string.setup_dual_screen_auto),
|
||||
com.droiddeck.launcher.input.DualScreen.MODE_ON to stringResource(R.string.setup_dual_screen_on),
|
||||
com.droiddeck.launcher.input.DualScreen.MODE_SWAPPED to stringResource(R.string.setup_dual_screen_swapped),
|
||||
com.droiddeck.launcher.input.DualScreen.MODE_OFF to stringResource(R.string.setup_dual_screen_off),
|
||||
), a.dualScreenMode, chipModifier = track("dual-screen-mode"), onPick = a.onDualScreenMode)
|
||||
if (swapsGame) ChoiceRow(host, "game-screen", stringResource(R.string.swap_game_screen), null,
|
||||
if (a.gameSwapBuiltIn) listOf(false to stringResource(R.string.swap_game_screen_top), true to stringResource(R.string.swap_game_screen_bottom))
|
||||
else listOf(false to stringResource(R.string.main_primary), true to stringResource(R.string.main_secondary)),
|
||||
|
||||
@@ -93,8 +93,6 @@ internal object SettingsIndex {
|
||||
s(SettingsSection.CONTROLLER, R.string.setup_tab_controller, "gamepad", "buttons", "mapping", "profile", "remap"),
|
||||
SettingsEntry(SettingsPlace.TAB, R.string.rail_storage, tab = "storage", words = listOf("sd card", "space", "uninstall", "disk")),
|
||||
SettingsEntry(SettingsPlace.TAB, R.string.rail_sync, tab = "sync", words = listOf("syncthing", "saves")),
|
||||
SettingsEntry(SettingsPlace.TAB, R.string.rail_decky, tab = "decky", words = listOf("plugins", "plugin store", "homebrew", "loader")),
|
||||
SettingsEntry(SettingsPlace.TAB, R.string.rail_boot_movies, tab = "boot-movies", words = listOf("startup movie", "boot video", "animation", "steamdeckrepo")),
|
||||
s(SettingsSection.GLASSES, R.string.setup_tab_glasses, "xreal", "viture", "vr", "ar"),
|
||||
|
||||
s(SettingsSection.LAUNCHER, R.string.setup_theme, "color", "dark"),
|
||||
|
||||
@@ -49,12 +49,6 @@ internal fun SettingsPillSearch(
|
||||
val icon = remember { FocusRequester() }
|
||||
var toIcon by remember { mutableStateOf(false) }
|
||||
var focusOnOpen by remember { mutableStateOf(false) }
|
||||
var focusTap by remember { mutableStateOf(0) }
|
||||
var fieldFocused by remember { mutableStateOf(false) }
|
||||
CancelPendingFocus(focusOnOpen, focusTap, fieldFocused) {
|
||||
focusOnOpen = false
|
||||
if (query.isEmpty()) onClose()
|
||||
}
|
||||
val close = { toIcon = true; focusOnOpen = false; onClose() }
|
||||
BackHandler(enabled = searching) { close() }
|
||||
LaunchedEffect(toIcon, searching, open <= 0.01f) {
|
||||
@@ -79,18 +73,15 @@ internal fun SettingsPillSearch(
|
||||
Box(Modifier.width(w).graphicsLayer { alpha = (open * 1.6f).coerceAtMost(1f) }) {
|
||||
AdbTextField(
|
||||
value = query, onValueChange = onQuery, label = "", keyboardType = KeyboardType.Text, imeAction = ImeAction.Search,
|
||||
placeholder = stringResource(R.string.settings_search), compact = true, showLabel = false, focusOnShow = focusOnOpen, focusAtTap = focusTap,
|
||||
placeholder = stringResource(R.string.settings_search), compact = true, showLabel = false, focusOnShow = focusOnOpen,
|
||||
clearFocus = !searching,
|
||||
onFocusChange = { focused ->
|
||||
fieldFocused = focused
|
||||
if (!focused && query.isEmpty() && searching) { focusOnOpen = false; onClose() }
|
||||
},
|
||||
onFocusChange = { focused -> if (!focused && query.isEmpty() && searching) { focusOnOpen = false; onClose() } },
|
||||
)
|
||||
}
|
||||
SmallIconButton(Icons.Filled.Close, stringResource(R.string.settings_search_clear), tint = colors.onSurfaceVariant) { close() }
|
||||
}
|
||||
} else {
|
||||
Box(Modifier.focusRequester(icon)) { SearchIcon(stringResource(R.string.settings_search)) { focusTap = ScreenTaps.count; focusOnOpen = true; onOpen() } }
|
||||
Box(Modifier.focusRequester(icon)) { SearchIcon(stringResource(R.string.settings_search)) { focusOnOpen = true; onOpen() } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,8 +163,6 @@ internal fun Modifier.bumpers(onPrevious: () -> Unit, onNext: () -> Unit): Modif
|
||||
}
|
||||
}
|
||||
|
||||
internal val LocalRevealChecked = androidx.compose.runtime.compositionLocalOf { true }
|
||||
|
||||
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
internal fun TabStrip(
|
||||
@@ -349,7 +347,7 @@ fun AnchoredMenu(
|
||||
}
|
||||
}
|
||||
.verticalScroll(scroll),
|
||||
) { androidx.compose.runtime.CompositionLocalProvider(LocalRevealChecked provides true) { content(firstItemFocus) } }
|
||||
) { content(firstItemFocus) }
|
||||
if (scroll.canScrollForward) Icon(
|
||||
Icons.Filled.KeyboardArrowDown, contentDescription = null, tint = colors.onSurfaceVariant,
|
||||
modifier = Modifier.align(Alignment.BottomCenter).size(20.dp),
|
||||
@@ -379,7 +377,7 @@ fun MenuItem(
|
||||
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
|
||||
val shift by animateFloatAsState(if (hot) 2f else 0f, Motion.sp(0.5f), label = "miShift")
|
||||
val reveal = remember { androidx.compose.foundation.relocation.BringIntoViewRequester() }
|
||||
if (checked && LocalRevealChecked.current) LaunchedEffect(Unit) { reveal.bringIntoView() }
|
||||
if (checked) LaunchedEffect(Unit) { reveal.bringIntoView() }
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = modifier.fillMaxWidth()
|
||||
|
||||
@@ -29,13 +29,8 @@ import androidx.compose.foundation.layout.wrapContentSize
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
@@ -145,7 +140,6 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
|
||||
onOpen = a.onSteamSettings, onPrimary = a.onPlay,
|
||||
modifier = modifier.clipToBounds(),
|
||||
start = if (narrow) 20.dp else 44.dp, bottom = 44.dp,
|
||||
onTextBounds = { words = it },
|
||||
background = {
|
||||
when {
|
||||
games.isEmpty() -> EmptyLibrary(
|
||||
@@ -158,56 +152,28 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
|
||||
},
|
||||
scrim = { if (games.size >= WALL_MIN_GAMES) WallFade() },
|
||||
words = {
|
||||
val onboardingActive by com.droiddeck.launcher.session.Onboarding.active.collectAsState()
|
||||
val onboardingFailed by com.droiddeck.launcher.session.Onboarding.failed.collectAsState()
|
||||
val onboardingFacts by com.droiddeck.launcher.session.Onboarding.facts.collectAsState()
|
||||
val onboardingRows = com.droiddeck.launcher.session.Onboarding.rows(onboardingActive, onboardingFailed, onboardingFacts)
|
||||
val firstRun by com.droiddeck.launcher.session.Onboarding.firstRun.collectAsState()
|
||||
val settling = firstRun && onboardingActive.isNotEmpty() && com.droiddeck.launcher.session.Onboarding.pending(onboardingRows)
|
||||
val limitBlocks = com.droiddeck.launcher.core.PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
|
||||
val mark: @Composable () -> Unit = {
|
||||
Wordmark(if (narrow) 30.dp else 40.dp)
|
||||
}
|
||||
val runtimeStatus: @Composable () -> Unit = {
|
||||
if (!settling && (s.busy || (s.available != null && s.available != s.installed))) RuntimeChip(s)
|
||||
else if (!settling && setupNeedsAttention(s)) SecondaryButton(stringResource(R.string.play_needs_you), compact = true,
|
||||
if (s.busy || (s.available != null && s.available != s.installed)) RuntimeChip(s)
|
||||
else if (setupNeedsAttention(s)) SecondaryButton(stringResource(R.string.play_needs_you), compact = true,
|
||||
modifier = Modifier.testTag("play-needs-you")) { SetupTabs.openSection = SettingsSection.OVERVIEW }
|
||||
else if (!settling && s.integration.suggested && signedIn && !limitBlocks)
|
||||
else if (s.integration.suggested && signedIn && !com.droiddeck.launcher.core.PhantomProcessLimit.blocksSteam(s.phantomProcessStatus))
|
||||
IntegrationSuggestion(s.integration, { a.onSteamIntegration(null) }, a.onDismissIntegration)
|
||||
}
|
||||
if (narrow) Column(
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.onPlaced { words = it.boundsInParent() },
|
||||
) {
|
||||
mark()
|
||||
Wordmark(30.dp)
|
||||
runtimeStatus()
|
||||
} else Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.onPlaced { words = it.boundsInParent() },
|
||||
) {
|
||||
mark()
|
||||
Wordmark(if (narrow) 30.dp else 40.dp)
|
||||
runtimeStatus()
|
||||
}
|
||||
},
|
||||
button = { click ->
|
||||
val onboardingActive by com.droiddeck.launcher.session.Onboarding.active.collectAsState()
|
||||
val onboardingFailed by com.droiddeck.launcher.session.Onboarding.failed.collectAsState()
|
||||
val onboardingFacts by com.droiddeck.launcher.session.Onboarding.facts.collectAsState()
|
||||
val onboardingRows = com.droiddeck.launcher.session.Onboarding.rows(onboardingActive, onboardingFailed, onboardingFacts)
|
||||
val firstRun by com.droiddeck.launcher.session.Onboarding.firstRun.collectAsState()
|
||||
val settling = firstRun && onboardingActive.isNotEmpty() && com.droiddeck.launcher.session.Onboarding.pending(onboardingRows)
|
||||
val overall = com.droiddeck.launcher.session.Onboarding.overall(onboardingRows)
|
||||
val limitBlocks = com.droiddeck.launcher.core.PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
|
||||
LaunchedEffect(settling) {
|
||||
while (settling) {
|
||||
kotlinx.coroutines.delay(2_000)
|
||||
a.onRefreshPhantomStatus()
|
||||
}
|
||||
a.onRefreshPhantomStatus()
|
||||
}
|
||||
if (settling) PrimaryButton(
|
||||
stringResource(if (limitBlocks) R.string.onboarding_button_finish else R.string.onboarding_button_getting_ready, overall),
|
||||
enabled = limitBlocks, main = true, large = true, progress = overall / 100f,
|
||||
modifier = Modifier.testTag("play-steam"), onClick = { a.onQueuePlaySteam(); ChildProcessSetup.request?.invoke() ?: a.onShowPhantomGate() },
|
||||
) else PrimaryButton(stringResource(R.string.games_play_steam), enabled = !s.busy, main = true, large = true, icon = Icons.Filled.PlayArrow, modifier = Modifier.testTag("play-steam"), onClick = click)
|
||||
PrimaryButton(stringResource(R.string.games_play_steam), enabled = !s.busy, main = true, large = true, icon = Icons.Filled.PlayArrow, modifier = Modifier.testTag("play-steam"), onClick = click)
|
||||
},
|
||||
rows = { tab -> a.modeSheet(mode, tab, extras) },
|
||||
)
|
||||
|
||||
@@ -23,7 +23,6 @@ import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.AutoAwesome
|
||||
import androidx.compose.material.icons.outlined.Close
|
||||
import androidx.compose.material.icons.outlined.Bluetooth
|
||||
import androidx.compose.material.icons.outlined.Home
|
||||
import androidx.compose.material.icons.outlined.KeyboardCommandKey
|
||||
import androidx.compose.material.icons.outlined.LightMode
|
||||
@@ -62,7 +61,6 @@ internal fun SteamIntegration.State.enabled(feature: Feature) = when (feature) {
|
||||
Feature.BRIGHTNESS -> brightness
|
||||
Feature.HOME -> home
|
||||
Feature.SHORTCUTS -> shortcuts
|
||||
Feature.BLUETOOTH -> bluetooth
|
||||
}
|
||||
|
||||
internal fun SteamIntegration.State.enabledCount() = Feature.entries.count { enabled(it) }
|
||||
@@ -118,7 +116,6 @@ private fun IntegrationRow(
|
||||
feature == Feature.WIFI -> if (on) R.string.integration_wifi_on else R.string.integration_wifi_hint
|
||||
feature == Feature.BRIGHTNESS -> R.string.integration_brightness_hint
|
||||
feature == Feature.HOME -> R.string.integration_home_hint
|
||||
feature == Feature.BLUETOOTH -> R.string.integration_bluetooth_hint
|
||||
else -> R.string.integration_shortcuts_hint
|
||||
})
|
||||
Row(
|
||||
@@ -167,7 +164,6 @@ private fun featureIcon(feature: Feature) = when (feature) {
|
||||
Feature.BRIGHTNESS -> Icons.Outlined.LightMode
|
||||
Feature.HOME -> Icons.Outlined.Home
|
||||
Feature.SHORTCUTS -> Icons.Outlined.KeyboardCommandKey
|
||||
Feature.BLUETOOTH -> Icons.Outlined.Bluetooth
|
||||
}
|
||||
|
||||
private fun featureTitle(feature: Feature) = when (feature) {
|
||||
@@ -175,7 +171,6 @@ private fun featureTitle(feature: Feature) = when (feature) {
|
||||
Feature.BRIGHTNESS -> R.string.integration_brightness
|
||||
Feature.HOME -> R.string.integration_home
|
||||
Feature.SHORTCUTS -> R.string.integration_shortcuts
|
||||
Feature.BLUETOOTH -> R.string.integration_bluetooth
|
||||
}
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -45,7 +45,6 @@ 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.onFocusChanged
|
||||
import androidx.compose.ui.geometry.Rect
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Matrix
|
||||
@@ -175,7 +174,6 @@ internal fun StepOut(
|
||||
var grown by remember { mutableStateOf(false) }
|
||||
var measured by remember { mutableStateOf<IntSize?>(null) }
|
||||
val first = remember { FocusRequester() }
|
||||
var holdsFocus by remember { mutableStateOf(false) }
|
||||
val glide = LocalFocusGlide.current
|
||||
val opener = remember { arrayOfNulls<GlideSource>(1) }
|
||||
val openNow = androidx.compose.runtime.rememberUpdatedState(open)
|
||||
@@ -243,12 +241,8 @@ internal fun StepOut(
|
||||
LaunchedEffect(open, measured) {
|
||||
if (!open || measured == null || inputMode.inputMode != InputMode.Keyboard) return@LaunchedEffect
|
||||
delay(Motion.ms(300).toLong())
|
||||
// Another focus group can hold on to focus for a few frames, so the request is repeated until it lands.
|
||||
repeat(30) {
|
||||
withFrameNanos { }
|
||||
if (holdsFocus) return@LaunchedEffect
|
||||
runCatching { first.requestFocus() }
|
||||
}
|
||||
withFrameNanos { }
|
||||
runCatching { first.requestFocus() }
|
||||
}
|
||||
|
||||
LaunchedEffect(open, grown, inputMode.inputMode) {
|
||||
@@ -295,7 +289,6 @@ internal fun StepOut(
|
||||
.heightIn(max = availableHeight)
|
||||
.onSizeChanged { if (measured != it) measured = it }
|
||||
.controllerBack(onDismiss)
|
||||
.onFocusChanged { holdsFocus = it.hasFocus }
|
||||
.focusProperties { exit = { if (openNow.value) FocusRequester.Cancel else FocusRequester.Default } }
|
||||
.focusGroup()
|
||||
.verticalScroll(rememberScrollState())
|
||||
|
||||
@@ -453,7 +453,7 @@ private fun BucketCard(
|
||||
modifier = modifier.paneItem("storage:${bucket.name}")
|
||||
.graphicsLayer { scaleX = scale; scaleY = scale }
|
||||
.clip(Shape14)
|
||||
.background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier)
|
||||
.background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)
|
||||
.glideBorder(hot, Shape14, pal.signal, pal.line)
|
||||
.then(if (onClick != null) Modifier.hoverable(src)
|
||||
.clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
|
||||
|
||||
@@ -174,7 +174,7 @@ internal fun AchievementRow(a: Achievement, compact: Boolean, modifier: Modifier
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = modifier.fillMaxWidth().clip(shape)
|
||||
.background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier)
|
||||
.background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)
|
||||
.glideBorder(hot, shape, pal.signal, pal.line)
|
||||
.focusable(interactionSource = interaction)
|
||||
.padding(if (compact) 8.dp else 10.dp),
|
||||
@@ -369,7 +369,7 @@ internal fun DrawerAchievementsRow(progress: Pair<Int, Int>?, modifier: Modifier
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
modifier = modifier.fillMaxWidth().height(44.dp).clip(shape)
|
||||
.background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.14f)) else Modifier)
|
||||
.background(if (hot) pal.signal.copy(alpha = 0.14f) else colors.surface)
|
||||
.glideBorder(hot, shape, pal.signal, pal.line)
|
||||
.clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = interaction, indication = LocalIndication.current, onClick = onClick)
|
||||
.controllerConfirm(onClick = onClick)
|
||||
|
||||
@@ -533,7 +533,7 @@ private fun AppCard(app: CardApp, size: Dp, first: Boolean, cards: HashMap<Strin
|
||||
Column(
|
||||
Modifier.width(size).paneItem("tile:store:${app.id}").then(if (first) Modifier.firstTile() else Modifier)
|
||||
.graphicsLayer { scaleX = scale; scaleY = scale }
|
||||
.clip(shape).background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier)
|
||||
.clip(shape).background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)
|
||||
.glideBorder(hot, shape, pal.signal, pal.line)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
|
||||
.controllerConfirm(onClick = onClick)
|
||||
|
||||
@@ -925,12 +925,6 @@ internal fun ModeHeader(
|
||||
val pal = LocalPalette.current
|
||||
var searching by remember { mutableStateOf(query.isNotEmpty()) }
|
||||
var focusOnOpen by remember { mutableStateOf(false) }
|
||||
var focusTap by remember { mutableStateOf(0) }
|
||||
var fieldFocused by remember { mutableStateOf(false) }
|
||||
CancelPendingFocus(focusOnOpen, focusTap, fieldFocused) {
|
||||
focusOnOpen = false
|
||||
if (query.isEmpty()) searching = false
|
||||
}
|
||||
val open by animateFloatAsState(if (searching) 1f else 0f, Motion.sp(0.75f, 420f), label = "searchOpen")
|
||||
// Closing takes the field away with focus still in it; the search button gets it once it is back on screen.
|
||||
val searchIcon = remember { FocusRequester() }
|
||||
@@ -961,12 +955,9 @@ internal fun ModeHeader(
|
||||
Box(Modifier.width(w).graphicsLayer { alpha = (open * 1.6f).coerceAtMost(1f) }) {
|
||||
AdbTextField(
|
||||
value = query, onValueChange = onQuery, label = "", keyboardType = KeyboardType.Text, imeAction = ImeAction.Search,
|
||||
placeholder = placeholder, compact = true, showLabel = false, focusOnShow = focusOnOpen, focusAtTap = focusTap,
|
||||
placeholder = placeholder, compact = true, showLabel = false, focusOnShow = focusOnOpen,
|
||||
clearFocus = clearSearchFocus || !searching,
|
||||
onFocusChange = { focused ->
|
||||
fieldFocused = focused
|
||||
if (!focused && query.isEmpty()) { searching = false; focusOnOpen = false }
|
||||
},
|
||||
onFocusChange = { focused -> if (!focused && query.isEmpty()) { searching = false; focusOnOpen = false } },
|
||||
)
|
||||
}
|
||||
if (searching && closable) SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = colors.onSurfaceVariant, onClick = close)
|
||||
@@ -974,7 +965,7 @@ internal fun ModeHeader(
|
||||
}
|
||||
}
|
||||
val searchButton: @Composable () -> Unit = {
|
||||
Box(Modifier.focusRequester(searchIcon)) { SearchIcon(stringResource(R.string.stores_search_open)) { focusTap = ScreenTaps.count; searching = true; focusOnOpen = true } }
|
||||
Box(Modifier.focusRequester(searchIcon)) { SearchIcon(stringResource(R.string.stores_search_open)) { searching = true; focusOnOpen = true } }
|
||||
}
|
||||
BoxWithConstraints(Modifier.fillMaxWidth()) {
|
||||
val stacked = maxWidth < NarrowPaneWidth
|
||||
|
||||
@@ -213,10 +213,10 @@ internal fun SortableRows(
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun MoreLine(height: androidx.compose.ui.unit.Dp = TAB_ROW) {
|
||||
private fun MoreLine() {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Column(Modifier.fillMaxWidth().height(height).testTag("tab-more-line")) {
|
||||
Column(Modifier.fillMaxWidth().height(TAB_ROW).testTag("tab-more-line")) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.SystemUpdate
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.PathFillType
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.graphics.vector.addPathNodes
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.update.AppUpdates
|
||||
|
||||
internal enum class BuildKind { STABLE, PREVIEW, TEST, LOCAL }
|
||||
|
||||
internal object RunningBuild {
|
||||
var channel by mutableStateOf(AppUpdates.Channel.STABLE)
|
||||
|
||||
fun kind(me: AppUpdates.Installed = AppUpdates.installed(), channel: AppUpdates.Channel = this.channel): BuildKind = when {
|
||||
me.pr > 0 -> BuildKind.TEST
|
||||
!me.ciBuild -> BuildKind.LOCAL
|
||||
channel == AppUpdates.Channel.NIGHTLY -> BuildKind.PREVIEW
|
||||
else -> BuildKind.STABLE
|
||||
}
|
||||
}
|
||||
|
||||
private const val PHONE = "M17,1.01L7,1c-1.1,0 -2,0.9 -2,2v18c0,1.1 0.9,2 2,2h10c1.1,0 2,-0.9 2,-2V3c0,-1.1 -0.9,-1.99 -2,-1.99zM17,19H7V5h10v14z"
|
||||
private const val LETTER_P = "M9.6,7.6 H12.6 A2.4,2.4 0 0 1 12.6,12.4 H11.4 V16.4 H9.6 Z M11.4,9.2 V10.8 H12.6 A0.8,0.8 0 0 0 12.6,9.2 Z"
|
||||
private const val LETTER_T = "M8.6,7.6 H15.4 V9.3 H12.9 V16.4 H11.1 V9.3 H8.6 Z"
|
||||
private const val LETTER_L = "M9.8,7.6 H11.6 V14.7 H15 V16.4 H9.8 Z"
|
||||
|
||||
private fun phoneWith(name: String, letter: String) =
|
||||
ImageVector.Builder(name, 24.dp, 24.dp, 24f, 24f)
|
||||
.addPath(addPathNodes(PHONE), fill = SolidColor(Color.Black))
|
||||
.addPath(addPathNodes(letter), fill = SolidColor(Color.Black), pathFillType = PathFillType.EvenOdd)
|
||||
.build()
|
||||
|
||||
private val PreviewIcon by lazy { phoneWith("UpdatesPreview", LETTER_P) }
|
||||
private val TestIcon by lazy { phoneWith("UpdatesTest", LETTER_T) }
|
||||
private val LocalIcon by lazy { phoneWith("UpdatesLocal", LETTER_L) }
|
||||
|
||||
internal fun updatesIcon(kind: BuildKind): ImageVector = when (kind) {
|
||||
BuildKind.STABLE -> Icons.Filled.SystemUpdate
|
||||
BuildKind.PREVIEW -> PreviewIcon
|
||||
BuildKind.TEST -> TestIcon
|
||||
BuildKind.LOCAL -> LocalIcon
|
||||
}
|
||||
@@ -0,0 +1,626 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import com.droiddeck.launcher.R
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import android.text.Editable
|
||||
import android.text.InputType
|
||||
import android.text.TextWatcher
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import android.widget.EditText
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
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.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusDirection
|
||||
import androidx.compose.ui.focus.FocusManager
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
||||
import androidx.compose.ui.text.TextRange
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.ImeOptions
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.TextFieldValue
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
import com.droiddeck.launcher.core.WirelessAdbFix
|
||||
import kotlin.math.min
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
@Composable
|
||||
fun WirelessAdbFixPage(
|
||||
onBack: () -> Unit,
|
||||
desiredEnabled: Boolean,
|
||||
onOpenDeveloperOptions: () -> Unit,
|
||||
onPair: (String, Int, String, (String?) -> Unit) -> Unit,
|
||||
onFindConnectPort: (String, (Int?) -> Unit) -> Unit,
|
||||
onApply: (String, Int, Boolean, (String?) -> Unit) -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val savedAddress = remember { WirelessAdbFix.savedConnectionAddress(context) }
|
||||
var step by rememberSaveable { mutableStateOf(if (savedAddress == null) 0 else 1) }
|
||||
var pairingAddress by rememberSaveable { mutableStateOf("") }
|
||||
var connectionAddress by rememberSaveable { mutableStateOf(savedAddress.orEmpty()) }
|
||||
var pairingCode by rememberSaveable { mutableStateOf("") }
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
var editing by remember { mutableStateOf(false) }
|
||||
var message by remember { mutableStateOf<String?>(null) }
|
||||
var messageIsError by remember { mutableStateOf(false) }
|
||||
val focusManager = LocalFocusManager.current
|
||||
val keyboardController = LocalSoftwareKeyboardController.current
|
||||
val pairingEndpoint = parseAdbAddress(pairingAddress)
|
||||
|
||||
val pairNow: () -> Unit = {
|
||||
parseAdbAddress(pairingAddress)?.let { endpoint ->
|
||||
keyboardController?.hide()
|
||||
focusManager.clearFocus()
|
||||
busy = true
|
||||
editing = false
|
||||
message = null
|
||||
messageIsError = false
|
||||
onPair(endpoint.host, endpoint.port, pairingCode) { error ->
|
||||
pairingCode = ""
|
||||
if (error != null) {
|
||||
busy = false
|
||||
message = error
|
||||
messageIsError = true
|
||||
} else {
|
||||
step = 1
|
||||
busy = true
|
||||
message = context.getString(R.string.wadb_finding_port)
|
||||
onFindConnectPort(endpoint.host) { discoveredPort ->
|
||||
if (discoveredPort == null) {
|
||||
connectionAddress = formatAddressHost(endpoint.host) + ":"
|
||||
busy = false
|
||||
message = context.getString(R.string.wadb_enter_port)
|
||||
} else {
|
||||
connectionAddress = formatAdbAddress(endpoint.host, discoveredPort)
|
||||
message = context.getString(R.string.wadb_applying)
|
||||
onApply(endpoint.host, discoveredPort, desiredEnabled) { applyError ->
|
||||
busy = false
|
||||
if (applyError == null) {
|
||||
step = 2
|
||||
message = null
|
||||
} else {
|
||||
message = context.getString(R.string.wadb_apply_failed, applyError)
|
||||
messageIsError = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
val applyAddress: () -> Unit = {
|
||||
parseAdbAddress(connectionAddress)?.let { endpoint ->
|
||||
keyboardController?.hide()
|
||||
focusManager.clearFocus()
|
||||
busy = true
|
||||
editing = false
|
||||
message = null
|
||||
messageIsError = false
|
||||
onApply(endpoint.host, endpoint.port, desiredEnabled) { error ->
|
||||
busy = false
|
||||
if (error == null) {
|
||||
step = 2
|
||||
message = null
|
||||
} else {
|
||||
message = error
|
||||
messageIsError = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
val pairAgain: () -> Unit = {
|
||||
step = 0
|
||||
pairingAddress = ""
|
||||
pairingCode = ""
|
||||
message = null
|
||||
messageIsError = false
|
||||
}
|
||||
|
||||
BackHandler { if (!busy) onBack() }
|
||||
|
||||
BoxWithConstraints(Modifier.fillMaxSize()) {
|
||||
val compactSplit = maxWidth < 620.dp && maxHeight < 500.dp
|
||||
val form: @Composable () -> Unit = {
|
||||
WirelessStepForm(
|
||||
step = step,
|
||||
pairingAddress = pairingAddress,
|
||||
onPairingAddressChange = { pairingAddress = it },
|
||||
pairingCode = pairingCode,
|
||||
onPairingCodeChange = { pairingCode = it.filter(Char::isDigit).take(6) },
|
||||
connectionAddress = connectionAddress,
|
||||
onConnectionAddressChange = { connectionAddress = it },
|
||||
busy = busy,
|
||||
message = message,
|
||||
messageIsError = messageIsError,
|
||||
compact = compactSplit,
|
||||
editing = editing,
|
||||
onEditingChanged = { editing = it },
|
||||
focusManager = focusManager,
|
||||
desiredEnabled = desiredEnabled,
|
||||
canPair = pairingEndpoint != null && pairingCode.length == 6,
|
||||
onPair = pairNow,
|
||||
onApply = applyAddress,
|
||||
onPairAgain = pairAgain,
|
||||
)
|
||||
}
|
||||
SettingsPage(
|
||||
host = rememberMenuHost(),
|
||||
title = when {
|
||||
compactSplit && step < 2 -> stringResource(R.string.wadb_title_wireless)
|
||||
step == 2 -> stringResource(R.string.wadb_title_done)
|
||||
else -> stringResource(R.string.wadb_title)
|
||||
},
|
||||
eyebrow = stringResource(R.string.setup_title),
|
||||
lede = when {
|
||||
compactSplit && step == 0 -> stringResource(R.string.wadb_lede_compact0)
|
||||
compactSplit && step == 1 -> stringResource(R.string.wadb_lede_compact1)
|
||||
compactSplit -> stringResource(R.string.wadb_lede_done)
|
||||
step == 0 -> stringResource(R.string.wadb_lede0)
|
||||
step == 1 -> stringResource(R.string.wadb_lede1)
|
||||
else -> stringResource(R.string.wadb_lede_done_long)
|
||||
},
|
||||
onBack = { if (!busy) onBack() },
|
||||
action = if (compactSplit && step < 2) {
|
||||
{ SecondaryButton(stringResource(R.string.setup_dev_options), compact = true, enabled = !busy, onClick = onOpenDeveloperOptions) }
|
||||
} else null,
|
||||
scrollContent = !compactSplit,
|
||||
compactLayout = compactSplit,
|
||||
) {
|
||||
BoxWithConstraints(Modifier.fillMaxWidth()) {
|
||||
val wide = maxWidth >= 620.dp
|
||||
if (step == 2) {
|
||||
Column(
|
||||
modifier = Modifier.widthIn(max = 680.dp).fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
SettingsGroup(stringResource(R.string.setup_limit), compact = compactSplit) {
|
||||
Text(
|
||||
if (desiredEnabled) stringResource(R.string.wadb_confirmed_on) else stringResource(R.string.wadb_confirmed_off),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(14.dp),
|
||||
)
|
||||
}
|
||||
PrimaryButton(stringResource(R.string.setup_check_done), enabled = !busy, onClick = onBack)
|
||||
}
|
||||
} else if (compactSplit) {
|
||||
Column(
|
||||
modifier = Modifier.widthIn(max = 600.dp).fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp),
|
||||
) {
|
||||
form()
|
||||
if (!editing) CompactComputerFallback(desiredEnabled)
|
||||
}
|
||||
} else {
|
||||
val routes: @Composable () -> Unit = {
|
||||
FallbackOrder(desiredEnabled, busy, onOpenDeveloperOptions)
|
||||
}
|
||||
if (wide) {
|
||||
Row(
|
||||
modifier = Modifier.widthIn(max = 900.dp).fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(14.dp),
|
||||
verticalAlignment = Alignment.Top,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) { routes() }
|
||||
Column(Modifier.weight(1f)) { form() }
|
||||
}
|
||||
} else {
|
||||
Column(
|
||||
modifier = Modifier.widthIn(max = 600.dp).fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp),
|
||||
) {
|
||||
routes()
|
||||
form()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun WirelessStepForm(
|
||||
step: Int,
|
||||
pairingAddress: String,
|
||||
onPairingAddressChange: (String) -> Unit,
|
||||
pairingCode: String,
|
||||
onPairingCodeChange: (String) -> Unit,
|
||||
connectionAddress: String,
|
||||
onConnectionAddressChange: (String) -> Unit,
|
||||
busy: Boolean,
|
||||
message: String?,
|
||||
messageIsError: Boolean,
|
||||
compact: Boolean,
|
||||
editing: Boolean,
|
||||
onEditingChanged: (Boolean) -> Unit,
|
||||
focusManager: FocusManager,
|
||||
desiredEnabled: Boolean,
|
||||
canPair: Boolean,
|
||||
onPair: () -> Unit,
|
||||
onApply: () -> Unit,
|
||||
onPairAgain: () -> Unit,
|
||||
) {
|
||||
if (step == 0) {
|
||||
SettingsGroup(stringResource(R.string.wadb_pair_group), compact = compact) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = if (compact) 8.dp else 12.dp, vertical = if (compact) 6.dp else 12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(if (compact) 5.dp else 6.dp),
|
||||
) {
|
||||
AdbTextField(
|
||||
value = pairingAddress,
|
||||
onValueChange = onPairingAddressChange,
|
||||
label = stringResource(R.string.wadb_pair_address),
|
||||
placeholder = "192.168.1.42:37123",
|
||||
keyboardType = KeyboardType.Ascii,
|
||||
imeAction = ImeAction.Next,
|
||||
compact = compact,
|
||||
onFocusChange = onEditingChanged,
|
||||
onNext = { focusManager.moveFocus(FocusDirection.Next) },
|
||||
)
|
||||
Row(
|
||||
verticalAlignment = Alignment.Bottom,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
AdbTextField(
|
||||
value = pairingCode,
|
||||
onValueChange = onPairingCodeChange,
|
||||
label = stringResource(R.string.wadb_pin),
|
||||
placeholder = stringResource(R.string.wadb_pin_placeholder),
|
||||
keyboardType = KeyboardType.Number,
|
||||
imeAction = ImeAction.Done,
|
||||
compact = compact,
|
||||
onFocusChange = onEditingChanged,
|
||||
onDone = {
|
||||
focusManager.clearFocus()
|
||||
},
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
PrimaryButton(stringResource(R.string.wadb_pair), compact = compact, enabled = !busy && canPair, onClick = onPair)
|
||||
}
|
||||
StatusMessage(busy, message, isError = messageIsError)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
SettingsGroup(stringResource(R.string.wadb_apply_group), compact = compact) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = if (compact) 8.dp else 12.dp, vertical = if (compact) 6.dp else 12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(if (compact) 5.dp else 6.dp),
|
||||
) {
|
||||
AdbTextField(
|
||||
value = connectionAddress,
|
||||
onValueChange = onConnectionAddressChange,
|
||||
label = stringResource(R.string.wadb_connect_address),
|
||||
placeholder = "192.168.1.42:45678",
|
||||
keyboardType = KeyboardType.Ascii,
|
||||
imeAction = ImeAction.Done,
|
||||
compact = compact,
|
||||
onFocusChange = onEditingChanged,
|
||||
onDone = { focusManager.clearFocus() },
|
||||
)
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
StatusMessage(busy, message, Modifier.weight(1f), isError = messageIsError)
|
||||
SecondaryButton(stringResource(R.string.wadb_pair_again), compact = compact, enabled = !busy, onClick = onPairAgain)
|
||||
PrimaryButton(
|
||||
if (desiredEnabled) stringResource(R.string.setup_limit_turn_on) else stringResource(R.string.wadb_turn_off),
|
||||
compact = compact,
|
||||
enabled = !busy && parseAdbAddress(connectionAddress) != null,
|
||||
onClick = onApply,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun AdbTextField(
|
||||
value: String,
|
||||
onValueChange: (String) -> Unit,
|
||||
label: String,
|
||||
keyboardType: KeyboardType,
|
||||
imeAction: ImeAction,
|
||||
modifier: Modifier = Modifier,
|
||||
placeholder: String? = null,
|
||||
compact: Boolean = false,
|
||||
onFocusChange: (Boolean) -> Unit = {},
|
||||
clearFocus: Boolean = false,
|
||||
onNext: (() -> Unit)? = null,
|
||||
onDone: (() -> Unit)? = null,
|
||||
focusOnShow: Boolean = false,
|
||||
showLabel: Boolean = true,
|
||||
onBack: (() -> Unit)? = null,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val onBackLatest = rememberUpdatedState(onBack)
|
||||
val focusAsked = remember { booleanArrayOf(false) }
|
||||
val palette = LocalPalette.current
|
||||
val onValueChangeLatest = rememberUpdatedState(onValueChange)
|
||||
val onNextLatest = rememberUpdatedState(onNext)
|
||||
val onDoneLatest = rememberUpdatedState(onDone)
|
||||
val onFocusChangeLatest = rememberUpdatedState(onFocusChange)
|
||||
var focused by remember { mutableStateOf(false) }
|
||||
val shape = RoundedCornerShape(8.dp)
|
||||
val inputHeight = if (compact) 44.dp else 52.dp
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val bottomTyping = LocalBottomTyping.current
|
||||
val bottomTypingLatest = rememberUpdatedState(bottomTyping)
|
||||
val typingRequest = remember { arrayOfNulls<TypingRequest>(1) }
|
||||
|
||||
fun typeOnBottom(editText: EditText): Boolean {
|
||||
if (!bottomTypingLatest.value || !DualScreenPanel.attached) return false
|
||||
val text = editText.text.toString()
|
||||
lateinit var request: TypingRequest
|
||||
request = TypingRequest(
|
||||
TextFieldValue(text, TextRange(editText.selectionStart.coerceIn(0, text.length), editText.selectionEnd.coerceIn(0, text.length))),
|
||||
ImeOptions(singleLine = true, keyboardType = keyboardType, imeAction = imeAction),
|
||||
{ next ->
|
||||
if (editText.text.toString() != next.text) editText.setText(next.text)
|
||||
editText.setSelection(next.selection.start.coerceIn(0, next.text.length), next.selection.end.coerceIn(0, next.text.length))
|
||||
},
|
||||
{ action -> editText.onEditorAction(imeActionFlag(action)) },
|
||||
{ editText.post { if (typingRequest[0] === request) onBackLatest.value?.invoke() ?: editText.clearFocus() } },
|
||||
)
|
||||
typingRequest[0] = request
|
||||
DualScreenPanel.startTyping(request)
|
||||
return true
|
||||
}
|
||||
|
||||
DisposableEffect(Unit) {
|
||||
onDispose { typingRequest[0]?.let { DualScreenPanel.stopTyping(it) } }
|
||||
}
|
||||
|
||||
Column(modifier = modifier.fillMaxWidth()) {
|
||||
if (showLabel) Text(
|
||||
label,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = colors.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
)
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(inputHeight)
|
||||
.background(colors.surfaceVariant, shape)
|
||||
.glideBorder(focused, shape, palette.signal, palette.line2)
|
||||
.padding(horizontal = 10.dp),
|
||||
contentAlignment = Alignment.CenterStart,
|
||||
) {
|
||||
AndroidView(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
factory = { viewContext ->
|
||||
EditText(viewContext).apply {
|
||||
isSingleLine = true
|
||||
setHorizontallyScrolling(true)
|
||||
background = null
|
||||
setPadding((2 * context.resources.displayMetrics.density).roundToInt(), 0, 0, 0)
|
||||
setTextSize(android.util.TypedValue.COMPLEX_UNIT_SP, if (compact) 13f else 14f)
|
||||
setTextColor(colors.onBackground.toArgb())
|
||||
setHintTextColor(colors.onSurfaceVariant.toArgb())
|
||||
contentDescription = label
|
||||
inputType = if (keyboardType == KeyboardType.Number) {
|
||||
InputType.TYPE_CLASS_NUMBER
|
||||
} else {
|
||||
InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
|
||||
}
|
||||
imeOptions = imeActionFlag(imeAction) or EditorInfo.IME_FLAG_NO_FULLSCREEN or EditorInfo.IME_FLAG_NO_EXTRACT_UI
|
||||
hint = placeholder
|
||||
setOnEditorActionListener { _, actionId, event ->
|
||||
val isEnter = event?.keyCode == android.view.KeyEvent.KEYCODE_ENTER
|
||||
when {
|
||||
imeAction == ImeAction.Next && (actionId == EditorInfo.IME_ACTION_NEXT || isEnter) -> {
|
||||
onNextLatest.value?.invoke()
|
||||
true
|
||||
}
|
||||
imeAction == ImeAction.Done && (actionId == EditorInfo.IME_ACTION_DONE || isEnter) -> {
|
||||
onDoneLatest.value?.invoke()
|
||||
true
|
||||
}
|
||||
// Search and Go are terminal: leaving them unhandled
|
||||
// keeps focus in the field, so the keyboard would stay
|
||||
// up over the results it was used to find.
|
||||
imeAction in setOf(ImeAction.Search, ImeAction.Go) &&
|
||||
(actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_GO || isEnter) -> {
|
||||
onDoneLatest.value?.invoke()
|
||||
post {
|
||||
clearFocus()
|
||||
(context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE)
|
||||
as? android.view.inputmethod.InputMethodManager)
|
||||
?.hideSoftInputFromWindow(windowToken, 0)
|
||||
}
|
||||
true
|
||||
}
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
showSoftInputOnFocus = !bottomTyping
|
||||
// B on a controller puts the keyboard away first; with no keyboard up it goes back as usual.
|
||||
var hidingKeyboard = false
|
||||
setOnKeyListener { view, keyCode, event ->
|
||||
if (keyCode != android.view.KeyEvent.KEYCODE_BUTTON_B) return@setOnKeyListener false
|
||||
if (event.action == android.view.KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||
hidingKeyboard = androidx.core.view.ViewCompat.getRootWindowInsets(view)
|
||||
?.isVisible(androidx.core.view.WindowInsetsCompat.Type.ime()) == true
|
||||
if (hidingKeyboard) (view.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager)
|
||||
?.hideSoftInputFromWindow(view.windowToken, 0)
|
||||
onBackLatest.value?.let { hidingKeyboard = true; it() }
|
||||
}
|
||||
hidingKeyboard
|
||||
}
|
||||
setOnClickListener { if (hasFocus() && !typeOnBottom(this) && bottomTypingLatest.value) showKeyboardHere(this) }
|
||||
setOnFocusChangeListener { _, hasFocus ->
|
||||
focused = hasFocus
|
||||
if (hasFocus) { if (!typeOnBottom(this) && bottomTypingLatest.value) showKeyboardHere(this) }
|
||||
else typingRequest[0]?.let { DualScreenPanel.stopTyping(it) }
|
||||
onFocusChangeLatest.value(hasFocus)
|
||||
}
|
||||
addTextChangedListener(object : TextWatcher {
|
||||
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
|
||||
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit
|
||||
override fun afterTextChanged(s: Editable?) {
|
||||
onValueChangeLatest.value(s?.toString().orEmpty())
|
||||
}
|
||||
})
|
||||
}
|
||||
},
|
||||
update = { editText ->
|
||||
editText.showSoftInputOnFocus = !bottomTyping
|
||||
if (focusOnShow && !focusAsked[0]) {
|
||||
focusAsked[0] = true
|
||||
editText.post {
|
||||
editText.requestFocus()
|
||||
if (!bottomTypingLatest.value) (editText.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager)
|
||||
?.showSoftInput(editText, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT)
|
||||
}
|
||||
}
|
||||
if (clearFocus && editText.hasFocus()) {
|
||||
editText.clearFocus()
|
||||
(editText.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager)
|
||||
?.hideSoftInputFromWindow(editText.windowToken, 0)
|
||||
}
|
||||
editText.setTextColor(colors.onBackground.toArgb())
|
||||
editText.setHintTextColor(colors.onSurfaceVariant.toArgb())
|
||||
editText.hint = placeholder
|
||||
editText.contentDescription = label
|
||||
if (editText.text.toString() != value) {
|
||||
val cursor = if (editText.hasFocus()) editText.selectionStart.coerceAtLeast(0) else value.length
|
||||
editText.setText(value)
|
||||
editText.setSelection(min(cursor, value.length))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FallbackOrder(
|
||||
desiredEnabled: Boolean,
|
||||
busy: Boolean,
|
||||
onOpenDeveloperOptions: () -> Unit,
|
||||
) {
|
||||
SettingsGroup(stringResource(R.string.wadb_other_ways)) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
Text(stringResource(R.string.wadb_dev_try_first), style = MaterialTheme.typography.bodySmall, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground)
|
||||
Text(if (desiredEnabled) stringResource(R.string.wadb_restrict_on) else stringResource(R.string.wadb_restrict_off), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
SecondaryButton(stringResource(R.string.gate_open_dev), enabled = !busy, onClick = onOpenDeveloperOptions)
|
||||
Text(stringResource(R.string.wadb_computer_last), style = MaterialTheme.typography.bodySmall, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground)
|
||||
Text(stringResource(R.string.wadb_only_if), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Text(
|
||||
PhantomProcessLimit.adbCommand(desiredEnabled),
|
||||
style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CompactComputerFallback(desiredEnabled: Boolean) {
|
||||
SettingsGroup(stringResource(R.string.wadb_computer_group), compact = true) {
|
||||
Text(
|
||||
PhantomProcessLimit.adbCommand(desiredEnabled),
|
||||
style = MaterialTheme.typography.labelSmall.copy(fontFamily = FontFamily.Monospace),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatusMessage(busy: Boolean, message: String?, modifier: Modifier = Modifier, isError: Boolean = false) {
|
||||
if (busy) {
|
||||
Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp)
|
||||
Text(message ?: stringResource(R.string.common_working), style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
} else {
|
||||
message?.let {
|
||||
Text(
|
||||
it,
|
||||
modifier = modifier,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = if (isError) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private data class AdbEndpoint(val host: String, val port: Int)
|
||||
|
||||
private fun parseAdbAddress(value: String): AdbEndpoint? {
|
||||
val address = value.trim()
|
||||
val host: String
|
||||
val portText: String
|
||||
if (address.startsWith("[")) {
|
||||
val closingBracket = address.indexOf(']')
|
||||
if (closingBracket <= 1 || address.getOrNull(closingBracket + 1) != ':') return null
|
||||
host = address.substring(1, closingBracket)
|
||||
if (':' !in host) return null
|
||||
portText = address.substring(closingBracket + 2)
|
||||
} else {
|
||||
val colon = address.lastIndexOf(':')
|
||||
if (colon <= 0 || address.indexOf(':') != colon) return null
|
||||
host = address.substring(0, colon)
|
||||
portText = address.substring(colon + 1)
|
||||
}
|
||||
if (host.isBlank() || host.any(Char::isWhitespace)) return null
|
||||
val port = portText.toIntOrNull()?.takeIf { it in 1..65535 } ?: return null
|
||||
return AdbEndpoint(host, port)
|
||||
}
|
||||
|
||||
private fun formatAddressHost(host: String): String = if (':' in host) "[$host]" else host
|
||||
private fun formatAdbAddress(host: String, port: Int): String = "${formatAddressHost(host)}:$port"
|
||||
|
||||
private fun showKeyboardHere(editText: EditText) {
|
||||
(editText.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager)
|
||||
?.showSoftInput(editText, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT)
|
||||
}
|
||||
|
||||
private fun imeActionFlag(action: ImeAction): Int = when (action) {
|
||||
ImeAction.Next -> EditorInfo.IME_ACTION_NEXT
|
||||
ImeAction.Done -> EditorInfo.IME_ACTION_DONE
|
||||
ImeAction.Go -> EditorInfo.IME_ACTION_GO
|
||||
ImeAction.Search -> EditorInfo.IME_ACTION_SEARCH
|
||||
else -> EditorInfo.IME_ACTION_UNSPECIFIED
|
||||
}
|
||||
@@ -332,6 +332,7 @@
|
||||
<string name="mode_startup">بدء التشغيل</string>
|
||||
<string name="mode_startup_session">الفتح عند التشغيل</string>
|
||||
<string name="mode_startup_session_hint">يبدأ هذه الجلسة عند تشغيل DroidDeck.</string>
|
||||
<string name="mode_decky">Decky</string>
|
||||
<string name="mode_decky_checking">جارٍ البحث عن إصدارات…</string>
|
||||
<string name="mode_decky_ready">جاهز لتثبيت %1$s.</string>
|
||||
<string name="mode_decky_none">لم يتم العثور على إصدار متوافق. حاول مرة أخرى لاحقًا.</string>
|
||||
@@ -340,10 +341,14 @@
|
||||
<string name="mode_decky_current">محدَّث · %1$s</string>
|
||||
<string name="mode_decky_loader">المُحمِّل</string>
|
||||
<string name="mode_decky_install_latest">تثبيت أحدث إصدار</string>
|
||||
<string name="decky_channel">قناة التحديث</string>
|
||||
<string name="decky_channel_hint">إصدارات Decky Loader التي تُثبَّت. يستخدم مُحدِّث Decky نفسه القناة ذاتها.</string>
|
||||
<string name="decky_channel_stable">مستقرة</string>
|
||||
<string name="decky_channel_prerelease">إصدار تجريبي مسبق</string>
|
||||
<string name="decky_channel_testing">اختبار</string>
|
||||
<string name="decky_channel_failed">تعذّر حفظ قناة تحديث Decky</string>
|
||||
<string name="mode_decky_on">يبدأ مع Steam. أثناء تفعيله، قد تتمكن التطبيقات الأخرى على هذا الجهاز من التحكم في Steam.</string>
|
||||
<string name="mode_decky_off">متوقف. يبقى منفذ تصحيح الأخطاء عن بُعد في Steam مغلقًا.</string>
|
||||
<string name="mode_decky_remove_title">هل تريد إلغاء تثبيت Decky Loader؟</string>
|
||||
<string name="mode_decky_remove_text">يزيل المُحمِّل. يتم الاحتفاظ بالمكونات الإضافية والإعدادات.</string>
|
||||
<string name="mode_client">العميل</string>
|
||||
@@ -1304,6 +1309,8 @@
|
||||
<string name="gate_open_dev">فتح خيارات المطوّرين</string>
|
||||
<string name="gate_no_toggle">لا يحتوي إصدار Android هذا على مفتاح لذلك، لذا يغيّره DroidDeck عبر تصحيح الأخطاء اللاسلكي. يستغرق نحو دقيقة، ولا يحتاج إلى جهاز كمبيوتر.</string>
|
||||
<string name="gate_needs_wifi">يحتاج تصحيح الأخطاء اللاسلكي إلى Wi-Fi. تعمل أي شبكة؛ فهو لا يحتاج إلى اتصال بالإنترنت.</string>
|
||||
<string name="gate_needs_notifications">يظهر رمز الإقران في إشعار. فعِّل الإشعارات لـ DroidDeck، أو استخدم «طرق أخرى».</string>
|
||||
<string name="gate_allow_notifications">السماح بالإشعارات</string>
|
||||
<string name="gate_step1">افتح الإعدادات ← خيارات المطوّرين ← تصحيح الأخطاء اللاسلكي وفعِّله</string>
|
||||
<string name="gate_step2">اضغط على «إقران جهاز برمز إقران»</string>
|
||||
<string name="gate_step3">أدخل الرمز في إشعار DroidDeck</string>
|
||||
@@ -1320,13 +1327,48 @@
|
||||
<string name="gate_status">الحالة</string>
|
||||
<string name="gate_polling">يتم التحقّق كل ثانيتين. تُغلَق هذه الصفحة عند إيقافه.</string>
|
||||
<string name="gate_other_ways">طرق أخرى</string>
|
||||
<string name="gate_other_toggle">تصحيح الأخطاء اللاسلكي، عنوان يدوي، ADB من كمبيوتر</string>
|
||||
<string name="gate_other_no_toggle">عنوان يدوي، ADB من كمبيوتر، خيارات المطوّرين</string>
|
||||
<string name="gate_use_wireless_instead">استخدام تصحيح الأخطاء اللاسلكي بدلًا من ذلك</string>
|
||||
<string name="gate_some_roms">تضيف بعض إصدارات ROM هذا المفتاح رغم ذلك. ابحث عن «العمليات الفرعية» في خيارات المطوّرين.</string>
|
||||
<string name="gate_manual_hint">إذا لم ينجح الإشعار، أدخل عنوان النافذة المنبثقة ورمزها بنفسك.</string>
|
||||
<string name="gate_enter_manually">إدخال العنوان يدويًا</string>
|
||||
<string name="gate_from_computer">من جهاز كمبيوتر يحتوي على ADB:</string>
|
||||
<string name="gate_copy_command">نسخ الأمر</string>
|
||||
<string name="gate_sidequest_steps">وصّل النظارة بالكمبيوتر وافتح SideQuest. اختر “Run ADB Command” ثم “Custom Command”، واكتب الأمر الظاهر أدناه، ثم اختر “Run Command”.</string>
|
||||
<string name="gate_choose_display">اختر الشاشة التي ستُفتَح فيها إعدادات Android.</string>
|
||||
<string name="gate_main_screen">الشاشة الرئيسية</string>
|
||||
<string name="wadb_finding_port">تم الإقران. جارٍ البحث عن منفذ تصحيح الأخطاء اللاسلكي…</string>
|
||||
<string name="wadb_enter_port">تم الإقران. أدخل المنفذ من الإعدادات.</string>
|
||||
<string name="wadb_applying">تم العثور على الجهاز. جارٍ تطبيق الإعداد…</string>
|
||||
<string name="wadb_apply_failed">تعذّر التطبيق تلقائيًا. تحقّق من العنوان أدناه وأعد المحاولة. %1$s</string>
|
||||
<string name="wadb_title_wireless">تصحيح الأخطاء اللاسلكي</string>
|
||||
<string name="wadb_title_done">تم تحديث حد العمليات الفرعية</string>
|
||||
<string name="wadb_title">تغيير حد العمليات الفرعية</string>
|
||||
<string name="wadb_lede_compact0">إذا كان هذا الخيار غير متاح، فأقرن عبر تصحيح الأخطاء اللاسلكي.</string>
|
||||
<string name="wadb_lede_compact1">تم الإقران. تحقّق من عنوان IP والمنفذ في تصحيح الأخطاء اللاسلكي.</string>
|
||||
<string name="wadb_lede_done">تم تحديث حد العمليات الفرعية.</string>
|
||||
<string name="wadb_lede0">استخدم الخطوة 2 إذا لم يكن في خيارات المطوّرين إعداد للعمليات الفرعية. افتح خيارات المطوّرين ← تصحيح الأخطاء اللاسلكي ← إقران جهاز برمز إقران.</string>
|
||||
<string name="wadb_lede1">تم الإقران. استخدم العنوان أدناه، أو حدِّثه من تصحيح الأخطاء اللاسلكي ← عنوان IP والمنفذ.</string>
|
||||
<string name="wadb_lede_done_long">تم تحديث حد العمليات الفرعية عبر تصحيح الأخطاء اللاسلكي.</string>
|
||||
<string name="wadb_confirmed_on">أكّد Android أن الحد مفعّل.</string>
|
||||
<string name="wadb_confirmed_off">أكّد Android أن الحد معطّل.</string>
|
||||
<string name="wadb_pair_group">2 · إقران تصحيح الأخطاء اللاسلكي</string>
|
||||
<string name="wadb_pair_address">عنوان IP ومنفذ النافذة المنبثقة للإقران</string>
|
||||
<string name="wadb_pin">رمز الإقران (PIN)</string>
|
||||
<string name="wadb_pin_placeholder">6 أرقام</string>
|
||||
<string name="wadb_pair">إقران</string>
|
||||
<string name="wadb_apply_group">2 · التطبيق عبر تصحيح الأخطاء اللاسلكي</string>
|
||||
<string name="wadb_connect_address">عنوان IP ومنفذ الاتصال</string>
|
||||
<string name="wadb_pair_again">إقران مرة أخرى</string>
|
||||
<string name="wadb_turn_off">إيقاف الحد</string>
|
||||
<string name="wadb_other_ways">طرق أخرى لتغييره</string>
|
||||
<string name="wadb_dev_try_first">1 · خيارات المطوّرين (جرّب هذا أولًا)</string>
|
||||
<string name="wadb_restrict_on">عطِّل «إيقاف القيود المفروضة على العمليات الثانوية».</string>
|
||||
<string name="wadb_restrict_off">فعِّل «إيقاف القيود المفروضة على العمليات الثانوية».</string>
|
||||
<string name="wadb_computer_last">3 · ADB من كمبيوتر (كخيار أخير)</string>
|
||||
<string name="wadb_only_if">فقط إذا كان تصحيح الأخطاء اللاسلكي غير متاح.</string>
|
||||
<string name="wadb_computer_group">3 · ADB من كمبيوتر (كخيار أخير)</string>
|
||||
<string name="ctrl_color">اللون</string>
|
||||
<string name="ctrl_custom">مخصّص</string>
|
||||
<string name="ctrl_opacity">العتامة</string>
|
||||
@@ -1638,6 +1680,8 @@
|
||||
<item quantity="many">تم محو %1$d مجلدًا لسجلات الجلسات.</item>
|
||||
<item quantity="other">تم محو %1$d مجلد لسجلات الجلسات.</item>
|
||||
</plurals>
|
||||
<string name="main_wadb_pair_failed">فشل الإقران عبر تصحيح الأخطاء اللاسلكي</string>
|
||||
<string name="main_wadb_command_failed">فشل أمر تصحيح الأخطاء اللاسلكي</string>
|
||||
<string name="main_wadb_unavailable">تصحيح الأخطاء اللاسلكي غير متاح</string>
|
||||
<string name="main_adb_copied">تم نسخ أمر ADB</string>
|
||||
<string name="main_pick_roms">اختر مجلد ROMs</string>
|
||||
@@ -4133,7 +4177,6 @@
|
||||
<string name="addons_sort_downloads">الأكثر تنزيلًا</string>
|
||||
<string name="addons_category_all">كل الفئات</string>
|
||||
<string name="addons_none_found">لم يتم العثور على إضافات</string>
|
||||
<string name="addons_curse_busy">أغلق CurseForge أولاً</string>
|
||||
<string name="addons_unreachable">تعذّر الوصول إلى %1$s</string>
|
||||
<string name="addons_no_file">لا يوجد ملف لإصدار اللعبة هذا</string>
|
||||
<string name="input_reset_positions">إعادة تعيين المواضع</string>
|
||||
|
||||
@@ -332,6 +332,7 @@
|
||||
<string name="mode_startup">Inicio</string>
|
||||
<string name="mode_startup_session">Abrir al iniciar</string>
|
||||
<string name="mode_startup_session_hint">Inicia esta sesión cuando se abre DroidDeck.</string>
|
||||
<string name="mode_decky">Decky</string>
|
||||
<string name="mode_decky_checking">Buscando versiones…</string>
|
||||
<string name="mode_decky_ready">Listo para instalar %1$s.</string>
|
||||
<string name="mode_decky_none">No se encontró ninguna versión compatible. Inténtalo más tarde.</string>
|
||||
@@ -340,10 +341,14 @@
|
||||
<string name="mode_decky_current">Al día · %1$s</string>
|
||||
<string name="mode_decky_loader">Loader</string>
|
||||
<string name="mode_decky_install_latest">Instalar la última</string>
|
||||
<string name="decky_channel">Canal de actualizaciones</string>
|
||||
<string name="decky_channel_hint">Qué versiones de Decky Loader se instalan. El actualizador propio de Decky usa el mismo canal.</string>
|
||||
<string name="decky_channel_stable">Estable</string>
|
||||
<string name="decky_channel_prerelease">Preliminar</string>
|
||||
<string name="decky_channel_testing">Pruebas</string>
|
||||
<string name="decky_channel_failed">No se pudo guardar el canal de actualizaciones de Decky</string>
|
||||
<string name="mode_decky_on">Se inicia con Steam. Mientras esté activado, otras apps de este dispositivo podrían controlar Steam.</string>
|
||||
<string name="mode_decky_off">Desactivado. El puerto de depuración remota de Steam permanece cerrado.</string>
|
||||
<string name="mode_decky_remove_title">¿Desinstalar Decky Loader?</string>
|
||||
<string name="mode_decky_remove_text">Elimina el loader. Tus plugins y ajustes se conservan.</string>
|
||||
<string name="mode_client">Cliente</string>
|
||||
@@ -1310,6 +1315,8 @@
|
||||
<string name="gate_open_dev">Abrir Opciones de desarrollador</string>
|
||||
<string name="gate_no_toggle">Esta versión de Android no tiene un interruptor para ello, así que DroidDeck lo cambia mediante la Depuración inalámbrica. Tarda un minuto y no necesitas una computadora.</string>
|
||||
<string name="gate_needs_wifi">La Depuración inalámbrica necesita Wi-Fi. Sirve cualquier red; no necesita internet.</string>
|
||||
<string name="gate_needs_notifications">El código de vinculación aparece en una notificación. Permite las notificaciones de DroidDeck o usa Otras formas.</string>
|
||||
<string name="gate_allow_notifications">Permitir notificaciones</string>
|
||||
<string name="gate_step1">Abre Ajustes → Opciones de desarrollador → Depuración inalámbrica y actívala</string>
|
||||
<string name="gate_step2">Toca “Vincular dispositivo con código de vinculación”</string>
|
||||
<string name="gate_step3">Escribe el código en la notificación de DroidDeck</string>
|
||||
@@ -1326,13 +1333,48 @@
|
||||
<string name="gate_status">Estado</string>
|
||||
<string name="gate_polling">Se comprueba cada 2 segundos. Esta página se cierra cuando esté desactivado.</string>
|
||||
<string name="gate_other_ways">Otras formas</string>
|
||||
<string name="gate_other_toggle">Depuración inalámbrica, dirección manual, ADB desde una computadora</string>
|
||||
<string name="gate_other_no_toggle">Dirección manual, ADB desde una computadora, Opciones de desarrollador</string>
|
||||
<string name="gate_use_wireless_instead">Usar Depuración inalámbrica en su lugar</string>
|
||||
<string name="gate_some_roms">Algunas ROM agregan el interruptor de todos modos. Busca “procesos secundarios” en Opciones de desarrollador.</string>
|
||||
<string name="gate_manual_hint">Si la notificación no funciona, ingresa manualmente la dirección y el código de la ventana.</string>
|
||||
<string name="gate_enter_manually">Ingresar dirección manualmente</string>
|
||||
<string name="gate_from_computer">Desde una computadora con ADB:</string>
|
||||
<string name="gate_copy_command">Copiar comando</string>
|
||||
<string name="gate_sidequest_steps">Conecta el visor a una computadora y abre SideQuest. Elige “Run ADB Command” y luego “Custom Command”, escribe el comando que aparece abajo y selecciona “Run Command”.</string>
|
||||
<string name="gate_choose_display">Elige en qué pantalla abrir los Ajustes de Android.</string>
|
||||
<string name="gate_main_screen">Pantalla principal</string>
|
||||
<string name="wadb_finding_port">Vinculado. Buscando el puerto de la Depuración inalámbrica…</string>
|
||||
<string name="wadb_enter_port">Vinculado. Ingresa el puerto de Ajustes.</string>
|
||||
<string name="wadb_applying">Dispositivo encontrado. Aplicando el ajuste…</string>
|
||||
<string name="wadb_apply_failed">No se pudo aplicar automáticamente. Revisa la dirección de abajo y reintenta. %1$s</string>
|
||||
<string name="wadb_title_wireless">Depuración inalámbrica</string>
|
||||
<string name="wadb_title_done">Límite de procesos secundarios actualizado</string>
|
||||
<string name="wadb_title">Cambiar el límite de procesos secundarios</string>
|
||||
<string name="wadb_lede_compact0">Si falta la opción, vincula mediante la Depuración inalámbrica.</string>
|
||||
<string name="wadb_lede_compact1">Vinculado. Revisa la dirección IP y el puerto en Depuración inalámbrica.</string>
|
||||
<string name="wadb_lede_done">El límite de procesos secundarios se actualizó.</string>
|
||||
<string name="wadb_lede0">Usa el paso 2 si las Opciones de desarrollador no tienen un ajuste de procesos secundarios. Abre Opciones de desarrollador → Depuración inalámbrica → Vincular dispositivo con código de vinculación.</string>
|
||||
<string name="wadb_lede1">Vinculado. Usa la dirección de abajo o actualízala desde Depuración inalámbrica → Dirección IP y puerto.</string>
|
||||
<string name="wadb_lede_done_long">El límite de procesos secundarios se actualizó mediante la Depuración inalámbrica.</string>
|
||||
<string name="wadb_confirmed_on">Android confirmó que el límite está activado.</string>
|
||||
<string name="wadb_confirmed_off">Android confirmó que el límite está desactivado.</string>
|
||||
<string name="wadb_pair_group">2 · Vincular Depuración inalámbrica</string>
|
||||
<string name="wadb_pair_address">Dirección IP y puerto de la ventana de vinculación</string>
|
||||
<string name="wadb_pin">Código de vinculación (PIN)</string>
|
||||
<string name="wadb_pin_placeholder">6 dígitos</string>
|
||||
<string name="wadb_pair">Vincular</string>
|
||||
<string name="wadb_apply_group">2 · Aplicar mediante Depuración inalámbrica</string>
|
||||
<string name="wadb_connect_address">Dirección IP y puerto de conexión</string>
|
||||
<string name="wadb_pair_again">Vincular de nuevo</string>
|
||||
<string name="wadb_turn_off">Desactivar límite</string>
|
||||
<string name="wadb_other_ways">Otras formas de cambiarlo</string>
|
||||
<string name="wadb_dev_try_first">1 · Opciones de desarrollador (pruébalo primero)</string>
|
||||
<string name="wadb_restrict_on">Desactiva “Inhabilitar restricciones de procesos secundarios”.</string>
|
||||
<string name="wadb_restrict_off">Activa “Inhabilitar restricciones de procesos secundarios”.</string>
|
||||
<string name="wadb_computer_last">3 · ADB desde una computadora (último recurso)</string>
|
||||
<string name="wadb_only_if">Solo si la Depuración inalámbrica no está disponible.</string>
|
||||
<string name="wadb_computer_group">3 · ADB desde una computadora (último recurso)</string>
|
||||
<string name="ctrl_color">Color</string>
|
||||
<string name="ctrl_custom">Personalizado</string>
|
||||
<string name="ctrl_opacity">Opacidad</string>
|
||||
@@ -1669,6 +1711,8 @@
|
||||
<item quantity="other">Se borraron %1$d carpetas de registros de sesión.</item>
|
||||
<item quantity="many">Se borraron %1$d carpetas de registros de sesión.</item>
|
||||
</plurals>
|
||||
<string name="main_wadb_pair_failed">Falló la vinculación de la Depuración inalámbrica</string>
|
||||
<string name="main_wadb_command_failed">Falló el comando de la Depuración inalámbrica</string>
|
||||
<string name="main_wadb_unavailable">La Depuración inalámbrica no está disponible</string>
|
||||
<string name="main_adb_copied">Comando ADB copiado</string>
|
||||
<string name="main_pick_roms">Elige la carpeta de ROMs</string>
|
||||
@@ -4013,7 +4057,6 @@
|
||||
<string name="addons_sort_downloads">Más descargados</string>
|
||||
<string name="addons_category_all">Todas las categorías</string>
|
||||
<string name="addons_none_found">No se encontraron complementos</string>
|
||||
<string name="addons_curse_busy">Cierra CurseForge primero</string>
|
||||
<string name="addons_unreachable">No se pudo conectar con %1$s</string>
|
||||
<string name="addons_no_file">No hay archivo para esta versión del juego</string>
|
||||
<string name="input_reset_positions">Restablecer posiciones</string>
|
||||
|
||||
@@ -332,6 +332,7 @@
|
||||
<string name="mode_startup">Стартиране</string>
|
||||
<string name="mode_startup_session">Отваряне при стартиране</string>
|
||||
<string name="mode_startup_session_hint">Стартира тази сесия, когато DroidDeck се стартира.</string>
|
||||
<string name="mode_decky">Decky</string>
|
||||
<string name="mode_decky_checking">Проверка за издания…</string>
|
||||
<string name="mode_decky_ready">Готово за инсталиране на %1$s.</string>
|
||||
<string name="mode_decky_none">Не е намерена съвместима версия. Опитайте по-късно.</string>
|
||||
@@ -340,10 +341,14 @@
|
||||
<string name="mode_decky_current">Актуално · %1$s</string>
|
||||
<string name="mode_decky_loader">Зареждач</string>
|
||||
<string name="mode_decky_install_latest">Инсталиране на последната версия</string>
|
||||
<string name="decky_channel">Канал за актуализации</string>
|
||||
<string name="decky_channel_hint">Кои издания на Decky Loader да се инсталират. Собственият актуализатор на Decky използва същия канал.</string>
|
||||
<string name="decky_channel_stable">Стабилен</string>
|
||||
<string name="decky_channel_prerelease">Предварителен</string>
|
||||
<string name="decky_channel_testing">Тестов</string>
|
||||
<string name="decky_channel_failed">Каналът за актуализации на Decky не можа да бъде запазен</string>
|
||||
<string name="mode_decky_on">Стартира заедно със Steam. Докато е включено, други приложения на това устройство може да могат да контролират Steam.</string>
|
||||
<string name="mode_decky_off">Изключено. Портът за отдалечено дебъгване на Steam остава затворен.</string>
|
||||
<string name="mode_decky_remove_title">Деинсталиране на Decky Loader?</string>
|
||||
<string name="mode_decky_remove_text">Премахва зареждащия модул. Плъгините и настройките ви се запазват.</string>
|
||||
<string name="mode_client">Клиент</string>
|
||||
@@ -1276,6 +1281,8 @@
|
||||
<string name="gate_open_dev">Отваряне на Опции за програмисти</string>
|
||||
<string name="gate_no_toggle">Тази версия на Android няма превключвател за това, затова DroidDeck го променя чрез безжично отстраняване на грешки. Отнема около минута, не е нужен компютър.</string>
|
||||
<string name="gate_needs_wifi">Безжичното отстраняване на грешки изисква Wi-Fi. Работи с всяка мрежа; не е необходим интернет.</string>
|
||||
<string name="gate_needs_notifications">Кодът за сдвояване се показва в известие. Разрешете известията за DroidDeck или използвайте „Други начини“.</string>
|
||||
<string name="gate_allow_notifications">Разрешаване на известията</string>
|
||||
<string name="gate_step1">Отворете Настройки → Опции за програмисти → Безжично отстраняване на грешки и го включете</string>
|
||||
<string name="gate_step2">Докоснете „Сдвояване на устройство с код за сдвояване“</string>
|
||||
<string name="gate_step3">Въведете кода в известието на DroidDeck</string>
|
||||
@@ -1292,13 +1299,48 @@
|
||||
<string name="gate_status">Състояние</string>
|
||||
<string name="gate_polling">Проверява се на всеки 2 секунди. Тази страница се затваря, когато е изключено.</string>
|
||||
<string name="gate_other_ways">Други начини</string>
|
||||
<string name="gate_other_toggle">Безжично отстраняване на грешки, ръчен адрес, ADB от компютър</string>
|
||||
<string name="gate_other_no_toggle">Ръчен адрес, ADB от компютър, Опции за програмисти</string>
|
||||
<string name="gate_use_wireless_instead">Използване на безжично отстраняване на грешки вместо това</string>
|
||||
<string name="gate_some_roms">Някои ROM-и добавят превключвателя въпреки това. Потърсете „child process“ в Опции за програмисти.</string>
|
||||
<string name="gate_manual_hint">Ако известието не работи, въведете сами адреса и кода от изскачащия прозорец.</string>
|
||||
<string name="gate_enter_manually">Ръчно въвеждане на адреса</string>
|
||||
<string name="gate_from_computer">От компютър с ADB:</string>
|
||||
<string name="gate_copy_command">Копиране на командата</string>
|
||||
<string name="gate_sidequest_steps">Свържете шлема с компютър и отворете SideQuest. Изберете „Run ADB Command“, после „Custom Command“, въведете командата, показана по-долу, и изберете „Run Command“.</string>
|
||||
<string name="gate_choose_display">Изберете на кой екран да се отворят настройките на Android.</string>
|
||||
<string name="gate_main_screen">Основен екран</string>
|
||||
<string name="wadb_finding_port">Сдвоено. Търсене на порта за безжично отстраняване на грешки…</string>
|
||||
<string name="wadb_enter_port">Сдвоено. Въведете порта от Настройки.</string>
|
||||
<string name="wadb_applying">Устройството е намерено. Прилагане на настройката…</string>
|
||||
<string name="wadb_apply_failed">Не можа да се приложи автоматично. Проверете адреса по-долу и опитайте отново. %1$s</string>
|
||||
<string name="wadb_title_wireless">Безжично отстраняване на грешки</string>
|
||||
<string name="wadb_title_done">Ограничението на дъщерните процеси е актуализирано</string>
|
||||
<string name="wadb_title">Промяна на ограничението на дъщерните процеси</string>
|
||||
<string name="wadb_lede_compact0">Ако опцията липсва, сдвоете чрез безжично отстраняване на грешки.</string>
|
||||
<string name="wadb_lede_compact1">Сдвоено. Проверете IP адреса и порта в безжичното отстраняване на грешки.</string>
|
||||
<string name="wadb_lede_done">Ограничението на дъщерните процеси беше актуализирано.</string>
|
||||
<string name="wadb_lede0">Използвайте стъпка 2, ако Опции за програмисти нямат настройка за дъщерни процеси. Отворете Опции за програмисти → Безжично отстраняване на грешки → Сдвояване на устройство с код за сдвояване.</string>
|
||||
<string name="wadb_lede1">Сдвоено. Използвайте адреса по-долу или го обновете от Безжично отстраняване на грешки → IP адрес и порт.</string>
|
||||
<string name="wadb_lede_done_long">Ограничението на дъщерните процеси беше актуализирано чрез безжично отстраняване на грешки.</string>
|
||||
<string name="wadb_confirmed_on">Android потвърди, че ограничението е включено.</string>
|
||||
<string name="wadb_confirmed_off">Android потвърди, че ограничението е изключено.</string>
|
||||
<string name="wadb_pair_group">2 · Сдвояване на безжично отстраняване на грешки</string>
|
||||
<string name="wadb_pair_address">IP адрес и порт на изскачащия прозорец за сдвояване</string>
|
||||
<string name="wadb_pin">Код за сдвояване (PIN)</string>
|
||||
<string name="wadb_pin_placeholder">6 цифри</string>
|
||||
<string name="wadb_pair">Сдвояване</string>
|
||||
<string name="wadb_apply_group">2 · Прилагане чрез безжично отстраняване на грешки</string>
|
||||
<string name="wadb_connect_address">IP адрес и порт за връзка</string>
|
||||
<string name="wadb_pair_again">Сдвояване отново</string>
|
||||
<string name="wadb_turn_off">Изключване на ограничението</string>
|
||||
<string name="wadb_other_ways">Други начини за промяна</string>
|
||||
<string name="wadb_dev_try_first">1 · Опции за програмисти (пробвайте първо)</string>
|
||||
<string name="wadb_restrict_on">Изключете „Деактивиране на ограниченията за дъщерните процеси“.</string>
|
||||
<string name="wadb_restrict_off">Включете „Деактивиране на ограниченията за дъщерните процеси“.</string>
|
||||
<string name="wadb_computer_last">3 · ADB от компютър (последна възможност)</string>
|
||||
<string name="wadb_only_if">Само ако безжичното отстраняване на грешки не е достъпно.</string>
|
||||
<string name="wadb_computer_group">3 · ADB от компютър (последна възможност)</string>
|
||||
<string name="ctrl_color">Цвят</string>
|
||||
<string name="ctrl_custom">Персонализиран</string>
|
||||
<string name="ctrl_opacity">Прозрачност</string>
|
||||
@@ -1586,6 +1628,8 @@
|
||||
<item quantity="one">Изчистена %1$d папка с логове от сесия.</item>
|
||||
<item quantity="other">Изчистени %1$d папки с логове от сесии.</item>
|
||||
</plurals>
|
||||
<string name="main_wadb_pair_failed">Чифтосването за безжично отстраняване на грешки се провали</string>
|
||||
<string name="main_wadb_command_failed">Командата за безжично отстраняване на грешки се провали</string>
|
||||
<string name="main_wadb_unavailable">Безжичното отстраняване на грешки не е достъпно</string>
|
||||
<string name="main_adb_copied">Командата за ADB е копирана</string>
|
||||
<string name="main_pick_roms">Избор на папката ROMs</string>
|
||||
@@ -3973,7 +4017,6 @@
|
||||
<string name="addons_sort_downloads">Най-изтегляни</string>
|
||||
<string name="addons_category_all">Всички категории</string>
|
||||
<string name="addons_none_found">Няма намерени добавки</string>
|
||||
<string name="addons_curse_busy">Първо затворете CurseForge</string>
|
||||
<string name="addons_unreachable">Няма връзка с %1$s</string>
|
||||
<string name="addons_no_file">Няма файл за тази версия на играта</string>
|
||||
<string name="input_reset_positions">Нулиране на позициите</string>
|
||||
|
||||
@@ -332,6 +332,7 @@
|
||||
<string name="mode_startup">Spouštění</string>
|
||||
<string name="mode_startup_session">Otevřít při spuštění</string>
|
||||
<string name="mode_startup_session_hint">Spustí tuto relaci při spuštění DroidDeck.</string>
|
||||
<string name="mode_decky">Decky</string>
|
||||
<string name="mode_decky_checking">Hledání vydání…</string>
|
||||
<string name="mode_decky_ready">Připraveno k instalaci %1$s.</string>
|
||||
<string name="mode_decky_none">Nenalezeno žádné kompatibilní sestavení. Zkuste to později.</string>
|
||||
@@ -340,10 +341,14 @@
|
||||
<string name="mode_decky_current">Aktuální · %1$s</string>
|
||||
<string name="mode_decky_loader">Loader</string>
|
||||
<string name="mode_decky_install_latest">Nainstalovat nejnovější</string>
|
||||
<string name="decky_channel">Kanál aktualizací</string>
|
||||
<string name="decky_channel_hint">Která vydání Decky Loader instalovat. Vlastní aktualizátor Decky používá stejný kanál.</string>
|
||||
<string name="decky_channel_stable">Stabilní</string>
|
||||
<string name="decky_channel_prerelease">Předběžné vydání</string>
|
||||
<string name="decky_channel_testing">Testovací</string>
|
||||
<string name="decky_channel_failed">Kanál aktualizací Decky se nepodařilo uložit</string>
|
||||
<string name="mode_decky_on">Spouští se se Steamem. Když je zapnuto, jiné aplikace na tomto zařízení mohou mít možnost ovládat Steam.</string>
|
||||
<string name="mode_decky_off">Vypnuto. Port pro vzdálené ladění Steamu zůstává zavřený.</string>
|
||||
<string name="mode_decky_remove_title">Odinstalovat Decky Loader?</string>
|
||||
<string name="mode_decky_remove_text">Odstraní loader. Vaše pluginy a nastavení zůstanou zachovány.</string>
|
||||
<string name="mode_client">Klient</string>
|
||||
@@ -1290,6 +1295,8 @@
|
||||
<string name="gate_open_dev">Otevřít Možnosti pro vývojáře</string>
|
||||
<string name="gate_no_toggle">Tato verze Androidu pro to nemá přepínač, proto to DroidDeck změní přes Bezdrátové ladění. Zabere to asi minutu, počítač není potřeba.</string>
|
||||
<string name="gate_needs_wifi">Bezdrátové ladění potřebuje Wi-Fi. Funguje jakákoli síť, internet není nutný.</string>
|
||||
<string name="gate_needs_notifications">Párovací kód se zobrazí v oznámení. Povolte oznámení pro DroidDeck, nebo použijte Jiné způsoby.</string>
|
||||
<string name="gate_allow_notifications">Povolit oznámení</string>
|
||||
<string name="gate_step1">Otevřete Nastavení → Možnosti pro vývojáře → Bezdrátové ladění a zapněte ho</string>
|
||||
<string name="gate_step2">Klepněte na „Spárovat zařízení pomocí párovacího kódu“</string>
|
||||
<string name="gate_step3">Zadejte kód do oznámení DroidDecku</string>
|
||||
@@ -1306,13 +1313,48 @@
|
||||
<string name="gate_status">Stav</string>
|
||||
<string name="gate_polling">Kontroluje se každé 2 sekundy. Tato stránka se zavře, až bude vypnuto.</string>
|
||||
<string name="gate_other_ways">Jiné způsoby</string>
|
||||
<string name="gate_other_toggle">Bezdrátové ladění, ruční adresa, ADB z počítače</string>
|
||||
<string name="gate_other_no_toggle">Ruční adresa, ADB z počítače, Možnosti pro vývojáře</string>
|
||||
<string name="gate_use_wireless_instead">Použít místo toho Bezdrátové ladění</string>
|
||||
<string name="gate_some_roms">Některé ROM přepínač přidávají i tak. Hledejte v Možnostech pro vývojáře „child process“.</string>
|
||||
<string name="gate_manual_hint">Pokud oznámení nefunguje, zadejte adresu a kód z okna sami.</string>
|
||||
<string name="gate_enter_manually">Zadat adresu ručně</string>
|
||||
<string name="gate_from_computer">Z počítače s ADB:</string>
|
||||
<string name="gate_copy_command">Kopírovat příkaz</string>
|
||||
<string name="gate_sidequest_steps">Připojte headset k počítači a otevřete SideQuest. Zvolte „Run ADB Command“, pak „Custom Command“, opište příkaz zobrazený níže a vyberte „Run Command“.</string>
|
||||
<string name="gate_choose_display">Vyberte, na kterém displeji se má otevřít Nastavení Androidu.</string>
|
||||
<string name="gate_main_screen">Hlavní obrazovka</string>
|
||||
<string name="wadb_finding_port">Spárováno. Hledání portu Bezdrátového ladění…</string>
|
||||
<string name="wadb_enter_port">Spárováno. Zadejte port z Nastavení.</string>
|
||||
<string name="wadb_applying">Zařízení nalezeno. Používá se nastavení…</string>
|
||||
<string name="wadb_apply_failed">Nepodařilo se použít automaticky. Zkontrolujte adresu níže a zkuste to znovu. %1$s</string>
|
||||
<string name="wadb_title_wireless">Bezdrátové ladění</string>
|
||||
<string name="wadb_title_done">Omezení pro dětské procesy aktualizováno</string>
|
||||
<string name="wadb_title">Změnit omezení pro dětské procesy</string>
|
||||
<string name="wadb_lede_compact0">Pokud volba chybí, spárujte přes Bezdrátové ladění.</string>
|
||||
<string name="wadb_lede_compact1">Spárováno. Zkontrolujte IP adresu a port v Bezdrátovém ladění.</string>
|
||||
<string name="wadb_lede_done">Omezení pro dětské procesy bylo aktualizováno.</string>
|
||||
<string name="wadb_lede0">Krok 2 použijte, pokud Možnosti pro vývojáře nemají nastavení pro dětské procesy. Otevřete Možnosti pro vývojáře → Bezdrátové ladění → Spárovat zařízení pomocí párovacího kódu.</string>
|
||||
<string name="wadb_lede1">Spárováno. Použijte adresu níže, nebo ji aktualizujte z Bezdrátové ladění → IP adresa a port.</string>
|
||||
<string name="wadb_lede_done_long">Omezení pro dětské procesy bylo aktualizováno přes Bezdrátové ladění.</string>
|
||||
<string name="wadb_confirmed_on">Android potvrdil, že omezení je zapnuto.</string>
|
||||
<string name="wadb_confirmed_off">Android potvrdil, že omezení je vypnuto.</string>
|
||||
<string name="wadb_pair_group">2 · Spárovat Bezdrátové ladění</string>
|
||||
<string name="wadb_pair_address">IP adresa a port párovacího okna</string>
|
||||
<string name="wadb_pin">Párovací kód (PIN)</string>
|
||||
<string name="wadb_pin_placeholder">6 číslic</string>
|
||||
<string name="wadb_pair">Spárovat</string>
|
||||
<string name="wadb_apply_group">2 · Použít přes Bezdrátové ladění</string>
|
||||
<string name="wadb_connect_address">IP adresa a port pro připojení</string>
|
||||
<string name="wadb_pair_again">Spárovat znovu</string>
|
||||
<string name="wadb_turn_off">Vypnout omezení</string>
|
||||
<string name="wadb_other_ways">Jiné způsoby změny</string>
|
||||
<string name="wadb_dev_try_first">1 · Možnosti pro vývojáře (zkusit nejdřív)</string>
|
||||
<string name="wadb_restrict_on">Vypněte „Deaktivace omezení podřízených procesů“.</string>
|
||||
<string name="wadb_restrict_off">Zapněte „Deaktivace omezení podřízených procesů“.</string>
|
||||
<string name="wadb_computer_last">3 · ADB z počítače (poslední možnost)</string>
|
||||
<string name="wadb_only_if">Jen pokud Bezdrátové ladění není k dispozici.</string>
|
||||
<string name="wadb_computer_group">3 · ADB z počítače (poslední možnost)</string>
|
||||
<string name="ctrl_color">Barva</string>
|
||||
<string name="ctrl_custom">Vlastní</string>
|
||||
<string name="ctrl_opacity">Průhlednost</string>
|
||||
@@ -1612,6 +1654,8 @@
|
||||
<item quantity="many">Vyčištěno %1$d složek s logy relace.</item>
|
||||
<item quantity="other">Vyčištěno %1$d složek s logy relace.</item>
|
||||
</plurals>
|
||||
<string name="main_wadb_pair_failed">Párování bezdrátového ladění se nezdařilo</string>
|
||||
<string name="main_wadb_command_failed">Příkaz bezdrátového ladění se nezdařil</string>
|
||||
<string name="main_wadb_unavailable">Bezdrátové ladění není k dispozici</string>
|
||||
<string name="main_adb_copied">Příkaz ADB zkopírován</string>
|
||||
<string name="main_pick_roms">Vybrat složku ROMs</string>
|
||||
@@ -4053,7 +4097,6 @@
|
||||
<string name="addons_sort_downloads">Nejstahovanější</string>
|
||||
<string name="addons_category_all">Všechny kategorie</string>
|
||||
<string name="addons_none_found">Nenalezeny žádné doplňky</string>
|
||||
<string name="addons_curse_busy">Nejprve zavřete CurseForge</string>
|
||||
<string name="addons_unreachable">Nelze se připojit k %1$s</string>
|
||||
<string name="addons_no_file">Pro tuto verzi hry není k dispozici soubor</string>
|
||||
<string name="input_reset_positions">Obnovit pozice</string>
|
||||
|
||||
@@ -332,6 +332,7 @@
|
||||
<string name="mode_startup">Opstart</string>
|
||||
<string name="mode_startup_session">Åbn ved start</string>
|
||||
<string name="mode_startup_session_hint">Starter denne session, når DroidDeck startes.</string>
|
||||
<string name="mode_decky">Decky</string>
|
||||
<string name="mode_decky_checking">Søger efter udgivelser…</string>
|
||||
<string name="mode_decky_ready">Klar til at installere %1$s.</string>
|
||||
<string name="mode_decky_none">Ingen kompatibel build fundet. Prøv igen senere.</string>
|
||||
@@ -340,10 +341,14 @@
|
||||
<string name="mode_decky_current">Opdateret · %1$s</string>
|
||||
<string name="mode_decky_loader">Loader</string>
|
||||
<string name="mode_decky_install_latest">Installer nyeste</string>
|
||||
<string name="decky_channel">Opdateringskanal</string>
|
||||
<string name="decky_channel_hint">Hvilke Decky Loader-udgivelser der installeres. Deckys egen opdatering bruger samme kanal.</string>
|
||||
<string name="decky_channel_stable">Stabil</string>
|
||||
<string name="decky_channel_prerelease">Forhåndsudgivelse</string>
|
||||
<string name="decky_channel_testing">Test</string>
|
||||
<string name="decky_channel_failed">Kunne ikke gemme Decky-opdateringskanalen</string>
|
||||
<string name="mode_decky_on">Starter med Steam. Mens den er til, kan andre apps på denne enhed muligvis styre Steam.</string>
|
||||
<string name="mode_decky_off">Fra. Steams fjerndebugport forbliver lukket.</string>
|
||||
<string name="mode_decky_remove_title">Afinstaller Decky Loader?</string>
|
||||
<string name="mode_decky_remove_text">Fjerner loaderen. Dine plugins og indstillinger bevares.</string>
|
||||
<string name="mode_client">Klient</string>
|
||||
@@ -1276,6 +1281,8 @@
|
||||
<string name="gate_open_dev">Åbn Udviklerindstillinger</string>
|
||||
<string name="gate_no_toggle">Denne Android-version har ingen kontakt til det, så DroidDeck ændrer det via Trådløs fejlretning. Tager omkring et minut, ingen computer nødvendig.</string>
|
||||
<string name="gate_needs_wifi">Trådløs fejlretning kræver Wi-Fi. Alle netværk fungerer; det kræver ikke internet.</string>
|
||||
<string name="gate_needs_notifications">Parringskoden kommer i en notifikation. Tillad notifikationer for DroidDeck, eller brug Andre måder.</string>
|
||||
<string name="gate_allow_notifications">Tillad notifikationer</string>
|
||||
<string name="gate_step1">Åbn Indstillinger → Udviklerindstillinger → Trådløs fejlretning, og slå den til</string>
|
||||
<string name="gate_step2">Tryk på “Par enhed med parringskode”</string>
|
||||
<string name="gate_step3">Indtast koden i DroidDeck-notifikationen</string>
|
||||
@@ -1292,13 +1299,48 @@
|
||||
<string name="gate_status">Status</string>
|
||||
<string name="gate_polling">Kontrollerer hvert 2. sekund. Denne side lukker, når den er fra.</string>
|
||||
<string name="gate_other_ways">Andre måder</string>
|
||||
<string name="gate_other_toggle">Trådløs fejlretning, manuel adresse, computer-ADB</string>
|
||||
<string name="gate_other_no_toggle">Manuel adresse, computer-ADB, Udviklerindstillinger</string>
|
||||
<string name="gate_use_wireless_instead">Brug Trådløs fejlretning i stedet</string>
|
||||
<string name="gate_some_roms">Nogle ROM’er tilføjer kontakten alligevel. Kig efter “underprocesser” i Udviklerindstillinger.</string>
|
||||
<string name="gate_manual_hint">Hvis notifikationen ikke virker, kan du selv indtaste vinduets adresse og kode.</string>
|
||||
<string name="gate_enter_manually">Indtast adresse manuelt</string>
|
||||
<string name="gate_from_computer">Fra en computer med ADB:</string>
|
||||
<string name="gate_copy_command">Kopier kommando</string>
|
||||
<string name="gate_sidequest_steps">Slut headsettet til en computer, og åbn SideQuest. Vælg “Run ADB Command” og derefter “Custom Command”, skriv kommandoen vist nedenfor, og vælg “Run Command”.</string>
|
||||
<string name="gate_choose_display">Vælg, hvilken skærm Android-indstillinger skal åbnes på.</string>
|
||||
<string name="gate_main_screen">Hovedskærm</string>
|
||||
<string name="wadb_finding_port">Parret. Finder porten for Trådløs fejlretning…</string>
|
||||
<string name="wadb_enter_port">Parret. Indtast porten fra Indstillinger.</string>
|
||||
<string name="wadb_applying">Enhed fundet. Anvender indstillingen…</string>
|
||||
<string name="wadb_apply_failed">Kunne ikke anvendes automatisk. Kontroller adressen nedenfor, og prøv igen. %1$s</string>
|
||||
<string name="wadb_title_wireless">Trådløs fejlretning</string>
|
||||
<string name="wadb_title_done">Grænsen for underprocesser opdateret</string>
|
||||
<string name="wadb_title">Ændr grænsen for underprocesser</string>
|
||||
<string name="wadb_lede_compact0">Hvis indstillingen mangler, skal du parre via Trådløs fejlretning.</string>
|
||||
<string name="wadb_lede_compact1">Parret. Kontroller IP-adressen og porten i Trådløs fejlretning.</string>
|
||||
<string name="wadb_lede_done">Grænsen for underprocesser blev opdateret.</string>
|
||||
<string name="wadb_lede0">Brug trin 2, hvis Udviklerindstillinger ikke har en indstilling for underprocesser. Åbn Udviklerindstillinger → Trådløs fejlretning → Par enhed med parringskode.</string>
|
||||
<string name="wadb_lede1">Parret. Brug adressen nedenfor, eller opdater den fra Trådløs fejlretning → IP-adresse og port.</string>
|
||||
<string name="wadb_lede_done_long">Grænsen for underprocesser blev opdateret via Trådløs fejlretning.</string>
|
||||
<string name="wadb_confirmed_on">Android bekræftede, at grænsen er til.</string>
|
||||
<string name="wadb_confirmed_off">Android bekræftede, at grænsen er fra.</string>
|
||||
<string name="wadb_pair_group">2 · Par Trådløs fejlretning</string>
|
||||
<string name="wadb_pair_address">Parringsvinduets IP-adresse og port</string>
|
||||
<string name="wadb_pin">Parringskode (PIN)</string>
|
||||
<string name="wadb_pin_placeholder">6 cifre</string>
|
||||
<string name="wadb_pair">Par</string>
|
||||
<string name="wadb_apply_group">2 · Anvend via Trådløs fejlretning</string>
|
||||
<string name="wadb_connect_address">Forbindelsens IP-adresse og port</string>
|
||||
<string name="wadb_pair_again">Par igen</string>
|
||||
<string name="wadb_turn_off">Slå grænsen fra</string>
|
||||
<string name="wadb_other_ways">Andre måder at ændre det</string>
|
||||
<string name="wadb_dev_try_first">1 · Udviklerindstillinger (prøv først)</string>
|
||||
<string name="wadb_restrict_on">Slå “Deaktiver begrænsningerne for underprocesser” fra.</string>
|
||||
<string name="wadb_restrict_off">Slå “Deaktiver begrænsningerne for underprocesser” til.</string>
|
||||
<string name="wadb_computer_last">3 · Computer-ADB (sidste udvej)</string>
|
||||
<string name="wadb_only_if">Kun hvis Trådløs fejlretning ikke er tilgængelig.</string>
|
||||
<string name="wadb_computer_group">3 · Computer-ADB (sidste udvej)</string>
|
||||
<string name="ctrl_color">Farve</string>
|
||||
<string name="ctrl_custom">Brugerdefineret</string>
|
||||
<string name="ctrl_opacity">Gennemsigtighed</string>
|
||||
@@ -1586,6 +1628,8 @@
|
||||
<item quantity="one">Ryddede %1$d sessionslogmappe.</item>
|
||||
<item quantity="other">Ryddede %1$d sessionslogmapper.</item>
|
||||
</plurals>
|
||||
<string name="main_wadb_pair_failed">Parring til trådløs fejlretning mislykkedes</string>
|
||||
<string name="main_wadb_command_failed">Kommando til trådløs fejlretning mislykkedes</string>
|
||||
<string name="main_wadb_unavailable">Trådløs fejlretning er ikke tilgængelig</string>
|
||||
<string name="main_adb_copied">ADB-kommando kopieret</string>
|
||||
<string name="main_pick_roms">Vælg ROMs-mappen</string>
|
||||
@@ -3973,7 +4017,6 @@
|
||||
<string name="addons_sort_downloads">Mest downloadet</string>
|
||||
<string name="addons_category_all">Alle kategorier</string>
|
||||
<string name="addons_none_found">Ingen tilføjelser fundet</string>
|
||||
<string name="addons_curse_busy">Luk CurseForge først</string>
|
||||
<string name="addons_unreachable">Kunne ikke nå %1$s</string>
|
||||
<string name="addons_no_file">Ingen fil til denne spilversion</string>
|
||||
<string name="input_reset_positions">Nulstil placeringer</string>
|
||||
|
||||
@@ -332,6 +332,7 @@
|
||||
<string name="mode_startup">Start</string>
|
||||
<string name="mode_startup_session">Beim Start öffnen</string>
|
||||
<string name="mode_startup_session_hint">Startet diese Sitzung, wenn DroidDeck startet.</string>
|
||||
<string name="mode_decky">Decky</string>
|
||||
<string name="mode_decky_checking">Suche nach Releases…</string>
|
||||
<string name="mode_decky_ready">Bereit zur Installation von %1$s.</string>
|
||||
<string name="mode_decky_none">Kein kompatibler Build gefunden. Versuch es später noch einmal.</string>
|
||||
@@ -340,10 +341,14 @@
|
||||
<string name="mode_decky_current">Aktuell · %1$s</string>
|
||||
<string name="mode_decky_loader">Loader</string>
|
||||
<string name="mode_decky_install_latest">Neueste Version installieren</string>
|
||||
<string name="decky_channel">Update-Kanal</string>
|
||||
<string name="decky_channel_hint">Welche Decky-Loader-Releases installiert werden. Deckys eigener Updater nutzt denselben Kanal.</string>
|
||||
<string name="decky_channel_stable">Stabil</string>
|
||||
<string name="decky_channel_prerelease">Vorabversion</string>
|
||||
<string name="decky_channel_testing">Test</string>
|
||||
<string name="decky_channel_failed">Decky-Update-Kanal konnte nicht gespeichert werden</string>
|
||||
<string name="mode_decky_on">Startet mit Steam. Solange aktiv, können andere Apps auf diesem Gerät Steam möglicherweise steuern.</string>
|
||||
<string name="mode_decky_off">Aus. Der Remote-Debugging-Port von Steam bleibt geschlossen.</string>
|
||||
<string name="mode_decky_remove_title">Decky Loader deinstallieren?</string>
|
||||
<string name="mode_decky_remove_text">Entfernt den Loader. Deine Plugins und Einstellungen bleiben erhalten.</string>
|
||||
<string name="mode_client">Client</string>
|
||||
@@ -1268,6 +1273,8 @@
|
||||
<string name="gate_open_dev">Entwickleroptionen öffnen</string>
|
||||
<string name="gate_no_toggle">Diese Android-Version hat dafür keinen Schalter, deshalb ändert DroidDeck es über „Debugging über WLAN“. Dauert etwa eine Minute, kein Computer nötig.</string>
|
||||
<string name="gate_needs_wifi">„Debugging über WLAN“ braucht eine Wi-Fi-Verbindung. Jedes Netzwerk geht; Internet ist nicht nötig.</string>
|
||||
<string name="gate_needs_notifications">Der Kopplungscode wird in eine Benachrichtigung eingegeben. Erlaube Benachrichtigungen für DroidDeck oder nutze „Andere Wege“.</string>
|
||||
<string name="gate_allow_notifications">Benachrichtigungen erlauben</string>
|
||||
<string name="gate_step1">Öffne Einstellungen → Entwickleroptionen → Debugging über WLAN und aktiviere es</string>
|
||||
<string name="gate_step2">Tippe auf „Gerät über einen Kopplungscode koppeln“</string>
|
||||
<string name="gate_step3">Gib den Code in die DroidDeck-Benachrichtigung ein</string>
|
||||
@@ -1284,13 +1291,48 @@
|
||||
<string name="gate_status">Status</string>
|
||||
<string name="gate_polling">Prüft alle 2 Sekunden. Diese Seite schließt sich, sobald es aus ist.</string>
|
||||
<string name="gate_other_ways">Andere Wege</string>
|
||||
<string name="gate_other_toggle">Debugging über WLAN, manuelle Adresse, ADB am Computer</string>
|
||||
<string name="gate_other_no_toggle">Manuelle Adresse, ADB am Computer, Entwickleroptionen</string>
|
||||
<string name="gate_use_wireless_instead">Stattdessen „Debugging über WLAN“ verwenden</string>
|
||||
<string name="gate_some_roms">Manche ROMs haben den Schalter trotzdem. Suche in den Entwickleroptionen nach „untergeordnete Prozesse“.</string>
|
||||
<string name="gate_manual_hint">Falls die Benachrichtigung nicht funktioniert, gib Adresse und Code des Pop-ups selbst ein.</string>
|
||||
<string name="gate_enter_manually">Adresse manuell eingeben</string>
|
||||
<string name="gate_from_computer">Von einem Computer mit ADB:</string>
|
||||
<string name="gate_copy_command">Befehl kopieren</string>
|
||||
<string name="gate_sidequest_steps">Verbinde das Headset mit einem Computer und öffne SideQuest. Wähle „Run ADB Command“, dann „Custom Command“, tippe den unten gezeigten Befehl ein und wähle „Run Command“.</string>
|
||||
<string name="gate_choose_display">Wähle, auf welchem Display die Android-Einstellungen geöffnet werden.</string>
|
||||
<string name="gate_main_screen">Hauptbildschirm</string>
|
||||
<string name="wadb_finding_port">Gekoppelt. Suche den Port für Debugging über WLAN…</string>
|
||||
<string name="wadb_enter_port">Gekoppelt. Gib den Port aus den Einstellungen ein.</string>
|
||||
<string name="wadb_applying">Gerät gefunden. Einstellung wird angewendet…</string>
|
||||
<string name="wadb_apply_failed">Automatisches Anwenden fehlgeschlagen. Prüfe die Adresse unten und versuch es erneut. %1$s</string>
|
||||
<string name="wadb_title_wireless">Debugging über WLAN</string>
|
||||
<string name="wadb_title_done">Limit für untergeordnete Prozesse aktualisiert</string>
|
||||
<string name="wadb_title">Limit für untergeordnete Prozesse ändern</string>
|
||||
<string name="wadb_lede_compact0">Fehlt die Option, kopple über „Debugging über WLAN“.</string>
|
||||
<string name="wadb_lede_compact1">Gekoppelt. Prüfe IP-Adresse und Port unter „Debugging über WLAN“.</string>
|
||||
<string name="wadb_lede_done">Das Limit für untergeordnete Prozesse wurde aktualisiert.</string>
|
||||
<string name="wadb_lede0">Nutze Schritt 2, wenn die Entwickleroptionen keine Einstellung für untergeordnete Prozesse haben. Öffne Entwickleroptionen → Debugging über WLAN → Gerät über einen Kopplungscode koppeln.</string>
|
||||
<string name="wadb_lede1">Gekoppelt. Nutze die Adresse unten oder aktualisiere sie über Debugging über WLAN → IP-Adresse und Port.</string>
|
||||
<string name="wadb_lede_done_long">Das Limit für untergeordnete Prozesse wurde über „Debugging über WLAN“ aktualisiert.</string>
|
||||
<string name="wadb_confirmed_on">Android hat bestätigt, dass das Limit aktiv ist.</string>
|
||||
<string name="wadb_confirmed_off">Android hat bestätigt, dass das Limit aus ist.</string>
|
||||
<string name="wadb_pair_group">2 · Für Debugging über WLAN koppeln</string>
|
||||
<string name="wadb_pair_address">IP-Adresse und Port aus dem Kopplungs-Pop-up</string>
|
||||
<string name="wadb_pin">Kopplungscode (PIN)</string>
|
||||
<string name="wadb_pin_placeholder">6 Ziffern</string>
|
||||
<string name="wadb_pair">Koppeln</string>
|
||||
<string name="wadb_apply_group">2 · Per Debugging über WLAN anwenden</string>
|
||||
<string name="wadb_connect_address">IP-Adresse und Port für die Verbindung</string>
|
||||
<string name="wadb_pair_again">Erneut koppeln</string>
|
||||
<string name="wadb_turn_off">Limit deaktivieren</string>
|
||||
<string name="wadb_other_ways">Andere Wege, es zu ändern</string>
|
||||
<string name="wadb_dev_try_first">1 · Entwickleroptionen (zuerst versuchen)</string>
|
||||
<string name="wadb_restrict_on">Schalte „Beschränkungen für Unterprozesse deaktivieren“ aus.</string>
|
||||
<string name="wadb_restrict_off">Schalte „Beschränkungen für Unterprozesse deaktivieren“ ein.</string>
|
||||
<string name="wadb_computer_last">3 · ADB am Computer (letzter Ausweg)</string>
|
||||
<string name="wadb_only_if">Nur wenn „Debugging über WLAN“ nicht verfügbar ist.</string>
|
||||
<string name="wadb_computer_group">3 · ADB am Computer (letzter Ausweg)</string>
|
||||
<string name="ctrl_color">Farbe</string>
|
||||
<string name="ctrl_custom">Benutzerdefiniert</string>
|
||||
<string name="ctrl_opacity">Deckkraft</string>
|
||||
@@ -1578,6 +1620,8 @@
|
||||
<item quantity="one">%1$d Ordner mit Sitzungsprotokollen gelöscht.</item>
|
||||
<item quantity="other">%1$d Ordner mit Sitzungsprotokollen gelöscht.</item>
|
||||
</plurals>
|
||||
<string name="main_wadb_pair_failed">Kopplung für Debugging über WLAN fehlgeschlagen</string>
|
||||
<string name="main_wadb_command_failed">Befehl für Debugging über WLAN fehlgeschlagen</string>
|
||||
<string name="main_wadb_unavailable">Debugging über WLAN ist nicht verfügbar</string>
|
||||
<string name="main_adb_copied">ADB-Befehl kopiert</string>
|
||||
<string name="main_pick_roms">ROMs-Ordner auswählen</string>
|
||||
@@ -3973,7 +4017,6 @@
|
||||
<string name="addons_sort_downloads">Meistgeladen</string>
|
||||
<string name="addons_category_all">Alle Kategorien</string>
|
||||
<string name="addons_none_found">Keine Addons gefunden</string>
|
||||
<string name="addons_curse_busy">Schließe zuerst CurseForge</string>
|
||||
<string name="addons_unreachable">%1$s ist nicht erreichbar</string>
|
||||
<string name="addons_no_file">Keine Datei für diese Spielversion</string>
|
||||
<string name="input_reset_positions">Positionen zurücksetzen</string>
|
||||
|
||||
Loaded 100 of 273 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user