From 367151be2cdd72ebc7ee89f899b06a45c6ccd0e3 Mon Sep 17 00:00:00 2001 From: K11MCH1 <81425424+K11MCH1@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:56:31 +0900 Subject: [PATCH 001/141] fix(epic): start parent-checking Epic titles under an EpicGamesLauncher.exe stand-in and stage their Rockstar SDK (#2932) * fix(epic): start Epic titles that check their parent under an EpicGamesLauncher.exe stand-in Rockstar's launcher only accepts an Epic copy of GTA V when a process named EpicGamesLauncher.exe started it. DroidDeck's Epic client is a Linux program, so the launcher logged "Epic Games Launcher not detected as parent process", failed to relaunch through Epic and showed the game as unowned. - tools/epic-launcher: a small Windows EpicGamesLauncher.exe that starts the game with the rest of its own command line, unchanged, waits for it and returns its exit code. It ships as the epic add-on pack. - The Epic .droiddeck-launch.bat runs the game through it for Epic titles known to need it (GTA V, GTA V Enhanced, RDR2, RDR, GTA SA DE, Returnal, Phantom Blade: Executioners), or for any Epic game whose per-game environment sets DD_EPIC_PARENT=1; DD_EPIC_PARENT=0 turns it off. Those titles also start without Steam's SteamAppId. Without the staged stand-in the game starts directly, as before. - Steam launch options now reach Epic games (%*). - The launch hook fetches the pack when such a title finds it missing. - Rockstar's launcher found no Social Club SDK in the prefix and ran Social-Club-Setup.exe /silent, which never exits under Wine. For Epic titles that carry a Rockstar SDK installer, the hook now extracts the SDK from the launcher's own Redistributables copy (the version the launcher compares against) or, before the launcher is installed, from the game's copy, and registers it. It re-extracts when that installer changes and leaves the Rockstar Games Launcher key alone, so PlayGTAV still installs the launcher on first start. * fix(epic): fetch the parent stand-in exactly when the game will use it; keep Cargo output out of source digests The launch hook runs before droiddeck-game-env applies per-game variables, so it now resolves DD_EPIC_PARENT through droiddeck-game-env's own apply_config and game_id: an unlisted title with DD_EPIC_PARENT=1 fetches the pack, a listed title with DD_EPIC_PARENT=0 no longer waits for it. runtime_inputs no longer hashes the target directory beside a Cargo.toml under its source paths, so a local cargo build of a Windows helper does not fail verify(). tools/epic-launcher gets the same .gitignore as the other helpers. * fix(epic): a DD_EPIC_PARENT in the game's sidecar env decides the stand-in fetch too The .bat sets the sidecar's env before it reads DD_EPIC_PARENT, so that value overrides the game environment there; the launch hook now gives it the same precedence when deciding whether to fetch the pack. * test(epic): keep an inherited DD_EPIC_PARENT out of the launch hook tests --------- Co-authored-by: MaxsTechReview --- .github/workflows/build.yml | 7 + .github/workflows/publish-packs.yml | 2 +- .gitignore | 1 + app/build.gradle | 4 +- .../main/java/com/droiddeck/launcher/App.kt | 2 + .../com/droiddeck/launcher/core/AddonPack.kt | 1 + .../launcher/session/SessionFiles.kt | 3 + .../droiddeck/launcher/stores/StoreLaunch.kt | 23 ++- .../launcher/stores/StoreGameSidecarTest.kt | 35 ++++- tools/build_local.sh | 7 + tools/epic-launcher/.gitignore | 1 + tools/epic-launcher/Cargo.lock | 7 + tools/epic-launcher/Cargo.toml | 16 ++ tools/epic-launcher/README.md | 13 ++ tools/epic-launcher/build.sh | 9 ++ tools/epic-launcher/src/lib.rs | 110 +++++++++++++ tools/epic-launcher/src/main.rs | 42 +++++ .../usr/local/bin/droiddeck-store-launch | 100 ++++++++++-- tools/packs/build.sh | 1 + tools/release/runtime_inputs.py | 15 +- tools/tests/test_runtime_inputs.py | 28 ++++ tools/tests/test_store_launch_rockstar.py | 145 ++++++++++++++++++ 22 files changed, 543 insertions(+), 29 deletions(-) create mode 100644 tools/epic-launcher/.gitignore create mode 100644 tools/epic-launcher/Cargo.lock create mode 100644 tools/epic-launcher/Cargo.toml create mode 100644 tools/epic-launcher/README.md create mode 100755 tools/epic-launcher/build.sh create mode 100644 tools/epic-launcher/src/lib.rs create mode 100644 tools/epic-launcher/src/main.rs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index cfe3e2d57d..c3b3f50cf6 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -577,6 +577,12 @@ jobs: command -v i686-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-i686; } bash tools/rockstar-launcher/build.sh + - name: Epic Games Launcher parent stand-in (x86_64-pc-windows-gnu) + 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 + - uses: actions/download-artifact@v4 with: name: xbox-arm64 @@ -823,6 +829,7 @@ jobs: run: | cargo test --locked --manifest-path tools/ubisoft-launcher/Cargo.toml cargo test --locked --manifest-path tools/rockstar-launcher/Cargo.toml + cargo test --locked --manifest-path tools/epic-launcher/Cargo.toml python-tests: name: Python and native regression tests diff --git a/.github/workflows/publish-packs.yml b/.github/workflows/publish-packs.yml index c9e036f2db..a3c46b8f8b 100644 --- a/.github/workflows/publish-packs.yml +++ b/.github/workflows/publish-packs.yml @@ -55,7 +55,7 @@ jobs: jq -r --arg n "$2" '.assets // [] | .[] | select(.name == $n) | .digest // empty' } commit=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$BUILD_RUN" --jq .head_sha 2>/dev/null || echo "$GITHUB_SHA") - for name in proot directaudio tracking xbox comet butler powervr ubisoft rockstar dirt; do + for name in proot directaudio tracking xbox comet butler powervr ubisoft rockstar dirt epic; do file="packs/$name.tar.zst" [ -f "$file" ] || { echo "::error::$name.tar.zst is missing from Build APK run $BUILD_RUN"; exit 1; } sha=$(sha256sum "$file" | cut -d' ' -f1) diff --git a/.gitignore b/.gitignore index eeb1404467..395d551a1f 100644 --- a/.gitignore +++ b/.gitignore @@ -37,3 +37,4 @@ app/src/main/assets/directaudio/ app/src/main/assets/hybris/ /tools/vr/out/ app/src/main/assets/linuxfs/usr/local/lib/droiddeck-rockstar/ +app/src/main/assets/linuxfs/usr/local/lib/droiddeck-epic/ diff --git a/app/build.gradle b/app/build.gradle index c271f963b9..634a41eec0 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -93,7 +93,7 @@ def trackingPack = rootProject.file('tools/packs/tracking/release.env').readLine def prootPackPin = rootProject.file('tools/packs/proot/release.env').readLines() .findAll { it.contains('=') && !it.startsWith('#') } .collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] } -def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt'].collectEntries { name -> +def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt', 'epic'].collectEntries { name -> def pack = file("build/packs/${name}.tar.zst") if (!pack.isFile()) { if (ciBuild) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs") @@ -202,7 +202,7 @@ android { } androidResources { - ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:_*:!CVS:!thumbs.db:!picasa.ini:!*~:droiddeck-xbox:droiddeck-comet:droiddeck-ubisoft:droiddeck-rockstar:droiddeck-dirt:directaudio:hybris' + ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:_*:!CVS:!thumbs.db:!picasa.ini:!*~:droiddeck-xbox:droiddeck-comet:droiddeck-ubisoft:droiddeck-rockstar:droiddeck-dirt:droiddeck-epic:directaudio:hybris' } packagingOptions { diff --git a/app/src/main/java/com/droiddeck/launcher/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt index 1a45ab8512..e02bbc9d2d 100644 --- a/app/src/main/java/com/droiddeck/launcher/App.kt +++ b/app/src/main/java/com/droiddeck/launcher/App.kt @@ -96,6 +96,8 @@ class App : Application() { com.droiddeck.launcher.session.SessionFiles.ensureUbisoftService(app) if (com.droiddeck.launcher.stores.StoreAccounts.signedInAs(app, com.droiddeck.launcher.stores.Store.ROCKSTAR) != null) com.droiddeck.launcher.session.SessionFiles.ensureRockstarService(app) + if (com.droiddeck.launcher.stores.StoreAccounts.signedInAs(app, com.droiddeck.launcher.stores.Store.EPIC) != null) + com.droiddeck.launcher.session.SessionFiles.ensureEpicParent(app) com.droiddeck.launcher.handtracking.HandTracking.load(app) }.onFailure { android.util.Log.w("App", "add-on pack prefetch failed", it) } }, "addon-packs").start() diff --git a/app/src/main/java/com/droiddeck/launcher/core/AddonPack.kt b/app/src/main/java/com/droiddeck/launcher/core/AddonPack.kt index fec75b544a..d0e2f2b575 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/AddonPack.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/AddonPack.kt @@ -175,5 +175,6 @@ internal class AddonPack( val ROCKSTAR = AddonPack("rockstar", BuildConfig.PACK_ROCKSTAR_SHA256, BuildConfig.PACK_ROCKSTAR_SIZE, listOf("Launcher32.exe", "Launcher64.exe")) val DIRT = AddonPack("dirt", BuildConfig.PACK_DIRT_SHA256, BuildConfig.PACK_DIRT_SIZE, listOf("ws2_32.dll")) + val EPIC = AddonPack("epic", BuildConfig.PACK_EPIC_SHA256, BuildConfig.PACK_EPIC_SIZE, listOf("EpicGamesLauncher.exe")) } } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index 53b54e9ca2..9fb0aaab95 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -39,6 +39,7 @@ object SessionFiles { private val SERVICE_PACKS = mapOf( AddonPack.UBISOFT to "usr/local/lib/droiddeck-ubisoft", AddonPack.ROCKSTAR to "usr/local/lib/droiddeck-rockstar", + AddonPack.EPIC to "usr/local/lib/droiddeck-epic", AddonPack.DIRT to "usr/local/lib/droiddeck-dirt", ) @@ -47,6 +48,8 @@ object SessionFiles { fun ensureRockstarService(context: Context) = ensureStoreService(context, AddonPack.ROCKSTAR) + fun ensureEpicParent(context: Context) = ensureStoreService(context, AddonPack.EPIC) + /** The DiRT 3 / DiRT Showdown ws2_32 stand-in; droiddeck-game-env applies it only when it is staged. */ fun ensureDirtStandIn(context: Context) = ensureStoreService(context, AddonPack.DIRT) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunch.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunch.kt index f45a23c654..e3b8c7932e 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunch.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunch.kt @@ -13,6 +13,15 @@ object StoreLaunch { const val EPIC_ARGS = ".droiddeck-epic-args" const val UBISOFT_LAUNCH = ".droiddeck-ubisoft.json" private const val UBISOFT_SERVICE = "Z:\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe" + const val EPIC_PARENT = "Z:\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe" + /** Per-game environment switch: 1 starts any Epic game under [EPIC_PARENT], 0 never does. */ + const val EPIC_PARENT_SWITCH = "DD_EPIC_PARENT" + /** Epic app names whose launchers treat the game as unowned unless a process named EpicGamesLauncher.exe started it. */ + val EPIC_PARENT_TITLES = setOf( + "9d2d0eb64d5c44529cece33fe2a46482", "8769e24080ea413b8ebca3f1b8c50951", "Heather", + "c180bd9859624278aa20f1333918498a", "0828ecd4297c4f89bfcc45420e695b67", + "e5f031908d2e460b8757387d1a136e48", "afd9f29c1af44610b9e0f9b69742e257", + ) const val EA_ENV = ".droiddeck-ea-env" /** A sleeping stand-in that the launch hook installs; older EA SDKs require a running Origin process. */ const val EA_ORIGIN = "C:\\Program Files (x86)\\Origin\\Origin.exe" @@ -39,22 +48,29 @@ object StoreLaunch { val args = sidecar.args.joinToString(" ") { if (sidecar.store == Store.ROCKSTAR) batchArg(it) else quoteArg(it) } val run = "\"%~dp0$exe\"" + (if (args.isNotEmpty()) " $args" else "") if (sidecar.store == Store.EPIC) { + lines += "set \"$PARENT_VAR=${if (sidecar.id in EPIC_PARENT_TITLES) "1" else ""}\"" + lines += "if \"%$EPIC_PARENT_SWITCH%\"==\"1\" set \"$PARENT_VAR=1\"" + lines += "if \"%$EPIC_PARENT_SWITCH%\"==\"0\" set \"$PARENT_VAR=\"" + lines += "if defined $PARENT_VAR set \"SteamAppId=\"" + lines += "if defined $PARENT_VAR if not exist \"$EPIC_PARENT\" set \"$PARENT_VAR=\"" + lines += "if defined $PARENT_VAR set $PARENT_VAR=\"$EPIC_PARENT\"" + val game = "%$PARENT_VAR% $run" lines += "if exist \"%~dp0$EPIC_ARGS\" goto client" lines += "set \"$CODE_VAR=\"" lines += "if exist \"%~dp0$EPIC_CODE\" set /p $CODE_VAR=<\"%~dp0$EPIC_CODE\"" lines += "if exist \"%~dp0$EPIC_CODE\" del \"%~dp0$EPIC_CODE\"" lines += "if defined $CODE_VAR goto signed" - lines += run + lines += "$game %*" lines += "goto :eof" lines += ":signed" - lines += "set \"$CODE_VAR=\" & $run -AUTH_LOGIN=unused -AUTH_PASSWORD=%$CODE_VAR% -AUTH_TYPE=exchangecode" + lines += "set \"$CODE_VAR=\" & $game -AUTH_LOGIN=unused -AUTH_PASSWORD=%$CODE_VAR% -AUTH_TYPE=exchangecode %*" lines += "goto :eof" lines += ":client" lines += "set \"$CLIENT_VAR=\"" lines += "set /p $CLIENT_VAR=<\"%~dp0$EPIC_ARGS\"" lines += "del \"%~dp0$EPIC_ARGS\"" lines += "if exist \"%~dp0$EPIC_CODE\" del \"%~dp0$EPIC_CODE\"" - lines += "set \"$CLIENT_VAR=\" & \"%~dp0$exe\" %$CLIENT_VAR%" + lines += "set \"$CLIENT_VAR=\" & %$PARENT_VAR% \"%~dp0$exe\" %$CLIENT_VAR% %*" } else if (sidecar.store == Store.ROCKSTAR) { lines += "if not exist \"C:\\Program Files\\Rockstar Games\\Launcher\\launch.json\" goto direct" lines += "\"C:\\Program Files\\Rockstar Games\\Launcher\\Launcher.exe\"" @@ -107,6 +123,7 @@ object StoreLaunch { private const val CODE_VAR = "DD_X" private const val CLIENT_VAR = "DD_A" + private const val PARENT_VAR = "DD_P" fun installedGame(context: Context, store: Store, id: String): Library.SteamGame? { val folder = StoreInstallRoot.gameFolders(context).firstOrNull { folder -> diff --git a/app/src/test/java/com/droiddeck/launcher/stores/StoreGameSidecarTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/StoreGameSidecarTest.kt index b4217895c2..cfde73c1d2 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/StoreGameSidecarTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/StoreGameSidecarTest.kt @@ -117,9 +117,9 @@ class StoreGameSidecarTest { val text = StoreLaunch.launcherText(sample.copy(exe = "Binaries/Win64/Celeste.exe")) assertTrue(text.contains("cd /d \"%~dp0Binaries\\Win64\"\r\n")) assertTrue(text.contains("set \"FOO=bar\"\r\n")) - assertTrue(text.contains("\r\n\"%~dp0Binaries\\Win64\\Celeste.exe\" -EpicPortal -epicusername=\"Some One\"\r\n")) + assertTrue(text.contains("\r\n%DD_P% \"%~dp0Binaries\\Win64\\Celeste.exe\" -EpicPortal -epicusername=\"Some One\" %*\r\n")) assertTrue(text.contains("set /p DD_X=<\"%~dp0.droiddeck-epic-code\"")) - assertTrue(text.contains("set \"DD_X=\" & \"%~dp0Binaries\\Win64\\Celeste.exe\" -EpicPortal -epicusername=\"Some One\" -AUTH_LOGIN=unused -AUTH_PASSWORD=%DD_X% -AUTH_TYPE=exchangecode\r\n")) + assertTrue(text.contains("set \"DD_X=\" & %DD_P% \"%~dp0Binaries\\Win64\\Celeste.exe\" -EpicPortal -epicusername=\"Some One\" -AUTH_LOGIN=unused -AUTH_PASSWORD=%DD_X% -AUTH_TYPE=exchangecode %*\r\n")) assertFalse(text.contains("AUTH=")) assertFalse(text.contains("DD_AUTH")) } @@ -157,11 +157,38 @@ class StoreGameSidecarTest { "set /p DD_A=<\"%~dp0.droiddeck-epic-args\"", "del \"%~dp0.droiddeck-epic-args\"", "if exist \"%~dp0.droiddeck-epic-code\" del \"%~dp0.droiddeck-epic-code\"", - "set \"DD_A=\" & \"%~dp0Binaries\\Win64\\Celeste.exe\" %DD_A%", + "set \"DD_A=\" & %DD_P% \"%~dp0Binaries\\Win64\\Celeste.exe\" %DD_A% %*", ), lines.subList(client + 1, client + 6), ) - assertTrue(text.endsWith("%DD_A%\r\n")) + assertTrue(text.endsWith("%DD_A% %*\r\n")) + } + + private val parentLines = listOf( + "if \"%DD_EPIC_PARENT%\"==\"1\" set \"DD_P=1\"", + "if \"%DD_EPIC_PARENT%\"==\"0\" set \"DD_P=\"", + "if defined DD_P set \"SteamAppId=\"", + "if defined DD_P if not exist \"Z:\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe\" set \"DD_P=\"", + "if defined DD_P set DD_P=\"Z:\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe\"", + ) + + @Test fun epicTitlesThatCheckTheirParentStartUnderTheStandIn() { + for (id in listOf("9d2d0eb64d5c44529cece33fe2a46482", "8769e24080ea413b8ebca3f1b8c50951", "Heather")) { + val lines = StoreLaunch.launcherText(StoreGameSidecar(Store.EPIC, id, "Rockstar title", "PlayGTAV.exe")).split("\r\n") + val on = lines.indexOf("set \"DD_P=1\"") + assertTrue(id, on > lines.indexOf("cd /d \"%~dp0\"")) + assertEquals(parentLines, lines.subList(on + 1, on + 6)) + assertEquals("if exist \"%~dp0.droiddeck-epic-args\" goto client", lines[on + 6]) + assertEquals(3, lines.count { it.contains("%DD_P% \"%~dp0PlayGTAV.exe\"") }) + } + } + + @Test fun otherEpicGamesUseTheStandInOnlyWhenTheirEnvironmentAsksForIt() { + val lines = StoreLaunch.launcherText(sample).split("\r\n") + val off = lines.indexOf("set \"DD_P=\"") + assertTrue(off > 0) + assertFalse(lines.contains("set \"DD_P=1\"")) + assertEquals(parentLines, lines.subList(off + 1, off + 6)) } @Test fun gogLauncherHasNoEpicBlockAndIsOnlyWrittenWhenNeeded() { diff --git a/tools/build_local.sh b/tools/build_local.sh index 6f8d004ffa..4251997416 100755 --- a/tools/build_local.sh +++ b/tools/build_local.sh @@ -440,6 +440,13 @@ if [[ "${DROIDDECK_SKIP_RUST:-0}" != 1 ]]; then CARGO_TARGET_DIR="${cache_dir}/rockstar-target" bash tools/rockstar-launcher/build.sh "${rockstar_out}" save_step rockstar "${rockstar_key}" "${rockstar_out}" fi + epic_out="${linuxfs_dir}/usr/local/lib/droiddeck-epic" + epic_key=$(inputs_hash "x86_64-pc-windows-gnu" tools/epic-launcher/src tools/epic-launcher/Cargo.toml tools/epic-launcher/Cargo.lock tools/epic-launcher/build.sh) + if ! restore_step epic "${epic_key}" "${epic_out}"; then + command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1 || { echo "x86_64-w64-mingw32-gcc is required for EpicGamesLauncher.exe." >&2; exit 1; } + CARGO_TARGET_DIR="${cache_dir}/epic-target" bash tools/epic-launcher/build.sh "${epic_out}" + save_step epic "${epic_key}" "${epic_out}" + fi fi python3 tools/powervr/fetch.py bash tools/packs/build.sh app/build/packs diff --git a/tools/epic-launcher/.gitignore b/tools/epic-launcher/.gitignore new file mode 100644 index 0000000000..b83d22266a --- /dev/null +++ b/tools/epic-launcher/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/tools/epic-launcher/Cargo.lock b/tools/epic-launcher/Cargo.lock new file mode 100644 index 0000000000..569575bb09 --- /dev/null +++ b/tools/epic-launcher/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "droiddeck-epic-launcher" +version = "0.1.0" diff --git a/tools/epic-launcher/Cargo.toml b/tools/epic-launcher/Cargo.toml new file mode 100644 index 0000000000..fb5974a4b2 --- /dev/null +++ b/tools/epic-launcher/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "droiddeck-epic-launcher" +version = "0.1.0" +edition = "2021" +license = "GPL-3.0-only" +publish = false + +[[bin]] +name = "EpicGamesLauncher" +path = "src/main.rs" + +[profile.release] +opt-level = "s" +lto = true +panic = "abort" +strip = true diff --git a/tools/epic-launcher/README.md b/tools/epic-launcher/README.md new file mode 100644 index 0000000000..97dbce402f --- /dev/null +++ b/tools/epic-launcher/README.md @@ -0,0 +1,13 @@ +# Epic Games Launcher parent stand-in + +`EpicGamesLauncher.exe` starts the game named by its first argument as its own child, passes the rest of its command line to the game unchanged, waits for the game and returns its exit code. + +Some Epic titles only accept a launch whose parent process is named `EpicGamesLauncher.exe`. Rockstar's launcher logs `Epic Games Launcher not detected as parent process.` and then treats the Epic copy as unowned. In DroidDeck the Epic client is a Linux program, so it can never be that parent. The check matches the process name, not its path: Heroic's stand-in works from `C:\windows\command` and from the game folder. + +`StoreLaunch` writes the Epic `.droiddeck-launch.bat` to run the game through this executable for the titles in `EPIC_PARENT_TITLES`, or for any Epic game whose per-game environment sets `DD_EPIC_PARENT=1`. `DD_EPIC_PARENT=0` turns it off. Without the staged executable the game starts directly, as before. + +`build.sh` builds it with the GNU Windows target for the `epic` add-on pack. The app fetches the pack when it starts signed in to Epic, or when a launch that needs it finds it missing, and stages it in the Linux runtime at `/usr/local/lib/droiddeck-epic`. + +```sh +cargo test --locked --manifest-path tools/epic-launcher/Cargo.toml +``` diff --git a/tools/epic-launcher/build.sh b/tools/epic-launcher/build.sh new file mode 100755 index 0000000000..5db23c420d --- /dev/null +++ b/tools/epic-launcher/build.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +out=${1:-"$here/../../app/src/main/assets/linuxfs/usr/local/lib/droiddeck-epic"} +target=x86_64-pc-windows-gnu +rustup target add "$target" >/dev/null 2>&1 || true +cargo build --manifest-path "$here/Cargo.toml" --release --locked --target "$target" +mkdir -p "$out" +install -m644 "${CARGO_TARGET_DIR:-$here/target}/$target/release/EpicGamesLauncher.exe" "$out/EpicGamesLauncher.exe" diff --git a/tools/epic-launcher/src/lib.rs b/tools/epic-launcher/src/lib.rs new file mode 100644 index 0000000000..f842dc13c2 --- /dev/null +++ b/tools/epic-launcher/src/lib.rs @@ -0,0 +1,110 @@ +const QUOTE: u16 = b'"' as u16; +const BACKSLASH: u16 = b'\\' as u16; + +fn blank(c: u16) -> bool { + c == b' ' as u16 || c == b'\t' as u16 +} + +fn trim_start(line: &[u16]) -> &[u16] { + let start = line.iter().position(|&c| !blank(c)).unwrap_or(line.len()); + &line[start..] +} + +/// Splits this program's command line into the game executable that follows the program name and +/// the rest of the line, which reaches the game unchanged. +pub fn split(line: &[u16]) -> Option<(Vec, &[u16])> { + let mut quoted = false; + let mut end = line.len(); + for (i, &c) in line.iter().enumerate() { + if c == QUOTE { + quoted = !quoted; + } else if blank(c) && !quoted { + end = i; + break; + } + } + let rest = trim_start(&line[end..]); + let mut exe = Vec::new(); + let mut quoted = false; + let mut slashes = 0; + let mut end = rest.len(); + for (i, &c) in rest.iter().enumerate() { + if c == BACKSLASH { + slashes += 1; + continue; + } + if c == QUOTE { + exe.extend(std::iter::repeat(BACKSLASH).take(slashes / 2)); + if slashes % 2 == 1 { + exe.push(QUOTE); + } else { + quoted = !quoted; + } + } else if blank(c) && !quoted { + exe.extend(std::iter::repeat(BACKSLASH).take(slashes)); + end = i; + slashes = 0; + break; + } else { + exe.extend(std::iter::repeat(BACKSLASH).take(slashes)); + exe.push(c); + } + slashes = 0; + } + exe.extend(std::iter::repeat(BACKSLASH).take(slashes)); + if exe.is_empty() { + return None; + } + Some((exe, trim_start(&rest[end..]))) +} + +#[cfg(test)] +mod tests { + use super::split; + + fn wide(s: &str) -> Vec { + s.encode_utf16().collect() + } + + fn parts(line: &str) -> Option<(String, String)> { + let line = wide(line); + split(&line).map(|(exe, rest)| (String::from_utf16(&exe).unwrap(), String::from_utf16(rest).unwrap())) + } + + #[test] + fn the_game_gets_the_rest_of_the_line_exactly_as_written() { + assert_eq!( + parts(r#""Z:\usr\local\lib\droiddeck-epic\EpicGamesLauncher.exe" "Z:\root\Games\Stores\Epic\Grand Theft Auto V\PlayGTAV.exe" -AUTH_LOGIN=unused -epicusername="A B" -nobattleye"#), + Some(( + r"Z:\root\Games\Stores\Epic\Grand Theft Auto V\PlayGTAV.exe".into(), + r#"-AUTH_LOGIN=unused -epicusername="A B" -nobattleye"#.into() + )) + ); + } + + #[test] + fn a_game_without_arguments_gets_none() { + assert_eq!(parts(r#"EpicGamesLauncher.exe "C:\Games\x.exe" "#), Some((r"C:\Games\x.exe".into(), String::new()))); + assert_eq!(parts(r"EpicGamesLauncher.exe C:\Games\x.exe"), Some((r"C:\Games\x.exe".into(), String::new()))); + } + + #[test] + fn the_program_name_follows_its_own_quoting_rules() { + assert_eq!(parts("\"C:\\a b\\\"EpicGamesLauncher.exe\tgame.exe -x"), Some(("game.exe".into(), "-x".into()))); + } + + #[test] + fn the_executable_follows_the_argument_quoting_rules() { + assert_eq!(parts(r#"e "C:\dir with\"part\"s\x.exe" -y"#), Some((r#"C:\dir with"part"s\x.exe"#.into(), "-y".into()))); + assert_eq!(parts(r#"e C:\a"b c"\x.exe -y"#), Some((r"C:\ab c\x.exe".into(), "-y".into()))); + assert_eq!(parts(r"e C:\games\ -y"), Some((r"C:\games\".into(), "-y".into()))); + } + + #[test] + fn a_missing_executable_is_refused() { + assert_eq!(parts("EpicGamesLauncher.exe"), None); + assert_eq!(parts("EpicGamesLauncher.exe "), None); + assert_eq!(parts(r#"EpicGamesLauncher.exe "" -x"#), None); + assert_eq!(parts(""), None); + } +} diff --git a/tools/epic-launcher/src/main.rs b/tools/epic-launcher/src/main.rs new file mode 100644 index 0000000000..0b3ac53837 --- /dev/null +++ b/tools/epic-launcher/src/main.rs @@ -0,0 +1,42 @@ +#[cfg(windows)] +fn main() { + use std::ffi::OsString; + use std::os::windows::ffi::OsStringExt; + use std::os::windows::process::CommandExt; + + #[link(name = "kernel32")] + extern "system" { + fn GetCommandLineW() -> *const u16; + } + + let line = unsafe { + let start = GetCommandLineW(); + let mut len = 0; + while *start.add(len) != 0 { + len += 1; + } + std::slice::from_raw_parts(start, len) + }; + let Some((exe, rest)) = droiddeck_epic_launcher::split(line) else { + eprintln!("usage: EpicGamesLauncher.exe [arguments]"); + std::process::exit(2); + }; + let exe = OsString::from_wide(&exe); + let mut command = std::process::Command::new(&exe); + if !rest.is_empty() { + command.raw_arg(OsString::from_wide(rest)); + } + match command.status() { + Ok(status) => std::process::exit(status.code().unwrap_or(1)), + Err(error) => { + eprintln!("EpicGamesLauncher: could not start {}: {error}", exe.to_string_lossy()); + std::process::exit(1); + } + } +} + +#[cfg(not(windows))] +fn main() { + eprintln!("EpicGamesLauncher.exe runs on Windows or Wine"); + std::process::exit(1); +} diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch b/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch index 5031cb93dc..76bdb395f0 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch @@ -5,6 +5,7 @@ import binascii import json import os import re +import runpy import shlex import shutil import stat @@ -337,6 +338,13 @@ UBISOFT_INSTALLER_URL = "https://static3.cdn.ubi.com/orbit/launcher_installer/Ub ROCKSTAR_SERVICE = Path("/usr/local/lib/droiddeck-rockstar") SERVICE_WAIT = 300.0 ROCKSTAR_FOLDER = "drive_c/Program Files/Rockstar Games/Launcher" +EPIC_SDK_SETUP = ROCKSTAR_FOLDER + "/Redistributables/SocialClub/Social-Club-Setup.exe" +SDK_SOURCE = ".droiddeck-sdk-source" +SDK_SETUP_LIMIT = 256 * 1024 * 1024 +EPIC_PARENT = Path("/usr/local/lib/droiddeck-epic/EpicGamesLauncher.exe") +EPIC_PARENT_ON = 'set "DD_P=1"' +EPIC_PARENT_SWITCH = "DD_EPIC_PARENT" +EPIC_SERVICE_WAIT = 60.0 ROCKSTAR_TITLES = {"gta3": "Grand Theft Auto III", "gtavc": "Grand Theft Auto: Vice City", "gtasa": "GTA: San Andreas", "gta4": "Grand Theft Auto IV", "lanoire": "LANoireMTL"} @@ -394,10 +402,9 @@ def rockstar_sdk(folder, sidecar): return False -def rockstar_registry(folder, title, compat_data, proton, sdk_arch=None): +def rockstar_registry(folder, title, compat_data, proton, sdk_arch=None, launcher=True): pfx = Path(compat_data) / "pfx" - launcher = r"C:\Program Files\Rockstar Games\Launcher" - values = [(r"Rockstar Games\Launcher", launcher)] + values = [(r"Rockstar Games\Launcher", r"C:\Program Files\Rockstar Games\Launcher")] if launcher else [] if title: values.append(("Rockstar Games\\" + title, windows_path(str(folder)))) entries = [("Software\\" + view + key, value) for view in ("", "Wow6432Node\\") for key, value in values] @@ -420,23 +427,29 @@ def rockstar_registry(folder, title, compat_data, proton, sdk_arch=None): return result.returncode == 0 -def rockstar_runtime(folder, exe, compat_data, arch): +def rockstar_runtime(folder, exe, compat_data, arch, installer=None): if arch == "x86": - rockstar_runtime(folder, exe, compat_data, "x64") + rockstar_runtime(folder, exe, compat_data, "x64", installer) pfx = Path(compat_data) / "pfx" target = pfx / "drive_c" / ("Program Files (x86)" if arch == "x86" else "Program Files") / "Rockstar Games/Social Club" if not target.resolve().is_relative_to(pfx.resolve()): raise ValueError("invalid Social Club destination") required = ("socialclub.dll", "socialclub.pak") + (("SocialClubHelper.exe",) if arch == "x64" else ()) marker = target / ".droiddeck-installing" - if all((target / name).is_file() for name in required) and not marker.exists(): + source_file, stamp = target / SDK_SOURCE, None + if installer is not None: + info = installer.stat() + stamp = "%d %d %s" % (info.st_size, info.st_mtime_ns, installer) + current = stamp is None or source_file.is_file() and not source_file.is_symlink() and source_file.read_text(errors="replace") == stamp + if all((target / name).is_file() for name in required) and not marker.exists() and current: return "present" - root = folder.resolve() - installers = [base / sub / "Social-Club-Setup.exe" for base in (root, exe.parent) - for sub in ("Redistributables", "Installers")] - installer = next((p for p in installers if p.is_file() and p.resolve().is_relative_to(root) and p.stat().st_size <= 256 * 1024 * 1024), None) if installer is None: - return "game-runtime" + root = folder.resolve() + installers = [base / sub / "Social-Club-Setup.exe" for base in (root, exe.parent) + for sub in ("Redistributables", "Installers")] + installer = next((p for p in installers if p.is_file() and p.resolve().is_relative_to(root) and p.stat().st_size <= SDK_SETUP_LIMIT), None) + if installer is None: + return "game-runtime" tool = shutil.which("7z") if not tool: return "no-unpacker" @@ -488,15 +501,67 @@ def rockstar_runtime(folder, exe, compat_data, arch): raise os.replace(stage_path, output) marker.unlink() + if stamp is not None: + source_file.unlink(missing_ok=True) + source_file.write_text(stamp) return "installed" -def fetch_service(service, store, launch_dir, ask_app=None): +def epic_parent_switch(sidecar, env=None): + own = sidecar.get("env") if isinstance(sidecar.get("env"), dict) else {} + if EPIC_PARENT_SWITCH in own: + return str(own[EPIC_PARENT_SWITCH]).replace('"', "") + env = os.environ if env is None else env + try: + game_env = runpy.run_path(str(Path(__file__).resolve().with_name("droiddeck-game-env"))) + try: + config = json.loads((Path(env.get("HOME") or "/root") / ".config/droiddeck/game-environment.json").read_text(encoding="utf-8")) + except FileNotFoundError: + config = {"version": 1} + env = game_env["apply_config"](env, config, game_env["game_id"](env)) + except (OSError, ValueError, KeyError, TypeError, AttributeError): + pass + return env.get(EPIC_PARENT_SWITCH, "") + + +def wants_epic_parent(folder, switch): + if switch in ("0", "1"): + return switch == "1" + try: + return EPIC_PARENT_ON in (folder / LAUNCHER).read_text(errors="replace").splitlines() + except OSError: + return False + + +def epic_rockstar_sdk(folder, sidecar, compat_data, proton): + if not compat_data: + return None + pfx = Path(compat_data) / "pfx" + root = folder.resolve() + exe = (folder / str(sidecar.get("exe") or "").replace("\\", "/")).resolve() + if not exe.is_relative_to(root): + return None + setups = [(pfx / EPIC_SDK_SETUP, pfx)] + [(base / sub / "Social-Club-Setup.exe", root) for base in (root, exe.parent) + for sub in ("Redistributables", "Installers")] + setup = next((path for path, inside in setups if path.is_file() and path.resolve().is_relative_to(inside.resolve()) + and path.stat().st_size <= SDK_SETUP_LIMIT), None) + if setup is None: + return None + made = "present" if (pfx / "user.reg").is_file() else create_prefix(compat_data, proton) + if made not in ("created", "present"): + return "prefix-" + made + state = rockstar_runtime(folder, exe, compat_data, "x64", setup) + if state in ("present", "installed") and not rockstar_registry(folder, None, compat_data, proton, sdk_arch="x64", launcher=False): + return state + " registry-unavailable" + return state + + +def fetch_service(service, store, launch_dir, ask_app=None, timeout=SERVICE_WAIT): if service.is_file(): return True if not launch_dir: return False - answer = (ask_app or ask)(Path(launch_dir) / "stores", {"op": "store-service", "store": store}, timeout=SERVICE_WAIT) + answer = (ask_app or ask)(Path(launch_dir) / "stores", {"op": "store-service", "store": store}, timeout=timeout) return isinstance(answer, dict) and bool(answer.get("ok")) and service.is_file() @@ -1650,6 +1715,15 @@ def main(argv): pass log("ubisoft %s: not prepared (%s), starting directly" % (game, e)) if store == "epic": + try: + if launch_dir and not EPIC_PARENT.is_file() and wants_epic_parent(folder, epic_parent_switch(sidecar)): + got = fetch_service(EPIC_PARENT, "epic", launch_dir, timeout=EPIC_SERVICE_WAIT) + log("epic parent stand-in: " + ("staged" if got else "unavailable")) + sdk = epic_rockstar_sdk(folder, sidecar, compat_data, os.environ.get("DD_STORE_PROTON", "")) + except (OSError, ValueError, subprocess.TimeoutExpired) as error: + sdk = "failed (%s)" % type(error).__name__ + if sdk: + log("epic rockstar sdk: " + sdk) handled = os.environ.get(EPIC_HANDLED) == "1" and (folder / EPIC_ARGS).is_file() if not handled: drop_stale(folder) diff --git a/tools/packs/build.sh b/tools/packs/build.sh index b2a99c6110..062fbd5270 100755 --- a/tools/packs/build.sh +++ b/tools/packs/build.sh @@ -98,6 +98,7 @@ pack powervr "$repo/app/src/main/assets/hybris" runtime.tzst version.txt [ ! -f "$linuxfs/droiddeck-ubisoft/droiddeck-upc.exe" ] || pack ubisoft "$linuxfs/droiddeck-ubisoft" droiddeck-upc.exe [ ! -f "$linuxfs/droiddeck-rockstar/Launcher64.exe" ] || pack rockstar "$linuxfs/droiddeck-rockstar" Launcher32.exe Launcher64.exe [ ! -f "$linuxfs/droiddeck-dirt/ws2_32.dll" ] || pack dirt "$linuxfs/droiddeck-dirt" ws2_32.dll +[ ! -f "$linuxfs/droiddeck-epic/EpicGamesLauncher.exe" ] || pack epic "$linuxfs/droiddeck-epic" EpicGamesLauncher.exe mkdir "$work/butler" fetch "https://broth.itch.zone/butler/linux-arm64/${BUTLER_VERSION}/archive/default" \ diff --git a/tools/release/runtime_inputs.py b/tools/release/runtime_inputs.py index 4b02d29c26..89488e1ba5 100644 --- a/tools/release/runtime_inputs.py +++ b/tools/release/runtime_inputs.py @@ -15,18 +15,18 @@ MANIFEST = Path('app/build/runtime-inputs.json') PACKS = Path('app/build/packs') PACKED = {'assets/linuxfs/usr/local/lib/droiddeck-xbox/': 'xbox', 'assets/linuxfs/usr/local/lib/droiddeck-comet/': 'comet', 'assets/linuxfs/usr/local/lib/droiddeck-ubisoft/': 'ubisoft', 'assets/linuxfs/usr/local/lib/droiddeck-rockstar/': 'rockstar', - 'assets/linuxfs/usr/local/lib/droiddeck-dirt/': 'dirt', + 'assets/linuxfs/usr/local/lib/droiddeck-dirt/': 'dirt', 'assets/linuxfs/usr/local/lib/droiddeck-epic/': 'epic', 'assets/directaudio/': 'directaudio', 'assets/hybris/': 'powervr'} # DrWeb flags proot itself as Tool.Linux.Proot; the app runs the pack's copy through Android's linker. PACKED_FILES = {'lib/arm64-v8a/libproot.so': ('proot', 'libproot.so')} # The loader is execve'd, which targetSdk 29+ allows only from the APK's native library directory. PROOT_LOADER = {'lib/arm64-v8a/libproot-loader.so': 'libproot-loader.so'} PACKED_LIBRARIES = ['lib/arm64-v8a/libopencv_java4.so', 'lib/arm64-v8a/libmediapipe_tasks_jni.so'] -PACK_NAMES = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt'] +PACK_NAMES = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt', 'epic'] SOURCE_PATHS = ['app/build.gradle', 'app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/assets/pulseaudio.tzst', 'tools/linuxfs', 'tools/proot', 'tools/aaudio-sink', 'tools/directaudio', 'tools/packs', 'tools/gamescope/release.env', 'tools/droiddeck-esync/release.env', - 'tools/mangoapp', 'tools/msitools', 'tools/pipewire', 'tools/comet', 'tools/xbox', 'tools/dirt-ws2', 'tools/ubisoft-launcher', 'tools/rockstar-launcher', 'tools/components', 'tools/ci', 'tools/build_local.sh', + 'tools/mangoapp', 'tools/msitools', 'tools/pipewire', 'tools/comet', 'tools/xbox', 'tools/dirt-ws2', 'tools/ubisoft-launcher', 'tools/rockstar-launcher', 'tools/epic-launcher', 'tools/components', 'tools/ci', 'tools/build_local.sh', 'tools/powervr', 'tools/hybris', 'tools/dxvk', 'tools/vulkan-wsi', 'tools/release/runtime_inputs.py', 'app/src/main/assets/desktop-removal', 'tools/quest', 'tools/vr/src', 'tools/vr/driver_droiddeck', 'tools/vr/layer', 'tools/vr/build.sh', @@ -49,12 +49,15 @@ def digest(path): def sources(root): - files = [] + files, builds = [], set() for name in SOURCE_PATHS: path = root / name files.extend(path.rglob('*') if path.is_dir() else [path]) + if path.is_dir(): + builds.update(manifest.parent / 'target' for manifest in path.rglob('Cargo.toml')) return {path.relative_to(root).as_posix(): digest(path) for path in sorted(set(files)) - if path.is_file() and '__pycache__' not in path.parts and path.suffix != '.pyc'} + if path.is_file() and '__pycache__' not in path.parts and path.suffix != '.pyc' + and not any(build in path.parents for build in builds)} def outputs(root): @@ -227,7 +230,7 @@ def windows_binaries(package): def check_apk(apk, root=ROOT): data = verify(root) packs = {name: pack_digests(root, name) for name in PACK_NAMES - if name not in ('ubisoft', 'rockstar', 'dirt') or (root / PACKS / (name + '.tar.zst')).is_file()} + if name not in ('ubisoft', 'rockstar', 'dirt', 'epic') or (root / PACKS / (name + '.tar.zst')).is_file()} for name, rel in PROOT_LOADER.items(): if packs['proot'].get(rel) != data['outputs'][name]['sha256']: raise ValueError('Add-on pack proot is missing or has a stale ' + rel) diff --git a/tools/tests/test_runtime_inputs.py b/tools/tests/test_runtime_inputs.py index 954ea76f66..92f2ae1c79 100644 --- a/tools/tests/test_runtime_inputs.py +++ b/tools/tests/test_runtime_inputs.py @@ -137,6 +137,19 @@ class RuntimeInputsTest(unittest.TestCase): with self.assertRaisesRegex(ValueError, 'sources changed'): runtime.verify(self.root) + def test_cargo_output_beside_a_windows_helper_is_not_a_source(self): + crate = self.root / 'tools/epic-launcher' + (crate / 'src').mkdir(parents=True) + (crate / 'Cargo.toml').write_text('[package]\n') + (crate / 'src/lib.rs').write_text('old') + runtime.record(self.root) + (crate / 'target/debug').mkdir(parents=True) + (crate / 'target/debug/build.log').write_text('local cargo test') + runtime.verify(self.root) + (crate / 'src/lib.rs').write_text('new') + with self.assertRaisesRegex(ValueError, 'sources changed'): + runtime.verify(self.root) + def test_missing_quest_driver_cannot_be_attested(self): (self.root / 'app/build/prepared-assets/graphics_driver/adrenotools-turnip25.1.0-quest1.tzst').unlink() with self.assertRaisesRegex(ValueError, 'quest1.tzst'): @@ -248,6 +261,21 @@ class RuntimeInputsTest(unittest.TestCase): runtime.check_apk(apk, self.root) runtime.check_apk(self.current_apk(self.root / 'current.apk'), self.root) + def test_an_apk_still_carrying_the_epic_parent_stand_in_is_rejected(self): + epic = self.root / 'app/src/main/assets/linuxfs/usr/local/lib/droiddeck-epic' + epic.mkdir(parents=True) + (epic / 'EpicGamesLauncher.exe').write_bytes(b'MZ parent') + self.packs() + name = 'assets/linuxfs/usr/local/lib/droiddeck-epic/EpicGamesLauncher.exe' + self.assertIn(name, runtime.outputs(self.root)) + apk = self.current_apk(self.root / 'bundled.apk', {name: b'MZ parent'}) + with self.assertRaisesRegex(ValueError, 'epic pack provides'): + runtime.check_apk(apk, self.root) + runtime.check_apk(self.current_apk(self.root / 'current.apk'), self.root) + self.pack('epic', {'EpicGamesLauncher.exe': b'MZ older parent'}) + with self.assertRaisesRegex(ValueError, 'epic is missing or has a stale'): + runtime.check_apk(self.current_apk(self.root / 'current.apk'), self.root) + def test_an_apk_still_carrying_the_powervr_runtime_is_rejected(self): apk = self.current_apk(self.root / 'bundled.apk', {'assets/hybris/runtime.tzst': b'runtime'}) with self.assertRaisesRegex(ValueError, 'powervr pack provides'): diff --git a/tools/tests/test_store_launch_rockstar.py b/tools/tests/test_store_launch_rockstar.py index 277d2a9f2b..ccd12e24d5 100644 --- a/tools/tests/test_store_launch_rockstar.py +++ b/tools/tests/test_store_launch_rockstar.py @@ -292,5 +292,150 @@ class RockstarLaunch(unittest.TestCase): self.assertIn('Grand Theft Auto: Vice City', text) +SDK_FILES = {'socialclub.dll': b'sdk dll', 'socialclub.pak': b'sdk pak', 'SocialClubHelper.exe': b'sdk helper'} + + +class EpicRockstarLaunch(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.root = Path(temp.name) + self.folder = self.root / 'Grand Theft Auto V' + self.folder.mkdir() + (self.folder / 'PlayGTAV.exe').write_bytes(b'MZ') + self.sidecar = {'store': 'epic', 'id': '9d2d0eb64d5c44529cece33fe2a46482', 'title': 'Grand Theft Auto V', 'exe': 'PlayGTAV.exe'} + (self.folder / '.droiddeck-store.json').write_text(json.dumps(self.sidecar)) + self.prefix = self.root / 'prefix' + (self.prefix / 'pfx').mkdir(parents=True) + (self.prefix / 'pfx/user.reg').write_text('WINE REGISTRY Version 2\n') + (self.prefix / 'pfx/system.reg').write_text('WINE REGISTRY Version 2\n') + self.sdk = self.prefix / 'pfx/drive_c/Program Files/Rockstar Games/Social Club' + self.unpacked = [] + + def unpacker(self, command, **kwargs): + if command[1] == 'l': + listing = ''.join('Path = x64/%s\nSize = %d\n\n' % (name, len(data)) for name, data in SDK_FILES.items()) + return type('Listing', (), {'returncode': 0, 'stdout': listing.encode()})() + self.unpacked.append(Path(command[-2])) + out = Path(next(arg[2:] for arg in command if arg.startswith('-o'))) / 'x64' + out.mkdir(parents=True) + for name, data in SDK_FILES.items(): + (out / name).write_bytes(data + b' from ' + Path(command[-2]).read_bytes()) + return type('Done', (), {'returncode': 0})() + + def stage(self): + with patch.object(store.shutil, 'which', return_value='/bin/7z'), patch.object(store.subprocess, 'run', side_effect=self.unpacker), \ + patch.object(store, 'wait_for_server', return_value=True), \ + patch.object(store, 'create_prefix', side_effect=AssertionError('the prefix already exists')): + return store.epic_rockstar_sdk(self.folder, self.sidecar, str(self.prefix), '') + + def test_the_launchers_own_sdk_installer_is_staged_so_it_never_runs_it(self): + setup = self.prefix / 'pfx' / store.EPIC_SDK_SETUP + setup.parent.mkdir(parents=True) + setup.write_bytes(b'launcher setup') + (self.folder / 'Installers').mkdir() + (self.folder / 'Installers/Social-Club-Setup.exe').write_bytes(b'older game setup') + self.assertEqual('installed', self.stage()) + self.assertEqual([setup], self.unpacked) + self.assertEqual(b'sdk dll from launcher setup', (self.sdk / 'socialclub.dll').read_bytes()) + text = (self.prefix / 'pfx/system.reg').read_text() + self.assertIn(r'[Software\\Wow6432Node\\Rockstar Games\\Rockstar Games Social Club]', text) + self.assertIn(r'"InstallFolder"="C:\\Program Files\\Rockstar Games\\Social Club"', text) + self.assertNotIn(r'Rockstar Games\\Launcher]', text) + self.assertEqual('present', self.stage()) + self.assertEqual([setup], self.unpacked) + + def test_an_updated_launcher_installer_is_staged_again(self): + setup = self.prefix / 'pfx' / store.EPIC_SDK_SETUP + setup.parent.mkdir(parents=True) + setup.write_bytes(b'launcher setup') + self.assertEqual('installed', self.stage()) + setup.write_bytes(b'newer launcher setup') + self.assertEqual('installed', self.stage()) + self.assertEqual(b'sdk dll from newer launcher setup', (self.sdk / 'socialclub.dll').read_bytes()) + + def test_before_the_launcher_is_installed_the_games_installer_is_used(self): + (self.folder / 'Redistributables').mkdir() + (self.folder / 'Redistributables/Social-Club-Setup.exe').write_bytes(b'game setup') + self.assertEqual('installed', self.stage()) + self.assertEqual(b'sdk dll from game setup', (self.sdk / 'socialclub.dll').read_bytes()) + self.assertNotIn(r'Rockstar Games\\Launcher]', (self.prefix / 'pfx/system.reg').read_text()) + + def test_other_epic_games_are_left_alone(self): + self.assertIsNone(self.stage()) + self.assertEqual([], self.unpacked) + self.assertFalse(self.sdk.exists()) + self.assertEqual('WINE REGISTRY Version 2\n', (self.prefix / 'pfx/system.reg').read_text()) + + def test_an_installer_linked_from_outside_the_game_is_ignored(self): + outside = self.root / 'outside.exe' + outside.write_bytes(b'not the game') + (self.folder / 'Installers').mkdir() + (self.folder / 'Installers/Social-Club-Setup.exe').symlink_to(outside) + self.assertIsNone(self.stage()) + self.assertEqual([], self.unpacked) + + def game_environment(self, shared=None, games=None): + config = self.root / 'home/.config/droiddeck/game-environment.json' + config.parent.mkdir(parents=True, exist_ok=True) + config.write_text(json.dumps({'version': 1, 'shared': shared or {}, 'games': games or {}})) + + def launch(self, bat, parent, compat_data=''): + (self.folder / '.droiddeck-launch.bat').write_text(bat) + calls = [] + env = {'DD_LAUNCH_DIR': str(self.root / 'launch'), 'STEAM_COMPAT_DATA_PATH': compat_data, 'HOME': str(self.root / 'home'), + 'DD_EPIC_PARENT': ''} + with patch.dict(os.environ, env), patch.object(store, 'EPIC_PARENT', parent), \ + patch.object(store, 'client_wanted', return_value=False), \ + patch.object(store, 'ask', side_effect=lambda channel, request, timeout=0, claim=False: calls.append((request['op'], timeout)) or {'ok': False}): + store.main([str(self.folder / '.droiddeck-launch.bat')]) + return calls + + def test_a_title_that_needs_the_parent_fetches_the_stand_in_before_its_code(self): + bat = '@echo off\r\nsetlocal\r\nset "DD_P=1"\r\n' + calls = self.launch(bat, self.root / 'missing/EpicGamesLauncher.exe') + self.assertEqual([('store-service', store.EPIC_SERVICE_WAIT), 'epic-code', 'cloud-down'], + [calls[0]] + [op for op, _ in calls[1:]]) + staged = self.root / 'EpicGamesLauncher.exe' + staged.write_bytes(b'MZ') + self.assertEqual(['epic-code', 'cloud-down'], [op for op, _ in self.launch(bat, staged)]) + + def test_other_epic_games_do_not_fetch_the_stand_in(self): + bat = '@echo off\r\nsetlocal\r\nset "DD_P="\r\nif "%DD_EPIC_PARENT%"=="1" set "DD_P=1"\r\n' + calls = self.launch(bat, self.root / 'missing/EpicGamesLauncher.exe') + self.assertEqual(['epic-code', 'cloud-down'], [op for op, _ in calls]) + + def test_the_games_own_switch_decides_whether_the_stand_in_is_fetched(self): + compat_data = str(self.root / 'compatdata/4089453117') + missing = self.root / 'missing/EpicGamesLauncher.exe' + self.game_environment(games={'4089453117': {'DD_EPIC_PARENT': '1'}}) + self.assertEqual('store-service', self.launch('@echo off\r\nset "DD_P="\r\n', missing, compat_data)[0][0]) + self.game_environment(games={'4089453117': {'DD_EPIC_PARENT': '0'}}) + self.assertEqual(['epic-code', 'cloud-down'], [op for op, _ in self.launch('@echo off\r\nset "DD_P=1"\r\n', missing, compat_data)]) + self.game_environment(games={'4089453117': {'DD_EPIC_PARENT': None}}, shared={'DD_EPIC_PARENT': '0'}) + self.assertEqual('store-service', self.launch('@echo off\r\nset "DD_P=1"\r\n', missing, compat_data)[0][0]) + + def test_the_sidecars_own_environment_wins_like_it_does_in_the_batch(self): + compat_data = str(self.root / 'compatdata/4089453117') + missing = self.root / 'missing/EpicGamesLauncher.exe' + sidecar = self.folder / '.droiddeck-store.json' + sidecar.write_text(json.dumps(dict(self.sidecar, env={'DD_EPIC_PARENT': '1'}))) + self.assertEqual('store-service', self.launch('@echo off\r\nset "DD_P="\r\n', missing, compat_data)[0][0]) + self.game_environment(games={'4089453117': {'DD_EPIC_PARENT': '1'}}) + sidecar.write_text(json.dumps(dict(self.sidecar, env={'DD_EPIC_PARENT': '"0"'}))) + self.assertEqual(['epic-code', 'cloud-down'], [op for op, _ in self.launch('@echo off\r\nset "DD_P=1"\r\n', missing, compat_data)]) + + def test_the_switch_is_read_the_way_the_game_will_see_it(self): + env = {'HOME': str(self.root / 'home'), 'STEAM_COMPAT_DATA_PATH': str(self.root / 'compatdata/4089453117')} + self.assertEqual('', store.epic_parent_switch({}, env)) + self.assertEqual('1', store.epic_parent_switch({}, dict(env, DD_EPIC_PARENT='1'))) + self.game_environment(shared={'DD_EPIC_PARENT': '1'}, games={'4089453117': {'DD_EPIC_PARENT': '0'}, '7': {'DD_EPIC_PARENT': '1'}}) + self.assertEqual('0', store.epic_parent_switch({}, env)) + self.assertEqual('1', store.epic_parent_switch({'env': {'DD_EPIC_PARENT': '1'}}, env)) + self.assertEqual('1', store.epic_parent_switch({}, dict(env, STEAM_COMPAT_DATA_PATH=str(self.root / 'compatdata/12')))) + (self.root / 'home/.config/droiddeck/game-environment.json').write_text('{"version": 9}') + self.assertEqual('1', store.epic_parent_switch({}, dict(env, DD_EPIC_PARENT='1'))) + + if __name__ == '__main__': unittest.main() From f29f72d5d919685f9dd8898834a640bb867d1a91 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:17:52 -0500 Subject: [PATCH 002/141] fix(input): restore Steam controller reattach (#2963) --- tools/linuxfs/preload/net.c | 4 + tools/linuxfs/preload/udevmon.c | 79 ++++++++++++++++++-- tools/tests/test_cdp_guard.py | 3 +- tools/tests/test_udevmon_preload.py | 112 ++++++++++++++++++++++++++++ 4 files changed, 189 insertions(+), 9 deletions(-) create mode 100644 tools/tests/test_udevmon_preload.py diff --git a/tools/linuxfs/preload/net.c b/tools/linuxfs/preload/net.c index f7c9db9406..de3cfdaee7 100644 --- a/tools/linuxfs/preload/net.c +++ b/tools/linuxfs/preload/net.c @@ -111,6 +111,9 @@ typedef int (*accept4_fn)(int, struct sockaddr *, socklen_t *, int); static unsigned guarded_port(void); __attribute__((visibility("hidden"))) int dd_udevmon_stand_in(int fd); +__attribute__((visibility("hidden"))) int dd_udevmon_bind(int fd, const struct sockaddr *addr, socklen_t len, + int (*real_bind)(int, const struct sockaddr *, socklen_t), + int *rc); __attribute__((visibility("hidden"))) int dd_nl_bind(int fd, const struct sockaddr *addr, socklen_t len, int *rc); __attribute__((visibility("hidden"))) int dd_nl_connect(int fd, const struct sockaddr *addr, @@ -121,6 +124,7 @@ int bind(int fd, const struct sockaddr *addr, socklen_t len) { int nl_rc; if (!real) real = (bind_fn)dlsym(RTLD_NEXT, "bind"); if (dd_nl_bind(fd, addr, len, &nl_rc)) return nl_rc; + if (dd_udevmon_bind(fd, addr, len, real, &nl_rc)) return nl_rc; if (dd_udevmon_stand_in(fd)) { if (addr == NULL || len < sizeof(struct sockaddr_nl) || addr->sa_family != AF_NETLINK) { errno = EINVAL; diff --git a/tools/linuxfs/preload/udevmon.c b/tools/linuxfs/preload/udevmon.c index d3af29ef43..43b426ce30 100644 --- a/tools/linuxfs/preload/udevmon.c +++ b/tools/linuxfs/preload/udevmon.c @@ -14,6 +14,7 @@ #include #include #include +#include #include struct stand_in { @@ -40,6 +41,19 @@ static ino_t socket_inode(int fd) { return fstat(fd, &st) == 0 ? st.st_ino : 0; } +static struct stand_in *available_stand_in(void) { + for (size_t i = 0; i < sizeof(stand_ins) / sizeof(stand_ins[0]); i++) { + struct stand_in *entry = &stand_ins[i]; + if (entry->fd == -1) return entry; + if (entry->inode != socket_inode(entry->fd)) { + close(entry->peer); + entry->fd = -1; + return entry; + } + } + return NULL; +} + static int is_stand_in(int fd) { int found = 0; if (fd < 0) @@ -86,14 +100,11 @@ static int make_stand_in(int type) { } fcntl(sv[1], F_SETFD, FD_CLOEXEC); pthread_mutex_lock(&lock); - for (size_t i = 0; i < sizeof(stand_ins) / sizeof(stand_ins[0]); i++) { - if (stand_ins[i].fd == -1) { - stand_ins[i].fd = sv[0]; - stand_ins[i].peer = sv[1]; - stand_ins[i].inode = socket_inode(sv[0]); - pthread_mutex_unlock(&lock); - return sv[0]; - } + struct stand_in *entry = available_stand_in(); + if (entry != NULL) { + *entry = (struct stand_in){.fd = sv[0], .peer = sv[1], .inode = socket_inode(sv[0])}; + pthread_mutex_unlock(&lock); + return sv[0]; } pthread_mutex_unlock(&lock); close(sv[0]); @@ -146,6 +157,58 @@ __attribute__((visibility("hidden"))) int dd_udevmon_stand_in(int fd) { return is_stand_in(fd); } +static int subscribed(int fd) { +#ifdef UDEVMON_TEST + if (getenv("DD_UDEVMON_REFUSE") != NULL) return 0; +#endif + struct sockaddr_nl nl; + socklen_t len = sizeof(nl); + memset(&nl, 0, sizeof(nl)); + return getsockname(fd, (struct sockaddr *)&nl, &len) == 0 && nl.nl_groups != 0; +} + +/* Android lets an app open a uevent socket but not join its multicast groups, and libudev joins none + when no udev daemon runs, so a monitor bound there hears nothing. Such a socket is replaced, under + the same descriptor, by a stand-in. */ +__attribute__((visibility("hidden"))) int dd_udevmon_bind(int fd, const struct sockaddr *addr, socklen_t len, + int (*real_bind)(int, const struct sockaddr *, socklen_t), + int *rc) { + int protocol = -1; + socklen_t protocol_len = sizeof(protocol); + if (addr == NULL || len < sizeof(struct sockaddr_nl) || addr->sa_family != AF_NETLINK) return 0; + if (is_stand_in(fd) || is_wine_process()) return 0; + if (getsockopt(fd, SOL_SOCKET, SO_PROTOCOL, &protocol, &protocol_len) != 0 || protocol != NETLINK_KOBJECT_UEVENT) + return 0; + *rc = real_bind(fd, addr, len); + int refused = errno; + if (subscribed(fd)) { + errno = refused; + return 1; + } + int status = fcntl(fd, F_GETFL); + int descriptor = fcntl(fd, F_GETFD); + int sv[2]; + if (status < 0 || descriptor < 0 || socketpair(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0, sv) != 0) { + errno = refused; + return 1; + } + pthread_mutex_lock(&lock); + struct stand_in *entry = available_stand_in(); + if (entry == NULL || dup3(sv[0], fd, (descriptor & FD_CLOEXEC) ? O_CLOEXEC : 0) < 0) { + pthread_mutex_unlock(&lock); + close(sv[0]); + close(sv[1]); + errno = refused; + return 1; + } + close(sv[0]); + if (status & O_NONBLOCK) fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK); + *entry = (struct stand_in){.fd = fd, .peer = sv[1], .inode = socket_inode(fd)}; + pthread_mutex_unlock(&lock); + *rc = 0; + return 1; +} + int getsockname(int fd, struct sockaddr *addr, socklen_t *len) { static int (*real_getsockname)(int, struct sockaddr *, socklen_t *); struct sockaddr_nl nl; diff --git a/tools/tests/test_cdp_guard.py b/tools/tests/test_cdp_guard.py index 9dc5891f36..0fc023e872 100644 --- a/tools/tests/test_cdp_guard.py +++ b/tools/tests/test_cdp_guard.py @@ -19,7 +19,8 @@ class CdpGuardTest(unittest.TestCase): subprocess.run(["cc", "-shared", "-fPIC", "-O2", str(SOURCE), str(SOURCE.parent / "binfmt.c"), str(SOURCE.parent / "webhelper.c"), str(Path(__file__).with_name("netlink_stubs.c")), "-x", "c", "-", "-ldl", "-o", str(cls.library)], - input=b"int dd_udevmon_stand_in(int fd) { return 0; }", check=True, capture_output=True) + input=b"int dd_udevmon_stand_in(int fd) { return 0; }\n" + b"int dd_udevmon_bind(int fd, const void *addr, unsigned len, void *real, int *rc) { return 0; }", check=True, capture_output=True) @classmethod def tearDownClass(cls): diff --git a/tools/tests/test_udevmon_preload.py b/tools/tests/test_udevmon_preload.py new file mode 100644 index 0000000000..ae100ecfbb --- /dev/null +++ b/tools/tests/test_udevmon_preload.py @@ -0,0 +1,112 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload" + +PROGRAM = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char **argv) { + unsigned groups = argc > 1 ? (unsigned)atoi(argv[1]) : 2; + const char *mode = argc > 2 ? argv[2] : ""; + if (!strcmp(mode, "churn")) { + for (int i = 0; i < 16; i++) { + int closed = socket(AF_NETLINK, SOCK_RAW, NETLINK_KOBJECT_UEVENT); + struct sockaddr_nl unsubscribed = {.nl_family = AF_NETLINK}; + if (closed < 0 || bind(closed, (struct sockaddr *)&unsubscribed, sizeof(unsubscribed)) != 0) return 3; + close(closed); + if (open("/dev/null", O_RDONLY) != closed) return 4; + } + } + int fd = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC | SOCK_NONBLOCK, NETLINK_KOBJECT_UEVENT); + if (fd < 0) { printf("socket failed\n"); return 2; } + struct sockaddr_nl nl = {.nl_family = AF_NETLINK, .nl_groups = groups}; + printf("bind %d\n", bind(fd, (struct sockaddr *)&nl, sizeof(nl))); + if (!strcmp(mode, "rebind")) { + nl.nl_pid = (unsigned)getpid() + 1; + printf("rebind %d\n", bind(fd, (struct sockaddr *)&nl, sizeof(nl))); + } + printf("cloexec %d nonblock %d\n", (fcntl(fd, F_GETFD) & FD_CLOEXEC) != 0, (fcntl(fd, F_GETFL) & O_NONBLOCK) != 0); + int (*inject)(const char *, const char *, const char *, const char *, unsigned, unsigned) = + (int (*)(const char *, const char *, const char *, const char *, unsigned, unsigned))dlsym(RTLD_DEFAULT, "dd_udevmon_inject"); + int sent = inject("add", "/devices/droiddeck/usb4/4-1:1.3/0003:054C:09CC.0005/hidraw/hidraw20", "hidraw", + "/dev/hidraw20", 245, 20); + printf("sent %d\n", sent); + struct pollfd p = {.fd = fd, .events = POLLIN}; + if (sent > 0 && poll(&p, 1, 1000) == 1) { + char buf[2048]; + struct sockaddr_nl from; + struct iovec iov = {.iov_base = buf, .iov_len = sizeof(buf)}; + struct msghdr msg = {.msg_name = &from, .msg_namelen = sizeof(from), .msg_iov = &iov, .msg_iovlen = 1}; + ssize_t n = recvmsg(fd, &msg, 0); + int found = 0; + for (ssize_t i = 0; n > 0 && i < n; i += (ssize_t)strlen(buf + i) + 1) + if (!strcmp(buf + i, "ACTION=add") || !strcmp(buf + i, "DEVNAME=/dev/hidraw20")) found++; + printf("received %s fields %d\n", n > 0 && !memcmp(buf, "libudev", 8) ? "libudev" : "nothing", found); + } + return 0; +} +""" + + +@unittest.skipUnless(shutil.which("gcc") and os.uname().machine == "x86_64", "needs gcc on an x86-64 host") +class UdevMonitorPreloadTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tmp = Path(tempfile.mkdtemp()) + cls.library = cls.tmp / "libudevmon.so" + subprocess.run(["gcc", "-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror", "-DUDEVMON_TEST", "-DBINFMT_TEST", + '-DBINFMT_HANDLER="/bin/false"', "-o", str(cls.library), "-pthread"] + + [str(PRELOAD / name) for name in ("binfmt.c", "net.c", "udevmon.c", "pathcache.c", "perms.c", "webhelper.c")] + + [str(Path(__file__).with_name("netlink_stubs.c")), "-ldl"], check=True) + source = cls.tmp / "program.c" + source.write_text(PROGRAM) + cls.program = cls.tmp / "program" + subprocess.run(["gcc", "-O2", "-o", str(cls.program), str(source), "-ldl"], check=True) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, True) + + def run_program(self, *args, refuse=False): + env = dict(os.environ, LD_PRELOAD=str(self.library)) + env.pop("DD_UDEVMON_REFUSE", None) + if refuse: + env["DD_UDEVMON_REFUSE"] = "1" + return subprocess.run([str(self.program), *args], env=env, capture_output=True, text=True, check=True).stdout.splitlines() + + def test_a_monitor_the_system_will_not_subscribe_hears_the_sessions_events(self): + out = self.run_program(refuse=True) + self.assertEqual(["bind 0", "cloexec 1 nonblock 1", "sent 1", "received libudev fields 2"], out) + + def test_a_monitor_the_system_subscribes_stays_on_the_real_socket(self): + self.assertEqual(["bind 0", "cloexec 1 nonblock 1", "sent 0"], self.run_program()) + + def test_a_monitor_bound_without_groups_hears_the_sessions_events(self): + out = self.run_program("0") + self.assertEqual(["bind 0", "cloexec 1 nonblock 1", "sent 1", "received libudev fields 2"], out) + + def test_failed_rebind_leaves_the_original_subscription_in_place(self): + out = self.run_program("2", "rebind") + self.assertEqual(["bind 0", "rebind -1", "cloexec 1 nonblock 1", "sent 0"], out) + + def test_closed_monitors_do_not_exhaust_stand_in_slots(self): + out = self.run_program("0", "churn") + self.assertEqual(["bind 0", "cloexec 1 nonblock 1", "sent 1", "received libudev fields 2"], out) + + +if __name__ == "__main__": + unittest.main() From 4349563fd10a3035810552c846f9348c3fc604ea Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Sat, 21 Nov 2026 00:26:50 -0500 Subject: [PATCH 003/141] feat(display): zero-copy presentation toggle and compositor display buffers (#2905) * feat(display): zero-copy presentation toggle and compositor display buffers Adds a Zero-copy presentation switch under Steam Settings, Display, Session Display (on by default), and a display-buffer allocator in the compositor: a Vulkan driver that states displayBuffers asks it for the memory of the images it exports, so frames presented through the nested compositor are gralloc buffers that go on the display layer without a copy. Compressed buffers are offered only where the device's allocator matches the layout the drivers render to; everything else stays on the copy path. The private buffer protocol is renamed to droiddeck-ahb-v1. * fix(display): zero-copy frames keep the full refresh rate Two buffers set on the game layer inside one refresh replaced each other, and a frame that slipped into the next refresh made the compositor hold and drop the on-time frame behind it. The layer now queues buffers, and a refresh takes a second frame when the one before it took none. The pacing tool no longer counts its dump time in the frame rate. * Keep cropped scenes on the display layer and pace layer frames evenly Accept any in-bounds source crop for the display layer and map the draw geometry the same way the copy path does. Time layer frames against the display's frame timeline, and when the game's rate is a steady whole fraction of the refresh rate show each frame a fixed number of refreshes after the last so uneven arrivals no longer reach the screen. * List zero-copy in the settings map * Hold display buffers until the display releases them A buffer the game or gamescope rendered straight into went back to its client as soon as the next one was latched, with the display's release fence attached to the dma-buf. The KGSL driver does not wait on that fence, so the client could draw into a buffer the panel was still reading. Display buffers now wait for the release fence before the release event, and gamescope composites only into output images the host has released. * Keep the game picture copy-free when an overlay has no display layer When the display cannot give a second layer of its own to an overlay, the compositor tells gamescope how many planes it can show directly. gamescope then composes its overlays into the game picture, which still reaches the display without a copy. * feat(session): the panel refresh rate follows the session's frame rate The session learns the panel's refresh rates and reports the refresh rate and frame rate it wants. The panel moves to the highest rate the frame rate divides evenly, frame generation counts at its output rate, and a panel whose rate the system holds offers only that rate. * feat(session): the panel follows a frame rate the game holds on its own The compositor reports the game's frame rate once a second. A rate that holds for three seconds and divides a panel rate becomes the content rate when neither the app's limit nor the session's limiter is setting the pace, so a game capped in its own settings gets a panel rate its frames divide into. A rate that was dropped has to hold twice as long before it is used again. * Show generated frames on the game's display layer With frame generation on, the game's own frames stay on their display layer untouched and each generated frame is placed on the same layer between them, timed across the game's frame interval. The compositor pass is kept when effects, HDR routing or a cursor need it, or when the panel cannot show the multiplied rate. * Keep scaling, generated frames and HDR on the display layer A scaler or frame generation with zero-copy on now draws once into the display layer instead of falling back to the copied surface. HDR output goes to the layer when the panel supports it; on a panel without HDR the picture is tone-mapped on the same path, and the toggle is labelled to match what the panel can do. * Spread a frame limit the refresh rate does not divide evenly across refreshes * Cover the spare-tick and panel-rate paths in the compositor source tests * Pin the gamescope build with the display-plane, release, refresh and limiter patches * Give the layer and terminal-caller harnesses the black fill state they compile against * feat(display): switch HDR during a session without restarting the app The compositor now offers HDR whenever the device can present it, and the HDR setting only decides whether the session uses it. Both HDR switches set gamescope's hdr_enabled, the compositor's HDR output and zero-copy for the running session. gamescope patch 0139 lets hdr_enabled change after start. The 'Restart the app to apply.' hint is removed from every locale. * Remake the output images in the new format when HDR is switched during a session * Pin the gamescope build that switches HDR during a session * Apply a saved HDR opt-out at session start and keep HDR retries with their session * Serialise the HDR output switch with the gate opening * feat(display): keep the client's HDR setting and the session's in step The session publishes its HDR state with the other device controls and the client helper applies it to the client's own display setting. A change made in the client is reported back and goes through the same switch the drawer and Session Display use, so all three always show one value. * fix(desktop): keep the display-buffer socket when the runtime directory is cleared The desktop launcher removed everything in the runtime directory except the compositor's Wayland socket, which took the display-buffer socket with it, so no desktop program could ask for display buffers and every frame was copied. * fix(display): the client's HDR setting follows the session in every client mode The bridge only ran when a variable nothing sets was present, so the client's HDR setting and the session's never met. It now runs whenever the session publishes an HDR state, and a client that has no such setting is asked again only every ten seconds. * fix(display): harden display-buffer hand-off, layer fallbacks and HDR sync - Stop closing a buffer handle's descriptor the allocator still owns, and free an allocation whose reply could not be sent. - Rebuild the advertised buffer formats when zero-copy is switched during a session. - Fall back to the copy path when a layer buffer cannot be allocated, and hide the game layer when it is skipped for a frame. - Keep a release fence that has not signalled instead of rendering into a buffer the display still reads. - Ignore a refresh-target reset from a client that does not own the target. - Restart the content-rate measurement after a pause, clear it when the game stops, and lengthen engagement only for a rate that was released before. - Compare colour conversions by their values, and read padded cursor buffers at their row width. - Use the running session's mode for the HDR and zero-copy settings, probe the display before screen effects are pushed, retry a held panel mode, and ignore callbacks after the activity is destroyed. - Write a newer HDR value while an earlier write is settling, and reapply the value after the bridge is reinstalled. --- app/src/main/cpp/waylandcomp/CMakeLists.txt | 4 +- .../main/cpp/waylandcomp/ZERO_COPY_SPIKE.md | 12 +- ...protocol.c => droiddeck-ahb-v1-protocol.c} | 20 +- ...l.h => droiddeck-ahb-v1-server-protocol.h} | 28 +- .../generated/droiddeck-refresh-v1-protocol.c | 59 ++ .../droiddeck-refresh-v1-server-protocol.h | 175 +++++ ...banner-ahb-v1.xml => droiddeck-ahb-v1.xml} | 4 +- .../protocols/droiddeck-refresh-v1.xml | 81 +++ .../main/cpp/waylandcomp/src/ahb_swapchain.c | 114 ++-- .../main/cpp/waylandcomp/src/ahb_swapchain.h | 7 +- app/src/main/cpp/waylandcomp/src/compositor.c | 298 ++++++++- .../cpp/waylandcomp/src/compositor_internal.h | 1 + .../cpp/waylandcomp/src/display_buffers.c | 343 ++++++++++ .../cpp/waylandcomp/src/display_buffers.h | 12 + .../cpp/waylandcomp/src/droiddeck_color.h | 3 + .../main/cpp/waylandcomp/src/hdr_compose.c | 13 +- .../main/cpp/waylandcomp/src/hdr_compose.h | 4 + .../main/cpp/waylandcomp/src/hdr_encode.frag | 40 +- .../cpp/waylandcomp/src/hdr_encode_frag.h | 610 ++++++++++-------- app/src/main/cpp/waylandcomp/src/sc_layer.c | 255 ++++++-- app/src/main/cpp/waylandcomp/src/sc_layer.h | 15 +- app/src/main/cpp/waylandcomp/src/vk_present.c | 135 +++- app/src/main/cpp/waylandcomp/src/vk_present.h | 6 +- .../cpp/waylandcomp/src/waylandcomp_jni.c | 56 +- .../main/cpp/waylandcomp/src/wl_color_mgmt.c | 207 +++++- app/src/main/cpp/waylandcomp/src/wl_dmabuf.c | 21 +- .../droiddeck/launcher/FrontEndActivity.kt | 17 +- .../com/droiddeck/launcher/SessionActivity.kt | 170 ++++- .../droiddeck/launcher/agent/AgentGuest.kt | 14 + .../com/droiddeck/launcher/gpu/FrameGen.kt | 2 + .../gpu/LinuxVulkanDriverManager.java | 6 + .../droiddeck/launcher/gpu/ScreenEffects.kt | 3 +- .../runtime/DeviceControlsComponent.kt | 14 +- .../launcher/session/ContentCadence.kt | 65 ++ .../droiddeck/launcher/session/PerfMode.kt | 70 +- .../droiddeck/launcher/session/SessionHdr.kt | 36 ++ .../launcher/session/SessionPrefs.kt | 12 +- .../launcher/session/SessionService.kt | 3 + .../launcher/session/SessionState.kt | 4 + .../launcher/ui/ModeSettingsDialog.kt | 9 +- .../droiddeck/launcher/ui/SessionOverlay.kt | 7 +- .../droiddeck/launcher/ui/SettingsIndex.kt | 2 +- .../launcher/wayland/CompositorHost.kt | 32 +- .../droiddeck/launcher/wayland/HdrSupport.kt | 5 +- .../launcher/wayland/WaylandCompositor.java | 75 ++- app/src/main/res/values-ar/strings.xml | 2 +- app/src/main/res/values-b+es+419/strings.xml | 2 +- app/src/main/res/values-bg/strings.xml | 2 +- app/src/main/res/values-cs/strings.xml | 2 +- app/src/main/res/values-da/strings.xml | 2 +- app/src/main/res/values-de/strings.xml | 2 +- app/src/main/res/values-el/strings.xml | 2 +- app/src/main/res/values-es/strings.xml | 2 +- app/src/main/res/values-fi/strings.xml | 2 +- app/src/main/res/values-fr/strings.xml | 2 +- app/src/main/res/values-hi/strings.xml | 2 +- app/src/main/res/values-hu/strings.xml | 2 +- app/src/main/res/values-in/strings.xml | 2 +- app/src/main/res/values-it/strings.xml | 2 +- app/src/main/res/values-ja/strings.xml | 2 +- app/src/main/res/values-ko/strings.xml | 2 +- app/src/main/res/values-ms/strings.xml | 2 +- app/src/main/res/values-nb/strings.xml | 2 +- app/src/main/res/values-nl/strings.xml | 2 +- app/src/main/res/values-pl/strings.xml | 2 +- app/src/main/res/values-pt-rPT/strings.xml | 2 +- app/src/main/res/values-pt/strings.xml | 2 +- app/src/main/res/values-ro/strings.xml | 2 +- app/src/main/res/values-ru/strings.xml | 2 +- app/src/main/res/values-sv/strings.xml | 2 +- app/src/main/res/values-th/strings.xml | 2 +- app/src/main/res/values-tr/strings.xml | 2 +- app/src/main/res/values-uk/strings.xml | 2 +- app/src/main/res/values-vi/strings.xml | 2 +- app/src/main/res/values-zh-rCN/strings.xml | 2 +- app/src/main/res/values-zh-rHK/strings.xml | 2 +- app/src/main/res/values-zh-rTW/strings.xml | 2 +- app/src/main/res/values/strings.xml | 2 +- .../launcher/session/ContentCadenceTest.kt | 84 +++ .../launcher/session/PerfModeTest.kt | 60 ++ docs/progress-log.md | 5 +- docs/settings-map.md | 2 +- tools/droiddeckctl | 2 +- tools/gamescope/PATCHES.md | 48 ++ .../0135-wayland-overlay-plane-limit.patch | 20 + ...omposite-into-released-output-images.patch | 218 +++++++ ...7-wayland-backend-host-refresh-rates.patch | 293 +++++++++ .../patches/0138-limiter-even-cadence.patch | 67 ++ .../patches/0139-hdr-switch-live.patch | 54 ++ tools/gamescope/release.env | 4 +- tools/linuxfs/desktop/droiddeck-desktop | 2 +- .../usr/local/bin/droiddeck-steam-compat | 107 ++- tools/tests/test_desktop_display_buffers.py | 29 + tools/tests/test_effects_source_resolution.py | 6 +- tools/tests/test_gamescope_limiter_cadence.py | 118 ++++ tools/tests/test_hdr_live_switch.py | 87 +++ tools/tests/test_hdr_steam_sync.py | 185 ++++++ tools/tests/test_output_refresh.py | 9 +- tools/tests/test_render_on_commit.py | 13 +- tools/tests/test_vk_linear_dmabuf.py | 1 + tools/tests/vk_terminal_callers_test.c | 2 +- 101 files changed, 3927 insertions(+), 624 deletions(-) rename app/src/main/cpp/waylandcomp/generated/{banner-ahb-v1-protocol.c => droiddeck-ahb-v1-protocol.c} (76%) rename app/src/main/cpp/waylandcomp/generated/{banner-ahb-v1-server-protocol.h => droiddeck-ahb-v1-server-protocol.h} (73%) create mode 100644 app/src/main/cpp/waylandcomp/generated/droiddeck-refresh-v1-protocol.c create mode 100644 app/src/main/cpp/waylandcomp/generated/droiddeck-refresh-v1-server-protocol.h rename app/src/main/cpp/waylandcomp/protocols/{banner-ahb-v1.xml => droiddeck-ahb-v1.xml} (98%) create mode 100644 app/src/main/cpp/waylandcomp/protocols/droiddeck-refresh-v1.xml create mode 100644 app/src/main/cpp/waylandcomp/src/display_buffers.c create mode 100644 app/src/main/cpp/waylandcomp/src/display_buffers.h create mode 100644 app/src/main/java/com/droiddeck/launcher/session/ContentCadence.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/session/SessionHdr.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/session/ContentCadenceTest.kt create mode 100644 tools/gamescope/patches/0135-wayland-overlay-plane-limit.patch create mode 100644 tools/gamescope/patches/0136-composite-into-released-output-images.patch create mode 100644 tools/gamescope/patches/0137-wayland-backend-host-refresh-rates.patch create mode 100644 tools/gamescope/patches/0138-limiter-even-cadence.patch create mode 100644 tools/gamescope/patches/0139-hdr-switch-live.patch create mode 100644 tools/tests/test_desktop_display_buffers.py create mode 100644 tools/tests/test_gamescope_limiter_cadence.py create mode 100644 tools/tests/test_hdr_live_switch.py create mode 100644 tools/tests/test_hdr_steam_sync.py diff --git a/app/src/main/cpp/waylandcomp/CMakeLists.txt b/app/src/main/cpp/waylandcomp/CMakeLists.txt index 13e9e1b3e0..5bdc1e8385 100644 --- a/app/src/main/cpp/waylandcomp/CMakeLists.txt +++ b/app/src/main/cpp/waylandcomp/CMakeLists.txt @@ -8,6 +8,7 @@ add_library(droiddeckwayland SHARED src/vk_loader.c src/sc_layer.c src/ahb_swapchain.c + src/display_buffers.c src/waylandcomp_jni.c src/gpu_clock_pin.c src/droiddeck_ext.c @@ -34,7 +35,8 @@ add_library(droiddeckwayland SHARED generated/text-input-unstable-v3-protocol.c generated/xdg-toplevel-icon-v1-protocol.c generated/single-pixel-buffer-v1-protocol.c - generated/banner-ahb-v1-protocol.c + generated/droiddeck-ahb-v1-protocol.c + generated/droiddeck-refresh-v1-protocol.c src/framegen_bridge.c src/framegen_jni.c src/hudframes.c diff --git a/app/src/main/cpp/waylandcomp/ZERO_COPY_SPIKE.md b/app/src/main/cpp/waylandcomp/ZERO_COPY_SPIKE.md index 37b08b2334..f5e7177244 100644 --- a/app/src/main/cpp/waylandcomp/ZERO_COPY_SPIKE.md +++ b/app/src/main/cpp/waylandcomp/ZERO_COPY_SPIKE.md @@ -19,8 +19,8 @@ exactly how Turnip already imports every gralloc buffer on Android (`vk_android. in play already have every extension needed; nothing is missing in the drivers. What is missing is a **WSI hook**: Mesa's Wayland WSI always allocates its own dma-bufs and has no way to receive or allocate compositor-visible buffers, so **option (a) or (c) each need a ~300-line patch to -`wsi_common_wayland.c` in our own Wayland Turnip build** (banners-turnip-wayland -`build_turnip_wayland_wsi.sh`, Mesa `7cda7850`) plus a small private Wayland protocol. Nothing in +`wsi_common_wayland.c` in our own Wayland Turnip build** +(`build_turnip_wayland_wsi.sh`, Mesa `7cda7850`) plus a small private Wayland protocol. Nothing in the app can remove the copy on its own. Recommended: **option (a′) - the game's WSI allocates its swapchain images as `AHardwareBuffer`s (gralloc-native, UBWC), imports them through the AHB path Turnip already has, and hands the compositor the AHB over a Unix socket (`AHardwareBuffer_send/ @@ -77,7 +77,7 @@ Mesa's Wayland WSI creates every native swapchain image with `wsi_create_native_ (the Android-WSI import path, `tu_image.cc:880-925`) is only reachable from the Android swapchain. The patch (in our Wayland Turnip build): a new `create_mem` for the Wayland chain, selected when the -compositor advertises a private global `banner_layer_buffer_v1`: +compositor advertises a private global `droiddeck_layer_buffer_v1`: 1. `AHardwareBuffer_allocate(w, h, R8G8B8A8, GPU_COLOR_OUTPUT | GPU_SAMPLED_IMAGE)`; `vkGetAndroidHardwareBufferPropertiesANDROID` → `vkAllocateMemory` with `VkImportAndroidHardwareBufferInfoANDROID` (Turnip: `tu_device.cc:3828`), bind - the image was @@ -85,7 +85,7 @@ compositor advertises a private global `banner_layer_buffer_v1`: 2. `wsi_image.dma_buf_fd = dup(native_handle->data[0])`, `drm_modifier` / `row_pitches[0]` from the same layout → the existing `zwp_linux_dmabuf_v1` path stays untouched: the compositor keeps importing a dma-buf and can keep the blit path as the fallback. -3. `banner_layer_buffer_v1.attach(wl_buffer, socket_fd)`: the WSI creates a `socketpair`, sends one +3. `droiddeck_layer_buffer_v1.attach(wl_buffer, socket_fd)`: the WSI creates a `socketpair`, sends one end in the request, and calls `AHardwareBuffer_sendHandleToUnixSocket(ahb, other_end)`; the compositor's request handler does `AHardwareBuffer_recvHandleFromUnixSocket` and stores the AHB on `struct dmabuf_buffer`. Per swapchain image, once - not per frame. @@ -262,7 +262,7 @@ D3D12 tabs) as the workload, session log in `Download/Wayland-logs/`. since the blit only changed its destination) and `dumpsys gfxinfo`/battery for 5 min each. This is the baseline the WSI patch is measured against. 4. **Fence probe outcome → choose the acquire-fence design** (§3) before starting the WSI patch. -5. **WSI patch (option a) in banners-turnip-wayland**, wcp rebuild, then the same steps 1–3 with +5. **WSI patch (option a) in the Wayland Turnip build**, wcp rebuild, then the same steps 1–3 with the AHB arriving from the guest: log line to add on the compositor side `layer: buffer N of "" received from the game (AHardwareBuffer WxH, UBWC)` and the fps delta vs X11. @@ -296,7 +296,7 @@ unchanged. Off by default: with the variable unset no new code runs. Not zero-copy yet - it is the receive side. The copy disappears when step 5 lands and `sc_layer_present` is handed the game's own `AHardwareBuffer` instead of a pool slot. -## 7. Step 5 implemented (feat/wayland-zero-copy-wsi + banners-turnip-wayland `banner_ahb_wsi.py`) +## 7. Step 5 implemented (feat/wayland-zero-copy-wsi + the Wayland Turnip build `droiddeck_ahb_wsi.py`) Option (a′) as recommended, with one deviation forced by the build: the Wayland Turnip is a `platforms=wayland` build with Android detection off, so `VK_ANDROID_external_memory_android_hardware_buffer` diff --git a/app/src/main/cpp/waylandcomp/generated/banner-ahb-v1-protocol.c b/app/src/main/cpp/waylandcomp/generated/droiddeck-ahb-v1-protocol.c similarity index 76% rename from app/src/main/cpp/waylandcomp/generated/banner-ahb-v1-protocol.c rename to app/src/main/cpp/waylandcomp/generated/droiddeck-ahb-v1-protocol.c index 17b0c0dfd1..1c7e42dbf5 100644 --- a/app/src/main/cpp/waylandcomp/generated/banner-ahb-v1-protocol.c +++ b/app/src/main/cpp/waylandcomp/generated/droiddeck-ahb-v1-protocol.c @@ -38,7 +38,7 @@ extern const struct wl_interface wl_buffer_interface; -static const struct wl_interface *banner_ahb_v1_types[] = { +static const struct wl_interface *droiddeck_ahb_v1_types[] = { NULL, &wl_buffer_interface, NULL, @@ -50,18 +50,18 @@ static const struct wl_interface *banner_ahb_v1_types[] = { NULL, }; -static const struct wl_message banner_ahb_v1_requests[] = { - { "destroy", "", banner_ahb_v1_types + 0 }, - { "attach", "ohuuuuuu", banner_ahb_v1_types + 1 }, +static const struct wl_message droiddeck_ahb_v1_requests[] = { + { "destroy", "", droiddeck_ahb_v1_types + 0 }, + { "attach", "ohuuuuuu", droiddeck_ahb_v1_types + 1 }, }; -static const struct wl_message banner_ahb_v1_events[] = { - { "mode", "2u", banner_ahb_v1_types + 0 }, +static const struct wl_message droiddeck_ahb_v1_events[] = { + { "mode", "2u", droiddeck_ahb_v1_types + 0 }, }; -WL_PRIVATE const struct wl_interface banner_ahb_v1_interface = { - "banner_ahb_v1", 2, - 2, banner_ahb_v1_requests, - 1, banner_ahb_v1_events, +WL_PRIVATE const struct wl_interface droiddeck_ahb_v1_interface = { + "droiddeck_ahb_v1", 2, + 2, droiddeck_ahb_v1_requests, + 1, droiddeck_ahb_v1_events, }; diff --git a/app/src/main/cpp/waylandcomp/generated/banner-ahb-v1-server-protocol.h b/app/src/main/cpp/waylandcomp/generated/droiddeck-ahb-v1-server-protocol.h similarity index 73% rename from app/src/main/cpp/waylandcomp/generated/banner-ahb-v1-server-protocol.h rename to app/src/main/cpp/waylandcomp/generated/droiddeck-ahb-v1-server-protocol.h index 788982c105..118ca6c611 100644 --- a/app/src/main/cpp/waylandcomp/generated/banner-ahb-v1-server-protocol.h +++ b/app/src/main/cpp/waylandcomp/generated/droiddeck-ahb-v1-server-protocol.h @@ -1,6 +1,6 @@ -#ifndef BANNER_AHB_V1_SERVER_PROTOCOL_H -#define BANNER_AHB_V1_SERVER_PROTOCOL_H +#ifndef DROIDDECK_AHB_V1_SERVER_PROTOCOL_H +#define DROIDDECK_AHB_V1_SERVER_PROTOCOL_H #include #include @@ -14,7 +14,7 @@ struct wl_client; struct wl_resource; /* - * @section page_copyright_banner_ahb_v1 Copyright + * @section page_copyright_droiddeck_ahb_v1 Copyright * * Copyright 2026 The412Banner * @@ -42,15 +42,15 @@ struct wl_resource; -struct banner_ahb_v1; +struct droiddeck_ahb_v1; struct wl_buffer; -#ifndef BANNER_AHB_V1_INTERFACE -#define BANNER_AHB_V1_INTERFACE -extern const struct wl_interface banner_ahb_v1_interface; +#ifndef DROIDDECK_AHB_V1_INTERFACE +#define DROIDDECK_AHB_V1_INTERFACE +extern const struct wl_interface droiddeck_ahb_v1_interface; #endif -struct banner_ahb_v1_interface { +struct droiddeck_ahb_v1_interface { void (*destroy)(struct wl_client *client, struct wl_resource *resource); void (*attach)(struct wl_client *client, @@ -65,17 +65,17 @@ struct banner_ahb_v1_interface { uint32_t image_count); }; -#define BANNER_AHB_V1_MODE 0 +#define DROIDDECK_AHB_V1_MODE 0 -#define BANNER_AHB_V1_MODE_SINCE_VERSION 2 +#define DROIDDECK_AHB_V1_MODE_SINCE_VERSION 2 -#define BANNER_AHB_V1_DESTROY_SINCE_VERSION 1 -#define BANNER_AHB_V1_ATTACH_SINCE_VERSION 1 +#define DROIDDECK_AHB_V1_DESTROY_SINCE_VERSION 1 +#define DROIDDECK_AHB_V1_ATTACH_SINCE_VERSION 1 static inline void -banner_ahb_v1_send_mode(struct wl_resource *resource_, uint32_t enabled) +droiddeck_ahb_v1_send_mode(struct wl_resource *resource_, uint32_t enabled) { - wl_resource_post_event(resource_, BANNER_AHB_V1_MODE, enabled); + wl_resource_post_event(resource_, DROIDDECK_AHB_V1_MODE, enabled); } #ifdef __cplusplus diff --git a/app/src/main/cpp/waylandcomp/generated/droiddeck-refresh-v1-protocol.c b/app/src/main/cpp/waylandcomp/generated/droiddeck-refresh-v1-protocol.c new file mode 100644 index 0000000000..bd26d77a28 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/generated/droiddeck-refresh-v1-protocol.c @@ -0,0 +1,59 @@ +/* + * Copyright 2026 DroidDeck contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice (including the next + * paragraph) shall be included in all copies or substantial portions of the + * Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +#include +#include +#include "wayland-util.h" + +#ifndef __has_attribute +# define __has_attribute(x) 0 /* Compatibility with non-clang compilers. */ +#endif + +#if (__has_attribute(visibility) || defined(__GNUC__) && __GNUC__ >= 4) +#define WL_PRIVATE __attribute__ ((visibility("hidden"))) +#else +#define WL_PRIVATE +#endif + + +static const struct wl_interface *droiddeck_refresh_v1_types[] = { + NULL, + NULL, +}; + +static const struct wl_message droiddeck_refresh_v1_requests[] = { + { "destroy", "", droiddeck_refresh_v1_types + 0 }, + { "set_target", "uu", droiddeck_refresh_v1_types + 0 }, +}; + +static const struct wl_message droiddeck_refresh_v1_events[] = { + { "rate", "u", droiddeck_refresh_v1_types + 0 }, + { "done", "", droiddeck_refresh_v1_types + 0 }, +}; + +WL_PRIVATE const struct wl_interface droiddeck_refresh_v1_interface = { + "droiddeck_refresh_v1", 1, + 2, droiddeck_refresh_v1_requests, + 2, droiddeck_refresh_v1_events, +}; + diff --git a/app/src/main/cpp/waylandcomp/generated/droiddeck-refresh-v1-server-protocol.h b/app/src/main/cpp/waylandcomp/generated/droiddeck-refresh-v1-server-protocol.h new file mode 100644 index 0000000000..32d1c17782 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/generated/droiddeck-refresh-v1-server-protocol.h @@ -0,0 +1,175 @@ + +#ifndef DROIDDECK_REFRESH_V1_SERVER_PROTOCOL_H +#define DROIDDECK_REFRESH_V1_SERVER_PROTOCOL_H + +#include +#include +#include "wayland-server.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct wl_client; +struct wl_resource; + +/** + * @page page_droiddeck_refresh_v1 The droiddeck_refresh_v1 protocol + * @section page_ifaces_droiddeck_refresh_v1 Interfaces + * - @subpage page_iface_droiddeck_refresh_v1 - panel refresh rates a nested compositor may ask for + * @section page_copyright_droiddeck_refresh_v1 Copyright + *
+ *
+ * Copyright 2026 DroidDeck contributors
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the next
+ * paragraph) shall be included in all copies or substantial portions of the
+ * Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ * 
+ */ +struct droiddeck_refresh_v1; + +#ifndef DROIDDECK_REFRESH_V1_INTERFACE +#define DROIDDECK_REFRESH_V1_INTERFACE +/** + * @page page_iface_droiddeck_refresh_v1 droiddeck_refresh_v1 + * @section page_iface_droiddeck_refresh_v1_desc Description + * + * A nested compositor paces its clients against the refresh rate of the + * panel it is shown on. When its clients are held to a frame rate the + * panel's current rate does not divide evenly, frames are shown for an + * uneven number of refreshes. This interface lets the nested compositor + * see every refresh rate the panel can run at its current size and ask + * for the one that suits the frame rate it is pacing to. + * + * On bind the compositor sends one rate event per refresh rate, lowest + * first, followed by done. The list is sent again, in full, whenever it + * changes (a different panel, or a limit the user placed on the panel's + * rate). The rate the panel is running at is still reported the standard + * way, through wl_output.mode. + * + * A request is a preference, not a guarantee: the user, the platform or + * another output mirroring the panel may hold the panel at another rate. + * The client reads the result from wl_output.mode. + * @section page_iface_droiddeck_refresh_v1_api API + * See @ref iface_droiddeck_refresh_v1. + */ +/** + * @defgroup iface_droiddeck_refresh_v1 The droiddeck_refresh_v1 interface + * + * A nested compositor paces its clients against the refresh rate of the + * panel it is shown on. When its clients are held to a frame rate the + * panel's current rate does not divide evenly, frames are shown for an + * uneven number of refreshes. This interface lets the nested compositor + * see every refresh rate the panel can run at its current size and ask + * for the one that suits the frame rate it is pacing to. + * + * On bind the compositor sends one rate event per refresh rate, lowest + * first, followed by done. The list is sent again, in full, whenever it + * changes (a different panel, or a limit the user placed on the panel's + * rate). The rate the panel is running at is still reported the standard + * way, through wl_output.mode. + * + * A request is a preference, not a guarantee: the user, the platform or + * another output mirroring the panel may hold the panel at another rate. + * The client reads the result from wl_output.mode. + */ +extern const struct wl_interface droiddeck_refresh_v1_interface; +#endif + +/** + * @ingroup iface_droiddeck_refresh_v1 + * @struct droiddeck_refresh_v1_interface + */ +struct droiddeck_refresh_v1_interface { + /** + * destroy the object + * + * The preference set through this object is dropped. + */ + void (*destroy)(struct wl_client *client, + struct wl_resource *resource); + /** + * ask for a refresh rate + * + * refresh is the panel rate the client would like, in Hz, taken + * from the advertised list; 0 withdraws the preference. frame_rate + * is the frame rate the client holds its content to, in frames per + * second, or 0 when the content is not held to a rate. The + * compositor may multiply the content's frame rate itself + * (generated frames); when it does, it picks the advertised rate + * that the multiplied frame rate divides evenly instead of the + * requested one. + * @param refresh wanted panel refresh rate in Hz, 0 for none + * @param frame_rate content frame rate in frames per second, 0 for unpaced + */ + void (*set_target)(struct wl_client *client, + struct wl_resource *resource, + uint32_t refresh, + uint32_t frame_rate); +}; + +#define DROIDDECK_REFRESH_V1_RATE 0 +#define DROIDDECK_REFRESH_V1_DONE 1 + +/** + * @ingroup iface_droiddeck_refresh_v1 + */ +#define DROIDDECK_REFRESH_V1_RATE_SINCE_VERSION 1 +/** + * @ingroup iface_droiddeck_refresh_v1 + */ +#define DROIDDECK_REFRESH_V1_DONE_SINCE_VERSION 1 + +/** + * @ingroup iface_droiddeck_refresh_v1 + */ +#define DROIDDECK_REFRESH_V1_DESTROY_SINCE_VERSION 1 +/** + * @ingroup iface_droiddeck_refresh_v1 + */ +#define DROIDDECK_REFRESH_V1_SET_TARGET_SINCE_VERSION 1 + +/** + * @ingroup iface_droiddeck_refresh_v1 + * Sends an rate event to the client owning the resource. + * @param resource_ The client's resource + * @param refresh panel refresh rate in Hz + */ +static inline void +droiddeck_refresh_v1_send_rate(struct wl_resource *resource_, uint32_t refresh) +{ + wl_resource_post_event(resource_, DROIDDECK_REFRESH_V1_RATE, refresh); +} + +/** + * @ingroup iface_droiddeck_refresh_v1 + * Sends an done event to the client owning the resource. + * @param resource_ The client's resource + */ +static inline void +droiddeck_refresh_v1_send_done(struct wl_resource *resource_) +{ + wl_resource_post_event(resource_, DROIDDECK_REFRESH_V1_DONE); +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/app/src/main/cpp/waylandcomp/protocols/banner-ahb-v1.xml b/app/src/main/cpp/waylandcomp/protocols/droiddeck-ahb-v1.xml similarity index 98% rename from app/src/main/cpp/waylandcomp/protocols/banner-ahb-v1.xml rename to app/src/main/cpp/waylandcomp/protocols/droiddeck-ahb-v1.xml index 1560c8f7cb..a40b0dcd88 100644 --- a/app/src/main/cpp/waylandcomp/protocols/banner-ahb-v1.xml +++ b/app/src/main/cpp/waylandcomp/protocols/droiddeck-ahb-v1.xml @@ -1,5 +1,5 @@ - + Copyright 2026 The412Banner @@ -23,7 +23,7 @@ DEALINGS IN THE SOFTWARE. - + Zero-copy window layers on Android. A Vulkan swapchain image that the client allocated as an Android AHardwareBuffer (gralloc) is still shared diff --git a/app/src/main/cpp/waylandcomp/protocols/droiddeck-refresh-v1.xml b/app/src/main/cpp/waylandcomp/protocols/droiddeck-refresh-v1.xml new file mode 100644 index 0000000000..c4464a0416 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/protocols/droiddeck-refresh-v1.xml @@ -0,0 +1,81 @@ + + + + Copyright 2026 DroidDeck contributors + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice (including the next + paragraph) shall be included in all copies or substantial portions of the + Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + + + + A nested compositor paces its clients against the refresh rate of the + panel it is shown on. When its clients are held to a frame rate the + panel's current rate does not divide evenly, frames are shown for an + uneven number of refreshes. This interface lets the nested compositor + see every refresh rate the panel can run at its current size and ask + for the one that suits the frame rate it is pacing to. + + On bind the compositor sends one rate event per refresh rate, lowest + first, followed by done. The list is sent again, in full, whenever it + changes (a different panel, or a limit the user placed on the panel's + rate). The rate the panel is running at is still reported the standard + way, through wl_output.mode. + + A request is a preference, not a guarantee: the user, the platform or + another output mirroring the panel may hold the panel at another rate. + The client reads the result from wl_output.mode. + + + + + The preference set through this object is dropped. + + + + + + refresh is the panel rate the client would like, in Hz, taken from + the advertised list; 0 withdraws the preference. frame_rate is the + frame rate the client holds its content to, in frames per second, or + 0 when the content is not held to a rate. The compositor may multiply + the content's frame rate itself (generated frames); when it does, it + picks the advertised rate that the multiplied frame rate divides + evenly instead of the requested one. + + + + + + + + Sent once per rate, lowest first, in Hz rounded to the nearest whole + number. + + + + + + + Ends a list of rate events. The rates received since the previous + done replace the earlier list. + + + + diff --git a/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c b/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c index e33b0c77b4..c31915a45b 100644 --- a/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c +++ b/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c @@ -4,7 +4,7 @@ #include "droiddeck_ext.h" #include "sc_layer.h" #include "vk_present.h" -#include "banner-ahb-v1-server-protocol.h" +#include "droiddeck-ahb-v1-server-protocol.h" #include #include #include @@ -25,6 +25,7 @@ struct droiddeck_dma_buf_sync_file { uint32_t flags; int32_t fd; }; #define DROIDDECK_DMA_BUF_IOCTL_IMPORT_SYNC_FILE _IOW('b', 3, struct droiddeck_dma_buf_sync_file) extern volatile int g_zero_copy; +void droiddeck_dmabuf_formats_stale(void); struct ahb_buf { uint64_t id; @@ -37,6 +38,7 @@ struct ahb_buf { struct wl_client *client; struct wl_resource *resource; struct wl_listener resource_destroy; + int display; int on_layer; int release_pending; int64_t deferred_ns; @@ -131,10 +133,10 @@ static void handle_released(uint64_t id, int fd) { if (fd >= 0) { struct droiddeck_dma_buf_sync_file imp = {.flags = DROIDDECK_DMA_BUF_SYNC_READ, .fd = fd}; int dmabuf_fd = droiddeck_dmabuf_fd(ab->b); - if (dmabuf_fd >= 0 && ioctl(dmabuf_fd, DROIDDECK_DMA_BUF_IOCTL_IMPORT_SYNC_FILE, &imp) == 0) { + if (!ab->display && dmabuf_fd >= 0 && ioctl(dmabuf_fd, DROIDDECK_DMA_BUF_IOCTL_IMPORT_SYNC_FILE, &imp) == 0) { close(fd); } else { - if (!g_import_failed_logged) { + if (!ab->display && !g_import_failed_logged) { g_import_failed_logged = 1; droiddeck_log("layer", "zero-copy: DMA_BUF_IOCTL_IMPORT_SYNC_FILE failed (%s): releases wait for the display's fence here instead", strerror(errno)); @@ -187,7 +189,7 @@ int ahb_swapchain_has_ahb(const struct dmabuf_buffer *b) { return b && *droiddeck_dmabuf_ahb_slot((struct dmabuf_buffer *)b) != NULL; } -int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_w, int scene_h) { +int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_w, int scene_h, const struct vkp_draw *draw) { struct ahb_buf *ab = b ? *droiddeck_dmabuf_ahb_slot(b) : NULL; if (!ab) return -1; int dmabuf_fd = droiddeck_dmabuf_fd(b); @@ -205,7 +207,7 @@ int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_ int r; do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR); } - int r = sc_layer_present_ahb(ab->ahb, ab->w, ab->h, acquire, (void *)(uintptr_t)ab->id, scene_w, scene_h, + int r = sc_layer_present_ahb(ab->ahb, ab->w, ab->h, acquire, (void *)(uintptr_t)ab->id, scene_w, scene_h, draw, s ? droiddeck_surface_color(s) : NULL, ab->format); if (r < 0) return -1; if (r == 1) return 0; @@ -259,6 +261,58 @@ uint32_t ahb_swapchain_ahb_format(const struct dmabuf_buffer *b) { } +static int adopt(struct wl_client *c, struct wl_resource *buffer, struct dmabuf_buffer *b, AHardwareBuffer *ahb, + uint32_t stride, uint32_t image_count, uint64_t modifier) { + AHardwareBuffer_Desc d; + AHardwareBuffer_describe(ahb, &d); + int bw, bh; + droiddeck_dmabuf_size(b, &bw, &bh); + struct ahb_buf *ab = calloc(1, sizeof(*ab)); + if (!ab) return -1; + ab->id = g_next_id++; + ab->b = b; + droiddeck_dmabuf_ref(b); + ab->ahb = ahb; + ab->w = bw; ab->h = bh; + ab->stride = d.stride ? d.stride : stride; + ab->image_count = image_count; + ab->format = d.format; + ab->modifier = modifier; + ab->client = c; + ab->resource = buffer; + ab->resource_destroy.notify = on_buffer_resource_destroyed; + wl_resource_add_destroy_listener(buffer, &ab->resource_destroy); + ab->fence_fd = -1; + wl_list_insert(g_bufs.prev, &ab->link); + *droiddeck_dmabuf_ahb_slot(b) = ab; + + if (g_last_chain.client != c || g_last_chain.w != bw || g_last_chain.h != bh || + g_last_chain.image_count != image_count || g_last_chain.modifier != modifier || g_last_chain.format != d.format) { + char count[32] = ""; + if (image_count) snprintf(count, sizeof(count), "%u images, ", image_count); + g_last_chain = (struct chain_seen){c, bw, bh, image_count, modifier, d.format}; + droiddeck_log("layer", "zero-copy: %s from %s (%s%dx%d, %s, %s, stride %u px)", + image_count ? "AHB swapchain" : "display buffers", droiddeck_client_name(c), count, bw, bh, + droiddeck_ahb_format_name(d.format), modifier == MOD_QCOM_COMPRESSED ? "UBWC (QCOM_COMPRESSED)" + : modifier == 0 ? "linear" : "unknown modifier", ab->stride); + } + return 0; +} + +int ahb_swapchain_adopt(struct wl_client *c, struct wl_resource *buffer, struct dmabuf_buffer *b, AHardwareBuffer *ahb, + uint64_t modifier) { + if (!g_advertised || *droiddeck_dmabuf_ahb_slot(b)) return -1; + AHardwareBuffer_acquire(ahb); + if (adopt(c, buffer, b, ahb, 0, 0, modifier) != 0) { AHardwareBuffer_release(ahb); return -1; } + ((struct ahb_buf *)*droiddeck_dmabuf_ahb_slot(b))->display = 1; + return 0; +} + +AHardwareBuffer *ahb_swapchain_display_buffer(const struct dmabuf_buffer *b) { + struct ahb_buf *ab = b ? *droiddeck_dmabuf_ahb_slot((struct dmabuf_buffer *)b) : NULL; + return ab && ab->display ? ab->ahb : NULL; +} + static void ahb_destroy(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); } static void ahb_attach(struct wl_client *c, struct wl_resource *r, struct wl_resource *buffer, int32_t sock, @@ -295,36 +349,13 @@ static void ahb_attach(struct wl_client *c, struct wl_resource *r, struct wl_res AHardwareBuffer_release(ahb); return; } - - struct ahb_buf *ab = calloc(1, sizeof(*ab)); - if (!ab) { AHardwareBuffer_release(ahb); wl_client_post_no_memory(c); return; } - ab->id = g_next_id++; - ab->b = b; - droiddeck_dmabuf_ref(b); - ab->ahb = ahb; - ab->w = bw; ab->h = bh; - ab->stride = d.stride ? d.stride : stride; - ab->image_count = image_count; - ab->format = d.format; - ab->modifier = modifier; - ab->client = c; - ab->resource = buffer; - ab->resource_destroy.notify = on_buffer_resource_destroyed; - wl_resource_add_destroy_listener(buffer, &ab->resource_destroy); - ab->fence_fd = -1; - wl_list_insert(g_bufs.prev, &ab->link); - *slot = ab; - - if (g_last_chain.client != c || g_last_chain.w != bw || g_last_chain.h != bh || - g_last_chain.image_count != image_count || g_last_chain.modifier != modifier || g_last_chain.format != d.format) { - g_last_chain = (struct chain_seen){c, bw, bh, image_count, modifier, d.format}; - droiddeck_log("layer", "zero-copy: AHB swapchain from %s (%u images, %dx%d, %s, %s, stride %u px)", droiddeck_client_name(c), - image_count, bw, bh, droiddeck_ahb_format_name(d.format), modifier == MOD_QCOM_COMPRESSED ? "UBWC (QCOM_COMPRESSED)" - : modifier == 0 ? "linear" : "unknown modifier", ab->stride); + if (adopt(c, buffer, b, ahb, stride, image_count, modifier) != 0) { + AHardwareBuffer_release(ahb); + wl_client_post_no_memory(c); } } -static const struct banner_ahb_v1_interface ahb_impl = { +static const struct droiddeck_ahb_v1_interface ahb_impl = { .destroy = ahb_destroy, .attach = ahb_attach, }; @@ -336,20 +367,21 @@ static void on_client_resource_destroyed(struct wl_resource *r) { static void bind_ahb(struct wl_client *c, void *data, uint32_t ver, uint32_t id) { static struct wl_client *last_named; if (ver > 2) ver = 2; - struct wl_resource *r = wl_resource_create(c, &banner_ahb_v1_interface, (int)ver, id); + struct wl_resource *r = wl_resource_create(c, &droiddeck_ahb_v1_interface, (int)ver, id); if (!r) { wl_client_post_no_memory(c); return; } wl_resource_set_implementation(r, &ahb_impl, NULL, on_client_resource_destroyed); wl_list_insert(&g_clients, wl_resource_get_link(r)); - if (ver >= BANNER_AHB_V1_MODE_SINCE_VERSION) banner_ahb_v1_send_mode(r, g_zero_copy ? 1u : 0u); + if (ver >= DROIDDECK_AHB_V1_MODE_SINCE_VERSION) droiddeck_ahb_v1_send_mode(r, g_zero_copy ? 1u : 0u); if (last_named != c) { last_named = c; - droiddeck_log("layer", "zero-copy: %s bound banner_ahb_v1 version %u (%s)", droiddeck_client_name(c), ver, + droiddeck_log("layer", "zero-copy: %s bound droiddeck_ahb_v1 version %u (%s)", droiddeck_client_name(c), ver, ver >= 2 ? "follows the live switch" : "version 1: decides from its launch environment only"); } } void ahb_swapchain_set_mode(int on, int live) { on = on ? 1 : 0; + if (g_zero_copy != on) droiddeck_dmabuf_formats_stale(); g_zero_copy = on; if (!g_advertised) { if (live) droiddeck_log("layer", "zero-copy switched %s from the drawer, but no display layer is available on this device: no change", @@ -361,8 +393,8 @@ void ahb_swapchain_set_mode(int on, int live) { int told = 0; struct wl_resource *r; wl_resource_for_each(r, &g_clients) { - if (wl_resource_get_version(r) >= BANNER_AHB_V1_MODE_SINCE_VERSION) { - banner_ahb_v1_send_mode(r, (uint32_t)on); + if (wl_resource_get_version(r) >= DROIDDECK_AHB_V1_MODE_SINCE_VERSION) { + droiddeck_ahb_v1_send_mode(r, (uint32_t)on); told++; } } @@ -385,7 +417,7 @@ void ahb_swapchain_init(struct wl_display *display) { wl_list_init(&g_bufs); wl_list_init(&g_clients); if (!sc_layer_available()) { - droiddeck_log("layer", "zero-copy: no display layer on this device (see the line above): banner_ahb_v1 not advertised"); + droiddeck_log("layer", "zero-copy: no display layer on this device (see the line above): droiddeck_ahb_v1 not advertised"); return; } g_loop = wl_display_get_event_loop(display); @@ -395,11 +427,11 @@ void ahb_swapchain_init(struct wl_display *display) { return; } wl_event_loop_add_fd(g_loop, g_rel_pipe[0], WL_EVENT_READABLE, on_release_pipe, NULL); - if (!wl_global_create(display, &banner_ahb_v1_interface, 2, NULL, bind_ahb)) { - droiddeck_log("error", "zero-copy: banner_ahb_v1 global creation failed"); + if (!wl_global_create(display, &droiddeck_ahb_v1_interface, 2, NULL, bind_ahb)) { + droiddeck_log("error", "zero-copy: droiddeck_ahb_v1 global creation failed"); return; } g_advertised = 1; - droiddeck_log("layer", "zero-copy: banner_ahb_v1 version 2 advertised (games built for it present their own gralloc buffers while the switch is on)"); + droiddeck_log("layer", "zero-copy: droiddeck_ahb_v1 version 2 advertised (games built for it present their own gralloc buffers while the switch is on)"); ahb_swapchain_set_mode(g_zero_copy, 0); } diff --git a/app/src/main/cpp/waylandcomp/src/ahb_swapchain.h b/app/src/main/cpp/waylandcomp/src/ahb_swapchain.h index 7774482734..9002e6fc0a 100644 --- a/app/src/main/cpp/waylandcomp/src/ahb_swapchain.h +++ b/app/src/main/cpp/waylandcomp/src/ahb_swapchain.h @@ -2,16 +2,21 @@ #define AHB_SWAPCHAIN_H #include #include +#include #include struct dmabuf_buffer; struct surface; +struct vkp_draw; void ahb_swapchain_init(struct wl_display *display); void ahb_swapchain_set_mode(int on, int live); int ahb_swapchain_last_frame_age_ms(void); int ahb_swapchain_has_ahb(const struct dmabuf_buffer *b); -int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_w, int scene_h); +int ahb_swapchain_adopt(struct wl_client *c, struct wl_resource *buffer, struct dmabuf_buffer *b, AHardwareBuffer *ahb, + uint64_t modifier); +AHardwareBuffer *ahb_swapchain_display_buffer(const struct dmabuf_buffer *b); +int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_w, int scene_h, const struct vkp_draw *draw); int ahb_swapchain_defer_release(struct dmabuf_buffer *b, struct wl_resource *buffer, struct surface *s, int paced); void ahb_swapchain_surface_gone(struct surface *s); unsigned ahb_swapchain_stats_take(void); diff --git a/app/src/main/cpp/waylandcomp/src/compositor.c b/app/src/main/cpp/waylandcomp/src/compositor.c index f78f0d3f86..38c13055be 100644 --- a/app/src/main/cpp/waylandcomp/src/compositor.c +++ b/app/src/main/cpp/waylandcomp/src/compositor.c @@ -23,8 +23,10 @@ #include "linux-dmabuf-v1-server-protocol.h" #include "sc_layer.h" #include "ahb_swapchain.h" +#include "display_buffers.h" #include "viewporter-server-protocol.h" #include "droiddeck-desktop-v1-server-protocol.h" +#include "droiddeck-refresh-v1-server-protocol.h" #include "presentation-time-server-protocol.h" #include "pointer-constraints-unstable-v1-server-protocol.h" #include "relative-pointer-unstable-v1-server-protocol.h" @@ -218,6 +220,7 @@ struct surface { struct vkp_image *shm_img; + int black_fill; struct wl_resource *dmabuf; struct dmabuf_buffer *dmabuf_buf; struct wl_listener dmabuf_destroy; @@ -280,6 +283,8 @@ static int g_dirty; static int64_t g_dirty_since_ns; volatile int g_render_on_commit = 1; static int64_t g_rendered_tick_ns; +static int g_tick_spare; +static int g_scene_queues; static int g_tick_held; static int64_t g_hold_missed_ns; #define HOLD_RETRY_NS 1000000000LL @@ -289,7 +294,11 @@ static struct { int64_t tick_late_ns, tick_late_max_ns, wait_ns, wait_max_ns; const void *buffers[PACE_BUFFERS]; uint64_t game_frames_seen; + unsigned gaps[4]; } g_pace; +static int64_t g_game_frame_ns; + +static void note_game_frame_gap(void); static void pace_note_buffer(const void *buffer) { for (unsigned i = 0; i < g_pace.distinct && i < PACE_BUFFERS; i++) @@ -318,6 +327,16 @@ volatile int g_hide_shell; volatile int g_zero_copy; static int g_zero_copy_paused; +extern volatile int g_display_buffer_driver; +extern void droiddeck_on_overlay_planes(int planes); +static int g_overlay_planes_told = -1; + +static void tell_overlay_planes(void) { + const int planes = (g_zero_copy && g_display_buffer_driver) ? (sc_layer_overlay_affordable() ? 1 : 0) : -1; + if (planes == g_overlay_planes_told) return; + g_overlay_planes_told = planes; + droiddeck_on_overlay_planes(planes); +} static int g_zero_copy_fx_skip_said; volatile int g_ubwc = 1; @@ -689,6 +708,13 @@ const struct wl_buffer_interface dbuf_buffer_impl = { .destroy = dbuf_buffer_destroy_req, }; +static struct vkp_image *import_dmabuf(struct dmabuf_buffer *b) { + AHardwareBuffer *ahb = ahb_swapchain_display_buffer(b); + struct vkp_image *img = ahb ? vkp_image_from_ahb(ahb) : NULL; + return img ? img : vkp_image_from_dmabuf(b->fd[0], b->format, b->modifier, b->width, b->height, b->stride[0], + b->offset[0]); +} + static struct dmabuf_buffer *get_dmabuf(struct wl_resource *buffer) { if (buffer && wl_resource_instance_of(buffer, &wl_buffer_interface, &dbuf_buffer_impl)) return wl_resource_get_user_data(buffer); @@ -868,6 +894,12 @@ int droiddeck_hud_frame_times(float *out, int len, int64_t *total) { static uint64_t g_game_frames; extern void droiddeck_on_game_surface(const char *window, const char *gpu); extern void droiddeck_on_game_frame(void); +extern void droiddeck_on_content_rate(int fps); +static int64_t g_cadence_ns; +static int64_t g_cadence_frames; +static int g_content_fps; +static int g_framegen_layer_said; +static int g_framegen_layer; extern void droiddeck_on_game_program(int pid, const char *program); static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_resource *buffer) { @@ -888,6 +920,7 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res s->buf_w = w; s->buf_h = h; s->buf_alpha = wl_shm_buffer_get_format(shm) == WL_SHM_FORMAT_ARGB8888; + s->black_fill = 0; s->has_content = s->shm_img != NULL; g_stat_shm++; struct client_info *ci = client_info_of(wl_resource_get_client(s->resource)); @@ -932,6 +965,7 @@ static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resou s->buf_w = 1; s->buf_h = 1; s->buf_alpha = bgra[3] != 0xff; + s->black_fill = !bgra[0] && !bgra[1] && !bgra[2] && bgra[3] == 0xff; s->has_content = s->shm_img != NULL; } @@ -950,8 +984,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re wl_resource_add_destroy_listener(buffer, &s->dmabuf_destroy); } if (!b->img && !b->import_failed && b->n_planes >= 1) { - b->img = vkp_image_from_dmabuf(b->fd[0], b->format, b->modifier, b->width, b->height, - b->stride[0], b->offset[0]); + b->img = import_dmabuf(b); if (b->img && g_zero_copy) sc_layer_probe_dmabuf_fd(b->fd[0]); if (!b->img) { b->import_failed = 1; @@ -1019,7 +1052,25 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re } if (s == g_hud_surface) { g_hud_alive_ns = now_ns(); - if (!repeat) { g_hud_last_ns = g_hud_alive_ns; g_hud_fresh = 1; g_hud_new = 1; g_game_frames++; droiddeck_on_game_frame(); } + if (!repeat) { g_hud_last_ns = g_hud_alive_ns; g_hud_fresh = 1; g_hud_new = 1; g_game_frames++; note_game_frame_gap(); droiddeck_on_game_frame(); } + } +} + +static void note_game_frame_gap(void) { + const int64_t now = now_ns(); + if (g_game_frame_ns && g_refresh_ns > 0) { + const int64_t gap = (now - g_game_frame_ns + g_refresh_ns / 2) / g_refresh_ns; + g_pace.gaps[gap < 1 ? 0 : gap > 4 ? 3 : gap - 1]++; + } + if (g_game_frame_ns && now - g_game_frame_ns >= 1000000000LL) { g_cadence_ns = 0; g_cadence_frames = 0; } + g_game_frame_ns = now; + if (!g_cadence_ns) g_cadence_ns = now; + g_cadence_frames++; + if (now - g_cadence_ns >= 1000000000LL) { + g_content_fps = (int)((g_cadence_frames * 1000000000LL + (now - g_cadence_ns) / 2) / (now - g_cadence_ns)); + droiddeck_on_content_rate(g_content_fps); + g_cadence_ns = now; + g_cadence_frames = 0; } } @@ -1204,8 +1255,7 @@ static void cursor_publish_buffer(struct surface *s, struct wl_resource *buffer) } else if (db && db->n_planes >= 1 && db->width > 0 && db->height > 0 && (int64_t)db->width * db->height <= CURSOR_MAX_PX) { if (!db->img && !db->import_failed) { - db->img = vkp_image_from_dmabuf(db->fd[0], db->format, db->modifier, db->width, db->height, - db->stride[0], db->offset[0]); + db->img = import_dmabuf(db); if (!db->img) db->import_failed = 1; } if (!db->img) return; @@ -1213,8 +1263,9 @@ static void cursor_publish_buffer(struct surface *s, struct wl_resource *buffer) int r; do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR); if (vkp_image_readback(db->img, g_cursor_rb, CURSOR_MAX_PX) != 0) return; + const int row = vkp_image_width(db->img); cursor_publish_pixels((const uint8_t *)g_cursor_rb, db->width, db->height, - (size_t)db->width * 4, g_cursor_hx, g_cursor_hy); + (size_t)(row > db->width ? row : db->width) * 4, g_cursor_hx, g_cursor_hy); } else { return; } @@ -1884,6 +1935,57 @@ static void output_send_mode(struct wl_resource *r, int mhz) { mhz); } +#define PANEL_RATES_MAX 16 +extern void droiddeck_on_refresh_target(int refresh, int frame_rate); +static pthread_mutex_t g_panel_rates_lock = PTHREAD_MUTEX_INITIALIZER; +static int g_panel_rates[PANEL_RATES_MAX], g_panel_rate_count; +static atomic_int g_panel_rates_pending; +static struct wl_list g_refresh_clients; +static struct wl_resource *g_refresh_target_owner; + +static void refresh_send_rates(struct wl_resource *r) { + int rates[PANEL_RATES_MAX]; + pthread_mutex_lock(&g_panel_rates_lock); + const int count = g_panel_rate_count; + memcpy(rates, g_panel_rates, sizeof(rates)); + pthread_mutex_unlock(&g_panel_rates_lock); + for (int i = 0; i < count; i++) droiddeck_refresh_v1_send_rate(r, (uint32_t)rates[i]); + droiddeck_refresh_v1_send_done(r); +} + +static void refresh_notify_rates(void) { + struct wl_resource *r; + wl_resource_for_each(r, &g_refresh_clients) refresh_send_rates(r); +} + +static void refresh_resource_destroy(struct wl_resource *r) { + wl_list_remove(wl_resource_get_link(r)); + if (g_refresh_target_owner != r) return; + g_refresh_target_owner = NULL; + droiddeck_on_refresh_target(0, 0); +} + +static void refresh_destroy_req(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); } + +static void refresh_set_target(struct wl_client *c, struct wl_resource *r, uint32_t refresh, uint32_t frame_rate) { + if (!refresh && !frame_rate && g_refresh_target_owner && g_refresh_target_owner != r) return; + g_refresh_target_owner = refresh || frame_rate ? r : NULL; + droiddeck_on_refresh_target((int)refresh, (int)frame_rate); +} + +static const struct droiddeck_refresh_v1_interface refresh_impl = { + .destroy = refresh_destroy_req, + .set_target = refresh_set_target, +}; + +static void bind_refresh(struct wl_client *c, void *data, uint32_t ver, uint32_t id) { + struct wl_resource *r = wl_resource_create(c, &droiddeck_refresh_v1_interface, ver, id); + if (!r) { wl_client_post_no_memory(c); return; } + wl_resource_set_implementation(r, &refresh_impl, NULL, refresh_resource_destroy); + wl_list_insert(&g_refresh_clients, wl_resource_get_link(r)); + refresh_send_rates(r); +} + static void bind_output(struct wl_client *c, void *data, uint32_t ver, uint32_t id) { struct wl_resource *r = wl_resource_create(c, &wl_output_interface, ver, id); if (!r) { wl_client_post_no_memory(c); return; } @@ -2014,19 +2116,47 @@ static int on_frame_timer(void *data) { return 0; } +static int black_fill_below(const struct draw_list *dl, int n) { + for (int i = 0; i < n; i++) { + struct surface *s, *found = NULL; + wl_list_for_each(s, &g_surfaces, link) + if (s->shm_img == dl->d[i].img) { found = s; break; } + if (!found || !found->black_fill || dl->d[i].blend) return 0; + } + return 1; +} + static int layer_candidate(const struct draw_list *dl, int scene_w, int scene_h) { for (int i = dl->n - 1; i >= 0 && i >= dl->n - 2; i--) { const struct vkp_draw *d = &dl->d[i]; if (d->blend) continue; if (!vkp_image_is_dmabuf(d->img)) continue; - if (d->dx != 0 || d->dy != 0 || d->dw != scene_w || d->dh != scene_h) continue; - if (d->sx != 0 || d->sy != 0 || (int)d->sw != vkp_image_width(d->img) || - (int)d->sh != vkp_image_height(d->img)) continue; + if (d->sx < 0 || d->sy < 0 || d->sw < 1.0f || d->sh < 1.0f || + d->sx + d->sw >= vkp_image_width(d->img) + 1.0f || + d->sy + d->sh >= vkp_image_height(d->img) + 1.0f) continue; + if (d->dx == 0 && d->dy == 0 && d->dw == scene_w && d->dh == scene_h) return i; + if (d->dx < 0 || d->dy < 0 || d->dw <= 0 || d->dh <= 0 || d->dx + d->dw > scene_w || + d->dy + d->dh > scene_h || !black_fill_below(dl, i)) continue; return i; } return -1; } +static void note_copy_scene(const struct draw_list *dl, int scene_w, int scene_h, int pointer) { + static int said[6]; + const struct vkp_draw *t = dl->n > 0 ? &dl->d[dl->n - 1] : NULL; + const int now[6] = {dl->n, pointer, t ? t->dw : 0, t ? t->dh : 0, scene_w, scene_h}; + if (!memcmp(now, said, sizeof(said))) return; + memcpy(said, now, sizeof(said)); + if (pointer) + droiddeck_log("layer", "zero-copy: copy path while the pointer is drawn into the scene"); + else if (t) + droiddeck_log("layer", "zero-copy: copy path: no window fills the %dx%d scene on its own (%d surfaces, top one " + "%dx%d at %d,%d from %.2f,%.2f %.2fx%.2f of a %dx%d %s buffer%s)", scene_w, scene_h, dl->n, t->dw, t->dh, + t->dx, t->dy, t->sx, t->sy, t->sw, t->sh, vkp_image_width(t->img), vkp_image_height(t->img), + vkp_image_is_dmabuf(t->img) ? "GPU" : "memory", t->blend ? ", translucent" : ""); +} + static struct surface *surface_for_image(const struct vkp_image *img) { struct surface *s; wl_list_for_each(s, &g_surfaces, link) @@ -2066,17 +2196,28 @@ static struct surface *hdr_unimported_fullscreen(const struct draw_list *dl, int } static int is_hdr_surface(struct surface *s) { + const struct droiddeck_color *c = s ? droiddeck_color_of(s->resource) : NULL; + return c && (c->dataspace || c->convert); +} + +static int is_raw_hdr_surface(struct surface *s) { const struct droiddeck_color *c = s ? droiddeck_color_of(s->resource) : NULL; return c && c->dataspace; } +static int framegen_fits_layer(void) { + const int64_t rate = (int64_t)g_content_fps * (1 + vkp_framegen_extra_images()) * 1000; + return g_content_fps > 0 && + rate * 100 <= (int64_t)atomic_load(&g_output_refresh_mhz) * (g_framegen_layer ? 108 : 104); +} + static int hdr_plan(const struct draw_list *dl, int w, int h, int fx_on, int framegen, struct hdr_scene *hs) { memset(hs, 0, sizeof(*hs)); if (!droiddeck_color_hdr_open()) return 0; struct surface *un = hdr_unimported_fullscreen(dl, w, h); if (!un) { struct surface *lo = ahb_layer_only_candidate(w, h); - if (lo && is_hdr_surface(lo)) un = lo; + if (lo && is_raw_hdr_surface(lo)) un = lo; } if (un && g_zero_copy) { hs->color = droiddeck_color_of(un->resource); hs->who = un; return 3; } hs->hf.tonemap = !droiddeck_color_output(); @@ -2084,24 +2225,48 @@ static int hdr_plan(const struct draw_list *dl, int w, int h, int fx_on, int fra for (int i = 0; i < dl->n; i++) { struct surface *s = surface_for_image(dl->d[i].img); if (!is_hdr_surface(s)) continue; - hs->is_hdr[i] = 1; + const struct droiddeck_color *c = droiddeck_color_of(s->resource); + if (c->convert && hs->hf.convert && (hs->hf.convert->gain != c->gain || + memcmp(hs->hf.convert->to2020, c->to2020, sizeof(c->to2020)) != 0)) { + static int said; + if (!said) { + said = 1; + droiddeck_log("color", "two windows need different colour conversions in one frame: the upper one is " + "shown as SDR"); + } + continue; + } + hs->is_hdr[i] = c->convert ? 2 : 1; + if (c->convert) hs->hf.convert = c; hs->n_hdr++; - hs->color = droiddeck_color_of(s->resource); + hs->color = c; hs->who = s; } if (!hs->n_hdr) { free(hs->is_hdr); hs->is_hdr = NULL; return 0; } + if (hs->color->convert) { + static struct droiddeck_color composed; + composed = *hs->color; + composed.dataspace = DROIDDECK_ADATASPACE_BT2020_PQ; + composed.convert = 0; + hs->color = &composed; + } hs->hf.is_hdr = hs->is_hdr; hs->hf.color = hs->color; hs->hf.peak_nits = hs->color->max_cll > 0.0f ? hs->color->max_cll : hs->color->has_st2086 ? hs->color->max_lum : 1000.0f; - if (framegen) return 2; + if (framegen) { + if (!g_zero_copy || !framegen_fits_layer()) return 2; + hs->why = "frame generation is on"; + return 1; + } int li = g_zero_copy ? layer_candidate(dl, w, h) : -1; int over = li >= 0 ? dl->n - 1 - li : 0; - if (!hs->hf.tonemap && !fx_on && li >= 0 && hs->is_hdr[li] && + if (!hs->hf.tonemap && !hs->hf.convert && !fx_on && li >= 0 && hs->is_hdr[li] && (over == 0 || (over == 1 && sc_layer_overlay_affordable()))) return 0; hs->why = hs->hf.tonemap ? "HDR output is switched off in the drawer" : fx_on ? "screen effects are on" + : hs->hf.convert ? "its colours are converted to BT.2020 PQ" : !g_zero_copy ? "zero-copy presentation is off" : (li >= 0 && hs->is_hdr[li]) ? "a window is above the game and this display cannot compose a second layer" : "the HDR game is not one fullscreen window"; @@ -2174,8 +2339,7 @@ static void hdr_note_precedence(struct surface *hs, int fx_on, int framegen) { static void hdr_count_copied(const struct draw_list *dl, const char *reason) { for (int i = 0; i < dl->n; i++) { struct surface *s = surface_for_image(dl->d[i].img); - const struct droiddeck_color *c = s ? droiddeck_color_of(s->resource) : NULL; - if (!c || !c->dataspace) continue; + if (!is_hdr_surface(s)) continue; char name[160]; describe(s, name, sizeof(name)); droiddeck_color_frame_copied(name, reason); @@ -2317,6 +2481,8 @@ static void render_scene(void) { g_dirty_since_ns = 0; } g_dirty = 0; + if (g_rendered_tick_ns == g_tick_vsync_ns) g_tick_spare = 0; + g_scene_queues = 0; g_rendered_tick_ns = g_tick_vsync_ns; g_tick_held = 0; g_hud_fresh = 0; @@ -2378,7 +2544,13 @@ static void render_scene(void) { static int fell_back; vkp_apply_window_request(); sc_layer_hide_overlay(); - if (sc_layer_present_hdr_scene(dl.d, dl.n, &hs.hf, w, h, hs.color) == 0) { + const int generated = framegen ? sc_layer_present_generated(dl.d, dl.n, &hs.hf, w, h, 1, hs.color) : 0; + if (framegen) g_framegen_layer = generated >= 0; + if (generated > 0 && g_framegen_layer_said != 3) { + g_framegen_layer_said = 3; + droiddeck_log("framegen", "generated frames and the composed HDR picture go on the game's display layer"); + } + if (framegen ? generated >= 0 : sc_layer_present_hdr_scene(dl.d, dl.n, &hs.hf, w, h, hs.color) == 0) { rendered = vkp_base_black(w, h) == 0; if (fell_back) { fell_back = 0; droiddeck_log("color", "the composed picture is on the game's display layer again"); } } else { @@ -2404,13 +2576,16 @@ static void render_scene(void) { rendered = vkp_render(w, h, dl.d, dl.n) == 0; } else if (hdr_route == 0 || hdr_route == 3) { const int pass_on = fx_on || framegen; - int li = (g_zero_copy && !framegen && !bfi && !cardboard && !cursor_on) ? layer_candidate(&dl, w, h) : -1; + tell_overlay_planes(); + const int fg_layer = framegen && hdr_route == 0 && framegen_fits_layer(); + g_framegen_layer = fg_layer; + int li = (g_zero_copy && (!framegen || fg_layer) && !bfi && !cardboard && !cursor_on) ? layer_candidate(&dl, w, h) : -1; int over = li >= 0 ? dl.n - 1 - li : 0; const int fx_blocks = (li >= 0 && fx_on && over > 0); if (fx_blocks) { li = -1; over = 0; } const int ov_blocks = (li >= 0 && over > 0 && !fx_blocks && !sc_layer_overlay_affordable()); if (ov_blocks) { li = -1; over = 0; } - const int blocked = framegen ? 1 : bfi ? 4 : (fx_blocks ? 2 : (ov_blocks ? 3 : 0)); + const int blocked = (framegen && !fg_layer) ? 1 : bfi ? 4 : (fx_blocks ? 2 : (ov_blocks ? 3 : 0)); if (g_zero_copy && !cursor_on && blocked != g_zero_copy_paused) { g_zero_copy_paused = blocked; if (blocked == 1) @@ -2419,14 +2594,21 @@ static void render_scene(void) { droiddeck_log("effects", "zero-copy paused: a window above the game needs the compositor pass for the whole scene"); else if (blocked == 4) droiddeck_log("bfi", "zero-copy paused: black frame insertion needs the compositor pass"); - else if (blocked == 3) - droiddeck_log("layer", "zero-copy paused: a window above the game would need a second display layer, " - "which this display cannot compose in hardware - whole scene on the copy path"); + else if (blocked == 3) { + const struct vkp_draw *top = &dl.d[dl.n - 1]; + struct surface *ts = surface_for_image(top->img); + droiddeck_log("layer", "zero-copy paused: a window above the game (%dx%d at %d,%d%s, %s) would need a second " + "display layer, which this display cannot compose in hardware - whole scene on the copy path", + top->dw, top->dh, top->dx, top->dy, top->blend ? ", translucent" : "", + ts ? client_name(wl_resource_get_client(ts->resource)) : "no client surface"); + } else droiddeck_log("effects", "zero-copy resumed: the game is back on its own display layer"); } struct surface *ls = li >= 0 ? surface_for_image(dl.d[li].img) : NULL; + const struct vkp_draw *ld = li >= 0 ? &dl.d[li] : NULL; if (li < 0) ls = layer_only; + if (g_zero_copy && li < 0 && !ls && !blocked && !cardboard) note_copy_scene(&dl, w, h, cursor_on); if (cardboard) ls = NULL; if (cursor_on) ls = NULL; if (bfi) ls = NULL; @@ -2439,11 +2621,23 @@ static void render_scene(void) { if (li >= 0 || ls) { vkp_apply_window_request(); int r = -1; - if (!(fx_on && li >= 0) && ls && ls->dmabuf_buf && ahb_swapchain_has_ahb(ls->dmabuf_buf)) - r = ahb_swapchain_present(ls->dmabuf_buf, ls, w, h); - if (r != 0 && li >= 0) + const int fg_pass = framegen && fx_on && li >= 0; + const int generated = (framegen && li >= 0) + ? sc_layer_present_generated(&dl.d[li], 1, NULL, w, h, fg_pass, + ls ? droiddeck_surface_color(ls) : NULL) : 0; + if (generated > 0 && g_framegen_layer_said != 1 + fg_pass) { + g_framegen_layer_said = 1 + fg_pass; + droiddeck_log("framegen", fg_pass + ? "generated frames and the game's frames go on the game's display layer straight from the screen effects pass" + : "generated frames go on the game's display layer between the game's own frames"); + } + if (fg_pass) + r = generated >= 0 ? 0 : -1; + else if (generated >= 0 && !(fx_on && li >= 0) && ls && ls->dmabuf_buf && ahb_swapchain_has_ahb(ls->dmabuf_buf)) + r = ahb_swapchain_present(ls->dmabuf_buf, ls, w, h, ld); + if (!fg_pass && generated >= 0 && r != 0 && li >= 0) r = fx_on ? sc_layer_present_pass(&dl.d[li], 1, w, h) - : sc_layer_present(dl.d[li].img, w, h, ls ? droiddeck_surface_color(ls) : NULL); + : sc_layer_present(dl.d[li].img, w, h, ld, ls ? droiddeck_surface_color(ls) : NULL); if (r == 0) { if (ls) ls->drawn = 1; int go[8], ov = 0; @@ -2457,8 +2651,10 @@ static void render_scene(void) { hdr_copy = "the overlay layer refused the window above it"; } else { rendered = vkp_base_black(w, h) == 0; + g_scene_queues = sc_layer_queues(); } } else { + sc_layer_hide(); rendered = vkp_render(w, h, dl.d, dl.n) == 0; copy = 1; hdr_copy = "its display layer was unavailable this frame"; @@ -2518,8 +2714,12 @@ static int commit_renders_on(void) { !g_bfi_running; } +static int tick_takes_scene(void) { + return g_rendered_tick_ns != g_tick_vsync_ns || (g_tick_spare && g_scene_queues); +} + static int render_on_commit(void) { - return commit_renders_on() && !g_render_idle && g_rendered_tick_ns != g_tick_vsync_ns; + return commit_renders_on() && !g_render_idle && tick_takes_scene(); } static void schedule_render(void) { @@ -2546,7 +2746,7 @@ static int scene_waits_for_game(int64_t now) { static void on_commit_idle(void *data) { g_render_idle = NULL; - if (!g_dirty || !commit_renders_on() || g_rendered_tick_ns == g_tick_vsync_ns || scene_waits_for_game(now_ns())) return; + if (!g_dirty || !commit_renders_on() || !tick_takes_scene() || scene_waits_for_game(now_ns())) return; g_pace.commit_renders++; render_scene(); } @@ -2621,6 +2821,7 @@ static void on_vsync(int64_t frame_time_ns) { if (d > 3000000LL && d < 40000000LL) g_refresh_ns = (g_refresh_ns * 7 + d) / 8; } g_last_vsync_ns = now; + g_tick_spare = g_rendered_tick_ns != g_tick_vsync_ns; g_tick_vsync_ns = frame_time_ns; int tick_change = 0; if (vkp_apply_window_request()) tick_change = 1; @@ -3843,6 +4044,10 @@ static int on_input_readable(int fd, uint32_t mask, void *data) { output_notify_mode(); wl_display_flush_clients(g_display); } + if (atomic_exchange(&g_panel_rates_pending, 0)) { + refresh_notify_rates(); + wl_display_flush_clients(g_display); + } if (vsync) on_vsync(vsync_ns); return 0; } @@ -3892,6 +4097,23 @@ void droiddeck_wayland_output_resized(void) { (void)n; } +void droiddeck_wayland_set_panel_rates(const int *rates, int count) { + if (count > PANEL_RATES_MAX) count = PANEL_RATES_MAX; + pthread_mutex_lock(&g_panel_rates_lock); + const int same = count == g_panel_rate_count && !memcmp(rates, g_panel_rates, (size_t)count * sizeof(int)); + if (!same) { + memcpy(g_panel_rates, rates, (size_t)count * sizeof(int)); + g_panel_rate_count = count; + } + pthread_mutex_unlock(&g_panel_rates_lock); + if (same || g_input_pipe[1] < 0) return; + atomic_store(&g_panel_rates_pending, 1); + struct input_msg m = { 10, 0, 0, 0, 0 }; + ssize_t n; + do { n = write(g_input_pipe[1], &m, sizeof(m)); } while (n < 0 && errno == EINTR); + (void)n; +} + void droiddeck_wayland_set_output_refresh_rate(int mhz) { if (mhz <= 0) mhz = 60000; if (atomic_exchange(&g_output_refresh_mhz, mhz) == mhz || g_input_pipe[1] < 0) return; @@ -3974,12 +4196,15 @@ static int on_stats_timer(void *data) { struct vkp_perf vp; vkp_perf_take(&vp); const unsigned drops = sc_layer_drops_take(); + unsigned aimed_next, aimed_later, aimed_even; + sc_layer_aim_take(&aimed_next, &aimed_later, &aimed_even); #define PERF_MS(sum, n) ((n) ? (double)(sum) / 1e6 / (double)(n) : 0.0) if (g_perf.scenes || vp.presents || g_perf.releases || drops) droiddeck_log("perf", "last 10 s: %u ticks, %u scenes, %u on screen (copy %u, zero-copy %u, layer copy %u) | " "render_scene %.2f/%.2f ms | base %u black kept, %u presented | acquire %.2f/%.2f ms | " "present %.2f/%.2f ms (%u) | fence wait %.2f/%.2f ms (%u, %u GPU release waits) | " - "release %.2f/%.2f ms (%u, %u held) | %u pool drops", + "release %.2f/%.2f ms (%u, %u held) | %u pool drops | layer frames timed for the next refresh %u, " + "the one after %u, held to an even step %u", g_perf.ticks, g_perf.scenes, g_stat_frames, g_perf.copy_scenes, zero_copy, layer_frames, PERF_MS(g_perf.scene_ns, g_perf.scenes), (double)g_perf.scene_max_ns / 1e6, vp.base_kept, vp.base_presents, @@ -3987,7 +4212,7 @@ static int on_stats_timer(void *data) { PERF_MS(vp.present_ns, vp.presents), (double)vp.present_max_ns / 1e6, vp.presents, PERF_MS(vp.wait_ns, vp.waits), (double)vp.wait_max_ns / 1e6, vp.waits, vp.gpu_release_waits, PERF_MS(g_perf.release_ns, g_perf.releases), (double)g_perf.release_max_ns / 1e6, - g_perf.releases, g_perf.releases_held, drops); + g_perf.releases, g_perf.releases_held, drops, aimed_next, aimed_later, aimed_even); #undef PERF_MS memset(&g_perf, 0, sizeof(g_perf)); } @@ -3997,12 +4222,12 @@ static int on_stats_timer(void *data) { droiddeck_log("pacing", "last 10 s: tick reaches compositor %.2f/%.2f ms late (%u ticks, %u over 2 ms) | " "new frame waits %.2f/%.2f ms to be drawn (%u scenes, %u on arrival) | %llu game frames, %u re-attached after an " "empty attach, %u empty attaches, %u distinct buffers | feedback %u shown, %u replaced before drawing, " - "%u not drawn", + "%u not drawn | game frames arrived 1/2/3/4+ refreshes apart %u/%u/%u/%u", g_pace.ticks ? (double)g_pace.tick_late_ns / 1e6 / g_pace.ticks : 0.0, (double)g_pace.tick_late_max_ns / 1e6, g_pace.ticks, g_pace.ticks_late_2ms, g_pace.renders ? (double)g_pace.wait_ns / 1e6 / g_pace.renders : 0.0, (double)g_pace.wait_max_ns / 1e6, g_pace.renders, g_pace.commit_renders, (unsigned long long)game, g_pace.reattaches, g_pace.null_attaches, g_pace.distinct, - g_pace.presented, g_pace.replaced, g_pace.undrawn); + g_pace.presented, g_pace.replaced, g_pace.undrawn, g_pace.gaps[0], g_pace.gaps[1], g_pace.gaps[2], g_pace.gaps[3]); } if (g_bfi_stats.lit || g_bfi_stats.dark || g_bfi_stats.failed) { droiddeck_log("bfi", "last 10 s: %u pictures, %u black refreshes, %u black refreshes not presented", @@ -4028,6 +4253,12 @@ static int on_stats_timer(void *data) { "draw - expect a black picture (main device %u:%u)", ci->name, (unsigned)major(g_main_device), (unsigned)minor(g_main_device)); } + if (g_content_fps > 0 && now_ns() - g_game_frame_ns >= 2000000000LL) { + g_content_fps = 0; + g_cadence_ns = 0; + g_cadence_frames = 0; + droiddeck_on_content_rate(0); + } wl_event_source_timer_update(g_stats_timer, 10000); return 0; } @@ -4106,6 +4337,7 @@ int droiddeck_wayland_run(void) { wl_list_init(&g_surfaces); wl_list_init(&g_toplevels); wl_list_init(&g_outputs); + wl_list_init(&g_refresh_clients); wl_list_init(&g_constraints); wl_list_init(&g_relative_pointers); open_session_log(); @@ -4143,6 +4375,7 @@ int droiddeck_wayland_run(void) { wl_display_init_shm(display); wl_global_create(display, &wl_output_interface, 4, NULL, bind_output); + wl_global_create(display, &droiddeck_refresh_v1_interface, 1, NULL, bind_refresh); wl_global_create(display, &xdg_wm_base_interface, 1, NULL, bind_xdg_wm_base); wl_global_create(display, &zwp_linux_dmabuf_v1_interface, 4, NULL, bind_dmabuf); droiddeck_android_wlegl_init(display); @@ -4153,6 +4386,7 @@ int droiddeck_wayland_run(void) { wl_global_create(display, &zwp_relative_pointer_manager_v1_interface, 1, NULL, bind_relative_pointer_manager); droiddeck_ext_init(display); ahb_swapchain_init(display); + display_buffers_init(display); droiddeck_color_init(display); diff --git a/app/src/main/cpp/waylandcomp/src/compositor_internal.h b/app/src/main/cpp/waylandcomp/src/compositor_internal.h index c70f9dd193..b17329c124 100644 --- a/app/src/main/cpp/waylandcomp/src/compositor_internal.h +++ b/app/src/main/cpp/waylandcomp/src/compositor_internal.h @@ -20,6 +20,7 @@ #define DRM_XBGR8888 FOURCC('X', 'B', '2', '4') #define MOD_LINEAR VKP_MOD_LINEAR #define MOD_INVALID VKP_MOD_INVALID +#define MOD_QCOM_COMPRESSED VKP_MOD_QCOM_COMPRESSED #define MAX_PLANES 4 struct dmabuf_params { diff --git a/app/src/main/cpp/waylandcomp/src/display_buffers.c b/app/src/main/cpp/waylandcomp/src/display_buffers.c new file mode 100644 index 0000000000..99f6993a56 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/display_buffers.c @@ -0,0 +1,343 @@ +#define _GNU_SOURCE +#include "display_buffers.h" +#include "ahb_swapchain.h" +#include "compositor_internal.h" +#include "droiddeck_color.h" +#include "droiddeck_ext.h" +#include "sc_layer.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define DISPLAY_BUFFERS_SOCKET "droiddeck-display-buffers" +#define DISPLAY_BUFFERS_MAGIC 0x42444444u +#define DISPLAY_BUFFERS_VERSION 1u +#define DISPLAY_BUFFERS_ALLOC 1u +#define DISPLAY_BUFFERS_FREE 2u +#define DISPLAY_BUFFERS_MAX_SIDE 16384u +#define DISPLAY_BUFFERS_MAX_PER_CLIENT 256 +#define DISPLAY_BUFFERS_PROBE_W 1280u +#define DISPLAY_BUFFERS_PROBE_H 720u +#define ALIGN_UP(v, a) (((v) + (a) - 1) / (a) * (a)) + +extern volatile int g_zero_copy; +volatile int g_display_buffer_driver; + +struct display_buffers_request { + uint32_t magic, version, op, width, height, format, stride, offset; + uint64_t size, id, modifier; +}; + +struct display_buffers_reply { + uint32_t magic, status; + uint64_t id, size; +}; + +struct peer { + int fd; + pid_t pid; + int count; + int logged_w, logged_h; + uint32_t logged_format; + struct wl_event_source *src; +}; + +struct entry { + uint64_t id; + dev_t dev; + ino_t ino; + AHardwareBuffer *ahb; + uint32_t format, stride, width, height; + uint64_t modifier; + struct peer *peer; + struct wl_list link; +}; + +static struct wl_list g_entries; +static struct wl_event_loop *g_loop; +static uint64_t g_next_id = 1; +static int g_refused_logged; +static int g_ubwc_promised; +static int g_ubwc_probed[2]; + +static uint32_t ahb_format_of(uint32_t drm, uint64_t modifier) { + switch (drm) { + case DRM_ABGR8888: case DRM_XBGR8888: return AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM; + case DRM_ARGB8888: case DRM_XRGB8888: return modifier == MOD_QCOM_COMPRESSED ? AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM : 0; + case FOURCC('A', 'B', '3', '0'): case FOURCC('X', 'B', '3', '0'): return AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM; + default: return 0; + } +} + +static uint64_t ubwc_meta_size(uint32_t w, uint32_t h) { + return ALIGN_UP((uint64_t)ALIGN_UP((w + 15) / 16, 64) * ALIGN_UP((h + 3) / 4, 16), 4096); +} + +static uint64_t ubwc_size(uint32_t w, uint32_t h, uint32_t stride) { + return ubwc_meta_size(w, h) + ALIGN_UP((uint64_t)stride * ALIGN_UP(h, 16), 4096); +} + +static void entry_free(struct entry *e) { + wl_list_remove(&e->link); + e->peer->count--; + AHardwareBuffer_release(e->ahb); + free(e); +} + +static AHardwareBuffer *allocate_ubwc(uint32_t w, uint32_t h, uint32_t format, uint32_t stride, int *fd, uint64_t *size) { + const uint64_t tiers[2] = {SC_LAYER_AHB_USAGE_VENDOR_UBWC, 0}; + for (int i = 0; i < 2; i++) { + AHardwareBuffer_Desc d = { + .width = w, .height = h, .layers = 1, .format = format, + .usage = AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | + AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY | tiers[i]}; + AHardwareBuffer *ahb = NULL; + if (AHardwareBuffer_allocate(&d, &ahb) != 0 || !ahb) continue; + AHardwareBuffer_Desc got; + AHardwareBuffer_describe(ahb, &got); + const uint64_t need = ubwc_size(w, h, got.stride * 4); + *fd = !stride || (uint64_t)got.stride * 4 == stride ? sc_layer_ahb_fd(ahb, need) : -1; + if (*fd >= 0 && (uint64_t)lseek(*fd, 0, SEEK_END) == need) { *size = need; return ahb; } + *fd = -1; + AHardwareBuffer_release(ahb); + } + return NULL; +} + +static uint64_t gralloc_bytes(uint32_t format, uint64_t usage, uint32_t *stride) { + AHardwareBuffer_Desc d = { + .width = DISPLAY_BUFFERS_PROBE_W, .height = DISPLAY_BUFFERS_PROBE_H, .layers = 1, .format = format, + .usage = AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | + AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY | usage}; + AHardwareBuffer *ahb = NULL; + if (AHardwareBuffer_allocate(&d, &ahb) != 0 || !ahb) return 0; + AHardwareBuffer_describe(ahb, &d); + const int fd = sc_layer_ahb_fd(ahb, 1); + const off_t bytes = fd >= 0 ? lseek(fd, 0, SEEK_END) : 0; + if (fd >= 0) lseek(fd, 0, SEEK_SET); + AHardwareBuffer_release(ahb); + *stride = d.stride; + return bytes > 0 ? (uint64_t)bytes : 0; +} + +static int ubwc_probe(uint32_t format) { + int *state = &g_ubwc_probed[format == AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM ? 0 : 1]; + if (*state) return *state > 0; + uint32_t stride = 0, linear_stride = 0; + const uint64_t flagged = gralloc_bytes(format, SC_LAYER_AHB_USAGE_VENDOR_UBWC, &stride); + const uint64_t plain = gralloc_bytes(format, 0, &stride); + const uint64_t linear = gralloc_bytes(format, AHARDWAREBUFFER_USAGE_CPU_READ_RARELY, &linear_stride); + const uint64_t need = ubwc_size(DISPLAY_BUFFERS_PROBE_W, DISPLAY_BUFFERS_PROBE_H, stride * 4); + *state = stride && linear != need && (flagged == need || plain == need) ? 1 : -1; + droiddeck_log("layer", "display buffers: gralloc %s buffers %s (%ux%u: the layout takes %llu bytes; gralloc gives %llu " + "asked for UBWC, %llu unasked, %llu linear)", droiddeck_ahb_format_name(format), + *state > 0 ? "use the UBWC layout the drivers render to: compressed frames can go on the display layer" + : "do not match the UBWC layout the drivers render to: compressed frames are not offered", + DISPLAY_BUFFERS_PROBE_W, DISPLAY_BUFFERS_PROBE_H, (unsigned long long)need, (unsigned long long)flagged, + (unsigned long long)plain, (unsigned long long)linear); + return *state > 0; +} + +int display_buffers_offer_ubwc(uint32_t drm) { + const uint32_t format = ahb_format_of(drm, MOD_QCOM_COMPRESSED); + if (!g_loop || !g_zero_copy || !g_ubwc || !g_display_buffer_driver || !format || !ubwc_probe(format)) return 0; + g_ubwc_promised = 1; + return 1; +} + +void display_buffers_withdraw_ubwc(void) { g_ubwc_promised = 0; } + +static AHardwareBuffer *allocate(const struct display_buffers_request *q, uint32_t format, int *fd) { + const uint32_t rows = (uint32_t)((q->size + q->stride - 1) / q->stride); + const uint32_t dims[2][2] = {{q->width, q->height}, {q->stride / 4, rows}}; + for (int i = 0; i < 2; i++) { + AHardwareBuffer_Desc d = { + .width = dims[i][0], .height = dims[i][1], .layers = 1, .format = format, + .usage = AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | + AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY | AHARDWAREBUFFER_USAGE_CPU_READ_RARELY}; + AHardwareBuffer *ahb = NULL; + if (i && dims[1][0] == dims[0][0] && dims[1][1] == dims[0][1]) break; + if (AHardwareBuffer_allocate(&d, &ahb) != 0 || !ahb) continue; + AHardwareBuffer_Desc got; + AHardwareBuffer_describe(ahb, &got); + *fd = (uint64_t)got.stride * 4 == q->stride ? sc_layer_ahb_fd(ahb, q->size) : -1; + if (*fd >= 0) return ahb; + AHardwareBuffer_release(ahb); + } + return NULL; +} + +static int reply(struct peer *p, const struct display_buffers_reply *r, int fd) { + char control[CMSG_SPACE(sizeof(int))] = {0}; + struct iovec iov = {.iov_base = (void *)r, .iov_len = sizeof(*r)}; + struct msghdr msg = {.msg_iov = &iov, .msg_iovlen = 1}; + if (fd >= 0) { + msg.msg_control = control; + msg.msg_controllen = sizeof(control); + struct cmsghdr *c = CMSG_FIRSTHDR(&msg); + c->cmsg_level = SOL_SOCKET; + c->cmsg_type = SCM_RIGHTS; + c->cmsg_len = CMSG_LEN(sizeof(int)); + memcpy(CMSG_DATA(c), &fd, sizeof(int)); + } + ssize_t n; + do { n = sendmsg(p->fd, &msg, MSG_NOSIGNAL); } while (n < 0 && errno == EINTR); + return n == (ssize_t)sizeof(*r) ? 0 : -1; +} + +static void handle_alloc(struct peer *p, const struct display_buffers_request *q) { + struct display_buffers_reply r = {.magic = DISPLAY_BUFFERS_MAGIC, .status = 1}; + const int compressed = q->modifier == MOD_QCOM_COMPRESSED; + const uint32_t format = compressed || q->modifier == MOD_LINEAR ? ahb_format_of(q->format, q->modifier) : 0; + struct entry *e = NULL; + AHardwareBuffer *ahb = NULL; + struct stat st; + uint64_t need = 0; + int fd = -1; + const int sized = format && q->width && q->height && q->width <= DISPLAY_BUFFERS_MAX_SIDE && + q->height <= DISPLAY_BUFFERS_MAX_SIDE && q->stride % 4 == 0 && q->stride / 4 >= q->width && + q->stride / 4 <= DISPLAY_BUFFERS_MAX_SIDE; + const int sane = !sized ? 0 + : compressed ? q->offset == ubwc_meta_size(q->width, q->height) && + q->size == ubwc_size(q->width, q->height, q->stride) + : q->offset == 0 && q->size >= (uint64_t)q->stride * q->height && + q->size <= (uint64_t)q->stride * DISPLAY_BUFFERS_MAX_SIDE; + const int wanted = compressed ? g_ubwc_promised : g_zero_copy; + if (sane && wanted && ahb_swapchain_advertised() && p->count < DISPLAY_BUFFERS_MAX_PER_CLIENT) + ahb = compressed ? allocate_ubwc(q->width, q->height, format, q->stride, &fd, &need) : allocate(q, format, &fd); + if (ahb && fstat(fd, &st) == 0) e = calloc(1, sizeof(*e)); + if (e) { + e->id = r.id = g_next_id++; + e->dev = st.st_dev; e->ino = st.st_ino; + e->ahb = ahb; + e->format = format; e->stride = q->stride; + e->width = q->width; e->height = q->height; + e->modifier = q->modifier; + e->peer = p; + p->count++; + wl_list_insert(&g_entries, &e->link); + r.status = 0; + r.size = (uint64_t)lseek(fd, 0, SEEK_END); + lseek(fd, 0, SEEK_SET); + if (p->logged_w != (int)q->width || p->logged_h != (int)q->height || p->logged_format != q->format) { + AHardwareBuffer_Desc got; + AHardwareBuffer_describe(ahb, &got); + p->logged_w = (int)q->width; p->logged_h = (int)q->height; p->logged_format = q->format; + droiddeck_log("layer", "display buffers: pid %d renders %ux%u %c%c%c%c %s straight into gralloc buffers " + "(%s %ux%u, stride %u px, %llu bytes for the %llu it asked for)", (int)p->pid, q->width, q->height, + q->format & 0xff, (q->format >> 8) & 0xff, (q->format >> 16) & 0xff, (q->format >> 24) & 0xff, + compressed ? "UBWC" : "linear", droiddeck_ahb_format_name(format), got.width, got.height, + got.stride, (unsigned long long)r.size, (unsigned long long)q->size); + } + } else { + if (ahb) AHardwareBuffer_release(ahb); + fd = -1; + if (sized && wanted && (compressed || !g_refused_logged)) { + g_refused_logged = 1; + droiddeck_log(compressed ? "error" : "layer", "display buffers: no gralloc buffer matches pid %d's %ux%u " + "%c%c%c%c %s layout (stride %u bytes, pixels at %u, %llu bytes; gralloc's layout has pixels at " + "%llu, %llu bytes): %s", (int)p->pid, q->width, q->height, + q->format & 0xff, (q->format >> 8) & 0xff, (q->format >> 16) & 0xff, (q->format >> 24) & 0xff, + compressed ? "UBWC" : "linear", q->stride, q->offset, (unsigned long long)q->size, + (unsigned long long)(compressed ? ubwc_meta_size(q->width, q->height) : 0), + (unsigned long long)(compressed ? ubwc_size(q->width, q->height, q->stride) : q->size), + compressed ? "its compressed frames cannot be shown" : "its frames keep the copy path"); + } + } + if (reply(p, &r, fd) != 0 && e) entry_free(e); +} + +static void peer_gone(struct peer *p) { + struct entry *e, *tmp; + wl_list_for_each_safe(e, tmp, &g_entries, link) + if (e->peer == p) entry_free(e); + wl_event_source_remove(p->src); + close(p->fd); + free(p); +} + +static int on_peer(int fd, uint32_t mask, void *data) { + struct peer *p = data; + for (;;) { + struct display_buffers_request q; + ssize_t n = recv(fd, &q, sizeof(q), MSG_DONTWAIT); + if (n < 0 && errno == EINTR) continue; + if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) return 0; + if (n != (ssize_t)sizeof(q) || q.magic != DISPLAY_BUFFERS_MAGIC || q.version != DISPLAY_BUFFERS_VERSION) break; + if (q.op == DISPLAY_BUFFERS_ALLOC) { + handle_alloc(p, &q); + } else if (q.op == DISPLAY_BUFFERS_FREE) { + struct entry *e, *tmp; + wl_list_for_each_safe(e, tmp, &g_entries, link) + if (e->peer == p && e->id == q.id) entry_free(e); + } else { + break; + } + } + peer_gone(p); + return 0; +} + +static int on_listen(int fd, uint32_t mask, void *data) { + int c = accept4(fd, NULL, NULL, SOCK_CLOEXEC | SOCK_NONBLOCK); + if (c < 0) return 0; + struct peer *p = calloc(1, sizeof(*p)); + if (!p) { close(c); return 0; } + struct ucred cred = {0}; + socklen_t len = sizeof(cred); + if (getsockopt(c, SOL_SOCKET, SO_PEERCRED, &cred, &len) == 0) p->pid = cred.pid; + p->fd = c; + p->src = wl_event_loop_add_fd(g_loop, c, WL_EVENT_READABLE, on_peer, p); + if (!p->src) { close(c); free(p); } + return 0; +} + +void display_buffers_match(struct wl_client *c, struct wl_resource *buffer, struct dmabuf_buffer *b) { + struct stat st; + struct entry *e; + if (!g_loop || wl_list_empty(&g_entries) || b->n_planes != 1 || b->offset[0] != 0 || fstat(b->fd[0], &st) != 0) return; + wl_list_for_each(e, &g_entries, link) { + if (e->dev != st.st_dev || e->ino != st.st_ino) continue; + AHardwareBuffer_Desc d; + AHardwareBuffer_describe(e->ahb, &d); + const int compressed = e->modifier == MOD_QCOM_COMPRESSED; + const int laid_out = compressed ? b->modifier == MOD_QCOM_COMPRESSED && (uint32_t)b->width == e->width && + (uint32_t)b->height == e->height + : (b->modifier == MOD_LINEAR || b->modifier == MOD_INVALID) && + e->stride == b->stride[0]; + if (laid_out && e->format == ahb_format_of(b->format, e->modifier) && b->width > 0 && b->height > 0 && + (uint32_t)b->width <= d.width && (uint32_t)b->height <= d.height) + ahb_swapchain_adopt(c, buffer, b, e->ahb, e->modifier); + return; + } +} + +void display_buffers_init(struct wl_display *display) { + wl_list_init(&g_entries); + const char *dir = getenv("XDG_RUNTIME_DIR"); + struct sockaddr_un addr = {.sun_family = AF_UNIX}; + if (!ahb_swapchain_advertised() || !dir) return; + if (snprintf(addr.sun_path, sizeof(addr.sun_path), "%s/" DISPLAY_BUFFERS_SOCKET, dir) >= (int)sizeof(addr.sun_path)) { + droiddeck_log("layer", "display buffers: %s is too long for a socket path, not offered", dir); + return; + } + int fd = socket(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC | SOCK_NONBLOCK, 0); + if (fd < 0) return; + unlink(addr.sun_path); + struct wl_event_loop *loop = wl_display_get_event_loop(display); + if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0 || listen(fd, 16) != 0 || + !wl_event_loop_add_fd(loop, fd, WL_EVENT_READABLE, on_listen, NULL)) { + droiddeck_log("layer", "display buffers: socket %s failed (%s), not offered", addr.sun_path, strerror(errno)); + close(fd); + return; + } + g_loop = loop; + droiddeck_log("layer", "display buffers: offered on %s (programs whose driver asks render into gralloc buffers while " + "zero-copy is on)", addr.sun_path); +} diff --git a/app/src/main/cpp/waylandcomp/src/display_buffers.h b/app/src/main/cpp/waylandcomp/src/display_buffers.h new file mode 100644 index 0000000000..4943be521e --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/display_buffers.h @@ -0,0 +1,12 @@ +#ifndef DISPLAY_BUFFERS_H +#define DISPLAY_BUFFERS_H +#include + +struct dmabuf_buffer; + +void display_buffers_init(struct wl_display *display); +int display_buffers_offer_ubwc(uint32_t drm); +void display_buffers_withdraw_ubwc(void); +void display_buffers_match(struct wl_client *c, struct wl_resource *buffer, struct dmabuf_buffer *b); + +#endif diff --git a/app/src/main/cpp/waylandcomp/src/droiddeck_color.h b/app/src/main/cpp/waylandcomp/src/droiddeck_color.h index a578301ae5..8809b7ed63 100644 --- a/app/src/main/cpp/waylandcomp/src/droiddeck_color.h +++ b/app/src/main/cpp/waylandcomp/src/droiddeck_color.h @@ -16,6 +16,9 @@ struct droiddeck_color { float max_lum, min_lum; int has_cta861; float max_cll, max_fall; + int convert; + float to2020[9]; + float gain; char text[256]; }; diff --git a/app/src/main/cpp/waylandcomp/src/hdr_compose.c b/app/src/main/cpp/waylandcomp/src/hdr_compose.c index 01d8be6f66..8cedd51b55 100644 --- a/app/src/main/cpp/waylandcomp/src/hdr_compose.c +++ b/app/src/main/cpp/waylandcomp/src/hdr_compose.c @@ -12,7 +12,7 @@ #define MIXED_FORMAT VK_FORMAT_A2B10G10R10_UNORM_PACK32 -struct pc_encode { float ndc[4]; float params[4]; float rects[HDRC_MAX_RECTS][4]; }; +struct pc_encode { float ndc[4]; float params[4]; uint32_t rects[HDRC_MAX_RECTS][2]; float conv[3][4]; }; static VkDevice g_dev; static int g_ready; @@ -266,7 +266,16 @@ int hdrc_encode(VkCommandBuffer cmd, VkImage mixed, VkImage out, VkFormat out_fm pc.params[1] = p->peak_nits > 0.0f ? p->peak_nits : 1000.0f; pc.params[2] = p->mode == HDRC_OUT_SDR ? 1.0f : 0.0f; pc.params[3] = (float)count + 16.0f * (float)mask; - for (int i = 0; i < count; i++) memcpy(pc.rects[i], p->rects[i], sizeof(pc.rects[i])); + for (int i = 0; i < count; i++) { + uint32_t v[4]; + for (int k = 0; k < 4; k++) v[k] = p->rects[i][k] <= 0.0f ? 0u : p->rects[i][k] >= 65535.0f ? 65535u : (uint32_t)p->rects[i][k]; + pc.rects[i][0] = v[0] | v[1] << 16; + pc.rects[i][1] = v[2] | v[3] << 16; + } + for (int k = 0; k < 3; k++) memcpy(pc.conv[k], &p->conv[3 * k], 3 * sizeof(float)); + pc.conv[0][3] = (float)(p->conv_mask & mask); + pc.conv[1][3] = p->conv_linear ? 1.0f : 0.0f; + pc.conv[2][3] = p->conv_gain; VkRenderPassBeginInfo rpi = {.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, .renderPass = g_out[slot].rp, .framebuffer = fb, .renderArea = {{0, 0}, {(uint32_t)w, (uint32_t)h}}}; diff --git a/app/src/main/cpp/waylandcomp/src/hdr_compose.h b/app/src/main/cpp/waylandcomp/src/hdr_compose.h index 5a37d42ad8..e49f575a3e 100644 --- a/app/src/main/cpp/waylandcomp/src/hdr_compose.h +++ b/app/src/main/cpp/waylandcomp/src/hdr_compose.h @@ -14,6 +14,10 @@ struct hdrc_params { int count; unsigned hdr_mask; float rects[HDRC_MAX_RECTS][4]; + unsigned conv_mask; + int conv_linear; + float conv_gain; + float conv[9]; }; void hdrc_bind_device(VkDevice dev, const VkPhysicalDeviceMemoryProperties *memprops); diff --git a/app/src/main/cpp/waylandcomp/src/hdr_encode.frag b/app/src/main/cpp/waylandcomp/src/hdr_encode.frag index db3ea8bcaf..1900bc4b9e 100644 --- a/app/src/main/cpp/waylandcomp/src/hdr_encode.frag +++ b/app/src/main/cpp/waylandcomp/src/hdr_encode.frag @@ -6,7 +6,8 @@ layout(binding = 0) uniform sampler2D Mixed; layout(push_constant) uniform PC { vec4 ndc; vec4 params; - vec4 rects[6]; + uvec2 rects[6]; + vec4 conv[3]; } pc; layout(location = 0) in vec2 fragTexCoord; @@ -55,28 +56,38 @@ float toneCurve(float x, float peak) { return knee + (1.0 - knee) * (1.0 - exp(-(x - knee) / rate)); } -bool isHdrPixel(vec2 p) { - float packed = pc.params.w; - float count = mod(packed, 16.0); - float mask = floor(packed / 16.0); +int rectAt(vec2 p) { + float count = mod(pc.params.w, 16.0); for (int i = 0; i < 6; i++) { if (float(i) >= count - 0.5) break; - vec4 r = pc.rects[i]; - if (p.x >= r.x && p.y >= r.y && p.x < r.z && p.y < r.w) { - float bit = mod(floor(mask / exp2(float(i))), 2.0); - return bit > 0.5; - } + uvec2 r = pc.rects[i]; + vec2 lo = vec2(float(r.x & 0xFFFFu), float(r.x >> 16)); + vec2 hi = vec2(float(r.y & 0xFFFFu), float(r.y >> 16)); + if (p.x >= lo.x && p.y >= lo.y && p.x < hi.x && p.y < hi.y) return i; } - return false; + return -1; +} + +bool bitOf(float mask, int i) { + return i >= 0 && mod(floor(mask / exp2(float(i))), 2.0) > 0.5; +} + +vec3 convertedNits(vec3 c) { + vec3 lin = pc.conv[1].w > 0.5 ? c : pqToLinear(c); + return vec3(dot(pc.conv[0].xyz, lin), dot(pc.conv[1].xyz, lin), dot(pc.conv[2].xyz, lin)) * pc.conv[2].w; } void main() { vec3 c = texelFetch(Mixed, ivec2(gl_FragCoord.xy), 0).rgb; - bool hdr = isHdrPixel(gl_FragCoord.xy); + int at = rectAt(gl_FragCoord.xy); + bool hdr = bitOf(floor(pc.params.w / 16.0), at); + bool conv = hdr && bitOf(pc.conv[0].w, at); float sdrWhite = max(pc.params.x, 1.0); vec3 outc; if (pc.params.z < 0.5) { - if (hdr) { + if (conv) { + outc = linearToPq(max(convertedNits(c), 0.0) / 10000.0); + } else if (hdr) { outc = c; } else { vec3 nits = (BT709_TO_BT2020 * srgbToLinear(c)) * sdrWhite; @@ -86,7 +97,8 @@ void main() { if (!hdr) { outc = c; } else { - vec3 rel = max(BT2020_TO_BT709 * (pqToLinear(c) * 10000.0), 0.0) / sdrWhite; + vec3 nits = conv ? convertedNits(c) : pqToLinear(c) * 10000.0; + vec3 rel = max(BT2020_TO_BT709 * nits, 0.0) / sdrWhite; float m = max(max(rel.r, rel.g), rel.b); if (m > 1e-6) rel *= toneCurve(m, max(pc.params.y, sdrWhite) / sdrWhite) / m; outc = linearToSrgb(clamp(rel, 0.0, 1.0)); diff --git a/app/src/main/cpp/waylandcomp/src/hdr_encode_frag.h b/app/src/main/cpp/waylandcomp/src/hdr_encode_frag.h index ba52146fc7..68baea4f82 100644 --- a/app/src/main/cpp/waylandcomp/src/hdr_encode_frag.h +++ b/app/src/main/cpp/waylandcomp/src/hdr_encode_frag.h @@ -1,8 +1,8 @@ #pragma once const uint32_t hdr_encode_code[] = { - 0x07230203,0x00010000,0x0008000b,0x0000018e,0x00000000,0x00020011,0x00000001,0x0006000b, + 0x07230203,0x00010000,0x0008000b,0x000001ff,0x00000000,0x00020011,0x00000001,0x0006000b, 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001, - 0x0008000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x0000010d,0x00000186,0x0000018d, + 0x0008000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000151,0x000001f7,0x000001fe, 0x00030010,0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004, 0x6e69616d,0x00000000,0x00070005,0x0000000b,0x62677273,0x694c6f54,0x7261656e,0x33667628, 0x0000003b,0x00030005,0x0000000a,0x00000063,0x00070005,0x0000000e,0x656e696c,0x6f547261, @@ -10,272 +10,354 @@ const uint32_t hdr_encode_code[] = { 0x6f547170,0x656e694c,0x76287261,0x003b3366,0x00030005,0x00000010,0x00000065,0x00060005, 0x00000014,0x656e696c,0x6f547261,0x76287150,0x003b3366,0x00030005,0x00000013,0x00000079, 0x00070005,0x0000001a,0x656e6f74,0x76727543,0x31662865,0x3b31663b,0x00000000,0x00030005, - 0x00000018,0x00000078,0x00040005,0x00000019,0x6b616570,0x00000000,0x00060005,0x00000021, - 0x64487369,0x78695072,0x76286c65,0x003b3266,0x00030005,0x00000020,0x00000070,0x00030005, - 0x00000023,0x00006f6c,0x00030005,0x00000028,0x00006968,0x00030005,0x0000003c,0x00006f6c, - 0x00030005,0x0000003f,0x00006968,0x00030005,0x00000050,0x00000070,0x00030005,0x0000006f, - 0x00000070,0x00040005,0x0000008c,0x6e617073,0x00000000,0x00040005,0x00000091,0x65746172, - 0x00000000,0x00040005,0x000000a2,0x6b636170,0x00006465,0x00030005,0x000000a7,0x00004350, - 0x00040006,0x000000a7,0x00000000,0x0063646e,0x00050006,0x000000a7,0x00000001,0x61726170, - 0x0000736d,0x00050006,0x000000a7,0x00000002,0x74636572,0x00000073,0x00030005,0x000000a9, - 0x00006370,0x00040005,0x000000b0,0x6e756f63,0x00000074,0x00040005,0x000000b4,0x6b73616d, - 0x00000000,0x00030005,0x000000b9,0x00000069,0x00030005,0x000000cd,0x00000072,0x00030005, - 0x000000f5,0x00746962,0x00030005,0x00000106,0x00000063,0x00040005,0x0000010a,0x6578694d, - 0x00000064,0x00060005,0x0000010d,0x465f6c67,0x43676172,0x64726f6f,0x00000000,0x00030005, - 0x00000116,0x00726468,0x00040005,0x00000117,0x61726170,0x0000006d,0x00050005,0x0000011b, - 0x57726473,0x65746968,0x00000000,0x00040005,0x00000127,0x6374756f,0x00000000,0x00040005, - 0x0000012a,0x7374696e,0x00000000,0x00040005,0x00000139,0x61726170,0x0000006d,0x00040005, - 0x00000143,0x61726170,0x0000006d,0x00030005,0x0000014c,0x006c6572,0x00040005,0x0000015a, - 0x61726170,0x0000006d,0x00030005,0x00000164,0x0000006d,0x00040005,0x00000177,0x61726170, - 0x0000006d,0x00040005,0x00000179,0x61726170,0x0000006d,0x00040005,0x00000183,0x61726170, - 0x0000006d,0x00050005,0x00000186,0x4374756f,0x726f6c6f,0x00000000,0x00060005,0x0000018d, - 0x67617266,0x43786554,0x64726f6f,0x00000000,0x00040047,0x000000a6,0x00000006,0x00000010, - 0x00030047,0x000000a7,0x00000002,0x00050048,0x000000a7,0x00000000,0x00000023,0x00000000, - 0x00050048,0x000000a7,0x00000001,0x00000023,0x00000010,0x00050048,0x000000a7,0x00000002, - 0x00000023,0x00000020,0x00040047,0x0000010a,0x00000021,0x00000000,0x00040047,0x0000010a, - 0x00000022,0x00000000,0x00040047,0x0000010d,0x0000000b,0x0000000f,0x00040047,0x00000186, - 0x0000001e,0x00000000,0x00040047,0x0000018d,0x0000001e,0x00000000,0x00020013,0x00000002, - 0x00030021,0x00000003,0x00000002,0x00030016,0x00000006,0x00000020,0x00040017,0x00000007, - 0x00000006,0x00000003,0x00040020,0x00000008,0x00000007,0x00000007,0x00040021,0x00000009, - 0x00000007,0x00000008,0x00040020,0x00000016,0x00000007,0x00000006,0x00050021,0x00000017, - 0x00000006,0x00000016,0x00000016,0x00040017,0x0000001c,0x00000006,0x00000002,0x00040020, - 0x0000001d,0x00000007,0x0000001c,0x00020014,0x0000001e,0x00040021,0x0000001f,0x0000001e, - 0x0000001d,0x0004002b,0x00000006,0x00000025,0x414eb852,0x0004002b,0x00000006,0x0000002a, - 0x3d6147ae,0x0004002b,0x00000006,0x0000002d,0x3f870a3d,0x0004002b,0x00000006,0x00000030, - 0x4019999a,0x0006002c,0x00000007,0x00000031,0x00000030,0x00000030,0x00000030,0x0004002b, - 0x00000006,0x00000035,0x3d25aee6,0x0006002c,0x00000007,0x00000036,0x00000035,0x00000035, - 0x00000035,0x0004002b,0x00000006,0x00000041,0x3ed55555,0x0006002c,0x00000007,0x00000042, - 0x00000041,0x00000041,0x00000041,0x0004002b,0x00000006,0x00000049,0x3b4d2e1c,0x0006002c, - 0x00000007,0x0000004a,0x00000049,0x00000049,0x00000049,0x0004002b,0x00000006,0x00000052, - 0x00000000,0x0004002b,0x00000006,0x00000053,0x3f800000,0x0004002b,0x00000006,0x00000057, - 0x3c4fcdac,0x0006002c,0x00000007,0x00000058,0x00000057,0x00000057,0x00000057,0x0004002b, - 0x00000006,0x0000005b,0x3f560000,0x0004002b,0x00000006,0x00000060,0x4196d000,0x0004002b, - 0x00000006,0x00000061,0x41958000,0x0004002b,0x00000006,0x00000066,0x358637bd,0x0004002b, - 0x00000006,0x0000006a,0x40c8e06b,0x0006002c,0x00000007,0x0000006b,0x0000006a,0x0000006a, - 0x0000006a,0x0004002b,0x00000006,0x00000074,0x3e232000,0x0006002c,0x00000007,0x00000075, - 0x00000074,0x00000074,0x00000074,0x0004002b,0x00000006,0x00000080,0x429db000,0x0006002c, - 0x00000007,0x00000081,0x00000080,0x00000080,0x00000080,0x0004002b,0x00000006,0x00000086, - 0x3f4ccccd,0x0004002b,0x00000006,0x0000008f,0x3d4ccccd,0x0004002b,0x00000006,0x00000093, - 0x407a5e35,0x0004002b,0x00000006,0x00000095,0x3e4ccccd,0x00040017,0x000000a3,0x00000006, - 0x00000004,0x00040015,0x000000a4,0x00000020,0x00000000,0x0004002b,0x000000a4,0x000000a5, - 0x00000006,0x0004001c,0x000000a6,0x000000a3,0x000000a5,0x0005001e,0x000000a7,0x000000a3, - 0x000000a3,0x000000a6,0x00040020,0x000000a8,0x00000009,0x000000a7,0x0004003b,0x000000a8, - 0x000000a9,0x00000009,0x00040015,0x000000aa,0x00000020,0x00000001,0x0004002b,0x000000aa, - 0x000000ab,0x00000001,0x0004002b,0x000000a4,0x000000ac,0x00000003,0x00040020,0x000000ad, - 0x00000009,0x00000006,0x0004002b,0x00000006,0x000000b2,0x41800000,0x00040020,0x000000b8, - 0x00000007,0x000000aa,0x0004002b,0x000000aa,0x000000ba,0x00000000,0x0004002b,0x000000aa, - 0x000000c1,0x00000006,0x0004002b,0x00000006,0x000000c6,0x3f000000,0x00040020,0x000000cc, - 0x00000007,0x000000a3,0x0004002b,0x000000aa,0x000000ce,0x00000002,0x00040020,0x000000d0, - 0x00000009,0x000000a3,0x0004002b,0x000000a4,0x000000d3,0x00000000,0x0004002b,0x000000a4, - 0x000000db,0x00000001,0x0004002b,0x000000a4,0x000000e6,0x00000002,0x0004002b,0x00000006, - 0x000000fc,0x40000000,0x0003002a,0x0000001e,0x00000103,0x00090019,0x00000107,0x00000006, - 0x00000001,0x00000000,0x00000000,0x00000000,0x00000001,0x00000000,0x0003001b,0x00000108, - 0x00000107,0x00040020,0x00000109,0x00000000,0x00000108,0x0004003b,0x00000109,0x0000010a, - 0x00000000,0x00040020,0x0000010c,0x00000001,0x000000a3,0x0004003b,0x0000010c,0x0000010d, - 0x00000001,0x00040017,0x00000110,0x000000aa,0x00000002,0x00040020,0x00000115,0x00000007, - 0x0000001e,0x00040018,0x0000012b,0x00000007,0x00000003,0x0004002b,0x00000006,0x0000012c, - 0x3f209d49,0x0004002b,0x00000006,0x0000012d,0x3d8d844d,0x0004002b,0x00000006,0x0000012e, - 0x3c86594b,0x0006002c,0x00000007,0x0000012f,0x0000012c,0x0000012d,0x0000012e,0x0004002b, - 0x00000006,0x00000130,0x3ea89a02,0x0004002b,0x00000006,0x00000131,0x3f6b645a,0x0004002b, - 0x00000006,0x00000132,0x3db43958,0x0006002c,0x00000007,0x00000133,0x00000130,0x00000131, - 0x00000132,0x0004002b,0x00000006,0x00000134,0x3d315b57,0x0004002b,0x00000006,0x00000135, - 0x3c3ac711,0x0004002b,0x00000006,0x00000136,0x3f65460b,0x0006002c,0x00000007,0x00000137, - 0x00000134,0x00000135,0x00000136,0x0006002c,0x0000012b,0x00000138,0x0000012f,0x00000133, - 0x00000137,0x0004002b,0x00000006,0x00000140,0x461c4000,0x0004002b,0x00000006,0x0000014d, - 0x3fd48b44,0x0004002b,0x00000006,0x0000014e,0xbdff2e49,0x0004002b,0x00000006,0x0000014f, - 0xbc95182b,0x0006002c,0x00000007,0x00000150,0x0000014d,0x0000014e,0x0000014f,0x0004002b, - 0x00000006,0x00000151,0xbf166cf4,0x0004002b,0x00000006,0x00000152,0x3f9102de,0x0004002b, - 0x00000006,0x00000153,0xbdce075f,0x0006002c,0x00000007,0x00000154,0x00000151,0x00000152, - 0x00000153,0x0004002b,0x00000006,0x00000155,0xbd95182b,0x0004002b,0x00000006,0x00000156, - 0xbc07fcb9,0x0004002b,0x00000006,0x00000157,0x3f8f3190,0x0006002c,0x00000007,0x00000158, - 0x00000155,0x00000156,0x00000157,0x0006002c,0x0000012b,0x00000159,0x00000150,0x00000154, - 0x00000158,0x00040020,0x00000185,0x00000003,0x000000a3,0x0004003b,0x00000185,0x00000186, - 0x00000003,0x00040020,0x0000018c,0x00000001,0x0000001c,0x0004003b,0x0000018c,0x0000018d, + 0x00000018,0x00000078,0x00040005,0x00000019,0x6b616570,0x00000000,0x00050005,0x00000021, + 0x74636572,0x76287441,0x003b3266,0x00030005,0x00000020,0x00000070,0x00060005,0x00000028, + 0x4f746962,0x31662866,0x3b31693b,0x00000000,0x00040005,0x00000026,0x6b73616d,0x00000000, + 0x00030005,0x00000027,0x00000069,0x00070005,0x0000002b,0x766e6f63,0x65747265,0x74694e64, + 0x66762873,0x00003b33,0x00030005,0x0000002a,0x00000063,0x00030005,0x0000002d,0x00006f6c, + 0x00030005,0x00000032,0x00006968,0x00030005,0x00000046,0x00006f6c,0x00030005,0x00000049, + 0x00006968,0x00030005,0x0000005a,0x00000070,0x00030005,0x00000079,0x00000070,0x00040005, + 0x00000096,0x6e617073,0x00000000,0x00040005,0x0000009b,0x65746172,0x00000000,0x00040005, + 0x000000ac,0x6e756f63,0x00000074,0x00030005,0x000000b4,0x00004350,0x00040006,0x000000b4, + 0x00000000,0x0063646e,0x00050006,0x000000b4,0x00000001,0x61726170,0x0000736d,0x00050006, + 0x000000b4,0x00000002,0x74636572,0x00000073,0x00050006,0x000000b4,0x00000003,0x766e6f63, + 0x00000000,0x00030005,0x000000b6,0x00006370,0x00030005,0x000000bd,0x00000069,0x00030005, + 0x000000d1,0x00000072,0x00030005,0x000000d7,0x00006f6c,0x00030005,0x000000e5,0x00006968, + 0x00030005,0x00000126,0x006e696c,0x00040005,0x00000130,0x61726170,0x0000006d,0x00030005, + 0x0000014a,0x00000063,0x00040005,0x0000014e,0x6578694d,0x00000064,0x00060005,0x00000151, + 0x465f6c67,0x43676172,0x64726f6f,0x00000000,0x00030005,0x00000159,0x00007461,0x00040005, + 0x0000015a,0x61726170,0x0000006d,0x00030005,0x0000015f,0x00726468,0x00040005,0x00000164, + 0x61726170,0x0000006d,0x00040005,0x00000165,0x61726170,0x0000006d,0x00040005,0x00000168, + 0x766e6f63,0x00000000,0x00040005,0x0000016c,0x61726170,0x0000006d,0x00040005,0x0000016f, + 0x61726170,0x0000006d,0x00050005,0x00000173,0x57726473,0x65746968,0x00000000,0x00040005, + 0x00000180,0x6374756f,0x00000000,0x00040005,0x00000181,0x61726170,0x0000006d,0x00040005, + 0x00000189,0x61726170,0x0000006d,0x00040005,0x00000191,0x7374696e,0x00000000,0x00040005, + 0x000001a0,0x61726170,0x0000006d,0x00040005,0x000001a9,0x61726170,0x0000006d,0x00040005, + 0x000001b2,0x7374696e,0x00000000,0x00040005,0x000001b7,0x61726170,0x0000006d,0x00040005, + 0x000001bb,0x61726170,0x0000006d,0x00030005,0x000001c0,0x006c6572,0x00030005,0x000001d5, + 0x0000006d,0x00040005,0x000001e8,0x61726170,0x0000006d,0x00040005,0x000001ea,0x61726170, + 0x0000006d,0x00040005,0x000001f4,0x61726170,0x0000006d,0x00050005,0x000001f7,0x4374756f, + 0x726f6c6f,0x00000000,0x00060005,0x000001fe,0x67617266,0x43786554,0x64726f6f,0x00000000, + 0x00040047,0x000000b1,0x00000006,0x00000008,0x00040047,0x000000b3,0x00000006,0x00000010, + 0x00030047,0x000000b4,0x00000002,0x00050048,0x000000b4,0x00000000,0x00000023,0x00000000, + 0x00050048,0x000000b4,0x00000001,0x00000023,0x00000010,0x00050048,0x000000b4,0x00000002, + 0x00000023,0x00000020,0x00050048,0x000000b4,0x00000003,0x00000023,0x00000050,0x00040047, + 0x0000014e,0x00000021,0x00000000,0x00040047,0x0000014e,0x00000022,0x00000000,0x00040047, + 0x00000151,0x0000000b,0x0000000f,0x00040047,0x000001f7,0x0000001e,0x00000000,0x00040047, + 0x000001fe,0x0000001e,0x00000000,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002, + 0x00030016,0x00000006,0x00000020,0x00040017,0x00000007,0x00000006,0x00000003,0x00040020, + 0x00000008,0x00000007,0x00000007,0x00040021,0x00000009,0x00000007,0x00000008,0x00040020, + 0x00000016,0x00000007,0x00000006,0x00050021,0x00000017,0x00000006,0x00000016,0x00000016, + 0x00040017,0x0000001c,0x00000006,0x00000002,0x00040020,0x0000001d,0x00000007,0x0000001c, + 0x00040015,0x0000001e,0x00000020,0x00000001,0x00040021,0x0000001f,0x0000001e,0x0000001d, + 0x00040020,0x00000023,0x00000007,0x0000001e,0x00020014,0x00000024,0x00050021,0x00000025, + 0x00000024,0x00000016,0x00000023,0x0004002b,0x00000006,0x0000002f,0x414eb852,0x0004002b, + 0x00000006,0x00000034,0x3d6147ae,0x0004002b,0x00000006,0x00000037,0x3f870a3d,0x0004002b, + 0x00000006,0x0000003a,0x4019999a,0x0006002c,0x00000007,0x0000003b,0x0000003a,0x0000003a, + 0x0000003a,0x0004002b,0x00000006,0x0000003f,0x3d25aee6,0x0006002c,0x00000007,0x00000040, + 0x0000003f,0x0000003f,0x0000003f,0x0004002b,0x00000006,0x0000004b,0x3ed55555,0x0006002c, + 0x00000007,0x0000004c,0x0000004b,0x0000004b,0x0000004b,0x0004002b,0x00000006,0x00000053, + 0x3b4d2e1c,0x0006002c,0x00000007,0x00000054,0x00000053,0x00000053,0x00000053,0x0004002b, + 0x00000006,0x0000005c,0x00000000,0x0004002b,0x00000006,0x0000005d,0x3f800000,0x0004002b, + 0x00000006,0x00000061,0x3c4fcdac,0x0006002c,0x00000007,0x00000062,0x00000061,0x00000061, + 0x00000061,0x0004002b,0x00000006,0x00000065,0x3f560000,0x0004002b,0x00000006,0x0000006a, + 0x4196d000,0x0004002b,0x00000006,0x0000006b,0x41958000,0x0004002b,0x00000006,0x00000070, + 0x358637bd,0x0004002b,0x00000006,0x00000074,0x40c8e06b,0x0006002c,0x00000007,0x00000075, + 0x00000074,0x00000074,0x00000074,0x0004002b,0x00000006,0x0000007e,0x3e232000,0x0006002c, + 0x00000007,0x0000007f,0x0000007e,0x0000007e,0x0000007e,0x0004002b,0x00000006,0x0000008a, + 0x429db000,0x0006002c,0x00000007,0x0000008b,0x0000008a,0x0000008a,0x0000008a,0x0004002b, + 0x00000006,0x00000090,0x3f4ccccd,0x0004002b,0x00000006,0x00000099,0x3d4ccccd,0x0004002b, + 0x00000006,0x0000009d,0x407a5e35,0x0004002b,0x00000006,0x0000009f,0x3e4ccccd,0x00040017, + 0x000000ad,0x00000006,0x00000004,0x00040015,0x000000ae,0x00000020,0x00000000,0x00040017, + 0x000000af,0x000000ae,0x00000002,0x0004002b,0x000000ae,0x000000b0,0x00000006,0x0004001c, + 0x000000b1,0x000000af,0x000000b0,0x0004002b,0x000000ae,0x000000b2,0x00000003,0x0004001c, + 0x000000b3,0x000000ad,0x000000b2,0x0006001e,0x000000b4,0x000000ad,0x000000ad,0x000000b1, + 0x000000b3,0x00040020,0x000000b5,0x00000009,0x000000b4,0x0004003b,0x000000b5,0x000000b6, + 0x00000009,0x0004002b,0x0000001e,0x000000b7,0x00000001,0x00040020,0x000000b8,0x00000009, + 0x00000006,0x0004002b,0x00000006,0x000000bb,0x41800000,0x0004002b,0x0000001e,0x000000be, + 0x00000000,0x0004002b,0x0000001e,0x000000c5,0x00000006,0x0004002b,0x00000006,0x000000ca, + 0x3f000000,0x00040020,0x000000d0,0x00000007,0x000000af,0x0004002b,0x0000001e,0x000000d2, + 0x00000002,0x00040020,0x000000d4,0x00000009,0x000000af,0x0004002b,0x000000ae,0x000000d8, + 0x00000000,0x00040020,0x000000d9,0x00000007,0x000000ae,0x0004002b,0x000000ae,0x000000dc, + 0x0000ffff,0x0004002b,0x0000001e,0x000000e1,0x00000010,0x0004002b,0x000000ae,0x000000e6, + 0x00000001,0x0004002b,0x0000001e,0x00000113,0xffffffff,0x0004002b,0x00000006,0x00000120, + 0x40000000,0x0004002b,0x0000001e,0x00000127,0x00000003,0x00040020,0x00000134,0x00000009, + 0x000000ad,0x00090019,0x0000014b,0x00000006,0x00000001,0x00000000,0x00000000,0x00000000, + 0x00000001,0x00000000,0x0003001b,0x0000014c,0x0000014b,0x00040020,0x0000014d,0x00000000, + 0x0000014c,0x0004003b,0x0000014d,0x0000014e,0x00000000,0x00040020,0x00000150,0x00000001, + 0x000000ad,0x0004003b,0x00000150,0x00000151,0x00000001,0x00040017,0x00000154,0x0000001e, + 0x00000002,0x00040020,0x0000015e,0x00000007,0x00000024,0x0004002b,0x000000ae,0x00000177, + 0x00000002,0x0004002b,0x00000006,0x00000186,0x461c4000,0x00040018,0x00000192,0x00000007, + 0x00000003,0x0004002b,0x00000006,0x00000193,0x3f209d49,0x0004002b,0x00000006,0x00000194, + 0x3d8d844d,0x0004002b,0x00000006,0x00000195,0x3c86594b,0x0006002c,0x00000007,0x00000196, + 0x00000193,0x00000194,0x00000195,0x0004002b,0x00000006,0x00000197,0x3ea89a02,0x0004002b, + 0x00000006,0x00000198,0x3f6b645a,0x0004002b,0x00000006,0x00000199,0x3db43958,0x0006002c, + 0x00000007,0x0000019a,0x00000197,0x00000198,0x00000199,0x0004002b,0x00000006,0x0000019b, + 0x3d315b57,0x0004002b,0x00000006,0x0000019c,0x3c3ac711,0x0004002b,0x00000006,0x0000019d, + 0x3f65460b,0x0006002c,0x00000007,0x0000019e,0x0000019b,0x0000019c,0x0000019d,0x0006002c, + 0x00000192,0x0000019f,0x00000196,0x0000019a,0x0000019e,0x0004002b,0x00000006,0x000001c1, + 0x3fd48b44,0x0004002b,0x00000006,0x000001c2,0xbdff2e49,0x0004002b,0x00000006,0x000001c3, + 0xbc95182b,0x0006002c,0x00000007,0x000001c4,0x000001c1,0x000001c2,0x000001c3,0x0004002b, + 0x00000006,0x000001c5,0xbf166cf4,0x0004002b,0x00000006,0x000001c6,0x3f9102de,0x0004002b, + 0x00000006,0x000001c7,0xbdce075f,0x0006002c,0x00000007,0x000001c8,0x000001c5,0x000001c6, + 0x000001c7,0x0004002b,0x00000006,0x000001c9,0xbd95182b,0x0004002b,0x00000006,0x000001ca, + 0xbc07fcb9,0x0004002b,0x00000006,0x000001cb,0x3f8f3190,0x0006002c,0x00000007,0x000001cc, + 0x000001c9,0x000001ca,0x000001cb,0x0006002c,0x00000192,0x000001cd,0x000001c4,0x000001c8, + 0x000001cc,0x00040020,0x000001f6,0x00000003,0x000000ad,0x0004003b,0x000001f6,0x000001f7, + 0x00000003,0x00040020,0x000001fd,0x00000001,0x0000001c,0x0004003b,0x000001fd,0x000001fe, 0x00000001,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,0x00000005, - 0x0004003b,0x00000008,0x00000106,0x00000007,0x0004003b,0x00000115,0x00000116,0x00000007, - 0x0004003b,0x0000001d,0x00000117,0x00000007,0x0004003b,0x00000016,0x0000011b,0x00000007, - 0x0004003b,0x00000008,0x00000127,0x00000007,0x0004003b,0x00000008,0x0000012a,0x00000007, - 0x0004003b,0x00000008,0x00000139,0x00000007,0x0004003b,0x00000008,0x00000143,0x00000007, - 0x0004003b,0x00000008,0x0000014c,0x00000007,0x0004003b,0x00000008,0x0000015a,0x00000007, - 0x0004003b,0x00000016,0x00000164,0x00000007,0x0004003b,0x00000016,0x00000177,0x00000007, - 0x0004003b,0x00000016,0x00000179,0x00000007,0x0004003b,0x00000008,0x00000183,0x00000007, - 0x0004003d,0x00000108,0x0000010b,0x0000010a,0x0004003d,0x000000a3,0x0000010e,0x0000010d, - 0x0007004f,0x0000001c,0x0000010f,0x0000010e,0x0000010e,0x00000000,0x00000001,0x0004006e, - 0x00000110,0x00000111,0x0000010f,0x00040064,0x00000107,0x00000112,0x0000010b,0x0007005f, - 0x000000a3,0x00000113,0x00000112,0x00000111,0x00000002,0x000000ba,0x0008004f,0x00000007, - 0x00000114,0x00000113,0x00000113,0x00000000,0x00000001,0x00000002,0x0003003e,0x00000106, - 0x00000114,0x0004003d,0x000000a3,0x00000118,0x0000010d,0x0007004f,0x0000001c,0x00000119, - 0x00000118,0x00000118,0x00000000,0x00000001,0x0003003e,0x00000117,0x00000119,0x00050039, - 0x0000001e,0x0000011a,0x00000021,0x00000117,0x0003003e,0x00000116,0x0000011a,0x00060041, - 0x000000ad,0x0000011c,0x000000a9,0x000000ab,0x000000d3,0x0004003d,0x00000006,0x0000011d, - 0x0000011c,0x0007000c,0x00000006,0x0000011e,0x00000001,0x00000028,0x0000011d,0x00000053, - 0x0003003e,0x0000011b,0x0000011e,0x00060041,0x000000ad,0x0000011f,0x000000a9,0x000000ab, - 0x000000e6,0x0004003d,0x00000006,0x00000120,0x0000011f,0x000500b8,0x0000001e,0x00000121, - 0x00000120,0x000000c6,0x000300f7,0x00000123,0x00000000,0x000400fa,0x00000121,0x00000122, - 0x00000145,0x000200f8,0x00000122,0x0004003d,0x0000001e,0x00000124,0x00000116,0x000300f7, - 0x00000126,0x00000000,0x000400fa,0x00000124,0x00000125,0x00000129,0x000200f8,0x00000125, - 0x0004003d,0x00000007,0x00000128,0x00000106,0x0003003e,0x00000127,0x00000128,0x000200f9, - 0x00000126,0x000200f8,0x00000129,0x0004003d,0x00000007,0x0000013a,0x00000106,0x0003003e, - 0x00000139,0x0000013a,0x00050039,0x00000007,0x0000013b,0x0000000b,0x00000139,0x00050091, - 0x00000007,0x0000013c,0x00000138,0x0000013b,0x0004003d,0x00000006,0x0000013d,0x0000011b, - 0x0005008e,0x00000007,0x0000013e,0x0000013c,0x0000013d,0x0003003e,0x0000012a,0x0000013e, - 0x0004003d,0x00000007,0x0000013f,0x0000012a,0x00060050,0x00000007,0x00000141,0x00000140, - 0x00000140,0x00000140,0x00050088,0x00000007,0x00000142,0x0000013f,0x00000141,0x0003003e, - 0x00000143,0x00000142,0x00050039,0x00000007,0x00000144,0x00000014,0x00000143,0x0003003e, - 0x00000127,0x00000144,0x000200f9,0x00000126,0x000200f8,0x00000126,0x000200f9,0x00000123, - 0x000200f8,0x00000145,0x0004003d,0x0000001e,0x00000146,0x00000116,0x000400a8,0x0000001e, - 0x00000147,0x00000146,0x000300f7,0x00000149,0x00000000,0x000400fa,0x00000147,0x00000148, - 0x0000014b,0x000200f8,0x00000148,0x0004003d,0x00000007,0x0000014a,0x00000106,0x0003003e, - 0x00000127,0x0000014a,0x000200f9,0x00000149,0x000200f8,0x0000014b,0x0004003d,0x00000007, - 0x0000015b,0x00000106,0x0003003e,0x0000015a,0x0000015b,0x00050039,0x00000007,0x0000015c, - 0x00000011,0x0000015a,0x0005008e,0x00000007,0x0000015d,0x0000015c,0x00000140,0x00050091, - 0x00000007,0x0000015e,0x00000159,0x0000015d,0x00060050,0x00000007,0x0000015f,0x00000052, - 0x00000052,0x00000052,0x0007000c,0x00000007,0x00000160,0x00000001,0x00000028,0x0000015e, - 0x0000015f,0x0004003d,0x00000006,0x00000161,0x0000011b,0x00060050,0x00000007,0x00000162, - 0x00000161,0x00000161,0x00000161,0x00050088,0x00000007,0x00000163,0x00000160,0x00000162, - 0x0003003e,0x0000014c,0x00000163,0x00050041,0x00000016,0x00000165,0x0000014c,0x000000d3, - 0x0004003d,0x00000006,0x00000166,0x00000165,0x00050041,0x00000016,0x00000167,0x0000014c, - 0x000000db,0x0004003d,0x00000006,0x00000168,0x00000167,0x0007000c,0x00000006,0x00000169, - 0x00000001,0x00000028,0x00000166,0x00000168,0x00050041,0x00000016,0x0000016a,0x0000014c, - 0x000000e6,0x0004003d,0x00000006,0x0000016b,0x0000016a,0x0007000c,0x00000006,0x0000016c, - 0x00000001,0x00000028,0x00000169,0x0000016b,0x0003003e,0x00000164,0x0000016c,0x0004003d, - 0x00000006,0x0000016d,0x00000164,0x000500ba,0x0000001e,0x0000016e,0x0000016d,0x00000066, - 0x000300f7,0x00000170,0x00000000,0x000400fa,0x0000016e,0x0000016f,0x00000170,0x000200f8, - 0x0000016f,0x00060041,0x000000ad,0x00000171,0x000000a9,0x000000ab,0x000000db,0x0004003d, - 0x00000006,0x00000172,0x00000171,0x0004003d,0x00000006,0x00000173,0x0000011b,0x0007000c, - 0x00000006,0x00000174,0x00000001,0x00000028,0x00000172,0x00000173,0x0004003d,0x00000006, - 0x00000175,0x0000011b,0x00050088,0x00000006,0x00000176,0x00000174,0x00000175,0x0004003d, - 0x00000006,0x00000178,0x00000164,0x0003003e,0x00000177,0x00000178,0x0003003e,0x00000179, - 0x00000176,0x00060039,0x00000006,0x0000017a,0x0000001a,0x00000177,0x00000179,0x0004003d, - 0x00000006,0x0000017b,0x00000164,0x00050088,0x00000006,0x0000017c,0x0000017a,0x0000017b, - 0x0004003d,0x00000007,0x0000017d,0x0000014c,0x0005008e,0x00000007,0x0000017e,0x0000017d, - 0x0000017c,0x0003003e,0x0000014c,0x0000017e,0x000200f9,0x00000170,0x000200f8,0x00000170, - 0x0004003d,0x00000007,0x0000017f,0x0000014c,0x00060050,0x00000007,0x00000180,0x00000052, - 0x00000052,0x00000052,0x00060050,0x00000007,0x00000181,0x00000053,0x00000053,0x00000053, - 0x0008000c,0x00000007,0x00000182,0x00000001,0x0000002b,0x0000017f,0x00000180,0x00000181, - 0x0003003e,0x00000183,0x00000182,0x00050039,0x00000007,0x00000184,0x0000000e,0x00000183, - 0x0003003e,0x00000127,0x00000184,0x000200f9,0x00000149,0x000200f8,0x00000149,0x000200f9, - 0x00000123,0x000200f8,0x00000123,0x0004003d,0x00000007,0x00000187,0x00000127,0x00050051, - 0x00000006,0x00000188,0x00000187,0x00000000,0x00050051,0x00000006,0x00000189,0x00000187, - 0x00000001,0x00050051,0x00000006,0x0000018a,0x00000187,0x00000002,0x00070050,0x000000a3, - 0x0000018b,0x00000188,0x00000189,0x0000018a,0x00000053,0x0003003e,0x00000186,0x0000018b, + 0x0004003b,0x00000008,0x0000014a,0x00000007,0x0004003b,0x00000023,0x00000159,0x00000007, + 0x0004003b,0x0000001d,0x0000015a,0x00000007,0x0004003b,0x0000015e,0x0000015f,0x00000007, + 0x0004003b,0x00000016,0x00000164,0x00000007,0x0004003b,0x00000023,0x00000165,0x00000007, + 0x0004003b,0x0000015e,0x00000168,0x00000007,0x0004003b,0x00000016,0x0000016c,0x00000007, + 0x0004003b,0x00000023,0x0000016f,0x00000007,0x0004003b,0x00000016,0x00000173,0x00000007, + 0x0004003b,0x00000008,0x00000180,0x00000007,0x0004003b,0x00000008,0x00000181,0x00000007, + 0x0004003b,0x00000008,0x00000189,0x00000007,0x0004003b,0x00000008,0x00000191,0x00000007, + 0x0004003b,0x00000008,0x000001a0,0x00000007,0x0004003b,0x00000008,0x000001a9,0x00000007, + 0x0004003b,0x00000008,0x000001b2,0x00000007,0x0004003b,0x00000008,0x000001b4,0x00000007, + 0x0004003b,0x00000008,0x000001b7,0x00000007,0x0004003b,0x00000008,0x000001bb,0x00000007, + 0x0004003b,0x00000008,0x000001c0,0x00000007,0x0004003b,0x00000016,0x000001d5,0x00000007, + 0x0004003b,0x00000016,0x000001e8,0x00000007,0x0004003b,0x00000016,0x000001ea,0x00000007, + 0x0004003b,0x00000008,0x000001f4,0x00000007,0x0004003d,0x0000014c,0x0000014f,0x0000014e, + 0x0004003d,0x000000ad,0x00000152,0x00000151,0x0007004f,0x0000001c,0x00000153,0x00000152, + 0x00000152,0x00000000,0x00000001,0x0004006e,0x00000154,0x00000155,0x00000153,0x00040064, + 0x0000014b,0x00000156,0x0000014f,0x0007005f,0x000000ad,0x00000157,0x00000156,0x00000155, + 0x00000002,0x000000be,0x0008004f,0x00000007,0x00000158,0x00000157,0x00000157,0x00000000, + 0x00000001,0x00000002,0x0003003e,0x0000014a,0x00000158,0x0004003d,0x000000ad,0x0000015b, + 0x00000151,0x0007004f,0x0000001c,0x0000015c,0x0000015b,0x0000015b,0x00000000,0x00000001, + 0x0003003e,0x0000015a,0x0000015c,0x00050039,0x0000001e,0x0000015d,0x00000021,0x0000015a, + 0x0003003e,0x00000159,0x0000015d,0x00060041,0x000000b8,0x00000160,0x000000b6,0x000000b7, + 0x000000b2,0x0004003d,0x00000006,0x00000161,0x00000160,0x00050088,0x00000006,0x00000162, + 0x00000161,0x000000bb,0x0006000c,0x00000006,0x00000163,0x00000001,0x00000008,0x00000162, + 0x0003003e,0x00000164,0x00000163,0x0004003d,0x0000001e,0x00000166,0x00000159,0x0003003e, + 0x00000165,0x00000166,0x00060039,0x00000024,0x00000167,0x00000028,0x00000164,0x00000165, + 0x0003003e,0x0000015f,0x00000167,0x0004003d,0x00000024,0x00000169,0x0000015f,0x000300f7, + 0x0000016b,0x00000000,0x000400fa,0x00000169,0x0000016a,0x0000016b,0x000200f8,0x0000016a, + 0x00070041,0x000000b8,0x0000016d,0x000000b6,0x00000127,0x000000be,0x000000b2,0x0004003d, + 0x00000006,0x0000016e,0x0000016d,0x0003003e,0x0000016c,0x0000016e,0x0004003d,0x0000001e, + 0x00000170,0x00000159,0x0003003e,0x0000016f,0x00000170,0x00060039,0x00000024,0x00000171, + 0x00000028,0x0000016c,0x0000016f,0x000200f9,0x0000016b,0x000200f8,0x0000016b,0x000700f5, + 0x00000024,0x00000172,0x00000169,0x00000005,0x00000171,0x0000016a,0x0003003e,0x00000168, + 0x00000172,0x00060041,0x000000b8,0x00000174,0x000000b6,0x000000b7,0x000000d8,0x0004003d, + 0x00000006,0x00000175,0x00000174,0x0007000c,0x00000006,0x00000176,0x00000001,0x00000028, + 0x00000175,0x0000005d,0x0003003e,0x00000173,0x00000176,0x00060041,0x000000b8,0x00000178, + 0x000000b6,0x000000b7,0x00000177,0x0004003d,0x00000006,0x00000179,0x00000178,0x000500b8, + 0x00000024,0x0000017a,0x00000179,0x000000ca,0x000300f7,0x0000017c,0x00000000,0x000400fa, + 0x0000017a,0x0000017b,0x000001ab,0x000200f8,0x0000017b,0x0004003d,0x00000024,0x0000017d, + 0x00000168,0x000300f7,0x0000017f,0x00000000,0x000400fa,0x0000017d,0x0000017e,0x0000018b, + 0x000200f8,0x0000017e,0x0004003d,0x00000007,0x00000182,0x0000014a,0x0003003e,0x00000181, + 0x00000182,0x00050039,0x00000007,0x00000183,0x0000002b,0x00000181,0x00060050,0x00000007, + 0x00000184,0x0000005c,0x0000005c,0x0000005c,0x0007000c,0x00000007,0x00000185,0x00000001, + 0x00000028,0x00000183,0x00000184,0x00060050,0x00000007,0x00000187,0x00000186,0x00000186, + 0x00000186,0x00050088,0x00000007,0x00000188,0x00000185,0x00000187,0x0003003e,0x00000189, + 0x00000188,0x00050039,0x00000007,0x0000018a,0x00000014,0x00000189,0x0003003e,0x00000180, + 0x0000018a,0x000200f9,0x0000017f,0x000200f8,0x0000018b,0x0004003d,0x00000024,0x0000018c, + 0x0000015f,0x000300f7,0x0000018e,0x00000000,0x000400fa,0x0000018c,0x0000018d,0x00000190, + 0x000200f8,0x0000018d,0x0004003d,0x00000007,0x0000018f,0x0000014a,0x0003003e,0x00000180, + 0x0000018f,0x000200f9,0x0000018e,0x000200f8,0x00000190,0x0004003d,0x00000007,0x000001a1, + 0x0000014a,0x0003003e,0x000001a0,0x000001a1,0x00050039,0x00000007,0x000001a2,0x0000000b, + 0x000001a0,0x00050091,0x00000007,0x000001a3,0x0000019f,0x000001a2,0x0004003d,0x00000006, + 0x000001a4,0x00000173,0x0005008e,0x00000007,0x000001a5,0x000001a3,0x000001a4,0x0003003e, + 0x00000191,0x000001a5,0x0004003d,0x00000007,0x000001a6,0x00000191,0x00060050,0x00000007, + 0x000001a7,0x00000186,0x00000186,0x00000186,0x00050088,0x00000007,0x000001a8,0x000001a6, + 0x000001a7,0x0003003e,0x000001a9,0x000001a8,0x00050039,0x00000007,0x000001aa,0x00000014, + 0x000001a9,0x0003003e,0x00000180,0x000001aa,0x000200f9,0x0000018e,0x000200f8,0x0000018e, + 0x000200f9,0x0000017f,0x000200f8,0x0000017f,0x000200f9,0x0000017c,0x000200f8,0x000001ab, + 0x0004003d,0x00000024,0x000001ac,0x0000015f,0x000400a8,0x00000024,0x000001ad,0x000001ac, + 0x000300f7,0x000001af,0x00000000,0x000400fa,0x000001ad,0x000001ae,0x000001b1,0x000200f8, + 0x000001ae,0x0004003d,0x00000007,0x000001b0,0x0000014a,0x0003003e,0x00000180,0x000001b0, + 0x000200f9,0x000001af,0x000200f8,0x000001b1,0x0004003d,0x00000024,0x000001b3,0x00000168, + 0x000300f7,0x000001b6,0x00000000,0x000400fa,0x000001b3,0x000001b5,0x000001ba,0x000200f8, + 0x000001b5,0x0004003d,0x00000007,0x000001b8,0x0000014a,0x0003003e,0x000001b7,0x000001b8, + 0x00050039,0x00000007,0x000001b9,0x0000002b,0x000001b7,0x0003003e,0x000001b4,0x000001b9, + 0x000200f9,0x000001b6,0x000200f8,0x000001ba,0x0004003d,0x00000007,0x000001bc,0x0000014a, + 0x0003003e,0x000001bb,0x000001bc,0x00050039,0x00000007,0x000001bd,0x00000011,0x000001bb, + 0x0005008e,0x00000007,0x000001be,0x000001bd,0x00000186,0x0003003e,0x000001b4,0x000001be, + 0x000200f9,0x000001b6,0x000200f8,0x000001b6,0x0004003d,0x00000007,0x000001bf,0x000001b4, + 0x0003003e,0x000001b2,0x000001bf,0x0004003d,0x00000007,0x000001ce,0x000001b2,0x00050091, + 0x00000007,0x000001cf,0x000001cd,0x000001ce,0x00060050,0x00000007,0x000001d0,0x0000005c, + 0x0000005c,0x0000005c,0x0007000c,0x00000007,0x000001d1,0x00000001,0x00000028,0x000001cf, + 0x000001d0,0x0004003d,0x00000006,0x000001d2,0x00000173,0x00060050,0x00000007,0x000001d3, + 0x000001d2,0x000001d2,0x000001d2,0x00050088,0x00000007,0x000001d4,0x000001d1,0x000001d3, + 0x0003003e,0x000001c0,0x000001d4,0x00050041,0x00000016,0x000001d6,0x000001c0,0x000000d8, + 0x0004003d,0x00000006,0x000001d7,0x000001d6,0x00050041,0x00000016,0x000001d8,0x000001c0, + 0x000000e6,0x0004003d,0x00000006,0x000001d9,0x000001d8,0x0007000c,0x00000006,0x000001da, + 0x00000001,0x00000028,0x000001d7,0x000001d9,0x00050041,0x00000016,0x000001db,0x000001c0, + 0x00000177,0x0004003d,0x00000006,0x000001dc,0x000001db,0x0007000c,0x00000006,0x000001dd, + 0x00000001,0x00000028,0x000001da,0x000001dc,0x0003003e,0x000001d5,0x000001dd,0x0004003d, + 0x00000006,0x000001de,0x000001d5,0x000500ba,0x00000024,0x000001df,0x000001de,0x00000070, + 0x000300f7,0x000001e1,0x00000000,0x000400fa,0x000001df,0x000001e0,0x000001e1,0x000200f8, + 0x000001e0,0x00060041,0x000000b8,0x000001e2,0x000000b6,0x000000b7,0x000000e6,0x0004003d, + 0x00000006,0x000001e3,0x000001e2,0x0004003d,0x00000006,0x000001e4,0x00000173,0x0007000c, + 0x00000006,0x000001e5,0x00000001,0x00000028,0x000001e3,0x000001e4,0x0004003d,0x00000006, + 0x000001e6,0x00000173,0x00050088,0x00000006,0x000001e7,0x000001e5,0x000001e6,0x0004003d, + 0x00000006,0x000001e9,0x000001d5,0x0003003e,0x000001e8,0x000001e9,0x0003003e,0x000001ea, + 0x000001e7,0x00060039,0x00000006,0x000001eb,0x0000001a,0x000001e8,0x000001ea,0x0004003d, + 0x00000006,0x000001ec,0x000001d5,0x00050088,0x00000006,0x000001ed,0x000001eb,0x000001ec, + 0x0004003d,0x00000007,0x000001ee,0x000001c0,0x0005008e,0x00000007,0x000001ef,0x000001ee, + 0x000001ed,0x0003003e,0x000001c0,0x000001ef,0x000200f9,0x000001e1,0x000200f8,0x000001e1, + 0x0004003d,0x00000007,0x000001f0,0x000001c0,0x00060050,0x00000007,0x000001f1,0x0000005c, + 0x0000005c,0x0000005c,0x00060050,0x00000007,0x000001f2,0x0000005d,0x0000005d,0x0000005d, + 0x0008000c,0x00000007,0x000001f3,0x00000001,0x0000002b,0x000001f0,0x000001f1,0x000001f2, + 0x0003003e,0x000001f4,0x000001f3,0x00050039,0x00000007,0x000001f5,0x0000000e,0x000001f4, + 0x0003003e,0x00000180,0x000001f5,0x000200f9,0x000001af,0x000200f8,0x000001af,0x000200f9, + 0x0000017c,0x000200f8,0x0000017c,0x0004003d,0x00000007,0x000001f8,0x00000180,0x00050051, + 0x00000006,0x000001f9,0x000001f8,0x00000000,0x00050051,0x00000006,0x000001fa,0x000001f8, + 0x00000001,0x00050051,0x00000006,0x000001fb,0x000001f8,0x00000002,0x00070050,0x000000ad, + 0x000001fc,0x000001f9,0x000001fa,0x000001fb,0x0000005d,0x0003003e,0x000001f7,0x000001fc, 0x000100fd,0x00010038,0x00050036,0x00000007,0x0000000b,0x00000000,0x00000009,0x00030037, - 0x00000008,0x0000000a,0x000200f8,0x0000000c,0x0004003b,0x00000008,0x00000023,0x00000007, - 0x0004003b,0x00000008,0x00000028,0x00000007,0x0004003d,0x00000007,0x00000024,0x0000000a, - 0x00060050,0x00000007,0x00000026,0x00000025,0x00000025,0x00000025,0x00050088,0x00000007, - 0x00000027,0x00000024,0x00000026,0x0003003e,0x00000023,0x00000027,0x0004003d,0x00000007, - 0x00000029,0x0000000a,0x00060050,0x00000007,0x0000002b,0x0000002a,0x0000002a,0x0000002a, - 0x00050081,0x00000007,0x0000002c,0x00000029,0x0000002b,0x00060050,0x00000007,0x0000002e, - 0x0000002d,0x0000002d,0x0000002d,0x00050088,0x00000007,0x0000002f,0x0000002c,0x0000002e, - 0x0007000c,0x00000007,0x00000032,0x00000001,0x0000001a,0x0000002f,0x00000031,0x0003003e, - 0x00000028,0x00000032,0x0004003d,0x00000007,0x00000033,0x00000023,0x0004003d,0x00000007, - 0x00000034,0x00000028,0x0004003d,0x00000007,0x00000037,0x0000000a,0x0007000c,0x00000007, - 0x00000038,0x00000001,0x00000030,0x00000036,0x00000037,0x0008000c,0x00000007,0x00000039, - 0x00000001,0x0000002e,0x00000033,0x00000034,0x00000038,0x000200fe,0x00000039,0x00010038, + 0x00000008,0x0000000a,0x000200f8,0x0000000c,0x0004003b,0x00000008,0x0000002d,0x00000007, + 0x0004003b,0x00000008,0x00000032,0x00000007,0x0004003d,0x00000007,0x0000002e,0x0000000a, + 0x00060050,0x00000007,0x00000030,0x0000002f,0x0000002f,0x0000002f,0x00050088,0x00000007, + 0x00000031,0x0000002e,0x00000030,0x0003003e,0x0000002d,0x00000031,0x0004003d,0x00000007, + 0x00000033,0x0000000a,0x00060050,0x00000007,0x00000035,0x00000034,0x00000034,0x00000034, + 0x00050081,0x00000007,0x00000036,0x00000033,0x00000035,0x00060050,0x00000007,0x00000038, + 0x00000037,0x00000037,0x00000037,0x00050088,0x00000007,0x00000039,0x00000036,0x00000038, + 0x0007000c,0x00000007,0x0000003c,0x00000001,0x0000001a,0x00000039,0x0000003b,0x0003003e, + 0x00000032,0x0000003c,0x0004003d,0x00000007,0x0000003d,0x0000002d,0x0004003d,0x00000007, + 0x0000003e,0x00000032,0x0004003d,0x00000007,0x00000041,0x0000000a,0x0007000c,0x00000007, + 0x00000042,0x00000001,0x00000030,0x00000040,0x00000041,0x0008000c,0x00000007,0x00000043, + 0x00000001,0x0000002e,0x0000003d,0x0000003e,0x00000042,0x000200fe,0x00000043,0x00010038, 0x00050036,0x00000007,0x0000000e,0x00000000,0x00000009,0x00030037,0x00000008,0x0000000d, - 0x000200f8,0x0000000f,0x0004003b,0x00000008,0x0000003c,0x00000007,0x0004003b,0x00000008, - 0x0000003f,0x00000007,0x0004003d,0x00000007,0x0000003d,0x0000000d,0x0005008e,0x00000007, - 0x0000003e,0x0000003d,0x00000025,0x0003003e,0x0000003c,0x0000003e,0x0004003d,0x00000007, - 0x00000040,0x0000000d,0x0007000c,0x00000007,0x00000043,0x00000001,0x0000001a,0x00000040, - 0x00000042,0x0005008e,0x00000007,0x00000044,0x00000043,0x0000002d,0x00060050,0x00000007, - 0x00000045,0x0000002a,0x0000002a,0x0000002a,0x00050083,0x00000007,0x00000046,0x00000044, - 0x00000045,0x0003003e,0x0000003f,0x00000046,0x0004003d,0x00000007,0x00000047,0x0000003c, - 0x0004003d,0x00000007,0x00000048,0x0000003f,0x0004003d,0x00000007,0x0000004b,0x0000000d, - 0x0007000c,0x00000007,0x0000004c,0x00000001,0x00000030,0x0000004a,0x0000004b,0x0008000c, - 0x00000007,0x0000004d,0x00000001,0x0000002e,0x00000047,0x00000048,0x0000004c,0x000200fe, - 0x0000004d,0x00010038,0x00050036,0x00000007,0x00000011,0x00000000,0x00000009,0x00030037, - 0x00000008,0x00000010,0x000200f8,0x00000012,0x0004003b,0x00000008,0x00000050,0x00000007, - 0x0004003d,0x00000007,0x00000051,0x00000010,0x00060050,0x00000007,0x00000054,0x00000052, - 0x00000052,0x00000052,0x00060050,0x00000007,0x00000055,0x00000053,0x00000053,0x00000053, - 0x0008000c,0x00000007,0x00000056,0x00000001,0x0000002b,0x00000051,0x00000054,0x00000055, - 0x0007000c,0x00000007,0x00000059,0x00000001,0x0000001a,0x00000056,0x00000058,0x0003003e, - 0x00000050,0x00000059,0x0004003d,0x00000007,0x0000005a,0x00000050,0x00060050,0x00000007, - 0x0000005c,0x0000005b,0x0000005b,0x0000005b,0x00050083,0x00000007,0x0000005d,0x0000005a, - 0x0000005c,0x00060050,0x00000007,0x0000005e,0x00000052,0x00000052,0x00000052,0x0007000c, - 0x00000007,0x0000005f,0x00000001,0x00000028,0x0000005d,0x0000005e,0x0004003d,0x00000007, - 0x00000062,0x00000050,0x0005008e,0x00000007,0x00000063,0x00000062,0x00000061,0x00060050, - 0x00000007,0x00000064,0x00000060,0x00000060,0x00000060,0x00050083,0x00000007,0x00000065, - 0x00000064,0x00000063,0x00060050,0x00000007,0x00000067,0x00000066,0x00000066,0x00000066, - 0x0007000c,0x00000007,0x00000068,0x00000001,0x00000028,0x00000065,0x00000067,0x00050088, - 0x00000007,0x00000069,0x0000005f,0x00000068,0x0007000c,0x00000007,0x0000006c,0x00000001, - 0x0000001a,0x00000069,0x0000006b,0x000200fe,0x0000006c,0x00010038,0x00050036,0x00000007, + 0x000200f8,0x0000000f,0x0004003b,0x00000008,0x00000046,0x00000007,0x0004003b,0x00000008, + 0x00000049,0x00000007,0x0004003d,0x00000007,0x00000047,0x0000000d,0x0005008e,0x00000007, + 0x00000048,0x00000047,0x0000002f,0x0003003e,0x00000046,0x00000048,0x0004003d,0x00000007, + 0x0000004a,0x0000000d,0x0007000c,0x00000007,0x0000004d,0x00000001,0x0000001a,0x0000004a, + 0x0000004c,0x0005008e,0x00000007,0x0000004e,0x0000004d,0x00000037,0x00060050,0x00000007, + 0x0000004f,0x00000034,0x00000034,0x00000034,0x00050083,0x00000007,0x00000050,0x0000004e, + 0x0000004f,0x0003003e,0x00000049,0x00000050,0x0004003d,0x00000007,0x00000051,0x00000046, + 0x0004003d,0x00000007,0x00000052,0x00000049,0x0004003d,0x00000007,0x00000055,0x0000000d, + 0x0007000c,0x00000007,0x00000056,0x00000001,0x00000030,0x00000054,0x00000055,0x0008000c, + 0x00000007,0x00000057,0x00000001,0x0000002e,0x00000051,0x00000052,0x00000056,0x000200fe, + 0x00000057,0x00010038,0x00050036,0x00000007,0x00000011,0x00000000,0x00000009,0x00030037, + 0x00000008,0x00000010,0x000200f8,0x00000012,0x0004003b,0x00000008,0x0000005a,0x00000007, + 0x0004003d,0x00000007,0x0000005b,0x00000010,0x00060050,0x00000007,0x0000005e,0x0000005c, + 0x0000005c,0x0000005c,0x00060050,0x00000007,0x0000005f,0x0000005d,0x0000005d,0x0000005d, + 0x0008000c,0x00000007,0x00000060,0x00000001,0x0000002b,0x0000005b,0x0000005e,0x0000005f, + 0x0007000c,0x00000007,0x00000063,0x00000001,0x0000001a,0x00000060,0x00000062,0x0003003e, + 0x0000005a,0x00000063,0x0004003d,0x00000007,0x00000064,0x0000005a,0x00060050,0x00000007, + 0x00000066,0x00000065,0x00000065,0x00000065,0x00050083,0x00000007,0x00000067,0x00000064, + 0x00000066,0x00060050,0x00000007,0x00000068,0x0000005c,0x0000005c,0x0000005c,0x0007000c, + 0x00000007,0x00000069,0x00000001,0x00000028,0x00000067,0x00000068,0x0004003d,0x00000007, + 0x0000006c,0x0000005a,0x0005008e,0x00000007,0x0000006d,0x0000006c,0x0000006b,0x00060050, + 0x00000007,0x0000006e,0x0000006a,0x0000006a,0x0000006a,0x00050083,0x00000007,0x0000006f, + 0x0000006e,0x0000006d,0x00060050,0x00000007,0x00000071,0x00000070,0x00000070,0x00000070, + 0x0007000c,0x00000007,0x00000072,0x00000001,0x00000028,0x0000006f,0x00000071,0x00050088, + 0x00000007,0x00000073,0x00000069,0x00000072,0x0007000c,0x00000007,0x00000076,0x00000001, + 0x0000001a,0x00000073,0x00000075,0x000200fe,0x00000076,0x00010038,0x00050036,0x00000007, 0x00000014,0x00000000,0x00000009,0x00030037,0x00000008,0x00000013,0x000200f8,0x00000015, - 0x0004003b,0x00000008,0x0000006f,0x00000007,0x0004003d,0x00000007,0x00000070,0x00000013, - 0x00060050,0x00000007,0x00000071,0x00000052,0x00000052,0x00000052,0x00060050,0x00000007, - 0x00000072,0x00000053,0x00000053,0x00000053,0x0008000c,0x00000007,0x00000073,0x00000001, - 0x0000002b,0x00000070,0x00000071,0x00000072,0x0007000c,0x00000007,0x00000076,0x00000001, - 0x0000001a,0x00000073,0x00000075,0x0003003e,0x0000006f,0x00000076,0x0004003d,0x00000007, - 0x00000077,0x0000006f,0x0005008e,0x00000007,0x00000078,0x00000077,0x00000060,0x00060050, - 0x00000007,0x00000079,0x0000005b,0x0000005b,0x0000005b,0x00050081,0x00000007,0x0000007a, - 0x00000079,0x00000078,0x0004003d,0x00000007,0x0000007b,0x0000006f,0x0005008e,0x00000007, - 0x0000007c,0x0000007b,0x00000061,0x00060050,0x00000007,0x0000007d,0x00000053,0x00000053, - 0x00000053,0x00050081,0x00000007,0x0000007e,0x0000007d,0x0000007c,0x00050088,0x00000007, - 0x0000007f,0x0000007a,0x0000007e,0x0007000c,0x00000007,0x00000082,0x00000001,0x0000001a, - 0x0000007f,0x00000081,0x000200fe,0x00000082,0x00010038,0x00050036,0x00000006,0x0000001a, + 0x0004003b,0x00000008,0x00000079,0x00000007,0x0004003d,0x00000007,0x0000007a,0x00000013, + 0x00060050,0x00000007,0x0000007b,0x0000005c,0x0000005c,0x0000005c,0x00060050,0x00000007, + 0x0000007c,0x0000005d,0x0000005d,0x0000005d,0x0008000c,0x00000007,0x0000007d,0x00000001, + 0x0000002b,0x0000007a,0x0000007b,0x0000007c,0x0007000c,0x00000007,0x00000080,0x00000001, + 0x0000001a,0x0000007d,0x0000007f,0x0003003e,0x00000079,0x00000080,0x0004003d,0x00000007, + 0x00000081,0x00000079,0x0005008e,0x00000007,0x00000082,0x00000081,0x0000006a,0x00060050, + 0x00000007,0x00000083,0x00000065,0x00000065,0x00000065,0x00050081,0x00000007,0x00000084, + 0x00000083,0x00000082,0x0004003d,0x00000007,0x00000085,0x00000079,0x0005008e,0x00000007, + 0x00000086,0x00000085,0x0000006b,0x00060050,0x00000007,0x00000087,0x0000005d,0x0000005d, + 0x0000005d,0x00050081,0x00000007,0x00000088,0x00000087,0x00000086,0x00050088,0x00000007, + 0x00000089,0x00000084,0x00000088,0x0007000c,0x00000007,0x0000008c,0x00000001,0x0000001a, + 0x00000089,0x0000008b,0x000200fe,0x0000008c,0x00010038,0x00050036,0x00000006,0x0000001a, 0x00000000,0x00000017,0x00030037,0x00000016,0x00000018,0x00030037,0x00000016,0x00000019, - 0x000200f8,0x0000001b,0x0004003b,0x00000016,0x0000008c,0x00000007,0x0004003b,0x00000016, - 0x00000091,0x00000007,0x0004003d,0x00000006,0x00000085,0x00000018,0x000500bc,0x0000001e, - 0x00000087,0x00000085,0x00000086,0x000300f7,0x00000089,0x00000000,0x000400fa,0x00000087, - 0x00000088,0x00000089,0x000200f8,0x00000088,0x0004003d,0x00000006,0x0000008a,0x00000018, - 0x000200fe,0x0000008a,0x000200f8,0x00000089,0x0004003d,0x00000006,0x0000008d,0x00000019, - 0x00050083,0x00000006,0x0000008e,0x0000008d,0x00000086,0x0007000c,0x00000006,0x00000090, - 0x00000001,0x00000028,0x0000008e,0x0000008f,0x0003003e,0x0000008c,0x00000090,0x0004003d, - 0x00000006,0x00000092,0x0000008c,0x00050088,0x00000006,0x00000094,0x00000092,0x00000093, - 0x0007000c,0x00000006,0x00000096,0x00000001,0x00000028,0x00000094,0x00000095,0x0003003e, - 0x00000091,0x00000096,0x0004003d,0x00000006,0x00000097,0x00000018,0x00050083,0x00000006, - 0x00000098,0x00000097,0x00000086,0x0004007f,0x00000006,0x00000099,0x00000098,0x0004003d, - 0x00000006,0x0000009a,0x00000091,0x00050088,0x00000006,0x0000009b,0x00000099,0x0000009a, - 0x0006000c,0x00000006,0x0000009c,0x00000001,0x0000001b,0x0000009b,0x00050083,0x00000006, - 0x0000009d,0x00000053,0x0000009c,0x00050085,0x00000006,0x0000009e,0x00000095,0x0000009d, - 0x00050081,0x00000006,0x0000009f,0x00000086,0x0000009e,0x000200fe,0x0000009f,0x00010038, + 0x000200f8,0x0000001b,0x0004003b,0x00000016,0x00000096,0x00000007,0x0004003b,0x00000016, + 0x0000009b,0x00000007,0x0004003d,0x00000006,0x0000008f,0x00000018,0x000500bc,0x00000024, + 0x00000091,0x0000008f,0x00000090,0x000300f7,0x00000093,0x00000000,0x000400fa,0x00000091, + 0x00000092,0x00000093,0x000200f8,0x00000092,0x0004003d,0x00000006,0x00000094,0x00000018, + 0x000200fe,0x00000094,0x000200f8,0x00000093,0x0004003d,0x00000006,0x00000097,0x00000019, + 0x00050083,0x00000006,0x00000098,0x00000097,0x00000090,0x0007000c,0x00000006,0x0000009a, + 0x00000001,0x00000028,0x00000098,0x00000099,0x0003003e,0x00000096,0x0000009a,0x0004003d, + 0x00000006,0x0000009c,0x00000096,0x00050088,0x00000006,0x0000009e,0x0000009c,0x0000009d, + 0x0007000c,0x00000006,0x000000a0,0x00000001,0x00000028,0x0000009e,0x0000009f,0x0003003e, + 0x0000009b,0x000000a0,0x0004003d,0x00000006,0x000000a1,0x00000018,0x00050083,0x00000006, + 0x000000a2,0x000000a1,0x00000090,0x0004007f,0x00000006,0x000000a3,0x000000a2,0x0004003d, + 0x00000006,0x000000a4,0x0000009b,0x00050088,0x00000006,0x000000a5,0x000000a3,0x000000a4, + 0x0006000c,0x00000006,0x000000a6,0x00000001,0x0000001b,0x000000a5,0x00050083,0x00000006, + 0x000000a7,0x0000005d,0x000000a6,0x00050085,0x00000006,0x000000a8,0x0000009f,0x000000a7, + 0x00050081,0x00000006,0x000000a9,0x00000090,0x000000a8,0x000200fe,0x000000a9,0x00010038, 0x00050036,0x0000001e,0x00000021,0x00000000,0x0000001f,0x00030037,0x0000001d,0x00000020, - 0x000200f8,0x00000022,0x0004003b,0x00000016,0x000000a2,0x00000007,0x0004003b,0x00000016, - 0x000000b0,0x00000007,0x0004003b,0x00000016,0x000000b4,0x00000007,0x0004003b,0x000000b8, - 0x000000b9,0x00000007,0x0004003b,0x000000cc,0x000000cd,0x00000007,0x0004003b,0x00000016, - 0x000000f5,0x00000007,0x00060041,0x000000ad,0x000000ae,0x000000a9,0x000000ab,0x000000ac, - 0x0004003d,0x00000006,0x000000af,0x000000ae,0x0003003e,0x000000a2,0x000000af,0x0004003d, - 0x00000006,0x000000b1,0x000000a2,0x0005008d,0x00000006,0x000000b3,0x000000b1,0x000000b2, - 0x0003003e,0x000000b0,0x000000b3,0x0004003d,0x00000006,0x000000b5,0x000000a2,0x00050088, - 0x00000006,0x000000b6,0x000000b5,0x000000b2,0x0006000c,0x00000006,0x000000b7,0x00000001, - 0x00000008,0x000000b6,0x0003003e,0x000000b4,0x000000b7,0x0003003e,0x000000b9,0x000000ba, - 0x000200f9,0x000000bb,0x000200f8,0x000000bb,0x000400f6,0x000000bd,0x000000be,0x00000000, - 0x000200f9,0x000000bf,0x000200f8,0x000000bf,0x0004003d,0x000000aa,0x000000c0,0x000000b9, - 0x000500b1,0x0000001e,0x000000c2,0x000000c0,0x000000c1,0x000400fa,0x000000c2,0x000000bc, - 0x000000bd,0x000200f8,0x000000bc,0x0004003d,0x000000aa,0x000000c3,0x000000b9,0x0004006f, - 0x00000006,0x000000c4,0x000000c3,0x0004003d,0x00000006,0x000000c5,0x000000b0,0x00050083, - 0x00000006,0x000000c7,0x000000c5,0x000000c6,0x000500be,0x0000001e,0x000000c8,0x000000c4, - 0x000000c7,0x000300f7,0x000000ca,0x00000000,0x000400fa,0x000000c8,0x000000c9,0x000000ca, - 0x000200f8,0x000000c9,0x000200f9,0x000000bd,0x000200f8,0x000000ca,0x0004003d,0x000000aa, - 0x000000cf,0x000000b9,0x00060041,0x000000d0,0x000000d1,0x000000a9,0x000000ce,0x000000cf, - 0x0004003d,0x000000a3,0x000000d2,0x000000d1,0x0003003e,0x000000cd,0x000000d2,0x00050041, - 0x00000016,0x000000d4,0x00000020,0x000000d3,0x0004003d,0x00000006,0x000000d5,0x000000d4, - 0x00050041,0x00000016,0x000000d6,0x000000cd,0x000000d3,0x0004003d,0x00000006,0x000000d7, - 0x000000d6,0x000500be,0x0000001e,0x000000d8,0x000000d5,0x000000d7,0x000300f7,0x000000da, - 0x00000000,0x000400fa,0x000000d8,0x000000d9,0x000000da,0x000200f8,0x000000d9,0x00050041, - 0x00000016,0x000000dc,0x00000020,0x000000db,0x0004003d,0x00000006,0x000000dd,0x000000dc, - 0x00050041,0x00000016,0x000000de,0x000000cd,0x000000db,0x0004003d,0x00000006,0x000000df, - 0x000000de,0x000500be,0x0000001e,0x000000e0,0x000000dd,0x000000df,0x000200f9,0x000000da, - 0x000200f8,0x000000da,0x000700f5,0x0000001e,0x000000e1,0x000000d8,0x000000ca,0x000000e0, - 0x000000d9,0x000300f7,0x000000e3,0x00000000,0x000400fa,0x000000e1,0x000000e2,0x000000e3, - 0x000200f8,0x000000e2,0x00050041,0x00000016,0x000000e4,0x00000020,0x000000d3,0x0004003d, - 0x00000006,0x000000e5,0x000000e4,0x00050041,0x00000016,0x000000e7,0x000000cd,0x000000e6, - 0x0004003d,0x00000006,0x000000e8,0x000000e7,0x000500b8,0x0000001e,0x000000e9,0x000000e5, - 0x000000e8,0x000200f9,0x000000e3,0x000200f8,0x000000e3,0x000700f5,0x0000001e,0x000000ea, - 0x000000e1,0x000000da,0x000000e9,0x000000e2,0x000300f7,0x000000ec,0x00000000,0x000400fa, - 0x000000ea,0x000000eb,0x000000ec,0x000200f8,0x000000eb,0x00050041,0x00000016,0x000000ed, - 0x00000020,0x000000db,0x0004003d,0x00000006,0x000000ee,0x000000ed,0x00050041,0x00000016, - 0x000000ef,0x000000cd,0x000000ac,0x0004003d,0x00000006,0x000000f0,0x000000ef,0x000500b8, - 0x0000001e,0x000000f1,0x000000ee,0x000000f0,0x000200f9,0x000000ec,0x000200f8,0x000000ec, - 0x000700f5,0x0000001e,0x000000f2,0x000000ea,0x000000e3,0x000000f1,0x000000eb,0x000300f7, - 0x000000f4,0x00000000,0x000400fa,0x000000f2,0x000000f3,0x000000f4,0x000200f8,0x000000f3, - 0x0004003d,0x00000006,0x000000f6,0x000000b4,0x0004003d,0x000000aa,0x000000f7,0x000000b9, - 0x0004006f,0x00000006,0x000000f8,0x000000f7,0x0006000c,0x00000006,0x000000f9,0x00000001, - 0x0000001d,0x000000f8,0x00050088,0x00000006,0x000000fa,0x000000f6,0x000000f9,0x0006000c, - 0x00000006,0x000000fb,0x00000001,0x00000008,0x000000fa,0x0005008d,0x00000006,0x000000fd, - 0x000000fb,0x000000fc,0x0003003e,0x000000f5,0x000000fd,0x0004003d,0x00000006,0x000000fe, - 0x000000f5,0x000500ba,0x0000001e,0x000000ff,0x000000fe,0x000000c6,0x000200fe,0x000000ff, - 0x000200f8,0x000000f4,0x000200f9,0x000000be,0x000200f8,0x000000be,0x0004003d,0x000000aa, - 0x00000101,0x000000b9,0x00050080,0x000000aa,0x00000102,0x00000101,0x000000ab,0x0003003e, - 0x000000b9,0x00000102,0x000200f9,0x000000bb,0x000200f8,0x000000bd,0x000200fe,0x00000103, - 0x00010038 + 0x000200f8,0x00000022,0x0004003b,0x00000016,0x000000ac,0x00000007,0x0004003b,0x00000023, + 0x000000bd,0x00000007,0x0004003b,0x000000d0,0x000000d1,0x00000007,0x0004003b,0x0000001d, + 0x000000d7,0x00000007,0x0004003b,0x0000001d,0x000000e5,0x00000007,0x00060041,0x000000b8, + 0x000000b9,0x000000b6,0x000000b7,0x000000b2,0x0004003d,0x00000006,0x000000ba,0x000000b9, + 0x0005008d,0x00000006,0x000000bc,0x000000ba,0x000000bb,0x0003003e,0x000000ac,0x000000bc, + 0x0003003e,0x000000bd,0x000000be,0x000200f9,0x000000bf,0x000200f8,0x000000bf,0x000400f6, + 0x000000c1,0x000000c2,0x00000000,0x000200f9,0x000000c3,0x000200f8,0x000000c3,0x0004003d, + 0x0000001e,0x000000c4,0x000000bd,0x000500b1,0x00000024,0x000000c6,0x000000c4,0x000000c5, + 0x000400fa,0x000000c6,0x000000c0,0x000000c1,0x000200f8,0x000000c0,0x0004003d,0x0000001e, + 0x000000c7,0x000000bd,0x0004006f,0x00000006,0x000000c8,0x000000c7,0x0004003d,0x00000006, + 0x000000c9,0x000000ac,0x00050083,0x00000006,0x000000cb,0x000000c9,0x000000ca,0x000500be, + 0x00000024,0x000000cc,0x000000c8,0x000000cb,0x000300f7,0x000000ce,0x00000000,0x000400fa, + 0x000000cc,0x000000cd,0x000000ce,0x000200f8,0x000000cd,0x000200f9,0x000000c1,0x000200f8, + 0x000000ce,0x0004003d,0x0000001e,0x000000d3,0x000000bd,0x00060041,0x000000d4,0x000000d5, + 0x000000b6,0x000000d2,0x000000d3,0x0004003d,0x000000af,0x000000d6,0x000000d5,0x0003003e, + 0x000000d1,0x000000d6,0x00050041,0x000000d9,0x000000da,0x000000d1,0x000000d8,0x0004003d, + 0x000000ae,0x000000db,0x000000da,0x000500c7,0x000000ae,0x000000dd,0x000000db,0x000000dc, + 0x00040070,0x00000006,0x000000de,0x000000dd,0x00050041,0x000000d9,0x000000df,0x000000d1, + 0x000000d8,0x0004003d,0x000000ae,0x000000e0,0x000000df,0x000500c2,0x000000ae,0x000000e2, + 0x000000e0,0x000000e1,0x00040070,0x00000006,0x000000e3,0x000000e2,0x00050050,0x0000001c, + 0x000000e4,0x000000de,0x000000e3,0x0003003e,0x000000d7,0x000000e4,0x00050041,0x000000d9, + 0x000000e7,0x000000d1,0x000000e6,0x0004003d,0x000000ae,0x000000e8,0x000000e7,0x000500c7, + 0x000000ae,0x000000e9,0x000000e8,0x000000dc,0x00040070,0x00000006,0x000000ea,0x000000e9, + 0x00050041,0x000000d9,0x000000eb,0x000000d1,0x000000e6,0x0004003d,0x000000ae,0x000000ec, + 0x000000eb,0x000500c2,0x000000ae,0x000000ed,0x000000ec,0x000000e1,0x00040070,0x00000006, + 0x000000ee,0x000000ed,0x00050050,0x0000001c,0x000000ef,0x000000ea,0x000000ee,0x0003003e, + 0x000000e5,0x000000ef,0x00050041,0x00000016,0x000000f0,0x00000020,0x000000d8,0x0004003d, + 0x00000006,0x000000f1,0x000000f0,0x00050041,0x00000016,0x000000f2,0x000000d7,0x000000d8, + 0x0004003d,0x00000006,0x000000f3,0x000000f2,0x000500be,0x00000024,0x000000f4,0x000000f1, + 0x000000f3,0x000300f7,0x000000f6,0x00000000,0x000400fa,0x000000f4,0x000000f5,0x000000f6, + 0x000200f8,0x000000f5,0x00050041,0x00000016,0x000000f7,0x00000020,0x000000e6,0x0004003d, + 0x00000006,0x000000f8,0x000000f7,0x00050041,0x00000016,0x000000f9,0x000000d7,0x000000e6, + 0x0004003d,0x00000006,0x000000fa,0x000000f9,0x000500be,0x00000024,0x000000fb,0x000000f8, + 0x000000fa,0x000200f9,0x000000f6,0x000200f8,0x000000f6,0x000700f5,0x00000024,0x000000fc, + 0x000000f4,0x000000ce,0x000000fb,0x000000f5,0x000300f7,0x000000fe,0x00000000,0x000400fa, + 0x000000fc,0x000000fd,0x000000fe,0x000200f8,0x000000fd,0x00050041,0x00000016,0x000000ff, + 0x00000020,0x000000d8,0x0004003d,0x00000006,0x00000100,0x000000ff,0x00050041,0x00000016, + 0x00000101,0x000000e5,0x000000d8,0x0004003d,0x00000006,0x00000102,0x00000101,0x000500b8, + 0x00000024,0x00000103,0x00000100,0x00000102,0x000200f9,0x000000fe,0x000200f8,0x000000fe, + 0x000700f5,0x00000024,0x00000104,0x000000fc,0x000000f6,0x00000103,0x000000fd,0x000300f7, + 0x00000106,0x00000000,0x000400fa,0x00000104,0x00000105,0x00000106,0x000200f8,0x00000105, + 0x00050041,0x00000016,0x00000107,0x00000020,0x000000e6,0x0004003d,0x00000006,0x00000108, + 0x00000107,0x00050041,0x00000016,0x00000109,0x000000e5,0x000000e6,0x0004003d,0x00000006, + 0x0000010a,0x00000109,0x000500b8,0x00000024,0x0000010b,0x00000108,0x0000010a,0x000200f9, + 0x00000106,0x000200f8,0x00000106,0x000700f5,0x00000024,0x0000010c,0x00000104,0x000000fe, + 0x0000010b,0x00000105,0x000300f7,0x0000010e,0x00000000,0x000400fa,0x0000010c,0x0000010d, + 0x0000010e,0x000200f8,0x0000010d,0x0004003d,0x0000001e,0x0000010f,0x000000bd,0x000200fe, + 0x0000010f,0x000200f8,0x0000010e,0x000200f9,0x000000c2,0x000200f8,0x000000c2,0x0004003d, + 0x0000001e,0x00000111,0x000000bd,0x00050080,0x0000001e,0x00000112,0x00000111,0x000000b7, + 0x0003003e,0x000000bd,0x00000112,0x000200f9,0x000000bf,0x000200f8,0x000000c1,0x000200fe, + 0x00000113,0x00010038,0x00050036,0x00000024,0x00000028,0x00000000,0x00000025,0x00030037, + 0x00000016,0x00000026,0x00030037,0x00000023,0x00000027,0x000200f8,0x00000029,0x0004003d, + 0x0000001e,0x00000116,0x00000027,0x000500af,0x00000024,0x00000117,0x00000116,0x000000be, + 0x000300f7,0x00000119,0x00000000,0x000400fa,0x00000117,0x00000118,0x00000119,0x000200f8, + 0x00000118,0x0004003d,0x00000006,0x0000011a,0x00000026,0x0004003d,0x0000001e,0x0000011b, + 0x00000027,0x0004006f,0x00000006,0x0000011c,0x0000011b,0x0006000c,0x00000006,0x0000011d, + 0x00000001,0x0000001d,0x0000011c,0x00050088,0x00000006,0x0000011e,0x0000011a,0x0000011d, + 0x0006000c,0x00000006,0x0000011f,0x00000001,0x00000008,0x0000011e,0x0005008d,0x00000006, + 0x00000121,0x0000011f,0x00000120,0x000500ba,0x00000024,0x00000122,0x00000121,0x000000ca, + 0x000200f9,0x00000119,0x000200f8,0x00000119,0x000700f5,0x00000024,0x00000123,0x00000117, + 0x00000029,0x00000122,0x00000118,0x000200fe,0x00000123,0x00010038,0x00050036,0x00000007, + 0x0000002b,0x00000000,0x00000009,0x00030037,0x00000008,0x0000002a,0x000200f8,0x0000002c, + 0x0004003b,0x00000008,0x00000126,0x00000007,0x0004003b,0x00000008,0x0000012b,0x00000007, + 0x0004003b,0x00000008,0x00000130,0x00000007,0x00070041,0x000000b8,0x00000128,0x000000b6, + 0x00000127,0x000000b7,0x000000b2,0x0004003d,0x00000006,0x00000129,0x00000128,0x000500ba, + 0x00000024,0x0000012a,0x00000129,0x000000ca,0x000300f7,0x0000012d,0x00000000,0x000400fa, + 0x0000012a,0x0000012c,0x0000012f,0x000200f8,0x0000012c,0x0004003d,0x00000007,0x0000012e, + 0x0000002a,0x0003003e,0x0000012b,0x0000012e,0x000200f9,0x0000012d,0x000200f8,0x0000012f, + 0x0004003d,0x00000007,0x00000131,0x0000002a,0x0003003e,0x00000130,0x00000131,0x00050039, + 0x00000007,0x00000132,0x00000011,0x00000130,0x0003003e,0x0000012b,0x00000132,0x000200f9, + 0x0000012d,0x000200f8,0x0000012d,0x0004003d,0x00000007,0x00000133,0x0000012b,0x0003003e, + 0x00000126,0x00000133,0x00060041,0x00000134,0x00000135,0x000000b6,0x00000127,0x000000be, + 0x0004003d,0x000000ad,0x00000136,0x00000135,0x0008004f,0x00000007,0x00000137,0x00000136, + 0x00000136,0x00000000,0x00000001,0x00000002,0x0004003d,0x00000007,0x00000138,0x00000126, + 0x00050094,0x00000006,0x00000139,0x00000137,0x00000138,0x00060041,0x00000134,0x0000013a, + 0x000000b6,0x00000127,0x000000b7,0x0004003d,0x000000ad,0x0000013b,0x0000013a,0x0008004f, + 0x00000007,0x0000013c,0x0000013b,0x0000013b,0x00000000,0x00000001,0x00000002,0x0004003d, + 0x00000007,0x0000013d,0x00000126,0x00050094,0x00000006,0x0000013e,0x0000013c,0x0000013d, + 0x00060041,0x00000134,0x0000013f,0x000000b6,0x00000127,0x000000d2,0x0004003d,0x000000ad, + 0x00000140,0x0000013f,0x0008004f,0x00000007,0x00000141,0x00000140,0x00000140,0x00000000, + 0x00000001,0x00000002,0x0004003d,0x00000007,0x00000142,0x00000126,0x00050094,0x00000006, + 0x00000143,0x00000141,0x00000142,0x00060050,0x00000007,0x00000144,0x00000139,0x0000013e, + 0x00000143,0x00070041,0x000000b8,0x00000145,0x000000b6,0x00000127,0x000000d2,0x000000b2, + 0x0004003d,0x00000006,0x00000146,0x00000145,0x0005008e,0x00000007,0x00000147,0x00000144, + 0x00000146,0x000200fe,0x00000147,0x00010038 }; diff --git a/app/src/main/cpp/waylandcomp/src/sc_layer.c b/app/src/main/cpp/waylandcomp/src/sc_layer.c index c760d91c22..05b201b2e5 100644 --- a/app/src/main/cpp/waylandcomp/src/sc_layer.c +++ b/app/src/main/cpp/waylandcomp/src/sc_layer.c @@ -3,6 +3,7 @@ #include "ahb_swapchain.h" #include "droiddeck_color.h" #include "vk_present.h" +#include "framegen_bridge.h" #include #include #include @@ -64,6 +65,8 @@ static struct { void (*setHdrMetadata_cta861_3)(ASurfaceTransaction *, ASurfaceControl *, const struct droiddeck_hdr_cta861_3 *); const void *(*getNativeHandle)(const AHardwareBuffer *); void (*setDesiredHdrHeadroom)(ASurfaceTransaction *, ASurfaceControl *, float); + void (*setEnableBackPressure)(ASurfaceTransaction *, ASurfaceControl *, bool); + void (*setDesiredPresentTime)(ASurfaceTransaction *, int64_t); int state; } api; @@ -105,6 +108,8 @@ static int load_api(void) { SYM(setHdrMetadata_smpte2086, "ASurfaceTransaction_setHdrMetadata_smpte2086"); SYM(setHdrMetadata_cta861_3, "ASurfaceTransaction_setHdrMetadata_cta861_3"); SYM(setDesiredHdrHeadroom, "ASurfaceTransaction_setDesiredHdrHeadroom"); + SYM(setEnableBackPressure, "ASurfaceTransaction_setEnableBackPressure"); + SYM(setDesiredPresentTime, "ASurfaceTransaction_setDesiredPresentTime"); #undef SYM if (!api.createFromWindow || !api.release || !api.txCreate || !api.txDelete || !api.txApply || !api.setBuffer || !api.setZOrder || !api.setVisibility || !api.setGeometry || @@ -134,7 +139,7 @@ void sc_layer_set_frame_rate(float fps) { } -#define POOL_MAX 5 +#define POOL_MAX 8 struct slot { AHardwareBuffer *ahb; @@ -183,6 +188,12 @@ static int g_layers_ready; static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER; static int g_pending_cb; static unsigned g_stat_layer_frames; +static pthread_mutex_t g_timeline_lock = PTHREAD_MUTEX_INITIALIZER; +static int64_t g_timeline_present_ns, g_timeline_deadline_ns, g_timeline_period_ns; +static int g_timeline_late; +static int64_t g_cadence_seen_ns, g_cadence_gap_ns, g_cadence_target_ns; +static int g_group_frames = 1, g_group_index; +static unsigned g_stat_aimed_next, g_stat_aimed_later, g_stat_aimed_even; static int g_two_logged; static AHardwareBuffer *g_blank; static ASurfaceControl *g_base_sc; @@ -219,6 +230,58 @@ static int64_t now_ns(void) { return (int64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec; } +void sc_layer_frame_timeline(int64_t present_ns, int64_t deadline_ns, int64_t period_ns) { + pthread_mutex_lock(&g_timeline_lock); + g_timeline_present_ns = present_ns; + g_timeline_deadline_ns = deadline_ns; + g_timeline_period_ns = period_ns; + pthread_mutex_unlock(&g_timeline_lock); +} + +static int64_t cadence_target(int64_t now, int64_t earliest, int64_t period) { + const int64_t gap = now - g_cadence_seen_ns; + g_cadence_seen_ns = now; + if (gap <= 0 || gap > 8 * period) { + g_cadence_gap_ns = 0; + g_cadence_target_ns = earliest; + return earliest; + } + g_cadence_gap_ns = g_cadence_gap_ns ? (g_cadence_gap_ns * 15 + gap) / 16 : gap; + const int64_t steps = (g_cadence_gap_ns + period / 2) / period; + const int64_t even = g_cadence_target_ns + steps * period; + int64_t target = earliest; + if (steps >= 1 && llabs(g_cadence_gap_ns - steps * period) < period / 8 && + even > earliest + period / 2 && even < earliest + steps * period + period / 2) { + target = even; + g_stat_aimed_even++; + } + g_cadence_target_ns = target; + return target; +} + +static void apply_present_time(ASurfaceTransaction *tx, int game) { + if (!api.setDesiredPresentTime) return; + pthread_mutex_lock(&g_timeline_lock); + const int64_t present = g_timeline_present_ns, deadline = g_timeline_deadline_ns, period = g_timeline_period_ns; + pthread_mutex_unlock(&g_timeline_lock); + const int64_t now = now_ns(); + if (period <= 0 || now - deadline > 4 * period) return; + int64_t ahead = now > deadline ? (now - deadline + period - 1) / period : -((deadline - now) / period); + const int64_t slack = deadline + ahead * period - now; + g_timeline_late = slack < (g_timeline_late ? period * 5 / 8 : period / 8); + if (g_timeline_late) { ahead++; g_stat_aimed_later++; } else g_stat_aimed_next++; + int64_t target = present + ahead * period; + if (game && g_group_index > 0) { + int64_t steps = (g_group_index * g_cadence_gap_ns / g_group_frames + period / 2) / period; + if (steps < g_group_index) steps = g_group_index; + if (target < g_cadence_target_ns + steps * period) target = g_cadence_target_ns + steps * period; + } else if (game) { + target = cadence_target(now, target, period); + } + if (game && g_group_frames > 1 && ++g_group_index >= g_group_frames) { g_group_index = 0; g_group_frames = 1; } + api.setDesiredPresentTime(tx, target - period / 2); +} + static void on_complete(void *context, ASurfaceTransactionStats *stats) { struct complete_ctx *ctx = context; pthread_mutex_lock(&g_lock); @@ -401,10 +464,22 @@ static void describe_handle(const struct droiddeck_native_handle *h, char *out, o += (size_t)snprintf(out + o, n - o, " %#x", (unsigned)h->data[h->numFds + i]); } +static int handle_fd(const struct droiddeck_native_handle *h, off_t need, int *which) { + for (int i = 0; h && i < h->numFds; i++) { + off_t sz = lseek(h->data[i], 0, SEEK_END); + if (sz >= 0) lseek(h->data[i], 0, SEEK_SET); + if (sz >= need) { if (which) *which = i; return h->data[i]; } + } + return -1; +} + +int sc_layer_ahb_fd(AHardwareBuffer *ahb, uint64_t need) { + return load_api() == 0 ? handle_fd(api.getNativeHandle(ahb), (off_t)need, NULL) : -1; +} + static int g_alloc_failed; enum { TIER_UBWC, TIER_PLAIN, TIER_LINEAR }; -#define DROIDDECK_AHB_USAGE_VENDOR_UBWC (1ULL << 28) static const char *tier_name(int tier) { return tier == TIER_UBWC ? "asked for UBWC" : tier == TIER_PLAIN ? "no UBWC request" : "linear by request (CPU bit)"; @@ -419,7 +494,7 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm .format = fmt, .usage = AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY | - (tier == TIER_UBWC ? DROIDDECK_AHB_USAGE_VENDOR_UBWC : 0) | + (tier == TIER_UBWC ? SC_LAYER_AHB_USAGE_VENDOR_UBWC : 0) | (tier == TIER_LINEAR ? AHARDWAREBUFFER_USAGE_CPU_READ_RARELY : 0)}; AHardwareBuffer *ahb = NULL; if (AHardwareBuffer_allocate(&d, &ahb) != 0 || !ahb) { @@ -459,13 +534,8 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm path = "AHardwareBuffer"; img = vkp_image_import_ahb(ahb, info, sizeof(info)); if (!img && tier == TIER_LINEAR) { - const off_t need = (off_t)got.stride * 4 * h; - int fd = -1, which = -1; - for (int i = 0; nh && i < nh->numFds; i++) { - off_t sz = lseek(nh->data[i], 0, SEEK_END); - if (sz >= 0) lseek(nh->data[i], 0, SEEK_SET); - if (sz >= need) { fd = nh->data[i]; which = i; break; } - } + int which = -1; + int fd = handle_fd(nh, (off_t)got.stride * 4 * h, &which); if (fd < 0 && nh && nh->numFds > 0) { fd = nh->data[0]; which = 0; } mod = MOD_LINEAR; path = "linear dma-buf"; @@ -506,16 +576,27 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm return -1; } -static int fence_signalled(int fd) { +static int fence_wait(int fd, int timeout_ms) { struct pollfd p = {.fd = fd, .events = POLLIN}; int r; - do { r = poll(&p, 1, 0); } while (r < 0 && errno == EINTR); - return r > 0; + do { r = poll(&p, 1, timeout_ms); } while (r < 0 && errno == EINTR); + return r; +} + +static int fence_signalled(int fd) { + return fence_wait(fd, 0) > 0; +} + +static void slot_keep_fence(struct slot *s, int fd) { + pthread_mutex_lock(&g_lock); + if (s->release_fd < 0) s->release_fd = fd; else close(fd); + pthread_mutex_unlock(&g_lock); } static int take_free_slot(struct layer *l, int w, int h, uint32_t fmt, int *wait_fd) { int idx = -1, pending = -1, fd = -1; *wait_fd = -1; + g_alloc_failed = 0; pthread_mutex_lock(&g_lock); for (int i = 0; i < l->pool_n; i++) { if (i == l->cur_slot || l->slots[i].busy) continue; @@ -535,15 +616,7 @@ static int take_free_slot(struct layer *l, int w, int h, uint32_t fmt, int *wait memset(s, 0, sizeof(*s)); s->release_fd = -1; } if (fd >= 0 && !vkp_can_wait_sync_fd()) { - struct pollfd p = {.fd = fd, .events = POLLIN}; - int r; - do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR); - if (r == 0) { - pthread_mutex_lock(&g_lock); - if (s->release_fd < 0) s->release_fd = fd; else close(fd); - pthread_mutex_unlock(&g_lock); - return -1; - } + if (fence_wait(fd, 100) == 0) { slot_keep_fence(s, fd); return -1; } close(fd); fd = -1; } @@ -558,6 +631,8 @@ static int take_free_slot(struct layer *l, int w, int h, uint32_t fmt, int *wait int sc_layer_available(void) { return load_api() == 0; } +int sc_layer_queues(void) { return load_api() == 0 && api.setEnableBackPressure != NULL; } + void sc_layer_probe_dmabuf_fd(int fd) { static int done; if (done || fd < 0) return; @@ -595,9 +670,10 @@ static int ensure_sc(struct layer *l) { return 0; } -static int layer_geometry(int w, int h, int scene_w, int scene_h, int r[8]) { +static int layer_geometry(int w, int h, int scene_w, int scene_h, const struct vkp_draw *draw, int r[8]) { if (vkp_update_map(scene_w, scene_h) != 0) return -1; - return vkp_map_rect(w, h, scene_w, scene_h, r) ? 1 : 0; + if (draw) return vkp_map_draw(draw, r) ? 1 : 0; + return vkp_map_rect(w, h, (const int[4]){0, 0, scene_w, scene_h}, r) ? 1 : 0; } static ARect g_game_src, g_game_dst; @@ -757,6 +833,7 @@ static int present_slot(struct layer *l, int idx, const int r[8], const struct d ASurfaceControl *old = swap_sc_begin(l); if (old) api.setZOrder(tx, l->sc, l->z); api.setBuffer(tx, l->sc, s->ahb, -1); + if (api.setEnableBackPressure) api.setEnableBackPressure(tx, l->sc, true); api.setBufferTransparency(tx, l->sc, translucent ? ASC_TRANSPARENCY_TRANSLUCENT : ASC_TRANSPARENCY_OPAQUE); apply_geometry(tx, l, r); @@ -769,6 +846,7 @@ static int present_slot(struct layer *l, int idx, const int r[8], const struct d pthread_mutex_lock(&g_lock); s->busy = 1; pthread_mutex_unlock(&g_lock); + apply_present_time(tx, l == &g_layers[SC_LAYER_GAME]); api.txApply(tx); api.txDelete(tx); l->cur_slot = idx; @@ -799,11 +877,12 @@ unsigned sc_layer_drops_take(void) { } int sc_layer_present_ahb(AHardwareBuffer *ahb, int w, int h, int acquire_fd, void *token, int scene_w, int scene_h, + const struct vkp_draw *draw, const struct droiddeck_color *color, uint32_t ahb_format) { struct layer *l = layer_of(SC_LAYER_GAME); int r[8]; if (!ahb || !token || ensure_sc(l) != 0) goto unavailable; - int g = layer_geometry(w, h, scene_w, scene_h, r); + int g = layer_geometry(w, h, scene_w, scene_h, draw, r); if (g < 0) goto unavailable; if (g == 0) { if (acquire_fd >= 0) close(acquire_fd); sc_layer_hide(); return 1; } if (token == l->cur_token && l->shown && !l->recreate_pending) { @@ -821,6 +900,7 @@ int sc_layer_present_ahb(AHardwareBuffer *ahb, int w, int h, int acquire_fd, voi ASurfaceControl *old = swap_sc_begin(l); if (old) api.setZOrder(tx, l->sc, l->z); api.setBuffer(tx, l->sc, ahb, acquire_fd); + if (api.setEnableBackPressure) api.setEnableBackPressure(tx, l->sc, true); api.setBufferTransparency(tx, l->sc, ASC_TRANSPARENCY_OPAQUE); apply_geometry(tx, l, r); apply_frame_rate(tx, l); @@ -834,6 +914,7 @@ int sc_layer_present_ahb(AHardwareBuffer *ahb, int w, int h, int acquire_fd, voi l->ds_applied = -1; l->md_applied = 0; l->hr_applied = -1.0f; return -1; } + apply_present_time(tx, 1); api.txApply(tx); api.txDelete(tx); l->cur_slot = -1; @@ -848,12 +929,13 @@ unavailable: return -1; } -int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct droiddeck_color *color) { +int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct vkp_draw *draw, + const struct droiddeck_color *color) { struct layer *l = layer_of(SC_LAYER_GAME); if (!src || ensure_sc(l) != 0) return -1; int sw = vkp_image_width(src), sh = vkp_image_height(src); int r[8]; - int g = layer_geometry(sw, sh, scene_w, scene_h, r); + int g = layer_geometry(sw, sh, scene_w, scene_h, draw, r); if (g < 0) return -1; if (g == 0) { sc_layer_hide(); return 0; } @@ -879,10 +961,10 @@ int sc_layer_present_pass(const struct vkp_draw *draws, int n, int scene_w, int if (!draws || n <= 0 || ensure_sc(l) != 0) return -1; if (vkp_update_map(scene_w, scene_h) != 0) return -1; if (vkp_pass_begin(scene_w, scene_h, draws, n, &rw, &rh) != 0) return -1; - if (!vkp_map_rect(rw, rh, scene_w, scene_h, r)) { vkp_pass_abort(); sc_layer_hide(); return 0; } + if (!vkp_map_rect(rw, rh, (const int[4]){0, 0, scene_w, scene_h}, r)) { vkp_pass_abort(); sc_layer_hide(); return 0; } int wait_fd; int idx = take_free_slot(l, rw, rh, AHB_RGBA8, &wait_fd); - if (idx < 0) { vkp_pass_abort(); log_drop(l); return 0; } + if (idx < 0) { vkp_pass_abort(); log_drop(l); return g_alloc_failed ? -1 : 0; } if (vkp_pass_copy_to(l->slots[idx].img, wait_fd) != 0) return -1; if (present_slot(l, idx, r, NULL, 0) != 0) return -1; if (!l->first_logged) { @@ -895,8 +977,97 @@ int sc_layer_present_pass(const struct vkp_draw *draws, int n, int scene_w, int return 0; } +static void slots_idle(struct layer *l, const int *idx, int from, int to) { + pthread_mutex_lock(&g_lock); + for (int i = from; i < to; i++) l->slots[idx[i]].busy = 0; + pthread_mutex_unlock(&g_lock); +} + static uint32_t g_hdr_pool_fmt = AHB_RGB10A2; +static int take_hdr_slot(struct layer *l, int w, int h, int *wait_fd) { + int idx = take_free_slot(l, w, h, g_hdr_pool_fmt, wait_fd); + if (idx < 0 && g_alloc_failed && g_hdr_pool_fmt == AHB_RGB10A2) { + g_hdr_pool_fmt = AHB_RGBA8; + droiddeck_log("color", "%s: this device will not make a 10-bit layer buffer (RGBA1010102): the HDR picture goes " + "on 8-bit buffers instead (still tagged BT2020_PQ; less precision)", l->name); + idx = take_free_slot(l, w, h, g_hdr_pool_fmt, wait_fd); + } + return idx; +} + +int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws, const struct vkp_hdr_frame *hf, + int scene_w, int scene_h, int composed, const struct droiddeck_color *color) { + struct layer *l = layer_of(SC_LAYER_GAME); + int rw = 0, rh = 0, r[8], idx[VKP_FG_MAX_GENERATIONS + 1], m = 0, first_fd = -1, have_fd = 0; + struct vkp_image *dst[VKP_FG_MAX_GENERATIONS], *real = NULL; + g_group_index = 0; + g_group_frames = 1; + if (!draws || n_draws <= 0 || ensure_sc(l) != 0) return -1; + if (vkp_update_map(scene_w, scene_h) != 0) return -1; + const int deep = hf && !hf->tonemap; + if (hf) composed = 1; + if (hf && hf->tonemap) color = NULL; + int n = vkp_pass_begin_generate(scene_w, scene_h, draws, n_draws, hf, &rw, &rh); + if (n < 0) return -1; + const int mapped = vkp_map_rect(rw, rh, (const int[4]){0, 0, scene_w, scene_h}, r); + if (!mapped) n = 0; + if (composed) { + if (!mapped) { vkp_pass_abort(); sc_layer_hide(); return 0; } + idx[VKP_FG_MAX_GENERATIONS] = deep ? take_hdr_slot(l, rw, rh, &first_fd) + : take_free_slot(l, rw, rh, AHB_RGBA8, &first_fd); + if (idx[VKP_FG_MAX_GENERATIONS] < 0) { vkp_pass_abort(); log_drop(l); return g_alloc_failed ? -1 : 0; } + pthread_mutex_lock(&g_lock); + l->slots[idx[VKP_FG_MAX_GENERATIONS]].busy = 1; + pthread_mutex_unlock(&g_lock); + real = l->slots[idx[VKP_FG_MAX_GENERATIONS]].img; + have_fd = 1; + } + for (; m < n; m++) { + int fd; + idx[m] = take_free_slot(l, rw, rh, deep ? g_hdr_pool_fmt : AHB_RGBA8, &fd); + if (idx[m] < 0) { log_drop(l); break; } + if (have_fd && fd >= 0) { + if (fence_wait(fd, 100) == 0) { slot_keep_fence(&l->slots[idx[m]], fd); log_drop(l); break; } + close(fd); + } + pthread_mutex_lock(&g_lock); + l->slots[idx[m]].busy = 1; + pthread_mutex_unlock(&g_lock); + dst[m] = l->slots[idx[m]].img; + if (!have_fd) { first_fd = fd; have_fd = 1; } + } + if (vkp_pass_copy_generated(dst, m, real, first_fd) != 0) { + slots_idle(l, idx, 0, m); + if (real) slots_idle(l, idx, VKP_FG_MAX_GENERATIONS, VKP_FG_MAX_GENERATIONS + 1); + return -1; + } + g_group_frames = m + 1; + for (int k = 0; k < m; k++) { + if (present_slot(l, idx[k], r, color, 0) == 0) continue; + slots_idle(l, idx, k, m); + if (real) slots_idle(l, idx, VKP_FG_MAX_GENERATIONS, VKP_FG_MAX_GENERATIONS + 1); + g_group_index = 0; + g_group_frames = 1; + return -1; + } + vkp_framegen_presented(m); + if (real) { + if (present_slot(l, idx[VKP_FG_MAX_GENERATIONS], r, color, 0) != 0) { + slots_idle(l, idx, VKP_FG_MAX_GENERATIONS, VKP_FG_MAX_GENERATIONS + 1); + g_group_index = 0; + g_group_frames = 1; + return -1; + } + l->first_logged = 1; + vkp_signal_first_frame(); + } + if (hf && hf->color && hf->color->dataspace) + droiddeck_color_frame_shown(hf->color, deep ? DROIDDECK_HDR_COMPOSED : DROIDDECK_HDR_TONEMAPPED, + deep ? g_hdr_pool_fmt : AHB_RGBA8); + return m; +} + int sc_layer_present_hdr_scene(const struct vkp_draw *draws, int n, const struct vkp_hdr_frame *hf, int scene_w, int scene_h, const struct droiddeck_color *color) { struct layer *l = layer_of(SC_LAYER_GAME); @@ -904,19 +1075,11 @@ int sc_layer_present_hdr_scene(const struct vkp_draw *draws, int n, const struct if (!draws || n <= 0 || !hf || ensure_sc(l) != 0) return -1; if (vkp_update_map(scene_w, scene_h) != 0) return -1; if (vkp_pass_begin_hdr(scene_w, scene_h, draws, n, hf, &rw, &rh) != 0) return -1; - if (!vkp_map_rect(rw, rh, scene_w, scene_h, r)) { vkp_pass_abort(); sc_layer_hide(); return 0; } + if (!vkp_map_rect(rw, rh, (const int[4]){0, 0, scene_w, scene_h}, r)) { vkp_pass_abort(); sc_layer_hide(); return 0; } const int tm = hf->tonemap; - const uint32_t fmt = tm ? AHB_RGBA8 : g_hdr_pool_fmt; - g_alloc_failed = 0; int wait_fd; - int idx = take_free_slot(l, rw, rh, fmt, &wait_fd); - if (idx < 0 && g_alloc_failed && fmt == AHB_RGB10A2) { - g_hdr_pool_fmt = AHB_RGBA8; - droiddeck_log("color", "%s: this device will not make a 10-bit layer buffer (RGBA1010102): the HDR picture goes " - "on 8-bit buffers instead (still tagged BT2020_PQ; less precision)", l->name); - idx = take_free_slot(l, rw, rh, g_hdr_pool_fmt, &wait_fd); - } - if (idx < 0) { vkp_pass_abort(); log_drop(l); return 0; } + int idx = tm ? take_free_slot(l, rw, rh, AHB_RGBA8, &wait_fd) : take_hdr_slot(l, rw, rh, &wait_fd); + if (idx < 0) { vkp_pass_abort(); log_drop(l); return g_alloc_failed ? -1 : 0; } if (vkp_pass_copy_to(l->slots[idx].img, wait_fd) != 0) return -1; if (present_slot(l, idx, r, tm ? NULL : color, 0) != 0) return -1; if (color && color->dataspace) @@ -967,8 +1130,9 @@ int sc_layer_overlay_affordable(void) { if (want) droiddeck_log("layer", "overlay layer declined: this display rotates every layer %d° and the game " "layer is scaled %dx%d -> %dx%d, and on that combination a second layer drops the " - "whole frame to GPU composition for the rest of the session (measured). The window " - "above the game goes on the copy path instead - same picture, one blit.", + "whole frame to GPU composition for the rest of the session (measured). A nested " + "compositor is asked to compose its own overlays into the game picture; any other " + "window above the game goes on the copy path instead.", deg, sr[0], sr[1], ds[0], ds[1]); else if (!first) droiddeck_log("layer", "overlay layer allowed again: the game layer is no longer both rotated and " @@ -1033,6 +1197,13 @@ void sc_layer_window_gone(void) { drain_and_free_pools(); } +void sc_layer_aim_take(unsigned *next, unsigned *later, unsigned *even) { + *next = g_stat_aimed_next; + *later = g_stat_aimed_later; + *even = g_stat_aimed_even; + g_stat_aimed_next = g_stat_aimed_later = g_stat_aimed_even = 0; +} + unsigned sc_layer_frames_take(void) { unsigned n = g_stat_layer_frames; g_stat_layer_frames = 0; diff --git a/app/src/main/cpp/waylandcomp/src/sc_layer.h b/app/src/main/cpp/waylandcomp/src/sc_layer.h index 58fe5f6d61..24a24fc25e 100644 --- a/app/src/main/cpp/waylandcomp/src/sc_layer.h +++ b/app/src/main/cpp/waylandcomp/src/sc_layer.h @@ -7,10 +7,13 @@ struct vkp_image; struct vkp_draw; struct droiddeck_color; +struct vkp_hdr_frame; enum sc_layer_id { SC_LAYER_GAME = 0, SC_LAYER_OVERLAY = 1, SC_LAYER_COUNT = 2 }; int sc_layer_available(void); +#define SC_LAYER_AHB_USAGE_VENDOR_UBWC (1ULL << 28) +int sc_layer_ahb_fd(AHardwareBuffer *ahb, uint64_t need); void sc_layer_probe_dmabuf_fd(int fd); @@ -18,21 +21,25 @@ int sc_layer_can_tag_hdr(void); void sc_layer_hdr_symbols(char *out, size_t size); -int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct droiddeck_color *color); +int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct vkp_draw *draw, + const struct droiddeck_color *color); int sc_layer_present_pass(const struct vkp_draw *draws, int n, int scene_w, int scene_h); +int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws, const struct vkp_hdr_frame *hf, + int scene_w, int scene_h, int composed, const struct droiddeck_color *color); -struct vkp_hdr_frame; int sc_layer_present_hdr_scene(const struct vkp_draw *draws, int n, const struct vkp_hdr_frame *hf, int scene_w, int scene_h, const struct droiddeck_color *color); int sc_layer_present_ahb(AHardwareBuffer *ahb, int w, int h, int acquire_fd, void *token, - int scene_w, int scene_h, const struct droiddeck_color *color, uint32_t ahb_format); + int scene_w, int scene_h, const struct vkp_draw *draw, const struct droiddeck_color *color, uint32_t ahb_format); void sc_layer_set_frame_rate(float fps); int sc_layer_overlay_affordable(void); +int sc_layer_queues(void); + int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int translucent); void sc_layer_hide(void); @@ -42,6 +49,8 @@ void sc_layer_hide_overlay(void); void sc_layer_window_gone(void); +void sc_layer_frame_timeline(int64_t present_ns, int64_t deadline_ns, int64_t period_ns); +void sc_layer_aim_take(unsigned *next, unsigned *later, unsigned *even); unsigned sc_layer_frames_take(void); unsigned sc_layer_drops_take(void); diff --git a/app/src/main/cpp/waylandcomp/src/vk_present.c b/app/src/main/cpp/waylandcomp/src/vk_present.c index cbf0c6f69a..ebd9404281 100644 --- a/app/src/main/cpp/waylandcomp/src/vk_present.c +++ b/app/src/main/cpp/waylandcomp/src/vk_present.c @@ -1880,6 +1880,11 @@ static int compose_hdr(VkCommandBuffer cmd, const struct vkp_draw *draws, int n, struct hdrc_params p = {.mode = mode, .sdr_white_nits = droiddeck_color_sdr_white(), .peak_nits = hf->peak_nits > 0.0f ? hf->peak_nits : 1000.0f}; + if (hf->convert) { + p.conv_linear = hf->convert->convert == 2; + p.conv_gain = hf->convert->gain; + memcpy(p.conv, hf->convert->to2020, sizeof(p.conv)); + } int lowest_hdr = -1; for (int i = 0; i < n; i++) { VkImageBlit blit; @@ -1896,6 +1901,7 @@ static int compose_hdr(VkCommandBuffer cmd, const struct vkp_draw *draws, int n, p.rects[p.count][0] = (float)blit.dstOffsets[0].x; p.rects[p.count][1] = (float)blit.dstOffsets[0].y; p.rects[p.count][2] = (float)blit.dstOffsets[1].x; p.rects[p.count][3] = (float)blit.dstOffsets[1].y; if (hf->is_hdr[i]) p.hdr_mask |= 1u << p.count; + if (hf->is_hdr[i] == 2 && hf->convert) p.conv_mask |= 1u << p.count; p.count++; } if (i >= lowest_hdr && !truncated_said) { @@ -2500,9 +2506,9 @@ int vkp_update_map(int scene_w, int scene_h) { return g_map.valid ? 0 : -1; } -int vkp_map_rect(int img_w, int img_h, int scene_w, int scene_h, int out[8]) { +int vkp_map_rect(int img_w, int img_h, const int dst[4], int out[8]) { struct vkp_image tmp = {.w = img_w, .h = img_h}; - struct vkp_draw d = {&tmp, 0, 0, (float)img_w, (float)img_h, 0, 0, scene_w, scene_h}; + struct vkp_draw d = {&tmp, 0, 0, (float)img_w, (float)img_h, dst[0], dst[1], dst[2], dst[3]}; return vkp_map_draw(&d, out); } @@ -2703,24 +2709,33 @@ static struct { int active; VkImage result; int rw, rh; + int ngen; + VkImage gens[VKP_FG_MAX_GENERATIONS]; } g_pass; static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draws, int n, - const struct vkp_hdr_frame *hf, int *rw, int *rh); + const struct vkp_hdr_frame *hf, int generate, int *rw, int *rh); int vkp_pass_begin(int scene_w, int scene_h, const struct vkp_draw *draws, int n, int *rw, int *rh) { - return pass_begin_impl(scene_w, scene_h, draws, n, NULL, rw, rh); + return pass_begin_impl(scene_w, scene_h, draws, n, NULL, 0, rw, rh); +} + +int vkp_pass_begin_generate(int scene_w, int scene_h, const struct vkp_draw *draws, int n, + const struct vkp_hdr_frame *hf, int *rw, int *rh) { + if (pass_begin_impl(scene_w, scene_h, draws, n, hf, 1, rw, rh) != 0) return -1; + return g_pass.ngen; } int vkp_pass_begin_hdr(int scene_w, int scene_h, const struct vkp_draw *draws, int n, const struct vkp_hdr_frame *hf, int *rw, int *rh) { if (!hf) return -1; - return pass_begin_impl(scene_w, scene_h, draws, n, hf, rw, rh); + return pass_begin_impl(scene_w, scene_h, draws, n, hf, 0, rw, rh); } static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draws, int n, - const struct vkp_hdr_frame *hf, int *rw, int *rh) { + const struct vkp_hdr_frame *hf, int generate, int *rw, int *rh) { if (g_pass.active) vkp_pass_abort(); + g_pass.ngen = 0; if (vkp_update_map(scene_w, scene_h) != 0) return -1; int input_w = scene_w, input_h = scene_h; int pass_n = n, overlay_start = n; @@ -2740,13 +2755,31 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw effects_source_note(scene_w, scene_h, draws, n, input_w, input_h, (int)(scene_w * g_map.kx + 0.5f), (int)(scene_h * g_map.ky + 0.5f)); } - if (hf) { + const int deep = hf && generate && !hf->tonemap && vkp_framegen_format_ok(FG_HDR_FMT) && + ensure_img(&g_fgscene, scene_w, scene_h, FG_HDR_FMT, + VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | + VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, + "HDR frame generation (scene)") == 0; + const int narrow = hf && generate && !deep; + if (hf && !deep && !narrow) { if (ensure_img(&g_hdrscene, scene_w, scene_h, HDR_FMT, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, "HDR composition (picture)") != 0) return -1; - } else if (ensure_scene_image(input_w, input_h) != 0) return -1; + } else if (!deep && ensure_scene_image(input_w, input_h) != 0) return -1; + const VkFormat scene_fmt = deep ? FG_HDR_FMT : narrow || !hf ? SCENE_FMT : HDR_FMT; + if (hf && generate) { + static int said = -1; + if (said != deep + 2 * hf->tonemap) { + said = deep + 2 * hf->tonemap; + droiddeck_log("color", hf->tonemap + ? "frame generation runs on the tone-mapped picture in 8 bits, onto the game's display layer" + : deep ? "frame generation runs on the HDR picture in FP16 (RGBA16F), onto the game's display layer" + : "frame generation runs on the HDR picture in 8 bits (the engine cannot take FP16 here), onto " + "the game's display layer: banding possible in smooth gradients"); + } + } VkCommandBuffer cmd = g_cmds[0]; g_vk.ResetCommandBuffer(cmd, 0); @@ -2760,7 +2793,7 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw VkImageMemoryBarrier *bars = calloc((size_t)n + 1, sizeof(*bars)); if (!bars) { g_vk.EndCommandBuffer(cmd); return -1; } int nb = 0; - VkImage scene_img = hf ? g_hdrscene.img : g_scene.img; + VkImage scene_img = deep ? g_fgscene.img : narrow || !hf ? g_scene.img : g_hdrscene.img; bars[nb++] = (VkImageMemoryBarrier){ .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, .newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, @@ -2791,12 +2824,12 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw free(bars); if (hf) { - if (compose_hdr(cmd, draws, n, hf, scene_w, scene_h, g_hdrscene.img, HDR_FMT, + if (compose_hdr(cmd, draws, n, hf, scene_w, scene_h, scene_img, scene_fmt, hf->tonemap ? HDRC_OUT_SDR : HDRC_OUT_PQ) != 0) { g_vk.EndCommandBuffer(cmd); return -1; } - if (vkp_effects_active()) vkp_effects_set_formats(HDR_FMT, HDR_FMT); + if (vkp_effects_active()) vkp_effects_set_formats(scene_fmt, scene_fmt); } else { VkClearColorValue black = {.float32 = {0.0f, 0.0f, 0.0f, 1.0f}}; g_vk.CmdClearColorImage(cmd, g_scene.img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &black, 1, &range); @@ -2815,24 +2848,42 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw } int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f); + if (generate && !vkp_effects_sharpening()) { mapped_w = scene_w; mapped_h = scene_h; } g_pass.rw = input_w; g_pass.rh = input_h; g_pass.result = vkp_effects_run(cmd, scene_img, input_w, input_h, mapped_w, mapped_h, &g_pass.rw, &g_pass.rh); effects_overlay_draws(cmd, g_pass.result, g_pass.rw, g_pass.rh, scene_w, scene_h, draws ? draws + overlay_start : NULL, n - overlay_start); release_external_client_draws(cmd, draws, n); + if (generate) { + VkImageMemoryBarrier b = { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + .newLayout = VK_IMAGE_LAYOUT_GENERAL, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .image = g_pass.result, .subresourceRange = range, + .srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT, + .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_SHADER_READ_BIT}; + g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + 0, 0, NULL, 0, NULL, 1, &b); + int ngen = vkp_framegen_run(cmd, g_pass.result, VK_NULL_HANDLE, g_pass.rw, g_pass.rh, scene_fmt, g_pass.gens); + if (ngen < 0) ngen = 0; + g_pass.ngen = ngen > VKP_FG_MAX_GENERATIONS ? VKP_FG_MAX_GENERATIONS : ngen; + } g_pass.active = 1; if (rw) *rw = g_pass.rw; if (rh) *rh = g_pass.rh; return 0; } -int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd) { +static int pass_finish(const VkImage *srcs, VkImageLayout src_layout, struct vkp_image *const *dsts, int n, + int wait_fd) { if (!g_pass.active) { if (wait_fd >= 0) close(wait_fd); return -1; } g_pass.active = 0; if (g_dev_state != 1) { if (wait_fd >= 0) close(wait_fd); return -1; } VkCommandBuffer cmd = g_cmds[0]; - if (!dst || !dst->blit_dst) { + for (int i = 0; i < n; i++) { + if (dsts[i] && dsts[i]->blit_dst) continue; if (wait_fd >= 0) close(wait_fd); g_vk.EndCommandBuffer(cmd); return -1; @@ -2841,27 +2892,30 @@ int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd) { if (gpu_wait < 0) { g_vk.EndCommandBuffer(cmd); return -1; } VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - VkImageMemoryBarrier acq = { - .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, - .newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, - .dstQueueFamilyIndex = g_qfam, .image = dst->image, .subresourceRange = range, - .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}; - g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, - 0, 0, NULL, 0, NULL, 1, &acq); - VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, - .srcOffsets = {{0, 0, 0}, {g_pass.rw, g_pass.rh, 1}}, - .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, - .dstOffsets = {{0, 0, 0}, {dst->w, dst->h, 1}}}; - g_vk.CmdBlitImage(cmd, g_pass.result, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dst->image, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, - (g_pass.rw == dst->w && g_pass.rh == dst->h) ? VK_FILTER_NEAREST : VK_FILTER_LINEAR); - VkImageMemoryBarrier rel = { - .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - .newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam, - .dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .image = dst->image, .subresourceRange = range, - .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}; - g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - 0, 0, NULL, 0, NULL, 1, &rel); + for (int i = 0; i < n; i++) { + struct vkp_image *dst = dsts[i]; + VkImageMemoryBarrier acq = { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, + .dstQueueFamilyIndex = g_qfam, .image = dst->image, .subresourceRange = range, + .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}; + g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, 0, NULL, 0, NULL, 1, &acq); + VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, + .srcOffsets = {{0, 0, 0}, {g_pass.rw, g_pass.rh, 1}}, + .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, + .dstOffsets = {{0, 0, 0}, {dst->w, dst->h, 1}}}; + g_vk.CmdBlitImage(cmd, srcs[i], src_layout, dst->image, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, + (g_pass.rw == dst->w && g_pass.rh == dst->h) ? VK_FILTER_NEAREST : VK_FILTER_LINEAR); + VkImageMemoryBarrier rel = { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + .newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .image = dst->image, .subresourceRange = range, + .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}; + g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, + 0, 0, NULL, 0, NULL, 1, &rel); + } g_vk.EndCommandBuffer(cmd); VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT; @@ -2881,6 +2935,19 @@ int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd) { return 0; } +int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd) { + return pass_finish(&g_pass.result, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, &dst, 1, wait_fd); +} + +int vkp_pass_copy_generated(struct vkp_image *const *dsts, int n, struct vkp_image *real, int wait_fd) { + VkImage srcs[VKP_FG_MAX_GENERATIONS + 1]; + struct vkp_image *all[VKP_FG_MAX_GENERATIONS + 1]; + if (n > g_pass.ngen) n = g_pass.ngen; + for (int i = 0; i < n; i++) { srcs[i] = g_pass.gens[i]; all[i] = dsts[i]; } + if (real) { srcs[n] = g_pass.result; all[n] = real; } + return pass_finish(srcs, VK_IMAGE_LAYOUT_GENERAL, all, n + (real ? 1 : 0), wait_fd); +} + void vkp_pass_abort(void) { if (!g_pass.active) return; g_pass.active = 0; diff --git a/app/src/main/cpp/waylandcomp/src/vk_present.h b/app/src/main/cpp/waylandcomp/src/vk_present.h index b8cd889219..69af7dca23 100644 --- a/app/src/main/cpp/waylandcomp/src/vk_present.h +++ b/app/src/main/cpp/waylandcomp/src/vk_present.h @@ -96,6 +96,7 @@ struct vkp_hdr_frame { float peak_nits; int tonemap; const struct droiddeck_color *color; + const struct droiddeck_color *convert; }; int vkp_render_hdr(int scene_w, int scene_h, const struct vkp_draw *draws, int n, const struct vkp_hdr_frame *hf, int *how); @@ -106,7 +107,7 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd); int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px); int vkp_update_map(int scene_w, int scene_h); int vkp_map_draw(const struct vkp_draw *d, int out[8]); -int vkp_map_rect(int img_w, int img_h, int scene_w, int scene_h, int out[8]); +int vkp_map_rect(int img_w, int img_h, const int dst[4], int out[8]); int vkp_surface_rotation_degrees(void); ANativeWindow *vkp_window(void); @@ -114,6 +115,9 @@ void vkp_signal_first_frame(void); int vkp_pass_begin(int scene_w, int scene_h, const struct vkp_draw *draws, int n, int *rw, int *rh); int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd); +int vkp_pass_begin_generate(int scene_w, int scene_h, const struct vkp_draw *draws, int n, + const struct vkp_hdr_frame *hf, int *rw, int *rh); +int vkp_pass_copy_generated(struct vkp_image *const *dsts, int n, struct vkp_image *real, int wait_fd); void vkp_pass_abort(void); void droiddeck_log(const char *tag, const char *fmt, ...) __attribute__((format(printf, 2, 3))); diff --git a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c index 7879d51521..4dc2f2c08c 100644 --- a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c +++ b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c @@ -34,11 +34,13 @@ extern int droiddeck_cursor_input_pos(int *x, int *y); extern void droiddeck_wayland_send_scene_input(int type, int a, int b); extern void droiddeck_wayland_set_cursor_composite(int on); extern void droiddeck_wayland_vsync(int64_t frame_time_ns); +extern void sc_layer_frame_timeline(int64_t present_ns, int64_t deadline_ns, int64_t period_ns); extern void droiddeck_stream_set(int on); extern void droiddeck_stream_frame(AHardwareBuffer *ahb); extern unsigned droiddeck_stream_frames(void); extern void droiddeck_wayland_output_resized(void); extern void droiddeck_wayland_set_output_refresh_rate(int mhz); +extern void droiddeck_wayland_set_panel_rates(const int *rates, int count); extern volatile int g_fps_limit; extern volatile int g_release_unpaced; extern volatile int g_render_on_commit; @@ -48,6 +50,8 @@ extern volatile int g_hide_shell; extern volatile int g_zero_copy; extern volatile unsigned g_zero_copy_last; extern volatile int g_ubwc; +extern volatile int g_display_buffer_driver; +void droiddeck_dmabuf_formats_stale(void); extern volatile int g_no_render_node; extern volatile int g_output_w, g_output_h; @@ -63,6 +67,9 @@ static jmethodID g_on_game_program; static jmethodID g_on_pointer_lock; static jmethodID g_on_clipboard; static jmethodID g_on_text_input; +static jmethodID g_on_overlay_planes; +static jmethodID g_on_refresh_target; +static jmethodID g_on_content_rate; JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { (void)reserved; @@ -84,6 +91,9 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { g_on_clipboard = (*env)->GetStaticMethodID(env, g_compositor_cls, "onClipboardText", "([B)V"); g_on_text_input = (*env)->GetStaticMethodID(env, g_compositor_cls, "onTextInput", "(ZLjava/lang/String;IIII)V"); + g_on_overlay_planes = (*env)->GetStaticMethodID(env, g_compositor_cls, "onOverlayPlanes", "(I)V"); + g_on_refresh_target = (*env)->GetStaticMethodID(env, g_compositor_cls, "onRefreshTarget", "(II)V"); + g_on_content_rate = (*env)->GetStaticMethodID(env, g_compositor_cls, "onContentRate", "(I)V"); } } return JNI_VERSION_1_6; @@ -144,6 +154,27 @@ void droiddeck_on_game_frame(void) { if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env); } +void droiddeck_on_refresh_target(int refresh, int frame_rate) { + JNIEnv *env; + if (!g_compositor_cls || !g_on_refresh_target || !(env = thread_env())) return; + (*env)->CallStaticVoidMethod(env, g_compositor_cls, g_on_refresh_target, (jint)refresh, (jint)frame_rate); + if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env); +} + +void droiddeck_on_content_rate(int fps) { + JNIEnv *env; + if (!g_compositor_cls || !g_on_content_rate || !(env = thread_env())) return; + (*env)->CallStaticVoidMethod(env, g_compositor_cls, g_on_content_rate, (jint)fps); + if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env); +} + +void droiddeck_on_overlay_planes(int planes) { + JNIEnv *env; + if (!g_compositor_cls || !g_on_overlay_planes || !(env = thread_env())) return; + (*env)->CallStaticVoidMethod(env, g_compositor_cls, g_on_overlay_planes, (jint)planes); + if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env); +} + void droiddeck_on_pointer_lock(int locked, int x, int y) { JNIEnv *env; if (!g_compositor_cls || !g_on_pointer_lock || !(env = thread_env())) return; @@ -365,6 +396,12 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeVsync(JNIEnv *env, j droiddeck_wayland_vsync((int64_t)frameTimeNanos); } +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeFrameTimeline(JNIEnv *env, jclass clazz, jlong presentNanos, + jlong deadlineNanos, jlong periodNanos) { + sc_layer_frame_timeline((int64_t)presentNanos, (int64_t)deadlineNanos, (int64_t)periodNanos); +} + JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetClockControl(JNIEnv *env, jclass clazz, jstring path) { const char *value = path ? (*env)->GetStringUTFChars(env, path, NULL) : NULL; @@ -380,11 +417,18 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetHideShell(JNIEnv JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetZeroCopy(JNIEnv *env, jclass clazz, jboolean on) { int live = droiddeck_get_display() != NULL; - if (!live) g_zero_copy = on ? 1 : 0; + if (!live) { g_zero_copy = on ? 1 : 0; droiddeck_dmabuf_formats_stale(); } droiddeck_host_zero_copy(on ? 1 : 0, live); __android_log_print(ANDROID_LOG_INFO, TAG, "zero-copy layer mode %s%s", on ? "on" : "off", live ? " (live)" : ""); } +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetDisplayBufferDriver(JNIEnv *env, jclass clazz, jboolean on) { + g_display_buffer_driver = on ? 1 : 0; + droiddeck_dmabuf_formats_stale(); + __android_log_print(ANDROID_LOG_INFO, TAG, "session driver %s for display buffers", on ? "asks" : "does not ask"); +} + JNIEXPORT jint JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeZeroCopyLastFrameAgeMs(JNIEnv *env, jclass clazz) { return (jint)ahb_swapchain_last_frame_age_ms(); @@ -418,6 +462,16 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetOutputRefreshRate droiddeck_wayland_set_output_refresh_rate(hz > 1.0f ? (int)(hz * 1000.0f + 0.5f) : 0); } +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetPanelRates(JNIEnv *env, jclass clazz, jintArray rates) { + (void)clazz; + jint values[16]; + jsize count = rates ? (*env)->GetArrayLength(env, rates) : 0; + if (count > 16) count = 16; + if (count > 0) (*env)->GetIntArrayRegion(env, rates, 0, count, values); + droiddeck_wayland_set_panel_rates((const int *)values, (int)count); +} + extern void vkp_reset_first_frame(void); JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeResetFirstFrame(JNIEnv *env, jclass clazz) { diff --git a/app/src/main/cpp/waylandcomp/src/wl_color_mgmt.c b/app/src/main/cpp/waylandcomp/src/wl_color_mgmt.c index 1ba254c4cd..a45d2691cf 100644 --- a/app/src/main/cpp/waylandcomp/src/wl_color_mgmt.c +++ b/app/src/main/cpp/waylandcomp/src/wl_color_mgmt.c @@ -84,15 +84,18 @@ static struct { static _Atomic int g_gate = -1; static char g_gate_why[320]; static _Atomic int g_output_on = 1; +static _Atomic int g_output_wanted = 1; +static pthread_mutex_t g_output_mu = PTHREAD_MUTEX_INITIALIZER; void droiddeck_color_set_request(int mode, const char *source, int dxvk_hdr, int zero_copy_forced) { pthread_mutex_lock(&g_mu); - g_req.mode = mode < 0 ? 0 : mode > 2 ? 2 : mode; + g_req.mode = mode < 0 ? 0 : mode > 3 ? 3 : mode; snprintf(g_req.source, sizeof(g_req.source), "%s", source ? source : "environment"); g_req.dxvk_hdr = dxvk_hdr ? 1 : 0; g_req.zero_copy_forced = zero_copy_forced ? 1 : 0; pthread_mutex_unlock(&g_mu); atomic_store(&g_output_on, 1); + atomic_store(&g_output_wanted, 1); } void droiddeck_color_set_display(int id, const char *name, const char *formats, int hdr10, float max_lum, @@ -610,11 +613,23 @@ int droiddeck_color_tonemapped_on_screen(void) { void droiddeck_color_set_output(int on) { on = on ? 1 : 0; - if (atomic_load(&g_gate) != 1) { - droiddeck_log(TAG, "HDR output switch (%s) ignored: HDR is not open in this session", on ? "on" : "off"); + pthread_mutex_lock(&g_mu); + const int tonemap_only = g_req.mode == 3; + pthread_mutex_unlock(&g_mu); + pthread_mutex_lock(&g_output_mu); + atomic_store(&g_output_wanted, on); + const int gate = atomic_load(&g_gate); + const int changed = gate == 1 && !(on && tonemap_only) && atomic_exchange(&g_output_on, on) != on; + pthread_mutex_unlock(&g_output_mu); + if (gate != 1) { + if (gate == 0) droiddeck_log(TAG, "HDR output switch (%s) ignored: HDR is not open in this session", on ? "on" : "off"); return; } - if (atomic_exchange(&g_output_on, on) == on) return; + if (on && tonemap_only) { + droiddeck_log(TAG, "HDR output switch (on) ignored: this display cannot show HDR10, HDR frames stay tone-mapped"); + return; + } + if (!changed) return; char who[160]; int age = droiddeck_color_last_frame_age_ms(), tm = droiddeck_color_tonemapped_on_screen(); pthread_mutex_lock(&g_mu); @@ -658,6 +673,8 @@ static void desc_unref(struct cm_desc *d) { if (d && --d->refs <= 0) free(d); } struct cm_params { uint32_t tf, primaries; + int has_prim; int32_t prim[8]; + int has_lum; uint32_t lum_ref; int has_mprim; int32_t mprim[8]; int has_mlum; uint32_t mlum_min, mlum_max; int has_cll; uint32_t cll; @@ -730,9 +747,83 @@ static void make_output_description(struct wl_client *c, struct wl_resource *par droiddeck_client_name(c), what, col->text); } +static const float BT709_XY[8] = {0.64f, 0.33f, 0.30f, 0.60f, 0.15f, 0.06f, 0.3127f, 0.3290f}; +static const float BT2020_XY[8] = {0.708f, 0.292f, 0.170f, 0.797f, 0.131f, 0.046f, 0.3127f, 0.3290f}; + +static void mat_mul(const double a[9], const double b[9], double out[9]) { + double m[9]; + for (int i = 0; i < 3; i++) + for (int j = 0; j < 3; j++) + m[3 * i + j] = a[3 * i] * b[j] + a[3 * i + 1] * b[3 + j] + a[3 * i + 2] * b[6 + j]; + memcpy(out, m, sizeof(m)); +} + +static int mat_invert(const double m[9], double out[9]) { + const double det = m[0] * (m[4] * m[8] - m[5] * m[7]) - m[1] * (m[3] * m[8] - m[5] * m[6]) + + m[2] * (m[3] * m[7] - m[4] * m[6]); + if (det > -1e-12 && det < 1e-12) return -1; + const double k = 1.0 / det; + double r[9] = {(m[4] * m[8] - m[5] * m[7]) * k, (m[2] * m[7] - m[1] * m[8]) * k, (m[1] * m[5] - m[2] * m[4]) * k, + (m[5] * m[6] - m[3] * m[8]) * k, (m[0] * m[8] - m[2] * m[6]) * k, (m[2] * m[3] - m[0] * m[5]) * k, + (m[3] * m[7] - m[4] * m[6]) * k, (m[1] * m[6] - m[0] * m[7]) * k, (m[0] * m[4] - m[1] * m[3]) * k}; + memcpy(out, r, sizeof(r)); + return 0; +} + +static int rgb_to_xyz(const float xy[8], double out[9], double white[3]) { + for (int i = 0; i < 4; i++) + if (xy[2 * i + 1] < 1e-4f) return -1; + double p[9], inv[9]; + for (int i = 0; i < 3; i++) { + const double x = xy[2 * i], y = xy[2 * i + 1]; + p[i] = x / y; p[3 + i] = 1.0; p[6 + i] = (1.0 - x - y) / y; + } + white[0] = xy[6] / xy[7]; white[1] = 1.0; white[2] = (1.0 - xy[6] - xy[7]) / xy[7]; + if (mat_invert(p, inv) != 0) return -1; + for (int i = 0; i < 3; i++) { + const double scale = inv[3 * i] * white[0] + inv[3 * i + 1] * white[1] + inv[3 * i + 2] * white[2]; + out[i] = p[i] * scale; out[3 + i] = p[3 + i] * scale; out[6 + i] = p[6 + i] * scale; + } + return 0; +} + +static int matrix_to_bt2020(const float xy[8], float out[9]) { + static const double bradford[9] = {0.8951, 0.2664, -0.1614, -0.7502, 1.7135, 0.0367, 0.0389, -0.0685, 1.0296}; + double src[9], dst[9], dst_inv[9], sw[3], dw[3], cone_inv[9], adapt[9], m[9]; + if (rgb_to_xyz(xy, src, sw) != 0 || rgb_to_xyz(BT2020_XY, dst, dw) != 0) return -1; + if (mat_invert(dst, dst_inv) != 0 || mat_invert(bradford, cone_inv) != 0) return -1; + double scale[9] = {0}; + for (int i = 0; i < 3; i++) { + const double from = bradford[3 * i] * sw[0] + bradford[3 * i + 1] * sw[1] + bradford[3 * i + 2] * sw[2]; + const double to = bradford[3 * i] * dw[0] + bradford[3 * i + 1] * dw[1] + bradford[3 * i + 2] * dw[2]; + if (from > -1e-9 && from < 1e-9) return -1; + scale[4 * i] = to / from; + } + mat_mul(scale, bradford, adapt); + mat_mul(cone_inv, adapt, adapt); + mat_mul(adapt, src, m); + mat_mul(dst_inv, m, m); + for (int i = 0; i < 9; i++) out[i] = (float)m[i]; + return 0; +} + +static struct wl_resource *publish_description(struct wl_client *client, struct wl_resource *parent, uint32_t id, + struct cm_desc *d) { + struct wl_resource *out = wl_resource_create(client, &wp_image_description_v1_interface, + wl_resource_get_version(parent), id); + if (!out) { free(d); wl_client_post_no_memory(client); return NULL; } + d->refs = 1; + wl_resource_set_implementation(out, &image_description_impl, d, image_description_resource_destroy); + wp_image_description_v1_send_ready(out, d->c.identity); + pthread_mutex_lock(&g_mu); + g_hdr.descs++; + pthread_mutex_unlock(&g_mu); + return out; +} + static void params_create(struct wl_client *client, struct wl_resource *r, uint32_t id) { struct cm_params *p = wl_resource_get_user_data(r); - if (!p->tf || !p->primaries) { + if (!p->tf || (!p->primaries && !p->has_prim)) { wl_resource_post_error(r, WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_INCOMPLETE_SET, "transfer function and primaries must both be set"); return; @@ -744,10 +835,29 @@ static void params_create(struct wl_client *client, struct wl_resource *r, uint3 if (!g_next_identity) g_next_identity = 1; c->primaries = p->primaries; c->tf = p->tf; - if (p->primaries == WP_COLOR_MANAGER_V1_PRIMARIES_BT2020 && p->tf == WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_ST2084_PQ) + const float ref = p->has_lum ? (float)p->lum_ref : 203.0f; + float xy[8]; + for (int i = 0; i < 8; i++) + xy[i] = p->has_prim ? p->prim[i] / 1e6f + : p->primaries == WP_COLOR_MANAGER_V1_PRIMARIES_SRGB ? BT709_XY[i] : BT2020_XY[i]; + if (p->primaries == WP_COLOR_MANAGER_V1_PRIMARIES_BT2020 && ref == 203.0f) { c->dataspace = DROIDDECK_ADATASPACE_BT2020_PQ; - else if (p->primaries == WP_COLOR_MANAGER_V1_PRIMARIES_BT2020 && p->tf == WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_HLG) - c->dataspace = DROIDDECK_ADATASPACE_BT2020_HLG; + } else if (matrix_to_bt2020(xy, c->to2020) == 0) { + c->convert = 1; + c->gain = 10000.0f * 203.0f / ref; + } else { + struct wl_resource *bad = wl_resource_create(client, &wp_image_description_v1_interface, + wl_resource_get_version(r), id); + free(d); + if (!bad) { wl_client_post_no_memory(client); return; } + wl_resource_set_implementation(bad, &image_description_impl, NULL, NULL); + wp_image_description_v1_send_failed(bad, WP_IMAGE_DESCRIPTION_V1_CAUSE_UNSUPPORTED, + "the primaries do not form a colour space"); + droiddeck_log(TAG, "image description from %s refused: its primaries do not form a colour space", + droiddeck_client_name(client)); + wl_resource_destroy(r); + return; + } char dropped[160] = ""; float mlum_min = 0.005f, mlum_max = 10000.0f; @@ -781,7 +891,12 @@ static void params_create(struct wl_client *client, struct wl_resource *r, uint3 } if (cll > 0.0f || fall > 0.0f) { c->has_cta861 = 1; c->max_cll = cll; c->max_fall = fall; } - int n = snprintf(c->text, sizeof(c->text), "%s, %s", primaries_name(c->primaries), tf_name(c->tf)); + int n = snprintf(c->text, sizeof(c->text), "%s, %s", p->has_prim ? "custom primaries" : primaries_name(c->primaries), + tf_name(c->tf)); + if (c->convert && n < (int)sizeof(c->text)) + n += snprintf(c->text + n, sizeof(c->text) - (size_t)n, + "; R %.4f,%.4f G %.4f,%.4f B %.4f,%.4f W %.4f,%.4f, reference white %.0f nits", + xy[0], xy[1], xy[2], xy[3], xy[4], xy[5], xy[6], xy[7], ref); if (c->has_st2086 && n < (int)sizeof(c->text)) n += snprintf(c->text + n, sizeof(c->text) - (size_t)n, "; mastering R %.4f,%.4f G %.4f,%.4f B %.4f,%.4f W %.4f,%.4f, %.4f-%.0f nits%s", @@ -793,19 +908,13 @@ static void params_create(struct wl_client *client, struct wl_resource *r, uint3 if (!c->has_st2086 && !c->has_cta861 && n < (int)sizeof(c->text)) snprintf(c->text + n, sizeof(c->text) - (size_t)n, " (no HDR metadata: the game has not called vkSetHdrMetadataEXT)"); - struct wl_resource *out = wl_resource_create(client, &wp_image_description_v1_interface, - wl_resource_get_version(r), id); - if (!out) { free(d); wl_client_post_no_memory(client); return; } - d->refs = 1; - wl_resource_set_implementation(out, &image_description_impl, d, image_description_resource_destroy); - wp_image_description_v1_send_ready(out, c->identity); - if (c->dataspace) { - pthread_mutex_lock(&g_mu); - g_hdr.descs++; - pthread_mutex_unlock(&g_mu); - } - droiddeck_log(TAG, "image description #%u from %s: %s -> ready (on a display layer: dataspace %s)", c->identity, - droiddeck_client_name(client), c->text, dataspace_name(c->dataspace)); + if (!publish_description(client, r, id, d)) return; + if (c->convert) + droiddeck_log(TAG, "image description #%u from %s: %s -> ready (converted to BT.2020 PQ when the scene is " + "composed)", c->identity, droiddeck_client_name(client), c->text); + else + droiddeck_log(TAG, "image description #%u from %s: %s -> ready (on a display layer: dataspace %s)", c->identity, + droiddeck_client_name(client), c->text, dataspace_name(c->dataspace)); if (dropped[0]) { size_t l = strlen(dropped); if (l && dropped[l - 1] == ',') dropped[l - 1] = 0; @@ -840,8 +949,8 @@ static void params_set_tf_power(struct wl_client *c, struct wl_resource *r, uint } static void params_set_primaries_named(struct wl_client *c, struct wl_resource *r, uint32_t primaries) { struct cm_params *p = wl_resource_get_user_data(r); - PARAMS_ONCE(p->primaries, "primaries"); - if (primaries != WP_COLOR_MANAGER_V1_PRIMARIES_BT2020) { + PARAMS_ONCE(p->primaries || p->has_prim, "primaries"); + if (primaries != WP_COLOR_MANAGER_V1_PRIMARIES_BT2020 && primaries != WP_COLOR_MANAGER_V1_PRIMARIES_SRGB) { wl_resource_post_error(r, WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_INVALID_PRIMARIES_NAMED, "primaries %u were not advertised", primaries); return; @@ -850,12 +959,21 @@ static void params_set_primaries_named(struct wl_client *c, struct wl_resource * } static void params_set_primaries(struct wl_client *c, struct wl_resource *r, int32_t rx, int32_t ry, int32_t gx, int32_t gy, int32_t bx, int32_t by, int32_t wx, int32_t wy) { - wl_resource_post_error(r, WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_UNSUPPORTED_FEATURE, - "set_primaries is not supported"); + struct cm_params *p = wl_resource_get_user_data(r); + PARAMS_ONCE(p->primaries || p->has_prim, "primaries"); + p->has_prim = 1; + p->prim[0] = rx; p->prim[1] = ry; p->prim[2] = gx; p->prim[3] = gy; + p->prim[4] = bx; p->prim[5] = by; p->prim[6] = wx; p->prim[7] = wy; } static void params_set_luminances(struct wl_client *c, struct wl_resource *r, uint32_t mn, uint32_t mx, uint32_t ref) { - wl_resource_post_error(r, WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_UNSUPPORTED_FEATURE, - "set_luminances is not supported"); + struct cm_params *p = wl_resource_get_user_data(r); + PARAMS_ONCE(p->has_lum, "luminances"); + if ((uint64_t)mx * 10000u <= mn || (uint64_t)ref * 10000u <= mn) { + wl_resource_post_error(r, WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_INVALID_LUMINANCE, + "maximum and reference luminance must be above the minimum"); + return; + } + p->has_lum = 1; p->lum_ref = ref; } static void params_set_mastering_display_primaries(struct wl_client *c, struct wl_resource *r, int32_t rx, int32_t ry, int32_t gx, int32_t gy, int32_t bx, int32_t by, int32_t wx, int32_t wy) { @@ -1083,7 +1201,20 @@ static void cm_create_parametric_creator(struct wl_client *c, struct wl_resource } static void cm_create_windows_scrgb(struct wl_client *c, struct wl_resource *r, uint32_t id) { - wl_resource_post_error(r, WP_COLOR_MANAGER_V1_ERROR_UNSUPPORTED_FEATURE, "windows_scrgb is not supported"); + struct cm_desc *d = calloc(1, sizeof(*d)); + if (!d) { wl_client_post_no_memory(c); return; } + struct droiddeck_color *col = &d->c; + col->identity = g_next_identity++; + if (!g_next_identity) g_next_identity = 1; + col->primaries = WP_COLOR_MANAGER_V1_PRIMARIES_SRGB; + col->tf = WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_EXT_LINEAR; + col->convert = 2; + col->gain = 80.0f; + matrix_to_bt2020(BT709_XY, col->to2020); + snprintf(col->text, sizeof(col->text), "%s, %s (1.0 = 80 nits)", primaries_name(col->primaries), tf_name(col->tf)); + if (!publish_description(c, r, id, d)) return; + droiddeck_log(TAG, "image description #%u from %s: %s -> ready (converted to BT.2020 PQ when the scene is composed)", + col->identity, droiddeck_client_name(c), col->text); } static const struct wp_color_manager_v1_interface cm_impl = { @@ -1103,14 +1234,20 @@ static void bind_cm(struct wl_client *c, void *data, uint32_t ver, uint32_t id) wl_resource_set_implementation(r, &cm_impl, NULL, NULL); wp_color_manager_v1_send_supported_intent(r, WP_COLOR_MANAGER_V1_RENDER_INTENT_PERCEPTUAL); wp_color_manager_v1_send_supported_feature(r, WP_COLOR_MANAGER_V1_FEATURE_PARAMETRIC); + wp_color_manager_v1_send_supported_feature(r, WP_COLOR_MANAGER_V1_FEATURE_SET_PRIMARIES); + wp_color_manager_v1_send_supported_feature(r, WP_COLOR_MANAGER_V1_FEATURE_SET_LUMINANCES); wp_color_manager_v1_send_supported_feature(r, WP_COLOR_MANAGER_V1_FEATURE_SET_MASTERING_DISPLAY_PRIMARIES); + wp_color_manager_v1_send_supported_feature(r, WP_COLOR_MANAGER_V1_FEATURE_EXTENDED_TARGET_VOLUME); + wp_color_manager_v1_send_supported_feature(r, WP_COLOR_MANAGER_V1_FEATURE_WINDOWS_SCRGB); + wp_color_manager_v1_send_supported_primaries_named(r, WP_COLOR_MANAGER_V1_PRIMARIES_SRGB); wp_color_manager_v1_send_supported_primaries_named(r, WP_COLOR_MANAGER_V1_PRIMARIES_BT2020); wp_color_manager_v1_send_supported_tf_named(r, WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_ST2084_PQ); wp_color_manager_v1_send_done(r); if (last_named != c) { last_named = c; droiddeck_log(TAG, "%s bound wp_color_manager_v1 version %u (offered: perceptual intent; parametric descriptions " - "with mastering metadata; BT.2020 primaries; ST 2084 PQ) - its Vulkan driver can now list " + "with custom primaries, luminances and mastering metadata; Windows scRGB; sRGB and BT.2020 primaries; " + "ST 2084 PQ) - its Vulkan driver can now list " "VK_COLOR_SPACE_HDR10_ST2084_EXT", droiddeck_client_name(c), ver > 1 ? 1u : ver); } } @@ -1150,6 +1287,7 @@ void droiddeck_color_init(struct wl_display *display) { char asked[128]; if (mode == 2) snprintf(asked, sizeof(asked), "DROIDDECK_WAYLAND_HDR=force (%s)", source); + else if (mode == 3) snprintf(asked, sizeof(asked), "HDR is on, tone-mapped for this display (%s)", source); else if (strstr(source, "env")) snprintf(asked, sizeof(asked), "DROIDDECK_WAYLAND_HDR=1 (%s)", source); else snprintf(asked, sizeof(asked), "HDR output is on (%s)", source); @@ -1168,7 +1306,7 @@ void droiddeck_color_init(struct wl_display *display) { snprintf(why, sizeof(why), "this Android has no display layers with dataspace control " "(ASurfaceControl + ASurfaceTransaction_setBufferDataSpace, Android 10+)"); else if (!ahb_ok) - snprintf(why, sizeof(why), "zero-copy presentation is unavailable here (banner_ahb_v1 not advertised), and an " + snprintf(why, sizeof(why), "zero-copy presentation is unavailable here (droiddeck_ahb_v1 not advertised), and an " "HDR frame is only honest on the game's own display layer"); if (why[0]) { @@ -1198,13 +1336,20 @@ void droiddeck_color_init(struct wl_display *display) { log_verdict(1); return; } + pthread_mutex_lock(&g_output_mu); atomic_store(&g_gate, 1); + if (mode == 3 || !atomic_load(&g_output_wanted)) atomic_store(&g_output_on, 0); + pthread_mutex_unlock(&g_output_mu); char syms[160]; sc_layer_hdr_symbols(syms, sizeof(syms)); droiddeck_log(TAG, "HDR gate %s: %s and %s. Offering games HDR10: wp_color_manager_v1 version 1 (BT.2020 primaries " "+ ST 2084 PQ, parametric descriptions with mastering metadata) and 10-bit AB30/XB30 dma-buf formats; HDR " "frames go on the game's own display layer as BT2020_PQ (%s)", mode == 2 ? "FORCED OPEN (testing)" : "OPEN", asked, disp, syms); + if (mode == 3) { + droiddeck_log(TAG, "this display cannot show HDR10: games still render HDR and every HDR frame is tone-mapped to " + "SDR on the game's display layer"); + } if (mode == 2 && !hdr10) droiddeck_log(TAG, "DROIDDECK_WAYLAND_HDR=force on a display without HDR10 - testing only: SurfaceFlinger will tone-map " "the game layer for this panel (expect GPU/CLIENT composition for it), nothing looks HDR"); diff --git a/app/src/main/cpp/waylandcomp/src/wl_dmabuf.c b/app/src/main/cpp/waylandcomp/src/wl_dmabuf.c index cc85bd32e6..a6e0eac3a6 100644 --- a/app/src/main/cpp/waylandcomp/src/wl_dmabuf.c +++ b/app/src/main/cpp/waylandcomp/src/wl_dmabuf.c @@ -14,6 +14,7 @@ #include "droiddeck_ext.h" #include "droiddeck_color.h" #include "compositor_internal.h" +#include "display_buffers.h" static void dbuf_buffer_resource_destroy(struct wl_resource *r) { @@ -58,6 +59,7 @@ static struct wl_resource *params_do_create(struct wl_client *c, struct wl_resou wl_resource_set_implementation(buf, &dbuf_buffer_impl, b, dbuf_buffer_resource_destroy); struct client_info *ci = client_info_of(c); if (ci) ci->dmabuf_buffers++; + display_buffers_match(c, buf, b); return buf; } static void params_create(struct wl_client *c, struct wl_resource *r, int32_t w, int32_t h, @@ -111,13 +113,16 @@ static const struct zwp_linux_dmabuf_v1_interface dmabuf_impl = { static struct { uint32_t fmt; uint64_t mods[DMABUF_NMOD]; int n; } g_dmabuf_fmts[DMABUF_NFMT_MAX] = { {DRM_ARGB8888}, {DRM_XRGB8888}, {DRM_ABGR8888}, {DRM_XBGR8888}, {DRM_ABGR2101010}, {DRM_XBGR2101010}}; static int g_dmabuf_nfmt = DMABUF_NFMT_SDR; -static int g_dmabuf_fmts_ready; +static volatile int g_dmabuf_fmts_ready; static void dmabuf_build_feedback(void); +void droiddeck_dmabuf_formats_stale(void) { g_dmabuf_fmts_ready = 0; } + static void dmabuf_build_formats(void) { char line[320]; - int pos = 0, compressed = 0; + int pos = 0, compressed = 0, backed = 0; g_dmabuf_fmts_ready = 1; + display_buffers_withdraw_ubwc(); g_dmabuf_nfmt = droiddeck_color_hdr_open() ? DMABUF_NFMT_MAX : DMABUF_NFMT_SDR; for (int f = 0; f < g_dmabuf_nfmt; f++) { uint64_t got[DMABUF_NMOD]; @@ -129,6 +134,12 @@ static void dmabuf_build_formats(void) { g_dmabuf_fmts[f].mods[k++] = got[i]; if (got[i] == VKP_MOD_QCOM_COMPRESSED) compressed++; } + int listed = 0; + for (int i = 0; i < k; i++) if (g_dmabuf_fmts[f].mods[i] == VKP_MOD_QCOM_COMPRESSED) listed = 1; + if (display_buffers_offer_ubwc(g_dmabuf_fmts[f].fmt) && !listed) { + g_dmabuf_fmts[f].mods[k++] = VKP_MOD_QCOM_COMPRESSED; + backed++; + } g_dmabuf_fmts[f].mods[k++] = MOD_INVALID; g_dmabuf_fmts[f].n = k; uint32_t fmt = g_dmabuf_fmts[f].fmt; @@ -141,7 +152,10 @@ static void dmabuf_build_formats(void) { } droiddeck_log("dmabuf", "formats: %s%s", line, !g_ubwc ? " (DROIDDECK_WAYLAND_UBWC=0: qcom_compressed not advertised)" : ""); - if (g_ubwc && !compressed) + if (backed) + droiddeck_log("dmabuf", "qcom_compressed is advertised for %d formats the compositor's driver (%s) does not " + "import as dma-bufs: this session's driver renders them into gralloc buffers", backed, vkp_gpu_name()); + else if (g_ubwc && !compressed) droiddeck_log("dmabuf", "the compositor's driver (%s) reports no importable qcom_compressed layout: " "game swapchains stay linear", vkp_gpu_name()); if (g_dmabuf_nfmt > DMABUF_NFMT_SDR) { @@ -212,6 +226,7 @@ static void dmabuf_build_feedback(void) { return; } fcntl(fd, F_ADD_SEALS, F_SEAL_SEAL | F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE); + if (g_fmt_table_fd >= 0) close(g_fmt_table_fd); g_fmt_table_fd = fd; g_fmt_table_size = size; g_fmt_table_n = (uint16_t)n; diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index d286cce1f5..0cb8e939b2 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -596,9 +596,11 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private var theme by mutableStateOf("graphite") private var appScale by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE) private var hdrOn by mutableStateOf(false) + private var zeroCopyOn by mutableStateOf(true) private var upscaler by mutableStateOf(0) private var upscaleSharpness by mutableStateOf(75) private var hdrReason by mutableStateOf(null) + private var hdrDisplay by mutableStateOf(true) private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO) private var pen by mutableStateOf(null) private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL) @@ -2079,6 +2081,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet refreshHomeAppState() } if (settingsMode == SessionService.MODE_STEAM) refreshFoundSteamLibraries() + settingsMode?.let { hdrOn = SessionPrefs.hdr(this, it) } compatLaunchVisible = true com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false) com.droiddeck.launcher.ui.DualScreenPanel.ownerPaused(taskId, false) @@ -2586,7 +2589,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet ModeSettings( mode = mode, resolution = resolution, panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this), - hdr = hdrOn, hdrReason = hdrReason, + hdr = hdrOn, hdrReason = hdrReason, hdrDisplay = hdrDisplay, zeroCopy = zeroCopyOn, upscaler = upscaler, upscaleSharpness = upscaleSharpness, gpuDrivers = drivers.summary(), touchMode = touchMode, @@ -2639,7 +2642,13 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet onIntegrationAppInfo = ::openAppInfo, onIntegrationLocation = ::openWifiDiscoverySettings, onResolution = { value -> SessionPrefs.setResolutionChoice(this, mode, value); resolution = value }, - onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on }, + onHdr = { on -> com.droiddeck.launcher.session.SessionHdr.set(this, mode, on); hdrOn = on }, + onZeroCopy = { on -> + SessionPrefs.setZeroCopy(this, mode, on); zeroCopyOn = on + if (com.droiddeck.launcher.wayland.CompositorHost.isStarted && !SessionState.hdr && + SessionPrefs.prefMode(SessionState.mode) == SessionPrefs.prefMode(mode)) + com.droiddeck.launcher.wayland.WaylandCompositor.nativeSetZeroCopy(on) + }, onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) }, onUpscaler = { m -> SessionPrefs.setUpscaler(this, m); upscaler = m }, onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct }, @@ -2983,9 +2992,11 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet startupSession = SessionPrefs.startupSession(this) loadBootMovie() hdrOn = SessionPrefs.hdr(this, mode) + zeroCopyOn = SessionPrefs.zeroCopy(this, mode) upscaler = SessionPrefs.upscaler(this) upscaleSharpness = SessionPrefs.upscaleSharpness(this) - hdrReason = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason + hdrReason = com.droiddeck.launcher.wayland.HdrSupport.blocked(this) + hdrDisplay = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason == null touchMode = SessionPrefs.touchMode(this) if (!SessionPrefs.penSeen(this) && com.droiddeck.launcher.input.PenStream.penConnected()) SessionPrefs.setPenSeen(this) pen = SessionPrefs.pen(this).takeIf { SessionPrefs.penSeen(this) } diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 08c8f958cf..cb5ee53185 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -109,6 +109,7 @@ import com.droiddeck.launcher.input.TouchpadGestures import com.droiddeck.launcher.input.TouchscreenGestures import com.droiddeck.launcher.input.ScrollTouchGestures import com.droiddeck.launcher.runtime.LinuxRuntime +import com.droiddeck.launcher.session.ContentCadence import com.droiddeck.launcher.session.LoadingState import com.droiddeck.launcher.hud.DroidDeckHudConfig import com.droiddeck.launcher.hud.DroidDeckHudHost @@ -306,7 +307,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var directHoldBehavior by mutableStateOf(com.droiddeck.launcher.input.TouchGestureConfig.MOUSE_BEHAVIOR_CLICK) private var relativeMouseMode by mutableIntStateOf(0) @Volatile private var appliedRelativeMouseMode: Int? = null - private val agentReadyListener: () -> Unit = { relativeMouseRetries = 0; requestRelativeMouse() } + private val agentReadyListener: () -> Unit = { + relativeMouseRetries = 0 + requestRelativeMouse() + appliedOverlayPlanes = null + overlayPlanesRetries = 0 + requestOverlayPlanes() + } private val appTextFocus get() = wowChat.request != null private val wowChat by lazy { com.droiddeck.launcher.ui.WowChat(this, ::sendWowChat, ::cancelWowChat, ::readGameField) } private var wowChatBottom: SecondScreenPresentation? = null @@ -510,6 +517,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun fpsLimitKey(): String? = if (SessionState.running) SessionPrefs.fpsLimitKey(SessionState.mode, SessionState.gameId) else SessionPrefs.fpsLimitKey(intent.getStringExtra(SessionService.EXTRA_MODE), intent.getStringExtra(SessionService.EXTRA_GAME_ID)) private var blackFrameInsertion by mutableStateOf(false) + private var hdrWanted by mutableStateOf(false) + private var hdrAvailable by mutableStateOf(false) private fun noSteamSession(): Boolean = (SessionState.mode == SessionService.MODE_RUN && SessionState.program in setOf( @@ -610,6 +619,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde syncActiveScreenEffectsProfile() } } + private val hdrPrefListener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key -> + if (key == SessionPrefs.hdrKey(hdrPrefMode())) uiHandler.post { hdrWanted = SessionPrefs.hdr(this, hdrPrefMode()) } + } private val shortcutPrefListener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key -> if (key == null || key == PhysicalShortcuts.KEY) { physicalShortcuts.bindings = PhysicalShortcuts.read(this) @@ -1038,6 +1050,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde updateOnScreenControls() WaylandCompositor.setFirstFrameListener(firstFrameListener) WaylandCompositor.setPointerLockListener(pointerLockListener) + WaylandCompositor.setOverlayPlanesListener(overlayPlanesListener) + WaylandCompositor.setRefreshTargetListener(refreshTargetListener) + WaylandCompositor.setContentRateListener(contentRateListener) SessionEvents.markReadyIfPossible() SessionState.endListener = endListener onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) { @@ -1645,6 +1660,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde blackFrameInsertion = on CompositorHost.setBlackFrameInsertion(on, refreshHz(), outputFpsLimit()) }, + hdr = hdrWanted, + hdrAvailable = hdrAvailable, + onHdr = { on -> com.droiddeck.launcher.session.SessionHdr.set(this@SessionActivity, hdrPrefMode(), on); hdrWanted = on }, onFrameGenPick = { mode -> val appId = frameGenTargetGameId() @@ -2492,6 +2510,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde hudOn = SessionPrefs.hudEnabled(this) gpuClockPin = gpuClockHeld() blackFrameInsertion = SessionPrefs.blackFrameInsertion(this) + hdrWanted = SessionPrefs.hdr(this, hdrPrefMode()) + hdrAvailable = HdrSupport.probe(this, glassesScreen?.display).reason == null hudConfig = DroidDeckHudConfig.load(this) hudColor = SessionPrefs.hudColor(this) hudOpacity = SessionPrefs.hudOpacity(this) @@ -2747,6 +2767,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde .onFailure { Log.e(TAG, "Could not update game environment", it) } }, "game-env-publish").start() applyGameAlignment() + val attached = CompositorHost.isStarted + val probe = if (attached) null else HdrSupport.probe(this, glassesScreen?.display) + if (probe != null) SessionState.hdrDisplay = probe.reason == null val activeProfileId = currentScreenEffectsProfileId() val activeUpscaler = SessionPrefs.screenEffectsUpscaler(this, activeProfileId) val activeEffects = SessionPrefs.screenEffects(this, activeProfileId) @@ -2766,27 +2789,31 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde Log.w(TAG, "could not point the compositor's log at $waylandLog", e) } } - if (!CompositorHost.isStarted) { - val mode = SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM) - val probe = HdrSupport.probe(this, glassesScreen?.display) + val mode = hdrPrefMode() + if (probe != null) { WaylandCompositor.nativeSetHdrDisplay( probe.displayId, probe.name, probe.formats, probe.hdr10, probe.maxLuminance, probe.maxAverageLuminance, probe.minLuminance, probe.ratioAvailable, probe.ratio, Build.VERSION.SDK_INT, ) - val wanted = SessionPrefs.hdr(this, mode) - val on = wanted && probe.reason == null - SessionState.hdr = on - if (on) { + val capable = HdrSupport.blocked(this) == null + val tonemap = capable && probe.reason != null + SessionState.hdrCapable = capable + if (capable) { try { android.system.Os.setenv("DROIDDECK_WAYLAND_HDR", "1", true) } catch (e: Exception) { Log.w(TAG, "DROIDDECK_WAYLAND_HDR", e) } - WaylandCompositor.nativeSetZeroCopy(true) } WaylandCompositor.nativeSetHdrRequest( - if (on) WaylandCompositor.HDR_MODE_ON else WaylandCompositor.HDR_MODE_OFF, - "$mode session settings" + (if (wanted && !on) " (refused: ${probe.reason})" else ""), - on, on, + if (tonemap) WaylandCompositor.HDR_MODE_TONEMAP else if (capable) WaylandCompositor.HDR_MODE_ON else WaylandCompositor.HDR_MODE_OFF, + "$mode session settings", capable, false, ) - Log.i(TAG, "hdr: " + (if (on) "on" else if (wanted) "wanted but ${probe.reason}" else "off") + " · display ${probe.formats.ifEmpty { "SDR" }}") + Log.i(TAG, "hdr: " + (if (tonemap) "tone-mapped (${probe.reason})" else if (capable) "available" else "unavailable") + " · display ${probe.formats.ifEmpty { "SDR" }}") + } + if (!SessionState.running) { + val on = SessionState.hdrCapable && SessionPrefs.hdr(this, mode) + SessionState.hdr = on + WaylandCompositor.nativeSetHdrOutput(on) + WaylandCompositor.nativeSetZeroCopy(on || SessionPrefs.zeroCopy(this, mode)) + Log.i(TAG, "hdr: " + (if (on) "on" else "off") + " for this $mode session") } com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "compositor.start driver=$driverId") CompositorHost.startOrAttach( @@ -2962,6 +2989,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde return if (capped > 1f) capped else 60f } + private fun hdrPrefMode(): String = SessionPrefs.prefMode( + if (SessionState.running) SessionState.mode + else intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM, + ) + private fun blackFrameInsertionAvailable(): Boolean { // Glasses that present the game run at their own rate, uncapped, as refreshHz() reads them. glassesScreen?.display?.let { glasses -> @@ -2981,9 +3013,38 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun outputFpsLimit(pip: Boolean): Int = SessionPrefs.compositorFpsLimit(mirrorRefreshLimit(), if (noSteamSession()) SessionState.fpsLimit else 0, pip) + private var panelHeld = false + private val panelHeldCheck = Runnable { + if (!panelHeld && hasWindowFocus() && PerfMode.panelHeld(this)) { + panelHeld = true + uiHandler.removeCallbacks(panelHeldRetry) + uiHandler.postDelayed(panelHeldRetry, PANEL_HELD_RETRY_MS) + applyOutputPacing() + } + } + private val panelHeldRetry = Runnable { + if (panelHeld && !isDestroyed) { + panelHeld = false + applyOutputPacing() + } + } + private fun applyOutputPacing() { - Log.i(TAG, "perf: " + PerfMode.apply(this, outputFpsLimit(false), mirrorRefreshLimit())) + val frameGen = appliedFrameGenMode + pacedFrameGenMode = frameGen + val ownLimit = outputFpsLimit(false) + val content = PerfMode.contentRate( + PerfMode.pacedRate(ownLimit, guestFrameRate, guestRefresh, contentCadence.rate), + frameGen?.outputFactor ?: 1, frameGen?.target ?: 0, + ) + Log.i(TAG, "perf: " + PerfMode.apply(this, content, mirrorRefreshLimit(), if (ownLimit > 0) 0 else guestRefresh, panelHeld)) + uiHandler.removeCallbacks(panelHeldCheck) + if (!panelHeld) uiHandler.postDelayed(panelHeldCheck, PANEL_HELD_CHECK_MS) if (CompositorHost.isStarted) { + WaylandCompositor.nativeSetPanelRates( + if (glassesScreen == null && !bottomOutputActive) PerfMode.panelRates(this, mirrorRefreshLimit(), panelHeld) + else IntArray(0), + ) val hz = refreshHz() val changed = kotlin.math.abs(SessionState.refreshHz - hz) > 0.1f CompositorHost.updatePacing(hz, outputFpsLimit()) @@ -3149,6 +3210,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (frameGenActivityGeneration != frameGenGlobalGeneration.get()) return@runOnUiThread lossless = state if (problem != null) Toast.makeText(this, problem, Toast.LENGTH_LONG).show() + if (appliedFrameGenMode != pacedFrameGenMode) applyOutputPacing() } }, "frame-gen").start() } @@ -3749,8 +3811,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } - private val relativeMouseRequests = java.util.concurrent.Executors.newSingleThreadExecutor { runnable -> - Thread(runnable, "relative-mouse").apply { isDaemon = true } + private val gamescopeConvarRequests = java.util.concurrent.Executors.newSingleThreadExecutor { runnable -> + Thread(runnable, "gamescope-convar").apply { isDaemon = true } } @Volatile private var desiredRelativeMouseMode = 0 @@ -3763,7 +3825,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun requestRelativeMouse() { - runCatching { relativeMouseRequests.execute { applyRelativeMouse() } } + runCatching { gamescopeConvarRequests.execute { applyRelativeMouse() } } } private fun applyRelativeMouse() { @@ -3777,23 +3839,58 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde )) == com.droiddeck.launcher.input.TouchRouter.Route.TOUCHPAD val mode = com.droiddeck.launcher.input.TouchGestureConfig.gamescopeRelativeMouse(wanted, mouseAttached(), touchpadRoute) if (appliedRelativeMouseMode == mode) return - val request = org.json.JSONObject() - .put("kind", "exec") - .put("argv", org.json.JSONArray(listOf("gamescopectl", "relative_mouse", mode.toString()))) - .put("timeout", 5.0) - val result = runCatching { AgentGuest.call(this, request, 8_000, trusted = true) } - val answer = result.getOrNull() - val applied = answer?.optBoolean("ok") == true - && answer.optInt("exitCode", -1) == 0 - && !answer.optBoolean("timedOut") - if (applied) appliedRelativeMouseMode = mode - else { - Log.w(TAG, "gamescope did not take relative mouse $mode: ${result.exceptionOrNull() ?: answer}") - if (relativeMouseRetries++ < RELATIVE_MOUSE_MAX_RETRIES) uiHandler.postDelayed({ requestRelativeMouse() }, 2_000) - } + if (AgentGuest.setGamescopeConvar(this, "relative_mouse", mode)) appliedRelativeMouseMode = mode + else if (relativeMouseRetries++ < RELATIVE_MOUSE_MAX_RETRIES) uiHandler.postDelayed({ requestRelativeMouse() }, 2_000) if (desiredRelativeMouseMode != wanted) requestRelativeMouse() } + @Volatile private var desiredOverlayPlanes = -1 + @Volatile private var appliedOverlayPlanes: Int? = -1 + @Volatile private var overlayPlanesRetries = 0 + @Volatile private var guestRefresh = 0 + @Volatile private var guestFrameRate = 0 + private var pacedFrameGenMode: FrameGen.Mode? = null + private val contentCadence = ContentCadence() + private val contentRateListener = WaylandCompositor.ContentRateListener { fps -> + runOnUiThread { + if (isDestroyed) return@runOnUiThread + val changed = if (fps > 0) contentCadence.note(fps, PerfMode.panelRates(this, mirrorRefreshLimit(), panelHeld)) + else contentCadence.reset() + if (changed) { + Log.i(TAG, "perf: steady content rate " + contentCadence.rate + " fps") + applyOutputPacing() + } + } + } + private val refreshTargetListener = WaylandCompositor.RefreshTargetListener { refresh, frameRate -> + runOnUiThread { + if (isDestroyed) return@runOnUiThread + if (guestRefresh != refresh || guestFrameRate != frameRate) { + guestRefresh = refresh + guestFrameRate = frameRate + applyOutputPacing() + } + } + } + + private val overlayPlanesListener = WaylandCompositor.OverlayPlanesListener { planes -> + desiredOverlayPlanes = planes + overlayPlanesRetries = 0 + requestOverlayPlanes() + } + + private fun requestOverlayPlanes() { + runCatching { gamescopeConvarRequests.execute { applyOverlayPlanes() } } + } + + private fun applyOverlayPlanes() { + val wanted = desiredOverlayPlanes + if (appliedOverlayPlanes == wanted) return + if (AgentGuest.setGamescopeConvar(this, "wayland_overlay_planes", wanted)) appliedOverlayPlanes = wanted + else if (overlayPlanesRetries++ < RELATIVE_MOUSE_MAX_RETRIES) uiHandler.postDelayed({ requestOverlayPlanes() }, 2_000) + if (desiredOverlayPlanes != wanted) requestOverlayPlanes() + } + private fun refreshGestureConfig() { gestureConfig = com.droiddeck.launcher.input.GesturePrefs.read(this, gestureGame) directHoldBehavior = gestureConfig.directHoldBehavior @@ -5754,6 +5851,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde updatePadMotion() ControllerPrefs.prefs(this).registerOnSharedPreferenceChangeListener(shortcutPrefListener) SessionPrefs.sessionPrefs(this).registerOnSharedPreferenceChangeListener(screenEffectsProfilePrefListener) + SessionPrefs.sessionPrefs(this).registerOnSharedPreferenceChangeListener(hdrPrefListener) observedScreenEffectsProfileId = SessionPrefs.activeScreenEffectsProfileId(this) readPrefs() observedScreenEffectsProfileId = SessionPrefs.activeScreenEffectsProfileId(this) @@ -5824,6 +5922,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde hidePrimaryKeyboard() pendingFieldKeyboard = pendingKeyboard SessionPrefs.sessionPrefs(this).unregisterOnSharedPreferenceChangeListener(cardboardPrefListener) + SessionPrefs.sessionPrefs(this).unregisterOnSharedPreferenceChangeListener(hdrPrefListener) SessionPrefs.sessionPrefs(this).unregisterOnSharedPreferenceChangeListener(screenEffectsProfilePrefListener) ControllerPrefs.prefs(this).unregisterOnSharedPreferenceChangeListener(shortcutPrefListener) updateHeadTracker() @@ -6438,6 +6537,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } override fun onDestroy() { + uiHandler.removeCallbacks(panelHeldCheck) + uiHandler.removeCallbacks(panelHeldRetry) synchronized(frameGenGlobalLock) { frameGenActivityActive = false frameGenRequests.incrementAndGet() @@ -6445,7 +6546,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (AgentGuest.readyListener === agentReadyListener) AgentGuest.readyListener = null if (com.droiddeck.launcher.agent.AgentAttachments.gameFrame === gameFrame) com.droiddeck.launcher.agent.AgentAttachments.gameFrame = null com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this) - relativeMouseRequests.shutdownNow() + gamescopeConvarRequests.shutdownNow() backQamInput.cancel() steamVrRecovery.close() uiHandler.removeCallbacks(steamTouchRetry) @@ -6488,6 +6589,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (SessionState.endListener === endListener) SessionState.endListener = null WaylandCompositor.clearFirstFrameListener(firstFrameListener) WaylandCompositor.clearPointerLockListener(pointerLockListener) + WaylandCompositor.clearOverlayPlanesListener(overlayPlanesListener) + WaylandCompositor.clearRefreshTargetListener(refreshTargetListener) + WaylandCompositor.clearContentRateListener(contentRateListener) super.onDestroy() } @@ -6562,6 +6666,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde const val EXTRA_STEAMVR = "steamVr" const val EXTRA_PLAYED_GAME = "com.droiddeck.launcher.PLAYED_GAME" const val EXTRA_REPAIR_RUNTIME = "repairRuntime" + private const val PANEL_HELD_CHECK_MS = 2_500L + private const val PANEL_HELD_RETRY_MS = 60_000L private const val LEAVE_TIMEOUT_MS = 1_500L private const val TEXT_FIELD_TAP_MS = 1_000L private const val PAUSED_FRAME_MAX_EDGE = 1920f diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentGuest.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentGuest.kt index e04dda2580..abe8abb3a3 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentGuest.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentGuest.kt @@ -230,6 +230,20 @@ object AgentGuest { call(context, JSONObject().put("kind", "cdp").put("expression", expression).put("timeout", timeoutMs / 1000.0), timeoutMs + 2_000, trusted = true) + fun setGamescopeConvar(context: Context, name: String, value: Int): Boolean { + val request = JSONObject() + .put("kind", "exec") + .put("argv", org.json.JSONArray(listOf("gamescopectl", name, value.toString()))) + .put("timeout", 5.0) + val result = runCatching { call(context, request, 8_000, trusted = true) } + val answer = result.getOrNull() + val applied = answer?.optBoolean("ok") == true + && answer.optInt("exitCode", -1) == 0 + && !answer.optBoolean("timedOut") + if (!applied) Log.w(TAG, "gamescope did not take $name $value: ${result.exceptionOrNull() ?: answer}") + return applied + } + fun call(context: Context, request: JSONObject, timeoutMs: Long, trusted: Boolean = false): JSONObject { if (!trusted && request.optString("kind") in setOf("exec", "cdp")) AgentAccess.requireCommands(context) if (!SessionState.running) throw AgentException("NO_ACTIVE_SESSION", "There is no running session") diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt b/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt index 1623c10106..25124a6a52 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt @@ -21,6 +21,8 @@ object FrameGen { private const val PREFS = "frame_gen" data class Mode(val engine: String, val multiplier: Int = 2, val target: Int = 0) { + val outputFactor: Int get() = if (engine == ENGINE_OFF) 1 else multiplier + companion object { val OFF = Mode(ENGINE_OFF) } diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/LinuxVulkanDriverManager.java b/app/src/main/java/com/droiddeck/launcher/gpu/LinuxVulkanDriverManager.java index 4f0b62eddb..11fc19c877 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/LinuxVulkanDriverManager.java +++ b/app/src/main/java/com/droiddeck/launcher/gpu/LinuxVulkanDriverManager.java @@ -89,6 +89,11 @@ public class LinuxVulkanDriverManager { return m != null ? m.optString("minGlibc", "") : ""; } + public boolean rendersToDisplayBuffers(String id) { + JSONObject m = id == null || id.isEmpty() ? null : readMeta(id); + return m != null && m.optBoolean("displayBuffers", false); + } + public void removeDriver(String id) { if (id == null || id.isEmpty() || id.contains("/") || id.contains("..")) return; Log.d(TAG, "removing imported Linux Vulkan driver " + id); @@ -182,6 +187,7 @@ public class LinuxVulkanDriverManager { meta.put("driverVersion", version); meta.put("libc", "glibc"); meta.put("minGlibc", minGlibc); + meta.put("displayBuffers", zipMeta != null && zipMeta.optBoolean("displayBuffers", false)); meta.put("sourceLibraryName", soName); meta.put("libraryName", stored); meta.put("importedAt", System.currentTimeMillis()); diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/ScreenEffects.kt b/app/src/main/java/com/droiddeck/launcher/gpu/ScreenEffects.kt index 84b29bd5d9..c3ecfa5145 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/ScreenEffects.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/ScreenEffects.kt @@ -2,6 +2,7 @@ package com.droiddeck.launcher.gpu import androidx.annotation.StringRes import com.droiddeck.launcher.R +import com.droiddeck.launcher.session.SessionState import com.droiddeck.launcher.wayland.WaylandCompositor import org.json.JSONObject import kotlin.math.abs @@ -30,7 +31,7 @@ data class ScreenEffects( fun push(upscaler: Int) { WaylandCompositor.nativeSetCas(cas, casLevel) - WaylandCompositor.nativeSetHdr(hdr) + WaylandCompositor.nativeSetHdr(hdr && !SessionState.hdrDisplay) WaylandCompositor.nativeSetDeband(deband, debandStrength) WaylandCompositor.nativeSetScreenEffects(brightness.toFloat(), contrast.toFloat(), gamma, saturation.toFloat(), aaMode, toon, crt, ntsc) WaylandCompositor.nativeSetLookName(ScreenEffectLooks.match(this, upscaler)?.name) diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt b/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt index 0f5c48ce21..e589c5c8b5 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt @@ -17,6 +17,9 @@ import android.provider.Settings import android.util.Log import com.droiddeck.launcher.core.SessionPart import com.droiddeck.launcher.R +import com.droiddeck.launcher.session.SessionHdr +import com.droiddeck.launcher.session.SessionPrefs +import com.droiddeck.launcher.session.SessionState import java.io.File import java.nio.file.Files import java.nio.file.StandardCopyOption @@ -74,8 +77,10 @@ class DeviceControlsComponent(context: Context, root: File, private val activity val value = Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 128) write("backlight/droiddeck/brightness", "$value\n") write("backlight/droiddeck/actual_brightness", "$value\n") - val state = JSONObject().put("brightness", (value.coerceIn(1, 255) - 1) / 254.0) - .put("brightnessWritable", Settings.System.canWrite(context)).toString() + val controls = JSONObject().put("brightness", (value.coerceIn(1, 255) - 1) / 254.0) + .put("brightnessWritable", Settings.System.canWrite(context)) + if (SessionState.hdrCapable) controls.put("hdr", SessionState.hdr) + val state = controls.toString() if (force || state != previous) { write("state.json", JSONObject(state).put("revision", ++revision).toString()) previous = state @@ -132,6 +137,9 @@ class DeviceControlsComponent(context: Context, root: File, private val activity audio.setStreamVolume(AudioManager.STREAM_MUSIC, it.coerceIn(0, audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC)), 0) } + "hdr.request" -> if (text == "0" || text == "1") { + SessionHdr.set(context, SessionPrefs.prefMode(SessionState.mode), text == "1") + } "mute.request" -> if (text == "0" || text == "1") { audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, if (text == "1") AudioManager.ADJUST_MUTE else AudioManager.ADJUST_UNMUTE, 0) @@ -196,7 +204,7 @@ class DeviceControlsComponent(context: Context, root: File, private val activity private const val STREAM_MUTE_CHANGED_ACTION = "android.media.STREAM_MUTE_CHANGED_ACTION" private const val PERMISSION_CHANNEL = "brightness_permission" private const val PERMISSION_NOTIFICATION = 0x4442 - private val REQUESTS = setOf("brightness.request", "volume.request", "mute.request") + private val REQUESTS = setOf("brightness.request", "volume.request", "mute.request", "hdr.request") @JvmStatic fun directory(root: File) = File(root, "etc/droiddeck-device-controls") @JvmStatic fun prepareBacklight(context: Context, root: File): File { val base = File(directory(root), "backlight") diff --git a/app/src/main/java/com/droiddeck/launcher/session/ContentCadence.kt b/app/src/main/java/com/droiddeck/launcher/session/ContentCadence.kt new file mode 100644 index 0000000000..a0a5fae498 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/ContentCadence.kt @@ -0,0 +1,65 @@ +package com.droiddeck.launcher.session + +class ContentCadence { + var rate = 0 + private set + private var candidate = 0 + private var streak = 0 + private var misses = 0 + private val reengage = HashMap() + + fun note(fps: Int, panelRates: IntArray): Boolean { + val snapped = snap(fps, panelRates) + if (rate != 0) { + if (snapped == rate) { + misses = 0 + return false + } + if (++misses < RELEASE_SAMPLES) return false + reengage[rate] = minOf((reengage[rate] ?: ENGAGE_SAMPLES) * 2, MAX_ENGAGE_SAMPLES) + rate = 0 + misses = 0 + candidate = snapped + streak = if (snapped > 0) 1 else 0 + return true + } + if (snapped == 0 || snapped != candidate) { + candidate = snapped + streak = if (snapped > 0) 1 else 0 + return false + } + if (++streak < (reengage[snapped] ?: ENGAGE_SAMPLES)) return false + rate = snapped + misses = 0 + return true + } + + fun reset(): Boolean { + val engaged = rate != 0 + rate = 0 + candidate = 0 + streak = 0 + misses = 0 + return engaged + } + + companion object { + const val ENGAGE_SAMPLES = 3 + const val RELEASE_SAMPLES = 3 + const val MAX_ENGAGE_SAMPLES = 30 + private const val MIN_FPS = 20 + private const val MAX_DIVISOR = 6 + + fun snap(fps: Int, panelRates: IntArray): Int { + if (fps < MIN_FPS) return 0 + var best = 0 + for (hz in panelRates) for (divisor in 1..MAX_DIVISOR) { + if (hz % divisor != 0) continue + val step = hz / divisor + val miss = Math.abs(step - fps) + if (miss <= 1 && (best == 0 || miss < Math.abs(best - fps) || (miss == Math.abs(best - fps) && step > best))) best = step + } + return best + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/PerfMode.kt b/app/src/main/java/com/droiddeck/launcher/session/PerfMode.kt index 531f5f4607..71e97a9fcc 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/PerfMode.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/PerfMode.kt @@ -13,15 +13,19 @@ object PerfMode { private const val TAG = "PerfMode" const val BFI_MIN_REFRESH_HZ = 100f - fun apply(a: Activity, fpsLimit: Int = 0, refreshLimit: Int = 0): String { + fun apply(a: Activity, fpsLimit: Int = 0, refreshLimit: Int = 0, requestedRefresh: Int = 0, held: Boolean = false): String { val parts = ArrayList(2) parts += try { val display = if (Build.VERSION.SDK_INT >= 30) a.display else @Suppress("DEPRECATION") a.windowManager.defaultDisplay - if (display == null || Build.VERSION.SDK_INT < 23) "display mode unchanged" else { + if (display == null || Build.VERSION.SDK_INT < 23) "display mode unchanged" else if (held) { + if (a.window.attributes.preferredDisplayModeId != 0) { + a.window.attributes = a.window.attributes.apply { preferredDisplayModeId = 0 } + } + "display ${display.mode.refreshRate.toInt()} Hz (set by the system)" + } else { val cur = display.mode - val cap = minOf(peakRefreshCap(a), refreshLimit.takeIf { it > 0 }?.toFloat() ?: Float.POSITIVE_INFINITY) - val best = selectMode(display.supportedModes, cur, fpsLimit, cap) + val best = selectMode(display.supportedModes, cur, fpsLimit, refreshCap(a, refreshLimit), requestedRefresh) if (best != null && needsChange(display.supportedModes, a.window.attributes.preferredDisplayModeId, best)) { a.window.attributes = a.window.attributes.apply { preferredDisplayModeId = best.modeId } "display ${cur.refreshRate.toInt()} → ${best.refreshRate.toInt()} Hz (mode ${best.modeId})" @@ -55,12 +59,64 @@ object PerfMode { return if (peak >= 1f) peak else Float.POSITIVE_INFINITY } - internal fun selectMode(modes: Array, current: Display.Mode, fpsLimit: Int, cap: Float): Display.Mode? { + private fun refreshCap(context: Context, refreshLimit: Int): Float = + minOf(peakRefreshCap(context), refreshLimit.takeIf { it > 0 }?.toFloat() ?: Float.POSITIVE_INFINITY) + + fun panelRates(a: Activity, refreshLimit: Int = 0, held: Boolean = false): IntArray = try { + val display = if (Build.VERSION.SDK_INT >= 30) a.display else @Suppress("DEPRECATION") a.windowManager.defaultDisplay + if (display == null || Build.VERSION.SDK_INT < 23) IntArray(0) + else panelRates(display.supportedModes, display.mode, refreshCap(a, refreshLimit), held) + } catch (t: Throwable) { Log.w(TAG, "panel rates", t); IntArray(0) } + + internal fun panelRates(modes: Array, current: Display.Mode, cap: Float, held: Boolean = false): IntArray = + if (held) intArrayOf(Math.round(current.refreshRate)) + else allowedModes(modes, current, cap).map { Math.round(it.refreshRate) }.distinct().sorted().toIntArray() + + fun panelHeld(a: Activity): Boolean = try { + val display = if (Build.VERSION.SDK_INT >= 30) a.display else @Suppress("DEPRECATION") a.windowManager.defaultDisplay + val wanted = a.window.attributes.preferredDisplayModeId + val requested = display?.supportedModes?.firstOrNull { wanted != 0 && it.modeId == wanted } + display != null && requested != null && panelHeld(requested.refreshRate, display.mode.refreshRate) + } catch (t: Throwable) { Log.w(TAG, "panel held", t); false } + + internal fun panelHeld(requestedHz: Float, activeHz: Float): Boolean = + requestedHz > 1f && activeHz > 1f && Math.abs(requestedHz - activeHz) > 0.5f + + fun pacedRate(ownLimit: Int, limiterRate: Int, limiterRefresh: Int, steadyRate: Int): Int = when { + ownLimit > 0 -> ownLimit + limiterRate <= 0 -> steadyRate + steadyRate <= 0 || limiterRate < limiterRefresh || limiterRefresh <= 0 -> limiterRate + cadenceFits(limiterRate.toFloat(), steadyRate) -> limiterRate + else -> steadyRate + } + + fun contentRate(fps: Int, frameGenFactor: Int, frameGenTarget: Int): Int = when { + frameGenFactor <= 1 -> fps + frameGenTarget > 0 -> frameGenTarget + else -> fps * frameGenFactor + } + + private fun allowedModes(modes: Array, current: Display.Mode, cap: Float): List = + modes.filter { + it.physicalWidth == current.physicalWidth && it.physicalHeight == current.physicalHeight && + it.refreshRate <= cap + 0.5f + } + + internal fun selectMode( + modes: Array, + current: Display.Mode, + fpsLimit: Int, + cap: Float, + requestedRefresh: Int = 0, + ): Display.Mode? { val sameSize = modes.filter { it.physicalWidth == current.physicalWidth && it.physicalHeight == current.physicalHeight } - val allowed = sameSize.filter { it.refreshRate <= cap + 0.5f } - return allowed.filter { cadenceFits(it.refreshRate, fpsLimit) }.maxByOrNull { it.refreshRate } + val allowed = allowedModes(modes, current, cap) + val requested = if (fpsLimit > 0 || requestedRefresh <= 0) null else allowed + .filter { it.refreshRate >= requestedRefresh - 0.5f }.minByOrNull { it.refreshRate } + return requested + ?: allowed.filter { cadenceFits(it.refreshRate, fpsLimit) }.maxByOrNull { it.refreshRate } ?: allowed.maxByOrNull { it.refreshRate } ?: sameSize.minByOrNull { it.refreshRate } } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionHdr.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionHdr.kt new file mode 100644 index 0000000000..e559ac4ff0 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionHdr.kt @@ -0,0 +1,36 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import com.droiddeck.launcher.agent.AgentGuest +import com.droiddeck.launcher.wayland.CompositorHost +import com.droiddeck.launcher.wayland.WaylandCompositor +import java.util.concurrent.Executors + +object SessionHdr { + private const val RETRIES = 5 + private const val RETRY_MS = 2_000L + + private val requests = Executors.newSingleThreadExecutor { runnable -> + Thread(runnable, "session-hdr").apply { isDaemon = true } + } + @Volatile private var wanted = false + + fun set(context: Context, mode: String, on: Boolean) { + SessionPrefs.setHdr(context, mode, on) + if (!SessionState.running || !SessionState.hdrCapable || !CompositorHost.isStarted) return + if (SessionPrefs.prefMode(SessionState.mode) != mode) return + SessionState.hdr = on + wanted = on + WaylandCompositor.nativeSetHdrOutput(on) + WaylandCompositor.nativeSetZeroCopy(on || SessionPrefs.zeroCopy(context, mode)) + val app = context.applicationContext + val session = SessionState.sessionId + requests.execute { + var tries = 0 + while (wanted == on && SessionState.running && SessionState.sessionId == session && + !AgentGuest.setGamescopeConvar(app, "hdr_enabled", if (on) 1 else 0) && tries++ < RETRIES) { + try { Thread.sleep(RETRY_MS) } catch (e: InterruptedException) { return@execute } + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 2c87bb86ce..ab258b95ce 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -1620,10 +1620,18 @@ object SessionPrefs { return Pair(w and 1.inv(), h and 1.inv()) } - fun hdr(context: Context, mode: String): Boolean = prefs(context).getBoolean("hdr.$mode", false) + fun hdrKey(mode: String): String = "hdr.$mode" + + fun hdr(context: Context, mode: String): Boolean = prefs(context).getBoolean(hdrKey(mode), false) fun setHdr(context: Context, mode: String, on: Boolean) { - prefs(context).edit().putBoolean("hdr.$mode", on).apply() + prefs(context).edit().putBoolean(hdrKey(mode), on).apply() + } + + fun zeroCopy(context: Context, mode: String): Boolean = prefs(context).getBoolean("zeroCopy.$mode", true) + + fun setZeroCopy(context: Context, mode: String, on: Boolean) { + prefs(context).edit().putBoolean("zeroCopy.$mode", on).apply() } const val FPS_UNPACED = -1 diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index 285f6b7c08..5d78730013 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -1025,6 +1025,9 @@ class SessionService : Service() { if (!bridge && !venus && SystemVulkanDriver.usesDefault(linuxDriverId)) { SystemVulkanDriver.addEnvironment(this, guest) } + com.droiddeck.launcher.wayland.WaylandCompositor.nativeSetDisplayBufferDriver( + !bridge && !venus && LinuxVulkanDriverManager(this).rendersToDisplayBuffers(linuxDriverId), + ) (if (bridge || venus) null else LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)) ?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) } if (!com.droiddeck.launcher.core.DeviceSupport.adreno() && lastXwaylandCrashed()) { diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt index 6124947151..847ed340b6 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt @@ -115,6 +115,10 @@ object SessionState { @JvmStatic var hdr = false + @JvmStatic var hdrCapable = false + + @JvmStatic var hdrDisplay = false + @Volatile private var deckPadValue = false @JvmStatic var deckPad: Boolean get() = deckPadValue diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt index 1cc0393388..f871406fce 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -59,6 +59,8 @@ class ModeSettings( val panelSize: Pair = 1280 to 720, val hdr: Boolean, val hdrReason: String?, + val hdrDisplay: Boolean = true, + val zeroCopy: Boolean = true, val gpuDrivers: String? = null, val upscaler: Int = 0, val upscaleSharpness: Int = 75, @@ -114,6 +116,7 @@ class ModeSettings( class ModeSettingsActions( val onResolution: (String) -> Unit, val onHdr: (Boolean) -> Unit, + val onZeroCopy: (Boolean) -> Unit = {}, val onGpuDrivers: () -> Unit = {}, val onUpscaler: (Int) -> Unit = {}, val onUpscaleSharpness: (Int) -> Unit = {}, @@ -250,6 +253,7 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: listOf(false to stringResource(R.string.display_preserve), true to stringResource(R.string.display_stretch)), s.stretch16x9 && canStretch, enabled = canStretch, onPick = a.onStretch16x9) } + ToggleRow(host, "zero-copy", stringResource(R.string.display_zero_copy), null, checked = s.zeroCopy, onChange = a.onZeroCopy) } SettingsGroup(stringResource(R.string.display_image_scaling)) { s.integerScaling?.let { enabled -> @@ -276,9 +280,8 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: } SettingsGroup(stringResource(R.string.mode_hdr)) { ToggleRow( - host, "hdr", stringResource(R.string.mode_hdr10), - s.hdrReason?.let { stringResource(R.string.mode_hdr_unavailable, it) } - ?: stringResource(R.string.mode_hdr_restart), + host, "hdr", stringResource(if (s.hdrDisplay) R.string.mode_hdr10 else R.string.drawer_fake_hdr), + s.hdrReason?.let { stringResource(R.string.mode_hdr_unavailable, it) }, checked = s.hdr && s.hdrReason == null, enabled = s.hdrReason == null, onChange = a.onHdr, ) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index 09e169e73b..9c244b930f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -281,6 +281,9 @@ class DrawerActions( val blackFrameInsertion: Boolean = false, val blackFrameInsertionAvailable: Boolean = false, val onBlackFrameInsertion: (Boolean) -> Unit = {}, + val hdr: Boolean = false, + val hdrAvailable: Boolean = false, + val onHdr: (Boolean) -> Unit = {}, val onImportLossless: () -> Unit, val onKeyboard: () -> Unit, val onHardwareKeyboard: () -> Unit, @@ -1161,7 +1164,9 @@ private fun ScreenEffectsGroup( ToggleRow(host, "toon", stringResource(R.string.drawer_toon), null, e.toon, chipModifier = track("toon")) { a.onEffects(e.copy(toon = it)) } ToggleRow(host, "crt", stringResource(R.string.drawer_crt), null, e.crt, chipModifier = track("crt")) { a.onEffects(e.copy(crt = it)) } ToggleRow(host, "ntsc", stringResource(R.string.drawer_ntsc), null, e.ntsc, chipModifier = track("ntsc")) { a.onEffects(e.copy(ntsc = it)) } - ToggleRow(host, "fake-hdr", stringResource(R.string.drawer_fake_hdr), null, e.hdr, chipModifier = track("fake-hdr")) { a.onEffects(e.copy(hdr = it)) } + if (a.hdrAvailable) ToggleRow(host, "hdr", stringResource(R.string.mode_hdr), null, a.hdr, + chipModifier = track("hdr"), onChange = a.onHdr) + else ToggleRow(host, "fake-hdr", stringResource(R.string.drawer_fake_hdr), null, e.hdr, chipModifier = track("fake-hdr")) { a.onEffects(e.copy(hdr = it)) } if (a.blackFrameInsertionAvailable) ToggleRow(host, "bfi", stringResource(R.string.drawer_bfi), stringResource(R.string.drawer_bfi_note), a.blackFrameInsertion, chipModifier = track("bfi"), onChange = a.onBlackFrameInsertion) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt index 135cd79a63..9f9c1b4a4e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt @@ -137,7 +137,7 @@ internal object SettingsIndex { SettingsEntry(SettingsPlace.STEAM_QAM, R.string.drawer_frame_limit, R.string.perf_title, words = listOf("fps", "cap", "limit", "steam games")), SettingsEntry(SettingsPlace.STEAM_QAM, R.string.perf_title, words = listOf("performance overlay", "fps", "counter", "tdp")), - sh(R.string.drawer_page_display, R.string.display_session, "resolution", "scaling", "hdr", "refresh"), + sh(R.string.drawer_page_display, R.string.display_session, "resolution", "scaling", "hdr", "refresh", "zero-copy"), sh(R.string.drawer_page_display, R.string.sheet_graphics_drivers, "turnip", "driver", "gpu", "adreno", "mali"), sh(R.string.mode_tab_steam, R.string.setup_offline, "offline", "steam"), sh(R.string.mode_audio, R.string.mode_mic, "microphone", "voice"), diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt index 4ad4263161..8d43d09c7b 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.wayland +import android.os.Build import android.os.Handler import android.os.HandlerThread import android.os.Process @@ -29,11 +30,28 @@ object CompositorHost { @Volatile private var vsyncGeneration = 0 - private fun vsyncCallback(generation: Int) = object : Choreographer.FrameCallback { - override fun doFrame(frameTimeNanos: Long) { - if (generation != vsyncGeneration) return + private fun postVsync(generation: Int) { + val choreographer = Choreographer.getInstance() + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + choreographer.postVsyncCallback { data -> + if (generation != vsyncGeneration) return@postVsyncCallback + val lines = data.frameTimelines + val line = data.preferredFrameTimeline + val period = if (lines.size > 1) { + lines[1].expectedPresentationTimeNanos - lines[0].expectedPresentationTimeNanos + } else { + 0L + } + WaylandCompositor.nativeFrameTimeline(line.expectedPresentationTimeNanos, line.deadlineNanos, period) + WaylandCompositor.nativeVsync(data.frameTimeNanos) + if (vsyncRunning) postVsync(generation) + } + return + } + choreographer.postFrameCallback { frameTimeNanos -> + if (generation != vsyncGeneration) return@postFrameCallback WaylandCompositor.nativeVsync(frameTimeNanos) - if (vsyncRunning) Choreographer.getInstance().postFrameCallback(this) + if (vsyncRunning) postVsync(generation) } } @@ -149,14 +167,14 @@ object CompositorHost { private fun resumeVsync() { if (vsyncRunning) return - val callback = vsyncCallback(++vsyncGeneration) + val generation = ++vsyncGeneration vsyncRunning = true WaylandCompositor.nativeLog("screen", if (ownVsyncThread) "screen tick runs on its own display-priority thread" else "screen tick runs on the main thread") if (!ownVsyncThread) { - Choreographer.getInstance().postFrameCallback(callback) + postVsync(generation) return } - vsyncHandler.post { Choreographer.getInstance().postFrameCallback(callback) } + vsyncHandler.post { postVsync(generation) } } private fun pauseVsync() { diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/HdrSupport.kt b/app/src/main/java/com/droiddeck/launcher/wayland/HdrSupport.kt index 91f408d916..0a5cb88be2 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/HdrSupport.kt +++ b/app/src/main/java/com/droiddeck/launcher/wayland/HdrSupport.kt @@ -48,8 +48,11 @@ object HdrSupport { ) } + fun blocked(context: Context): String? = + if (Build.VERSION.SDK_INT < 29) context.getString(R.string.hdr_needs_android_10) else null + private fun reason(context: Context, hdr10: Boolean, formats: String): String? = when { - Build.VERSION.SDK_INT < 29 -> context.getString(R.string.hdr_needs_android_10) + Build.VERSION.SDK_INT < 29 -> blocked(context) !hdr10 -> if (formats.isEmpty()) context.getString(R.string.hdr_none) else context.getString(R.string.hdr_not_hdr10, formats) else -> null } diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java index 874493e41c..81543e6d1c 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java +++ b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java @@ -94,6 +94,73 @@ public final class WaylandCompositor { if (l != null) l.onPointerLock(locked, x, y); } + public interface OverlayPlanesListener { + void onOverlayPlanes(int planes); + } + + private static volatile OverlayPlanesListener overlayPlanesListener; + private static volatile int overlayPlanes = -1; + + public static synchronized void setOverlayPlanesListener(OverlayPlanesListener l) { + overlayPlanesListener = l; + if (l != null) l.onOverlayPlanes(overlayPlanes); + } + + public static synchronized void clearOverlayPlanesListener(OverlayPlanesListener l) { + if (overlayPlanesListener == l) overlayPlanesListener = null; + } + + @SuppressWarnings("unused") + static synchronized void onOverlayPlanes(int planes) { + overlayPlanes = planes; + OverlayPlanesListener l = overlayPlanesListener; + if (l != null) l.onOverlayPlanes(planes); + } + + public interface RefreshTargetListener { + void onRefreshTarget(int refresh, int frameRate); + } + + private static volatile RefreshTargetListener refreshTargetListener; + private static volatile long refreshTarget; + + public static void setRefreshTargetListener(RefreshTargetListener l) { + refreshTargetListener = l; + long target = refreshTarget; + if (l != null) l.onRefreshTarget((int) (target >> 32), (int) target); + } + + public static void clearRefreshTargetListener(RefreshTargetListener l) { + if (refreshTargetListener == l) refreshTargetListener = null; + } + + public interface ContentRateListener { + void onContentRate(int fps); + } + + private static volatile ContentRateListener contentRateListener; + + public static void setContentRateListener(ContentRateListener l) { + contentRateListener = l; + } + + public static void clearContentRateListener(ContentRateListener l) { + if (contentRateListener == l) contentRateListener = null; + } + + @SuppressWarnings("unused") + static void onContentRate(int fps) { + ContentRateListener l = contentRateListener; + if (l != null) l.onContentRate(fps); + } + + @SuppressWarnings("unused") + static void onRefreshTarget(int refresh, int frameRate) { + refreshTarget = ((long) refresh << 32) | (frameRate & 0xffffffffL); + RefreshTargetListener l = refreshTargetListener; + if (l != null) l.onRefreshTarget(refresh, frameRate); + } + public interface ClipboardListener { void onGuestClipboardText(String text); } @@ -180,6 +247,8 @@ public final class WaylandCompositor { public static native void nativeVsync(long frameTimeNanos); + public static native void nativeFrameTimeline(long presentNanos, long deadlineNanos, long periodNanos); + public static native void nativeSetClockControl(String path); public static native int nativeCompositorTid(); @@ -210,8 +279,12 @@ public final class WaylandCompositor { public static native void nativeSetOutputRefreshRate(float hz); + public static native void nativeSetPanelRates(int[] rates); + public static native void nativeSetZeroCopy(boolean on); + public static native void nativeSetDisplayBufferDriver(boolean on); + public static native int nativeZeroCopyFrames(); public static native int nativeZeroCopyLastFrameAgeMs(); @@ -247,7 +320,7 @@ public final class WaylandCompositor { public static native void nativeResetFirstFrame(); - public static final int HDR_MODE_OFF = 0, HDR_MODE_ON = 1, HDR_MODE_FORCE = 2; + public static final int HDR_MODE_OFF = 0, HDR_MODE_ON = 1, HDR_MODE_FORCE = 2, HDR_MODE_TONEMAP = 3; public static native void nativeSetHdrRequest(int mode, String source, boolean dxvkHdr, boolean zeroCopyForced); diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 6433943918..f9d6d205b2 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -281,7 +281,6 @@ HDR إخراج HDR10 غير متاح: %1$s. - أعد تشغيل التطبيق لتطبيق التغيير. برامج التشغيل برامج تشغيل GPU مشتركة بين Steam وسطح المكتب. يتم ضبطها في صفحة «المكوّنات». @@ -2565,6 +2564,7 @@ Android + Linux %1$s. %2$s\n\n%3$s شاشة الجلسة + العرض بدون نسخ الدقة ملاءمة اللعبة لنسبة 16:9 كيفية ملاءمة ألعاب 16:9 لهذه الشاشة. يُطبَّق في الجلسة التالية. diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 922b1407f3..194e5d3afb 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -281,7 +281,6 @@ HDR Salida HDR10 No disponible: %1$s. - Reinicia la app para aplicarlo. Controladores Controladores de GPU Compartidos por Steam y Escritorio. Se definen en la página Componentes. @@ -2557,6 +2556,7 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Pantalla de la sesión + Presentación sin copia Resolución Ajuste de juegos 16:9 Cómo se ajustan los juegos 16:9 a esta pantalla. Próxima sesión. diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index 57566ec959..03ba45f845 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -281,7 +281,6 @@ HDR HDR10 изход Не е налично: %1$s. - Рестартирайте приложението, за да се приложи. Драйвери GPU драйвери Общи за Steam и работния плот. Задават се в страницата Компоненти. @@ -2461,6 +2460,7 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Екран на сесията + Представяне без копиране Разделителна способност Напасване на игра 16:9 Как игрите с 16:9 се напасват на този екран. При следващата сесия. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index c2b89c6e12..246926fff0 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -281,7 +281,6 @@ HDR Výstup HDR10 Není k dispozici: %1$s. - Pro použití restartujte aplikaci. Ovladače Ovladače GPU Společné pro Steam a Plochu. Nastavuje se na stránce Komponenty. @@ -2513,6 +2512,7 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Obrazovka relace + Zobrazení bez kopírování Rozlišení Přizpůsobení hry 16:9 Jak se hry s poměrem 16:9 přizpůsobí této obrazovce. Příští relace. diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 67037ab952..dc190f6e62 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -281,7 +281,6 @@ HDR HDR10-output Ikke tilgængelig: %1$s. - Genstart appen for at anvende ændringen. Drivere GPU-drivere Delt mellem Steam og Skrivebord. Indstilles på siden Komponenter. @@ -2461,6 +2460,7 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Sessionsskærm + Præsentation uden kopiering Opløsning 16:9-spiltilpasning Hvordan 16:9-spil tilpasses denne skærm. Fra næste session. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index c913e57c78..3f42bc4e29 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -281,7 +281,6 @@ HDR HDR10-Ausgabe Nicht verfügbar: %1$s. - Starte die App neu, um dies anzuwenden. Treiber GPU-Treiber Für Steam und Desktop gemeinsam. Wird auf der Seite „Komponenten“ festgelegt. @@ -2453,6 +2452,7 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Sitzungsanzeige + Kopierfreie Darstellung Auflösung 16:9-Spielanpassung Wie 16:9-Spiele auf dieses Display passen. Ab der nächsten Sitzung. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index c1e1ffcb79..6cce64d9ce 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -281,7 +281,6 @@ HDR Έξοδος HDR10 Μη διαθέσιμο: %1$s. - Κάντε επανεκκίνηση της εφαρμογής για να εφαρμοστεί. Προγράμματα οδήγησης Προγράμματα οδήγησης GPU Κοινά για το Steam και την Επιφάνεια εργασίας. Ορίζονται στη σελίδα Στοιχεία. @@ -2461,6 +2460,7 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Οθόνη συνεδρίας + Παρουσίαση χωρίς αντιγραφή Ανάλυση Προσαρμογή παιχνιδιού 16:9 Πώς προσαρμόζονται τα παιχνίδια 16:9 σε αυτή την οθόνη. Από την επόμενη συνεδρία. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 124192c1a2..ac6c6d8945 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -281,7 +281,6 @@ HDR Salida HDR10 No disponible: %1$s. - Reinicia la app para aplicarlo. Controladores Controladores de GPU Compartidos por Steam y Escritorio. Se definen en la página Componentes. @@ -2487,6 +2486,7 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Pantalla de la sesión + Presentación sin copia Resolución Ajuste de juegos 16:9 Cómo se ajustan los juegos 16:9 a esta pantalla. Próxima sesión. diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 2d7ea36c72..8164624f87 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -281,7 +281,6 @@ HDR HDR10-lähtö Ei käytettävissä: %1$s. - Käynnistä sovellus uudelleen, jotta muutos tulee voimaan. Ajurit GPU-ajurit Jaettu Steamin ja Työpöydän kesken. Asetetaan Komponentit-sivulla. @@ -2461,6 +2460,7 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Istunnon näyttö + Kopioimaton esitys Tarkkuus 16:9-pelin sovitus Miten 16:9-pelit sovitetaan tähän näyttöön. Seuraava istunto. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index f21ab1e3a2..1743a855ea 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -281,7 +281,6 @@ HDR Sortie HDR10 Non disponible : %1$s. - Prendra effet après le redémarrage de l\'application. Pilotes Pilotes GPU Partagés entre Steam et le bureau. À configurer dans la page « Composants ». @@ -2486,6 +2485,7 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Affichage de la session + Affichage sans copie Résolution Ajustement des jeux 16:9 Comment les jeux 16:9 s\'adaptent à cet écran. À la prochaine session. diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index d322fa0d01..01ad1e44d3 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -281,7 +281,6 @@ HDR HDR10 आउटपुट उपलब्ध नहीं: %1$s। - लागू करने के लिए ऐप रीस्टार्ट करें। ड्राइवर GPU ड्राइवर Steam और डेस्कटॉप दोनों में साझा। Components पेज पर सेट करें। @@ -2461,6 +2460,7 @@ ANDROID + LINUX %1$s। %2$s\n\n%3$s सेशन डिस्प्ले + बिना कॉपी प्रस्तुति रिज़ॉल्यूशन 16:9 गेम फ़िट 16:9 गेम इस डिस्प्ले में कैसे फ़िट होते हैं। अगले सेशन से। diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 4f7ad2c7c6..ab299b1229 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -281,7 +281,6 @@ HDR HDR10-kimenet Nem elérhető: %1$s. - Indítsa újra az alkalmazást az érvényesítéshez. Illesztőprogramok GPU-illesztőprogramok A Steam és az Asztal közösen használja. Az Összetevők oldalon állítható be. @@ -2461,6 +2460,7 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Munkamenet kijelzője + Másolásmentes megjelenítés Felbontás 16:9 játék illesztése Hogyan illeszkednek a 16:9 játékok ehhez a kijelzőhöz. A következő munkamenettől. diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 4ea3788f5f..23a49ce8d9 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -281,7 +281,6 @@ HDR Output HDR10 Tidak tersedia: %1$s. - Mulai ulang aplikasi untuk menerapkannya. Driver Driver GPU Digunakan bersama oleh Steam dan Desktop. Diatur di halaman Komponen. @@ -2436,6 +2435,7 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Tampilan sesi + Presentasi tanpa salin Resolusi Penyesuaian gim 16:9 Cara gim 16:9 disesuaikan dengan tampilan ini. Berlaku pada sesi berikutnya. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 4e7fdf08d1..7e6909e998 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -281,7 +281,6 @@ HDR Uscita HDR10 Non disponibile: %1$s. - Riavvia l\'app per applicare. Driver Driver GPU Condivisi da Steam e Desktop. Si impostano nella pagina Componenti. @@ -2478,6 +2477,7 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Schermo della sessione + Presentazione senza copia Risoluzione Adattamento giochi 16:9 Come i giochi 16:9 si adattano a questo schermo. Dalla prossima sessione. diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index e74e3e706a..a9927cc1c3 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -281,7 +281,6 @@ HDR HDR10出力 利用不可:%1$s。 - アプリの再起動後に有効になります。 ドライバー GPUドライバー Steamとデスクトップで共有されます。「コンポーネント」ページで設定してください。 @@ -2436,6 +2435,7 @@ ANDROID + LINUX %1$s。%2$s\n\n%3$s セッションの表示 + ゼロコピー表示 解像度 16:9ゲームの表示 16:9のゲームをこのディスプレイにどう合わせるか。次回のセッションから。 diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 557cabab25..aba825df85 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -281,7 +281,6 @@ HDR HDR10 출력 사용 불가: %1$s. - 앱을 다시 시작한 후 적용됩니다. 드라이버 GPU 드라이버 Steam과 데스크톱에서 공유됩니다. \"구성 요소\" 페이지에서 설정하세요. @@ -2436,6 +2435,7 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s 세션 디스플레이 + 제로카피 표시 해상도 16:9 게임 맞춤 16:9 게임을 이 디스플레이에 맞추는 방식입니다. 다음 세션부터 적용됩니다. diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index 168ceaa971..21f75a28c2 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -281,7 +281,6 @@ HDR Output HDR10 Tidak tersedia: %1$s. - Mulakan semula apl untuk menggunakannya. Pemacu Pemacu GPU Dikongsi oleh Steam dan Desktop. Ditetapkan pada halaman Komponen. @@ -2436,6 +2435,7 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Paparan sesi + Paparan tanpa salinan Resolusi Suaian permainan 16:9 Cara permainan 16:9 disuaikan ke paparan ini. Sesi seterusnya. diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index e5115e83aa..f4772e7a0d 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -281,7 +281,6 @@ HDR HDR10-utgang Ikke tilgjengelig: %1$s. - Start appen på nytt for å bruke dette. Drivere GPU-drivere Delt av Steam og Skrivebord. Angis på Komponenter-siden. @@ -2461,6 +2460,7 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Sesjonsskjerm + Presentasjon uten kopiering Oppløsning 16:9-spilltilpasning Hvordan 16:9-spill tilpasses denne skjermen. Fra neste sesjon. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 9151d3b212..9292a1a568 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -281,7 +281,6 @@ HDR HDR10-uitvoer Niet beschikbaar: %1$s. - Start de app opnieuw om dit toe te passen. Drivers GPU-drivers Gedeeld door Steam en Desktop. In te stellen op de pagina Componenten. @@ -2461,6 +2460,7 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Sessiescherm + Weergave zonder kopie Resolutie 16:9-beeldvulling Hoe 16:9-games dit scherm vullen. Volgende sessie. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 31742655ac..12a3bed38d 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -281,7 +281,6 @@ HDR Wyjście HDR10 Niedostępne: %1$s. - Uruchom ponownie aplikację, aby zastosować. Sterowniki Sterowniki GPU Wspólne dla Steam i pulpitu. Ustawiane na stronie Komponenty. @@ -2513,6 +2512,7 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Ekran sesji + Prezentacja bez kopiowania Rozdzielczość Dopasowanie gier 16:9 Jak gry 16:9 mieszczą się na tym ekranie. Od następnej sesji. diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index a5745195b4..39c9526f17 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -281,7 +281,6 @@ HDR Saída HDR10 Indisponível: %1$s. - Reinicie a app para aplicar. Controladores Controladores da GPU Partilhados pelo Steam e pelo Ambiente de trabalho. Defina-os na página Componentes. @@ -2492,6 +2491,7 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Ecrã da sessão + Apresentação sem cópia Resolução Ajuste de jogos 16:9 Como os jogos 16:9 se ajustam a este ecrã. Próxima sessão. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index f5eca4b046..80bbc786f5 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -281,7 +281,6 @@ HDR Saída HDR10 Indisponível: %1$s. - Reinicie o app para aplicar. Drivers Drivers de GPU Compartilhados pela Steam e pela Área de trabalho. Defina na página Componentes. @@ -2500,6 +2499,7 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Tela da sessão + Apresentação sem cópia Resolução Ajuste de jogos 16:9 Como os jogos 16:9 se ajustam a esta tela. Na próxima sessão. diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index cc7a55a184..a4cc2e9436 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -281,7 +281,6 @@ HDR Ieșire HDR10 Indisponibil: %1$s. - Repornește aplicația pentru a aplica. Drivere Drivere GPU Partajate de Steam și Desktop. Se stabilesc pe pagina Componente. @@ -2487,6 +2486,7 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Afișajul sesiunii + Prezentare fără copiere Rezoluție Potrivire joc 16:9 Cum se potrivesc jocurile 16:9 cu acest afișaj. Sesiunea următoare. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index a5f31948ad..6e403bc05b 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -281,7 +281,6 @@ HDR Вывод HDR10 Недоступно: %1$s. - Вступит в силу после перезапуска приложения. Драйверы Драйверы GPU Общие для Steam и рабочего стола. Настройте на странице «Компоненты». @@ -2513,6 +2512,7 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Экран сессии + Вывод без копирования Разрешение Игры 16:9 Как игры 16:9 вписываются в этот экран. Вступит в силу в следующей сессии. diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 9bc129df9a..588673ab19 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -281,7 +281,6 @@ HDR HDR10-utgång Inte tillgängligt: %1$s. - Starta om appen för att tillämpa. Drivrutiner GPU-drivrutiner Delas av Steam och skrivbordet. Ställs in på sidan Komponenter. @@ -2461,6 +2460,7 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Sessionsskärm + Presentation utan kopiering Upplösning 16:9-spelanpassning Hur 16:9-spel anpassas till den här skärmen. Nästa session. diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 2402c15f86..8706c82ef0 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -281,7 +281,6 @@ HDR เอาต์พุต HDR10 ไม่พร้อมใช้งาน: %1$s - รีสตาร์ทแอปเพื่อให้มีผล ไดรเวอร์ ไดรเวอร์ GPU ใช้ร่วมกันระหว่าง Steam และเดสก์ท็อป ตั้งค่าได้ที่หน้า Components @@ -2436,6 +2435,7 @@ ANDROID + LINUX %1$s %2$s\n\n%3$s การแสดงผลของเซสชัน + การแสดงผลแบบไม่คัดลอก ความละเอียด การแสดงเกม 16:9 ให้พอดี วิธีที่เกม 16:9 แสดงพอดีกับหน้าจอนี้ มีผลในเซสชันถัดไป diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index bdcb3b8b0f..b9bc2ab818 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -281,7 +281,6 @@ HDR HDR10 çıkışı Kullanılamıyor: %1$s. - Uygulamak için uygulamayı yeniden başlatın. Sürücüler GPU sürücüleri Steam ve Masaüstü tarafından paylaşılır. Bileşenler sayfasından ayarlanır. @@ -2453,6 +2452,7 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Oturum ekranı + Kopyasız sunum Çözünürlük 16:9 oyun sığdırma 16:9 oyunların bu ekrana nasıl sığacağı. Sonraki oturumda. diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 6259160400..2c8caec508 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -281,7 +281,6 @@ HDR Вивід HDR10 Недоступно: %1$s. - Перезапустіть додаток, щоб застосувати. Драйвери Драйвери GPU Спільні для Steam і робочого столу. Налаштовуються на сторінці «Компоненти». @@ -2513,6 +2512,7 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Дисплей сеансу + Показ без копіювання Роздільна здатність Вписування гри 16:9 Як ігри 16:9 вписуються в цей дисплей. З наступного сеансу. diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 424ff42df2..7c1a384f3c 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -281,7 +281,6 @@ HDR Xuất HDR10 Không khả dụng: %1$s. - Khởi động lại ứng dụng để áp dụng. Driver Driver GPU Dùng chung cho Steam và Desktop. Đặt ở trang Components. @@ -2436,6 +2435,7 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Hiển thị phiên + Hiển thị không sao chép Độ phân giải Khớp game 16:9 Cách game 16:9 khớp với màn hình này. Từ phiên sau. diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 4343a946ba..b2085b2861 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -281,7 +281,6 @@ HDR HDR10 输出 不可用:%1$s。 - 重启应用以生效。 驱动 GPU 驱动 由 Steam 和桌面共享。在“组件”页面设置。 @@ -2513,6 +2512,7 @@ Android + Linux %1$s。%2$s\n\n%3$s 会话显示 + 零拷贝呈现 分辨率 16:9 游戏适配 16:9 游戏如何适配此屏幕。下次会话生效。 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 71ec80c4d0..84d53e7341 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -281,7 +281,6 @@ HDR HDR10 輸出 不可用:%1$s。 - 重新啟動應用程式後生效。 驅動程式 GPU 驅動程式 Steam 和桌面共用,請在「組件」頁面設定。 @@ -2433,6 +2432,7 @@ ANDROID + LINUX %1$s。%2$s\n\n%3$s 會話顯示 + 零複製呈現 解像度 16:9 遊戲顯示方式 16:9 遊戲如何配合此螢幕。下次會話生效。 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 105d095c98..0d10927002 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -281,7 +281,6 @@ HDR HDR10 輸出 無法使用:%1$s。 - 重新啟動應用程式後生效。 驅動程式 GPU 驅動程式 Steam 和桌面共用。請在「元件」頁面設定。 @@ -2433,6 +2432,7 @@ ANDROID + LINUX %1$s。%2$s\n\n%3$s 工作階段顯示 + 零複製呈現 解析度 16:9 遊戲顯示方式 16:9 遊戲如何配合此螢幕。下次工作階段生效。 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index a2e6d905e8..8d3d519ea6 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -309,7 +309,6 @@ HDR HDR10 output Not available: %1$s. - Restart the app to apply. Drivers GPU drivers Shared by Steam and Desktop. Set on the Components page. @@ -2716,6 +2715,7 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Session display + Zero-copy presentation Resolution 16:9 game fit How 16:9 games fit this display. Next session. diff --git a/app/src/test/java/com/droiddeck/launcher/session/ContentCadenceTest.kt b/app/src/test/java/com/droiddeck/launcher/session/ContentCadenceTest.kt new file mode 100644 index 0000000000..2cb2e42fdb --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/ContentCadenceTest.kt @@ -0,0 +1,84 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class ContentCadenceTest { + private val rates = intArrayOf(60, 90, 120, 144) + + @Test + fun aMeasuredRateSnapsToAStepAPanelRateDividesInto() { + assertEquals(45, ContentCadence.snap(44, rates)) + assertEquals(48, ContentCadence.snap(49, rates)) + assertEquals(72, ContentCadence.snap(72, rates)) + assertEquals(60, ContentCadence.snap(61, rates)) + assertEquals(0, ContentCadence.snap(53, rates)) + assertEquals(0, ContentCadence.snap(12, rates)) + assertEquals(0, ContentCadence.snap(45, intArrayOf(60))) + } + + @Test + fun aSteadyRateEngagesOnlyAfterItHolds() { + val cadence = ContentCadence() + assertFalse(cadence.note(45, rates)) + assertFalse(cadence.note(44, rates)) + assertEquals(0, cadence.rate) + assertTrue(cadence.note(45, rates)) + assertEquals(45, cadence.rate) + } + + @Test + fun aWanderingRateNeverEngages() { + val cadence = ContentCadence() + for (fps in intArrayOf(45, 53, 60, 71, 48, 45, 66, 45, 45, 58)) assertFalse(cadence.note(fps, rates)) + assertEquals(0, cadence.rate) + } + + @Test + fun oneOffSampleDoesNotReleaseAnEngagedRate() { + val cadence = ContentCadence() + repeat(3) { cadence.note(72, rates) } + assertFalse(cadence.note(55, rates)) + assertFalse(cadence.note(72, rates)) + assertFalse(cadence.note(51, rates)) + assertFalse(cadence.note(53, rates)) + assertEquals(72, cadence.rate) + assertTrue(cadence.note(55, rates)) + assertEquals(0, cadence.rate) + } + + @Test + fun aRateThatWasReleasedMustHoldLongerToEngageAgain() { + val cadence = ContentCadence() + repeat(3) { cadence.note(45, rates) } + repeat(3) { cadence.note(57, rates) } + assertEquals(0, cadence.rate) + repeat(5) { assertFalse(cadence.note(45, rates)) } + assertTrue(cadence.note(45, rates)) + assertEquals(45, cadence.rate) + } + + @Test + fun aReleasedRateDoesNotDelayARateThatWasNeverReleased() { + val cadence = ContentCadence() + repeat(3) { cadence.note(45, rates) } + repeat(3) { cadence.note(57, rates) } + assertEquals(0, cadence.rate) + repeat(2) { assertFalse(cadence.note(60, rates)) } + assertTrue(cadence.note(60, rates)) + assertEquals(60, cadence.rate) + } + + @Test + fun aResetDropsTheEngagedRateAndReportsTheChangeOnce() { + val cadence = ContentCadence() + repeat(3) { cadence.note(60, rates) } + assertTrue(cadence.reset()) + assertEquals(0, cadence.rate) + assertFalse(cadence.reset()) + repeat(2) { assertFalse(cadence.note(60, rates)) } + assertTrue(cadence.note(60, rates)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/PerfModeTest.kt b/app/src/test/java/com/droiddeck/launcher/session/PerfModeTest.kt index 3a7dff017f..1bd7ed3444 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/PerfModeTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/PerfModeTest.kt @@ -56,4 +56,64 @@ class PerfModeTest { assertTrue(PerfMode.needsChange(modes, 0, oneTwenty)) assertTrue(PerfMode.needsChange(modes, 99, oneTwenty)) } + + @Test fun aGuestFrameRateChoosesTheHighestPanelRateItDividesEvenly() { + val modes = arrayOf(mode(1, 60f), mode(2, 90f), mode(3, 120f), mode(4, 144f)) + val current = modes[3] + assertEquals(modes[2], PerfMode.selectMode(modes, current, 60, Float.POSITIVE_INFINITY, 120)) + assertEquals(modes[2], PerfMode.selectMode(modes, current, 40, Float.POSITIVE_INFINITY, 120)) + assertEquals(modes[1], PerfMode.selectMode(modes, current, 45, Float.POSITIVE_INFINITY, 90)) + assertEquals(modes[3], PerfMode.selectMode(modes, current, 72, Float.POSITIVE_INFINITY, 144)) + assertEquals(modes[3], PerfMode.selectMode(modes, current, 50, Float.POSITIVE_INFINITY, 144)) + } + + @Test fun frameGenerationRaisesThePanelRateToItsOutputRate() { + val modes = arrayOf(mode(1, 60f), mode(2, 90f), mode(3, 120f), mode(4, 144f)) + val current = modes[0] + assertEquals(120, PerfMode.contentRate(60, 2, 0)) + assertEquals(60, PerfMode.contentRate(60, 1, 0)) + assertEquals(90, PerfMode.contentRate(40, 3, 90)) + assertEquals(0, PerfMode.contentRate(0, 2, 0)) + assertEquals(modes[2], PerfMode.selectMode(modes, current, PerfMode.contentRate(60, 2, 0), Float.POSITIVE_INFINITY)) + assertEquals(modes[1], PerfMode.selectMode(modes, current, PerfMode.contentRate(45, 2, 0), Float.POSITIVE_INFINITY)) + assertEquals(modes[3], PerfMode.selectMode(modes, current, PerfMode.contentRate(72, 2, 0), Float.POSITIVE_INFINITY)) + assertEquals(modes[3], PerfMode.selectMode(modes, current, PerfMode.contentRate(60, 3, 0), Float.POSITIVE_INFINITY)) + assertEquals(modes[2], PerfMode.selectMode(modes, current, PerfMode.contentRate(60, 4, 0), 120f)) + } + + @Test fun aGuestRefreshRequestWithoutAFrameRatePicksThatPanelRate() { + val modes = arrayOf(mode(1, 60f), mode(2, 90f), mode(3, 120f)) + val current = modes[2] + assertEquals(modes[0], PerfMode.selectMode(modes, current, 0, Float.POSITIVE_INFINITY, 60)) + assertEquals(modes[1], PerfMode.selectMode(modes, current, 0, Float.POSITIVE_INFINITY, 75)) + assertEquals(modes[1], PerfMode.selectMode(modes, current, 0, 90f, 120)) + assertEquals(modes[2], PerfMode.selectMode(modes, current, 0, Float.POSITIVE_INFINITY, 0)) + } + + @Test fun panelRatesListOnlyTheCurrentSizeWithinTheCap() { + val modes = arrayOf(mode(1, 60f), mode(2, 120f), mode(3, 144f), mode(4, 90f, 720), mode(5, 59.94f)) + assertEquals(listOf(60, 120, 144), PerfMode.panelRates(modes, modes[1], Float.POSITIVE_INFINITY).toList()) + assertEquals(listOf(60, 120), PerfMode.panelRates(modes, modes[1], 120f).toList()) + } + + @Test fun aPanelTheSystemHoldsOffersOnlyItsCurrentRate() { + val modes = arrayOf(mode(1, 60f), mode(2, 120f), mode(3, 185f)) + assertTrue(PerfMode.panelHeld(185f, 120f)) + assertTrue(PerfMode.panelHeld(60f, 120f)) + assertFalse(PerfMode.panelHeld(120f, 119.88f)) + assertFalse(PerfMode.panelHeld(0f, 120f)) + assertEquals(listOf(120), PerfMode.panelRates(modes, modes[1], Float.POSITIVE_INFINITY, true).toList()) + assertEquals(listOf(60, 120, 185), PerfMode.panelRates(modes, modes[1], Float.POSITIVE_INFINITY, false).toList()) + } + + @Test + fun aSteadyRateBelowAnUnconstrainingLimiterSetsThePace() { + assertEquals(30, PerfMode.pacedRate(30, 120, 120, 45)) + assertEquals(45, PerfMode.pacedRate(0, 0, 0, 45)) + assertEquals(40, PerfMode.pacedRate(0, 40, 120, 45)) + assertEquals(45, PerfMode.pacedRate(0, 120, 120, 45)) + assertEquals(120, PerfMode.pacedRate(0, 120, 120, 60)) + assertEquals(120, PerfMode.pacedRate(0, 120, 120, 0)) + assertEquals(60, PerfMode.pacedRate(0, 60, 0, 45)) + } } diff --git a/docs/progress-log.md b/docs/progress-log.md index 462affde2a..5fcfa60707 100644 --- a/docs/progress-log.md +++ b/docs/progress-log.md @@ -1449,8 +1449,9 @@ State: **main = `90c7574`** (PR #14 merge), main build run 35895701784. No tag, - A runtime script must be named `bannerlator-*` or CI never packages it. - `gh release create --target` needs the full sha. - A proot bind is invisible to a program's "Computer" list; put what users need under home. -- The compositor decides its driver and its HDR gate once per app process - anything that changes - them applies after the app is fully closed, and the UI must say so. +- The compositor decides its driver once per app process - anything that changes it applies after + the app is fully closed, and the UI must say so. Its HDR gate follows what the device can present, + so the HDR setting itself switches during a session. - Bannerlator's File Manager ports mechanically (`port_fm.py` anchors) once the container hooks are cut; do not hand-edit 2,500 lines. - Deleting a release asset on GitHub can drop a sibling asset - re-list and restore. diff --git a/docs/settings-map.md b/docs/settings-map.md index cfbdf196de..8e19e9db84 100644 --- a/docs/settings-map.md +++ b/docs/settings-map.md @@ -94,7 +94,7 @@ Links of the form `droiddeck://settings/
` open a Settings section direc | Setting | Where | Also matches | | --- | --- | --- | -| Session display | Steam or Desktop options (swipe up) › Display | resolution, scaling, hdr, refresh | +| Session display | Steam or Desktop options (swipe up) › Display | resolution, scaling, hdr, refresh, zero-copy | | Graphics drivers | Steam or Desktop options (swipe up) › Display | turnip, driver, gpu, adreno, mali | | Offline mode | Steam or Desktop options (swipe up) › Steam | offline, steam | | Microphone | Steam or Desktop options (swipe up) › Audio | microphone, voice | diff --git a/tools/droiddeckctl b/tools/droiddeckctl index 50ff42423d..2a404c1c6c 100755 --- a/tools/droiddeckctl +++ b/tools/droiddeckctl @@ -412,10 +412,10 @@ def pacing(adb: str, serial: str, seconds: float) -> dict: try: time.sleep(seconds) dump = run_adb(adb, serial, *timestats, "-dump", timeout=60) + elapsed = time.monotonic() - started except ControlError as exc: raise ControlError(str(exc), "PACING_FAILED") from exc finally: - elapsed = time.monotonic() - started try: disabled = run_adb(adb, serial, *timestats, "-disable").returncode == 0 except ControlError: diff --git a/tools/gamescope/PATCHES.md b/tools/gamescope/PATCHES.md index 953bab4a0c..f5a569ddc8 100644 --- a/tools/gamescope/PATCHES.md +++ b/tools/gamescope/PATCHES.md @@ -358,3 +358,51 @@ and clears the held flag. wlroots counts repeated presses of one button and send reaches zero, so a second finger touching before the first lifted left the button pressed in the seat for good: the game saw a held click, and later taps only raised and lowered the count. A finger now presses the button only when no earlier finger holds it. `tools/tests/test_gamescope_touch_click.py` compiles the rule from this patch. + +## 0135 Wayland backend: a limit on the planes handed to the host + +`wayland_overlay_planes` says how many planes above the base one the host compositor shows without composing them +itself. With more layers than that, gamescope composites them into one picture, as it already does for a scaler or +`composite_force`. -1, the default, keeps every layer on its own plane. The app sets it while a host that shows the +game picture directly cannot give an overlay a display layer of its own, so the overlay is drawn into the game +picture here and the frame still reaches the display without a copy. + +## 0136 rendervulkan, Wayland backend: composite only into output images the host has released + +The composite output images were used in a fixed rotation of three, with no check that the host compositor had +released the one about to be written. A host that puts the buffer on the display itself, without copying it, was +still reading that image when the next composite wrote into it. A backend framebuffer now says whether the host +holds it, the Wayland backend answers from the buffer's release event, and the composite takes the next image the +host does not hold. Backends that are not a session get five images instead of three, so one is free while the +host holds two and the last and deferred pictures stay intact. Session backends keep three images and their order. + +## 0137 Wayland backend: the host's refresh rates and the app's target + +A nested session had one refresh rate, the host's, so Steam offered no refresh control and a frame limit never moved +the display. The backend binds the host's `droiddeck_refresh_v1`, takes the list of rates the host display can switch +between and returns it as the connector's dynamic refresh rates, so the rates reach Steam with the rest of the +display state and are sent again when the list changes. On every present it tells the host the refresh rate the +frame limit resolves to and the limit itself; the host switches its display and the new rate comes back through +`wl_output`, which the nested refresh already follows. A host without the global leaves all of this as it was. + +## 0138 Frame limiter: a limit the refresh rate does not divide is spread evenly + +The limiter held a window for a whole number of refreshes, the refresh rate divided by the limit and rounded down. A +limit of 45 or 40 on a 60 Hz display rounded to one refresh per frame, so the limit did nothing, and each frame was +timed from the moment the previous one was shown, so a late frame pushed every frame after it. The limited cycle is +now the exact time between frames at the limit, and each window keeps the time its next frame is due on that line. +A frame is released on the refresh nearest its due time: 45 on 60 Hz shows frames for one, one and two refreshes in +turn, 40 for one and two, and a limit that divides the refresh rate is paced as before. A frame that arrives most of a +refresh late, or more than a refresh early, starts the line again from that frame, so a stall is not followed by a +burst. `tools/tests/test_gamescope_limiter_cadence.py` compiles the two rules from this patch and runs them across +refresh rates and limits. + +## 0139 HDR output can be switched while a session runs + +The Wayland backend read `hdr_enabled` once, when the host compositor described its output, and kept the answer: a +session started with HDR off told its clients the display had no HDR for as long as it ran, and its environment +carried `DXVK_HDR=0`. Whether the display can show HDR now comes from the host's output description alone, and +`hdr_enabled` decides only whether HDR is used, so setting it during a session takes effect on the next frame in +either direction. The 10-bit output format is chosen only while HDR is enabled, so an SDR session keeps the 8-bit +output it had, and the output images are made again in the other format when the setting changes. On a display that can show HDR, a session that starts with HDR off leaves `DXVK_HDR` unset instead of +forcing it to 0, so a game started after HDR is switched on finds it. diff --git a/tools/gamescope/patches/0135-wayland-overlay-plane-limit.patch b/tools/gamescope/patches/0135-wayland-overlay-plane-limit.patch new file mode 100644 index 0000000000..7961ec5050 --- /dev/null +++ b/tools/gamescope/patches/0135-wayland-overlay-plane-limit.patch @@ -0,0 +1,20 @@ +diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp +index 372fc08..fe38c7d 100644 +--- a/src/Backends/WaylandBackend.cpp ++++ b/src/Backends/WaylandBackend.cpp +@@ -126,6 +126,7 @@ namespace gamescope + gamescope::ConVar cv_wayland_mouse_warp_without_keyboard_focus( "wayland_mouse_warp_without_keyboard_focus", true, "Should we only forward mouse warps to the app when we have keyboard focus?" ); + gamescope::ConVar cv_wayland_mouse_relmotion_without_keyboard_focus( "wayland_mouse_relmotion_without_keyboard_focus", false, "Should we only forward mouse relative motion to the app when we have keyboard focus?" ); + gamescope::ConVar cv_wayland_use_modifiers( "wayland_use_modifiers", true, "Use DMA-BUF modifiers?" ); ++ gamescope::ConVar cv_wayland_overlay_planes( "wayland_overlay_planes", -1, "How many planes above the base one the host shows without composing them itself; more are composited here into one. -1 for no limit." ); + + gamescope::ConVar cv_wayland_hdr10_saturation_scale( "wayland_hdr10_saturation_scale", 1.0, "Saturation scale for HDR10 content by gamut expansion. 1.0 - 1.2 is a good range to play with." ); + +@@ -1102,6 +1103,7 @@ namespace gamescope + eLayer0Filter == GamescopeUpscaleFilter::PIXEL ) && !bLayer0ScreenSize; + + bNeedsFullComposite |= cv_composite_force; ++ bNeedsFullComposite |= cv_wayland_overlay_planes >= 0 && pFrameInfo->layers.count() > 1 + cv_wayland_overlay_planes; + bNeedsFullComposite |= pFrameInfo->useFSRLayer0; + bNeedsFullComposite |= pFrameInfo->useNISLayer0; + bNeedsFullComposite |= pFrameInfo->useSGSRLayer0; diff --git a/tools/gamescope/patches/0136-composite-into-released-output-images.patch b/tools/gamescope/patches/0136-composite-into-released-output-images.patch new file mode 100644 index 0000000000..2f827f8703 --- /dev/null +++ b/tools/gamescope/patches/0136-composite-into-released-output-images.patch @@ -0,0 +1,218 @@ +diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp +index fe38c7d..be99e6d 100644 +--- a/src/Backends/WaylandBackend.cpp ++++ b/src/Backends/WaylandBackend.cpp +@@ -503,6 +503,8 @@ namespace gamescope + wl_buffer *GetHostBuffer() const { return m_pHostBuffer; } + wlr_buffer *GetClientBuffer() const { return m_pClientBuffer; } + ++ bool HeldByHost() const override { return m_bCompositorAcquired; } ++ + void Wayland_Buffer_Release( wl_buffer *pBuffer ); + static const wl_buffer_listener s_BufferListener; + +diff --git a/src/backend.h b/src/backend.h +index fbfa7c7..30b42ca 100644 +--- a/src/backend.h ++++ b/src/backend.h +@@ -288,6 +288,8 @@ namespace gamescope + virtual void SetReleasePoint( std::shared_ptr pReleasePoint ) = 0; + + virtual IBackendFb *EnsureImported() = 0; ++ ++ virtual bool HeldByHost() const { return false; } + }; + + class IBackendPlane +diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp +index 0835bfe..42cc9c4 100644 +--- a/src/rendervulkan.cpp ++++ b/src/rendervulkan.cpp +@@ -3644,15 +3644,12 @@ static bool vulkan_make_output_images( VulkanOutput_t *pOutput ) + outputImageflags.bSampled = true; // for pipewire blits + outputImageflags.bOutputImage = true; + +- pOutput->outputImages.resize(3); // extra image for partial composition. +- pOutput->outputImagesPartialOverlay.resize(3); ++ const uint32_t uImageCount = GetBackend()->IsSessionBased() ? 3u : 5u; + +- pOutput->outputImages[0] = nullptr; +- pOutput->outputImages[1] = nullptr; +- pOutput->outputImages[2] = nullptr; +- pOutput->outputImagesPartialOverlay[0] = nullptr; +- pOutput->outputImagesPartialOverlay[1] = nullptr; +- pOutput->outputImagesPartialOverlay[2] = nullptr; ++ pOutput->outputImages.clear(); ++ pOutput->outputImagesPartialOverlay.clear(); ++ pOutput->outputImages.resize( uImageCount ); ++ pOutput->outputImagesPartialOverlay.resize( uImageCount ); + + uint32_t uDRMFormat = pOutput->uOutputFormat; + +@@ -3662,28 +3659,14 @@ static bool vulkan_make_output_images( VulkanOutput_t *pOutput ) + if ( g_uOutputRotation & 1u ) + std::swap( uOutputWidth, uOutputHeight ); + +- pOutput->outputImages[0] = new CVulkanTexture(); +- bool bSuccess = pOutput->outputImages[0]->BInit( uOutputWidth, uOutputHeight, 1u, uDRMFormat, outputImageflags ); +- if ( bSuccess != true ) +- { +- vk_log.errorf( "failed to allocate buffer for KMS" ); +- return false; +- } +- +- pOutput->outputImages[1] = new CVulkanTexture(); +- bSuccess = pOutput->outputImages[1]->BInit( uOutputWidth, uOutputHeight, 1u, uDRMFormat, outputImageflags ); +- if ( bSuccess != true ) ++ for ( uint32_t i = 0; i < uImageCount; i++ ) + { +- vk_log.errorf( "failed to allocate buffer for KMS" ); +- return false; +- } +- +- pOutput->outputImages[2] = new CVulkanTexture(); +- bSuccess = pOutput->outputImages[2]->BInit( uOutputWidth, uOutputHeight, 1u, uDRMFormat, outputImageflags ); +- if ( bSuccess != true ) +- { +- vk_log.errorf( "failed to allocate buffer for KMS" ); +- return false; ++ pOutput->outputImages[i] = new CVulkanTexture(); ++ if ( !pOutput->outputImages[i]->BInit( uOutputWidth, uOutputHeight, 1u, uDRMFormat, outputImageflags ) ) ++ { ++ vk_log.errorf( "failed to allocate buffer for KMS" ); ++ return false; ++ } + } + + // Oh no. +@@ -3696,28 +3679,14 @@ static bool vulkan_make_output_images( VulkanOutput_t *pOutput ) + { + uint32_t uPartialDRMFormat = pOutput->uOutputFormatOverlay; + +- pOutput->outputImagesPartialOverlay[0] = new CVulkanTexture(); +- bool bSuccess = pOutput->outputImagesPartialOverlay[0]->BInit( uOutputWidth, uOutputHeight, 1u, uPartialDRMFormat, outputImageflags, nullptr, 0, 0, pOutput->outputImages[0].get() ); +- if ( bSuccess != true ) +- { +- vk_log.errorf( "failed to allocate buffer for KMS" ); +- return false; +- } +- +- pOutput->outputImagesPartialOverlay[1] = new CVulkanTexture(); +- bSuccess = pOutput->outputImagesPartialOverlay[1]->BInit( uOutputWidth, uOutputHeight, 1u, uPartialDRMFormat, outputImageflags, nullptr, 0, 0, pOutput->outputImages[1].get() ); +- if ( bSuccess != true ) ++ for ( uint32_t i = 0; i < uImageCount; i++ ) + { +- vk_log.errorf( "failed to allocate buffer for KMS" ); +- return false; +- } +- +- pOutput->outputImagesPartialOverlay[2] = new CVulkanTexture(); +- bSuccess = pOutput->outputImagesPartialOverlay[2]->BInit( uOutputWidth, uOutputHeight, 1u, uPartialDRMFormat, outputImageflags, nullptr, 0, 0, pOutput->outputImages[2].get() ); +- if ( bSuccess != true ) +- { +- vk_log.errorf( "failed to allocate buffer for KMS" ); +- return false; ++ pOutput->outputImagesPartialOverlay[i] = new CVulkanTexture(); ++ if ( !pOutput->outputImagesPartialOverlay[i]->BInit( uOutputWidth, uOutputHeight, 1u, uPartialDRMFormat, outputImageflags, nullptr, 0, 0, pOutput->outputImages[i].get() ) ) ++ { ++ vk_log.errorf( "failed to allocate buffer for KMS" ); ++ return false; ++ } + } + } + +@@ -3755,6 +3724,8 @@ bool vulkan_remake_output_images() + g_device.waitIdle(); + + pOutput->nOutImage = 0; ++ pOutput->nLastOutImage = 0; ++ pOutput->nDeferredOutImage = 0; + + // Delete screenshot/capture textures to be remade if needed + for (auto& pScreenshotTexture : pOutput->pScreenshotTextures) +@@ -4604,6 +4575,30 @@ namespace + + ReshadeEffectPipeline *g_pLastReshadeEffect = nullptr; + ++static bool vulkan_output_image_held( uint32_t nImage ) ++{ ++ for ( const auto &pImage : { g_output.outputImages[ nImage ], g_output.outputImagesPartialOverlay[ nImage ] } ) ++ { ++ if ( pImage != nullptr && pImage->GetBackendFb() != nullptr && pImage->GetBackendFb()->HeldByHost() ) ++ return true; ++ } ++ return false; ++} ++ ++static uint32_t vulkan_free_output_image( uint32_t nFirst ) ++{ ++ const uint32_t uCount = g_output.outputImages.size(); ++ for ( uint32_t i = 0; i < uCount; i++ ) ++ { ++ const uint32_t nImage = ( nFirst + i ) % uCount; ++ if ( uCount > 3 && ( nImage == g_output.nLastOutImage || nImage == g_output.nDeferredOutImage ) ) ++ continue; ++ if ( !vulkan_output_image_held( nImage ) ) ++ return nImage; ++ } ++ return nFirst; ++} ++ + std::optional vulkan_composite( struct FrameInfo_t *frameInfo, gamescope::Rc pPipewireTexture, bool partial, gamescope::Rc pOutputOverride, bool increment, std::unique_ptr pInCommandBuffer ) + { + EOTF outputTF = frameInfo->outputEncodingEOTF; +@@ -4643,6 +4638,9 @@ std::optional vulkan_composite( struct FrameInfo_t *frameInfo, gamesco + if ( !pOutputOverride && !vulkan_ensure_output_images() ) + return std::nullopt; + ++ if ( !pOutputOverride && !GetBackend()->UsesVulkanSwapchain() ) ++ g_output.nOutImage = vulkan_free_output_image( g_output.nOutImage ); ++ + gamescope::Rc compositeImage; + if ( pOutputOverride ) + compositeImage = pOutputOverride; +@@ -4877,7 +4875,9 @@ std::optional vulkan_composite( struct FrameInfo_t *frameInfo, gamesco + + if ( !GetBackend()->UsesVulkanSwapchain() && pOutputOverride == nullptr && increment ) + { +- g_output.nOutImage = ( g_output.nOutImage + 1 ) % 3; ++ g_output.nDeferredOutImage = g_output.nLastOutImage; ++ g_output.nLastOutImage = g_output.nOutImage; ++ g_output.nOutImage = ( g_output.nOutImage + 1 ) % g_output.outputImages.size(); + } + + return sequence; +@@ -4931,19 +4931,7 @@ bool vulkan_format_supports_features(VkFormat format, VkFormatFeatureFlags featu + + gamescope::Rc vulkan_get_last_output_image( bool partial, bool defer ) + { +- // Get previous image ( +2 ) +- // 1 2 3 +- // | +- // | +- uint32_t nRegularImage = ( g_output.nOutImage + 2 ) % 3; +- +- // Get previous previous image ( +1 ) +- // 1 2 3 +- // | +- // | +- uint32_t nDeferredImage = ( g_output.nOutImage + 1 ) % 3; +- +- uint32_t nOutImage = defer ? nDeferredImage : nRegularImage; ++ uint32_t nOutImage = defer ? g_output.nDeferredOutImage : g_output.nLastOutImage; + + if ( partial ) + { +diff --git a/src/rendervulkan.hpp b/src/rendervulkan.hpp +index e0ede11..8ae3b71 100644 +--- a/src/rendervulkan.hpp ++++ b/src/rendervulkan.hpp +@@ -591,6 +591,8 @@ struct VulkanOutput_t + std::vector> presentationImages; + + uint32_t nOutImage; // swapchain index in nested mode, or ping/pong between two RTs ++ uint32_t nLastOutImage = 0; ++ uint32_t nDeferredOutImage = 0; + std::vector> outputImages; + std::vector> outputImagesPartialOverlay; + gamescope::OwningRc temporaryHackyBlankImage; diff --git a/tools/gamescope/patches/0137-wayland-backend-host-refresh-rates.patch b/tools/gamescope/patches/0137-wayland-backend-host-refresh-rates.patch new file mode 100644 index 0000000000..04860928c4 --- /dev/null +++ b/tools/gamescope/patches/0137-wayland-backend-host-refresh-rates.patch @@ -0,0 +1,293 @@ +diff --git a/protocol/droiddeck-refresh-v1.xml b/protocol/droiddeck-refresh-v1.xml +new file mode 100644 +index 0000000..c4464a0 +--- /dev/null ++++ b/protocol/droiddeck-refresh-v1.xml +@@ -0,0 +1,81 @@ ++ ++ ++ ++ Copyright 2026 DroidDeck contributors ++ ++ Permission is hereby granted, free of charge, to any person obtaining a ++ copy of this software and associated documentation files (the "Software"), ++ to deal in the Software without restriction, including without limitation ++ the rights to use, copy, modify, merge, publish, distribute, sublicense, ++ and/or sell copies of the Software, and to permit persons to whom the ++ Software is furnished to do so, subject to the following conditions: ++ ++ The above copyright notice and this permission notice (including the next ++ paragraph) shall be included in all copies or substantial portions of the ++ Software. ++ ++ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ++ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ++ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ++ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ++ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ++ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ++ DEALINGS IN THE SOFTWARE. ++ ++ ++ ++ ++ A nested compositor paces its clients against the refresh rate of the ++ panel it is shown on. When its clients are held to a frame rate the ++ panel's current rate does not divide evenly, frames are shown for an ++ uneven number of refreshes. This interface lets the nested compositor ++ see every refresh rate the panel can run at its current size and ask ++ for the one that suits the frame rate it is pacing to. ++ ++ On bind the compositor sends one rate event per refresh rate, lowest ++ first, followed by done. The list is sent again, in full, whenever it ++ changes (a different panel, or a limit the user placed on the panel's ++ rate). The rate the panel is running at is still reported the standard ++ way, through wl_output.mode. ++ ++ A request is a preference, not a guarantee: the user, the platform or ++ another output mirroring the panel may hold the panel at another rate. ++ The client reads the result from wl_output.mode. ++ ++ ++ ++ ++ The preference set through this object is dropped. ++ ++ ++ ++ ++ ++ refresh is the panel rate the client would like, in Hz, taken from ++ the advertised list; 0 withdraws the preference. frame_rate is the ++ frame rate the client holds its content to, in frames per second, or ++ 0 when the content is not held to a rate. The compositor may multiply ++ the content's frame rate itself (generated frames); when it does, it ++ picks the advertised rate that the multiplied frame rate divides ++ evenly instead of the requested one. ++ ++ ++ ++ ++ ++ ++ ++ Sent once per rate, lowest first, in Hz rounded to the nearest whole ++ number. ++ ++ ++ ++ ++ ++ ++ Ends a list of rate events. The rates received since the previous ++ done replace the earlier list. ++ ++ ++ ++ +diff --git a/protocol/meson.build b/protocol/meson.build +index cf8fbd1..71fe31b 100644 +--- a/protocol/meson.build ++++ b/protocol/meson.build +@@ -43,6 +43,8 @@ protocols = [ + 'gamescope-private.xml', + 'gamescope-action-binding.xml', + ++ 'droiddeck-refresh-v1.xml', ++ + # wlroots protocols + 'wlr-layer-shell-unstable-v1.xml', + ] +diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp +index be99e6d..9862641 100644 +--- a/src/Backends/WaylandBackend.cpp ++++ b/src/Backends/WaylandBackend.cpp +@@ -38,6 +38,7 @@ + #include + #include + #include ++#include + #include "wlr_end.hpp" + + #include "drm_include.h" +@@ -705,6 +706,10 @@ namespace gamescope + virtual bool UsesVulkanSwapchain() const override; + + virtual bool IsSessionBased() const override; ++ virtual bool HackTemporarySetDynamicRefresh( int nRefresh ) override; ++ ++ std::span GetHostRefreshRates() const; ++ void SyncHostRefreshTarget(); + virtual bool SupportsExplicitSync() const override; + + virtual bool IsPaused() const override; +@@ -778,6 +783,10 @@ namespace gamescope + void Wayland_Output_Geometry( wl_output *pOutput, int32_t nX, int32_t nY, int32_t nPhysicalWidth, int32_t nPhysicalHeight, int32_t nSubpixel, const char *pMake, const char *pModel, int32_t nTransform ); + void Wayland_Output_Mode( wl_output *pOutput, uint32_t uFlags, int32_t nWidth, int32_t nHeight, int32_t nRefresh ); + void Wayland_Output_Done( wl_output *pOutput ); ++ ++ void Wayland_Refresh_Rate( droiddeck_refresh_v1 *pRefresh, uint32_t uRefresh ); ++ void Wayland_Refresh_Done( droiddeck_refresh_v1 *pRefresh ); ++ static const droiddeck_refresh_v1_listener s_RefreshListener; + void Wayland_Output_Scale( wl_output *pOutput, int32_t nFactor ); + void Wayland_Output_Name( wl_output *pOutput, const char *pName ); + void Wayland_Output_Description( wl_output *pOutput, const char *pDescription ); +@@ -829,6 +838,12 @@ namespace gamescope + OwningRc m_pOwnedBlackFb; + OwningRc m_pBlackTexture; + wp_presentation *m_pPresentation = nullptr; ++ droiddeck_refresh_v1 *m_pHostRefresh = nullptr; ++ std::array m_HostRefreshRates{}; ++ std::atomic m_uHostRefreshRateCount = { 0 }; ++ std::vector m_PendingHostRefreshRates; ++ int m_nSentHostRefresh = 0; ++ int m_nSentHostFrameRate = 0; + frog_color_management_factory_v1 *m_pFrogColorMgmtFactory = nullptr; + wp_color_manager_v1 *m_pWPColorManager = nullptr; + wp_image_description_v1 *m_pWPImageDescriptions[ GamescopeAppTextureColorspace_Count ]{}; +@@ -890,6 +905,11 @@ namespace gamescope + .global = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_Registry_Global ), + .global_remove = WAYLAND_NULL(), + }; ++ const droiddeck_refresh_v1_listener CWaylandBackend::s_RefreshListener = ++ { ++ .rate = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_Refresh_Rate ), ++ .done = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_Refresh_Done ), ++ }; + const wl_output_listener CWaylandBackend::s_OutputListener = + { + .geometry = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_Output_Geometry ), +@@ -1087,6 +1107,7 @@ namespace gamescope + { + droiddeck::frame_trace::Record( droiddeck::frame_trace::Event::OutputPresent ); + UpdateFullscreenState(); ++ m_pBackend->SyncHostRefreshTarget(); + + bool bNeedsFullComposite = false; + +@@ -1244,7 +1265,7 @@ namespace gamescope + } + std::span CWaylandConnector::GetValidDynamicRefreshRates() const + { +- return std::span{}; ++ return m_pBackend->GetHostRefreshRates(); + } + + void CWaylandConnector::GetNativeColorimetry( +@@ -2396,6 +2417,52 @@ namespace gamescope + return false; + } + ++ std::span CWaylandBackend::GetHostRefreshRates() const ++ { ++ const uint32_t uCount = m_uHostRefreshRateCount; ++ if ( uCount < 2 ) ++ return std::span{}; ++ return std::span{ m_HostRefreshRates.data(), uCount }; ++ } ++ ++ bool CWaylandBackend::HackTemporarySetDynamicRefresh( int nRefresh ) ++ { ++ if ( !m_pHostRefresh ) ++ return false; ++ SyncHostRefreshTarget(); ++ return true; ++ } ++ ++ void CWaylandBackend::SyncHostRefreshTarget() ++ { ++ if ( !m_pHostRefresh ) ++ return; ++ const int nFrameRate = steamcompmgr_get_app_target_fps(); ++ const int nRefresh = steamcompmgr_get_app_dynamic_refresh(); ++ if ( nRefresh == m_nSentHostRefresh && nFrameRate == m_nSentHostFrameRate ) ++ return; ++ xdg_log.infof( "Asking the host for %dhz at %dfps", nRefresh, nFrameRate ); ++ droiddeck_refresh_v1_set_target( m_pHostRefresh, nRefresh, nFrameRate ); ++ m_nSentHostRefresh = nRefresh; ++ m_nSentHostFrameRate = nFrameRate; ++ } ++ ++ void CWaylandBackend::Wayland_Refresh_Rate( droiddeck_refresh_v1 *pRefresh, uint32_t uRefresh ) ++ { ++ m_PendingHostRefreshRates.push_back( uRefresh ); ++ } ++ void CWaylandBackend::Wayland_Refresh_Done( droiddeck_refresh_v1 *pRefresh ) ++ { ++ std::sort( m_PendingHostRefreshRates.begin(), m_PendingHostRefreshRates.end() ); ++ const uint32_t uCount = std::min( m_PendingHostRefreshRates.size(), m_HostRefreshRates.size() ); ++ m_uHostRefreshRateCount = 0; ++ std::copy_n( m_PendingHostRefreshRates.begin(), uCount, m_HostRefreshRates.begin() ); ++ m_uHostRefreshRateCount = uCount; ++ m_PendingHostRefreshRates.clear(); ++ steamcompmgr_display_rates_changed(); ++ force_repaint(); ++ } ++ + bool CWaylandBackend::SupportsExplicitSync() const + { + // GAMESCOPE_DISABLE_EXPLICIT_SYNC=1: a kernel without DRM_IOCTL_SYNCOBJ_EVENTFD (before +@@ -2647,6 +2714,11 @@ namespace gamescope + wl_output_add_listener( pOutput , &s_OutputListener, this ); + m_pOutputs.emplace( std::make_pair( std::move( pOutput ), WaylandOutputInfo{} ) ); + } ++ else if ( !strcmp( pInterface, droiddeck_refresh_v1_interface.name ) ) ++ { ++ m_pHostRefresh = (droiddeck_refresh_v1 *)wl_registry_bind( pRegistry, uName, &droiddeck_refresh_v1_interface, 1u ); ++ droiddeck_refresh_v1_add_listener( m_pHostRefresh, &s_RefreshListener, this ); ++ } + else if ( !strcmp( pInterface, frog_color_management_factory_v1_interface.name ) ) + { + m_pFrogColorMgmtFactory = (frog_color_management_factory_v1 *)wl_registry_bind( pRegistry, uName, &frog_color_management_factory_v1_interface, 1u ); +diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp +index 38b304b..d7d11b3 100644 +--- a/src/steamcompmgr.cpp ++++ b/src/steamcompmgr.cpp +@@ -1229,6 +1229,25 @@ static int g_nCombinedAppRefreshCycleOverride[gamescope::GAMESCOPE_SCREEN_TYPE_C + bool g_nCombinedAppRefreshCycleChangeRefresh[gamescope::GAMESCOPE_SCREEN_TYPE_COUNT] = { true, true }; + bool g_nCombinedAppRefreshCycleChangeFPS[gamescope::GAMESCOPE_SCREEN_TYPE_COUNT] = { true, true }; + ++int steamcompmgr_get_app_target_fps() ++{ ++ return g_nSteamCompMgrTargetFPS; ++} ++ ++int steamcompmgr_get_app_dynamic_refresh() ++{ ++ if ( !GetBackend()->GetCurrentConnector() ) ++ return 0; ++ return g_nDynamicRefreshRate[ GetBackend()->GetCurrentConnector()->GetScreenType() ]; ++} ++ ++static std::atomic g_bDisplayRatesChanged = { false }; ++ ++void steamcompmgr_display_rates_changed() ++{ ++ g_bDisplayRatesChanged = true; ++} ++ + static void _update_app_target_refresh_cycle() + { + if ( !GetBackend()->GetCurrentConnector() ) +@@ -9703,7 +9722,8 @@ void update_vrr_atoms(xwayland_ctx_t *root_ctx, bool force, bool* needs_flush = + *needs_flush = true; + } + +- if ( g_nOutputRefresh != g_nCurrentRefreshRate_CachedValue || force ) ++ const bool bDisplayRatesChanged = g_bDisplayRatesChanged.exchange( false ); ++ if ( g_nOutputRefresh != g_nCurrentRefreshRate_CachedValue || bDisplayRatesChanged || force ) + { + int32_t nRefresh = gamescope::ConvertmHzToHz( g_nOutputRefresh ); + XChangeProperty(root_ctx->dpy, root_ctx->root, root_ctx->atoms.gamescopeDisplayRefreshRateFeedback, XA_CARDINAL, 32, PropModeReplace, +diff --git a/src/steamcompmgr.hpp b/src/steamcompmgr.hpp +index ff54d8e..9e0bb79 100644 +--- a/src/steamcompmgr.hpp ++++ b/src/steamcompmgr.hpp +@@ -202,4 +202,7 @@ MouseCursor *steamcompmgr_get_server_cursor(uint32_t serverId); + + extern gamescope::ConVar cv_tearing_enabled; + ++extern int steamcompmgr_get_app_target_fps(); ++extern int steamcompmgr_get_app_dynamic_refresh(); ++extern void steamcompmgr_display_rates_changed(); + extern void steamcompmgr_set_app_refresh_cycle_override( gamescope::GamescopeScreenType type, int override_fps, bool change_refresh, bool change_fps_cap ); diff --git a/tools/gamescope/patches/0138-limiter-even-cadence.patch b/tools/gamescope/patches/0138-limiter-even-cadence.patch new file mode 100644 index 0000000000..429aa78933 --- /dev/null +++ b/tools/gamescope/patches/0138-limiter-even-cadence.patch @@ -0,0 +1,67 @@ +diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp +index d7d11b3..cfec551 100644 +--- a/src/steamcompmgr.cpp ++++ b/src/steamcompmgr.cpp +@@ -7188,6 +7188,19 @@ init_runtime_info() + update_runtime_info(); + } + ++static uint64_t limiter_latch_target( uint64_t ulPreviousTarget, uint64_t ulLatched, uint64_t ulLimitedCycle, uint64_t ulRefreshCycle ) ++{ ++ const uint64_t ulTarget = ulPreviousTarget + ulLimitedCycle; ++ const bool bLate = ulTarget + ulRefreshCycle * 3 / 4 < ulLatched; ++ const bool bEarly = ulTarget > ulLatched + ulRefreshCycle; ++ return ( bLate || bEarly ) ? ulLatched : ulTarget; ++} ++ ++static bool limiter_holds_vblank( uint64_t ulTarget, uint64_t ulNow, uint64_t ulLimitedCycle, uint64_t ulRefreshCycle ) ++{ ++ return ulNow + ulRefreshCycle / 2 < ulTarget + ulLimitedCycle; ++} ++ + static void + steamcompmgr_flush_frame_done( steamcompmgr_win_t *w ) + { +@@ -7206,6 +7219,9 @@ steamcompmgr_flush_frame_done( steamcompmgr_win_t *w ) + + w->last_commit_first_latch_time = timespec_to_nanos(now); + ++ w->limiter_latch_target_time = limiter_latch_target( w->limiter_latch_target_time, w->last_commit_first_latch_time, ++ g_SteamCompMgrLimitedAppRefreshCycle, g_SteamCompMgrAppRefreshCycle ); ++ + // Acknowledge commit once. + wlserver_lock(); + +@@ -7258,8 +7274,7 @@ static bool steamcompmgr_should_vblank_window( bool bShouldLimitFPS, uint64_t vb + { + if ( w && now ) + { +- uint64_t schedule = w->last_commit_first_latch_time + g_SteamCompMgrLimitedAppRefreshCycle; +- if ( now + g_SteamCompMgrAppRefreshCycle / 2 < schedule ) ++ if ( limiter_holds_vblank( w->limiter_latch_target_time, now, g_SteamCompMgrLimitedAppRefreshCycle, g_SteamCompMgrAppRefreshCycle ) ) + bSendCallback = false; + } + else +@@ -11047,9 +11062,7 @@ steamcompmgr_main(int argc, char **argv) + } + else + { +- int nVblankDivisor = nRealRefreshHz / nTargetFPS; +- +- g_SteamCompMgrLimitedAppRefreshCycle = g_SteamCompMgrAppRefreshCycle * nVblankDivisor; ++ g_SteamCompMgrLimitedAppRefreshCycle = g_SteamCompMgrAppRefreshCycle * nRealRefreshHz / nTargetFPS; + } + } + } +diff --git a/src/steamcompmgr_shared.hpp b/src/steamcompmgr_shared.hpp +index 0fcc80b..3c74d62 100644 +--- a/src/steamcompmgr_shared.hpp ++++ b/src/steamcompmgr_shared.hpp +@@ -146,6 +146,7 @@ struct steamcompmgr_win_t { + bool outdatedInteractiveFocus = false; + + uint64_t last_commit_first_latch_time = 0; ++ uint64_t limiter_latch_target_time = 0; + uint64_t last_commit_present_time = 0; + + bool hasHwndStyle = false; diff --git a/tools/gamescope/patches/0139-hdr-switch-live.patch b/tools/gamescope/patches/0139-hdr-switch-live.patch new file mode 100644 index 0000000000..3c1b839620 --- /dev/null +++ b/tools/gamescope/patches/0139-hdr-switch-live.patch @@ -0,0 +1,54 @@ +diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp +index 9862641..e9d2923 100644 +--- a/src/Backends/WaylandBackend.cpp ++++ b/src/Backends/WaylandBackend.cpp +@@ -1972,7 +1972,7 @@ namespace gamescope + { + auto *pHDRInfo = &m_pConnector->m_HDRInfo; + if (m_pBackend->SupportsColorManagement()) { +- pHDRInfo->bExposeHDRSupport = ( cv_hdr_enabled && m_pConnector->m_uMaxTargetLuminance > m_pConnector->m_uReferenceLuminance ); ++ pHDRInfo->bExposeHDRSupport = ( m_pConnector->m_uMaxTargetLuminance > m_pConnector->m_uReferenceLuminance ); + pHDRInfo->eOutputEncodingEOTF = pHDRInfo->bExposeHDRSupport ? EOTF_PQ : EOTF_Gamma22; + } + +@@ -2282,7 +2282,7 @@ namespace gamescope + + assert( u8BitFormat != DRM_FORMAT_INVALID ); + +- *pPrimaryPlaneFormat = u10BitFormat != DRM_FORMAT_INVALID ? u10BitFormat : u8BitFormat; ++ *pPrimaryPlaneFormat = ( cv_hdr_enabled && u10BitFormat != DRM_FORMAT_INVALID ) ? u10BitFormat : u8BitFormat; + *pOverlayPlaneFormat = u8BitFormat; + } + +@@ -2493,13 +2493,17 @@ namespace gamescope + + // XXX: We should do this a better way that handles per-window and appid stuff + // down the line +- if ( cv_hdr_enabled && GetCurrentConnector()->GetHDRInfo().bExposeHDRSupport ) ++ if ( !GetCurrentConnector()->GetHDRInfo().bExposeHDRSupport ) ++ { ++ setenv( "DXVK_HDR", "0", true ); ++ } ++ else if ( cv_hdr_enabled ) + { + setenv( "DXVK_HDR", "1", true ); + } + else + { +- setenv( "DXVK_HDR", "0", true ); ++ unsetenv( "DXVK_HDR" ); + } + + WritePatchedEdid( GetCurrentConnector()->GetRawEDID(), GetCurrentConnector()->GetHDRInfo(), false ); +diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp +index 42cc9c4..d0d21f0 100644 +--- a/src/rendervulkan.cpp ++++ b/src/rendervulkan.cpp +@@ -3735,6 +3735,7 @@ bool vulkan_remake_output_images() + + if ( vulkan_defer_output_images() ) + { ++ GetBackend()->GetPreferredOutputFormat( &pOutput->uOutputFormat, &pOutput->uOutputFormatOverlay ); + pOutput->outputImages.clear(); + pOutput->outputImagesPartialOverlay.clear(); + pOutput->temporaryHackyBlankImage = vulkan_create_debug_blank_texture(); diff --git a/tools/gamescope/release.env b/tools/gamescope/release.env index bf5211b032..c2ff293485 100644 --- a/tools/gamescope/release.env +++ b/tools/gamescope/release.env @@ -1,3 +1,3 @@ GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components -GAMESCOPE_TAG=gamescope-3.16.29-p23 -GAMESCOPE_SHA256=f5f2b8f658234ad2910a1be53c238188db7e7b2a9079f8cc5fa9ea006bebbe7e +GAMESCOPE_TAG=gamescope-3.16.29-zerocopy-8df683f1-qa +GAMESCOPE_SHA256=609198c39b125094a65e1703ffcfd6538e88c9784a1a6596bf673f2e5dc7af80 diff --git a/tools/linuxfs/desktop/droiddeck-desktop b/tools/linuxfs/desktop/droiddeck-desktop index d063bab657..f715ad18d7 100644 --- a/tools/linuxfs/desktop/droiddeck-desktop +++ b/tools/linuxfs/desktop/droiddeck-desktop @@ -24,7 +24,7 @@ if [ -n "${DD_DEBUG_DIR:-}" ]; then exec >>"$DD_DEBUG_DIR/desktop.log" 2>&1 echo "== droiddeck-desktop $(date -u '+%Y-%m-%d %H:%M:%S UTC') ${DD_WIDTH:-1280}x${DD_HEIGHT:-720}" fi -find "$XDG_RUNTIME_DIR" -mindepth 1 -maxdepth 1 ! -name 'wayland-0*' ! -name 'keymap.xkb' -exec rm -rf {} + 2>/dev/null +find "$XDG_RUNTIME_DIR" -mindepth 1 -maxdepth 1 ! -name 'wayland-0*' ! -name 'keymap.xkb' ! -name 'droiddeck-display-buffers' -exec rm -rf {} + 2>/dev/null chmod 700 "$XDG_RUNTIME_DIR" 2>/dev/null mkdir -p /tmp/.X11-unix /tmp/.ICE-unix && chmod 1777 /tmp/.X11-unix /tmp/.ICE-unix 2>/dev/null export DD_DESKTOP=1 diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat index b39682bc29..32a9889b87 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat @@ -66,19 +66,32 @@ BRIGHTNESS_JS = r""" """.replace("__BINDING__", BRIGHTNESS_BINDING) +def control_request(name, text, directory): + path = os.path.join(directory, name) + with open(path + ".tmp", "w") as target: + target.write(text + "\n") + os.replace(path + ".tmp", path) + + def brightness_request(payload, directory=CONTROLS_DIR): try: value = float(payload) if not math.isfinite(value) or not 0 <= value <= 1: return - path = os.path.join(directory, "brightness.request") - with open(path + ".tmp", "w") as target: - target.write(str(value) + "\n") - os.replace(path + ".tmp", path) + control_request("brightness.request", str(value), directory) except (ValueError, TypeError, OSError): return +def hdr_request(payload, directory=CONTROLS_DIR): + if payload not in ("0", "1"): + return + try: + control_request("hdr.request", payload, directory) + except OSError: + return + + INSTALL_JS = r""" (() => { if (window.__droiddeckCompat) return "present"; @@ -256,6 +269,49 @@ TOUR_JS = r""" return "off"; })() """ +SET_SETTING_JS = r"""(field, value) => { + const bytes = []; + for (let n of [field * 8, value]) { + while (n > 127) { bytes.push((n & 127) | 128); n = Math.floor(n / 128); } + bytes.push(n); + } + return SteamClient.Settings.SetSetting(btoa(String.fromCharCode(...bytes))); + }""" +HDR_BINDING = "droiddeckHdrChanged" +HDR_JS = r""" +(() => { + if (window.__droiddeckHdr) return "present"; + const settings = window.settingsStore; + if (typeof settings?.clientSettings?.gamescope_hdr_enabled !== "boolean" || + typeof SteamClient.Settings?.SetSetting !== "function") return "unavailable"; + const write = __SET_SETTING__; + const HOLD_MS = 3000; + const self = { known: settings.clientSettings.gamescope_hdr_enabled, pending: null, until: 0 }; + self.set = value => { + if (typeof value !== "boolean") return true; + self.known = value; + if (settings.clientSettings.gamescope_hdr_enabled === value && self.pending === null) return true; + self.pending = value; + self.until = performance.now() + HOLD_MS; + write(21015, value ? 1 : 0); + return true; + }; + self.check = () => { + const value = settings.clientSettings.gamescope_hdr_enabled; + if (typeof value !== "boolean") return; + if (self.pending !== null) { + if (value !== self.pending && performance.now() < self.until) return; + self.pending = null; + } + if (value === self.known) return; + self.known = value; + if (typeof window.__BINDING__ === "function") window.__BINDING__(value ? "1" : "0"); + }; + self.interval = setInterval(self.check, 500); + window.__droiddeckHdr = self; + return "installed"; +})() +""".replace("__BINDING__", HDR_BINDING).replace("__SET_SETTING__", SET_SETTING_JS) FRAME_LIMIT_JS = r""" (() => { if (window.__droiddeckFrameLimit) return "present"; @@ -281,14 +337,7 @@ FRAME_LIMIT_JS = r""" } if (!service || !settings?.clientSettings || typeof SteamClient.Settings?.SetSetting !== "function") return "unavailable"; const self = { timer: null }; - const write = value => { - const bytes = []; - for (let n of [21002 * 8, value]) { - while (n > 127) { bytes.push((n & 127) | 128); n = Math.floor(n / 128); } - bytes.push(n); - } - return SteamClient.Settings.SetSetting(btoa(String.fromCharCode(...bytes))); - }; + const write = value => (__SET_SETTING__)(21002, value); self.check = async () => { let rates; try { @@ -316,7 +365,7 @@ FRAME_LIMIT_JS = r""" window.__droiddeckFrameLimit = self; return "installed"; })() -""" +""".replace("__SET_SETTING__", SET_SETTING_JS) WINDOW_BINDING = "droiddeckWindowAction" WINDOW_TARGET = "createflags=18" WINDOW_MOVES = {"nw": 0, "n": 1, "ne": 2, "e": 3, "se": 4, "s": 5, "sw": 6, "w": 7, "move": 8} @@ -923,6 +972,9 @@ class Helper: self.controls_installed = False self.frame_limit_state = None self.frame_limit_retry = 0 + self.hdr_state = None + self.hdr_installed = False + self.hdr_retry = 0 self.windows = {} self.windows_retry = 0 @@ -983,6 +1035,29 @@ class Helper: except (Closed, OSError, ValueError): del self.windows[ident] + def sync_hdr(self): + try: + with open(os.path.join(CONTROLS_DIR, "state.json")) as source: + value = json.load(source).get("hdr") + if not isinstance(value, bool): + return + if not self.hdr_installed: + if time.monotonic() < self.hdr_retry: + return + self.page.call("Runtime.addBinding", {"name": HDR_BINDING}) + self.hdr_installed = self.page.evaluate(HDR_JS) in ("installed", "present") + if not self.hdr_installed: + self.hdr_retry = time.monotonic() + 10 + return + if value != self.hdr_state: + if self.page.evaluate("window.__droiddeckHdr ? window.__droiddeckHdr.set(%s) : false" % json.dumps(value)) is True: + self.hdr_state = value + else: + self.hdr_state = None + self.hdr_installed = False + except (OSError, ValueError, TypeError, AttributeError): + pass + def sync_frame_limit(self): if self.frame_limit_state in ("installed", "present") or time.monotonic() < self.frame_limit_retry: return @@ -1095,6 +1170,9 @@ class Helper: self.controls_installed = False self.frame_limit_state = None self.frame_limit_retry = 0 + self.hdr_state = None + self.hdr_installed = False + self.hdr_retry = 0 self.sync_controls() return True @@ -1231,6 +1309,8 @@ class Helper: for e in events: if called(e, BRIGHTNESS_BINDING): brightness_request(e.get("params", {}).get("payload")) + if called(e, HDR_BINDING): + hdr_request(e.get("params", {}).get("payload")) if called(e, FILE_BINDING) and isinstance(e.get("params", {}).get("payload"), str): self.open_chooser(e["params"]["payload"]) return events @@ -1260,6 +1340,7 @@ class Helper: while True: self.sync_controls() self.sync_frame_limit() + self.sync_hdr() self.sync_windows() sources = [self.page.ws] + ([watcher] if watcher.fileno() >= 0 else []) sources += [page.ws for page in self.windows.values()] diff --git a/tools/tests/test_desktop_display_buffers.py b/tools/tests/test_desktop_display_buffers.py new file mode 100644 index 0000000000..0c3defcb83 --- /dev/null +++ b/tools/tests/test_desktop_display_buffers.py @@ -0,0 +1,29 @@ +from pathlib import Path +import re +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] +DESKTOP = ROOT / "tools/linuxfs/desktop/droiddeck-desktop" +SOURCE = ROOT / "app/src/main/cpp/waylandcomp/src/display_buffers.c" + + +class DesktopDisplayBuffersTest(unittest.TestCase): + def test_clearing_the_runtime_directory_keeps_what_the_compositor_serves(self): + socket = re.search(r'#define DISPLAY_BUFFERS_SOCKET "([^"]+)"', SOURCE.read_text()).group(1) + lines = [line for line in DESKTOP.read_text().splitlines() if line.startswith('find "$XDG_RUNTIME_DIR"')] + self.assertEqual(len(lines), 1) + with tempfile.TemporaryDirectory() as directory: + runtime = Path(directory) / "runtime" + (runtime / "dbus-1").mkdir(parents=True) + kept = ["wayland-0", "wayland-0.lock", "keymap.xkb", socket] + for name in kept + ["wayland-1", "pipewire-0", "dbus-1/session"]: + (runtime / name).write_text("") + subprocess.run(["bash", "-c", lines[0]], env={"XDG_RUNTIME_DIR": str(runtime), "PATH": "/usr/bin:/bin"}, + check=True, timeout=20) + self.assertEqual(sorted(path.name for path in runtime.iterdir()), sorted(kept)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_effects_source_resolution.py b/tools/tests/test_effects_source_resolution.py index 92ae2d6150..cd63c69d64 100644 --- a/tools/tests/test_effects_source_resolution.py +++ b/tools/tests/test_effects_source_resolution.py @@ -203,7 +203,7 @@ static struct { float kx, ky, off_x, off_y; int rx, ry, rw, rh; } g_map; static struct { VkImage img; int w, h; } g_scene; struct vkp_img_slot { VkImage img; int w, h; }; static struct vkp_img_slot g_hdrscene, g_fgscene; -static struct { int active, rw, rh; VkImage result; } g_pass; +static struct { int active, rw, rh, ngen; VkImage result; VkImage gens[VKP_FG_MAX_GENERATIONS]; } g_pass; static struct { int64_t present_ns, present_max_ns; unsigned presents; } g_perf; static int effects_active = 1, framegen, cardboard; struct fx_settings { int scaling, cas_on, cas_pct; }; @@ -368,7 +368,7 @@ static void run_path(int offscreen, const struct vkp_draw *draw, int n, const st assert(n > 0 && n <= 4); memcpy(before, draw, n * sizeof(*draw)); int rw = 0, rh = 0; - assert((offscreen ? pass_begin_impl(1920, 1080, draw, n, hdr, &rw, &rh) + assert((offscreen ? pass_begin_impl(1920, 1080, draw, n, hdr, 0, &rw, &rh) : render_impl(1920, 1080, draw, n, hdr, NULL)) == 0); assert(memcmp(draw, before, n * sizeof(*draw)) == 0); if (offscreen) assert(rw == (fail_effects ? effects_w : (int)g_extent.width) && @@ -393,7 +393,7 @@ static void check_path(int offscreen) { run_path(offscreen, &draw, 1, NULL); check_input(1280, 720); reset(); draw = fullscreen(); draw.dw = 1280; draw.dh = 720; int rw, rh; - assert((offscreen ? pass_begin_impl(1280, 720, &draw, 1, NULL, &rw, &rh) + assert((offscreen ? pass_begin_impl(1280, 720, &draw, 1, NULL, 0, &rw, &rh) : render_impl(1280, 720, &draw, 1, NULL, NULL)) == 0); check_input(1280, 720); } diff --git a/tools/tests/test_gamescope_limiter_cadence.py b/tools/tests/test_gamescope_limiter_cadence.py new file mode 100644 index 0000000000..79a4319adb --- /dev/null +++ b/tools/tests/test_gamescope_limiter_cadence.py @@ -0,0 +1,118 @@ +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +PATCH = ROOT / "tools/gamescope/patches/0138-limiter-even-cadence.patch" + + +def added_source(): + return "\n".join(line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")) + + +def block(text, start): + begin = text.index(start) + return text[begin:text.index("\n}", begin) + 3] + + +PREAMBLE = r''' +#include +#include +#include +#include +''' + +MAIN = r''' +struct Run { + std::vector gaps; + int frames = 0; +}; + +static Run run(int hz, int fps, int vblanks, uint64_t latency) { + const uint64_t cycle = 1000000000ull / hz; + const uint64_t limited = cycle * hz / fps; + uint64_t target = 0; + int last = -1; + Run r; + for (int i = 0; i < vblanks; i++) { + const uint64_t now = (1000ull + i) * cycle; + if (limiter_holds_vblank(target, now, limited, cycle)) continue; + target = limiter_latch_target(target, now + latency, limited, cycle); + if (last >= 0) r.gaps.push_back(i - last); + last = i; + r.frames++; + } + return r; +} + +static void check(int hz, int fps, uint64_t latency) { + const int vblanks = hz * 20; + const Run r = run(hz, fps, vblanks, latency); + const int low = hz / fps; + const int high = (hz + fps - 1) / fps; + for (int gap : r.gaps) { + if (gap != low && gap != high) { + std::printf("%d Hz at %d fps: a frame was held for %d refreshes\n", hz, fps, gap); + assert(false); + } + } + const int expected = fps * 20; + if (r.frames < expected - 1 || r.frames > expected + 1) { + std::printf("%d Hz at %d fps: %d frames, expected %d\n", hz, fps, r.frames, expected); + assert(false); + } +} + +int main() { + const int rates[] = {60, 90, 120, 144, 165}; + const int limits[] = {24, 30, 36, 40, 45, 48, 50, 60, 72, 80, 90, 100, 120, 144}; + for (int hz : rates) { + for (int fps : limits) { + if (fps > hz) continue; + check(hz, fps, 0); + check(hz, fps, 1000000000ull / hz / 4); + } + } + + const Run even = run(60, 30, 600, 0); + for (int gap : even.gaps) assert(gap == 2); + const Run full = run(120, 120, 600, 0); + for (int gap : full.gaps) assert(gap == 1); + const Run two_of_three = run(60, 40, 600, 0); + for (size_t i = 1; i < two_of_three.gaps.size(); i++) assert(two_of_three.gaps[i] != two_of_three.gaps[i - 1]); + + const uint64_t cycle = 16666666, limited = cycle * 60 / 45; + assert(limiter_latch_target(1000 * cycle, 1500 * cycle, limited, cycle) == 1500 * cycle); + assert(limiter_latch_target(1500 * cycle, 1000 * cycle, limited, cycle) == 1000 * cycle); + assert(limiter_latch_target(1000 * cycle, 1001 * cycle, limited, cycle) == 1000 * cycle + limited); + return 0; +} +''' + + +class GamescopeLimiterCadenceTest(unittest.TestCase): + def test_a_limit_the_refresh_rate_does_not_divide_is_spread_evenly(self): + compiler = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++") + if not compiler: + self.skipTest("no C++ compiler") + added = added_source() + source = PREAMBLE + block(added, "static uint64_t limiter_latch_target") + block(added, "static bool limiter_holds_vblank") + MAIN + with tempfile.TemporaryDirectory() as tmp: + src = Path(tmp) / "limiter_cadence.cpp" + exe = Path(tmp) / "limiter_cadence" + src.write_text(source) + subprocess.run([compiler, "-std=c++17", "-Wall", "-Werror", "-UNDEBUG", str(src), "-o", str(exe)], check=True) + subprocess.run([str(exe)], check=True) + + def test_the_limited_cycle_is_no_longer_a_whole_number_of_refreshes(self): + added = added_source() + self.assertIn("g_SteamCompMgrAppRefreshCycle * nRealRefreshHz / nTargetFPS", added) + removed = "\n".join(line[1:] for line in PATCH.read_text().splitlines() if line.startswith("-") and not line.startswith("---")) + self.assertIn("nVblankDivisor", removed) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_hdr_live_switch.py b/tools/tests/test_hdr_live_switch.py new file mode 100644 index 0000000000..4468be5048 --- /dev/null +++ b/tools/tests/test_hdr_live_switch.py @@ -0,0 +1,87 @@ +from pathlib import Path +import re +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +PATCH = ROOT / "tools/gamescope/patches/0139-hdr-switch-live.patch" +APP = ROOT / "app/src/main/java/com/droiddeck/launcher" +RES = ROOT / "app/src/main/res" + + +def lines(prefix): + return [line[1:] for line in PATCH.read_text().splitlines() + if line.startswith(prefix) and not line.startswith(prefix * 3)] + + +class HdrLiveSwitchTest(unittest.TestCase): + def test_display_capability_does_not_depend_on_the_setting(self): + added = [line for line in lines("+") if "bExposeHDRSupport =" in line] + self.assertEqual(len(added), 1) + self.assertNotIn("cv_hdr_enabled", added[0]) + self.assertIn("m_uMaxTargetLuminance > m_pConnector->m_uReferenceLuminance", added[0]) + + def test_sdr_keeps_the_8_bit_output(self): + added = [line for line in lines("+") if "*pPrimaryPlaneFormat" in line] + self.assertEqual(len(added), 1) + self.assertRegex(added[0], r"cv_hdr_enabled && u10BitFormat != DRM_FORMAT_INVALID \) \? u10BitFormat : u8BitFormat") + + def test_remade_output_images_pick_the_format_again(self): + text = PATCH.read_text() + hunk = text[text.index("src/rendervulkan.cpp"):] + added = [line[1:] for line in hunk.splitlines() if line.startswith("+") and not line.startswith("+++")] + self.assertEqual([line.strip() for line in added], + ["GetBackend()->GetPreferredOutputFormat( &pOutput->uOutputFormat, &pOutput->uOutputFormatOverlay );"]) + self.assertIn("if ( vulkan_defer_output_images() )", hunk[:hunk.index(added[0])]) + + def test_capable_display_does_not_force_dxvk_hdr_off(self): + added = "\n".join(lines("+")) + self.assertIn('unsetenv( "DXVK_HDR" )', added) + off = added.index('setenv( "DXVK_HDR", "0", true )') + self.assertIn("!GetCurrentConnector()->GetHDRInfo().bExposeHDRSupport", added[:off]) + + def test_the_gate_follows_the_display_not_the_setting(self): + text = (APP / "SessionActivity.kt").read_text() + start = text.index("val attached = CompositorHost.isStarted") + block = text[start:text.index("DriverSetupLog.write", start)] + request = block[block.index("nativeSetHdrRequest("):block.index("Log.i", block.index("nativeSetHdrRequest("))] + self.assertNotIn("SessionPrefs.hdr", block[:block.index("if (!SessionState.running)")]) + self.assertIn("capable, false", request) + self.assertIn("SessionState.hdrCapable && SessionPrefs.hdr(this, mode)", block) + + def test_both_switches_apply_to_the_running_session(self): + helper = (APP / "session/SessionHdr.kt").read_text() + self.assertIn('setGamescopeConvar(app, "hdr_enabled", if (on) 1 else 0)', helper) + self.assertIn("nativeSetHdrOutput(on)", helper) + self.assertIn("nativeSetZeroCopy(on || SessionPrefs.zeroCopy(context, mode))", helper) + self.assertIn("SessionPrefs.prefMode(SessionState.mode) != mode", helper) + for name in ("SessionActivity.kt", "FrontEndActivity.kt"): + text = (APP / name).read_text() + self.assertEqual(len(re.findall(r"onHdr = \{ on -> com\.droiddeck\.launcher\.session\.SessionHdr\.set\(", text)), 1, name) + self.assertNotIn("SessionPrefs.setHdr(", text, name) + + def test_a_saved_opt_out_applies_before_the_gate_opens(self): + native = (ROOT / "app/src/main/cpp/waylandcomp/src/wl_color_mgmt.c").read_text() + switch = native[native.index("void droiddeck_color_set_output(int on)"):] + switch = switch[:switch.index("if (gate != 1)")] + self.assertLess(switch.index("pthread_mutex_lock(&g_output_mu)"), switch.index("atomic_store(&g_output_wanted, on)")) + self.assertLess(switch.index("atomic_exchange(&g_output_on, on)"), switch.index("pthread_mutex_unlock(&g_output_mu)")) + opened = native[native.index("atomic_store(&g_gate, 1);") - 40:] + opened = opened[:opened.index("pthread_mutex_unlock(&g_output_mu)")] + self.assertIn("pthread_mutex_lock(&g_output_mu)", opened) + self.assertIn("if (mode == 3 || !atomic_load(&g_output_wanted)) atomic_store(&g_output_on, 0);", opened) + text = (APP / "SessionActivity.kt").read_text() + self.assertNotIn("if (attached) WaylandCompositor.nativeSetHdrOutput", text) + + def test_retries_stay_with_the_session_that_asked(self): + helper = (APP / "session/SessionHdr.kt").read_text() + self.assertIn("val session = SessionState.sessionId", helper) + self.assertIn("SessionState.sessionId == session", helper) + + def test_no_restart_hint_is_left(self): + for path in list(RES.glob("values*/strings.xml")) + list(APP.rglob("*.kt")): + self.assertNotIn("mode_hdr_restart", path.read_text(), str(path)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_hdr_steam_sync.py b/tools/tests/test_hdr_steam_sync.py new file mode 100644 index 0000000000..c550a892d8 --- /dev/null +++ b/tools/tests/test_hdr_steam_sync.py @@ -0,0 +1,185 @@ +import json +from pathlib import Path +import runpy +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] +BIN = ROOT / "tools/linuxfs/overlay/usr/local/bin" +APP = ROOT / "app/src/main/java/com/droiddeck/launcher" +LIVE = runpy.run_path(str(BIN / "droiddeck-steam-compat")) + +HARNESS = r""" +const assert = require('assert'); +globalThis.window = globalThis; +globalThis.btoa = text => Buffer.from(text, 'binary').toString('base64'); +let now = 0, tick = null; +Object.defineProperty(globalThis, 'performance', { value: { now: () => now }, configurable: true }); +globalThis.setInterval = callback => { tick = callback; return 1; }; +const varints = bytes => { const out = []; let value = 0, shift = 0; + for (const b of bytes) { value += (b & 127) * 2 ** shift; shift += 7; if (b < 128) { out.push(value); value = 0; shift = 0; } } + return out; }; +const writes = [], told = []; +let apply = true; +globalThis.settingsStore = { clientSettings: { gamescope_hdr_enabled: false } }; +globalThis.SteamClient = { Settings: { SetSetting(encoded) { + const [key, value] = varints([...Buffer.from(encoded, 'base64')]); + assert.strictEqual(key, 21015 * 8); + writes.push(value); + if (apply) settingsStore.clientSettings.gamescope_hdr_enabled = value === 1; +} } }; +window.droiddeckHdrChanged = value => told.push(value); +const script = require('fs').readFileSync(process.argv[2], 'utf8'); +assert.strictEqual(eval(script), 'installed'); +assert.strictEqual(eval(script), 'present'); +const bridge = window.__droiddeckHdr; +tick(); +assert.deepStrictEqual(told, [], 'an unchanged client setting is not reported'); +assert.strictEqual(bridge.set(true), true); +assert.deepStrictEqual(writes, [1]); +tick(); +assert.deepStrictEqual(told, [], 'a value the app set is not reported back to it'); +assert.strictEqual(bridge.set(true), true); +assert.deepStrictEqual(writes, [1], 'an equal value is not written again'); +settingsStore.clientSettings.gamescope_hdr_enabled = false; +tick(); +assert.deepStrictEqual(told, ['0'], 'a change made in the client reaches the app'); +tick(); +assert.deepStrictEqual(told, ['0']); +settingsStore.clientSettings.gamescope_hdr_enabled = true; +tick(); +assert.deepStrictEqual(told, ['0', '1']); +apply = false; +bridge.set(false); +assert.deepStrictEqual(writes, [1, 0]); +now += 500; tick(); +assert.deepStrictEqual(told, ['0', '1'], 'the old value is not reported while a write is settling'); +now += 3000; tick(); +assert.deepStrictEqual(told, ['0', '1', '1'], 'a write the client did not take is reported as its real value'); +assert.strictEqual(bridge.set('yes'), true); +assert.deepStrictEqual(writes, [1, 0]); +bridge.set(false); +bridge.set(true); +assert.deepStrictEqual(writes, [1, 0, 0, 1], 'a newer opposite value is written while the earlier write is settling'); +settingsStore.clientSettings.gamescope_hdr_enabled = false; +now += 500; tick(); +settingsStore.clientSettings.gamescope_hdr_enabled = true; +now += 500; tick(); +assert.deepStrictEqual(told, ['0', '1', '1'], 'the earlier write landing late is not reported to the app'); +delete globalThis.__droiddeckHdr; +delete settingsStore.clientSettings.gamescope_hdr_enabled; +assert.strictEqual(eval(script), 'unavailable'); +""" + + +class HdrSteamSyncTest(unittest.TestCase): + def test_bridge_keeps_the_client_setting_and_the_app_equal(self): + with tempfile.TemporaryDirectory() as directory: + script = Path(directory) / "bridge.js" + script.write_text(LIVE["HDR_JS"]) + test = Path(directory) / "test.js" + test.write_text(HARNESS) + result = subprocess.run(["node", str(test), str(script)], capture_output=True, text=True, timeout=20) + self.assertEqual(result.returncode, 0, result.stderr) + + def test_requests_accept_only_on_and_off(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "hdr.request" + for value in ["2", "true", "", None, 1]: + LIVE["hdr_request"](value, directory) + self.assertFalse(path.exists()) + LIVE["hdr_request"]("1", directory) + self.assertEqual(path.read_text(), "1\n") + LIVE["hdr_request"]("0", directory) + self.assertEqual(path.read_text(), "0\n") + + def helper(self, directory): + helper = LIVE["Helper"]("/steam", 0) + calls = [] + + class Page: + answer = True + + def call(self, method, params=None): + calls.append((method, params)) + + def evaluate(self, expression): + calls.append(expression) + return "installed" if expression == LIVE["HDR_JS"] else self.answer + + helper.page = Page() + return helper, calls + + def test_the_app_state_is_applied_once_per_change(self): + with tempfile.TemporaryDirectory() as directory: + globals_ = LIVE["Helper"].sync_hdr.__globals__ + previous = globals_["CONTROLS_DIR"] + try: + globals_["CONTROLS_DIR"] = directory + helper, calls = self.helper(directory) + path = Path(directory) / "state.json" + helper.sync_hdr() + path.write_text(json.dumps({"brightness": 0.5})) + helper.sync_hdr() + self.assertEqual(calls, [], "a session that cannot show HDR leaves the client setting alone") + path.write_text(json.dumps({"brightness": 0.5, "hdr": True})) + helper.sync_hdr() + helper.sync_hdr() + self.assertEqual(calls[0], ("Runtime.addBinding", {"name": LIVE["HDR_BINDING"]})) + self.assertEqual(calls[1], LIVE["HDR_JS"]) + self.assertEqual(calls[2:], ["window.__droiddeckHdr ? window.__droiddeckHdr.set(true) : false"]) + path.write_text(json.dumps({"brightness": 0.7, "hdr": True})) + helper.sync_hdr() + self.assertEqual(len(calls), 3) + path.write_text(json.dumps({"hdr": False})) + helper.sync_hdr() + self.assertEqual(calls[3], "window.__droiddeckHdr ? window.__droiddeckHdr.set(false) : false") + helper.page.answer = False + path.write_text(json.dumps({"hdr": True})) + helper.sync_hdr() + self.assertFalse(helper.hdr_installed) + self.assertIsNone(helper.hdr_state) + helper.page.answer = True + path.write_text(json.dumps({"hdr": False})) + helper.sync_hdr() + self.assertEqual(calls[-1], "window.__droiddeckHdr ? window.__droiddeckHdr.set(false) : false") + finally: + globals_["CONTROLS_DIR"] = previous + + def test_a_client_without_the_setting_is_left_alone(self): + with tempfile.TemporaryDirectory() as directory: + globals_ = LIVE["Helper"].sync_hdr.__globals__ + previous = globals_["CONTROLS_DIR"] + try: + globals_["CONTROLS_DIR"] = directory + helper, calls = self.helper(directory) + helper.page.evaluate = lambda expression: calls.append(expression) or "unavailable" + (Path(directory) / "state.json").write_text(json.dumps({"hdr": True})) + helper.sync_hdr() + self.assertEqual(calls, [("Runtime.addBinding", {"name": LIVE["HDR_BINDING"]}), LIVE["HDR_JS"]]) + self.assertFalse(helper.hdr_installed) + self.assertIsNone(helper.hdr_state) + helper.sync_hdr() + self.assertEqual(len(calls), 2, "a client without the setting is not asked again straight away") + finally: + globals_["CONTROLS_DIR"] = previous + + def test_the_app_publishes_and_takes_the_shared_value(self): + controls = (APP / "runtime/DeviceControlsComponent.kt").read_text() + self.assertIn('if (SessionState.hdrCapable) controls.put("hdr", SessionState.hdr)', controls) + self.assertIn('"hdr.request" -> if (text == "0" || text == "1")', controls) + self.assertIn('SessionHdr.set(context, SessionPrefs.prefMode(SessionState.mode), text == "1")', controls) + self.assertIn('"hdr.request")', controls[controls.index("REQUESTS = setOf"):]) + session = (APP / "SessionActivity.kt").read_text() + self.assertIn("if (key == SessionPrefs.hdrKey(hdrPrefMode()))", session) + self.assertIn("registerOnSharedPreferenceChangeListener(hdrPrefListener)", session) + self.assertIn("unregisterOnSharedPreferenceChangeListener(hdrPrefListener)", session) + + def test_frame_limit_writes_share_the_setting_writer(self): + self.assertIn("(21002, value)", LIVE["FRAME_LIMIT_JS"]) + self.assertNotIn("__SET_SETTING__", LIVE["FRAME_LIMIT_JS"] + LIVE["HDR_JS"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_output_refresh.py b/tools/tests/test_output_refresh.py index 8896d3e551..96817b2f4f 100644 --- a/tools/tests/test_output_refresh.py +++ b/tools/tests/test_output_refresh.py @@ -44,10 +44,11 @@ static struct surface surface = { .xdg_toplevel = 1, .toplevel_committed = 1 }; static int g_input_pipe[2] = {-1, -1}; static atomic_int g_output_refresh_mhz = 60000; static atomic_int g_output_refresh_pending; +static atomic_int g_panel_rates_pending; static int g_output_announced_refresh_mhz = 60000; static int g_output_w = 1920, g_output_h = 1080; static int flushes, resizes, pointers, ticks; -static int scale_changes, scale_mode, scale_alignment, renders; +static int scale_changes, scale_mode, scale_alignment, renders, rate_notifies; static void *g_display; #define WL_OUTPUT_MODE_CURRENT 1 #define WL_OUTPUT_MODE_PREFERRED 2 @@ -77,6 +78,7 @@ static void vk_present_set_scale_mode(int mode, int alignment) { scale_changes++; scale_mode = mode; scale_alignment = alignment; } static void schedule_render(void) { renders++; } +static void refresh_notify_rates(void) { rate_notifies++; } ''' CHECKS = r''' @@ -138,6 +140,11 @@ int main(void) { droiddeck_wayland_set_output_refresh_rate(90000); drain(); expect(6, 90000, 1); assert(scale_changes == 2 && scale_mode == 1 && scale_alignment == 3 && renders == 2); + atomic_store(&g_panel_rates_pending, 1); + drain(); + assert(rate_notifies == 1 && !atomic_load(&g_panel_rates_pending)); + drain(); + assert(rate_notifies == 1); close(g_input_pipe[0]); close(g_input_pipe[1]); puts("PASS"); } diff --git a/tools/tests/test_render_on_commit.py b/tools/tests/test_render_on_commit.py index c0b8c436d5..66abb89d7f 100644 --- a/tools/tests/test_render_on_commit.py +++ b/tools/tests/test_render_on_commit.py @@ -26,7 +26,7 @@ static struct wl_event_source *g_render_idle, *g_fallback_timer; static int g_fallback_armed, g_dirty, g_hud_fresh, framegen; static void *g_hud_surface; static int64_t g_dirty_since_ns, g_last_vsync_ns, g_tick_vsync_ns, g_hud_last_ns, g_rendered_tick_ns; -static int g_tick_held; +static int g_tick_held, g_tick_spare, g_scene_queues; static int64_t g_hold_missed_ns; #define HOLD_RETRY_NS 1000000000LL static int64_t g_refresh_ns = 16666667; @@ -254,6 +254,15 @@ int main(void) { clock_ns += 200000000LL; schedule_render(); assert(idles_added == idles && g_fallback_armed == 1 && timers_armed == 1); + g_rendered_tick_ns = g_tick_vsync_ns; + g_tick_spare = 0; g_scene_queues = 1; + assert(!tick_takes_scene()); + g_tick_spare = 1; + assert(tick_takes_scene()); + g_scene_queues = 0; + assert(!tick_takes_scene()); + g_rendered_tick_ns = g_tick_vsync_ns - 1; + assert(tick_takes_scene()); puts("PASS"); return 0; } @@ -270,7 +279,7 @@ class RenderOnCommitTest(unittest.TestCase): render = extract_function(source, 'render_scene') self.assertIn('g_rendered_tick_ns = g_tick_vsync_ns;', render) self.assertIn('g_tick_held = 0;', render) - functions = ('scene_held_for_limit', 'commit_renders_on', 'render_on_commit', 'schedule_render', 'scene_waits_for_game', 'on_commit_idle', + functions = ('scene_held_for_limit', 'commit_renders_on', 'tick_takes_scene', 'render_on_commit', 'schedule_render', 'scene_waits_for_game', 'on_commit_idle', 'bfi_blocked', 'bfi_update', 'bfi_tick', 'on_vsync') harness = PREAMBLE + '\n'.join(extract_function(source, name) for name in functions) + CHECKS with tempfile.TemporaryDirectory(prefix='droiddeck-render-on-commit-') as folder: diff --git a/tools/tests/test_vk_linear_dmabuf.py b/tools/tests/test_vk_linear_dmabuf.py index 32f6a7f375..a91df519c6 100644 --- a/tools/tests/test_vk_linear_dmabuf.py +++ b/tools/tests/test_vk_linear_dmabuf.py @@ -33,6 +33,7 @@ static const uint32_t g_qfam = 2; %(is_dmabuf)s %(width)s %(height)s +static int black_fill_below(const struct draw_list *dl, int n) { (void)dl; (void)n; return 0; } %(candidate)s static int candidate(struct vkp_image *img) { diff --git a/tools/tests/vk_terminal_callers_test.c b/tools/tests/vk_terminal_callers_test.c index 2398608bd2..ebf8fbf096 100644 --- a/tools/tests/vk_terminal_callers_test.c +++ b/tools/tests/vk_terminal_callers_test.c @@ -110,7 +110,7 @@ struct damage_list { int n; }; struct surface { struct vkp_image *shm_img; struct wl_resource *resource; - int buf_w, buf_h, buf_alpha, has_content; + int buf_w, buf_h, buf_alpha, has_content, black_fill; /* Read by take_shm's game-frame detection; with no damage it stays off here. */ int src_set; float src[4]; struct damage_list damage_buf, damage_local; From 64b7339da90f8a77b4491fccb8e2b9b464639bed Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Sat, 21 Nov 2026 03:42:45 -0500 Subject: [PATCH 004/141] feat(input): restyle Steam Deck buttons (#2966) * feat(input): restyle Steam Deck buttons * feat(input): add Steam overlay options * fix(input): align floating overlay previews * fix(input): polish floating Steam trackpads * fix(input): restore overlay options on startup * fix(input): restore original Steam Deck artwork * fix(input): restore Steam Deck overlay geometry * fix(input): keep the Steam Deck shortcut row apart on small screens The Steam pill sits right of the keyboard by a density-based margin while Select and Start sit at unit-scaled offsets from the middle, so on a small, dense surface (800x450 at xxxhdpi) the Steam pill covered Select. Lay out Steam, Select, Start and Quick Access left to right with an 8 dp gap. * fix(input): fit the Steam Deck shortcut row inside the safe area Clamping each pill on its own after spacing could move Quick Access back onto Start when a cutout inset narrows the right side. Fit the keyboard, Steam, Select, Start and Quick Access as one row: push each right past its neighbour, pull the row back inside the right edge, and shrink the 8 dp gap only when the row would not fit otherwise. --------- Co-authored-by: K11MCH1 <81425424+K11MCH1@users.noreply.github.com> --- .../com/droiddeck/launcher/SessionActivity.kt | 35 ++- .../launcher/input/FloatingSteamOverlay.kt | 92 ++++++ .../launcher/input/OnScreenControls.kt | 21 +- .../launcher/input/OnScreenLayout.kt | 22 +- .../input/SteamDeckOverlayGeometry.kt | 116 ++++++++ .../launcher/session/SessionPrefs.kt | 6 + .../launcher/ui/InputLayoutWidgets.kt | 9 +- .../launcher/ui/InputSettingsPage.kt | 4 +- .../launcher/ui/InputSurfaceEditorView.kt | 13 +- .../droiddeck/launcher/ui/InputSurfaceView.kt | 89 +++++- .../droiddeck/launcher/ui/SessionOverlay.kt | 11 + .../launcher/ui/SteamDeckButtonArt.kt | 277 ++++++++++++++++++ app/src/main/res/values/strings.xml | 2 + .../launcher/input/OnScreenLayoutTest.kt | 96 +++++- .../launcher/ui/InputSurfaceTouchTest.kt | 17 ++ 15 files changed, 785 insertions(+), 25 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/input/FloatingSteamOverlay.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/input/SteamDeckOverlayGeometry.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/ui/SteamDeckButtonArt.kt diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index cb5ee53185..fb788f2ef1 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -77,6 +77,7 @@ import com.droiddeck.launcher.input.KeyboardHost import com.droiddeck.launcher.input.ControllerPrefs import com.droiddeck.launcher.input.SessionClipboard import com.droiddeck.launcher.input.OnScreenControls +import com.droiddeck.launcher.input.OnScreenLayout import com.droiddeck.launcher.input.InputRouter import com.droiddeck.launcher.input.InputOutput import com.droiddeck.launcher.input.InputCommand @@ -246,7 +247,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var handCamera: com.droiddeck.launcher.handtracking.HandCamera? = null private var padMotion: com.droiddeck.launcher.input.PadMotion? = null private var resumed by mutableStateOf(false) - private val deckPadListener: () -> Unit = { uiHandler.post { updatePadMotion(); openDeckRing("deck pad changed"); applyUnfoldedControls(); leaveDeckPanel() } } + private val deckPadListener: () -> Unit = { + uiHandler.post { + updatePadMotion() + openDeckRing("deck pad changed") + onScreenControls?.reload() + bottomInputControls?.reload() + applyUnfoldedControls() + leaveDeckPanel() + } + } private fun openDeckRing(why: String) { val deck = SessionState.deckPad @@ -659,6 +669,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL) private var steamDownloadsInBackground by mutableStateOf(false) private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO) + private var oscRearButtons by mutableStateOf(false) + private var oscTrackpads by mutableStateOf(false) private var onScreenButtonsVisible by mutableStateOf(false) private var secondScreenMode by mutableStateOf(SessionState.secondScreenMode) private var secondScreenDisplays by mutableStateOf>(emptyList()) @@ -1703,6 +1715,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde com.droiddeck.launcher.input.FakeInputWriter.setPadType(SessionPrefs.padType(id)) com.droiddeck.launcher.session.InputSysfsComponent.padTypeChanged(SessionPrefs.padType(id)) padType = id + onScreenControls?.reload() + bottomInputControls?.reload() }, backHold = backHold, onBackHold = { on -> @@ -1814,6 +1828,23 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde primaryInputLayout?.let { com.droiddeck.launcher.input.InputLibraries.setAdaptiveSticks(this@SessionActivity, it.id, on) } refreshInputProfile() }, + showFloatingSteamControls = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad && unfoldedPanel == null && + oscMode != SessionPrefs.OSC_NEVER && oscMode != SessionPrefs.OSC_STEAM_QAM && + !steamTouchInUse && OnScreenLayout.supportsFloatingSteamControls(padType, primaryInputLayout), + oscRearButtons = oscRearButtons, + oscTrackpads = oscTrackpads, + onOscRearButtons = { shown -> + SessionPrefs.setOscRearButtons(this@SessionActivity, shown) + oscRearButtons = shown + onScreenControls?.reload() + bottomInputControls?.reload() + }, + onOscTrackpads = { shown -> + SessionPrefs.setOscTrackpads(this@SessionActivity, shown) + oscTrackpads = shown + onScreenControls?.reload() + bottomInputControls?.reload() + }, quickButtons = quickButtons.takeIf { unfoldedPanel != null || oscMode != SessionPrefs.OSC_NEVER && !steamTouchInUse }.orEmpty(), @@ -2555,6 +2586,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode) steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this) oscMode = SessionPrefs.oscMode(this, SessionState.mode == SessionService.MODE_STEAM) + oscRearButtons = SessionPrefs.oscRearButtons(this) + oscTrackpads = SessionPrefs.oscTrackpads(this) backHold = SessionPrefs.backHold(this) backActionsInverted = SessionPrefs.backActionsInverted(this) physicalShortcuts.bindings = PhysicalShortcuts.read(this) diff --git a/app/src/main/java/com/droiddeck/launcher/input/FloatingSteamOverlay.kt b/app/src/main/java/com/droiddeck/launcher/input/FloatingSteamOverlay.kt new file mode 100644 index 0000000000..0dcbf8764f --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/FloatingSteamOverlay.kt @@ -0,0 +1,92 @@ +package com.droiddeck.launcher.input + +import android.graphics.Rect +import kotlin.math.min + +internal class FloatingSteamOverlay(width: Int, height: Int, safe: Rect, density: Float) { + private val w = width.toFloat() + private val h = height.toFloat() + private val left = safe.left / w + private val top = safe.top / h + private val right = 1f - safe.right / w + private val bottom = 1f - safe.bottom / h + private val gap = 3f * density + private val bottomPadding = 14f * density + private val dp = min(density, min(width, height) / 250f) + + fun place(elements: List, lowerShortcuts: Boolean, + rearButtons: Boolean?, trackpads: Boolean?): List { + val visible = elements.filter { element -> + when { + !isStock(element) -> true + element.control in rear -> rearButtons != false + element.control.isTrackpad -> trackpads != false + else -> true + } + } + val lowered = if (lowerShortcuts) lower(visible) else visible + if (rearButtons != true && trackpads != true) return lowered + val placed = lowered.toMutableList() + fun add(control: InputControl, x: Float, y: List, widthDp: Int, heightDp: Int, shape: InputButtonShape) { + if (placed.any { it.id == "legacy:${control.id}" }) return + val element = InputSurfaceElement(control, 0f, 0f, (widthDp * dp / w).coerceAtLeast(.03f), + (heightDp * dp / h).coerceAtLeast(.03f), floating = false, buttonShape = shape, showLabel = !control.isTrackpad) + findSpace(element, x, y, placed)?.let(placed::add) + } + if (rearButtons == true) { + add(InputControl.L4, .045f, listOf(.48f, .38f, .58f), 28, 46, InputButtonShape.PILL) + add(InputControl.L5, .045f, listOf(.62f, .72f, .53f), 28, 46, InputButtonShape.PILL) + add(InputControl.R4, .955f, listOf(.48f, .38f, .58f), 28, 46, InputButtonShape.PILL) + add(InputControl.R5, .955f, listOf(.62f, .72f, .53f), 28, 46, InputButtonShape.PILL) + } + if (trackpads == true) { + val rows = listOf(.45f, .36f, .54f, .27f, .63f) + add(InputControl.LEFT_PAD, .34f, rows, 68, 63, InputButtonShape.ROUNDED) + add(InputControl.RIGHT_PAD, .66f, rows, 68, 63, InputButtonShape.ROUNDED) + } + return placed + } + + private fun lower(elements: List): List { + val row = elements.filter { isStock(it) && it.control in shortcuts } + val occupied = (elements - row.toSet()).toMutableList() + val moved = mutableMapOf() + for (element in row.sortedBy { shortcuts.getValue(it.control) }) { + val y = bottom - bottomPadding / h - element.height / 2f + val position = findSpace(element, shortcuts.getValue(element.control), listOf(y, y - .07f), occupied) + ?: return elements + occupied += position + moved[element.id] = position + } + return elements.map { moved[it.id] ?: it } + } + + private fun findSpace(element: InputSurfaceElement, x: Float, rows: List, + occupied: List): InputSurfaceElement? { + val maxX = right - element.width + val maxY = bottom - element.height + if (maxX < left || maxY < top) return null + for (y in rows) { + for (dx in horizontalOffsets) { + val candidate = element.copy( + x = (x + dx - element.width / 2f).coerceIn(left, maxX), + y = (y - element.height / 2f).coerceIn(top, maxY), + ) + if (occupied.none { overlaps(candidate, it) }) return candidate + } + } + return null + } + + private fun overlaps(a: InputSurfaceElement, b: InputSurfaceElement): Boolean = + a.x < b.x + b.width + gap / w && b.x < a.x + a.width + gap / w && + a.y < b.y + b.height + gap / h && b.y < a.y + a.height + gap / h + + private fun isStock(element: InputSurfaceElement) = element.id == "legacy:${element.control.id}" + + private companion object { + val rear = setOf(InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5) + val shortcuts = mapOf(InputControl.GUIDE to .23f, InputControl.SELECT to .41f, InputControl.START to .59f, InputControl.QAM to .77f) + val horizontalOffsets = listOf(0f, -.035f, .035f, -.07f, .07f, -.105f, .105f) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt b/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt index ee3a6560ae..389dfcfb46 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt @@ -14,6 +14,9 @@ import android.view.View import android.view.WindowInsets import android.widget.FrameLayout import com.droiddeck.launcher.ui.InputSurfaceView +import com.droiddeck.launcher.session.SessionPrefs +import com.droiddeck.launcher.session.SessionService +import com.droiddeck.launcher.session.SessionState class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayout.Dock? = null) : FrameLayout(context) { private val surface = InputSurfaceView(context, pad, inputRole = InputRole.PRIMARY, haptics = dock != null) @@ -77,7 +80,10 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo private fun placed(): List { val key = Placement(layout, viewWidth, viewHeight, Rect(safe), isButtonsOnly) return placements.getOrPut(key) { - OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, isButtonsOnly, dock) + val steam = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad + OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, isButtonsOnly, dock, + rearButtons = SessionPrefs.oscRearButtons(context).takeIf { steam }, + trackpads = SessionPrefs.oscTrackpads(context).takeIf { steam }) } } @@ -88,11 +94,16 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo isQuickHidden -> elements.filter { it.id == "builtin:keyboard" || it.alwaysShown } else -> elements }) - val style = layout?.style ?: InputSurfaceStyle() - surface.updateStyle(style) - quickToggle.tint = style.tint - quickToggle.alpha = style.opacity / 100f quickToggle.visibility = if (isButtonsOnly || isPinnedOnly || layout == null || dock != null) GONE else VISIBLE + refreshAppearance() + } + + private fun refreshAppearance() { + val style = layout?.style ?: InputSurfaceStyle() + val deck = dock == null && OnScreenLayout.usesSteamDeckButtons(context, layout) + surface.updateStyle(style, steamDeckButtons = deck) + quickToggle.tint = style.tint.takeUnless { deck } + quickToggle.alpha = style.opacity / 100f quickToggle.invalidate() } diff --git a/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt b/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt index 9fbb01c7ad..363a6d761c 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt @@ -2,12 +2,20 @@ package com.droiddeck.launcher.input import android.content.Context import android.graphics.Rect +import com.droiddeck.launcher.session.SessionPrefs import kotlin.math.abs import kotlin.math.max import kotlin.math.min import kotlin.math.roundToInt object OnScreenLayout { + internal fun usesSteamDeckButtons(context: Context, layout: SavedInputLayout?) = + layout?.id == InputLibraries.OVERLAY && SessionPrefs.steamController(context) == SessionPrefs.CONTROLLER_DECK + + internal fun supportsFloatingSteamControls(controller: String, layout: SavedInputLayout?) = + layout?.id == InputLibraries.OVERLAY && + (controller == SessionPrefs.CONTROLLER_DECK || controller == SessionPrefs.CONTROLLER_STEAM) + data class Dock(val portrait: Boolean, val grips: Boolean, val left: InputControl = InputControl.LS, val right: InputControl = InputControl.RS) { companion object { fun deck(portrait: Boolean, gamepad: SavedInputLayout?): Dock { @@ -25,7 +33,8 @@ object OnScreenLayout { private const val KEYBOARD_ID = "builtin:keyboard" fun elements(context: Context, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect, - buttonsOnly: Boolean = false, dock: Dock? = null): List { + buttonsOnly: Boolean = false, dock: Dock? = null, rearButtons: Boolean? = null, + trackpads: Boolean? = null): List { val stored = layout?.elements ?: return emptyList() if (width <= 0 || height <= 0) return stored val generator = LegacyGamepadLayout(context, width, height, safe, layout.scale) @@ -39,7 +48,16 @@ object OnScreenLayout { else -> generator.regenerate(gamepad) } val byId = (placed + others).associateBy { it.id } - return stored.mapNotNull { byId[it.id] } + placed.filter { p -> stored.none { it.id == p.id } } + val ordered = stored.mapNotNull { byId[it.id] } + placed.filter { p -> stored.none { it.id == p.id } } + if (dock != null || !supportsFloatingSteamControls(SessionPrefs.steamController(context), layout)) return ordered + if (generated && width >= height && usesSteamDeckButtons(context, layout) && + ControllerPrefs.layout(context, reference.first.toInt(), reference.second.toInt()).isEmpty() && + ControllerPrefs.layout(context, width, height).isEmpty()) { + return SteamDeckOverlayGeometry(width, height, safe, context.resources.displayMetrics, layout.scale) + .place(ordered, rearButtons == true, trackpads == true) + } + return FloatingSteamOverlay(width, height, safe, context.resources.displayMetrics.density) + .place(ordered, lowerShortcuts = generated, rearButtons = rearButtons, trackpads = trackpads) } fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false): List = diff --git a/app/src/main/java/com/droiddeck/launcher/input/SteamDeckOverlayGeometry.kt b/app/src/main/java/com/droiddeck/launcher/input/SteamDeckOverlayGeometry.kt new file mode 100644 index 0000000000..4efd5e1fda --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/SteamDeckOverlayGeometry.kt @@ -0,0 +1,116 @@ +package com.droiddeck.launcher.input + +import android.graphics.Rect +import android.util.DisplayMetrics +import kotlin.math.max +import kotlin.math.min + +internal class SteamDeckOverlayGeometry( + width: Int, height: Int, private val safe: Rect, metrics: DisplayMetrics, scale: Float, +) { + private val w = width.toFloat() + private val h = height.toFloat() + private val density = metrics.density + private val dpi = metrics.ydpi.takeIf { it in metrics.densityDpi * .6f..metrics.densityDpi * 1.6f } + ?: metrics.densityDpi.toFloat() + private val unit = minOf( + min(w / 1600f, h / 900f) * min(1f, 80f / max(h / dpi * 25.4f, 1f)) * scale, + (w - safe.left - safe.right).coerceAtLeast(1f) / 1200f, + (h - safe.top - safe.bottom).coerceAtLeast(1f) / 900f, + ) + + private fun anchor(value: Float, reference: Float, extent: Float, start: Int, end: Int): Float { + val low = start + value * unit + val high = extent - end - (reference - value) * unit + return when { + value < reference / 3f -> low + value > reference * 2f / 3f -> high + else -> (extent / 2f + (value - reference / 2f) * unit).coerceIn(low, max(low, high)) + } + } + + fun place(elements: List, rearButtons: Boolean, trackpads: Boolean): List { + val x = { ref: Float -> anchor(ref, 1600f, w, safe.left, safe.right) } + val y = { ref: Float -> anchor(ref, 900f, h, safe.top, safe.bottom) } + val leftEdge = safe.left + 52f * density + val middle = (w + safe.left - safe.right) / 2f + val keyboard = Box(max(x(136f), leftEdge + 46f * unit), y(848f), 46f).takeIf { elements.any { it.id == KEYBOARD } } + val row = fitRow(listOfNotNull(keyboard, + Box(max(x(370f), leftEdge + 66f * unit), y(852f), 66f, 30f), + Box(middle - 140f * unit, y(850f), 46f, 26f), + Box(middle + 140f * unit, y(850f), 46f, 26f), + Box(x(1230f), y(852f), 66f, 30f)), leftEdge) + val (guide, select, start, qam) = row.takeLast(4) + val positions = mapOf( + InputControl.LT to Box(x(140f), y(66f), 88f, 34f), + InputControl.LB to Box(x(140f), y(148f), 88f, 30f), + InputControl.RT to Box(x(1460f), y(66f), 88f, 34f), + InputControl.RB to Box(x(1460f), y(148f), 88f, 30f), + InputControl.Y to Box(x(1375f), y(345f) - 96f * unit, 58f), + InputControl.X to Box(x(1375f) - 96f * unit, y(345f), 58f), + InputControl.B to Box(x(1375f) + 96f * unit, y(345f), 58f), + InputControl.A to Box(x(1375f), y(345f) + 96f * unit, 58f), + InputControl.UP to Box(x(220f), y(345f) - 102.5f * unit, 55.5f, 47.5f), + InputControl.RIGHT to Box(x(220f) + 102.5f * unit, y(345f), 47.5f, 55.5f), + InputControl.DOWN to Box(x(220f), y(345f) + 102.5f * unit, 55.5f, 47.5f), + InputControl.LEFT to Box(x(220f) - 102.5f * unit, y(345f), 47.5f, 55.5f), + InputControl.LS to Box(x(290f), y(640f), 96f), + InputControl.RS to Box(x(1310f), y(640f), 96f), + InputControl.SELECT to select, + InputControl.START to start, + InputControl.GUIDE to guide, + InputControl.QAM to qam, + ) + val rear = mapOf( + InputControl.L4 to Box(x(30f), y(470f), 30f, 58f), + InputControl.L5 to Box(x(30f), y(590f), 30f, 58f), + InputControl.R4 to Box(x(1570f), y(470f), 30f, 58f), + InputControl.R5 to Box(x(1570f), y(590f), 30f, 58f), + ) + val pads = mapOf( + InputControl.LEFT_PAD to Box(x(470f), y(360f), 88f), + InputControl.RIGHT_PAD to Box(x(1130f), y(360f), 88f), + ) + val optional = rear.filterKeys { rearButtons } + pads.filterKeys { trackpads } + val placed = elements.mapNotNull { element -> + when { + element.id == KEYBOARD -> row.first().place(element) + element.id != "legacy:${element.control.id}" -> element + element.control in rear || element.control in pads -> optional[element.control]?.place(element) + else -> positions[element.control]?.place(element) ?: element + } + } + return placed + optional.mapNotNull { (control, box) -> + if (placed.any { it.id == "legacy:${control.id}" }) null else box.place(InputSurfaceElement(control, + 0f, 0f, 0f, 0f, floating = false, buttonShape = InputButtonShape.PILL, showLabel = !control.isTrackpad)) + } + } + + private fun fitRow(row: List, start: Float): List { + val end = w - safe.right + val gap = ((end - start - row.fold(0f) { sum, box -> sum + box.width }) / (row.size - 1)).coerceIn(0f, 8f * density) + var edge = start - gap + val pushed = row.map { box -> box.at(max(box.cx, edge + gap + box.width / 2f)).also { edge = it.cx + it.width / 2f } } + edge = end + gap + return pushed.asReversed().map { box -> box.at(min(box.cx, edge - gap - box.width / 2f)).also { edge = it.cx - it.width / 2f } }.asReversed() + } + + private inner class Box(val cx: Float, val cy: Float, val hw: Float, val hh: Float = hw) { + val width get() = max(hw * 2f * unit, w * .03f) + + fun at(cx: Float) = Box(cx, cy, hw, hh) + + fun place(element: InputSurfaceElement): InputSurfaceElement { + val height = max(hh * 2f * unit, h * .03f) + return element.copy( + x = (cx - width / 2f).coerceIn(safe.left.toFloat(), max(safe.left.toFloat(), w - safe.right - width)) / w, + y = (cy - height / 2f).coerceIn(safe.top.toFloat(), max(safe.top.toFloat(), h - safe.bottom - height)) / h, + width = width / w, height = height / h, + ).bounded() + } + } + + private companion object { + const val KEYBOARD = "builtin:keyboard" + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index ab258b95ce..38c78cade7 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -673,6 +673,12 @@ object SessionPrefs { prefs(context).edit().putString("osc", mode).apply() } + fun oscRearButtons(context: Context): Boolean = prefs(context).getBoolean("oscRearButtons", false) + fun setOscRearButtons(context: Context, shown: Boolean) { prefs(context).edit().putBoolean("oscRearButtons", shown).apply() } + + fun oscTrackpads(context: Context): Boolean = prefs(context).getBoolean("oscTrackpads", false) + fun setOscTrackpads(context: Context, shown: Boolean) { prefs(context).edit().putBoolean("oscTrackpads", shown).apply() } + fun linuxDriver(context: Context): String = prefs(context).getString("linuxDriver", null) ?: prefs(context).getString("linuxDriver.steam", null) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputLayoutWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputLayoutWidgets.kt index f35d3daa46..e180e6daba 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputLayoutWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputLayoutWidgets.kt @@ -18,6 +18,7 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import com.droiddeck.launcher.R import com.droiddeck.launcher.input.* +import com.droiddeck.launcher.session.SessionPrefs @Composable internal fun InputLayoutRow(layout: SavedInputLayout, role: InputRole, detail: String?, onManage: () -> Unit, onPick: () -> Unit) { @@ -46,8 +47,12 @@ internal class InputLayoutPreviewView(context: Context) : View(context) { private var sourceHeight = 563 fun update(layout: SavedInputLayout, role: InputRole) { sourceHeight = if (role == InputRole.PRIMARY) 563 else 870 - renderer.updateCustomLayout(layout.elements) - renderer.updateStyle(layout.style.copy(opacity = 100)) + val primary = role == InputRole.PRIMARY + val steamOverlay = primary && OnScreenLayout.supportsFloatingSteamControls(SessionPrefs.steamController(context), layout) + val elements = if (steamOverlay) OnScreenLayout.editorElements(context, layout, 1000, sourceHeight) else layout.elements + renderer.updateCustomLayout(elements) + renderer.updateStyle(layout.style.copy(opacity = 100), + steamDeckButtons = primary && OnScreenLayout.usesSteamDeckButtons(context, layout)) renderer.measure(MeasureSpec.makeMeasureSpec(1000, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(sourceHeight, MeasureSpec.EXACTLY)) renderer.layout(0, 0, 1000, sourceHeight) contentDescription = layout.name diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt index 812557f368..87406a4ff5 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt @@ -278,7 +278,9 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe else InputHint(layout.name) InputNavigationRow(stringResource(R.string.input_saved_layouts), stringResource(R.string.input_saved_layouts_hint)) { go(InputPage.LAYOUTS) } if (layout.editable) { - InputColorRow(host, layout.style.tint) { color -> update { it.withLayout(layout.copy(style = layout.style.copy(tint = color))) } } + if (!OnScreenLayout.usesSteamDeckButtons(context, layout)) { + InputColorRow(host, layout.style.tint) { color -> update { it.withLayout(layout.copy(style = layout.style.copy(tint = color))) } } + } SliderRow(stringResource(R.string.ctrl_opacity), null, layout.style.opacity, 1..100, step = 1, format = { "$it%" }) { opacity -> update { it.withLayout(layout.copy(style = layout.style.copy(opacity = opacity))) } } for (button in layout.quickButtons) ToggleRow(host, "quick-${button.name.lowercase()}", stringResource(quickButtonLabel(button)), null, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt index 1e21a245de..353ab699b9 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt @@ -22,9 +22,14 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { var aspect = 1f set(value) { field = value; refreshElements(); invalidate() } var sourceLayout: SavedInputLayout? = null - set(value) { field = value; refreshElements(); invalidate() } + set(value) { + field = value + updatePreviewStyle() + refreshElements() + invalidate() + } var style = InputSurfaceStyle() - set(value) { field = value; preview.updateStyle(value) } + set(value) { field = value; updatePreviewStyle() } var snap = true set(value) { field = value; if (!value) clearGuides() } private var guideX: Float? = null @@ -50,6 +55,10 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { addView(preview, LayoutParams(-1, -1)) } + private fun updatePreviewStyle() { + preview.updateStyle(style, steamDeckButtons = OnScreenLayout.usesSteamDeckButtons(context, sourceLayout)) + } + private fun refreshElements() { visibleElements = sourceLayout?.let { layout -> OnScreenLayout.editorElements(context, layout.copy(elements = elements, aspect = aspect), width, height) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt index 0058224c01..cd3e57435f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt @@ -56,6 +56,10 @@ class InputSurfaceView( private val elementSources = ArrayList() private var customCanvas: ViewGroup? = null private val owners = HashMap() + private var steamDeckButtons = false + private val deckArt by lazy(LazyThreadSafetyMode.NONE) { SteamDeckButtonArt(context) } + private var deckDpad = emptyList() + private val deckDpadBounds = RectF() private var requestedLayout = customLayout init { customLayout = surfaceStyle.shown(customLayout); addView(content, LayoutParams(-1, -1)); renderCustom(pad) } @@ -134,12 +138,16 @@ class InputSurfaceView( } } - fun updateStyle(style: InputSurfaceStyle) { - if (surfaceStyle == style) return + fun updateStyle(style: InputSurfaceStyle, steamDeckButtons: Boolean = false) { + if (surfaceStyle == style && this.steamDeckButtons == steamDeckButtons) return val relayout = surfaceStyle.hidden != style.hidden surfaceStyle = style + this.steamDeckButtons = steamDeckButtons if (relayout) updateCustomLayout(requestedLayout) - customCanvas?.let { canvas -> for (i in 0 until canvas.childCount) styleElement(canvas.getChildAt(i)) } + customCanvas?.let { canvas -> + for (i in 0 until canvas.childCount) styleElement(canvas.getChildAt(i)) + canvas.invalidate() + } } private fun styleElement(view: View) { @@ -173,6 +181,7 @@ class InputSurfaceView( } private fun renderCustom(pad: PadBridge?) { + deckDpad = emptyList() val canvas = object : ViewGroup(context) { override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val layout = customLayout @@ -190,6 +199,20 @@ class InputSurfaceView( val x = (width * e.x).toInt(); val y = (height * e.y).toInt() child.layout(x, y, x + child.measuredWidth, y + child.measuredHeight) } + updateDeckDpad(this) + } + + override fun dispatchDraw(canvas: Canvas) { + if (steamDeckButtons && deckDpad.isNotEmpty()) { + val alpha = (deckDpad.first().alpha * 255f).toInt() + val saved = if (alpha == 255) canvas.save() + else canvas.saveLayerAlpha(deckDpadBounds, alpha) + canvas.translate(deckDpadBounds.left, deckDpadBounds.top) + val held = deckDpad.foldIndexed(0) { i, bits, button -> if (button.highlighted) bits or (1 shl i) else bits } + deckArt.dpad(canvas, deckDpadBounds.width(), deckDpadBounds.height(), held) + canvas.restoreToCount(saved) + } + super.dispatchDraw(canvas) } } canvas.clipChildren = customLayout.none { it.kind == InputElementKind.STICK && (classic(it) || adaptive(it)) } @@ -197,7 +220,7 @@ class InputSurfaceView( val source = pad?.let { InputSurfaceSource(it, inputRole, element).also { s -> elementSources += s } } canvas.addView(when (element.kind) { InputElementKind.STICK -> StickView(context, element, source, element.floating, element.hideWhenIdle && pad != null) - InputElementKind.TRACKPAD -> TrackpadView(context, element.control == InputControl.RIGHT_PAD, source = source) + InputElementKind.TRACKPAD -> TrackpadView(context, element.control == InputControl.RIGHT_PAD, captioned = element.showLabel, source = source) InputElementKind.DPAD -> DirectionPad(context, element, source) else -> HoldButton(context, element, source) }.apply { tag = element; contentDescription = element.name; styleElement(this); source?.onStateChanged = { postInvalidate() } }) @@ -206,6 +229,29 @@ class InputSurfaceView( customCanvas = canvas } + private fun updateDeckDpad(canvas: ViewGroup) { + val buttons = DIRECTIONS.mapNotNull { direction -> + val index = customLayout.indexOfFirst { element -> + element.control == direction && classic(element) && element.buttonShape == InputButtonShape.CIRCLE && + element.name == direction.label && element.icon == 0 && element.image.isEmpty() && + element.showLabel && !element.toggle && element.opacity == 1f + } + canvas.getChildAt(index) as? HoldButton + } + deckDpad = emptyList() + if (buttons.size != DIRECTIONS.size) return + val (up, right, down, left) = buttons + val centerX = (left.left + right.right) / 2f + val centerY = (up.top + down.bottom) / 2f + if (kotlin.math.abs((up.left + up.right) / 2f - centerX) > 2f || + kotlin.math.abs((down.left + down.right) / 2f - centerX) > 2f || + kotlin.math.abs((left.top + left.bottom) / 2f - centerY) > 2f || + kotlin.math.abs((right.top + right.bottom) / 2f - centerY) > 2f || + up.bottom >= down.top || left.right >= right.left) return + deckDpadBounds.set(left.left.toFloat(), up.top.toFloat(), right.right.toFloat(), down.bottom.toFloat()) + deckDpad = buttons + } + override fun onAttachedToWindow() { super.onAttachedToWindow() if (pad != null && elementSources.isEmpty()) { @@ -344,9 +390,20 @@ class InputSurfaceView( } private val imageRect = RectF() + val highlighted get() = if (element.toggle) source?.latched == true else down + override fun onDraw(canvas: Canvas) { - val lit = if (element.toggle) source?.latched == true else down + val lit = highlighted val classic = classic(element) + if (steamDeckButtons && element.image.isEmpty() && element.showLabel) { + if (this in deckDpad) return + if (element.id == "builtin:keyboard" && element.icon == InputButtonIcons.KEYBOARD) { + deckArt.keyboard(canvas, width, height, lit) + return + } + val native = element.id == "legacy:${element.control.id}" && element.name == element.control.label && element.icon == 0 + if (native && deckArt.button(canvas, width, height, element.control, lit)) return + } drawSurface(canvas, lit, element.buttonShape, classic) val cx = width / 2f labelPaint.color = if (classic && tint != null) textColor(lit) else if (lit) ACCENT else TEXT @@ -364,7 +421,7 @@ class InputSurfaceView( if (classic && element.name == element.control.label) { val radius = min(width, height) / 2f val direction = DIRECTIONS.indexOf(element.control) - if (direction >= 0) { drawArrow(canvas, cx, height / 2f, radius * 0.34f, direction, labelPaint); return } + if (direction >= 0) { drawArrow(canvas, cx, height / 2f, radius * .34f, direction, labelPaint); return } val glyph = glyph(element.control) labelPaint.textSize = when { element.buttonShape == InputButtonShape.PILL -> height / 2f * 0.8f @@ -395,6 +452,7 @@ class InputSurfaceView( if (pressed) feedback(this, HapticFeedbackConstants.VIRTUAL_KEY) if (!pressed && cancelled) source?.cancel() else source?.update(if (pressed) 1f else 0f) invalidate() + if (steamDeckButtons && this in deckDpad) customCanvas?.invalidate() } } @@ -421,18 +479,22 @@ class InputSurfaceView( private val glow = Paint(Paint.ANTI_ALIAS_FLAG) override fun onDraw(canvas: Canvas) { + if (!captioned) { + deckArt.trackpad(canvas, width.toFloat(), height.toFloat(), touching || clicked, fingerX, fingerY) + return + } drawSurface(canvas, clicked) val cx = width / 2f val cy = height / 2f guide.strokeWidth = density - val reach = min(width, height) / 2f - 24 * density + val reach = (min(width, height) / 2f - 24 * density).coerceAtLeast(0f) canvas.drawCircle(cx, cy, reach, guide) canvas.drawCircle(cx, cy, reach / 2f, guide) canvas.drawLine(cx - reach, cy, cx + reach, cy, guide) canvas.drawLine(cx, cy - reach, cx, cy + reach, guide) captionPaint.textSize = 12 * density captionPaint.color = if (touching) ACCENT else TEXT_DIM - if (captioned) canvas.drawText((contentDescription?.toString() ?: if (right) context.getString(R.string.deck_right_trackpad) else context.getString(R.string.deck_left_trackpad)).uppercase(), cx, 28 * density, captionPaint) + canvas.drawText((contentDescription?.toString() ?: if (right) context.getString(R.string.deck_right_trackpad) else context.getString(R.string.deck_left_trackpad)).uppercase(), cx, 28 * density, captionPaint) if (touching) { val radius = 56 * density glow.shader = RadialGradient(fingerX, fingerY, radius, ACCENT_GLOW, Color.TRANSPARENT, Shader.TileMode.CLAMP) @@ -534,6 +596,17 @@ class InputSurfaceView( if (hideWhenIdle && !touching) return val cx = if (touching) originX else centreX() val cy = if (touching) originY else height / 2f + if (steamDeckButtons && classic(element)) { + val radius = min(width, height) / 2f - 2f * density + if (radius > 0f) { + deckArt.stick(canvas, cx, cy, radius, knobX, knobY, touching || clicking) + if (element.showLabel) { + labelPaint.color = TEXT + drawDirectionLabels(canvas, source, false, cx, cy, radius * .66f, radius * .34f, labelPaint) + } + return + } + } val color = tint if (classic(element) && color != null) { val radius = min(width, height) / 2f - 0.75f * density diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index 9c244b930f..04f0de55e3 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -343,6 +343,11 @@ class DrawerActions( val unfoldedControls: Boolean? = null, val adaptiveSticks: Boolean? = null, val onAdaptiveSticks: (Boolean) -> Unit = {}, + val showFloatingSteamControls: Boolean = false, + val oscRearButtons: Boolean = false, + val oscTrackpads: Boolean = false, + val onOscRearButtons: (Boolean) -> Unit = {}, + val onOscTrackpads: (Boolean) -> Unit = {}, val quickButtons: Map = emptyMap(), val onQuickButton: (com.droiddeck.launcher.input.InputCommand, Boolean) -> Unit = { _, _ -> }, val onUnfoldedControls: (Boolean) -> Unit = {}, @@ -721,6 +726,12 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont ToggleRow(host, "adaptive-sticks", stringResource(R.string.ctrl_adaptive), null, on, chipModifier = focus.track(page, "adaptive-sticks"), onChange = a.onAdaptiveSticks) } + if (a.showFloatingSteamControls) { + ToggleRow(host, "rear-buttons", stringResource(R.string.osc_rear_buttons), null, a.oscRearButtons, + chipModifier = focus.track(page, "rear-buttons"), onChange = a.onOscRearButtons) + ToggleRow(host, "trackpads", stringResource(R.string.osc_trackpads), null, a.oscTrackpads, + chipModifier = focus.track(page, "trackpads"), onChange = a.onOscTrackpads) + } for ((button, shown) in a.quickButtons) { val key = "quick-${button.name.lowercase()}" ToggleRow(host, key, stringResource(quickButtonLabel(button)), null, shown, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SteamDeckButtonArt.kt b/app/src/main/java/com/droiddeck/launcher/ui/SteamDeckButtonArt.kt new file mode 100644 index 0000000000..80d996f40b --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/SteamDeckButtonArt.kt @@ -0,0 +1,277 @@ +package com.droiddeck.launcher.ui + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.LinearGradient +import android.graphics.Paint +import android.graphics.Path +import android.graphics.RadialGradient +import android.graphics.RectF +import android.graphics.Shader +import android.graphics.Typeface +import com.droiddeck.launcher.input.InputControl +import kotlin.math.atan2 +import kotlin.math.cos +import kotlin.math.max +import kotlin.math.min +import kotlin.math.sin + +internal class SteamDeckButtonArt(context: Context) { + private val density = context.resources.displayMetrics.density + private val body = Paint(Paint.ANTI_ALIAS_FLAG) + private val shine = Paint(Paint.ANTI_ALIAS_FLAG) + private val edge = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE } + private val ink = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER; typeface = Typeface.create("sans-serif-medium", Typeface.BOLD) } + private val line = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeCap = Paint.Cap.ROUND; strokeJoin = Paint.Join.ROUND } + private val fill = Paint(Paint.ANTI_ALIAS_FLAG) + private val path = Path() + private val arm = Path() + private val bar = Path() + private val rect = RectF() + private var shineTop = Float.NaN + private var shineHeight = Float.NaN + + private fun dp(value: Float) = value * density + + private fun glass(canvas: Canvas, shape: Path, pressed: Boolean, tint: Int = BODY) { + shape.computeBounds(rect, false) + body.color = if (pressed) PRESSED else tint + body.setShadowLayer(dp(2.5f), 0f, dp(1.5f), SHADOW) + canvas.drawPath(shape, body) + body.clearShadowLayer() + if (!pressed) { + if (rect.top != shineTop || rect.height() != shineHeight) { + shineTop = rect.top; shineHeight = rect.height() + shine.shader = LinearGradient(0f, rect.top, 0f, rect.top + rect.height() * .55f, SHINE, Color.TRANSPARENT, Shader.TileMode.CLAMP) + } + canvas.drawPath(shape, shine) + } + edge.color = if (pressed) EDGE_PRESSED else EDGE + edge.strokeWidth = dp(1.25f) + canvas.drawPath(shape, edge) + } + + private fun circle(cx: Float, cy: Float, r: Float): Path = path.apply { reset(); addCircle(cx, cy, r, Path.Direction.CW) } + + private fun roundRect(l: Float, t: Float, r: Float, b: Float, radius: Float): Path = path.apply { + reset(); addRoundRect(RectF(l, t, r, b), radius, radius, Path.Direction.CW) + } + + private fun corners(l: Float, t: Float, r: Float, b: Float, tl: Float, tr: Float, br: Float, bl: Float): Path = path.apply { + reset(); addRoundRect(RectF(l, t, r, b), floatArrayOf(tl, tl, tr, tr, br, br, bl, bl), Path.Direction.CW) + } + + private fun text(canvas: Canvas, value: String, cx: Float, cy: Float, size: Float, color: Int, maxWidth: Float = Float.MAX_VALUE) { + ink.textSize = size + val measured = ink.measureText(value) + if (measured > maxWidth) ink.textSize = size * maxWidth / measured + ink.color = color + canvas.drawText(value, cx, cy - (ink.ascent() + ink.descent()) / 2f, ink) + } + + fun button(canvas: Canvas, width: Int, height: Int, control: InputControl, pressed: Boolean): Boolean { + val w = width.toFloat() + val h = height.toFloat() + if (min(w, h) <= dp(4f)) return false + when (control) { + InputControl.A, InputControl.B, InputControl.X, InputControl.Y -> { + val radius = min(w, h) / 2f - dp(2f) + glass(canvas, circle(w / 2f, h / 2f, radius), pressed) + text(canvas, control.label, w / 2f, h / 2f, radius * .95f, if (pressed) ON_ACCENT else INK) + } + InputControl.LB, InputControl.RB, InputControl.LT, InputControl.RT -> shoulder(canvas, w, h, control, pressed) + InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5 -> grip(canvas, w, h, control.label, pressed) + InputControl.SELECT -> system(canvas, w, h, Shape.CHIP, Icon.VIEW, pressed) + InputControl.START -> system(canvas, w, h, Shape.CHIP, Icon.MENU, pressed) + InputControl.GUIDE -> system(canvas, w, h, Shape.PILL, Icon.STEAM, pressed) + InputControl.QAM -> system(canvas, w, h, Shape.PILL, Icon.QAM, pressed) + else -> return false + } + return true + } + + fun keyboard(canvas: Canvas, w: Int, h: Int, pressed: Boolean) = + system(canvas, w.toFloat(), h.toFloat(), Shape.ROUND, Icon.KEYBOARD, pressed) + + private fun shoulder(canvas: Canvas, w: Float, h: Float, control: InputControl, pressed: Boolean) { + val inset = dp(2f) + val l = inset; val t = inset; val r = w - inset; val b = h - inset + val trigger = control == InputControl.LT || control == InputControl.RT + val big = (b - t) * if (trigger) .9f else .62f + val small = dp(5f) + val left = control == InputControl.LT || control == InputControl.LB + glass(canvas, if (left) corners(l, t, r, b, big, small, small, small) else corners(l, t, r, b, small, big, small, small), pressed) + text(canvas, when (control) { + InputControl.LB -> "L1" + InputControl.RB -> "R1" + InputControl.LT -> "L2" + else -> "R2" + }, w / 2f, h / 2f, (b - t) * .46f, if (pressed) ON_ACCENT else INK, (r - l) * .8f) + } + + /** A back grip: a capsule along the long side of its box, at most 2.2 times as long as it is thick. */ + private fun grip(canvas: Canvas, w: Float, h: Float, label: String, pressed: Boolean) { + val inset = dp(3f) + val thick = (min(w, h) - 2 * inset).coerceAtLeast(1f) + val long = (max(w, h) - 2 * inset).coerceAtMost(thick * 2.2f) + val bw = if (w >= h) long else thick; val bh = if (w >= h) thick else long + val cx = w / 2f; val cy = h / 2f + glass(canvas, roundRect(cx - bw / 2, cy - bh / 2, cx + bw / 2, cy + bh / 2, thick / 2), pressed) + text(canvas, label, cx, cy, thick * .42f, if (pressed) ON_ACCENT else INK_SOFT) + } + + private enum class Shape { ROUND, PILL, CHIP } + private enum class Icon { VIEW, MENU, QAM, KEYBOARD, STEAM } + + private fun system(canvas: Canvas, w: Float, h: Float, shape: Shape, icon: Icon, pressed: Boolean, ink: Int = INK) { + val cx = w / 2f; val cy = h / 2f + val size = when (shape) { + Shape.ROUND -> { val r = min(w, h) / 2f * VISUAL; glass(canvas, circle(cx, cy, r), pressed); r * 1.2f } + Shape.PILL -> { val vh = min(h * VISUAL, w * VISUAL / 2.3f); val vw = vh * 2.3f + glass(canvas, roundRect(cx - vw / 2, cy - vh / 2, cx + vw / 2, cy + vh / 2, vh / 2), pressed); vh * 1.1f } + Shape.CHIP -> { val vh = min(h * VISUAL, w * VISUAL / 1.9f); val vw = vh * 1.9f + glass(canvas, roundRect(cx - vw / 2, cy - vh / 2, cx + vw / 2, cy + vh / 2, vh * .32f), pressed); vh * 1.05f } + } + icon(canvas, cx, cy, size, icon, if (pressed) ON_ACCENT else ink) + } + + private fun icon(canvas: Canvas, cx: Float, cy: Float, size: Float, icon: Icon, color: Int) { + val u = size / 28f + line.color = color; line.strokeWidth = 3.2f * u + fill.color = color; fill.shader = null + when (icon) { + Icon.VIEW -> { + canvas.drawRoundRect(RectF(cx - 12 * u, cy - 9 * u, cx + 3 * u, cy + 3 * u), 3 * u, 3 * u, line) + fill.color = Color.argb(230, 14, 16, 20) + canvas.drawRoundRect(RectF(cx - 4 * u, cy - 3 * u, cx + 11 * u, cy + 9 * u), 3 * u, 3 * u, fill) + canvas.drawRoundRect(RectF(cx - 4 * u, cy - 3 * u, cx + 11 * u, cy + 9 * u), 3 * u, 3 * u, line) + } + Icon.MENU -> for (dy in intArrayOf(-7, 0, 7)) canvas.drawLine(cx - 11 * u, cy + dy * u, cx + 11 * u, cy + dy * u, line) + Icon.QAM -> for (dx in intArrayOf(-10, 0, 10)) canvas.drawCircle(cx + dx * u, cy, 3.4f * u, fill) + Icon.KEYBOARD -> { + canvas.drawRoundRect(RectF(cx - 16 * u, cy - 11 * u, cx + 16 * u, cy + 11 * u), 4.5f * u, 4.5f * u, line) + for (row in 0..1) for (col in 0..3) canvas.drawCircle(cx + (-9 + col * 6) * u, cy + (-4 + row * 5) * u, 1.7f * u, fill) + line.strokeWidth = 2.6f * u; canvas.drawLine(cx - 6 * u, cy + 6 * u, cx + 6 * u, cy + 6 * u, line) + } + Icon.STEAM -> { + ink.letterSpacing = .12f + text(canvas, "STEAM", cx, cy, 14 * u, color, size * 1.9f) + ink.letterSpacing = 0f + } + } + } + + private fun chevron(canvas: Canvas, ax: Float, ay: Float, dx: Float, dy: Float, k: Float, color: Int, width: Float) { + val px = -dy; val py = dx + line.color = color; line.strokeWidth = width + canvas.drawPath(path.apply { + reset(); moveTo(ax - dx * k * .5f + px * k, ay - dy * k * .5f + py * k); lineTo(ax + dx * k * .6f, ay + dy * k * .6f) + lineTo(ax - dx * k * .5f - px * k, ay - dy * k * .5f - py * k) + }, line) + } + + private fun cross(target: Path, cx: Float, cy: Float, s: Float, h: Float, rc: Float) = target.apply { + reset() + addRoundRect(RectF(cx - h, cy - s, cx + h, cy + s), rc, rc, Path.Direction.CW) + bar.reset() + bar.addRoundRect(RectF(cx - s, cy - h, cx + s, cy + h), rc, rc, Path.Direction.CW) + op(bar, Path.Op.UNION) + } + + fun dpad(canvas: Canvas, w: Float, h: Float, held: Int) { + val cx = w / 2f + val cy = h / 2f + val arms = min(w, h) / 2f - dp(3f) + if (arms <= 0f) return + val half = arms * .37f + glass(canvas, cross(arm, cx, cy, arms, half, half * .43f), false) + for (i in 0..3) { + val dx = when (i) { 1 -> 1f; 3 -> -1f; else -> 0f } + val dy = when (i) { 0 -> -1f; 2 -> 1f; else -> 0f } + val on = held and (1 shl i) != 0 + if (on && half > dp(2f)) { + fill.shader = null + fill.color = PRESSED + val near = half + dp(1f) + val far = arms - dp(2f) + val side = half - dp(2f) + rect.set(if (dx == 0f) cx - side else if (dx > 0) cx + near else cx - far, + if (dy == 0f) cy - side else if (dy > 0) cy + near else cy - far, + if (dx == 0f) cx + side else if (dx > 0) cx + far else cx - near, + if (dy == 0f) cy + side else if (dy > 0) cy + far else cy - near) + canvas.drawRoundRect(rect, half * .4f, half * .4f, fill) + } + val m = (arms + half) / 2f + chevron(canvas, cx + dx * m, cy + dy * m, dx, dy, half * .32f, if (on) ON_ACCENT else INK, half * .17f) + } + fill.shader = null + fill.color = Color.argb(18, 255, 255, 255) + canvas.drawCircle(cx, cy, half * .36f, fill) + } + + fun stick(canvas: Canvas, cx: Float, cy: Float, radius: Float, kx: Float, ky: Float, active: Boolean) { + fill.alpha = 255 + fill.shader = RadialGradient(cx, cy, radius, WELL_IN, WELL_OUT, Shader.TileMode.CLAMP) + fill.setShadowLayer(dp(2.5f), 0f, dp(1.5f), SHADOW) + canvas.drawCircle(cx, cy, radius, fill) + fill.clearShadowLayer(); fill.shader = null + edge.color = Color.argb(61, 255, 255, 255); edge.strokeWidth = dp(1.25f) + canvas.drawCircle(cx, cy, radius, edge) + line.color = Color.argb(71, 255, 255, 255); line.strokeWidth = dp(1.4f) + for (i in 0 until 8) { + val a = i * Math.PI / 4 + val c = cos(a).toFloat(); val n = sin(a).toFloat() + canvas.drawLine(cx + c * (radius - dp(7f)), cy + n * (radius - dp(7f)), cx + c * (radius - dp(3.5f)), cy + n * (radius - dp(3.5f)), line) + } + if (active && (kx != 0f || ky != 0f)) { + val angle = Math.toDegrees(atan2(ky, kx).toDouble()).toFloat() + line.color = ACCENT; line.strokeWidth = dp(3f) + val r = radius - dp(2f) + canvas.drawArc(RectF(cx - r, cy - r, cx + r, cy + r), angle - 35f, 70f, false, line) + } + val k = radius * .46f + val x = cx + kx; val y = cy + ky + line.color = if (active) ACCENT else Color.argb(140, 226, 232, 240) + line.strokeWidth = dp(2.8f) + canvas.drawCircle(x, y, k * 1.14f, line) + glass(canvas, circle(x, y, k), false) + edge.color = Color.argb(36, 255, 255, 255) + edge.strokeWidth = dp(1f) + canvas.drawCircle(x, y, k * .66f, edge) + } + + fun trackpad(canvas: Canvas, w: Float, h: Float, touching: Boolean, fx: Float, fy: Float) { + if (w <= 0f || h <= 0f) return + val inset = dp(1.5f) + val radius = min(w, h) * .14f + fill.shader = null; fill.color = Color.argb(51, 14, 16, 20) + rect.set(inset, inset, w - inset, h - inset) + canvas.drawRoundRect(rect, radius, radius, fill) + edge.color = if (touching) Color.argb(191, 0x1A, 0x9F, 0xFF) else Color.argb(51, 255, 255, 255) + edge.strokeWidth = dp(if (touching) 1.5f else 1f) + canvas.drawRoundRect(rect, radius, radius, edge) + if (!touching) return + val glow = min(w, h) * .3f + fill.shader = RadialGradient(fx, fy, glow, GLOW, Color.TRANSPARENT, Shader.TileMode.CLAMP) + canvas.drawCircle(fx, fy, glow, fill); fill.shader = null + fill.color = ACCENT; canvas.drawCircle(fx, fy, dp(5f), fill) + } + + companion object { + private const val VISUAL = .72f + private val ACCENT = Color.rgb(0x1A, 0x9F, 0xFF) + private val ON_ACCENT = Color.rgb(0x03, 0x11, 0x1F) + val INK = Color.rgb(0xF4, 0xF7, 0xFB) + private val INK_SOFT = Color.argb(209, 0xF4, 0xF7, 0xFB) + private val BODY = Color.argb(133, 14, 16, 20) + private val PRESSED = Color.argb(235, 0x1A, 0x9F, 0xFF) + private val SHINE = Color.argb(43, 255, 255, 255) + private val EDGE = Color.argb(77, 255, 255, 255) + private val EDGE_PRESSED = Color.argb(140, 255, 255, 255) + private val SHADOW = Color.argb(97, 0, 0, 0) + private val WELL_IN = Color.argb(140, 5, 7, 10) + private val WELL_OUT = Color.argb(71, 14, 16, 20) + private val GLOW = Color.argb(140, 0x1A, 0x9F, 0xFF) + } +} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 8d3d519ea6..7cdceeb723 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -323,6 +323,8 @@ Side button On-screen controls Steam + QAM + Rear buttons + Trackpads Auto shows the controls when no controller is connected. Steam touch (beta) Steam\'s touch controls start with the next Steam session diff --git a/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt index cfe027586a..d1a7520ef2 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt @@ -2,6 +2,7 @@ package com.droiddeck.launcher.input import android.content.Context import android.graphics.Rect +import com.droiddeck.launcher.session.SessionPrefs import org.json.JSONObject import org.junit.Assert.* import org.junit.Before @@ -26,6 +27,16 @@ class OnScreenLayoutTest { private fun px(e: InputSurfaceElement, w: Int, h: Int) = floatArrayOf(e.x * w, e.y * h, e.width * w, e.height * h) + private val shortcuts = setOf(InputControl.SELECT, InputControl.START, InputControl.GUIDE, InputControl.QAM) + + private fun assertOnlyShortcutPositionsChanged(before: List, after: List) { + assertEquals(before.map { it.id }, after.map { it.id }) + for ((original, placed) in before.zip(after)) { + val expected = if (original.control in shortcuts) original.copy(x = placed.x, y = placed.y) else original + assertEquals(expected, placed) + } + } + private fun assertSquare(e: InputSurfaceElement, w: Int, h: Int) = assertEquals(e.width * w, e.height * h, 1.5f) private fun assertInside(elements: List, w: Int, h: Int, safe: Rect = Rect()) { @@ -38,12 +49,47 @@ class OnScreenLayoutTest { } } + @Test fun theFloatingSteamPadOffersIndependentVisibilityAndLowersOnlyTheDefaultShortcuts() { + val w = 1280 + val h = 960 + val safe = Rect(24, 8, 12, 16) + val layout = gamepad() + val original = LegacyGamepadLayout(context, w, h, safe).regenerate(layout.elements) + val extraRear = setOf(InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5) + val extraPads = setOf(InputControl.LEFT_PAD, InputControl.RIGHT_PAD) + fun placed(rear: Boolean, pads: Boolean) = + OnScreenLayout.elements(context, layout, w, h, safe, rearButtons = rear, trackpads = pads) + for (type in listOf(SessionPrefs.CONTROLLER_DECK, SessionPrefs.CONTROLLER_STEAM)) { + SessionPrefs.setSteamController(context, type) + val base = placed(false, false) + for (control in listOf(InputControl.SELECT, InputControl.START)) { + val old = original.single { it.control == control } + val moved = base.single { it.control == control } + assertTrue(control.id, moved.y > old.y) + } + val standard = base.map { it.control }.toSet() + assertEquals(extraRear, placed(true, false).map { it.control }.toSet() - standard) + assertEquals(extraPads, placed(false, true).map { it.control }.toSet() - standard) + val both = placed(true, true) + assertEquals(extraRear + extraPads, both.map { it.control }.toSet() - standard) + assertInside(both, w, h, safe) + assertEquals(base, both.filter { it.control in standard }) + } + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_XBOX360) + assertEquals(original, placed(true, true)) + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK) + val edited = layout.copy(elements = layout.elements.map { e -> if (e.control == InputControl.START) e.copy(y = .3f) else e }) + val fitted = OnScreenLayout.elements(context, edited, w, h, safe) + assertTrue(fitted.single { it.control == InputControl.START }.y < .5f) + } + @Test fun theBuiltInGamepadIsRegeneratedForEverySizeWithoutStretching() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_STEAM) val layout = gamepad() for ((w, h) in listOf(1200 to 540, 540 to 1200, 900 to 850)) { val placed = OnScreenLayout.elements(context, layout, w, h, Rect()) assertEquals(layout.elements.map { it.id }, placed.map { it.id }) - assertEquals(LegacyGamepadLayout(context, w, h).regenerate(layout.elements), placed) + assertOnlyShortcutPositionsChanged(LegacyGamepadLayout(context, w, h).regenerate(layout.elements), placed) for (id in listOf("legacy:a", "legacy:up", "legacy:guide")) assertSquare(placed.first { it.id == id }, w, h) assertInside(placed, w, h) } @@ -51,13 +97,15 @@ class OnScreenLayoutTest { @Test @Config(qualifiers = "w745dp-h343dp-land-420dpi") fun aBuiltInGamepadSavedAtTheDisplaySizeRegeneratesForTheMeasuredSurface() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_STEAM) val saved = gamepad().copy(elements = LegacyGamepadLayout(context, 2608, 1200).elements(), aspect = 2608f / 1200) val placed = OnScreenLayout.elements(context, saved, 2048, 1200, Rect()) - assertEquals(LegacyGamepadLayout(context, 2048, 1200).regenerate(saved.elements), placed) + assertOnlyShortcutPositionsChanged(LegacyGamepadLayout(context, 2048, 1200).regenerate(saved.elements), placed) } @Test @Config(qualifiers = "w745dp-h343dp-land-420dpi") fun previouslyGeneratedEdgeSticksRegenerateWithoutOverridingCustomGeometry() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_STEAM) val w = 2608 val h = 1200 ControllerPrefs.setLayout(context, w, h, mapOf("ls" to (0f to .5f), "rs" to (1f to .5f))) @@ -66,7 +114,7 @@ class OnScreenLayoutTest { val current = generator.elements() assertTrue(old.filter { it.control == InputControl.LS || it.control == InputControl.RS }.zip(current.filter { it.control == InputControl.LS || it.control == InputControl.RS }).any { (a, b) -> kotlin.math.abs(a.width - b.width) > .01f }) val saved = gamepad().copy(elements = old, aspect = w.toFloat() / h) - assertEquals(LegacyGamepadLayout(context, 2048, h).regenerate(old), OnScreenLayout.elements(context, saved, 2048, h, Rect())) + assertOnlyShortcutPositionsChanged(LegacyGamepadLayout(context, 2048, h).regenerate(old), OnScreenLayout.elements(context, saved, 2048, h, Rect())) val custom = saved.copy(elements = old.map { if (it.id == "legacy:a") it.copy(x = .4f) else it }) assertEquals(OnScreenLayout.fit(custom.elements, custom.aspect, 1f, 2048, h, Rect()), OnScreenLayout.elements(context, custom, 2048, h, Rect())) } @@ -122,11 +170,12 @@ class OnScreenLayoutTest { val original = gamepad() val moved = original.copy(elements = original.elements.map { if (it.id == "legacy:a") it.copy(x = .3f) else it }, aspect = w.toFloat() / h) val reset = LegacyGamepadLayout(context, w, h).regenerate(moved.elements) - assertEquals(LegacyGamepadLayout(context, w, h).regenerate(original.elements), OnScreenLayout.elements(context, moved.copy(elements = reset), w, h, Rect())) + assertEquals(OnScreenLayout.elements(context, original, w, h, Rect()), OnScreenLayout.elements(context, moved.copy(elements = reset), w, h, Rect())) } } @Test fun regenerationKeepsTheUsersButtonStylesAndRemovedButtons() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_STEAM) val layout = gamepad().let { g -> g.copy(elements = g.elements.filterNot { it.id == "legacy:y" }.map { if (it.id == "legacy:a") it.copy(opacity = .4f, icon = 0, name = "Jump") else it }) } val placed = OnScreenLayout.elements(context, layout, 2000, 1000, Rect()) assertNull(placed.firstOrNull { it.id == "legacy:y" }) @@ -136,6 +185,45 @@ class OnScreenLayoutTest { assertEquals(LegacyGamepadLayout(context, 2000, 1000).elements().first { it.id == "legacy:a" }.x, a.x, .0001f) } + @Test @Config(qualifiers = "w800dp-h450dp-land-320dpi") + fun theDefaultDeckUsesTheRedesignReferenceGeometry() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK) + val placed = OnScreenLayout.elements(context, gamepad(), 1600, 900, Rect(), rearButtons = true, trackpads = true) + fun center(control: InputControl): Pair = placed.single { it.id == "legacy:${control.id}" } + .let { (it.x + it.width / 2f) * 1600f to (it.y + it.height / 2f) * 900f } + fun assertCenter(control: InputControl, x: Float, y: Float) { + val (cx, cy) = center(control) + assertEquals(control.id, x, cx, .01f) + assertEquals(control.id, y, cy, .01f) + } + assertCenter(InputControl.LT, 140f, 66f) + assertCenter(InputControl.LB, 140f, 148f) + assertCenter(InputControl.UP, 220f, 242.5f) + assertCenter(InputControl.RIGHT, 322.5f, 345f) + assertCenter(InputControl.LS, 290f, 640f) + assertCenter(InputControl.RS, 1310f, 640f) + assertCenter(InputControl.LEFT_PAD, 470f, 360f) + assertCenter(InputControl.RIGHT_PAD, 1130f, 360f) + assertCenter(InputControl.SELECT, 660f, 850f) + assertCenter(InputControl.START, 940f, 850f) + assertInside(placed, 1600, 900) + } + + @Test @Config(qualifiers = "w800dp-h450dp-land-xxxhdpi") + fun theDeckShortcutRowStaysApartOnSmallDenseSurfaces() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK) + val row = listOf("builtin:keyboard", "legacy:guide", "legacy:select", "legacy:start", "legacy:qam") + for ((size, safe) in listOf(800 to 450 to Rect(), 600 to 450 to Rect(), 600 to 450 to Rect(0, 0, 120, 0), + 600 to 450 to Rect(120, 0, 0, 0), 1600 to 900 to Rect())) { + val (w, h) = size + val placed = OnScreenLayout.elements(context, gamepad(), w, h, safe) + for ((left, right) in row.map { id -> placed.single { it.id == id } }.zipWithNext()) { + assertTrue("${left.id} reaches ${right.id} at ${w}x$h $safe", (left.x + left.width) * w <= right.x * w + .5f) + } + assertInside(placed, w, h, safe) + } + } + @Test fun anEditedLayoutKeepsItsAspectAndCornersWhenTheScreenRotates() { val corner = InputSurfaceElement(InputControl.A, .85f, .7f, .1f, .2f) val left = InputSurfaceElement(InputControl.LS, .05f, .5f, .2f, .4f) diff --git a/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceTouchTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceTouchTest.kt index 3df8d65e0f..fe00507fec 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceTouchTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceTouchTest.kt @@ -77,6 +77,23 @@ class InputSurfaceTouchTest { assertFalse(state().isDown(PadState.A)) } + @Test fun steamDeckStylingKeepsTheHeldButtonAndItsHitArea() { + val button = a.copy(buttonShape = InputButtonShape.CIRCLE) + show(button) + val surface = view.inputSurface + val shown = surface.shownElements + + touch(MotionEvent.ACTION_DOWN, 1 to (800f to 240f)) + assertTrue(state().isDown(PadState.A)) + surface.updateStyle(InputSurfaceStyle(), steamDeckButtons = true) + assertEquals(shown, surface.shownElements) + assertTrue(surface.takesTouchAt(800f, 240f)) + assertTrue(state().isDown(PadState.A)) + + touch(MotionEvent.ACTION_UP, 1 to (800f to 240f)) + assertFalse(state().isDown(PadState.A)) + } + @Test fun aStickKeepsItsFingerWhenItCrossesAButton() { touch(MotionEvent.ACTION_DOWN, 1 to (200f to 300f)) touch(MotionEvent.ACTION_MOVE, 1 to (800f to 240f)) From c0cc3b46a077d1cc548b837a61b31b072b2ef93d Mon Sep 17 00:00:00 2001 From: FX192 <120828496+FX192@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:08:27 +0300 Subject: [PATCH 005/141] feat(session): add an Avoid notch toggle to the Steam display options Keeps the Steam session picture, controls and overlays inside the display cutout's safe area so the notch no longer covers part of the image, in landscape or portrait. Off by default. --- .../droiddeck/launcher/FrontEndActivity.kt | 4 +++ .../com/droiddeck/launcher/SessionActivity.kt | 22 ++++++++++++ .../droiddeck/launcher/core/DeviceReport.kt | 1 + .../launcher/session/SessionPrefs.kt | 6 ++++ .../launcher/session/SettingsReset.kt | 2 +- .../launcher/ui/ModeSettingsDialog.kt | 6 ++++ app/src/main/res/values-ar/strings.xml | 2 ++ app/src/main/res/values-b+es+419/strings.xml | 2 ++ app/src/main/res/values-bg/strings.xml | 2 ++ app/src/main/res/values-cs/strings.xml | 2 ++ app/src/main/res/values-da/strings.xml | 2 ++ app/src/main/res/values-de/strings.xml | 2 ++ app/src/main/res/values-el/strings.xml | 2 ++ app/src/main/res/values-es/strings.xml | 2 ++ app/src/main/res/values-fi/strings.xml | 2 ++ app/src/main/res/values-fr/strings.xml | 2 ++ app/src/main/res/values-hi/strings.xml | 2 ++ app/src/main/res/values-hu/strings.xml | 2 ++ app/src/main/res/values-in/strings.xml | 2 ++ app/src/main/res/values-it/strings.xml | 2 ++ app/src/main/res/values-ja/strings.xml | 2 ++ app/src/main/res/values-ko/strings.xml | 2 ++ app/src/main/res/values-ms/strings.xml | 2 ++ app/src/main/res/values-nb/strings.xml | 2 ++ app/src/main/res/values-nl/strings.xml | 2 ++ app/src/main/res/values-pl/strings.xml | 2 ++ app/src/main/res/values-pt-rPT/strings.xml | 2 ++ app/src/main/res/values-pt/strings.xml | 2 ++ app/src/main/res/values-ro/strings.xml | 2 ++ app/src/main/res/values-ru/strings.xml | 2 ++ app/src/main/res/values-sv/strings.xml | 2 ++ app/src/main/res/values-th/strings.xml | 2 ++ app/src/main/res/values-tr/strings.xml | 2 ++ app/src/main/res/values-uk/strings.xml | 2 ++ app/src/main/res/values-vi/strings.xml | 2 ++ app/src/main/res/values-zh-rCN/strings.xml | 2 ++ app/src/main/res/values-zh-rHK/strings.xml | 2 ++ app/src/main/res/values-zh-rTW/strings.xml | 2 ++ app/src/main/res/values/strings.xml | 2 ++ .../launcher/session/AvoidNotchPrefsTest.kt | 36 +++++++++++++++++++ 40 files changed, 142 insertions(+), 1 deletion(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/session/AvoidNotchPrefsTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index 0cb8e939b2..ca5e23cefe 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -194,6 +194,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private var picturePosition by mutableStateOf("center") private var integerScaling by mutableStateOf(false) private var stretch16x9 by mutableStateOf(false) + private var avoidNotch by mutableStateOf(false) private var orientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) private var launcherOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER) private var homePage by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM) @@ -2607,6 +2608,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet picturePosition = if (mode == SessionService.MODE_STEAM) picturePosition else null, integerScaling = if (mode == SessionService.MODE_STEAM) integerScaling else null, stretch16x9 = if (mode == SessionService.MODE_STEAM) stretch16x9 else null, + avoidNotch = if (mode == SessionService.MODE_STEAM) avoidNotch else null, mic = if (mode == SessionService.MODE_STEAM) mic else null, gameStorage = if (mode == SessionService.MODE_STEAM) gameStorage else null, storageOptions = storageOptions, @@ -2675,6 +2677,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet onPicturePosition = { value -> SessionPrefs.setPicturePosition(this, value); picturePosition = value }, onIntegerScaling = { on -> SessionPrefs.setIntegerScaling(this, on); integerScaling = on }, onStretch16x9 = { on -> SessionPrefs.setStretch16x9(this, on); stretch16x9 = on }, + onAvoidNotch = { on -> SessionPrefs.setAvoidNotch(this, on); avoidNotch = on }, onMic = { on -> SessionPrefs.setMicEnabled(this, on) mic = on @@ -3009,6 +3012,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet picturePosition = SessionPrefs.picturePosition(this) integerScaling = SessionPrefs.integerScaling(this) stretch16x9 = SessionPrefs.stretch16x9(this) + avoidNotch = SessionPrefs.avoidNotch(this) mic = SessionPrefs.micEnabled(this) refreshWifiDiscovery() gameStorage = SessionPrefs.gameStorage(this) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index fb788f2ef1..d3c58bd978 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -177,6 +177,21 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var quickButtons by mutableStateOf>(emptyMap()) private var picturePosition by mutableStateOf("center") private var integerScaling by mutableStateOf(false) + private var avoidNotch = false + + private fun applyNotchInset(insets: android.view.WindowInsets? = window.decorView.rootWindowInsets) { + if (!::sessionRoot.isInitialized) return + val cutout = if (avoidNotch && Build.VERSION.SDK_INT >= 28 && SessionState.mode == SessionService.MODE_STEAM && + !pipUi && !isInPictureInPictureMode && glassesScreen == null && bottomGame == null && !cardboard.enabled) + insets?.displayCutout else null + val left = cutout?.safeInsetLeft ?: 0 + val top = cutout?.safeInsetTop ?: 0 + val right = cutout?.safeInsetRight ?: 0 + val bottom = cutout?.safeInsetBottom ?: 0 + if (sessionRoot.paddingLeft == left && sessionRoot.paddingTop == top && + sessionRoot.paddingRight == right && sessionRoot.paddingBottom == bottom) return + sessionRoot.setPadding(left, top, right, bottom) + } private fun applyGameAlignment() { if (!CompositorHost.isStarted) return @@ -863,6 +878,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde else super.onResolvePointerIcon(event, pointerIndex) } sessionRoot = root + window.decorView.setOnApplyWindowInsetsListener { view, insets -> + applyNotchInset(insets) + view.onApplyWindowInsets(insets) + } surfaceView = SurfaceView(this) surfaceView.holder.addCallback(this) root.addView(surfaceView) @@ -2538,6 +2557,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde unfoldedControlsWithController = SessionPrefs.unfoldedControlsWithController(this) picturePosition = SessionPrefs.picturePosition(this) integerScaling = SessionPrefs.integerScaling(this) + avoidNotch = SessionPrefs.avoidNotch(this) + applyNotchInset() hudOn = SessionPrefs.hudEnabled(this) gpuClockPin = gpuClockHeld() blackFrameInsertion = SessionPrefs.blackFrameInsertion(this) @@ -2942,6 +2963,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } cancelTouchGestures() applyFollowOrientation(newConfig) + applyNotchInset() applyUnfoldedControls() resizeOutputForWindow(surfaceW, surfaceH) } diff --git a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt index fe835b10c8..dbc78c6a2d 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt @@ -289,6 +289,7 @@ object DeviceReport { k("Guest host name", SessionPrefs.guestHostname(context)) k("DirectAudio for games", SessionPrefs.directAudio(context)) k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context)) + k("Avoid notch", SessionPrefs.avoidNotch(context)) k("Return to launcher after a game", SessionPrefs.returnAfterGame(context)) k("Microphone", SessionPrefs.micEnabled(context)) k("On-screen controls", SessionPrefs.oscMode(context)) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 38c78cade7..09c0b781ec 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -835,6 +835,12 @@ object SessionPrefs { prefs(context).edit().putBoolean("stretch16x9", on).apply() } + fun avoidNotch(context: Context): Boolean = prefs(context).getBoolean("avoidNotch", false) + + fun setAvoidNotch(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("avoidNotch", on).apply() + } + fun directAudio(context: Context): Boolean = prefs(context).getBoolean("directAudio", true) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt index f85318b595..d2963582e6 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt @@ -18,7 +18,7 @@ object SettingsReset { "storesInstallLanguage", "hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController", "gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController", - "stretch16x9", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys", + "stretch16x9", "avoidNotch", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys", "gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop", "tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores", "directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus", diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt index f871406fce..73580d8676 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -87,6 +87,7 @@ class ModeSettings( val picturePosition: String? = null, val integerScaling: Boolean? = null, val stretch16x9: Boolean? = null, + val avoidNotch: Boolean? = null, val steamClientArch: String? = null, val returnAfterGame: Boolean? = null, val shaderPrecache: Boolean? = null, @@ -145,6 +146,7 @@ class ModeSettingsActions( val onPicturePosition: (String) -> Unit = {}, val onIntegerScaling: (Boolean) -> Unit = {}, val onStretch16x9: (Boolean) -> Unit = {}, + val onAvoidNotch: (Boolean) -> Unit = {}, val onSteamRepair: () -> Unit = {}, val onSteamClientArch: (String) -> Unit = {}, val onMangoapp: (Boolean) -> Unit = {}, @@ -253,6 +255,10 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: listOf(false to stringResource(R.string.display_preserve), true to stringResource(R.string.display_stretch)), s.stretch16x9 && canStretch, enabled = canStretch, onPick = a.onStretch16x9) } + s.avoidNotch?.let { enabled -> + ToggleRow(host, "avoid-notch", stringResource(R.string.display_avoid_notch), + stringResource(R.string.display_avoid_notch_hint), checked = enabled, onChange = a.onAvoidNotch) + } ToggleRow(host, "zero-copy", stringResource(R.string.display_zero_copy), null, checked = s.zeroCopy, onChange = a.onZeroCopy) } SettingsGroup(stringResource(R.string.display_image_scaling)) { diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index f9d6d205b2..2444ea2650 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -2569,6 +2569,8 @@ ملاءمة اللعبة لنسبة 16:9 كيفية ملاءمة ألعاب 16:9 لهذه الشاشة. يُطبَّق في الجلسة التالية. اختر «مطابقة الشاشة» أو حجمًا مخصَّصًا أضيق من 16:9. + تجنب الحواف + يُبقي الصورة بعيدًا عن فتحة الكاميرا. يُطبَّق عند العودة إلى الجلسة. الحفاظ على النسب تمديد لملء الشاشة تكبير الصورة diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 194e5d3afb..5549df7437 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -2561,6 +2561,8 @@ Ajuste de juegos 16:9 Cómo se ajustan los juegos 16:9 a esta pantalla. Próxima sesión. Elige Igual a la pantalla o un tamaño personalizado más estrecho que 16:9. + Evitar la muesca + Mantiene la imagen fuera del recorte de la cámara. Se aplica al volver a la sesión. Mantener proporciones Estirar a la pantalla Escalado de imagen diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index 03ba45f845..38005ba0b8 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -2465,6 +2465,8 @@ Напасване на игра 16:9 Как игрите с 16:9 се напасват на този екран. При следващата сесия. Избери „Напасване на екрана“ или собствен размер, по-тесен от 16:9. + Избягване на прореза + Държи картината извън прореза за камерата. Важи при връщане към сесията. Запазване на пропорциите Разтягане до екрана Мащабиране на изображението diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 246926fff0..e659eaf255 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -2517,6 +2517,8 @@ Přizpůsobení hry 16:9 Jak se hry s poměrem 16:9 přizpůsobí této obrazovce. Příští relace. Vyberte Podle obrazovky nebo vlastní velikost užší než 16:9. + Vyhnout se výřezu + Obraz zůstane mimo výřez kamery. Použije se po návratu do relace. Zachovat proporce Roztáhnout na obrazovku Škálování obrazu diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index dc190f6e62..b1de62f68f 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -2465,6 +2465,8 @@ 16:9-spiltilpasning Hvordan 16:9-spil tilpasses denne skærm. Fra næste session. Vælg Match skærm eller en brugerdefineret størrelse, der er smallere end 16:9. + Undgå notch + Holder billedet uden for kameraudskæringen. Træder i kraft, når du vender tilbage til sessionen. Bevar proportioner Stræk til skærm Billedskalering diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 3f42bc4e29..e24db01500 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -2457,6 +2457,8 @@ 16:9-Spielanpassung Wie 16:9-Spiele auf dieses Display passen. Ab der nächsten Sitzung. Wähle „An Bildschirm anpassen“ oder eine eigene Größe schmaler als 16:9. + Notch aussparen + Hält das Bild aus der Kameraaussparung heraus. Gilt, sobald du zur Sitzung zurückkehrst. Seitenverhältnis beibehalten Auf Display strecken Bildskalierung diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 6cce64d9ce..4bb5fc7344 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -2465,6 +2465,8 @@ Προσαρμογή παιχνιδιού 16:9 Πώς προσαρμόζονται τα παιχνίδια 16:9 σε αυτή την οθόνη. Από την επόμενη συνεδρία. Επιλέξτε Αντιστοίχιση οθόνης ή ένα προσαρμοσμένο μέγεθος πιο στενό από 16:9. + Αποφυγή εγκοπής + Κρατά την εικόνα μακριά από την εγκοπή της κάμερας. Εφαρμόζεται όταν επιστρέψεις στη συνεδρία. Διατήρηση αναλογιών Διάταση στην οθόνη Κλιμάκωση εικόνας diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index ac6c6d8945..354828c595 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -2491,6 +2491,8 @@ Ajuste de juegos 16:9 Cómo se ajustan los juegos 16:9 a esta pantalla. Próxima sesión. Elige Igual a la pantalla o un tamaño personalizado más estrecho que 16:9. + Evitar la muesca + Mantiene la imagen fuera del recorte de la cámara. Se aplica al volver a la sesión. Mantener proporciones Estirar a la pantalla Escalado de imagen diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 8164624f87..48387e6806 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -2465,6 +2465,8 @@ 16:9-pelin sovitus Miten 16:9-pelit sovitetaan tähän näyttöön. Seuraava istunto. Valitse Sovita näyttöön tai mukautettu koko, joka on 16:9:ää kapeampi. + Vältä lovea + Pitää kuvan poissa kameran lovesta. Tulee voimaan, kun palaat istuntoon. Säilytä kuvasuhde Venytä näyttöön Kuvan skaalaus diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 1743a855ea..90348a7edc 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -2490,6 +2490,8 @@ Ajustement des jeux 16:9 Comment les jeux 16:9 s\'adaptent à cet écran. À la prochaine session. Choisissez « Adapter à l\'écran » ou une taille personnalisée plus étroite que 16:9. + Éviter l\'encoche + Garde l\'image hors de la découpe de la caméra. S\'applique au retour dans la session. Conserver les proportions Étirer sur l\'écran Mise à l\'échelle de l\'image diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 01ad1e44d3..bac24154ff 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -2465,6 +2465,8 @@ 16:9 गेम फ़िट 16:9 गेम इस डिस्प्ले में कैसे फ़िट होते हैं। अगले सेशन से। Match screen चुनें या 16:9 से पतला कस्टम आकार चुनें। + नॉच से बचें + तस्वीर को कैमरा कटआउट से दूर रखता है। सेशन में लौटने पर लागू होता है। अनुपात बनाए रखें डिस्प्ले में स्ट्रेच करें इमेज स्केलिंग diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index ab299b1229..f2a0cf774d 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -2465,6 +2465,8 @@ 16:9 játék illesztése Hogyan illeszkednek a 16:9 játékok ehhez a kijelzőhöz. A következő munkamenettől. Válassza a Képernyőhöz illesztést, vagy egy 16:9-nél szűkebb egyéni méretet. + Kamera-kivágás kerülése + A képet távol tartja a kameralyuktól. A munkamenetbe való visszatéréskor lép életbe. Arányok megtartása Nyújtás a kijelzőhöz Képméretezés diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 23a49ce8d9..67516678dc 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -2440,6 +2440,8 @@ Penyesuaian gim 16:9 Cara gim 16:9 disesuaikan dengan tampilan ini. Berlaku pada sesi berikutnya. Pilih Sesuaikan layar atau ukuran khusus yang lebih sempit dari 16:9. + Hindari poni + Menjauhkan gambar dari lubang kamera. Berlaku saat Anda kembali ke sesi. Pertahankan proporsi Bentangkan ke tampilan Penskalaan gambar diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 7e6909e998..ce0632f450 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -2482,6 +2482,8 @@ Adattamento giochi 16:9 Come i giochi 16:9 si adattano a questo schermo. Dalla prossima sessione. Scegli Adatta allo schermo o una dimensione personalizzata più stretta di 16:9. + Evita il notch + Tiene l\'immagine fuori dal ritaglio della fotocamera. Si applica al ritorno alla sessione. Mantieni proporzioni Estendi allo schermo Ridimensionamento immagine diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index a9927cc1c3..2b37a68447 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -2440,6 +2440,8 @@ 16:9ゲームの表示 16:9のゲームをこのディスプレイにどう合わせるか。次回のセッションから。 「画面に合わせる」か、16:9より縦長のカスタムサイズを選んでください。 + ノッチを避ける + 映像をカメラの切り欠きから離します。セッションに戻ると反映されます。 縦横比を保持 画面いっぱいに引き伸ばす 画像のスケーリング diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index aba825df85..ca9a31ec99 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -2440,6 +2440,8 @@ 16:9 게임 맞춤 16:9 게임을 이 디스플레이에 맞추는 방식입니다. 다음 세션부터 적용됩니다. 화면에 맞춤 또는 16:9보다 좁은 사용자 정의 크기를 선택하세요. + 노치 피하기 + 화면을 카메라 컷아웃 밖에 표시합니다. 세션으로 돌아오면 적용됩니다. 비율 유지 화면에 맞게 늘이기 이미지 스케일링 diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index 21f75a28c2..769c6f2c7a 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -2440,6 +2440,8 @@ Suaian permainan 16:9 Cara permainan 16:9 disuaikan ke paparan ini. Sesi seterusnya. Pilih Sepadan skrin atau saiz tersuai lebih nipis daripada 16:9. + Elak takuk + Memastikan gambar tidak berada di potongan kamera. Digunakan apabila anda kembali ke sesi. Kekalkan nisbah Regang ke paparan Penskalaan imej diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index f4772e7a0d..2533182c77 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -2465,6 +2465,8 @@ 16:9-spilltilpasning Hvordan 16:9-spill tilpasses denne skjermen. Fra neste sesjon. Velg Tilpass skjerm eller en egendefinert størrelse smalere enn 16:9. + Unngå notch + Holder bildet unna kamerautskjæringen. Gjelder når du går tilbake til økten. Behold proporsjoner Strekk til skjermen Bildeskalering diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 9292a1a568..be6d86c508 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -2465,6 +2465,8 @@ 16:9-beeldvulling Hoe 16:9-games dit scherm vullen. Volgende sessie. Kies Schermformaat of een aangepast formaat dat smaller is dan 16:9. + Notch vermijden + Houdt het beeld buiten de camerauitsparing. Geldt zodra je terugkeert naar de sessie. Beeldverhouding behouden Uitrekken naar scherm Beeldschaling diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 12a3bed38d..80486fc3cd 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -2517,6 +2517,8 @@ Dopasowanie gier 16:9 Jak gry 16:9 mieszczą się na tym ekranie. Od następnej sesji. Wybierz „Dopasuj do ekranu” lub własny rozmiar węższy niż 16:9. + Omijaj notch + Utrzymuje obraz poza wycięciem na aparat. Działa po powrocie do sesji. Zachowaj proporcje Rozciągnij do ekranu Skalowanie obrazu diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 39c9526f17..19e92b33fd 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -2496,6 +2496,8 @@ Ajuste de jogos 16:9 Como os jogos 16:9 se ajustam a este ecrã. Próxima sessão. Escolha «Igual ao ecrã» ou um tamanho personalizado mais estreito do que 16:9. + Evitar o entalhe + Mantém a imagem fora do recorte da câmara. Aplica-se ao voltar à sessão. Manter proporções Esticar até ao ecrã Escala da imagem diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 80bbc786f5..aa4a3fec32 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -2504,6 +2504,8 @@ Ajuste de jogos 16:9 Como os jogos 16:9 se ajustam a esta tela. Na próxima sessão. Escolha Igual à tela ou um tamanho personalizado mais estreito que 16:9. + Evitar o notch + Mantém a imagem fora do recorte da câmera. Aplica-se ao voltar à sessão. Manter proporções Esticar para a tela Escala de imagem diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index a4cc2e9436..fa7ba56548 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -2491,6 +2491,8 @@ Potrivire joc 16:9 Cum se potrivesc jocurile 16:9 cu acest afișaj. Sesiunea următoare. Alege Potrivire ecran sau o dimensiune personalizată mai îngustă decât 16:9. + Evită decupajul + Ține imaginea departe de decupajul camerei. Se aplică la revenirea în sesiune. Păstrează proporțiile Întinde pe afișaj Scalarea imaginii diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 6e403bc05b..1cf83c57c5 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -2517,6 +2517,8 @@ Игры 16:9 Как игры 16:9 вписываются в этот экран. Вступит в силу в следующей сессии. Выберите «По размеру экрана» или свой размер уже 16:9. + Обходить вырез + Не выводит картинку под вырез камеры. Применяется при возврате в сессию. Сохранять пропорции Растянуть на экран Масштабирование изображения diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 588673ab19..1669d9b650 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -2465,6 +2465,8 @@ 16:9-spelanpassning Hur 16:9-spel anpassas till den här skärmen. Nästa session. Välj Matcha skärmen eller en anpassad storlek som är smalare än 16:9. + Undvik notch + Håller bilden utanför kameraurtaget. Gäller när du återvänder till sessionen. Behåll proportionerna Sträck ut till skärmen Bildskalning diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 8706c82ef0..d2067ebb29 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -2440,6 +2440,8 @@ การแสดงเกม 16:9 ให้พอดี วิธีที่เกม 16:9 แสดงพอดีกับหน้าจอนี้ มีผลในเซสชันถัดไป เลือกพอดีหน้าจอ หรือขนาดกำหนดเองที่แคบกว่า 16:9 + เลี่ยงรอยบาก + ไม่แสดงภาพทับช่องกล้อง มีผลเมื่อคุณกลับเข้าสู่เซสชัน คงสัดส่วนไว้ ยืดให้พอดีหน้าจอ การปรับขนาดภาพ diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index b9bc2ab818..015e080979 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -2457,6 +2457,8 @@ 16:9 oyun sığdırma 16:9 oyunların bu ekrana nasıl sığacağı. Sonraki oturumda. Ekrana Uydur\'u veya 16:9\'dan daha dar özel bir boyutu seçin. + Çentikten kaçın + Görüntüyü kamera çentiğinin dışında tutar. Oturuma döndüğünüzde uygulanır. Oranları koru Ekrana uzat Görüntü ölçekleme diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 2c8caec508..0ae16d9a5d 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -2517,6 +2517,8 @@ Вписування гри 16:9 Як ігри 16:9 вписуються в цей дисплей. З наступного сеансу. Виберіть «Під екран» або власний розмір, вужчий за 16:9. + Обходити виріз + Не виводить зображення під виріз камери. Застосовується після повернення до сесії. Зберігати пропорції Розтягнути на весь дисплей Масштабування зображення diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 7c1a384f3c..a2601eb6c1 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -2440,6 +2440,8 @@ Khớp game 16:9 Cách game 16:9 khớp với màn hình này. Từ phiên sau. Chọn Khớp màn hình hoặc một kích thước tùy chỉnh hẹp hơn 16:9. + Tránh tai thỏ + Giữ hình ảnh tránh khỏi phần khuyết camera. Áp dụng khi bạn quay lại phiên. Giữ tỷ lệ Kéo giãn để khớp màn hình Chia tỷ lệ hình ảnh diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index b2085b2861..802aa28274 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -2517,6 +2517,8 @@ 16:9 游戏适配 16:9 游戏如何适配此屏幕。下次会话生效。 请选择“匹配屏幕”或比 16:9 更窄的自定义尺寸。 + 避开刘海 + 让画面避开摄像头挖孔区域。返回会话时生效。 保持比例 拉伸至屏幕 画面缩放 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 84d53e7341..b7b9481b52 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -2437,6 +2437,8 @@ 16:9 遊戲顯示方式 16:9 遊戲如何配合此螢幕。下次會話生效。 請選擇「配合螢幕」或比 16:9 更窄的自訂尺寸。 + 避開瀏海 + 讓畫面避開鏡頭挖孔區域。返回工作階段時生效。 保持比例 拉伸至螢幕 畫面縮放 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 0d10927002..945485063e 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -2437,6 +2437,8 @@ 16:9 遊戲顯示方式 16:9 遊戲如何配合此螢幕。下次工作階段生效。 請選擇「符合螢幕」或比 16:9 更窄的自訂尺寸。 + 避開瀏海 + 讓畫面避開鏡頭挖孔區域。返回工作階段時生效。 維持比例 延展至螢幕 畫面縮放 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 7cdceeb723..81d2a929e0 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -2722,6 +2722,8 @@ 16:9 game fit How 16:9 games fit this display. Next session. Choose Match screen or a custom size that isn\'t 16:9. + Avoid notch + Keeps the picture out of the camera cutout. Applies when you return to the session. Keep proportions Stretch to display Image scaling diff --git a/app/src/test/java/com/droiddeck/launcher/session/AvoidNotchPrefsTest.kt b/app/src/test/java/com/droiddeck/launcher/session/AvoidNotchPrefsTest.kt new file mode 100644 index 0000000000..5f07411473 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/AvoidNotchPrefsTest.kt @@ -0,0 +1,36 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class AvoidNotchPrefsTest { + private val app get() = RuntimeEnvironment.getApplication() + private val saved get() = app.getSharedPreferences("session", Context.MODE_PRIVATE) + + @Before fun clear() { saved.edit().clear().commit() } + + @Test fun theNotchIsLeftAloneUntilAskedToAvoidIt() { + assertFalse(SessionPrefs.avoidNotch(app)) + } + + @Test fun theChoiceIsKept() { + SessionPrefs.setAvoidNotch(app, true) + assertTrue(SessionPrefs.avoidNotch(app)) + SessionPrefs.setAvoidNotch(app, false) + assertFalse(SessionPrefs.avoidNotch(app)) + } + + @Test fun resettingSettingsTurnsItOff() { + SessionPrefs.setAvoidNotch(app, true) + assertTrue(SettingsReset.resetAll(app, gameProfiles = false)) + assertFalse(SessionPrefs.avoidNotch(app)) + } +} From ca29850d043a9652a26dcc4cea84f970cfe6881d Mon Sep 17 00:00:00 2001 From: FX192 <120828496+FX192@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:25:19 +0300 Subject: [PATCH 006/141] fix(session): keep mouse, pen and unfolded layout correct with the notch inset Map activity-level mouse and pen events into the surface's space, size the unfolded layout from the padded content area, re-evaluate the inset when the output moves to glasses, the bottom screen or cardboard, and use a clearer Arabic label. --- .../com/droiddeck/launcher/SessionActivity.kt | 38 +++++++++++++++---- app/src/main/res/values-ar/strings.xml | 2 +- 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index d3c58bd978..17be4002e3 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -182,7 +182,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun applyNotchInset(insets: android.view.WindowInsets? = window.decorView.rootWindowInsets) { if (!::sessionRoot.isInitialized) return val cutout = if (avoidNotch && Build.VERSION.SDK_INT >= 28 && SessionState.mode == SessionService.MODE_STEAM && - !pipUi && !isInPictureInPictureMode && glassesScreen == null && bottomGame == null && !cardboard.enabled) + !pipUi && !isInPictureInPictureMode && glassesScreen == null && bottomGame == null && !activeCardboard.enabled) insets?.displayCutout else null val left = cutout?.safeInsetLeft ?: 0 val top = cutout?.safeInsetTop ?: 0 @@ -191,6 +191,23 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (sessionRoot.paddingLeft == left && sessionRoot.paddingTop == top && sessionRoot.paddingRight == right && sessionRoot.paddingBottom == bottom) return sessionRoot.setPadding(left, top, right, bottom) + uiHandler.post { applyUnfoldedControls() } + } + + private fun rootContentWidth() = sessionRoot.width - sessionRoot.paddingLeft - sessionRoot.paddingRight + + private fun rootContentHeight() = sessionRoot.height - sessionRoot.paddingTop - sessionRoot.paddingBottom + + private inline fun inSurfaceSpace(event: MotionEvent, block: () -> T): T { + val dx = if (outputView() === surfaceView) -surfaceView.left.toFloat() else 0f + val dy = if (outputView() === surfaceView) -surfaceView.top.toFloat() else 0f + if (dx == 0f && dy == 0f) return block() + event.offsetLocation(dx, dy) + try { + return block() + } finally { + event.offsetLocation(-dx, -dy) + } } private fun applyGameAlignment() { @@ -3701,12 +3718,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (pen >= 0) when (routePen(event, pen)) { PenRouter.Route.TOUCH -> {} PenRouter.Route.PEN -> { - if (!appUiOwnsPointer()) return penSample(event, pen) || super.dispatchGenericMotionEvent(event) + if (!appUiOwnsPointer()) return inSurfaceSpace(event) { penSample(event, pen) } || super.dispatchGenericMotionEvent(event) if (super.dispatchGenericMotionEvent(event)) { penStream.cancel() return true } - return !touchEditorOpen && penSample(event, pen) + return !touchEditorOpen && inSurfaceSpace(event) { penSample(event, pen) } } else -> return super.dispatchGenericMotionEvent(event) } @@ -3714,10 +3731,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (appUiOwnsPointer()) { if (super.dispatchGenericMotionEvent(event)) return true if (touchEditorOpen) return false - if (onMouse(event)) return true + if (inSurfaceSpace(event) { onMouse(event) }) return true return false } - if (onMouse(event)) return true + if (inSurfaceSpace(event) { onMouse(event) }) return true } return super.dispatchGenericMotionEvent(event) } @@ -4591,14 +4608,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun controlsBelowWanted(): Boolean { if (!::sessionRoot.isInitialized || glassesScreen != null || bottomGame != null || cardboard.enabled) return false - return SessionPrefs.controlsBelowWanted(this, SessionState.mode, sessionRoot.width, sessionRoot.height, + return SessionPrefs.controlsBelowWanted(this, SessionState.mode, rootContentWidth(), rootContentHeight(), pipUi || isInPictureInPictureMode) } private fun applyUnfoldedControls() { if (!::sessionRoot.isInitialized) return - val width = sessionRoot.width - val height = sessionRoot.height + val width = rootContentWidth() + val height = rootContentHeight() val wanted = controlsBelowWanted() val tabRow = unfoldedColumn?.getChildAt(0)?.height?.let { it - (com.droiddeck.launcher.ui.BAR_HEIGHT.value * resources.displayMetrics.density + 0.5f).toInt() @@ -6131,6 +6148,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val e = effectiveCardboard(c) activeCardboard = e applyGameAlignment() + applyNotchInset() if (CompositorHost.isStarted) pushCardboard(e) if (e.enabled && !was.enabled) headTracker?.recenter() updateHeadTracker() @@ -6214,6 +6232,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde glassesOutputActive = false surfaceW = 0 surfaceH = 0 + applyNotchInset() CompositorHost.detach(screen.holder.surface) surfaceView.visibility = View.VISIBLE applyOutputPacing() @@ -6263,6 +6282,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde bottomGame = screen surfaceW = 0 surfaceH = 0 + applyNotchInset() screen.setOnDismissListener { if (bottomGame === screen) { restoreTopOutput(screen) @@ -6304,6 +6324,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde updateOnScreenPad() surfaceW = 0 surfaceH = 0 + applyNotchInset() CompositorHost.detach(screen.holder.surface) if (glassesScreen != null) return surfaceView.visibility = View.VISIBLE @@ -6468,6 +6489,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde bottomGame?.let { restoreTopOutput(it); runCatching { it.dismiss() } } val screen = GlassesScreen(this, target, Glasses.outputHz(), this, Glasses.outputResolution()) glassesScreen = screen + applyNotchInset() applyOutputPacing() surfaceW = 0 surfaceH = 0 diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 2444ea2650..d47088cf05 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -2569,7 +2569,7 @@ ملاءمة اللعبة لنسبة 16:9 كيفية ملاءمة ألعاب 16:9 لهذه الشاشة. يُطبَّق في الجلسة التالية. اختر «مطابقة الشاشة» أو حجمًا مخصَّصًا أضيق من 16:9. - تجنب الحواف + تجنّب فتحة الكاميرا يُبقي الصورة بعيدًا عن فتحة الكاميرا. يُطبَّق عند العودة إلى الجلسة. الحفاظ على النسب تمديد لملء الشاشة From dc6b7f29cfea57256eb6ee3b3e94c293410050ba Mon Sep 17 00:00:00 2001 From: FX192 <120828496+FX192@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:34:36 +0300 Subject: [PATCH 007/141] fix(session): map activity-level mouse touches into the surface space --- app/src/main/java/com/droiddeck/launcher/SessionActivity.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 17be4002e3..9d4b11c826 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -5047,7 +5047,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde override fun onTouchEvent(event: MotionEvent): Boolean { val pen = PenStream.penIndex(event) val penRouted = if (pen >= 0) routePen(event, pen).takeIf { it != PenRouter.Route.TOUCH } else null - if (penRouted == null && event.isFromSource(android.view.InputDevice.SOURCE_MOUSE)) return onMouse(event) + if (penRouted == null && event.isFromSource(android.view.InputDevice.SOURCE_MOUSE)) return inSurfaceSpace(event) { onMouse(event) } when (event.actionMasked) { MotionEvent.ACTION_DOWN -> { sessionTouchDown = true From 3962b3e27ff103c4f91b7f995e8d3f4e7047b3a4 Mon Sep 17 00:00:00 2001 From: FX192 <120828496+FX192@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:42:14 +0300 Subject: [PATCH 008/141] fix(session): convert activity-level mouse touches once, not control-forwarded ones --- .../com/droiddeck/launcher/SessionActivity.kt | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 9d4b11c826..1b47acae80 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -943,7 +943,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde controls.onTouchMiss = miss@{ event -> if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.ON_SCREEN_CONTROLS, event)) return@miss event.offsetLocation(controls.left - surfaceView.left.toFloat(), controls.top - surfaceView.top.toFloat()) - onTouchEvent(event) + handleTouch(event) } root.addView(controls) } @@ -988,7 +988,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde false } else if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SURFACE, event)) { false - } else onTouchEvent(event) + } else handleTouch(event) } padMouse = PadMouse(padMouseListener) bridge.setTouchRoute(object : PadBridge.TouchRoute { @@ -5044,10 +5044,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde secondScreenPresentation?.controlsView, swappedInputSurface, ).any { it.isShown && inputProfile.showsMouseButton(it.inputRole, it.shownElements, stockInputProfile) } - override fun onTouchEvent(event: MotionEvent): Boolean { + override fun onTouchEvent(event: MotionEvent): Boolean = + if (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE)) inSurfaceSpace(event) { handleTouch(event) } + else handleTouch(event) + + private fun handleTouch(event: MotionEvent): Boolean { val pen = PenStream.penIndex(event) val penRouted = if (pen >= 0) routePen(event, pen).takeIf { it != PenRouter.Route.TOUCH } else null - if (penRouted == null && event.isFromSource(android.view.InputDevice.SOURCE_MOUSE)) return inSurfaceSpace(event) { onMouse(event) } + if (penRouted == null && event.isFromSource(android.view.InputDevice.SOURCE_MOUSE)) return onMouse(event) when (event.actionMasked) { MotionEvent.ACTION_DOWN -> { sessionTouchDown = true @@ -5171,7 +5175,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (event.pointerCount > 1) { var fingers = 0 for (index in 0 until event.pointerCount) if (!PenStream.isPen(event, index)) fingers = fingers or (1 shl event.getPointerId(index)) - event.pointerSubset(fingers)?.let { split -> try { onTouchEvent(split) } finally { split.recycle() } } + event.pointerSubset(fingers)?.let { split -> try { handleTouch(split) } finally { split.recycle() } } } when (route) { PenRouter.Route.PEN -> penSample(event, pen) @@ -5482,7 +5486,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde view.onTouchMiss = miss@{ event -> if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.ON_SCREEN_CONTROLS, event)) return@miss event.offsetLocation(view.left - surfaceView.left.toFloat(), view.top - surfaceView.top.toFloat()) - onTouchEvent(event) + handleTouch(event) } root.addView(view, root.indexOfChild(onScreenControls) + 1) steamTouchControls = view @@ -6355,7 +6359,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde gestureTouchStreamGate.reset() } if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SURFACE, event)) return false - return onTouchEvent(event) + return handleTouch(event) } @androidx.compose.runtime.Composable From e57bc43f6ad61ac43845ba5d747856783e712436 Mon Sep 17 00:00:00 2001 From: FX192 <120828496+FX192@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:55:36 +0300 Subject: [PATCH 009/141] fix(session): map every activity-level touch into the surface space --- app/src/main/java/com/droiddeck/launcher/SessionActivity.kt | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 1b47acae80..a95ae09118 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -5044,9 +5044,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde secondScreenPresentation?.controlsView, swappedInputSurface, ).any { it.isShown && inputProfile.showsMouseButton(it.inputRole, it.shownElements, stockInputProfile) } - override fun onTouchEvent(event: MotionEvent): Boolean = - if (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE)) inSurfaceSpace(event) { handleTouch(event) } - else handleTouch(event) + override fun onTouchEvent(event: MotionEvent): Boolean = inSurfaceSpace(event) { handleTouch(event) } private fun handleTouch(event: MotionEvent): Boolean { val pen = PenStream.penIndex(event) From 50dace99588a6fb5375333a30dff568c10a8e95b Mon Sep 17 00:00:00 2001 From: FX192 <120828496+FX192@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:21:08 +0300 Subject: [PATCH 010/141] feat(session): split the display resolution into landscape and portrait Landscape and Portrait resolution rows with the same options, each with a Follow option so one can mirror the other. Existing choices stay as the landscape resolution and portrait follows landscape by default, so nothing changes until portrait is set. --- .../droiddeck/launcher/FrontEndActivity.kt | 14 +++- .../com/droiddeck/launcher/SessionActivity.kt | 20 +++-- .../droiddeck/launcher/core/DeviceReport.kt | 8 +- .../launcher/session/SessionDisplay.kt | 20 +++++ .../launcher/session/SessionPrefs.kt | 36 +++++++-- .../launcher/ui/ModeSettingsDialog.kt | 15 +++- .../droiddeck/launcher/ui/ResolutionRow.kt | 18 +++-- app/src/main/res/values-ar/strings.xml | 5 +- app/src/main/res/values-b+es+419/strings.xml | 5 +- app/src/main/res/values-bg/strings.xml | 5 +- app/src/main/res/values-cs/strings.xml | 5 +- app/src/main/res/values-da/strings.xml | 5 +- app/src/main/res/values-de/strings.xml | 5 +- app/src/main/res/values-el/strings.xml | 5 +- app/src/main/res/values-es/strings.xml | 5 +- app/src/main/res/values-fi/strings.xml | 5 +- app/src/main/res/values-fr/strings.xml | 5 +- app/src/main/res/values-hi/strings.xml | 5 +- app/src/main/res/values-hu/strings.xml | 5 +- app/src/main/res/values-in/strings.xml | 5 +- app/src/main/res/values-it/strings.xml | 5 +- app/src/main/res/values-ja/strings.xml | 5 +- app/src/main/res/values-ko/strings.xml | 5 +- app/src/main/res/values-ms/strings.xml | 5 +- app/src/main/res/values-nb/strings.xml | 5 +- app/src/main/res/values-nl/strings.xml | 5 +- app/src/main/res/values-pl/strings.xml | 5 +- app/src/main/res/values-pt-rPT/strings.xml | 5 +- app/src/main/res/values-pt/strings.xml | 5 +- app/src/main/res/values-ro/strings.xml | 5 +- app/src/main/res/values-ru/strings.xml | 5 +- app/src/main/res/values-sv/strings.xml | 5 +- app/src/main/res/values-th/strings.xml | 5 +- app/src/main/res/values-tr/strings.xml | 5 +- app/src/main/res/values-uk/strings.xml | 5 +- app/src/main/res/values-vi/strings.xml | 5 +- app/src/main/res/values-zh-rCN/strings.xml | 5 +- app/src/main/res/values-zh-rHK/strings.xml | 5 +- app/src/main/res/values-zh-rTW/strings.xml | 5 +- app/src/main/res/values/strings.xml | 5 +- .../session/PortraitResolutionTest.kt | 73 +++++++++++++++++++ 41 files changed, 305 insertions(+), 64 deletions(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index ca5e23cefe..66e718dc2c 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -585,6 +585,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } private var settingsMode by mutableStateOf(null) private var resolution by mutableStateOf(com.droiddeck.launcher.session.SessionDisplay.DEFAULT_RESOLUTION) + private var resolutionPortrait by mutableStateOf(com.droiddeck.launcher.session.SessionDisplay.LINK_LANDSCAPE) private var fexPreset by mutableStateOf("") private var forceSsbs by mutableStateOf(false) private var steamClientArch by mutableStateOf("arm64") @@ -2588,7 +2589,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet if (settingsMode != mode) return com.droiddeck.launcher.ui.ModeSheetRows( ModeSettings( - mode = mode, resolution = resolution, + mode = mode, resolution = resolution, resolutionPortrait = resolutionPortrait, panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this), hdr = hdrOn, hdrReason = hdrReason, hdrDisplay = hdrDisplay, zeroCopy = zeroCopyOn, upscaler = upscaler, upscaleSharpness = upscaleSharpness, @@ -2643,7 +2644,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet onIntegration = ::configureIntegration, onIntegrationAppInfo = ::openAppInfo, onIntegrationLocation = ::openWifiDiscoverySettings, - onResolution = { value -> SessionPrefs.setResolutionChoice(this, mode, value); resolution = value }, + onResolution = { value -> SessionPrefs.setResolutionChoice(this, mode, value); loadResolutions(mode) }, + onResolutionPortrait = { value -> SessionPrefs.setResolutionChoice(this, mode, value, portrait = true); loadResolutions(mode) }, onHdr = { on -> com.droiddeck.launcher.session.SessionHdr.set(this, mode, on); hdrOn = on }, onZeroCopy = { on -> SessionPrefs.setZeroCopy(this, mode, on); zeroCopyOn = on @@ -2976,11 +2978,17 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet }, "shader-precache").start() } + private fun loadResolutions(mode: String) { + val panel = com.droiddeck.launcher.session.SessionDisplay.panelSize(this) + resolution = SessionPrefs.resolutionStored(this, mode, panel, false) + resolutionPortrait = SessionPrefs.resolutionStored(this, mode, panel, true) + } + private fun loadModeSettings(mode: String) { pipAutoEnter = SessionPrefs.pipAutoEnter(this) unfoldedControls = SessionPrefs.unfoldedControls(this) unfoldedControlsWithController = SessionPrefs.unfoldedControlsWithController(this) - resolution = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this)) + loadResolutions(mode) fexPreset = SessionPrefs.fexPreset(this) forceSsbs = SessionPrefs.forceSsbs(this) fastSync = SessionPrefs.fastSync(this) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index a95ae09118..bc40319467 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -2958,14 +2958,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun followScale(): Float { val mode = displayMode() - val choice = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this)) + val choice = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this), portraitOutput()) return com.droiddeck.launcher.session.SessionDisplay.followScale(choice) ?: 1f } private fun followChoice(): Boolean { val mode = displayMode() return com.droiddeck.launcher.session.SessionDisplay.isFollow( - SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this))) + SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this), portraitOutput())) } private fun applyFollowOrientation(config: android.content.res.Configuration) { @@ -3031,17 +3031,21 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun displayMode(): String = SessionPrefs.displayMode(this, intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM, intent.getStringExtra(SessionService.EXTRA_PROGRAM)) - private fun outputSize(): Pair = - com.droiddeck.launcher.session.SessionDisplay.resolveChoice(com.droiddeck.launcher.session.SessionDisplay.panelSize(this), - resolutionChoice(), SessionPrefs.portrait(this) && !controlsBelowWanted()) + private fun portraitOutput(): Boolean = SessionPrefs.portrait(this) && !controlsBelowWanted() - private fun resolutionChoice(): String { + private fun outputSize(): Pair { + val portrait = portraitOutput() + return com.droiddeck.launcher.session.SessionDisplay.resolveChoice(com.droiddeck.launcher.session.SessionDisplay.panelSize(this), + resolutionChoice(portrait), portrait) + } + + private fun resolutionChoice(portrait: Boolean = portraitOutput()): String { val mode = displayMode() val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM) return if (intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_RUN && - Library.drawsAtPanel(program) && !SessionPrefs.resolutionChosen(this, mode)) + Library.drawsAtPanel(program) && !SessionPrefs.resolutionChosen(this, mode, portrait)) com.droiddeck.launcher.session.SessionDisplay.MATCH_SCREEN - else SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this)) + else SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this), portrait) } private fun refreshHz(): Float = refreshHz(null) diff --git a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt index dbc78c6a2d..6cd2585557 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt @@ -207,9 +207,11 @@ object DeviceReport { k("refresh_rate_mode", runCatching { Settings.Secure.getString(context.contentResolver, "refresh_rate_mode") }.getOrNull() ?: "not set") val panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(context) for ((label, mode) in listOf("Resolution (Steam)" to SessionService.MODE_STEAM, "Resolution (Desktop)" to SessionService.MODE_DESKTOP)) { - val choice = SessionPrefs.resolutionChoice(context, mode, panelSize) - val size = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panelSize, choice) - k(label, "$choice (${size.first}x${size.second})") + for ((suffix, portrait) in listOf("landscape" to false, "portrait" to true)) { + val choice = SessionPrefs.resolutionChoice(context, mode, panelSize, portrait) + val size = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panelSize, choice, portrait) + k("$label $suffix", "$choice (${size.first}x${size.second})") + } } k("Foldable", context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle")) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt index 9b253d88a7..a9f809c079 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt @@ -12,6 +12,9 @@ object SessionDisplay { const val FOLLOW_SCALE_MAX = 8f private const val FOLLOW_SCALED_PREFIX = "follow/" + const val LINK_LANDSCAPE = "link/landscape" + const val LINK_PORTRAIT = "link/portrait" + const val DEFAULT_RESOLUTION = "720p" private val PRESET_HEIGHTS = listOf(720, 900, 1080) @@ -35,6 +38,23 @@ object SessionDisplay { else -> null } + fun isLink(choice: String): Boolean = choice == LINK_LANDSCAPE || choice == LINK_PORTRAIT + + fun orientCustom(choice: String, portrait: Boolean): String { + val parts = choice.split('x').map { it.toIntOrNull() } + if (parts.size != 2 || parts.any { it == null || it <= 0 }) return choice + val width = parts[0]!! + val height = parts[1]!! + return if ((portrait && width > height) || (!portrait && height > width)) "${height}x$width" else choice + } + + fun effectiveChoice(landscape: String, portrait: String, forPortrait: Boolean): String { + val own = if (forPortrait) portrait else landscape + if (!isLink(own)) return own + val other = if (forPortrait) landscape else portrait + return if (isLink(other)) DEFAULT_RESOLUTION else orientCustom(other, forPortrait) + } + fun screenSize(panel: Pair): Pair = (maxOf(panel.first, panel.second) and 1.inv()) to (minOf(panel.first, panel.second) and 1.inv()) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 09c0b781ec..f243d3f31a 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -1296,14 +1296,27 @@ object SessionPrefs { private fun resolutionCap(context: Context, mode: String): Int = prefs(context).getInt("resolutionCap.$mode", 720) - fun resolutionChosen(context: Context, mode: String): Boolean = + fun resolutionChosen(context: Context, mode: String, portrait: Boolean = false): Boolean = prefs(context).contains("displayResolution.$mode") || - prefs(context).contains("resolutionCap.$mode") || customResolution(context, mode) != null + prefs(context).contains("resolutionCap.$mode") || customResolution(context, mode) != null || + (portrait && prefs(context).contains("displayResolution.portrait.$mode")) - fun resolutionChoice(context: Context, mode: String, panel: Pair): String { + fun resolutionChoice(context: Context, mode: String, panel: Pair, portrait: Boolean = false): String = + SessionDisplay.effectiveChoice( + resolutionStored(context, mode, panel, false), resolutionStored(context, mode, panel, true), portrait) + + fun resolutionStored(context: Context, mode: String, panel: Pair, portrait: Boolean): String { + if (!portrait) return landscapeResolutionStored(context, mode, panel) + val value = prefs(context).getString("displayResolution.portrait.$mode", null) ?: return SessionDisplay.LINK_LANDSCAPE + if (value == SessionDisplay.LINK_LANDSCAPE || value == SessionDisplay.MATCH_SCREEN || SessionDisplay.isFollow(value) || + SessionDisplay.presetHeight(value) != null) return value + return parseResolution(value)?.let { "${it.first}x${it.second}" } ?: SessionDisplay.LINK_LANDSCAPE + } + + private fun landscapeResolutionStored(context: Context, mode: String, panel: Pair): String { val saved = prefs(context) saved.getString("displayResolution.$mode", null)?.let { value -> - if (value == SessionDisplay.MATCH_SCREEN || SessionDisplay.isFollow(value) || + if (value == SessionDisplay.MATCH_SCREEN || value == SessionDisplay.LINK_PORTRAIT || SessionDisplay.isFollow(value) || SessionDisplay.presetHeight(value) != null) return value parseResolution(value)?.let { return "${it.first}x${it.second}" } } @@ -1315,13 +1328,22 @@ object SessionPrefs { else "${legacy.first}x${legacy.second}" } - fun setResolutionChoice(context: Context, mode: String, choice: String) { - val value = if (choice == SessionDisplay.MATCH_SCREEN || SessionDisplay.isFollow(choice) || + fun setResolutionChoice(context: Context, mode: String, choice: String, portrait: Boolean = false) { + val link = if (portrait) SessionDisplay.LINK_LANDSCAPE else SessionDisplay.LINK_PORTRAIT + val value = if (choice == link || choice == SessionDisplay.MATCH_SCREEN || SessionDisplay.isFollow(choice) || SessionDisplay.presetHeight(choice) != null) choice else { val size = requireNotNull(parseResolution(choice)) { "Invalid resolution" } "${size.first}x${size.second}" } - prefs(context).edit().putString("displayResolution.$mode", value).apply() + val panel = SessionDisplay.panelSize(context) + val landscapeStored = resolutionStored(context, mode, panel, false) + val portraitStored = resolutionStored(context, mode, panel, true) + val edit = prefs(context).edit() + if (value == link && SessionDisplay.isLink(if (portrait) landscapeStored else portraitStored)) { + val concrete = SessionDisplay.effectiveChoice(landscapeStored, portraitStored, !portrait) + edit.putString(if (portrait) "displayResolution.$mode" else "displayResolution.portrait.$mode", concrete) + } + edit.putString(if (portrait) "displayResolution.portrait.$mode" else "displayResolution.$mode", value).apply() } fun fexPreset(context: Context): String = prefs(context).getString("fexPreset", DEFAULT_FEX_PRESET) ?: DEFAULT_FEX_PRESET diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt index 73580d8676..9d0933aa6a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -56,6 +56,7 @@ class DownloadRow(val key: String, val label: String, val detail: String, val pr class ModeSettings( val mode: String, val resolution: String, + val resolutionPortrait: String = com.droiddeck.launcher.session.SessionDisplay.LINK_LANDSCAPE, val panelSize: Pair = 1280 to 720, val hdr: Boolean, val hdrReason: String?, @@ -116,6 +117,7 @@ class ModeSettings( class ModeSettingsActions( val onResolution: (String) -> Unit, + val onResolutionPortrait: (String) -> Unit = {}, val onHdr: (Boolean) -> Unit, val onZeroCopy: (Boolean) -> Unit = {}, val onGpuDrivers: () -> Unit = {}, @@ -234,9 +236,16 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: val controlsBelow = SessionPrefs.controlsBelowWanted(context, s.mode, if (portraitWindow) shortSide else longSide, if (portraitWindow) longSide else shortSide) val portrait = portraitWindow && !controlsBelow - val displaySize = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(s.panelSize, s.resolution, portrait) + val sessionDisplay = com.droiddeck.launcher.session.SessionDisplay + val landscapeChoice = sessionDisplay.effectiveChoice(s.resolution, s.resolutionPortrait, false) + val portraitChoice = sessionDisplay.effectiveChoice(s.resolution, s.resolutionPortrait, true) + val activeChoice = if (portrait) portraitChoice else landscapeChoice + val displaySize = sessionDisplay.resolveChoice(s.panelSize, activeChoice, portrait) SettingsGroup(stringResource(R.string.display_session)) { - ResolutionRow(host, s.resolution, s.panelSize, a.onResolution, portrait = portrait) + ResolutionRow(host, "resolution", stringResource(R.string.display_resolution_landscape), s.resolution, landscapeChoice, + com.droiddeck.launcher.session.SessionDisplay.LINK_PORTRAIT, s.panelSize, a.onResolution, portrait = false) + ResolutionRow(host, "resolution-portrait", stringResource(R.string.display_resolution_portrait), s.resolutionPortrait, portraitChoice, + com.droiddeck.launcher.session.SessionDisplay.LINK_LANDSCAPE, s.panelSize, a.onResolutionPortrait, portrait = true) s.picturePosition?.let { position -> ChoiceRow(host, "picture-position", stringResource(R.string.display_picture_position), null, listOf("top" to stringResource(R.string.display_position_top), @@ -248,7 +257,7 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: } if (s.stretch16x9 != null && (com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(s.panelSize) || com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(displaySize))) { - val canStretch = !com.droiddeck.launcher.session.SessionDisplay.isFollow(s.resolution) && + val canStretch = !com.droiddeck.launcher.session.SessionDisplay.isFollow(activeChoice) && com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(displaySize) ChoiceRow(host, "game-fit", stringResource(R.string.display_game_fit), stringResource(if (canStretch) R.string.display_game_fit_hint else R.string.display_game_fit_unavailable), diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt b/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt index 7112d4f399..efcbbc526a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt @@ -12,20 +12,24 @@ import com.droiddeck.launcher.session.SessionDisplay @Composable fun ResolutionRow( - host: MenuHost, choice: String, panel: Pair, onPick: (String) -> Unit, + host: MenuHost, id: String, title: String, stored: String, choice: String, link: String, + panel: Pair, onPick: (String) -> Unit, chipModifier: Modifier = Modifier, portrait: Boolean = false, ) { val custom = "custom" + val linked = stored == link val size = SessionDisplay.resolveChoice(panel, choice, portrait) val screen = SessionDisplay.resolveChoice(panel, SessionDisplay.MATCH_SCREEN, portrait) val choices = SessionDisplay.resolutionOptions(panel) - val customFollow = SessionDisplay.isFollow(choice) && choice !in choices - val selected = if (SessionDisplay.isFollow(choice)) choice + val customFollow = !linked && SessionDisplay.isFollow(choice) && choice !in choices + val selected = if (linked) link else if (SessionDisplay.isFollow(choice)) choice else if (size == screen) SessionDisplay.MATCH_SCREEN else choice var editCustom by remember { mutableStateOf(false) } var editFollow by remember { mutableStateOf(false) } - val options = choices.map { value -> + val linkLabel = stringResource(if (link == SessionDisplay.LINK_LANDSCAPE) R.string.display_follow_landscape else R.string.display_follow_portrait, + size.first, size.second) + val options = listOf(link to linkLabel) + choices.map { value -> val dimensions = SessionDisplay.resolveChoice(panel, value, portrait) value to if (value == SessionDisplay.MATCH_SCREEN) stringResource(R.string.display_match_screen, screen.first, screen.second) else if (value == SessionDisplay.FOLLOW_SCREEN) stringResource(R.string.display_follow_screen) @@ -35,11 +39,11 @@ fun ResolutionRow( else "${dimensions.first}×${dimensions.second}" } + listOf(SessionDisplay.FOLLOW_CUSTOM to stringResource(R.string.display_follow_screen_scaled, if (customFollow) SessionDisplay.formatScale(SessionDisplay.followScale(choice) ?: 1f) else "…" - ) + if (customFollow) " (${size.first}×${size.second})" else "") + (custom to if (selected in choices) stringResource(R.string.mode_res_custom) + ) + if (customFollow) " (${size.first}×${size.second})" else "") + (custom to if (selected in choices || linked) stringResource(R.string.mode_res_custom) else stringResource(R.string.mode_res_custom_value, size.first, size.second)) - ChoiceRow(host, "resolution", stringResource(R.string.display_resolution), + ChoiceRow(host, id, title, stringResource(R.string.common_applies_next_session), - options, if (selected in choices) selected else if (customFollow) SessionDisplay.FOLLOW_CUSTOM else custom, chipModifier = chipModifier, + options, if (linked || selected in choices) selected else if (customFollow) SessionDisplay.FOLLOW_CUSTOM else custom, chipModifier = chipModifier, onPick = { value -> if (value == custom) editCustom = true else if (value == SessionDisplay.FOLLOW_CUSTOM) editFollow = true diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index d47088cf05..b236ec7954 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -2565,7 +2565,10 @@ %1$s. %2$s\n\n%3$s شاشة الجلسة العرض بدون نسخ - الدقة + دقة الوضع الأفقي + دقة الوضع العمودي + اتباع الأفقي (%1$d×%2$d) + اتباع العمودي (%1$d×%2$d) ملاءمة اللعبة لنسبة 16:9 كيفية ملاءمة ألعاب 16:9 لهذه الشاشة. يُطبَّق في الجلسة التالية. اختر «مطابقة الشاشة» أو حجمًا مخصَّصًا أضيق من 16:9. diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 5549df7437..c1505584fc 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -2557,7 +2557,10 @@ %1$s. %2$s\n\n%3$s Pantalla de la sesión Presentación sin copia - Resolución + Resolución horizontal + Resolución vertical + Igual que horizontal (%1$d×%2$d) + Igual que vertical (%1$d×%2$d) Ajuste de juegos 16:9 Cómo se ajustan los juegos 16:9 a esta pantalla. Próxima sesión. Elige Igual a la pantalla o un tamaño personalizado más estrecho que 16:9. diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index 38005ba0b8..dc9116e960 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -2461,7 +2461,10 @@ %1$s. %2$s\n\n%3$s Екран на сесията Представяне без копиране - Разделителна способност + Резолюция в пейзажен режим + Резолюция в портретен режим + Като пейзажния (%1$d×%2$d) + Като портретния (%1$d×%2$d) Напасване на игра 16:9 Как игрите с 16:9 се напасват на този екран. При следващата сесия. Избери „Напасване на екрана“ или собствен размер, по-тесен от 16:9. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index e659eaf255..d566a893f5 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -2513,7 +2513,10 @@ %1$s. %2$s\n\n%3$s Obrazovka relace Zobrazení bez kopírování - Rozlišení + Rozlišení na šířku + Rozlišení na výšku + Jako na šířku (%1$d×%2$d) + Jako na výšku (%1$d×%2$d) Přizpůsobení hry 16:9 Jak se hry s poměrem 16:9 přizpůsobí této obrazovce. Příští relace. Vyberte Podle obrazovky nebo vlastní velikost užší než 16:9. diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index b1de62f68f..e1c48d2cc7 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -2461,7 +2461,10 @@ %1$s. %2$s\n\n%3$s Sessionsskærm Præsentation uden kopiering - Opløsning + Opløsning i landskab + Opløsning i portræt + Følg landskab (%1$d×%2$d) + Følg portræt (%1$d×%2$d) 16:9-spiltilpasning Hvordan 16:9-spil tilpasses denne skærm. Fra næste session. Vælg Match skærm eller en brugerdefineret størrelse, der er smallere end 16:9. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index e24db01500..f986336c08 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -2453,7 +2453,10 @@ %1$s. %2$s\n\n%3$s Sitzungsanzeige Kopierfreie Darstellung - Auflösung + Auflösung im Querformat + Auflösung im Hochformat + Wie Querformat (%1$d×%2$d) + Wie Hochformat (%1$d×%2$d) 16:9-Spielanpassung Wie 16:9-Spiele auf dieses Display passen. Ab der nächsten Sitzung. Wähle „An Bildschirm anpassen“ oder eine eigene Größe schmaler als 16:9. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 4bb5fc7344..47cddc9a95 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -2461,7 +2461,10 @@ %1$s. %2$s\n\n%3$s Οθόνη συνεδρίας Παρουσίαση χωρίς αντιγραφή - Ανάλυση + Ανάλυση σε οριζόντιο προσανατολισμό + Ανάλυση σε κατακόρυφο προσανατολισμό + Ίδια με οριζόντιο (%1$d×%2$d) + Ίδια με κατακόρυφο (%1$d×%2$d) Προσαρμογή παιχνιδιού 16:9 Πώς προσαρμόζονται τα παιχνίδια 16:9 σε αυτή την οθόνη. Από την επόμενη συνεδρία. Επιλέξτε Αντιστοίχιση οθόνης ή ένα προσαρμοσμένο μέγεθος πιο στενό από 16:9. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 354828c595..637678281f 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -2487,7 +2487,10 @@ %1$s. %2$s\n\n%3$s Pantalla de la sesión Presentación sin copia - Resolución + Resolución horizontal + Resolución vertical + Igual que horizontal (%1$d×%2$d) + Igual que vertical (%1$d×%2$d) Ajuste de juegos 16:9 Cómo se ajustan los juegos 16:9 a esta pantalla. Próxima sesión. Elige Igual a la pantalla o un tamaño personalizado más estrecho que 16:9. diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 48387e6806..47d447af21 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -2461,7 +2461,10 @@ %1$s. %2$s\n\n%3$s Istunnon näyttö Kopioimaton esitys - Tarkkuus + Vaakatilan resoluutio + Pystytilan resoluutio + Seuraa vaakaa (%1$d×%2$d) + Seuraa pystyä (%1$d×%2$d) 16:9-pelin sovitus Miten 16:9-pelit sovitetaan tähän näyttöön. Seuraava istunto. Valitse Sovita näyttöön tai mukautettu koko, joka on 16:9:ää kapeampi. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 90348a7edc..ae3d8f72bd 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -2486,7 +2486,10 @@ %1$s. %2$s\n\n%3$s Affichage de la session Affichage sans copie - Résolution + Résolution en paysage + Résolution en portrait + Comme le paysage (%1$d×%2$d) + Comme le portrait (%1$d×%2$d) Ajustement des jeux 16:9 Comment les jeux 16:9 s\'adaptent à cet écran. À la prochaine session. Choisissez « Adapter à l\'écran » ou une taille personnalisée plus étroite que 16:9. diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index bac24154ff..109385a8ec 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -2461,7 +2461,10 @@ %1$s। %2$s\n\n%3$s सेशन डिस्प्ले बिना कॉपी प्रस्तुति - रिज़ॉल्यूशन + लैंडस्केप रेज़ोल्यूशन + पोर्ट्रेट रेज़ोल्यूशन + लैंडस्केप जैसा (%1$d×%2$d) + पोर्ट्रेट जैसा (%1$d×%2$d) 16:9 गेम फ़िट 16:9 गेम इस डिस्प्ले में कैसे फ़िट होते हैं। अगले सेशन से। Match screen चुनें या 16:9 से पतला कस्टम आकार चुनें। diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index f2a0cf774d..d512c72569 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -2461,7 +2461,10 @@ %1$s. %2$s\n\n%3$s Munkamenet kijelzője Másolásmentes megjelenítés - Felbontás + Fekvő felbontás + Álló felbontás + Mint a fekvő (%1$d×%2$d) + Mint az álló (%1$d×%2$d) 16:9 játék illesztése Hogyan illeszkednek a 16:9 játékok ehhez a kijelzőhöz. A következő munkamenettől. Válassza a Képernyőhöz illesztést, vagy egy 16:9-nél szűkebb egyéni méretet. diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 67516678dc..1f36e35536 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -2436,7 +2436,10 @@ %1$s. %2$s\n\n%3$s Tampilan sesi Presentasi tanpa salin - Resolusi + Resolusi lanskap + Resolusi potret + Ikuti lanskap (%1$d×%2$d) + Ikuti potret (%1$d×%2$d) Penyesuaian gim 16:9 Cara gim 16:9 disesuaikan dengan tampilan ini. Berlaku pada sesi berikutnya. Pilih Sesuaikan layar atau ukuran khusus yang lebih sempit dari 16:9. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index ce0632f450..d41da79a4d 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -2478,7 +2478,10 @@ %1$s. %2$s\n\n%3$s Schermo della sessione Presentazione senza copia - Risoluzione + Risoluzione orizzontale + Risoluzione verticale + Come orizzontale (%1$d×%2$d) + Come verticale (%1$d×%2$d) Adattamento giochi 16:9 Come i giochi 16:9 si adattano a questo schermo. Dalla prossima sessione. Scegli Adatta allo schermo o una dimensione personalizzata più stretta di 16:9. diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 2b37a68447..130ef44453 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -2436,7 +2436,10 @@ %1$s。%2$s\n\n%3$s セッションの表示 ゼロコピー表示 - 解像度 + 横向きの解像度 + 縦向きの解像度 + 横向きに合わせる (%1$d×%2$d) + 縦向きに合わせる (%1$d×%2$d) 16:9ゲームの表示 16:9のゲームをこのディスプレイにどう合わせるか。次回のセッションから。 「画面に合わせる」か、16:9より縦長のカスタムサイズを選んでください。 diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index ca9a31ec99..267eff113e 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -2436,7 +2436,10 @@ %1$s. %2$s\n\n%3$s 세션 디스플레이 제로카피 표시 - 해상도 + 가로 해상도 + 세로 해상도 + 가로와 동일 (%1$d×%2$d) + 세로와 동일 (%1$d×%2$d) 16:9 게임 맞춤 16:9 게임을 이 디스플레이에 맞추는 방식입니다. 다음 세션부터 적용됩니다. 화면에 맞춤 또는 16:9보다 좁은 사용자 정의 크기를 선택하세요. diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index 769c6f2c7a..ccfcb1b69f 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -2436,7 +2436,10 @@ %1$s. %2$s\n\n%3$s Paparan sesi Paparan tanpa salinan - Resolusi + Resolusi landskap + Resolusi potret + Ikut landskap (%1$d×%2$d) + Ikut potret (%1$d×%2$d) Suaian permainan 16:9 Cara permainan 16:9 disuaikan ke paparan ini. Sesi seterusnya. Pilih Sepadan skrin atau saiz tersuai lebih nipis daripada 16:9. diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index 2533182c77..d9d6d76a62 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -2461,7 +2461,10 @@ %1$s. %2$s\n\n%3$s Sesjonsskjerm Presentasjon uten kopiering - Oppløsning + Oppløsning i liggende + Oppløsning i stående + Følg liggende (%1$d×%2$d) + Følg stående (%1$d×%2$d) 16:9-spilltilpasning Hvordan 16:9-spill tilpasses denne skjermen. Fra neste sesjon. Velg Tilpass skjerm eller en egendefinert størrelse smalere enn 16:9. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index be6d86c508..0f3ba678fc 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -2461,7 +2461,10 @@ %1$s. %2$s\n\n%3$s Sessiescherm Weergave zonder kopie - Resolutie + Resolutie in liggend + Resolutie in staand + Volg liggend (%1$d×%2$d) + Volg staand (%1$d×%2$d) 16:9-beeldvulling Hoe 16:9-games dit scherm vullen. Volgende sessie. Kies Schermformaat of een aangepast formaat dat smaller is dan 16:9. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 80486fc3cd..85b3ed455a 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -2513,7 +2513,10 @@ %1$s. %2$s\n\n%3$s Ekran sesji Prezentacja bez kopiowania - Rozdzielczość + Rozdzielczość w poziomie + Rozdzielczość w pionie + Jak w poziomie (%1$d×%2$d) + Jak w pionie (%1$d×%2$d) Dopasowanie gier 16:9 Jak gry 16:9 mieszczą się na tym ekranie. Od następnej sesji. Wybierz „Dopasuj do ekranu” lub własny rozmiar węższy niż 16:9. diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 19e92b33fd..44e3b263bf 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -2492,7 +2492,10 @@ %1$s. %2$s\n\n%3$s Ecrã da sessão Apresentação sem cópia - Resolução + Resolução na horizontal + Resolução na vertical + Igual à horizontal (%1$d×%2$d) + Igual à vertical (%1$d×%2$d) Ajuste de jogos 16:9 Como os jogos 16:9 se ajustam a este ecrã. Próxima sessão. Escolha «Igual ao ecrã» ou um tamanho personalizado mais estreito do que 16:9. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index aa4a3fec32..f745446219 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -2500,7 +2500,10 @@ %1$s. %2$s\n\n%3$s Tela da sessão Apresentação sem cópia - Resolução + Resolução na horizontal + Resolução na vertical + Igual à horizontal (%1$d×%2$d) + Igual à vertical (%1$d×%2$d) Ajuste de jogos 16:9 Como os jogos 16:9 se ajustam a esta tela. Na próxima sessão. Escolha Igual à tela ou um tamanho personalizado mais estreito que 16:9. diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index fa7ba56548..b43faecae5 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -2487,7 +2487,10 @@ %1$s. %2$s\n\n%3$s Afișajul sesiunii Prezentare fără copiere - Rezoluție + Rezoluție în peisaj + Rezoluție în portret + Ca peisajul (%1$d×%2$d) + Ca portretul (%1$d×%2$d) Potrivire joc 16:9 Cum se potrivesc jocurile 16:9 cu acest afișaj. Sesiunea următoare. Alege Potrivire ecran sau o dimensiune personalizată mai îngustă decât 16:9. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 1cf83c57c5..4de7f5cac9 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -2513,7 +2513,10 @@ %1$s. %2$s\n\n%3$s Экран сессии Вывод без копирования - Разрешение + Разрешение в альбомной ориентации + Разрешение в портретной ориентации + Как в альбомной (%1$d×%2$d) + Как в портретной (%1$d×%2$d) Игры 16:9 Как игры 16:9 вписываются в этот экран. Вступит в силу в следующей сессии. Выберите «По размеру экрана» или свой размер уже 16:9. diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 1669d9b650..e8b824c9c9 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -2461,7 +2461,10 @@ %1$s. %2$s\n\n%3$s Sessionsskärm Presentation utan kopiering - Upplösning + Upplösning i liggande + Upplösning i stående + Följ liggande (%1$d×%2$d) + Följ stående (%1$d×%2$d) 16:9-spelanpassning Hur 16:9-spel anpassas till den här skärmen. Nästa session. Välj Matcha skärmen eller en anpassad storlek som är smalare än 16:9. diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index d2067ebb29..34d772a59b 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -2436,7 +2436,10 @@ %1$s %2$s\n\n%3$s การแสดงผลของเซสชัน การแสดงผลแบบไม่คัดลอก - ความละเอียด + ความละเอียดแนวนอน + ความละเอียดแนวตั้ง + ตามแนวนอน (%1$d×%2$d) + ตามแนวตั้ง (%1$d×%2$d) การแสดงเกม 16:9 ให้พอดี วิธีที่เกม 16:9 แสดงพอดีกับหน้าจอนี้ มีผลในเซสชันถัดไป เลือกพอดีหน้าจอ หรือขนาดกำหนดเองที่แคบกว่า 16:9 diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 015e080979..725a568c15 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -2453,7 +2453,10 @@ %1$s. %2$s\n\n%3$s Oturum ekranı Kopyasız sunum - Çözünürlük + Yatay çözünürlük + Dikey çözünürlük + Yatayı izle (%1$d×%2$d) + Dikeyi izle (%1$d×%2$d) 16:9 oyun sığdırma 16:9 oyunların bu ekrana nasıl sığacağı. Sonraki oturumda. Ekrana Uydur\'u veya 16:9\'dan daha dar özel bir boyutu seçin. diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 0ae16d9a5d..cf0594346c 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -2513,7 +2513,10 @@ %1$s. %2$s\n\n%3$s Дисплей сеансу Показ без копіювання - Роздільна здатність + Роздільна здатність в альбомній орієнтації + Роздільна здатність у портретній орієнтації + Як в альбомній (%1$d×%2$d) + Як у портретній (%1$d×%2$d) Вписування гри 16:9 Як ігри 16:9 вписуються в цей дисплей. З наступного сеансу. Виберіть «Під екран» або власний розмір, вужчий за 16:9. diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index a2601eb6c1..290bf2b030 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -2436,7 +2436,10 @@ %1$s. %2$s\n\n%3$s Hiển thị phiên Hiển thị không sao chép - Độ phân giải + Độ phân giải chiều ngang + Độ phân giải chiều dọc + Theo chiều ngang (%1$d×%2$d) + Theo chiều dọc (%1$d×%2$d) Khớp game 16:9 Cách game 16:9 khớp với màn hình này. Từ phiên sau. Chọn Khớp màn hình hoặc một kích thước tùy chỉnh hẹp hơn 16:9. diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 802aa28274..70cda7d67e 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -2513,7 +2513,10 @@ %1$s。%2$s\n\n%3$s 会话显示 零拷贝呈现 - 分辨率 + 横屏分辨率 + 竖屏分辨率 + 跟随横屏 (%1$d×%2$d) + 跟随竖屏 (%1$d×%2$d) 16:9 游戏适配 16:9 游戏如何适配此屏幕。下次会话生效。 请选择“匹配屏幕”或比 16:9 更窄的自定义尺寸。 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index b7b9481b52..93608c774d 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -2433,7 +2433,10 @@ %1$s。%2$s\n\n%3$s 會話顯示 零複製呈現 - 解像度 + 橫向解析度 + 直向解析度 + 跟隨橫向 (%1$d×%2$d) + 跟隨直向 (%1$d×%2$d) 16:9 遊戲顯示方式 16:9 遊戲如何配合此螢幕。下次會話生效。 請選擇「配合螢幕」或比 16:9 更窄的自訂尺寸。 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 945485063e..5a8eaf443d 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -2433,7 +2433,10 @@ %1$s。%2$s\n\n%3$s 工作階段顯示 零複製呈現 - 解析度 + 橫向解析度 + 直向解析度 + 跟隨橫向 (%1$d×%2$d) + 跟隨直向 (%1$d×%2$d) 16:9 遊戲顯示方式 16:9 遊戲如何配合此螢幕。下次工作階段生效。 請選擇「符合螢幕」或比 16:9 更窄的自訂尺寸。 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 81d2a929e0..b8e92e2562 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -2718,7 +2718,10 @@ %1$s. %2$s\n\n%3$s Session display Zero-copy presentation - Resolution + Landscape resolution + Portrait resolution + Follow landscape (%1$d×%2$d) + Follow portrait (%1$d×%2$d) 16:9 game fit How 16:9 games fit this display. Next session. Choose Match screen or a custom size that isn\'t 16:9. diff --git a/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt b/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt new file mode 100644 index 0000000000..a589ac8be8 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt @@ -0,0 +1,73 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class PortraitResolutionTest { + private val app get() = RuntimeEnvironment.getApplication() + private val panel = 2400 to 1080 + + @Before fun clear() { + app.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() + } + + @Test fun portraitFollowsLandscapeUntilItIsSet() { + assertEquals(SessionDisplay.LINK_LANDSCAPE, SessionPrefs.resolutionStored(app, "steam", panel, true)) + SessionPrefs.setResolutionChoice(app, "steam", "900p") + assertEquals("900p", SessionPrefs.resolutionChoice(app, "steam", panel, false)) + assertEquals("900p", SessionPrefs.resolutionChoice(app, "steam", panel, true)) + } + + @Test fun eachOrientationKeepsItsOwnResolution() { + SessionPrefs.setResolutionChoice(app, "steam", "1600x720") + SessionPrefs.setResolutionChoice(app, "steam", "1080p", portrait = true) + assertEquals("1600x720", SessionPrefs.resolutionChoice(app, "steam", panel, false)) + assertEquals("1080p", SessionPrefs.resolutionChoice(app, "steam", panel, true)) + assertEquals("1080p", SessionPrefs.resolutionStored(app, "steam", panel, true)) + } + + @Test fun landscapeCanFollowPortrait() { + SessionPrefs.setResolutionChoice(app, "steam", "720x1280", portrait = true) + SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.LINK_PORTRAIT) + assertEquals(SessionDisplay.LINK_PORTRAIT, SessionPrefs.resolutionStored(app, "steam", panel, false)) + assertEquals("1280x720", SessionPrefs.resolutionChoice(app, "steam", panel, false)) + assertEquals("720x1280", SessionPrefs.resolutionChoice(app, "steam", panel, true)) + } + + @Test fun followingEachOtherNeverLoops() { + SessionPrefs.setResolutionChoice(app, "steam", "900p") + SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.LINK_PORTRAIT) + assertEquals("900p", SessionPrefs.resolutionChoice(app, "steam", panel, false)) + assertEquals("900p", SessionPrefs.resolutionChoice(app, "steam", panel, true)) + assertFalse(SessionDisplay.isLink(SessionPrefs.resolutionStored(app, "steam", panel, true))) + } + + @Test fun modesKeepSeparateChoices() { + SessionPrefs.setResolutionChoice(app, "steam", "1080p", portrait = true) + assertEquals(SessionDisplay.LINK_LANDSCAPE, SessionPrefs.resolutionStored(app, "lxqt", panel, true)) + } + + @Test fun resettingSettingsClearsThePortraitChoice() { + SessionPrefs.setResolutionChoice(app, "steam", "1080p", portrait = true) + assertTrue(SettingsReset.isSessionSetting("displayResolution.portrait.steam")) + } + + @Test fun effectiveChoiceFollowsTheOtherOrientation() { + val d = SessionDisplay + assertEquals("900p", d.effectiveChoice("900p", d.LINK_LANDSCAPE, true)) + assertEquals("1600x720", d.effectiveChoice("1600x720", "1080p", false)) + assertEquals("720x1600", d.effectiveChoice("1600x720", d.LINK_LANDSCAPE, true)) + assertEquals("1600x720", d.effectiveChoice(d.LINK_PORTRAIT, "720x1600", false)) + assertEquals(d.DEFAULT_RESOLUTION, d.effectiveChoice(d.LINK_PORTRAIT, d.LINK_LANDSCAPE, true)) + assertEquals("follow/2", d.effectiveChoice("follow/2", d.LINK_LANDSCAPE, true)) + assertEquals(d.MATCH_SCREEN, d.effectiveChoice(d.LINK_PORTRAIT, d.MATCH_SCREEN, false)) + } +} From a9054aac3f45f134b2e091d3f9028f36ba944894 Mon Sep 17 00:00:00 2001 From: FX192 <120828496+FX192@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:46:45 +0300 Subject: [PATCH 011/141] fix(session): address review on the landscape and portrait resolution split Accept generated portrait sizes on reload, use the right orientation and output target when deciding follow screen, show the real size behind each Follow option, treat a saved portrait Desktop resolution as chosen, and update the orientation hint in every locale. --- .../com/droiddeck/launcher/SessionActivity.kt | 16 ++++++++++++++-- .../droiddeck/launcher/session/SessionPrefs.kt | 10 +++++++--- .../droiddeck/launcher/ui/ModeSettingsDialog.kt | 8 ++++++-- .../com/droiddeck/launcher/ui/ResolutionRow.kt | 5 +++-- app/src/main/res/values-ar/strings.xml | 2 +- app/src/main/res/values-b+es+419/strings.xml | 2 +- app/src/main/res/values-bg/strings.xml | 2 +- app/src/main/res/values-cs/strings.xml | 2 +- app/src/main/res/values-da/strings.xml | 2 +- app/src/main/res/values-de/strings.xml | 2 +- app/src/main/res/values-el/strings.xml | 2 +- app/src/main/res/values-es/strings.xml | 2 +- app/src/main/res/values-fi/strings.xml | 2 +- app/src/main/res/values-fr/strings.xml | 2 +- app/src/main/res/values-hi/strings.xml | 2 +- app/src/main/res/values-hu/strings.xml | 2 +- app/src/main/res/values-in/strings.xml | 2 +- app/src/main/res/values-it/strings.xml | 2 +- app/src/main/res/values-ja/strings.xml | 2 +- app/src/main/res/values-ko/strings.xml | 2 +- app/src/main/res/values-ms/strings.xml | 2 +- app/src/main/res/values-nb/strings.xml | 2 +- app/src/main/res/values-nl/strings.xml | 2 +- app/src/main/res/values-pl/strings.xml | 2 +- app/src/main/res/values-pt-rPT/strings.xml | 2 +- app/src/main/res/values-pt/strings.xml | 2 +- app/src/main/res/values-ro/strings.xml | 2 +- app/src/main/res/values-ru/strings.xml | 2 +- app/src/main/res/values-sv/strings.xml | 2 +- app/src/main/res/values-th/strings.xml | 2 +- app/src/main/res/values-tr/strings.xml | 2 +- app/src/main/res/values-uk/strings.xml | 2 +- app/src/main/res/values-vi/strings.xml | 2 +- app/src/main/res/values-zh-rCN/strings.xml | 2 +- app/src/main/res/values-zh-rHK/strings.xml | 2 +- app/src/main/res/values-zh-rTW/strings.xml | 2 +- app/src/main/res/values/strings.xml | 2 +- .../launcher/session/PortraitResolutionTest.kt | 15 +++++++++++++++ 38 files changed, 78 insertions(+), 42 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index bc40319467..6028afe1ed 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -2956,16 +2956,28 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde WaylandCompositor.nativeResizeOutput(size.first, size.second) } + private fun followPortrait(): Boolean { + if (glassesScreen != null) return false + if (::sessionRoot.isInitialized && sessionRoot.width > 0) return portraitOutput() + val portraitWindow = SessionPrefs.portrait(this) + val panel = com.droiddeck.launcher.session.SessionDisplay.panelSize(this) + val long = maxOf(panel.first, panel.second) + val short = minOf(panel.first, panel.second) + val below = SessionPrefs.controlsBelowWanted(this, intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM, + if (portraitWindow) short else long, if (portraitWindow) long else short) + return portraitWindow && !below + } + private fun followScale(): Float { val mode = displayMode() - val choice = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this), portraitOutput()) + val choice = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this), followPortrait()) return com.droiddeck.launcher.session.SessionDisplay.followScale(choice) ?: 1f } private fun followChoice(): Boolean { val mode = displayMode() return com.droiddeck.launcher.session.SessionDisplay.isFollow( - SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this), portraitOutput())) + SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this), followPortrait())) } private fun applyFollowOrientation(config: android.content.res.Configuration) { diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index f243d3f31a..87f28dc8eb 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -1310,9 +1310,13 @@ object SessionPrefs { val value = prefs(context).getString("displayResolution.portrait.$mode", null) ?: return SessionDisplay.LINK_LANDSCAPE if (value == SessionDisplay.LINK_LANDSCAPE || value == SessionDisplay.MATCH_SCREEN || SessionDisplay.isFollow(value) || SessionDisplay.presetHeight(value) != null) return value - return parseResolution(value)?.let { "${it.first}x${it.second}" } ?: SessionDisplay.LINK_LANDSCAPE + return parseOrientedResolution(value)?.let { "${it.first}x${it.second}" } ?: SessionDisplay.LINK_LANDSCAPE } + private fun parseOrientedResolution(text: String): Pair? = + parseResolution(text) ?: text.trim().split('x', 'X', '×', '*').takeIf { it.size == 2 } + ?.let { parseResolution("${it[1]}x${it[0]}") }?.let { it.second to it.first } + private fun landscapeResolutionStored(context: Context, mode: String, panel: Pair): String { val saved = prefs(context) saved.getString("displayResolution.$mode", null)?.let { value -> @@ -1332,7 +1336,7 @@ object SessionPrefs { val link = if (portrait) SessionDisplay.LINK_LANDSCAPE else SessionDisplay.LINK_PORTRAIT val value = if (choice == link || choice == SessionDisplay.MATCH_SCREEN || SessionDisplay.isFollow(choice) || SessionDisplay.presetHeight(choice) != null) choice else { - val size = requireNotNull(parseResolution(choice)) { "Invalid resolution" } + val size = requireNotNull(if (portrait) parseOrientedResolution(choice) else parseResolution(choice)) { "Invalid resolution" } "${size.first}x${size.second}" } val panel = SessionDisplay.panelSize(context) @@ -1982,7 +1986,7 @@ object SessionPrefs { fun displayMode(context: Context, mode: String, program: String?): String = if (mode == SessionService.MODE_RUN && com.droiddeck.launcher.runtime.UserApps.launches(program) && - resolutionChosen(context, SessionService.MODE_DESKTOP)) SessionService.MODE_DESKTOP + (resolutionChosen(context, SessionService.MODE_DESKTOP) || resolutionChosen(context, SessionService.MODE_DESKTOP, true))) SessionService.MODE_DESKTOP else prefMode(mode) fun pipAutoEnter(context: Context): Boolean = prefs(context).getBoolean("pipAutoEnter", true) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt index 9d0933aa6a..dda562a583 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -243,9 +243,13 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: val displaySize = sessionDisplay.resolveChoice(s.panelSize, activeChoice, portrait) SettingsGroup(stringResource(R.string.display_session)) { ResolutionRow(host, "resolution", stringResource(R.string.display_resolution_landscape), s.resolution, landscapeChoice, - com.droiddeck.launcher.session.SessionDisplay.LINK_PORTRAIT, s.panelSize, a.onResolution, portrait = false) + com.droiddeck.launcher.session.SessionDisplay.LINK_PORTRAIT, + if (sessionDisplay.isLink(s.resolutionPortrait)) landscapeChoice else sessionDisplay.orientCustom(s.resolutionPortrait, false), + s.panelSize, a.onResolution, portrait = false) ResolutionRow(host, "resolution-portrait", stringResource(R.string.display_resolution_portrait), s.resolutionPortrait, portraitChoice, - com.droiddeck.launcher.session.SessionDisplay.LINK_LANDSCAPE, s.panelSize, a.onResolutionPortrait, portrait = true) + com.droiddeck.launcher.session.SessionDisplay.LINK_LANDSCAPE, + if (sessionDisplay.isLink(s.resolution)) portraitChoice else sessionDisplay.orientCustom(s.resolution, true), + s.panelSize, a.onResolutionPortrait, portrait = true) s.picturePosition?.let { position -> ChoiceRow(host, "picture-position", stringResource(R.string.display_picture_position), null, listOf("top" to stringResource(R.string.display_position_top), diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt b/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt index efcbbc526a..9a84adbe0a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt @@ -12,7 +12,7 @@ import com.droiddeck.launcher.session.SessionDisplay @Composable fun ResolutionRow( - host: MenuHost, id: String, title: String, stored: String, choice: String, link: String, + host: MenuHost, id: String, title: String, stored: String, choice: String, link: String, followTarget: String, panel: Pair, onPick: (String) -> Unit, chipModifier: Modifier = Modifier, portrait: Boolean = false, @@ -27,8 +27,9 @@ fun ResolutionRow( else if (size == screen) SessionDisplay.MATCH_SCREEN else choice var editCustom by remember { mutableStateOf(false) } var editFollow by remember { mutableStateOf(false) } + val followSize = SessionDisplay.resolveChoice(panel, followTarget, portrait) val linkLabel = stringResource(if (link == SessionDisplay.LINK_LANDSCAPE) R.string.display_follow_landscape else R.string.display_follow_portrait, - size.first, size.second) + followSize.first, followSize.second) val options = listOf(link to linkLabel) + choices.map { value -> val dimensions = SessionDisplay.resolveChoice(panel, value, portrait) value to if (value == SessionDisplay.MATCH_SCREEN) stringResource(R.string.display_match_screen, screen.first, screen.second) diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index b236ec7954..32f76cd6db 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -964,7 +964,7 @@ اتّباع تدوير الجهاز عمودي اتجاه الجلسة - يُطبَّق على Steam والألعاب وسطح المكتب ومحرّر وحدة التحكم. تدور الدقّات المُعدّة مسبقًا مع الجلسة، ويبقى العرض والارتفاع المخصّصان كما أُدخلا. + يُطبَّق على Steam والألعاب وسطح المكتب ومحرّر وحدة التحكم. تدور الدقّات المُعدّة مسبقًا مع الجلسة، وعندما يتبع أحد الاتجاهين الآخر ينعكس العرض والارتفاع المخصّصان ليتطابقا. أفقي تلقائي أفقي أفقي معكوس diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index c1505584fc..e0dda7fdc0 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -982,7 +982,7 @@ Seguir la rotación del dispositivo Vertical Orientación de la sesión - Se aplica a Steam, los juegos, el escritorio y el editor de controles. Los ajustes predefinidos de resolución giran con la sesión; el ancho y el alto personalizados se mantienen como se ingresaron. + Se aplica a Steam, los juegos, el escritorio y el editor de controles. Los ajustes predefinidos de resolución giran con la sesión; cuando una orientación sigue a la otra, el ancho y el alto personalizados se invierten para coincidir. Horizontal automática Horizontal Horizontal invertida diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index dc9116e960..0fdc0b1918 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -952,7 +952,7 @@ Следва завъртането на устройството Вертикална Ориентация на сесията - Прилага се за Steam, игрите, работния плот и редактора на контролера. Предварително зададените резолюции се завъртат със сесията; персонализираните ширина и височина остават както са въведени. + Прилага се за Steam, игрите, работния плот и редактора на контролера. Предварително зададените резолюции се завъртат със сесията; когато едната ориентация следва другата, персонализираните ширина и височина се разменят, за да съвпадат. Автоматичен хоризонтален Хоризонтална Обърната хоризонтална diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index d566a893f5..59d74654f3 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -958,7 +958,7 @@ Podle otočení zařízení Na výšku Orientace relace - Platí pro Steam, hry, Plochu a editor ovladače. Předvolby rozlišení se otáčejí s relací; vlastní šířka a výška zůstávají, jak jsou zadány. + Platí pro Steam, hry, Plochu a editor ovladače. Předvolby rozlišení se otáčejí s relací; když jedna orientace sleduje druhou, vlastní šířka a výška se prohodí, aby odpovídaly. Automaticky na šířku Na šířku Na šířku obráceně diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index e1c48d2cc7..9964a06315 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -952,7 +952,7 @@ Følg enhedens rotation Stående Sessionens retning - Gælder Steam, spil, skrivebordet og controllereditoren. Opløsningsforudindstillinger roterer med sessionen; brugerdefineret bredde og højde forbliver som angivet. + Gælder Steam, spil, skrivebordet og controllereditoren. Opløsningsforudindstillinger roterer med sessionen; når den ene orientering følger den anden, byttes brugerdefineret bredde og højde, så de passer. Automatisk liggende Liggende Omvendt liggende diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index f986336c08..bcb221a120 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -944,7 +944,7 @@ Gerätedrehung folgen Hochformat Sitzungsausrichtung - Gilt für Steam, Spiele, Desktop und den Controller-Editor. Auflösungsvoreinstellungen drehen sich mit der Sitzung; eigene Breite und Höhe bleiben wie eingegeben. + Gilt für Steam, Spiele, Desktop und den Controller-Editor. Auflösungsvoreinstellungen drehen sich mit der Sitzung; folgt eine Ausrichtung der anderen, werden eigene Breite und Höhe passend vertauscht. Automatisch Querformat Querformat Umgekehrtes Querformat diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 47cddc9a95..f5bd31d63c 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -952,7 +952,7 @@ Ακολουθεί την περιστροφή της συσκευής Κατακόρυφος Προσανατολισμός συνεδρίας - Ισχύει για το Steam, τα παιχνίδια, την επιφάνεια εργασίας και τον επεξεργαστή χειριστηρίου. Οι προκαθορισμένες αναλύσεις περιστρέφονται με τη συνεδρία· το προσαρμοσμένο πλάτος και ύψος μένουν όπως καταχωρίστηκαν. + Ισχύει για το Steam, τα παιχνίδια, την επιφάνεια εργασίας και τον επεξεργαστή χειριστηρίου. Οι προκαθορισμένες αναλύσεις περιστρέφονται με τη συνεδρία· όταν ένας προσανατολισμός ακολουθεί τον άλλον, το προσαρμοσμένο πλάτος και ύψος αντιστρέφονται ώστε να ταιριάζουν. Αυτόματος οριζόντιος προσανατολισμός Οριζόντιος προσανατολισμός Αντίστροφος οριζόντιος προσανατολισμός diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 637678281f..47a00a8435 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -955,7 +955,7 @@ Seguir la rotación del dispositivo Vertical Orientación de la sesión - Se aplica a Steam, los juegos, el escritorio y el editor de mandos. Los ajustes predefinidos de resolución giran con la sesión; el ancho y el alto personalizados se mantienen como se introdujeron. + Se aplica a Steam, los juegos, el escritorio y el editor de mandos. Los ajustes predefinidos de resolución giran con la sesión; cuando una orientación sigue a la otra, el ancho y el alto personalizados se invierten para coincidir. Horizontal automática Horizontal Horizontal invertida diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 47d447af21..64792a6d6d 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -952,7 +952,7 @@ Seuraa laitteen kiertoa Pystysuunta Istunnon suunta - Koskee Steamia, pelejä, työpöytää ja ohjainmuokkainta. Resoluution esiasetukset kääntyvät istunnon mukana; mukautettu leveys ja korkeus pysyvät syötetyn mukaisina. + Koskee Steamia, pelejä, työpöytää ja ohjainmuokkainta. Resoluution esiasetukset kääntyvät istunnon mukana; kun toinen suunta seuraa toista, mukautettu leveys ja korkeus vaihtavat paikkaa vastaamaan toisiaan. Automaattinen vaakasuunta Vaakasuunta Käänteinen vaakasuunta diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index ae3d8f72bd..ee7bbbb419 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -955,7 +955,7 @@ Suivre la rotation de l\'appareil Portrait Orientation de la session - S\'applique à Steam, aux jeux, au bureau et à l\'éditeur de manette. Les préréglages de résolution pivotent avec la session ; la largeur et la hauteur personnalisées restent telles que saisies. + S\'applique à Steam, aux jeux, au bureau et à l\'éditeur de manette. Les préréglages de résolution pivotent avec la session ; lorsqu\'une orientation suit l\'autre, la largeur et la hauteur personnalisées sont inversées pour correspondre. Paysage automatique Paysage Paysage inversé diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 109385a8ec..be2c9d973e 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -952,7 +952,7 @@ डिवाइस रोटेशन के अनुसार पोर्ट्रेट सेशन ओरिएंटेशन - Steam, गेम, डेस्कटॉप और कंट्रोलर एडिटर पर लागू होता है। रिज़ॉल्यूशन प्रीसेट सेशन के साथ घूमते हैं; कस्टम चौड़ाई और ऊंचाई जैसी डाली गई वैसी ही रहती हैं। + Steam, गेम, डेस्कटॉप और कंट्रोलर एडिटर पर लागू होता है। रिज़ॉल्यूशन प्रीसेट सेशन के साथ घूमते हैं; जब एक ओरिएंटेशन दूसरे को फ़ॉलो करता है, तो कस्टम चौड़ाई और ऊंचाई बदलकर मेल खाती हैं। ऑटोमैटिक लैंडस्केप लैंडस्केप उलटा लैंडस्केप diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index d512c72569..2cb432d717 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -952,7 +952,7 @@ Az eszköz elforgatásának követése Álló Munkamenet tájolása - A Steamre, a játékokra, az asztalra és a kontrollerszerkesztőre vonatkozik. A felbontás-előbeállítások a munkamenettel együtt forognak; az egyéni szélesség és magasság a megadott módon marad. + A Steamre, a játékokra, az asztalra és a kontrollerszerkesztőre vonatkozik. A felbontás-előbeállítások a munkamenettel együtt forognak; ha az egyik tájolás a másikat követi, az egyéni szélesség és magasság felcserélődik. Automatikus fekvő Fekvő Fordított fekvő diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 1f36e35536..c8449cb389 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -949,7 +949,7 @@ Ikuti rotasi perangkat Potret Orientasi sesi - Berlaku untuk Steam, gim, desktop, dan editor pengontrol. Preset resolusi ikut berputar dengan sesi; lebar dan tinggi kustom tetap seperti yang dimasukkan. + Berlaku untuk Steam, gim, desktop, dan editor pengontrol. Preset resolusi ikut berputar dengan sesi; saat satu orientasi mengikuti yang lain, lebar dan tinggi kustom ditukar agar sesuai. Lanskap otomatis Lanskap Lanskap terbalik diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index d41da79a4d..51f13aee73 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -947,7 +947,7 @@ Segui la rotazione del dispositivo Verticale Orientamento della sessione - Si applica a Steam, ai giochi, al desktop e all\'editor del controller. I preset di risoluzione ruotano con la sessione; larghezza e altezza personalizzate restano come inserite. + Si applica a Steam, ai giochi, al desktop e all\'editor del controller. I preset di risoluzione ruotano con la sessione; quando un\'orientamento segue l\'altro, larghezza e altezza personalizzate vengono invertite per corrispondere. Orizzontale automatico Orizzontale Orizzontale invertito diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 130ef44453..ea088f306b 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -949,7 +949,7 @@ デバイスの回転に合わせる 縦向き セッションの向き - Steam、ゲーム、デスクトップ、コントローラーエディターに適用されます。解像度プリセットはセッションに合わせて回転し、カスタムの幅と高さは入力したとおりになります。 + Steam、ゲーム、デスクトップ、コントローラーエディターに適用されます。解像度プリセットはセッションに合わせて回転し、一方の向きがもう一方に従う場合、カスタムの幅と高さは向きに合わせて入れ替わります。 横向き(自動回転) 横向き 横向き(反転) diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 267eff113e..96ee8f2ab4 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -949,7 +949,7 @@ 기기 회전 따르기 세로 세션 방향 - Steam, 게임, 데스크톱 및 컨트롤러 편집기에 적용됩니다. 해상도 프리셋은 세션에 맞춰 회전하며, 사용자 정의 너비와 높이는 입력한 그대로 유지됩니다. + Steam, 게임, 데스크톱 및 컨트롤러 편집기에 적용됩니다. 해상도 프리셋은 세션에 맞춰 회전하며, 한 방향이 다른 방향을 따를 때 사용자 정의 너비와 높이는 방향에 맞게 서로 바뀝니다. 자동 가로 모드 가로 모드 역방향 가로 모드 diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index ccfcb1b69f..0ad66431af 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -949,7 +949,7 @@ Ikut putaran peranti Potret Orientasi sesi - Berkuat kuasa pada Steam, permainan, desktop dan editor pengawal. Pratetap resolusi berputar bersama sesi; lebar dan tinggi tersuai kekal seperti yang dimasukkan. + Berkuat kuasa pada Steam, permainan, desktop dan editor pengawal. Pratetap resolusi berputar bersama sesi; apabila satu orientasi mengikuti yang lain, lebar dan tinggi tersuai ditukar supaya sepadan. Lanskap automatik Lanskap Lanskap songsang diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index d9d6d76a62..9f2085f5ec 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -952,7 +952,7 @@ Følg enhetens rotasjon Stående Retning for sesjonen - Gjelder Steam, spill, skrivebordet og kontrollerredigeringen. Forhåndsinnstilte oppløsninger roterer med sesjonen; egendefinert bredde og høyde forblir som angitt. + Gjelder Steam, spill, skrivebordet og kontrollerredigeringen. Forhåndsinnstilte oppløsninger roterer med sesjonen; når én retning følger den andre, byttes egendefinert bredde og høyde slik at de passer. Automatisk liggende Liggende Omvendt liggende diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 0f3ba678fc..9e00bc86e3 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -952,7 +952,7 @@ Apparaatrotatie volgen Staand Oriëntatie van sessie - Geldt voor Steam, games, desktop en de controllereditor. Resolutievoorinstellingen draaien mee met de sessie; aangepaste breedte en hoogte blijven zoals ingevoerd. + Geldt voor Steam, games, desktop en de controllereditor. Resolutievoorinstellingen draaien mee met de sessie; als de ene oriëntatie de andere volgt, worden aangepaste breedte en hoogte omgewisseld. Automatisch liggend Liggend Liggend omgekeerd diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 85b3ed455a..25768ef8f7 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -958,7 +958,7 @@ Zgodnie z obrotem urządzenia Pionowa Orientacja sesji - Dotyczy Steam, gier, pulpitu i edytora kontrolera. Presety rozdzielczości obracają się z sesją; własna szerokość i wysokość pozostają jak wpisano. + Dotyczy Steam, gier, pulpitu i edytora kontrolera. Presety rozdzielczości obracają się z sesją; gdy jedna orientacja podąża za drugą, własna szerokość i wysokość są zamieniane. Automatyczna pozioma Pozioma Odwrócona pozioma diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 44e3b263bf..51ea157863 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -947,7 +947,7 @@ Seguir a rotação do dispositivo Vertical Orientação da sessão - Aplica-se ao Steam, aos jogos, ao ambiente de trabalho e ao editor de comandos. As predefinições de resolução rodam com a sessão; a largura e a altura personalizadas ficam como foram introduzidas. + Aplica-se ao Steam, aos jogos, ao ambiente de trabalho e ao editor de comandos. As predefinições de resolução rodam com a sessão; quando uma orientação segue a outra, a largura e a altura personalizadas são trocadas para corresponder. Horizontal automática Horizontal Horizontal invertida diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index f745446219..c10d3cfa7c 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -954,7 +954,7 @@ Seguir a rotação do dispositivo Retrato Orientação da sessão - Vale para a Steam, os jogos, a área de trabalho e o editor de controle. As predefinições de resolução giram com a sessão; largura e altura personalizadas ficam como foram digitadas. + Vale para a Steam, os jogos, a área de trabalho e o editor de controle. As predefinições de resolução giram com a sessão; quando uma orientação segue a outra, largura e altura personalizadas são trocadas para corresponder. Paisagem automática Paisagem Paisagem invertida diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index b43faecae5..e74bec3b84 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -955,7 +955,7 @@ Urmează rotirea dispozitivului Portret Orientarea sesiunii - Se aplică pentru Steam, jocuri, desktop și editorul de controller. Presetările de rezoluție se rotesc odată cu sesiunea; lățimea și înălțimea personalizate rămân cum au fost introduse. + Se aplică pentru Steam, jocuri, desktop și editorul de controller. Presetările de rezoluție se rotesc odată cu sesiunea; când o orientare o urmează pe cealaltă, lățimea și înălțimea personalizate se inversează pentru a se potrivi. Peisaj automat Peisaj Peisaj inversat diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 4de7f5cac9..de792927ec 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -958,7 +958,7 @@ Следовать повороту устройства Портретная Ориентация сессии - Применяется к Steam, играм, рабочему столу и редактору контроллера. Предустановки разрешения поворачиваются вместе с сессией; свои ширина и высота остаются как введены. + Применяется к Steam, играм, рабочему столу и редактору контроллера. Предустановки разрешения поворачиваются вместе с сессией; когда одна ориентация следует за другой, свои ширина и высота меняются местами. Альбомная (авто) Альбомная Перевернутая альбомная diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index e8b824c9c9..8e951147a9 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -952,7 +952,7 @@ Följ enhetens rotation Stående Sessionens orientering - Gäller Steam, spel, skrivbordet och kontrollredigeraren. Upplösningsförinställningar roterar med sessionen; anpassad bredd och höjd förblir som angivet. + Gäller Steam, spel, skrivbordet och kontrollredigeraren. Upplösningsförinställningar roterar med sessionen; när en orientering följer den andra byts anpassad bredd och höjd så att de passar. Automatiskt liggande Liggande Liggande, upp och ned diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 34d772a59b..1a826fcb28 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -949,7 +949,7 @@ หมุนตามอุปกรณ์ แนวตั้ง การวางแนวของเซสชัน - มีผลกับ Steam เกม เดสก์ท็อป และตัวแก้ไขคอนโทรลเลอร์ ค่าความละเอียดที่ตั้งไว้ล่วงหน้าจะหมุนตามเซสชัน ส่วนความกว้างและความสูงที่กำหนดเองจะคงตามที่ป้อนไว้ + มีผลกับ Steam เกม เดสก์ท็อป และตัวแก้ไขคอนโทรลเลอร์ ค่าความละเอียดที่ตั้งไว้ล่วงหน้าจะหมุนตามเซสชัน เมื่อแนวหนึ่งตามอีกแนวหนึ่ง ความกว้างและความสูงที่กำหนดเองจะสลับกันให้ตรงกัน แนวนอนอัตโนมัติ แนวนอน แนวนอนกลับด้าน diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 725a568c15..3644798c45 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -944,7 +944,7 @@ Cihaz dönüşünü izle Dikey Oturum yönü - Steam, oyunlar, masaüstü ve kumanda düzenleyicisi için geçerlidir. Çözünürlük ön ayarları oturumla birlikte döner; özel genişlik ve yükseklik girildiği gibi kalır. + Steam, oyunlar, masaüstü ve kumanda düzenleyicisi için geçerlidir. Çözünürlük ön ayarları oturumla birlikte döner; bir yön diğerini izlediğinde özel genişlik ve yükseklik eşleşmek üzere yer değiştirir. Otomatik yatay Yatay Ters yatay diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index cf0594346c..6f67409b1a 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -958,7 +958,7 @@ Слідувати повороту пристрою Книжкова Орієнтація сеансу - Застосовується до Steam, ігор, робочого столу й редактора контролера. Готові роздільні здатності повертаються разом із сеансом; власні ширина й висота залишаються як введено. + Застосовується до Steam, ігор, робочого столу й редактора контролера. Готові роздільні здатності повертаються разом із сеансом; коли одна орієнтація слідує за іншою, власні ширина й висота міняються місцями. Автоматично альбомна Альбомна Перевернута альбомна diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 290bf2b030..5c5d7e4077 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -949,7 +949,7 @@ Theo hướng xoay thiết bị Dọc Hướng màn hình phiên - Áp dụng cho Steam, game, desktop và trình chỉnh sửa tay cầm. Độ phân giải đặt sẵn xoay theo phiên; chiều rộng và chiều cao tùy chỉnh giữ nguyên như đã nhập. + Áp dụng cho Steam, game, desktop và trình chỉnh sửa tay cầm. Độ phân giải đặt sẵn xoay theo phiên; khi một hướng theo hướng còn lại, chiều rộng và chiều cao tùy chỉnh được hoán đổi cho khớp. Ngang tự động Ngang Ngang ngược diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 70cda7d67e..1d181502b1 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -949,7 +949,7 @@ 跟随设备旋转 竖屏 会话方向 - 适用于 Steam、游戏、桌面和手柄编辑器。分辨率预设会随会话旋转;自定义宽度和高度保持输入值不变。 + 适用于 Steam、游戏、桌面和手柄编辑器。分辨率预设会随会话旋转;当一个方向跟随另一个方向时,自定义宽度和高度会互换以保持一致。 自动横屏 横屏 反向横屏 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 93608c774d..a4d0cca3f2 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -948,7 +948,7 @@ 跟隨裝置旋轉 直向 會話方向 - 套用至 Steam、遊戲、桌面和控制器編輯器。解像度預設會隨會話旋轉;自訂的寬度和高度則維持輸入值。 + 套用至 Steam、遊戲、桌面和控制器編輯器。解像度預設會隨會話旋轉;當一個方向跟隨另一個方向時,自訂的寬度和高度會互換以保持一致。 自動橫向 橫向 反向橫向 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 5a8eaf443d..b0462383cf 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -948,7 +948,7 @@ 跟隨裝置旋轉 直向 工作階段方向 - 套用至 Steam、遊戲、桌面和控制器編輯器。解析度預設會隨工作階段旋轉;自訂的寬度和高度則維持輸入值。 + 套用至 Steam、遊戲、桌面和控制器編輯器。解析度預設會隨工作階段旋轉;當一個方向跟隨另一個方向時,自訂的寬度和高度會互換以保持一致。 自動橫向 橫向 反向橫向 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index b8e92e2562..b6e0aca8e1 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1025,7 +1025,7 @@ Follow device rotation Portrait Session orientation - Applies to Steam, games, desktop, and the controller editor. Resolution presets rotate with the session; custom width and height stay as entered. + Applies to Steam, games, desktop, and the controller editor. Resolution presets rotate with the session; when one orientation follows the other, custom width and height flip to match. Automatic landscape Landscape Reverse landscape diff --git a/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt b/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt index a589ac8be8..503e260869 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt @@ -50,6 +50,21 @@ class PortraitResolutionTest { assertFalse(SessionDisplay.isLink(SessionPrefs.resolutionStored(app, "steam", panel, true))) } + @Test fun aGeneratedPortraitSizeSurvivesAReload() { + SessionPrefs.setResolutionChoice(app, "steam", "2560x1440") + SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.LINK_PORTRAIT) + assertEquals("1440x2560", SessionPrefs.resolutionStored(app, "steam", panel, true)) + assertEquals("2560x1440", SessionPrefs.resolutionChoice(app, "steam", panel, false)) + assertEquals("1440x2560", SessionPrefs.resolutionChoice(app, "steam", panel, true)) + } + + @Test fun aSavedDesktopResolutionInEitherOrientationCountsAsChosen() { + SessionPrefs.setResolutionChoice(app, SessionService.MODE_DESKTOP, "1080p", portrait = true) + assertTrue(SessionPrefs.resolutionChosen(app, SessionService.MODE_DESKTOP, true)) + assertEquals(SessionService.MODE_DESKTOP, + SessionPrefs.displayMode(app, SessionService.MODE_RUN, com.droiddeck.launcher.runtime.UserApps.SCRIPT_LAUNCHER)) + } + @Test fun modesKeepSeparateChoices() { SessionPrefs.setResolutionChoice(app, "steam", "1080p", portrait = true) assertEquals(SessionDisplay.LINK_LANDSCAPE, SessionPrefs.resolutionStored(app, "lxqt", panel, true)) From 567181d05fe2637fc87a07d46ca4216ab010fcf5 Mon Sep 17 00:00:00 2001 From: FX192 <120828496+FX192@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:56:29 +0300 Subject: [PATCH 012/141] fix(session): let the portrait custom resolution dialog accept tall sizes --- .../java/com/droiddeck/launcher/session/SessionPrefs.kt | 2 +- .../java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt | 4 ++-- .../main/java/com/droiddeck/launcher/ui/ResolutionRow.kt | 2 +- .../droiddeck/launcher/session/PortraitResolutionTest.kt | 9 +++++++++ 4 files changed, 13 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 87f28dc8eb..c3ce0da60b 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -1313,7 +1313,7 @@ object SessionPrefs { return parseOrientedResolution(value)?.let { "${it.first}x${it.second}" } ?: SessionDisplay.LINK_LANDSCAPE } - private fun parseOrientedResolution(text: String): Pair? = + fun parseOrientedResolution(text: String): Pair? = parseResolution(text) ?: text.trim().split('x', 'X', '×', '*').takeIf { it.size == 2 } ?.let { parseResolution("${it[1]}x${it[0]}") }?.let { it.second to it.first } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt index dda562a583..3218579f8a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -720,10 +720,10 @@ internal fun SgdbKeyDialog(hasKey: Boolean, onSave: (String) -> Unit, onDismiss: @OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class) @Composable -internal fun CustomResolutionDialog(initial: Pair?, onSave: (Pair) -> Unit, onDismiss: () -> Unit) { +internal fun CustomResolutionDialog(initial: Pair?, onSave: (Pair) -> Unit, onDismiss: () -> Unit, portrait: Boolean = false) { var w by remember { mutableStateOf(initial?.first?.toString() ?: "") } var h by remember { mutableStateOf(initial?.second?.toString() ?: "") } - val parsed = SessionPrefs.parseResolution("${w}x$h") + val parsed = if (portrait) SessionPrefs.parseOrientedResolution("${w}x$h") else SessionPrefs.parseResolution("${w}x$h") com.droiddeck.launcher.ui.GlideAlertDialog( onDismissRequest = onDismiss, title = { Text(stringResource(R.string.mode_custom_res_title)) }, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt b/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt index 9a84adbe0a..ca9ca5976c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt @@ -51,7 +51,7 @@ fun ResolutionRow( else onPick(value) }) if (editCustom) CustomResolutionDialog(size, onSave = { value -> editCustom = false; onPick("${value.first}x${value.second}") }, - onDismiss = { editCustom = false }) + onDismiss = { editCustom = false }, portrait = portrait) if (editFollow) CustomFollowScaleDialog(SessionDisplay.followScale(choice)?.takeIf { it > 1f }, onSave = { value -> editFollow = false; onPick(SessionDisplay.followScaled(value)) }, onDismiss = { editFollow = false }) diff --git a/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt b/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt index 503e260869..fb9199157b 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt @@ -65,6 +65,15 @@ class PortraitResolutionTest { SessionPrefs.displayMode(app, SessionService.MODE_RUN, com.droiddeck.launcher.runtime.UserApps.SCRIPT_LAUNCHER)) } + @Test fun portraitInputAcceptsTallSizesLandscapeInputDoesNot() { + assertNull(SessionPrefs.parseResolution("1440x2560")) + assertEquals(1440 to 2560, SessionPrefs.parseOrientedResolution("1440x2560")) + assertEquals(1280 to 720, SessionPrefs.parseOrientedResolution("1280x720")) + assertNull(SessionPrefs.parseOrientedResolution("100x100")) + SessionPrefs.setResolutionChoice(app, "steam", "1440x2560", portrait = true) + assertEquals("1440x2560", SessionPrefs.resolutionStored(app, "steam", panel, true)) + } + @Test fun modesKeepSeparateChoices() { SessionPrefs.setResolutionChoice(app, "steam", "1080p", portrait = true) assertEquals(SessionDisplay.LINK_LANDSCAPE, SessionPrefs.resolutionStored(app, "lxqt", panel, true)) From 31dd8f998734ffe17f0554818c4d667cca3b30d0 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:25:45 -0500 Subject: [PATCH 013/141] feat(session): arrange and hide in-session menu pages, round pinned end-session button (#2989) * feat(session): arrange and hide the in-session menu pages * fix(session): the end-session button is a true circle pinned to the right of the menu header * fix(session): arrange-pages drag reads the current list; reset reloads the page layout even if the activity was recreated * fix(session): Back leaves Arrange pages first; UI zoo previews don't save page layout * fix(session): Back on a grabbed page row restores its order before anything else --- .../main/java/com/droiddeck/launcher/App.kt | 1 + .../droiddeck/launcher/FrontEndActivity.kt | 1 + .../launcher/session/SessionPrefs.kt | 12 +++ .../launcher/session/SettingsReset.kt | 2 +- .../launcher/ui/ManageDrawerPages.kt | 93 +++++++++++++++++++ .../com/droiddeck/launcher/ui/ManageStores.kt | 6 +- .../launcher/ui/SessionDrawerPage.kt | 65 ++++++++++++- .../droiddeck/launcher/ui/SessionOverlay.kt | 44 ++++++--- .../com/droiddeck/launcher/ui/TabsSettings.kt | 5 + app/src/main/res/values/strings.xml | 3 + .../launcher/ui/SessionDrawerPageTest.kt | 13 +++ 11 files changed, 227 insertions(+), 18 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/ui/ManageDrawerPages.kt diff --git a/app/src/main/java/com/droiddeck/launcher/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt index e02bbc9d2d..be2deadbed 100644 --- a/app/src/main/java/com/droiddeck/launcher/App.kt +++ b/app/src/main/java/com/droiddeck/launcher/App.kt @@ -46,6 +46,7 @@ class App : Application() { com.droiddeck.launcher.input.ShortcutsRelay.Holder.install(this) com.droiddeck.launcher.agent.AgentHost.refresh(this) com.droiddeck.launcher.ui.NavTabs.load(this) + com.droiddeck.launcher.ui.DrawerPages.load(this) com.droiddeck.launcher.ui.DeveloperTools.load(this) com.droiddeck.launcher.ui.AgentPet.install(this) if (com.droiddeck.launcher.agent.AgentTab.visible) com.droiddeck.launcher.lab.LabNotice.openOnInstall = "agent" diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index ca5e23cefe..010d503be4 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -3343,6 +3343,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet Thread({ val ok = com.droiddeck.launcher.session.SettingsReset.resetAll(this, gameProfiles, scopes) ui.post { + com.droiddeck.launcher.ui.DrawerPages.load(applicationContext) if (isDestroyed) return@post com.droiddeck.launcher.core.AppLanguage.setChosen(this, com.droiddeck.launcher.core.AppLanguage.SYSTEM) if (!ok) android.widget.Toast.makeText(this, R.string.setup_reset_settings_partial, android.widget.Toast.LENGTH_LONG).show() diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 09c0b781ec..1376517288 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -419,6 +419,18 @@ object SessionPrefs { e.remove("gameStoresEnabled").remove("soundtracksEnabled").remove("agentTab").putInt("navTabLayout", version).apply() } + fun drawerPageOrder(context: Context): List = idList(prefs(context).getString("drawerPageOrder", null)) + + fun setDrawerPageOrder(context: Context, order: List) { + prefs(context).edit().putString("drawerPageOrder", order.joinToString(",")).apply() + } + + fun drawerPageHidden(context: Context): Set = idList(prefs(context).getString("drawerPageHidden", null)).toSet() + + fun setDrawerPageHidden(context: Context, keys: Set) { + prefs(context).edit().putString("drawerPageHidden", keys.joinToString(",")).apply() + } + fun setNavTabHidden(context: Context, keys: Set) { prefs(context).edit().putString("navTabHidden", keys.joinToString(",")).apply() } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt index d2963582e6..b2ca79e52b 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt @@ -18,7 +18,7 @@ object SettingsReset { "storesInstallLanguage", "hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController", "gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController", - "stretch16x9", "avoidNotch", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys", + "stretch16x9", "avoidNotch", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "drawerPageOrder", "drawerPageHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys", "gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop", "tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores", "directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus", diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ManageDrawerPages.kt b/app/src/main/java/com/droiddeck/launcher/ui/ManageDrawerPages.kt new file mode 100644 index 0000000000..30a9c554f9 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/ManageDrawerPages.kt @@ -0,0 +1,93 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.DragHandle +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.focus.focusProperties +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.activity.compose.BackHandler +import com.droiddeck.launcher.R + +@Composable +internal fun ManageDrawerPages(offeredNow: List, modifier: Modifier = Modifier, releaseSignal: Int = 0, onDone: () -> Unit) { + val ctx = LocalContext.current + val current by rememberUpdatedState(offeredNow) + val previewing = DevPreview.drawer != null + DisposableEffect(Unit) { onDispose { DrawerPages.heldFrom = null } } + DisposableEffect(previewing) { onDispose { if (previewing) DrawerPages.load(ctx) } } + val colors = MaterialTheme.colorScheme + BackHandler { onDone() } + Column(modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + stringResource(R.string.drawer_manage_pages), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, + color = colors.onBackground, modifier = Modifier.weight(1f), + ) + if (!DrawerPages.isDefault()) DrawerOutlineButton(stringResource(R.string.drawer_pages_reset)) { DrawerPages.reset(ctx) } + Spacer(Modifier.width(8.dp)) + DrawerOutlineButton(stringResource(R.string.drawer_pages_done), onClick = onDone) + } + SortableRows( + rows = { current.map { it.name } }, + commit = { names -> DrawerPages.rearrange(ctx, names.mapNotNull { n -> current.firstOrNull { it.name == n } }) }, + movable = { true }, + rowHeight = STORE_ROW, handleWidth = STORE_HANDLE, + releaseSignal = releaseSignal, + onGrab = { before -> DrawerPages.heldFrom = before?.mapNotNull { n -> current.firstOrNull { it.name == n } } }, + onActivate = { name -> + current.firstOrNull { it.name == name }?.let { DrawerPages.setHidden(ctx, it, it !in DrawerPages.hidden) } + }, + ) { name, held, offset, hint, rowModifier, onFocus -> + val page = current.first { it.name == name } + val shown = page !in DrawerPages.hidden + val pal = LocalPalette.current + val label = stringResource(page.title) + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + SortRowFrame(held, offset, rowModifier.testTag("drawer-page-row-$name"), hot, src, onFocus) { + Box(contentAlignment = Alignment.Center, modifier = Modifier.size(width = STORE_HANDLE, height = STORE_ROW)) { + Icon(Icons.Filled.DragHandle, null, tint = if (held) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) + } + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier.weight(1f).alpha(if (shown) 1f else 0.5f), + ) { + Icon(page.icon, null, tint = colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) + Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + if (hint != null) KeyHint("Y", hint) + ToggleSwitch( + shown, DrawerPages.hideable(page), label, + Modifier.testTag("drawer-page-shown-$name").focusProperties { canFocus = false }, + ) { DrawerPages.setHidden(ctx, page, !it) } + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt b/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt index 7e732d4fe4..39c4badb7e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt @@ -221,8 +221,8 @@ internal fun SideSheet(open: Boolean, onClose: () -> Unit, returnFocus: FocusReq } } -private val STORE_ROW = 60.dp -private val STORE_HANDLE = 44.dp +internal val STORE_ROW = 60.dp +internal val STORE_HANDLE = 44.dp @Composable internal fun ManageStoresSheet() { @@ -302,7 +302,7 @@ private fun StoreSortRow( } @Composable -private fun SortRowFrame( +internal fun SortRowFrame( held: Boolean, offset: Float, modifier: Modifier, hot: Boolean, src: MutableInteractionSource, onFocus: (Boolean) -> Unit, content: @Composable androidx.compose.foundation.layout.RowScope.() -> Unit, ) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt index 3751702897..5dd8ba682f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt @@ -1,5 +1,11 @@ package com.droiddeck.launcher.ui +import android.content.Context +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import com.droiddeck.launcher.session.SessionPrefs + internal enum class SessionDrawerPage(val firstControl: String) { CONTROLLER("input-profile"), GLASSES("glasses-game"), @@ -12,14 +18,69 @@ internal enum class SessionDrawerPage(val firstControl: String) { SESSION("suspend"), } -internal fun sessionDrawerPages( +internal object DrawerPages { + var order by mutableStateOf(SessionDrawerPage.entries.toList()) + private set + var hidden by mutableStateOf(emptySet()) + private set + + /** The order captured when a page row was grabbed in Arrange pages; Back restores it. */ + var heldFrom: List? = null + + fun hideable(page: SessionDrawerPage) = page != SessionDrawerPage.SESSION + + fun load(context: Context) { + order = arrange(SessionPrefs.drawerPageOrder(context)) + hidden = SessionPrefs.drawerPageHidden(context).mapNotNull { name -> SessionDrawerPage.entries.firstOrNull { it.name == name } } + .filter(::hideable).toSet() + } + + fun arrange(saved: List): List { + val all = SessionDrawerPage.entries + val out = saved.mapNotNull { name -> all.firstOrNull { it.name == name } }.distinct().toMutableList() + for (page in all.filterNot { it in out }) { + val before = all.subList(0, all.indexOf(page)).lastOrNull { it in out } + out.add(if (before == null) 0 else out.indexOf(before) + 1, page) + } + return out + } + + fun setHidden(context: Context, page: SessionDrawerPage, hide: Boolean) { + hidden = if (hide && hideable(page)) hidden + page else hidden - page + if (DevPreview.drawer == null) SessionPrefs.setDrawerPageHidden(context, hidden.map { it.name }.toSet()) + } + + /** [placed] holds the pages on offer in their new order; pages not on offer keep their slots. */ + fun rearrange(context: Context, placed: List) { + if (placed.isEmpty() || !order.containsAll(placed)) return + val next = placed.iterator() + order = order.map { if (it in placed) next.next() else it } + if (DevPreview.drawer == null) SessionPrefs.setDrawerPageOrder(context, order.map { it.name }) + } + + fun reset(context: Context) { + order = SessionDrawerPage.entries.toList() + hidden = emptySet() + if (DevPreview.drawer != null) return + SessionPrefs.setDrawerPageOrder(context, order.map { it.name }) + SessionPrefs.setDrawerPageHidden(context, emptySet()) + } + + fun isDefault() = order == SessionDrawerPage.entries.toList() && hidden.isEmpty() +} + +internal fun offeredDrawerPages( hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown, ): List = - SessionDrawerPage.entries.filter { + DrawerPages.order.filter { (hasGlasses || it != SessionDrawerPage.GLASSES) && (hasAgent || it != SessionDrawerPage.AGENT) } +internal fun sessionDrawerPages( + hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown, +): List = offeredDrawerPages(hasGlasses, hasAgent).filter { it !in DrawerPages.hidden } + internal fun List.step(current: SessionDrawerPage, direction: Int): SessionDrawerPage { val index = indexOf(current).coerceAtLeast(0) return this[Math.floorMod(index + direction, size)] diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index 04f0de55e3..474e613c6a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -47,6 +47,7 @@ import androidx.compose.material.icons.outlined.Pause import androidx.compose.material.icons.outlined.PictureInPictureAlt import androidx.compose.material.icons.automirrored.outlined.ExitToApp import androidx.compose.material.icons.outlined.Settings +import androidx.compose.material.icons.outlined.Tune import androidx.compose.material.icons.outlined.Speed import androidx.compose.material.icons.outlined.SportsEsports import androidx.compose.material3.Icon @@ -162,7 +163,7 @@ import com.droiddeck.launcher.input.TouchGestureConfig.Companion.MOUSE_BEHAVIOR_ import kotlinx.coroutines.flow.collect import java.util.Locale -private val SessionDrawerPage.title: Int get() = when (this) { +internal val SessionDrawerPage.title: Int get() = when (this) { SessionDrawerPage.CONTROLLER -> R.string.drawer_page_controller SessionDrawerPage.GLASSES -> R.string.drawer_page_glasses SessionDrawerPage.DISPLAY -> R.string.drawer_page_display @@ -174,7 +175,7 @@ private val SessionDrawerPage.title: Int get() = when (this) { SessionDrawerPage.SESSION -> R.string.mode_session } -private val SessionDrawerPage.icon get() = when (this) { +internal val SessionDrawerPage.icon get() = when (this) { SessionDrawerPage.CONTROLLER -> Icons.Outlined.SportsEsports SessionDrawerPage.GLASSES -> GlassesIcon SessionDrawerPage.DISPLAY -> Icons.Outlined.DesktopWindows @@ -392,7 +393,10 @@ class DrawerActions( internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, controllerActive: Boolean, onPageChange: (SessionDrawerPage) -> Unit, a: DrawerActions, docked: Boolean = false, backRequest: Int = 0, onLayerChange: (Boolean) -> Unit = {}) { val pages = sessionDrawerPages(a.glassesPresent) - val page = requestedPage.takeIf { it in pages } ?: SessionDrawerPage.CONTROLLER + val page = requestedPage.takeIf { it in pages } ?: pages.first() + var managing by rememberSaveable { mutableStateOf(false) } + var releaseSignal by remember { mutableStateOf(0) } + val drawerContext = androidx.compose.ui.platform.LocalContext.current LaunchedEffect(requestedPage, pages) { if (page != requestedPage) onPageChange(page) } val colors = MaterialTheme.colorScheme val pal = LocalPalette.current @@ -509,16 +513,24 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont .blockTouches() .focusGroup() .controllerBack { - if (host.open != null) host.open = null else a.onClose() + when { + host.open != null -> host.open = null + managing -> DrawerPages.heldFrom?.let { held -> + DrawerPages.rearrange(drawerContext, held) + releaseSignal++ + } ?: run { managing = false } + else -> a.onClose() + } } .padding(12.dp), ) { val showPicker = a.secondScreenDisplays.isNotEmpty() val roomyHeader = sheetWidth >= if (showPicker) 560.dp else 408.dp + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), - modifier = Modifier.fillMaxWidth().heightIn(min = 44.dp) + modifier = Modifier.weight(1f).heightIn(min = 44.dp) .then(if (roomyHeader) Modifier else Modifier.horizontalScroll(rememberScrollState())), ) { SteamActionPill( @@ -540,7 +552,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont if (a.pipSupported) SteamActionPill( stringResource(R.string.pip_title), Icons.Outlined.PictureInPictureAlt, focus.track(page, "pip"), ) { host.open = null; a.onPip() } - if (docked) StopSessionButton(modifier = focus.track(page, "stop").onGloballyPositioned { stopCoords = it }) { host.open = null; confirmStop = true } val steamActions = a.steam && a.onSteamMenu != null && a.onQam != null val qamInteraction = remember { MutableInteractionSource() } var qamStartedOnPress by remember { mutableStateOf(false) } @@ -570,7 +581,8 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont onQamConfirm = { host.open = null; a.onQam?.invoke() }, showShortcuts = !docked, ) - if (!docked) StopSessionButton(modifier = focus.track(page, "stop").onGloballyPositioned { stopCoords = it }) { host.open = null; confirmStop = true } + } + StopSessionButton(modifier = focus.track(page, "stop").onGloballyPositioned { stopCoords = it }) { host.open = null; confirmStop = true } } a.onAchievements?.let { show -> DrawerAchievementsRow(a.achievementsProgress, Modifier.padding(top = if (short) 6.dp else 10.dp).then(focus.track(page, "achievements"))) { @@ -589,7 +601,15 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont DrawerBumper("RB", stringResource(R.string.drawer_next_page), modifier = focus.track(page, "next")) { 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 (managing) ManageDrawerPages( + offeredDrawerPages(a.glassesPresent), + Modifier.weight(1f).fillMaxWidth().padding(top = 8.dp, start = 14.dp, end = 14.dp), + releaseSignal, + ) { managing = false } else { if (page == SessionDrawerPage.GLASSES) SegmentedTabs( glassesPages, glassesTab, modifier = Modifier.fillMaxWidth().padding(top = 8.dp), tabModifier = { key -> focus.track(page, "glasses-tab-$key").testTag("glasses-tab-$key") }, @@ -926,6 +946,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont } } } } + } } StopConfirm( open = confirmStop, @@ -983,7 +1004,7 @@ private fun DrawerActionButton(text: String, icon: androidx.compose.ui.graphics. } @Composable -private fun DrawerOutlineButton(text: String, modifier: Modifier = Modifier, progress: Float? = null, onClick: () -> Unit) { +internal fun DrawerOutlineButton(text: String, modifier: Modifier = Modifier, progress: Float? = null, onClick: () -> Unit) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val source = remember { MutableInteractionSource() } @@ -1005,15 +1026,14 @@ private fun StopSessionButton(modifier: Modifier = Modifier, onClick: () -> Unit val src = remember { MutableInteractionSource() } val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value val fill by animateColorAsState(if (hot) colors.error.copy(alpha = 0.18f) else Color.Transparent, Motion.tw(220), label = "dangerFill") - val shape = RoundedCornerShape(20.dp) + val shape = androidx.compose.foundation.shape.CircleShape val stopDescription = stringResource(R.string.stop_session) Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center, - modifier = modifier.heightIn(min = 44.dp).widthIn(min = 44.dp).semantics { contentDescription = stopDescription }.testTag("drawer-stop") + modifier = modifier.size(44.dp).semantics { contentDescription = stopDescription }.testTag("drawer-stop") .clip(shape).background(fill).glideBorder(hot, shape, colors.error.copy(alpha = 0.9f), colors.error.copy(alpha = 0.55f)) .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = onClick) - .controllerConfirm(onClick = onClick) - .padding(horizontal = 12.dp), + .controllerConfirm(onClick = onClick), ) { Icon(Icons.Outlined.PowerSettingsNew, contentDescription = null, tint = colors.error, modifier = Modifier.size(18.dp)) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt b/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt index efe8a808bc..0e081d5cda 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt @@ -118,6 +118,8 @@ internal fun SortableRows( rowHeight: androidx.compose.ui.unit.Dp, handleWidth: androidx.compose.ui.unit.Dp, onActivate: (String) -> Unit, + onGrab: (before: List?) -> Unit = {}, + releaseSignal: Int = 0, row: @Composable (key: String, held: Boolean, offset: Float, hint: String?, modifier: Modifier, onFocus: (Boolean) -> Unit) -> Unit, ) { val pad = LocalInputModeManager.current.inputMode == InputMode.Keyboard @@ -129,6 +131,9 @@ internal fun SortableRows( val rowPx = with(LocalDensity.current) { rowHeight.toPx() } val handlePx = with(LocalDensity.current) { handleWidth.toPx() } val list = rows() + val grab by rememberUpdatedState(onGrab) + LaunchedEffect(grabbed) { grab(if (grabbed != null) before else null) } + LaunchedEffect(releaseSignal) { if (releaseSignal > 0) grabbed = null } Column( Modifier.fillMaxWidth().pointerInput(Unit) { awaitEachGesture { diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 81d2a929e0..3b7c9eecb9 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -708,6 +708,9 @@ Open Quick Access Menu Previous page Next page + Arrange pages + Reset + Done Performance HUD Frame rate Battery temperature diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt index adbbbe248a..019f47784c 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt @@ -29,4 +29,17 @@ class SessionDrawerPageTest { assertEquals(SessionDrawerPage.SESSION, with.step(SessionDrawerPage.AGENT, 1)) assertFalse(SessionDrawerPage.AGENT in sessionDrawerPages(hasAgent = false)) } + + @Test fun arrangeKeepsSavedOrderAndSlotsNewPagesAfterTheirNeighbour() { + val saved = listOf("SESSION", "HUD", "CONTROLLER") + val out = DrawerPages.arrange(saved) + assertEquals(SessionDrawerPage.entries.toSet(), out.toSet()) + assertEquals(listOf(SessionDrawerPage.SESSION, SessionDrawerPage.HUD), out.filter { it in setOf(SessionDrawerPage.SESSION, SessionDrawerPage.HUD) }) + assertTrue(out.indexOf(SessionDrawerPage.HUD) < out.indexOf(SessionDrawerPage.CONTROLLER)) + } + + @Test fun sessionPageCannotBeHidden() { + assertFalse(DrawerPages.hideable(SessionDrawerPage.SESSION)) + assertTrue(DrawerPages.hideable(SessionDrawerPage.HUD)) + } } From 088c8ff1cf1a46475eca96d15a1e579ff375b682 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Sat, 21 Nov 2026 15:31:18 -0500 Subject: [PATCH 014/141] fix(battlenet): follow the selected FEX instead of pinning an old build (#2987) * fix(battlenet): follow the selected FEX instead of pinning a d2rfix build The Battle.net prefix forced the newest FEXCore d2rfix package from the Nightlies listing, which stopped updating. Its fixes are in the bundled and nightly FEX, so the prefix now uses whatever FEX is selected. Existing d2rfix selections for the Battle.net profile are cleared once; any other choice is kept. The DXVK memory cap and Start without Steam defaults are now applied when a session starts. * fix(battlenet): import the legacy plugin state before unpinning the Battle.net FEX --- .../droiddeck/launcher/runtime/BattleNet.kt | 73 +----------- .../launcher/session/ComponentsManager.kt | 16 +++ .../launcher/session/SessionFiles.kt | 1 + .../launcher/session/SessionService.kt | 10 +- .../launcher/runtime/BattleNetTest.kt | 105 ++++-------------- .../session/ComponentsRepublishTest.kt | 31 ++++++ .../stores/battlenet/BattleNetRequestTest.kt | 3 +- .../overlay/usr/local/bin/droiddeck-battlenet | 33 ------ tools/tests/test_battlenet.py | 39 +------ 9 files changed, 79 insertions(+), 232 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt b/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt index eeab317afe..7fb5cdc04b 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt @@ -12,9 +12,6 @@ object BattleNet { const val APP_ID = 2596113170L - const val FEX_REQUEST = "battlenet-fex.request" - const val FEX_RESULT = "battlenet-fex.result" - const val PROGRAM = "/usr/local/bin/droiddeck-battlenet" class Title(val uid: String, val name: String, val code: String, val steam: Int? = null, val shop: String? = null, val product: String? = null, val flavor: String? = null) @@ -162,8 +159,6 @@ object BattleNet { source = com.droiddeck.launcher.stores.Store.BATTLENET.id, ) - fun fexInUse(context: Context): String? = ComponentsManager.gameComponents(context, APP_ID.toString())["fex"] - internal fun title(uid: String): Title? { val id = uid.lowercase() TITLES.firstOrNull { it.uid == id }?.let { return it } @@ -391,54 +386,6 @@ object BattleNet { Log.i(TAG, "removed") } - private val D2RFIX = Regex("""(?i)FEXCore-(\d+(?:\.\d+)*)-d2rfix(\d+)-linux\.wcp""") - - private const val LISTING_MAX_AGE = 6 * 3600L - - private val NEWEST = Comparator, Long>> { a, b -> - for (i in 0 until minOf(a.first.size, b.first.size)) if (a.first[i] != b.first[i]) return@Comparator a.first[i].compareTo(b.first[i]) - if (a.first.size != b.first.size) a.first.size.compareTo(b.first.size) else a.second.compareTo(b.second) - } - - internal fun d2rfix(file: String): Pair, Long>? { - val m = D2RFIX.matchEntire(file) ?: return null - val version = m.groupValues[1].split('.').map { it.toLongOrNull() ?: return null } - return version to (m.groupValues[2].toLongOrNull() ?: return null) - } - - internal fun newestD2rFix(items: List): ComponentsManager.CatalogItem? = - items.filter { it.comp == "fex" }.mapNotNull { item -> d2rfix(item.file)?.let { item to it } } - .maxWithOrNull { a, b -> NEWEST.compare(a.second, b.second) }?.first - - fun ensureFex(context: Context): String = ensureFex(context) { ComponentsManager.catalog(it, true).items } - - @Synchronized - internal fun ensureFex(context: Context, refresh: (Context) -> List): String { - val item = newestD2rFix(listing(context, refresh)) ?: error("no d2rfix FEXCore build in the Nightlies listing") - val file = ComponentsManager.safeName(item.file) - if (ComponentsManager.packages(context).none { it.file == file }) { - Log.i(TAG, "downloading ${item.file}") - ComponentsManager.download(context, item) {} - } - val scope = APP_ID.toString() - if (ComponentsManager.gameComponents(context, scope)["fex"] != file) { - ComponentsManager.setGameComponent(context, scope, "fex", file) - Log.i(TAG, "FEX for the Battle.net prefix: $file") - } else if (ComponentsManager.republish(context)) { - Log.i(TAG, "FEX for the Battle.net prefix: $file, now in every installed Proton") - } - return file - } - - private fun listing(context: Context, refresh: (Context) -> List): List { - val cached = ComponentsManager.catalog(context, false) - val age = System.currentTimeMillis() / 1000 - cached.fetchedAt - if (age in 0 until LISTING_MAX_AGE && newestD2rFix(cached.items) != null) return cached.items - val fetched = runCatching { refresh(context) } - .onFailure { Log.w(TAG, "Nightlies listing: ${it.message}") }.getOrNull().orEmpty() - return if (newestD2rFix(fetched) != null) fetched else cached.items - } - internal fun videoMemory(totalMb: Long): Int = (totalMb / 5 / 512 * 512).coerceIn(1536, 3584).toInt() internal fun videoMemoryOptions(megabytes: Int): String = @@ -464,21 +411,9 @@ object BattleNet { return true } - fun answerFexRequest(context: Context, dir: File) { - val app = context.applicationContext - Thread({ - runCatching { ensureVideoMemory(app) }.onFailure { Log.w(TAG, "video memory cap for the Battle.net profile", it) } - runCatching { ensureNoSteam(app) }.onFailure { Log.w(TAG, "Start without Steam for the Battle.net profile", it) } - val answer = try { - "ok " + ensureFex(app) - } catch (e: Exception) { - Log.w(TAG, "FEX for the Battle.net prefix", e) - "error " + (e.message ?: e.javaClass.simpleName) - } - Log.i(TAG, "FEX request: $answer") - val result = File(dir, FEX_RESULT) - val partial = File(dir, "$FEX_RESULT.tmp") - runCatching { partial.writeText(answer.replace('\n', ' ') + "\n"); partial.renameTo(result) } - }, "battlenet-fex").start() + fun ensureDefaults(context: Context, program: String?) { + if (program != PROGRAM && !installed(context)) return + runCatching { ensureVideoMemory(context) }.onFailure { Log.w(TAG, "video memory cap for the Battle.net profile", it) } + runCatching { ensureNoSteam(context) }.onFailure { Log.w(TAG, "Start without Steam for the Battle.net profile", it) } } } diff --git a/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt b/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt index 749532cddf..fdc8e2bf51 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt @@ -238,6 +238,20 @@ object ComponentsManager { saveState(context, state) } + private val UNPINNED_FEX = Regex("""(?i)FEXCore-\d+(?:\.\d+)*-d2rfix\d+-linux\.wcp""") + + fun migrateBattleNetFex(context: Context) = synchronized(lock) { + val marker = File(dataDir(context), ".battlenet-fex-unpinned") + if (marker.isFile) return@synchronized + migratePlugin(context) + val scope = com.droiddeck.launcher.runtime.BattleNet.APP_ID.toString() + if (gameComponents(context, scope)["fex"]?.let(UNPINNED_FEX::matches) == true) { + setGameComponent(context, scope, "fex", null) + Log.i(TAG, "Battle.net follows the selected FEX again") + } + marker.writeText("1\n") + } + private fun migratePlugin(context: Context) { val marker = File(dataDir(context), ".plugin-imported") if (marker.isFile) return @@ -487,6 +501,7 @@ object ComponentsManager { fun snapshotAll(context: Context) = synchronized(lock) { migratePlugin(context) + runCatching { migrateBattleNetFex(context) }.onFailure { Log.w(TAG, "Battle.net FEX selection", it) } val state = loadState(context) for (p in protons(context)) for (comp in COMPONENTS) { runCatching { ensureOriginal(context, p, comp, state) }.onFailure { Log.w(TAG, "original $comp of ${p.name}", it) } @@ -497,6 +512,7 @@ object ComponentsManager { fun snapshot(context: Context): Snapshot = synchronized(lock) { migratePlugin(context) + runCatching { migrateBattleNetFex(context) }.onFailure { Log.w(TAG, "Battle.net FEX selection", it) } val state = loadState(context) val reapplied = HashMap() runCatching { diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index 9fb0aaab95..1082de60d5 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -287,6 +287,7 @@ object SessionFiles { File(root, "usr/share/vulkan/implicit_layer.d/droiddeck_vram_cap.json").delete() LegacyNames.migrateRootfs(root) ComponentsManager.migrateLaunchDir(context) + runCatching { ComponentsManager.migrateBattleNetFex(context) }.onFailure { Log.w(TAG, "Battle.net FEX selection", it) } EsyncPacks.stageBundled(context, root) val directAudio = arrayOf( "aarch64-unix/winedirectaudio.so", diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index 5d78730013..15d2844d34 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -589,7 +589,10 @@ class SessionService : Service() { val sessionDir = openSessionFolder() try { - SessionEvents.step("game-environment") { GameEnvironmentStore.publish(this) } + SessionEvents.step("game-environment") { + com.droiddeck.launcher.runtime.BattleNet.ensureDefaults(this, SessionState.program) + GameEnvironmentStore.publish(this) + } } catch (e: Exception) { Log.e(TAG, "could not publish the game environment", e) failSession(gen, "GAME_ENVIRONMENT_FAILED", getString(R.string.session_game_environment_failed), -1) @@ -1951,11 +1954,6 @@ class SessionService : Service() { } return } - if (path == com.droiddeck.launcher.runtime.BattleNet.FEX_REQUEST) { - File(dir, path).delete() - com.droiddeck.launcher.runtime.BattleNet.answerFexRequest(this@SessionService, dir) - return - } if (path != null && path.startsWith("desktop-import-") && path.endsWith(".request")) { val request = File(dir, path) val text = runCatching { request.readText() }.getOrNull() ?: return diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt index f74528c725..ea0c471faa 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt @@ -73,72 +73,6 @@ class BattleNetTest { assertEquals(crc or 0x80000000L, BattleNet.APP_ID) } - @Test fun theNewestD2rfixIsTheHighestFexThenTheHighestFix() { - val items = listOf( - item("FEXCore-2610-linux.wcp"), - item("FEXCore-2609-d2rfix25-linux.wcp"), - item("FEXCore-2610-d2rfix9-linux.wcp"), - item("FEXCore-2610-d2rfix28-linux.wcp"), - item("FEXCore-2509.1-d2rfix40-linux.wcp"), - ) - assertEquals("FEXCore-2610-d2rfix28-linux.wcp", BattleNet.newestD2rFix(items)?.file) - assertEquals("FEXCore-2610.1-d2rfix1-linux.wcp", BattleNet.newestD2rFix(items + item("FEXCore-2610.1-d2rfix1-linux.wcp"))?.file) - assertEquals("FexCore-2611-D2RFIX2-linux.wcp", BattleNet.newestD2rFix(items + item("FexCore-2611-D2RFIX2-linux.wcp"))?.file) - } - - @Test fun onlyFexD2rfixPackagesCount() { - assertNull(BattleNet.newestD2rFix(listOf(item("FEXCore-2610-linux.wcp"), item("FEXCore-2610-d2rfix28-linux.wcp", comp = "dxvk")))) - assertNull(BattleNet.d2rfix("FEXCore-2610-d2rfix28-linux.wcp.part")) - assertNull(BattleNet.d2rfix("FEXCore-2610-d2rfix-linux.wcp")) - assertEquals(listOf(2610L) to 28L, BattleNet.d2rfix("FEXCore-2610-d2rfix28-linux.wcp")) - } - - @Test fun theNewestStoredBuildIsSetForThePrefix() { - catalog("FEXCore-2609-d2rfix25-linux.wcp", "FEXCore-2610-d2rfix28-linux.wcp", "FEXCore-2610-linux.wcp") - store("FEXCore-2610-d2rfix28-linux.wcp") - - assertEquals("FEXCore-2610-d2rfix28-linux.wcp", BattleNet.ensureFex(context, ::noRefresh)) - - assertEquals(mapOf("fex" to "FEXCore-2610-d2rfix28-linux.wcp"), ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())) - assertEquals("FEXCore-2610-d2rfix28-linux.wcp", BattleNet.ensureFex(context, ::noRefresh)) - } - - @Test fun aNewerBuildReplacesTheOldOne() { - catalog("FEXCore-2609-d2rfix25-linux.wcp") - store("FEXCore-2609-d2rfix25-linux.wcp") - BattleNet.ensureFex(context, ::noRefresh) - catalog("FEXCore-2609-d2rfix25-linux.wcp", "FEXCore-2610-d2rfix28-linux.wcp") - store("FEXCore-2610-d2rfix28-linux.wcp") - - BattleNet.ensureFex(context, ::noRefresh) - - assertEquals("FEXCore-2610-d2rfix28-linux.wcp", ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())["fex"]) - } - - @Test fun aStaleListingIsFetchedAgain() { - catalog("FEXCore-2609-d2rfix25-linux.wcp", fetchedAt = 1) - store("FEXCore-2610-d2rfix28-linux.wcp") - - BattleNet.ensureFex(context) { listOf(item("FEXCore-2609-d2rfix25-linux.wcp"), item("FEXCore-2610-d2rfix28-linux.wcp")) } - - assertEquals("FEXCore-2610-d2rfix28-linux.wcp", ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())["fex"]) - } - - @Test fun aFailedFetchFallsBackOnTheCachedListing() { - catalog("FEXCore-2609-d2rfix25-linux.wcp", fetchedAt = 1) - store("FEXCore-2609-d2rfix25-linux.wcp") - - assertEquals("FEXCore-2609-d2rfix25-linux.wcp", BattleNet.ensureFex(context) { error("offline") }) - } - - @Test fun aListingWithoutD2rfixIsAnError() { - catalog("FEXCore-2610-linux.wcp") - var refreshed = 0 - assertThrows(IllegalStateException::class.java) { BattleNet.ensureFex(context) { refreshed++; emptyList() } } - assertEquals(1, refreshed) - assertEquals(emptyMap(), ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())) - } - @Test fun installedIsTheLauncherInThePrefix() { assertFalse(BattleNet.installed(context)) launcher().apply { parentFile!!.mkdirs(); writeText("MZ") } @@ -152,9 +86,9 @@ class BattleNetTest { } @Test fun removeTakesThePrefixItsMenuEntryAndCacheButNothingItLinksTo() { - catalog("FEXCore-2610-d2rfix28-linux.wcp") - store("FEXCore-2610-d2rfix28-linux.wcp") - BattleNet.ensureFex(context, ::noRefresh) + store("FEXCore-2610-linux.wcp") + ComponentsManager.setGameComponent(context, BattleNet.APP_ID.toString(), "fex", "FEXCore-2610-linux.wcp") + assertEquals(mapOf("fex" to "FEXCore-2610-linux.wcp"), ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())) val root = LinuxRuntime.rootDir(context) fun put(relative: String) = File(root, relative).apply { parentFile!!.mkdirs(); writeText("x") } launcher().apply { parentFile!!.mkdirs(); writeText("MZ") } @@ -176,7 +110,7 @@ class BattleNetTest { assertTrue(otherMenu.isFile) assertFalse(log.parentFile!!.exists()) assertTrue(otherPrefix.isFile) - assertNull(BattleNet.fexInUse(context)) + assertEquals(emptyMap(), ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())) outside.deleteRecursively() } @@ -481,6 +415,22 @@ class BattleNetTest { assertTrue(BattleNet.ensureVideoMemory(context)) } + @Test fun theProfileDefaultsAreSetForTheBattleNetProgramOrOnceInstalledAndNeverForAnythingElse() { + File(context.filesDir, "game-environment.json").delete() + val manager = context.getSystemService(android.app.ActivityManager::class.java) + org.robolectric.Shadows.shadowOf(manager).setMemoryInfo(android.app.ActivityManager.MemoryInfo().apply { totalMem = 11113L shl 20 }) + val scope = BattleNet.APP_ID.toString() + BattleNet.ensureDefaults(context, null) + assertNull(GameEnvironmentStore.read(context).games[scope]?.get("DXVK_CONFIG")) + BattleNet.ensureDefaults(context, BattleNet.PROGRAM) + assertEquals(BattleNet.videoMemoryOptions(2048), GameEnvironmentStore.read(context).games[scope]?.get("DXVK_CONFIG")) + assertTrue(com.droiddeck.launcher.session.SessionPrefs.battleNetNoSteamSet(context)) + File(context.filesDir, "game-environment.json").delete() + launcher().apply { parentFile!!.mkdirs(); writeText("MZ") } + BattleNet.ensureDefaults(context, null) + assertEquals(BattleNet.videoMemoryOptions(2048), GameEnvironmentStore.read(context).games[scope]?.get("DXVK_CONFIG")) + } + private fun launcher() = File(BattleNet.prefix(context), "pfx/drive_c/Program Files (x86)/Battle.net/Battle.net Launcher.exe") private fun varint(value: Long): ByteArray { @@ -496,21 +446,6 @@ class BattleNetTest { private fun varintField(number: Int, value: Long) = varint((number shl 3).toLong()) + varint(value) private fun message(vararg fields: ByteArray) = fields.fold(ByteArray(0)) { all, f -> all + f } - private fun noRefresh(context: Context): List = error("the cached listing was fresh") - - private fun item(file: String, comp: String = "fex") = ComponentsManager.CatalogItem( - file, comp, "FexCore-Linux", "https://github.com/The412Banner/Nightlies/releases/download/FexCore-Linux/$file", 4, "sha256:" + "ab".repeat(32), - ) - - private fun catalog(vararg files: String, fetchedAt: Long = System.currentTimeMillis() / 1000) { - val cache = File(context.filesDir, "components/catalog.json") - cache.parentFile!!.mkdirs() - val items = JSONArray() - for (file in files) items.put(JSONObject().put("file", file).put("comp", "fex").put("release", "FexCore-Linux") - .put("url", item(file).url).put("size", 4).put("digest", item(file).digest)) - cache.writeText(JSONObject().put("items", items).put("fetchedAt", fetchedAt).toString()) - } - private fun store(file: String) { val wcp = File(context.filesDir, "components/packages/$file") wcp.parentFile!!.mkdirs() diff --git a/app/src/test/java/com/droiddeck/launcher/session/ComponentsRepublishTest.kt b/app/src/test/java/com/droiddeck/launcher/session/ComponentsRepublishTest.kt index 74978ee30c..58d36b8166 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/ComponentsRepublishTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/ComponentsRepublishTest.kt @@ -82,6 +82,37 @@ class ComponentsRepublishTest { private fun scopedTools() = rows().filter { it[0] == scope }.map { it[1] }.toSet() + @Test fun battleNetDropsAnOldPinnedFexOnceAndKeepsAnyOtherChoice() { + proton("DroidDeck-Proton 11-11.8", "DroidDeck-Proton-11-11.8") + packageFile() + ComponentsManager.setGameComponent(context, scope, "fex", fex) + ComponentsManager.setGameComponent(context, "123", "fex", fex) + assertTrue(rows().any { it[0] == scope }) + + ComponentsManager.migrateBattleNetFex(context) + + assertEquals(emptyMap(), ComponentsManager.gameComponents(context, scope)) + assertEquals(fex, ComponentsManager.gameComponents(context, "123")["fex"]) + assertTrue(rows().none { it[0] == scope }) + assertTrue(rows().any { it[0] == "123" }) + + ComponentsManager.setGameComponent(context, scope, "fex", fex) + ComponentsManager.migrateBattleNetFex(context) + assertEquals(fex, ComponentsManager.gameComponents(context, scope)["fex"]) + } + + @Test fun battleNetKeepsAFexTheUserChoseThemselves() { + proton("DroidDeck-Proton 11-11.8", "DroidDeck-Proton-11-11.8") + val own = "FEXCore-2612-linux.wcp" + packageFile() + File(context.filesDir, "components/packages/$fex").copyTo(File(context.filesDir, "components/packages/$own")) + ComponentsManager.setGameComponent(context, scope, "fex", own) + + ComponentsManager.migrateBattleNetFex(context) + + assertEquals(own, ComponentsManager.gameComponents(context, scope)["fex"]) + } + private fun rows() = launchState().readLines().filter { it.isNotEmpty() }.map { it.split('\t') } private fun launchState() = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-components/desired.tsv") diff --git a/app/src/test/java/com/droiddeck/launcher/stores/battlenet/BattleNetRequestTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/battlenet/BattleNetRequestTest.kt index f1141a8715..2da34d3db4 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/battlenet/BattleNetRequestTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/battlenet/BattleNetRequestTest.kt @@ -31,8 +31,7 @@ class BattleNetRequestTest { BattleNetClient.request(root, listOf("launch", "WTCG")) java.io.File(root, "battlenet-request").writeText("launch\nPro\n") java.io.File(root, "battlenet-request.1.tmp").writeText("launch\nPro\n") - java.io.File(root, "battlenet-fex.request").writeText("x") BattleNetClient.clearRequests(root) - assertEquals(listOf("battlenet-fex.request"), root.list()!!.toList()) + assertEquals(0, root.list()!!.size) } } diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet b/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet index 066f9c572e..0cddb3fb4b 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet @@ -37,9 +37,6 @@ USER_PREFERENCES = "UserPreferencesMask" WINE_USER_PREFERENCES = bytes((0x10, 0x00, 0x00, 0x80, 0x12, 0x00, 0x00, 0x00)) CLIENT_AREA_ANIMATION = (4, 0x02) WALLPAPER_MAX = (1280, 720) -FEX_REQUEST = "battlenet-fex.request" -FEX_RESULT = "battlenet-fex.result" -FEX_WAIT = 120 START_GRACE = 90 POLL = 2 STOP_WAIT = 5 @@ -779,32 +776,6 @@ def write_menu(path=MENU): say("menu entry not written: %s" % error) -def ask_fex(launch_dir, wait=FEX_WAIT): - if not launch_dir or not os.path.isdir(launch_dir): - say("not inside a DroidDeck session; FEX stays as Components has it") - return None - result = os.path.join(launch_dir, FEX_RESULT) - request = os.path.join(launch_dir, FEX_REQUEST) - try: - os.unlink(result) - except OSError: - pass - with open(request + ".tmp", "w", encoding="utf-8") as f: - f.write("appid=%s\n" % APP_ID) - os.replace(request + ".tmp", request) - deadline = time.monotonic() + wait - while time.monotonic() < deadline: - try: - with open(result, encoding="utf-8") as f: - answer = f.read().strip() - except OSError: - time.sleep(0.5) - continue - os.unlink(result) - return answer - return None - - def wine_processes(pfx, proc="/proc"): want = os.path.realpath(pfx).rstrip("/") found = [] @@ -1148,8 +1119,6 @@ def stop_leftovers(pfx): def open_client(root, reinstall=False): pfx = os.path.join(prefix(root), "pfx") write_menu() - answer = ask_fex(os.environ.get("DD_LAUNCH_DIR")) - say("FEX: %s" % (answer or "no answer from the app; Components' choice stays")) if running(pfx): say("Battle.net is already running in its prefix; waiting for it to close") wait_while_open(pfx, grace=0) @@ -1238,8 +1207,6 @@ def launch(root, code): try: own = None if lock is not None and not running(pfx): - answer = ask_fex(os.environ.get("DD_LAUNCH_DIR")) - say("FEX: %s" % (answer or "no answer from the app; Components' choice stays")) verb = None if stop_leftovers(pfx) else "run" configure(root, LIBRARY) own = start(launcher(root), verb) diff --git a/tools/tests/test_battlenet.py b/tools/tests/test_battlenet.py index ece44f60d6..52ba9e8d46 100644 --- a/tools/tests/test_battlenet.py +++ b/tools/tests/test_battlenet.py @@ -6,7 +6,6 @@ import re import runpy import shutil import tempfile -import threading import time import unittest from unittest import mock @@ -93,8 +92,6 @@ class IdTest(unittest.TestCase): self.assertEqual(int(BNET["APP_ID"]), zlib.crc32(b'"droiddeck-battlenet"Battle.net') | 0x80000000) found = re.search(r"const val APP_ID = (\d+)L", KOTLIN.read_text()) self.assertEqual(found.group(1), BNET["APP_ID"]) - for name in ("FEX_REQUEST", "FEX_RESULT"): - self.assertIn('const val %s = "%s"' % (name, BNET[name]), KOTLIN.read_text()) class ProtonRunOptionsTest(Temp): @@ -761,36 +758,6 @@ class TidyTest(unittest.TestCase): self.assertEqual(self.stopped, []) -class FexRequestTest(Temp): - def answer(self, text, delay=0.2): - def respond(): - request = self.tmp / BNET["FEX_REQUEST"] - deadline = time.monotonic() + 5 - while not request.exists() and time.monotonic() < deadline: - time.sleep(0.02) - self.requested = request.read_text() - request.unlink() - time.sleep(delay) - (self.tmp / (BNET["FEX_RESULT"] + ".tmp")).write_text(text + "\n") - os.replace(self.tmp / (BNET["FEX_RESULT"] + ".tmp"), self.tmp / BNET["FEX_RESULT"]) - thread = threading.Thread(target=respond) - thread.start() - self.addCleanup(thread.join) - - def test_the_apps_answer_comes_back(self): - (self.tmp / BNET["FEX_RESULT"]).write_text("ok an-old-answer\n") - self.answer("ok FEXCore-2610-d2rfix28-linux.wcp") - self.assertEqual(BNET["ask_fex"](str(self.tmp), wait=5), "ok FEXCore-2610-d2rfix28-linux.wcp") - self.assertEqual(self.requested, "appid=%s\n" % BNET["APP_ID"]) - self.assertFalse((self.tmp / BNET["FEX_RESULT"]).exists()) - - def test_no_answer_or_no_session_starts_without_one(self): - with mock.patch.dict(BNET, {"say": lambda message: None}): - self.assertIsNone(BNET["ask_fex"](str(self.tmp), wait=0.3)) - self.assertIsNone(BNET["ask_fex"](None)) - self.assertIsNone(BNET["ask_fex"](str(self.tmp / "gone"))) - - class OpenTest(Temp): def setUp(self): super().setUp() @@ -799,7 +766,6 @@ class OpenTest(Temp): self.alive = [] self.menu = self.tmp / "droiddeck-battlenet.desktop" patcher = mock.patch.dict(BNET, { - "ask_fex": lambda launch_dir, wait=0: "ok fex.wcp", "say": lambda message: None, "notify": lambda *a, **k: self.calls.append(("notify", a[0])), "wine_processes": lambda pfx, proc="/proc": list(self.alive), "stop": lambda processes, wait=0: self.calls.append(("stop", [pid for pid, _ in processes])) or self.alive.clear(), @@ -988,7 +954,6 @@ class Harness(Temp): self.states = [] self.last = [] patcher = mock.patch.dict(BNET, { - "ask_fex": lambda launch_dir, wait=0: self.calls.append(("fex",)) or "ok fex.wcp", "say": lambda message: None, "notify": lambda *a, **k: self.calls.append(("notify", a[0])), "wine_processes": self.processes, "stop": lambda processes, wait=0: self.calls.append(("stop", sorted(pid for pid, _ in processes))), @@ -1019,7 +984,7 @@ class LaunchTest(Harness): self.states = [[], [], up, up + [(40, self.GAME)], up, up] self.assertEqual(BNET["launch"](self.root, "Fen"), 0) self.assertEqual(self.calls, [ - ("fex",), ("start", "Battle.net Launcher.exe", None), + ("start", "Battle.net Launcher.exe", None), ("spawn", "Battle.net.exe", "run", ["--exec=launch Fen"]), ("stop", [10, 11, 12, 13, 14, 30]), ]) @@ -1034,7 +999,7 @@ class LaunchTest(Harness): with mock.patch.dict(BNET, {"GAME_SETTLE": 0}): self.assertEqual(BNET["launch"](self.root, "Fen"), 0) self.assertEqual(self.calls, [ - ("fex",), ("start", "Battle.net Launcher.exe", None), + ("start", "Battle.net Launcher.exe", None), ("spawn", "Battle.net.exe", "run", ["--exec=launch Fen"]), ("stop", [10, 11, 12, 13, 14, 30]), ("stop", [50]), From 0399c3e51020f10f4a6d057ec41f1830cb1b609c Mon Sep 17 00:00:00 2001 From: FX192 <120828496+FX192@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:50:19 +0300 Subject: [PATCH 015/141] Use the portrait resolution in the controls-below layout and size the game area to the output aspect --- .../com/droiddeck/launcher/SessionActivity.kt | 26 ++++++------------- .../launcher/session/SessionDisplay.kt | 8 ++++-- .../launcher/ui/ModeSettingsDialog.kt | 2 +- .../launcher/session/SessionDisplayTest.kt | 5 ++++ 4 files changed, 20 insertions(+), 21 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 6028afe1ed..205814127c 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -2956,17 +2956,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde WaylandCompositor.nativeResizeOutput(size.first, size.second) } - private fun followPortrait(): Boolean { - if (glassesScreen != null) return false - if (::sessionRoot.isInitialized && sessionRoot.width > 0) return portraitOutput() - val portraitWindow = SessionPrefs.portrait(this) - val panel = com.droiddeck.launcher.session.SessionDisplay.panelSize(this) - val long = maxOf(panel.first, panel.second) - val short = minOf(panel.first, panel.second) - val below = SessionPrefs.controlsBelowWanted(this, intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM, - if (portraitWindow) short else long, if (portraitWindow) long else short) - return portraitWindow && !below - } + private fun followPortrait(): Boolean = glassesScreen == null && SessionPrefs.portrait(this) private fun followScale(): Float { val mode = displayMode() @@ -3045,13 +3035,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun portraitOutput(): Boolean = SessionPrefs.portrait(this) && !controlsBelowWanted() - private fun outputSize(): Pair { - val portrait = portraitOutput() - return com.droiddeck.launcher.session.SessionDisplay.resolveChoice(com.droiddeck.launcher.session.SessionDisplay.panelSize(this), - resolutionChoice(portrait), portrait) - } + private fun outputSize(): Pair = + com.droiddeck.launcher.session.SessionDisplay.resolveChoice(com.droiddeck.launcher.session.SessionDisplay.panelSize(this), + resolutionChoice(), portraitOutput()) - private fun resolutionChoice(portrait: Boolean = portraitOutput()): String { + private fun resolutionChoice(portrait: Boolean = SessionPrefs.portrait(this)): String { val mode = displayMode() val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM) return if (intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_RUN && @@ -4636,7 +4624,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val tabRow = unfoldedColumn?.getChildAt(0)?.height?.let { it - (com.droiddeck.launcher.ui.BAR_HEIGHT.value * resources.displayMetrics.density + 0.5f).toInt() } ?: 0 - val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height, tabRow) + val outputAspect = if (!wanted || SessionState.followScreen) 0f + else outputSize().let { it.first.toFloat() / it.second.coerceAtLeast(1) } + val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height, tabRow, outputAspect) else FrameLayout.LayoutParams.MATCH_PARENT val params = surfaceView.layoutParams as FrameLayout.LayoutParams if (params.height != gameHeight) { diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt index a9f809c079..919891fa45 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt @@ -89,8 +89,12 @@ object SessionDisplay { const val UNFOLDED_MIN_DP = 600 - fun unfoldedGameHeight(width: Int, height: Int, tabRow: Int = 0): Int = - (minOf(width * 9 / 16, (height * UNFOLDED_MAX_GAME_SHARE).toInt()) - tabRow.coerceAtLeast(0)).coerceAtLeast(0) and 1.inv() + fun unfoldedGameHeight(width: Int, height: Int, tabRow: Int = 0, aspect: Float = 0f): Int { + val row = tabRow.coerceAtLeast(0) + val cap = (height * UNFOLDED_MAX_GAME_SHARE).toInt() + if (aspect > 0f && aspect < 16f / 9f) return minOf((width / aspect).toInt(), cap - row).coerceAtLeast(0) and 1.inv() + return (minOf(width * 9 / 16, cap) - row).coerceAtLeast(0) and 1.inv() + } fun unfoldedControlsWanted( enabled: Boolean, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt index 3218579f8a..fc611d6ca6 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -239,7 +239,7 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: val sessionDisplay = com.droiddeck.launcher.session.SessionDisplay val landscapeChoice = sessionDisplay.effectiveChoice(s.resolution, s.resolutionPortrait, false) val portraitChoice = sessionDisplay.effectiveChoice(s.resolution, s.resolutionPortrait, true) - val activeChoice = if (portrait) portraitChoice else landscapeChoice + val activeChoice = if (portraitWindow) portraitChoice else landscapeChoice val displaySize = sessionDisplay.resolveChoice(s.panelSize, activeChoice, portrait) SettingsGroup(stringResource(R.string.display_session)) { ResolutionRow(host, "resolution", stringResource(R.string.display_resolution_landscape), s.resolution, landscapeChoice, diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionDisplayTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionDisplayTest.kt index 1835b6b85d..28fc21d54a 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionDisplayTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionDisplayTest.kt @@ -55,6 +55,11 @@ class SessionDisplayTest { @Test fun unfoldedControlsKeepTheGameSixteenByNineAcrossTheWidth() { assertEquals(606, SessionDisplay.unfoldedGameHeight(1080, 1920)) + assertEquals(606, SessionDisplay.unfoldedGameHeight(1080, 1920, 0, 16f / 9f)) + assertEquals(606, SessionDisplay.unfoldedGameHeight(1080, 1920, 0, 2.2f)) + assertEquals(1080, SessionDisplay.unfoldedGameHeight(1440, 3039, 192, 4f / 3f)) + assertEquals(1080, SessionDisplay.unfoldedGameHeight(1440, 3039, 0, 4f / 3f)) + assertEquals(2238, SessionDisplay.unfoldedGameHeight(1440, 3039, 0, 0.5f)) assertEquals(1376, SessionDisplay.unfoldedGameHeight(2448, 1848)) assertEquals(1038, SessionDisplay.unfoldedGameHeight(1848, 2448)) assertEquals(864, SessionDisplay.unfoldedGameHeight(1920, 1080)) From 86226910c36a794ed4b287ceea617ce07ff4e2bf Mon Sep 17 00:00:00 2001 From: FX192 <120828496+FX192@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:09:51 +0300 Subject: [PATCH 016/141] Correct the tall-aspect game height expectation in the test --- .../java/com/droiddeck/launcher/session/SessionDisplayTest.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionDisplayTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionDisplayTest.kt index 28fc21d54a..f8dd6e34e2 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionDisplayTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionDisplayTest.kt @@ -59,7 +59,7 @@ class SessionDisplayTest { assertEquals(606, SessionDisplay.unfoldedGameHeight(1080, 1920, 0, 2.2f)) assertEquals(1080, SessionDisplay.unfoldedGameHeight(1440, 3039, 192, 4f / 3f)) assertEquals(1080, SessionDisplay.unfoldedGameHeight(1440, 3039, 0, 4f / 3f)) - assertEquals(2238, SessionDisplay.unfoldedGameHeight(1440, 3039, 0, 0.5f)) + assertEquals(2430, SessionDisplay.unfoldedGameHeight(1440, 3039, 0, 0.5f)) assertEquals(1376, SessionDisplay.unfoldedGameHeight(2448, 1848)) assertEquals(1038, SessionDisplay.unfoldedGameHeight(1848, 2448)) assertEquals(864, SessionDisplay.unfoldedGameHeight(1920, 1080)) From 6af598b25e9a6b5ce371b43e534a6e2cc10c64a6 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:31:58 -0500 Subject: [PATCH 017/141] feat(launcher): tick haptics for controller navigation (#2993) * feat(launcher): tick haptics for controller navigation, off for touch * docs: regenerate settings map for controller haptics * fix(launcher): tick for hat and stick navigation, which arrive as joystick-source keys * fix(launcher): tick before the Components tab consumes L1/R1 --- .../droiddeck/launcher/FrontEndActivity.kt | 5 +++ .../launcher/session/SessionPrefs.kt | 6 +++ .../launcher/session/SettingsReset.kt | 2 +- .../launcher/ui/ControllerHaptics.kt | 41 +++++++++++++++++++ .../droiddeck/launcher/ui/FrontEndScreen.kt | 2 + .../droiddeck/launcher/ui/FrontEndSetup.kt | 5 +++ .../droiddeck/launcher/ui/SettingsIndex.kt | 1 + app/src/main/res/values/strings.xml | 2 + docs/settings-map.md | 1 + 9 files changed, 64 insertions(+), 1 deletion(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/ui/ControllerHaptics.kt diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index 010d503be4..99e164d108 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -199,6 +199,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private var launcherOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER) private var homePage by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM) private var launcherFullscreen by mutableStateOf(true) + private var controllerHaptics by mutableStateOf(true) private var downloadSource by mutableStateOf(DownloadSource.MODE_AUTO) private var downloadMirror by mutableStateOf("") private var downloadPrefix by mutableStateOf("") @@ -1264,6 +1265,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet requestedOrientation = launcherOrientation homePage = com.droiddeck.launcher.core.AppUiPrefs.homePage(this) launcherFullscreen = SessionPrefs.launcherFullscreen(this) + controllerHaptics = SessionPrefs.controllerHaptics(this) downloadSource = DownloadSource.mode(this) downloadMirror = DownloadSource.mirror(this) downloadPrefix = DownloadSource.custom(this) @@ -1363,6 +1365,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet launcherOrientation = launcherOrientation, homePage = homePage, launcherFullscreen = launcherFullscreen, + controllerHaptics = controllerHaptics, downloadSource = downloadSource, downloadMirror = downloadMirror, downloadPrefix = downloadPrefix, @@ -1679,6 +1682,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet com.droiddeck.launcher.core.AppUiPrefs.setHomePage(this, value) homePage = value }, + onControllerHaptics = { on -> SessionPrefs.setControllerHaptics(this, on); controllerHaptics = on }, onLauncherFullscreen = { on -> SessionPrefs.setLauncherFullscreen(this, on) launcherFullscreen = on @@ -2047,6 +2051,7 @@ 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 (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)) { if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) { diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 1376517288..826cfac74a 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -85,6 +85,12 @@ object SessionPrefs { prefs(context).edit().putBoolean("launcherFullscreen", on).apply() } + fun controllerHaptics(context: Context): Boolean = prefs(context).getBoolean("controllerHaptics", true) + + fun setControllerHaptics(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("controllerHaptics", on).apply() + } + fun blackFrameInsertion(context: Context): Boolean = prefs(context).getBoolean("blackFrameInsertion", false) fun setBlackFrameInsertion(context: Context, on: Boolean) { diff --git a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt index b2ca79e52b..2bb6190ce5 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt @@ -12,7 +12,7 @@ object SettingsReset { private const val TAG = "SettingsReset" internal val SESSION_KEYS = setOf( - "orientation", "launcherFullscreen", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt", + "orientation", "launcherFullscreen", "controllerHaptics", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt", "dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard", "soundtracksIngame", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature", "storesInstallLanguage", diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ControllerHaptics.kt b/app/src/main/java/com/droiddeck/launcher/ui/ControllerHaptics.kt new file mode 100644 index 0000000000..8f06cd50af --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/ControllerHaptics.kt @@ -0,0 +1,41 @@ +package com.droiddeck.launcher.ui + +import android.content.Context +import android.os.Build +import android.os.VibrationEffect +import android.os.Vibrator +import android.os.VibratorManager +import android.view.InputDevice +import android.view.KeyEvent + +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, + ) + + fun onKey(context: Context, event: KeyEvent) { + if (event.action != KeyEvent.ACTION_DOWN || event.keyCode !in navKeys) return + if (event.keyCode == KeyEvent.KEYCODE_BUTTON_A && event.repeatCount > 0) return + val fromController = event.isFromSource(InputDevice.SOURCE_GAMEPAD) || + event.isFromSource(InputDevice.SOURCE_DPAD) || event.isFromSource(InputDevice.SOURCE_JOYSTICK) + if (!fromController) return + tick(context) + } + + fun tick(context: Context) { + val vibrator = if (Build.VERSION.SDK_INT >= 31) { + context.getSystemService(VibratorManager::class.java)?.defaultVibrator + } else { + @Suppress("DEPRECATION") context.getSystemService(Context.VIBRATOR_SERVICE) as? Vibrator + } ?: return + if (!vibrator.hasVibrator()) return + if (Build.VERSION.SDK_INT >= 29) { + vibrator.vibrate(VibrationEffect.createPredefined(VibrationEffect.EFFECT_TICK)) + } else if (Build.VERSION.SDK_INT >= 26) { + vibrator.vibrate(VibrationEffect.createOneShot(10, VibrationEffect.DEFAULT_AMPLITUDE)) + } else { + @Suppress("DEPRECATION") vibrator.vibrate(10) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt index 2267bef930..b74e179384 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -174,6 +174,7 @@ class FrontEndState( val launcherOrientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER, val homePage: String = com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM, val launcherFullscreen: Boolean = true, + val controllerHaptics: Boolean = true, val downloadSource: String = DownloadSource.MODE_AUTO, val downloadMirror: String = "", val downloadPrefix: String = "", @@ -279,6 +280,7 @@ class FrontEndActions( val onLauncherOrientation: (Int) -> Unit = {}, val onHomePage: (String) -> Unit = {}, val onLauncherFullscreen: (Boolean) -> Unit = {}, + val onControllerHaptics: (Boolean) -> Unit = {}, val onAnimationsEnabled: (Boolean) -> Unit = {}, val onLowStorageWarning: (Boolean) -> Unit = {}, val onDualScreenMode: (String) -> Unit = {}, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt index b7976c89dd..ec3b1c1b55 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -516,6 +516,11 @@ internal fun SetupPanel( if (s.launcherFullscreen) stringResource(R.string.setup_fullscreen_on) else stringResource(R.string.setup_fullscreen_off), s.launcherFullscreen, ) { a.onLauncherFullscreen(it) } + ToggleRow( + host, "controller-haptics", stringResource(R.string.setup_controller_haptics), + stringResource(R.string.setup_controller_haptics_hint), + s.controllerHaptics, + ) { a.onControllerHaptics(it) } if (s.dualScreenDevice) { val dualModes = listOf( com.droiddeck.launcher.input.DualScreen.MODE_AUTO to stringResource(R.string.setup_dual_screen_auto), diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt index 9f9c1b4a4e..baa2b0e69a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt @@ -108,6 +108,7 @@ internal object SettingsIndex { s(SettingsSection.LAUNCHER, R.string.setup_launcher_orientation, "rotate", "portrait"), s(SettingsSection.LAUNCHER, R.string.setup_session_orientation, "rotate", "portrait"), s(SettingsSection.LAUNCHER, R.string.setup_fullscreen), + s(SettingsSection.LAUNCHER, R.string.setup_controller_haptics, "vibration", "rumble"), s(SettingsSection.LAUNCHER, R.string.setup_dual_screen_launcher, "thor", "second screen", "bottom screen"), s(SettingsSection.LAUNCHER, R.string.setup_low_storage_warning), s(SettingsSection.LAUNCHER, R.string.mode_sgdb_key, "artwork", "steamgriddb"), diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 3b7c9eecb9..a57afab493 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1035,6 +1035,8 @@ Fullscreen Hides the Android status and navigation bars Shows the Android status and navigation bars + Controller haptics + A light tick when the D-pad, A or the shoulder buttons move or select in the launcher. Touch stays silent Dual screen launcher Automatic puts the launcher sections (Steam, Library, Stores and the rest) on the second screen of handhelds with a built-in one. On uses any second display. Off keeps the launcher on one screen. Dual screen sessions diff --git a/docs/settings-map.md b/docs/settings-map.md index 8e19e9db84..a292309bc9 100644 --- a/docs/settings-map.md +++ b/docs/settings-map.md @@ -44,6 +44,7 @@ Links of the form `droiddeck://settings/
` open a Settings section direc | Launcher orientation | Settings › Launcher (`droiddeck://settings/launcher`) | rotate, portrait | | Session orientation | Settings › Launcher (`droiddeck://settings/launcher`) | rotate, portrait | | Fullscreen | Settings › Launcher (`droiddeck://settings/launcher`) | | +| Controller haptics | Settings › Launcher (`droiddeck://settings/launcher`) | vibration, rumble | | Dual screen launcher | Settings › Launcher (`droiddeck://settings/launcher`) | thor, second screen, bottom screen | | Warn when storage is low | Settings › Launcher (`droiddeck://settings/launcher`) | | | SteamGridDB API key | Settings › Launcher (`droiddeck://settings/launcher`) | artwork, steamgriddb | From 183cbd9351955f34cbf73cf9a35d53f9fbde23c9 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Sat, 21 Nov 2026 20:11:18 -0500 Subject: [PATCH 018/141] fix(preload): start apps that check for a single thread and stop the first-call allocation hang (#2995) * fix(preload): look up the native glibc symbol version first so wrapped calls never allocate On x86 the first dlvsym lookup asked for GLIBC_2.17, which only exists on arm64. The failed lookup makes glibc allocate, which deadlocks when the first wrapped call happens inside a program's own allocator setup. Each architecture now asks for its base version first. * fix(zram): start the page-out worker per request instead of keeping a thread in every process Every process that loaded the session preload carried a resident zr-worker thread from its constructor on. Programs that check they are single-threaded before forking or before unshare(CLONE_NEWUSER) failed, for example Chromium's zygote, which could not start its GPU process. The signal handler now starts the worker with a raw clone on a stack the preload maps itself. The worker makes only raw system calls and exits when no request is left, so starting it from the handler is safe and idle processes stay single-threaded. When the worker cannot be started, the process trims inline in small steps as before. * fix(preload): start the page-out worker with the same clone flags as a thread Programs that filter clone to the flag set threads use, as browser sandboxes do, now accept the worker. The kernel clears the stack-busy word and wakes waiters when the worker exits. * fix(preload): page out inline in single-threaded and self-sandboxed processes A process with one thread may be about to check that it is single-threaded before fork or unshare, and a process that added a seccomp filter after it started may trap system calls into its own handler. Neither gets a worker thread now; both trim inline in small steps as before. * fix(preload): check the signalled thread's own seccomp filters before starting the worker Read Seccomp_filters from /proc/thread-self/status so a thread that installed its own filter without TSYNC trims inline instead of calling clone under that filter, and fall back to the inline path when the signal mask cannot be changed. * test(preload): start parked threads with SIGURG already blocked * test(preload): count only page-out workers when checking for leftover threads --- docs/development/low-memory.md | 14 +- tools/linuxfs/preload/inputudev.c | 8 + tools/linuxfs/preload/zram.c | 312 +++++++++++++++++++++----- tools/tests/test_inputudev_preload.py | 73 +++++- tools/tests/test_zram_preload.py | 189 +++++++++++++--- 5 files changed, 509 insertions(+), 87 deletions(-) diff --git a/docs/development/low-memory.md b/docs/development/low-memory.md index 218d1fd8e9..50e78363ef 100644 --- a/docs/development/low-memory.md +++ b/docs/development/low-memory.md @@ -99,10 +99,16 @@ available. ## Threads -Page-out never runs on a thread of the game. The preload's signal handler only wakes its -`zr-worker` thread, which does the `madvise` calls. A forked process -without a worker trims inline in steps of at most 32 MiB per request and looks at no more -than 512 MiB of its address space each time. The page-out for a suspend and the read-back +When a worker can be started, page-out runs outside the game's threads. The preload's signal +handler starts a `zr-worker` thread for the request, which does the `madvise` calls and exits once no request +is left, so a process that is not paging out has no thread the preload added. Programs that +check they are single-threaded before they fork or call `unshare(CLONE_NEWUSER)`, such as +Chromium's zygote, keep working. The worker is a bare `clone` with the flags of a normal +thread, on a stack the preload maps itself, and makes only raw system calls, so starting it +from the signal handler is safe and seccomp filters that only allow thread clones accept it. A +process that has a single thread, or whose signalled thread added a seccomp filter after the +process started, as browser sandboxes do, gets no worker. When there is no worker, the process trims inline in steps of at most 32 MiB per request and +looks at no more than 512 MiB of its address space each time. The page-out for a suspend and the read-back after it are not limited there: they run once, while the process is being stopped or started, and cover all of it. The monitor is a shell loop in the session, outside every game process. diff --git a/tools/linuxfs/preload/inputudev.c b/tools/linuxfs/preload/inputudev.c index 823614bfd3..3dcb5a1049 100644 --- a/tools/linuxfs/preload/inputudev.c +++ b/tools/linuxfs/preload/inputudev.c @@ -1045,7 +1045,15 @@ static void *own_udev_symbol(const char *name) { } static void *dlvsym_any(const char *name) { +#if defined(__aarch64__) + static const char *versions[] = {"GLIBC_2.17", "GLIBC_2.34"}; +#elif defined(__x86_64__) + static const char *versions[] = {"GLIBC_2.2.5", "GLIBC_2.34"}; +#elif defined(__i386__) + static const char *versions[] = {"GLIBC_2.0", "GLIBC_2.34"}; +#else static const char *versions[] = {"GLIBC_2.17", "GLIBC_2.2.5", "GLIBC_2.0", "GLIBC_2.34"}; +#endif size_t i; void *resolved = NULL; diff --git a/tools/linuxfs/preload/zram.c b/tools/linuxfs/preload/zram.c index 551a6e148c..ad13d8258b 100644 --- a/tools/linuxfs/preload/zram.c +++ b/tools/linuxfs/preload/zram.c @@ -1,8 +1,9 @@ #define _GNU_SOURCE -#include +#pragma GCC optimize("no-stack-protector", "no-tree-loop-distribute-patterns") #include #include #include +#include #include #include #include @@ -10,6 +11,9 @@ #include #include #include +#if defined(__i386__) +#include +#endif #include @@ -31,13 +35,156 @@ #define ZR_INLINE_CHUNKS 512UL #define ZR_FAILED (~0UL) #define ZR_FUTEX_WAIT 0 -#define ZR_FUTEX_WAKE 1 +#define ZR_STACK (128UL << 10) +#define ZR_THREAD (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM | \ + CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID) +#define ZR_TEXT(x) #x +#define ZR_NR(x) ZR_TEXT(x) +#define ZR_CALL(n, a, b, c, d, e, f, ...) \ + zr_call((long)(n), (long)(a), (long)(b), (long)(c), (long)(d), (long)(e), (long)(f)) +#define zr_sys(...) ZR_CALL(__VA_ARGS__, 0, 0, 0, 0, 0, 0, 0) + +#if defined(__aarch64__) +#define ZR_MMAP SYS_mmap +__asm__(".pushsection .text\n" + ".p2align 2\n" + ".hidden zr_call\n" + ".type zr_call, %function\n" + "zr_call:\n" + " mov x8, x0\n" + " mov x0, x1\n" + " mov x1, x2\n" + " mov x2, x3\n" + " mov x3, x4\n" + " mov x4, x5\n" + " mov x5, x6\n" + " svc #0\n" + " ret\n" + ".size zr_call, . - zr_call\n" + ".hidden zr_clone\n" + ".type zr_clone, %function\n" + "zr_clone:\n" + " mov x5, x2\n" + " mov x2, x3\n" + " mov x3, x4\n" + " mov x4, x5\n" + " mov x8, #" ZR_NR(SYS_clone) "\n" + " svc #0\n" + " cbnz x0, 1f\n" + " mov x29, xzr\n" + " mov x30, xzr\n" + " bl zr_thread\n" + " mov x0, xzr\n" + " mov x8, #" ZR_NR(SYS_exit) "\n" + " svc #0\n" + " brk #0\n" + "1:\n" + " ret\n" + ".size zr_clone, . - zr_clone\n" + ".popsection\n"); +#elif defined(__x86_64__) +#define ZR_MMAP SYS_mmap +__asm__(".pushsection .text\n" + ".p2align 4\n" + ".hidden zr_call\n" + ".type zr_call, @function\n" + "zr_call:\n" + " mov %rdi, %rax\n" + " mov %rsi, %rdi\n" + " mov %rdx, %rsi\n" + " mov %rcx, %rdx\n" + " mov %r8, %r10\n" + " mov %r9, %r8\n" + " mov 8(%rsp), %r9\n" + " syscall\n" + " ret\n" + ".size zr_call, . - zr_call\n" + ".hidden zr_clone\n" + ".type zr_clone, @function\n" + "zr_clone:\n" + " mov %rdx, %r10\n" + " mov %rcx, %rdx\n" + " mov $" ZR_NR(SYS_clone) ", %eax\n" + " syscall\n" + " test %rax, %rax\n" + " jnz 1f\n" + " xor %ebp, %ebp\n" + " call zr_thread\n" + " xor %edi, %edi\n" + " mov $" ZR_NR(SYS_exit) ", %eax\n" + " syscall\n" + " hlt\n" + "1:\n" + " ret\n" + ".size zr_clone, . - zr_clone\n" + ".popsection\n"); +#elif defined(__i386__) +#define ZR_MMAP SYS_mmap2 +__asm__(".pushsection .text\n" + ".p2align 4\n" + ".hidden zr_call\n" + ".type zr_call, @function\n" + "zr_call:\n" + " push %ebp\n" + " push %edi\n" + " push %esi\n" + " push %ebx\n" + " mov 20(%esp), %eax\n" + " mov 24(%esp), %ebx\n" + " mov 28(%esp), %ecx\n" + " mov 32(%esp), %edx\n" + " mov 36(%esp), %esi\n" + " mov 40(%esp), %edi\n" + " mov 44(%esp), %ebp\n" + " int $0x80\n" + " pop %ebx\n" + " pop %esi\n" + " pop %edi\n" + " pop %ebp\n" + " ret\n" + ".size zr_call, . - zr_call\n" + ".hidden zr_clone\n" + ".type zr_clone, @function\n" + "zr_clone:\n" + " push %ebx\n" + " push %esi\n" + " push %edi\n" + " mov 16(%esp), %ebx\n" + " mov 20(%esp), %ecx\n" + " mov 24(%esp), %edi\n" + " mov 28(%esp), %edx\n" + " mov 32(%esp), %esi\n" + " mov $" ZR_NR(SYS_clone) ", %eax\n" + " int $0x80\n" + " test %eax, %eax\n" + " jnz 1f\n" + " xor %ebp, %ebp\n" + " call zr_thread\n" + " xor %ebx, %ebx\n" + " mov $" ZR_NR(SYS_exit) ", %eax\n" + " int $0x80\n" + " hlt\n" + "1:\n" + " pop %edi\n" + " pop %esi\n" + " pop %ebx\n" + " ret\n" + ".size zr_clone, . - zr_clone\n" + ".popsection\n"); +#else +#error "zram.c needs a raw system call for this architecture" +#endif + +long zr_call(long n, long a, long b, long c, long d, long e, long f) __attribute__((visibility("hidden"))); +long zr_clone(long flags, char *stack, int *child, int *parent, void *tls) __attribute__((visibility("hidden"))); +void zr_thread(void) __attribute__((visibility("hidden"))); -static long (*zr_sys)(long, ...); static unsigned long zr_page; -static int zr_busy; -static int zr_pending; -static int zr_worker; +static unsigned zr_requests; +static int zr_stack_busy; +static int zr_tid; +static long zr_filters; +static char *zr_stack; static char zr_maps[8192]; static uint64_t zr_entries[ZR_BATCH]; static struct iovec zr_iov[ZR_BATCH]; @@ -54,6 +201,18 @@ static uint16_t zr_gen = 1; static unsigned long zr_cursor; static unsigned long zr_visits; +static int zr_prefix(const char *text, const char *prefix) { + while (*prefix) + if (*text++ != *prefix++) return 0; + return 1; +} + +static char *zr_find(char *text, char c, size_t n) { + for (; n > 0; n--, text++) + if (*text == c) return text; + return NULL; +} + static int zr_open(const char *path) { return (int)zr_sys(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC, 0); } @@ -103,7 +262,7 @@ static int zr_eligible(const char *line, int compress, unsigned long *start, uns while (*p && *p != ' ') p++; while (*p == ' ') p++; } - return *p == 0 || strncmp(p, "[heap]", 6) == 0 || strncmp(p, "[anon:", 6) == 0; + return *p == 0 || zr_prefix(p, "[heap]") || zr_prefix(p, "[anon:"); } static void zr_read_back(int pagemap, unsigned long start, unsigned long end) { @@ -137,7 +296,7 @@ static unsigned long zr_count(int pagemap, unsigned long start, unsigned long en do { if (zr_sys(SYS_lseek, pagemap, (long)(start / zr_page * sizeof(uint64_t)), SEEK_SET) < 0) return ZR_FAILED; got = zr_sys(SYS_read, pagemap, zr_entries, size); - } while (got < 0 && errno == EINTR); + } while (got == -EINTR); if (got != size) return ZR_FAILED; for (long i = 0; i < got / (long)sizeof(uint64_t); i++) if (zr_entries[i] & bit) count++; @@ -157,8 +316,7 @@ static struct zr_slot *zr_slot(unsigned long addr, int create) { } } if (!create) return NULL; - memset(&zr_slots[home], 0, sizeof(zr_slots[home])); - zr_slots[home].key = key; + zr_slots[home] = (struct zr_slot){.key = key}; return &zr_slots[home]; } @@ -228,13 +386,13 @@ static unsigned long zr_walk(int mode, unsigned long want, unsigned long lo, uns size_t have = 0; while (done < want && zr_visits > 0) { long n = zr_sys(SYS_read, maps, zr_maps + have, sizeof(zr_maps) - 1 - have); - if (n < 0 && errno == EINTR) continue; + if (n == -EINTR) continue; if (n <= 0) break; have += (size_t)n; zr_maps[have] = 0; char *line = zr_maps; char *nl; - while (done < want && zr_visits > 0 && (nl = memchr(line, '\n', have - (size_t)(line - zr_maps))) != NULL) { + while (done < want && zr_visits > 0 && (nl = zr_find(line, '\n', have - (size_t)(line - zr_maps))) != NULL) { *nl = 0; unsigned long s, e; if (zr_eligible(line, mode != 0, &s, &e) && e > s) { @@ -245,7 +403,7 @@ static unsigned long zr_walk(int mode, unsigned long want, unsigned long lo, uns line = nl + 1; } have -= (size_t)(line - zr_maps); - memmove(zr_maps, line, have); + for (size_t i = 0; i < have; i++) zr_maps[i] = line[i]; if (have == sizeof(zr_maps) - 1) have = 0; } if (pagemap >= 0) zr_sys(SYS_close, pagemap); @@ -291,15 +449,88 @@ static void zr_request(int worker) { zr_ack((long)(done * (zr_page / 1024)), 1); } -static void *zr_worker_main(void *unused) { - (void)unused; - prctl(PR_SET_NAME, "zr-worker", 0, 0, 0); - for (;;) { - while (!__atomic_exchange_n(&zr_pending, 0, __ATOMIC_SEQ_CST)) - zr_sys(SYS_futex, &zr_pending, ZR_FUTEX_WAIT, 0, NULL, NULL, 0); - zr_request(1); +static void zr_drain(int worker) { + unsigned seen; + do { + seen = __atomic_load_n(&zr_requests, __ATOMIC_ACQUIRE); + zr_request(worker); + } while (!__atomic_compare_exchange_n(&zr_requests, &seen, 0, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)); +} + +void zr_thread(void) { + zr_sys(SYS_prctl, PR_SET_NAME, "zr-worker"); + zr_drain(1); +} + +static void *zr_tls(void *desc) { +#if defined(__aarch64__) + (void)desc; + return __builtin_thread_pointer(); +#elif defined(__x86_64__) + (void)desc; + void *self; + __asm__("mov %%fs:0, %0" : "=r"(self)); + return self; +#else + struct user_desc *entry = desc; + unsigned short selector; + __asm__("mov %%gs, %0" : "=r"(selector)); + entry->entry_number = selector >> 3; + return zr_sys(SYS_get_thread_area, entry) == 0 ? entry : NULL; +#endif +} + +static long zr_field(const char *text, const char *key) { + for (const char *line = text; *line; line++) { + if ((line == text || line[-1] == '\n') && zr_prefix(line, key)) { + long value = 0; + for (const char *k = key; *k; k++) line++; + while (*line == ' ' || *line == '\t') line++; + for (; *line >= '0' && *line <= '9'; line++) value = value * 10 + (*line - '0'); + return value; + } } - return NULL; + return -1; +} + +static int zr_status(long *threads, long *filters) { + int fd = zr_open("/proc/thread-self/status"); + if (fd < 0) return 0; + long have = 0, n; + while (have < (long)sizeof(zr_maps) - 1 && + ((n = zr_sys(SYS_read, fd, zr_maps + have, sizeof(zr_maps) - 1 - (size_t)have)) > 0 || n == -EINTR)) + if (n > 0) have += n; + zr_sys(SYS_close, fd); + zr_maps[have] = 0; + *threads = zr_field(zr_maps, "Threads:"); + *filters = zr_field(zr_maps, "Seccomp_filters:"); + return have > 0; +} + +static int zr_start(void) { + long threads, filters; + if (!zr_status(&threads, &filters) || threads < 2 || filters > zr_filters) return 0; + if (zr_stack == NULL) { + long base = zr_sys(ZR_MMAP, 0, ZR_STACK, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK | MAP_NORESERVE, -1, 0); + if ((unsigned long)base > -4096UL) return 0; + zr_stack = (char *)base; + } + struct { long sec, nsec; } wait = {0, 5000000}; + for (int i = 0; i < 20 && __atomic_load_n(&zr_stack_busy, __ATOMIC_ACQUIRE); i++) + zr_sys(SYS_futex, &zr_stack_busy, ZR_FUTEX_WAIT, 1, &wait, NULL, 0); + if (__atomic_load_n(&zr_stack_busy, __ATOMIC_ACQUIRE)) return 0; + uint64_t desc[4] = {0}; + void *tls = zr_tls(desc); + if (tls == NULL) return 0; + uint64_t all = ~0ULL, previous; + if (zr_sys(SYS_rt_sigprocmask, SIG_SETMASK, &all, &previous, sizeof(all)) != 0) return 0; + __atomic_store_n(&zr_stack_busy, 1, __ATOMIC_RELEASE); + long tid = zr_clone(ZR_THREAD, zr_stack + ZR_STACK, &zr_stack_busy, &zr_tid, tls); + zr_sys(SYS_rt_sigprocmask, SIG_SETMASK, &previous, NULL, sizeof(previous)); + if (tid > 0) return 1; + __atomic_store_n(&zr_stack_busy, 0, __ATOMIC_RELEASE); + return 0; } static void zr_handler(int sig, siginfo_t *info, void *context) { @@ -307,34 +538,23 @@ static void zr_handler(int sig, siginfo_t *info, void *context) { (void)context; if (info == NULL || info->si_code != SI_USER) return; int saved = errno; - __atomic_store_n(&zr_pending, 1, __ATOMIC_SEQ_CST); - if (__atomic_load_n(&zr_worker, __ATOMIC_ACQUIRE)) { - zr_sys(SYS_futex, &zr_pending, ZR_FUTEX_WAKE, 1, NULL, NULL, 0); - } else while (__atomic_load_n(&zr_pending, __ATOMIC_SEQ_CST) - && !__atomic_exchange_n(&zr_busy, 1, __ATOMIC_SEQ_CST)) { - __atomic_store_n(&zr_pending, 0, __ATOMIC_SEQ_CST); - zr_request(0); - __atomic_store_n(&zr_busy, 0, __ATOMIC_SEQ_CST); - } + if (__atomic_fetch_add(&zr_requests, 1, __ATOMIC_ACQ_REL) == 0 && !zr_start()) zr_drain(0); errno = saved; } static void zr_child(void) { - __atomic_store_n(&zr_busy, 0, __ATOMIC_SEQ_CST); - __atomic_store_n(&zr_pending, 0, __ATOMIC_SEQ_CST); - __atomic_store_n(&zr_worker, 0, __ATOMIC_RELEASE); + __atomic_store_n(&zr_requests, 0, __ATOMIC_RELEASE); + __atomic_store_n(&zr_stack_busy, 0, __ATOMIC_RELEASE); } __attribute__((constructor)) static void zr_init(void) { - void *libc = dlopen("libc.so.6", RTLD_LAZY | RTLD_NOLOAD); - if (libc == NULL) return; - zr_sys = (long (*)(long, ...))dlsym(libc, "syscall"); - if (zr_sys == NULL) return; int fd = zr_open(ZR_CTL); if (fd < 0) return; zr_sys(SYS_close, fd); long page = sysconf(_SC_PAGESIZE); zr_page = page > 0 ? (unsigned long)page : 4096UL; + long threads; + if (!zr_status(&threads, &zr_filters)) zr_filters = -1; struct sigaction old; if (sigaction(SIGURG, NULL, &old) != 0) return; if ((old.sa_flags & SA_SIGINFO) || old.sa_handler != SIG_DFL) return; @@ -343,21 +563,5 @@ __attribute__((constructor)) static void zr_init(void) { sa.sa_sigaction = zr_handler; sa.sa_flags = SA_SIGINFO | SA_RESTART; sigemptyset(&sa.sa_mask); - if (sigaction(SIGURG, &sa, NULL) == 0) { - pthread_atfork(NULL, NULL, zr_child); - pthread_attr_t attr; - if (pthread_attr_init(&attr) == 0) { - pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); - pthread_t thread; - sigset_t blocked; - sigset_t previous; - if (sigfillset(&blocked) == 0 && - pthread_sigmask(SIG_SETMASK, &blocked, &previous) == 0) { - if (pthread_create(&thread, &attr, zr_worker_main, NULL) == 0) - __atomic_store_n(&zr_worker, 1, __ATOMIC_RELEASE); - pthread_sigmask(SIG_SETMASK, &previous, NULL); - } - pthread_attr_destroy(&attr); - } - } + if (sigaction(SIGURG, &sa, NULL) == 0) pthread_atfork(NULL, NULL, zr_child); } diff --git a/tools/tests/test_inputudev_preload.py b/tools/tests/test_inputudev_preload.py index c1d970fd1d..8e4cf66e80 100644 --- a/tools/tests/test_inputudev_preload.py +++ b/tools/tests/test_inputudev_preload.py @@ -77,6 +77,66 @@ char *realpath(const char *path, char *resolved) { } """ +LOCKED = r""" +#include +#include + +extern int busy; + +__attribute__((constructor)) static void start(void) { + busy = 1; + syscall(SYS_getpid); + busy = 0; +} +""" + +ARENA = r""" +#include +#include +#include + +static _Alignas(64) unsigned char arena[1 << 23]; +static size_t used; +int busy; +static int busy_allocations; + +void *memalign(size_t align, size_t size) { + uintptr_t start; + if (busy) busy_allocations++; + if (align < 16) align = 16; + start = ((uintptr_t)(arena + used) + 16 + align - 1) & ~(uintptr_t)(align - 1); + if (start + size > (uintptr_t)(arena + sizeof(arena))) return NULL; + ((size_t *)start)[-1] = size; + used = start + size - (uintptr_t)arena; + return (void *)start; +} + +void *malloc(size_t size) { return memalign(16, size); } +void *aligned_alloc(size_t align, size_t size) { return memalign(align, size); } +int posix_memalign(void **out, size_t align, size_t size) { return (*out = memalign(align, size)) ? 0 : 12; } +void free(void *p) { (void)p; } + +void *calloc(size_t n, size_t size) { + void *p = malloc(n * size); + if (p) memset(p, 0, n * size); + return p; +} + +void *realloc(void *p, size_t size) { + void *q = malloc(size); + if (p && q) { + size_t old = ((size_t *)p)[-1]; + memcpy(q, p, old < size ? old : size); + } + return q; +} + +int main(void) { + printf("allocations %d\n", busy_allocations); + return 0; +} +""" + UDEV = r""" #include #include @@ -414,7 +474,7 @@ class InputUdevPreloadTest(unittest.TestCase): if "__GLIBC__" not in compile_c("-dM", "-E", "-x", "c", "-include", "limits.h", "/dev/null"): raise unittest.SkipTest("needs a glibc toolchain") sources = (("once.c", ONCE), ("first.c", FIRST), ("second.c", SECOND), ("chain.c", CHAIN), ("mark.c", MARK), - ("udev.c", UDEV), ("program.c", PROGRAM)) + ("udev.c", UDEV), ("program.c", PROGRAM), ("locked.c", LOCKED), ("arena.c", ARENA)) for name, text in sources: (build / name).write_text(text) cls.lib = cls.dir / "libddsession.so" @@ -427,6 +487,11 @@ class InputUdevPreloadTest(unittest.TestCase): compile_c("-shared", "-fPIC", "-O2", "-o", str(cls.udev), str(build / "udev.c")) cls.program = cls.dir / "program" compile_c("-O0", "-o", str(cls.program), str(build / "program.c"), str(cls.dir / "libfirst.so"), "-ldl") + compile_c("-shared", "-fPIC", "-O0", "-o", str(cls.dir / "liblocked.so"), str(build / "locked.c")) + cls.arena = cls.dir / "arena" + compile_c("-O0", "-rdynamic", "-o", str(cls.arena), str(build / "arena.c"), "-Wl,--no-as-needed", + str(cls.dir / "liblocked.so"), + f"-Wl,-rpath,{cls.dir}") cls.pads = cls.pad_dir("pads", "event0") @classmethod @@ -449,6 +514,12 @@ class InputUdevPreloadTest(unittest.TestCase): def test_a_lookup_from_another_preloads_initialiser_does_not_reenter_it(self): self.assertEqual(self.run_program("once", "libonce.so"), ["readlink 1"]) + def test_a_first_wrapped_call_inside_the_programs_allocator_does_not_allocate(self): + result = subprocess.run([str(self.arena)], env=dict(os.environ, LD_PRELOAD=str(self.lib)), capture_output=True, + text=True, timeout=20) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.splitlines(), ["allocations 0"]) + def test_the_real_lookup_still_sees_the_original_caller(self): self.assertEqual(self.run_program("next", "libfirst.so", "libsecond.so"), ["next 2"]) diff --git a/tools/tests/test_zram_preload.py b/tools/tests/test_zram_preload.py index bf1e8391cd..8a9f813480 100644 --- a/tools/tests/test_zram_preload.py +++ b/tools/tests/test_zram_preload.py @@ -18,7 +18,14 @@ PROGRAM = r""" #include #include #include +#include +#include +#include +#include +#include #include +#include +#include #include #include #include @@ -31,14 +38,15 @@ static unsigned char *shared; static volatile sig_atomic_t urg_tid; static volatile sig_atomic_t usr_tid; static int urg_count, usr_count; -static int worker_tid; static int worker_delivery; _Static_assert(__atomic_always_lock_free(sizeof(int), 0), "signal state must be lock-free"); static void signal_tid(int sig) { sig_atomic_t tid = (sig_atomic_t)syscall(SYS_gettid); - if (tid == __atomic_load_n(&worker_tid, __ATOMIC_RELAXED)) + char name[16] = {0}; + prctl(PR_GET_NAME, name, 0, 0, 0); + if (!strcmp(name, "zr-worker")) __atomic_store_n(&worker_delivery, 1, __ATOMIC_RELAXED); if (sig == SIGURG) { __atomic_store_n(&urg_tid, tid, __ATOMIC_RELAXED); @@ -123,6 +131,75 @@ static long trim(char mode, long kb) { exit(5); } +static int workers(void) { + DIR *dir = opendir("/proc/self/task"); + struct dirent *entry; + int count = 0; + while (dir && (entry = readdir(dir)) != NULL) { + if (entry->d_name[0] == '.') continue; + char path[64], name[32] = {0}; + snprintf(path, sizeof(path), "/proc/self/task/%s/comm", entry->d_name); + FILE *comm = fopen(path, "r"); + if (comm && fgets(name, sizeof(name), comm) && !strcmp(name, "zr-worker\n")) count++; + if (comm) fclose(comm); + } + if (dir) closedir(dir); + return count; +} + +static void without_threads(void) { + struct rlimit limit; + if (getrlimit(RLIMIT_NPROC, &limit)) _exit(15); + limit.rlim_cur = 0; + if (setrlimit(RLIMIT_NPROC, &limit)) _exit(15); +} + +static void *park(void *arg) { + (void)arg; + for (;;) pause(); + return NULL; +} + +static void parked(void) { + pthread_t thread; + sigset_t urg, previous; + sigemptyset(&urg); + sigaddset(&urg, SIGURG); + pthread_sigmask(SIG_BLOCK, &urg, &previous); + if (pthread_create(&thread, NULL, park, NULL)) _exit(16); + pthread_sigmask(SIG_SETMASK, &previous, NULL); +} + +static void filter_clone(unsigned long allowed) { + struct sock_filter rules[] = { + BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SYS_clone, 0, 3), + BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, args[0])), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, allowed, 1, 0), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_KILL_PROCESS), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW), + }; + struct sock_fprog program = {sizeof(rules) / sizeof(rules[0]), rules}; + if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) || prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &program)) _exit(17); +} + +static volatile int sandbox_ready; + +static void *sandbox(void *arg) { + (void)arg; + sigset_t urg; + sigemptyset(&urg); + sigaddset(&urg, SIGURG); + filter_clone(0); + pthread_sigmask(SIG_UNBLOCK, &urg, NULL); + sandbox_ready = 1; + for (;;) pause(); + return NULL; +} + +static const unsigned long thread_clone = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | + CLONE_SYSVSEM | CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID; + static uint64_t sum(const unsigned char *p, size_t n) { uint64_t s = 0; for (size_t i = 0; i < n; i += 64) s = s * 31 + p[i]; @@ -155,6 +232,7 @@ int main(int argc, char **argv) { memset(shared, 0, size); pthread_t t[2]; for (uintptr_t i = 0; i < 2; i++) pthread_create(&t[i], NULL, writer, (void *)i); + parked(); struct sigaction sa; sigaction(SIGURG, NULL, &sa); printf("handler %d\n", (sa.sa_flags & SA_SIGINFO) ? 1 : 0); @@ -164,27 +242,21 @@ int main(int argc, char **argv) { memset(&signal_action, 0, sizeof(signal_action)); signal_action.sa_handler = signal_tid; sigemptyset(&signal_action.sa_mask); - sigaction(SIGURG, &signal_action, NULL); sigaction(SIGUSR1, &signal_action, NULL); + int fd = open(ctl, O_WRONLY | O_TRUNC); + if (fd < 0 || write(fd, "1", 1) != 1) return 10; + close(fd); printf("ready %d\n", getpid()); fflush(stdout); - int id; - if (scanf("%d", &id) != 1) return 10; - __atomic_store_n(&worker_tid, id, __ATOMIC_RELAXED); - printf("armed 1\n"); - fflush(stdout); for (int round = 1; round <= 100; round++) { int i; - for (i = 0; i < 5000 && - (__atomic_load_n(&urg_count, __ATOMIC_ACQUIRE) < round || - __atomic_load_n(&usr_count, __ATOMIC_ACQUIRE) < round); i++) usleep(1000); + for (i = 0; i < 5000 && __atomic_load_n(&usr_count, __ATOMIC_ACQUIRE) < round; i++) usleep(1000); if (i == 5000) return 11; printf("received %d\n", round); fflush(stdout); } stop = 1; for (int i = 0; i < 2; i++) pthread_join(t[i], NULL); - printf("urg %d\n", __atomic_load_n(&urg_tid, __ATOMIC_RELAXED)); printf("usr %d\n", __atomic_load_n(&usr_tid, __ATOMIC_RELAXED)); printf("worker %d\n", __atomic_load_n(&worker_delivery, __ATOMIC_RELAXED)); return 0; @@ -199,6 +271,13 @@ int main(int argc, char **argv) { int status_code; waitpid(child, &status_code, 0); printf("childack %d\n", WIFEXITED(status_code) && WEXITSTATUS(status_code) == 0); + } else if (!strcmp(argv[4], "threads")) { + stop = 1; + for (int i = 0; i < 2; i++) pthread_join(t[i], NULL); + printf("idle %d\n", workers()); + request('1'); + printf("after %d\n", workers()); + return 0; } else if (!strcmp(argv[4], "trim")) { stop = 1; for (int i = 0; i < 2; i++) pthread_join(t[i], NULL); @@ -271,8 +350,47 @@ int main(int argc, char **argv) { _exit(0); } waitpid(child, NULL, 0); + child = fork(); + if (child < 0) exit(6); + if (child == 0) { + parked(); + without_threads(); + for (size_t i = 0; i < size; i += page) data[i]++; + printf("nothread_trim %ld\n", trim('2', 1L << 30)); + fflush(stdout); + _exit(0); + } + waitpid(child, NULL, 0); printf("worker_trim %ld\n", trim('2', 1L << 30)); return 0; + } else if (!strcmp(argv[4], "sandboxed")) { + stop = 1; + for (int i = 0; i < 2; i++) pthread_join(t[i], NULL); + filter_clone(thread_clone); + printf("sandboxed_trim %ld\n", trim('2', 1L << 30)); + return 0; + } else if (!strcmp(argv[4], "thread-sandboxed")) { + stop = 1; + for (int i = 0; i < 2; i++) pthread_join(t[i], NULL); + sigset_t urg; + sigemptyset(&urg); + sigaddset(&urg, SIGURG); + pthread_sigmask(SIG_BLOCK, &urg, NULL); + pthread_t thread; + if (pthread_create(&thread, NULL, sandbox, NULL)) exit(16); + while (!sandbox_ready) usleep(1000); + printf("thread_sandboxed_trim %ld\n", trim('2', 1L << 30)); + return 0; + } else if (!strcmp(argv[4], "filtered")) { + fflush(stdout); + filter_clone(thread_clone); + execl("/proc/self/exe", argv[0], argv[1], argv[2], "0", "filtered-trim", (char *)NULL); + return 18; + } else if (!strcmp(argv[4], "filtered-trim")) { + stop = 1; + for (int i = 0; i < 2; i++) pthread_join(t[i], NULL); + printf("filtered_trim %ld\n", trim('2', 1L << 30)); + return 0; } else if (!strcmp(argv[4], "burst")) { send_request('0'); usleep(10000); @@ -283,6 +401,7 @@ int main(int argc, char **argv) { pid_t child = fork(); if (child < 0) exit(8); if (child == 0) { + without_threads(); if (!strcmp(argv[4], "timed-inline-single")) { if (munmap(data, size) || munmap(shared, size)) _exit(12); data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); @@ -431,6 +550,11 @@ class ZramPreloadTest(unittest.TestCase): self.assertEqual([1], out["intact"]) self.assertEqual(6, len(out["out"])) + def test_a_process_keeps_no_extra_thread_while_nothing_is_paged_out(self): + out = self.run_program(None, 8, 0, "threads") + self.assertEqual([0], out["idle"]) + self.assertEqual([0], out["after"]) + def test_process_signals_do_not_reach_zram_worker(self): environment = dict(os.environ, LD_PRELOAD=str(self.lib)) process = subprocess.Popen([str(self.steam), str(self.ctl), "1", "0", "signals"], @@ -439,30 +563,16 @@ class ZramPreloadTest(unittest.TestCase): process.stdout.readline() ready = process.stdout.readline().split() self.assertEqual("ready", ready[0]) - worker = None - task_dir = Path("/proc") / ready[1] / "task" - for task in task_dir.iterdir(): - if (task / "comm").read_text().strip() == "zr-worker": - worker = int(task.name) - break - self.assertIsNotNone(worker) - self.assertEqual(os.sched_getscheduler(process.pid), os.sched_getscheduler(worker)) - process.stdin.write(f"{worker}\n") - process.stdin.flush() - self.assertEqual("armed 1", process.stdout.readline().strip()) - for _ in range(100): + for round in range(100): os.kill(process.pid, signal.SIGURG) os.kill(process.pid, signal.SIGUSR1) - self.assertEqual(f"received {_ + 1}", process.stdout.readline().strip()) + self.assertEqual(f"received {round + 1}", process.stdout.readline().strip()) process.stdin.close() process.wait(timeout=10) output = process.stdout.read() values = dict(line.split() for line in output.splitlines()) - self.assertNotEqual(0, int(values["urg"])) self.assertNotEqual(0, int(values["usr"])) self.assertEqual(0, int(values["worker"])) - self.assertNotEqual(worker, int(values["urg"])) - self.assertNotEqual(worker, int(values["usr"])) finally: if process.poll() is None: process.kill() @@ -537,10 +647,33 @@ class ZramPreloadTest(unittest.TestCase): @unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap") def test_process_without_a_worker_trims_in_small_steps(self): + if os.geteuid() == 0: + self.skipTest("the thread limit does not apply to root") + out = self.run_program(None, 48, 0, "trim-fork") + self.assertTrue(16 * 1024 < out["nothread_trim"][0] <= 32 * 1024, out) + self.assertGreater(out["worker_trim"][0], 64 * 1024, out) + + @unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap") + def test_a_single_threaded_process_trims_without_starting_a_thread(self): out = self.run_program(None, 48, 0, "trim-fork") self.assertTrue(16 * 1024 < out["inline_trim"][0] <= 32 * 1024, out) self.assertGreater(out["worker_trim"][0], 64 * 1024, out) + @unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap") + def test_a_process_that_sandboxed_itself_trims_without_starting_a_thread(self): + out = self.run_program(None, 48, 0, "sandboxed") + self.assertTrue(16 * 1024 < out["sandboxed_trim"][0] <= 32 * 1024, out) + + @unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap") + def test_a_thread_that_sandboxed_itself_trims_without_starting_a_thread(self): + out = self.run_program(None, 48, 0, "thread-sandboxed") + self.assertTrue(16 * 1024 < out["thread_sandboxed_trim"][0] <= 32 * 1024, out) + + @unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap") + def test_the_worker_passes_a_filter_that_only_allows_thread_clones(self): + out = self.run_program(None, 48, 0, "filtered") + self.assertGreater(out["filtered_trim"][0], 40 * 1024, out) + def test_worker_acknowledges_back_to_back_requests(self): out = self.run_program(None, 48, 0, "burst") self.assertEqual([1], out["burstack"]) From 378175c6ac309f58ef3ef170334d37e95aa14758 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Sat, 21 Nov 2026 20:11:21 -0500 Subject: [PATCH 019/141] feat(input): controller-specific on-screen controls with editor, rotation and tablet fixes (#2988) * feat(input): restore controller-specific overlay designs * fix(input): restore portrait controller layouts * fix(input): fix duplicates, rotation and tablet placement in the controller overlays - Hide the below-game controls while the layout editor is open, and give the editor the same cutout insets and optional Steam controls as the game view, so the editor never shows a second copy of a control. - Keep a separate portrait frame for layouts edited in portrait. A layout edited in one orientation keeps the stock kit positions in the other instead of being stretched across. - Anchor the overlay to the bottom of the screen and cap the portrait panel's physical size, so tablets keep the controls in the lower half. - Put L2/L1 and R1/R2 side by side in every kit. - List deleted stock controls in the editor's Add dialog so they can be restored, and keep removed rear buttons and trackpads removed. * fix(input): scale edited overlay layouts around the controller artwork positions * fix(input): keep stock landscape controls, color setting, keyboard action and displayed frame edits consistent * fix(input): draw the layout editor with the kit artwork at the size it will be saved The editor placed its controls in onSizeChanged, which runs during layout, so the preview canvas was rebuilt or remeasured too late: new controls were laid out at 0x0 and existing ones kept stale sizes, losing the kit D-pad artwork. Placement now happens in onMeasure, before the canvas measures its children. The editor preview used the saved button size instead of the slider value, so the slider showed a different layout from the one Done saved. D-pad pieces that joined or left the kit cross were never redrawn, so moving one piece hid all four. * fix(input): keep portrait rear buttons and trackpads where they were saved A portrait save stores the rear buttons and trackpads only in the rotated frame, but loading that frame only moved controls that already existed in the main frame, so they were regenerated at the screen edges. * fix(input): adopt the displayed portrait frame for layouts edited only in landscape Button size and reset positions now switch to the frame on screen whenever the edited layout's orientation differs from the editor, not only when a rotated frame exists, so a portrait change is saved as the portrait frame instead of overwriting the landscape edits. The tools panel stays open while that happens. * fix(input): keep a separate button size for the rotated frame * fix(input): take the shown frame's button size whenever editing switches orientation --------- Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> --- .../com/droiddeck/launcher/SessionActivity.kt | 10 +- ...ometry.kt => ControllerOverlayGeometry.kt} | 92 ++++- .../input/ControllerPortraitGeometry.kt | 127 ++++++ .../launcher/input/FloatingSteamOverlay.kt | 3 +- .../launcher/input/InputLibraries.kt | 35 +- .../droiddeck/launcher/input/InputLibrary.kt | 5 + .../launcher/input/LegacyGamepadLayout.kt | 34 +- .../launcher/input/OnScreenControls.kt | 21 +- .../launcher/input/OnScreenLayout.kt | 82 +++- .../com/droiddeck/launcher/input/PadKit.kt | 54 +++ .../launcher/ui/InputLayoutWidgets.kt | 8 +- .../launcher/ui/InputSettingsPage.kt | 2 +- .../launcher/ui/InputSurfaceDialog.kt | 106 ++++- .../launcher/ui/InputSurfaceEditorView.kt | 30 +- .../droiddeck/launcher/ui/InputSurfaceView.kt | 76 ++-- .../java/com/droiddeck/launcher/ui/PadArt.kt | 378 ++++++++++++++++++ .../launcher/ui/SteamDeckButtonArt.kt | 277 ------------- .../launcher/input/InputLayoutToolsTest.kt | 1 + .../launcher/input/OnScreenLayoutTest.kt | 192 ++++++++- .../launcher/ui/InputSettingsTest.kt | 58 +++ .../launcher/ui/InputSurfaceEditorViewTest.kt | 170 +++++++- .../launcher/ui/InputSurfaceTouchTest.kt | 10 +- 22 files changed, 1345 insertions(+), 426 deletions(-) rename app/src/main/java/com/droiddeck/launcher/input/{SteamDeckOverlayGeometry.kt => ControllerOverlayGeometry.kt} (53%) create mode 100644 app/src/main/java/com/droiddeck/launcher/input/ControllerPortraitGeometry.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/input/PadKit.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/ui/PadArt.kt delete mode 100644 app/src/main/java/com/droiddeck/launcher/ui/SteamDeckButtonArt.kt diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index a95ae09118..db0ac0f2b1 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -1752,6 +1752,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde com.droiddeck.launcher.session.InputSysfsComponent.padTypeChanged(SessionPrefs.padType(id)) padType = id onScreenControls?.reload() + applyUnfoldedControls() + unfoldedPanel?.reload() bottomInputControls?.reload() }, backHold = backHold, @@ -4629,7 +4631,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde else "unfolded controls: game full screen") } val portrait = !com.droiddeck.launcher.session.SessionDisplay.foldable(this) - val dock = if (SessionState.deckPad) com.droiddeck.launcher.input.OnScreenLayout.Dock.deck(portrait, deckPanelLayouts[com.droiddeck.launcher.input.DeckPanel.GAMEPAD]) + val kit = com.droiddeck.launcher.input.PadKit.forOverlay(this, primaryInputLayout) + val dock = if (SessionState.deckPad && kit?.steam != false) + com.droiddeck.launcher.input.OnScreenLayout.Dock.deck(portrait, deckPanelLayouts[com.droiddeck.launcher.input.DeckPanel.GAMEPAD]) else com.droiddeck.launcher.input.OnScreenLayout.Dock(portrait, false) var panel = unfoldedPanel if (panel != null && (!wanted || panel.dock != dock)) { @@ -5510,6 +5514,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde .takeIf { it.isFile } ?.let { FileUtils.readString(it)?.trim()?.lowercase() } ?: SessionPrefs.oscMode(this, SessionState.mode == SessionService.MODE_STEAM) + unfoldedColumn?.let { column -> + val shown = if (inputSettingsOpen) View.INVISIBLE else View.VISIBLE + if (column.visibility != shown) { unfoldedPanel?.releaseAll(); unfoldedDeckSurface?.releaseInputs(); column.visibility = shown } + } val controls = onScreenControls ?: return fun showPinned() { controls.setPinnedOnly(true) diff --git a/app/src/main/java/com/droiddeck/launcher/input/SteamDeckOverlayGeometry.kt b/app/src/main/java/com/droiddeck/launcher/input/ControllerOverlayGeometry.kt similarity index 53% rename from app/src/main/java/com/droiddeck/launcher/input/SteamDeckOverlayGeometry.kt rename to app/src/main/java/com/droiddeck/launcher/input/ControllerOverlayGeometry.kt index 4efd5e1fda..c5d33d9508 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/SteamDeckOverlayGeometry.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/ControllerOverlayGeometry.kt @@ -5,7 +5,7 @@ import android.util.DisplayMetrics import kotlin.math.max import kotlin.math.min -internal class SteamDeckOverlayGeometry( +internal class ControllerOverlayGeometry( width: Int, height: Int, private val safe: Rect, metrics: DisplayMetrics, scale: Float, ) { private val w = width.toFloat() @@ -29,9 +29,12 @@ internal class SteamDeckOverlayGeometry( } } - fun place(elements: List, rearButtons: Boolean, trackpads: Boolean): List { - val x = { ref: Float -> anchor(ref, 1600f, w, safe.left, safe.right) } - val y = { ref: Float -> anchor(ref, 900f, h, safe.top, safe.bottom) } + private fun x(ref: Float) = anchor(ref, 1600f, w, safe.left, safe.right) + + private fun y(ref: Float) = max(safe.top + ref * unit, h - safe.bottom - (900f - ref) * unit) + + fun place(elements: List, kit: PadKit, rearButtons: Boolean, trackpads: Boolean): List { + if (!kit.steam) return placeStandardPad(elements, kit) val leftEdge = safe.left + 52f * density val middle = (w + safe.left - safe.right) / 2f val keyboard = Box(max(x(136f), leftEdge + 46f * unit), y(848f), 46f).takeIf { elements.any { it.id == KEYBOARD } } @@ -41,15 +44,7 @@ internal class SteamDeckOverlayGeometry( Box(middle + 140f * unit, y(850f), 46f, 26f), Box(x(1230f), y(852f), 66f, 30f)), leftEdge) val (guide, select, start, qam) = row.takeLast(4) - val positions = mapOf( - InputControl.LT to Box(x(140f), y(66f), 88f, 34f), - InputControl.LB to Box(x(140f), y(148f), 88f, 30f), - InputControl.RT to Box(x(1460f), y(66f), 88f, 34f), - InputControl.RB to Box(x(1460f), y(148f), 88f, 30f), - InputControl.Y to Box(x(1375f), y(345f) - 96f * unit, 58f), - InputControl.X to Box(x(1375f) - 96f * unit, y(345f), 58f), - InputControl.B to Box(x(1375f) + 96f * unit, y(345f), 58f), - InputControl.A to Box(x(1375f), y(345f) + 96f * unit, 58f), + val positions = shoulders() + face(1375f, 345f, 96f) + mapOf( InputControl.UP to Box(x(220f), y(345f) - 102.5f * unit, 55.5f, 47.5f), InputControl.RIGHT to Box(x(220f) + 102.5f * unit, y(345f), 47.5f, 55.5f), InputControl.DOWN to Box(x(220f), y(345f) + 102.5f * unit, 55.5f, 47.5f), @@ -80,12 +75,81 @@ internal class SteamDeckOverlayGeometry( else -> positions[element.control]?.place(element) ?: element } } + val chosen = placed.filter { it.id == "legacy:${it.control.id}" }.map { it.control } return placed + optional.mapNotNull { (control, box) -> - if (placed.any { it.id == "legacy:${control.id}" }) null else box.place(InputSurfaceElement(control, + if (chosen.any { if (control in rear) it in rear else it in pads }) null else box.place(InputSurfaceElement(control, 0f, 0f, 0f, 0f, floating = false, buttonShape = InputButtonShape.PILL, showLabel = !control.isTrackpad)) } } + private fun placeStandardPad(elements: List, kit: PadKit): List { + val leftEdge = safe.left + 52f * density + val middle = (w + safe.left - safe.right) / 2f + val keyboard = Box(max(x(136f), leftEdge + 46f * unit), y(848f), 46f).takeIf { elements.any { it.id == KEYBOARD } } + val controls = if (kit.playStation) listOf( + InputControl.QAM to Box(x(220f), y(848f), 46f), + InputControl.SELECT to Box(middle - 160f * unit, y(850f), 50f, 30f), + InputControl.GUIDE to Box(middle, y(850f), 46f), + InputControl.START to Box(middle + 160f * unit, y(850f), 50f, 30f), + ) else listOf( + InputControl.QAM to Box(x(220f), y(848f), 46f), + InputControl.SELECT to Box(middle - 110f * unit, y(850f), 38f), + InputControl.GUIDE to Box(middle, y(850f), 46f), + InputControl.START to Box(middle + 110f * unit, y(850f), 38f), + ) + val row = fitRow(listOfNotNull(keyboard) + controls.map { it.second }, leftEdge) + val positions = controls.map { it.first }.zip(row.takeLast(controls.size)).toMap() + shoulders() + + if (kit.playStation) { + face(1350f, 395f, 96f) + dpad(250f, 395f, 125f, kit.dpad) + mapOf( + InputControl.LS to Box(x(565f), y(690f), 100f), + InputControl.RS to Box(x(1035f), y(690f), 100f), + InputControl.L3 to Box(x(565f) - 135f * unit, y(690f) - 100f * unit, 42f), + InputControl.R3 to Box(x(1035f) + 135f * unit, y(690f) - 100f * unit, 42f), + ) + } else { + face(1375f, 400f, 94f) + dpad(470f, 675f, 118f, kit.dpad) + mapOf( + InputControl.LS to Box(x(235f), y(400f), 104f), + InputControl.RS to Box(x(1130f), y(690f), 104f), + InputControl.L3 to Box(x(235f) + 150f * unit, y(400f) - 110f * unit, 42f), + InputControl.R3 to Box(x(1130f) + 160f * unit, y(690f) + 100f * unit, 42f), + ) + } + return elements.map { element -> + when (element.id) { + KEYBOARD -> row.first().place(element) + "legacy:${element.control.id}" -> positions[element.control]?.place(element) ?: element + else -> element + } + } + } + + private fun shoulders() = mapOf( + InputControl.LT to Box(x(120f), y(96f), 80f, 34f), + InputControl.LB to Box(x(310f), y(96f), 80f, 34f), + InputControl.RB to Box(x(1290f), y(96f), 80f, 34f), + InputControl.RT to Box(x(1480f), y(96f), 80f, 34f), + ) + + private fun face(cx: Float, cy: Float, offset: Float) = mapOf( + InputControl.Y to Box(x(cx), y(cy) - offset * unit, 58f), + InputControl.X to Box(x(cx) - offset * unit, y(cy), 58f), + InputControl.B to Box(x(cx) + offset * unit, y(cy), 58f), + InputControl.A to Box(x(cx), y(cy) + offset * unit, 58f), + ) + + private fun dpad(cx: Float, cy: Float, radius: Float, style: DpadStyle): Map { + val inner = radius * if (style == DpadStyle.DISC) .25f else .14f + val depth = (radius - inner) / 2f + val offset = (radius - depth) * unit + val side = radius * .25f + return mapOf( + InputControl.UP to Box(x(cx), y(cy) - offset, side, depth), + InputControl.RIGHT to Box(x(cx) + offset, y(cy), depth, side), + InputControl.DOWN to Box(x(cx), y(cy) + offset, side, depth), + InputControl.LEFT to Box(x(cx) - offset, y(cy), depth, side), + ) + } + private fun fitRow(row: List, start: Float): List { val end = w - safe.right val gap = ((end - start - row.fold(0f) { sum, box -> sum + box.width }) / (row.size - 1)).coerceIn(0f, 8f * density) diff --git a/app/src/main/java/com/droiddeck/launcher/input/ControllerPortraitGeometry.kt b/app/src/main/java/com/droiddeck/launcher/input/ControllerPortraitGeometry.kt new file mode 100644 index 0000000000..907d71c70d --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/ControllerPortraitGeometry.kt @@ -0,0 +1,127 @@ +package com.droiddeck.launcher.input + +import android.graphics.Rect +import com.droiddeck.launcher.input.GamepadGeometry.Box +import kotlin.math.min + +internal class ControllerPortraitGeometry( + private val width: Float, + private val height: Float, + private val safe: Rect, + private val density: Float, +) { + fun place( + elements: List, kit: PadKit, docked: Boolean, scale: Float, + rearButtons: Boolean, trackpads: Boolean, + ): List { + val w = width - safe.left - safe.right + val h = height - safe.top - safe.bottom + if (w <= 0 || h <= 0) return elements + val presented = elements.toMutableList() + val buttons = mutableMapOf() + val rear = presented.filter { it.control in REAR && isStock(it) } + val pads = presented.filter { it.control.isTrackpad && isStock(it) } + if (!docked && kit.steam) { + if (!rearButtons) presented.removeAll(rear) else if (rear.isEmpty()) REAR.forEach { addOptional(presented, it) } + if (!trackpads) presented.removeAll(pads) else if (pads.isEmpty()) { + addOptional(presented, InputControl.LEFT_PAD) + addOptional(presented, InputControl.RIGHT_PAD) + } + } + fun put(control: InputControl, box: Box) { buttons["legacy:${control.id}"] = box } + val reserve = if (docked) 0f else min(60f * density, h * .15f) + val panel = if (docked) h else min(minOf(h * .60f, w * 1.15f, PANEL_DP * density) * scale, h - reserve) + val top = height - safe.bottom - reserve - panel + val unit = min(density, min(w / 275f, panel / 300f)) + val pad = 8f * unit + val gap = 8f * unit + val buttonHeight = 44f * unit + val shoulders = if (docked) listOf(InputControl.LT, InputControl.LB, InputControl.SELECT, InputControl.START, InputControl.RB, InputControl.RT) + else listOf(InputControl.LT, InputControl.LB, InputControl.RB, InputControl.RT) + fun row(controls: List, y: Float, rowHeight: Float, spacing: Float) { + val cell = (w - 2f * pad - (controls.size - 1) * spacing) / controls.size + controls.forEachIndexed { index, control -> + put(control, Box(safe.left + pad + cell / 2f + index * (cell + spacing), y, cell, rowHeight)) + } + } + row(shoulders, top + pad + buttonHeight / 2f, buttonHeight, 4f * unit) + var bodyTop = top + pad + buttonHeight + gap + if (presented.any { it.control in REAR && isStock(it) }) { + val rearHeight = min(56f * unit, (panel - bodyTop + top) * .12f).coerceAtLeast(buttonHeight) + row(REAR, bodyTop + rearHeight / 2f, rearHeight, gap) + bodyTop += rearHeight + gap + } + val floor = height - safe.bottom - reserve - pad + val bodyHeight = floor - bodyTop - gap + if (bodyHeight <= 0f) return elements + val hasLeftPad = presented.any { it.control == InputControl.LEFT_PAD && isStock(it) } + val hasRightPad = presented.any { it.control == InputControl.RIGHT_PAD && isStock(it) } + val hasLeftStick = presented.any { it.control == InputControl.LS && isStock(it) } + val hasRightStick = presented.any { it.control == InputControl.RS && isStock(it) } + val four = hasLeftPad && hasLeftStick || hasRightPad && hasRightStick + val main = min(w * .46f, bodyHeight * .53f) + val second = min(w * .42f, bodyHeight - main) + val mainY = floor - main / 2f + val secondY = bodyTop + second / 2f + val left = safe.left + w * .25f + val right = safe.left + w * .75f + if (four) { + val col = (w - 2f * pad - 3f * gap) / 4f + val stick = min(col, main) + put(InputControl.LEFT_PAD, Box(safe.left + pad + col * .5f, mainY, col, main)) + put(InputControl.LS, Box(safe.left + pad + col * 1.5f + gap, mainY, stick, stick)) + put(InputControl.RS, Box(safe.left + w - pad - col * 1.5f - gap, mainY, stick, stick)) + put(InputControl.RIGHT_PAD, Box(safe.left + w - pad - col * .5f, mainY, col, main)) + } else { + put(if (hasLeftPad) InputControl.LEFT_PAD else InputControl.LS, Box(left, mainY, main, main)) + put(if (hasRightPad) InputControl.RIGHT_PAD else InputControl.RS, Box(right, mainY, main, main)) + } + val radius = second / 2f + val armWidth = radius * if (kit.dpad == DpadStyle.CROSS) .37f else .25f + val inner = if (kit.dpad == DpadStyle.ARROWS) radius * .14f else armWidth + val depth = radius - inner + val distance = (radius + inner) / 2f + put(InputControl.UP, Box(left, secondY - distance, armWidth * 2f, depth)) + put(InputControl.RIGHT, Box(left + distance, secondY, depth, armWidth * 2f)) + put(InputControl.DOWN, Box(left, secondY + distance, armWidth * 2f, depth)) + put(InputControl.LEFT, Box(left - distance, secondY, depth, armWidth * 2f)) + val face = second * .34f + val spread = second * .30f + put(InputControl.Y, Box(right, secondY - spread, face, face)) + put(InputControl.X, Box(right - spread, secondY, face, face)) + put(InputControl.B, Box(right + spread, secondY, face, face)) + put(InputControl.A, Box(right, secondY + spread, face, face)) + if (!docked) { + val ids = listOf(KEYBOARD, "legacy:guide", "legacy:select", "legacy:start", "legacy:qam") + .filter { id -> presented.any { it.id == id } } + val inset = min(52f * density, w * .17f) + val rowWidth = (w - inset - pad - gap * (ids.size - 1)) / ids.size.coerceAtLeast(1) + val rowHeight = min(reserve * .8f, 44f * unit) + ids.forEachIndexed { i, id -> + val center = safe.left + inset + rowWidth / 2f + i * (rowWidth + gap) + buttons[id] = Box(center, height - safe.bottom - reserve / 2f, rowWidth, rowHeight) + } + } + return presented.map { element -> + val box = buttons[element.id] + if (box == null) element else element.copy( + x = box.left / width, y = box.top / height, width = box.width / width, height = box.height / height, + ).bounded() + } + } + + private fun isStock(element: InputSurfaceElement) = element.id == "legacy:${element.control.id}" + + private fun addOptional(elements: MutableList, control: InputControl) { + if (elements.none { it.control == control && isStock(it) }) { + elements += InputSurfaceElement(control, 0f, 0f, 0f, 0f, floating = false, + buttonShape = InputButtonShape.PILL, showLabel = !control.isTrackpad) + } + } + + private companion object { + const val KEYBOARD = "builtin:keyboard" + const val PANEL_DP = 504f + val REAR = listOf(InputControl.L4, InputControl.L5, InputControl.R5, InputControl.R4) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/FloatingSteamOverlay.kt b/app/src/main/java/com/droiddeck/launcher/input/FloatingSteamOverlay.kt index 0dcbf8764f..39a916fbcd 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/FloatingSteamOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/FloatingSteamOverlay.kt @@ -27,8 +27,9 @@ internal class FloatingSteamOverlay(width: Int, height: Int, safe: Rect, density val lowered = if (lowerShortcuts) lower(visible) else visible if (rearButtons != true && trackpads != true) return lowered val placed = lowered.toMutableList() + val chosen = lowered.filter(::isStock).map { it.control } fun add(control: InputControl, x: Float, y: List, widthDp: Int, heightDp: Int, shape: InputButtonShape) { - if (placed.any { it.id == "legacy:${control.id}" }) return + if (chosen.any { if (control in rear) it in rear else it.isTrackpad }) return val element = InputSurfaceElement(control, 0f, 0f, (widthDp * dp / w).coerceAtLeast(.03f), (heightDp * dp / h).coerceAtLeast(.03f), floating = false, buttonShape = shape, showLabel = !control.isTrackpad) findSpace(element, x, y, placed)?.let(placed::add) diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt b/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt index 2571fd1111..4683aece97 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt @@ -324,15 +324,27 @@ object InputLibraries { layout.copy(screen = screen) }) + private fun encodeElements(list: List) = JSONArray().also { elements -> + for (e in list) elements.put(JSONObject().put("id", e.id).put("kind", e.kind.name) + .put("control", e.control.id).put("name", e.name).put("x", e.x.toDouble()).put("y", e.y.toDouble()) + .put("width", e.width.toDouble()).put("height", e.height.toDouble()).put("floating", e.floating).put("hideWhenIdle", e.hideWhenIdle).put("mouseGestures", e.mouseGestures).put("toggle", e.toggle).put("icon", e.icon).put("image", e.image) + .put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown)) + } + + private fun decodeElements(array: JSONArray) = array.objects(64).map { e -> + InputSurfaceElement(requireNotNull(InputControl.fromId(e.getString("control"))), e.getDouble("x").toFloat(), + e.getDouble("y").toFloat(), e.getDouble("width").toFloat(), e.getDouble("height").toFloat(), + e.getString("id"), InputElementKind.valueOf(e.getString("kind")), e.getString("name"), + e.optBoolean("floating", true), e.optBoolean("hideWhenIdle", false), e.optBoolean("mouseGestures", false), e.optBoolean("toggle", false), e.optInt("icon", 0), e.optString("image", ""), + e.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true), e.optBoolean("alwaysShown", false)) + } + internal fun encode(library: InputLibrary): String { val layouts = JSONArray() for (layout in library.layouts) { - val elements = JSONArray() - for (e in layout.elements) elements.put(JSONObject().put("id", e.id).put("kind", e.kind.name) - .put("control", e.control.id).put("name", e.name).put("x", e.x.toDouble()).put("y", e.y.toDouble()) - .put("width", e.width.toDouble()).put("height", e.height.toDouble()).put("floating", e.floating).put("hideWhenIdle", e.hideWhenIdle).put("mouseGestures", e.mouseGestures).put("toggle", e.toggle).put("icon", e.icon).put("image", e.image) - .put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown)) - layouts.put(JSONObject().put("id", layout.id).put("name", layout.name).put("template", layout.template.name).put("elements", elements) + val encoded = JSONObject().put("id", layout.id).put("name", layout.name).put("template", layout.template.name).put("elements", encodeElements(layout.elements)) + if (layout.rotated.isNotEmpty()) encoded.put("rotated", encodeElements(layout.rotated)).put("rotatedAspect", layout.rotatedAspect.toDouble()).put("rotatedScale", layout.rotatedScale.toDouble()) + layouts.put(encoded .put("tint", layout.style.tint ?: JSONObject.NULL).put("opacity", layout.style.opacity).put("screen", layout.screen.name).put("aspect", layout.aspect.toDouble()).put("scale", layout.scale.toDouble()) .put("hidden", JSONArray(layout.style.hidden.map { it.name }.sorted())).put("origin", layout.origin ?: JSONObject.NULL)) } @@ -371,13 +383,7 @@ object InputLibraries { require(version in 2..VERSION || restore) val generated = mutableSetOf() val layouts = doc.getJSONArray("layouts").objects(256).map { layout -> - val stored = layout.getJSONArray("elements").objects(64).map { e -> - InputSurfaceElement(requireNotNull(InputControl.fromId(e.getString("control"))), e.getDouble("x").toFloat(), - e.getDouble("y").toFloat(), e.getDouble("width").toFloat(), e.getDouble("height").toFloat(), - e.getString("id"), InputElementKind.valueOf(e.getString("kind")), e.getString("name"), - e.optBoolean("floating", true), e.optBoolean("hideWhenIdle", false), e.optBoolean("mouseGestures", false), e.optBoolean("toggle", false), e.optInt("icon", 0), e.optString("image", ""), - e.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true), e.optBoolean("alwaysShown", false)) - } + val stored = decodeElements(layout.getJSONArray("elements")) val id = layout.getString("id") val origin = layout.optionalString("origin") val followsGamepad = restore && !layout.optBoolean("kitless") && @@ -388,7 +394,8 @@ object InputLibraries { InputSurfaceStyle(if (!layout.has("tint")) ControllerPrefs.STEAM_BLUE else if (layout.isNull("tint")) null else layout.getInt("tint"), layout.optInt("opacity", 100), layout.optJSONArray("hidden")?.let { hidden -> (0 until hidden.length()).map { InputCommand.valueOf(hidden.getString(it)) }.toSet() }.orEmpty()), InputLayoutScreen.valueOf(layout.optString("screen", InputLayoutScreen.BOTH.name)), layout.optDouble("aspect", 0.0).toFloat(), origin, - layout.optDouble("scale", 1.0).toFloat()) + layout.optDouble("scale", 1.0).toFloat(), layout.optJSONArray("rotated")?.let(::decodeElements).orEmpty(), + layout.optDouble("rotatedAspect", 0.0).toFloat(), layout.optDouble("rotatedScale", layout.optDouble("scale", 1.0)).toFloat()) } val bindings = doc.getJSONArray("bindings").objects(512).map { b -> val controls = b.getJSONObject("controls").actions(28).mapKeys { requireNotNull(InputControl.fromId(it.key)) } diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt b/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt index 0e5ed4261f..ca8838a199 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt @@ -22,6 +22,9 @@ data class SavedInputLayout( val aspect: Float = 0f, val origin: String? = null, val scale: Float = 1f, + val rotated: List = emptyList(), + val rotatedAspect: Float = 0f, + val rotatedScale: Float = 1f, ) { val editable get() = template == InputLayoutTemplate.CUSTOM val quickButtons get() = QUICK_BUTTONS.filter { button -> elements.any { it.quickButton == button } } @@ -249,6 +252,8 @@ data class InputLibrary( for (layout in layouts) { require(layout.style.opacity in 1..100 && layout.style.hidden.all { it in QUICK_BUTTONS }) require(layout.aspect == 0f || layout.aspect.isFinite() && layout.aspect in .05f..20f) + require(layout.rotated.isEmpty() || layout.rotatedAspect.isFinite() && layout.rotatedAspect in .05f..20f && layout.rotatedScale.isFinite() && layout.rotatedScale in .5f..2f) + require(layout.rotated.size <= 64 && layout.rotated.all { r -> listOf(r.x, r.y, r.width, r.height).all { it.isFinite() } }) require(layout.scale.isFinite() && layout.scale in .5f..2f) inputName(layout.name); require(layout.elements.size <= 64); unique(layout.elements.map { it.id }) for (e in layout.elements) { diff --git a/app/src/main/java/com/droiddeck/launcher/input/LegacyGamepadLayout.kt b/app/src/main/java/com/droiddeck/launcher/input/LegacyGamepadLayout.kt index 2a36489e85..5d81a356d9 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/LegacyGamepadLayout.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/LegacyGamepadLayout.kt @@ -197,19 +197,8 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid fun regenerate(stored: List): List = withGeometry(stored, elements()) - fun rescale(stored: List, from: LegacyGamepadLayout): List { - val before = from.elements().associateBy { it.id } - val after = elements().associateBy { it.id } - return stored.map { e -> - val b = before[e.id] ?: return@map e - val a = after[e.id] ?: return@map e - val w = (a.width * e.width / b.width).coerceIn(.03f, 1f) - val h = (a.height * e.height / b.height).coerceIn(.03f, 1f) - val cx = a.x + a.width / 2 + (e.x + e.width / 2 - b.x - b.width / 2) - val cy = a.y + a.height / 2 + (e.y + e.height / 2 - b.y - b.height / 2) - e.copy(x = (cx - w / 2).coerceIn(0f, 1f - w), y = (cy - h / 2).coerceIn(0f, 1f - h), width = w, height = h).bounded() - } - } + fun rescale(stored: List, from: LegacyGamepadLayout): List = + rescaleBetween(stored, from.elements(), elements()) fun buttonsOnly(stored: List): List { val inset = dp(BUTTONS_ONLY_INSET_DP) @@ -360,3 +349,22 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid InputControl.R5 to GamepadGeometry.Slot.R5, InputControl.R4 to GamepadGeometry.Slot.R4) } } + +internal fun rescaleBetween(stored: List, from: List, to: List, + sizeFrom: List = from, sizeTo: List = to): List { + val before = from.associateBy { it.id } + val after = to.associateBy { it.id } + val smaller = sizeFrom.associateBy { it.id } + val larger = sizeTo.associateBy { it.id } + return stored.map { e -> + val b = before[e.id] ?: return@map e + val a = after[e.id] ?: return@map e + val sb = smaller[e.id] ?: b + val sa = larger[e.id] ?: a + val w = (sa.width * e.width / sb.width).coerceIn(.03f, 1f) + val h = (sa.height * e.height / sb.height).coerceIn(.03f, 1f) + val cx = a.x + a.width / 2 + (e.x + e.width / 2 - b.x - b.width / 2) + val cy = a.y + a.height / 2 + (e.y + e.height / 2 - b.y - b.height / 2) + e.copy(x = (cx - w / 2).coerceIn(0f, 1f - w), y = (cy - h / 2).coerceIn(0f, 1f - h), width = w, height = h).bounded() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt b/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt index 389dfcfb46..142846a04f 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt @@ -14,9 +14,6 @@ import android.view.View import android.view.WindowInsets import android.widget.FrameLayout import com.droiddeck.launcher.ui.InputSurfaceView -import com.droiddeck.launcher.session.SessionPrefs -import com.droiddeck.launcher.session.SessionService -import com.droiddeck.launcher.session.SessionState class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayout.Dock? = null) : FrameLayout(context) { private val surface = InputSurfaceView(context, pad, inputRole = InputRole.PRIMARY, haptics = dock != null) @@ -75,15 +72,15 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo render() } - private data class Placement(val layout: SavedInputLayout?, val width: Int, val height: Int, val safe: Rect, val buttonsOnly: Boolean) + private data class Placement(val layout: SavedInputLayout?, val width: Int, val height: Int, val safe: Rect, val buttonsOnly: Boolean, + val kit: PadKit?, val optional: Pair) private fun placed(): List { - val key = Placement(layout, viewWidth, viewHeight, Rect(safe), isButtonsOnly) + val optional = OnScreenLayout.optionalControls(context) + val key = Placement(layout, viewWidth, viewHeight, Rect(safe), isButtonsOnly, PadKit.forOverlay(context, layout), optional) return placements.getOrPut(key) { - val steam = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, isButtonsOnly, dock, - rearButtons = SessionPrefs.oscRearButtons(context).takeIf { steam }, - trackpads = SessionPrefs.oscTrackpads(context).takeIf { steam }) + rearButtons = optional.first, trackpads = optional.second) } } @@ -100,9 +97,9 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo private fun refreshAppearance() { val style = layout?.style ?: InputSurfaceStyle() - val deck = dock == null && OnScreenLayout.usesSteamDeckButtons(context, layout) - surface.updateStyle(style, steamDeckButtons = deck) - quickToggle.tint = style.tint.takeUnless { deck } + val artwork = PadKit.forOverlay(context, layout) + surface.updateStyle(style, artwork) + quickToggle.tint = style.tint.takeUnless { artwork != null } quickToggle.alpha = style.opacity / 100f quickToggle.invalidate() } @@ -136,7 +133,7 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo params.bottomMargin = bottom quickToggle.layoutParams = params } - val fresh = Rect(cutout?.safeInsetLeft ?: 0, if (dock == null) cutout?.safeInsetTop ?: 0 else 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0) + val fresh = OnScreenLayout.safeInsets(insets, dock != null) if (fresh != safe) { safe.set(fresh) render() diff --git a/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt b/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt index 363a6d761c..3f74de743f 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt @@ -3,15 +3,14 @@ package com.droiddeck.launcher.input import android.content.Context import android.graphics.Rect import com.droiddeck.launcher.session.SessionPrefs +import com.droiddeck.launcher.session.SessionService +import com.droiddeck.launcher.session.SessionState import kotlin.math.abs import kotlin.math.max import kotlin.math.min import kotlin.math.roundToInt object OnScreenLayout { - internal fun usesSteamDeckButtons(context: Context, layout: SavedInputLayout?) = - layout?.id == InputLibraries.OVERLAY && SessionPrefs.steamController(context) == SessionPrefs.CONTROLLER_DECK - internal fun supportsFloatingSteamControls(controller: String, layout: SavedInputLayout?) = layout?.id == InputLibraries.OVERLAY && (controller == SessionPrefs.CONTROLLER_DECK || controller == SessionPrefs.CONTROLLER_STEAM) @@ -31,41 +30,92 @@ 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) - fun elements(context: Context, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect, + 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 { - val stored = layout?.elements ?: return emptyList() - if (width <= 0 || height <= 0) return stored + if (saved == null) return emptyList() + if (width <= 0 || height <= 0) return saved.elements + val layout = oriented(saved, width, height) + val stored = layout.elements val generator = LegacyGamepadLayout(context, width, height, safe, layout.scale) - val (reference, generated) = reference(context, layout, width, height) + 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) + 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() val others = fit(stored.filterNot { generated && isGamepad(it) || dock != null && it.alwaysShown }, reference.first, reference.second, width, height, safe) - val placed = when { + val regenerated = when { gamepad.isEmpty() -> emptyList() dock != null -> generator.dock(gamepad, dock.portrait, dock.grips, dock.left, dock.right) else -> generator.regenerate(gamepad) } + val placed = regenerated + gamepad.filter { g -> dock == null && optional(g) && regenerated.none { it.id == g.id } } val byId = (placed + others).associateBy { it.id } val ordered = stored.mapNotNull { byId[it.id] } + placed.filter { p -> stored.none { it.id == p.id } } - if (dock != null || !supportsFloatingSteamControls(SessionPrefs.steamController(context), layout)) return ordered - if (generated && width >= height && usesSteamDeckButtons(context, layout) && + val kit = PadKit.forOverlay(context, layout) ?: return ordered + if (generated && ControllerPrefs.layout(context, reference.first.toInt(), reference.second.toInt()).isEmpty() && ControllerPrefs.layout(context, width, height).isEmpty()) { - return SteamDeckOverlayGeometry(width, height, safe, context.resources.displayMetrics, layout.scale) - .place(ordered, rearButtons == true, trackpads == true) + if (dock != null || height > width) { + return ControllerPortraitGeometry(width.toFloat(), height.toFloat(), safe, context.resources.displayMetrics.density) + .place(ordered, kit, dock != null, layout.scale, rearButtons == true, trackpads == true) + } + return ControllerOverlayGeometry(width, height, safe, context.resources.displayMetrics, layout.scale) + .place(ordered, kit, rearButtons == true, trackpads == true) } + if (dock != null || !kit.steam) return ordered return FloatingSteamOverlay(width, height, safe, context.resources.displayMetrics.density) .place(ordered, lowerShortcuts = generated, rearButtons = rearButtons, trackpads = trackpads) } - fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false): List = - elements(context, if (edited && width > 0 && height > 0) layout.copy(aspect = width.toFloat() / height) else layout, width, height, Rect()) + 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 } + + layout.rotated.filter { r -> optional(r) && layout.elements.none { it.id == r.id } }, + aspect = layout.rotatedAspect, scale = layout.rotatedScale, rotated = emptyList(), rotatedAspect = 0f, rotatedScale = 1f) + } + + fun withFrame(context: Context, saved: SavedInputLayout, elements: List, aspect: Float, scale: Float = saved.scale): SavedInputLayout { + val (_, metrics) = InputLibraries.primaryDisplay(context) + val generated = generatedSize(context, saved, metrics.widthPixels, metrics.heightPixels) != null + val portraitMain = saved.aspect > 0f && saved.aspect < 1f + if (aspect <= 0f || aspect >= 1f || portraitMain && !generated) { + val rotated = if (aspect >= 1f && portraitMain && !generated) Triple(saved.elements, saved.aspect, saved.scale) else Triple(saved.rotated, saved.rotatedAspect, saved.rotatedScale) + return saved.copy(elements = elements, aspect = aspect, scale = scale, rotated = rotated.first, + rotatedAspect = if (rotated.first.isEmpty()) 0f else rotated.second, rotatedScale = if (rotated.first.isEmpty()) 1f else rotated.third) + } + val main = if (portraitMain) 1f / saved.aspect else saved.aspect.takeIf { it > 0f } ?: (1f / aspect) + val ids = elements.associateBy { it.id } + val kept = saved.elements.mapNotNull { e -> ids[e.id]?.copy(x = e.x, y = e.y, width = e.width, height = e.height) } + val added = fit(elements.filter { d -> !optional(d) && saved.elements.none { it.id == d.id } }, aspect, 1f, (main * 1000).roundToInt().coerceAtLeast(1), 1000, Rect()) + return saved.copy(elements = kept + added, aspect = main, rotated = elements, rotatedAspect = aspect, rotatedScale = scale) + } + + fun optionalControls(context: Context): Pair { + val steam = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad + return SessionPrefs.oscRearButtons(context).takeIf { steam } to SessionPrefs.oscTrackpads(context).takeIf { steam } + } + + fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false, safe: Rect = Rect()): List { + val (rear, pads) = optionalControls(context) + return elements(context, if (edited && width > 0 && height > 0) layout.copy(aspect = width.toFloat() / height) else layout, width, height, safe, + rearButtons = rear, trackpads = pads) + } fun editorFrame(layout: SavedInputLayout, displayed: List): List { val byId = displayed.associateBy { it.id } - return layout.elements.map { byId[it.id] ?: it } + return layout.elements.map { byId[it.id] ?: it } + displayed.filter { d -> + optional(d) && layout.elements.none { it.id == d.id } + } + } + + fun safeInsets(insets: android.view.WindowInsets?, docked: Boolean): Rect { + val cutout = if (android.os.Build.VERSION.SDK_INT >= 28) insets?.displayCutout else null + return Rect(cutout?.safeInsetLeft ?: 0, if (docked) 0 else cutout?.safeInsetTop ?: 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0) } fun fit(elements: List, referenceWidth: Float, referenceHeight: Float, width: Int, height: Int, safe: Rect): List { @@ -91,6 +141,8 @@ object OnScreenLayout { } } + private fun optional(e: InputSurfaceElement) = e.id == "legacy:${e.control.id}" && (e.control.isTrackpad || e.control in REAR) + private fun isGamepad(e: InputSurfaceElement) = e.id.startsWith("legacy:") || e.id == KEYBOARD_ID fun generatedSize(context: Context, layout: SavedInputLayout, width: Int, height: Int): Pair? = diff --git a/app/src/main/java/com/droiddeck/launcher/input/PadKit.kt b/app/src/main/java/com/droiddeck/launcher/input/PadKit.kt new file mode 100644 index 0000000000..c976d310e9 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/PadKit.kt @@ -0,0 +1,54 @@ +package com.droiddeck.launcher.input + +import android.content.Context +import com.droiddeck.launcher.session.SessionPrefs + +internal enum class FaceGlyphs { MONO_LETTERS, COLOR_LETTERS, COLOR_SYMBOLS, MONO_SYMBOLS } +internal enum class DpadStyle { CROSS, DISC, ARROWS } +internal enum class StickCap { RINGED, DISHED, KNURLED } + +internal enum class PadKit(val face: FaceGlyphs, val dpad: DpadStyle, val stick: StickCap, private val xbox: Boolean = false) { + STEAM_DECK(FaceGlyphs.MONO_LETTERS, DpadStyle.CROSS, StickCap.RINGED), + STEAM_CONTROLLER(FaceGlyphs.MONO_LETTERS, DpadStyle.CROSS, StickCap.RINGED), + XBOX(FaceGlyphs.COLOR_LETTERS, DpadStyle.DISC, StickCap.DISHED, xbox = true), + DUALSHOCK(FaceGlyphs.COLOR_SYMBOLS, DpadStyle.ARROWS, StickCap.KNURLED), + DUALSENSE(FaceGlyphs.MONO_SYMBOLS, DpadStyle.ARROWS, StickCap.KNURLED); + + val steam get() = this == STEAM_DECK || this == STEAM_CONTROLLER + val playStation get() = this == DUALSHOCK || this == DUALSENSE + + fun label(control: InputControl): String = when (control) { + InputControl.LB -> if (xbox) "LB" else "L1" + InputControl.RB -> if (xbox) "RB" else "R1" + InputControl.LT -> if (xbox) "LT" else "L2" + InputControl.RT -> if (xbox) "RT" else "R2" + else -> control.label + } + + /** What the player calls [control] on this controller. */ + fun name(control: InputControl): String = if (!playStation) label(control) else when (control) { + InputControl.A -> "Cross" + InputControl.B -> "Circle" + InputControl.X -> "Square" + InputControl.Y -> "Triangle" + else -> label(control) + } + + fun native(element: InputSurfaceElement) = element.id == "legacy:${element.control.id}" && element.icon == 0 && + (element.name == element.control.label || element.name == name(element.control)) + + fun artwork(element: InputSurfaceElement) = element.image.isEmpty() && element.showLabel && + (native(element) || element.id == "builtin:keyboard" && element.icon == InputButtonIcons.KEYBOARD) + + companion object { + fun forOverlay(context: Context, layout: SavedInputLayout?): PadKit? = + if (layout?.id != InputLibraries.OVERLAY) null else when (SessionPrefs.steamController(context)) { + SessionPrefs.CONTROLLER_DECK -> STEAM_DECK + SessionPrefs.CONTROLLER_STEAM -> STEAM_CONTROLLER + SessionPrefs.CONTROLLER_XBOX360 -> XBOX + SessionPrefs.CONTROLLER_DS4 -> DUALSHOCK + SessionPrefs.CONTROLLER_DUALSENSE -> DUALSENSE + else -> null + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputLayoutWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputLayoutWidgets.kt index e180e6daba..47952e8502 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputLayoutWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputLayoutWidgets.kt @@ -18,7 +18,6 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import com.droiddeck.launcher.R import com.droiddeck.launcher.input.* -import com.droiddeck.launcher.session.SessionPrefs @Composable internal fun InputLayoutRow(layout: SavedInputLayout, role: InputRole, detail: String?, onManage: () -> Unit, onPick: () -> Unit) { @@ -48,11 +47,10 @@ internal class InputLayoutPreviewView(context: Context) : View(context) { fun update(layout: SavedInputLayout, role: InputRole) { sourceHeight = if (role == InputRole.PRIMARY) 563 else 870 val primary = role == InputRole.PRIMARY - val steamOverlay = primary && OnScreenLayout.supportsFloatingSteamControls(SessionPrefs.steamController(context), layout) - val elements = if (steamOverlay) OnScreenLayout.editorElements(context, layout, 1000, sourceHeight) else layout.elements + val artwork = if (primary) PadKit.forOverlay(context, layout) else null + val elements = if (artwork != null) OnScreenLayout.editorElements(context, layout, 1000, sourceHeight) else layout.elements renderer.updateCustomLayout(elements) - renderer.updateStyle(layout.style.copy(opacity = 100), - steamDeckButtons = primary && OnScreenLayout.usesSteamDeckButtons(context, layout)) + renderer.updateStyle(layout.style.copy(opacity = 100), artwork) renderer.measure(MeasureSpec.makeMeasureSpec(1000, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(sourceHeight, MeasureSpec.EXACTLY)) renderer.layout(0, 0, 1000, sourceHeight) contentDescription = layout.name diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt index 87406a4ff5..bd319dc2d9 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt @@ -278,7 +278,7 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe else InputHint(layout.name) InputNavigationRow(stringResource(R.string.input_saved_layouts), stringResource(R.string.input_saved_layouts_hint)) { go(InputPage.LAYOUTS) } if (layout.editable) { - if (!OnScreenLayout.usesSteamDeckButtons(context, layout)) { + if (PadKit.forOverlay(context, layout).let { kit -> role != InputRole.PRIMARY || kit == null || layout.elements.any { !kit.artwork(it) } }) { InputColorRow(host, layout.style.tint) { color -> update { it.withLayout(layout.copy(style = layout.style.copy(tint = color))) } } } SliderRow(stringResource(R.string.ctrl_opacity), null, layout.style.opacity, 1..100, step = 1, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt index 5b94225115..ca701cebf8 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt @@ -63,10 +63,17 @@ import com.droiddeck.launcher.session.SessionState private data class SurfaceSnapshot(val elements: List, val actions: Map, val clicks: Map, val scale: Float, val aspect: Float) -private class GamepadScaler(private val context: android.content.Context, private val width: Int, private val height: Int) { +private class GamepadScaler(private val context: android.content.Context, private val width: Int, private val height: Int, + private val layout: SavedInputLayout) { private fun generator(scale: Float) = LegacyGamepadLayout(context, width, height, scale = scale) val ids = generator(1f).elements().map { it.id }.toSet() - fun rescale(stored: List, from: Float, to: Float) = generator(to).rescale(stored, generator(from)) + fun stock(scale: Float) = generator(scale).elements() + private fun placed(scale: Float) = OnScreenLayout.editorElements(context, + layout.copy(elements = stock(scale), aspect = 0f, rotated = emptyList(), scale = scale), width, height) + fun rescale(stored: List, from: Float, to: Float) = + if (PadKit.forOverlay(context, layout) == null || OnScreenLayout.generatedSize(context, layout.copy(elements = stored, scale = from), width, height) != null) + generator(to).rescale(stored, generator(from)) + else rescaleBetween(stored, placed(from), placed(to), stock(from), stock(to)) fun reset(stored: List) = generator(1f).regenerate(stored).associateBy { it.id }.let { placed -> stored.map { placed[it.id] ?: it } } } @@ -78,13 +85,14 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB var clicks by mutableStateOf(preset.clicks) var selected by mutableStateOf(null) var toolsExpanded by mutableStateOf(false) - var toolsX by mutableFloatStateOf(.02f) + var toolsX by mutableFloatStateOf(-1f) var toolsY by mutableFloatStateOf(.02f) var snap by mutableStateOf(snap) var adding by mutableStateOf(false) var properties by mutableStateOf(false) var clickProperties by mutableStateOf(false) var history by mutableStateOf>(emptyList()) + var canvas by mutableStateOf(IntSize.Zero) var layoutScale by mutableFloatStateOf(layout.scale) var aspect by mutableFloatStateOf(layout.aspect) private var scaleBase by mutableStateOf, List, Float>?>(null) @@ -92,7 +100,8 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB private val rescales get() = gamepad?.let { pad -> elements.any { it.id in pad.ids } } == true val scale get() = when { scaleBase?.second == elements -> scaleValue - rescales -> (layoutScale * 100).roundToInt() + rescales -> ((if (canvas.width > 0 && canvas.height > 0 && aspect > 0f && (aspect < 1f) != (canvasAspect < 1f)) + OnScreenLayout.oriented(layout, canvas.width, canvas.height).scale else layoutScale) * 100).roundToInt() else -> 100 } val positioned get() = (if (rescales) gamepad!!.reset(elements) else defaults?.let { elements.withPositionsOf(refit(it, defaultsFrame)) }) @@ -102,18 +111,29 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB if (from <= 0f || aspect <= 0f || abs(from / aspect - 1f) < .01f) return placed return OnScreenLayout.fit(placed, from, 1f, (aspect * 1000).roundToInt().coerceAtLeast(1), 1000, Rect()) } - val element get() = elements.firstOrNull { it.id == selected } + val element get() = elements.firstOrNull { it.id == selected } ?: shown.firstOrNull { it.id == selected } val dirty get() = elements != layout.elements || actions != preset.elements || clicks != preset.clicks || layoutScale != layout.scale || aspect != layout.aspect fun checkpoint() { history = (history + SurfaceSnapshot(elements, actions, clicks, layoutScale, aspect)).takeLast(40) } fun undo() { history.lastOrNull()?.let { elements = it.elements; actions = it.actions; clicks = it.clicks; layoutScale = it.scale; aspect = it.aspect; history = history.dropLast(1) } } + private fun adoptDisplayedFrame(context: android.content.Context): Boolean { + if (canvas.width <= 0 || canvas.height <= 0 || shown.isEmpty() || aspect <= 0f || (aspect < 1f) == (canvasAspect < 1f)) return false + val open = toolsExpanded + beginEdit(shown, canvasAspect, gamepad?.let { GamepadScaler(context, canvas.width, canvas.height, layout) }) + toolsExpanded = open + return true + } + fun beginEdit(displayed: List, aspect: Float, scaler: GamepadScaler? = gamepad) { checkpoint() + toolsExpanded = false elements = OnScreenLayout.editorFrame(layout.copy(elements = elements), displayed) + if (this.aspect > 0f && aspect > 0f && (this.aspect < 1f) != (aspect < 1f)) layoutScale = OnScreenLayout.oriented(layout, (aspect * 1000).roundToInt(), 1000).scale this.aspect = aspect scaler?.let { gamepad = it } } - fun scaleAll(percent: Int) { - val base = scaleBase?.takeIf { it.second == elements } ?: Triple(elements, elements, if (rescales) layoutScale else 0f).also { checkpoint() } + fun scaleAll(context: android.content.Context, percent: Int) { + val adopted = adoptDisplayedFrame(context) + val base = scaleBase?.takeIf { it.second == elements } ?: Triple(elements, elements, if (rescales) layoutScale else 0f).also { if (!adopted) checkpoint() } val factor = percent / 100f val pad = gamepad elements = if (base.third > 0f && pad != null) { @@ -123,7 +143,47 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB } else base.first.scaled(factor) scaleValue = percent; scaleBase = Triple(base.first, elements, base.third) } - fun resetPositions() { positioned?.let { checkpoint(); elements = it; if (rescales) layoutScale = 1f } } + var shown by mutableStateOf>(emptyList()) + private val canvasAspect get() = canvas.width.toFloat() / canvas.height.coerceAtLeast(1) + + private fun stored(id: String): Boolean { + if (elements.any { it.id == id }) return true + if (shown.none { it.id == id }) return false + beginEdit(shown, canvasAspect) + return true + } + + fun missing(context: android.content.Context): List { + val pad = gamepad ?: return emptyList() + if (canvas.width <= 0 || canvas.height <= 0) return emptyList() + val ids = shown.map { it.id }.toSet() + return OnScreenLayout.editorElements(context, layout.copy(elements = pad.stock(layoutScale), aspect = 0f, rotated = emptyList(), scale = layoutScale), + canvas.width, canvas.height).filter { it.id !in ids } + } + + fun restore(context: android.content.Context, element: InputSurfaceElement) { + val legacy = gamepad?.stock(layoutScale)?.firstOrNull { it.id == element.id } + val generated = OnScreenLayout.generatedSize(context, layout.copy(elements = elements), canvas.width, canvas.height) != null + if (generated && legacy != null) { checkpoint(); elements = elements + legacy } + else { beginEdit(shown, canvasAspect); elements = elements + element } + if (element.id == "builtin:keyboard" && actions[element.id] == null) actions = actions + (element.id to InputAction.Command(InputCommand.KEYBOARD)) + selected = element.id + } + + fun remove(id: String) { + if (elements.any { it.id == id }) checkpoint() else stored(id) + elements = elements.filterNot { it.id == id }; actions = actions - id; clicks = clicks - id; selected = null + } + + fun update(element: InputSurfaceElement) { + stored(element.id) + elements = elements.map { if (it.id == element.id) element else it } + } + + fun resetPositions(context: android.content.Context) { + val adopted = adoptDisplayedFrame(context) + positioned?.let { if (!adopted) checkpoint(); elements = it; if (rescales) layoutScale = 1f } + } fun action(e: InputSurfaceElement) = preset.copy(elements = actions).action(e) fun clickAction(e: InputSurfaceElement) = preset.copy(elements = actions, clicks = clicks).clickAction(e) } @@ -142,7 +202,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> val (display, metrics) = InputLibraries.primaryDisplay(context) val gamepad = savedLayout.elements.takeIf { e -> e.any { it.id.startsWith("legacy:") } }?.let { val (w, h) = OnScreenLayout.generatedSize(context, savedLayout, metrics.widthPixels, metrics.heightPixels) ?: (metrics.widthPixels to metrics.heightPixels) - GamepadScaler(display, w, h) + GamepadScaler(display, w, h, savedLayout) } val defaults = InputLibraries.defaultPositions(context, library, savedLayout) SurfaceDraft(savedLayout, savedBindings, defaults?.first, defaults?.second ?: 0f, gamepad, ControllerPrefs.snap(context)) @@ -166,7 +226,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> InputLibraries.update(context) { latest -> val l = latest.layouts.first { it.id == savedLayout.id } val p = latest.preset(savedBindings.id) - latest.withLayout(l.copy(elements = draft.elements, aspect = draft.aspect, scale = draft.layoutScale)).withPreset(p.copy(elements = draft.actions.filterKeys { id -> draft.elements.any { it.id == id } }, + latest.withLayout(OnScreenLayout.withFrame(context, l, draft.elements, draft.aspect, draft.layoutScale)).withPreset(p.copy(elements = draft.actions.filterKeys { id -> draft.elements.any { it.id == id } }, clicks = draft.clicks.filterKeys { id -> draft.elements.any { it.id == id && it.hasClick } })) } }.onSuccess { onChanged(); onDismiss() }.onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) } @@ -225,7 +285,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> else "${library.profile(profile).name} · ${roleLabel(role)}", onSave = { action -> draft.checkpoint() if (draft.clickProperties) draft.clicks = draft.clicks + (element.id to action) else draft.actions = draft.actions + (element.id to action) - draft.elements = draft.elements.map { if (it.id == element.id) properties.copy(name = properties.name.trim().ifBlank { element.name }) else it } + draft.update(properties.copy(name = properties.name.trim().ifBlank { element.name })) draft.properties = false }) } @@ -245,7 +305,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> } } } - if (draft.adding) AlertDialog(onDismissRequest = { draft.adding = false }, title = { Text(stringResource(R.string.input_add_element)) }, confirmButton = {}, text = { Column { + if (draft.adding) AlertDialog(onDismissRequest = { draft.adding = false }, title = { Text(stringResource(R.string.input_add_element)) }, confirmButton = {}, text = { Column(Modifier.verticalScroll(rememberScrollState())) { for (kind in InputElementKind.entries) PadTextButton(onClick = { draft.checkpoint() val w = if (kind.control.dimensions == 2) .4f else .2f val h = .3f @@ -253,6 +313,11 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> val element = InputSurfaceElement(kind.control, (1f - w) / 2, (1f - h) / 2, w, h, newInputId(), kind, name) draft.elements = draft.elements + element; draft.selected = element.id draft.adding = false; draft.toolsExpanded = false }) { Text(stringResource(kind.label())) } + val missing = remember(draft.elements, draft.canvas) { draft.missing(context) } + if (missing.isNotEmpty()) HorizontalDivider() + for (element in missing) PadTextButton(onClick = { draft.restore(context, element); draft.adding = false; draft.toolsExpanded = false }) { + Text(PadKit.forOverlay(context, savedLayout)?.name(element.control)?.takeIf { element.name == element.control.label } ?: element.name) + } } }) if (discard) AlertDialog(onDismissRequest = { discard = false }, title = { Text(stringResource(R.string.input_editor_discard)) }, confirmButton = { PadTextButton(onClick = onDismiss) { Text(stringResource(R.string.common_ok)) } }, @@ -266,10 +331,12 @@ private fun SurfaceCanvas(draft: SurfaceDraft, transparent: Boolean = false) { AndroidView(factory = { InputSurfaceEditorView(it) }, modifier = Modifier.fillMaxSize().testTag("input-layout-canvas"), update = { view -> view.setBackgroundColor(if (transparent) android.graphics.Color.TRANSPARENT else android.graphics.Color.rgb(10, 11, 13)) - view.style = draft.layout.style.copy(hidden = emptySet()); view.sourceLayout = draft.layout; view.aspect = draft.aspect; view.elements = draft.elements; view.selected = draft.selected; view.snap = draft.snap + view.style = draft.layout.style.copy(hidden = emptySet()); view.sourceLayout = draft.layout.copy(scale = draft.layoutScale); view.aspect = draft.aspect; view.elements = draft.elements; view.selected = draft.selected; view.snap = draft.snap view.isEnabled = !draft.properties && !draft.adding view.onSelect = { if (!draft.properties) draft.selected = it } - view.onBeginEdit = { e, w, h -> draft.beginEdit(e, w.toFloat() / h, if (draft.hasGamepad) GamepadScaler(view.context, w, h) else null) } + view.onBeginEdit = { e, w, h -> draft.beginEdit(e, w.toFloat() / h, if (draft.hasGamepad) GamepadScaler(view.context, w, h, draft.layout) else null) } + view.onResize = { w, h -> draft.canvas = IntSize(w, h) } + view.onDisplayed = { draft.shown = it } view.onChange = { e -> if (!draft.properties) draft.elements = draft.elements.map { if (it.id == e.id) e else it } } }) @@ -283,7 +350,8 @@ private fun FloatingSurfaceTools(draft: SurfaceDraft, onSave: () -> Unit, onLeav val screenHeight = with(density) { maxHeight.toPx() } val margin = with(density) { 8.dp.toPx() } var panelSize by remember { mutableStateOf(IntSize.Zero) } - val x = (draft.toolsX * screenWidth).coerceIn(margin, (screenWidth - panelSize.width - margin).coerceAtLeast(margin)) + val x = (if (draft.toolsX < 0f) (screenWidth - panelSize.width) / 2f else draft.toolsX * screenWidth) + .coerceIn(margin, (screenWidth - panelSize.width - margin).coerceAtLeast(margin)) val y = (draft.toolsY * screenHeight).coerceIn(margin, (screenHeight - panelSize.height - margin).coerceAtLeast(margin)) val position by rememberUpdatedState(Offset(x, y)) val expandedWidth = minOf(420.dp, maxWidth - 16.dp) @@ -332,7 +400,7 @@ private fun SurfaceToolbar(draft: SurfaceDraft, onSave: () -> Unit, onLeave: () SecondaryButton(stringResource(R.string.common_cancel), compact = true, onClick = onLeave) SecondaryButton(stringResource(R.string.input_editor_add), enabled = draft.elements.size < 64, compact = true) { draft.adding = true } SecondaryButton(stringResource(R.string.input_editor_undo), enabled = draft.history.isNotEmpty(), compact = true) { draft.undo() } - if (draft.defaults != null) SecondaryButton(stringResource(R.string.input_reset_positions), enabled = draft.positioned != null, compact = true) { draft.resetPositions() } + if (draft.defaults != null) SecondaryButton(stringResource(R.string.input_reset_positions), enabled = draft.positioned != null, compact = true) { draft.resetPositions(context) } Row(verticalAlignment = Alignment.CenterVertically) { Checkbox(draft.snap, { draft.snap = it; ControllerPrefs.setSnap(context, it) }) Text(stringResource(R.string.ctrl_editor_snap)) @@ -340,7 +408,7 @@ private fun SurfaceToolbar(draft: SurfaceDraft, onSave: () -> Unit, onLeave: () PrimaryButton(stringResource(R.string.input_editor_done), compact = true, onClick = onSave) } if (draft.elements.isNotEmpty()) SliderRow(stringResource(R.string.ctrl_size), null, draft.scale, 80..125, step = 5, - format = { "$it%" }, modifier = Modifier.testTag("input-editor-scale")) { draft.scaleAll(it) } + format = { "$it%" }, modifier = Modifier.testTag("input-editor-scale")) { draft.scaleAll(context, it) } } @OptIn(ExperimentalLayoutApi::class) @@ -352,9 +420,7 @@ private fun SurfaceSelection(draft: SurfaceDraft) { FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { PrimaryButton(stringResource(R.string.input_properties), compact = true) { draft.clickProperties = false; draft.properties = true } if (e.hasClick) SecondaryButton(stringResource(R.string.input_click_properties), compact = true) { draft.clickProperties = true; draft.properties = true } - SecondaryButton(stringResource(R.string.input_remove_element), compact = true) { - draft.checkpoint(); draft.elements = draft.elements.filterNot { it.id == e.id }; draft.actions = draft.actions - e.id; draft.clicks = draft.clicks - e.id; draft.selected = null - } + SecondaryButton(stringResource(R.string.input_remove_element), compact = true) { draft.remove(e.id) } } } ?: Text(stringResource(R.string.input_editor_hint)) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt index 353ab699b9..d3922ef0c5 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt @@ -5,11 +5,14 @@ import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint +import android.graphics.Rect import android.view.HapticFeedbackConstants import android.view.MotionEvent import android.view.ViewConfiguration +import android.view.WindowInsets import android.widget.FrameLayout import com.droiddeck.launcher.input.OnScreenLayout +import com.droiddeck.launcher.input.PadKit import com.droiddeck.launcher.input.SavedInputLayout import com.droiddeck.launcher.input.InputSurfaceElement import com.droiddeck.launcher.input.InputSurfaceStyle @@ -39,6 +42,8 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { var onSelect: (String?) -> Unit = {} var onBeginEdit: (List, Int, Int) -> Unit = { _, _, _ -> } var onChange: (InputSurfaceElement) -> Unit = {} + var onResize: (Int, Int) -> Unit = { _, _ -> } + var onDisplayed: (List) -> Unit = {} private val preview = InputSurfaceView(context) private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.rgb(26, 159, 255); strokeWidth = 2 * resources.displayMetrics.density } private val radius = 14 * resources.displayMetrics.density @@ -56,19 +61,38 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { } private fun updatePreviewStyle() { - preview.updateStyle(style, steamDeckButtons = OnScreenLayout.usesSteamDeckButtons(context, sourceLayout)) + preview.updateStyle(style, PadKit.forOverlay(context, sourceLayout)) } + private var safe = Rect() + private var frameWidth = 0 + private var frameHeight = 0 + private fun refreshElements() { visibleElements = sourceLayout?.let { layout -> - OnScreenLayout.editorElements(context, layout.copy(elements = elements, aspect = aspect), width, height) + OnScreenLayout.editorElements(context, layout.copy(elements = elements, aspect = aspect), frameWidth, frameHeight, safe = safe) } ?: elements preview.updateCustomLayout(visibleElements) + onDisplayed(visibleElements) + } + + override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets { + val fresh = OnScreenLayout.safeInsets(insets, false) + if (fresh != safe) { safe = fresh; refreshElements(); invalidate() } + return super.onApplyWindowInsets(insets) + } + + override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { + super.onMeasure(widthMeasureSpec, heightMeasureSpec) + if (measuredWidth == frameWidth && measuredHeight == frameHeight) return + frameWidth = measuredWidth; frameHeight = measuredHeight + refreshElements() + super.onMeasure(widthMeasureSpec, heightMeasureSpec) } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) - refreshElements() + onResize(w, h) } override fun dispatchDraw(canvas: Canvas) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt index cd3e57435f..79ee2d8491 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt @@ -37,6 +37,7 @@ import com.droiddeck.launcher.input.InputButtonIcons import com.droiddeck.launcher.input.InputButtonShape import com.droiddeck.launcher.input.InputButtonImages import com.droiddeck.launcher.input.PadBridge +import com.droiddeck.launcher.input.PadKit import com.droiddeck.launcher.input.pcKeyLabel import com.droiddeck.launcher.session.SessionPrefs import kotlin.math.atan2 @@ -56,10 +57,10 @@ class InputSurfaceView( private val elementSources = ArrayList() private var customCanvas: ViewGroup? = null private val owners = HashMap() - private var steamDeckButtons = false - private val deckArt by lazy(LazyThreadSafetyMode.NONE) { SteamDeckButtonArt(context) } - private var deckDpad = emptyList() - private val deckDpadBounds = RectF() + private var artwork: PadKit? = null + private val art by lazy(LazyThreadSafetyMode.NONE) { PadArt(context) } + private var artworkDpad = emptyList() + private val artworkDpadBounds = RectF() private var requestedLayout = customLayout init { customLayout = surfaceStyle.shown(customLayout); addView(content, LayoutParams(-1, -1)); renderCustom(pad) } @@ -138,11 +139,11 @@ class InputSurfaceView( } } - fun updateStyle(style: InputSurfaceStyle, steamDeckButtons: Boolean = false) { - if (surfaceStyle == style && this.steamDeckButtons == steamDeckButtons) return + internal fun updateStyle(style: InputSurfaceStyle, artwork: PadKit? = null) { + if (surfaceStyle == style && this.artwork == artwork) return val relayout = surfaceStyle.hidden != style.hidden surfaceStyle = style - this.steamDeckButtons = steamDeckButtons + this.artwork = artwork if (relayout) updateCustomLayout(requestedLayout) customCanvas?.let { canvas -> for (i in 0 until canvas.childCount) styleElement(canvas.getChildAt(i)) @@ -181,7 +182,7 @@ class InputSurfaceView( } private fun renderCustom(pad: PadBridge?) { - deckDpad = emptyList() + artworkDpad = emptyList() val canvas = object : ViewGroup(context) { override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val layout = customLayout @@ -199,17 +200,18 @@ class InputSurfaceView( val x = (width * e.x).toInt(); val y = (height * e.y).toInt() child.layout(x, y, x + child.measuredWidth, y + child.measuredHeight) } - updateDeckDpad(this) + updateArtworkDpad(this) } override fun dispatchDraw(canvas: Canvas) { - if (steamDeckButtons && deckDpad.isNotEmpty()) { - val alpha = (deckDpad.first().alpha * 255f).toInt() + val kit = artwork + if (kit != null && artworkDpad.isNotEmpty()) { + val alpha = (artworkDpad.first().alpha * 255f).toInt() val saved = if (alpha == 255) canvas.save() - else canvas.saveLayerAlpha(deckDpadBounds, alpha) - canvas.translate(deckDpadBounds.left, deckDpadBounds.top) - val held = deckDpad.foldIndexed(0) { i, bits, button -> if (button.highlighted) bits or (1 shl i) else bits } - deckArt.dpad(canvas, deckDpadBounds.width(), deckDpadBounds.height(), held) + else canvas.saveLayerAlpha(artworkDpadBounds, alpha) + canvas.translate(artworkDpadBounds.left, artworkDpadBounds.top) + val held = artworkDpad.foldIndexed(0) { i, bits, button -> if (button.highlighted) bits or (1 shl i) else bits } + art.dpad(canvas, artworkDpadBounds.width(), artworkDpadBounds.height(), kit, held) canvas.restoreToCount(saved) } super.dispatchDraw(canvas) @@ -220,7 +222,8 @@ class InputSurfaceView( val source = pad?.let { InputSurfaceSource(it, inputRole, element).also { s -> elementSources += s } } canvas.addView(when (element.kind) { InputElementKind.STICK -> StickView(context, element, source, element.floating, element.hideWhenIdle && pad != null) - InputElementKind.TRACKPAD -> TrackpadView(context, element.control == InputControl.RIGHT_PAD, captioned = element.showLabel, source = source) + InputElementKind.TRACKPAD -> TrackpadView(context, element.control == InputControl.RIGHT_PAD, captioned = element.showLabel, + stock = element.id == "legacy:${element.control.id}", source = source) InputElementKind.DPAD -> DirectionPad(context, element, source) else -> HoldButton(context, element, source) }.apply { tag = element; contentDescription = element.name; styleElement(this); source?.onStateChanged = { postInvalidate() } }) @@ -229,7 +232,7 @@ class InputSurfaceView( customCanvas = canvas } - private fun updateDeckDpad(canvas: ViewGroup) { + private fun updateArtworkDpad(canvas: ViewGroup) { val buttons = DIRECTIONS.mapNotNull { direction -> val index = customLayout.indexOfFirst { element -> element.control == direction && classic(element) && element.buttonShape == InputButtonShape.CIRCLE && @@ -238,8 +241,13 @@ class InputSurfaceView( } canvas.getChildAt(index) as? HoldButton } - deckDpad = emptyList() - if (buttons.size != DIRECTIONS.size) return + val previous = artworkDpad + artworkDpad = if (crossed(buttons)) buttons else emptyList() + if (artworkDpad != previous) (previous + artworkDpad).forEach { it.invalidate() } + } + + private fun crossed(buttons: List): Boolean { + if (buttons.size != DIRECTIONS.size) return false val (up, right, down, left) = buttons val centerX = (left.left + right.right) / 2f val centerY = (up.top + down.bottom) / 2f @@ -247,9 +255,9 @@ class InputSurfaceView( kotlin.math.abs((down.left + down.right) / 2f - centerX) > 2f || kotlin.math.abs((left.top + left.bottom) / 2f - centerY) > 2f || kotlin.math.abs((right.top + right.bottom) / 2f - centerY) > 2f || - up.bottom >= down.top || left.right >= right.left) return - deckDpadBounds.set(left.left.toFloat(), up.top.toFloat(), right.right.toFloat(), down.bottom.toFloat()) - deckDpad = buttons + up.bottom >= down.top || left.right >= right.left) return false + artworkDpadBounds.set(left.left.toFloat(), up.top.toFloat(), right.right.toFloat(), down.bottom.toFloat()) + return true } override fun onAttachedToWindow() { @@ -395,14 +403,14 @@ class InputSurfaceView( override fun onDraw(canvas: Canvas) { val lit = highlighted val classic = classic(element) - if (steamDeckButtons && element.image.isEmpty() && element.showLabel) { - if (this in deckDpad) return + val kit = artwork + if (kit != null && element.image.isEmpty() && element.showLabel) { + if (this in artworkDpad) return if (element.id == "builtin:keyboard" && element.icon == InputButtonIcons.KEYBOARD) { - deckArt.keyboard(canvas, width, height, lit) + art.system(canvas, width.toFloat(), height.toFloat(), PadArt.Shape.ROUND, PadArt.Icon.KEYBOARD, lit) return } - val native = element.id == "legacy:${element.control.id}" && element.name == element.control.label && element.icon == 0 - if (native && deckArt.button(canvas, width, height, element.control, lit)) return + if (kit.native(element) && art.button(canvas, width, height, element.control, kit, lit)) return } drawSurface(canvas, lit, element.buttonShape, classic) val cx = width / 2f @@ -452,11 +460,12 @@ class InputSurfaceView( if (pressed) feedback(this, HapticFeedbackConstants.VIRTUAL_KEY) if (!pressed && cancelled) source?.cancel() else source?.update(if (pressed) 1f else 0f) invalidate() - if (steamDeckButtons && this in deckDpad) customCanvas?.invalidate() + if (artwork != null && this in artworkDpad) customCanvas?.invalidate() } } - private inner class TrackpadView(context: Context, private val right: Boolean, private val captioned: Boolean = true, + private inner class TrackpadView(context: Context, private val right: Boolean, private val captioned: Boolean, + private val stock: Boolean, private val source: InputSurfaceSource? = null) : Surface(context) { private var gestureX = 0f private var gestureY = 0f @@ -479,8 +488,8 @@ class InputSurfaceView( private val glow = Paint(Paint.ANTI_ALIAS_FLAG) override fun onDraw(canvas: Canvas) { - if (!captioned) { - deckArt.trackpad(canvas, width.toFloat(), height.toFloat(), touching || clicked, fingerX, fingerY) + if (!captioned || stock && artwork?.steam == true) { + art.trackpad(canvas, width.toFloat(), height.toFloat(), touching || clicked, fingerX, fingerY) return } drawSurface(canvas, clicked) @@ -596,10 +605,11 @@ class InputSurfaceView( if (hideWhenIdle && !touching) return val cx = if (touching) originX else centreX() val cy = if (touching) originY else height / 2f - if (steamDeckButtons && classic(element)) { + val kit = artwork + if (kit != null && classic(element)) { val radius = min(width, height) / 2f - 2f * density if (radius > 0f) { - deckArt.stick(canvas, cx, cy, radius, knobX, knobY, touching || clicking) + art.stick(canvas, cx, cy, radius, kit, knobX, knobY, touching || clicking) if (element.showLabel) { labelPaint.color = TEXT drawDirectionLabels(canvas, source, false, cx, cy, radius * .66f, radius * .34f, labelPaint) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PadArt.kt b/app/src/main/java/com/droiddeck/launcher/ui/PadArt.kt new file mode 100644 index 0000000000..f92e694241 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/PadArt.kt @@ -0,0 +1,378 @@ +package com.droiddeck.launcher.ui + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.DashPathEffect +import android.graphics.LinearGradient +import android.graphics.Paint +import android.graphics.Path +import android.graphics.RadialGradient +import android.graphics.RectF +import android.graphics.Shader +import android.graphics.Typeface +import com.droiddeck.launcher.input.DpadStyle +import com.droiddeck.launcher.input.FaceGlyphs +import com.droiddeck.launcher.input.InputControl +import com.droiddeck.launcher.input.PadKit +import com.droiddeck.launcher.input.StickCap +import kotlin.math.atan2 +import kotlin.math.cos +import kotlin.math.max +import kotlin.math.min +import kotlin.math.sin + +/** The on-screen controls' shared drawing: one glass material, shaped per virtual controller. */ +internal class PadArt(context: Context) { + private val density = context.resources.displayMetrics.density + private val body = Paint(Paint.ANTI_ALIAS_FLAG) + private val shine = Paint(Paint.ANTI_ALIAS_FLAG) + private val edge = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE } + private val ink = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER; typeface = Typeface.create("sans-serif-medium", Typeface.BOLD) } + private val line = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeCap = Paint.Cap.ROUND; strokeJoin = Paint.Join.ROUND } + private val fill = Paint(Paint.ANTI_ALIAS_FLAG) + private val path = Path() + private val arm = Path() + private val bar = Path() + private val rect = RectF() + private var shineTop = Float.NaN + private var shineHeight = Float.NaN + + private fun dp(value: Float) = value * density + + fun button(canvas: Canvas, width: Int, height: Int, control: InputControl, kit: PadKit, pressed: Boolean): Boolean { + val w = width.toFloat() + val h = height.toFloat() + if (min(w, h) <= dp(4f)) return false + when (control) { + InputControl.A, InputControl.B, InputControl.X, InputControl.Y -> + face(canvas, w / 2f, h / 2f, min(w, h) / 2f - dp(2f), control, kit, pressed) + InputControl.LB, InputControl.RB, InputControl.LT, InputControl.RT -> shoulder(canvas, w, h, control, kit, pressed) + InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5 -> grip(canvas, w, h, control.label, pressed) + InputControl.L3, InputControl.R3 -> small(canvas, w, h, control.label, pressed) + InputControl.SELECT, InputControl.START, InputControl.GUIDE, InputControl.QAM -> { + val (shape, icon) = systemLook(kit, control) + system(canvas, w, h, shape, icon, pressed) + } + else -> return false + } + return true + } + + private fun systemLook(kit: PadKit, control: InputControl): Pair = when { + kit.steam -> when (control) { + InputControl.SELECT -> Shape.CHIP to Icon.VIEW + InputControl.START -> Shape.CHIP to Icon.MENU + InputControl.GUIDE -> Shape.PILL to Icon.STEAM + else -> Shape.PILL to Icon.QAM + } + kit.playStation -> when (control) { + InputControl.SELECT -> Shape.PILL to if (kit == PadKit.DUALSHOCK) Icon.SHARE else Icon.CREATE + InputControl.START -> Shape.PILL to if (kit == PadKit.DUALSHOCK) Icon.OPTIONS else Icon.MENU + InputControl.GUIDE -> Shape.ROUND to Icon.HOME + else -> Shape.ROUND to Icon.QAM + } + else -> Shape.ROUND to when (control) { + InputControl.SELECT -> Icon.BACK + InputControl.START -> Icon.START + InputControl.GUIDE -> Icon.HOME + else -> Icon.QAM + } + } + + fun glass(canvas: Canvas, shape: Path, pressed: Boolean, tint: Int = BODY) { + shape.computeBounds(rect, false) + body.color = if (pressed) PRESSED else tint + body.setShadowLayer(dp(2.5f), 0f, dp(1.5f), SHADOW) + canvas.drawPath(shape, body) + body.clearShadowLayer() + if (!pressed) { + if (rect.top != shineTop || rect.height() != shineHeight) { + shineTop = rect.top; shineHeight = rect.height() + shine.shader = LinearGradient(0f, rect.top, 0f, rect.top + rect.height() * .55f, SHINE, Color.TRANSPARENT, Shader.TileMode.CLAMP) + } + canvas.drawPath(shape, shine) + } + edge.color = if (pressed) EDGE_PRESSED else EDGE + edge.strokeWidth = dp(1.25f) + canvas.drawPath(shape, edge) + } + + fun circle(cx: Float, cy: Float, r: Float): Path = path.apply { reset(); addCircle(cx, cy, r, Path.Direction.CW) } + + fun roundRect(l: Float, t: Float, r: Float, b: Float, radius: Float): Path = path.apply { + reset(); addRoundRect(RectF(l, t, r, b), radius, radius, Path.Direction.CW) + } + + private fun corners(l: Float, t: Float, r: Float, b: Float, tl: Float, tr: Float, br: Float, bl: Float): Path = path.apply { + reset(); addRoundRect(RectF(l, t, r, b), floatArrayOf(tl, tl, tr, tr, br, br, bl, bl), Path.Direction.CW) + } + + fun text(canvas: Canvas, value: String, cx: Float, cy: Float, size: Float, color: Int, maxWidth: Float = Float.MAX_VALUE) { + ink.textSize = size + val measured = ink.measureText(value) + if (measured > maxWidth) ink.textSize = size * maxWidth / measured + ink.color = color + canvas.drawText(value, cx, cy - (ink.ascent() + ink.descent()) / 2f, ink) + } + + fun face(canvas: Canvas, cx: Float, cy: Float, r: Float, control: InputControl, kit: PadKit, pressed: Boolean) { + glass(canvas, circle(cx, cy, r), pressed) + when (kit.face) { + FaceGlyphs.COLOR_SYMBOLS -> symbol(canvas, cx, cy, r, control, if (pressed) ON_ACCENT else SYMBOL_COLORS[control] ?: INK) + FaceGlyphs.MONO_SYMBOLS -> symbol(canvas, cx, cy, r, control, if (pressed) ON_ACCENT else INK_SOFT) + FaceGlyphs.COLOR_LETTERS -> text(canvas, control.label, cx, cy, r * .95f, if (pressed) ON_ACCENT else LETTER_COLORS[control] ?: INK) + FaceGlyphs.MONO_LETTERS -> text(canvas, control.label, cx, cy, r * .95f, if (pressed) ON_ACCENT else INK) + } + } + + private fun symbol(canvas: Canvas, cx: Float, cy: Float, r: Float, control: InputControl, color: Int) { + val s = r * .4f + line.color = color; line.strokeWidth = r * .12f + when (control) { + InputControl.A -> { canvas.drawLine(cx - s, cy - s, cx + s, cy + s, line); canvas.drawLine(cx + s, cy - s, cx - s, cy + s, line) } + InputControl.B -> canvas.drawCircle(cx, cy, s * 1.05f, line) + InputControl.X -> canvas.drawRoundRect(RectF(cx - s * .95f, cy - s * .95f, cx + s * .95f, cy + s * .95f), s * .18f, s * .18f, line) + else -> canvas.drawPath(path.apply { reset(); moveTo(cx, cy - s * 1.1f); lineTo(cx + s * 1.1f, cy + s * .85f); lineTo(cx - s * 1.1f, cy + s * .85f); close() }, line) + } + } + + fun shoulder(canvas: Canvas, w: Float, h: Float, control: InputControl, kit: PadKit, pressed: Boolean) { + val inset = dp(2f) + val l = inset; val t = inset; val r = w - inset; val b = h - inset + val trigger = control == InputControl.LT || control == InputControl.RT + val big = (b - t) * if (trigger) .9f else .62f + val small = dp(5f) + val left = control == InputControl.LT || control == InputControl.LB + glass(canvas, if (left) corners(l, t, r, b, big, small, small, small) else corners(l, t, r, b, small, big, small, small), pressed) + text(canvas, kit.label(control), w / 2f, h / 2f, (b - t) * .46f, if (pressed) ON_ACCENT else INK, (r - l) * .8f) + } + + /** A back grip: a capsule along the long side of its box, at most 2.2 times as long as it is thick. */ + fun grip(canvas: Canvas, w: Float, h: Float, label: String, pressed: Boolean) { + val inset = dp(3f) + val thick = (min(w, h) - 2 * inset).coerceAtLeast(1f) + val long = (max(w, h) - 2 * inset).coerceAtMost(thick * 2.2f) + val bw = if (w >= h) long else thick; val bh = if (w >= h) thick else long + val cx = w / 2f; val cy = h / 2f + glass(canvas, roundRect(cx - bw / 2, cy - bh / 2, cx + bw / 2, cy + bh / 2, thick / 2), pressed) + text(canvas, label, cx, cy, thick * .42f, if (pressed) ON_ACCENT else INK_SOFT) + } + + fun small(canvas: Canvas, w: Float, h: Float, label: String, pressed: Boolean) { + val r = min(w, h) / 2f * VISUAL + glass(canvas, circle(w / 2f, h / 2f, r), pressed) + text(canvas, label, w / 2f, h / 2f, r * .62f, if (pressed) ON_ACCENT else INK) + } + + enum class Shape { ROUND, PILL, CHIP } + enum class Icon { VIEW, MENU, QAM, KEYBOARD, BACK, START, CREATE, HOME, STEAM, SHARE, OPTIONS } + + fun system(canvas: Canvas, w: Float, h: Float, shape: Shape, icon: Icon, pressed: Boolean, ink: Int = INK) { + val cx = w / 2f; val cy = h / 2f + val size = when (shape) { + Shape.ROUND -> { val r = min(w, h) / 2f * VISUAL; glass(canvas, circle(cx, cy, r), pressed); r * 1.2f } + Shape.PILL -> { val vh = min(h * VISUAL, w * VISUAL / 2.3f); val vw = vh * 2.3f + glass(canvas, roundRect(cx - vw / 2, cy - vh / 2, cx + vw / 2, cy + vh / 2, vh / 2), pressed); vh * 1.1f } + Shape.CHIP -> { val vh = min(h * VISUAL, w * VISUAL / 1.9f); val vw = vh * 1.9f + glass(canvas, roundRect(cx - vw / 2, cy - vh / 2, cx + vw / 2, cy + vh / 2, vh * .32f), pressed); vh * 1.05f } + } + icon(canvas, cx, cy, size, icon, if (pressed) ON_ACCENT else ink) + } + + fun icon(canvas: Canvas, cx: Float, cy: Float, size: Float, icon: Icon, color: Int) { + val u = size / 28f + line.color = color; line.strokeWidth = 3.2f * u + fill.color = color; fill.shader = null + when (icon) { + Icon.VIEW -> { + canvas.drawRoundRect(RectF(cx - 12 * u, cy - 9 * u, cx + 3 * u, cy + 3 * u), 3 * u, 3 * u, line) + fill.color = Color.argb(230, 14, 16, 20) + canvas.drawRoundRect(RectF(cx - 4 * u, cy - 3 * u, cx + 11 * u, cy + 9 * u), 3 * u, 3 * u, fill) + canvas.drawRoundRect(RectF(cx - 4 * u, cy - 3 * u, cx + 11 * u, cy + 9 * u), 3 * u, 3 * u, line) + } + Icon.MENU -> for (dy in intArrayOf(-7, 0, 7)) canvas.drawLine(cx - 11 * u, cy + dy * u, cx + 11 * u, cy + dy * u, line) + Icon.QAM -> for (dx in intArrayOf(-10, 0, 10)) canvas.drawCircle(cx + dx * u, cy, 3.4f * u, fill) + Icon.KEYBOARD -> { + canvas.drawRoundRect(RectF(cx - 16 * u, cy - 11 * u, cx + 16 * u, cy + 11 * u), 4.5f * u, 4.5f * u, line) + for (row in 0..1) for (col in 0..3) canvas.drawCircle(cx + (-9 + col * 6) * u, cy + (-4 + row * 5) * u, 1.7f * u, fill) + line.strokeWidth = 2.6f * u; canvas.drawLine(cx - 6 * u, cy + 6 * u, cx + 6 * u, cy + 6 * u, line) + } + Icon.BACK, Icon.START -> { + val f = if (icon == Icon.START) 1f else -1f + line.strokeWidth = 2.6f * u + canvas.drawPath(path.apply { reset(); moveTo(cx - 6 * f * u, cy - 8 * u); lineTo(cx + 7 * f * u, cy); lineTo(cx - 6 * f * u, cy + 8 * u); close() }, line) + } + Icon.CREATE -> { + line.strokeWidth = 2.8f * u + canvas.drawLine(cx - 8 * u, cy + 8 * u, cx - 2 * u, cy - 8 * u, line) + canvas.drawLine(cx + u, cy + 8 * u, cx + 4 * u, cy - 2 * u, line) + canvas.drawLine(cx + 8 * u, cy + 8 * u, cx + 9 * u, cy + 3 * u, line) + } + Icon.HOME -> canvas.drawPath(path.apply { + reset(); moveTo(cx - 13 * u, cy - u); lineTo(cx, cy - 13 * u); lineTo(cx + 13 * u, cy - u) + moveTo(cx - 9 * u, cy - 4 * u); lineTo(cx - 9 * u, cy + 11 * u); lineTo(cx + 9 * u, cy + 11 * u); lineTo(cx + 9 * u, cy - 4 * u) + }, line) + Icon.STEAM, Icon.SHARE, Icon.OPTIONS -> { + ink.letterSpacing = .12f + text(canvas, when (icon) { Icon.STEAM -> "STEAM"; Icon.SHARE -> "SHARE"; else -> "OPTIONS" }, cx, cy, 14 * u, color, size * 1.9f) + ink.letterSpacing = 0f + } + } + } + + private fun chevron(canvas: Canvas, ax: Float, ay: Float, dx: Float, dy: Float, k: Float, color: Int, width: Float) { + val px = -dy; val py = dx + line.color = color; line.strokeWidth = width + canvas.drawPath(path.apply { + reset(); moveTo(ax - dx * k * .5f + px * k, ay - dy * k * .5f + py * k); lineTo(ax + dx * k * .6f, ay + dy * k * .6f) + lineTo(ax - dx * k * .5f - px * k, ay - dy * k * .5f - py * k) + }, line) + } + + private fun cross(target: Path, cx: Float, cy: Float, s: Float, h: Float, rc: Float) = target.apply { + reset() + addRoundRect(RectF(cx - h, cy - s, cx + h, cy + s), rc, rc, Path.Direction.CW) + bar.reset() + bar.addRoundRect(RectF(cx - s, cy - h, cx + s, cy + h), rc, rc, Path.Direction.CW) + op(bar, Path.Op.UNION) + } + + /** [held] bits: up 1, right 2, down 4, left 8. */ + fun dpad(canvas: Canvas, w: Float, h: Float, kit: PadKit, held: Int, chevrons: Boolean = true, ink: Int = INK) { + val cx = w / 2f; val cy = h / 2f + val s = min(w, h) / 2f - dp(3f) + if (s <= 0f) return + val dirs = arrayOf(floatArrayOf(0f, -1f), floatArrayOf(1f, 0f), floatArrayOf(0f, 1f), floatArrayOf(-1f, 0f)) + when (kit.dpad) { + DpadStyle.CROSS, DpadStyle.DISC -> { + val disc = kit.dpad == DpadStyle.DISC + val arms = if (disc) s * .78f else s + val half = if (disc) s * .25f else s * .37f + if (disc) { + glass(canvas, circle(cx, cy, s), false) + fill.shader = null; fill.color = Color.argb(18, 255, 255, 255) + canvas.drawPath(cross(arm, cx, cy, arms, half, half * .5f), fill) + edge.color = Color.argb(56, 255, 255, 255); edge.strokeWidth = dp(1f) + canvas.drawPath(arm, edge) + } else glass(canvas, cross(arm, cx, cy, arms, half, half * .43f), false) + for (i in 0..3) { + val dx = dirs[i][0]; val dy = dirs[i][1] + val on = held and (1 shl i) != 0 + if (on && half > dp(2f)) { + fill.shader = null; fill.color = PRESSED + val near = half + dp(1f); val far = arms - dp(2f); val side = half - dp(2f) + rect.set(if (dx == 0f) cx - side else if (dx > 0) cx + near else cx - far, if (dy == 0f) cy - side else if (dy > 0) cy + near else cy - far, + if (dx == 0f) cx + side else if (dx > 0) cx + far else cx - near, if (dy == 0f) cy + side else if (dy > 0) cy + far else cy - near) + canvas.drawRoundRect(rect, half * .4f, half * .4f, fill) + } + val m = (arms + half) / 2f + if (chevrons) chevron(canvas, cx + dx * m, cy + dy * m, dx, dy, half * .32f, if (on) ON_ACCENT else ink, half * .17f) + } + if (!disc) { fill.shader = null; fill.color = Color.argb(18, 255, 255, 255); canvas.drawCircle(cx, cy, half * .36f, fill) } + } + DpadStyle.ARROWS -> { + fill.shader = null; fill.color = Color.argb(56, 0, 0, 0) + canvas.drawCircle(cx, cy, s, fill) + edge.color = Color.argb(36, 255, 255, 255); edge.strokeWidth = dp(1f) + canvas.drawCircle(cx, cy, s, edge) + val bw = s * .5f; val tip = s * .14f; val base = s * .38f; val top = s * .9f; val rc = s * .11f + for (i in 0..3) { + canvas.save() + canvas.rotate(i * 90f, cx, cy) + arm.reset() + arm.moveTo(cx, cy - tip); arm.lineTo(cx - bw / 2, cy - base); arm.lineTo(cx - bw / 2, cy - top + rc) + arm.quadTo(cx - bw / 2, cy - top, cx - bw / 2 + rc, cy - top); arm.lineTo(cx + bw / 2 - rc, cy - top) + arm.quadTo(cx + bw / 2, cy - top, cx + bw / 2, cy - top + rc); arm.lineTo(cx + bw / 2, cy - base); arm.close() + val on = held and (1 shl i) != 0 + glass(canvas, arm, on) + val ty = cy - (base + top) / 2f; val ts = s * .07f + fill.shader = null; fill.color = if (on) ON_ACCENT else INK_SOFT + if (chevrons) canvas.drawPath(path.apply { reset(); moveTo(cx, ty - ts); lineTo(cx + ts, ty + ts * .7f); lineTo(cx - ts, ty + ts * .7f); close() }, fill) + canvas.restore() + } + } + } + } + + fun stick(canvas: Canvas, cx: Float, cy: Float, radius: Float, kit: PadKit, kx: Float, ky: Float, active: Boolean) { + fill.alpha = 255 + fill.shader = RadialGradient(cx, cy, radius, WELL_IN, WELL_OUT, Shader.TileMode.CLAMP) + fill.setShadowLayer(dp(2.5f), 0f, dp(1.5f), SHADOW) + canvas.drawCircle(cx, cy, radius, fill) + fill.clearShadowLayer(); fill.shader = null + edge.color = Color.argb(61, 255, 255, 255); edge.strokeWidth = dp(1.25f) + canvas.drawCircle(cx, cy, radius, edge) + line.color = Color.argb(71, 255, 255, 255); line.strokeWidth = dp(1.4f) + for (i in 0 until 8) { + val a = i * Math.PI / 4 + val c = cos(a).toFloat(); val n = sin(a).toFloat() + canvas.drawLine(cx + c * (radius - dp(7f)), cy + n * (radius - dp(7f)), cx + c * (radius - dp(3.5f)), cy + n * (radius - dp(3.5f)), line) + } + if (active && (kx != 0f || ky != 0f)) { + val angle = Math.toDegrees(atan2(ky, kx).toDouble()).toFloat() + line.color = ACCENT; line.strokeWidth = dp(3f) + val r = radius - dp(2f) + canvas.drawArc(RectF(cx - r, cy - r, cx + r, cy + r), angle - 35f, 70f, false, line) + } + val k = radius * .46f + val x = cx + kx; val y = cy + ky + if (kit.stick == StickCap.RINGED) { + line.color = if (active) ACCENT else Color.argb(140, 226, 232, 240); line.strokeWidth = dp(2.8f) + canvas.drawCircle(x, y, k * 1.14f, line) + } + glass(canvas, circle(x, y, k), false) + when (kit.stick) { + StickCap.DISHED -> { + fill.shader = RadialGradient(x, y - k * .1f, k * .74f, Color.argb(107, 0, 0, 0), Color.TRANSPARENT, Shader.TileMode.CLAMP) + canvas.drawCircle(x, y, k * .74f, fill); fill.shader = null + edge.color = if (active) ACCENT else Color.argb(51, 255, 255, 255); edge.strokeWidth = dp(1f) + canvas.drawCircle(x, y, k * .74f, edge) + } + StickCap.KNURLED -> { + line.color = if (active) ACCENT else Color.argb(66, 255, 255, 255); line.strokeWidth = dp(2.3f) + line.pathEffect = DashPathEffect(floatArrayOf(dp(1.2f), dp(1.9f)), 0f) + canvas.drawCircle(x, y, k * .9f, line); line.pathEffect = null + fill.color = Color.argb(56, 0, 0, 0); canvas.drawCircle(x, y, k * .6f, fill) + } + StickCap.RINGED -> { edge.color = Color.argb(36, 255, 255, 255); edge.strokeWidth = dp(1f); canvas.drawCircle(x, y, k * .66f, edge) } + } + } + + fun trackpad(canvas: Canvas, w: Float, h: Float, touching: Boolean, fx: Float, fy: Float) { + val inset = dp(1.5f) + val radius = min(w, h) * .14f + fill.shader = null; fill.color = Color.argb(51, 14, 16, 20) + rect.set(inset, inset, w - inset, h - inset) + canvas.drawRoundRect(rect, radius, radius, fill) + edge.color = if (touching) Color.argb(191, 0x1A, 0x9F, 0xFF) else Color.argb(51, 255, 255, 255) + edge.strokeWidth = dp(if (touching) 1.5f else 1f) + canvas.drawRoundRect(rect, radius, radius, edge) + if (!touching) return + val glow = min(w, h) * .3f + fill.shader = RadialGradient(fx, fy, glow, GLOW, Color.TRANSPARENT, Shader.TileMode.CLAMP) + canvas.drawCircle(fx, fy, glow, fill); fill.shader = null + fill.color = ACCENT; canvas.drawCircle(fx, fy, dp(5f), fill) + } + + companion object { + const val VISUAL = .72f + val ACCENT = Color.rgb(0x1A, 0x9F, 0xFF) + val ON_ACCENT = Color.rgb(0x03, 0x11, 0x1F) + val INK = Color.rgb(0xF4, 0xF7, 0xFB) + val INK_SOFT = Color.argb(209, 0xF4, 0xF7, 0xFB) + private val BODY = Color.argb(133, 14, 16, 20) + private val PRESSED = Color.argb(235, 0x1A, 0x9F, 0xFF) + private val SHINE = Color.argb(43, 255, 255, 255) + private val EDGE = Color.argb(77, 255, 255, 255) + private val EDGE_PRESSED = Color.argb(140, 255, 255, 255) + private val SHADOW = Color.argb(97, 0, 0, 0) + private val WELL_IN = Color.argb(140, 5, 7, 10) + private val WELL_OUT = Color.argb(71, 14, 16, 20) + private val GLOW = Color.argb(140, 0x1A, 0x9F, 0xFF) + private val LETTER_COLORS = mapOf(InputControl.A to Color.rgb(0x5C, 0xCB, 0x5F), InputControl.B to Color.rgb(0xF0, 0x50, 0x4A), + InputControl.X to Color.rgb(0x4C, 0x9B, 0xF0), InputControl.Y to Color.rgb(0xF5, 0xC0, 0x2E)) + private val SYMBOL_COLORS = mapOf(InputControl.A to Color.rgb(0x8D, 0xB4, 0xF2), InputControl.B to Color.rgb(0xF2, 0x61, 0x6B), + InputControl.X to Color.rgb(0xEE, 0x93, 0xD6), InputControl.Y to Color.rgb(0x45, 0xCB, 0xAA)) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SteamDeckButtonArt.kt b/app/src/main/java/com/droiddeck/launcher/ui/SteamDeckButtonArt.kt deleted file mode 100644 index 80d996f40b..0000000000 --- a/app/src/main/java/com/droiddeck/launcher/ui/SteamDeckButtonArt.kt +++ /dev/null @@ -1,277 +0,0 @@ -package com.droiddeck.launcher.ui - -import android.content.Context -import android.graphics.Canvas -import android.graphics.Color -import android.graphics.LinearGradient -import android.graphics.Paint -import android.graphics.Path -import android.graphics.RadialGradient -import android.graphics.RectF -import android.graphics.Shader -import android.graphics.Typeface -import com.droiddeck.launcher.input.InputControl -import kotlin.math.atan2 -import kotlin.math.cos -import kotlin.math.max -import kotlin.math.min -import kotlin.math.sin - -internal class SteamDeckButtonArt(context: Context) { - private val density = context.resources.displayMetrics.density - private val body = Paint(Paint.ANTI_ALIAS_FLAG) - private val shine = Paint(Paint.ANTI_ALIAS_FLAG) - private val edge = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE } - private val ink = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER; typeface = Typeface.create("sans-serif-medium", Typeface.BOLD) } - private val line = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeCap = Paint.Cap.ROUND; strokeJoin = Paint.Join.ROUND } - private val fill = Paint(Paint.ANTI_ALIAS_FLAG) - private val path = Path() - private val arm = Path() - private val bar = Path() - private val rect = RectF() - private var shineTop = Float.NaN - private var shineHeight = Float.NaN - - private fun dp(value: Float) = value * density - - private fun glass(canvas: Canvas, shape: Path, pressed: Boolean, tint: Int = BODY) { - shape.computeBounds(rect, false) - body.color = if (pressed) PRESSED else tint - body.setShadowLayer(dp(2.5f), 0f, dp(1.5f), SHADOW) - canvas.drawPath(shape, body) - body.clearShadowLayer() - if (!pressed) { - if (rect.top != shineTop || rect.height() != shineHeight) { - shineTop = rect.top; shineHeight = rect.height() - shine.shader = LinearGradient(0f, rect.top, 0f, rect.top + rect.height() * .55f, SHINE, Color.TRANSPARENT, Shader.TileMode.CLAMP) - } - canvas.drawPath(shape, shine) - } - edge.color = if (pressed) EDGE_PRESSED else EDGE - edge.strokeWidth = dp(1.25f) - canvas.drawPath(shape, edge) - } - - private fun circle(cx: Float, cy: Float, r: Float): Path = path.apply { reset(); addCircle(cx, cy, r, Path.Direction.CW) } - - private fun roundRect(l: Float, t: Float, r: Float, b: Float, radius: Float): Path = path.apply { - reset(); addRoundRect(RectF(l, t, r, b), radius, radius, Path.Direction.CW) - } - - private fun corners(l: Float, t: Float, r: Float, b: Float, tl: Float, tr: Float, br: Float, bl: Float): Path = path.apply { - reset(); addRoundRect(RectF(l, t, r, b), floatArrayOf(tl, tl, tr, tr, br, br, bl, bl), Path.Direction.CW) - } - - private fun text(canvas: Canvas, value: String, cx: Float, cy: Float, size: Float, color: Int, maxWidth: Float = Float.MAX_VALUE) { - ink.textSize = size - val measured = ink.measureText(value) - if (measured > maxWidth) ink.textSize = size * maxWidth / measured - ink.color = color - canvas.drawText(value, cx, cy - (ink.ascent() + ink.descent()) / 2f, ink) - } - - fun button(canvas: Canvas, width: Int, height: Int, control: InputControl, pressed: Boolean): Boolean { - val w = width.toFloat() - val h = height.toFloat() - if (min(w, h) <= dp(4f)) return false - when (control) { - InputControl.A, InputControl.B, InputControl.X, InputControl.Y -> { - val radius = min(w, h) / 2f - dp(2f) - glass(canvas, circle(w / 2f, h / 2f, radius), pressed) - text(canvas, control.label, w / 2f, h / 2f, radius * .95f, if (pressed) ON_ACCENT else INK) - } - InputControl.LB, InputControl.RB, InputControl.LT, InputControl.RT -> shoulder(canvas, w, h, control, pressed) - InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5 -> grip(canvas, w, h, control.label, pressed) - InputControl.SELECT -> system(canvas, w, h, Shape.CHIP, Icon.VIEW, pressed) - InputControl.START -> system(canvas, w, h, Shape.CHIP, Icon.MENU, pressed) - InputControl.GUIDE -> system(canvas, w, h, Shape.PILL, Icon.STEAM, pressed) - InputControl.QAM -> system(canvas, w, h, Shape.PILL, Icon.QAM, pressed) - else -> return false - } - return true - } - - fun keyboard(canvas: Canvas, w: Int, h: Int, pressed: Boolean) = - system(canvas, w.toFloat(), h.toFloat(), Shape.ROUND, Icon.KEYBOARD, pressed) - - private fun shoulder(canvas: Canvas, w: Float, h: Float, control: InputControl, pressed: Boolean) { - val inset = dp(2f) - val l = inset; val t = inset; val r = w - inset; val b = h - inset - val trigger = control == InputControl.LT || control == InputControl.RT - val big = (b - t) * if (trigger) .9f else .62f - val small = dp(5f) - val left = control == InputControl.LT || control == InputControl.LB - glass(canvas, if (left) corners(l, t, r, b, big, small, small, small) else corners(l, t, r, b, small, big, small, small), pressed) - text(canvas, when (control) { - InputControl.LB -> "L1" - InputControl.RB -> "R1" - InputControl.LT -> "L2" - else -> "R2" - }, w / 2f, h / 2f, (b - t) * .46f, if (pressed) ON_ACCENT else INK, (r - l) * .8f) - } - - /** A back grip: a capsule along the long side of its box, at most 2.2 times as long as it is thick. */ - private fun grip(canvas: Canvas, w: Float, h: Float, label: String, pressed: Boolean) { - val inset = dp(3f) - val thick = (min(w, h) - 2 * inset).coerceAtLeast(1f) - val long = (max(w, h) - 2 * inset).coerceAtMost(thick * 2.2f) - val bw = if (w >= h) long else thick; val bh = if (w >= h) thick else long - val cx = w / 2f; val cy = h / 2f - glass(canvas, roundRect(cx - bw / 2, cy - bh / 2, cx + bw / 2, cy + bh / 2, thick / 2), pressed) - text(canvas, label, cx, cy, thick * .42f, if (pressed) ON_ACCENT else INK_SOFT) - } - - private enum class Shape { ROUND, PILL, CHIP } - private enum class Icon { VIEW, MENU, QAM, KEYBOARD, STEAM } - - private fun system(canvas: Canvas, w: Float, h: Float, shape: Shape, icon: Icon, pressed: Boolean, ink: Int = INK) { - val cx = w / 2f; val cy = h / 2f - val size = when (shape) { - Shape.ROUND -> { val r = min(w, h) / 2f * VISUAL; glass(canvas, circle(cx, cy, r), pressed); r * 1.2f } - Shape.PILL -> { val vh = min(h * VISUAL, w * VISUAL / 2.3f); val vw = vh * 2.3f - glass(canvas, roundRect(cx - vw / 2, cy - vh / 2, cx + vw / 2, cy + vh / 2, vh / 2), pressed); vh * 1.1f } - Shape.CHIP -> { val vh = min(h * VISUAL, w * VISUAL / 1.9f); val vw = vh * 1.9f - glass(canvas, roundRect(cx - vw / 2, cy - vh / 2, cx + vw / 2, cy + vh / 2, vh * .32f), pressed); vh * 1.05f } - } - icon(canvas, cx, cy, size, icon, if (pressed) ON_ACCENT else ink) - } - - private fun icon(canvas: Canvas, cx: Float, cy: Float, size: Float, icon: Icon, color: Int) { - val u = size / 28f - line.color = color; line.strokeWidth = 3.2f * u - fill.color = color; fill.shader = null - when (icon) { - Icon.VIEW -> { - canvas.drawRoundRect(RectF(cx - 12 * u, cy - 9 * u, cx + 3 * u, cy + 3 * u), 3 * u, 3 * u, line) - fill.color = Color.argb(230, 14, 16, 20) - canvas.drawRoundRect(RectF(cx - 4 * u, cy - 3 * u, cx + 11 * u, cy + 9 * u), 3 * u, 3 * u, fill) - canvas.drawRoundRect(RectF(cx - 4 * u, cy - 3 * u, cx + 11 * u, cy + 9 * u), 3 * u, 3 * u, line) - } - Icon.MENU -> for (dy in intArrayOf(-7, 0, 7)) canvas.drawLine(cx - 11 * u, cy + dy * u, cx + 11 * u, cy + dy * u, line) - Icon.QAM -> for (dx in intArrayOf(-10, 0, 10)) canvas.drawCircle(cx + dx * u, cy, 3.4f * u, fill) - Icon.KEYBOARD -> { - canvas.drawRoundRect(RectF(cx - 16 * u, cy - 11 * u, cx + 16 * u, cy + 11 * u), 4.5f * u, 4.5f * u, line) - for (row in 0..1) for (col in 0..3) canvas.drawCircle(cx + (-9 + col * 6) * u, cy + (-4 + row * 5) * u, 1.7f * u, fill) - line.strokeWidth = 2.6f * u; canvas.drawLine(cx - 6 * u, cy + 6 * u, cx + 6 * u, cy + 6 * u, line) - } - Icon.STEAM -> { - ink.letterSpacing = .12f - text(canvas, "STEAM", cx, cy, 14 * u, color, size * 1.9f) - ink.letterSpacing = 0f - } - } - } - - private fun chevron(canvas: Canvas, ax: Float, ay: Float, dx: Float, dy: Float, k: Float, color: Int, width: Float) { - val px = -dy; val py = dx - line.color = color; line.strokeWidth = width - canvas.drawPath(path.apply { - reset(); moveTo(ax - dx * k * .5f + px * k, ay - dy * k * .5f + py * k); lineTo(ax + dx * k * .6f, ay + dy * k * .6f) - lineTo(ax - dx * k * .5f - px * k, ay - dy * k * .5f - py * k) - }, line) - } - - private fun cross(target: Path, cx: Float, cy: Float, s: Float, h: Float, rc: Float) = target.apply { - reset() - addRoundRect(RectF(cx - h, cy - s, cx + h, cy + s), rc, rc, Path.Direction.CW) - bar.reset() - bar.addRoundRect(RectF(cx - s, cy - h, cx + s, cy + h), rc, rc, Path.Direction.CW) - op(bar, Path.Op.UNION) - } - - fun dpad(canvas: Canvas, w: Float, h: Float, held: Int) { - val cx = w / 2f - val cy = h / 2f - val arms = min(w, h) / 2f - dp(3f) - if (arms <= 0f) return - val half = arms * .37f - glass(canvas, cross(arm, cx, cy, arms, half, half * .43f), false) - for (i in 0..3) { - val dx = when (i) { 1 -> 1f; 3 -> -1f; else -> 0f } - val dy = when (i) { 0 -> -1f; 2 -> 1f; else -> 0f } - val on = held and (1 shl i) != 0 - if (on && half > dp(2f)) { - fill.shader = null - fill.color = PRESSED - val near = half + dp(1f) - val far = arms - dp(2f) - val side = half - dp(2f) - rect.set(if (dx == 0f) cx - side else if (dx > 0) cx + near else cx - far, - if (dy == 0f) cy - side else if (dy > 0) cy + near else cy - far, - if (dx == 0f) cx + side else if (dx > 0) cx + far else cx - near, - if (dy == 0f) cy + side else if (dy > 0) cy + far else cy - near) - canvas.drawRoundRect(rect, half * .4f, half * .4f, fill) - } - val m = (arms + half) / 2f - chevron(canvas, cx + dx * m, cy + dy * m, dx, dy, half * .32f, if (on) ON_ACCENT else INK, half * .17f) - } - fill.shader = null - fill.color = Color.argb(18, 255, 255, 255) - canvas.drawCircle(cx, cy, half * .36f, fill) - } - - fun stick(canvas: Canvas, cx: Float, cy: Float, radius: Float, kx: Float, ky: Float, active: Boolean) { - fill.alpha = 255 - fill.shader = RadialGradient(cx, cy, radius, WELL_IN, WELL_OUT, Shader.TileMode.CLAMP) - fill.setShadowLayer(dp(2.5f), 0f, dp(1.5f), SHADOW) - canvas.drawCircle(cx, cy, radius, fill) - fill.clearShadowLayer(); fill.shader = null - edge.color = Color.argb(61, 255, 255, 255); edge.strokeWidth = dp(1.25f) - canvas.drawCircle(cx, cy, radius, edge) - line.color = Color.argb(71, 255, 255, 255); line.strokeWidth = dp(1.4f) - for (i in 0 until 8) { - val a = i * Math.PI / 4 - val c = cos(a).toFloat(); val n = sin(a).toFloat() - canvas.drawLine(cx + c * (radius - dp(7f)), cy + n * (radius - dp(7f)), cx + c * (radius - dp(3.5f)), cy + n * (radius - dp(3.5f)), line) - } - if (active && (kx != 0f || ky != 0f)) { - val angle = Math.toDegrees(atan2(ky, kx).toDouble()).toFloat() - line.color = ACCENT; line.strokeWidth = dp(3f) - val r = radius - dp(2f) - canvas.drawArc(RectF(cx - r, cy - r, cx + r, cy + r), angle - 35f, 70f, false, line) - } - val k = radius * .46f - val x = cx + kx; val y = cy + ky - line.color = if (active) ACCENT else Color.argb(140, 226, 232, 240) - line.strokeWidth = dp(2.8f) - canvas.drawCircle(x, y, k * 1.14f, line) - glass(canvas, circle(x, y, k), false) - edge.color = Color.argb(36, 255, 255, 255) - edge.strokeWidth = dp(1f) - canvas.drawCircle(x, y, k * .66f, edge) - } - - fun trackpad(canvas: Canvas, w: Float, h: Float, touching: Boolean, fx: Float, fy: Float) { - if (w <= 0f || h <= 0f) return - val inset = dp(1.5f) - val radius = min(w, h) * .14f - fill.shader = null; fill.color = Color.argb(51, 14, 16, 20) - rect.set(inset, inset, w - inset, h - inset) - canvas.drawRoundRect(rect, radius, radius, fill) - edge.color = if (touching) Color.argb(191, 0x1A, 0x9F, 0xFF) else Color.argb(51, 255, 255, 255) - edge.strokeWidth = dp(if (touching) 1.5f else 1f) - canvas.drawRoundRect(rect, radius, radius, edge) - if (!touching) return - val glow = min(w, h) * .3f - fill.shader = RadialGradient(fx, fy, glow, GLOW, Color.TRANSPARENT, Shader.TileMode.CLAMP) - canvas.drawCircle(fx, fy, glow, fill); fill.shader = null - fill.color = ACCENT; canvas.drawCircle(fx, fy, dp(5f), fill) - } - - companion object { - private const val VISUAL = .72f - private val ACCENT = Color.rgb(0x1A, 0x9F, 0xFF) - private val ON_ACCENT = Color.rgb(0x03, 0x11, 0x1F) - val INK = Color.rgb(0xF4, 0xF7, 0xFB) - private val INK_SOFT = Color.argb(209, 0xF4, 0xF7, 0xFB) - private val BODY = Color.argb(133, 14, 16, 20) - private val PRESSED = Color.argb(235, 0x1A, 0x9F, 0xFF) - private val SHINE = Color.argb(43, 255, 255, 255) - private val EDGE = Color.argb(77, 255, 255, 255) - private val EDGE_PRESSED = Color.argb(140, 255, 255, 255) - private val SHADOW = Color.argb(97, 0, 0, 0) - private val WELL_IN = Color.argb(140, 5, 7, 10) - private val WELL_OUT = Color.argb(71, 14, 16, 20) - private val GLOW = Color.argb(140, 0x1A, 0x9F, 0xFF) - } -} diff --git a/app/src/test/java/com/droiddeck/launcher/input/InputLayoutToolsTest.kt b/app/src/test/java/com/droiddeck/launcher/input/InputLayoutToolsTest.kt index cdaa68a779..0bb917a5d7 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/InputLayoutToolsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/InputLayoutToolsTest.kt @@ -132,6 +132,7 @@ class InputLayoutToolsTest { } @Test fun aScaledGamepadStaysGeneratedAndRegeneratesOnRotation() { + com.droiddeck.launcher.session.SessionPrefs.setSteamController(context, com.droiddeck.launcher.session.SessionPrefs.CONTROLLER_NONE) val (display, metrics) = InputLibraries.primaryDisplay(context) val long = maxOf(metrics.widthPixels, metrics.heightPixels) val short = minOf(metrics.widthPixels, metrics.heightPixels) diff --git a/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt index d1a7520ef2..79de797f02 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt @@ -76,20 +76,21 @@ class OnScreenLayoutTest { assertEquals(base, both.filter { it.control in standard }) } SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_XBOX360) - assertEquals(original, placed(true, true)) + assertEquals(original.map { it.id }, placed(true, true).map { it.id }) + assertEquals(placed(false, false), placed(true, true)) SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK) - val edited = layout.copy(elements = layout.elements.map { e -> if (e.control == InputControl.START) e.copy(y = .3f) else e }) + val edited = layout.copy(elements = layout.elements.map { e -> if (e.control == InputControl.START) e.copy(y = .3f) else e }, aspect = w.toFloat() / h) val fitted = OnScreenLayout.elements(context, edited, w, h, safe) assertTrue(fitted.single { it.control == InputControl.START }.y < .5f) } @Test fun theBuiltInGamepadIsRegeneratedForEverySizeWithoutStretching() { - SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_STEAM) + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE) val layout = gamepad() for ((w, h) in listOf(1200 to 540, 540 to 1200, 900 to 850)) { val placed = OnScreenLayout.elements(context, layout, w, h, Rect()) assertEquals(layout.elements.map { it.id }, placed.map { it.id }) - assertOnlyShortcutPositionsChanged(LegacyGamepadLayout(context, w, h).regenerate(layout.elements), placed) + assertEquals(LegacyGamepadLayout(context, w, h).regenerate(layout.elements), placed) for (id in listOf("legacy:a", "legacy:up", "legacy:guide")) assertSquare(placed.first { it.id == id }, w, h) assertInside(placed, w, h) } @@ -97,10 +98,10 @@ class OnScreenLayoutTest { @Test @Config(qualifiers = "w745dp-h343dp-land-420dpi") fun aBuiltInGamepadSavedAtTheDisplaySizeRegeneratesForTheMeasuredSurface() { - SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_STEAM) + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE) val saved = gamepad().copy(elements = LegacyGamepadLayout(context, 2608, 1200).elements(), aspect = 2608f / 1200) val placed = OnScreenLayout.elements(context, saved, 2048, 1200, Rect()) - assertOnlyShortcutPositionsChanged(LegacyGamepadLayout(context, 2048, 1200).regenerate(saved.elements), placed) + assertEquals(LegacyGamepadLayout(context, 2048, 1200).regenerate(saved.elements), placed) } @Test @Config(qualifiers = "w745dp-h343dp-land-420dpi") @@ -175,7 +176,7 @@ class OnScreenLayoutTest { } @Test fun regenerationKeepsTheUsersButtonStylesAndRemovedButtons() { - SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_STEAM) + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE) val layout = gamepad().let { g -> g.copy(elements = g.elements.filterNot { it.id == "legacy:y" }.map { if (it.id == "legacy:a") it.copy(opacity = .4f, icon = 0, name = "Jump") else it }) } val placed = OnScreenLayout.elements(context, layout, 2000, 1000, Rect()) assertNull(placed.firstOrNull { it.id == "legacy:y" }) @@ -196,8 +197,10 @@ class OnScreenLayoutTest { assertEquals(control.id, x, cx, .01f) assertEquals(control.id, y, cy, .01f) } - assertCenter(InputControl.LT, 140f, 66f) - assertCenter(InputControl.LB, 140f, 148f) + assertCenter(InputControl.LT, 120f, 96f) + assertCenter(InputControl.LB, 310f, 96f) + assertCenter(InputControl.RB, 1290f, 96f) + assertCenter(InputControl.RT, 1480f, 96f) assertCenter(InputControl.UP, 220f, 242.5f) assertCenter(InputControl.RIGHT, 322.5f, 345f) assertCenter(InputControl.LS, 290f, 640f) @@ -276,6 +279,7 @@ class OnScreenLayoutTest { } @Test fun theUnfoldedStripUsesTheDockGeometryInLandscapeAndPortrait() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE) for ((size, portrait) in listOf((2208 to 800) to false, (1080 to 1300) to true)) { val (w, h) = size val placed = OnScreenLayout.elements(context, gamepad(), w, h, Rect(), dock = OnScreenLayout.Dock(portrait, grips = true)) @@ -303,6 +307,41 @@ class OnScreenLayoutTest { assertEquals(.1f * 2208f / 1768 / .2f, fitted.width * 2208 / (fitted.height * 800), .01f) } + @Test fun thePortraitAndBelowGameKitsKeepDirectionalArtClearOfTheSticksAndFaceButtons() { + val directions = setOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT) + val face = setOf(InputControl.A, InputControl.B, InputControl.X, InputControl.Y) + val types = listOf(SessionPrefs.CONTROLLER_DECK, SessionPrefs.CONTROLLER_STEAM, SessionPrefs.CONTROLLER_XBOX360, + SessionPrefs.CONTROLLER_DS4, SessionPrefs.CONTROLLER_DUALSENSE) + val layout = gamepad() + val w = 1080 + for (type in types) { + SessionPrefs.setSteamController(context, type) + val steam = type == SessionPrefs.CONTROLLER_DECK || type == SessionPrefs.CONTROLLER_STEAM + val deckDock = if (steam) OnScreenLayout.Dock.deck(true, null) else OnScreenLayout.Dock(true, false) + for ((h, dock) in listOf(1920 to null, 1300 to deckDock, 385 to deckDock)) { + val placed = OnScreenLayout.elements(context, layout, w, h, Rect(), dock = dock, + rearButtons = true, trackpads = true) + assertInside(placed, w, h) + val dpad = placed.filter { it.control in directions } + assertEquals(4, dpad.size) + val rightEdge = dpad.maxOf { it.x + it.width } + val bottomEdge = dpad.maxOf { it.y + it.height } + assertTrue(type, placed.filter { it.control in face && it.id != "builtin:keyboard" }.all { it.x > rightEdge }) + assertTrue(type, placed.filter { it.kind == InputElementKind.STICK || it.kind == InputElementKind.TRACKPAD }.all { it.y > bottomEdge }) + if (dock == null) { + val row = placed.filter { it.control in shortcuts || it.id == "builtin:keyboard" } + assertEquals(5, row.size) + assertTrue(row.all { it.y > bottomEdge }) + assertEquals(steam, placed.any { it.kind == InputElementKind.TRACKPAD }) + } else { + assertFalse(placed.any { it.control == InputControl.GUIDE || it.control == InputControl.QAM }) + assertEquals(steam, placed.any { it.kind == InputElementKind.TRACKPAD }) + assertEquals(!steam, placed.any { it.control == InputControl.RS }) + } + } + } + } + private val legacyKeys = "29+33:0.3,0.7,44::Find::0.6:1:1:1" private fun importedOn(library: InputLibrary) = library.activeLayout(false, InputRole.PRIMARY)!!.elements.filter { it.id.startsWith("imported:") } @@ -398,6 +437,7 @@ class OnScreenLayoutTest { } @Test fun aDeckStripPutsTheDeckGamepadSurfacesInTheStickSlotsAndOtherPadsKeepSticks() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE) val stock = InputStockLayouts.layouts().first { it.id == DeckPanel.GAMEPAD.layout } val deck = OnScreenLayout.Dock.deck(false, stock) assertEquals(OnScreenLayout.Dock(false, true, InputControl.LS, InputControl.RIGHT_PAD), deck) @@ -454,4 +494,138 @@ class OnScreenLayoutTest { assertEquals(InputStockLayouts.layouts().filter { it.id != DeckPanel.GAMEPAD.layout }.map { it.elements }, others.filter { l -> InputStockLayouts.layouts().any { it.id == l.id } }.map { it.elements }) } + + private val kits = listOf(SessionPrefs.CONTROLLER_DECK, SessionPrefs.CONTROLLER_STEAM, SessionPrefs.CONTROLLER_XBOX360, + SessionPrefs.CONTROLLER_DS4, SessionPrefs.CONTROLLER_DUALSENSE) + + private fun List.at(control: InputControl) = single { it.id == "legacy:${control.id}" } + + @Test @Config(qualifiers = "w800dp-h450dp-land-320dpi") + fun everyKitPutsTriggersBesideTheirBumpers() { + for (kit in kits) { + SessionPrefs.setSteamController(context, kit) + val placed = OnScreenLayout.elements(context, gamepad(), 1600, 900, Rect(), rearButtons = true, trackpads = true) + val lt = placed.at(InputControl.LT); val lb = placed.at(InputControl.LB) + val rb = placed.at(InputControl.RB); val rt = placed.at(InputControl.RT) + for ((outer, inner) in listOf(lt to lb, rt to rb)) assertEquals(kit, outer.y + outer.height / 2f, inner.y + inner.height / 2f, .001f) + assertTrue(kit, lt.x + lt.width <= lb.x) + assertTrue(kit, rb.x + rb.width <= rt.x) + assertInside(placed, 1600, 900) + } + } + + @Test @Config(qualifiers = "w1280dp-h800dp-land-mdpi") + fun tabletOverlaysStayInTheLowerHalfOfTheScreen() { + for (kit in kits) { + SessionPrefs.setSteamController(context, kit) + val placed = OnScreenLayout.elements(context, gamepad(), 1280, 800, Rect(), rearButtons = true, trackpads = true) + for (e in placed) assertTrue("$kit ${e.id}", e.y >= .45f) + assertInside(placed, 1280, 800) + } + } + + @Test @Config(qualifiers = "w800dp-h450dp-land-320dpi") + fun phoneOverlaysStillUseTheFullHeight() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK) + val placed = OnScreenLayout.elements(context, gamepad(), 1600, 900, Rect()) + assertTrue(placed.at(InputControl.LT).y < .15f) + assertTrue(placed.at(InputControl.START).let { it.y + it.height } > .9f) + } + + @Test @Config(qualifiers = "w800dp-h450dp-land-320dpi") + fun aLayoutEditedInOneOrientationKeepsTheKitInTheOther() { + for (kit in kits) { + SessionPrefs.setSteamController(context, kit) + val layout = gamepad() + val landscape = OnScreenLayout.elements(context, layout, 1600, 900, Rect()) + val moved = landscape.map { if (it.control == InputControl.A) it.copy(x = .5f, y = .5f) else it } + val edited = layout.copy(elements = moved, aspect = 1600f / 900f) + assertEquals(kit, .5f, OnScreenLayout.elements(context, edited, 1600, 900, Rect()).at(InputControl.A).x, .001f) + val kitPortrait = OnScreenLayout.elements(context, layout, 900, 1600, Rect()) + val editedPortrait = OnScreenLayout.elements(context, edited, 900, 1600, Rect()) + for (control in listOf(InputControl.A, InputControl.LT, InputControl.RB, InputControl.LS, InputControl.UP)) + assertEquals("$kit ${control.id}", kitPortrait.at(control), editedPortrait.at(control)) + } + } + + @Test @Config(qualifiers = "w800dp-h450dp-land-320dpi") + fun eachOrientationKeepsItsOwnEdits() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_XBOX360) + val layout = gamepad() + val landscape = OnScreenLayout.elements(context, layout, 1600, 900, Rect()).map { if (it.control == InputControl.A) it.copy(x = .5f, y = .5f) else it } + val edited = OnScreenLayout.withFrame(context, layout, landscape, 1600f / 900f) + val portrait = OnScreenLayout.elements(context, edited, 900, 1600, Rect()).map { if (it.control == InputControl.B) it.copy(x = .1f, y = .2f) else it } + val both = OnScreenLayout.withFrame(context, edited, portrait, 900f / 1600f) + assertEquals(landscape.map { it.id to floatArrayOf(it.x, it.y).toList() }, both.elements.map { it.id to floatArrayOf(it.x, it.y).toList() }) + val wide = OnScreenLayout.elements(context, both, 1600, 900, Rect()) + val tall = OnScreenLayout.elements(context, both, 900, 1600, Rect()) + assertEquals(.5f, wide.at(InputControl.A).x, .001f) + assertEquals(.1f, tall.at(InputControl.B).x, .001f) + assertEquals(.2f, tall.at(InputControl.B).y, .001f) + val renamed = OnScreenLayout.withFrame(context, both, both.elements.map { if (it.control == InputControl.A) it.copy(name = "Jump") else it }, both.aspect) + assertEquals("Jump", OnScreenLayout.elements(context, renamed, 900, 1600, Rect()).at(InputControl.A).name) + assertEquals(.1f, OnScreenLayout.elements(context, renamed, 900, 1600, Rect()).at(InputControl.B).x, .001f) + val library = InputLibraries.read(context).withLayout(both) + assertEquals(both, InputLibraries.decode(InputLibraries.encode(library))!!.layouts.first { it.id == both.id }) + } + + @Test @Config(qualifiers = "w800dp-h450dp-land-320dpi") + fun aRemovedRearButtonStaysRemovedWhileTheOthersRemain() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK) + val layout = gamepad() + val displayed = OnScreenLayout.elements(context, layout, 1600, 900, Rect(), rearButtons = true, trackpads = true) + val frozen = OnScreenLayout.editorFrame(layout, displayed).filterNot { it.control == InputControl.L4 || it.control == InputControl.LEFT_PAD } + val edited = layout.copy(elements = frozen, aspect = 1600f / 900f) + for ((w, h) in listOf(1600 to 900, 900 to 1600)) { + val placed = OnScreenLayout.elements(context, edited, w, h, Rect(), rearButtons = true, trackpads = true).map { it.control } + assertFalse(InputControl.L4 in placed) + assertFalse(InputControl.LEFT_PAD in placed) + assertTrue(InputControl.R5 in placed) + assertTrue(InputControl.RIGHT_PAD in placed) + } + val hidden = OnScreenLayout.elements(context, edited, 1600, 900, Rect(), rearButtons = false, trackpads = false).map { it.control } + assertFalse(InputControl.R5 in hidden) + assertFalse(InputControl.RIGHT_PAD in hidden) + } + + @Test @Config(qualifiers = "w800dp-h450dp-land-320dpi") + fun aPortraitMainLayoutUsesTheStockControlsInLandscape() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_XBOX360) + val layout = gamepad() + val portrait = OnScreenLayout.elements(context, layout, 900, 1600, Rect()).map { if (it.control == InputControl.A) it.copy(x = .1f, y = .1f) else it } + val edited = layout.copy(elements = portrait, aspect = 900f / 1600f) + assertEquals(OnScreenLayout.elements(context, layout, 1600, 900, Rect()), OnScreenLayout.elements(context, edited, 1600, 900, Rect())) + assertEquals(.1f, OnScreenLayout.elements(context, edited, 900, 1600, Rect()).at(InputControl.A).x, .001f) + } + + @Test @Config(qualifiers = "w800dp-h450dp-land-320dpi") + fun aPortraitSaveKeepsOptionalControlsInThePortraitFrameOnly() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK) + val layout = gamepad() + val landscape = OnScreenLayout.elements(context, layout, 1600, 900, Rect()) + val edited = OnScreenLayout.withFrame(context, layout, landscape, 1600f / 900f) + val portrait = OnScreenLayout.elements(context, edited, 900, 1600, Rect(), rearButtons = true, trackpads = true) + .map { if (it.control == InputControl.B) it.copy(x = .1f, y = .2f) else it } + assertTrue(portrait.any { it.control == InputControl.L4 }) + val both = OnScreenLayout.withFrame(context, edited, portrait, 900f / 1600f) + assertTrue(both.elements.none { it.control == InputControl.L4 || it.control == InputControl.LEFT_PAD }) + assertTrue(both.rotated.any { it.control == InputControl.L4 }) + assertEquals(OnScreenLayout.elements(context, edited, 1600, 900, Rect(), rearButtons = true, trackpads = true), + OnScreenLayout.elements(context, both, 1600, 900, Rect(), rearButtons = true, trackpads = true)) + val tall = OnScreenLayout.elements(context, both, 900, 1600, Rect(), rearButtons = true, trackpads = true) + for (control in listOf(InputControl.L4, InputControl.LEFT_PAD, InputControl.B)) assertEquals(control.id, portrait.at(control), tall.at(control)) + assertTrue(OnScreenLayout.elements(context, both, 900, 1600, Rect(), rearButtons = false, trackpads = false) + .none { it.control == InputControl.L4 || it.control == InputControl.LEFT_PAD }) + } + + @Test fun stockControlsUseTheKitArtworkWhileAddedAndTrackpadControlsStillUseTheTint() { + for (kit in listOf(PadKit.XBOX, PadKit.DUALSENSE)) { + SessionPrefs.setSteamController(context, if (kit == PadKit.XBOX) SessionPrefs.CONTROLLER_XBOX360 else SessionPrefs.CONTROLLER_DUALSENSE) + val layout = gamepad() + assertTrue(kit.name, layout.elements.all { kit.artwork(it) }) + val added = InputSurfaceElement(InputControl.A, 0f, 0f, .1f, .1f, "custom", name = "Fire") + assertFalse(kit.artwork(added)) + assertFalse(kit.artwork(layout.elements.first { it.control == InputControl.A }.copy(image = "picture"))) + } + } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt index 8def5601a4..ed1d58f2bd 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt @@ -522,6 +522,64 @@ class InputSettingsTest { } } + @Test fun buttonSizeShowsTheGamepadWhereItWillBeSaved() { + val library = InputLibraries.read(context) + val layout = library.layout("game", InputRole.PRIMARY)!! + assertEquals(InputLibraries.OVERLAY, layout.id) + val round = mutableStateOf(0) + compose.setContent { DroidDeckTheme { androidx.compose.runtime.key(round.value) { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY, + layoutId = layout.id, bindingsId = library.profile("game").binding(InputRole.PRIMARY)) } } } + fun editor() = generateSequence(listOf(ShadowDialog.getLatestDialog().window!!.decorView)) { views -> + views.filterIsInstance().flatMap { g -> (0 until g.childCount).map(g::getChildAt) }.ifEmpty { null } + }.flatten().filterIsInstance().first() + val stock = compose.runOnIdle { editor().rendered() } + compose.onNodeWithTag("input-editor-tools").performClick() + compose.onNodeWithTag("input-editor-scale").performScrollTo().performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(95f) } + val scaled = compose.runOnIdle { editor().rendered() } + assertNotEquals(stock, scaled) + compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick() + compose.runOnIdle { assertEquals(.95f, InputLibraries.read(context).layouts.first { it.id == layout.id }.scale) } + compose.runOnIdle { round.value = 1 } + compose.runOnIdle { assertEquals(scaled, editor().rendered()) } + } + + @Test @Config(qualifiers = "w468dp-h833dp-port-369dpi") + fun buttonSizeInPortraitKeepsLandscapeEditsWithoutARotatedFrame() { + val face = setOf("legacy:a", "legacy:b", "legacy:x", "legacy:y") + val gamepad = InputLibraries.read(context).layout("game", InputRole.PRIMARY)!! + val landscape = gamepad.copy(elements = gamepad.elements.map { if (it.id in face) it.copy(x = it.x + .012f, y = it.y + .017f) else it }, + aspect = 1600f / 900f, rotated = emptyList(), rotatedAspect = 0f) + InputLibraries.update(context) { it.withLayout(landscape) } + val library = InputLibraries.read(context) + val round = mutableStateOf(0) + compose.setContent { DroidDeckTheme { androidx.compose.runtime.key(round.value) { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY, + layoutId = landscape.id, bindingsId = library.profile("game").binding(InputRole.PRIMARY)) } } } + compose.onNodeWithTag("input-editor-tools").performClick() + compose.onNodeWithTag("input-editor-scale").performScrollTo().performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(90f) } + compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick() + compose.runOnIdle { + val saved = InputLibraries.read(context).layouts.first { it.id == landscape.id } + assertEquals(landscape.aspect, saved.aspect) + for (id in face) assertEquals(landscape.elements.first { it.id == id }.let { it.x to it.y }, saved.elements.first { it.id == id }.let { it.x to it.y }) + assertTrue(saved.rotated.isNotEmpty() && saved.rotatedAspect < 1f) + assertEquals(landscape.scale, saved.scale) + assertEquals(.9f, saved.rotatedScale) + assertEquals(.9f, OnScreenLayout.oriented(saved, 900, 1600).scale) + assertEquals(landscape.scale, OnScreenLayout.oriented(saved, 1600, 900).scale) + } + compose.runOnIdle { round.value = 1 } + compose.onNodeWithTag("input-editor-tools").performClick() + val slider = compose.onNodeWithTag("input-editor-scale").performScrollTo() + assertEquals(90f, slider.fetchSemanticsNode().config[androidx.compose.ui.semantics.SemanticsProperties.ProgressBarRangeInfo].current, .5f) + slider.performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(80f) } + compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick() + compose.runOnIdle { + val saved = InputLibraries.read(context).layouts.first { it.id == landscape.id } + assertEquals(landscape.scale, saved.scale) + assertEquals(.8f, saved.rotatedScale) + } + } + @Test @Config(qualifiers = "w833dp-h468dp-land-369dpi") fun buttonSizeKeepsMovedGamepadGroupsInShape() { val face = setOf("legacy:a", "legacy:b", "legacy:x", "legacy:y") diff --git a/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceEditorViewTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceEditorViewTest.kt index 192e70d5e1..a6cbb2ab95 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceEditorViewTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceEditorViewTest.kt @@ -1,15 +1,29 @@ package com.droiddeck.launcher.ui +import android.content.Context +import android.view.InputDevice import android.view.MotionEvent +import android.view.View +import android.view.ViewGroup import com.droiddeck.launcher.input.InputControl +import com.droiddeck.launcher.input.InputLibraries import com.droiddeck.launcher.input.InputSurfaceElement import com.droiddeck.launcher.input.OnScreenLayout +import com.droiddeck.launcher.input.PadKit import com.droiddeck.launcher.input.SavedInputLayout +import com.droiddeck.launcher.session.SessionPrefs +import com.droiddeck.launcher.session.SessionService +import com.droiddeck.launcher.session.SessionState +import org.junit.After import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @@ -18,8 +32,17 @@ class InputSurfaceEditorViewTest { private val context get() = RuntimeEnvironment.getApplication() private val layout = SavedInputLayout("custom", "Custom", listOf(InputSurfaceElement(InputControl.A, .1f, .2f, .2f, .2f)), aspect = 2f) + @Before fun reset() { + for (name in listOf("input-profiles", "input-surfaces", "controller", "session")) context.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().commit() + } + + @After fun restoreSession() { + SessionState.deckPad = false + SessionState.mode = SessionService.MODE_STEAM + } + private fun view() = InputSurfaceEditorView(context).apply { - layout(0, 0, 1000, 1000) + place(1000, 1000) sourceLayout = layout aspect = layout.aspect elements = layout.elements @@ -27,13 +50,47 @@ class InputSurfaceEditorViewTest { } private fun center() = OnScreenLayout.editorElements(context, layout, 1000, 1000).first().let { (it.x + it.width / 2) * 1000 to (it.y + it.height / 2) * 1000 } - @Suppress("UNCHECKED_CAST") - private fun InputSurfaceEditorView.rendered() = javaClass.getDeclaredField("visibleElements").also { it.isAccessible = true }.get(this) as List + private fun overlay() = InputLibraries.read(context).layouts.first { it.id == InputLibraries.OVERLAY } + + private fun editor(layout: SavedInputLayout, w: Int, h: Int) = InputSurfaceEditorView(context).apply { + sourceLayout = layout + aspect = layout.aspect + elements = layout.elements + snap = false + place(w, h) + } + + private fun field(target: Any, name: String) = target.javaClass.getDeclaredField(name).also { it.isAccessible = true }.get(target) + private fun InputSurfaceEditorView.controls() = (field(field(this, "preview")!!, "customCanvas") as ViewGroup).let { canvas -> (0 until canvas.childCount).map(canvas::getChildAt) } + private fun InputSurfaceEditorView.artworkDpad() = field(field(this, "preview")!!, "artworkDpad") as List<*> + private fun InputSurfaceEditorView.rects() = controls().map { listOf(it.left, it.top, it.width, it.height) } + + private fun InputSurfaceEditorView.assertControlsDrawnWhereDisplayed() { + val shown = rendered() + val views = controls() + assertEquals(shown.size, views.size) + for ((e, v) in shown.zip(views)) { + assertEquals(e.id, e.x * width, v.left.toFloat(), 1f) + assertEquals(e.id, e.y * height, v.top.toFloat(), 1f) + assertEquals(e.id, e.width * width, v.width.toFloat(), 1f) + assertEquals(e.id, e.height * height, v.height.toFloat(), 1f) + } + } private fun InputSurfaceEditorView.touch(action: Int, x: Float, y: Float) { MotionEvent.obtain(0, 10, action, x, y, 0).also { onTouchEvent(it); it.recycle() } } + private fun InputSurfaceEditorView.mouse(action: Int, x: Float, y: Float) { + val properties = MotionEvent.PointerProperties().apply { id = 0; toolType = MotionEvent.TOOL_TYPE_MOUSE } + val coords = MotionEvent.PointerCoords().apply { this.x = x; this.y = y; pressure = 1f } + val buttons = if (action == MotionEvent.ACTION_UP) 0 else MotionEvent.BUTTON_PRIMARY + MotionEvent.obtain(0, 10, action, 1, arrayOf(properties), arrayOf(coords), 0, buttons, 1f, 1f, 0, 0, InputDevice.SOURCE_MOUSE, 0) + .also { dispatchTouchEvent(it); it.recycle() } + } + + private fun InputSurfaceEditorView.centre(id: String) = rendered().first { it.id == id }.let { (it.x + it.width / 2) * width to (it.y + it.height / 2) * height } + @Test fun editingStartsInTheDisplayedFrame() { val view = view() var started: Pair, Float>? = null @@ -70,7 +127,112 @@ class InputSurfaceEditorViewTest { view.elements = renamed view.aspect = 2f assertEquals(OnScreenLayout.editorElements(context, layout.copy(elements = renamed, aspect = 2f), 1000, 1000), view.rendered()) - view.layout(0, 0, 800, 1000) + view.place(800, 1000) assertEquals(OnScreenLayout.editorElements(context, layout.copy(elements = renamed, aspect = 2f), 800, 1000), view.rendered()) } + + @Test fun theOverlayEditorDrawsTheKitArtworkWhereTheSessionPlacesIt() { + val layout = overlay() + assertNotNull(PadKit.forOverlay(context, layout)) + val view = editor(layout, 2400, 1504) + assertEquals(OnScreenLayout.editorElements(context, layout, 2400, 1504), view.rendered()) + view.assertControlsDrawnWhereDisplayed() + assertEquals(4, view.artworkDpad().size) + } + + @Config(qualifiers = "xhdpi") + @Test fun controlsAddedForTheScreenAreDrawnOnTheFirstFrameInBothOrientations() { + SessionState.mode = SessionService.MODE_STEAM + SessionState.deckPad = true + SessionPrefs.setOscRearButtons(context, true) + SessionPrefs.setOscTrackpads(context, true) + val layout = overlay() + for ((w, h) in listOf(2400 to 1504, 1504 to 2400)) { + val view = editor(layout, w, h) + assertTrue(view.rendered().size > layout.elements.size) + view.assertControlsDrawnWhereDisplayed() + assertEquals(4, view.artworkDpad().size) + } + } + + @Test fun displayedControlsStayPutAcrossRepeatedRefreshesAndResizes() { + val view = editor(overlay(), 2400, 1504) + val first = view.rendered() + val drawn = view.rects() + repeat(3) { + view.elements = view.elements + view.aspect = view.aspect + view.sourceLayout = view.sourceLayout + view.place(1504, 2400) + view.assertControlsDrawnWhereDisplayed() + view.place(2400, 1504) + assertEquals(first, view.rendered()) + assertEquals(drawn, view.rects()) + assertEquals(4, view.artworkDpad().size) + } + } + + @Test fun dpadPiecesRedrawWhenTheyLeaveOrRejoinTheKitCross() { + val view = editor(overlay(), 2400, 1504) + val stock = view.rendered() + view.aspect = 2400f / 1504 + val pieces = view.controls().filter { (it.tag as InputSurfaceElement).id in setOf("legacy:up", "legacy:right", "legacy:down", "legacy:left") } + assertEquals(4, pieces.size) + for ((moved, expected) in listOf(stock.map { if (it.id == "legacy:up") it.copy(y = it.y - .2f) else it } to 0, stock to 4)) { + pieces.forEach { shadowOf(it).clearWasInvalidated() } + view.elements = moved + view.place(2400, 1504) + assertEquals(expected, view.artworkDpad().size) + pieces.forEach { assertTrue((it.tag as InputSurfaceElement).id, shadowOf(it).wasInvalidated()) } + } + } + + @Test fun draggingMovesTheTouchedControlByTheDragDistance() { + val view = editor(overlay(), 2400, 1504) + val a = view.rendered().first { it.id == "legacy:a" } + val changes = mutableListOf() + view.onChange = { changes += it } + val (x, y) = view.centre(a.id) + view.touch(MotionEvent.ACTION_DOWN, x, y) + view.touch(MotionEvent.ACTION_MOVE, x - 240f, y - 150f) + view.touch(MotionEvent.ACTION_UP, x - 240f, y - 150f) + val moved = changes.last() + assertEquals(a.id, moved.id) + assertEquals(a.x - 240f / 2400, moved.x, .0001f) + assertEquals(a.y - 150f / 1504, moved.y, .0001f) + assertEquals(a.width, moved.width, .0001f) + } + + @Test fun aMouseSelectsDragsAndResizesLikeATouch() { + val view = editor(overlay(), 2400, 1504) + val a = view.rendered().first { it.id == "legacy:a" } + val changes = mutableListOf() + var selection: String? = null + view.onSelect = { selection = it } + view.onChange = { changes += it } + val (x, y) = view.centre(a.id) + view.mouse(MotionEvent.ACTION_DOWN, x, y) + view.mouse(MotionEvent.ACTION_UP, x, y) + assertEquals(a.id, selection) + view.mouse(MotionEvent.ACTION_DOWN, x, y) + view.mouse(MotionEvent.ACTION_MOVE, x - 240f, y) + view.mouse(MotionEvent.ACTION_UP, x - 240f, y) + assertEquals(a.x - 240f / 2400, changes.last().x, .0001f) + val right = (a.x + a.width) * 2400; val bottom = (a.y + a.height) * 1504 + view.mouse(MotionEvent.ACTION_DOWN, right, bottom) + view.mouse(MotionEvent.ACTION_MOVE, right + 60f, bottom + 60f) + view.mouse(MotionEvent.ACTION_UP, right + 60f, bottom + 60f) + val resized = changes.last() + assertEquals(a.id, resized.id) + assertEquals(a.width + 60f / 2400, resized.width, .0001f) + assertEquals(a.height + 60f / 1504, resized.height, .0001f) + } } + +internal fun InputSurfaceEditorView.place(w: Int, h: Int) { + measure(View.MeasureSpec.makeMeasureSpec(w, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(h, View.MeasureSpec.EXACTLY)) + layout(0, 0, w, h) +} + +@Suppress("UNCHECKED_CAST") +internal fun InputSurfaceEditorView.rendered() = javaClass.getDeclaredField("visibleElements").also { it.isAccessible = true }.get(this) as List diff --git a/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceTouchTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceTouchTest.kt index fe00507fec..cd92665cc2 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceTouchTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceTouchTest.kt @@ -85,10 +85,12 @@ class InputSurfaceTouchTest { touch(MotionEvent.ACTION_DOWN, 1 to (800f to 240f)) assertTrue(state().isDown(PadState.A)) - surface.updateStyle(InputSurfaceStyle(), steamDeckButtons = true) - assertEquals(shown, surface.shownElements) - assertTrue(surface.takesTouchAt(800f, 240f)) - assertTrue(state().isDown(PadState.A)) + for (artwork in PadKit.entries) { + surface.updateStyle(InputSurfaceStyle(), artwork) + assertEquals(shown, surface.shownElements) + assertTrue(surface.takesTouchAt(800f, 240f)) + assertTrue(state().isDown(PadState.A)) + } touch(MotionEvent.ACTION_UP, 1 to (800f to 240f)) assertFalse(state().isDown(PadState.A)) From b2687701c141a34ad717acd3370f13cf51471f72 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:51:27 -0500 Subject: [PATCH 020/141] build: run the local macOS build natively, with no emulation (#2999) build: make the local macOS build run natively, with no emulation On an arm64 Mac the x86/i386 session preloads were built in a linux/amd64 container under emulation, and the Rockstar launcher failed to link against Homebrew's SJLJ i686 mingw. Both now build on the host's own architecture. - build_local.sh: on arm64 build the x86 preloads in a native arm64 Debian bullseye container with the x86_64/i686 cross toolchains (glibc 2.31, as before); x86 hosts keep the native gcc-multilib path. - build-x86-preloads.sh: X86_CROSS=1 selects the cross toolchains. - rockstar-launcher/build-container.sh: build the launcher in a native Ubuntu container with a DWARF2 mingw, used on macOS only. - vr/build.sh: stop aborting silently when ANDROID_NDK_HOME names an NDK that is not installed. - build_local.sh: expand the empty stores_check array safely on bash 3.2 so the script reaches its signing step. --- tools/build_local.sh | 22 ++++++++--- tools/linuxfs/build-x86-preloads.sh | 44 +++++++++++++--------- tools/rockstar-launcher/build-container.sh | 28 ++++++++++++++ tools/vr/build.sh | 2 +- 4 files changed, 73 insertions(+), 23 deletions(-) create mode 100755 tools/rockstar-launcher/build-container.sh diff --git a/tools/build_local.sh b/tools/build_local.sh index 4251997416..d90a458d2c 100755 --- a/tools/build_local.sh +++ b/tools/build_local.sh @@ -171,12 +171,20 @@ x86_key=$(inputs_hash bullseye tools/linuxfs/build-x86-preloads.sh tools/linuxfs app/src/main/cpp/fakeinput_steam.cpp) x86_stage="${staging_dir}/x86-preloads" if restore_step x86-preloads "${x86_key}" "${linuxfs_dir}"; then :; else - docker run --rm --platform linux/amd64 \ + x86_platform=linux/amd64 + x86_packages="gcc g++ gcc-multilib g++-multilib binutils" + x86_cross=0 + if [[ "${docker_platform}" == linux/arm64 ]]; then + x86_platform=linux/arm64 + x86_packages="gcc-x86-64-linux-gnu g++-x86-64-linux-gnu gcc-i686-linux-gnu g++-i686-linux-gnu libc6-dev-amd64-cross libc6-dev-i386-cross binutils-x86-64-linux-gnu binutils-i686-linux-gnu" + x86_cross=1 + fi + docker run --rm --platform "${x86_platform}" -e X86_CROSS="${x86_cross}" -e X86_PACKAGES="${x86_packages}" \ -v "${repo_root}:/src" -v "${git_common}:${git_common}" -w /src public.ecr.aws/docker/library/debian:bullseye bash -c ' set -euo pipefail printf "deb http://archive.debian.org/debian bullseye main\ndeb http://archive.debian.org/debian-security bullseye-security main\n" > /etc/apt/sources.list apt-get -o Acquire::Check-Valid-Until=false update -qq - DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends gcc g++ gcc-multilib g++-multilib binutils >/dev/null + DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends $X86_PACKAGES >/dev/null tools/linuxfs/build-x86-preloads.sh app/src/main/assets/linuxfs chown -R '"$(id -u):$(id -g)"' app/src/main/assets/linuxfs ' @@ -436,8 +444,12 @@ if [[ "${DROIDDECK_SKIP_RUST:-0}" != 1 ]]; then rockstar_out="${linuxfs_dir}/usr/local/lib/droiddeck-rockstar" rockstar_key=$(inputs_hash "windows-gnu" tools/rockstar-launcher/src tools/rockstar-launcher/Cargo.toml tools/rockstar-launcher/Cargo.lock tools/rockstar-launcher/build.sh) if ! restore_step rockstar "${rockstar_key}" "${rockstar_out}"; then - command -v i686-w64-mingw32-gcc >/dev/null 2>&1 || { echo "i686-w64-mingw32-gcc is required for the Rockstar launcher service." >&2; exit 1; } - CARGO_TARGET_DIR="${cache_dir}/rockstar-target" bash tools/rockstar-launcher/build.sh "${rockstar_out}" + if [[ "$(uname -s)" == Darwin ]]; then + bash tools/rockstar-launcher/build-container.sh "${rockstar_out}" + else + command -v i686-w64-mingw32-gcc >/dev/null 2>&1 || { echo "i686-w64-mingw32-gcc is required for the Rockstar launcher service." >&2; exit 1; } + CARGO_TARGET_DIR="${cache_dir}/rockstar-target" bash tools/rockstar-launcher/build.sh "${rockstar_out}" + fi save_step rockstar "${rockstar_key}" "${rockstar_out}" fi epic_out="${linuxfs_dir}/usr/local/lib/droiddeck-epic" @@ -473,7 +485,7 @@ readelf_path=$(find "${NDK}/toolchains/llvm/prebuilt" -name llvm-readelf | head [[ -x "${readelf_path}" ]] || { echo "NDK llvm-readelf is missing" >&2; exit 1; } stores_check=() [[ "${DROIDDECK_SKIP_RUST:-0}" != 1 ]] || stores_check+=(--without-stores) -python3 tools/release/check_android_libraries.py "${apk}" --readelf "${readelf_path}" "${stores_check[@]}" +python3 tools/release/check_android_libraries.py "${apk}" --readelf "${readelf_path}" ${stores_check[@]+"${stores_check[@]}"} git diff --exit-code -- app/src/main/rust/stores/Cargo.lock build_tools=$(find "${sdk_dir}/build-tools" -mindepth 1 -maxdepth 1 -type d -print | sort -V | tail -1) diff --git a/tools/linuxfs/build-x86-preloads.sh b/tools/linuxfs/build-x86-preloads.sh index a9c32a18d6..ccb00eeab4 100755 --- a/tools/linuxfs/build-x86-preloads.sh +++ b/tools/linuxfs/build-x86-preloads.sh @@ -1,26 +1,34 @@ #!/bin/sh set -eu out=${1:?usage: build-x86-preloads.sh } +tools() { + prefix= + if [ "${X86_CROSS:-}" = 1 ]; then + case $1 in i386) prefix=i686-linux-gnu- ;; *) prefix=x86_64-linux-gnu- ;; esac + fi + GCC=${prefix}gcc GXX=${prefix}g++ STRIP=${prefix}strip OBJDUMP=${prefix}objdump NM=${prefix}nm +} for arch in x86_64 i386; do + tools $arch case $arch in x86_64) bits=-m64 ;; i386) bits=-m32 ;; esac mkdir -p "$out/$arch" - gcc $bits -shared -fPIC -O2 -Wall -pthread \ + $GCC $bits -shared -fPIC -O2 -Wall -pthread \ -o "$out/$arch/libddsession.so" tools/linuxfs/preload/*.c -ldl - g++ $bits -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \ + $GXX $bits -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \ -pthread -std=c++17 -static-libstdc++ -static-libgcc -Wl,--exclude-libs,ALL \ -o "$out/$arch/libfakeinput.so" app/src/main/cpp/fakeinput_steam.cpp -ldl - strip --strip-unneeded "$out/$arch/libddsession.so" "$out/$arch/libfakeinput.so" + $STRIP --strip-unneeded "$out/$arch/libddsession.so" "$out/$arch/libfakeinput.so" for lib in "$out/$arch/libddsession.so" "$out/$arch/libfakeinput.so"; do - newest=$(objdump -T "$lib" | grep -o 'GLIBC_2\.[0-9]*' | sort -u -t. -k2,2n | tail -1) + newest=$($OBJDUMP -T "$lib" | grep -o 'GLIBC_2\.[0-9]*' | sort -u -t. -k2,2n | tail -1) minor=${newest#GLIBC_2.} if [ "$minor" -gt 31 ]; then echo "$lib needs $newest; Steam Linux Runtime 3.0 has glibc 2.31" >&2 exit 1 fi - if objdump -p "$lib" | grep -q 'NEEDED.*lib\(stdc++\|gcc_s\)'; then + if $OBJDUMP -p "$lib" | grep -q 'NEEDED.*lib\(stdc++\|gcc_s\)'; then echo "$lib links the C++ runtime dynamically" >&2 exit 1 fi @@ -28,37 +36,39 @@ for arch in x86_64 i386; do done for target in x86_64/faultreport i386/faultreport; do arch=${target%/*} name=${target#*/} + tools $arch case $arch in x86_64) bits=-m64 ;; i386) bits=-m32 ;; esac lib=$out/$arch/lib$name.so - gcc $bits -shared -fPIC -O2 -Wall -Wextra -nostdlib -fno-stack-protector -fno-builtin -fvisibility=hidden \ + $GCC $bits -shared -fPIC -O2 -Wall -Wextra -nostdlib -fno-stack-protector -fno-builtin -fvisibility=hidden \ -o "$lib" tools/linuxfs/fex/$name.c - strip --strip-unneeded "$lib" - if objdump -p "$lib" | grep -q NEEDED || [ -n "$(nm -D --undefined-only "$lib" 2>/dev/null)" ]; then + $STRIP --strip-unneeded "$lib" + if $OBJDUMP -p "$lib" | grep -q NEEDED || [ -n "$($NM -D --undefined-only "$lib" 2>/dev/null)" ]; then echo "$lib must not need any library" >&2 exit 1 fi done +tools x86_64 lib=$out/x86_64/libwebkitinput.so -gcc -m64 -shared -fPIC -O2 -Wall -Wextra -nostdlib -fno-stack-protector -fno-builtin -fvisibility=hidden \ +$GCC -m64 -shared -fPIC -O2 -Wall -Wextra -nostdlib -fno-stack-protector -fno-builtin -fvisibility=hidden \ -o "$lib" tools/linuxfs/fex/webkitinput.c -strip --strip-unneeded "$lib" -if objdump -p "$lib" | grep -q NEEDED || [ "$(nm -D --undefined-only "$lib" | awk '{print $1 $2}' | LC_ALL=C sort | tr '\n' ' ')" != "wdlsym wg_getenv wg_object_get_data wg_object_set wg_object_set_data wg_type_check_instance_is_a wgtk_container_forall wgtk_container_get_type wgtk_key_snooper_install wgtk_widget_get_toplevel wwebkit_user_script_new wwebkit_user_script_unref wwebkit_web_view_get_type wwebkit_web_view_get_uri wwebkit_web_view_run_javascript " ]; then +$STRIP --strip-unneeded "$lib" +if $OBJDUMP -p "$lib" | grep -q NEEDED || [ "$($NM -D --undefined-only "$lib" | awk '{print $1 $2}' | LC_ALL=C sort | tr '\n' ' ')" != "wdlsym wg_getenv wg_object_get_data wg_object_set wg_object_set_data wg_type_check_instance_is_a wgtk_container_forall wgtk_container_get_type wgtk_key_snooper_install wgtk_widget_get_toplevel wwebkit_user_script_new wwebkit_user_script_unref wwebkit_web_view_get_type wwebkit_web_view_get_uri wwebkit_web_view_run_javascript " ]; then echo "$lib must need nothing but weak GLib, GTK and WebKit calls" >&2 exit 1 fi stub=$(mktemp -d) -gcc -m64 -shared -nostdlib -Wl,-soname,/usr/lib/x86_64-linux-gnu/libvulkan.so.1 -o "$stub/libvulkan.so.1" -x c /dev/null +$GCC -m64 -shared -nostdlib -Wl,-soname,/usr/lib/x86_64-linux-gnu/libvulkan.so.1 -o "$stub/libvulkan.so.1" -x c /dev/null lib=$out/x86_64/libvulkan-thunk.so -gcc -m64 -shared -fPIC -O2 -Wall -Wextra -fvisibility=hidden -Wl,-soname,libvulkan.so.1 -Wl,-z,nodelete -Wl,--no-as-needed \ +$GCC -m64 -shared -fPIC -O2 -Wall -Wextra -fvisibility=hidden -Wl,-soname,libvulkan.so.1 -Wl,-z,nodelete -Wl,--no-as-needed \ -o "$lib" tools/linuxfs/fex/vulkanpin.c "$stub/libvulkan.so.1" -ldl rm -rf "$stub" -strip --strip-unneeded "$lib" -newest=$(objdump -T "$lib" | grep -o 'GLIBC_2\.[0-9]*' | sort -u -t. -k2,2n | tail -1) -if ! objdump -p "$lib" | grep -q 'NEEDED *\/usr/lib/x86_64-linux-gnu/libvulkan\.so\.1$' \ - || ! objdump -p "$lib" | grep -q 'FLAGS_1 *0x0*8$' || [ "${newest#GLIBC_2.}" -gt 31 ]; then +$STRIP --strip-unneeded "$lib" +newest=$($OBJDUMP -T "$lib" | grep -o 'GLIBC_2\.[0-9]*' | sort -u -t. -k2,2n | tail -1) +if ! $OBJDUMP -p "$lib" | grep -q 'NEEDED *\/usr/lib/x86_64-linux-gnu/libvulkan\.so\.1$' \ + || ! $OBJDUMP -p "$lib" | grep -q 'FLAGS_1 *0x0*8$' || [ "${newest#GLIBC_2.}" -gt 31 ]; then echo "$lib must be nodelete, need the Vulkan thunk and run on glibc 2.31" >&2 exit 1 fi diff --git a/tools/rockstar-launcher/build-container.sh b/tools/rockstar-launcher/build-container.sh new file mode 100755 index 0000000000..bee7c48774 --- /dev/null +++ b/tools/rockstar-launcher/build-container.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# Builds the Rockstar launcher in a container, on the host's own architecture. Rust's +# i686-pc-windows-gnu target needs a DWARF2 mingw; Homebrew's i686 mingw uses SJLJ and fails to link. +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +repo=$(cd "$here/../.." && pwd) +out=${1:?usage: build-container.sh } +. "$repo/tools/docker_platform.sh" +cache=${DROIDDECK_BUILD_CACHE:-$HOME/.cache/droiddeck-build}/rockstar-container +mkdir -p "$out" "$cache/cargo" "$cache/target" +out=$(cd "$out" && pwd) +image=droiddeck-rockstar-build:v2-${docker_platform#linux/} + +if ! docker image inspect "$image" >/dev/null 2>&1; then + docker build --platform "$docker_platform" -t "$image" - <<'EOF' +FROM public.ecr.aws/docker/library/ubuntu:24.04 +ENV DEBIAN_FRONTEND=noninteractive RUSTUP_HOME=/opt/rustup CARGO_HOME=/opt/cargo PATH=/opt/cargo/bin:$PATH +RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends ca-certificates curl gcc libc6-dev \ + gcc-mingw-w64-i686-posix gcc-mingw-w64-x86-64-posix >/dev/null +RUN curl -sSf https://sh.rustup.rs | sh -s -- -y -q --profile minimal --default-toolchain stable \ + -t i686-pc-windows-gnu -t x86_64-pc-windows-gnu && chmod -R a+rX /opt/rustup /opt/cargo +EOF +fi + +docker run --rm --platform "$docker_platform" --user "$(id -u):$(id -g)" \ + -e CARGO_HOME=/cache/cargo -e CARGO_TARGET_DIR=/cache/target -e HOME=/tmp \ + -v "$repo:/src" -v "$out:/out" -v "$cache:/cache" -w /src "$image" \ + bash tools/rockstar-launcher/build.sh /out diff --git a/tools/vr/build.sh b/tools/vr/build.sh index f28ef326b9..4e9fb12b95 100755 --- a/tools/vr/build.sh +++ b/tools/vr/build.sh @@ -14,7 +14,7 @@ if [ -z "$vkinc" ]; then for ndk in "${ANDROID_NDK_HOME:-}" "${ANDROID_NDK_LATEST_HOME:-}" \ $(ls -d "${ANDROID_HOME:-$HOME/Library/Android/sdk}"/ndk/* 2>/dev/null | sort -r); do [ -n "$ndk" ] || continue - cand=$(ls -d "$ndk"/toolchains/llvm/prebuilt/*/sysroot/usr/include 2>/dev/null | head -1) + cand=$(ls -d "$ndk"/toolchains/llvm/prebuilt/*/sysroot/usr/include 2>/dev/null | head -1 || true) if [ -n "$cand" ] && [ -f "$cand/vulkan/vk_layer.h" ]; then vkinc=$cand; break; fi done fi From a2587f4f207673435ee3718a608b3bc45f6724c8 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:40:11 -0500 Subject: [PATCH 021/141] fix(display): preserve padded layer buffer layouts (#2985) * fix(display): preserve padded layer buffer layouts * fix(display): fall back when layer allocation fails * fix(display): write linear targets at their row pitch --- app/src/main/cpp/waylandcomp/src/sc_layer.c | 8 +- .../cpp/waylandcomp/src/vk_linear_dmabuf.h | 12 +- app/src/main/cpp/waylandcomp/src/vk_loader.h | 2 +- app/src/main/cpp/waylandcomp/src/vk_present.c | 121 +++++++++++------- tools/tests/test_vk_linear_dmabuf.py | 17 +++ tools/tests/vk_linear_dmabuf_test.c | 22 +++- 6 files changed, 125 insertions(+), 57 deletions(-) diff --git a/app/src/main/cpp/waylandcomp/src/sc_layer.c b/app/src/main/cpp/waylandcomp/src/sc_layer.c index 05b201b2e5..a843500c95 100644 --- a/app/src/main/cpp/waylandcomp/src/sc_layer.c +++ b/app/src/main/cpp/waylandcomp/src/sc_layer.c @@ -518,6 +518,10 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm img = vkp_image_import_dmabuf(nh->data[0], fmt == AHB_RGB10A2 ? DRM_ABGR2101010 : DRM_ABGR8888, mod, w, h, got.stride * 4, 0, 1); path = "dma-buf (QTI handle)"; + if (!img && mod == MOD_LINEAR && vkp_can_import_ahb()) { + img = vkp_image_import_ahb(ahb, info, sizeof(info)); + if (img) { mod = SC_MOD_GRALLOC; path = "AHardwareBuffer"; } + } } else { if (tier == TIER_UBWC) { char hd[256]; @@ -941,7 +945,7 @@ int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const stru int wait_fd; int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &wait_fd); - if (idx < 0) { log_drop(l); return 0; } + if (idx < 0) { log_drop(l); return g_alloc_failed ? -1 : 0; } if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1; if (present_slot(l, idx, r, color, 0) != 0) return -1; if (color && color->dataspace) droiddeck_color_frame_shown(color, DROIDDECK_HDR_LAYER_COPY, AHB_RGBA8); @@ -1150,7 +1154,7 @@ int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int transl if (sw <= 0 || sh <= 0) return -1; int wait_fd; int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &wait_fd); - if (idx < 0) { log_drop(l); return 0; } + if (idx < 0) { log_drop(l); return g_alloc_failed ? -1 : 0; } if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1; if (present_slot(l, idx, geo, NULL, translucent) != 0) return -1; if (!l->first_logged) { diff --git a/app/src/main/cpp/waylandcomp/src/vk_linear_dmabuf.h b/app/src/main/cpp/waylandcomp/src/vk_linear_dmabuf.h index f0c92229a7..a820026930 100644 --- a/app/src/main/cpp/waylandcomp/src/vk_linear_dmabuf.h +++ b/app/src/main/cpp/waylandcomp/src/vk_linear_dmabuf.h @@ -24,6 +24,12 @@ static inline uint32_t vkp_linear_dmabuf_texel_bytes(VkFormat fmt) { return fmt == VK_FORMAT_R16G16B16A16_SFLOAT ? 8u : 4u; } +static inline int vkp_padded_linear_target_needs_layout(int drm_modifiers, uint64_t modifier, VkFormat fmt, + int w, uint32_t stride, uint32_t offset) { + return !drm_modifiers && modifier == 0 && + (offset != 0 || (uint64_t)stride != (uint64_t)w * vkp_linear_dmabuf_texel_bytes(fmt)); +} + static inline VkDeviceSize vkp_linear_dmabuf_copy(VkFormat fmt, int w, int h, uint32_t stride, uint32_t offset, VkBufferImageCopy *copy) { const uint32_t texel = vkp_linear_dmabuf_texel_bytes(fmt); @@ -39,11 +45,11 @@ static inline VkDeviceSize vkp_linear_dmabuf_copy(VkFormat fmt, int w, int h, ui } static inline VkBufferMemoryBarrier vkp_linear_dmabuf_ownership(VkBuffer buffer, uint32_t queue_family, - int acquire) { + VkAccessFlags access, int acquire) { return (VkBufferMemoryBarrier){ .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, - .srcAccessMask = acquire ? 0 : VK_ACCESS_TRANSFER_READ_BIT, - .dstAccessMask = acquire ? VK_ACCESS_TRANSFER_READ_BIT : 0, + .srcAccessMask = acquire ? 0 : access, + .dstAccessMask = acquire ? access : 0, .srcQueueFamilyIndex = acquire ? VK_QUEUE_FAMILY_FOREIGN_EXT : queue_family, .dstQueueFamilyIndex = acquire ? queue_family : VK_QUEUE_FAMILY_FOREIGN_EXT, .buffer = buffer, diff --git a/app/src/main/cpp/waylandcomp/src/vk_loader.h b/app/src/main/cpp/waylandcomp/src/vk_loader.h index ee6328a287..c0782140f0 100644 --- a/app/src/main/cpp/waylandcomp/src/vk_loader.h +++ b/app/src/main/cpp/waylandcomp/src/vk_loader.h @@ -22,7 +22,7 @@ X(ResetCommandBuffer) X(BeginCommandBuffer) X(CmdPipelineBarrier) X(CmdBlitImage) \ X(EndCommandBuffer) X(ResetFences) X(QueueSubmit) X(QueuePresentKHR) X(WaitForFences) \ X(QueueWaitIdle) X(GetMemoryFdPropertiesKHR) X(GetAndroidHardwareBufferPropertiesANDROID) \ - X(GetImageSubresourceLayout) X(MapMemory) X(UnmapMemory) X(CmdClearColorImage) \ + X(GetImageSubresourceLayout) X(MapMemory) X(UnmapMemory) X(CmdClearColorImage) X(CmdCopyImageToBuffer) \ X(CreateBuffer) X(DestroyBuffer) X(GetBufferMemoryRequirements) X(BindBufferMemory) \ X(CmdCopyBufferToImage) \ \ diff --git a/app/src/main/cpp/waylandcomp/src/vk_present.c b/app/src/main/cpp/waylandcomp/src/vk_present.c index ebd9404281..7184ff644f 100644 --- a/app/src/main/cpp/waylandcomp/src/vk_present.c +++ b/app/src/main/cpp/waylandcomp/src/vk_present.c @@ -1123,7 +1123,7 @@ static void release_external_client_draws(VkCommandBuffer cmd, const struct vkp_ static void stage_linear_dmabuf(VkCommandBuffer cmd, const struct vkp_image *img) { if (!img || !img->linear_buf) return; const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - VkBufferMemoryBarrier acquire = vkp_linear_dmabuf_ownership(img->linear_buf, g_qfam, 1); + VkBufferMemoryBarrier acquire = vkp_linear_dmabuf_ownership(img->linear_buf, g_qfam, VK_ACCESS_TRANSFER_READ_BIT, 1); VkImageMemoryBarrier write = { .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, .newLayout = VK_IMAGE_LAYOUT_GENERAL, @@ -1132,7 +1132,7 @@ static void stage_linear_dmabuf(VkCommandBuffer cmd, const struct vkp_image *img g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 1, &acquire, 1, &write); g_vk.CmdCopyBufferToImage(cmd, img->linear_buf, img->image, VK_IMAGE_LAYOUT_GENERAL, 1, &img->linear_copy); - VkBufferMemoryBarrier release = vkp_linear_dmabuf_ownership(img->linear_buf, g_qfam, 0); + VkBufferMemoryBarrier release = vkp_linear_dmabuf_ownership(img->linear_buf, g_qfam, VK_ACCESS_TRANSFER_READ_BIT, 0); VkImageMemoryBarrier read = { .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_GENERAL, .newLayout = VK_IMAGE_LAYOUT_GENERAL, @@ -1259,7 +1259,8 @@ static int import_linear_dmabuf(struct vkp_image *img, int fd, const VkBufferIma .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO, .handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT}; VkBufferCreateInfo bci = {.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .pNext = &ext, .size = size, - .usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT, .sharingMode = VK_SHARING_MODE_EXCLUSIVE}; + .usage = img->blit_dst ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : VK_BUFFER_USAGE_TRANSFER_SRC_BIT, + .sharingMode = VK_SHARING_MODE_EXCLUSIVE}; VkResult r = g_vk.CreateBuffer(g_dev, &bci, NULL, &img->linear_buf); if (r != VK_SUCCESS) goto fail; uint32_t allowed = 0xffffffff; @@ -1312,8 +1313,8 @@ static int import_linear_dmabuf(struct vkp_image *img, int fd, const VkBufferIma img->in_general = 1; return 0; fail: - LOGE("dmabuf: reading the linear %dx%d buffer at its row pitch failed (%s); importing it as an image", - img->w, img->h, vk_result_name(r)); + LOGE("dmabuf: %s the linear %dx%d buffer at its row pitch failed (%s)", + img->blit_dst ? "writing" : "reading", img->w, img->h, vk_result_name(r)); if (dupfd >= 0) close(dupfd); destroy_image_objects(img); return -1; @@ -1324,15 +1325,20 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t if (modifier == MOD_INVALID || w <= 0 || h <= 0) return NULL; if (dev_init() != 0) return NULL; + const VkFormat format = drm_to_vk(drm_format); + const int padded_target = as_blit_dst && + vkp_padded_linear_target_needs_layout(g_drm_modifiers, modifier, format, w, stride, offset); + if (padded_target && !g_vk.CmdCopyImageToBuffer) return NULL; + struct vkp_image *img = calloc(1, sizeof(*img)); if (!img) return NULL; img->w = w; img->h = h; img->dmabuf = 1; img->blit_dst = as_blit_dst ? 1 : 0; - img->fmt = drm_to_vk(drm_format); - const int through_buffer = vkp_linear_dmabuf_through_buffer(g_drm_modifiers, modifier, as_blit_dst); + img->fmt = format; + const int through_buffer = padded_target || vkp_linear_dmabuf_through_buffer(g_drm_modifiers, modifier, as_blit_dst); const VkImageUsageFlags sampled_usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; const int modifier_sampled = !as_blit_dst && g_drm_modifiers && g_vk.GetPhysicalDeviceImageFormatProperties2 && modifier_importable(img->fmt, modifier, sampled_usage); - img->sampled = through_buffer ? optimal_sampled(img->fmt) : modifier_sampled; + img->sampled = !as_blit_dst && (through_buffer ? optimal_sampled(img->fmt) : modifier_sampled); /* Each new format/modifier/size a client hands over, once, for the graphics report: a colour * or swizzle mismatch on a non-Adreno driver shows up as the pair it arrived as. */ { @@ -1358,7 +1364,12 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t if (through_buffer) { VkBufferImageCopy linear_copy; const VkDeviceSize linear_size = vkp_linear_dmabuf_copy(img->fmt, w, h, stride, offset, &linear_copy); - if (linear_size && import_linear_dmabuf(img, fd, &linear_copy, linear_size) == 0) return img; + if (linear_size && import_linear_dmabuf(img, fd, &linear_copy, linear_size) == 0) { + if (padded_target) droiddeck_log("gpu", "linear layer target %dx%d writes at pitch %u via DMA-BUF", + w, h, stride); + return img; + } + if (padded_target) { free(img); return NULL; } img->sampled = modifier_sampled; } VkSubresourceLayout plane = {.offset = offset, .rowPitch = stride}; @@ -2522,6 +2533,48 @@ int vkp_map_draw(const struct vkp_draw *d, int out[8]) { return 1; } +static void blit_to_layer(VkCommandBuffer cmd, VkImage src, VkImageLayout src_layout, struct vkp_image *dst, + const VkImageBlit *blit, VkFilter filter) { + const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + const VkImageMemoryBarrier acquire = { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + .srcQueueFamilyIndex = dst->staged ? VK_QUEUE_FAMILY_IGNORED : VK_QUEUE_FAMILY_FOREIGN_EXT, + .dstQueueFamilyIndex = dst->staged ? VK_QUEUE_FAMILY_IGNORED : g_qfam, + .image = dst->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}; + g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, 0, NULL, 0, NULL, 1, &acquire); + g_vk.CmdBlitImage(cmd, src, src_layout, dst->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, blit, filter); + if (dst->staged) { + const VkImageMemoryBarrier read = { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + .newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .image = dst->image, .subresourceRange = range, .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, + .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT}; + g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, 0, NULL, 0, NULL, 1, &read); + const VkBufferMemoryBarrier write = vkp_linear_dmabuf_ownership(dst->linear_buf, g_qfam, VK_ACCESS_TRANSFER_WRITE_BIT, 1); + g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, 0, NULL, 1, &write, 0, NULL); + VkBufferImageCopy copy = dst->linear_copy; + copy.imageExtent.width = (uint32_t)blit->dstOffsets[1].x; + copy.imageExtent.height = (uint32_t)blit->dstOffsets[1].y; + g_vk.CmdCopyImageToBuffer(cmd, dst->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dst->linear_buf, 1, ©); + const VkBufferMemoryBarrier release = vkp_linear_dmabuf_ownership(dst->linear_buf, g_qfam, VK_ACCESS_TRANSFER_WRITE_BIT, 0); + g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, + 0, 0, NULL, 1, &release, 0, NULL); + return; + } + const VkImageMemoryBarrier release = { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + .newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .image = dst->image, .subresourceRange = range, + .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}; + g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, + 0, 0, NULL, 0, NULL, 1, &release); +} + int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) { if (!src || src->blit_dst || !dst || !dst->blit_dst || g_dev_state == -2 || dev_init() != 0) { if (wait_fd >= 0) close(wait_fd); @@ -2540,41 +2593,28 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) { struct vkp_external_client_barrier_pair src_pair; const int src_external = vkp_external_client_barrier_pair( src->image, g_qfam, foreign_image(src), src->blit_dst, &src_pair); - VkImageMemoryBarrier acq[2] = { - src_external ? src_pair.acquire : (VkImageMemoryBarrier){ + VkImageMemoryBarrier acq = src_external ? src_pair.acquire : (VkImageMemoryBarrier){ .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, .newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT}, - {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, - .newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam, - .image = dst->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}}; + .image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT}; if (!src_external) { - acq[0].oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED; - acq[0].newLayout = VK_IMAGE_LAYOUT_GENERAL; - acq[0].srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; + acq.oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED; + acq.newLayout = VK_IMAGE_LAYOUT_GENERAL; + acq.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; src->in_general = 1; } g_vk.CmdPipelineBarrier(g_cmd, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 2, acq); + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, &acq); int bw = src->w < dst->w ? src->w : dst->w, bh = src->h < dst->h ? src->h : dst->h; VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, .srcOffsets = {{0, 0, 0}, {bw, bh, 1}}, .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, .dstOffsets = {{0, 0, 0}, {bw, bh, 1}}}; - g_vk.CmdBlitImage(g_cmd, src->image, - src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL, - dst->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_NEAREST); + blit_to_layer(g_cmd, src->image, src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL, + dst, &blit, VK_FILTER_NEAREST); release_external_client_image(g_cmd, src); - VkImageMemoryBarrier rel = { - .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - .newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam, - .dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .image = dst->image, .subresourceRange = range, - .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}; - g_vk.CmdPipelineBarrier(g_cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - 0, 0, NULL, 0, NULL, 1, &rel); g_vk.EndCommandBuffer(g_cmd); VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT; @@ -2890,31 +2930,14 @@ static int pass_finish(const VkImage *srcs, VkImageLayout src_layout, struct vkp } const int gpu_wait = take_wait_fd(wait_fd); if (gpu_wait < 0) { g_vk.EndCommandBuffer(cmd); return -1; } - VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - for (int i = 0; i < n; i++) { struct vkp_image *dst = dsts[i]; - VkImageMemoryBarrier acq = { - .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, - .newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, - .dstQueueFamilyIndex = g_qfam, .image = dst->image, .subresourceRange = range, - .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}; - g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, - 0, 0, NULL, 0, NULL, 1, &acq); VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, .srcOffsets = {{0, 0, 0}, {g_pass.rw, g_pass.rh, 1}}, .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, .dstOffsets = {{0, 0, 0}, {dst->w, dst->h, 1}}}; - g_vk.CmdBlitImage(cmd, srcs[i], src_layout, dst->image, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, - (g_pass.rw == dst->w && g_pass.rh == dst->h) ? VK_FILTER_NEAREST : VK_FILTER_LINEAR); - VkImageMemoryBarrier rel = { - .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - .newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam, - .dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .image = dst->image, .subresourceRange = range, - .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}; - g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - 0, 0, NULL, 0, NULL, 1, &rel); + blit_to_layer(cmd, srcs[i], src_layout, dst, &blit, + (g_pass.rw == dst->w && g_pass.rh == dst->h) ? VK_FILTER_NEAREST : VK_FILTER_LINEAR); } g_vk.EndCommandBuffer(cmd); diff --git a/tools/tests/test_vk_linear_dmabuf.py b/tools/tests/test_vk_linear_dmabuf.py index a91df519c6..08c4a24577 100644 --- a/tools/tests/test_vk_linear_dmabuf.py +++ b/tools/tests/test_vk_linear_dmabuf.py @@ -134,6 +134,23 @@ class VkLinearDmabufTest(unittest.TestCase): source.write_text(harness) compile_and_run(self, source, tmp, "vk-linear-layer") + def test_layer_import_failure_requests_compositor_fallback(self): + source = (SRC / "sc_layer.c").read_text() + for name in ("sc_layer_present", "sc_layer_present_overlay"): + with self.subTest(layer=name): + body = function(source, name) + self.assertRegex(body, r"if \(idx < 0\) \{ log_drop\(l\); return g_alloc_failed \? -1 : 0; \}") + + def test_layer_blits_use_the_imported_output_row_pitch(self): + source = (SRC / "vk_present.c").read_text() + blit = function(source, "blit_to_layer") + copy = blit.index("CmdCopyImageToBuffer") + self.assertLess(blit.index("VkBufferImageCopy copy = dst->linear_copy"), copy) + self.assertLess(blit.index("VK_ACCESS_TRANSFER_WRITE_BIT, 1"), copy) + self.assertGreater(blit.index("VK_ACCESS_TRANSFER_WRITE_BIT, 0"), copy) + for name in ("vkp_blit_image", "pass_finish"): + self.assertIn("blit_to_layer(", function(source, name)) + if __name__ == "__main__": unittest.main() diff --git a/tools/tests/vk_linear_dmabuf_test.c b/tools/tests/vk_linear_dmabuf_test.c index 3abb66da19..380dfa5c16 100644 --- a/tools/tests/vk_linear_dmabuf_test.c +++ b/tools/tests/vk_linear_dmabuf_test.c @@ -63,6 +63,16 @@ static void check_foreign_image(void) { assert(!vkp_linear_dmabuf_foreign_image(0, 1)); } +static void check_padded_layer_targets(void) { + const VkFormat rgba = VK_FORMAT_R8G8B8A8_UNORM; + const uint64_t qcom_compressed = 0x0500000000000001ULL; + assert(vkp_padded_linear_target_needs_layout(0, 0, rgba, 720, 3072, 0)); + assert(vkp_padded_linear_target_needs_layout(0, 0, rgba, 720, 2880, 64)); + assert(!vkp_padded_linear_target_needs_layout(0, 0, rgba, 1280, 5120, 0)); + assert(!vkp_padded_linear_target_needs_layout(1, 0, rgba, 720, 3072, 0)); + assert(!vkp_padded_linear_target_needs_layout(0, qcom_compressed, rgba, 720, 3072, 0)); +} + static void check_readback_order(void) { assert(vkp_linear_dmabuf_readback_stage(1) & VK_PIPELINE_STAGE_TRANSFER_BIT); assert(vkp_linear_dmabuf_readback_access(1) & VK_ACCESS_TRANSFER_WRITE_BIT); @@ -73,7 +83,7 @@ static void check_readback_order(void) { static void check_ownership(void) { const VkBuffer buffer = (VkBuffer)(uintptr_t)0x4321; const uint32_t queue_family = 3; - const VkBufferMemoryBarrier acquire = vkp_linear_dmabuf_ownership(buffer, queue_family, 1); + const VkBufferMemoryBarrier acquire = vkp_linear_dmabuf_ownership(buffer, queue_family, VK_ACCESS_TRANSFER_READ_BIT, 1); assert(acquire.sType == VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER); assert(acquire.pNext == NULL); assert(acquire.srcQueueFamilyIndex == VK_QUEUE_FAMILY_FOREIGN_EXT); @@ -84,7 +94,7 @@ static void check_ownership(void) { assert(acquire.offset == 0); assert(acquire.size == VK_WHOLE_SIZE); - const VkBufferMemoryBarrier release = vkp_linear_dmabuf_ownership(buffer, queue_family, 0); + const VkBufferMemoryBarrier release = vkp_linear_dmabuf_ownership(buffer, queue_family, VK_ACCESS_TRANSFER_READ_BIT, 0); assert(release.sType == VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER); assert(release.srcQueueFamilyIndex == queue_family); assert(release.dstQueueFamilyIndex == VK_QUEUE_FAMILY_FOREIGN_EXT); @@ -92,6 +102,13 @@ static void check_ownership(void) { assert(release.dstAccessMask == 0); assert(release.buffer == buffer); assert(release.size == VK_WHOLE_SIZE); + + const VkBufferMemoryBarrier write = vkp_linear_dmabuf_ownership(buffer, queue_family, VK_ACCESS_TRANSFER_WRITE_BIT, 1); + const VkBufferMemoryBarrier written = vkp_linear_dmabuf_ownership(buffer, queue_family, VK_ACCESS_TRANSFER_WRITE_BIT, 0); + assert(write.srcQueueFamilyIndex == VK_QUEUE_FAMILY_FOREIGN_EXT); + assert(write.dstAccessMask == VK_ACCESS_TRANSFER_WRITE_BIT); + assert(written.dstQueueFamilyIndex == VK_QUEUE_FAMILY_FOREIGN_EXT); + assert(written.srcAccessMask == VK_ACCESS_TRANSFER_WRITE_BIT); } int main(void) { @@ -99,6 +116,7 @@ int main(void) { check_offset_and_wide_texels(); check_rejected_layouts(); check_path_choice(); + check_padded_layer_targets(); check_foreign_image(); check_readback_order(); check_ownership(); From 3577073ab922094bd3ea811b0d851f791424b543 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Sat, 21 Nov 2026 23:47:35 -0500 Subject: [PATCH 022/141] fix(input): move and resize the on-screen D-pad as one control, per-control button size and sizes above 100% (#2996) * fix(input): move and resize the D-pad as one control, per-control button size and sizes above 100% * fix(input): controller art for copied layouts, keep the minimum size when shrinking the D-pad Copies and per-game versions of the on-screen gamepad now draw the same controller art and placement as the original, and resizing the D-pad from a corner or the per-control slider keeps every arrow at a usable size. * Keep other controls' moves when undoing a repeated resize --- .../input/ControllerOverlayGeometry.kt | 42 ++++++----- .../droiddeck/launcher/input/InputLibrary.kt | 1 + .../launcher/input/InputSurfaceLayout.kt | 23 ++++++ .../launcher/input/LegacyGamepadLayout.kt | 1 - .../launcher/input/OnScreenLayout.kt | 4 +- .../com/droiddeck/launcher/input/PadKit.kt | 2 +- .../launcher/ui/InputSurfaceDialog.kt | 29 +++++++- .../launcher/ui/InputSurfaceEditorView.kt | 44 +++++++---- .../java/com/droiddeck/launcher/ui/PadArt.kt | 14 ++++ .../launcher/input/OnScreenLayoutTest.kt | 26 +++++++ .../launcher/ui/InputSettingsTest.kt | 63 ++++++++++++++++ .../launcher/ui/InputSurfaceEditorViewTest.kt | 74 ++++++++++++++++++- 12 files changed, 279 insertions(+), 44 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/input/ControllerOverlayGeometry.kt b/app/src/main/java/com/droiddeck/launcher/input/ControllerOverlayGeometry.kt index c5d33d9508..d274269d4c 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/ControllerOverlayGeometry.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/ControllerOverlayGeometry.kt @@ -13,11 +13,13 @@ internal class ControllerOverlayGeometry( private val density = metrics.density private val dpi = metrics.ydpi.takeIf { it in metrics.densityDpi * .6f..metrics.densityDpi * 1.6f } ?: metrics.densityDpi.toFloat() - private val unit = minOf( - min(w / 1600f, h / 900f) * min(1f, 80f / max(h / dpi * 25.4f, 1f)) * scale, + private val fit = minOf( + min(w / 1600f, h / 900f) * min(1f, 80f / max(h / dpi * 25.4f, 1f)), (w - safe.left - safe.right).coerceAtLeast(1f) / 1200f, (h - safe.top - safe.bottom).coerceAtLeast(1f) / 900f, ) + private val unit = fit * min(scale, 1f) + private val size = fit * scale private fun anchor(value: Float, reference: Float, extent: Float, start: Int, end: Int): Float { val low = start + value * unit @@ -37,18 +39,18 @@ internal class ControllerOverlayGeometry( if (!kit.steam) return placeStandardPad(elements, kit) val leftEdge = safe.left + 52f * density val middle = (w + safe.left - safe.right) / 2f - val keyboard = Box(max(x(136f), leftEdge + 46f * unit), y(848f), 46f).takeIf { elements.any { it.id == KEYBOARD } } + val keyboard = Box(max(x(136f), leftEdge + 46f * size), y(848f), 46f).takeIf { elements.any { it.id == KEYBOARD } } val row = fitRow(listOfNotNull(keyboard, - Box(max(x(370f), leftEdge + 66f * unit), y(852f), 66f, 30f), + Box(max(x(370f), leftEdge + 66f * size), y(852f), 66f, 30f), Box(middle - 140f * unit, y(850f), 46f, 26f), Box(middle + 140f * unit, y(850f), 46f, 26f), Box(x(1230f), y(852f), 66f, 30f)), leftEdge) val (guide, select, start, qam) = row.takeLast(4) val positions = shoulders() + face(1375f, 345f, 96f) + mapOf( - InputControl.UP to Box(x(220f), y(345f) - 102.5f * unit, 55.5f, 47.5f), - InputControl.RIGHT to Box(x(220f) + 102.5f * unit, y(345f), 47.5f, 55.5f), - InputControl.DOWN to Box(x(220f), y(345f) + 102.5f * unit, 55.5f, 47.5f), - InputControl.LEFT to Box(x(220f) - 102.5f * unit, y(345f), 47.5f, 55.5f), + InputControl.UP to Box(x(220f), y(345f) - 102.5f * size, 55.5f, 47.5f), + InputControl.RIGHT to Box(x(220f) + 102.5f * size, y(345f), 47.5f, 55.5f), + InputControl.DOWN to Box(x(220f), y(345f) + 102.5f * size, 55.5f, 47.5f), + InputControl.LEFT to Box(x(220f) - 102.5f * size, y(345f), 47.5f, 55.5f), InputControl.LS to Box(x(290f), y(640f), 96f), InputControl.RS to Box(x(1310f), y(640f), 96f), InputControl.SELECT to select, @@ -85,7 +87,7 @@ internal class ControllerOverlayGeometry( private fun placeStandardPad(elements: List, kit: PadKit): List { val leftEdge = safe.left + 52f * density val middle = (w + safe.left - safe.right) / 2f - val keyboard = Box(max(x(136f), leftEdge + 46f * unit), y(848f), 46f).takeIf { elements.any { it.id == KEYBOARD } } + val keyboard = Box(max(x(136f), leftEdge + 46f * size), y(848f), 46f).takeIf { elements.any { it.id == KEYBOARD } } val controls = if (kit.playStation) listOf( InputControl.QAM to Box(x(220f), y(848f), 46f), InputControl.SELECT to Box(middle - 160f * unit, y(850f), 50f, 30f), @@ -103,15 +105,15 @@ internal class ControllerOverlayGeometry( face(1350f, 395f, 96f) + dpad(250f, 395f, 125f, kit.dpad) + mapOf( InputControl.LS to Box(x(565f), y(690f), 100f), InputControl.RS to Box(x(1035f), y(690f), 100f), - InputControl.L3 to Box(x(565f) - 135f * unit, y(690f) - 100f * unit, 42f), - InputControl.R3 to Box(x(1035f) + 135f * unit, y(690f) - 100f * unit, 42f), + InputControl.L3 to Box(x(565f) - 135f * size, y(690f) - 100f * size, 42f), + InputControl.R3 to Box(x(1035f) + 135f * size, y(690f) - 100f * size, 42f), ) } else { face(1375f, 400f, 94f) + dpad(470f, 675f, 118f, kit.dpad) + mapOf( InputControl.LS to Box(x(235f), y(400f), 104f), InputControl.RS to Box(x(1130f), y(690f), 104f), - InputControl.L3 to Box(x(235f) + 150f * unit, y(400f) - 110f * unit, 42f), - InputControl.R3 to Box(x(1130f) + 160f * unit, y(690f) + 100f * unit, 42f), + InputControl.L3 to Box(x(235f) + 150f * size, y(400f) - 110f * size, 42f), + InputControl.R3 to Box(x(1130f) + 160f * size, y(690f) + 100f * size, 42f), ) } return elements.map { element -> @@ -131,16 +133,16 @@ internal class ControllerOverlayGeometry( ) private fun face(cx: Float, cy: Float, offset: Float) = mapOf( - InputControl.Y to Box(x(cx), y(cy) - offset * unit, 58f), - InputControl.X to Box(x(cx) - offset * unit, y(cy), 58f), - InputControl.B to Box(x(cx) + offset * unit, y(cy), 58f), - InputControl.A to Box(x(cx), y(cy) + offset * unit, 58f), + InputControl.Y to Box(x(cx), y(cy) - offset * size, 58f), + InputControl.X to Box(x(cx) - offset * size, y(cy), 58f), + InputControl.B to Box(x(cx) + offset * size, y(cy), 58f), + InputControl.A to Box(x(cx), y(cy) + offset * size, 58f), ) private fun dpad(cx: Float, cy: Float, radius: Float, style: DpadStyle): Map { val inner = radius * if (style == DpadStyle.DISC) .25f else .14f val depth = (radius - inner) / 2f - val offset = (radius - depth) * unit + val offset = (radius - depth) * size val side = radius * .25f return mapOf( InputControl.UP to Box(x(cx), y(cy) - offset, side, depth), @@ -160,12 +162,12 @@ internal class ControllerOverlayGeometry( } private inner class Box(val cx: Float, val cy: Float, val hw: Float, val hh: Float = hw) { - val width get() = max(hw * 2f * unit, w * .03f) + val width get() = max(hw * 2f * size, w * .03f) fun at(cx: Float) = Box(cx, cy, hw, hh) fun place(element: InputSurfaceElement): InputSurfaceElement { - val height = max(hh * 2f * unit, h * .03f) + val height = max(hh * 2f * size, h * .03f) return element.copy( x = (cx - width / 2f).coerceIn(safe.left.toFloat(), max(safe.left.toFloat(), w - safe.right - width)) / w, y = (cy - height / 2f).coerceIn(safe.top.toFloat(), max(safe.top.toFloat(), h - safe.bottom - height)) / h, diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt b/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt index ca8838a199..9532f51778 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt @@ -27,6 +27,7 @@ data class SavedInputLayout( val rotatedScale: Float = 1f, ) { val editable get() = template == InputLayoutTemplate.CUSTOM + val overlay get() = (origin ?: id).let { it == InputLibraries.OVERLAY || it.startsWith("migrated.layout.") } val quickButtons get() = QUICK_BUTTONS.filter { button -> elements.any { it.quickButton == button } } fun withQuickButton(button: InputCommand, shown: Boolean) = copy(style = style.copy(hidden = if (shown) style.hidden - button else style.hidden + button)) diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputSurfaceLayout.kt b/app/src/main/java/com/droiddeck/launcher/input/InputSurfaceLayout.kt index e7e1c58a36..888e9bc260 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/InputSurfaceLayout.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/InputSurfaceLayout.kt @@ -3,6 +3,8 @@ package com.droiddeck.launcher.input import android.content.Context import org.json.JSONArray import org.json.JSONObject +import kotlin.math.max +import kotlin.math.min enum class InputElementKind(val control: InputControl) { BUTTON(InputControl.A), STICK(InputControl.LS), TRACKPAD(InputControl.LEFT_PAD), @@ -63,6 +65,27 @@ internal fun List.scaled(factor: Float): List.groupOf(e: InputSurfaceElement) = if (e.dpadPiece) filter { it.dpadPiece } else listOf(e) + +internal fun List.frame(): InputSurfaceElement { + val left = minOf { it.x }; val top = minOf { it.y } + return first().copy(x = left, y = top, width = maxOf { it.x + it.width } - left, height = maxOf { it.y + it.height } - top) +} + +internal fun List.resizedAroundCentre(factor: Float): List { + if (isEmpty()) return this + val f = frame() + val k = factor.coerceIn(.03f / minOf { min(it.width, it.height) }, 1f / max(f.width, f.height)) + val w = f.width * k; val h = f.height * k + val left = (f.x + f.width / 2 - w / 2).coerceIn(0f, 1f - w) + val top = (f.y + f.height / 2 - h / 2).coerceIn(0f, 1f - h) + return map { it.copy(x = left + (it.x - f.x) * k, y = top + (it.y - f.y) * k, width = it.width * k, height = it.height * k).bounded() } +} + internal fun List.withPositionsOf(defaults: List): List { val byId = defaults.associateBy { it.id } return map { e -> byId[e.id]?.let { d -> e.copy(x = d.x, y = d.y, width = d.width, height = d.height).bounded() } ?: e } diff --git a/app/src/main/java/com/droiddeck/launcher/input/LegacyGamepadLayout.kt b/app/src/main/java/com/droiddeck/launcher/input/LegacyGamepadLayout.kt index 5d81a356d9..a944ec28ef 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/LegacyGamepadLayout.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/LegacyGamepadLayout.kt @@ -334,7 +334,6 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid const val STICK_REACH = 1.25f const val LEGACY_DPAD_RADIUS_DP = 26f const val LEGACY_DPAD_OFFSET_DP = 52f - val DPAD = setOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT) const val KEYBOARD_ID = "builtin:keyboard" const val KEYBOARD_RADIUS_DP = 18f const val KEYBOARD_X_DP = 90f diff --git a/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt b/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt index 3f74de743f..33d951a626 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt @@ -12,7 +12,7 @@ import kotlin.math.roundToInt object OnScreenLayout { internal fun supportsFloatingSteamControls(controller: String, layout: SavedInputLayout?) = - layout?.id == InputLibraries.OVERLAY && + layout?.overlay == true && (controller == SessionPrefs.CONTROLLER_DECK || controller == SessionPrefs.CONTROLLER_STEAM) data class Dock(val portrait: Boolean, val grips: Boolean, val left: InputControl = InputControl.LS, val right: InputControl = InputControl.RS) { @@ -156,7 +156,7 @@ object OnScreenLayout { if (gamepad.any { it.id.startsWith("legacy:") }) { val named = layout.id.removePrefix("migrated.layout.").takeIf { it != layout.id }?.split('x')?.mapNotNull { it.toIntOrNull() } ?.takeIf { it.size == 2 && it.all { size -> size > 0 } }?.let { it[0] to it[1] } - val aspectSize = layout.aspect.takeIf { layout.id == InputLibraries.OVERLAY && it > 0f } + val aspectSize = layout.aspect.takeIf { layout.overlay && it > 0f } ?.let { (it * height).roundToInt().coerceAtLeast(1) to height } for ((w, h) in listOfNotNull(named, width to height, aspectSize, long to short, short to long).distinct()) { val generator = LegacyGamepadLayout(display, w, h, scale = layout.scale) diff --git a/app/src/main/java/com/droiddeck/launcher/input/PadKit.kt b/app/src/main/java/com/droiddeck/launcher/input/PadKit.kt index c976d310e9..750bceb5c9 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/PadKit.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/PadKit.kt @@ -42,7 +42,7 @@ internal enum class PadKit(val face: FaceGlyphs, val dpad: DpadStyle, val stick: companion object { fun forOverlay(context: Context, layout: SavedInputLayout?): PadKit? = - if (layout?.id != InputLibraries.OVERLAY) null else when (SessionPrefs.steamController(context)) { + if (layout?.overlay != true) null else when (SessionPrefs.steamController(context)) { SessionPrefs.CONTROLLER_DECK -> STEAM_DECK SessionPrefs.CONTROLLER_STEAM -> STEAM_CONTROLLER SessionPrefs.CONTROLLER_XBOX360 -> XBOX diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt index ca701cebf8..8f8e592cd2 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt @@ -97,8 +97,13 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB var aspect by mutableFloatStateOf(layout.aspect) private var scaleBase by mutableStateOf, List, Float>?>(null) private var scaleValue by mutableIntStateOf(100) + private var pieceBase by mutableStateOf, List, Int>?>(null) + private var pieceLayout: List? = null + private val piece get() = element?.let { e -> (if (elements.any { it.id == e.id }) elements else shown).groupOf(e) }.orEmpty() + val scaleRange get() = if (piece.isEmpty()) 80..125 else 50..200 private val rescales get() = gamepad?.let { pad -> elements.any { it.id in pad.ids } } == true val scale get() = when { + piece.isNotEmpty() -> pieceBase?.takeIf { it.second == piece && pieceLayout == elements }?.third ?: 100 scaleBase?.second == elements -> scaleValue rescales -> ((if (canvas.width > 0 && canvas.height > 0 && aspect > 0f && (aspect < 1f) != (canvasAspect < 1f)) OnScreenLayout.oriented(layout, canvas.width, canvas.height).scale else layoutScale) * 100).roundToInt() @@ -143,6 +148,24 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB } else base.first.scaled(factor) scaleValue = percent; scaleBase = Triple(base.first, elements, base.third) } + fun scaleSelected(context: android.content.Context, percent: Int) { + val id = selected ?: return + val adopted = adoptDisplayedFrame(context) + val base = pieceBase?.takeIf { it.second == piece && pieceLayout == elements } ?: run { + if (!adopted && canvas.width > 0 && canvas.height > 0 && shown.isNotEmpty()) { + val open = toolsExpanded + beginEdit(shown, canvasAspect) + toolsExpanded = open + } else if (!adopted) checkpoint() + val start = elements.firstOrNull { it.id == id }?.let { elements.groupOf(it) } ?: return + Triple(start, start, 100) + } + val resized = base.first.resizedAroundCentre(percent / 100f) + val byId = resized.associateBy { it.id } + elements = elements.map { byId[it.id] ?: it } + pieceBase = Triple(base.first, resized, percent) + pieceLayout = elements + } var shown by mutableStateOf>(emptyList()) private val canvasAspect get() = canvas.width.toFloat() / canvas.height.coerceAtLeast(1) @@ -337,7 +360,7 @@ private fun SurfaceCanvas(draft: SurfaceDraft, transparent: Boolean = false) { view.onBeginEdit = { e, w, h -> draft.beginEdit(e, w.toFloat() / h, if (draft.hasGamepad) GamepadScaler(view.context, w, h, draft.layout) else null) } view.onResize = { w, h -> draft.canvas = IntSize(w, h) } view.onDisplayed = { draft.shown = it } - view.onChange = { e -> if (!draft.properties) draft.elements = draft.elements.map { if (it.id == e.id) e else it } } + view.onChange = { changed -> if (!draft.properties) changed.associateBy { it.id }.let { byId -> draft.elements = draft.elements.map { byId[it.id] ?: it } } } }) } @@ -407,8 +430,8 @@ private fun SurfaceToolbar(draft: SurfaceDraft, onSave: () -> Unit, onLeave: () } PrimaryButton(stringResource(R.string.input_editor_done), compact = true, onClick = onSave) } - if (draft.elements.isNotEmpty()) SliderRow(stringResource(R.string.ctrl_size), null, draft.scale, 80..125, step = 5, - format = { "$it%" }, modifier = Modifier.testTag("input-editor-scale")) { draft.scaleAll(context, it) } + if (draft.elements.isNotEmpty()) SliderRow(stringResource(R.string.ctrl_size), null, draft.scale, draft.scaleRange, step = 5, + format = { "$it%" }, modifier = Modifier.testTag("input-editor-scale")) { if (draft.element != null) draft.scaleSelected(context, it) else draft.scaleAll(context, it) } } @OptIn(ExperimentalLayoutApi::class) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt index d3922ef0c5..301747dc18 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt @@ -16,6 +16,9 @@ import com.droiddeck.launcher.input.PadKit import com.droiddeck.launcher.input.SavedInputLayout import com.droiddeck.launcher.input.InputSurfaceElement import com.droiddeck.launcher.input.InputSurfaceStyle +import com.droiddeck.launcher.input.dpadPiece +import com.droiddeck.launcher.input.frame +import com.droiddeck.launcher.input.groupOf import com.droiddeck.launcher.input.snapSurfaceElement import kotlin.math.abs @@ -41,13 +44,13 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { set(value) { field = value; invalidate() } var onSelect: (String?) -> Unit = {} var onBeginEdit: (List, Int, Int) -> Unit = { _, _, _ -> } - var onChange: (InputSurfaceElement) -> Unit = {} + var onChange: (List) -> Unit = {} var onResize: (Int, Int) -> Unit = { _, _ -> } var onDisplayed: (List) -> Unit = {} private val preview = InputSurfaceView(context) private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.rgb(26, 159, 255); strokeWidth = 2 * resources.displayMetrics.density } private val radius = 14 * resources.displayMetrics.density - private var original: InputSurfaceElement? = null + private var original: List = emptyList() private var downX = 0f private var downY = 0f private var corner = 0 @@ -100,13 +103,15 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { paint.style = Paint.Style.STROKE guideX?.let { canvas.drawLine(width * it, 0f, width * it, height.toFloat(), paint) } guideY?.let { canvas.drawLine(0f, height * it, width.toFloat(), height * it, paint) } - val e = visibleElements.firstOrNull { it.id == selected } ?: return + val e = visibleElements.firstOrNull { it.id == selected }?.let { visibleElements.groupOf(it).frame() } ?: return val l = width * e.x; val t = height * e.y; val r = l + width * e.width; val b = t + height * e.height paint.style = Paint.Style.STROKE; canvas.drawRect(l, t, r, b, paint) paint.style = Paint.Style.FILL for (x in listOf(l, r)) for (y in listOf(t, b)) canvas.drawCircle(x, y, radius / 3, paint) } + private fun contains(e: InputSurfaceElement, x: Float, y: Float) = x / width in e.x..(e.x + e.width) && y / height in e.y..(e.y + e.height) + private fun clearGuides() { guideX = null; guideY = null; invalidate() } override fun onInterceptTouchEvent(event: MotionEvent) = true @@ -118,7 +123,7 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { MotionEvent.ACTION_DOWN -> { clearGuides() downX = event.x; downY = event.y; dragging = false; corner = 0 - val current = visibleElements.firstOrNull { it.id == selected } + val current = visibleElements.firstOrNull { it.id == selected }?.let { visibleElements.groupOf(it).frame() } if (current != null) { val left = width * current.x; val top = height * current.y val right = left + width * current.width; val bottom = top + height * current.height @@ -126,13 +131,16 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { val vertical = if (abs(downY - top) < radius) 4 else if (abs(downY - bottom) < radius) 8 else 0 if (horizontal != 0 && vertical != 0) corner = horizontal or vertical } - original = if (corner != 0) current else visibleElements.asReversed().firstOrNull { - downX / width in it.x..(it.x + it.width) && downY / height in it.y..(it.y + it.height) - } - selected = original?.id; onSelect(selected) + val touched = if (corner != 0) visibleElements.firstOrNull { it.id == selected } + else visibleElements.asReversed().firstOrNull { contains(it, downX, downY) } + ?: visibleElements.filter { it.dpadPiece }.takeIf { it.isNotEmpty() && contains(it.frame(), downX, downY) } + ?.let { pad -> pad.firstOrNull { it.id == selected } ?: pad.first() } + original = touched?.let { visibleElements.groupOf(it) }.orEmpty() + selected = touched?.id; onSelect(selected) } MotionEvent.ACTION_MOVE -> { - val e = original ?: return true + if (original.isEmpty()) return true + val e = original.frame() if (!dragging && abs(event.x - downX) + abs(event.y - downY) > ViewConfiguration.get(context).scaledTouchSlop) { dragging = true; onBeginEdit(visibleElements, width, height) } @@ -140,20 +148,24 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { val dx = (event.x - downX) / width; val dy = (event.y - downY) / height val next = if (corner == 0) e.copy(x = (e.x + dx).coerceIn(0f, 1f - e.width), y = (e.y + dy).coerceIn(0f, 1f - e.height)) else { - val left = if (corner and 1 != 0) (e.x + dx).coerceIn(0f, e.x + e.width - .03f) else e.x - val top = if (corner and 4 != 0) (e.y + dy).coerceIn(0f, e.y + e.height - .03f) else e.y - val right = if (corner and 2 != 0) (e.x + e.width + dx).coerceIn(left + .03f, 1f) else e.x + e.width - val bottom = if (corner and 8 != 0) (e.y + e.height + dy).coerceIn(top + .03f, 1f) else e.y + e.height + val minW = (.03f * e.width / original.minOf { it.width }).coerceIn(.03f, e.width.coerceAtLeast(.03f)) + val minH = (.03f * e.height / original.minOf { it.height }).coerceIn(.03f, e.height.coerceAtLeast(.03f)) + val left = if (corner and 1 != 0) (e.x + dx).coerceIn(0f, (e.x + e.width - minW).coerceAtLeast(0f)) else e.x + val top = if (corner and 4 != 0) (e.y + dy).coerceIn(0f, (e.y + e.height - minH).coerceAtLeast(0f)) else e.y + val right = if (corner and 2 != 0) (e.x + e.width + dx).coerceIn((left + minW).coerceAtMost(1f), 1f) else e.x + e.width + val bottom = if (corner and 8 != 0) (e.y + e.height + dy).coerceIn((top + minH).coerceAtMost(1f), 1f) else e.y + e.height e.copy(x = left, y = top, width = right - left, height = bottom - top).bounded() } - val aligned = if (snap) snapSurfaceElement(next, visibleElements.filter { it.id != e.id }, 9 * resources.displayMetrics.density / width, + val aligned = if (snap) snapSurfaceElement(next, visibleElements.filter { v -> original.none { it.id == v.id } }, 9 * resources.displayMetrics.density / width, 9 * resources.displayMetrics.density / height, corner) else null if (aligned != null && (aligned.x != null && aligned.x != guideX || aligned.y != null && aligned.y != guideY)) performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK) guideX = aligned?.x; guideY = aligned?.y - onChange(aligned?.element ?: next) + val f = aligned?.element ?: next + val sx = f.width / e.width; val sy = f.height / e.height + onChange(original.map { it.copy(x = f.x + (it.x - e.x) * sx, y = f.y + (it.y - e.y) * sy, width = it.width * sx, height = it.height * sy) }) invalidate() } - MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { original = null; dragging = false; clearGuides() } + MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { original = emptyList(); dragging = false; clearGuides() } } return true } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PadArt.kt b/app/src/main/java/com/droiddeck/launcher/ui/PadArt.kt index f92e694241..e0ae4c9480 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PadArt.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PadArt.kt @@ -50,6 +50,7 @@ internal class PadArt(context: Context) { InputControl.LB, InputControl.RB, InputControl.LT, InputControl.RT -> shoulder(canvas, w, h, control, kit, pressed) InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5 -> grip(canvas, w, h, control.label, pressed) InputControl.L3, InputControl.R3 -> small(canvas, w, h, control.label, pressed) + InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT -> arrow(canvas, w, h, control, pressed) InputControl.SELECT, InputControl.START, InputControl.GUIDE, InputControl.QAM -> { val (shape, icon) = systemLook(kit, control) system(canvas, w, h, shape, icon, pressed) @@ -238,6 +239,19 @@ internal class PadArt(context: Context) { op(bar, Path.Op.UNION) } + fun arrow(canvas: Canvas, w: Float, h: Float, control: InputControl, pressed: Boolean) { + val cx = w / 2f; val cy = h / 2f + val s = min(w, h) / 2f - dp(2f) + val (dx, dy) = when (control) { + InputControl.UP -> 0f to -1f + InputControl.RIGHT -> 1f to 0f + InputControl.DOWN -> 0f to 1f + else -> -1f to 0f + } + glass(canvas, roundRect(cx - s, cy - s, cx + s, cy + s, s * .32f), pressed) + chevron(canvas, cx, cy, dx, dy, s * .3f, if (pressed) ON_ACCENT else INK, s * .14f) + } + /** [held] bits: up 1, right 2, down 4, left 8. */ fun dpad(canvas: Canvas, w: Float, h: Float, kit: PadKit, held: Int, chevrons: Boolean = true, ink: Int = INK) { val cx = w / 2f; val cy = h / 2f diff --git a/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt index 79de797f02..d465b87a67 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt @@ -514,6 +514,32 @@ class OnScreenLayoutTest { } } + @Test @Config(qualifiers = "w800dp-h450dp-land-320dpi") + fun buttonSizeGrowsAndShrinksControlsOnAScreenWhoseHeightAlreadyLimitsTheLayout() { + val (display, _) = InputLibraries.primaryDisplay(context) + val stock = gamepad() + fun at(scale: Float) = OnScreenLayout.elements(context, stock.copy(scale = scale, + elements = LegacyGamepadLayout(display, 1600, 900, scale = scale).regenerate(stock.elements)), 1600, 900, Rect()) + fun List.centre(controls: List) = controls.map { at(it) }.let { c -> + c.sumOf { (it.x + it.width / 2).toDouble() } / c.size to c.sumOf { (it.y + it.height / 2).toDouble() } / c.size } + val face = listOf(InputControl.A, InputControl.B, InputControl.X, InputControl.Y) + val dpad = listOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT) + for (kit in kits) { + SessionPrefs.setSteamController(context, kit) + val normal = at(1f) + for (scale in listOf(.8f, 1.25f)) { + val placed = at(scale) + assertEquals("$kit $scale", normal.at(InputControl.A).width * scale, placed.at(InputControl.A).width, .002f) + assertEquals("$kit $scale", normal.at(InputControl.LS).height * scale, placed.at(InputControl.LS).height, .002f) + if (scale > 1f) for (cluster in listOf(face, dpad)) { + val (x0, y0) = normal.centre(cluster); val (x1, y1) = placed.centre(cluster) + assertEquals("$kit", x0, x1, .01); assertEquals("$kit", y0, y1, .01) + } + assertInside(placed, 1600, 900) + } + } + } + @Test @Config(qualifiers = "w1280dp-h800dp-land-mdpi") fun tabletOverlaysStayInTheLowerHalfOfTheScreen() { for (kit in kits) { diff --git a/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt index ed1d58f2bd..cda4bbeb9a 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt @@ -522,6 +522,69 @@ class InputSettingsTest { } } + @Test fun buttonSizeResizesOnlyTheSelectedControlAndEverythingWithoutASelection() { + val library = InputLibraries.read(context) + val layout = library.layout("game", InputRole.PRIMARY)!! + compose.setContent { DroidDeckTheme { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY, + layoutId = layout.id, bindingsId = library.profile("game").binding(InputRole.PRIMARY)) } } + fun editor() = generateSequence(listOf(ShadowDialog.getLatestDialog().window!!.decorView)) { views -> + views.filterIsInstance().flatMap { g -> (0 until g.childCount).map(g::getChildAt) }.ifEmpty { null } + }.flatten().filterIsInstance().first() + val stock = compose.runOnIdle { editor().rendered().associateBy { it.id } } + compose.onNodeWithTag("input-editor-tools").performClick() + compose.runOnIdle { editor().onSelect("legacy:a") } + val slider = compose.onNodeWithTag("input-editor-scale").performScrollTo() + slider.assert(SemanticsMatcher.expectValue(androidx.compose.ui.semantics.SemanticsProperties.StateDescription, "100%")) + slider.performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(150f) } + val one = compose.runOnIdle { editor().rendered().associateBy { it.id } } + assertEquals(stock.getValue("legacy:a").width * 1.5f, one.getValue("legacy:a").width, .002f) + for (id in listOf("legacy:b", "legacy:x", "legacy:ls")) stock.getValue(id).let { e -> one.getValue(id).let { o -> + assertEquals(id, e.x, o.x, .0001f); assertEquals(id, e.y, o.y, .0001f); assertEquals(id, e.width, o.width, .0001f) } } + compose.runOnIdle { editor().onSelect("legacy:up") } + slider.performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(150f) } + val pad = compose.runOnIdle { editor().rendered().associateBy { it.id } } + for (id in listOf("legacy:up", "legacy:down", "legacy:left", "legacy:right")) assertEquals(id, stock.getValue(id).height * 1.5f, pad.getValue(id).height, .002f) + compose.runOnIdle { assertEquals(4, editor().artworkDpad().size) } + compose.runOnIdle { editor().onSelect(null) } + slider.assert(SemanticsMatcher.expectValue(androidx.compose.ui.semantics.SemanticsProperties.StateDescription, "100%")) + slider.performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(110f) } + val all = compose.runOnIdle { editor().rendered().associateBy { it.id } } + assertEquals(stock.getValue("legacy:ls").width * 1.1f, all.getValue("legacy:ls").width, .003f) + assertEquals(stock.getValue("legacy:a").width * 1.65f, all.getValue("legacy:a").width, .004f) + compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick() + compose.runOnIdle { assertEquals(1.1f, InputLibraries.read(context).layouts.first { it.id == layout.id }.scale) } + } + + @Test fun undoAfterResizingAControlAgainKeepsAnotherControlsMove() { + val library = InputLibraries.read(context) + val layout = library.layout("game", InputRole.PRIMARY)!! + compose.setContent { DroidDeckTheme { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY, + layoutId = layout.id, bindingsId = library.profile("game").binding(InputRole.PRIMARY)) } } + fun editor() = generateSequence(listOf(ShadowDialog.getLatestDialog().window!!.decorView)) { views -> + views.filterIsInstance().flatMap { g -> (0 until g.childCount).map(g::getChildAt) }.ifEmpty { null } + }.flatten().filterIsInstance().first() + compose.onNodeWithTag("input-editor-tools").performClick() + compose.runOnIdle { editor().onSelect("legacy:a") } + fun slider() = compose.onNodeWithTag("input-editor-scale").performScrollTo() + slider().performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(150f) } + val resized = compose.runOnIdle { editor().rendered().associateBy { it.id } } + compose.runOnIdle { + val view = editor() + view.onBeginEdit(view.rendered(), view.width, view.height) + view.onChange(listOf(view.rendered().first { it.id == "legacy:b" }.let { it.copy(x = it.x - .1f) })) + } + val moved = compose.runOnIdle { editor().rendered().associateBy { it.id } } + assertEquals(resized.getValue("legacy:b").x - .1f, moved.getValue("legacy:b").x, .002f) + compose.onNodeWithTag("input-editor-tools").performClick() + compose.runOnIdle { editor().onSelect("legacy:a") } + slider().assert(SemanticsMatcher.expectValue(androidx.compose.ui.semantics.SemanticsProperties.StateDescription, "100%")) + slider().performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(120f) } + compose.onNodeWithText(context.getString(R.string.input_editor_undo)).performScrollTo().performClick() + val undone = compose.runOnIdle { editor().rendered().associateBy { it.id } } + assertEquals(moved.getValue("legacy:b").x, undone.getValue("legacy:b").x, .0001f) + assertEquals(resized.getValue("legacy:a").width, undone.getValue("legacy:a").width, .0001f) + } + @Test fun buttonSizeShowsTheGamepadWhereItWillBeSaved() { val library = InputLibraries.read(context) val layout = library.layout("game", InputRole.PRIMARY)!! diff --git a/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceEditorViewTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceEditorViewTest.kt index a6cbb2ab95..d322a387df 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceEditorViewTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceEditorViewTest.kt @@ -62,7 +62,6 @@ class InputSurfaceEditorViewTest { private fun field(target: Any, name: String) = target.javaClass.getDeclaredField(name).also { it.isAccessible = true }.get(target) private fun InputSurfaceEditorView.controls() = (field(field(this, "preview")!!, "customCanvas") as ViewGroup).let { canvas -> (0 until canvas.childCount).map(canvas::getChildAt) } - private fun InputSurfaceEditorView.artworkDpad() = field(field(this, "preview")!!, "artworkDpad") as List<*> private fun InputSurfaceEditorView.rects() = controls().map { listOf(it.left, it.top, it.width, it.height) } private fun InputSurfaceEditorView.assertControlsDrawnWhereDisplayed() { @@ -140,6 +139,25 @@ class InputSurfaceEditorViewTest { assertEquals(4, view.artworkDpad().size) } + @Test fun copiesOfTheOverlayDrawTheSameKitArtworkInTheSamePlaces() { + val source = overlay() + val copy = source.derived("copy", "Copy") + val again = copy.derived("again", "Again") + for (layout in listOf(copy, again)) { + assertEquals(PadKit.forOverlay(context, source), PadKit.forOverlay(context, layout)) + for ((w, h) in listOf(2400 to 1504, 1504 to 2400)) { + assertEquals(OnScreenLayout.editorElements(context, source, w, h), + OnScreenLayout.editorElements(context, layout, w, h)) + } + assertEquals(4, editor(layout, 2400, 1504).artworkDpad().size) + } + assertNotNull(PadKit.forOverlay(context, source.copy(id = "migrated.layout.2400x1504"))) + assertEquals(null, PadKit.forOverlay(context, this.layout)) + assertEquals(null, PadKit.forOverlay(context, this.layout.derived("custom-copy", "Copy"))) + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE) + assertEquals(null, PadKit.forOverlay(context, copy)) + } + @Config(qualifiers = "xhdpi") @Test fun controlsAddedForTheScreenAreDrawnOnTheFirstFrameInBothOrientations() { SessionState.mode = SessionService.MODE_STEAM @@ -203,6 +221,57 @@ class InputSurfaceEditorViewTest { assertEquals(a.width, moved.width, .0001f) } + @Test fun theDpadMovesAndResizesAsOneControlFromAnyArrowOrItsCentre() { + val view = editor(overlay(), 2400, 1504) + val arrows = listOf("legacy:up", "legacy:right", "legacy:down", "legacy:left") + fun pad() = view.rendered().filter { it.id in arrows }.associateBy { it.id } + val before = pad() + assertEquals(4, view.artworkDpad().size) + val changes = mutableListOf() + view.onBeginEdit = { shown, w, h -> view.aspect = w.toFloat() / h; view.elements = shown } + view.onChange = { changes += it; view.elements = view.elements.map { e -> it.firstOrNull { c -> c.id == e.id } ?: e } } + val left = before.getValue("legacy:left"); val right = before.getValue("legacy:right") + val x = (left.x + left.width + right.x) / 2 * 2400; val y = (left.y + left.height / 2) * 1504 + view.touch(MotionEvent.ACTION_DOWN, x, y) + view.touch(MotionEvent.ACTION_MOVE, x + 240f, y - 150f) + view.touch(MotionEvent.ACTION_UP, x + 240f, y - 150f) + val moved = changes.takeLast(4).associateBy { it.id } + assertEquals(arrows.toSet(), moved.keys) + for (id in arrows) { + assertEquals(id, before.getValue(id).x + 240f / 2400, moved.getValue(id).x, .0001f) + assertEquals(id, before.getValue(id).y - 150f / 1504, moved.getValue(id).y, .0001f) + } + assertEquals(4, view.artworkDpad().size) + val down = moved.getValue("legacy:down"); val r = moved.getValue("legacy:right") + val cx = (r.x + r.width) * 2400; val cy = (down.y + down.height) * 1504 + view.touch(MotionEvent.ACTION_DOWN, cx, cy) + view.touch(MotionEvent.ACTION_MOVE, cx + 80f, cy + 80f) + view.touch(MotionEvent.ACTION_UP, cx + 80f, cy + 80f) + val resized = changes.takeLast(4).associateBy { it.id } + assertEquals(arrows.toSet(), resized.keys) + assertTrue(resized.getValue("legacy:up").width > moved.getValue("legacy:up").width) + assertEquals(4, view.artworkDpad().size) + } + + @Test fun shrinkingTheDpadStopsBeforeAnyArrowIsSmallerThanASingleControlCanBe() { + val view = editor(overlay(), 2400, 1504) + val arrows = listOf("legacy:up", "legacy:right", "legacy:down", "legacy:left") + val pad = view.rendered().filter { it.id in arrows } + val changes = mutableListOf() + view.onBeginEdit = { shown, w, h -> view.aspect = w.toFloat() / h; view.elements = shown } + view.onChange = { changes += it; view.elements = view.elements.map { e -> it.firstOrNull { c -> c.id == e.id } ?: e } } + val right = pad.maxOf { it.x + it.width } * 2400; val bottom = pad.maxOf { it.y + it.height } * 1504 + val (ux, uy) = view.centre("legacy:up") + view.touch(MotionEvent.ACTION_DOWN, ux, uy) + view.touch(MotionEvent.ACTION_UP, ux, uy) + view.touch(MotionEvent.ACTION_DOWN, right, bottom) + view.touch(MotionEvent.ACTION_MOVE, 0f, 0f) + view.touch(MotionEvent.ACTION_UP, 0f, 0f) + val shrunk = changes.takeLast(4) + assertEquals(arrows.toSet(), shrunk.map { it.id }.toSet()) + shrunk.forEach { assertTrue(it.id, it.width >= .0299f && it.height >= .0299f) } + } + @Test fun aMouseSelectsDragsAndResizesLikeATouch() { val view = editor(overlay(), 2400, 1504) val a = view.rendered().first { it.id == "legacy:a" } @@ -236,3 +305,6 @@ internal fun InputSurfaceEditorView.place(w: Int, h: Int) { @Suppress("UNCHECKED_CAST") internal fun InputSurfaceEditorView.rendered() = javaClass.getDeclaredField("visibleElements").also { it.isAccessible = true }.get(this) as List + +internal fun InputSurfaceEditorView.artworkDpad() = javaClass.getDeclaredField("preview").also { it.isAccessible = true }.get(this)!!.let { preview -> + preview.javaClass.getDeclaredField("artworkDpad").also { it.isAccessible = true }.get(preview) as List<*> } From d6496b2f963ba5203a5fa03f3163ef263b0206c2 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Sat, 21 Nov 2026 23:47:58 -0500 Subject: [PATCH 023/141] feat(addons): install the CurseForge app and update addons per game (#2986) * feat(addons): install the CurseForge app and update addons per game The Addons tab installs the official CurseForge Linux app from its own update feed, checks it against the feed's SHA-512, shows its version, offers updates and removes it with the components delete button. Installed addons show their .toc version and are checked against WoWInterface by X-WoWI-ID or the recorded source of addons installed from the Download window; Update replaces them in place. The CurseForge web search chip is replaced by the app. * fix(addons): address review on update ordering, flavor filter, origins lock and failed checks * fix(addons): compact scrollable addon browser with list rows * fix(addons): compare release times as instants and replace the sources file atomically * fix(addons): open the addon browser at the top of the list * Keep the addon browser's search focus and installed version in sync * Track the search field's own focus in the addon browser * Key the installed addon version by install target * Install rar and 7z addon archives --- README.md | 2 +- .../droiddeck/launcher/FrontEndActivity.kt | 4 +- .../launcher/runtime/CurseForgeApp.kt | 10 + .../droiddeck/launcher/runtime/UserApps.kt | 68 +++++- .../launcher/runtime/WowAddonCatalog.kt | 39 +++- .../droiddeck/launcher/runtime/WowAddons.kt | 174 +++++++++++++--- .../launcher/stores/StoreArchiveUnpacker.kt | 65 ++++-- .../com/droiddeck/launcher/ui/AddAppDialog.kt | 2 + .../com/droiddeck/launcher/ui/AddonBrowser.kt | 197 +++++++++++++----- .../droiddeck/launcher/ui/ComponentsPage.kt | 28 +-- .../droiddeck/launcher/ui/FrontEndContent.kt | 8 +- .../com/droiddeck/launcher/ui/GameDetail.kt | 89 +++++++- .../launcher/runtime/UserAppsFeedTest.kt | 67 ++++++ .../launcher/runtime/WowAddonCatalogTest.kt | 41 +++- .../launcher/runtime/WowAddonsArchiveTest.kt | 78 +++++++ .../launcher/runtime/WowAddonsTest.kt | 46 ++++ 16 files changed, 765 insertions(+), 153 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/runtime/UserAppsFeedTest.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsArchiveTest.kt diff --git a/README.md b/README.md index 7154309b06..b6f80f6220 100644 --- a/README.md +++ b/README.md @@ -99,7 +99,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V - Battle.net installs drive Blizzard's Agent the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) does, with requests from [wowdev.wiki](https://wowdev.wiki/Agent). Read without taking code: [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader. - The Rockstar launcher service looks for launcher pipe names in the executables beside the game, since [CitizenFX](https://github.com/citizenfx/fivem)'s `ros-patches-five` shows GTA V opening `GTAVLauncher_Pipe` and [@pingod](https://github.com/pingod)'s [rdr2-linux-launcher](https://github.com/pingod/rdr2-linux-launcher) notes that Rockstar's protected executables resolve such strings only at run time. Read without taking code. - World of Warcraft addon imports replace an addon's folder from a temporary copy, as [WowUp](https://github.com/WowUp/WowUp) does, and read flavour folders the way [WoWDeck](https://github.com/sigboe/wowdeck) does. No code from either is used. -- The World of Warcraft addon Download window searches [WoWInterface](https://www.wowinterface.com) through its MMOUI API. [CurseForge](https://www.curseforge.com/wow) opens in the user's browser, with no API and no key. +- The World of Warcraft addon Download window searches [WoWInterface](https://www.wowinterface.com) through its MMOUI API. Installed addons show their `.toc` version and `X-WoWI-ID`, and are checked against that list for updates, as [WowUp](https://github.com/WowUp/WowUp) does. The Addons tab installs the official [CurseForge](https://www.curseforge.com/download/app) Linux app from CurseForge's own update feed (downloaded at install time and checked against its SHA-512, not included), which keeps its own sign-in. - The Xbox store runs [@domsvoboda](https://github.com/domsvoboda)'s [nexus-backend](https://github.com/domsvoboda/nexus-backend) 0.2.15 (GPL-3.0, a fork of [Xodus](https://github.com/xodus-gaming/xodus)), and Xbox games load the Windows modules of his [nexus-runtime](https://github.com/domsvoboda/nexus-runtime) (LGPL-2.1-or-later), including the C++ [nexus-xgameruntime](https://github.com/domsvoboda/nexus-xgameruntime) and `wintypes.dll`. Content licensing sends delegation-compact device tickets in the licensing wire form, as nexus-backend's Store license path (commit `27c335e`) does. Minecraft's GameInput setup was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT). - The Xbox Cloud Gaming player uses the WebRTC client of [@unknownskl](https://github.com/unknownskl)'s [Greenlight](https://github.com/unknownskl/greenlight) (MIT), and its offer tweaks and sharpening follow [@redphx](https://github.com/redphx)'s [Better xCloud](https://github.com/redphx/better-xcloud) (MIT). See `tools/xcloud-player/NOTICE.md`. - The itch.io butler pack ships butler's `7z.so`, itch.io's build of [7-Zip](https://www.7-zip.org) by Igor Pavlov (LGPL-2.1, unRAR restriction on RAR code), unmodified. Other archives use Apache Commons Compress and the runtime's bsdtar (libarchive). diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index 99e164d108..ac008894b8 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -530,7 +530,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet saveAction(getString(R.string.main_addons_importing, name)) { if (SessionState.running) return@saveAction getString(R.string.main_addons_close_session) val imported = try { - com.droiddeck.launcher.runtime.WowAddons.import(zip, target) + com.droiddeck.launcher.runtime.WowAddons.import(zip, target, context = this@FrontEndActivity) } catch (_: com.droiddeck.launcher.runtime.WowAddons.TooLarge) { return@saveAction getString(R.string.main_addons_too_large, zip.name) } @@ -539,7 +539,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } } val downloads = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).path - pickSaveZip.launch(InAppFilePicker.buildIntent(this, listOf("zip"), getString(R.string.main_addons_pick_zip, name), downloads)) + pickSaveZip.launch(InAppFilePicker.buildIntent(this, listOf("zip", "rar", "7z"), getString(R.string.main_addons_pick_zip, name), downloads)) } private fun exportSaves(name: String, layout: GameSaves.Layout, game: () -> GameSaves.Game) { diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt b/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt new file mode 100644 index 0000000000..1a40e6ead2 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt @@ -0,0 +1,10 @@ +package com.droiddeck.launcher.runtime + +object CurseForgeApp { + const val NAME = "CurseForge" + const val FEED = "https://curseforge.overwolf.com/electron/linux/latest-linux.yml" + + fun find(apps: List): UserApps.App? = apps.firstOrNull { it.feed == FEED } + + fun request(): UserApps.Request = UserApps.Request(UserApps.Source.Feed(FEED), NAME, null) +} diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/UserApps.kt b/app/src/main/java/com/droiddeck/launcher/runtime/UserApps.kt index cd16d03b42..efc460ee04 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/UserApps.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/UserApps.kt @@ -36,6 +36,7 @@ object UserApps { private const val GITHUB_TAG = "github-tag" private const val GITHUB_PUBLISHED = "github-published" private const val GITHUB_ASSET = "github-asset" + private const val FEED = "update-feed" enum class Kind { SCRIPT, APPIMAGE, FLATPAK } @@ -43,10 +44,15 @@ object UserApps { val key: String, val kind: Kind, val name: String, val icon: Any?, val detail: String?, val program: String, val args: List, val copied: Boolean = false, val repo: String? = null, val version: String? = null, - val fex: String = LinuxFex.AUTO, val arch: String? = null, - ) + val fex: String = LinuxFex.AUTO, val arch: String? = null, val feed: String? = null, + ) { + val updatable get() = repo != null || feed != null + } - class Release(val tag: String, val published: String, val asset: String, val url: String, val sha256: String? = null) + class Release( + val tag: String, val published: String, val asset: String, val url: String, + val sha256: String? = null, val sha512: String? = null, + ) sealed class UpdateCheck { class Current(val tag: String) : UpdateCheck() @@ -58,6 +64,7 @@ object UserApps { class Script(val file: File) : Source() class AppImage(val file: File) : Source() class GitHub(val repo: String, val asset: String? = null) : Source() + class Feed(val url: String) : Source() class Flatpak(val id: String) : Source() class FlatpakBundle(val file: File) : Source() } @@ -91,6 +98,7 @@ object UserApps { "appimage:${item.id}", Kind.APPIMAGE, item.name, item.icon, item.comment, AppImageManager.LAUNCHER, listOf(item.guestDir), repo = FileUtils.readString(File(dir, GITHUB_REPO))?.trim(), version = FileUtils.readString(File(dir, GITHUB_TAG))?.trim(), fex = LinuxFex.mode(dir), arch = FileUtils.readString(File(dir, "arch"))?.trim()?.takeIf { it.isNotEmpty() }, + feed = FileUtils.readString(File(dir, FEED))?.trim()?.takeIf { it.isNotEmpty() }, ) } val flatpaks = FlatpakManager.installedApps(context).map { app -> @@ -115,6 +123,7 @@ object UserApps { is Source.Script -> addScript(context, s.file, name, icon, request.meta, onProgress) is Source.AppImage -> AppImageManager.import(context, s.file, name, icon, request.meta) { onProgress(it, -1) } is Source.GitHub -> addFromGitHub(context, s.repo, s.asset, name, icon, onProgress) + is Source.Feed -> addFromFeed(context, s.url, name, icon, onProgress) is Source.Flatpak -> addFlatpak(context, s.id, name, icon, onProgress) is Source.FlatpakBundle -> addFlatpakBundle(context, s.file, name, icon, onProgress) } @@ -346,11 +355,15 @@ object UserApps { } private fun withDownload(context: Context, release: Release, onProgress: (String, Int) -> Unit, use: (File) -> String?): String? { - val download = File(context.cacheDir, "github-${release.asset}") + val download = File(File(context.cacheDir, "user-apps").apply { mkdirs() }, release.asset) try { val label = context.getString(R.string.user_apps_downloading, release.asset) val ok = Downloader.downloadFile(release.url, download, false, release.sha256) { f -> onProgress(label, if (f < 0) -1 else Math.round(f * 100f)) } - return if (ok) use(download) else context.getString(R.string.user_apps_download_failed) + if (!ok) return context.getString(R.string.user_apps_download_failed) + if (release.sha512 != null && !Hashes.sha512(download).equals(release.sha512, ignoreCase = true)) { + return context.getString(R.string.selfinst_checksum_mismatch) + } + return use(download) } finally { download.delete() } @@ -392,20 +405,57 @@ object UserApps { return urls + listOfNotNull(avatar) } + internal fun parseFeed(feed: String, body: String): Release? { + val top = body.lineSequence().filter { it.isNotEmpty() && !it[0].isWhitespace() && ':' in it } + .associate { it.substringBefore(':').trim() to it.substringAfter(':').trim().trim('\'', '"') } + val version = top["version"]?.takeIf { it.isNotEmpty() } ?: return null + val path = top["path"]?.takeIf { it.endsWith(".AppImage", ignoreCase = true) && '/' !in it && ".." !in it } ?: return null + val sha512 = top["sha512"]?.let { runCatching { java.util.Base64.getDecoder().decode(it) }.getOrNull() } + ?.takeIf { it.size == 64 }?.joinToString("") { "%02x".format(it) } ?: return null + val base = feed.substringBeforeLast('/', "").takeIf { it.startsWith("https://") } ?: return null + return Release(version, top["releaseDate"].orEmpty(), path, "$base/$path", sha512 = sha512) + } + + private fun feedRelease(context: Context, feed: String): Release? = + Downloader.downloadString(feed)?.let { parseFeed(feed, it) } + + private fun feedMeta(feed: String, release: Release) = + mapOf(FEED to feed, GITHUB_TAG to release.tag, GITHUB_PUBLISHED to release.published, GITHUB_ASSET to release.asset) + + private fun addFromFeed(context: Context, feed: String, name: String?, icon: File?, onProgress: (String, Int) -> Unit): String? { + onProgress(context.getString(R.string.user_apps_github_checking, name ?: feed), -1) + val release = feedRelease(context, feed) ?: return context.getString(R.string.user_apps_update_failed) + return withDownload(context, release, onProgress) { file -> + AppImageManager.import(context, file, name ?: release.asset.substringBefore('-'), icon, feedMeta(feed, release)) { onProgress(it, -1) } + } + } + + internal fun isNewer(release: Release, published: String, installed: String?): Boolean = + if (published.isNotEmpty() && release.published.isNotEmpty()) { + val feed = runCatching { java.time.Instant.parse(release.published) }.getOrNull() + val have = runCatching { java.time.Instant.parse(published) }.getOrNull() + if (feed != null && have != null) feed > have else release.published > published + } else release.tag != installed + fun checkUpdate(context: Context, app: App): UpdateCheck { + app.feed?.let { feed -> + val release = feedRelease(context, feed) ?: return UpdateCheck.Failed(context.getString(R.string.user_apps_update_failed)) + val published = FileUtils.readString(File(AppImageManager.dir(context, app.key.substringAfter(':')), GITHUB_PUBLISHED))?.trim().orEmpty() + return if (isNewer(release, published, app.version)) UpdateCheck.Available(release) else UpdateCheck.Current(app.version ?: release.tag) + } val repo = app.repo ?: return UpdateCheck.Failed(context.getString(R.string.user_apps_update_failed)) val dir = AppImageManager.dir(context, app.key.substringAfter(':')) val (release, problem) = latestRelease(context, repo, FileUtils.readString(File(dir, GITHUB_ASSET))?.trim()?.takeIf { it.isNotEmpty() }) if (release == null) return UpdateCheck.Failed(problem ?: context.getString(R.string.user_apps_update_failed)) val published = FileUtils.readString(File(dir, GITHUB_PUBLISHED))?.trim().orEmpty() - val newer = if (published.isNotEmpty() && release.published.isNotEmpty()) release.published > published else release.tag != app.version - return if (newer) UpdateCheck.Available(release) else UpdateCheck.Current(app.version ?: release.tag) + return if (isNewer(release, published, app.version)) UpdateCheck.Available(release) else UpdateCheck.Current(app.version ?: release.tag) } fun update(context: Context, app: App, release: Release, onProgress: (String, Int) -> Unit): String? { - val repo = app.repo ?: return context.getString(R.string.user_apps_update_failed) + val meta = app.feed?.let { feedMeta(it, release) } + ?: app.repo?.let { githubMeta(it, release) } ?: return context.getString(R.string.user_apps_update_failed) return withDownload(context, release, onProgress) { file -> - AppImageManager.replace(context, app.key.substringAfter(':'), file, githubMeta(repo, release)) { onProgress(it, -1) } + AppImageManager.replace(context, app.key.substringAfter(':'), file, meta) { onProgress(it, -1) } } } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddonCatalog.kt b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddonCatalog.kt index 63c1436f14..203e7aed5b 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddonCatalog.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddonCatalog.kt @@ -38,7 +38,6 @@ object WowAddonCatalog { internal class Cat(val id: String, val name: String, val parents: List) private const val WOWI = "https://api.mmoui.com/v3/game/WOW/" - private const val CURSEFORGE = "https://www.curseforge.com/wow/search?class=addons" private const val WOWI_FILES = "wowi-filelist.json" internal const val FRESH_MS = 6L * 60 * 60 * 1000 @@ -209,10 +208,12 @@ object WowAddonCatalog { fun categories(context: Context): List = wowiCategories(context).map { Category(it.id, it.name) } - internal fun parseWowiDetails(json: String): Pair? { + internal class Details(val url: String, val md5: String?, val version: String?) + + internal fun parseWowiDetails(json: String): Details? { val o = JSONArray(json).optJSONObject(0) ?: return null val url = o.optString("UIDownload").ifEmpty { return null } - return url to o.optString("UIMD5").ifEmpty { null } + return Details(url, o.optString("UIMD5").ifEmpty { null }, o.optString("UIVersion").trim().ifEmpty { null }) } internal fun isHttps(url: String) = url.startsWith("https://", ignoreCase = true) @@ -220,10 +221,11 @@ object WowAddonCatalog { internal fun md5Matches(file: File, expected: String?): Boolean = expected.isNullOrBlank() || Hashes.md5(file).equals(expected.trim(), ignoreCase = true) - fun download(context: Context, addon: Addon, dest: File, progress: (Int) -> Unit): File { + fun download(context: Context, addon: Addon, dest: File, progress: (Int) -> Unit): String? { val body = StoreNet.get(WOWI + "filedetails/${URLEncoder.encode(addon.id, "UTF-8")}.json", timeoutMs = 30_000) ?: throw unreachable(context) - val (url, md5) = parseWowiDetails(body) ?: throw IOException(context.getString(R.string.addons_no_file)) + val details = parseWowiDetails(body) ?: throw IOException(context.getString(R.string.addons_no_file)) + val url = details.url if (!isHttps(url)) throw IOException(context.getString(R.string.addons_no_file)) dest.parentFile?.mkdirs() dest.delete() @@ -232,14 +234,33 @@ object WowAddonCatalog { dest.delete() throw unreachable(context) } - if (!md5Matches(dest, md5)) { + if (!md5Matches(dest, details.md5)) { dest.delete() throw IOException(context.getString(R.string.selfinst_checksum_mismatch)) } progress(100) - return dest + return details.version } - internal fun curseForgeUrl(text: String): String = - text.trim().let { if (it.isEmpty()) CURSEFORGE else CURSEFORGE + "&search=" + URLEncoder.encode(it, "UTF-8") } + 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, installed: List): Map { + val byId = entries.associateBy { it.addon.id } + val seen = HashSet() + return installed.mapNotNull { item -> + 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 (sameVersion(version, latest.summary) || !seen.add(id)) null else item.name to latest + }.toMap() + } + + fun updates(context: Context, installed: List, target: WowAddons.Target): Map { + if (installed.none { it.wowiId != null }) return emptyMap() + val family = client(target).family + return runCatching { findUpdates(wowiEntries(context).filter { flavorMatches(it.flavors, family) }, installed) }.getOrDefault(emptyMap()) + } } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt index 60cfbf37c3..0763723d6a 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt @@ -2,15 +2,25 @@ package com.droiddeck.launcher.runtime import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf +import android.content.Context import androidx.compose.runtime.setValue +import com.droiddeck.launcher.R import com.droiddeck.launcher.frontend.Library import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoreArchiveUnpacker import com.droiddeck.launcher.stores.StoreInstalls +import com.droiddeck.launcher.stores.itch.ItchArchives import org.apache.commons.compress.archivers.zip.ZipFile import java.io.File import java.io.IOException +import java.io.InputStream +import java.nio.file.FileVisitResult import java.nio.file.Files import java.nio.file.LinkOption +import java.nio.file.Path +import java.nio.file.SimpleFileVisitor +import java.nio.file.attribute.BasicFileAttributes +import java.util.concurrent.atomic.AtomicBoolean object WowAddons { var imports by mutableIntStateOf(0) @@ -22,6 +32,12 @@ object WowAddons { class Addon(val name: String, val root: String) + 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" + internal const val MAX_EXPANDED_BYTES = 4L * 1024 * 1024 * 1024 private val SUFFIX = Regex("[-_](standard|mainline|classic|vanilla|tbc|bcc|wrath|wotlkc|cata|mists|forever)$", RegexOption.IGNORE_CASE) @@ -45,53 +61,149 @@ object WowAddons { target.addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") } .map { it.name }.sortedBy { it.lowercase() } + fun details(target: Target): List { + 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["Version"], origin?.id ?: toc["X-WoWI-ID"]) + } + } + + internal fun tocFields(text: String): Map { + val out = LinkedHashMap() + for (raw in text.lineSequence()) { + val line = raw.trim().removePrefix("\uFEFF") + if (!line.startsWith("##") || ':' !in line) continue + val key = line.removePrefix("##").substringBefore(':').trim() + val value = line.substringAfter(':').trim() + if (key.isNotEmpty() && value.isNotEmpty() && '@' !in value) out.putIfAbsent(key, value) + } + return out + } + + private fun toc(folder: File): Map { + 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 = text.lineSequence().mapNotNull { line -> + val parts = line.split('\t') + if (parts.size != 3 || parts.any { it.isBlank() }) null else parts[0] to Origin(parts[1], parts[2]) + }.toMap() + + internal fun formatOrigins(origins: Map): String = + origins.entries.sortedBy { it.key.lowercase() }.joinToString("") { (name, o) -> "$name\t${o.id}\t${o.version.replace(Regex("\\s+"), " ")}\n" } + + private fun originsFile(target: Target) = File(target.addOns, ORIGINS) + + private fun origins(target: Target): Map = + runCatching { parseOrigins(originsFile(target).readText()) }.getOrDefault(emptyMap()) + + private val originsLock = Any() + + private fun keepOrigins(target: Target, names: List, origin: Origin?) = synchronized(originsLock) { + val current = origins(target) + val next = current - names.toSet() + (origin?.let { o -> names.associateWith { o } } ?: emptyMap()) + if (next != current) { + val file = originsFile(target) + if (next.isEmpty()) file.delete() else { + val temp = File(target.addOns, "$ORIGINS.tmp") + temp.writeText(formatOrigins(next)) + if (!temp.renameTo(file)) { + temp.delete() + throw IOException("Cannot save $ORIGINS") + } + } + } + } + fun delete(target: Target, name: String) { val folder = target.addOns.listFiles()?.firstOrNull { it.name == name && !it.name.startsWith(".") } ?: throw IOException("Cannot find $name") StoreInstalls.deleteTree(folder) if (Files.exists(folder.toPath(), LinkOption.NOFOLLOW_LINKS)) throw IOException("Cannot delete $name") + runCatching { keepOrigins(target, listOf(name), null) } imports++ } - fun import(zipFile: File, target: Target): List { + fun import(archive: File, target: Target, origin: Origin? = null, context: Context? = null): List { + if (context == null || ItchArchives.kind(archive, archive.name) == "zip") return importZip(archive, target, origin) + val work = File(File(context.cacheDir, "wowaddons"), "unpack-${System.nanoTime()}") + try { + if (!work.mkdirs()) throw IOException("Cannot create ${work.path}") + val unpacker = StoreArchiveUnpacker(context, AtomicBoolean(), "Addons", R.string.stores_itch_archive, R.string.stores_itch_extract_failed, "addon-unpack") + unpacker.work = work + unpacker.limit = MAX_EXPANDED_BYTES + try { + unpacker.unpack(archive, archive.name, { _, _ -> }, {}) + } catch (_: StoreArchiveUnpacker.TooLarge) { + throw TooLarge() + } + return importFolder(work, target, origin) + } finally { + StoreInstalls.deleteTree(work) + } + } + + private class Entry(val path: String, val open: () -> InputStream) + + private fun importZip(zipFile: File, target: Target, origin: Origin?): List = ZipFile.builder().setFile(zipFile).get().use { zip -> val all = zip.entries.toList() if (all.any { it.isUnixSymlink }) return emptyList() - val entries = all.filter { clean(it.name) != null } - val addons = addons(entries.filter { !it.isDirectory }.mapNotNull { clean(it.name) }) - if (addons.isEmpty()) return emptyList() - val addOns = target.addOns - if (!addOns.isDirectory && !addOns.mkdirs()) throw IOException("Cannot create ${addOns.path}") - val stage = File(addOns.parentFile, ".addon-import-${System.nanoTime()}") - try { - val fresh = File(stage, "new") - val buffer = ByteArray(64 * 1024) - var written = 0L - for (entry in entries) { - if (entry.isDirectory) continue - val path = clean(entry.name) ?: continue - val addon = addons.firstOrNull { path.startsWith(it.root) } ?: continue - val out = inside(fresh, addon.name + "/" + path.removePrefix(addon.root)) ?: continue - out.parentFile?.mkdirs() - zip.getInputStream(entry).use { input -> - out.outputStream().use { output -> - while (true) { - val read = input.read(buffer) - if (read < 0) break - written += read - if (written > MAX_EXPANDED_BYTES) throw TooLarge() - output.write(buffer, 0, read) - } + importEntries(all.filter { !it.isDirectory }.mapNotNull { entry -> clean(entry.name)?.let { Entry(it) { zip.getInputStream(entry) } } }, target, origin) + } + + internal fun importFolder(folder: File, target: Target, origin: Origin?): List { + val entries = ArrayList() + var links = false + Files.walkFileTree(folder.toPath(), object : SimpleFileVisitor() { + override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult { + if (!attrs.isRegularFile) links = true + else clean(folder.toPath().relativize(file).joinToString("/"))?.let { entries.add(Entry(it) { Files.newInputStream(file, LinkOption.NOFOLLOW_LINKS) }) } + return if (links) FileVisitResult.TERMINATE else FileVisitResult.CONTINUE + } + }) + return if (links) emptyList() else importEntries(entries, target, origin) + } + + private fun importEntries(entries: List, target: Target, origin: Origin?): List { + val addons = addons(entries.map { it.path }) + if (addons.isEmpty()) return emptyList() + val addOns = target.addOns + if (!addOns.isDirectory && !addOns.mkdirs()) throw IOException("Cannot create ${addOns.path}") + val stage = File(addOns.parentFile, ".addon-import-${System.nanoTime()}") + try { + val fresh = File(stage, "new") + val buffer = ByteArray(64 * 1024) + var written = 0L + for (entry in entries) { + val addon = addons.firstOrNull { entry.path.startsWith(it.root) } ?: continue + val out = inside(fresh, addon.name + "/" + entry.path.removePrefix(addon.root)) ?: continue + out.parentFile?.mkdirs() + entry.open().use { input -> + out.outputStream().use { output -> + while (true) { + val read = input.read(buffer) + if (read < 0) break + written += read + if (written > MAX_EXPANDED_BYTES) throw TooLarge() + output.write(buffer, 0, read) } } } - swap(addons.map { File(fresh, it.name) to it.name }, addOns, File(stage, "old").apply { mkdirs() }) - } finally { - StoreInstalls.deleteTree(stage) } - imports++ - return addons.map { it.name } + swap(addons.map { File(fresh, it.name) to it.name }, addOns, File(stage, "old").apply { mkdirs() }) + } finally { + StoreInstalls.deleteTree(stage) } + runCatching { keepOrigins(target, addons.map { it.name }, origin) } + imports++ + return addons.map { it.name } } internal fun addons(files: List): List { diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreArchiveUnpacker.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreArchiveUnpacker.kt index ef355cc038..a99991996e 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreArchiveUnpacker.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreArchiveUnpacker.kt @@ -28,20 +28,26 @@ internal class StoreArchiveUnpacker( private val logName: String, ) { var work: File = File("") + var limit = Long.MAX_VALUE - fun unpack(archive: File, filename: String, handle: DownloadQueue.JobHandle) { + class TooLarge : java.io.IOException() + + fun unpack(archive: File, filename: String, handle: DownloadQueue.JobHandle) = + unpack(archive, filename, { done, total -> handle.stageProgress(done, total) }, handle::log) + + fun unpack(archive: File, filename: String, progress: (Long, Long) -> Unit, log: (String) -> Unit) { when (val kind = ItchArchives.kind(archive, filename)) { - "zip" -> unzip(archive, handle) + "zip" -> unzip(archive, progress, log) "7z" -> try { - sevenZip(archive, handle) + sevenZip(archive, progress, log) } catch (e: MemoryLimitException) { - handle.log("$label: ${archive.name} needs more memory than the app has, unpacking it in the runtime") - unrar(archive, handle, kind) + log("$label: ${archive.name} needs more memory than the app has, unpacking it in the runtime") + unrar(archive, progress, log, kind) } - "rar" -> unrar(archive, handle, kind) + "rar" -> unrar(archive, progress, log, kind) "exe" -> copy(archive, File(work, filename.ifBlank { "game.exe" })) - "tar" -> untar(archive, null, handle) - "gz", "bz2", "xz" -> untar(archive, kind, handle) ?: single(archive, kind, handle) + "tar" -> untar(archive, null, progress, log) + "gz", "bz2", "xz" -> untar(archive, kind, progress, log) ?: single(archive, kind, progress, log) else -> copy(archive, File(work, filename.ifBlank { "game" })) } } @@ -53,7 +59,7 @@ internal class StoreArchiveUnpacker( return if (path == root || path.startsWith(root + File.separator)) file else null } - private fun unrar(archive: File, handle: DownloadQueue.JobHandle, kind: String) { + private fun unrar(archive: File, progress: (Long, Long) -> Unit, log: (String) -> Unit, kind: String) { if (!LinuxRuntime.isInstalled(app)) throw IllegalStateException(app.getString(unsupported, kind)) val binds = if (listOf(app.filesDir, app.cacheDir).any { work.absolutePath.startsWith(it.absolutePath + "/") }) null else listOf(work.absolutePath) @@ -62,23 +68,28 @@ internal class StoreArchiveUnpacker( if (!line.startsWith("proot ")) onLine(line) } var entries = 0L - bsdtar(listOf("-tf", archive.absolutePath)) { entries++ } + var size = 0L + bsdtar(listOf("-tvf", archive.absolutePath)) { line -> + entries++ + size += LISTED_SIZE.find(line)?.groupValues?.get(1)?.toLongOrNull() ?: 0L + } + if (size > limit) throw TooLarge() var done = 0L val tail = ArrayDeque() val code = bsdtar(listOf("-xvf", archive.absolutePath, "-C", work.absolutePath)) { line -> - if (line.startsWith("x ")) handle.stageProgress(++done, entries) else { + if (line.startsWith("x ")) progress(++done, entries) else { if (tail.size == 5) tail.removeFirst() tail.addLast(line) } } if (cancelled.get()) return if (code != 0) { - handle.log("$label: bsdtar exited $code: ${tail.joinToString(" | ")}") + log("$label: bsdtar exited $code: ${tail.joinToString(" | ")}") throw IllegalStateException(app.getString(extractFailed, code)) } } - private fun sevenZip(archive: File, handle: DownloadQueue.JobHandle) { + private fun sevenZip(archive: File, progress: (Long, Long) -> Unit, log: (String) -> Unit) { val total = archive.length() var written = 0L val buffer = ByteArray(64 * 1024) @@ -90,7 +101,7 @@ internal class StoreArchiveUnpacker( val entry = seven.nextEntry ?: break val file = target(entry.name) if (file == null) { - handle.log("$label: skipped an entry outside the game folder") + log("$label: skipped an entry outside the game folder") continue } if (entry.isDirectory) { @@ -105,7 +116,8 @@ internal class StoreArchiveUnpacker( if (read < 0) break out.write(buffer, 0, read) written += read - handle.stageProgress(written, total) + if (written > limit) throw TooLarge() + progress(written, total) } } } @@ -113,7 +125,7 @@ internal class StoreArchiveUnpacker( } } - private fun untar(archive: File, codec: String?, handle: DownloadQueue.JobHandle): Unit? { + private fun untar(archive: File, codec: String?, progress: (Long, Long) -> Unit, log: (String) -> Unit): Unit? { val total = archive.length() var written = 0L var entries = 0 @@ -134,7 +146,7 @@ internal class StoreArchiveUnpacker( entries++ val file = target(entry.name) if (file == null) { - handle.log("$label: skipped an entry outside the game folder") + log("$label: skipped an entry outside the game folder") continue } if (entry.isDirectory) { @@ -149,7 +161,8 @@ internal class StoreArchiveUnpacker( if (read < 0) break out.write(buffer, 0, read) written += read - handle.stageProgress(written, total) + if (written > limit) throw TooLarge() + progress(written, total) } } } @@ -163,7 +176,7 @@ internal class StoreArchiveUnpacker( return null } - private fun single(archive: File, codec: String, handle: DownloadQueue.JobHandle) { + private fun single(archive: File, codec: String, progress: (Long, Long) -> Unit, log: (String) -> Unit) { val name = archive.name.substringBeforeLast('.') val file = target(name.ifBlank { "game" }) ?: throw IllegalStateException("archive") file.parentFile?.mkdirs() @@ -184,7 +197,8 @@ internal class StoreArchiveUnpacker( if (read < 0) break out.write(buffer, 0, read) written += read - handle.stageProgress(written, total) + if (written > limit) throw TooLarge() + progress(written, total) } } } @@ -196,7 +210,7 @@ internal class StoreArchiveUnpacker( FileInputStream(source).use { input -> FileOutputStream(target).use { out -> input.copyTo(out, 128 * 1024) } } } - private fun unzip(archive: File, handle: DownloadQueue.JobHandle) { + private fun unzip(archive: File, progress: (Long, Long) -> Unit, log: (String) -> Unit) { val total = archive.length() var written = 0L val buffer = ByteArray(64 * 1024) @@ -205,7 +219,7 @@ internal class StoreArchiveUnpacker( if (cancelled.get()) return val target = target(entry.name) if (target == null) { - handle.log("$label: skipped an entry outside the game folder") + log("$label: skipped an entry outside the game folder") continue } if (entry.isDirectory) { @@ -221,11 +235,16 @@ internal class StoreArchiveUnpacker( if (read < 0) break out.write(buffer, 0, read) written += read - handle.stageProgress(written, total) + if (written > limit) throw TooLarge() + progress(written, total) } } } } } } + + private companion object { + val LISTED_SIZE = Regex("""^\S+\s+\d+\s+\S+\s+\S+\s+(\d+)\s""") + } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt index 3acc241b17..f93395bb31 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt @@ -311,6 +311,7 @@ internal fun AppDialog( width: Dp? = null, fitContent: Boolean = false, back: (() -> Unit)? = null, scrollable: Boolean = true, + fillHeight: Boolean = false, scrollState: androidx.compose.foundation.ScrollState = rememberScrollState(), side: (@Composable () -> Unit)? = null, sideRoom: Dp = 0.dp, @@ -348,6 +349,7 @@ internal fun AppDialog( }, ) .heightIn(max = (LocalConfiguration.current.screenHeightDp - 24).dp) + .then(if (fillHeight) Modifier.fillMaxHeight() else Modifier) .shadow(24.dp, Shape16, ambientColor = Color.Black, spotColor = Color.Black) .clip(Shape16) .background(pal.surfaceVariant.copy(alpha = 0.97f)) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt index 89e84fe697..4987ad3bb4 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt @@ -1,28 +1,32 @@ package com.droiddeck.launcher.ui import android.content.Context -import android.content.Intent -import android.net.Uri import android.widget.Toast -import androidx.compose.foundation.LocalIndication -import androidx.compose.foundation.clickable -import androidx.compose.foundation.hoverable +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row 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.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.GridItemSpan +import androidx.compose.foundation.lazy.grid.LazyGridState import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Check -import androidx.compose.material3.Icon +import androidx.compose.foundation.lazy.grid.rememberLazyGridState +import androidx.compose.foundation.rememberScrollState import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme 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.LaunchedEffect import androidx.compose.runtime.getValue @@ -34,16 +38,29 @@ import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip -import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.draw.drawWithContent +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.geometry.CornerRadius +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +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.res.stringResource -import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp +import coil.compose.AsyncImage import com.droiddeck.launcher.R import com.droiddeck.launcher.runtime.WowAddonCatalog import com.droiddeck.launcher.runtime.WowAddons @@ -62,6 +79,10 @@ private class AddonResults { var more by mutableStateOf(false) } +private enum class AddonStatus { INSTALL, UPDATE, INSTALLED } + +private const val PAGES_AHEAD = 8 + @Composable internal fun AddonBrowserDialog(targets: List, initial: WowAddons.Target, onDismiss: () -> Unit) { val context = LocalContext.current.applicationContext @@ -74,10 +95,19 @@ internal fun AddonBrowserDialog(targets: List, initial: WowAdd var sort by remember { mutableStateOf(WowAddonCatalog.Sort.POPULAR) } val results = remember(text, category, sort, target) { AddonResults() } val installing = remember { mutableStateMapOf() } - val installed = remember { mutableStateMapOf() } + val installed = remember { mutableStateMapOf>() } val categories by produceState(emptyList()) { value = withContext(Dispatchers.IO) { runCatching { WowAddonCatalog.categories(context) }.getOrDefault(emptyList()) } } + val present by produceState(emptyMap(), target.addOns, WowAddons.imports) { + value = withContext(Dispatchers.IO) { WowAddons.details(target).mapNotNull { item -> item.wowiId?.let { it to item.version } }.toMap() } + } + fun status(addon: WowAddonCatalog.Addon): AddonStatus { + 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 if (have == null || latest.isBlank() || WowAddonCatalog.sameVersion(have, latest)) AddonStatus.INSTALLED else AddonStatus.UPDATE + } fun load(page: Int) { if (results.loading) return results.loading = true @@ -115,48 +145,93 @@ internal fun AddonBrowserDialog(targets: List, initial: WowAdd scope.launch { val message = withContext(Dispatchers.IO) { installAddon(context, addon, into) { pct -> scope.launch { if (key in installing) installing[key] = pct } } } installing.remove(key) - if (message.second) installed[key] = true + message.second?.let { installed[key] = addon.summary to it } Toast.makeText(context, message.first, Toast.LENGTH_LONG).show() } } val sourceName = stringResource(R.string.addons_source_wowi) - AppDialog(shown, close, "addonBrowser", wide = true, scrollable = false) { - DialogTitleRow(stringResource(R.string.addons_download), close) - ModeHeader(sourceName, text, { text = it }, stringResource(R.string.stores_search_catalog, sourceName)) { - BrowseChip(stringResource(R.string.addons_source_curse), false) { - runCatching { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(WowAddonCatalog.curseForgeUrl(text))).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } - } + val grid = rememberLazyGridState() + LaunchedEffect(results, grid) { + snapshotFlow { grid.layoutInfo.visibleItemsInfo.lastOrNull()?.index to grid.layoutInfo.totalItemsCount }.collect { (last, total) -> + if (last != null && results.more && results.failed == null && last >= total - PAGES_AHEAD) load(results.page + 1) } - ChipRow { + } + val firstAction = remember(results) { FocusRequester() } + val inputMode = LocalInputModeManager.current + var searching by remember { mutableStateOf(false) } + 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) { + val sortChip: @Composable () -> Unit = { BrowseDropdown(sortLabel(sort)) { first, done -> WowAddonCatalog.Sort.entries.forEachIndexed { index, option -> MenuItem(sortLabel(option), sort == option, focusRequester = if (index == 0) first else null) { sort = option; done() } } } + } + val categoryChip: @Composable () -> Unit = { 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() } } } + } + val flavorChip: @Composable () -> Unit = { if (targets.size > 1) BrowseDropdown(target.flavor) { first, done -> targets.forEachIndexed { index, option -> MenuItem(option.flavor, option.addOns == target.addOns, focusRequester = if (index == 0) first else null) { target = option; done() } } } } - val height = (LocalConfiguration.current.screenHeightDp * 0.62f).dp + val search: @Composable (Modifier) -> Unit = { modifier -> + AdbTextField( + value = text, onValueChange = { text = it }, label = "", keyboardType = KeyboardType.Text, imeAction = ImeAction.Search, + placeholder = stringResource(R.string.stores_search_catalog, sourceName), compact = true, showLabel = false, modifier = modifier, onFocusChange = { searching = it }, + ) + } + val closeButton: @Composable () -> Unit = { + SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = MaterialTheme.colorScheme.error, onClick = close) + } + BoxWithConstraints(Modifier.fillMaxWidth()) { + if (maxWidth >= 640.dp) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { + search(Modifier.weight(1f)) + sortChip() + categoryChip() + flavorChip() + closeButton() + } else Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { + search(Modifier.weight(1f)) + closeButton() + } + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier.horizontalScroll(rememberScrollState()), + ) { + sortChip() + categoryChip() + flavorChip() + } + } + } + val thumb = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f) LazyVerticalGrid( - GridCells.Adaptive(libraryTileWidth() + 40.dp), Modifier.fillMaxWidth().height(height), - horizontalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp), + GridCells.Adaptive(400.dp), Modifier.fillMaxWidth().weight(1f).scrollThumb(grid, thumb), state = grid, + contentPadding = PaddingValues(end = 8.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(6.dp), ) { items(results.items, key = { it.id }) { addon -> - AddonCard(addon, installing[installKey(addon, target)], installed[installKey(addon, target)] == true) { install(addon) } + val key = installKey(addon, target) + AddonRow(addon, status(addon), installing[key], if (addon.id == results.items.firstOrNull()?.id) Modifier.focusRequester(firstAction) else Modifier) { install(addon) } } - item(key = "tail", span = { GridItemSpan(maxLineSpan) }) { - Box(Modifier.fillMaxWidth().padding(vertical = 8.dp), contentAlignment = Alignment.Center) { + 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 -> BrowseChip(stringResource(R.string.stores_dl_retry), false) { load(if (results.items.isEmpty()) 0 else results.page + 1) } - results.more -> BrowseChip(stringResource(R.string.stores_itch_load_more), false) { load(results.page + 1) } + 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) } + } results.items.isEmpty() -> Text(stringResource(R.string.addons_none_found), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) } } @@ -166,29 +241,45 @@ internal fun AddonBrowserDialog(targets: List, initial: WowAdd } @Composable -private fun AddonCard(addon: WowAddonCatalog.Addon, progress: Int?, done: Boolean, onInstall: () -> Unit) { +private fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progress: Int?, action: Modifier, onInstall: () -> Unit) { + val colors = MaterialTheme.colorScheme val pal = LocalPalette.current - val src = remember { androidx.compose.foundation.interaction.MutableInteractionSource() } - val hot = rememberHot(src) - val shape = androidx.compose.foundation.shape.RoundedCornerShape(10.dp) - Column( - Modifier.fillMaxWidth().clip(shape).glideBorder(hot, shape, pal.signal, pal.line) - .hoverable(src) - .clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onInstall) - .controllerConfirm(onClick = onInstall), + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), + modifier = Modifier.fillMaxWidth().clip(Shape12).background(colors.surface.copy(alpha = 0.6f)).border(1.dp, pal.line, Shape12) + .padding(start = 8.dp, end = 8.dp, top = 6.dp, bottom = 6.dp), ) { - ArtCard(addon.name, addon.thumb, null, null, hot, capsule = false, chip = progress?.let { "$it%" }) { - if (done) Icon(Icons.Filled.Check, stringResource(R.string.stores_installed_chip), tint = pal.good, modifier = Modifier.height(11.dp)) - else Text(stringResource(if (progress != null) R.string.store_installing else R.string.store_install), fontSize = 10.sp, color = pal.signal, maxLines = 1) + Box(Modifier.size(44.dp).clip(Shape12).background(artBrush(hueOf(addon.name)))) { + if (addon.thumb != null) AsyncImage(model = addon.thumb, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize()) + } + Column(Modifier.weight(1f)) { + Text(addon.name, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text( + listOf(addon.author, addon.summary, formatCount(addon.downloads)).filter { it.isNotEmpty() }.joinToString(" · "), + fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, + ) + } + val size = Modifier.widthIn(min = 104.dp).then(action) + when { + 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) } - Text( - listOf(addon.author, formatCount(addon.downloads)).filter { it.isNotEmpty() }.joinToString(" · "), - fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, - modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp), - ) } } +private fun Modifier.scrollThumb(state: LazyGridState, color: Color): Modifier = drawWithContent { + drawContent() + val info = state.layoutInfo + val visible = info.visibleItemsInfo + if (visible.isEmpty() || visible.size >= info.totalItemsCount) return@drawWithContent + val total = info.totalItemsCount.toFloat() + val length = (size.height * visible.size / total).coerceAtLeast(24.dp.toPx()) + val top = (size.height - length) * (visible.first().index / (total - visible.size).coerceAtLeast(1f)).coerceIn(0f, 1f) + val width = 3.dp.toPx() + drawRoundRect(color, Offset(size.width - width, top), Size(width, length), CornerRadius(width / 2)) +} + @Composable private fun sortLabel(sort: WowAddonCatalog.Sort): String = stringResource( when (sort) { @@ -206,18 +297,18 @@ private fun formatCount(count: Long): String = when { else -> count.toString() } -private fun installAddon(context: Context, addon: WowAddonCatalog.Addon, target: WowAddons.Target, progress: (Int) -> Unit): Pair { +internal fun installAddon(context: Context, addon: WowAddonCatalog.Addon, target: WowAddons.Target, progress: (Int) -> Unit): Pair { val zip = File(File(context.cacheDir, "wowaddons"), "download-wowi-${addon.id.filter(Char::isLetterOrDigit)}-${java.util.UUID.randomUUID()}.zip") return try { - WowAddonCatalog.download(context, addon, zip, progress) - if (SessionState.running) return context.getString(R.string.main_addons_close_session) to false - val names = WowAddons.import(zip, target) - if (names.isEmpty()) context.getString(R.string.main_addons_none, addon.name) to false - else context.resources.getQuantityString(R.plurals.main_addons_imported, names.size, names.size, target.flavor) to true + val version = WowAddonCatalog.download(context, addon, zip, progress) ?: addon.summary + if (SessionState.running) return context.getString(R.string.main_addons_close_session) to null + val names = WowAddons.import(zip, target, WowAddons.Origin(addon.id, version).takeIf { version.isNotBlank() }, context) + if (names.isEmpty()) context.getString(R.string.main_addons_none, addon.name) to null + else context.resources.getQuantityString(R.plurals.main_addons_imported, names.size, names.size, target.flavor) to version } catch (_: WowAddons.TooLarge) { - context.getString(R.string.main_addons_too_large, addon.name) to false + context.getString(R.string.main_addons_too_large, addon.name) to null } catch (e: Exception) { - context.getString(R.string.stores_dl_failed_reason, e.message ?: e.javaClass.simpleName) to false + context.getString(R.string.stores_dl_failed_reason, e.message ?: e.javaClass.simpleName) to null } finally { zip.delete() } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt index 908f229e3a..0bdba211ad 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt @@ -1495,22 +1495,26 @@ private fun ChoiceLine( if (progress != null) ProgressBit(progress) } if (!removable) Spacer(Modifier.padding(end = 6.dp).size(44.dp)) - else { - val delSrc = remember { MutableInteractionSource() } - val delHot = rememberHot(delSrc) - Box( - contentAlignment = Alignment.Center, - modifier = Modifier.padding(end = 6.dp).size(44.dp).clip(ROW_SHAPE) - .background(if (delHot) colors.error.copy(alpha = 0.14f) else Color.Transparent) - .glideBorder(delHot, ROW_SHAPE, colors.error) - .hoverable(delSrc).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = delSrc, indication = null, onClick = onDelete) - .controllerConfirm(onClick = onDelete), - ) { Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.common_delete_named, name), tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(19.dp)) } - } + else DeleteButton(name, onDelete = onDelete) } Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line)) } +@Composable +internal fun DeleteButton(name: String, modifier: Modifier = Modifier, enabled: Boolean = true, onDelete: () -> Unit) { + val colors = MaterialTheme.colorScheme + val delSrc = remember { MutableInteractionSource() } + val delHot = rememberHot(delSrc) && enabled + Box( + contentAlignment = Alignment.Center, + modifier = modifier.padding(end = 6.dp).size(44.dp).clip(ROW_SHAPE) + .background(if (delHot) colors.error.copy(alpha = 0.14f) else Color.Transparent) + .glideBorder(delHot, ROW_SHAPE, colors.error) + .hoverable(delSrc).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = delSrc, indication = null, enabled = enabled, onClick = onDelete) + .controllerConfirm(enabled = enabled, onClick = onDelete), + ) { Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.common_delete_named, name), tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(19.dp)) } +} + @Composable private fun GetLine( name: String, detail: String, progress: Int?, enabled: Boolean, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt index adf55c4b1b..73782db2ed 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt @@ -477,7 +477,7 @@ private fun UserAppIcon(app: UserApps.App, size: Int) { } @Composable -private fun UserAppsProgress() { +internal fun UserAppsProgress() { val colors = MaterialTheme.colorScheme val working = UserAppsState.working Column(verticalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) { @@ -514,7 +514,9 @@ private fun UserAppPage(app: UserApps.App, s: FrontEndState, a: FrontEndActions, Column { Text(app.name, fontSize = if (narrow) 22.sp else 26.sp, fontWeight = FontWeight.Bold, color = colors.onBackground) Text( - (app.repo?.let { stringResource(R.string.user_apps_github_version, it, app.version.orEmpty()) } ?: stringResource(app.kind.label())) + + (app.repo?.let { stringResource(R.string.user_apps_github_version, it, app.version.orEmpty()) } + ?: app.version?.takeIf { app.feed != null }?.let { stringResource(R.string.user_apps_github_version, stringResource(app.kind.label()), it) } + ?: stringResource(app.kind.label())) + (if (app.arch == "x86_64" || app.arch == "i386") " · " + stringResource(R.string.app_fex_x86, app.arch) else ""), fontSize = 14.sp, color = colors.onSurfaceVariant, ) @@ -526,7 +528,7 @@ private fun UserAppPage(app: UserApps.App, s: FrontEndState, a: FrontEndActions, PrimaryButton(stringResource(R.string.user_apps_open, app.name), enabled = !s.busy, main = true) { a.onUserApp(app) } BusyChip(s) SecondaryButton(stringResource(R.string.user_apps_edit), enabled = UserAppsState.working == null) { editing = true } - if (app.repo != null) UpdateButton(app, s) + if (app.updatable) UpdateButton(app, s) RemoveAppButton(app, enabled = !s.busy && !s.sessionRunning && UserAppsState.working == null) { UserAppsState.remove(ctx, app); onSelect("desktop") } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt index 3b93f06527..ab54f3e2cb 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt @@ -42,6 +42,7 @@ import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Favorite import androidx.compose.material.icons.filled.FavoriteBorder import androidx.compose.material.icons.filled.PlayArrow +import androidx.compose.material.icons.outlined.Download import androidx.compose.material.icons.outlined.Delete import androidx.compose.material.icons.outlined.Edit import androidx.compose.material.icons.outlined.VideogameAsset @@ -54,6 +55,7 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.produceState import androidx.compose.runtime.remember @@ -94,7 +96,11 @@ import coil.compose.AsyncImage import com.droiddeck.launcher.R import com.droiddeck.launcher.frontend.GameRemoval import com.droiddeck.launcher.frontend.Library +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.store.UserAppsState import com.droiddeck.launcher.session.GameSaves import com.droiddeck.launcher.session.SessionState import com.droiddeck.launcher.stores.CatalogItem @@ -960,9 +966,14 @@ private fun AddonsTab(g: Library.SteamGame, targets: List, a: var browsing by remember(g.gameId) { mutableStateOf(null) } browsing?.let { AddonBrowserDialog(targets, it) { browsing = null } } Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) { + CurseForgeEntry(a) targets.forEach { target -> - val names by produceState(emptyList(), target.addOns, WowAddons.imports) { - value = withContext(Dispatchers.IO) { WowAddons.installed(target) } + val names by produceState(emptyList(), target.addOns, WowAddons.imports) { + value = withContext(Dispatchers.IO) { WowAddons.details(target) } + } + val context = LocalContext.current + val updates by produceState(emptyMap(), names) { + value = withContext(Dispatchers.IO) { WowAddonCatalog.updates(context, names, target) } } if (targets.size > 1) SectionLabel(target.flavor) MenuItem(stringResource(R.string.addons_download), checked = false) { browsing = target } @@ -974,17 +985,85 @@ private fun AddonsTab(g: Library.SteamGame, targets: List, a: target.addOns.mkdirs() a.onBrowseFiles(target.addOns) } - names.forEach { name -> AddonRow(name, target, a) } + names.forEach { item -> key(target.addOns, item.name) { AddonRow(item, updates[item.name], target, a) } } } } } @Composable -private fun AddonRow(name: String, target: WowAddons.Target, a: FrontEndActions) { +private fun CurseForgeEntry(a: FrontEndActions) { + val ctx = LocalContext.current + val name = stringResource(R.string.addons_source_curse) + LaunchedEffect(Unit) { UserAppsState.refresh(ctx) } + val app = CurseForgeApp.find(UserAppsState.items) + val idle = UserAppsState.working == null + if (app == null) { + MenuItem(stringResource(R.string.content_install_named, name), checked = false, enabled = idle && !SessionState.running) { + UserAppsState.add(ctx, CurseForgeApp.request(), name) + } + } else { + var asking by remember(app.key) { mutableStateOf(false) } + var checked by remember { mutableStateOf(null) } + val checkKey = app.key + "@" + app.version + LaunchedEffect(checkKey, UserAppsState.checking) { + if (UserAppsState.checking == null && checked != checkKey) { + checked = checkKey + UserAppsState.checkUpdate(ctx, app) + } + } + val update = (UserAppsState.updates[app.key] as? UserApps.UpdateCheck.Available)?.release + Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) { + MenuItem( + stringResource(R.string.user_apps_open, name), checked = false, enabled = idle, + detail = app.version, modifier = Modifier.weight(1f), + ) { a.onUserApp(app) } + DeleteButton(name, enabled = idle && !SessionState.running) { asking = true } + } + if (update != null) MenuItem(stringResource(R.string.user_apps_update_to, update.tag), checked = false, enabled = idle && !SessionState.running) { + UserAppsState.update(ctx, app, update) + } + (UserAppsState.updates[app.key] as? UserApps.UpdateCheck.Failed)?.let { failed -> + MenuItem(stringResource(R.string.user_apps_check_updates), checked = false, enabled = idle && UserAppsState.checking == null, detail = failed.message) { + UserAppsState.checkUpdate(ctx, app) + } + } + if (asking) ConfirmDialog( + title = stringResource(R.string.flathub_remove_title, name), + text = stringResource(R.string.flathub_remove_note), + confirm = stringResource(R.string.user_apps_remove), + onConfirm = { asking = false; UserAppsState.remove(ctx, app) }, + onDismiss = { asking = false }, + ) + } + if (UserAppsState.working == name || (UserAppsState.lastError?.startsWith(name) == true)) UserAppsProgress() +} + +@Composable +private fun AddonRow(item: WowAddons.Installed, update: WowAddonCatalog.Addon?, target: WowAddons.Target, a: FrontEndActions) { + val name = item.name var asking by remember(target.addOns, name) { mutableStateOf(false) } + var progress by remember(target.addOns, name) { mutableStateOf(null) } + val context = LocalContext.current + val scope = rememberCoroutineScope() val delete = stringResource(R.string.common_delete) + val colors = MaterialTheme.colorScheme Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(start = 16.dp, top = 2.dp, bottom = 2.dp)) { - Text(name, fontSize = 14.sp, color = MaterialTheme.colorScheme.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f)) + Column(Modifier.weight(1f)) { + Text(name, fontSize = 14.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + 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 (update != null) LocalPalette.current.signal else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, + ) + } + 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) { installAddon(context, update, target) { pct -> scope.launch { progress = pct } } } + progress = null + android.widget.Toast.makeText(context, message.first, android.widget.Toast.LENGTH_LONG).show() + } + } if (!SessionState.running) IconAction(Icons.Outlined.Delete, delete, "addon:delete:${target.flavor}:$name", danger = true) { asking = true } } if (asking) ConfirmDialog( diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/UserAppsFeedTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/UserAppsFeedTest.kt new file mode 100644 index 0000000000..e1c152b059 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/runtime/UserAppsFeedTest.kt @@ -0,0 +1,67 @@ +package com.droiddeck.launcher.runtime + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class UserAppsFeedTest { + private val feed = "https://example.com/apps/linux/latest-linux.yml" + private val sha = "ajcSve2Wq1CgocS5zWlmdfb0pI0C+JqNvbFx6Vm9j9/fW1Q/u2dnnNvNGmi0gulEXp7tnRkYCCc7rfwtjKcoNw==" + + private fun body(path: String = "App-1.2.0-7.AppImage", hash: String = sha) = """ + version: 1.2.0-7 + files: + - url: App-1.2.0-7.AppImage + sha512: $hash + size: 100 + - url: App_1.2.0-7_amd64.deb + sha512: other + path: $path + sha512: $hash + releaseDate: '2026-11-15T18:08:09.118Z' + """.trimIndent() + + @Test fun feedGivesTheAppImageRelease() { + val release = UserApps.parseFeed(feed, body())!! + assertEquals("1.2.0-7", release.tag) + assertEquals("App-1.2.0-7.AppImage", release.asset) + assertEquals("https://example.com/apps/linux/App-1.2.0-7.AppImage", release.url) + assertEquals("2026-11-15T18:08:09.118Z", release.published) + assertEquals(128, release.sha512!!.length) + assertEquals("6a3712bded96ab50a0a1c4b9cd696675f6f4a48d02f89a8dbdb171e959bd8fdfdf5b543fbb67679cdbcd1a68b482e9445e9eed9d191808273badfc2d8ca72837", release.sha512) + assertNull(release.sha256) + } + + @Test fun feedWithoutAnAppImageOrHashIsRefused() { + assertNull(UserApps.parseFeed(feed, body(path = "App_1.2.0-7_amd64.deb"))) + assertNull(UserApps.parseFeed(feed, body(path = "../App.AppImage"))) + assertNull(UserApps.parseFeed(feed, body(path = "sub/App.AppImage"))) + assertNull(UserApps.parseFeed(feed, body(hash = "c2hvcnQ="))) + assertNull(UserApps.parseFeed("http://example.com/latest-linux.yml", body())) + assertNull(UserApps.parseFeed(feed, "path: App.AppImage\n")) + } + + @Test fun curseForgeIsFoundByItsFeed() { + val other = UserApps.App("appimage:a", UserApps.Kind.APPIMAGE, "CurseForge", null, null, AppImageManager.LAUNCHER, emptyList()) + val official = UserApps.App("appimage:b", UserApps.Kind.APPIMAGE, "Mods", null, null, AppImageManager.LAUNCHER, emptyList(), feed = CurseForgeApp.FEED) + assertEquals("appimage:b", CurseForgeApp.find(listOf(other, official))?.key) + assertNull(CurseForgeApp.find(listOf(other))) + } + + @Test fun olderOrEqualFeedReleasesAreNotOffered() { + val release = UserApps.parseFeed(feed, body())!! + assertTrue(UserApps.isNewer(release, "2026-11-01T00:00:00.000Z", "1.0")) + assertFalse(UserApps.isNewer(release, "2099-01-01T00:00:00.000Z", "9.9")) + assertFalse(UserApps.isNewer(release, "", release.tag)) + assertTrue(UserApps.isNewer(release, "", "0.1")) + } + + @Test fun publicationTimesCompareAsInstantsWhateverTheirPrecision() { + val release = UserApps.parseFeed(feed, body())!! + assertTrue(UserApps.isNewer(release, "2026-11-15T18:08:09Z", "1.0")) + assertFalse(UserApps.isNewer(release, "2026-11-15T18:08:09.118000Z", "1.0")) + assertFalse(UserApps.isNewer(release, "2026-11-15T18:08:10Z", "1.0")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonCatalogTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonCatalogTest.kt index 43bb29bb48..451ec81bc3 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonCatalogTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonCatalogTest.kt @@ -150,8 +150,8 @@ us|1|aa|bb|cc||tpr/wow|h|s|t||1|12.1.0.65000|kk|wowf @Test fun wowiDetailsGiveUrlAndMd5() { val d = WowAddonCatalog.parseWowiDetails("""[{"UID":"1","UIMD5":"abc","UIDownload":"https://cdn.wowinterface.com/downloads/getfile.php?id=1"}]""") - assertEquals("https://cdn.wowinterface.com/downloads/getfile.php?id=1", d?.first) - assertEquals("abc", d?.second) + assertEquals("https://cdn.wowinterface.com/downloads/getfile.php?id=1", d?.url) + assertEquals("abc", d?.md5) assertNull(WowAddonCatalog.parseWowiDetails("""[{"UID":"1","UIDownload":""}]""")) assertNull(WowAddonCatalog.parseWowiDetails("[]")) } @@ -162,9 +162,40 @@ us|1|aa|bb|cc||tpr/wow|h|s|t||1|12.1.0.65000|kk|wowf assertTrue(WowAddonCatalog.isHttps("https://example.com/a.zip")) } - @Test fun curseForgeUrlAddsTheSearchText() { - assertEquals("https://www.curseforge.com/wow/search?class=addons", WowAddonCatalog.curseForgeUrl(" ")) - assertEquals("https://www.curseforge.com/wow/search?class=addons&search=deadly+boss+%26+mods", WowAddonCatalog.curseForgeUrl(" deadly boss & mods ")) + private fun entry(id: String, version: String) = + WowAddonCatalog.Entry(WowAddonCatalog.Addon(id, "Addon $id", "author", version, 0L, 0L, null), "1", null) + + @Test fun updatesComeFromTheInstalledSourceVersion() { + val entries = listOf(entry("10", "2.1.0"), entry("20", "v5"), entry("30", "")) + val installed = listOf( + WowAddons.Installed("Old", "2.0.9", "10"), + WowAddons.Installed("OldPart", "2.0.9", "10"), + WowAddons.Installed("Same", "5", "20"), + WowAddons.Installed("NoLatest", "1", "30"), + WowAddons.Installed("Unknown", "1", "99"), + WowAddons.Installed("Local", "1", null), + WowAddons.Installed("NoVersion", null, "10"), + ) + val updates = WowAddonCatalog.findUpdates(entries, installed) + assertEquals(setOf("Old"), updates.keys) + assertEquals("2.1.0", updates.getValue("Old").summary) + } + + @Test fun aCurrentRowDoesNotHideAnOutdatedRowWithTheSameSource() { + val installed = listOf(WowAddons.Installed("A", "2", "10"), WowAddons.Installed("B", "1", "10")) + assertEquals(setOf("B"), WowAddonCatalog.findUpdates(listOf(entry("10", "2")), installed).keys) + } + + @Test fun wowiDetailsCarryTheDownloadedVersion() { + val d = WowAddonCatalog.parseWowiDetails("""[{"UIDownload":"https://cdn.wowinterface.com/a.zip","UIVersion":" 2.0 "}]""") + assertEquals("2.0", d?.version) + assertNull(WowAddonCatalog.parseWowiDetails("""[{"UIDownload":"https://cdn.wowinterface.com/a.zip"}]""")?.version) + } + + @Test fun versionsCompareWithoutPrefixOrCase() { + assertTrue(WowAddonCatalog.sameVersion("v1.2.3", "1.2.3")) + assertTrue(WowAddonCatalog.sameVersion(" 1.2-Beta ", "1.2-beta")) + assertFalse(WowAddonCatalog.sameVersion("1.2.3", "1.2.4")) } @Test fun md5Check() { diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsArchiveTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsArchiveTest.kt new file mode 100644 index 0000000000..2df9241d91 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsArchiveTest.kt @@ -0,0 +1,78 @@ +package com.droiddeck.launcher.runtime + +import org.apache.commons.compress.archivers.sevenz.SevenZOutputFile +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import java.io.File +import java.nio.file.Files + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class WowAddonsArchiveTest { + @get:Rule val temp = TemporaryFolder() + + private fun target(): WowAddons.Target { + val root = temp.newFolder("World of Warcraft") + File(root, "_retail_").mkdirs() + return WowAddons.targets(BattleNet.title("wow")!!, root).single() + } + + private fun sevenZip(vararg files: Pair): File { + val file = temp.newFile("addon-${System.nanoTime()}.bin") + SevenZOutputFile(file).use { out -> + for ((name, text) in files) { + val entry = out.createArchiveEntry(File(name), name) + out.putArchiveEntry(entry) + out.write(text.toByteArray()) + out.closeArchiveEntry() + } + } + return file + } + + private fun unpacked() = File(RuntimeEnvironment.getApplication().cacheDir, "wowaddons").listFiles().orEmpty().filter { it.name.startsWith("unpack-") } + + @Test fun sevenZipArchivesImportLikeZips() { + val target = target() + val names = WowAddons.import(sevenZip("Pack/Foo/Foo.toc" to "toc", "Pack/Foo/core.lua" to "lua", "Pack/Bar/Bar.toc" to "toc"), target, context = RuntimeEnvironment.getApplication()) + assertEquals(listOf("Bar", "Foo"), names.sorted()) + assertEquals("lua", File(target.addOns, "Foo/core.lua").readText()) + assertTrue(File(target.addOns, "Bar/Bar.toc").isFile) + assertTrue(unpacked().isEmpty()) + } + + @Test fun sevenZipArchivesWithoutAnAddonChangeNothing() { + val target = target() + assertEquals(emptyList(), WowAddons.import(sevenZip("readme.txt" to "x"), target, context = RuntimeEnvironment.getApplication())) + assertFalse(target.addOns.exists()) + assertTrue(unpacked().isEmpty()) + } + + @Test fun aFolderWithAnyLinkIsRefusedWhole() { + val target = target() + val folder = temp.newFolder("unpacked") + File(folder, "Foo").mkdirs() + File(folder, "Foo/Foo.toc").writeText("toc") + Files.createSymbolicLink(File(folder, "Foo/link.lua").toPath(), File(folder, "Foo/Foo.toc").toPath()) + assertEquals(emptyList(), WowAddons.importFolder(folder, target, null)) + assertFalse(target.addOns.exists()) + } + + @Test fun aFolderImportKeepsEveryFile() { + val target = target() + val folder = temp.newFolder("unpacked") + File(folder, "Foo/Libs").mkdirs() + File(folder, "Foo/Foo.toc").writeText("toc") + File(folder, "Foo/Libs/lib.lua").writeText("lib") + assertEquals(listOf("Foo"), WowAddons.importFolder(folder, target, null)) + assertEquals("lib", File(target.addOns, "Foo/Libs/lib.lua").readText()) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsTest.kt index 8350ef519b..d64880e0d6 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsTest.kt @@ -218,4 +218,50 @@ class WowAddonsTest { File(root, "_retail_").mkdirs() assertEquals(emptyList(), WowAddons.targets(BattleNet.title("fenris")!!, root).map { it.flavor }) } + + @Test fun tocFieldsReadVersionAndSourceIds() { + val fields = WowAddons.tocFields("\uFEFF## Interface: 110002\n## Title: Foo\n## Version: 1.4.2\n## X-WoWI-ID: 1234\n## Version: 9\n## X-Curse-Project-ID: @curse-id@\nFoo.lua\n") + assertEquals("1.4.2", fields["Version"]) + assertEquals("1234", fields["X-WoWI-ID"]) + assertEquals(null, fields["X-Curse-Project-ID"]) + } + + @Test fun detailsUseTheTocAndTheRecordedSource() { + val target = target() + val foo = File(target.addOns, "Foo").apply { mkdirs() } + File(foo, "Foo_Mainline.toc").writeText("## Version: 1.0\n## X-WoWI-ID: 77\n") + File(target.addOns, "Bar").mkdirs() + val details = WowAddons.details(target).associateBy { it.name } + assertEquals(setOf("Bar", "Foo"), details.keys) + assertEquals("1.0", details.getValue("Foo").version) + assertEquals("77", details.getValue("Foo").wowiId) + assertEquals(null, details.getValue("Bar").version) + } + + @Test fun importRecordsTheSourceAndPlainImportsClearIt() { + val target = target() + WowAddons.import(zip("Foo/Foo.toc" to "## Version: 1.0\n"), target, WowAddons.Origin("55", "2.0")) + val recorded = WowAddons.details(target).single() + assertEquals("2.0", recorded.version) + assertEquals("55", recorded.wowiId) + WowAddons.import(zip("Foo/Foo.toc" to "## Version: 3.0\n"), target) + val plain = WowAddons.details(target).single() + assertEquals("3.0", plain.version) + assertEquals(null, plain.wowiId) + assertFalse(File(target.addOns, ".droiddeck-sources").exists()) + } + + @Test fun deleteForgetsTheRecordedSource() { + val target = target() + WowAddons.import(zip("Foo/Foo.toc" to "x", "Bar/Bar.toc" to "y"), target, WowAddons.Origin("55", "2.0")) + WowAddons.delete(target, "Foo") + assertEquals(mapOf("Bar" to "55"), WowAddons.parseOrigins(File(target.addOns, ".droiddeck-sources").readText()).mapValues { it.value.id }) + assertEquals(listOf("Bar"), WowAddons.installed(target)) + } + + @Test fun originsRoundTripAndSkipBrokenLines() { + val text = WowAddons.formatOrigins(mapOf("A" to WowAddons.Origin("1", "1.0 beta\t2"))) + assertEquals("1.0 beta 2", WowAddons.parseOrigins(text).getValue("A").version) + assertEquals(emptyMap(), WowAddons.parseOrigins("bad line\nA\t\t1\n")) + } } From bc11653c1514b9ae05c4cda8561915d87c781cfd Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Sat, 21 Nov 2026 23:52:53 -0500 Subject: [PATCH 024/141] fix(steam): start the web helper when Android refuses CPU pinning on every GPU (#2819) --- tools/linuxfs/overlay/usr/local/bin/droiddeck-session | 3 +-- tools/tests/test_steam_presentation.py | 4 ++-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session index ee13167e38..61dbb5feda 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session @@ -1417,11 +1417,10 @@ case $mode in export STEAM_STEAMRT_RECURSION_GUARD=1 export LD_LIBRARY_PATH=$steam_root/steamrtarm64:$steam_root/steamrtarm64/panorama${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} export SDL_VIDEO_X11_DGAMOUSE=0 - dd_steam_path=$PATH + dd_steam_path="/usr/local/libexec/droiddeck-steam:$PATH" dd_steam_angle=vulkan dd_steam_presentation=() if [ "${DD_STEAM_GL_PRESENT:-}" = 1 ]; then - dd_steam_path="/usr/local/libexec/droiddeck-steam:$PATH" export DISABLE_GAMESCOPE_WSI=1 LIBGL_KOPPER_DISABLE=true dd_steam_angle=gl dd_steam_presentation=(-cef-disable-gpu-compositing) diff --git a/tools/tests/test_steam_presentation.py b/tools/tests/test_steam_presentation.py index 801c1d4688..48508786db 100644 --- a/tools/tests/test_steam_presentation.py +++ b/tools/tests/test_steam_presentation.py @@ -12,7 +12,7 @@ SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/d class SteamPresentationTest(unittest.TestCase): def launch(self, enabled=None, inherited=None): source = SESSION.read_text() - begin = source.index(" dd_steam_path=$PATH") + begin = source.index(" dd_steam_path=") end = source.index("\n decky_loader=", begin) command = source.index(' PATH="$dd_steam_path"') command_end = source.index("\n rc=$?", command) @@ -41,7 +41,7 @@ class SteamPresentationTest(unittest.TestCase): env=env, capture_output=True, text=True, timeout=5) self.assertEqual(result.returncode, 0, result.stderr) launch = json.loads(result.stdout.splitlines()[-1]) - self.assertEqual(enabled == "1", launch["path"].startswith("/usr/local/libexec/droiddeck-steam:")) + self.assertEqual(launch["path"], "/usr/local/libexec/droiddeck-steam:" + env["PATH"]) self.assertEqual(launch["helper"], str(Path(tmp) / "steamrtarm64/steamwebhelper")) return launch From 6de3c59d7cb76d22aaf07b030aeab6412eae35fc Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Sat, 21 Nov 2026 23:52:56 -0500 Subject: [PATCH 025/141] fix(venus): lower the guest's SPIR-V to 1.3 for the phone's shader compiler (#2587) * fix(venus): lower the guest's SPIR-V to 1.3 for the phone's shader compiler * fix(venus): lower SPIR-V to 1.3 for Mali drivers * fix(venus): keep the SPIR-V cap valid and scoped to active layers Cap inline compute pipeline code too, leave the shader hooks off when the layer is turned off, strip clip and cull distances only where they are emulated, and leave modules alone whose capabilities, decorations or OpSelect results need a newer version or an undeclared extension. * fix(venus): keep application pipeline chains read-only and check non-semantic imports Inline stage code is handed to the driver through a copy of the stage's pNext chain instead of being written into the application's create info, pipeline hooks return VK_ERROR_OUT_OF_HOST_MEMORY when their allocations fail, and a NonSemantic import is only lowered to SPIR-V 1.3 when the module declares SPV_KHR_non_semantic_info. * fix(venus): preserve valid pipeline and shader behavior * fix(venus): lower compatible read-only shader parameters * fix(venus): install SPIR-V 1.3 lowering hooks on Vulkan 1.2+ devices or emulated gaps --- docs/development/mali-venus.md | 25 +- tools/tests/mali_compat_spirv_test.c | 548 ++++++++++++++++++++++++++ tools/tests/test_mali_compat_spirv.py | 90 +++++ tools/venus/layer/layer.c | 17 +- tools/venus/layer/mali_compat.h | 7 + tools/venus/layer/pipeline.c | 298 +++++++++----- tools/venus/layer/spirv.c | 299 ++++++++++++++ 7 files changed, 1183 insertions(+), 101 deletions(-) create mode 100644 tools/tests/mali_compat_spirv_test.c create mode 100644 tools/tests/test_mali_compat_spirv.py diff --git a/docs/development/mali-venus.md b/docs/development/mali-venus.md index caf0d2db70..5cdc4ab39f 100644 --- a/docs/development/mali-venus.md +++ b/docs/development/mali-venus.md @@ -128,10 +128,32 @@ What it does, per feature: - Pipelines and `vkCmdSetColorBlendEquationEXT` both. - Why alpha: output 0's color is the paint, its alpha is the usual coverage. Per-channel coverage collapses to one value; blending stays plain alpha blending, not tinted by the paint. +The SPIR-V version the driver gets: +- The phone's own driver compiles the guest's SPIR-V, and its compiler is old: on the MT6897 + Mali-G615 (r44p1, "Vulkan 1.3.247") it dies with a null read in `cmpbe_v2_compile_multiple_shaders` + while compiling a pipeline, and the render server dies with it, so every guest client that + draws loses its device. +- Zink writes SPIR-V 1.6 for any Vulkan 1.3 device (`zink_screen.c`: `spirv_version` from the + device's version), and SPIR-V 1.4 changed the entry point's interface: it has to list every + global variable, not only the input and output ones. +- The layer therefore lowers every module to SPIR-V 1.3 before the driver sees it: the version + word, the interface list (back to the input and output variables) and `OpTerminateInvocation` + (SPIR-V 1.6's name for `OpKill`). This covers shader modules, and code given inline to + graphics and compute pipelines. +- A module that uses something 1.3 cannot express is left alone and the layer says so in its + log: a `ShaderViewportIndex` capability, the Vulkan memory model, `OpCopyLogical`, an + `OpSelect` of a structure or array, the newer loop controls and image operands, or a + capability, decoration or instruction that became core later without the extension 1.3 + needs for it (`ShaderNonUniform` without `SPV_EXT_descriptor_indexing`). +- The version cap runs on every device the layer is active on; clip and cull distances are + only taken out where the layer emulates them. `DROIDDECK_MALI_COMPAT=0` turns both off. +- This is what Dawn ("Disable SPIR-V 1.4 on Android ARM"), ANGLE (`supportsSPIRV14`) and naga + (`AVOID_SPIRV_COPY_LOGICAL`) do for a proprietary compiler they cannot trust. + Files: - `layer.c`: loader plumbing, feature and limit reporting, device creation, the hook table. - `pipeline.c`: pipelines, shader modules, viewports. -- `spirv.c`: the SPIR-V rewriter for clip and cull distances and the second blend source. +- `spirv.c`: the SPIR-V rewriter for clip and cull distances and the second blend source, and the version cap. - `bc.c`: BC formats, images and uploads. - `VkLayer_droiddeck_mali_compat.json`: implicit layer manifest. @@ -149,6 +171,7 @@ How it ships: Not done yet: - Unit tests for the clip and cull distance rewriter. It is untested beyond DXVK's shaders, and unknown whether Silksong's shaders used clip distances at all. - The dual-source rewrite has them: `tools/tests/test_mali_compat_layer.py`. + - The version cap has them: `tools/tests/test_mali_compat_spirv.py`. - Performance: BC decoding on the CPU makes loads slow. A compute-shader decoder would be the next step. ## Changes on the branch diff --git a/tools/tests/mali_compat_spirv_test.c b/tools/tests/mali_compat_spirv_test.c new file mode 100644 index 0000000000..732251f1fe --- /dev/null +++ b/tools/tests/mali_compat_spirv_test.c @@ -0,0 +1,548 @@ +#include "mali_compat.h" + +#include +#include +#include +#include + +#define OPCODE(word) ((word) & 0xffffu) +#define LENGTH(word) ((word) >> 16) + +static const uint32_t newer[] = { + 0x07230203, 0x00010600, 0x00070000, 0x0000000a, 0x00000000, 0x00020011, 0x00000001, 0x0003000e, + 0x00000000, 0x00000001, 0x0007000f, 0x00000004, 0x00000001, 0x6e69616d, 0x00000000, 0x00000002, + 0x00000003, 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, 0x00000000, + 0x00020013, 0x00000004, 0x00030016, 0x00000005, 0x00000020, 0x00040020, 0x00000006, 0x00000003, + 0x00000005, 0x0004003b, 0x00000006, 0x00000002, 0x00000003, 0x00040020, 0x00000007, 0x00000006, + 0x00000005, 0x0004003b, 0x00000007, 0x00000003, 0x00000006, 0x00030021, 0x00000008, 0x00000004, + 0x00050036, 0x00000004, 0x00000001, 0x00000000, 0x00000008, 0x000200f8, 0x00000009, 0x00011140, + 0x00010038, +}; +static const size_t newer_count = sizeof(newer) / sizeof(uint32_t); + +static const uint32_t readonly_parameter[] = { + SpvMagicNumber, 0x00010600, 0, 13, 0, + (2u << 16) | SpvOpCapability, SpvCapabilityShader, + (3u << 16) | SpvOpMemoryModel, SpvAddressingModelLogical, SpvMemoryModelGLSL450, + (5u << 16) | SpvOpEntryPoint, SpvExecutionModelFragment, 7, 0x6e69616d, 0, + (3u << 16) | SpvOpExecutionMode, 7, SpvExecutionModeOriginUpperLeft, + (3u << 16) | SpvOpDecorate, 3, SpvDecorationBlock, + (5u << 16) | SpvOpMemberDecorate, 3, 0, SpvDecorationOffset, 0, + (3u << 16) | SpvOpDecorate, 10, SpvDecorationNonWritable, + (4u << 16) | SpvOpDecorate, 12, SpvDecorationDescriptorSet, 0, + (4u << 16) | SpvOpDecorate, 12, SpvDecorationBinding, 0, + (2u << 16) | SpvOpTypeVoid, 1, + (3u << 16) | SpvOpTypeFloat, 2, 32, + (3u << 16) | SpvOpTypeStruct, 3, 2, + (4u << 16) | SpvOpTypePointer, 4, SpvStorageClassStorageBuffer, 3, + (4u << 16) | SpvOpVariable, 4, 12, SpvStorageClassStorageBuffer, + (3u << 16) | SpvOpTypeFunction, 5, 1, + (4u << 16) | SpvOpTypeFunction, 6, 1, 4, + (5u << 16) | SpvOpFunction, 1, 7, 0, 5, + (2u << 16) | SpvOpLabel, 8, + (1u << 16) | SpvOpReturn, + (1u << 16) | SpvOpFunctionEnd, + (5u << 16) | SpvOpFunction, 1, 9, 0, 6, + (3u << 16) | SpvOpFunctionParameter, 4, 10, + (2u << 16) | SpvOpLabel, 11, + (1u << 16) | SpvOpReturn, + (1u << 16) | SpvOpFunctionEnd, +}; + +static const uint32_t older[] = { + 0x07230203, 0x00010300, 0x00070000, 0x00000008, 0x00000000, 0x00020011, 0x00000001, 0x0003000e, + 0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d, 0x00000000, 0x00000002, + 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, 0x00000000, 0x00020013, + 0x00000003, 0x00030016, 0x00000004, 0x00000020, 0x00040020, 0x00000005, 0x00000003, 0x00000004, + 0x0004003b, 0x00000005, 0x00000002, 0x00000003, 0x00030021, 0x00000006, 0x00000003, 0x00050036, + 0x00000003, 0x00000001, 0x00000000, 0x00000006, 0x000200f8, 0x00000007, 0x000100fd, 0x00010038, +}; +static const size_t older_count = sizeof(older) / sizeof(uint32_t); + +static const uint32_t capability[] = { + 0x07230203, 0x00010600, 0x00070000, 0x00000008, 0x00000000, 0x00020011, 0x00000001, 0x00020011, + 0x00000046, 0x0003000e, 0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d, + 0x00000000, 0x00000002, 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, + 0x00000000, 0x00020013, 0x00000003, 0x00030016, 0x00000004, 0x00000020, 0x00040020, 0x00000005, + 0x00000003, 0x00000004, 0x0004003b, 0x00000005, 0x00000002, 0x00000003, 0x00030021, 0x00000006, + 0x00000003, 0x00050036, 0x00000003, 0x00000001, 0x00000000, 0x00000006, 0x000200f8, 0x00000007, + 0x000100fd, 0x00010038, +}; +static const size_t capability_count = sizeof(capability) / sizeof(uint32_t); + +static const uint32_t memory[] = { + 0x07230203, 0x00010600, 0x00070000, 0x00000008, 0x00000000, 0x00020011, 0x00000001, 0x00020011, + 0x000014e1, 0x0003000e, 0x00000000, 0x00000003, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d, + 0x00000000, 0x00000002, 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, + 0x00000000, 0x00020013, 0x00000003, 0x00030016, 0x00000004, 0x00000020, 0x00040020, 0x00000005, + 0x00000003, 0x00000004, 0x0004003b, 0x00000005, 0x00000002, 0x00000003, 0x00030021, 0x00000006, + 0x00000003, 0x00050036, 0x00000003, 0x00000001, 0x00000000, 0x00000006, 0x000200f8, 0x00000007, + 0x000100fd, 0x00010038, +}; +static const size_t memory_count = sizeof(memory) / sizeof(uint32_t); + +static const uint32_t zinklike[] = { + 0x07230203, 0x00010600, 0x00070000, 0x00000017, 0x00000000, 0x00020011, 0x00000001, 0x0003000e, + 0x00000000, 0x00000001, 0x0007000f, 0x00000004, 0x00000001, 0x6e69616d, 0x00000000, 0x00000002, + 0x00000003, 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, 0x00000000, + 0x00020013, 0x00000004, 0x00030016, 0x00000005, 0x00000020, 0x00040015, 0x00000006, 0x00000020, + 0x00000001, 0x00040017, 0x00000007, 0x00000005, 0x00000004, 0x0003001e, 0x00000008, 0x00000007, + 0x00040020, 0x00000009, 0x00000003, 0x00000005, 0x0004003b, 0x00000009, 0x00000002, 0x00000003, + 0x00040020, 0x0000000a, 0x00000006, 0x00000008, 0x00040020, 0x0000000b, 0x00000007, 0x00000008, + 0x0004003b, 0x0000000a, 0x00000003, 0x00000006, 0x00040020, 0x0000000c, 0x00000006, 0x00000005, + 0x00040020, 0x0000000d, 0x00000007, 0x00000005, 0x0004002b, 0x00000005, 0x0000000e, 0x3f800000, + 0x0004002b, 0x00000006, 0x0000000f, 0x00000000, 0x00030021, 0x00000010, 0x00000004, 0x00050036, + 0x00000004, 0x00000001, 0x00000000, 0x00000010, 0x000200f8, 0x00000011, 0x0004003b, 0x0000000b, + 0x00000012, 0x00000007, 0x00060041, 0x0000000d, 0x00000013, 0x00000012, 0x0000000f, 0x0000000f, + 0x0003003e, 0x00000013, 0x0000000e, 0x0004003d, 0x00000005, 0x00000014, 0x00000013, 0x00070050, + 0x00000007, 0x00000015, 0x00000014, 0x00000014, 0x00000014, 0x00000014, 0x00040041, 0x00000009, + 0x00000016, 0x00000002, 0x0003003e, 0x00000016, 0x00000014, 0x000100fd, 0x00010038, +}; +static const size_t zinklike_count = sizeof(zinklike) / sizeof(uint32_t); + +static const uint32_t nonuniform[] = { + 0x07230203, 0x00010600, 0x00070000, 0x00000009, 0x00000000, 0x00020011, 0x00000001, 0x00020011, + 0x000014b5, 0x0003000e, 0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d, + 0x00000000, 0x00000002, 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, + 0x00000000, 0x00020013, 0x00000003, 0x00030016, 0x00000004, 0x00000020, 0x00040020, 0x00000005, + 0x00000003, 0x00000004, 0x0004003b, 0x00000005, 0x00000002, 0x00000003, 0x0004002b, 0x00000004, + 0x00000006, 0x3f800000, 0x00030021, 0x00000007, 0x00000003, 0x00050036, 0x00000003, 0x00000001, + 0x00000000, 0x00000007, 0x000200f8, 0x00000008, 0x0003003e, 0x00000002, 0x00000006, 0x000100fd, + 0x00010038, +}; +static const size_t nonuniform_count = sizeof(nonuniform) / sizeof(uint32_t); + +static const uint32_t nonuniform_extension[] = { + 0x07230203, 0x00010600, 0x00070000, 0x00000009, 0x00000000, 0x00020011, 0x00000001, 0x00020011, + 0x000014b5, 0x0008000a, 0x5f565053, 0x5f545845, 0x63736564, 0x74706972, 0x695f726f, 0x7865646e, + 0x00676e69, 0x0003000e, 0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d, + 0x00000000, 0x00000002, 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, + 0x00000000, 0x00020013, 0x00000003, 0x00030016, 0x00000004, 0x00000020, 0x00040020, 0x00000005, + 0x00000003, 0x00000004, 0x0004003b, 0x00000005, 0x00000002, 0x00000003, 0x0004002b, 0x00000004, + 0x00000006, 0x3f800000, 0x00030021, 0x00000007, 0x00000003, 0x00050036, 0x00000003, 0x00000001, + 0x00000000, 0x00000007, 0x000200f8, 0x00000008, 0x0003003e, 0x00000002, 0x00000006, 0x000100fd, + 0x00010038, +}; +static const size_t nonuniform_extension_count = sizeof(nonuniform_extension) / sizeof(uint32_t); + +static const uint32_t select_struct[] = { + 0x07230203, 0x00010600, 0x00070000, 0x00000011, 0x00000000, 0x00020011, 0x00000001, 0x0003000e, + 0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d, 0x00000000, 0x00000002, + 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, 0x00000000, 0x00020013, + 0x00000003, 0x00020014, 0x00000004, 0x00030016, 0x00000005, 0x00000020, 0x0004001e, 0x00000006, + 0x00000005, 0x00000005, 0x00040020, 0x00000007, 0x00000003, 0x00000005, 0x0004003b, 0x00000007, + 0x00000002, 0x00000003, 0x0004002b, 0x00000005, 0x00000008, 0x3f800000, 0x0004002b, 0x00000005, + 0x00000009, 0x00000000, 0x00030029, 0x00000004, 0x0000000a, 0x0005002c, 0x00000006, 0x0000000b, + 0x00000008, 0x00000009, 0x0005002c, 0x00000006, 0x0000000c, 0x00000009, 0x00000008, 0x00030021, + 0x0000000d, 0x00000003, 0x00050036, 0x00000003, 0x00000001, 0x00000000, 0x0000000d, 0x000200f8, + 0x0000000e, 0x000600a9, 0x00000006, 0x0000000f, 0x0000000a, 0x0000000b, 0x0000000c, 0x00050051, + 0x00000005, 0x00000010, 0x0000000f, 0x00000000, 0x0003003e, 0x00000002, 0x00000010, 0x000100fd, + 0x00010038, +}; +static const size_t select_struct_count = sizeof(select_struct) / sizeof(uint32_t); + +static const uint32_t select_scalar[] = { + 0x07230203, 0x00010600, 0x00070000, 0x0000000d, 0x00000000, 0x00020011, 0x00000001, 0x0003000e, + 0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d, 0x00000000, 0x00000002, + 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, 0x00000000, 0x00020013, + 0x00000003, 0x00020014, 0x00000004, 0x00030016, 0x00000005, 0x00000020, 0x00040020, 0x00000006, + 0x00000003, 0x00000005, 0x0004003b, 0x00000006, 0x00000002, 0x00000003, 0x0004002b, 0x00000005, + 0x00000007, 0x3f800000, 0x0004002b, 0x00000005, 0x00000008, 0x00000000, 0x00030029, 0x00000004, + 0x00000009, 0x00030021, 0x0000000a, 0x00000003, 0x00050036, 0x00000003, 0x00000001, 0x00000000, + 0x0000000a, 0x000200f8, 0x0000000b, 0x000600a9, 0x00000005, 0x0000000c, 0x00000009, 0x00000007, + 0x00000008, 0x0003003e, 0x00000002, 0x0000000c, 0x000100fd, 0x00010038, +}; +static const size_t select_scalar_count = sizeof(select_scalar) / sizeof(uint32_t); + +static const uint32_t nonsemantic[] = { + 0x07230203, 0x00010600, 0x00070000, 0x0000000c, 0x00000000, 0x00020011, 0x00000001, 0x0008000b, + 0x00000001, 0x536e6f4e, 0x6e616d65, 0x2e636974, 0x75626544, 0x69725067, 0x0066746e, 0x0003000e, + 0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000002, 0x6e69616d, 0x00000000, 0x00000003, + 0x00030010, 0x00000002, 0x00000007, 0x00030007, 0x00000004, 0x00000078, 0x00040047, 0x00000003, + 0x0000001e, 0x00000000, 0x00020013, 0x00000005, 0x00030016, 0x00000006, 0x00000020, 0x00040020, + 0x00000007, 0x00000003, 0x00000006, 0x0004003b, 0x00000007, 0x00000003, 0x00000003, 0x0004002b, + 0x00000006, 0x00000008, 0x3f800000, 0x00030021, 0x00000009, 0x00000005, 0x00050036, 0x00000005, + 0x00000002, 0x00000000, 0x00000009, 0x000200f8, 0x0000000a, 0x0006000c, 0x00000005, 0x0000000b, + 0x00000001, 0x00000001, 0x00000004, 0x0003003e, 0x00000003, 0x00000008, 0x000100fd, 0x00010038, +}; +static const size_t nonsemantic_count = sizeof(nonsemantic) / sizeof(uint32_t); + +static const uint32_t nonsemantic_extension[] = { + 0x07230203, 0x00010600, 0x00070000, 0x0000000c, 0x00000000, 0x00020011, 0x00000001, 0x0008000a, + 0x5f565053, 0x5f52484b, 0x5f6e6f6e, 0x616d6573, 0x6369746e, 0x666e695f, 0x0000006f, 0x0008000b, + 0x00000001, 0x536e6f4e, 0x6e616d65, 0x2e636974, 0x75626544, 0x69725067, 0x0066746e, 0x0003000e, + 0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000002, 0x6e69616d, 0x00000000, 0x00000003, + 0x00030010, 0x00000002, 0x00000007, 0x00030007, 0x00000004, 0x00000078, 0x00040047, 0x00000003, + 0x0000001e, 0x00000000, 0x00020013, 0x00000005, 0x00030016, 0x00000006, 0x00000020, 0x00040020, + 0x00000007, 0x00000003, 0x00000006, 0x0004003b, 0x00000007, 0x00000003, 0x00000003, 0x0004002b, + 0x00000006, 0x00000008, 0x3f800000, 0x00030021, 0x00000009, 0x00000005, 0x00050036, 0x00000005, + 0x00000002, 0x00000000, 0x00000009, 0x000200f8, 0x0000000a, 0x0006000c, 0x00000005, 0x0000000b, + 0x00000001, 0x00000001, 0x00000004, 0x0003003e, 0x00000003, 0x00000008, 0x000100fd, 0x00010038, +}; +static const size_t nonsemantic_extension_count = sizeof(nonsemantic_extension) / sizeof(uint32_t); + +static int failures; + +static void check(int condition, const char *what) +{ + if (!condition) { + printf("FAIL: %s\n", what); + failures++; + } +} + +static size_t count_opcodes(const uint32_t *words, size_t count, uint32_t opcode) +{ + size_t found = 0; + for (size_t i = 5; i < count; i += LENGTH(words[i])) { + if (OPCODE(words[i]) == opcode) + found++; + } + return found; +} + +static size_t interface_size(const uint32_t *words, size_t count) +{ + for (size_t i = 5; i < count; i += LENGTH(words[i])) { + if (OPCODE(words[i]) != SpvOpEntryPoint) + continue; + size_t length = LENGTH(words[i]); + size_t name = 3; + while (name < length) { + uint32_t word = words[i + name]; + if (!(word & 0xff) || !(word & 0xff00) || !(word & 0xff0000) || !(word & 0xff000000)) + break; + name++; + } + return length - (name + 1); + } + return 0; +} + +static void write_module(const char *path, const struct spirv_code *code) +{ + FILE *out = fopen(path, "wb"); + if (!out) { + printf("FAIL: %s cannot be written\n", path); + failures++; + return; + } + fwrite(code->words, sizeof(uint32_t), code->count, out); + fclose(out); +} + +static struct device test_device; +static int failed_allocations; +static bool fail_allocations; +static int driver_calls; +static bool chain_was_layer_owned; +static VkStructureType first_link; +static uint32_t driver_version; +static uint32_t driver_subgroup_size; + +void *test_calloc(size_t count, size_t size) +{ + if (fail_allocations) { + failed_allocations++; + return NULL; + } + if (size && count > SIZE_MAX / size) + return NULL; + size_t bytes = count * size; + void *memory = malloc(bytes > 0 ? bytes : 1); + if (memory) + memset(memory, 0, bytes); + return memory; +} + +struct device *device_from_handle(const void *dispatchable) +{ + return &test_device; +} + +void layer_log(const char *format, ...) +{ +} + +void *map_get(const struct handle_map *map, uint64_t key) +{ + return NULL; +} + +void map_put(struct handle_map *map, uint64_t key, void *value) +{ +} + +void *map_remove(struct handle_map *map, uint64_t key) +{ + return NULL; +} + +static void read_stage(const VkPipelineShaderStageCreateInfo *stage, const void *app_chain) +{ + driver_calls++; + chain_was_layer_owned = stage->pNext != app_chain; + first_link = stage->pNext ? ((const VkBaseInStructure *)stage->pNext)->sType : VK_STRUCTURE_TYPE_MAX_ENUM; + driver_version = 0; + driver_subgroup_size = 0; + for (const VkBaseInStructure *s = stage->pNext; s; s = s->pNext) { + if (s->sType == VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO) + driver_subgroup_size = ((const VkPipelineShaderStageRequiredSubgroupSizeCreateInfo *)s)->requiredSubgroupSize; + if (s->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO) { + const VkShaderModuleCreateInfo *info = (const VkShaderModuleCreateInfo *)s; + driver_version = spirv_version(info->pCode, info->codeSize / sizeof(uint32_t)); + } + } +} + +static const void *expected_chain; + +static VkResult VKAPI_CALL driver_compute(VkDevice device, VkPipelineCache cache, uint32_t count, + const VkComputePipelineCreateInfo *infos, + const VkAllocationCallbacks *allocator, VkPipeline *pipelines) +{ + read_stage(&infos[0].stage, expected_chain); + return VK_SUCCESS; +} + +static VkResult VKAPI_CALL driver_graphics(VkDevice device, VkPipelineCache cache, uint32_t count, + const VkGraphicsPipelineCreateInfo *infos, + const VkAllocationCallbacks *allocator, VkPipeline *pipelines) +{ + read_stage(&infos[0].pStages[0], expected_chain); + return VK_SUCCESS; +} + +static const VkShaderModuleCreateInfo app_module = { + .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, + .codeSize = sizeof(newer), + .pCode = newer, +}; + +static const VkPipelineShaderStageRequiredSubgroupSizeCreateInfo app_subgroup = { + .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO, + .pNext = &app_module, + .requiredSubgroupSize = 16, +}; + +static const VkApplicationInfo app_unknown = { + .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, + .pNext = &app_module, +}; + +static const VkPipelineShaderStageCreateInfo app_fragment = { + .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .pNext = &app_subgroup, + .stage = VK_SHADER_STAGE_FRAGMENT_BIT, + .pName = "main", +}; + +static void check_pipelines(void) +{ + VkDevice device = (VkDevice)&test_device; + VkPipeline pipeline = VK_NULL_HANDLE; + pthread_mutex_init(&test_device.lock, NULL); + test_device.CreateComputePipelines = driver_compute; + test_device.CreateGraphicsPipelines = driver_graphics; + + VkComputePipelineCreateInfo compute = { + .sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, + .stage = {.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .pNext = &app_subgroup, + .stage = VK_SHADER_STAGE_COMPUTE_BIT, + .pName = "main"}, + }; + expected_chain = &app_subgroup; + check(CreateComputePipelines(device, VK_NULL_HANDLE, 1, &compute, NULL, &pipeline) == VK_SUCCESS, + "a compute pipeline with inline code behind another structure is created"); + check(chain_was_layer_owned, "the compute stage gets the layer's own chain"); + check(first_link == VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO, + "the compute stage keeps its chain order"); + check(driver_subgroup_size == 16, "the compute stage keeps its required subgroup size"); + check(driver_version == 0x00010300u, "the compute stage's inline code reaches the driver as SPIR-V 1.3"); + check(app_module.pCode == newer && app_module.codeSize == sizeof(newer), + "the application's shader module create info is untouched"); + check(compute.stage.pNext == &app_subgroup, "the application's compute stage is untouched"); + + compute.stage.pNext = &app_module; + expected_chain = &app_module; + check(CreateComputePipelines(device, VK_NULL_HANDLE, 1, &compute, NULL, &pipeline) == VK_SUCCESS, + "a compute pipeline with inline code first in its chain is created"); + check(chain_was_layer_owned && driver_version == 0x00010300u, + "inline code first in the chain reaches the driver as SPIR-V 1.3"); + + compute.stage.pNext = &app_unknown; + expected_chain = &app_unknown; + check(CreateComputePipelines(device, VK_NULL_HANDLE, 1, &compute, NULL, &pipeline) == VK_SUCCESS, + "a compute pipeline behind an unknown structure is created"); + check(!chain_was_layer_owned && driver_version == 0x00010600u, + "a chain the layer cannot copy reaches the driver as the application wrote it"); + + VkGraphicsPipelineCreateInfo graphics = { + .sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, + .stageCount = 1, + .pStages = &app_fragment, + }; + expected_chain = &app_subgroup; + check(CreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &graphics, NULL, &pipeline) == VK_SUCCESS, + "a graphics pipeline with inline code behind another structure is created"); + check(chain_was_layer_owned && driver_subgroup_size == 16 && driver_version == 0x00010300u, + "the graphics stage reaches the driver capped with its chain intact"); + check(app_fragment.pNext == &app_subgroup && graphics.pStages == &app_fragment, + "the application's graphics stages are untouched"); + + driver_calls = 0; + failed_allocations = 0; + fail_allocations = true; + VkPipeline compute_outputs[2] = {(VkPipeline)(uintptr_t)1, (VkPipeline)(uintptr_t)2}; + VkPipeline graphics_outputs[2] = {(VkPipeline)(uintptr_t)1, (VkPipeline)(uintptr_t)2}; + VkResult compute_result = CreateComputePipelines(device, VK_NULL_HANDLE, 2, &compute, NULL, compute_outputs); + VkResult graphics_result = CreateGraphicsPipelines(device, VK_NULL_HANDLE, 2, &graphics, NULL, graphics_outputs); + fail_allocations = false; + check(failed_allocations > 0, "the allocations were made to fail"); + check(compute_result == VK_ERROR_OUT_OF_HOST_MEMORY, "a compute pipeline without memory reports it"); + check(graphics_result == VK_ERROR_OUT_OF_HOST_MEMORY, "a graphics pipeline without memory reports it"); + check(compute_outputs[0] == VK_NULL_HANDLE && compute_outputs[1] == VK_NULL_HANDLE, + "failed compute pipeline outputs are cleared"); + check(graphics_outputs[0] == VK_NULL_HANDLE && graphics_outputs[1] == VK_NULL_HANDLE, + "failed graphics pipeline outputs are cleared"); + check(driver_calls == 0, "the driver is not called without memory"); + pthread_mutex_destroy(&test_device.lock); +} + +int main(int argc, char **argv) +{ + struct spirv_code capped = {0}; + check(spirv_cap_version(newer, newer_count, &capped), "a SPIR-V 1.6 module is capped"); + check(capped.words != NULL, "the capped module is there"); + if (capped.words) { + check(capped.words[1] == 0x00010300u, "the capped module is SPIR-V 1.3"); + check(interface_size(capped.words, capped.count) == 1, + "the entry point lists only the input and output variables"); + check(count_opcodes(capped.words, capped.count, SpvOpKill) == 1, "the discard is an OpKill"); + check(count_opcodes(capped.words, capped.count, SpvOpTerminateInvocation) == 0, + "no OpTerminateInvocation is left"); + if (argc > 1) + write_module(argv[1], &capped); + free(capped.words); + } + + struct spirv_code kept = {0}; + check(!spirv_cap_version(older, older_count, &kept), "a SPIR-V 1.3 module is left alone"); + check(kept.words == NULL, "the untouched module is not handed back"); + check(!spirv_cap_version(capability, capability_count, &kept), + "a module with a capability from SPIR-V 1.5 is left alone"); + check(!spirv_cap_version(memory, memory_count, &kept), "a module with the Vulkan memory model is left alone"); + check(!spirv_cap_version(nonuniform, nonuniform_count, &kept), + "a module with ShaderNonUniform and no SPV_EXT_descriptor_indexing is left alone"); + check(!spirv_cap_version(select_struct, select_struct_count, &kept), + "a module selecting a structure is left alone"); + check(!spirv_cap_version(nonsemantic, nonsemantic_count, &kept), + "a module importing a NonSemantic set without SPV_KHR_non_semantic_info is left alone"); + uint32_t private_readonly[sizeof(zinklike) / sizeof(uint32_t) + 3]; + size_t declaration = 5; + while (OPCODE(zinklike[declaration]) != SpvOpTypeVoid) + declaration += LENGTH(zinklike[declaration]); + memcpy(private_readonly, zinklike, declaration * sizeof(uint32_t)); + private_readonly[declaration] = (3u << 16) | SpvOpDecorate; + private_readonly[declaration + 1] = 3; + private_readonly[declaration + 2] = SpvDecorationNonWritable; + memcpy(private_readonly + declaration + 3, zinklike + declaration, + (zinklike_count - declaration) * sizeof(uint32_t)); + check(!spirv_cap_version(private_readonly, zinklike_count + 3, &kept), + "a private NonWritable variable is left alone"); + if (argc > 6) { + struct spirv_code source = {.words = private_readonly, .count = zinklike_count + 3}; + write_module(argv[6], &source); + } + uint32_t converted[sizeof(zinklike) / sizeof(uint32_t) + 9]; + size_t function = declaration; + while (OPCODE(zinklike[function]) != SpvOpFunction) + function += LENGTH(zinklike[function]); + memcpy(converted, zinklike, function * sizeof(uint32_t)); + const uint32_t conversion[] = {(4u << 16) | SpvOpTypeInt, 23, 32, 0, + (5u << 16) | SpvOpSpecConstantOp, 23, 24, SpvOpUConvert, 15}; + memcpy(converted + function, conversion, sizeof(conversion)); + memcpy(converted + function + 9, zinklike + function, (zinklike_count - function) * sizeof(uint32_t)); + converted[3] = 25; + check(!spirv_cap_version(converted, zinklike_count + 9, &kept), + "a specialization UConvert without its extension is left alone"); + if (argc > 7) { + struct spirv_code source = {.words = converted, .count = zinklike_count + 9}; + write_module(argv[7], &source); + } + check(kept.words == NULL, "no rejected module is handed back"); + + struct spirv_code extension = {0}; + check(spirv_cap_version(nonuniform_extension, nonuniform_extension_count, &extension), + "a module declaring SPV_EXT_descriptor_indexing for ShaderNonUniform is capped"); + if (extension.words) { + check(extension.words[1] == 0x00010300u, "the module with the extension is SPIR-V 1.3"); + if (argc > 3) + write_module(argv[3], &extension); + free(extension.words); + } + + struct spirv_code scalar = {0}; + check(spirv_cap_version(select_scalar, select_scalar_count, &scalar), "a module selecting a scalar is capped"); + if (scalar.words) { + check(count_opcodes(scalar.words, scalar.count, SpvOpSelect) == 1, "the scalar select is kept"); + if (argc > 4) + write_module(argv[4], &scalar); + free(scalar.words); + } + + struct spirv_code debug = {0}; + check(spirv_cap_version(nonsemantic_extension, nonsemantic_extension_count, &debug), + "a module declaring SPV_KHR_non_semantic_info for its NonSemantic import is capped"); + if (debug.words) { + check(debug.words[1] == 0x00010300u, "the module with the NonSemantic import is SPIR-V 1.3"); + if (argc > 5) + write_module(argv[5], &debug); + free(debug.words); + } + + struct spirv_code guest = {0}; + check(spirv_cap_version(zinklike, zinklike_count, &guest), "a guest module with a private global is capped"); + if (guest.words) { + check(guest.words[1] == 0x00010300u, "the guest module is SPIR-V 1.3"); + check(interface_size(guest.words, guest.count) == 1, + "the guest module lists only the input and output variables"); + check(count_opcodes(guest.words, guest.count, SpvOpFunction) == 1, "the guest module keeps its function"); + if (argc > 2) + write_module(argv[2], &guest); + free(guest.words); + } + + struct spirv_code parameter = {0}; + size_t parameter_count = sizeof(readonly_parameter) / sizeof(uint32_t); + check(spirv_cap_version(readonly_parameter, parameter_count, ¶meter), + "a NonWritable storage buffer parameter is capped"); + if (parameter.words) { + check(count_opcodes(parameter.words, parameter.count, SpvOpFunctionParameter) == 1, + "the storage buffer parameter is preserved"); + if (argc > 8) + write_module(argv[8], ¶meter); + free(parameter.words); + } + uint32_t incompatible_parameter[sizeof(readonly_parameter) / sizeof(uint32_t)]; + memcpy(incompatible_parameter, readonly_parameter, sizeof(readonly_parameter)); + for (size_t i = 5; i < parameter_count; i += LENGTH(incompatible_parameter[i])) { + if (OPCODE(incompatible_parameter[i]) == SpvOpTypePointer) { + incompatible_parameter[i + 2] = SpvStorageClassPrivate; + check(!spirv_cap_version(incompatible_parameter, parameter_count, &kept), + "a NonWritable Private parameter is left alone"); + incompatible_parameter[i + 2] = SpvStorageClassFunction; + check(!spirv_cap_version(incompatible_parameter, parameter_count, &kept), + "a NonWritable Function parameter is left alone"); + } + } + + check_pipelines(); + + if (failures) + printf("%d check(s) failed\n", failures); + else + printf("mali compat spirv ok\n"); + return failures ? 1 : 0; +} diff --git a/tools/tests/test_mali_compat_spirv.py b/tools/tests/test_mali_compat_spirv.py new file mode 100644 index 0000000000..a5c0e38e2d --- /dev/null +++ b/tools/tests/test_mali_compat_spirv.py @@ -0,0 +1,90 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +LAYER = ROOT / "tools/venus/layer" +DEPS = ROOT / "build/layer-deps" +HARNESS = Path(__file__).with_name("mali_compat_spirv_test.c") + + +def include(variable, default): + return Path(os.environ.get(variable, str(default))) + + +class MaliCompatSpirvTest(unittest.TestCase): + def test_the_layer_lowers_a_module_to_the_version_the_driver_knows(self): + compiler = shutil.which(os.environ.get("CC", "cc")) + if not compiler: + self.fail("A C compiler is required for the Mali compatibility layer test") + vulkan = include("MALI_COMPAT_VULKAN_INCLUDE", DEPS / "vulkan/include") + spirv = include("MALI_COMPAT_SPIRV_INCLUDE", DEPS / "spirv/include") + missing = [str(path) for path in (vulkan / "vulkan/vk_layer.h", spirv / "spirv/unified1/spirv.h") + if not path.is_file()] + if missing: + message = "Vulkan 1.4 and SPIR-V headers are required: " + ", ".join(missing) + if os.environ.get("CI"): + self.fail(message) + self.skipTest(message) + with tempfile.TemporaryDirectory(prefix="droiddeck-mali-spirv-") as tmp: + program = Path(tmp) / "mali-compat-spirv" + module = Path(tmp) / "capped.spv" + guest = Path(tmp) / "guest.spv" + extension = Path(tmp) / "extension.spv" + scalar = Path(tmp) / "scalar.spv" + debug = Path(tmp) / "debug.spv" + private_readonly = Path(tmp) / "private-readonly.spv" + parameter = Path(tmp) / "parameter.spv" + converted = Path(tmp) / "converted.spv" + built = subprocess.run( + [compiler, "-std=gnu11", "-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter", "-UNDEBUG", + "-pthread", "-Dcalloc=test_calloc", "-I", str(LAYER), "-I", str(vulkan), "-I", str(spirv), + str(HARNESS), str(LAYER / "spirv.c"), str(LAYER / "pipeline.c"), "-o", str(program)], + capture_output=True, text=True) + self.assertEqual(built.returncode, 0, built.stdout + built.stderr) + ran = subprocess.run([str(program), str(module), str(guest), str(extension), str(scalar), str(debug), + str(private_readonly), str(converted), str(parameter)], + capture_output=True, text=True, timeout=30) + self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr) + self.assertIn("mali compat spirv ok", ran.stdout) + self.assertTrue(module.is_file()) + self.assertTrue(guest.is_file()) + self.assertTrue(extension.is_file()) + self.assertTrue(scalar.is_file()) + self.assertTrue(debug.is_file()) + validator = shutil.which("spirv-val") + if not validator: + return + for original in (private_readonly, converted): + checked = subprocess.run([validator, "--target-env", "vulkan1.3", str(original)], + capture_output=True, text=True) + self.assertEqual(checked.returncode, 0, checked.stdout + checked.stderr) + downgraded = bytearray(original.read_bytes()) + downgraded[4:8] = (0x00010300).to_bytes(4, "little") + offset = 20 + while True: + instruction = int.from_bytes(downgraded[offset:offset + 4], "little") + length, opcode = instruction >> 16, instruction & 0xffff + if opcode == 15: + downgraded[offset:offset + 4] = (((length - 1) << 16) | opcode).to_bytes(4, "little") + del downgraded[offset + (length - 1) * 4:offset + length * 4] + break + offset += length * 4 + original.write_bytes(downgraded) + checked = subprocess.run([validator, "--target-env", "vulkan1.1", str(original)], + capture_output=True, text=True) + self.assertNotEqual(checked.returncode, 0, "the 1.3 form must be rejected") + expected = "NonWritable" if original == private_readonly else "UConvert" + self.assertIn(expected, checked.stdout + checked.stderr) + for lowered in (module, guest, extension, scalar, debug, parameter): + checked = subprocess.run([validator, "--target-env", "vulkan1.1", str(lowered)], + capture_output=True, text=True) + self.assertEqual(checked.returncode, 0, checked.stdout + checked.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/venus/layer/layer.c b/tools/venus/layer/layer.c index 2f1e7ccd7d..a4e35e0a32 100644 --- a/tools/venus/layer/layer.c +++ b/tools/venus/layer/layer.c @@ -615,6 +615,7 @@ static VKAPI_ATTR VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice physical_dev inst->GetPhysicalDeviceMemoryProperties(physical_device, &dev->memory_properties); VkPhysicalDeviceProperties properties; inst->GetPhysicalDeviceProperties(physical_device, &properties); + dev->active = inst->active && (requested != 0 || properties.apiVersion >= VK_API_VERSION_1_2); uint32_t components = properties.limits.maxVertexOutputComponents; if (properties.limits.maxFragmentInputComponents < components) components = properties.limits.maxFragmentInputComponents; @@ -672,15 +673,18 @@ struct hook { const char *name; PFN_vkVoidFunction function; uint32_t gaps; + bool always; }; -#define HOOK(name, gaps) {"vk" #name, (PFN_vkVoidFunction)name, gaps} -#define HOOK_ALIAS(name, alias, gaps) {"vk" #alias, (PFN_vkVoidFunction)name, gaps} +#define HOOK(name, gaps) {"vk" #name, (PFN_vkVoidFunction)name, gaps, false} +#define HOOK_ALIAS(name, alias, gaps) {"vk" #alias, (PFN_vkVoidFunction)name, gaps, false} +#define HOOK_ALWAYS(name) {"vk" #name, (PFN_vkVoidFunction)name, 0, true} static const struct hook device_hooks[] = { - HOOK(CreateShaderModule, GAPS_SHADER | GAP_DUAL_SRC_BLEND), - HOOK(DestroyShaderModule, GAPS_SHADER | GAP_DUAL_SRC_BLEND), - HOOK(CreateGraphicsPipelines, GAPS_PIPELINE), + HOOK_ALWAYS(CreateShaderModule), + HOOK_ALWAYS(DestroyShaderModule), + HOOK_ALWAYS(CreateGraphicsPipelines), + HOOK_ALWAYS(CreateComputePipelines), HOOK(CmdSetViewport, GAP_MULTI_VIEWPORT), HOOK(CmdSetScissor, GAP_MULTI_VIEWPORT), HOOK(CmdSetViewportWithCount, GAP_MULTI_VIEWPORT), @@ -756,7 +760,8 @@ static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL GetDeviceProcAddr(VkDevice devic if (!next) return NULL; for (size_t i = 0; i < sizeof(device_hooks) / sizeof(device_hooks[0]); i++) { - if ((dev->emulated & device_hooks[i].gaps) && !strcmp(name, device_hooks[i].name)) + bool installed = device_hooks[i].always ? dev->active : (dev->emulated & device_hooks[i].gaps) != 0; + if (installed && !strcmp(name, device_hooks[i].name)) return device_hooks[i].function; } return next; diff --git a/tools/venus/layer/mali_compat.h b/tools/venus/layer/mali_compat.h index a785eaff4a..eb171bb6f9 100644 --- a/tools/venus/layer/mali_compat.h +++ b/tools/venus/layer/mali_compat.h @@ -89,6 +89,7 @@ struct instance { X(CreateShaderModule) \ X(DestroyShaderModule) \ X(CreateGraphicsPipelines) \ + X(CreateComputePipelines) \ X(CmdSetViewport) \ X(CmdSetScissor) \ X(CmdSetViewportWithCount) \ @@ -145,6 +146,7 @@ struct device { void *key; VkDevice handle; PFN_vkGetDeviceProcAddr gdpa; + bool active; /* The gaps the application enabled a made-up feature for. */ uint32_t emulated; /* Locations a clip distance varying may use, from the vertex output and fragment input limits. */ @@ -185,6 +187,8 @@ struct spirv_code { bool spirv_uses_distances(const uint32_t *words, size_t count); /* The module with clip and cull distances taken out; false when it cannot be rewritten. */ bool spirv_strip_distances(const uint32_t *words, size_t count, struct spirv_code *out); +uint32_t spirv_version(const uint32_t *words, size_t count); +bool spirv_cap_version(const uint32_t *words, size_t count, struct spirv_code *out); bool spirv_uses_dual_source(const uint32_t *words, size_t count); bool spirv_strip_dual_source(const uint32_t *words, size_t count, struct spirv_code *out); @@ -213,6 +217,9 @@ VKAPI_ATTR void VKAPI_CALL DestroyShaderModule(VkDevice device, VkShaderModule m VKAPI_ATTR VkResult VKAPI_CALL CreateGraphicsPipelines(VkDevice device, VkPipelineCache cache, uint32_t count, const VkGraphicsPipelineCreateInfo *infos, const VkAllocationCallbacks *allocator, VkPipeline *pipelines); +VKAPI_ATTR VkResult VKAPI_CALL CreateComputePipelines(VkDevice device, VkPipelineCache cache, uint32_t count, + const VkComputePipelineCreateInfo *infos, + const VkAllocationCallbacks *allocator, VkPipeline *pipelines); VKAPI_ATTR void VKAPI_CALL CmdSetViewport(VkCommandBuffer cmd, uint32_t first, uint32_t count, const VkViewport *viewports); VKAPI_ATTR void VKAPI_CALL CmdSetScissor(VkCommandBuffer cmd, uint32_t first, uint32_t count, diff --git a/tools/venus/layer/pipeline.c b/tools/venus/layer/pipeline.c index 906ef27d26..95c0ccd1ee 100644 --- a/tools/venus/layer/pipeline.c +++ b/tools/venus/layer/pipeline.c @@ -5,6 +5,13 @@ #define HANDLE(h) ((uint64_t)(uintptr_t)(h)) #define MAX_STAGES 8 +#define MAX_LINKS 8 + +static void log_spirv_version(const char *what, const uint32_t *words, size_t count) +{ + uint32_t version = spirv_version(words, count); + layer_log("shader module: SPIR-V %u.%u %s (%zu words)", (version >> 16) & 0xff, (version >> 8) & 0xff, what, count); +} /* A module with distances goes to the driver without them; its original stays here, for the * pipeline that can emulate its clip distances. */ @@ -12,49 +19,57 @@ VKAPI_ATTR VkResult VKAPI_CALL CreateShaderModule(VkDevice device, const VkShade const VkAllocationCallbacks *allocator, VkShaderModule *module) { struct device *dev = device_from_handle(device); - VkShaderModuleCreateInfo copy = *info; size_t count = info->codeSize / sizeof(uint32_t); + struct spirv_code capped = {0}; + bool have_capped = spirv_cap_version(info->pCode, count, &capped); + if (have_capped) + log_spirv_version("lowered to 1.3", info->pCode, count); + else if (spirv_version(info->pCode, count) > 0x00010300u) + log_spirv_version("left as it is", info->pCode, count); + const uint32_t *code = have_capped ? capped.words : info->pCode; + size_t words = have_capped ? capped.count : count; + struct spirv_code single = {0}; - if ((dev->emulated & GAP_DUAL_SRC_BLEND) && spirv_uses_dual_source(info->pCode, count)) { - if (spirv_strip_dual_source(info->pCode, count, &single)) { - copy.pCode = single.words; - copy.codeSize = single.count * sizeof(uint32_t); - count = single.count; + if ((dev->emulated & GAP_DUAL_SRC_BLEND) && spirv_uses_dual_source(code, words)) { + if (spirv_strip_dual_source(code, words, &single)) { + code = single.words; + words = single.count; } else { layer_log("could not take the second blend source out of a shader module"); } } - if (!(dev->emulated & GAPS_SHADER) || !spirv_uses_distances(copy.pCode, count)) { - VkResult result = dev->CreateShaderModule(device, ©, allocator, module); - free(single.words); - return result; - } - struct spirv_code stripped; - if (!spirv_strip_distances(copy.pCode, count, &stripped)) { - layer_log("could not take the clip and cull distances out of a shader module"); - VkResult result = dev->CreateShaderModule(device, ©, allocator, module); - free(single.words); - return result; + struct spirv_code stripped = {0}; + bool have_stripped = false; + if ((dev->emulated & GAPS_SHADER) && spirv_uses_distances(code, words)) { + have_stripped = spirv_strip_distances(code, words, &stripped); + if (!have_stripped) + layer_log("could not take the clip and cull distances out of a shader module"); } - struct spirv_code *original = malloc(sizeof(*original)); - original->count = count; - original->words = malloc(copy.codeSize); - memcpy(original->words, copy.pCode, copy.codeSize); - free(single.words); - copy.pCode = stripped.words; - copy.codeSize = stripped.count * sizeof(uint32_t); + if (!have_stripped && code == info->pCode) + return dev->CreateShaderModule(device, info, allocator, module); + + VkShaderModuleCreateInfo copy = *info; + copy.pCode = have_stripped ? stripped.words : code; + copy.codeSize = (have_stripped ? stripped.count : words) * sizeof(uint32_t); VkResult result = dev->CreateShaderModule(device, ©, allocator, module); - free(stripped.words); - if (result != VK_SUCCESS) { - free(original->words); - free(original); + if (result != VK_SUCCESS || !have_stripped) { + free(capped.words); + free(single.words); + free(stripped.words); return result; } + struct spirv_code *original = malloc(sizeof(*original)); + original->count = words; + original->words = malloc(words * sizeof(uint32_t)); + memcpy(original->words, code, words * sizeof(uint32_t)); pthread_mutex_lock(&dev->lock); map_put(&dev->shader_modules, HANDLE(*module), original); pthread_mutex_unlock(&dev->lock); + free(capped.words); + free(single.words); + free(stripped.words); return VK_SUCCESS; } @@ -76,9 +91,10 @@ struct stage_code { const uint32_t *words; size_t count; /* The application's own, when the code comes inline in the stage. */ - VkShaderModuleCreateInfo *inline_info; + const VkShaderModuleCreateInfo *inline_info; /* A module whose distances were already taken out at creation. */ bool stripped_module; + struct spirv_code capped; }; static void find_stage_code(struct device *dev, const VkPipelineShaderStageCreateInfo *stage, struct stage_code *code) @@ -86,9 +102,16 @@ static void find_stage_code(struct device *dev, const VkPipelineShaderStageCreat memset(code, 0, sizeof(*code)); for (const VkBaseInStructure *s = stage->pNext; s; s = s->pNext) { if (s->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO) { - code->inline_info = (VkShaderModuleCreateInfo *)s; + code->inline_info = (const VkShaderModuleCreateInfo *)s; code->words = code->inline_info->pCode; code->count = code->inline_info->codeSize / sizeof(uint32_t); + if (spirv_cap_version(code->words, code->count, &code->capped)) { + log_spirv_version("lowered to 1.3", code->words, code->count); + code->words = code->capped.words; + code->count = code->capped.count; + } else if (spirv_version(code->words, code->count) > 0x00010300u) { + log_spirv_version("left as it is", code->words, code->count); + } return; } } @@ -104,6 +127,15 @@ static void find_stage_code(struct device *dev, const VkPipelineShaderStageCreat } } +union stage_link { + VkBaseInStructure base; + VkDebugUtilsObjectNameInfoEXT name; + VkPipelineRobustnessCreateInfo robustness; + VkPipelineShaderStageModuleIdentifierCreateInfoEXT identifier; + VkPipelineShaderStageRequiredSubgroupSizeCreateInfo subgroup; + VkShaderModuleValidationCacheCreateInfoEXT validation_cache; +}; + struct pipeline_rewrite { VkPipelineRasterizationStateCreateInfo rasterization; VkPipelineColorBlendStateCreateInfo blend; @@ -116,12 +148,71 @@ struct pipeline_rewrite { struct spirv_code code[MAX_STAGES]; struct spirv_code single[MAX_STAGES]; VkShaderModule temporary[MAX_STAGES]; - /* Rewritten where they are, when they are not first in their stage's chain. */ - VkShaderModuleCreateInfo *in_place[MAX_STAGES]; - const uint32_t *in_place_code[MAX_STAGES]; - size_t in_place_size[MAX_STAGES]; + union stage_link links[MAX_STAGES][MAX_LINKS]; }; +static size_t link_size(VkStructureType type) +{ + switch (type) { + case VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT: + return sizeof(VkDebugUtilsObjectNameInfoEXT); + case VK_STRUCTURE_TYPE_PIPELINE_ROBUSTNESS_CREATE_INFO: + return sizeof(VkPipelineRobustnessCreateInfo); + case VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_MODULE_IDENTIFIER_CREATE_INFO_EXT: + return sizeof(VkPipelineShaderStageModuleIdentifierCreateInfoEXT); + case VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO: + return sizeof(VkPipelineShaderStageRequiredSubgroupSizeCreateInfo); + case VK_STRUCTURE_TYPE_SHADER_MODULE_VALIDATION_CACHE_CREATE_INFO_EXT: + return sizeof(VkShaderModuleValidationCacheCreateInfoEXT); + default: + return 0; + } +} + +static bool link_inline_code(VkPipelineShaderStageCreateInfo *stage, struct pipeline_rewrite *rw, + const struct stage_code *code, uint32_t i) +{ + union stage_link *links = rw->links[i]; + const VkBaseInStructure **next = (const VkBaseInStructure **)&stage->pNext; + uint32_t used = 0; + for (const VkBaseInStructure *s = stage->pNext; s != (const VkBaseInStructure *)code->inline_info; + s = s->pNext) { + size_t size = link_size(s->sType); + if (!size || used == MAX_LINKS) + return false; + memcpy(&links[used], s, size); + *next = &links[used].base; + next = (const VkBaseInStructure **)&links[used].base.pNext; + used++; + } + rw->modules[i] = *code->inline_info; + rw->modules[i].pCode = rw->code[i].words; + rw->modules[i].codeSize = rw->code[i].count * sizeof(uint32_t); + *next = (const VkBaseInStructure *)&rw->modules[i]; + return true; +} + +static void use_stage_code(struct device *dev, VkPipelineShaderStageCreateInfo *stage, struct pipeline_rewrite *rw, + const struct stage_code *code, uint32_t i) +{ + const struct spirv_code *out = &rw->code[i]; + if (code->inline_info) { + const void *app_chain = stage->pNext; + if (!link_inline_code(stage, rw, code, i)) { + stage->pNext = app_chain; + layer_log("could not rewrite a pipeline stage's inline shader code"); + } + } else { + VkShaderModuleCreateInfo module_info = { + .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, + .codeSize = out->count * sizeof(uint32_t), + .pCode = out->words, + }; + if (dev->CreateShaderModule(dev->handle, &module_info, NULL, &rw->temporary[i]) == VK_SUCCESS) + stage->module = rw->temporary[i]; + } +} + static void use_code(struct device *dev, VkGraphicsPipelineCreateInfo *info, struct pipeline_rewrite *rw, const struct stage_code *code, uint32_t i) { @@ -129,27 +220,7 @@ static void use_code(struct device *dev, VkGraphicsPipelineCreateInfo *info, str memcpy(rw->stages, info->pStages, info->stageCount * sizeof(*rw->stages)); info->pStages = rw->stages; } - const struct spirv_code *out = &rw->code[i]; - if (code->inline_info && rw->stages[i].pNext == code->inline_info) { - rw->modules[i] = *code->inline_info; - rw->modules[i].pCode = out->words; - rw->modules[i].codeSize = out->count * sizeof(uint32_t); - rw->stages[i].pNext = &rw->modules[i]; - } else if (code->inline_info) { - rw->in_place[i] = code->inline_info; - rw->in_place_code[i] = code->inline_info->pCode; - rw->in_place_size[i] = code->inline_info->codeSize; - code->inline_info->pCode = out->words; - code->inline_info->codeSize = out->count * sizeof(uint32_t); - } else { - VkShaderModuleCreateInfo module_info = { - .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, - .codeSize = out->count * sizeof(uint32_t), - .pCode = out->words, - }; - if (dev->CreateShaderModule(dev->handle, &module_info, NULL, &rw->temporary[i]) == VK_SUCCESS) - rw->stages[i].module = rw->temporary[i]; - } + use_stage_code(dev, &rw->stages[i], rw, code, i); } static int stage_index(const VkGraphicsPipelineCreateInfo *info, VkShaderStageFlagBits stage) @@ -174,6 +245,7 @@ static void rewrite_shaders(struct device *dev, VkGraphicsPipelineCreateInfo *in struct stage_code code[MAX_STAGES]; bool uses[MAX_STAGES]; bool any = false; + bool distances = (dev->emulated & GAPS_SHADER) != 0; for (uint32_t i = 0; i < n; i++) { find_stage_code(dev, &info->pStages[i], &code[i]); if ((dev->emulated & GAP_DUAL_SRC_BLEND) && code[i].inline_info && @@ -185,40 +257,40 @@ static void rewrite_shaders(struct device *dev, VkGraphicsPipelineCreateInfo *in layer_log("could not take the second blend source out of a pipeline's shader"); } } - uses[i] = (dev->emulated & GAPS_SHADER) && code[i].words && spirv_uses_distances(code[i].words, code[i].count); - any |= uses[i] || rw->single[i].words; + uses[i] = distances && code[i].words && spirv_uses_distances(code[i].words, code[i].count); + any |= uses[i]; } - if (!any) - return; - int producer = stage_index(info, VK_SHADER_STAGE_GEOMETRY_BIT); - if (producer < 0) - producer = stage_index(info, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT); - if (producer < 0) - producer = stage_index(info, VK_SHADER_STAGE_VERTEX_BIT); - int consumer = stage_index(info, VK_SHADER_STAGE_FRAGMENT_BIT); - bool emulate = (dev->emulated & GAP_CLIP_DISTANCE) && producer >= 0 && consumer >= 0 && uses[producer] && - code[consumer].words; - for (uint32_t i = 0; i < n && emulate; i++) { - if ((int)i != producer && (int)i != consumer && uses[i]) - emulate = false; - } - if (emulate) { - struct clip_info produced, consumed; - spirv_clip_info(code[producer].words, code[producer].count, CLIP_PRODUCER, &produced); - spirv_clip_info(code[consumer].words, code[consumer].count, CLIP_CONSUMER, &consumed); - uint32_t location = produced.locations_used > consumed.locations_used ? produced.locations_used - : consumed.locations_used; - emulate = produced.has_clip && location != UINT32_MAX && - location + produced.clip_count <= dev->max_varying_locations && - spirv_emulate_clip(code[producer].words, code[producer].count, CLIP_PRODUCER, location, - produced.clip_count, &rw->code[producer]) && - spirv_emulate_clip(code[consumer].words, code[consumer].count, CLIP_CONSUMER, location, - produced.clip_count, &rw->code[consumer]); - if (!emulate) { - free(rw->code[producer].words); - free(rw->code[consumer].words); - rw->code[producer] = rw->code[consumer] = (struct spirv_code){0}; + if (any) { + int producer = stage_index(info, VK_SHADER_STAGE_GEOMETRY_BIT); + if (producer < 0) + producer = stage_index(info, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT); + if (producer < 0) + producer = stage_index(info, VK_SHADER_STAGE_VERTEX_BIT); + int consumer = stage_index(info, VK_SHADER_STAGE_FRAGMENT_BIT); + bool emulate = (dev->emulated & GAP_CLIP_DISTANCE) && producer >= 0 && consumer >= 0 && uses[producer] && + code[consumer].words; + for (uint32_t i = 0; i < n && emulate; i++) { + if ((int)i != producer && (int)i != consumer && uses[i]) + emulate = false; + } + if (emulate) { + struct clip_info produced, consumed; + spirv_clip_info(code[producer].words, code[producer].count, CLIP_PRODUCER, &produced); + spirv_clip_info(code[consumer].words, code[consumer].count, CLIP_CONSUMER, &consumed); + uint32_t location = produced.locations_used > consumed.locations_used ? produced.locations_used + : consumed.locations_used; + emulate = produced.has_clip && location != UINT32_MAX && + location + produced.clip_count <= dev->max_varying_locations && + spirv_emulate_clip(code[producer].words, code[producer].count, CLIP_PRODUCER, location, + produced.clip_count, &rw->code[producer]) && + spirv_emulate_clip(code[consumer].words, code[consumer].count, CLIP_CONSUMER, location, + produced.clip_count, &rw->code[consumer]); + if (!emulate) { + free(rw->code[producer].words); + free(rw->code[consumer].words); + rw->code[producer] = rw->code[consumer] = (struct spirv_code){0}; + } } } @@ -231,8 +303,13 @@ static void rewrite_shaders(struct device *dev, VkGraphicsPipelineCreateInfo *in rw->code[i] = rw->single[i]; rw->single[i] = (struct spirv_code){0}; } + if (!rw->code[i].words && code[i].capped.words) { + rw->code[i] = code[i].capped; + code[i].capped.words = NULL; + } if (rw->code[i].words) use_code(dev, info, rw, &code[i], i); + free(code[i].capped.words); } } @@ -329,8 +406,7 @@ static void rewrite_pipeline(struct device *dev, VkGraphicsPipelineCreateInfo *i if (rw->attachments) info->pColorBlendState = &rw->blend; } - if (dev->emulated & (GAPS_SHADER | GAP_DUAL_SRC_BLEND)) - rewrite_shaders(dev, info, rw); + rewrite_shaders(dev, info, rw); } static void undo_rewrite(struct device *dev, struct pipeline_rewrite *rw) @@ -338,10 +414,6 @@ static void undo_rewrite(struct device *dev, struct pipeline_rewrite *rw) if (rw->clip_prev) rw->clip_prev->pNext = rw->clip_node; for (uint32_t i = 0; i < MAX_STAGES; i++) { - if (rw->in_place[i]) { - rw->in_place[i]->pCode = rw->in_place_code[i]; - rw->in_place[i]->codeSize = rw->in_place_size[i]; - } if (rw->temporary[i] != VK_NULL_HANDLE) dev->DestroyShaderModule(dev->handle, rw->temporary[i], NULL); free(rw->code[i].words); @@ -355,8 +427,15 @@ VKAPI_ATTR VkResult VKAPI_CALL CreateGraphicsPipelines(VkDevice device, VkPipeli const VkAllocationCallbacks *allocator, VkPipeline *pipelines) { struct device *dev = device_from_handle(device); - VkGraphicsPipelineCreateInfo *copies = malloc(count * sizeof(*copies)); + VkGraphicsPipelineCreateInfo *copies = calloc(count, sizeof(*copies)); struct pipeline_rewrite *rewrites = calloc(count, sizeof(*rewrites)); + if (count && (!copies || !rewrites)) { + for (uint32_t i = 0; i < count; i++) + pipelines[i] = VK_NULL_HANDLE; + free(copies); + free(rewrites); + return VK_ERROR_OUT_OF_HOST_MEMORY; + } for (uint32_t i = 0; i < count; i++) { copies[i] = infos[i]; rewrite_pipeline(dev, &copies[i], &rewrites[i]); @@ -369,6 +448,37 @@ VKAPI_ATTR VkResult VKAPI_CALL CreateGraphicsPipelines(VkDevice device, VkPipeli return result; } +VKAPI_ATTR VkResult VKAPI_CALL CreateComputePipelines(VkDevice device, VkPipelineCache cache, uint32_t count, + const VkComputePipelineCreateInfo *infos, + const VkAllocationCallbacks *allocator, VkPipeline *pipelines) +{ + struct device *dev = device_from_handle(device); + VkComputePipelineCreateInfo *copies = calloc(count, sizeof(*copies)); + struct pipeline_rewrite *rewrites = calloc(count, sizeof(*rewrites)); + if (count && (!copies || !rewrites)) { + for (uint32_t i = 0; i < count; i++) + pipelines[i] = VK_NULL_HANDLE; + free(copies); + free(rewrites); + return VK_ERROR_OUT_OF_HOST_MEMORY; + } + for (uint32_t i = 0; i < count; i++) { + copies[i] = infos[i]; + struct stage_code code; + find_stage_code(dev, &copies[i].stage, &code); + if (code.capped.words) { + rewrites[i].code[0] = code.capped; + use_stage_code(dev, &copies[i].stage, &rewrites[i], &code, 0); + } + } + VkResult result = dev->CreateComputePipelines(device, cache, count, copies, allocator, pipelines); + for (uint32_t i = 0; i < count; i++) + undo_rewrite(dev, &rewrites[i]); + free(rewrites); + free(copies); + return result; +} + /* The driver has one viewport and one scissor; anything past the first is left out. */ VKAPI_ATTR void VKAPI_CALL CmdSetViewport(VkCommandBuffer cmd, uint32_t first, uint32_t count, const VkViewport *viewports) diff --git a/tools/venus/layer/spirv.c b/tools/venus/layer/spirv.c index 9a9794d9ce..5265adde61 100644 --- a/tools/venus/layer/spirv.c +++ b/tools/venus/layer/spirv.c @@ -15,6 +15,7 @@ #define OPCODE(word) ((word) & 0xffffu) #define LENGTH(word) ((word) >> 16) +#define VERSION_1_3 0x00010300u #define VERSION_1_4 0x00010400u struct words { @@ -103,6 +104,7 @@ static bool declares_result_second(uint32_t op) case SpvOpUndef: case SpvOpVariable: case SpvOpFunction: + case SpvOpFunctionParameter: return true; default: return false; @@ -875,3 +877,300 @@ bool spirv_emulate_clip(const uint32_t *words, size_t count, enum clip_role role unload(&m); return done; } + +struct newer_feature { + uint32_t value; + const char *extension; + const char *alternative; +}; + +#define PHYSICAL_STORAGE_BUFFER "SPV_EXT_physical_storage_buffer", "SPV_KHR_physical_storage_buffer" + +static const struct newer_feature newer_opcodes[] = { + {SpvOpCopyLogical, NULL, NULL}, + {SpvOpPtrEqual, NULL, NULL}, + {SpvOpPtrNotEqual, NULL, NULL}, + {SpvOpPtrDiff, NULL, NULL}, + {SpvOpDemoteToHelperInvocation, "SPV_EXT_demote_to_helper_invocation", NULL}, + {SpvOpSDot, "SPV_KHR_integer_dot_product", NULL}, + {SpvOpUDot, "SPV_KHR_integer_dot_product", NULL}, + {SpvOpSUDot, "SPV_KHR_integer_dot_product", NULL}, + {SpvOpSDotAccSat, "SPV_KHR_integer_dot_product", NULL}, + {SpvOpUDotAccSat, "SPV_KHR_integer_dot_product", NULL}, + {SpvOpSUDotAccSat, "SPV_KHR_integer_dot_product", NULL}, + {SpvOpDecorateString, "SPV_GOOGLE_decorate_string", "SPV_GOOGLE_hlsl_functionality1"}, + {SpvOpMemberDecorateString, "SPV_GOOGLE_decorate_string", "SPV_GOOGLE_hlsl_functionality1"}, +}; + +static const struct newer_feature newer_capabilities[] = { + {SpvCapabilityShaderLayer, NULL, NULL}, + {SpvCapabilityShaderViewportIndex, NULL, NULL}, + {SpvCapabilityUniformDecoration, NULL, NULL}, + {SpvCapabilityStorageBuffer8BitAccess, "SPV_KHR_8bit_storage", NULL}, + {SpvCapabilityUniformAndStorageBuffer8BitAccess, "SPV_KHR_8bit_storage", NULL}, + {SpvCapabilityStoragePushConstant8, "SPV_KHR_8bit_storage", NULL}, + {SpvCapabilityDenormPreserve, "SPV_KHR_float_controls", NULL}, + {SpvCapabilityDenormFlushToZero, "SPV_KHR_float_controls", NULL}, + {SpvCapabilitySignedZeroInfNanPreserve, "SPV_KHR_float_controls", NULL}, + {SpvCapabilityRoundingModeRTE, "SPV_KHR_float_controls", NULL}, + {SpvCapabilityRoundingModeRTZ, "SPV_KHR_float_controls", NULL}, + {SpvCapabilityShaderNonUniform, "SPV_EXT_descriptor_indexing", NULL}, + {SpvCapabilityRuntimeDescriptorArray, "SPV_EXT_descriptor_indexing", NULL}, + {SpvCapabilityInputAttachmentArrayDynamicIndexing, "SPV_EXT_descriptor_indexing", NULL}, + {SpvCapabilityUniformTexelBufferArrayDynamicIndexing, "SPV_EXT_descriptor_indexing", NULL}, + {SpvCapabilityStorageTexelBufferArrayDynamicIndexing, "SPV_EXT_descriptor_indexing", NULL}, + {SpvCapabilityUniformBufferArrayNonUniformIndexing, "SPV_EXT_descriptor_indexing", NULL}, + {SpvCapabilitySampledImageArrayNonUniformIndexing, "SPV_EXT_descriptor_indexing", NULL}, + {SpvCapabilityStorageBufferArrayNonUniformIndexing, "SPV_EXT_descriptor_indexing", NULL}, + {SpvCapabilityStorageImageArrayNonUniformIndexing, "SPV_EXT_descriptor_indexing", NULL}, + {SpvCapabilityInputAttachmentArrayNonUniformIndexing, "SPV_EXT_descriptor_indexing", NULL}, + {SpvCapabilityUniformTexelBufferArrayNonUniformIndexing, "SPV_EXT_descriptor_indexing", NULL}, + {SpvCapabilityStorageTexelBufferArrayNonUniformIndexing, "SPV_EXT_descriptor_indexing", NULL}, + {SpvCapabilityVulkanMemoryModel, "SPV_KHR_vulkan_memory_model", NULL}, + {SpvCapabilityVulkanMemoryModelDeviceScope, "SPV_KHR_vulkan_memory_model", NULL}, + {SpvCapabilityPhysicalStorageBufferAddresses, PHYSICAL_STORAGE_BUFFER}, + {SpvCapabilityDemoteToHelperInvocation, "SPV_EXT_demote_to_helper_invocation", NULL}, + {SpvCapabilityDotProductInputAll, "SPV_KHR_integer_dot_product", NULL}, + {SpvCapabilityDotProductInput4x8Bit, "SPV_KHR_integer_dot_product", NULL}, + {SpvCapabilityDotProductInput4x8BitPacked, "SPV_KHR_integer_dot_product", NULL}, + {SpvCapabilityDotProduct, "SPV_KHR_integer_dot_product", NULL}, +}; + +static const struct newer_feature newer_decorations[] = { + {SpvDecorationUniformId, NULL, NULL}, + {SpvDecorationNoSignedWrap, "SPV_KHR_no_integer_wrap_decoration", NULL}, + {SpvDecorationNoUnsignedWrap, "SPV_KHR_no_integer_wrap_decoration", NULL}, + {SpvDecorationNonUniform, "SPV_EXT_descriptor_indexing", NULL}, + {SpvDecorationRestrictPointer, PHYSICAL_STORAGE_BUFFER}, + {SpvDecorationAliasedPointer, PHYSICAL_STORAGE_BUFFER}, + {SpvDecorationCounterBuffer, "SPV_GOOGLE_hlsl_functionality1", NULL}, + {SpvDecorationUserSemantic, "SPV_GOOGLE_hlsl_functionality1", NULL}, +}; + +#define NEWER_LOOP_CONTROLS \ + (SpvLoopControlMinIterationsMask | SpvLoopControlMaxIterationsMask | SpvLoopControlIterationMultipleMask | \ + SpvLoopControlPeelCountMask | SpvLoopControlPartialCountMask) +#define NEWER_IMAGE_OPERANDS \ + (SpvImageOperandsSignExtendMask | SpvImageOperandsZeroExtendMask | SpvImageOperandsNontemporalMask) + +static bool declares_extension(const struct module *m, const char *name) +{ + if (!name) + return false; + size_t size = strlen(name) + 1; + for (size_t i = 5; i < m->first_declaration; i += LENGTH(m->w[i])) { + uint32_t length = LENGTH(m->w[i]); + if (OPCODE(m->w[i]) == SpvOpExtension && (length - 1) * sizeof(uint32_t) >= size && + !memcmp(&m->w[i + 1], name, size)) + return true; + } + return false; +} + +static bool names_prefix(const uint32_t *words, uint32_t count, const char *prefix) +{ + size_t size = strlen(prefix); + return count * sizeof(uint32_t) > size && !memcmp(words, prefix, size); +} + +static bool available_in_1_3(const struct module *m, const struct newer_feature *features, size_t count, + uint32_t value) +{ + for (size_t i = 0; i < count; i++) { + if (features[i].value == value) + return declares_extension(m, features[i].extension) || declares_extension(m, features[i].alternative); + } + return true; +} + +#define AVAILABLE(m, table, value) available_in_1_3(m, table, sizeof(table) / sizeof(table[0]), value) + +static bool declares_capability(const struct module *m, uint32_t capability) +{ + for (size_t i = 5; i < m->first_declaration; i += LENGTH(m->w[i])) { + if (OPCODE(m->w[i]) == SpvOpCapability && LENGTH(m->w[i]) >= 2 && m->w[i + 1] == capability) + return true; + } + return false; +} + +static uint32_t image_operands_at(uint32_t op) +{ + switch (op) { + case SpvOpImageWrite: + return 4; + case SpvOpImageSampleImplicitLod: + case SpvOpImageSampleExplicitLod: + case SpvOpImageSampleProjImplicitLod: + case SpvOpImageSampleProjExplicitLod: + case SpvOpImageFetch: + case SpvOpImageRead: + case SpvOpImageSparseSampleImplicitLod: + case SpvOpImageSparseSampleExplicitLod: + case SpvOpImageSparseSampleProjImplicitLod: + case SpvOpImageSparseSampleProjExplicitLod: + case SpvOpImageSparseFetch: + case SpvOpImageSparseRead: + return 5; + case SpvOpImageSampleDrefImplicitLod: + case SpvOpImageSampleDrefExplicitLod: + case SpvOpImageSampleProjDrefImplicitLod: + case SpvOpImageSampleProjDrefExplicitLod: + case SpvOpImageGather: + case SpvOpImageDrefGather: + case SpvOpImageSparseSampleDrefImplicitLod: + case SpvOpImageSparseSampleDrefExplicitLod: + case SpvOpImageSparseSampleProjDrefImplicitLod: + case SpvOpImageSparseSampleProjDrefExplicitLod: + case SpvOpImageSparseGather: + case SpvOpImageSparseDrefGather: + return 6; + default: + return 0; + } +} + +static uint32_t memory_access_words(uint32_t mask) +{ + uint32_t words = 1; + if (mask & SpvMemoryAccessAlignedMask) + words++; + if (mask & SpvMemoryAccessMakePointerAvailableMask) + words++; + if (mask & SpvMemoryAccessMakePointerVisibleMask) + words++; + return words; +} + +static bool selects_scalar_vector_or_pointer(const struct module *m, uint32_t type) +{ + size_t d = definition(m, type); + if (!d) + return false; + switch (OPCODE(m->w[d])) { + case SpvOpTypeBool: + case SpvOpTypeInt: + case SpvOpTypeFloat: + case SpvOpTypeVector: + case SpvOpTypePointer: + return true; + default: + return false; + } +} + +static bool valid_in_1_3(const struct module *m, size_t i) +{ + uint32_t op = OPCODE(m->w[i]); + uint32_t length = LENGTH(m->w[i]); + if (!AVAILABLE(m, newer_opcodes, op)) + return false; + switch (op) { + case SpvOpMemoryModel: + return length >= 3 && m->w[i + 2] == SpvMemoryModelGLSL450; + case SpvOpCapability: + return length >= 2 && AVAILABLE(m, newer_capabilities, m->w[i + 1]); + case SpvOpExecutionModeId: + return length >= 3 && m->w[i + 2] != SpvExecutionModeLocalSizeId; + case SpvOpDecorate: + case SpvOpDecorateId: + case SpvOpDecorateString: + if (length < 3 || !AVAILABLE(m, newer_decorations, m->w[i + 2])) + return false; + if (m->w[i + 2] == SpvDecorationNonWritable) { + size_t d = definition(m, m->w[i + 1]); + if (!d || (OPCODE(m->w[d]) == SpvOpVariable && + (LENGTH(m->w[d]) < 4 || m->w[d + 3] == SpvStorageClassPrivate || + m->w[d + 3] == SpvStorageClassFunction))) + return false; + if (OPCODE(m->w[d]) == SpvOpFunctionParameter) { + size_t type = LENGTH(m->w[d]) >= 3 ? definition(m, m->w[d + 1]) : 0; + if (!type || OPCODE(m->w[type]) != SpvOpTypePointer || LENGTH(m->w[type]) < 4 || + m->w[type + 2] == SpvStorageClassPrivate || m->w[type + 2] == SpvStorageClassFunction) + return false; + } + } + return true; + case SpvOpMemberDecorate: + case SpvOpMemberDecorateString: + return length >= 4 && AVAILABLE(m, newer_decorations, m->w[i + 3]); + case SpvOpLoopMerge: + return length >= 4 && !(m->w[i + 3] & NEWER_LOOP_CONTROLS); + case SpvOpSelect: + return length >= 6 && selects_scalar_vector_or_pointer(m, m->w[i + 1]); + case SpvOpSpecConstantOp: + return length >= 5 && (m->w[i + 3] != SpvOpUConvert || + declares_capability(m, SpvCapabilityKernel) || + declares_extension(m, "SPV_AMD_gpu_shader_int16")); + case SpvOpExtInstImport: + return length >= 3 && (!names_prefix(&m->w[i + 2], length - 2, "NonSemantic.") || + declares_extension(m, "SPV_KHR_non_semantic_info")); + case SpvOpCopyMemory: + case SpvOpCopyMemorySized: { + uint32_t at = op == SpvOpCopyMemory ? 3 : 4; + return length <= at || at + memory_access_words(m->w[i + at]) >= length; + } + default: { + uint32_t at = image_operands_at(op); + return !at || length <= at || !(m->w[i + at] & NEWER_IMAGE_OPERANDS); + } + } +} + +static bool variable_storage(const struct module *m, uint32_t id, uint32_t *storage) +{ + size_t d = definition(m, id); + if (!d || OPCODE(m->w[d]) != SpvOpVariable) + return false; + *storage = m->w[d + 3]; + return true; +} + +static void trim_entry_interfaces(struct module *m) +{ + for (size_t i = 5; i < m->first_declaration; i += LENGTH(m->w[i])) { + if (OPCODE(m->w[i]) != SpvOpEntryPoint) + continue; + uint32_t length = LENGTH(m->w[i]); + if (length < 4) + continue; + uint32_t first = 3 + string_words(&m->w[i + 3], length - 3); + for (uint32_t k = first; k < length; k++) { + uint32_t id = m->w[i + k]; + uint32_t storage; + if (id < m->original_bound && variable_storage(m, id, &storage) && + storage != SpvStorageClassInput && storage != SpvStorageClassOutput) + m->interface_remove[id] = 1; + } + } +} +uint32_t spirv_version(const uint32_t *words, size_t count) +{ + if (count < 5 || words[0] != SpvMagicNumber) + return 0; + return words[1]; +} + +bool spirv_cap_version(const uint32_t *words, size_t count, struct spirv_code *out) +{ + if (count < 5 || words[0] != SpvMagicNumber || words[1] <= VERSION_1_3) + return false; + struct module m; + if (!load(&m, words, count)) + return false; + for (size_t i = 5; i < m.count; i += LENGTH(m.w[i])) { + if (!valid_in_1_3(&m, i)) { + unload(&m); + return false; + } + } + for (size_t i = 5; i < m.count; i += LENGTH(m.w[i])) { + if (OPCODE(m.w[i]) == SpvOpTerminateInvocation) + m.w[i] = (LENGTH(m.w[i]) << 16) | SpvOpKill; + } + trim_entry_interfaces(&m); + m.w[1] = VERSION_1_3; + bool done = finish(&m, out); + unload(&m); + return done; +} From 9cfab884d514b9bcdbc9e947bab900b5eff93abf Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:16:49 -0500 Subject: [PATCH 026/141] feat(session): the DroidDeck menu is a bottom-screen mode, and the controller stays with the game (#3001) --- .../com/droiddeck/launcher/SessionActivity.kt | 212 ++++++++++++++---- .../droiddeck/launcher/input/DualScreen.kt | 8 + .../launcher/input/SecondScreenMode.kt | 14 +- .../launcher/session/SessionPrefs.kt | 6 + .../launcher/session/SessionState.kt | 1 + .../launcher/session/SettingsReset.kt | 2 +- .../droiddeck/launcher/ui/BottomScreenBar.kt | 7 +- .../launcher/ui/SecondScreenPresentation.kt | 2 +- .../droiddeck/launcher/ui/SessionOverlay.kt | 23 +- app/src/main/res/values/strings.xml | 1 + .../launcher/input/DualScreenTest.kt | 28 +++ .../launcher/input/SecondScreenModeTest.kt | 57 ++--- .../input/SecondScreenProfileMigrationTest.kt | 17 +- docs/agent-control.md | 13 ++ tools/droiddeckctl | 77 ++++++- tools/tests/test_droiddeckctl_gamepad.py | 91 ++++++++ 16 files changed, 446 insertions(+), 113 deletions(-) create mode 100644 tools/tests/test_droiddeckctl_gamepad.py diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 99408071f7..7e6ad0376d 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -244,9 +244,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde override fun key(code: Int, down: Boolean) { heldKeys.set(4, code, down) } override fun button(code: Int, down: Boolean) { heldButtons.set(4, code, down) } override fun pointer(dx: Float, dy: Float) { - if (Looper.myLooper() == Looper.getMainLooper()) moveInputPointer(dx, dy) - else uiHandler.post { - if (resumed && !SessionState.suspended && !pipUi && !drawerOpen && !inputSettingsOpen) + if (Looper.myLooper() == Looper.getMainLooper()) { + if (!menuOwnsController) moveInputPointer(dx, dy) + } else uiHandler.post { + if (resumed && !SessionState.suspended && !pipUi && !menuOwnsController && !inputSettingsOpen) moveInputPointer(dx, dy) } } @@ -545,6 +546,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde drawerOpenState = value if (!value && drawerDocked) closeDockedMenu() } + private val dockedMenuIdle: Boolean get() = com.droiddeck.launcher.input.DualScreen.menuIdleOnBottom(drawerOpen, drawerDocked, drawerPinned, dockedMenuController) + private val dockedTouchOnly: Boolean get() = drawerOpen && drawerDocked && !dockedMenuController + private val menuOwnsController: Boolean get() = com.droiddeck.launcher.input.DualScreen.menuOwnsController(drawerOpen, drawerDocked, dockedMenuController) private var quitFrom by mutableStateOf(null) private var quitFlooded = false private var leaving by mutableStateOf(false) @@ -588,6 +592,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var drawerPage by mutableStateOf(SessionDrawerPage.CONTROLLER) private var drawerControllerActive by mutableStateOf(false) 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 backActionsInverted by mutableStateOf(false) private var backDoubleTapMs by mutableStateOf(500) private var lowLatency by mutableStateOf(true) @@ -838,6 +844,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde SessionState.programArgs = intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS)?.toList().orEmpty() SessionEvents.begin(this, mode, SessionPaths.label(mode, intent.getStringExtra(SessionService.EXTRA_PROGRAM))) SessionState.secondScreenAutoOpened = false + SessionState.bottomMenu = false SessionState.secondScreenProvisional = false SessionState.secondScreenAutomatic = false SessionState.gameOnBottom = false @@ -1109,6 +1116,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde when { ::loading.isInitialized && loading.ended -> finish() inputSettingsOpen -> inputSettingsOpen = false + dockedTouchOnly -> routeBackAction() drawerOpen -> drawerOpen = false achievementsOpen -> closeAchievements() pcKeyboardOpen -> pcKeyboardOpen = false @@ -1137,6 +1145,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } } val uiPointer = appUiOwnsPointer() + val cursorHidden = cursorHiddenByUi() androidx.compose.runtime.SideEffect { com.droiddeck.launcher.glasses.GlassesMenuMirror.setSessionMenuVisible(this@SessionActivity, (drawerOpen || achievementsOpen || pcKeyboardOpen) && !pipUi && steamVrStatus != SteamVr.Status.RUNNING) @@ -1187,7 +1196,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } } else { com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) { - CursorOverlay({ cursorPos }, cursorVisible && (!uiPointer || onlyPcKeyboardOpen()) && !bottomOutputActive, + CursorOverlay({ cursorPos }, cursorVisible && (!cursorHidden || onlyPcKeyboardOpen()) && !bottomOutputActive, resources.displayMetrics.density, cursorImage, cursorHotX, cursorHotY, cursorImageScale) if (memoryHud.text.isNotEmpty()) HudText(memoryHud.text, hudColor, hudOpacity) @@ -1304,9 +1313,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde runCatching { com.droiddeck.launcher.session.TelemetryOutput.applyAutomatic(this@SessionActivity, nextGame) } } } - LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, inputSettingsOpen, pipUi, SessionState.suspended, resumed, appTextFocus) { + LaunchedEffect(drawerOpen, menuOwnsController, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, inputSettingsOpen, pipUi, SessionState.suspended, resumed, appTextFocus) { updateOnScreenControls() - padBridge?.setInputEnabled(resumed && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen && !pipUi && !appTextFocus && !SessionState.suspended) + padBridge?.setInputEnabled(resumed && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen && !pipUi && !appTextFocus && !SessionState.suspended) if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || inputSettingsOpen || pipUi || appTextFocus || SessionState.suspended) { backQamInput.cancel() com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this@SessionActivity) @@ -1358,13 +1367,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde onDismiss = { gestureSettingsOpen = false }, onSaved = { gestureSettingsOpen = false; refreshGestureConfig() }, ) - androidx.compose.runtime.LaunchedEffect(drawerOpen) { + androidx.compose.runtime.LaunchedEffect(drawerOpen, menuOwnsController) { if (drawerOpen) { syncLossless() - releasePads() - androidx.compose.runtime.withFrameNanos { } - val requested = focusDrawer() - Log.i(TAG, "drawer root focus requested=$requested docked=$drawerDocked") + if (menuOwnsController) { + releasePads() + androidx.compose.runtime.withFrameNanos { } + val requested = focusDrawer() + Log.i(TAG, "drawer root focus requested=$requested docked=$drawerDocked") + } else { + releaseDrawerDirection() + } } else { releaseDrawerDirection() } @@ -1423,7 +1436,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (!SessionState.manualPause && !SessionState.suspended) pauseAnimated = false } SessionPausedOverlay( - suspended = SessionState.suspended && (!autoResume || SessionState.resumeFailed || SessionState.manualPause), + suspended = (SessionState.suspended || SessionState.manualPause) && (!autoResume || SessionState.resumeFailed || SessionState.manualPause), engaged = SessionState.resumeRequested || SessionState.resuming, failures = SessionState.resumeFailures, frame = pausedFrame, @@ -1761,6 +1774,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde SessionPrefs.setBackHold(this@SessionActivity, on) backHold = on }, + dockedMenuController = dockedMenuController, + onDockedMenuController = { on -> + SessionPrefs.setDockedMenuController(this@SessionActivity, on) + dockedMenuController = on + if (!on && drawerDocked) drawerControllerActive = false + }, backActionsInverted = backActionsInverted, backDoubleTapMs = backDoubleTapMs, onBackDoubleTapMs = { ms -> @@ -1829,6 +1848,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde setRelativeMouse(mode) }, onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() }, + onSelectMenuMode = ::pickMenuMode, onSecondScreenMode = { mode -> if (docked) drawerOpen = false pickSecondScreenMode(mode) @@ -1852,6 +1872,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde pipAutoEnter = pipAutoEnter, onPip = { pip.enter() }, onPause = ::pauseNow, + paused = SessionState.suspended || SessionState.manualPause, + onResume = { SessionService.resume(this@SessionActivity) }, + orientation = sessionOrientation, + onOrientation = { value -> + SessionPrefs.setOrientation(this@SessionActivity, value) + sessionOrientation = value + applyFollowOrientation(resources.configuration) + }, onPipAutoEnter = { on -> SessionPrefs.setPipAutoEnter(this@SessionActivity, on) pipAutoEnter = on @@ -1949,7 +1977,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun sendSteamGuide() { - drawerOpen = false + if (!dockedTouchOnly) drawerOpen = false padBridge?.triggerSteamMenu() } @@ -1996,7 +2024,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun triggerSteamQam() { - drawerOpen = false + if (!dockedTouchOnly) drawerOpen = false padBridge?.triggerQam() } @@ -2085,7 +2113,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun performBackAction(double: Boolean) { val isSteam = SessionState.mode == SessionService.MODE_STEAM val opensQam = isSteam && (double xor backActionsInverted) - if (opensQam) triggerSteamQam() else drawerOpen = !drawerOpen + if (opensQam) triggerSteamQam() else if (!dockedTouchOnly) drawerOpen = !drawerOpen } private fun handleHomeGuideIntent(incoming: Intent?) { @@ -2629,6 +2657,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde oscRearButtons = SessionPrefs.oscRearButtons(this) oscTrackpads = SessionPrefs.oscTrackpads(this) backHold = SessionPrefs.backHold(this) + dockedMenuController = SessionPrefs.dockedMenuController(this) + sessionOrientation = SessionPrefs.orientation(this) backActionsInverted = SessionPrefs.backActionsInverted(this) physicalShortcuts.bindings = PhysicalShortcuts.read(this) backDoubleTapMs = SessionPrefs.backDoubleTapMs(this) @@ -3523,7 +3553,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val steamVolume = SessionState.mode == SessionService.MODE_STEAM && SessionState.running && SessionState.firstFrameSeen && !SessionState.suspended && !ended && - !pipUi && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && + !pipUi && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen && !appTextFocus && window.decorView.hasWindowFocus() if (steamVolume) { val audio = getSystemService(android.media.AudioManager::class.java) @@ -3537,13 +3567,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (penStream.holdsKey(event) || (penSettings.mode != SessionPrefs.PEN_TOUCH && PenStream.isPenKey(event))) return penStream.onKey(event) if (appTextFocus) return super.dispatchKeyEvent(event) if (!pipUi) { - if (physicalInputBindings?.onKey(event, resumed && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && + if (physicalInputBindings?.onKey(event, resumed && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen && !inputSettingsOpen && !gestureSettingsOpen && !SessionState.suspended && !loading.visible) == true) return true if (physicalShortcuts.onKey( event, enabled = resumed && SessionState.running && !SessionState.suspended && - !(drawerOpen && event.keyCode == KeyEvent.KEYCODE_BUTTON_A) && - !(drawerOpen && PhysicalShortcuts.isDrawerNavigationKey(event)) && + !(menuOwnsController && event.keyCode == KeyEvent.KEYCODE_BUTTON_A) && + !(menuOwnsController && PhysicalShortcuts.isDrawerNavigationKey(event)) && (event.deviceId to event.keyCode) !in resumeKeysDown && !(::loading.isInitialized && (loading.visible || loading.ended)) && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen, @@ -3551,12 +3581,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde ) { action -> pendingBackAction?.let(uiHandler::removeCallbacks) pendingBackAction = null - drawerControllerActive = true + if (!dockedMenuIdle) drawerControllerActive = true Log.i(TAG, "physical shortcut ${action.name} device=${event.deviceId} key=${event.keyCode} scan=${event.scanCode}") when (action) { PhysicalShortcuts.Action.STEAM -> sendSteamGuide() PhysicalShortcuts.Action.QAM -> triggerSteamQam() - PhysicalShortcuts.Action.DROIDDECK -> drawerOpen = !drawerOpen + PhysicalShortcuts.Action.DROIDDECK -> if (!dockedTouchOnly) drawerOpen = !drawerOpen } }) return true } @@ -3582,7 +3612,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } } if (mouseBackHandled) return true - val backToQam = !pipUi && !appTextFocus && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && + val backToQam = !pipUi && !appTextFocus && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen && !inputSettingsOpen && !gestureSettingsOpen && SessionState.mode == SessionService.MODE_STEAM && SessionState.running && SessionState.firstFrameSeen && !SessionState.suspended && padBridge?.canHoldQam() == true @@ -3595,12 +3625,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val pad = com.droiddeck.launcher.input.JoyCon.normalize(event) if (pad !== event) return dispatchKeyEvent(pad) val fromController = PadBridge.isControllerKeyEvent(event) - if (fromController && (drawerOpen || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) { + if (fromController && (menuOwnsController || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) { padBridge?.setInputEnabled(false) padBridge?.onKeyEvent(event) } - if (fromController && event.action == KeyEvent.ACTION_DOWN) { - if (drawerOpen && !drawerControllerActive) focusDrawer() + if (fromController && event.action == KeyEvent.ACTION_DOWN && !dockedMenuIdle) { + if (menuOwnsController && !drawerControllerActive) focusDrawer() drawerControllerActive = true } if (fromController && event.keyCode == KeyEvent.KEYCODE_BUTTON_B && ::loading.isInitialized && loading.visible && !loading.ended && !drawerOpen) { @@ -3619,7 +3649,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } val drawerShortcutKey = event.deviceId to event.keyCode if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_SELECT || event.keyCode == KeyEvent.KEYCODE_BUTTON_START) && - ((drawerOpen && SessionState.mode == SessionService.MODE_STEAM) || drawerShortcutKey in drawerShortcutKeysDown)) { + ((menuOwnsController && SessionState.mode == SessionService.MODE_STEAM) || drawerShortcutKey in drawerShortcutKeysDown)) { if (event.action == KeyEvent.ACTION_DOWN) { drawerShortcutKeysDown.add(drawerShortcutKey) if (event.repeatCount == 0) { @@ -3631,7 +3661,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } return true } - if (drawerOpen) { + 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) { drawerPage = sessionDrawerPages(glasses.present) @@ -3701,11 +3731,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean { if (pipUi) return true notePress(event) - if (PadBridge.isControllerMotionEvent(event) && (drawerOpen || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) { + if (PadBridge.isControllerMotionEvent(event) && (menuOwnsController || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) { padBridge?.setInputEnabled(false) padBridge?.onMotionEvent(event) } - if (drawerOpen && PadBridge.isControllerMotionEvent(event)) { + if (menuOwnsController && PadBridge.isControllerMotionEvent(event)) { if (!drawerControllerActive) focusDrawer() drawerControllerActive = true if (event.actionMasked == MotionEvent.ACTION_MOVE && @@ -3882,6 +3912,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun closeDockedMenu() { + SessionState.bottomMenu = false drawerDocked = false val presentation = secondScreenPresentation ?: return presentation.showMenu(false) @@ -4307,7 +4338,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde ?: if (SessionState.gameOnBottom) bottomGameDisplay()?.displayId else null SessionState.secondScreenAutoOpened = true if (gameDisplay != null && gameDisplay != target.displayId && secondScreenDisplays.any { it.id == gameDisplay }) { - panelMode(openingPanel()) + panelMode(openingSurface()) } else { val selectionChanged = selectedSecondScreenDisplay != target.displayId selectedSecondScreenDisplay = target.displayId @@ -4326,14 +4357,43 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun openingPanel() = SecondScreenMode.opening(SessionPrefs.secondScreenPanel(this, desktopSession), SessionState.deckPad, - bottomPages().isNotEmpty(), com.droiddeck.launcher.session.BottomDesktop.available(), desktopSession) + bottomPages().isNotEmpty(), com.droiddeck.launcher.session.BottomDesktop.available()) + + private fun openingSurface() = openingPanel().takeIf { it != SecondScreenMode.MENU } ?: SecondScreenMode.KEYBOARD_TRACKPAD + + private fun menuShownOnBottom() = drawerDocked && (drawerOpen || drawerPinned) + + private fun pinDockedMenu() { + if (!dockDrawer()) return + drawerLayerOpen = false + if (!openDockedMenu()) return + drawerDocked = true + drawerOpenState = false + drawerPinned = true + updateKeyboardRoute() + } + + private fun showMenuMode() { + dualControlsProvisional = false + selectSecondScreenMode(secondScreenMode.takeIf { it != SecondScreenMode.NONE } ?: SecondScreenMode.KEYBOARD_TRACKPAD) + if (secondScreenMode != SecondScreenMode.NONE) pinDockedMenu() + } + + private fun pickMenuMode() { + typingReturnMode = null + automaticPanel = false + SessionPrefs.setSecondScreenPanel(this, desktopSession, SecondScreenMode.MENU.id) + drawerOpen = true + } private fun settleDualScreenControls() { if (!dualControlsProvisional || pipUi || !started || (::loading.isInitialized && loading.visible)) return dualControlsProvisional = false if (secondScreenMode == SecondScreenMode.NONE) return val wanted = openingPanel() - if (wanted != secondScreenMode) selectSecondScreenMode(wanted) else secondScreenPresentation?.retryTerminal() + if (wanted == SecondScreenMode.MENU) { + if (!menuShownOnBottom()) selectSecondScreenMode(wanted) else secondScreenPresentation?.retryTerminal() + } else if (wanted != secondScreenMode) selectSecondScreenMode(wanted) else secondScreenPresentation?.retryTerminal() } private fun selectSecondScreenDisplay(displayId: Int) { @@ -4354,6 +4414,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde closeSecondScreen(reset = true) return } + if (mode == SecondScreenMode.MENU) { + showMenuMode() + return + } if (secondScreenDisplays.isEmpty()) { panelMode(SecondScreenMode.NONE) return @@ -4370,7 +4434,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun showSecondScreen(requested: SecondScreenMode) { if (pipUi || !started) return - val mode = if (requested == SecondScreenMode.DECK_CONTROLS && !SessionState.deckPad) openingPanel() else requested + val mode = when { + requested == SecondScreenMode.MENU -> + secondScreenMode.takeIf { it != SecondScreenMode.NONE && it != SecondScreenMode.MENU } ?: SecondScreenMode.KEYBOARD_TRACKPAD + requested == SecondScreenMode.DECK_CONTROLS && !SessionState.deckPad -> openingSurface() + else -> requested + } val target = displayManager.getDisplay(selectedSecondScreenDisplay) if (target == null || !target.isValid || (target.flags and Display.FLAG_PRESENTATION) == 0) { closeSecondScreen(reset = false) @@ -4414,7 +4483,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun bottomScreenPicker(mode: SecondScreenMode) = com.droiddeck.launcher.ui.ScreenPicker( com.droiddeck.launcher.ui.secondScreenModes(false, SessionState.deckPad, bottomPages().isNotEmpty(), com.droiddeck.launcher.session.BottomDesktop.available()), - mode, ::pickSecondScreenMode, onMenu = { drawerOpen = true }, + mode, ::pickSecondScreenMode, onMenu = ::pickMenuMode, ) private fun secondScreenPresentation(target: Display) = SecondScreenPresentation( @@ -4840,6 +4909,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun dropDockedDrawer() { + if (drawerDocked && (drawerOpenState || drawerPinned)) SessionState.bottomMenu = true drawerPinned = false if (!drawerDocked) return drawerDocked = false @@ -4858,6 +4928,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (reset) { panelMode(SecondScreenMode.NONE) automaticPanel = false + SessionState.bottomMenu = false } } @@ -5410,8 +5481,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun onlyPcKeyboardOpen(): Boolean = pcKeyboardOpen && !drawerOpen && !achievementsOpen && !inputSettingsOpen && !pipUi && !glassesOutputActive && !touchEditorOpen && !wowChatOnTop - private fun appUiOwnsPointer(): Boolean = - drawerOpen || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || pipUi || glassesOutputActive || bottomOutputActive || touchEditorOpen || wowChatOnTop + private fun otherUiOwnsPointer(): Boolean = + pcKeyboardOpen || achievementsOpen || inputSettingsOpen || pipUi || glassesOutputActive || bottomOutputActive || touchEditorOpen || wowChatOnTop + + private fun appUiOwnsPointer(): Boolean = drawerOpen || otherUiOwnsPointer() + + /** A touch-only docked menu leaves the game cursor alone, so controller pointer moves stay visible. */ + private fun cursorHiddenByUi(): Boolean = menuOwnsController || otherUiOwnsPointer() private fun applyPlatformPointer(shown: Boolean) { if (!::sessionRoot.isInitialized || !::surfaceView.isInitialized) return @@ -5689,31 +5765,44 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde heldKeys.set(owner, code, down) } - private fun capturePausedFrame(manual: Boolean = false) { - if (!SessionState.running || pipUi || isInPictureInPictureMode || glassesOutputActive || bottomOutputActive) return + private fun capturePausedFrame(manual: Boolean = false, onDone: () -> Unit = {}) { + fun skipped(reason: String) { + if (manual) SessionEvents.record("pause.frame_skipped", mapOf("reason" to reason)) + onDone() + } + if (!SessionState.running || pipUi || isInPictureInPictureMode || glassesOutputActive || bottomOutputActive) { + return skipped("state running=${SessionState.running} pip=$pipUi glasses=$glassesOutputActive bottom=$bottomOutputActive") + } if (SessionState.suspended && pausedFrame != null) return - if ((suspendPolicy == SessionPrefs.SUSPEND_NEVER && !manual && !SessionState.manualPause) || !::surfaceView.isInitialized) return - if (surfaceView.holder.surface?.isValid != true) return + if ((suspendPolicy == SessionPrefs.SUSPEND_NEVER && !manual && !SessionState.manualPause) || !::surfaceView.isInitialized) return skipped("policy") + if (surfaceView.holder.surface?.isValid != true) return skipped("surface invalid") val width = surfaceView.width val height = surfaceView.height - if (width <= 0 || height <= 0) return + if (width <= 0 || height <= 0) return skipped("size ${width}x$height") val scale = minOf(1f, PAUSED_FRAME_MAX_EDGE / maxOf(width, height).toFloat()) val bitmap = try { android.graphics.Bitmap.createBitmap( maxOf(1, (width * scale).toInt()), maxOf(1, (height * scale).toInt()), android.graphics.Bitmap.Config.ARGB_8888, ) } catch (_: OutOfMemoryError) { - return + return skipped("oom") } val surfaceAt = IntArray(2).also { surfaceView.getLocationInWindow(it) } val overlayAt = IntArray(2).also { sessionOverlay.getLocationInWindow(it) } val left = surfaceAt[0] - overlayAt[0] val top = surfaceAt[1] - overlayAt[1] val bounds = android.graphics.Rect(left, top, left + width, top + height) + val requestedAt = SystemClock.elapsedRealtime() withPictureFrame { done -> try { android.view.PixelCopy.request(surfaceView, bitmap, { result -> done() + onDone() + if (manual) SessionEvents.record("pause.frame_copy", mapOf( + "result" to result, "ms" to SystemClock.elapsedRealtime() - requestedAt, + "zeroCopy" to SessionPrefs.zeroCopy(this, SessionState.mode), "size" to "${width}x$height", + "lit" to (result == android.view.PixelCopy.SUCCESS && bitmapHasPicture(bitmap)), + )) if (result == android.view.PixelCopy.SUCCESS && !isDestroyed) { pausedFrame = com.droiddeck.launcher.ui.PausedFrame(bitmap.asImageBitmap(), bounds) pausedFrameWanted = false @@ -5724,6 +5813,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } catch (_: IllegalArgumentException) { done() bitmap.recycle() + skipped("copy rejected") } } } @@ -5731,12 +5821,35 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun pauseNow() { if (!SessionState.running || SessionState.suspended) return pauseAnimated = true - drawerOpen = false + if (!dockedTouchOnly) drawerOpen = false pausedFrame = null - capturePausedFrame(manual = true) + if (zeroCopyActive()) { + WaylandCompositor.nativeSetZeroCopy(false) + val restore = java.util.concurrent.atomic.AtomicBoolean(false) + val back = { if (restore.compareAndSet(false, true)) WaylandCompositor.nativeSetZeroCopy(true) } + uiHandler.postDelayed({ capturePausedFrame(manual = true, onDone = back) }, ZERO_COPY_SETTLE_MS) + uiHandler.postDelayed({ back() }, ZERO_COPY_RESTORE_MS) + } else { + capturePausedFrame(manual = true) + } SessionService.pause(this) } + private fun zeroCopyActive(): Boolean = + CompositorHost.isStarted && !SessionState.hdr && SessionPrefs.zeroCopy(this, SessionState.mode) + + private fun bitmapHasPicture(bitmap: android.graphics.Bitmap): Boolean { + val w = bitmap.width + val h = bitmap.height + if (w <= 0 || h <= 0) return false + var lit = 0 + for (i in 0 until 64) { + val c = bitmap.getPixel((w * (i % 8 + 1)) / 9, (h * (i / 8 + 1)) / 9) + if (android.graphics.Color.red(c) + android.graphics.Color.green(c) + android.graphics.Color.blue(c) > 24) lit++ + } + return lit >= 3 + } + private fun requestPausedFrame() { if (pausedFrame != null) return pausedFrameWanted = true @@ -5840,8 +5953,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde reconcileDock(shownOnDisplayId) settleDualScreenControls() refreshSecondScreenDisplays() - if (secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode) - else openDualScreenControls() + if (secondScreenMode != SecondScreenMode.NONE) { + if (secondScreenPresentation == null) showSecondScreen(secondScreenMode) + if (com.droiddeck.launcher.input.DualScreen.menuReturnsOnStart(openingPanel(), SessionState.bottomMenu, menuShownOnBottom())) pinDockedMenu() + SessionState.bottomMenu = false + } else openDualScreenControls() startedScreens++ SessionService.setActivityVisible(this, true, sessionActivityDisplayId) Glasses.rescan() @@ -5992,7 +6108,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde heldKeys.clear() heldButtons.clear() if (!screenOff) { + val menuUp = menuShownOnBottom() drawerOpen = false + if (menuUp) SessionState.bottomMenu = true pcKeyboardOpen = false achievementsOpen = false } @@ -6764,6 +6882,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private const val LEAVE_TIMEOUT_MS = 1_500L private const val TEXT_FIELD_TAP_MS = 1_000L private const val PAUSED_FRAME_MAX_EDGE = 1920f + private const val ZERO_COPY_SETTLE_MS = 150L + private const val ZERO_COPY_RESTORE_MS = 1200L private const val BFI_PICTURE_SETTLE_MS = 50L private const val PAUSED_FRAME_REDRAW_MS = 150L private const val BOTTOM_RECOVERY_MS = 1_000L diff --git a/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt b/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt index 1d8bf5d682..a4de922ca7 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt @@ -23,6 +23,14 @@ object DualScreen { @Volatile private var takenDisplays: Set = emptySet() private val main by lazy { android.os.Handler(android.os.Looper.getMainLooper()) } + fun menuOwnsController(open: Boolean, docked: Boolean, optIn: Boolean): Boolean = open && (!docked || optIn) + + fun menuReturnsOnStart(selected: SecondScreenMode, menuWasShown: Boolean, menuUp: Boolean): Boolean = + !menuUp && (selected == SecondScreenMode.MENU || menuWasShown) + + fun menuIdleOnBottom(open: Boolean, docked: Boolean, pinned: Boolean, optIn: Boolean): Boolean = + docked && (open || pinned) && !menuOwnsController(open, docked, optIn) + fun yieldsBottom(model: String): Boolean = model.trim().lowercase().let { m -> knownModels.any(m::startsWith) } fun taken(displayId: Int): Boolean = displayId in takenDisplays diff --git a/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt b/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt index 590ef4fc08..476ac443ac 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt @@ -9,6 +9,7 @@ import com.droiddeck.launcher.session.SessionPrefs enum class SecondScreenMode(val id: String, @StringRes val label: Int, val bindings: String? = null) { NONE("none", R.string.second_mode_none), + MENU("menu", R.string.touch_droiddeck_menu), KEYBOARD_TRACKPAD("keyboard-trackpad", R.string.second_mode_keyboard_trackpad, InputStockLayouts.TRACKPAD), TERMINAL("terminal", R.string.second_mode_terminal), DECK_CONTROLS("deck-controls", R.string.second_mode_deck_controls, InputStockLayouts.DECK), @@ -21,19 +22,12 @@ enum class SecondScreenMode(val id: String, @StringRes val label: Int, val bindi fun panel(context: Context): String? = if (this == DECK_CONTROLS) SessionPrefs.deckPanel(context).bindings else bindings companion object { - fun opening(remembered: String?, deckPad: Boolean, dashboard: Boolean = false, bottomDesktop: Boolean = false, desktopSession: Boolean = false): SecondScreenMode { + /** The mode the bottom screen opens in: the one picked last if it is still available, else the DroidDeck menu. */ + fun opening(remembered: String?, deckPad: Boolean, dashboard: Boolean = false, bottomDesktop: Boolean = false): SecondScreenMode = entries.firstOrNull { it != NONE && it.id == remembered && (it != DECK_CONTROLS || deckPad) && (it != DASHBOARD || dashboard) && (it != DESKTOP || bottomDesktop) - }?.let { return it } - val picked = entries.any { it != NONE && it.id == remembered } - return when { - desktopSession -> KEYBOARD_TRACKPAD - deckPad -> DECK_CONTROLS - dashboard && !picked -> DASHBOARD - else -> KEYBOARD_TRACKPAD - } - } + } ?: MENU } } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 33ce049599..0ff3d76e38 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -614,6 +614,12 @@ object SessionPrefs { prefs(context).edit().putBoolean("backHold", on).apply() } + fun dockedMenuController(context: Context): Boolean = prefs(context).getBoolean("dockedMenuController", false) + + fun setDockedMenuController(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("dockedMenuController", on).apply() + } + fun backActionsInverted(context: Context): Boolean = prefs(context).getBoolean("backActionsInverted", false) fun setBackActionsInverted(context: Context, inverted: Boolean) { diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt index 847ed340b6..e695f8b932 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt @@ -133,6 +133,7 @@ object SessionState { @Volatile var padBridge: com.droiddeck.launcher.input.PadBridge? = null @Volatile var secondScreenMode = com.droiddeck.launcher.input.SecondScreenMode.NONE + @Volatile var bottomMenu = false @Volatile var secondScreenDisplay = -1 @Volatile var secondScreenAutoOpened = false @Volatile var secondScreenProvisional = false diff --git a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt index 2bb6190ce5..5a61619d12 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt @@ -16,7 +16,7 @@ object SettingsReset { "dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard", "soundtracksIngame", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature", "storesInstallLanguage", - "hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController", + "hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "dockedMenuController", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController", "gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController", "stretch16x9", "avoidNotch", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "drawerPageOrder", "drawerPageHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys", "gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop", diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomScreenBar.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomScreenBar.kt index 0fbbcf3f3e..b6509b332d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BottomScreenBar.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomScreenBar.kt @@ -230,6 +230,7 @@ internal fun BarButton( internal val SecondScreenMode.icon: ImageVector get() = when (this) { SecondScreenMode.NONE -> Icons.Outlined.DesktopAccessDisabled + SecondScreenMode.MENU -> Icons.Outlined.MoreHoriz SecondScreenMode.KEYBOARD_TRACKPAD -> Icons.Outlined.Keyboard SecondScreenMode.TERMINAL -> Icons.Outlined.Terminal SecondScreenMode.DECK_CONTROLS -> Icons.Outlined.SportsEsports @@ -290,17 +291,11 @@ private fun ScreenPickerMenu(picker: ScreenPicker, open: Boolean, dismiss: () -> leading = { Icon(painterResource(R.drawable.ic_stat_session), contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(18.dp)) }, focusRequester = first.takeIf { target == null }, modifier = Modifier.testTag("screen-picker-menu"), ) { dismiss(); menu() } - Box(Modifier.fillMaxWidth().padding(vertical = 4.dp).height(1.dp).background(pal.line)) - Text( - stringResource(R.string.drawer_second_screen).uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, - color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 10.dp, top = 6.dp, bottom = 4.dp), - ) } picker.modes.forEach { mode -> val current = mode == picker.current MenuItem( stringResource(mode.label), checked = current && !picker.menuShown, - detail = if (current && picker.menuShown) stringResource(R.string.screen_picker_last_used) else null, leading = { Icon(mode.icon, contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(18.dp)) }, focusRequester = first.takeIf { mode == target }, modifier = Modifier.testTag("screen-picker:${mode.id}"), ) { dismiss(); picker.onPick(mode) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt index 6944d5a302..ff0400860c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt @@ -305,7 +305,7 @@ class SecondScreenPresentation( (onSteamMenu to onQam).takeIf { SessionState.mode == SessionService.MODE_STEAM }, onSwap, picker = picker?.let { pick -> { pick(SecondScreenMode.DESKTOP) } }), weightParams()) } - SecondScreenMode.NONE -> Unit + SecondScreenMode.NONE, SecondScreenMode.MENU -> Unit } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index 474e613c6a..ffca74a17f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -44,6 +44,7 @@ import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.material.icons.outlined.DesktopWindows import androidx.compose.material.icons.outlined.Layers import androidx.compose.material.icons.outlined.Pause +import androidx.compose.material.icons.outlined.PlayArrow import androidx.compose.material.icons.outlined.PictureInPictureAlt import androidx.compose.material.icons.automirrored.outlined.ExitToApp import androidx.compose.material.icons.outlined.Settings @@ -230,6 +231,8 @@ class DrawerActions( val onMicEnabled: (Boolean) -> Unit = {}, val backHold: Boolean = true, val onBackHold: (Boolean) -> Unit = {}, + val dockedMenuController: Boolean = false, + val onDockedMenuController: (Boolean) -> Unit = {}, val backActionsInverted: Boolean, val backDoubleTapMs: Int = 500, val onBackDoubleTapMs: (Int) -> Unit = {}, @@ -332,6 +335,7 @@ class DrawerActions( val onSteamVr: (String) -> Unit = {}, val onTextureAnisotropy: (Int?) -> Unit = {}, val onTextureLodBias: (String?) -> Unit = {}, + val onSelectMenuMode: () -> Unit = {}, val onSecondScreenMode: (SecondScreenMode) -> Unit, val onSecondScreenDisplay: (Int) -> Unit, val onLaunchAndroidApp: (HomeApp.LaunchableApp, Int?) -> Unit, @@ -340,6 +344,10 @@ class DrawerActions( val pipAutoEnter: Boolean = false, val onPip: () -> Unit = {}, val onPause: () -> Unit = {}, + val paused: Boolean = false, + val orientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, + val onOrientation: (Int) -> Unit = {}, + val onResume: () -> Unit = {}, val onPipAutoEnter: (Boolean) -> Unit = {}, val unfoldedControls: Boolean? = null, val adaptiveSticks: Boolean? = null, @@ -541,14 +549,15 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont ScreenPicker( secondScreenModes(a.secondScreenNone, com.droiddeck.launcher.session.SessionState.deckPad, a.dashboardAvailable, a.desktopAvailable), a.secondScreenMode, onPick = { host.open = null; a.onSecondScreenMode(it) }, - onMenu = if (docked) ({ host.open = null }) else null, menuShown = docked, + onMenu = if (docked) ({ host.open = null; a.onSelectMenuMode() }) else null, menuShown = docked, ), focus.track(page, "screen").testTag("drawer-screen-picker"), ) } else if (roomyHeader) Spacer(Modifier.weight(1f)) SteamActionPill( - stringResource(R.string.stores_dl_pause), Icons.Outlined.Pause, focus.track(page, "pause"), - ) { host.open = null; a.onPause() } + stringResource(if (a.paused) R.string.resume_session else R.string.stores_dl_pause), + if (a.paused) Icons.Outlined.PlayArrow else Icons.Outlined.Pause, focus.track(page, "pause"), + ) { host.open = null; if (a.paused) a.onResume() else a.onPause() } if (a.pipSupported) SteamActionPill( stringResource(R.string.pip_title), Icons.Outlined.PictureInPictureAlt, focus.track(page, "pip"), ) { host.open = null; a.onPip() } @@ -664,6 +673,11 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont } } } + SettingsGroup(stringResource(R.string.setup_orientation)) { + ChoiceRow(host, "orientation", stringResource(R.string.setup_session_orientation), null, + SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) }, + a.orientation, chipModifier = focus.track(page, "orientation"), onPick = a.onOrientation) + } SettingsGroup(stringResource(R.string.display_image_scaling)) { if (a.steam) SettingsRow(stringResource(R.string.display_integer_scaling), null) { PadTextButton( @@ -780,6 +794,9 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont SessionPrefs.BACK_DOUBLE_TAP_MS_OPTIONS.map { it to stringResource(R.string.back_tap_ms, it) }, a.backDoubleTapMs, chipModifier = focus.track(page, "back-double-tap"), onPick = a.onBackDoubleTapMs) PhysicalShortcutRows(modifierFor = { focus.track(page, "physical-shortcut-${it.name}") }) + if (a.secondScreenDisplays.isNotEmpty()) ToggleRow(host, "docked-menu-controller", stringResource(R.string.drawer_docked_menu_controller), + null, a.dockedMenuController, + chipModifier = focus.track(page, "docked-menu-controller"), onChange = a.onDockedMenuController) ToggleRow(host, "corner-tap", stringResource(R.string.drawer_corner_tap), stringResource(R.string.drawer_corner_tap_hint), a.cornerTap, chipModifier = focus.track(page, "corner-tap"), onChange = a.onCornerTap) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ecb1b28ddb..579e08c381 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -4342,6 +4342,7 @@ %1$s opens this menu Back twice opens this menu · Back once opens Steam\'s menu Corner tap opens this menu + Physical controls can use bottom screen Double-tap the top-right corner, for devices without a Back button Open the session menu Settings need you diff --git a/app/src/test/java/com/droiddeck/launcher/input/DualScreenTest.kt b/app/src/test/java/com/droiddeck/launcher/input/DualScreenTest.kt index 7409d4558b..02380b0f25 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/DualScreenTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/DualScreenTest.kt @@ -23,6 +23,34 @@ class DualScreenTest { private val context: Context = ApplicationProvider.getApplicationContext() private val displays = context.getSystemService(DisplayManager::class.java) + @Test fun dockedMenuOnlyTakesTheControllerWhenOptedIn() { + assertFalse(DualScreen.menuOwnsController(open = false, docked = false, optIn = true)) + assertTrue(DualScreen.menuOwnsController(open = true, docked = false, optIn = false)) + assertFalse(DualScreen.menuOwnsController(open = true, docked = true, optIn = false)) + assertTrue(DualScreen.menuOwnsController(open = true, docked = true, optIn = true)) + } + + @Test fun theMenuComesBackOnStartWhenItIsTheSelectedModeOrWasShowingWhenTheScreenClosed() { + val menu = SecondScreenMode.MENU + val terminal = SecondScreenMode.TERMINAL + assertTrue(DualScreen.menuReturnsOnStart(menu, menuWasShown = false, menuUp = false)) + assertTrue(DualScreen.menuReturnsOnStart(menu, menuWasShown = true, menuUp = false)) + assertTrue(DualScreen.menuReturnsOnStart(terminal, menuWasShown = true, menuUp = false)) + assertFalse(DualScreen.menuReturnsOnStart(terminal, menuWasShown = false, menuUp = false)) + assertFalse(DualScreen.menuReturnsOnStart(menu, menuWasShown = true, menuUp = true)) + assertFalse(DualScreen.menuReturnsOnStart(terminal, menuWasShown = true, menuUp = true)) + } + + @Test fun aVisibleDockedMenuThatDoesNotOwnTheControllerIsIdle() { + assertFalse(DualScreen.menuIdleOnBottom(open = false, docked = false, pinned = false, optIn = false)) + assertFalse(DualScreen.menuIdleOnBottom(open = true, docked = false, pinned = false, optIn = false)) + assertTrue(DualScreen.menuIdleOnBottom(open = true, docked = true, pinned = false, optIn = false)) + assertTrue(DualScreen.menuIdleOnBottom(open = false, docked = true, pinned = true, optIn = false)) + assertTrue(DualScreen.menuIdleOnBottom(open = false, docked = true, pinned = true, optIn = true)) + assertFalse(DualScreen.menuIdleOnBottom(open = true, docked = true, pinned = false, optIn = true)) + assertFalse(DualScreen.menuIdleOnBottom(open = false, docked = true, pinned = false, optIn = false)) + } + @Test fun internalPanelsCountAsBuiltIn() { assertTrue(DualScreen.isBuiltIn(1, "Anything")) assertFalse(DualScreen.isBuiltIn(2, "Retroid Pocket Duo")) diff --git a/app/src/test/java/com/droiddeck/launcher/input/SecondScreenModeTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SecondScreenModeTest.kt index 566a091c42..d49a937e05 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/SecondScreenModeTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/SecondScreenModeTest.kt @@ -53,14 +53,10 @@ class SecondScreenModeTest { assertEquals(-1, SecondScreenDisplays.selection(-1, emptyList(), false)) } - @Test fun withNothingRememberedDeckPadsGetControlsAndOthersTheDashboard() { - assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening(null, deckPad = true, dashboard = true)) - assertEquals(SecondScreenMode.DASHBOARD, SecondScreenMode.opening(null, deckPad = false, dashboard = true)) - } - - @Test fun withNothingRememberedAndNoDashboardTheControllerPicksThePanel() { - assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening(null, deckPad = true)) - assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening(null, deckPad = false)) + @Test fun withNothingRememberedTheDroidDeckMenuOpens() { + for (deckPad in listOf(false, true)) for (dashboard in listOf(false, true)) for (desktop in listOf(false, true)) { + assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening(null, deckPad, dashboard, desktop)) + } } @Test fun thePanelTheUserPickedLastOpensAgain() { @@ -70,9 +66,18 @@ class SecondScreenModeTest { assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("keyboard-trackpad", deckPad = true)) } + @Test fun theMenuIsAModeAndOpensAgainWhenItWasPickedLast() { + for (deckPad in listOf(false, true)) { + assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening("menu", deckPad, dashboard = true, bottomDesktop = true)) + } + assertEquals("menu", SecondScreenMode.MENU.id) + assertEquals(false, SecondScreenMode.MENU.controls) + assertEquals(null, SecondScreenMode.MENU.bindings) + } + @Test fun deckControlsNeedTheDeckPad() { - assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("deck-controls", deckPad = false)) - assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("deck-controls", deckPad = false, dashboard = true)) + assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening("deck-controls", deckPad = false)) + assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening("deck-controls", deckPad = false, dashboard = true)) } @Test fun customControlsReopenWithEitherControllerType() { @@ -81,37 +86,23 @@ class SecondScreenModeTest { } } - @Test fun anUnknownOrClosedChoiceFallsBackToTheDefault() { - assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening("none", deckPad = true, dashboard = true)) - assertEquals(SecondScreenMode.DASHBOARD, SecondScreenMode.opening("gone", deckPad = false, dashboard = true)) - assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening("none", deckPad = true)) - assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("gone", deckPad = false)) + @Test fun anUnknownOrClosedChoiceFallsBackToTheMenu() { + assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening("none", deckPad = true, dashboard = true)) + assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening("gone", deckPad = false, dashboard = true)) + assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening("none", deckPad = true)) + assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening("gone", deckPad = false)) } @Test fun theDashboardOpensAgainOnlyWhileItHasPages() { assertEquals(SecondScreenMode.DASHBOARD, SecondScreenMode.opening("dashboard", deckPad = true, dashboard = true)) - assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening("dashboard", deckPad = true, dashboard = false)) - assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("dashboard", deckPad = false)) + assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening("dashboard", deckPad = true, dashboard = false)) + assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening("dashboard", deckPad = false)) } @Test fun theDesktopOpensAgainOnlyWhileItCanRun() { assertEquals(SecondScreenMode.DESKTOP, SecondScreenMode.opening("desktop", deckPad = true, dashboard = true, bottomDesktop = true)) - assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening("desktop", deckPad = true, dashboard = true)) - assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("desktop", deckPad = false)) - } - - @Test fun withNothingRememberedTheDesktopIsNeverPicked() { - assertEquals(SecondScreenMode.DASHBOARD, SecondScreenMode.opening(null, deckPad = false, dashboard = true, bottomDesktop = true)) - assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening(null, deckPad = false, bottomDesktop = true)) - } - - @Test fun desktopSessionsOpenTheTrackpadUntilTheUserPicksAnotherPanel() { - for (deckPad in listOf(false, true)) for (dashboard in listOf(false, true)) { - assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening(null, deckPad, dashboard, desktopSession = true)) - assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("gone", deckPad, dashboard, desktopSession = true)) - assertEquals(SecondScreenMode.CUSTOM_CONTROLS, SecondScreenMode.opening("custom-controls", deckPad, dashboard, desktopSession = true)) - assertEquals(SecondScreenMode.TERMINAL, SecondScreenMode.opening("terminal", deckPad, dashboard, desktopSession = true)) - } + assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening("desktop", deckPad = true, dashboard = true)) + assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening("desktop", deckPad = false)) } @Test fun theEditorOpensOnTheChosenBottomScreenUnlessAnotherAppHoldsIt() { diff --git a/app/src/test/java/com/droiddeck/launcher/input/SecondScreenProfileMigrationTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SecondScreenProfileMigrationTest.kt index 669db39752..ba688bcbd5 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/SecondScreenProfileMigrationTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/SecondScreenProfileMigrationTest.kt @@ -48,20 +48,14 @@ class SecondScreenProfileMigrationTest { SessionState.deckPad = previousDeckPad } - @Test fun firstOpeningKeepsTheLibraryAndOpensTheTrackpadOnDesktopAndTheControllerPanelInGames() { + @Test fun firstOpeningKeepsTheLibraryAndOpensTheMenuOverTheTrackpad() { for (desktop in listOf(false, true)) for (deckPad in listOf(false, true)) { val original = customLibrary(desktop) open(desktop, deckPad) assertEquals(original, InputLibraries.read(activity)) assertNull(SessionPrefs.secondScreenPanel(activity, desktop)) - val dashboard = ReflectionHelpers.callInstanceMethod>(activity, "bottomPages").isNotEmpty() - val expected = when { - desktop -> SecondScreenMode.KEYBOARD_TRACKPAD - deckPad -> SecondScreenMode.DECK_CONTROLS - dashboard -> SecondScreenMode.DASHBOARD - else -> SecondScreenMode.KEYBOARD_TRACKPAD - } - assertEquals(expected, SessionState.secondScreenMode) + assertEquals(SecondScreenMode.MENU, ReflectionHelpers.callInstanceMethod(activity, "openingPanel")) + assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SessionState.secondScreenMode) } } @@ -107,9 +101,8 @@ class SecondScreenProfileMigrationTest { customLibrary(desktop) SessionState.deckPad = false show(SecondScreenMode.DECK_CONTROLS) - val fallback = ReflectionHelpers.callInstanceMethod(activity, "openingPanel") - assertNotEquals(SecondScreenMode.DECK_CONTROLS, fallback) - if (desktop) assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, fallback) + val fallback = ReflectionHelpers.callInstanceMethod(activity, "openingSurface") + assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, fallback) assertEquals(fallback, SessionState.secondScreenMode) assertNotEquals(InputLibraries.DECK, routedLayout()?.id) } diff --git a/docs/agent-control.md b/docs/agent-control.md index 13bf1c232d..ac097234cf 100644 --- a/docs/agent-control.md +++ b/docs/agent-control.md @@ -135,6 +135,7 @@ tools/droiddeckctl input text 'hello world' tools/droiddeckctl input tap 640 360 tools/droiddeckctl input swipe 100 600 100 100 --duration 400 tools/droiddeckctl input pad a +tools/droiddeckctl input gamepad b rb up --hold 120 --gap 400 tools/droiddeckctl input stick left 0 -1 --hold 500 tools/droiddeckctl input trigger right 1.0 tools/droiddeckctl input pen tap 0.5 0.5 --pressure 0.7 @@ -234,6 +235,18 @@ and returns its exit code with the last 160 KiB of stdout and stderr (`--timeout that side over conflicts. The store id is the one in the game's install record (`library` shows it). Both need Setup > Developer > Debugging tools. +`input pad` writes to the session's virtual pad, the one the guest sees, and never reaches the app's +own key handling. To test how DroidDeck's own screens treat a controller (menu focus and outlines, +page switching with LB and RB, Back and Steam shortcuts), use `input gamepad`. It registers a real +gamepad called "DroidDeck test pad" with `adb shell uinput -`, so Android reports a physical +controller, and presses the buttons in order: `a b x y lb rb select start guide l3 r3` and the +d-pad `up down left right`. `--hold` (120 ms) is how long each stays down and `--gap` (400 ms) the +pause after it; a d-pad press always waits at least 20 ms, so Android sees each release before +the next press. The device exists only while the command runs, takes about a second to appear, and +works without a session or Setup > Developer > Debugging tools. Its name does not start with +`uinput-`, which the app treats as a system virtual device. `UINPUT_UNAVAILABLE` and `UINPUT_FAILED` +mean the same as for `input pen`. + `input pen` does not go through the app. It registers a virtual pen with `adb shell uinput -`, so Android's own input reader makes the stylus events, as for a built-in pen, and it works on whatever is on screen, without a session or Setup > Developer > Debugging tools. Positions are fractions of diff --git a/tools/droiddeckctl b/tools/droiddeckctl index 2a404c1c6c..2a4341c514 100755 --- a/tools/droiddeckctl +++ b/tools/droiddeckctl @@ -792,7 +792,7 @@ def uinput_commands(samples: list[dict], tool: str, viewport: dict) -> list[dict {"id": 1, "command": "sync", "syncToken": UINPUT_SYNC}] -def pen_uinput(adb: str, serial: str, samples: list[dict], tool: str) -> dict: +def uinput_check(adb: str, serial: str) -> None: probe = run_adb(adb, serial, "shell", "command -v uinput >/dev/null 2>&1 || echo no-uinput; [ -w /dev/uinput ] || echo no-dev-uinput") if probe.returncode != 0: @@ -802,6 +802,10 @@ def pen_uinput(adb: str, serial: str, samples: list[dict], tool: str) -> dict: raise ControlError("This device's shell has no `uinput` command", "UINPUT_UNAVAILABLE") if "no-dev-uinput" in missing: raise ControlError("The ADB shell cannot write /dev/uinput on this device", "UINPUT_UNAVAILABLE") + + +def pen_uinput(adb: str, serial: str, samples: list[dict], tool: str) -> dict: + uinput_check(adb, serial) viewport = input_viewport(run_adb(adb, serial, "shell", "dumpsys", "input").stdout.decode(errors="replace")) script = "".join(json.dumps(command) + "\n" for command in uinput_commands(samples, tool, viewport)) started = time.monotonic() @@ -817,6 +821,68 @@ def pen_uinput(adb: str, serial: str, samples: list[dict], tool: str) -> dict: "viewport": {key: viewport[key] for key in ("display", "rotation", "size")}} +GAMEPAD_NAME = "DroidDeck test pad" +GAMEPAD_SYNC = "droiddeckctl-gamepad-done" +GAMEPAD_BUTTONS = {"a": "BTN_SOUTH", "b": "BTN_EAST", "x": "BTN_NORTH", "y": "BTN_WEST", "lb": "BTN_TL", "rb": "BTN_TR", + "select": "BTN_SELECT", "start": "BTN_START", "guide": "BTN_MODE", "l3": "BTN_THUMBL", "r3": "BTN_THUMBR"} +GAMEPAD_DPAD = {"up": ("ABS_HAT0Y", -1), "down": ("ABS_HAT0Y", 1), "left": ("ABS_HAT0X", -1), "right": ("ABS_HAT0X", 1)} +GAMEPAD_MAX_PRESSES = 200 +GAMEPAD_DPAD_MIN_GAP_MS = 20 + + +def gamepad_commands(buttons: list[str], hold: int, gap: int) -> list[dict]: + def axis(code: str, low: int, high: int) -> dict: + return {"code": code, "info": {"value": 0, "minimum": low, "maximum": high, "fuzz": 0, "flat": 0, "resolution": 0}} + + unknown = [name for name in buttons if name not in GAMEPAD_BUTTONS and name not in GAMEPAD_DPAD] + if unknown: + raise ControlError(f"Unknown gamepad button {unknown[0]!r}; use " + f"{', '.join(list(GAMEPAD_BUTTONS) + list(GAMEPAD_DPAD))}", "INVALID_INPUT") + if not 1 <= len(buttons) <= GAMEPAD_MAX_PRESSES: + raise ControlError(f"Press between 1 and {GAMEPAD_MAX_PRESSES} buttons", "INVALID_INPUT") + if not 10 <= hold <= 5000 or not 0 <= gap <= 5000: + raise ControlError("--hold must be 10..5000 ms and --gap 0..5000 ms", "INVALID_INPUT") + commands: list[dict] = [ + {"id": 1, "command": "register", "name": GAMEPAD_NAME, "bus": "usb", "vid": 0x045E, "pid": 0x028E, + "configuration": [ + {"type": "UI_SET_EVBIT", "data": ["EV_KEY", "EV_ABS"]}, + {"type": "UI_SET_KEYBIT", "data": sorted(GAMEPAD_BUTTONS.values())}, + {"type": "UI_SET_ABSBIT", "data": ["ABS_X", "ABS_Y", "ABS_RX", "ABS_RY", "ABS_HAT0X", "ABS_HAT0Y"]}, + ], + "abs_info": [axis("ABS_X", -32768, 32767), axis("ABS_Y", -32768, 32767), axis("ABS_RX", -32768, 32767), + axis("ABS_RY", -32768, 32767), axis("ABS_HAT0X", -1, 1), axis("ABS_HAT0Y", -1, 1)]}, + {"id": 1, "command": "delay", "duration": UINPUT_REGISTER_MS}, + ] + for name in buttons: + code, down, up = (GAMEPAD_BUTTONS[name], 1, 0) if name in GAMEPAD_BUTTONS else \ + (GAMEPAD_DPAD[name][0], GAMEPAD_DPAD[name][1], 0) + kind = "EV_KEY" if name in GAMEPAD_BUTTONS else "EV_ABS" + commands += [{"id": 1, "command": "inject", "events": [kind, code, down, "EV_SYN", "SYN_REPORT", 0]}, + {"id": 1, "command": "delay", "duration": hold}, + {"id": 1, "command": "inject", "events": [kind, code, up, "EV_SYN", "SYN_REPORT", 0]}] + pause = gap if name in GAMEPAD_BUTTONS else max(gap, GAMEPAD_DPAD_MIN_GAP_MS) + if pause > 0: + commands.append({"id": 1, "command": "delay", "duration": pause}) + return commands + [{"id": 1, "command": "delay", "duration": UINPUT_TAIL_MS}, + {"id": 1, "command": "sync", "syncToken": GAMEPAD_SYNC}] + + +def gamepad_uinput(adb: str, serial: str, buttons: list[str], hold: int, gap: int) -> dict: + commands = gamepad_commands(buttons, hold, gap) + uinput_check(adb, serial) + script = "".join(json.dumps(command) + "\n" for command in commands) + started = time.monotonic() + result = run_adb(adb, serial, "shell", "uinput", "-", stdin=script.encode(), + timeout=(UINPUT_REGISTER_MS + len(buttons) * (hold + gap) + UINPUT_TAIL_MS) / 1000 + 30) + elapsed = round((time.monotonic() - started) * 1000) + if GAMEPAD_SYNC not in result.stdout.decode(errors="replace"): + detail = (result.stderr or result.stdout).decode(errors="replace").strip()[-400:] + raise ControlError(f"uinput stopped before the last button (exit {result.returncode})" + + (f": {detail}" if detail else "") + "; `adb logcat -s UINPUT UinputDevice` tells why", + "UINPUT_FAILED") + return {"ok": True, "command": "input", "type": "gamepad", "buttons": buttons, "ms": elapsed} + + def xr_ppm_to_png(data: bytes, linear: bool = False) -> bytes: header = re.match(rb"P6\n([0-9]+) ([0-9]+)\n255\n", data) if not header: @@ -1081,6 +1147,8 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict: if command == "input": if args.input_type == "pen": return add_serial(pen_uinput(adb, serial, pen_samples(args), args.tool), serial) + if args.input_type == "gamepad": + return add_serial(gamepad_uinput(adb, serial, args.buttons, args.hold, args.gap), serial) return add_serial(checked(provider_call(adb, serial, "input", request=input_request(args), timeout=60), "INPUT_FAILED"), serial) @@ -1359,6 +1427,13 @@ def build_parser() -> argparse.ArgumentParser: pad.add_argument("button") pad.add_argument("--action", choices=["tap", "down", "up"], default="tap") pad.add_argument("--hold", type=int, default=120) + gamepad = kinds.add_parser( + "gamepad", help="press buttons on a real uinput gamepad that Android sees as a physical controller " + "(unlike pad, which only feeds the guest's virtual pad)") + gamepad.add_argument("buttons", nargs="+", metavar="BUTTON", + help="a b x y lb rb select start guide l3 r3 up down left right, pressed in order") + gamepad.add_argument("--hold", type=int, default=120, help="ms each button stays down") + gamepad.add_argument("--gap", type=int, default=400, help="ms between buttons (a d-pad press always waits at least 20 ms)") stick = kinds.add_parser("stick", help="hold a stick at x, y (-1..1)") stick.add_argument("stick", choices=["left", "right"]) stick.add_argument("x", type=float) diff --git a/tools/tests/test_droiddeckctl_gamepad.py b/tools/tests/test_droiddeckctl_gamepad.py new file mode 100644 index 0000000000..201a92e599 --- /dev/null +++ b/tools/tests/test_droiddeckctl_gamepad.py @@ -0,0 +1,91 @@ +import json +import unittest + +from test_droiddeckctl import FakeAdbTest, ctl + + +def key_frames(commands): + found = [] + for command in commands: + if command["command"] == "inject": + events = command["events"] + found.append({code: value for code, value in zip(events[1::3], events[2::3]) if code != "SYN_REPORT"}) + return found + + +class GamepadTest(FakeAdbTest): + def setUp(self): + super().setUp() + self.configure({}) + + def gamepad(self, *argv): + return self.run_ctl("input", "gamepad", *argv) + + def script(self): + [call] = [c for c in self.calls() if c["args"][:3] == ["shell", "uinput", "-"]] + return [json.loads(line) for line in call["stdin"].splitlines()] + + def test_buttons_are_pressed_in_order_on_a_real_looking_gamepad(self): + code, out = self.gamepad("b", "rb", "--hold", "50", "--gap", "100") + self.assertEqual(0, code) + self.assertEqual({"ok": True, "command": "input", "type": "gamepad", "buttons": ["b", "rb"], "deviceSerial": "fake-1"}, + {k: v for k, v in out.items() if k != "ms"}) + self.assertFalse(self.calls("input")) + commands = self.script() + register = commands[0] + bits = {c["type"]: c["data"] for c in register["configuration"]} + self.assertEqual(("register", "usb", ["EV_KEY", "EV_ABS"]), (register["command"], register["bus"], bits["UI_SET_EVBIT"])) + self.assertFalse(register["name"].lower().startswith(("uinput-", "uinput_"))) + self.assertTrue({"BTN_SOUTH", "BTN_EAST", "BTN_TL", "BTN_TR", "BTN_START"} <= set(bits["UI_SET_KEYBIT"])) + self.assertEqual(set(bits["UI_SET_ABSBIT"]), {a["code"] for a in register["abs_info"]}) + self.assertEqual({"id": 1, "command": "delay", "duration": ctl.UINPUT_REGISTER_MS}, commands[1]) + self.assertEqual([{"BTN_EAST": 1}, {"BTN_EAST": 0}, {"BTN_TR": 1}, {"BTN_TR": 0}], key_frames(commands)) + self.assertEqual([50, 100, 50, 100], [c["duration"] for c in commands[2:-2] if c["command"] == "delay"]) + self.assertEqual({"id": 1, "command": "sync", "syncToken": ctl.GAMEPAD_SYNC}, commands[-1]) + + def test_a_zero_gap_sends_no_empty_delay_which_android_rejects(self): + code, _ = self.gamepad("a", "b", "--hold", "40", "--gap", "0") + self.assertEqual(0, code) + commands = self.script() + self.assertEqual([{"BTN_SOUTH": 1}, {"BTN_SOUTH": 0}, {"BTN_EAST": 1}, {"BTN_EAST": 0}], key_frames(commands)) + self.assertEqual([], [c for c in commands if c["command"] == "delay" and c["duration"] <= 0]) + self.assertEqual([40, 40], [c["duration"] for c in commands[2:-2] if c["command"] == "delay"]) + + def test_a_dpad_release_never_runs_into_the_next_press_even_at_zero_gap(self): + code, _ = self.gamepad("left", "left", "--hold", "40", "--gap", "0") + self.assertEqual(0, code) + commands = self.script() + self.assertEqual([{"ABS_HAT0X": -1}, {"ABS_HAT0X": 0}, {"ABS_HAT0X": -1}, {"ABS_HAT0X": 0}], key_frames(commands)) + self.assertEqual([40, ctl.GAMEPAD_DPAD_MIN_GAP_MS, 40, ctl.GAMEPAD_DPAD_MIN_GAP_MS], + [c["duration"] for c in commands[2:-2] if c["command"] == "delay"]) + + def test_the_dpad_uses_the_hat_axes(self): + code, _ = self.gamepad("up", "right", "down", "left") + self.assertEqual(0, code) + self.assertEqual([{"ABS_HAT0Y": -1}, {"ABS_HAT0Y": 0}, {"ABS_HAT0X": 1}, {"ABS_HAT0X": 0}, + {"ABS_HAT0Y": 1}, {"ABS_HAT0Y": 0}, {"ABS_HAT0X": -1}, {"ABS_HAT0X": 0}], + key_frames(self.script())) + + def test_an_unknown_button_or_bad_timing_is_refused_before_touching_the_device(self): + for argv, message in ((("nope",), "Unknown gamepad button 'nope'"), (("a", "--hold", "1"), "--hold must be"), + (("a", "--gap", "-5"), "--gap 0..5000")): + with self.subTest(argv=argv): + code, out = self.gamepad(*argv) + self.assertEqual((2, "INVALID_INPUT"), (code, out["error"]["code"])) + self.assertIn(message, out["error"]["message"]) + self.assertFalse(self.calls()) + + def test_a_shell_without_uinput_is_unavailable(self): + self.configure({}, uinput_probe="no-dev-uinput") + code, out = self.gamepad("a") + self.assertEqual((3, "UINPUT_UNAVAILABLE"), (code, out["error"]["code"])) + self.assertFalse([c for c in self.calls() if c["args"][:2] == ["shell", "uinput"]]) + + def test_uinput_that_stops_early_fails(self): + self.configure({}, uinput_stdout="") + code, out = self.gamepad("a") + self.assertEqual((3, "UINPUT_FAILED"), (code, out["error"]["code"])) + + +if __name__ == "__main__": + unittest.main() From a8d03d687f88f50648afe7cfb91ebabb2aabee30 Mon Sep 17 00:00:00 2001 From: Tamim Kabir <204907199+Necomer0920@users.noreply.github.com> Date: Sun, 22 Nov 2026 02:43:32 -0500 Subject: [PATCH 027/141] fix(input): SDL 3 games no longer crash on the virtual pads' udev devices (#2915) --- tools/linuxfs/preload/inputudev.c | 65 ++++++++++++++++++++++ tools/tests/test_inputudev_preload.py | 80 ++++++++++++++++++++++++--- 2 files changed, 137 insertions(+), 8 deletions(-) diff --git a/tools/linuxfs/preload/inputudev.c b/tools/linuxfs/preload/inputudev.c index 3dcb5a1049..4dd7d1f115 100644 --- a/tools/linuxfs/preload/inputudev.c +++ b/tools/linuxfs/preload/inputudev.c @@ -582,6 +582,16 @@ const char *udev_device_get_action(void *device) { return real_get(device); } +const char *udev_device_get_driver(void *device) { + static const char *(*real_get)(void *); + struct pad *pad = device_pad(device); + + if (pad != NULL) return NULL; + if (real_get == NULL) real_get = next_symbol("udev_device_get_driver"); + if (real_get == NULL) return NULL; + return real_get(device); +} + dev_t udev_device_get_devnum(void *device) { static dev_t (*real_get)(void *); struct pad *pad = device_pad(device); @@ -686,6 +696,54 @@ void *udev_device_get_sysattr_list_entry(void *device) { return real_get != NULL ? real_get(device) : NULL; } +void *udev_device_get_current_tags_list_entry(void *device) { + static void *(*real_get)(void *); + + if (device_pad(device) != NULL) return NULL; + if (real_get == NULL) real_get = next_symbol("udev_device_get_current_tags_list_entry"); + return real_get != NULL ? real_get(device) : NULL; +} + +int udev_device_has_current_tag(void *device, const char *tag) { + static int (*real_has)(void *, const char *); + + if (device_pad(device) != NULL) return 0; + if (real_has == NULL) real_has = next_symbol("udev_device_has_current_tag"); + return real_has != NULL ? real_has(device, tag) : 0; +} + +void *udev_device_get_devlinks_list_entry(void *device) { + static void *(*real_get)(void *); + + if (device_pad(device) != NULL) return NULL; + if (real_get == NULL) real_get = next_symbol("udev_device_get_devlinks_list_entry"); + return real_get != NULL ? real_get(device) : NULL; +} + +unsigned long long udev_device_get_seqnum(void *device) { + static unsigned long long (*real_get)(void *); + + if (device_pad(device) != NULL) return 0; + if (real_get == NULL) real_get = next_symbol("udev_device_get_seqnum"); + return real_get != NULL ? real_get(device) : 0; +} + +unsigned long long udev_device_get_usec_since_initialized(void *device) { + static unsigned long long (*real_get)(void *); + + if (device_pad(device) != NULL) return 0; + if (real_get == NULL) real_get = next_symbol("udev_device_get_usec_since_initialized"); + return real_get != NULL ? real_get(device) : 0; +} + +int udev_device_set_sysattr_value(void *device, const char *sysattr, const char *value) { + static int (*real_set)(void *, const char *, const char *); + + if (device_pad(device) != NULL) return -EACCES; + if (real_set == NULL) real_set = next_symbol("udev_device_set_sysattr_value"); + return real_set != NULL ? real_set(device, sysattr, value) : -ENOSYS; +} + void *udev_device_new_from_devnum(void *udev, char type, dev_t devnum) { static void *(*real_new)(void *, char, dev_t); struct pad pad; @@ -1011,6 +1069,7 @@ static const struct udev_symbol udev_symbols[] = { {"udev_device_get_subsystem", (void *)udev_device_get_subsystem}, {"udev_device_get_devtype", (void *)udev_device_get_devtype}, {"udev_device_get_action", (void *)udev_device_get_action}, + {"udev_device_get_driver", (void *)udev_device_get_driver}, {"udev_device_get_devnum", (void *)udev_device_get_devnum}, {"udev_device_get_sysattr_value", (void *)udev_device_get_sysattr_value}, {"udev_device_get_property_value", (void *)udev_device_get_property_value}, @@ -1023,6 +1082,12 @@ static const struct udev_symbol udev_symbols[] = { {"udev_device_get_properties_list_entry", (void *)udev_device_get_properties_list_entry}, {"udev_device_get_tags_list_entry", (void *)udev_device_get_tags_list_entry}, {"udev_device_get_sysattr_list_entry", (void *)udev_device_get_sysattr_list_entry}, + {"udev_device_get_current_tags_list_entry", (void *)udev_device_get_current_tags_list_entry}, + {"udev_device_has_current_tag", (void *)udev_device_has_current_tag}, + {"udev_device_get_devlinks_list_entry", (void *)udev_device_get_devlinks_list_entry}, + {"udev_device_get_seqnum", (void *)udev_device_get_seqnum}, + {"udev_device_get_usec_since_initialized", (void *)udev_device_get_usec_since_initialized}, + {"udev_device_set_sysattr_value", (void *)udev_device_set_sysattr_value}, {"udev_enumerate_new", (void *)udev_enumerate_new}, {"udev_enumerate_ref", (void *)udev_enumerate_ref}, {"udev_enumerate_unref", (void *)udev_enumerate_unref}, diff --git a/tools/tests/test_inputudev_preload.py b/tools/tests/test_inputudev_preload.py index 8e4cf66e80..7cb96a91d5 100644 --- a/tools/tests/test_inputudev_preload.py +++ b/tools/tests/test_inputudev_preload.py @@ -1,5 +1,6 @@ from pathlib import Path import os +import re import shutil import subprocess import sys @@ -181,20 +182,48 @@ void *udev_device_new_from_subsystem_sysname(void *udev, const char *subsystem, (void)udev; (void)subsystem; (void)sysname; return NULL; } -void *udev_device_unref(void *device) { (void)device; return NULL; } -void *udev_device_ref(void *device) { (void)device; return NULL; } -void *udev_device_get_parent(void *device) { (void)device; return NULL; } -void *udev_device_get_udev(void *device) { (void)device; return NULL; } -const char *udev_device_get_syspath(void *device) { (void)device; return "real"; } -const char *udev_device_get_sysnum(void *device) { (void)device; return "real"; } +int real_device_calls; +void *udev_device_unref(void *device) { (void)device; real_device_calls++; return NULL; } +void *udev_device_ref(void *device) { (void)device; real_device_calls++; return NULL; } +void *udev_device_get_parent(void *device) { (void)device; real_device_calls++; return NULL; } +void *udev_device_get_udev(void *device) { (void)device; real_device_calls++; return NULL; } +const char *udev_device_get_syspath(void *device) { (void)device; real_device_calls++; return "real"; } +const char *udev_device_get_sysnum(void *device) { (void)device; real_device_calls++; return "real"; } +void *udev_device_new_from_devnum(void *udev, char type, unsigned long devnum) { + (void)udev; (void)type; (void)devnum; + return NULL; +} """ +DEVICE_FUNCTIONS = ( + "p:udev_device_ref", "p:udev_device_get_udev", "p:udev_device_get_parent", + "P:udev_device_get_parent_with_subsystem_devtype", "s:udev_device_get_devpath", "s:udev_device_get_subsystem", + "s:udev_device_get_devtype", "s:udev_device_get_syspath", "s:udev_device_get_sysname", + "s:udev_device_get_sysnum", "s:udev_device_get_devnode", "i:udev_device_get_is_initialized", + "p:udev_device_get_devlinks_list_entry", "p:udev_device_get_properties_list_entry", + "p:udev_device_get_tags_list_entry", "p:udev_device_get_current_tags_list_entry", + "p:udev_device_get_sysattr_list_entry", "S:udev_device_get_property_value", "s:udev_device_get_driver", + "d:udev_device_get_devnum", "s:udev_device_get_action", "u:udev_device_get_seqnum", + "u:udev_device_get_usec_since_initialized", "S:udev_device_get_sysattr_value", + "W:udev_device_set_sysattr_value", "I:udev_device_has_tag", "I:udev_device_has_current_tag", + "p:udev_device_unref", +) +SIGNATURES = { + "p": ("void *", ""), "s": ("const char *", ""), "i": ("int", ""), "d": ("dev_t", ""), + "u": ("unsigned long long", ""), "S": ("const char *", ", const char *a"), "I": ("int", ", const char *a"), + "P": ("void *", ", const char *a, const char *b"), "W": ("int", ", const char *a, const char *b"), +} +UDEV += "#include \n" + "".join( + f"{SIGNATURES[kind][0]} {name}(void *device{SIGNATURES[kind][1]}) {{ (void)device; real_device_calls++; return 0; }}\n" + for kind, _, name in (entry.partition(":") for entry in DEVICE_FUNCTIONS) if not re.search(rf"\b{name}\(", UDEV)) + PROGRAM = r""" #define _GNU_SOURCE #include #include #include #include +#include #include #define PAD "/sys/devices/virtual/input/droiddeck0" @@ -400,6 +429,37 @@ static void run_enumerate(void) { printf("nothing added scan %d\n", scan(other)); } +static void run_every(int count, char **entries) { + void *(*from_devnum)(void *, char, dev_t) = sym("udev_device_new_from_devnum"); + int *real_calls = dlsym(lib, "real_device_calls"); + int udev; + void *pad = from_devnum(&udev, 'c', makedev(13, 64)); + int i; + + for (i = 0; pad != NULL && i < count; i++) { + const char *name = entries[i] + 2; + void *call = sym(name); + + if (call == NULL) { + printf("missing %s\n", name); + continue; + } + switch (entries[i][0]) { + case 'p': ((void *(*)(void *))call)(pad); break; + case 's': ((const char *(*)(void *))call)(pad); break; + case 'i': ((int (*)(void *))call)(pad); break; + case 'd': ((dev_t (*)(void *))call)(pad); break; + case 'u': ((unsigned long long (*)(void *))call)(pad); break; + case 'S': ((const char *(*)(void *, const char *))call)(pad, "attr"); break; + case 'I': ((int (*)(void *, const char *))call)(pad, "attr"); break; + case 'P': ((void *(*)(void *, const char *, const char *))call)(pad, "input", NULL); break; + case 'W': ((int (*)(void *, const char *, const char *))call)(pad, "attr", "value"); break; + default: printf("unknown signature %s\n", entries[i]); + } + } + printf("pad %d real calls %d\n", pad != NULL, real_calls != NULL ? *real_calls : -1); +} + static void run_probe(void) { int udev; @@ -447,6 +507,7 @@ int main(int argc, char **argv) { name = sym("udev_list_entry_get_name"); value = sym("udev_list_entry_get_value"); if (strcmp(argv[1], "probe") == 0) run_probe(); + else if (strcmp(argv[1], "every") == 0) run_every(argc - 3, argv + 3); else if (strcmp(argv[1], "stable") == 0) run_stable(); else if (strcmp(argv[1], "enumerate") == 0) run_enumerate(); else run_udev(); @@ -502,11 +563,11 @@ class InputUdevPreloadTest(unittest.TestCase): (pads / node).write_text("") return pads - def run_program(self, mode, *preloads, pads=None, slots="0=/pad", program=None): + def run_program(self, mode, *preloads, pads=None, slots="0=/pad", program=None, args=()): env = dict(os.environ, LD_PRELOAD=":".join(str(self.dir / name) for name in ("libddsession.so", *preloads)), FAKE_EVDEV_MEMFD_PATHS=slots, FAKE_EVDEV_DIR=str(pads or self.pads)) env.pop("FAKE_EVDEV_UINPUT", None) - result = subprocess.run([str(program or self.program), mode, str(self.udev)], env=env, capture_output=True, text=True, + result = subprocess.run([str(program or self.program), mode, str(self.udev), *args], env=env, capture_output=True, text=True, timeout=20) self.assertEqual(result.returncode, 0, result.stderr) return result.stdout.splitlines() @@ -554,6 +615,9 @@ class InputUdevPreloadTest(unittest.TestCase): "contexts 1 1", ]) + def test_no_device_call_on_a_pad_reaches_the_real_libudev(self): + self.assertEqual(self.run_program("every", args=DEVICE_FUNCTIONS), ["pad 1 real calls 0"]) + def test_a_handle_keeps_its_strings_after_the_pad_goes_away(self): self.assertEqual(self.run_program("stable", pads=self.pad_dir("stable", "event0")), [ "gone 1", From 1f70d43fe2d77719065baca14d038a31e239a436 Mon Sep 17 00:00:00 2001 From: Tushar Gandhe <19225304+2-Shar@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:56:39 +0530 Subject: [PATCH 028/141] feat(ui): a Launcher setting turns page swipes off, and edge swipes in landscape leave the page alone (#2924) --- .../com/droiddeck/launcher/core/AppUiPrefs.kt | 7 ++++++ .../droiddeck/launcher/ui/FrontEndScreen.kt | 4 +++- .../droiddeck/launcher/ui/FrontEndSetup.kt | 7 ++++++ .../com/droiddeck/launcher/ui/PageSwipe.kt | 24 +++++++++++++++---- .../droiddeck/launcher/ui/SettingsIndex.kt | 1 + app/src/main/res/values-ar/strings.xml | 2 ++ app/src/main/res/values-b+es+419/strings.xml | 2 ++ app/src/main/res/values-bg/strings.xml | 2 ++ app/src/main/res/values-cs/strings.xml | 2 ++ app/src/main/res/values-da/strings.xml | 2 ++ app/src/main/res/values-de/strings.xml | 2 ++ app/src/main/res/values-el/strings.xml | 2 ++ app/src/main/res/values-es/strings.xml | 2 ++ app/src/main/res/values-fi/strings.xml | 2 ++ app/src/main/res/values-fr/strings.xml | 2 ++ app/src/main/res/values-hi/strings.xml | 2 ++ app/src/main/res/values-hu/strings.xml | 2 ++ app/src/main/res/values-in/strings.xml | 2 ++ app/src/main/res/values-it/strings.xml | 2 ++ app/src/main/res/values-ja/strings.xml | 2 ++ app/src/main/res/values-ko/strings.xml | 2 ++ app/src/main/res/values-ms/strings.xml | 2 ++ app/src/main/res/values-nb/strings.xml | 2 ++ app/src/main/res/values-nl/strings.xml | 2 ++ app/src/main/res/values-pl/strings.xml | 2 ++ app/src/main/res/values-pt-rPT/strings.xml | 2 ++ app/src/main/res/values-pt/strings.xml | 2 ++ app/src/main/res/values-ro/strings.xml | 2 ++ app/src/main/res/values-ru/strings.xml | 2 ++ app/src/main/res/values-sv/strings.xml | 2 ++ app/src/main/res/values-th/strings.xml | 2 ++ app/src/main/res/values-tr/strings.xml | 2 ++ app/src/main/res/values-uk/strings.xml | 2 ++ app/src/main/res/values-vi/strings.xml | 2 ++ app/src/main/res/values-zh-rCN/strings.xml | 2 ++ app/src/main/res/values-zh-rHK/strings.xml | 2 ++ app/src/main/res/values-zh-rTW/strings.xml | 2 ++ app/src/main/res/values/strings.xml | 2 ++ docs/settings-map.md | 1 + 39 files changed, 105 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/core/AppUiPrefs.kt b/app/src/main/java/com/droiddeck/launcher/core/AppUiPrefs.kt index c4c29a2369..50af093a02 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/AppUiPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/AppUiPrefs.kt @@ -53,6 +53,13 @@ object AppUiPrefs { context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putBoolean("hide-home-from-recents", hidden).apply() } + fun pageSwipe(context: Context): Boolean = + context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).getBoolean("page-swipe", true) + + fun setPageSwipe(context: Context, on: Boolean) { + context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putBoolean("page-swipe", on).apply() + } + internal fun normalizeScale(percent: Int): Int = percent.takeIf { it in scales } ?: DEFAULT_SCALE fun scale(context: Context): Int = normalizeScale( diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt index b74e179384..0fd09b0693 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -762,6 +762,8 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com onRailSelect(key) }, a) 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 } } val agentKeyboardOpen = openTab == "agent" && WindowInsets.ime.getBottom(androidx.compose.ui.platform.LocalDensity.current) > 0 LauncherLayout( bottomNavigation && !s.dualScreen, pal.line, @@ -787,7 +789,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com ) { Pane( s, selected, a, page, - Modifier.fillMaxSize().then(paneFocus).pageSwipe({ !processSettingsPageVisible && appToChooseDisplay == null }) { dir -> + Modifier.fillMaxSize().then(paneFocus).pageSwipe({ !processSettingsPageVisible && appToChooseDisplay == null }, edgeGuard = { !bottomNavigation }) { dir -> val keys = navigationKeys(s) val at = keys.indexOf(railSelectionNow.value) if (at >= 0) keys.getOrNull(at + dir)?.let { key -> diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt index ec3b1c1b55..bb299cc06b 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -516,6 +516,13 @@ internal fun SetupPanel( if (s.launcherFullscreen) stringResource(R.string.setup_fullscreen_on) else stringResource(R.string.setup_fullscreen_off), s.launcherFullscreen, ) { a.onLauncherFullscreen(it) } + ToggleRow( + host, "page-swipe", stringResource(R.string.setup_page_swipe), + stringResource(R.string.setup_page_swipe_hint), PageSwipe.on, + ) { on -> + PageSwipe.on = on + com.droiddeck.launcher.core.AppUiPrefs.setPageSwipe(ctx, on) + } ToggleRow( host, "controller-haptics", stringResource(R.string.setup_controller_haptics), stringResource(R.string.setup_controller_haptics_hint), diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PageSwipe.kt b/app/src/main/java/com/droiddeck/launcher/ui/PageSwipe.kt index 3e4b57fb26..e510dbc848 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PageSwipe.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PageSwipe.kt @@ -6,6 +6,8 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset @@ -13,26 +15,40 @@ import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.input.pointer.util.VelocityTracker import androidx.compose.ui.input.pointer.util.addPointerInputChange +import androidx.compose.ui.layout.LayoutCoordinates +import androidx.compose.ui.layout.findRootCoordinates +import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.unit.dp import kotlin.math.abs internal object PageSwipe { var locks by mutableIntStateOf(0) var direction by mutableIntStateOf(0) + var on by mutableStateOf(true) } @Composable -internal fun Modifier.pageSwipe(enabled: () -> Boolean, onSwipe: (Int) -> Unit): Modifier { +internal fun Modifier.pageSwipe(enabled: () -> Boolean, edgeGuard: () -> Boolean = { false }, onSwipe: (Int) -> Unit): Modifier { val enabledNow by rememberUpdatedState(enabled) + val edgeGuardNow by rememberUpdatedState(edgeGuard) val onSwipeNow by rememberUpdatedState(onSwipe) - return pointerInput(Unit) { + val placed = remember { arrayOfNulls(1) } + return onGloballyPositioned { placed[0] = it }.pointerInput(Unit) { val distance = 72.dp.toPx() val flingDistance = 32.dp.toPx() val flingVelocity = 900.dp.toPx() val slop = viewConfiguration.touchSlop + val edge = 32.dp.toPx() awaitEachGesture { val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Final) - if (!enabledNow() || PageSwipe.locks > 0) return@awaitEachGesture + if (!PageSwipe.on || !enabledNow() || PageSwipe.locks > 0) return@awaitEachGesture + // A swipe in from the screen's edge brings back hidden system bars; it should not also turn the page. + if (edgeGuardNow()) { + val at = placed[0]?.takeIf { it.isAttached } + val x = at?.localToRoot(down.position)?.x ?: down.position.x + val width = at?.findRootCoordinates()?.size?.width?.toFloat() ?: size.width.toFloat() + if (x < edge || x > width - edge) return@awaitEachGesture + } val tracker = VelocityTracker() tracker.addPointerInputChange(down) var total = Offset.Zero @@ -48,7 +64,7 @@ internal fun Modifier.pageSwipe(enabled: () -> Boolean, onSwipe: (Int) -> Unit): if (!mine && abs(total.x) > slop && abs(total.x) > abs(total.y) * 2f) mine = true if (mine) change.consume() } - if (!mine || PageSwipe.locks > 0) return@awaitEachGesture + if (!mine || !PageSwipe.on || PageSwipe.locks > 0) return@awaitEachGesture val vx = tracker.calculateVelocity().x val horizontal = abs(total.x) > abs(total.y) * 1.5f val far = abs(total.x) > distance diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt index baa2b0e69a..cda181d501 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt @@ -108,6 +108,7 @@ internal object SettingsIndex { s(SettingsSection.LAUNCHER, R.string.setup_launcher_orientation, "rotate", "portrait"), s(SettingsSection.LAUNCHER, R.string.setup_session_orientation, "rotate", "portrait"), s(SettingsSection.LAUNCHER, R.string.setup_fullscreen), + s(SettingsSection.LAUNCHER, R.string.setup_page_swipe, "gesture"), s(SettingsSection.LAUNCHER, R.string.setup_controller_haptics, "vibration", "rumble"), s(SettingsSection.LAUNCHER, R.string.setup_dual_screen_launcher, "thor", "second screen", "bottom screen"), s(SettingsSection.LAUNCHER, R.string.setup_low_storage_warning), diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 32f76cd6db..b6b06e6f1c 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -971,6 +971,8 @@ ملء الشاشة يخفي شريطي الحالة والتنقّل في Android يعرض شريطي الحالة والتنقّل في Android + التمرير بين الصفحات + اسحب عبر الصفحة لتغيير علامة التبويب. المشغّل على شاشتين يضع الوضع «تلقائي» أقسام المشغّل (Steam والمكتبة والمتاجر وغيرها) على الشاشة الثانية في الأجهزة المحمولة المزوّدة بشاشة ثانية مدمجة. ويستخدم الوضع «تشغيل» أي شاشة ثانية. أما الوضع «إيقاف» فيُبقي المشغّل على شاشة واحدة. الجلسات على شاشتين diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index e0dda7fdc0..7105d0010e 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -989,6 +989,8 @@ Pantalla completa Oculta las barras de estado y navegación de Android Muestra las barras de estado y navegación de Android + Deslizar entre páginas + Desliza sobre una página para cambiar de pestaña. Lanzador de doble pantalla Automático coloca las secciones del lanzador (Steam, Biblioteca, Tiendas y las demás) en la segunda pantalla integrada de las consolas portátiles que la tienen. Activado usa cualquier segunda pantalla. Desactivado mantiene el lanzador en una sola pantalla. Sesiones de doble pantalla diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index 0fdc0b1918..e899caa026 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -959,6 +959,8 @@ Цял екран Скрива лентите за състояние и навигация на Android Показва лентите за състояние и навигация на Android + Плъзгане между страниците + Плъзнете по страница, за да смените раздела. Лаунчер с два екрана Автоматично: секциите на лаунчера (Steam, Библиотека, Магазини и останалите) се показват на втория екран при преносими устройства с вграден такъв. Включено: използва се всеки втори дисплей. Изключено: лаунчерът остава на един екран. Сесии с два екрана diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 59d74654f3..1878c9e970 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -965,6 +965,8 @@ Celá obrazovka Skryje stavový a navigační panel Androidu Zobrazí stavový a navigační panel Androidu + Přejíždění mezi stránkami + Přejetím přes stránku přepnete kartu. Spouštěč na dvou obrazovkách Automaticky přesune sekce spouštěče (Steam, Knihovna, Obchody a ostatní) na druhou obrazovku handheldů, které ji mají vestavěnou. Zapnuto použije libovolný druhý displej. Vypnuto ponechá spouštěč na jedné obrazovce. Relace na dvou obrazovkách diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 9964a06315..0de6201954 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -959,6 +959,8 @@ Fuldskærm Skjuler Androids status- og navigationsbjælker Viser Androids status- og navigationsbjælker + Stryg mellem sider + Stryg hen over en side for at skifte fane. Launcher til to skærme Automatisk placerer launcherens sektioner (Steam, Bibliotek, Butikker og resten) på den anden skærm på håndholdte enheder med en indbygget anden skærm. Til bruger enhver ekstra skærm. Fra holder launcheren på én skærm. Sessioner på to skærme diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index bcb221a120..28df13a1fc 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -951,6 +951,8 @@ Vollbild Blendet die Status- und Navigationsleiste von Android aus Zeigt die Status- und Navigationsleiste von Android an + Zwischen Seiten wischen + Über eine Seite wischen, um den Tab zu wechseln. Dual-Screen-Launcher Bei Automatisch liegen die Launcher-Bereiche (Steam, Bibliothek, Shops und die übrigen) auf dem zweiten Bildschirm von Handhelds mit integriertem zweitem Bildschirm. Ein nutzt einen beliebigen zweiten Bildschirm. Aus belässt den Launcher auf einem Bildschirm. Dual-Screen-Sitzungen diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index f5bd31d63c..8596d16797 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -959,6 +959,8 @@ Πλήρης οθόνη Αποκρύπτει τις γραμμές κατάστασης και πλοήγησης του Android Εμφανίζει τις γραμμές κατάστασης και πλοήγησης του Android + Σάρωση μεταξύ σελίδων + Σαρώστε κατά μήκος μιας σελίδας για να αλλάξετε καρτέλα. Εκκινητής διπλής οθόνης Η επιλογή Αυτόματα τοποθετεί τις ενότητες του εκκινητή (Steam, Βιβλιοθήκη, Καταστήματα και τις υπόλοιπες) στη δεύτερη οθόνη των φορητών κονσολών με ενσωματωμένη δεύτερη οθόνη. Η επιλογή Ενεργό χρησιμοποιεί οποιαδήποτε δεύτερη οθόνη. Η επιλογή Ανενεργό κρατά τον εκκινητή σε μία οθόνη. Συνεδρίες διπλής οθόνης diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 47a00a8435..40a6f4076d 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -962,6 +962,8 @@ Pantalla completa Oculta las barras de estado y navegación de Android Muestra las barras de estado y navegación de Android + Deslizar entre páginas + Desliza sobre una página para cambiar de pestaña. Lanzador de doble pantalla Automático coloca las secciones del lanzador (Steam, Biblioteca, Tiendas y el resto) en la segunda pantalla de las consolas portátiles que la llevan integrada. Activado usa cualquier segunda pantalla. Desactivado mantiene el lanzador en una sola pantalla. Sesiones de doble pantalla diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 64792a6d6d..7ac8d04517 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -959,6 +959,8 @@ Koko näyttö Piilottaa Androidin tila- ja navigointipalkit Näyttää Androidin tila- ja navigointipalkit + Pyyhkäise sivujen välillä + Vaihda välilehteä pyyhkäisemällä sivun poikki. Kahden näytön käynnistin Automaattinen siirtää käynnistimen osiot (Steam, Kirjasto, Kaupat ja muut) käsikonsolin sisäänrakennetulle toiselle näytölle. Päällä käyttää mitä tahansa toista näyttöä. Pois päältä pitää käynnistimen yhdellä näytöllä. Kahden näytön istunnot diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index ee7bbbb419..8a6f3d0078 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -962,6 +962,8 @@ Plein écran Masquer la barre d\'état et la barre de navigation Android Afficher la barre d\'état et la barre de navigation Android + Balayer entre les pages + Balayez une page pour changer d\'onglet. Lanceur double écran Automatique place les sections du lanceur (Steam, Bibliothèque, Boutiques et les autres) sur le second écran intégré des consoles portables qui en sont équipées. Activé utilise n\'importe quel écran secondaire. Désactivé conserve le lanceur sur un seul écran. Sessions double écran diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index be2c9d973e..b71ab1c9fd 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -959,6 +959,8 @@ फ़ुलस्क्रीन Android स्टेटस और नेविगेशन बार छिपाता है Android स्टेटस और नेविगेशन बार दिखाता है + पेजों के बीच स्वाइप करें + टैब बदलने के लिए किसी पेज पर स्वाइप करें। डुअल स्क्रीन लॉन्चर स्वचालित पर, बिल्ट-इन दूसरी स्क्रीन वाले हैंडहेल्ड में लॉन्चर के सेक्शन (Steam, लाइब्रेरी, स्टोर्स और बाकी) दूसरी स्क्रीन पर चले जाते हैं। चालू पर कोई भी दूसरी डिस्प्ले इस्तेमाल होती है। बंद पर लॉन्चर एक ही स्क्रीन पर रहता है। डुअल स्क्रीन सत्र diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 2cb432d717..500ab21232 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -959,6 +959,8 @@ Teljes képernyő Elrejti az Android állapot- és navigációs sávokat Megjeleníti az Android állapot- és navigációs sávokat + Lapozás csúsztatással + Csúsztasson végig egy oldalon a lapváltáshoz. Kétképernyős indító Az Automatikus mód a beépített második képernyővel rendelkező kézi eszközökön a második képernyőre helyezi az indító szakaszait (Steam, Könyvtár, Áruházak és a többi). A Be mód bármely második kijelzőt használ. A Ki mód egy képernyőn tartja az indítót. Kétképernyős munkamenetek diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index c8449cb389..9db5098f65 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -956,6 +956,8 @@ Layar penuh Menyembunyikan bilah status dan navigasi Android Menampilkan bilah status dan navigasi Android + Geser antarhalaman + Geser melintasi halaman untuk berganti tab. Peluncur layar ganda Otomatis menempatkan bagian peluncur (Steam, Pustaka, Toko, dan bagian lainnya) pada layar kedua bawaan perangkat genggam. Aktif memakai layar kedua mana pun. Nonaktif membuat peluncur tetap di satu layar saja. Sesi layar ganda diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 51f13aee73..906391587b 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -954,6 +954,8 @@ Schermo intero Nasconde la barra di stato e la barra di navigazione di Android Mostra la barra di stato e la barra di navigazione di Android + Scorri tra le pagine + Scorri su una pagina per cambiare scheda. Launcher a doppio schermo Automatico colloca le sezioni del launcher (Steam, Libreria, Store e le altre) sullo schermo secondario integrato delle console portatili che ne hanno uno. Con Attivo si usa qualsiasi display secondario. Con Disattivo il launcher resta su un solo schermo. Sessioni a doppio schermo diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index ea088f306b..edd13096f5 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -956,6 +956,8 @@ 全画面 Androidのステータスバーとナビゲーションバーを非表示 Androidのステータスバーとナビゲーションバーを表示 + スワイプでページを切り替え + ページを横切るようにスワイプすると、タブを切り替えます。 デュアルスクリーンランチャー 自動では、内蔵セカンドスクリーンを搭載した携帯ゲーム機で、ランチャーの各セクション(Steam、ライブラリ、ストアなど)を2画面目に表示します。オンでは任意のセカンドディスプレイを使用します。オフではランチャーを1画面に留めます。 デュアルスクリーンセッション diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 96ee8f2ab4..ce2a976f06 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -956,6 +956,8 @@ 전체 화면 Android 상태 표시줄 및 탐색 표시줄 숨기기 Android 상태 표시줄 및 탐색 표시줄 표시 + 스와이프로 페이지 전환 + 페이지를 가로질러 스와이프하면 탭이 바뀝니다. 듀얼 화면 런처 자동은 내장 두 번째 화면이 있는 휴대용 기기에서 런처 섹션(Steam, 라이브러리, 스토어 등)을 두 번째 화면에 표시합니다. 켜기는 어떤 두 번째 디스플레이든 사용합니다. 끄기는 런처를 한 화면에 유지합니다. 듀얼 화면 세션 diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index 0ad66431af..de79562b86 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -956,6 +956,8 @@ Skrin penuh Menyembunyikan bar status dan navigasi Android Memaparkan bar status dan navigasi Android + Leret antara halaman + Leret merentasi halaman untuk menukar tab. Pelancar dwi skrin Automatik meletakkan bahagian pelancar (Steam, Pustaka, Kedai dan selebihnya) pada skrin kedua terbina dalam peranti genggam. Hidup menggunakan sebarang paparan kedua. Mati mengekalkan pelancar pada satu skrin. Sesi dwi skrin diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index 9f2085f5ec..59188336c8 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -959,6 +959,8 @@ Fullskjerm Skjuler Androids status- og navigasjonslinjer Viser Androids status- og navigasjonslinjer + Sveip mellom sider + Sveip over en side for å bytte fane. Startprogram på to skjermer Automatisk plasserer startprogrammets deler (Steam, Bibliotek, Butikker og resten) på den andre skjermen på håndholdte enheter med innebygd sekundærskjerm. På bruker en hvilken som helst annen skjerm. Av holder startprogrammet på én skjerm. Økter på to skjermer diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 9e00bc86e3..11232dcc4a 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -959,6 +959,8 @@ Volledig scherm Verbergt de statusbalk en navigatiebalk van Android Toont de statusbalk en navigatiebalk van Android + Vegen tussen pagina\'s + Veeg over een pagina om van tabblad te wisselen. Launcher op twee schermen Automatisch zet de launchersecties (Steam, Bibliotheek, Winkels en de rest) op het tweede scherm van handhelds met een ingebouwd exemplaar. Aan gebruikt elk tweede scherm. Uit houdt de launcher op één scherm. Sessies op twee schermen diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 25768ef8f7..bfa42a349b 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -965,6 +965,8 @@ Pełny ekran Ukrywa systemowe paski stanu i nawigacji Pokazuje systemowe paski stanu i nawigacji + Przesuwanie między stronami + Przesuń palcem po stronie, aby zmienić kartę. Launcher na dwóch ekranach Automatycznie umieszcza sekcje launchera (Steam, Biblioteka, Sklepy i pozostałe) na wbudowanym drugim ekranie konsol przenośnych. Włączone używa dowolnego drugiego wyświetlacza. Wyłączone pozostawia launcher na jednym ekranie. Sesje na dwóch ekranach diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 51ea157863..a1d7069d48 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -954,6 +954,8 @@ Ecrã inteiro Oculta as barras de estado e de navegação do Android Mostra as barras de estado e de navegação do Android + Deslizar entre páginas + Deslize sobre uma página para mudar de separador. Iniciador de ecrã duplo Automático coloca as secções do iniciador (Steam, Biblioteca, Lojas e as restantes) no segundo ecrã das consolas portáteis com um segundo ecrã integrado. Ativado utiliza qualquer segundo ecrã. Desativado mantém o iniciador num único ecrã. Sessões de ecrã duplo diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index c10d3cfa7c..1e40678db5 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -961,6 +961,8 @@ Tela cheia Oculta as barras de status e de navegação do Android Mostra as barras de status e de navegação do Android + Deslizar entre páginas + Deslize sobre uma página para mudar de aba. Iniciador em duas telas O modo automático coloca as seções do iniciador (Steam, Biblioteca, Lojas e as demais) na segunda tela de consoles portáteis com uma tela secundária integrada. Ativado usa qualquer tela secundária. Desativado mantém o iniciador em uma única tela. Sessões em duas telas diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index e74bec3b84..8b626e5149 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -962,6 +962,8 @@ Ecran complet Ascunde barele de stare și de navigare Android Arată barele de stare și de navigare Android + Glisare între pagini + Glisați peste o pagină pentru a schimba fila. Lansator pe două ecrane Automat plasează secțiunile lansatorului (Steam, Bibliotecă, Magazine și celelalte) pe ecranul secundar al consolelor portabile cu unul integrat. Activat folosește orice ecran secundar. Dezactivat păstrează lansatorul pe un singur ecran. Sesiuni pe două ecrane diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index de792927ec..81e2120b02 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -965,6 +965,8 @@ Полноэкранный режим Скрывает строку состояния и панель навигации Android Показывает строку состояния и панель навигации Android + Перелистывание страниц свайпом + Проведите по странице, чтобы сменить вкладку. Лаунчер на двух экранах «Автоматически» переносит разделы лаунчера (Steam, Библиотека, Магазины и остальные) на второй экран портативных устройств со встроенным вторым экраном. «Вкл.» использует любой второй дисплей. «Выкл.» оставляет лаунчер на одном экране. Сессии на двух экранах diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 8e951147a9..98df4caab6 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -959,6 +959,8 @@ Helskärm Döljer Androids statusfält och navigeringsfält Visar Androids statusfält och navigeringsfält + Svep mellan sidor + Svep över en sida för att byta flik. Startprogram för två skärmar Automatiskt: placerar startprogrammets avsnitt (Steam, Bibliotek, Butiker med flera) på den inbyggda andra skärmen på handhållna enheter som har en. På: använder vilken andra bildskärm som helst. Av: behåller startprogrammet på en skärm. Sessioner med två skärmar diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 1a826fcb28..d9e1de3e60 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -956,6 +956,8 @@ เต็มจอ ซ่อนแถบสถานะและแถบนำทางของ Android แสดงแถบสถานะและแถบนำทางของ Android + ปัดเพื่อเปลี่ยนหน้า + ปัดผ่านหน้าเพื่อเปลี่ยนแท็บ ลอนเชอร์แบบสองจอ โหมดอัตโนมัติจะแสดงส่วนต่างๆ ของลอนเชอร์ (Steam, คลังเกม, ร้านค้า และส่วนอื่นๆ) บนจอที่สองของเครื่องเล่นพกพาที่มีจอที่สองในตัว โหมดเปิดใช้จอที่สองใดก็ได้ โหมดปิดจะแสดงลอนเชอร์บนจอเดียว เซสชันแบบสองจอ diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 3644798c45..b5e3ec8893 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -951,6 +951,8 @@ Tam ekran Android durum ve gezinme çubuklarını gizler Android durum ve gezinme çubuklarını gösterir + Sayfalar arasında kaydır + Sekme değiştirmek için sayfa boyunca kaydırın. Çift ekranlı başlatıcı Otomatik, yerleşik ikinci ekranı olan el konsollarında başlatıcı bölümlerini (Steam, Kitaplık, Mağazalar ve diğerleri) ikinci ekrana yerleştirir. Açık, herhangi bir ikinci ekranı kullanır. Kapalı, başlatıcıyı tek ekranda tutar. Çift ekranlı oturumlar diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 6f67409b1a..c6d9b97b8e 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -965,6 +965,8 @@ Повний екран Приховує рядок стану та панель навігації Android Показує рядок стану та панель навігації Android + Гортання сторінок свайпом + Проведіть по сторінці, щоб змінити вкладку. Лаунчер для двох екранів Автоматичний режим розміщує розділи лаунчера (Steam, Бібліотека, Магазини тощо) на вбудованому другому екрані портативних пристроїв. У режимі «Увімкнено» використовується будь-який другий дисплей. У режимі «Вимкнено» лаунчер залишається на одному екрані. Сеанси для двох екранів diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 5c5d7e4077..ac4f7e24fc 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -956,6 +956,8 @@ Toàn màn hình Ẩn thanh trạng thái và thanh điều hướng của Android Hiện thanh trạng thái và thanh điều hướng của Android + Vuốt để chuyển trang + Vuốt ngang trang để đổi thẻ. Trình khởi chạy hai màn hình Tự động đưa các phần của trình khởi chạy (Steam, Thư viện, Cửa hàng và phần còn lại) lên màn hình thứ hai tích hợp của máy cầm tay. Bật dùng bất kỳ màn hình thứ hai nào. Tắt giữ trình khởi chạy trên một màn hình. Phiên chơi hai màn hình diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 1d181502b1..d7be53560a 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -956,6 +956,8 @@ 全屏 隐藏 Android 状态栏和导航栏 显示 Android 状态栏和导航栏 + 滑动切换页面 + 在页面上滑动即可切换标签。 双屏启动器 自动会把启动器的各个板块(Steam、库、商店等)放到带内置副屏的掌机的第二块屏幕上。开启使用任意第二块显示屏。关闭则让启动器只显示在一块屏幕上。 双屏会话 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index a4d0cca3f2..8bee7a52bd 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -955,6 +955,8 @@ 全螢幕 隱藏 Android 狀態列和導覽列 顯示 Android 狀態列和導覽列 + 滑動切換頁面 + 在頁面上滑動即可切換標籤。 雙螢幕啟動器 自動會把啟動器各部分(Steam、收藏庫、商店及其他部分)放到內建雙螢幕手持裝置的第二螢幕。開啟會使用任何第二顯示器。關閉會將啟動器保持在單一螢幕。 雙螢幕工作階段 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index b0462383cf..9aff9a0931 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -955,6 +955,8 @@ 全螢幕 隱藏 Android 狀態列和導覽列 顯示 Android 狀態列和導覽列 + 滑動切換頁面 + 在頁面上滑動即可切換分頁。 雙螢幕啟動器 自動:在內建第二螢幕的掌機上,將啟動器區塊(Steam、收藏庫、商店等)放到第二螢幕。開啟:使用任一第二螢幕。關閉:啟動器維持在單一螢幕。 雙螢幕工作階段 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 579e08c381..f4357d67bd 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1035,6 +1035,8 @@ Fullscreen Hides the Android status and navigation bars Shows the Android status and navigation bars + Swipe between pages + Swipe across a page to change tabs. Controller haptics A light tick when the D-pad, A or the shoulder buttons move or select in the launcher. Touch stays silent Dual screen launcher diff --git a/docs/settings-map.md b/docs/settings-map.md index a292309bc9..6b13633780 100644 --- a/docs/settings-map.md +++ b/docs/settings-map.md @@ -44,6 +44,7 @@ Links of the form `droiddeck://settings/
` open a Settings section direc | Launcher orientation | Settings › Launcher (`droiddeck://settings/launcher`) | rotate, portrait | | Session orientation | Settings › Launcher (`droiddeck://settings/launcher`) | rotate, portrait | | Fullscreen | Settings › Launcher (`droiddeck://settings/launcher`) | | +| Swipe between pages | Settings › Launcher (`droiddeck://settings/launcher`) | gesture | | Controller haptics | Settings › Launcher (`droiddeck://settings/launcher`) | vibration, rumble | | Dual screen launcher | Settings › Launcher (`droiddeck://settings/launcher`) | thor, second screen, bottom screen | | Warn when storage is low | Settings › Launcher (`droiddeck://settings/launcher`) | | From 501debc7f6e6ef6d5d5a644f362856cc9c535641 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Sun, 22 Nov 2026 09:31:40 -0500 Subject: [PATCH 029/141] fix(game-env): Dragon's Dogma 2 starts with its Wine detection off (#3011) Dragon's Dogma 2 checks for Wine and takes a path that does not start. Launches of Steam app 2054970 now append the game's own /WineDetectionEnabled:False switch at launch time. Steam's stored Launch Options are untouched, and a /WineDetectionEnabled: value the user already passes keeps priority and is not repeated. --- docs/development/game-environment.md | 6 ++++++ .../linuxfs/overlay/usr/local/bin/droiddeck-game-env | 6 ++++++ tools/tests/test_game_environment.py | 12 ++++++++++++ 3 files changed, 24 insertions(+) diff --git a/docs/development/game-environment.md b/docs/development/game-environment.md index ac7be74c62..8d366151e6 100644 --- a/docs/development/game-environment.md +++ b/docs/development/game-environment.md @@ -293,6 +293,12 @@ configuration falls back to the inherited environment without evaluating its contents. Both component and environment selection normalize signed non-Steam prefix IDs to unsigned IDs. +A Dragon's Dogma 2 launch (Steam app 2054970) appends the game's own +`/WineDetectionEnabled:False` switch: the game checks for Wine and its Wine path +does not start. The switch is added only at launch, never to Steam's stored +Launch Options, and a user's own `/WineDetectionEnabled:` value in Launch +Options keeps priority and is not repeated. + The published file also carries generated `dxvkConfig` and `dxvkConfigGames` values the app's own file never has. The session menu's texture filtering (`core/TextureFiltering`) becomes `d3d9/d3d11.samplerAnisotropy` and diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env index b4b574a0aa..a465a93859 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env @@ -152,6 +152,12 @@ def deep_rock_gdk_raytracing(game): return {}, ["-noraytracing", "-ini:Engine:[/Script/Engine.RendererSettings]:r.RayTracing=False"], "Deep Rock Galactic GDK: ray tracing off (D3D12 pipeline creation fails on Thor)" +@fix +def dragons_dogma_2_wine_detection(game): + if game.app_id == "2054970" and not any(a.lower().startswith("/winedetectionenabled:") for a in game.args): + return {}, ["/WineDetectionEnabled:False"], "Dragon's Dogma 2: the game's Wine detection off (its Wine path does not start)" + + @fix def ff7_rebirth_feature_level(game): if game.stem in ("ff7rebirth", "ff7rebirth_"): diff --git a/tools/tests/test_game_environment.py b/tools/tests/test_game_environment.py index 41f05beb83..e2a6d85385 100644 --- a/tools/tests/test_game_environment.py +++ b/tools/tests/test_game_environment.py @@ -1536,6 +1536,18 @@ class GameEnvironmentTest(unittest.TestCase): self.assertEqual(MODULE["engine_fixes"]("/game/FSD-Win64-Shipping.exe", []), ({}, [], [])) self.assertEqual(MODULE["engine_fixes"]("/game/Other-WinGDK-Shipping.exe", []), ({}, [], [])) + def test_dragons_dogma_2_turns_its_wine_detection_off_unless_the_user_sets_it(self): + game = "/game/Dragons Dogma 2/DD2.exe" + env, extra, notes = MODULE["engine_fixes"](game, [], "2054970") + self.assertEqual(extra, ["/WineDetectionEnabled:False"]) + self.assertEqual(env, {}) + self.assertTrue(notes) + self.assertEqual(MODULE["engine_fixes"](game, ["-dx12"], "2054970")[1], ["/WineDetectionEnabled:False"]) + for own in ("/WineDetectionEnabled:False", "/WineDetectionEnabled:True", "/winedetectionenabled:false"): + self.assertEqual(MODULE["engine_fixes"](game, [own], "2054970"), ({}, [], [])) + self.assertEqual(MODULE["engine_fixes"](game, [], "42"), ({}, [], [])) + self.assertEqual(MODULE["engine_fixes"](game, []), ({}, [], [])) + def test_arkham_city_gets_full_x87_precision_over_the_preset(self): with tempfile.TemporaryDirectory() as tmp: city = Path(tmp) / "Batman Arkham City GOTY/Binaries/Win32" From 42f25c2a6c1a7c81108aa9679a20319cb19f8a91 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Sun, 22 Nov 2026 09:51:32 -0500 Subject: [PATCH 030/141] fix(input): controls edited in portrait keep their places in the panel below the game (#3013) * fix(input): controls edited in portrait keep their places in the panel below the game The panel below the game in portrait always regenerated the stock layout, so positions saved from the Controls editor were dropped and only the button styling carried over. The panel now orients to the portrait frame and fits the edited controls into the panel at their saved proportions; untouched stock layouts keep the generated panel. * Keep the Deck panel's trackpads and fitted sizes for edited portrait controls --- .../launcher/input/OnScreenLayout.kt | 27 +++++++++-- .../launcher/input/OnScreenLayoutTest.kt | 45 +++++++++++++++++++ 2 files changed, 69 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt b/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt index 33d951a626..ad5d8e2701 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt @@ -31,17 +31,20 @@ 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 { if (saved == null) return emptyList() if (width <= 0 || height <= 0) return saved.elements - val layout = oriented(saved, width, height) + val layout = oriented(saved, dock?.portrait ?: (height > width)) 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() @@ -70,8 +73,9 @@ object OnScreenLayout { .place(ordered, lowerShortcuts = generated, rearButtons = rearButtons, trackpads = trackpads) } - fun oriented(layout: SavedInputLayout, width: Int, height: Int): SavedInputLayout { - val portrait = height > width + fun oriented(layout: SavedInputLayout, width: Int, height: Int): SavedInputLayout = oriented(layout, height > width) + + private fun oriented(layout: SavedInputLayout, portrait: Boolean): SavedInputLayout { 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 } + @@ -131,6 +135,23 @@ object OnScreenLayout { } } + private fun cluster(elements: List, aspect: Float, width: Int, height: Int, safe: Rect): List { + 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 diff --git a/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt index d465b87a67..1fa557b6d9 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt @@ -307,6 +307,51 @@ class OnScreenLayoutTest { assertEquals(.1f * 2208f / 1768 / .2f, fitted.width * 2208 / (fitted.height * 800), .01f) } + @Test fun controlsEditedInPortraitKeepTheirPlacesInThePanelBelowTheGame() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE) + val (w, h) = 1080 to 2400 + val stock = gamepad() + val shown = OnScreenLayout.editorElements(context, stock, w, h) + val moved = shown.map { if (it.id == "legacy:a") it.copy(x = .05f) else if (it.id == "legacy:ls") it.copy(x = .6f) else it } + val edited = OnScreenLayout.withFrame(context, stock, OnScreenLayout.editorFrame(stock, moved), w.toFloat() / h) + val shownA = shown.first { it.id == "legacy:a" } + for (panelHeight in listOf(1100, 800)) { + val placed = OnScreenLayout.elements(context, edited, w, panelHeight, Rect(), dock = OnScreenLayout.Dock(true, false)) + val a = placed.first { it.id == "legacy:a" } + val ls = placed.first { it.id == "legacy:ls" } + val b = placed.first { it.id == "legacy:b" } + assertTrue(a.x < .2f) + assertTrue(ls.x > .5f) + assertTrue(b.x > a.x) + assertNull(placed.firstOrNull { it.id == "builtin:keyboard" || it.control == InputControl.GUIDE || it.control == InputControl.QAM }) + assertInside(placed, w, panelHeight) + assertEquals(shownA.width * w / (shownA.height * h), a.width * w / (a.height * panelHeight), .01f) + val untouched = OnScreenLayout.elements(context, stock, w, panelHeight, Rect(), dock = OnScreenLayout.Dock(true, false)) + assertTrue(untouched.first { it.id == "legacy:a" }.x > .5f) + assertTrue(untouched.first { it.id == "legacy:ls" }.x < .5f) + } + val landscape = OnScreenLayout.elements(context, edited, 2400, 1080, Rect()) + assertTrue(landscape.first { it.id == "legacy:a" }.x > .5f) + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK) + val deck = OnScreenLayout.elements(context, edited, w, 1100, Rect(), dock = OnScreenLayout.Dock.deck(true, null), trackpads = true) + assertTrue(deck.none { it.id == "legacy:rs" }) + assertTrue(deck.any { it.kind == InputElementKind.TRACKPAD && it.x + it.width / 2f > .5f }) + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE) + val tiny = stock.copy(aspect = .45f, elements = stock.elements.map { + when (it.id) { + "legacy:a" -> it.copy(x = .05f, y = .05f, width = .1f, height = .045f) + "legacy:b" -> it.copy(x = .16f, y = .05f, width = .1f, height = .045f) + "legacy:ls" -> it.copy(x = .8f, y = .85f, width = .15f, height = .1f) + else -> it + } + }, rotated = emptyList()) + val short = OnScreenLayout.elements(context, tiny, w, 385, Rect(), dock = OnScreenLayout.Dock(true, false)) + val sa = short.first { it.id == "legacy:a" } + val sb = short.first { it.id == "legacy:b" } + assertTrue(sa.x + sa.width <= sb.x) + assertEquals(1f, sa.width * w / (sa.height * 385), .01f) + } + @Test fun thePortraitAndBelowGameKitsKeepDirectionalArtClearOfTheSticksAndFaceButtons() { val directions = setOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT) val face = setOf(InputControl.A, InputControl.B, InputControl.X, InputControl.Y) From a9b5994a9126817193482d7055010e5716190786 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Sun, 22 Nov 2026 10:52:25 -0500 Subject: [PATCH 031/141] fix(library): drop the card's bottom gradient when it has no text to show (#3017) --- .../com/droiddeck/launcher/ui/LibraryPage.kt | 25 +++++++++++++------ 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt index d901b1a68f..0181d39398 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt @@ -90,6 +90,7 @@ 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 @@ -1121,14 +1122,22 @@ internal fun ArtCard( } val showName = LibraryDisplay.title || hot val showDetail = LibraryDisplay.size || hot - 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 (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 (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) From cb7edbefd2d1dc8001244485a7d416f26f833ca1 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Sun, 22 Nov 2026 10:56:03 -0500 Subject: [PATCH 032/141] fix(input): show the main screen layout editor first, like the second screen (#3019) The Screen visibility group sat above the Layout group on the Main screen page, so in landscape its description pushed Edit on screen below the fold and the page looked like it had no editor. The Layout group now comes first on both screens. --- .../com/droiddeck/launcher/ui/InputSettingsPage.kt | 12 ++++++------ .../com/droiddeck/launcher/ui/InputSettingsTest.kt | 12 ++++++++++++ 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt index bd319dc2d9..2fe1346034 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt @@ -267,12 +267,6 @@ 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) @@ -288,6 +282,12 @@ 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 })) diff --git a/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt index cda4bbeb9a..ac643381a5 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt @@ -258,6 +258,18 @@ class InputSettingsTest { compose.onNodeWithTag("input-layout-canvas").assertExists() } + @Test fun everyScreenOpensWithItsEditorFirst() { + compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } + compose.onNodeWithTag("input-profile-game").performScrollTo().performClick() + val tops = listOf("primary", "secondary").map { screen -> + compose.onNodeWithTag("input-part-$screen").performScrollTo().performClick() + val top = compose.onNodeWithTag("input-surface-$screen").assertIsDisplayed().fetchSemanticsNode().boundsInRoot.top + compose.onNodeWithText(context.getString(R.string.mode_back)).performClick() + top + } + assertEquals(tops[1], tops[0]) + } + @Test fun deviceSettingsAreInlineBelowProfiles() { compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } compose.onNodeWithTag("input-more").assertDoesNotExist() From c6b6e7362e3676deeced5e6ada17b56105c9b87e Mon Sep 17 00:00:00 2001 From: Tushar Gandhe <19225304+2-Shar@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:01:46 +0530 Subject: [PATCH 033/141] fix(ui): game page main action above its box, and tabs that scroll and slide (#2994) --- .../com/droiddeck/launcher/ui/AddAppDialog.kt | 2 +- .../droiddeck/launcher/ui/FrontEndWidgets.kt | 2 + .../com/droiddeck/launcher/ui/GameDetail.kt | 295 +++++++++++------- .../com/droiddeck/launcher/ui/GameGlass.kt | 1 + .../droiddeck/launcher/ui/SettingsWidgets.kt | 6 +- 5 files changed, 198 insertions(+), 108 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt index f93395bb31..df8bc0ed89 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt @@ -360,7 +360,7 @@ internal fun AppDialog( .then(if (scrollable) Modifier.verticalScroll(scrollState) else Modifier) .padding(horizontal = 18.dp, vertical = 16.dp), ) { - content() + androidx.compose.runtime.CompositionLocalProvider(LocalRevealChecked provides true) { content() } if (side != null && !beside) side() } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt index 6bc4fd2149..faa4667306 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt @@ -211,6 +211,7 @@ internal fun PrimaryButton( val pal = LocalPalette.current 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++ @@ -234,6 +235,7 @@ internal fun PrimaryButton( .clip(btnShape) .background(if (enabled) Brush.linearGradient(listOf(colors.primary, pal.primary2)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surfaceVariant))) .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) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt index ab54f3e2cb..25dba6fe37 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt @@ -75,6 +75,7 @@ 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 @@ -131,6 +132,9 @@ 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? = when { @@ -254,12 +258,18 @@ internal fun GameDetail( color = MaterialTheme.colorScheme.error, maxLines = 3, overflow = TextOverflow.Ellipsis, ) Spacer(Modifier.height(2.dp)) - GameCapsule(scores) { GameActions(store, id, game, item, installed, s, a, Modifier.focusRequester(lead), compactMenu = stacked, inStore = inStore) } + 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) } + } } } if (StoresMotion.heroLands) header() else Rise(1) { header() } if (tab != null) Rise(2) { - Column(Modifier.fillMaxWidth().padding(top = 14.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { + Column(Modifier.fillMaxWidth().padding(top = ActionGap), verticalArrangement = Arrangement.spacedBy(ActionGap)) { val labels = tabs.map { t -> when (t) { GameTab.ABOUT -> stringResource(R.string.game_tab_about) @@ -277,15 +287,17 @@ 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()}")) { - when (tab) { - GameTab.ABOUT -> AboutTab(developer, publisher, releaseDate, description, scores, stacked) { - if (!s.shortcutPicker) GameResourcesRow(title.takeUnless { it == id }.orEmpty(), game) + 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, a) + GameTab.INSTALL -> InstallTab(game, installed, item, store) } - 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) } } } @@ -348,14 +360,22 @@ 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().glass(RoundedCornerShape(30.dp)).padding(6.dp), + modifier = Modifier.fillMaxWidth().then(if (empty) Modifier else Modifier.padding(top = ActionGap).glass(RoundedCornerShape(30.dp)).padding(6.dp)), ) { - CompositionLocalProvider(LocalPillButtons provides true) { Box(Modifier.weight(1f)) { actions() } } - if (scores != null) CapsuleScores(scores, Modifier.padding(start = 8.dp, end = 10.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)) } } } @@ -367,41 +387,95 @@ private fun GameTabBar( ) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current + val scroll = rememberScrollState() + val spans = remember(tabs.size) { androidx.compose.runtime.mutableStateListOf(*arrayOfNulls(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) } - 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, - ) + 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, + ) + } + } + } } } 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(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 = 7.dp + val flat = BumperFlat val cap = if (leading) RoundedCornerShape(round, flat, flat, round) else RoundedCornerShape(flat, round, round, flat) Box( contentAlignment = Alignment.Center, @@ -433,12 +507,17 @@ 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 } @@ -448,127 +527,133 @@ internal fun GameActions( Actions { when { s.shortcutPicker && game != null -> { - PrimaryButton(stringResource(R.string.game_shortcut_choose), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn) { a.onSteamGame(game) } - FileButtons(game, a) + 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) } !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 - PrimaryButton( + if (lead) 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 (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 (rest) { + if (game != null) { + if (compactMenu) GameMoreMenu(game, a) else { + FileButtons(game, a) + GameShortcutMenu(game, a) } } - SecondaryButton(stringResource(R.string.bnet_open)) { a.onBattleNet() } - } - if (game != null && !compactMenu) { - HideButton(hideKey(game), game) - EditArtButton(game) + 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) + } } } download != null -> { - 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) } + 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) } } failed != null -> { - ActionChip(stringResource(R.string.stores_dl_failed), ok = false) - PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) { + if (rest) ActionChip(stringResource(R.string.stores_dl_failed), ok = false) + if (lead) PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) { if (item != null) StoresState.requestInstall(ctx, item) else DownloadQueue.retry(ctx, failed.key) } - ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { DownloadQueue.clear(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) } } cloud -> { val cloudId = game.storeId.orEmpty() - XboxStreamButton(cloudId, game.name, main = true, modifier = leadOn) - if (item?.installable == true && item.xboxPc) { + if (lead) XboxStreamButton(cloudId, game.name, main = true, modifier = leadOn) + if (rest && 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 (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) + 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) } - store == Store.BATTLENET && item != null -> InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) } + store == Store.BATTLENET && item != null -> if (lead) InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) } store == Store.XBOX && item != null && !item.xboxPc && item.xboxCloud -> { - XboxStreamButton(item.id, item.title, main = true, modifier = leadOn) - XboxLibraryButton(item.id, item) + if (lead) XboxStreamButton(item.id, item.title, main = true, modifier = leadOn) + if (rest) XboxLibraryButton(item.id, item) } item?.installable == true && StoresState.isUnfinished(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) } + 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) } } item?.installable == true -> { - InstallButton( + if (lead) InstallButton( if (downloadBytes > 0) stringResource(R.string.stores_install_size, formatBytes(downloadBytes)) else stringResource(R.string.stores_install), leadOn, ) { StoresState.requestInstall(ctx, item) } - if (store == Store.XBOX && item.xboxCloud) { + if (rest && store == Store.XBOX && item.xboxCloud) { XboxStreamButton(item.id, item.title) XboxLibraryButton(item.id, item) } - if (!item.accessible) SecondaryButton(buyLabel(item)) { openStoreUrl(ctx, item) } + if (rest && !item.accessible) SecondaryButton(buyLabel(item)) { openStoreUrl(ctx, item) } } item != null && (item.store == Store.ITCH || item.store == Store.GAMEJOLT) && item.isFree -> { - InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) } - SecondaryButton(stringResource(R.string.stores_view_on, item.store.shortLabel)) { openStoreUrl(ctx, item) } + 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) } } - item != null && item.isFree -> { + item != null && item.isFree -> if (lead) { 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 -> PrimaryButton(buyLabel(item), main = true, modifier = leadOn) { openStoreUrl(ctx, item) } + item != null -> if (lead) PrimaryButton(buyLabel(item), main = true, modifier = leadOn) { openStoreUrl(ctx, item) } } - val entryKey = game?.let(::hideKey) ?: storeKey - if (!s.shortcutPicker && entryKey != null && (game == null || cloud)) HideButton(entryKey, game) - if (cloud && (download != null || failed != null)) { - XboxStreamButton(game.storeId.orEmpty(), game.name) - XboxLibraryButton(game.storeId.orEmpty(), item) + 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) } - BusyChip(s) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameGlass.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameGlass.kt index 39c6b07768..6042598d8f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameGlass.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameGlass.kt @@ -58,6 +58,7 @@ 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 diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt index 5ebcc3c051..977fb98c44 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt @@ -163,6 +163,8 @@ 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( @@ -347,7 +349,7 @@ fun AnchoredMenu( } } .verticalScroll(scroll), - ) { content(firstItemFocus) } + ) { androidx.compose.runtime.CompositionLocalProvider(LocalRevealChecked provides true) { content(firstItemFocus) } } if (scroll.canScrollForward) Icon( Icons.Filled.KeyboardArrowDown, contentDescription = null, tint = colors.onSurfaceVariant, modifier = Modifier.align(Alignment.BottomCenter).size(20.dp), @@ -377,7 +379,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) LaunchedEffect(Unit) { reveal.bringIntoView() } + if (checked && LocalRevealChecked.current) LaunchedEffect(Unit) { reveal.bringIntoView() } Row( verticalAlignment = Alignment.CenterVertically, modifier = modifier.fillMaxWidth() From fd2e1652adb384e9d77237ed3f1991ec840336f1 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Sun, 22 Nov 2026 12:22:11 -0500 Subject: [PATCH 034/141] fix(fex): invalidate translated code written through a later writable alias (#3020) * fix(fex): invalidate translated code written through a later writable alias x86-64 CoreCLR maps its W^X memfd writable after the executable view was translated. Under SMCChecks=mtrack the new alias was never write-protected, so writes through it did not invalidate stale translations. Protect the overlapping part of an executable alias on mmap and mprotect. * fix(fex): protect every writable alias in one mprotect range and build fmt without modules * fix(fex): build without C++ module scanning or import std --- docs/development/x86-64-steam-client.md | 7 + tools/fex/build-in-arch.sh | 3 +- ...as-of-code-created-after-translation.patch | 81 +++++++ tools/tests/test_fex_smc_alias.py | 211 ++++++++++++++++++ 4 files changed, 301 insertions(+), 1 deletion(-) create mode 100644 tools/fex/patches/0006-smc-alias-of-code-created-after-translation.patch create mode 100644 tools/tests/test_fex_smc_alias.py diff --git a/docs/development/x86-64-steam-client.md b/docs/development/x86-64-steam-client.md index 7679a0a6c8..98d739dbd5 100644 --- a/docs/development/x86-64-steam-client.md +++ b/docs/development/x86-64-steam-client.md @@ -197,6 +197,13 @@ alone would then read as an installed client. restarted from the top forever (found with `perf_event_open` IP sampling, since proot holds ptrace). Such a range is now skipped whole and a second exhausted scan returns `-ENOMEM`, as the kernel does (`fex-2610-r3`). + - `0006-smc-alias-of-code-created-after-translation`: a JIT with a double-mapped memfd (CoreCLR's + W^X allocator) maps its writable alias after the executable alias was translated. Under + `SMCChecks=mtrack` the new alias was not write-protected, so writes through it never faulted and + never invalidated the translated code; x86-64 .NET programs ran stale code (access violations, + NullReferenceException, internal CLR errors). A writable mapping or mprotect now write-protects the + overlapping part of any alias that is already executable, so the first write faults and invalidates. + `FEX_SMCCHECKS=full` was the only workaround; no setting is needed with the patch. - **Building and publishing.** Droid-Deck/DroidDeck-Components' `build-fex.yml` builds `tools/fex` from this repository at a chosen ref (default `main`) with host thunks, in the same Arch Linux ARM container with a read-only token, then a separate job replaces `fex.tzst` on Components' single `fex` release, diff --git a/tools/fex/build-in-arch.sh b/tools/fex/build-in-arch.sh index 75bf7c22a3..f8ca08d4a8 100755 --- a/tools/fex/build-in-arch.sh +++ b/tools/fex/build-in-arch.sh @@ -56,7 +56,8 @@ cmake -S fex-src -B fex-build -G Ninja \ -DTUNE_CPU=none -DTUNE_ARCH=armv8-a \ -DBUILD_TESTING=OFF -DBUILD_FEXCONFIG=OFF -DENABLE_ASSERTIONS=OFF \ $( [ "$THUNKS" = 1 ] && echo "-DBUILD_THUNKS=ON -DX86_DEV_ROOTFS=$X86ROOT" || echo "-DBUILD_THUNKS=OFF" ) \ - -DENABLE_CCACHE=OFF -DENABLE_OFFLINE_TELEMETRY=OFF \ + -DENABLE_CCACHE=OFF -DENABLE_OFFLINE_TELEMETRY=OFF -DFMT_MODULE=OFF \ + -DCMAKE_CXX_MODULE_STD=OFF -DCMAKE_CXX_SCAN_FOR_MODULES=OFF \ ${FEX_EXTRA_CXXFLAGS:+-DCMAKE_CXX_FLAGS="$FEX_EXTRA_CXXFLAGS"} ninja -C fex-build DESTDIR="$WORK/out" ninja -C fex-build install diff --git a/tools/fex/patches/0006-smc-alias-of-code-created-after-translation.patch b/tools/fex/patches/0006-smc-alias-of-code-created-after-translation.patch new file mode 100644 index 0000000000..7311bb7c5d --- /dev/null +++ b/tools/fex/patches/0006-smc-alias-of-code-created-after-translation.patch @@ -0,0 +1,81 @@ +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h +index d720866..f55bce4 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h +@@ -288,6 +288,7 @@ public: + ///// VMA (Virtual Memory Area) tracking ///// + static bool HandleSegfault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* info, void* ucontext); + void MarkGuestExecutableRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) override; ++ void ProtectWritableAliasOfCode(uint64_t Base, uint64_t Length); + void InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) override; + std::optional + LookupExecutableFileSection(FEXCore::Core::InternalThreadState* Thread, uint64_t GuestAddr) final override; +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp +index 94bdd37..5d6c850 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp +@@ -196,6 +196,44 @@ void SyscallHandler::MarkGuestExecutableRange(FEXCore::Core::InternalThreadState + } + } + ++void SyscallHandler::ProtectWritableAliasOfCode(uint64_t Base, uint64_t Length) { ++ if (SMCChecks != FEXCore::Config::CONFIG_SMC_MTRACK) { ++ return; ++ } ++ ++ const auto End = Base + Length; ++ auto Mapping = VMATracking.FindVMAEntry(Base); ++ if (Mapping == VMATracking.VMAs.end()) { ++ Mapping = VMATracking.VMAs.lower_bound(Base); ++ } ++ ++ for (; Mapping != VMATracking.VMAs.end() && Mapping->first < End; ++Mapping) { ++ if (!Mapping->second.Flags.Shared || !Mapping->second.Prot.Writable || !Mapping->second.Resource) { ++ continue; ++ } ++ ++ const auto MapBase = std::max(Base, Mapping->first); ++ const auto MapTop = std::min(End, Mapping->first + Mapping->second.Length); ++ if (MapTop <= MapBase) { ++ continue; ++ } ++ ++ const auto OffsetBase = Mapping->second.Offset + (MapBase - Mapping->first); ++ const auto OffsetTop = OffsetBase + (MapTop - MapBase); ++ ++ for (auto VMA = Mapping->second.Resource->FirstVMA; VMA; VMA = VMA->ResourceNextVMA) { ++ if (!VMA->Prot.Executable || VMA->Offset >= OffsetTop || VMA->Offset + VMA->Length <= OffsetBase) { ++ continue; ++ } ++ ++ const auto OverlapBase = std::max(VMA->Offset, OffsetBase); ++ const auto OverlapTop = std::min(VMA->Offset + VMA->Length, OffsetTop); ++ auto rv = mprotect((void*)(MapBase + (OverlapBase - OffsetBase)), OverlapTop - OverlapBase, PROT_READ); ++ LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", OverlapBase, OverlapTop - OverlapBase); ++ } ++ } ++} ++ + void SyscallHandler::InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) { + InvalidateCodeRangeIfNecessary(Thread, Start, Length, false); + } +@@ -334,6 +372,9 @@ void* SyscallHandler::GuestMmap(bool Is64Bit, FEXCore::Core::InternalThreadState + } + + LateMetadata = TrackMmap(Thread, Result, length, prot, flags, fd, offset, CachedSection); ++ if (prot & PROT_WRITE) { ++ ProtectWritableAliasOfCode(Result, Size); ++ } + PendingResourceDeletion = VMATracking.HasPendingResourceDeletions(); + } + +@@ -479,6 +520,9 @@ uint64_t SyscallHandler::GuestMprotect(FEXCore::Core::InternalThreadState* Threa + } + + TrackMprotect(Thread, addr, len, prot); ++ if (prot & PROT_WRITE) { ++ ProtectWritableAliasOfCode(reinterpret_cast(addr), FEXCore::AlignUp(len, FEXCore::Utils::FEX_PAGE_SIZE)); ++ } + } + + InvalidateCodeRangeIfNecessary(Thread, reinterpret_cast(addr), len, false); diff --git a/tools/tests/test_fex_smc_alias.py b/tools/tests/test_fex_smc_alias.py new file mode 100644 index 0000000000..2af888d77b --- /dev/null +++ b/tools/tests/test_fex_smc_alias.py @@ -0,0 +1,211 @@ +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +PATCH = Path(__file__).resolve().parents[1] / "fex/patches/0006-smc-alias-of-code-created-after-translation.patch" + +HARNESS = r""" +#include +#include +#include +#include +#include +#include + +namespace FEXCore::Config { +enum { CONFIG_SMC_NONE, CONFIG_SMC_MTRACK, CONFIG_SMC_FULL }; +} +namespace LogMan::Throw { +template void AFmt(bool, const char*, Args...) {} +} + +union VMAProt { + struct { bool Readable : 1; bool Writable : 1; bool Executable : 1; }; +}; +struct VMAFlags { bool Shared : 1; }; +struct MappedResource; +struct VMAEntry { + MappedResource* Resource; + VMAEntry* ResourcePrevVMA; + VMAEntry* ResourceNextVMA; + uint64_t Base, Offset, Length; + VMAFlags Flags; + VMAProt Prot; +}; +struct MappedResource { VMAEntry* FirstVMA; }; +struct VMATrackingT { + std::map VMAs; + std::map::const_iterator FindVMAEntry(uint64_t Addr) const { + auto it = VMAs.upper_bound(Addr); + if (it == VMAs.begin()) return VMAs.end(); + --it; + return Addr < it->first + it->second.Length ? it : VMAs.end(); + } +}; + +struct Recorded { uint64_t Address, Length; int Prot; }; +static Recorded calls[16]; +static int count; +static int fake_mprotect(void* address, size_t length, int prot) { + calls[count++] = {(uint64_t)address, length, prot}; + return 0; +} +#define mprotect fake_mprotect + +struct SyscallHandler { + int SMCChecks = FEXCore::Config::CONFIG_SMC_MTRACK; + VMATrackingT VMATracking; + void ProtectWritableAliasOfCode(uint64_t Base, uint64_t Length); +}; + +#include "extracted.inc" + +static MappedResource resource, other; + +int main(int argc, char** argv) { + std::string scenario = argc > 1 ? argv[1] : ""; + SyscallHandler handler; + VMAEntry code{}, alias{}; + code.Resource = &resource; + code.Base = 0x100000; + code.Offset = 0x10000; + code.Length = 0x4000; + code.Flags.Shared = true; + code.Prot.Readable = true; + code.Prot.Executable = true; + alias.Resource = &resource; + alias.Base = 0x700000; + alias.Offset = 0x10000; + alias.Length = 0x4000; + alias.Flags.Shared = true; + alias.Prot.Readable = true; + alias.Prot.Writable = true; + uint64_t base = alias.Base, length = alias.Length; + if (scenario == "disjoint") { + code.Offset = 0x80000; + } else if (scenario == "partial") { + code.Offset = 0x12000; + code.Length = 0x1000; + } else if (scenario == "tail") { + base += 0x2000; + length = 0x10000; + } else if (scenario == "gap") { + base -= 0x2000; + length = 0x6000; + } else if (scenario == "two") { + length = 0x6000; + } else if (scenario == "no_code") { + code.Prot.Executable = false; + } else if (scenario == "private") { + alias.Flags.Shared = false; + } else if (scenario == "read_only") { + alias.Prot.Writable = false; + } else if (scenario == "full") { + handler.SMCChecks = FEXCore::Config::CONFIG_SMC_FULL; + } else if (scenario == "none") { + handler.SMCChecks = FEXCore::Config::CONFIG_SMC_NONE; + } + code.ResourceNextVMA = &alias; + alias.ResourcePrevVMA = &code; + resource.FirstVMA = &code; + handler.VMATracking.VMAs[code.Base] = code; + handler.VMATracking.VMAs[alias.Base] = alias; + handler.VMATracking.VMAs[code.Base].ResourceNextVMA = &handler.VMATracking.VMAs[alias.Base]; + handler.VMATracking.VMAs[alias.Base].ResourcePrevVMA = &handler.VMATracking.VMAs[code.Base]; + resource.FirstVMA = &handler.VMATracking.VMAs[code.Base]; + handler.VMATracking.VMAs[code.Base].Resource = &resource; + handler.VMATracking.VMAs[alias.Base].Resource = &resource; + if (scenario == "two") { + VMAEntry& next_code = handler.VMATracking.VMAs[0x200000]; + VMAEntry& next_alias = handler.VMATracking.VMAs[0x704000]; + next_code = {}; + next_code.Resource = &other; + next_code.Base = 0x200000; + next_code.Length = 0x2000; + next_code.Flags.Shared = true; + next_code.Prot.Readable = true; + next_code.Prot.Executable = true; + next_alias = {}; + next_alias.Resource = &other; + next_alias.Base = 0x704000; + next_alias.Length = 0x2000; + next_alias.Flags.Shared = true; + next_alias.Prot.Readable = true; + next_alias.Prot.Writable = true; + next_code.ResourceNextVMA = &next_alias; + next_alias.ResourcePrevVMA = &next_code; + other.FirstVMA = &next_code; + } + handler.ProtectWritableAliasOfCode(base, length); + printf("%d", count); + for (int i = 0; i < count; i++) printf(" %llx+%llx:%d", (unsigned long long)calls[i].Address, (unsigned long long)calls[i].Length, calls[i].Prot); + printf("\n"); + return 0; +} +""" + + +def extracted(): + text = PATCH.read_text() + section = re.search(r"^diff --git a/\S*SyscallsSMCTracking\.cpp .*?(?=^diff --git |\Z)", text, re.S | re.M).group(0) + added = [line[1:] for line in section.splitlines() if line.startswith("+") and not line.startswith("+++")] + body = "\n".join(added) + start = body.index("void SyscallHandler::ProtectWritableAliasOfCode") + end = body.index("\n}\n", start) + 3 + return body[start:end] + + +class SmcAliasTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + compiler = shutil.which("g++") or shutil.which("c++") + if not compiler: + raise unittest.SkipTest("no C++ compiler") + cls.tmp = Path(tempfile.mkdtemp(prefix="fex-smc-alias-")) + (cls.tmp / "extracted.inc").write_text(extracted()) + (cls.tmp / "harness.cpp").write_text(HARNESS) + subprocess.run([compiler, "-std=c++20", "-fno-strict-aliasing", "-I", str(cls.tmp), "-o", str(cls.tmp / "harness"), str(cls.tmp / "harness.cpp")], + check=True, capture_output=True, text=True) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def run_scenario(self, name=""): + return subprocess.run([str(self.tmp / "harness"), name], check=True, capture_output=True, text=True).stdout.strip() + + def test_writable_alias_of_translated_code_is_read_only_until_it_faults(self): + self.assertEqual(self.run_scenario(), "1 700000+4000:1") + + def test_only_the_overlapping_part_of_the_alias_is_protected(self): + self.assertEqual(self.run_scenario("partial"), "1 702000+1000:1") + + def test_alias_beyond_the_mapping_end_is_clamped(self): + self.assertEqual(self.run_scenario("tail"), "1 702000+2000:1") + + def test_range_starting_in_a_gap_reaches_the_alias_after_it(self): + self.assertEqual(self.run_scenario("gap"), "1 700000+4000:1") + + def test_every_alias_in_one_range_is_protected(self): + self.assertEqual(self.run_scenario("two"), "2 700000+4000:1 704000+2000:1") + + def test_alias_of_another_file_range_is_untouched(self): + self.assertEqual(self.run_scenario("disjoint"), "0") + + def test_alias_without_an_executable_mirror_is_untouched(self): + self.assertEqual(self.run_scenario("no_code"), "0") + + def test_private_and_read_only_mappings_are_untouched(self): + self.assertEqual(self.run_scenario("private"), "0") + self.assertEqual(self.run_scenario("read_only"), "0") + + def test_explicit_smc_check_settings_are_respected(self): + self.assertEqual(self.run_scenario("full"), "0") + self.assertEqual(self.run_scenario("none"), "0") + + +if __name__ == "__main__": + unittest.main() From 2d38f11b360cc3d0a3a092603b39700d38ff245c Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Sun, 22 Nov 2026 13:03:43 -0500 Subject: [PATCH 035/141] Build FEX's latest release, point releases included (#3026) The FEX build pinned FEX-2610 and its tag checks only accepted four digits, so FEX-2611.1 was never picked up. The build now takes the latest release tag, and Fixed-upstream compares the four-digit release. CMake 4.5 rejects DEPENDS in install(CODE), which stopped host thunk builds; patch 0007 drops it. --- .github/workflows/build-fex.yml | 5 ++++- docs/development/x86-64-steam-client.md | 7 ++++++- tools/fex/build-in-arch.sh | 6 ++++-- ...7-cmake-install-code-without-depends.patch | 20 +++++++++++++++++++ 4 files changed, 34 insertions(+), 4 deletions(-) create mode 100644 tools/fex/patches/0007-cmake-install-code-without-depends.patch diff --git a/.github/workflows/build-fex.yml b/.github/workflows/build-fex.yml index deb099100a..08d3ba957b 100644 --- a/.github/workflows/build-fex.yml +++ b/.github/workflows/build-fex.yml @@ -29,11 +29,14 @@ 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 - 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 + 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 sudo chown -R "$(id -u):$(id -g)" . - uses: actions/upload-artifact@v4 with: diff --git a/docs/development/x86-64-steam-client.md b/docs/development/x86-64-steam-client.md index 98d739dbd5..d8845742bd 100644 --- a/docs/development/x86-64-steam-client.md +++ b/docs/development/x86-64-steam-client.md @@ -204,13 +204,18 @@ alone would then read as an installed client. NullReferenceException, internal CLR errors). A writable mapping or mprotect now write-protects the overlapping part of any alias that is already executable, so the first write faults and invalidates. `FEX_SMCCHECKS=full` was the only workaround; no setting is needed with the patch. + - `0007-cmake-install-code-without-depends`: CMake 4.5 rejects the `DEPENDS` argument FEX passes to + `install(CODE ...)` for the guest thunk libraries, so builds with host thunks stopped at configure. + The guest libraries are external projects in the default build, which `install` already follows. - **Building and publishing.** Droid-Deck/DroidDeck-Components' `build-fex.yml` builds `tools/fex` from this repository at a chosen ref (default `main`) with host thunks, in the same Arch Linux ARM container with a read-only token, then a separate job replaces `fex.tzst` on Components' single `fex` release, checks the digest GitHub stored, and records the build's version, sha256 and size in its `fex.json` (in that order: a device that reads the old `fex.json` meanwhile gets a mismatching archive and keeps its FEX). This repository's `build-fex.yml` only builds `tools/fex` when it changes (and on dispatch, - for diagnostic builds such as `-DDEBUG_STRACE`); nothing is published from it. + for diagnostic builds such as `-DDEBUG_STRACE`); nothing is published from it. It builds FEX's latest + release, point releases (`FEX-2611.1`) included; `build-in-arch.sh` takes the tag from `FEX_VERSION` + and compares only its four-digit release against a patch's `Fixed-upstream`. - Releases so far: `fex-2609-r2` (no thunks), `fex-2609-r3` (thunks), `fex-2610-r1`, `fex-2610-r2`, `fex-2610-r3`, `fex-2610-r4` (in-root resolution when openat2 is missing, exact MAP_32BIT marking), `fex-2610-r5` (current: bundles libxxhash, which the Linux runtime does not ship; the diff --git a/tools/fex/build-in-arch.sh b/tools/fex/build-in-arch.sh index f8ca08d4a8..dccb24f882 100755 --- a/tools/fex/build-in-arch.sh +++ b/tools/fex/build-in-arch.sh @@ -1,6 +1,8 @@ #!/usr/bin/bash set -euxo pipefail -VERSION=${FEX_VERSION:-FEX-2610} +VERSION=${FEX_VERSION:?FEX_VERSION must name a FEX release tag, e.g. FEX-2611.1} +RELEASE=${VERSION#FEX-} +RELEASE=${RELEASE%%.*} WORK=/work cd "$WORK" grep -q '^DisableSandbox' /etc/pacman.conf || sed -i 's/^\[options\]/[options]\nDisableSandbox/' /etc/pacman.conf @@ -38,7 +40,7 @@ fi rm -rf fex-src out && git clone -q --depth 1 --branch "$VERSION" --recurse-submodules --shallow-submodules https://github.com/FEX-Emu/FEX.git fex-src for p in tools/fex/patches/*.patch; do upstream=$(sed -n 's/^Fixed-upstream: FEX-\([0-9]\{4\}\)$/\1/p' "$p") - if [ -n "$upstream" ] && [ "${VERSION#FEX-}" -ge "$upstream" ]; then + if [ -n "$upstream" ] && [ "$RELEASE" -ge "$upstream" ]; then echo "$(basename "$p"): already in FEX-$upstream, skipped for $VERSION" continue fi diff --git a/tools/fex/patches/0007-cmake-install-code-without-depends.patch b/tools/fex/patches/0007-cmake-install-code-without-depends.patch new file mode 100644 index 0000000000..6752b40280 --- /dev/null +++ b/tools/fex/patches/0007-cmake-install-code-without-depends.patch @@ -0,0 +1,20 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 8976588..3ae54f4 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -776,7 +776,6 @@ if (BUILD_THUNKS) + CODE " + execute_process(COMMAND ${CMAKE_COMMAND} --build . --target install + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/Guest)" +- DEPENDS guest-libs + COMPONENT Runtime) + + install( +@@ -784,7 +783,6 @@ if (BUILD_THUNKS) + CODE " + execute_process(COMMAND ${CMAKE_COMMAND} --build . --target install + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/Guest_32)" +- DEPENDS guest-libs-32 + COMPONENT Runtime) + + add_custom_target(uninstall_guest-libs From ff5e4c7ac76166bcc266a22eeca00b013a8b2c71 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Sun, 22 Nov 2026 13:37:44 -0500 Subject: [PATCH 036/141] fix(preload): accept NETLINK_ROUTE multicast subscriptions (#3015) * fix(preload): accept NETLINK_ROUTE multicast subscriptions Programs that watch for network changes bind their route socket with multicast groups or join them with NETLINK_ADD_MEMBERSHIP. The emulated socket refused both with EACCES, and .NET's NetworkChange treats that as fatal: CurseForge's Mods Agent failed to initialise with "Permission denied" from NetworkChange.CreateSocket(), so the app never loaded its library. Real Linux lets unprivileged sockets join rtnetlink groups. Accept the groups at bind and through ADD/DROP_MEMBERSHIP, report them from getsockname(), and keep queries on the same socket working. No change events are generated yet; queries still return the current snapshot. * fix(preload): keep netlink group membership in the shared socket state Memberships now live in the peer metadata the kernel holds for the socket, next to the port and cap ack, so they survive exec and a change made by one process after fork is seen by every process holding the socket. * fix(session): answer denied /proc/net socket tables Android's SELinux policy denies app processes every file under /proc/net. .NET lists TCP listeners from /proc/net/tcp and tcp6 before it binds a server port, so the CurseForge Mods Agent failed on every port with "An error was encountered while querying information from the operating system" on stock firmware. Denied tcp, tcp6, udp and udp6 reads now get a header-only table, through open and openat as well as fopen, the same way the route and interface tables already are. * fix(session): keep synthesized socket tables read-only and file-only Reopen the populated table read-only instead of duplicating its writable descriptor, and leave O_DIRECTORY opens with their original failure. --- tools/linuxfs/preload/netif.c | 133 ++++++++++++++++++++++------ tools/linuxfs/preload/opens.c | 5 +- tools/tests/test_netlink_preload.py | 129 ++++++++++++++++++++++++++- 3 files changed, 235 insertions(+), 32 deletions(-) diff --git a/tools/linuxfs/preload/netif.c b/tools/linuxfs/preload/netif.c index 5be0dde22a..04100065fb 100644 --- a/tools/linuxfs/preload/netif.c +++ b/tools/linuxfs/preload/netif.c @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -520,6 +521,13 @@ static void write_table(FILE *out, const char *table, const struct link *link) { fprintf(out, "%6s: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", link->name); } else if (strcmp(table, "arp") == 0) { fprintf(out, "IP address HW type Flags HW address Mask Device\n"); + } else if (strcmp(table, "tcp") == 0 || strcmp(table, "udp") == 0) { + fprintf(out, " sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode%s\n", + table[0] == 'u' ? " ref pointer drops" : ""); + } else if (strcmp(table, "tcp6") == 0 || strcmp(table, "udp6") == 0) { + fprintf(out, " sl local_address remote_address " + "st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode%s\n", + table[0] == 'u' ? " ref pointer drops" : ""); } else { fprintf(out, "1\n"); } @@ -527,7 +535,10 @@ static void write_table(FILE *out, const char *table, const struct link *link) { #define CARRIER_TABLE 5 -static const char *const net_tables[] = { "route", "ipv6_route", "if_inet6", "dev", "arp", "carrier" }; +#define SOCKET_TABLES 6 + +static const char *const net_tables[] = { "route", "ipv6_route", "if_inet6", "dev", "arp", "carrier", + "tcp", "tcp6", "udp", "udp6" }; static long long net_denied_at[sizeof(net_tables) / sizeof(net_tables[0])]; #define CARRIER_SLOTS 8 @@ -564,8 +575,8 @@ static void remember_denial(int table, const char *path) { static int denied_table(const char *path) { if (strncmp(path, "/proc/net/", 10) == 0) { - for (int i = 0; i < CARRIER_TABLE; i++) { - if (strcmp(path + 10, net_tables[i]) == 0) return i; + for (int i = 0; i < (int) (sizeof(net_tables) / sizeof(net_tables[0])); i++) { + if (i != CARRIER_TABLE && strcmp(path + 10, net_tables[i]) == 0) return i; } return -1; } @@ -576,9 +587,9 @@ static int denied_table(const char *path) { return -1; } -static FILE *synthesize(const char *table) { +static FILE *synthesize(int table) { struct link link; - if (!load_link(&link)) return NULL; + if (!load_link(&link) && table < SOCKET_TABLES) return NULL; int fd = memfd_create("droiddeck-net", MFD_CLOEXEC); if (fd < 0) return NULL; FILE *out = fdopen(fd, "w+"); @@ -586,7 +597,7 @@ static FILE *synthesize(const char *table) { close(fd); return NULL; } - write_table(out, table, &link); + write_table(out, net_tables[table], &link); if (fflush(out) != 0) { fclose(out); return NULL; @@ -610,11 +621,11 @@ static FILE *open_stream(fopen_fn real, const char *path, const char *mode, cons path = dd_oom_adj_redirect(path, mode && (mode[0] == 'w' || mode[0] == 'a' || strchr(mode, '+'))); int table = path && mode && mode[0] == 'r' ? denied_table(path) : -1; FILE *f; - if (table >= 0 && denied_recently(table, path) && (f = synthesize(net_tables[table])) != NULL) return f; + if (table >= 0 && denied_recently(table, path) && (f = synthesize(table)) != NULL) return f; f = real(path, mode); if (f || table < 0) return f; int saved = errno; - if ((f = synthesize(net_tables[table])) != NULL) { + if ((f = synthesize(table)) != NULL) { if (saved == EACCES) remember_denial(table, path); return f; } @@ -622,6 +633,30 @@ static FILE *open_stream(fopen_fn real, const char *path, const char *mode, cons return NULL; } +int dd_net_open(const char *path, int flags, int fd) __attribute__((visibility("hidden"))); + +int dd_net_open(const char *path, int flags, int fd) { + if (fd >= 0 || path == NULL || (flags & O_ACCMODE) != O_RDONLY || (flags & O_DIRECTORY)) return fd; + int table = denied_table(path); + if (table < 0) return fd; + int saved = errno; + FILE *f = synthesize(table); + if (f == NULL) { + errno = saved; + return fd; + } + char self[32]; + snprintf(self, sizeof(self), "/proc/self/fd/%d", fileno(f)); + int copy = open(self, O_RDONLY | (flags & O_CLOEXEC)); + fclose(f); + if (copy < 0) { + errno = saved; + return fd; + } + if (saved == EACCES) remember_denial(table, path); + return copy; +} + FILE *fopen(const char *path, const char *mode) { static fopen_fn real; if (real == NULL) real = (fopen_fn) dlsym(RTLD_NEXT, "fopen"); @@ -664,6 +699,7 @@ struct nl_socket { unsigned references; int type; int cap_ack; + uint64_t groups; struct nl_socket *next; }; @@ -685,13 +721,14 @@ struct nl_fd_page { struct nl_metadata { uint64_t nonce; + uint64_t groups; uint32_t port; uint32_t type; uint32_t cap_ack; char magic[12]; }; -_Static_assert(sizeof(struct nl_metadata) == 32, "netlink socket metadata ABI"); +_Static_assert(sizeof(struct nl_metadata) == 40, "netlink socket metadata ABI"); struct nl_packet { struct nl_packet *next; @@ -705,9 +742,9 @@ struct nl_reply { int overflow; }; -static const char nl_client_magic[12] = "dd-nl-c-v1"; -static const char nl_peer_magic[12] = "dd-nl-p-v1"; -static const char nl_reservation_magic[12] = "dd-nl-r-v1"; +static const char nl_client_magic[12] = "dd-nl-c-v2"; +static const char nl_peer_magic[12] = "dd-nl-p-v2"; +static const char nl_reservation_magic[12] = "dd-nl-r-v2"; static struct nl_socket *nl_sockets; static struct nl_fd *nl_fds; static struct nl_fd_page *nl_fd_pages[NL_FD_BUCKETS]; @@ -910,13 +947,13 @@ static int nl_save_packets(int fd, struct nl_packet **packets) { } } -static int nl_replace_peer(int fd, struct nl_socket *socket, unsigned port, int capped) { +static int nl_replace_peer(int fd, struct nl_socket *socket, unsigned port, int capped, uint64_t groups) { static int (*real_socket)(int, int, int); static int (*real_close)(int); if (real_socket == NULL) real_socket = (int (*)(int, int, int)) dlsym(RTLD_NEXT, "socket"); if (real_close == NULL) real_close = (int (*)(int)) dlsym(RTLD_NEXT, "close"); struct sockaddr_un client_addr, peer_addr; - struct nl_metadata client, peer = { .port = port, .type = socket->type, .cap_ack = capped }; + struct nl_metadata client, peer = { .groups = groups, .port = port, .type = socket->type, .cap_ack = capped }; if (!nl_address(fd, 0, &client_addr, &client, nl_client_magic)) { errno = EINVAL; return -1; @@ -955,6 +992,7 @@ static int nl_replace_peer(int fd, struct nl_socket *socket, unsigned port, int socket->peer_inode = status.st_ino; socket->port = port; socket->cap_ack = capped; + socket->groups = groups; errno = saved; return replayed; failed: { @@ -1025,7 +1063,7 @@ static struct nl_fd *nl_restore(int fd) { socket->device = status.st_dev; socket->inode = status.st_ino; socket->type = peer.type; - if (nl_replace_peer(fd, socket, peer.port, peer.cap_ack) != 0) { + if (nl_replace_peer(fd, socket, peer.port, peer.cap_ack, peer.groups) != 0) { free(socket); free(entry); return NULL; @@ -1159,7 +1197,7 @@ static int nl_peer_of(int fd) { if (nl_address(fd, 1, &addr, &metadata, nl_peer_magic)) { if ((metadata.nonce == socket->peer_inode && nl_identity(socket->peer, socket->device, socket->peer_inode)) - || nl_replace_peer(fd, socket, metadata.port, metadata.cap_ack) == 0) { + || nl_replace_peer(fd, socket, metadata.port, metadata.cap_ack, metadata.groups) == 0) { if (socket->port != 0 && (socket->reservation < 0 || !nl_identity(socket->reservation, socket->device, socket->reservation_inode))) nl_reserve_port(socket, socket->port); @@ -1317,7 +1355,7 @@ static int nl_bind_port(int fd, unsigned requested, int automatic) { } if (other == NULL) { if (nl_reserve_port(socket, port) == 0) { - result = nl_replace_peer(fd, socket, port, socket->cap_ack); + result = nl_replace_peer(fd, socket, port, socket->cap_ack, socket->groups); if (result != 0) nl_close_reservation(socket); break; } @@ -1342,6 +1380,23 @@ static int nl_autobind(int fd) { return nl_bind_port(fd, 0, 1); } +static int nl_set_groups(int fd, uint64_t keep, uint64_t add) { + int result = 0; + pthread_mutex_lock(&nl_sockets_lock); + struct nl_fd *entry = nl_find(fd); + if (entry) { + struct nl_socket *socket = entry->socket; + struct sockaddr_un addr; + struct nl_metadata metadata; + uint64_t current = nl_address(fd, 1, &addr, &metadata, nl_peer_magic) ? metadata.groups : socket->groups; + uint64_t groups = (current & keep) | add; + if (groups != current || groups != socket->groups) + result = nl_replace_peer(fd, socket, socket->port, socket->cap_ack, groups); + } + pthread_mutex_unlock(&nl_sockets_lock); + return result; +} + int dd_nl_bind(int fd, const struct sockaddr *addr, socklen_t len, int *rc) { const struct sockaddr_nl *nl; if (addr && len >= sizeof(sa_family_t) && addr->sa_family == AF_NETLINK) nl_discover(fd); @@ -1352,15 +1407,39 @@ int dd_nl_bind(int fd, const struct sockaddr *addr, socklen_t len, int *rc) { return 1; } nl = (const struct sockaddr_nl *) addr; - if (nl->nl_groups != 0) { - errno = EACCES; - *rc = -1; - return 1; - } *rc = nl_bind_port(fd, nl->nl_pid, 0); + if (*rc == 0) *rc = nl_set_groups(fd, ~(uint64_t) UINT32_MAX, nl->nl_groups); return 1; } +static unsigned nl_groups_of(int fd) { + struct sockaddr_un addr; + struct nl_metadata metadata; + if (nl_address(fd, 1, &addr, &metadata, nl_peer_magic)) return (unsigned) metadata.groups; + unsigned groups = 0; + pthread_mutex_lock(&nl_sockets_lock); + struct nl_fd *entry = nl_find(fd); + if (entry) groups = (unsigned) entry->socket->groups; + pthread_mutex_unlock(&nl_sockets_lock); + return groups; +} + +static int nl_membership(int fd, int option, const void *value, socklen_t len) { + unsigned group; + if (value == NULL || len < sizeof(group)) { + errno = value == NULL ? EFAULT : EINVAL; + return -1; + } + memcpy(&group, value, sizeof(group)); + if (group == 0 || group > RTNLGRP_MAX) { + errno = EINVAL; + return -1; + } + if (group > 64) return 0; + uint64_t bit = (uint64_t) 1 << (group - 1); + return nl_set_groups(fd, ~bit, option == NETLINK_ADD_MEMBERSHIP ? bit : 0); +} + int dd_nl_getsockname(int fd, struct sockaddr *addr, socklen_t *len, int *rc) { struct sockaddr_nl nl; socklen_t size; @@ -1373,6 +1452,7 @@ int dd_nl_getsockname(int fd, struct sockaddr *addr, socklen_t *len, int *rc) { memset(&nl, 0, sizeof(nl)); nl.nl_family = AF_NETLINK; nl.nl_pid = nl_port_of(fd); + nl.nl_groups = nl_groups_of(fd); size = *len < sizeof(nl) ? *len : (socklen_t) sizeof(nl); memcpy(addr, &nl, size); *len = sizeof(nl); @@ -1517,9 +1597,10 @@ int dd_nl_setsockopt(int fd, int level, int option, const void *value, socklen_t *rc = real(peer, level, option, value, len); return 1; } - if (option != NETLINK_CAP_ACK && option != NETLINK_EXT_ACK) { - errno = option == NETLINK_ADD_MEMBERSHIP || option == NETLINK_DROP_MEMBERSHIP - ? EACCES : ENOPROTOOPT; + if (option == NETLINK_ADD_MEMBERSHIP || option == NETLINK_DROP_MEMBERSHIP) { + *rc = nl_membership(fd, option, value, len); + } else if (option != NETLINK_CAP_ACK && option != NETLINK_EXT_ACK) { + errno = ENOPROTOOPT; *rc = -1; } else if (value == NULL || len < sizeof(int)) { errno = value == NULL ? EFAULT : EINVAL; @@ -1530,7 +1611,7 @@ int dd_nl_setsockopt(int fd, int level, int option, const void *value, socklen_t memcpy(&enabled, value, sizeof(enabled)); pthread_mutex_lock(&nl_sockets_lock); struct nl_fd *entry = nl_find(fd); - if (entry && nl_replace_peer(fd, entry->socket, entry->socket->port, enabled != 0) != 0) { + if (entry && nl_replace_peer(fd, entry->socket, entry->socket->port, enabled != 0, entry->socket->groups) != 0) { pthread_mutex_unlock(&nl_sockets_lock); *rc = -1; return 1; diff --git a/tools/linuxfs/preload/opens.c b/tools/linuxfs/preload/opens.c index c9df092b40..5ab362e93f 100644 --- a/tools/linuxfs/preload/opens.c +++ b/tools/linuxfs/preload/opens.c @@ -17,6 +17,7 @@ int dd_ntsync_open(const char *path, int flags) __attribute__((visibility("hidde const char *dd_oom_adj_redirect(const char *path, int writing) __attribute__((visibility("hidden"))); int dd_venc_open(const char *path, int flags) __attribute__((visibility("hidden"))); int dd_vdec_open(const char *path, int flags) __attribute__((visibility("hidden"))); +int dd_net_open(const char *path, int flags, int fd) __attribute__((visibility("hidden"))); int dd_dircache_create(int dirfd, const char *path, int flags, mode_t mode, int (*real)(int, const char *, int, mode_t)) __attribute__((visibility("hidden"))); @@ -62,7 +63,7 @@ static int open_from(const char *path, int flags, mode_t mode, const void *calle fd = dd_dircache_create(AT_FDCWD, path, flags, mode, via_open); if (retry_without_noatime(fd, flags)) fd = real_open(path, flags & ~O_NOATIME, mode); if (fd < 0 && dd_writable_retry(AT_FDCWD, path, flags)) fd = real_open(path, flags & ~O_NOATIME, mode); - return fd; + return dd_net_open(path, flags, fd); } static int openat_from(int dirfd, const char *path, int flags, mode_t mode, const void *caller) { @@ -85,7 +86,7 @@ static int openat_from(int dirfd, const char *path, int flags, mode_t mode, cons fd = dd_dircache_create(dirfd, path, flags, mode, via_openat); if (retry_without_noatime(fd, flags)) fd = real_openat(dirfd, path, flags & ~O_NOATIME, mode); if (fd < 0 && dd_writable_retry(dirfd, path, flags)) fd = real_openat(dirfd, path, flags & ~O_NOATIME, mode); - return fd; + return dd_net_open(path, flags, fd); } int open(const char *path, int flags, ...) { diff --git a/tools/tests/test_netlink_preload.py b/tools/tests/test_netlink_preload.py index 7c47c971f9..8a6dc79523 100644 --- a/tools/tests/test_netlink_preload.py +++ b/tools/tests/test_netlink_preload.py @@ -12,7 +12,10 @@ PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload" SHIM = r""" #define _GNU_SOURCE #include +#include +#include #include +#include #include #include #include @@ -92,6 +95,33 @@ FILE *fopen(const char *path, const char *mode) { return real(path, mode); } +static int denied(const char *path) { + const char *prefix = getenv("NETLINK_TEST_DENIED"); + if (!prefix || !path || strncmp(path, prefix, strlen(prefix))) return 0; + errno = EACCES; + return 1; +} + +int open(const char *path, int flags, ...) { + static int (*real)(const char *, int, ...); + if (!real) real = dlsym(RTLD_NEXT, "open"); + va_list ap; + va_start(ap, flags); + mode_t mode = va_arg(ap, mode_t); + va_end(ap); + return denied(path) ? -1 : real(path, flags, mode); +} + +int openat(int dirfd, const char *path, int flags, ...) { + static int (*real)(int, const char *, int, ...); + if (!real) real = dlsym(RTLD_NEXT, "openat"); + va_list ap; + va_start(ap, flags); + mode_t mode = va_arg(ap, mode_t); + va_end(ap); + return denied(path) ? -1 : real(dirfd, path, flags, mode); +} + int close_range(unsigned int first, unsigned int last, int flags) { return syscall(SYS_close_range, (long)first, (long)last, (long)flags, 0L, 0L, 0L); } @@ -137,6 +167,35 @@ static int route_socket(void) { return descriptor; } +static void proc_net_test(int denied) { + static const char *const tables[] = {"/proc/net/tcp", "/proc/net/tcp6", "/proc/net/udp", "/proc/net/udp6"}; + char text[512], target[128], link[64]; + for (unsigned i = 0; i < sizeof(tables) / sizeof(tables[0]); i++) { + int descriptor = i % 2 ? openat(AT_FDCWD, tables[i], O_RDONLY | O_CLOEXEC) : open(tables[i], O_RDONLY | O_CLOEXEC); + require(descriptor >= 0, "socket table opens"); + require(fcntl(descriptor, F_GETFD) & FD_CLOEXEC, "socket table keeps close-on-exec"); + snprintf(link, sizeof(link), "/proc/self/fd/%d", descriptor); + ssize_t length = readlink(link, target, sizeof(target) - 1); + require(length > 0, "socket table target"); + target[length] = 0; + require((strncmp(target, "/memfd:droiddeck-net", 20) == 0) == denied, "synthesized only when denied"); + if (denied) { + require((fcntl(descriptor, F_GETFL) & O_ACCMODE) == O_RDONLY, "socket table is read-only"); + require(write(descriptor, "x", 1) < 0 && errno == EBADF, "socket table rejects writes"); + ssize_t total = read(descriptor, text, sizeof(text) - 1); + require(total > 0, "socket table read"); + text[total] = 0; + require(strstr(text, "local_address") && strchr(text, '\n') == text + total - 1, "header without sockets"); + } + close(descriptor); + } + if (denied) { + require(open("/proc/net/tcp", O_WRONLY) < 0 && errno == EACCES, "socket table writes stay denied"); + require(open("/proc/net/netstat", O_RDONLY) < 0 && errno == EACCES, "other tables stay denied"); + require(open("/proc/net/tcp", O_RDONLY | O_DIRECTORY) < 0 && errno == EACCES, "directory opens stay denied"); + } +} + static unsigned port_of(int descriptor) { struct sockaddr_nl address; socklen_t length = sizeof(address); @@ -609,6 +668,13 @@ static void batch_test(int oversized) { close(descriptor); } +static unsigned groups_of(int descriptor) { + struct sockaddr_nl address; + socklen_t length = sizeof(address); + require(getsockname(descriptor, (struct sockaddr *)&address, &length) == 0, "getsockname"); + return address.nl_groups; +} + static void inherited_test(int argc, char **argv) { require(argc == 6, "inherited arguments"); int descriptor = atoi(argv[2]), closed = atoi(argv[4]), datagram = atoi(argv[5]); @@ -616,6 +682,7 @@ static void inherited_test(int argc, char **argv) { require(fcntl(closed, F_GETFD) == -1 && errno == EBADF, "cloexec descriptor closed"); require(port_of(descriptor) == port && !(fcntl(descriptor, F_GETFD) & FD_CLOEXEC), "inherited bound port"); + require(groups_of(descriptor) == RTMGRP_LINK, "membership survives exec"); socket_info(descriptor, SOCK_RAW); socket_info(datagram, SOCK_DGRAM); require(fcntl(datagram, F_GETFL) & O_NONBLOCK, "inherited nonblocking flag"); @@ -640,6 +707,9 @@ static void exec_test(const char *program, int forked) { int enabled = 1; require(setsockopt(descriptor, SOL_NETLINK, NETLINK_CAP_ACK, &enabled, sizeof(enabled)) == 0, "inherited cap ack"); + int group = RTNLGRP_LINK; + require(setsockopt(descriptor, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group)) == 0, + "inherited membership"); unsigned port = port_of(descriptor); int alias = fcntl(descriptor, F_DUPFD, 100); int closed = fcntl(descriptor, F_DUPFD_CLOEXEC, 200); @@ -718,8 +788,8 @@ static void ack_test(const char *mode) { static void options_test(void) { int descriptor = route_socket(); int group = RTNLGRP_LINK; - require(setsockopt(descriptor, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group)) == -1 - && errno == EACCES, "membership denied"); + require(setsockopt(descriptor, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group)) == 0, + "membership accepted"); require(setsockopt(descriptor, SOL_NETLINK, NETLINK_PKTINFO, &group, sizeof(group)) == -1 && errno == ENOPROTOOPT, "unsupported option"); require(setsockopt(descriptor, SOL_NETLINK, NETLINK_EXT_ACK, &group, sizeof(group)) == 0, "ext ack"); @@ -735,6 +805,44 @@ static void options_test(void) { close(descriptor); } +static void subscribe_test(void) { + unsigned wanted = RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR; + int descriptor = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE); + struct sockaddr_nl address = {.nl_family = AF_NETLINK, .nl_groups = wanted}; + require(descriptor >= 0, "socket"); + require(bind(descriptor, (struct sockaddr *)&address, sizeof(address)) == 0, "bind with groups"); + require(groups_of(descriptor) == wanted, "bound groups"); + int group = RTNLGRP_IPV4_ROUTE; + require(setsockopt(descriptor, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group)) == 0, + "add membership"); + require(groups_of(descriptor) == (wanted | RTMGRP_IPV4_ROUTE), "added group"); + group = RTNLGRP_LINK; + require(setsockopt(descriptor, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP, &group, sizeof(group)) == 0, + "drop membership"); + require(groups_of(descriptor) == ((wanted & ~RTMGRP_LINK) | RTMGRP_IPV4_ROUTE), "dropped group"); + pid_t child = fork(); + require(child >= 0, "membership fork"); + if (child == 0) { + group = RTNLGRP_IPV4_ROUTE; + _exit(setsockopt(descriptor, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP, &group, sizeof(group)) == 0 + && groups_of(descriptor) == (wanted & ~RTMGRP_LINK) ? 0 : 1); + } + int status; + require(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0, + "membership child"); + require(groups_of(descriptor) == (wanted & ~RTMGRP_LINK), "membership shared after fork"); + group = 0; + require(setsockopt(descriptor, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group)) == -1 + && errno == EINVAL, "group zero refused"); + struct timeval timeout = {.tv_usec = 30000}; + require(setsockopt(descriptor, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) == 0, "receive timeout"); + unsigned char buffer[4096]; + require(recv(descriptor, buffer, sizeof(buffer), 0) == -1 + && (errno == EAGAIN || errno == EWOULDBLOCK), "no unsolicited events"); + usable(descriptor); + close(descriptor); +} + static void dump_test(void) { int descriptor = route_socket(); send_link(descriptor, 0, NLM_F_DUMP | NLM_F_ACK); @@ -1040,6 +1148,7 @@ int main(int argc, char **argv) { if (!strcmp(argv[1], "ack") || !strcmp(argv[1], "error") || !strcmp(argv[1], "capped")) ack_test(argv[1]); else if (!strcmp(argv[1], "options")) options_test(); + else if (!strcmp(argv[1], "subscribe")) subscribe_test(); else if (!strcmp(argv[1], "dump")) dump_test(); else if (!strcmp(argv[1], "send_timeout")) send_timeout_test(0); else if (!strcmp(argv[1], "nonblocking")) send_timeout_test(1); @@ -1082,6 +1191,7 @@ int main(int argc, char **argv) { } else if (!strcmp(argv[1], "range") || !strcmp(argv[1], "cloexec") || !strcmp(argv[1], "closefrom")) close_range_test(argv[1]); + else if (!strcmp(argv[1], "proc_net")) proc_net_test(argc > 2 && !strcmp(argv[2], "denied")); else if (!strcmp(argv[1], "route")) { require(argc >= 3, "route destination"); route_test(argv[2]); @@ -1129,10 +1239,12 @@ class NetlinkPreloadTest(unittest.TestCase): def tearDownClass(cls): cls.temp.cleanup() - def run_program(self, mode, *arguments, snapshot=None): + def run_program(self, mode, *arguments, snapshot=None, denied=None): env = dict(os.environ, LD_PRELOAD=f"{self.preload}:{self.shim}", NETLINK_TEST_SNAPSHOT=str(snapshot or self.snapshot), DD_SYSV_DIR=str(self.directory / "sysv")) + if denied: + env["NETLINK_TEST_DENIED"] = denied result = subprocess.run([str(self.program), mode, *arguments], env=env, capture_output=True, text=True, timeout=5) self.assertEqual(0, result.returncode, result.stdout + result.stderr) @@ -1207,9 +1319,12 @@ class NetlinkPreloadTest(unittest.TestCase): def test_cloexec_sockets_release_their_ports_after_exec(self): self.run_program("all_cloexec") - def test_subscription_is_denied_and_receive_timeout_is_applied(self): + def test_membership_is_accepted_and_receive_timeout_is_applied(self): self.run_program("options") + def test_change_listeners_subscribe_and_still_query(self): + self.run_program("subscribe") + def test_dump_keeps_multipart_completion(self): self.run_program("dump") @@ -1249,6 +1364,12 @@ class NetlinkPreloadTest(unittest.TestCase): with self.subTest(mode=mode): self.run_program(mode) + def test_denied_socket_tables_open_as_empty_tables(self): + self.run_program("proc_net", "denied", denied="/proc/net/") + + def test_readable_socket_tables_stay_real(self): + self.run_program("proc_net") + def test_loopback_and_own_addresses_are_local_routes(self): for destination, source in (("127.0.0.2", "127.0.0.1"), ("::1", "::1"), ("192.168.1.10", "192.168.1.10"), ("2001:db8::10", "2001:db8::10")): From 1a29c65d4fb333577a3ba338e81fbc4450c4b3c6 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Sun, 22 Nov 2026 13:47:22 -0500 Subject: [PATCH 037/141] fix(gamescope): choose focus again when a window's opacity crosses zero (#3030) A window is a focus candidate only while _NET_WM_WINDOW_OPACITY is above zero, but a change of that property never re-ran focus selection. A layered window that maps fully transparent and fades in was skipped at map time and stayed skipped once opaque, so a nested desktop session hid its gamescope window and the game ran with nothing on screen. --- tools/gamescope/PATCHES.md | 10 +++ .../0140-focus-follows-window-opacity.patch | 32 +++++++++ tools/tests/test_gamescope_focus_opacity.py | 70 +++++++++++++++++++ 3 files changed, 112 insertions(+) create mode 100644 tools/gamescope/patches/0140-focus-follows-window-opacity.patch create mode 100644 tools/tests/test_gamescope_focus_opacity.py diff --git a/tools/gamescope/PATCHES.md b/tools/gamescope/PATCHES.md index f5a569ddc8..cc719ce35b 100644 --- a/tools/gamescope/PATCHES.md +++ b/tools/gamescope/PATCHES.md @@ -406,3 +406,13 @@ carried `DXVK_HDR=0`. Whether the display can show HDR now comes from the host's either direction. The 10-bit output format is chosen only while HDR is enabled, so an SDR session keeps the 8-bit output it had, and the output images are made again in the other format when the setting changes. On a display that can show HDR, a session that starts with HDR off leaves `DXVK_HDR` unset instead of forcing it to 0, so a game started after HDR is switched on finds it. + +## 0140 Focus is chosen again when a window turns visible or fully transparent + +A window is a focus candidate only while its `_NET_WM_WINDOW_OPACITY` is above zero, but a change of that property +did not ask for focus to be chosen again. Wine sets the property for layered windows, and a window that fades in maps +fully transparent, so it was skipped when it mapped and stayed skipped once it was opaque until something else +changed focus. In a nested session with no other window the SDL window stayed hidden, and the game ran with nothing +on screen. Focus is now chosen again whenever a window's opacity crosses zero in either direction; a change between +two visible opacities leaves focus alone. `tools/tests/test_gamescope_focus_opacity.py` compiles the rule from this +patch and checks the property handler applies it. diff --git a/tools/gamescope/patches/0140-focus-follows-window-opacity.patch b/tools/gamescope/patches/0140-focus-follows-window-opacity.patch new file mode 100644 index 0000000000..e4bd4f99b9 --- /dev/null +++ b/tools/gamescope/patches/0140-focus-follows-window-opacity.patch @@ -0,0 +1,32 @@ +diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp +index cfec551..e98d320 100644 +--- a/src/steamcompmgr.cpp ++++ b/src/steamcompmgr.cpp +@@ -6945,6 +6945,12 @@ handle_system_tray_opcode(xwayland_ctx_t *ctx, XClientMessageEvent *ev) + } + } + ++static bool ++opacity_changes_focus_candidacy( unsigned int oldOpacity, unsigned int newOpacity ) ++{ ++ return ( oldOpacity > TRANSLUCENT ) != ( newOpacity > TRANSLUCENT ); ++} ++ + /* See http://tronche.com/gui/x/icccm/sec-4.html#s-4.1.4 */ + static void + handle_wm_change_state(xwayland_ctx_t *ctx, steamcompmgr_win_t *w, XClientMessageEvent *ev) +@@ -7329,8 +7335,14 @@ handle_property_notify(xwayland_ctx_t *ctx, XPropertyEvent *ev) + + if (newOpacity != w->opacity) + { ++ const bool bFocusCandidacyChanged = opacity_changes_focus_candidacy( w->opacity, newOpacity ); + w->opacity = newOpacity; + ++ if ( bFocusCandidacyChanged ) ++ { ++ MakeFocusDirty(); ++ } ++ + if ( gameFocused && ( w == ctx->focus.overlayWindow || w == ctx->focus.notificationWindow ) ) + { + hasRepaintNonBasePlane = true; diff --git a/tools/tests/test_gamescope_focus_opacity.py b/tools/tests/test_gamescope_focus_opacity.py new file mode 100644 index 0000000000..3d5be63026 --- /dev/null +++ b/tools/tests/test_gamescope_focus_opacity.py @@ -0,0 +1,70 @@ +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +PATCH = ROOT / "tools/gamescope/patches/0140-focus-follows-window-opacity.patch" + + +def added_lines(): + return [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")] + + +def patched_rule(): + text = "\n".join(added_lines()) + start = text.index("static bool") + return text[start:text.index("\n}\n", start) + 3] + + +PREAMBLE = r''' +#include +#include + +#define TRANSLUCENT 0x00000000 +#define OPAQUE 0xffffffff +''' + +MAIN = r''' +int main() { + assert(opacity_changes_focus_candidacy(TRANSLUCENT, OPAQUE)); + assert(opacity_changes_focus_candidacy(TRANSLUCENT, 0x01010101u)); + assert(opacity_changes_focus_candidacy(OPAQUE, TRANSLUCENT)); + assert(opacity_changes_focus_candidacy(0x80808080u, TRANSLUCENT)); + assert(!opacity_changes_focus_candidacy(0x40404040u, 0xc0c0c0c0u)); + assert(!opacity_changes_focus_candidacy(OPAQUE, 0x80808080u)); + assert(!opacity_changes_focus_candidacy(TRANSLUCENT, TRANSLUCENT)); + assert(!opacity_changes_focus_candidacy(OPAQUE, OPAQUE)); + puts("ok"); + return 0; +} +''' + + +@unittest.skipUnless(shutil.which("c++"), "needs a C++ compiler") +class FocusOpacityRuleTest(unittest.TestCase): + def test_only_crossing_fully_transparent_changes_focus_candidacy(self): + with tempfile.TemporaryDirectory() as tmp: + source = Path(tmp) / "opacity.cpp" + binary = Path(tmp) / "opacity" + source.write_text(PREAMBLE + patched_rule() + MAIN) + subprocess.run(["c++", "-std=c++17", "-Wall", "-Werror", str(source), "-o", str(binary)], check=True) + self.assertEqual(subprocess.run([str(binary)], capture_output=True, text=True, check=True).stdout.strip(), "ok") + + +class FocusOpacityHandlerTest(unittest.TestCase): + def test_opacity_property_change_reevaluates_focus_when_candidacy_changes(self): + hunks = PATCH.read_text().split("\n@@ ") + handler = next(hunk for hunk in hunks if "handle_property_notify(" in hunk.split("\n", 1)[0]) + added = [line[1:].strip() for line in handler.splitlines() if line.startswith("+")] + self.assertIn("const bool bFocusCandidacyChanged = opacity_changes_focus_candidacy( w->opacity, newOpacity );", added) + self.assertIn("MakeFocusDirty();", added) + context = [line[1:].strip() for line in handler.splitlines() if line.startswith(" ")] + self.assertIn("w->opacity = newOpacity;", context) + self.assertLess(added.index("const bool bFocusCandidacyChanged = opacity_changes_focus_candidacy( w->opacity, newOpacity );"), added.index("MakeFocusDirty();")) + + +if __name__ == "__main__": + unittest.main() From b891019b87a8257e4de73839eb84d1c0ae8e89b4 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Sun, 22 Nov 2026 14:16:34 -0500 Subject: [PATCH 038/141] fix(steam-x64): keep the session's GL thunk for the x86 web helper (#3027) * fix(steam-x64): keep the session's GL thunk for the x86 web helper FEX's global AppConfig for steamwebhelper turns the GL thunk off and is read after FEX_THUNKCONFIG, so the x86 helper used the rootfs's x86 Mesa. Steam's browser compositor creates its window through SDL3 and GLX in the helper's browser process, x86 Mesa faulted in driCreateNewScreen3 (SIGSEGV) about 11 s after each start, and the client restarted the helper every 12 s. For every global FEX AppConfig that turns off a thunk the session uses, the launcher writes a local AppConfig with the session's thunk set. It leaves local files with other content alone and removes its own files when the client runs in software. * fix(steam-x64): write FEX AppConfig overrides atomically * fix(steam-x64): stage AppConfig overrides in a unique temporary file * fix(steam-x64): publish AppConfig overrides without replacing a newer file --- docs/development/x86-64-steam-client.md | 12 +++ .../overlay/usr/local/bin/droiddeck-steam-x64 | 60 ++++++++++++- .../tests/test_steam_x64_thunk_appconfigs.py | 89 +++++++++++++++++++ 3 files changed, 159 insertions(+), 2 deletions(-) create mode 100644 tools/tests/test_steam_x64_thunk_appconfigs.py diff --git a/docs/development/x86-64-steam-client.md b/docs/development/x86-64-steam-client.md index d8845742bd..87b92e5ac5 100644 --- a/docs/development/x86-64-steam-client.md +++ b/docs/development/x86-64-steam-client.md @@ -131,6 +131,18 @@ The client's web helper draws its whole UI. There are two: blank. `LinuxRuntime` binds an empty folder over `/sys/bus/pci/devices` on such devices; device: 0 GPU process exits, ANGLE on zink and Turnip. +FEX ships per-program AppConfigs, and `/usr/local/share/fex-emu/AppConfig/steamwebhelper.json` turns +the GL thunk off for every program named `steamwebhelper`. A program's AppConfig is read after +`FEX_THUNKCONFIG`, so the x86 helper got the rootfs's x86 Mesa while the client next to it had the +thunk. Steam's browser compositor creates its output window through SDL3 and GLX in the helper's +browser process, and x86 Mesa's `driCreateNewScreen3` (kisak libgallium 26.1.6) faulted there +(SIGSEGV, exit 139) about 11 s after every start; the client restarted it each time (device: 57 +restarts in 11 minutes). `x64_env` therefore writes, for every global AppConfig that turns off a +thunk the session uses, a local AppConfig (`$X64_HOME/.config/fex-emu/AppConfig/.json`, read +after the global one) with the session's thunk set. It never touches a local file with other content, +so a user's own AppConfig wins, and removes its own files when the client runs in software. Device: +helper up for over 10 minutes with no restart, ANGLE on zink and Turnip through the thunk. + The session shim (`preload/net.c`) turns `steamrt64/steamwebhelper.sh`'s exec of `./steamwebhelper` into `DD_X64_ARM_WEBHELPER`. Nothing in the client's folder is edited: the client checksums its files as it starts and reinstalled itself over an edited launcher (2-3 minutes) on every start. diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64 b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64 index 2c77626a1c..97185184c3 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64 +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64 @@ -713,14 +713,67 @@ x64_webhelper_gpu() { x64_gpu && [ "${DD_X64_CLIENT_SOFTWARE:-0}" != 1 ] && [ "${DD_X64_CEF_GPU:-1}" != 0 ] } +x64_thunk_appconfigs() { + python3 - "$1" "$2" "$3" "$4" <<'PY' || true +import json, os, sys, tempfile +src, dst, cfg, on = sys.argv[1:5] +want = json.loads(cfg) +try: + names = sorted(os.listdir(src)) +except OSError: + names = [] +for name in names: + if not name.endswith(".json"): + continue + try: + db = json.load(open(os.path.join(src, name), encoding="utf-8")).get("ThunksDB") or {} + if not any(k in want["ThunksDB"] and not v for k, v in db.items()): + continue + except (OSError, ValueError, AttributeError): + continue + path = os.path.join(dst, name) + try: + cur = json.load(open(path, encoding="utf-8")) + except FileNotFoundError: + cur = None + except (OSError, ValueError): + continue + if cur is not None and cur != want: + continue + if on == "1" and cur is None: + try: + os.makedirs(dst, exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=dst, prefix=".fex", suffix=".tmp") + except OSError: + continue + try: + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.write(cfg + "\n") + os.link(tmp, path) + except OSError: + pass + finally: + try: + os.remove(tmp) + except OSError: + pass + elif on != "1" and cur is not None: + try: + os.remove(path) + except OSError: + pass +PY +} + x64_env() { export -p | grep -v -E '^declare -x (PWD|OLDPWD|SHLVL|_)=' > "$X64_HOME/arm-session.env.new" || true mv -f "$X64_HOME/arm-session.env.new" "$X64_HOME/arm-session.env" unset LD_LIBRARY_PATH LD_PRELOAD STEAM_RUNTIME STEAM_RUNTIME_PREFER_HOST_LIBRARIES gpu_vars="GALLIUM_DRIVER MESA_LOADER_DRIVER_OVERRIDE VK_ICD_FILENAMES VK_DRIVER_FILES LIBGL_KOPPER_DRI2 ZINK_DEBUG ZINK_DESCRIPTORS TU_DEBUG MESA_NO_ERROR mesa_glthread" +thunk_cfg='{"ThunksDB": {"GL": 1, "Vulkan": 1}}' rm -f "$X64_HOME/game-gpu.env" if x64_gpu; then - printf '{"ThunksDB": {"GL": 1, "Vulkan": 1}}\n' > "$X64_HOME/thunks.json" + printf '%s\n' "$thunk_cfg" > "$X64_HOME/thunks.json" { echo "export FEX_THUNKCONFIG='$X64_HOME/thunks.json'" echo "unset LIBGL_ALWAYS_SOFTWARE LIBGL_DRI3_DISABLE GALLIUM_DRIVER" @@ -729,7 +782,10 @@ if x64_gpu; then done } > "$X64_HOME/game-gpu.env" fi -if x64_gpu && [ "${DD_X64_CLIENT_SOFTWARE:-0}" != 1 ]; then +client_thunks=0 +x64_gpu && [ "${DD_X64_CLIENT_SOFTWARE:-0}" != 1 ] && client_thunks=1 +x64_thunk_appconfigs /usr/local/share/fex-emu/AppConfig "$X64_HOME/.config/fex-emu/AppConfig" "$thunk_cfg" "$client_thunks" +if [ "$client_thunks" = 1 ]; then export FEX_THUNKCONFIG=$X64_HOME/thunks.json unset LIBGL_ALWAYS_SOFTWARE LIBGL_DRI3_DISABLE else diff --git a/tools/tests/test_steam_x64_thunk_appconfigs.py b/tools/tests/test_steam_x64_thunk_appconfigs.py new file mode 100644 index 0000000000..a949a5d753 --- /dev/null +++ b/tools/tests/test_steam_x64_thunk_appconfigs.py @@ -0,0 +1,89 @@ +import json +import os +from pathlib import Path +import re +import subprocess +import tempfile +import unittest + + +SCRIPT = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-steam-x64' +SOURCE = SCRIPT.read_text() +FUNCTION = re.search(r'^x64_thunk_appconfigs\(\) \{\n.*?^\}\n', SOURCE, re.M | re.S).group() +CFG = '{"ThunksDB": {"GL": 1, "Vulkan": 1}}' + + +class SteamX64ThunkAppConfigsTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + root = Path(self.temp.name) + self.src = root / 'global' + self.dst = root / 'local' + self.src.mkdir() + + def write_global(self, name, data): + (self.src / name).write_text(json.dumps(data)) + + def run_fn(self, on): + shell = FUNCTION + 'x64_thunk_appconfigs "$SRC" "$DST" "$CFG" "$ON"\n' + env = dict(os.environ, SRC=str(self.src), DST=str(self.dst), CFG=CFG, ON=on) + result = subprocess.run(['bash', '-eu', '-c', shell], env=env, capture_output=True, text=True, timeout=20) + self.assertEqual(0, result.returncode, result.stderr) + + def test_program_with_a_disabled_thunk_gets_the_session_thunks(self): + self.write_global('anyprogram.json', {'Comment': 'x', 'ThunksDB': {'GL': 0}}) + self.run_fn('1') + self.assertEqual(json.loads(CFG), json.loads((self.dst / 'anyprogram.json').read_text())) + + def test_disabled_vulkan_counts_too(self): + self.write_global('other.json', {'ThunksDB': {'Vulkan': 0}}) + self.run_fn('1') + self.assertTrue((self.dst / 'other.json').exists()) + + def test_programs_without_a_thunk_opt_out_are_untouched(self): + self.write_global('client.json', {'Config': {'HideHypervisorBit': '1'}}) + self.write_global('enabled.json', {'ThunksDB': {'GL': 1}}) + self.write_global('unrelated.json', {'ThunksDB': {'asound': 0}}) + self.run_fn('1') + self.assertFalse(self.dst.exists()) + + def test_user_override_is_kept(self): + self.write_global('anyprogram.json', {'ThunksDB': {'GL': 0}}) + self.dst.mkdir() + user = {'ThunksDB': {'GL': 0}, 'Config': {'Multiblock': '0'}} + (self.dst / 'anyprogram.json').write_text(json.dumps(user)) + self.run_fn('1') + self.assertEqual(user, json.loads((self.dst / 'anyprogram.json').read_text())) + self.run_fn('0') + self.assertEqual(user, json.loads((self.dst / 'anyprogram.json').read_text())) + + def test_software_mode_removes_only_the_written_file(self): + self.write_global('anyprogram.json', {'ThunksDB': {'GL': 0}}) + self.run_fn('1') + self.run_fn('0') + self.assertFalse((self.dst / 'anyprogram.json').exists()) + + def test_software_mode_writes_nothing(self): + self.write_global('anyprogram.json', {'ThunksDB': {'GL': 0}}) + self.run_fn('0') + self.assertFalse(self.dst.exists()) + + def test_broken_global_configs_do_not_fail(self): + (self.src / 'broken.json').write_text('{') + self.write_global('list.json', [1, 2]) + self.run_fn('1') + self.assertFalse(self.dst.exists()) + + def test_missing_global_dir_does_not_fail(self): + self.src = self.src / 'missing' + self.run_fn('1') + self.assertFalse(self.dst.exists()) + + def test_launcher_applies_it_to_the_fex_app_config_dirs(self): + self.assertIn('x64_thunk_appconfigs /usr/local/share/fex-emu/AppConfig "$X64_HOME/.config/fex-emu/AppConfig" "$thunk_cfg" "$client_thunks"', SOURCE) + self.assertIn('''printf '%s\\n' "$thunk_cfg" > "$X64_HOME/thunks.json"''', SOURCE) + + +if __name__ == '__main__': + unittest.main() From 7f61e514e69d9dcf47ac2a22087a5f3eb3f45306 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Sun, 22 Nov 2026 14:27:08 -0500 Subject: [PATCH 039/141] chore: pin gamescope to the release with the opacity focus fix (#3031) --- tools/gamescope/release.env | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/gamescope/release.env b/tools/gamescope/release.env index c2ff293485..52d5d20e44 100644 --- a/tools/gamescope/release.env +++ b/tools/gamescope/release.env @@ -1,3 +1,3 @@ GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components -GAMESCOPE_TAG=gamescope-3.16.29-zerocopy-8df683f1-qa -GAMESCOPE_SHA256=609198c39b125094a65e1703ffcfd6538e88c9784a1a6596bf673f2e5dc7af80 +GAMESCOPE_TAG=gamescope-3.16.29-1a29c65d +GAMESCOPE_SHA256=18620dfedb65860da00003e965cc09784a650ef6ecc9a17056405fe0a1392a02 From 2c2d55058ee6dfa2621b2a6f1df1b098b647a579 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Sun, 22 Nov 2026 16:20:34 -0500 Subject: [PATCH 040/141] fix(preload): open synthesized socket tables when the fd reopen is denied (#3034) --- tools/linuxfs/preload/netif.c | 5 +++- tools/tests/test_netlink_preload.py | 37 ++++++++++++++++++++++------- 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/tools/linuxfs/preload/netif.c b/tools/linuxfs/preload/netif.c index 04100065fb..38453ba5ab 100644 --- a/tools/linuxfs/preload/netif.c +++ b/tools/linuxfs/preload/netif.c @@ -590,7 +590,7 @@ static int denied_table(const char *path) { static FILE *synthesize(int table) { struct link link; if (!load_link(&link) && table < SOCKET_TABLES) return NULL; - int fd = memfd_create("droiddeck-net", MFD_CLOEXEC); + int fd = memfd_create("droiddeck-net", MFD_CLOEXEC | MFD_ALLOW_SEALING); if (fd < 0) return NULL; FILE *out = fdopen(fd, "w+"); if (out == NULL) { @@ -648,6 +648,9 @@ int dd_net_open(const char *path, int flags, int fd) { char self[32]; snprintf(self, sizeof(self), "/proc/self/fd/%d", fileno(f)); int copy = open(self, O_RDONLY | (flags & O_CLOEXEC)); + if (copy < 0 && fcntl(fileno(f), F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE | F_SEAL_SEAL) == 0) { + copy = fcntl(fileno(f), flags & O_CLOEXEC ? F_DUPFD_CLOEXEC : F_DUPFD, 0); + } fclose(f); if (copy < 0) { errno = saved; diff --git a/tools/tests/test_netlink_preload.py b/tools/tests/test_netlink_preload.py index 8a6dc79523..9c52c909f3 100644 --- a/tools/tests/test_netlink_preload.py +++ b/tools/tests/test_netlink_preload.py @@ -96,10 +96,17 @@ FILE *fopen(const char *path, const char *mode) { } static int denied(const char *path) { - const char *prefix = getenv("NETLINK_TEST_DENIED"); - if (!prefix || !path || strncmp(path, prefix, strlen(prefix))) return 0; - errno = EACCES; - return 1; + const char *prefixes = getenv("NETLINK_TEST_DENIED"); + if (!prefixes || !path) return 0; + for (const char *prefix = prefixes; *prefix;) { + size_t length = strcspn(prefix, ":"); + if (length && !strncmp(path, prefix, length)) { + errno = EACCES; + return 1; + } + prefix += length + (prefix[length] == ':'); + } + return 0; } int open(const char *path, int flags, ...) { @@ -112,6 +119,12 @@ int open(const char *path, int flags, ...) { return denied(path) ? -1 : real(path, flags, mode); } +int __open_2(const char *path, int flags) { + static int (*real)(const char *, int); + if (!real) real = dlsym(RTLD_NEXT, "__open_2"); + return denied(path) ? -1 : real(path, flags); +} + int openat(int dirfd, const char *path, int flags, ...) { static int (*real)(int, const char *, int, ...); if (!real) real = dlsym(RTLD_NEXT, "openat"); @@ -167,7 +180,7 @@ static int route_socket(void) { return descriptor; } -static void proc_net_test(int denied) { +static void proc_net_test(int denied, int sealed) { static const char *const tables[] = {"/proc/net/tcp", "/proc/net/tcp6", "/proc/net/udp", "/proc/net/udp6"}; char text[512], target[128], link[64]; for (unsigned i = 0; i < sizeof(tables) / sizeof(tables[0]); i++) { @@ -180,8 +193,13 @@ static void proc_net_test(int denied) { target[length] = 0; require((strncmp(target, "/memfd:droiddeck-net", 20) == 0) == denied, "synthesized only when denied"); if (denied) { - require((fcntl(descriptor, F_GETFL) & O_ACCMODE) == O_RDONLY, "socket table is read-only"); - require(write(descriptor, "x", 1) < 0 && errno == EBADF, "socket table rejects writes"); + if (sealed) { + require(fcntl(descriptor, F_GET_SEALS) & F_SEAL_WRITE, "socket table is sealed"); + require(write(descriptor, "x", 1) < 0 && errno == EPERM, "sealed socket table rejects writes"); + } else { + require((fcntl(descriptor, F_GETFL) & O_ACCMODE) == O_RDONLY, "socket table is read-only"); + require(write(descriptor, "x", 1) < 0 && errno == EBADF, "socket table rejects writes"); + } ssize_t total = read(descriptor, text, sizeof(text) - 1); require(total > 0, "socket table read"); text[total] = 0; @@ -1191,7 +1209,7 @@ int main(int argc, char **argv) { } else if (!strcmp(argv[1], "range") || !strcmp(argv[1], "cloexec") || !strcmp(argv[1], "closefrom")) close_range_test(argv[1]); - else if (!strcmp(argv[1], "proc_net")) proc_net_test(argc > 2 && !strcmp(argv[2], "denied")); + else if (!strcmp(argv[1], "proc_net")) proc_net_test(argc > 2 && strcmp(argv[2], "allowed"), argc > 2 && !strcmp(argv[2], "sealed")); else if (!strcmp(argv[1], "route")) { require(argc >= 3, "route destination"); route_test(argv[2]); @@ -1367,6 +1385,9 @@ class NetlinkPreloadTest(unittest.TestCase): def test_denied_socket_tables_open_as_empty_tables(self): self.run_program("proc_net", "denied", denied="/proc/net/") + def test_denied_socket_tables_open_when_fd_reopen_is_denied(self): + self.run_program("proc_net", "sealed", denied="/proc/net/:/proc/self/fd/") + def test_readable_socket_tables_stay_real(self): self.run_program("proc_net") From a0e7c1715a885f3cd1ce5512f507275e6fd64f23 Mon Sep 17 00:00:00 2001 From: Tushar Gandhe <19225304+2-Shar@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:28:49 +0530 Subject: [PATCH 041/141] fix(ui): smaller game page link pills with a gap between rows (#2973) --- .../main/java/com/droiddeck/launcher/ui/GameResources.kt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameResources.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameResources.kt index 3eb42902b3..275c9361ef 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameResources.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameResources.kt @@ -60,7 +60,7 @@ internal fun gameResources(title: String, game: Library.SteamGame?): List Date: Mon, 23 Nov 2026 03:28:53 +0530 Subject: [PATCH 042/141] fix(library): put the store accounts button on the right of the source chips, as on other pages (#2929) --- app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt index 0181d39398..e940e7b47f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt @@ -914,7 +914,6 @@ private fun LibraryFilters(sources: List, 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) { @@ -946,6 +945,7 @@ private fun LibraryFilters(sources: List, source: String, onSource: (Str } if (highlighted in keys) ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown) } + if (manage) ManageStoresChip() } } } From c3809c0a7509bd7221aada9208685a861dcba5f3 Mon Sep 17 00:00:00 2001 From: Tushar Gandhe <19225304+2-Shar@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:28:57 +0530 Subject: [PATCH 043/141] fix(ui): keep the Agent composer above the keyboard and release search fields on tap (#2852) * fix(agent): keep the composer above the keyboard outside fullscreen * fix(ui): release a search field when another control is tapped * fix(ui): release the add-on search field in its dialog, and let a reopened search take focus * fix(ui): a drag that returns to where it began does not release the search field --- .../droiddeck/launcher/FrontEndActivity.kt | 33 ++++++++ .../com/droiddeck/launcher/ui/AddonBrowser.kt | 2 +- .../com/droiddeck/launcher/ui/AgentPage.kt | 5 ++ .../com/droiddeck/launcher/ui/ScreenTaps.kt | 76 +++++++++++++++++++ .../droiddeck/launcher/ui/SettingsSearch.kt | 15 +++- .../com/droiddeck/launcher/ui/StoresPage.kt | 15 +++- .../launcher/ui/WirelessAdbFixPage.kt | 9 ++- 7 files changed, 146 insertions(+), 9 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/ui/ScreenTaps.kt diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index b798893aa7..d8b78f2c68 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -17,8 +17,11 @@ 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 @@ -2042,6 +2045,36 @@ 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) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt index 4987ad3bb4..656166a243 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt @@ -162,7 +162,7 @@ internal fun AddonBrowserDialog(targets: List, 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) { + AppDialog(shown, close, "addonBrowser", wide = true, maxWidth = 980.dp, scrollable = false, fillHeight = true, modifier = Modifier.releaseTextFieldOnTap()) { val sortChip: @Composable () -> Unit = { BrowseDropdown(sortLabel(sort)) { first, done -> WowAddonCatalog.Sort.entries.forEachIndexed { index, option -> diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt index 225b81444a..f447b15686 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt @@ -2,6 +2,7 @@ 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 @@ -184,7 +185,11 @@ private fun AgentPageContent( ?: generateSequence(view.context) { (it as? ContextWrapper)?.baseContext } .filterIsInstance().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) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ScreenTaps.kt b/app/src/main/java/com/droiddeck/launcher/ui/ScreenTaps.kt new file mode 100644 index 0000000000..20c942dea6 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/ScreenTaps.kt @@ -0,0 +1,76 @@ +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(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) + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsSearch.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsSearch.kt index f2adebd9bf..0a4ab5590c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsSearch.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsSearch.kt @@ -49,6 +49,12 @@ 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) { @@ -73,15 +79,18 @@ 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, + placeholder = stringResource(R.string.settings_search), compact = true, showLabel = false, focusOnShow = focusOnOpen, focusAtTap = focusTap, clearFocus = !searching, - onFocusChange = { focused -> if (!focused && query.isEmpty() && searching) { focusOnOpen = false; onClose() } }, + onFocusChange = { focused -> + fieldFocused = 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)) { focusOnOpen = true; onOpen() } } + Box(Modifier.focusRequester(icon)) { SearchIcon(stringResource(R.string.settings_search)) { focusTap = ScreenTaps.count; focusOnOpen = true; onOpen() } } } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt index a54c7f9bfb..30caa5fca7 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt @@ -925,6 +925,12 @@ 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() } @@ -955,9 +961,12 @@ 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, + placeholder = placeholder, compact = true, showLabel = false, focusOnShow = focusOnOpen, focusAtTap = focusTap, clearFocus = clearSearchFocus || !searching, - onFocusChange = { focused -> if (!focused && query.isEmpty()) { searching = false; focusOnOpen = false } }, + onFocusChange = { focused -> + fieldFocused = 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) @@ -965,7 +974,7 @@ internal fun ModeHeader( } } val searchButton: @Composable () -> Unit = { - Box(Modifier.focusRequester(searchIcon)) { SearchIcon(stringResource(R.string.stores_search_open)) { searching = true; focusOnOpen = true } } + Box(Modifier.focusRequester(searchIcon)) { SearchIcon(stringResource(R.string.stores_search_open)) { focusTap = ScreenTaps.count; searching = true; focusOnOpen = true } } } BoxWithConstraints(Modifier.fillMaxWidth()) { val stacked = maxWidth < NarrowPaneWidth diff --git a/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt index ebcfcb1ea7..c2e79b9c86 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt @@ -365,11 +365,13 @@ internal fun AdbTextField( 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(1) } val palette = LocalPalette.current val onValueChangeLatest = rememberUpdatedState(onValueChange) val onNextLatest = rememberUpdatedState(onNext) @@ -502,9 +504,12 @@ internal fun AdbTextField( }, update = { editText -> editText.showSoftInputOnFocus = !bottomTyping - if (focusOnShow && !focusAsked[0]) { - focusAsked[0] = true + // 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) From 234e40157e23ad1b476bc9098411e2e6b79d6cc9 Mon Sep 17 00:00:00 2001 From: Tushar Gandhe <19225304+2-Shar@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:29:01 +0530 Subject: [PATCH 044/141] feat(launcher): LT and RT step between the main tabs from anywhere in the launcher (#3035) * feat(launcher): LT and RT step between the main tabs from anywhere in the launcher LT and RT move to the previous and next main tab on every layout. The activity handles them before any page sees the key, so a focused control, an embedded Android view such as the terminal, or nothing being focused no longer swallows them; dialogs and popups keep their own keys. Pads that report the triggers only as axes, like the Xbox Wireless Controller, get an L2/R2 press when a trigger passes 60% of its travel; pads that send their own trigger keys are left alone. * fix(launcher): trigger tab steps tick, drop a pending press on focus loss, and move once per pull Controller haptics now ticks for L2 and R2. A synthetic trigger press waiting its 40 ms is cancelled when the launcher loses window focus or is destroyed, so a dialog that opens in between keeps the page behind it. Each pull is tracked: when a synthetic press has gone out, the pad's own trigger key for the same pull is swallowed instead of stepping a second tab. --- .../droiddeck/launcher/FrontEndActivity.kt | 13 +++ .../droiddeck/launcher/input/TriggerKeys.kt | 81 +++++++++++++++++++ .../launcher/ui/ControllerHaptics.kt | 1 + .../droiddeck/launcher/ui/FrontEndScreen.kt | 32 +++++--- 4 files changed, 114 insertions(+), 13 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/input/TriggerKeys.kt diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index d8b78f2c68..eb9d67c1e4 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -2016,6 +2016,7 @@ 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() @@ -2085,6 +2086,14 @@ 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)) { @@ -2102,9 +2111,12 @@ 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) } @@ -2234,6 +2246,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } override fun onDestroy() { + triggerKeys.cancel() gameLaunchRequest.incrementAndGet() cancelCompatLaunch() updates.unregister() diff --git a/app/src/main/java/com/droiddeck/launcher/input/TriggerKeys.kt b/app/src/main/java/com/droiddeck/launcher/input/TriggerKeys.kt new file mode 100644 index 0000000000..785414ed8b --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/TriggerKeys.kt @@ -0,0 +1,81 @@ +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() + private val pulls = HashMap() + 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 + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ControllerHaptics.kt b/app/src/main/java/com/droiddeck/launcher/ui/ControllerHaptics.kt index 8f06cd50af..da1d8d4bb4 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ControllerHaptics.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ControllerHaptics.kt @@ -12,6 +12,7 @@ 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) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt index 0fd09b0693..0fa75a5855 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -761,6 +761,20 @@ 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 } } @@ -768,19 +782,7 @@ 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 (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), + .then(if (openTab == "agent") Modifier.imePadding() else Modifier), navigation = { if (s.dualScreen || (bottomNavigation && agentKeyboardOpen)) Unit else if (bottomNavigation) BottomBar(s, railSelection, onRailSelect, onRailFocus, a, railFocus) @@ -902,3 +904,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com } } } + +internal object MainTabSteps { + @Volatile var handler: ((Int) -> Unit)? = null +} From 210c127446f22778b1211ca2210a1eefc9f4f70d Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Sun, 22 Nov 2026 17:02:35 -0500 Subject: [PATCH 045/141] feat(addons): add a CurseForge source to the addon browser (#3028) * feat(addons): add a CurseForge source to the addon browser Search and install CurseForge addons from the Download addons window by driving the installed CurseForge app in the background: it starts minimized on the session's X display with its inspector bound to 127.0.0.1, and the window's own renderer services handle game detection, search, install and shutdown. Sign-in stays inside the CurseForge app. The Install buttons in the addon list now size to their label, so the label is centered and the button matches the other compact buttons. * fix(curseforge): secret inspector URL, hold mode and serialised starts - Start CurseForge with its Node inspector on 127.0.0.1:0 and publish only the UUID websocket URL, kept in the 0700 state directory, so no fixed unauthenticated debug port is exposed. - The agent evaluates through that URL instead of a fixed port. - Add a hold mode that runs as a session program and stops the app on exit, and a lock so hold and start never launch twice. * feat(addons): run CurseForge in a hidden session when none is running - Opening the CurseForge source with no session starts one headlessly (offscreen compositor output, shared start path with SessionActivity via CompositorHost) running the CurseForge hold helper; leaving the dialog stops the app and that session. A session the user already had is reused and left running. - Drop the "start a session" notice from every locale. - Addon browser link: cleanup shares the link's lock off the UI thread, stops the app at once on close, refuses work after close and stops a launch that finishes after close. - CurseForgeApp.start stops the app before every failed return. - instanceFor returns no instance when the populated list has no match. * Harden headless CurseForge session and helper lifecycle Scope the hidden session to its id, roll back partial starts, release the offscreen reader once the session ends, re-acquire the inspector when its endpoint goes away, bound DevTools calls by one deadline, key the installed snapshot by target, track the helper launch by pid start time and directory, fail on lock errors, and update the HDR gate test to its new location. * Map DevTools send failures and recheck the hidden session id * fix(addons): bind the hidden session to the id it claims at launch * Keep the CurseForge helper quiet when no launch is recorded --- .../com/droiddeck/launcher/SessionActivity.kt | 37 +--- .../launcher/runtime/CurseForgeApp.kt | 206 ++++++++++++++++++ .../launcher/runtime/WowAddonCatalog.kt | 3 +- .../droiddeck/launcher/runtime/WowAddons.kt | 8 + .../launcher/session/BackgroundSession.kt | 119 ++++++++++ .../launcher/session/SessionFiles.kt | 1 + .../com/droiddeck/launcher/ui/AddonBrowser.kt | 168 +++++++++++++- .../com/droiddeck/launcher/ui/GameDetail.kt | 2 +- .../launcher/wayland/CompositorHost.kt | 48 ++++ app/src/main/res/values-ar/strings.xml | 1 + app/src/main/res/values-b+es+419/strings.xml | 1 + app/src/main/res/values-bg/strings.xml | 1 + app/src/main/res/values-cs/strings.xml | 1 + app/src/main/res/values-da/strings.xml | 1 + app/src/main/res/values-de/strings.xml | 1 + app/src/main/res/values-el/strings.xml | 1 + app/src/main/res/values-es/strings.xml | 1 + app/src/main/res/values-fi/strings.xml | 1 + app/src/main/res/values-fr/strings.xml | 1 + app/src/main/res/values-hi/strings.xml | 1 + app/src/main/res/values-hu/strings.xml | 1 + app/src/main/res/values-in/strings.xml | 1 + app/src/main/res/values-it/strings.xml | 1 + app/src/main/res/values-ja/strings.xml | 1 + app/src/main/res/values-ko/strings.xml | 1 + app/src/main/res/values-ms/strings.xml | 1 + app/src/main/res/values-nb/strings.xml | 1 + app/src/main/res/values-nl/strings.xml | 1 + app/src/main/res/values-pl/strings.xml | 1 + app/src/main/res/values-pt-rPT/strings.xml | 1 + app/src/main/res/values-pt/strings.xml | 1 + app/src/main/res/values-ro/strings.xml | 1 + app/src/main/res/values-ru/strings.xml | 1 + app/src/main/res/values-sv/strings.xml | 1 + app/src/main/res/values-th/strings.xml | 1 + app/src/main/res/values-tr/strings.xml | 1 + app/src/main/res/values-uk/strings.xml | 1 + app/src/main/res/values-vi/strings.xml | 1 + app/src/main/res/values-zh-rCN/strings.xml | 1 + app/src/main/res/values-zh-rHK/strings.xml | 1 + app/src/main/res/values-zh-rTW/strings.xml | 1 + app/src/main/res/values/strings.xml | 1 + .../launcher/runtime/CurseForgeAppTest.kt | 161 ++++++++++++++ .../overlay/usr/local/bin/droiddeck-agent | 77 +++++-- .../usr/local/bin/droiddeck-curseforge | 150 +++++++++++++ tools/tests/test_curseforge_helper.py | 173 +++++++++++++++ tools/tests/test_droiddeck_agent.py | 33 +++ tools/tests/test_hdr_live_switch.py | 10 +- 48 files changed, 1162 insertions(+), 67 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/session/BackgroundSession.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt create mode 100755 tools/linuxfs/overlay/usr/local/bin/droiddeck-curseforge create mode 100644 tools/tests/test_curseforge_helper.py diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 7e6ad0376d..1d51cd2a88 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -2846,17 +2846,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (!SessionState.running) { SessionEvents.transition(SessionPhase.STARTING_COMPOSITOR, "compositor.starting") } - val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() } - FileUtils.copyAsset(this, "wayland/keymap.xkb", File(runtimeDir, "keymap.xkb")) - com.droiddeck.launcher.input.VrControllers.publish(this) - - val turnip = TurnipDriver(this) - com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "surface.driver-setup") - if (!CompositorHost.isStarted) { - CompositorHost.displayChoice = SessionPrefs.androidDriver(this) - com.droiddeck.launcher.gpu.AutoDriverTrial.displayStarting(this, SessionPrefs.androidDriver(this)) - } - val driverId = if (CompositorHost.isStarted) null else turnip.install() + val output = CompositorHost.prepare(this) val previous = SessionState.outputSize val live = windowOutputSize(holder.surfaceFrame.width(), holder.surfaceFrame.height()) @@ -2883,15 +2873,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde pushCardboard(activeCardboard) WaylandCompositor.nativeSetCardboardPoseFile(File(filesDir, ".wayland-rt/droiddeck-headpose").path) com.droiddeck.launcher.glasses.SpatialTracking.attachPublisher(File(filesDir, ".wayland-rt/droiddeck-spatialpose").path) - if (!SessionState.running) { - val waylandLog = File(SessionPaths.beginOrCurrent(this), "wayland.log") - WaylandCompositor.setSessionLogFile(waylandLog) - try { - android.system.Os.setenv("DD_WAYLAND_LOG", waylandLog.path, true) - } catch (e: Exception) { - Log.w(TAG, "could not point the compositor's log at $waylandLog", e) - } - } + if (!SessionState.running) CompositorHost.logToSession(this) val mode = hdrPrefMode() if (probe != null) { WaylandCompositor.nativeSetHdrDisplay( @@ -2911,19 +2893,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde ) Log.i(TAG, "hdr: " + (if (tonemap) "tone-mapped (${probe.reason})" else if (capable) "available" else "unavailable") + " · display ${probe.formats.ifEmpty { "SDR" }}") } - if (!SessionState.running) { - val on = SessionState.hdrCapable && SessionPrefs.hdr(this, mode) - SessionState.hdr = on - WaylandCompositor.nativeSetHdrOutput(on) - WaylandCompositor.nativeSetZeroCopy(on || SessionPrefs.zeroCopy(this, mode)) - Log.i(TAG, "hdr: " + (if (on) "on" else "off") + " for this $mode session") - } - com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "compositor.start driver=$driverId") - CompositorHost.startOrAttach( - this, holder.surface, runtimeDir.path, - driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) }, - applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(holder), outputFpsLimit(), - ) + if (!SessionState.running) CompositorHost.applyHdr(this, mode) + CompositorHost.start(this, output, holder.surface, size, refreshHz(holder), outputFpsLimit()) onOutputAttached(holder) if (SessionState.running && size != previous) { Log.i(TAG, "output resized: ${previous.first}x${previous.second} -> ${size.first}x${size.second} on a new surface") diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt b/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt index 1a40e6ead2..5477c8ede1 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt @@ -1,10 +1,216 @@ package com.droiddeck.launcher.runtime +import android.content.Context +import com.droiddeck.launcher.agent.AgentException +import com.droiddeck.launcher.agent.AgentGuest +import org.json.JSONArray +import org.json.JSONObject +import java.time.Instant + 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" + private const val READY_MS = 120_000L + private const val INSTALL_MS = 300_000L + + enum class Start { READY, BUSY, NO_DISPLAY, FAILED } + + class Started(val state: Start, val inspector: String? = null) + + private 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? = 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("/") } + + fun holdArgs(app: UserApps.App): List? = dir(app)?.let { listOf("hold", it) } + + 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 + 4 -> Start.NO_DISPLAY + else -> Start.FAILED + } + + internal fun sortOf(sort: WowAddonCatalog.Sort): Pair = 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 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 inner = "(async () => { const s = $SERVICES[${JSONObject.quote(service)}]; " + + "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 projectIds(value: Any?): Set { + val list = value as? JSONArray ?: return emptySet() + return (0 until list.length()).mapNotNull { list.opt(it)?.toString()?.takeIf { id -> id.isNotBlank() && id != "null" } }.toSet() + } + + private fun call(context: Context, inspector: String, service: String, method: String, args: JSONArray?, timeoutMs: Long, pick: String = "r => r"): Any? { + val request = JSONObject().put("kind", "cdp").put("inspector", inspector).put("commandLineApi", true) + .put("expression", expression(service, method, args, pick)).put("timeout", timeoutMs / 1000.0) + return unwrap(AgentGuest.call(context, request, timeoutMs + 3_000, trusted = true)) + } + + private fun helper(context: Context, command: String, dir: String, timeoutMs: Long): JSONObject? { + val request = JSONObject().put("kind", "exec").put("argv", JSONArray(listOf(HELPER, command, dir))).put("timeout", timeoutMs / 1000.0) + return runCatching { AgentGuest.call(context, request, timeoutMs + 5_000, trusted = true) }.getOrNull() + } + + fun start(context: Context, app: UserApps.App): Started { + val dir = dir(app) ?: return Started(Start.FAILED) + val answer = helper(context, "start", dir, 90_000) + if (answer == null || !answer.optBoolean("ok") || answer.optBoolean("timedOut")) { + stop(context, app, null) + return Started(Start.FAILED) + } + val state = startState(answer.optInt("exitCode", -1)) + if (state == Start.BUSY || state == Start.NO_DISPLAY) return Started(state) + val inspector = inspectorUrl(answer.optJSONObject("stdout")?.optString("text").orEmpty()) + if (state != Start.READY || inspector == null) { + stop(context, app, null) + return Started(Start.FAILED) + } + val deadline = System.currentTimeMillis() + READY_MS + while (System.currentTimeMillis() < deadline) { + val ready = runCatching { call(context, inspector, "InstalledProjectsAppService", "installAddon", null, 10_000) } + if (ready.isSuccess) return Started(Start.READY, inspector) + val error = ready.exceptionOrNull() + if (error is AgentException && error.code == "NO_ACTIVE_SESSION") break + Thread.sleep(1_000) + } + stop(context, app, inspector) + return Started(Start.FAILED) + } + + fun stop(context: Context, app: UserApps.App, inspector: String?) { + val dir = dir(app) ?: return + if (inspector != null) runCatching { call(context, inspector, "CoreService", "shutdown", JSONArray(), 30_000, "r => true") } + helper(context, "stop", dir, 30_000) + } + + private fun connect(context: Context, inspector: String) { + call(context, inspector, "CoreService", "connect", JSONArray(), 120_000, "r => true") + } + + fun instance(context: Context, inspector: String, root: String, flavorDir: String): String { + connect(context, inspector) + val detected = call(context, inspector, "GameDetectionAppService", "detectGameFromPath", JSONArray().put(root).put(WOW), 60_000) as? JSONObject + val instances = call(context, inspector, "GameAppService", "getGameInstances", JSONArray().put(WOW), 30_000, + "r => (r || []).map(i => ({ guid: i.guid, installPath: i.installPath }))") + return instanceFor(instances, 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 installed(context: Context, inspector: String, guid: String): Set { + connect(context, inspector) + return projectIds(call(context, inspector, "InstalledProjectsAppService", "getProjects", JSONArray().put(guid), 30_000, "r => (r || []).map(p => String(p.id))")) + } + + fun install(context: Context, inspector: String, guid: String, projectId: String): Boolean { + connect(context, inspector) + if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return false + val deadline = System.currentTimeMillis() + INSTALL_MS + while (System.currentTimeMillis() < deadline) { + val listed = runCatching { installed(context, inspector, guid) } + val error = listed.exceptionOrNull() + if (error is Failure && error.gone || error is AgentException && error.code == "NO_ACTIVE_SESSION") throw error + if (projectId in listed.getOrDefault(emptySet())) return true + Thread.sleep(1_000) + } + return false + } } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddonCatalog.kt b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddonCatalog.kt index 203e7aed5b..bca0627bec 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddonCatalog.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddonCatalog.kt @@ -93,8 +93,7 @@ object WowAddonCatalog { Client(folder, version?.let(::flavorOf) ?: folderFamily(folder)) fun client(target: WowAddons.Target): Client { - val dir = target.addOns.parentFile?.parentFile - return client(target.flavor, dir?.let(::clientVersion)) + return client(target.flavor, WowAddons.flavorDir(target)?.let(::clientVersion)) } internal fun flavorMatches(flavors: Set?, family: String?): Boolean = diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt index 0763723d6a..799cfe7717 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt @@ -28,6 +28,14 @@ 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) diff --git a/app/src/main/java/com/droiddeck/launcher/session/BackgroundSession.kt b/app/src/main/java/com/droiddeck/launcher/session/BackgroundSession.kt new file mode 100644 index 0000000000..50c60f5747 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/BackgroundSession.kt @@ -0,0 +1,119 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import android.graphics.PixelFormat +import android.media.ImageReader +import android.os.Handler +import android.os.Looper +import android.util.Log +import com.droiddeck.launcher.agent.AgentGuest +import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller +import com.droiddeck.launcher.storage.StorageState +import com.droiddeck.launcher.wayland.CompositorHost +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean + +object BackgroundSession { + private const val TAG = "BackgroundSession" + private const val WIDTH = 1280 + private const val HEIGHT = 720 + private const val REFRESH_HZ = 60f + private const val BEGIN_MS = 30_000L + private const val AGENT_MS = 120_000L + private const val STOP_MS = 30_000L + private val ended = setOf(SessionPhase.IDLE, SessionPhase.FAILED) + private val main by lazy { Handler(Looper.getMainLooper()) } + private var reader: ImageReader? = null + + fun start(context: Context, program: String, args: List): String? { + val app = context.applicationContext + val claim = AtomicBoolean(false) + val began = CountDownLatch(1) + var own: String? = null + main.post { + if (claim.compareAndSet(false, true)) { + own = runCatching { begin(app, program, args) } + .onFailure { Log.w(TAG, "could not start a hidden session for $program", it) } + .getOrNull() + } + began.countDown() + } + if (!began.await(BEGIN_MS, TimeUnit.MILLISECONDS) && claim.compareAndSet(false, true)) return null + began.await() + val session = own ?: return null + val deadline = System.currentTimeMillis() + AGENT_MS + val settle = System.currentTimeMillis() + 5_000 + while (System.currentTimeMillis() < deadline) { + if (SessionState.sessionId != session) return null + if (SessionState.running && AgentGuest.hello(app) != null && SessionState.sessionId == session) return session + if (SessionState.phase == SessionPhase.FAILED) break + if (!SessionState.running && SessionState.phase in ended && System.currentTimeMillis() > settle) break + Thread.sleep(250) + } + stop(app, session) + return null + } + + fun stop(context: Context, session: String) { + val app = context.applicationContext + if (SessionState.sessionId != session) return + main.post { if (SessionState.sessionId == session) SessionService.stop(app) } + val deadline = System.currentTimeMillis() + STOP_MS + while (live(session) && System.currentTimeMillis() < deadline) Thread.sleep(250) + if (!live(session)) { + main.post { release() } + return + } + Thread { + while (live(session)) Thread.sleep(1_000) + main.post { release() } + }.start() + } + + private fun live(session: String) = + SessionState.sessionId == session && (SessionState.running || SessionState.phase !in ended) + + private fun begin(context: Context, program: String, args: List): String? { + if (SessionState.running || SessionState.phase !in ended || LinuxRuntimeInstaller.isBusy() || + SessionState.installing != null || StorageState.cleaning) return null + release() + SessionEvents.begin(context, SessionService.MODE_RUN, SessionPaths.label(SessionService.MODE_RUN, program)) + val session = SessionState.sessionId ?: return null + SessionState.stopRequested = false + SessionEvents.transition(SessionPhase.STARTING_COMPOSITOR, "compositor.starting") + var requested = false + try { + val output = CompositorHost.prepare(context) + val size = WIDTH to HEIGHT + SessionState.outputSize = size + SessionState.refreshHz = REFRESH_HZ + CompositorHost.logToSession(context) + CompositorHost.applyHdr(context, SessionPrefs.prefMode(SessionService.MODE_RUN)) + val offscreen = ImageReader.newInstance(WIDTH, HEIGHT, PixelFormat.RGBA_8888, 2) + reader = offscreen + offscreen.setOnImageAvailableListener({ it.acquireLatestImage()?.close() }, main) + CompositorHost.start(context, output, offscreen.surface, size, REFRESH_HZ, 0) + CompositorHost.detach(offscreen.surface) + SessionEvents.record("compositor.started") + SessionEvents.transition(SessionPhase.STARTING_GUEST, "guest.starting") + requested = true + SessionService.start(context, SessionService.MODE_RUN, program, programArgs = args.toTypedArray()) + return session + } catch (e: Exception) { + if (requested) SessionService.stop(context) + if (!SessionState.running) { + reader?.close() + reader = null + SessionEvents.transition(SessionPhase.FAILED, "hidden.failed", mapOf("error" to e.toString())) + } + throw e + } + } + + private fun release() { + if (SessionState.running) return + reader?.close() + reader = null + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index 1082de60d5..afb8fcb8d4 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -180,6 +180,7 @@ 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-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", diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt index 656166a243..b8fa6c6278 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt @@ -14,7 +14,6 @@ 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 @@ -28,6 +27,7 @@ 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 @@ -62,8 +62,13 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp 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.BackgroundSession +import com.droiddeck.launcher.session.SessionService import com.droiddeck.launcher.session.SessionState import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay @@ -81,10 +86,101 @@ private class AddonResults { private enum class AddonStatus { INSTALL, UPDATE, INSTALLED } +private enum class AddonSource { WOWI, CURSE } + +private class CurseState(val notice: Int? = null) : Exception() + +private class CurseLink(val app: UserApps.App) { + class Linked(val inspector: String, val guid: String) + + private val lock = Object() + @Volatile private var closed = false + private var held = false + private var ownSession: String? = null + private var started = false + @Volatile private var launching = false + @Volatile private var inspector: String? = null + private val guids = HashMap() + + fun call(context: Context, target: WowAddons.Target, block: (Linked) -> T): T { + val linked = synchronized(lock) { link(context, target) } + try { + return block(linked) + } catch (e: CurseForgeApp.Failure) { + if (e.gone) synchronized(lock) { + if (inspector == linked.inspector) { + inspector = null + guids.clear() + } + } + throw e + } + } + + private fun link(context: Context, target: WowAddons.Target): Linked { + if (closed) throw CurseState() + if (!SessionState.running) { + started = false + launching = false + held = false + ownSession = null + inspector = null + guids.clear() + val args = CurseForgeApp.holdArgs(app) ?: throw CurseState() + ownSession = BackgroundSession.start(context, CurseForgeApp.HELPER, args) ?: throw CurseState() + } + if (closed) throw CurseState() + if (!held) { + held = true + SessionService.holdForSignIn(context, true) + } + val awake = System.currentTimeMillis() + 30_000 + while ((SessionState.suspended || SessionState.suspending) && System.currentTimeMillis() < awake) Thread.sleep(250) + val url = inspector ?: run { + launching = true + val done = CurseForgeApp.start(context, app) + when (done.state) { + CurseForgeApp.Start.READY -> { + started = true + inspector = done.inspector + 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 close(context: Context) { + closed = true + Thread { + if (launching) CurseForgeApp.stop(context, app, inspector) + synchronized(lock) { + if (started) CurseForgeApp.stop(context, app, inspector) + val owned = ownSession + if (owned != null) BackgroundSession.stop(context, owned) + else if (held) SessionService.holdForSignIn(context, false) + started = false + launching = false + ownSession = null + held = false + inspector = null + } + }.start() + } +} + private const val PAGES_AHEAD = 8 @Composable -internal fun AddonBrowserDialog(targets: List, initial: WowAddons.Target, onDismiss: () -> Unit) { +internal fun AddonBrowserDialog(targets: List, initial: WowAddons.Target, curseForge: UserApps.App?, onDismiss: () -> Unit) { val context = LocalContext.current.applicationContext val scope = rememberCoroutineScope() val shown = rememberShown(onDismiss) @@ -93,15 +189,30 @@ internal fun AddonBrowserDialog(targets: List, initial: WowAdd var text by remember { mutableStateOf("") } var category by remember { mutableStateOf(null) } var sort by remember { mutableStateOf(WowAddonCatalog.Sort.POPULAR) } - val results = remember(text, category, sort, target) { AddonResults() } + var source by remember { mutableStateOf(AddonSource.WOWI) } + val curse = if (source == AddonSource.CURSE) curseForge else null + val link = remember(curseForge?.key) { curseForge?.let(::CurseLink) } + DisposableEffect(link) { + onDispose { link?.close(context) } + } + var notice by remember { mutableStateOf(null) } + var curseInstalls by remember { mutableIntStateOf(0) } + val results = remember(text, category, sort, target, curse) { AddonResults() } val installing = remember { mutableStateMapOf() } val installed = remember { mutableStateMapOf>() } val categories by produceState(emptyList()) { value = withContext(Dispatchers.IO) { runCatching { WowAddonCatalog.categories(context) }.getOrDefault(emptyList()) } } - val present by produceState(emptyMap(), target.addOns, WowAddons.imports) { - value = withContext(Dispatchers.IO) { WowAddons.details(target).mapNotNull { item -> item.wowiId?.let { it to item.version } }.toMap() } + val presentKey = curse to target.addOns + val snapshot by produceState(presentKey to emptyMap(), target.addOns, WowAddons.imports, curse, curseInstalls, results.items.isEmpty()) { + val into = target + val key = curse to into.addOns + value = key to withContext(Dispatchers.IO) { + if (curse != null && link != null) runCatching { link.call(context, into) { CurseForgeApp.installed(context, it.inspector, it.guid) }.associateWith { null } }.getOrDefault(emptyMap()) + else WowAddons.details(into).mapNotNull { item -> item.wowiId?.let { it to item.version } }.toMap() + } } + val present = snapshot.second.takeIf { snapshot.first == presentKey } ?: emptyMap() fun status(addon: WowAddonCatalog.Addon): AddonStatus { if (addon.id !in present) return AddonStatus.INSTALL val have = present[addon.id] @@ -116,10 +227,16 @@ internal fun AddonBrowserDialog(targets: List, 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 { WowAddonCatalog.search(context, WowAddonCatalog.Query(words, cat, WowAddonCatalog.client(into), order), page) } + 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) + } } + 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 } }) @@ -136,6 +253,27 @@ internal fun AddonBrowserDialog(targets: List, 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 + installing[key] = 0 + scope.launch { + val done = withContext(Dispatchers.IO) { runCatching { via.call(context, into) { CurseForgeApp.install(context, it.inspector, it.guid, addon.id) } } } + installing.remove(key) + val ok = done.getOrNull() == true + if (ok) { + WowAddons.changed() + curseInstalls++ + } + val message = when { + 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 @@ -149,7 +287,7 @@ internal fun AddonBrowserDialog(targets: List, initial: WowAdd Toast.makeText(context, message.first, Toast.LENGTH_LONG).show() } } - val sourceName = stringResource(R.string.addons_source_wowi) + val sourceName = stringResource(if (curse != null) R.string.addons_source_curse else R.string.addons_source_wowi) val grid = rememberLazyGridState() LaunchedEffect(results, grid) { snapshotFlow { grid.layoutInfo.visibleItemsInfo.lastOrNull()?.index to grid.layoutInfo.totalItemsCount }.collect { (last, total) -> @@ -170,8 +308,14 @@ internal fun AddonBrowserDialog(targets: List, 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 (categories.isNotEmpty()) BrowseDropdown(category?.name ?: stringResource(R.string.addons_category_all)) { first, done -> + if (curse == null && 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() } } } @@ -195,6 +339,7 @@ internal fun AddonBrowserDialog(targets: List, 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() @@ -208,6 +353,7 @@ internal fun AddonBrowserDialog(targets: List, initial: WowAdd verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.horizontalScroll(rememberScrollState()), ) { + sourceChip() sortChip() categoryChip() flavorChip() @@ -228,6 +374,10 @@ internal fun AddonBrowserDialog(targets: List, initial: WowAdd 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) } @@ -259,7 +409,7 @@ private fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progress fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, ) } - val size = Modifier.widthIn(min = 104.dp).then(action) + val size = action when { 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) {} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt index 25dba6fe37..447d3ef73f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt @@ -1049,7 +1049,7 @@ private fun SavesTab(g: Library.SteamGame, prefix: File, a: FrontEndActions) { @Composable private fun AddonsTab(g: Library.SteamGame, targets: List, a: FrontEndActions) { var browsing by remember(g.gameId) { mutableStateOf(null) } - browsing?.let { AddonBrowserDialog(targets, it) { browsing = null } } + browsing?.let { AddonBrowserDialog(targets, it, CurseForgeApp.find(UserAppsState.items)) { browsing = null } } Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) { CurseForgeEntry(a) targets.forEach { target -> diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt index 8d43d09c7b..89ae2b1cb3 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt @@ -10,6 +10,8 @@ import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.SessionState object CompositorHost { + private const val TAG = "DroidDeck" + @Volatile private var started = false @@ -55,6 +57,52 @@ object CompositorHost { } } + class Output internal constructor( + internal val runtimeDir: java.io.File, + internal val turnip: com.droiddeck.launcher.gpu.TurnipDriver, + internal val driverId: String?, + ) + + fun prepare(context: android.content.Context): Output { + val runtimeDir = java.io.File(context.filesDir, ".wayland-rt").apply { mkdirs() } + com.droiddeck.launcher.core.FileUtils.copyAsset(context, "wayland/keymap.xkb", java.io.File(runtimeDir, "keymap.xkb")) + com.droiddeck.launcher.input.VrControllers.publish(context) + val turnip = com.droiddeck.launcher.gpu.TurnipDriver(context) + com.droiddeck.launcher.gpu.DriverSetupLog.write(context, "surface.driver-setup") + if (!started) { + displayChoice = SessionPrefs.androidDriver(context) + com.droiddeck.launcher.gpu.AutoDriverTrial.displayStarting(context, SessionPrefs.androidDriver(context)) + } + return Output(runtimeDir, turnip, if (started) null else turnip.install()) + } + + fun logToSession(context: android.content.Context) { + val waylandLog = java.io.File(com.droiddeck.launcher.session.SessionPaths.beginOrCurrent(context), "wayland.log") + WaylandCompositor.setSessionLogFile(waylandLog) + try { + android.system.Os.setenv("DD_WAYLAND_LOG", waylandLog.path, true) + } catch (e: Exception) { + android.util.Log.w(TAG, "could not point the compositor's log at $waylandLog", e) + } + } + + fun applyHdr(context: android.content.Context, mode: String) { + val on = SessionState.hdrCapable && SessionPrefs.hdr(context, mode) + SessionState.hdr = on + WaylandCompositor.nativeSetHdrOutput(on) + WaylandCompositor.nativeSetZeroCopy(on || SessionPrefs.zeroCopy(context, mode)) + android.util.Log.i(TAG, "hdr: " + (if (on) "on" else "off") + " for this $mode session") + } + + fun start(context: android.content.Context, output: Output, surface: Surface, size: Pair, refreshHz: Float, fpsLimit: Int): Boolean { + com.droiddeck.launcher.gpu.DriverSetupLog.write(context, "compositor.start driver=${output.driverId}") + return startOrAttach( + context, surface, output.runtimeDir.path, + output.driverId?.let { output.turnip.driverPath(it) }, output.driverId?.let { output.turnip.libraryName(it) }, + context.applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz, fpsLimit, + ) + } + @Synchronized fun startOrAttach( context: android.content.Context, diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index b6b06e6f1c..f8217b0fd5 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -4177,6 +4177,7 @@ الأكثر تنزيلًا كل الفئات لم يتم العثور على إضافات + أغلق CurseForge أولاً تعذّر الوصول إلى %1$s لا يوجد ملف لإصدار اللعبة هذا إعادة تعيين المواضع diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 7105d0010e..8b0e2378e3 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -4057,6 +4057,7 @@ Más descargados Todas las categorías No se encontraron complementos + Cierra CurseForge primero No se pudo conectar con %1$s No hay archivo para esta versión del juego Restablecer posiciones diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index e899caa026..8531a5dab1 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -4017,6 +4017,7 @@ Най-изтегляни Всички категории Няма намерени добавки + Първо затворете CurseForge Няма връзка с %1$s Няма файл за тази версия на играта Нулиране на позициите diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 1878c9e970..e8d2dc5c94 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -4097,6 +4097,7 @@ Nejstahovanější Všechny kategorie Nenalezeny žádné doplňky + Nejprve zavřete CurseForge Nelze se připojit k %1$s Pro tuto verzi hry není k dispozici soubor Obnovit pozice diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 0de6201954..043a52c4b8 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -4017,6 +4017,7 @@ Mest downloadet Alle kategorier Ingen tilføjelser fundet + Luk CurseForge først Kunne ikke nå %1$s Ingen fil til denne spilversion Nulstil placeringer diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 28df13a1fc..4d52b46b32 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -4017,6 +4017,7 @@ Meistgeladen Alle Kategorien Keine Addons gefunden + Schließe zuerst CurseForge %1$s ist nicht erreichbar Keine Datei für diese Spielversion Positionen zurücksetzen diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 8596d16797..826d8680e6 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -4017,6 +4017,7 @@ Περισσότερες λήψεις Όλες οι κατηγορίες Δεν βρέθηκαν πρόσθετα + Κλείστε πρώτα το CurseForge Δεν ήταν δυνατή η σύνδεση με %1$s Δεν υπάρχει αρχείο για αυτή την έκδοση του παιχνιδιού Επαναφορά θέσεων diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 40a6f4076d..3dcc0a4d1e 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -4057,6 +4057,7 @@ Más descargados Todas las categorías No se han encontrado complementos + Cierra CurseForge primero No se pudo conectar con %1$s No hay ningún archivo para esta versión del juego Restablecer posiciones diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 7ac8d04517..ebe843786e 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -4017,6 +4017,7 @@ Ladatuimmat Kaikki luokat Lisäosia ei löytynyt + Sulje CurseForge ensin Yhteyttä palveluun %1$s ei saatu Tälle peliversiolle ei ole tiedostoa Palauta sijainnit diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 8a6f3d0078..bd5525aa28 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -4056,6 +4056,7 @@ Les plus téléchargés Toutes les catégories Aucun addon trouvé + Fermez d\'abord CurseForge Impossible de joindre %1$s Aucun fichier pour cette version du jeu Réinitialiser les positions diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index b71ab1c9fd..7cd6bf3050 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -4017,6 +4017,7 @@ सबसे ज़्यादा डाउनलोड सभी श्रेणियाँ कोई ऐडऑन नहीं मिला + पहले CurseForge बंद करें %1$s तक नहीं पहुँच सके गेम के इस संस्करण के लिए कोई फ़ाइल नहीं है स्थितियाँ रीसेट करें diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 500ab21232..d4c46656d6 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -4017,6 +4017,7 @@ Legtöbbet letöltött Minden kategória Nem található kiegészítő + Előbb zárd be a CurseForge-ot A(z) %1$s nem érhető el Nincs fájl ehhez a játékverzióhoz Pozíciók visszaállítása diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 9db5098f65..53c9708ecc 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -3987,6 +3987,7 @@ Paling banyak diunduh Semua kategori Tidak ada addon ditemukan + Tutup CurseForge terlebih dahulu Tidak dapat menjangkau %1$s Tidak ada file untuk versi game ini Atur ulang posisi diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 906391587b..78a9ae250a 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -4056,6 +4056,7 @@ Più scaricati Tutte le categorie Nessun addon trovato + Chiudi prima CurseForge Impossibile raggiungere %1$s Nessun file per questa versione del gioco Ripristina posizioni diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index edd13096f5..a7f1d18d19 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -3987,6 +3987,7 @@ ダウンロード数順 すべてのカテゴリ アドオンが見つかりません + 先に CurseForge を閉じてください %1$s に接続できませんでした このゲームバージョン用のファイルがありません 位置をリセット diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index ce2a976f06..f97db37e65 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -3987,6 +3987,7 @@ 다운로드 많은 순 모든 카테고리 애드온을 찾을 수 없음 + 먼저 CurseForge를 닫으세요 %1$s에 연결할 수 없습니다 이 게임 버전용 파일이 없습니다 위치 초기화 diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index de79562b86..9d2d102625 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -3987,6 +3987,7 @@ Paling banyak dimuat turun Semua kategori Tiada addon ditemui + Tutup CurseForge dahulu Tidak dapat mencapai %1$s Tiada fail untuk versi permainan ini Tetapkan semula kedudukan diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index 59188336c8..a09d35a922 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -4017,6 +4017,7 @@ Mest nedlastet Alle kategorier Fant ingen tillegg + Lukk CurseForge først Fikk ikke kontakt med %1$s Ingen fil for denne spillversjonen Tilbakestill plasseringer diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 11232dcc4a..023fe7bb97 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -4017,6 +4017,7 @@ Meest gedownload Alle categorieën Geen add-ons gevonden + Sluit eerst CurseForge Kan %1$s niet bereiken Geen bestand voor deze gameversie Posities herstellen diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index bfa42a349b..3ff4e06620 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -4097,6 +4097,7 @@ Najczęściej pobierane Wszystkie kategorie Nie znaleziono dodatków + Najpierw zamknij CurseForge Nie można połączyć się z %1$s Brak pliku dla tej wersji gry Resetuj położenie diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index a1d7069d48..15c7cb206c 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -4070,6 +4070,7 @@ Mais transferidos Todas as categorias Nenhum addon encontrado + Feche primeiro o CurseForge Não foi possível contactar %1$s Não há ficheiro para esta versão do jogo Repor posições diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 1e40678db5..1e291f316b 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -4078,6 +4078,7 @@ Mais baixados Todas as categorias Nenhum addon encontrado + Feche o CurseForge primeiro Não foi possível acessar %1$s Não há arquivo para esta versão do jogo Redefinir posições diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index 8b626e5149..f5868d56e5 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -4057,6 +4057,7 @@ Cele mai descărcate Toate categoriile Nu s-au găsit suplimente + Închide mai întâi CurseForge Nu s-a putut accesa %1$s Nu există fișier pentru această versiune a jocului Resetează pozițiile diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 81e2120b02..da7e65b3f6 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -4097,6 +4097,7 @@ Самые скачиваемые Все категории Аддоны не найдены + Сначала закройте CurseForge Не удалось подключиться к %1$s Нет файла для этой версии игры Сбросить положение diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 98df4caab6..58be1afa71 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -4017,6 +4017,7 @@ Mest nedladdade Alla kategorier Inga tillägg hittades + Stäng CurseForge först Kunde inte nå %1$s Ingen fil för den här spelversionen Återställ positioner diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index d9e1de3e60..d8ec6f41e1 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -3987,6 +3987,7 @@ ดาวน์โหลดมากที่สุด ทุกหมวดหมู่ ไม่พบแอดออน + ปิด CurseForge ก่อน ไม่สามารถเชื่อมต่อ %1$s ได้ ไม่มีไฟล์สำหรับเกมเวอร์ชันนี้ รีเซ็ตตำแหน่ง diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index b5e3ec8893..6bec3f37b5 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -4017,6 +4017,7 @@ En çok indirilen Tüm kategoriler Eklenti bulunamadı + Önce CurseForge\'u kapatın %1$s adresine ulaşılamadı Bu oyun sürümü için dosya yok Konumları sıfırla diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index c6d9b97b8e..472a1d8050 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -4097,6 +4097,7 @@ Найбільше завантажень Усі категорії Аддонів не знайдено + Спочатку закрийте CurseForge Не вдалося під’єднатися до %1$s Немає файлу для цієї версії гри Скинути розташування diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index ac4f7e24fc..fbf6432863 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -3987,6 +3987,7 @@ Tải nhiều nhất Tất cả danh mục Không tìm thấy addon + Hãy đóng CurseForge trước Không thể kết nối tới %1$s Không có tệp cho phiên bản trò chơi này Đặt lại vị trí diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index d7be53560a..4446a1fb81 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -3987,6 +3987,7 @@ 下载最多 所有类别 未找到插件 + 请先关闭 CurseForge 无法连接到 %1$s 没有适用于此游戏版本的文件 重置位置 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 8bee7a52bd..daa483e57d 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -3987,6 +3987,7 @@ 下載最多 所有類別 找不到插件 + 請先關閉 CurseForge 無法連接 %1$s 沒有適用於此遊戲版本的檔案 重設位置 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 9aff9a0931..18805781c2 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -3987,6 +3987,7 @@ 下載最多 所有類別 找不到插件 + 請先關閉 CurseForge 無法連線至 %1$s 沒有適用於此遊戲版本的檔案 重設位置 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index f4357d67bd..ad2bdfe362 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -4202,6 +4202,7 @@ Most downloaded All categories No addons found + Close CurseForge first Could not reach %1$s No file for this game version WoWInterface diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt new file mode 100644 index 0000000000..98cdd9376f --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt @@ -0,0 +1,161 @@ +package com.droiddeck.launcher.runtime + +import android.app.Application +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.File + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33], manifest = Config.NONE, application = Application::class) +class CurseForgeAppTest { + @get:Rule val temp = TemporaryFolder() + + private val search = """{"success":true,"injectedCount":0, + "pagination":{"index":0,"pageSize":20,"resultCount":20,"totalCount":150}, + "mods":[ + {"id":486246,"name":"RestedXP Guide","summary":"Leveling guide","downloads":12345678, + "thumbnailUrl":"https://media.forgecdn.net/avatars/rxp.png","authors":[{"name":"RestedXP"}], + "updateVersion":{"id":7,"filename":"RXPGuides.zip","fileDate":"2026-11-20T10:00:00.000Z"}}, + {"id":2,"name":"Plain","downloads":5,"thumbnailUrl":"http://insecure/x.png","primaryAuthor":{"name":"Main"}, + "authors":[{"name":"Other"}],"projectLatestReleaseDate":"2026-01-01T00:00:00Z"}, + {"id":0,"name":"No id"}, + {"id":3,"name":""} + ]}""" + + @Test + fun searchResultsBecomeCatalogEntries() { + val page = CurseForgeApp.parseSearch(JSONObject(search)) + assertEquals(listOf("486246", "2"), page.items.map { it.id }) + val rxp = page.items[0] + assertEquals("RestedXP Guide", rxp.name) + assertEquals("RestedXP", rxp.author) + assertEquals(12345678L, rxp.downloads) + assertEquals(java.time.Instant.parse("2026-11-20T10:00:00Z").toEpochMilli(), rxp.updated) + assertEquals("https://media.forgecdn.net/avatars/rxp.png", rxp.thumb) + assertEquals("Main", page.items[1].author) + assertNull(page.items[1].thumb) + assertTrue(page.more) + } + + @Test + fun theLastPageHasNoMore() { + val last = JSONObject(search).put("pagination", JSONObject("""{"index":140,"resultCount":10,"totalCount":150}""")) + assertFalse(CurseForgeApp.parseSearch(last).more) + assertThrows(CurseForgeApp.Failure::class.java) { CurseForgeApp.parseSearch(JSONObject("""{"success":false}""")) } + assertThrows(CurseForgeApp.Failure::class.java) { CurseForgeApp.parseSearch(null) } + } + + @Test + fun searchRequestsUseTheInstanceAndOneBasedPages() { + val request = CurseForgeApp.searchRequest("guid-1", " Rested ", WowAddonCatalog.Sort.NAME, 0) + assertEquals(1, request.getInt("gameId")) + assertEquals("Rested", request.getString("searchText")) + assertEquals(1, request.getInt("page")) + assertEquals(1, request.getInt("sortColumn")) + assertEquals(1, request.getInt("sortOrder")) + assertEquals("guid-1", request.getString("gameInstanceGuid")) + assertEquals(2, CurseForgeApp.searchRequest("g", "", WowAddonCatalog.Sort.DOWNLOADS, 1).getInt("page")) + assertEquals(WowAddonCatalog.Sort.entries.size, WowAddonCatalog.Sort.entries.map(CurseForgeApp::sortOf).toSet().size) + } + + @Test + fun installRequestsInstallTheLatestFileIntoTheInstance() { + val request = CurseForgeApp.installRequest("guid-1", "486246") + assertEquals("guid-1", request.getString("instanceId")) + assertEquals(486246L, request.getLong("projectId")) + assertTrue(request.getBoolean("installLatestFile")) + } + + @Test + fun theInstanceIsPickedByItsFlavorFolder() { + val instances = JSONArray("""[ + {"guid":"retail","installPath":"/root/Games/WoW/_retail_/"}, + {"guid":"forever","installPath":"/root/Games/WoW/_forever_/"} + ]""") + assertEquals("forever", CurseForgeApp.instanceFor(instances, "/root/Games/WoW/_forever_", "retail")) + assertEquals("retail", CurseForgeApp.instanceFor(instances, "/root/Games/WoW/_retail_", null)) + assertNull(CurseForgeApp.instanceFor(instances, "/root/Games/WoW/_classic_", "retail")) + val single = JSONArray("""[{"guid":"retail","installPath":"/root/Games/WoW/_retail_/"}]""") + assertNull(CurseForgeApp.instanceFor(single, "/root/Games/WoW/_classic_", "retail")) + assertEquals("retail", CurseForgeApp.instanceFor(single, "/root/Games/WoW/_retail_", "other")) + assertEquals("only", CurseForgeApp.instanceFor(JSONArray(), "/x/_forever_", "only")) + assertEquals("only", CurseForgeApp.instanceFor(null, "/x/_forever_", "only")) + assertNull(CurseForgeApp.instanceFor(JSONArray(), "/x/_forever_", "")) + } + + @Test + fun answersAreUnwrapped() { + val ok = JSONObject().put("ok", true).put("value", """{"value":{"resultStatus":3,"gameInstanceGuid":"g"}}""") + assertEquals("g", (CurseForgeApp.unwrap(ok) as JSONObject).getString("gameInstanceGuid")) + assertEquals(true, CurseForgeApp.unwrap(JSONObject().put("ok", true).put("value", """{"value":true}"""))) + val missing = JSONObject().put("ok", true).put("value", """{"missing":true}""") + assertThrows(CurseForgeApp.Failure::class.java) { CurseForgeApp.unwrap(missing) } + val failed = JSONObject().put("ok", false).put("error", JSONObject().put("code", "NO_TARGET").put("message", "no node")) + val failure = assertThrows(CurseForgeApp.Failure::class.java) { CurseForgeApp.unwrap(failed) } + assertEquals("no node", failure.message) + assertEquals("NO_TARGET", failure.code) + assertFalse(failure.gone) + val lost = JSONObject().put("ok", false).put("error", JSONObject().put("code", "DEVTOOLS_UNREACHABLE").put("message", "refused")) + assertTrue(assertThrows(CurseForgeApp.Failure::class.java) { CurseForgeApp.unwrap(lost) }.gone) + } + + @Test + fun expressionsDriveTheHiddenDesktopWindow() { + val text = CurseForgeApp.expression("ProjectAppService", "search", JSONArray().put(JSONObject().put("searchText", "it's \"x\""))) + assertTrue(text.startsWith("(() => { const w = require('electron').BrowserWindow.getAllWindows()")) + assertTrue(text.contains("desktop.html")) + assertTrue(text.contains("executeJavaScript(")) + assertFalse(text.contains("show()")) + val probe = CurseForgeApp.expression("InstalledProjectsAppService", "installAddon", null) + assertFalse(probe.contains("await s[")) + val connect = CurseForgeApp.expression("CoreService", "connect", JSONArray(), "r => true") + assertTrue(connect.contains("(r => true)(await s[\\\"connect\\\"](...[]))")) + } + + @Test + fun installedIdsAndExitCodes() { + assertEquals(setOf("486246", "2"), CurseForgeApp.projectIds(JSONArray("""["486246","2",null]"""))) + assertEquals(emptySet(), CurseForgeApp.projectIds(JSONObject())) + assertEquals(CurseForgeApp.Start.READY, CurseForgeApp.startState(0)) + assertEquals(CurseForgeApp.Start.BUSY, CurseForgeApp.startState(3)) + assertEquals(CurseForgeApp.Start.NO_DISPLAY, CurseForgeApp.startState(4)) + assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.startState(5)) + } + + @Test + fun onlyASecretInspectorUrlIsTaken() { + val url = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e" + assertEquals(url, CurseForgeApp.inspectorUrl("noise\n$url\n")) + assertNull(CurseForgeApp.inspectorUrl("ready\n")) + assertNull(CurseForgeApp.inspectorUrl("ws://127.0.0.1:9229/\n")) + assertNull(CurseForgeApp.inspectorUrl("ws://10.0.0.2:43117/0f8fad5b-d9cb-469f-a165-70867728950e")) + assertNull(CurseForgeApp.inspectorUrl("$url/json")) + } + + @Test + fun theWowRootIsTheParentOfEveryFlavor() { + val root = temp.newFolder("World of Warcraft") + for (flavor in listOf("_classic_", "_classic_era_")) { + File(root, "$flavor/Interface/AddOns").mkdirs() + File(root, "$flavor/.flavor.info").writeText("x") + } + val title = BattleNet.TITLES.first { it.flavor == "_classic_" } + val targets = WowAddons.targets(title, File(root, "_classic_")) + assertEquals(listOf("_classic_", "_classic_era_"), targets.map { it.flavor }.sorted()) + for (target in targets) { + assertEquals(root, WowAddons.root(target)) + assertEquals(File(root, target.flavor), WowAddons.flavorDir(target)) + } + } +} diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent b/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent index 114e608e33..4edfc22cb0 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent @@ -432,7 +432,7 @@ class FocusWatcher(threading.Thread): class WebSocket: - def __init__(self, url, timeout): + def __init__(self, url, timeout, bounded=False): target = urllib.parse.urlsplit(url) if (target.scheme != "ws" or target.hostname not in ("127.0.0.1", "::1", "localhost") or target.username is not None or target.password is not None or target.fragment): @@ -442,6 +442,7 @@ class WebSocket: if target.query: path += "?" + target.query host = "127.0.0.1" if target.hostname == "localhost" else target.hostname + self.deadline = time.monotonic() + timeout if bounded else None self.s = socket.create_connection((host, target.port or 80), timeout=timeout) try: self._handshake(path, hostport) @@ -457,6 +458,7 @@ class WebSocket: ).encode()) head = b"" while b"\r\n\r\n" not in head: + self._wait() chunk = self.s.recv(4096) if not chunk: raise OSError("DevTools closed the connection during the handshake") @@ -468,8 +470,17 @@ class WebSocket: raise OSError("DevTools refused the WebSocket: " + status.decode(errors="replace")) self.buffer = head.split(b"\r\n\r\n", 1)[1] + def _wait(self): + if self.deadline is None: + return + left = self.deadline - time.monotonic() + if left <= 0: + raise socket.timeout("DevTools did not answer in time") + self.s.settimeout(left) + def _read(self, n): while len(self.buffer) < n: + self._wait() chunk = self.s.recv(65536) if not chunk: raise OSError("DevTools closed the connection") @@ -547,22 +558,51 @@ def cdp_targets(agent_dir, timeout=5): raise AgentError("DEVTOOLS_UNREACHABLE", "Could not reach the client's DevTools at %s: %s" % (url, e)) -def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15): - targets = [t for t in cdp_targets(agent_dir) if t.get("webSocketDebuggerUrl")] - want = target or "SharedJSContext" - match = [t for t in targets if want in (t.get("title") or "") or want in (t.get("url") or "")] - if not match: - names = ", ".join(sorted({t.get("title") or t.get("url") or "?" for t in targets})) - raise AgentError("NO_TARGET", "No DevTools target matches '%s' (have: %s)" % (want, names)) - ws = WebSocket(match[0]["webSocketDebuggerUrl"], timeout) +INSPECTOR_URL = re.compile(r"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}") + + +def inspector_url(url): + found = INSPECTOR_URL.fullmatch(url) if isinstance(url, str) else None + if not found or not 1024 <= int(found.group(1)) <= 65535: + raise AgentError("INVALID_REQUEST", "inspector must be a ws://127.0.0.1 inspector URL with its session id") + return url + + +def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15, inspector=None, + command_line_api=False): + if inspector is not None: + url, name = inspector_url(inspector), "inspector" + else: + targets = [t for t in cdp_targets(agent_dir) if t.get("webSocketDebuggerUrl")] + want = target or "SharedJSContext" + match = [t for t in targets if want in (t.get("title") or "") or want in (t.get("url") or "")] + if not match: + names = ", ".join(sorted({t.get("title") or t.get("url") or "?" for t in targets})) + raise AgentError("NO_TARGET", "No DevTools target matches '%s' (have: %s)" % (want, names)) + url, name = match[0]["webSocketDebuggerUrl"], match[0].get("title") try: - ws.send(json.dumps({"id": 1, "method": "Runtime.evaluate", "params": { - "expression": expression, "returnByValue": True, "awaitPromise": await_promise, - "userGesture": True, - }})) - deadline = time.monotonic() + timeout - while time.monotonic() < deadline: - message = json.loads(ws.recv()) + ws = WebSocket(url, timeout, bounded=True) + except socket.timeout: + raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout) + except OSError as e: + raise AgentError("DEVTOOLS_UNREACHABLE", "Could not reach DevTools: %s" % e) + try: + try: + ws.send(json.dumps({"id": 1, "method": "Runtime.evaluate", "params": { + "expression": expression, "returnByValue": True, "awaitPromise": await_promise, + "userGesture": True, "includeCommandLineAPI": command_line_api, + }})) + except socket.timeout: + raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout) + except OSError as e: + raise AgentError("DEVTOOLS_UNREACHABLE", "DevTools went away: %s" % e) + while True: + try: + message = json.loads(ws.recv()) + except socket.timeout: + raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout) + except OSError as e: + raise AgentError("DEVTOOLS_UNREACHABLE", "DevTools went away: %s" % e) if message.get("id") != 1: continue if "error" in message: @@ -573,9 +613,8 @@ def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15) text = (details.get("exception") or {}).get("description") or details.get("text") or "exception" raise AgentError("JS_EXCEPTION", text) value = result.get("result", {}) - return {"target": match[0].get("title"), "type": value.get("type"), + return {"target": name, "type": value.get("type"), "value": value.get("value"), "description": value.get("description")} - raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout) finally: ws.close() @@ -1157,7 +1196,7 @@ def handle(agent_dir, req): if not isinstance(expression, str) or not expression: raise AgentError("INVALID_REQUEST", "cdp eval needs an expression") return cdp_eval(agent_dir, expression, req.get("target"), bool(req.get("awaitPromise", True)), - request_timeout(req, 15)) + request_timeout(req, 15), req.get("inspector"), req.get("commandLineApi") is True) if kind == "steam-selection": return steam_selection(agent_dir, request_timeout(req, 5)) if kind == "quit": diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-curseforge b/tools/linuxfs/overlay/usr/local/bin/droiddeck-curseforge new file mode 100755 index 0000000000..a329c15862 --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-curseforge @@ -0,0 +1,150 @@ +#!/bin/bash +set -u +umask 077 +self=${BASH_SOURCE[0]} +proc=${DD_PROC:-/proc} +state=${DD_CURSEFORGE_STATE:-${XDG_RUNTIME_DIR:-/tmp}/droiddeck-curseforge} +runner=${DD_APPIMAGE_RUN:-${self%/*}/droiddeck-appimage-run} +wait_s=${DD_CURSEFORGE_WAIT:-60} +cmd=${1:-} +dir=${2:-} +flag=--inspect-publish-uid=stderr +case $cmd in start|hold|stop|display) ;; *) echo "usage: droiddeck-curseforge start|hold|stop|display " >&2; exit 2 ;; esac +if [ "$cmd" != display ] && [ ! -d "$dir/app" ]; then + echo "droiddeck-curseforge: $dir is not an imported AppImage" >&2 + exit 2 +fi + +x_display() { + if [ -n "${DISPLAY:-}" ]; then + printf '%s\n%s\n' "$DISPLAY" "${XAUTHORITY:-}" + return 0 + fi + local p name a prev display auth + for p in "$proc"/[0-9]*; do + name=$(tr '\0' '\n' 2>/dev/null < "$p/cmdline" | head -n 1) + case ${name##*/} in Xwayland|Xorg|Xvfb) ;; *) continue ;; esac + display= auth= prev= + while IFS= read -r a; do + case $a in :[0-9]*) [ -z "$display" ] && display=$a ;; esac + [ "$prev" = -auth ] && auth=$a + prev=$a + done < <(tr '\0' '\n' 2>/dev/null < "$p/cmdline") + if [ -n "$display" ]; then + printf '%s\n%s\n' "$display" "$auth" + return 0 + fi + done + return 1 +} + +running() { + local p + for p in "$proc"/[0-9]*; do + tr '\0' '\n' 2>/dev/null < "$p/cmdline" | grep -qF -- "$dir/app/" && return 0 + done + return 1 +} + +started_at() { + local stat + stat=$(cat "/proc/$1/stat" 2>/dev/null) || return 1 + stat=${stat##*) } + set -- $stat + echo "${20}" +} + +tracked() { + local pid at launched + read -r pid at launched 2>/dev/null < "$state/pid" || return 1 + case $pid in ''|*[!0-9]*) return 1 ;; esac + kill -0 "$pid" 2>/dev/null && [ "$(started_at "$pid")" = "$at" ] || return 1 + printf '%s %s\n' "$pid" "$launched" +} + +ours() { + local pid launched + read -r pid launched <<<"$(tracked)" + [ -n "$pid" ] && [ "$launched" = "$dir" ] && echo "$pid" +} + +lock() { + mkdir -p "$state" && chmod 700 "$state" || return 1 + exec 9>"$state/lock" || return 1 + flock 9 +} + +inspector() { + grep -aom1 'ws://127\.0\.0\.1:[0-9]*/[0-9a-f]\{8\}-[0-9a-f]\{4\}-[0-9a-f]\{4\}-[0-9a-f]\{4\}-[0-9a-f]\{12\}' "$state/log" 2>/dev/null +} + +start() { + local shown display auth url pid + lock || { echo "droiddeck-curseforge: cannot lock $state" >&2; return 5; } + if ! ours >/dev/null; then + if tracked >/dev/null || running; then + exec 9>&- + echo busy + return 3 + fi + shown=$(x_display) || { exec 9>&-; echo "no X display" >&2; return 4; } + display=$(sed -n 1p <<<"$shown") + auth=$(sed -n 2p <<<"$shown") + env -u DBUS_SESSION_BUS_ADDRESS -u WAYLAND_DISPLAY -u GAMESCOPE_WAYLAND_DISPLAY DISPLAY="$display" ${auth:+XAUTHORITY="$auth"} \ + setsid "$runner" "$dir" --minimized --inspect=127.0.0.1:0 "$flag" "$state/log" 2>&1 9>&- & + pid=$! + printf '%s %s %s\n' "$pid" "$(started_at "$pid")" "$dir" > "$state/pid" + fi + exec 9>&- + for _ in $(seq 1 $((wait_s * 2))); do + if url=$(inspector); then + echo "$url" + return 0 + fi + ours >/dev/null || break + sleep 0.5 + done + tail -n 20 "$state/log" >&2 + return 5 +} + +stop() { + local pid p + lock || return 1 + pid=$(ours) || { tracked >/dev/null || rm -f "$state/pid"; exec 9>&-; return 0; } + kill -TERM -- "-$pid" 2>/dev/null + for _ in $(seq 1 20); do + kill -0 -- "-$pid" 2>/dev/null || break + sleep 0.5 + done + kill -KILL -- "-$pid" 2>/dev/null + for p in "$proc"/[0-9]*; do + tr '\0' '\n' 2>/dev/null < "$p/cmdline" | grep -qF -- "$dir/app/" && kill -KILL "${p##*/}" 2>/dev/null + done + rm -f "$state/pid" + exec 9>&- + return 0 +} + +case $cmd in + display) + x_display || exit 4 + ;; + start) + start + exit $? + ;; + hold) + start >/dev/null || exit $? + trap 'stop; exit 0' TERM INT HUP + while ours >/dev/null; do + sleep 1 & + wait $! + done + exit 0 + ;; + stop) + stop + exit 0 + ;; +esac diff --git a/tools/tests/test_curseforge_helper.py b/tools/tests/test_curseforge_helper.py new file mode 100644 index 0000000000..4dd25790db --- /dev/null +++ b/tools/tests/test_curseforge_helper.py @@ -0,0 +1,173 @@ +import os +import shlex +import shutil +import signal +import subprocess +import tempfile +import time +import unittest +from pathlib import Path + +HELPER = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-curseforge" +URL = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e" + + +class CurseForgeHelperTest(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.tmp, True) + self.proc = self.tmp / "proc" + self.proc.mkdir() + self.dir = self.tmp / "curseforge" + (self.dir / "app").mkdir(parents=True) + self.state = self.tmp / "state" + self.runner = self.tmp / "runner" + self.seen = self.tmp / "seen" + self.runner.write_text( + "#!/bin/bash\n" + "printf '%%s\\n' \"DISPLAY=$DISPLAY\" \"XAUTHORITY=${XAUTHORITY-}\" \"WAYLAND=${WAYLAND_DISPLAY-}\" " + "\"DBUS=${DBUS_SESSION_BUS_ADDRESS-}\" \"$@\" > %s\n" + "mkdir -p %s/$$ && printf '%%s\\0' bash \"$0\" \"$@\" > %s/$$/cmdline\n" + "echo 'Debugger listening on %s'\n" + "echo 'For help, see: https://nodejs.org/en/docs/inspector'\n" + "exec sleep 60\n" + % (shlex.quote(str(self.seen)), shlex.quote(str(self.proc)), shlex.quote(str(self.proc)), URL)) + self.runner.chmod(0o755) + + def fake(self, pid, *argv): + d = self.proc / str(pid) + d.mkdir() + (d / "cmdline").write_bytes(b"".join(a.encode() + b"\0" for a in argv)) + + def env(self, extra=None): + base = {k: v for k, v in os.environ.items() if k not in ("DISPLAY", "XAUTHORITY")} + base.update(DD_PROC=str(self.proc), DD_CURSEFORGE_STATE=str(self.state), DD_APPIMAGE_RUN=str(self.runner), + DD_CURSEFORGE_WAIT="10", WAYLAND_DISPLAY="wayland-0", DBUS_SESSION_BUS_ADDRESS="unix:path=/x") + base.update(extra or {}) + return base + + def run_helper(self, *args, env=None): + return subprocess.run(["bash", str(HELPER), *args], env=self.env(env), capture_output=True, text=True, timeout=60) + + def stop(self): + self.run_helper("stop", str(self.dir)) + + def pid(self): + return int((self.state / "pid").read_text().split()[0]) + + def gone(self, pid): + for _ in range(50): + try: + os.kill(pid, 0) + except ProcessLookupError: + return True + time.sleep(0.1) + return False + + def test_the_desktop_x_display_is_found_from_xwayland(self): + self.fake(40, "/usr/bin/kwin_wayland", ":9") + self.fake(41, "/usr/bin/Xwayland", ":0", "-rootless", "-auth", "/run/droiddeck/xauth_abc", "-listenfd", "5") + out = self.run_helper("display", "") + self.assertEqual(0, out.returncode, out.stderr) + self.assertEqual([":0", "/run/droiddeck/xauth_abc"], out.stdout.splitlines()) + + def test_the_session_display_wins(self): + self.fake(41, "/usr/bin/Xwayland", ":3") + out = self.run_helper("display", "", env={"DISPLAY": ":0"}) + self.assertEqual(":0", out.stdout.splitlines()[0]) + + def test_no_display_is_reported(self): + out = self.run_helper("start", str(self.dir)) + self.assertEqual(4, out.returncode) + + def test_a_running_instance_without_the_inspector_is_busy(self): + self.fake(50, "/usr/bin/FEX", str(self.dir) + "/app/curseforge", "--no-sandbox") + out = self.run_helper("start", str(self.dir), env={"DISPLAY": ":0"}) + self.assertEqual(3, out.returncode) + self.assertEqual("busy", out.stdout.strip()) + self.stop() + self.assertTrue((self.proc / "50").exists()) + + def test_start_uses_a_random_port_and_a_secret_inspector_url_kept_private(self): + self.fake(41, "/usr/bin/Xwayland", ":0", "-auth", "/run/droiddeck/xauth_abc") + out = self.run_helper("start", str(self.dir)) + self.addCleanup(self.stop) + self.assertEqual(0, out.returncode, out.stderr) + self.assertEqual(URL, out.stdout.strip()) + seen = self.seen.read_text().splitlines() + self.assertEqual(["DISPLAY=:0", "XAUTHORITY=/run/droiddeck/xauth_abc", "WAYLAND=", "DBUS=", str(self.dir), + "--minimized", "--inspect=127.0.0.1:0", "--inspect-publish-uid=stderr"], seen) + self.assertEqual(0o700, self.state.stat().st_mode & 0o777) + self.assertEqual(0o600, (self.state / "log").stat().st_mode & 0o777) + again = self.run_helper("start", str(self.dir)) + self.assertEqual(URL, again.stdout.strip()) + pid = self.pid() + self.stop() + self.assertFalse((self.state / "pid").exists()) + self.assertTrue(self.gone(pid), "the started instance is still running") + + def test_hold_keeps_the_app_until_it_is_signalled(self): + held = subprocess.Popen(["bash", str(HELPER), "hold", str(self.dir)], env=self.env({"DISPLAY": ":0"}), + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + self.addCleanup(self.end, held) + for _ in range(100): + if (self.state / "pid").exists() and self.seen.exists(): + break + time.sleep(0.1) + pid = self.pid() + time.sleep(1) + self.assertIsNone(held.poll()) + held.send_signal(signal.SIGTERM) + self.assertEqual(0, held.wait(timeout=30)) + self.assertTrue(self.gone(pid), "hold left the app running") + self.assertFalse((self.state / "pid").exists()) + + def end(self, held): + if held.poll() is None: + held.send_signal(signal.SIGTERM) + try: + held.wait(timeout=15) + except subprocess.TimeoutExpired: + held.kill() + held.wait() + record = self.state / "pid" + if record.exists(): + try: + os.killpg(self.pid(), signal.SIGKILL) + except (ProcessLookupError, PermissionError): + pass + + def test_a_launch_for_another_directory_is_busy(self): + other = self.tmp / "other" + (other / "app").mkdir(parents=True) + first = self.run_helper("start", str(self.dir), env={"DISPLAY": ":0"}) + self.addCleanup(self.stop) + self.assertEqual(0, first.returncode, first.stderr) + out = self.run_helper("start", str(other), env={"DISPLAY": ":0"}) + self.assertEqual(3, out.returncode) + self.assertEqual("busy", out.stdout.strip()) + pid = self.pid() + self.run_helper("stop", str(other)) + self.assertEqual(pid, self.pid()) + os.kill(pid, 0) + + def test_hold_ends_when_the_app_exits(self): + proc = shlex.quote(str(self.proc)) + self.runner.write_text("#!/bin/bash\nmkdir -p %s/$$ && printf '%%s\\0' bash \"$0\" \"$@\" > %s/$$/cmdline\n" + "echo 'Debugger listening on %s'\nsleep 2\nrm -r %s/$$\n" % (proc, proc, URL, proc)) + out = subprocess.run(["bash", str(HELPER), "hold", str(self.dir)], env=self.env({"DISPLAY": ":0"}), + capture_output=True, text=True, timeout=60) + self.assertEqual(0, out.returncode, out.stderr) + + def test_stop_without_a_launch_is_quiet(self): + out = self.run_helper("stop", str(self.dir)) + self.assertEqual(0, out.returncode) + self.assertEqual("", out.stderr) + + def test_bad_arguments_are_refused(self): + self.assertEqual(2, self.run_helper("start", str(self.tmp / "missing")).returncode) + self.assertEqual(2, self.run_helper("launch", str(self.dir)).returncode) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_droiddeck_agent.py b/tools/tests/test_droiddeck_agent.py index a84a54ca8b..6bf1b0da8c 100644 --- a/tools/tests/test_droiddeck_agent.py +++ b/tools/tests/test_droiddeck_agent.py @@ -348,6 +348,23 @@ class AgentTest(unittest.TestCase): self.assertEqual("INVALID_TARGET", caught.exception.code) connect.assert_not_called() + def test_a_devtools_endpoint_lost_while_sending_is_reported_as_gone(self): + class Lost: + def __init__(self, *args, **kwargs): + pass + + def send(self, text): + raise BrokenPipeError("closed") + + def close(self): + pass + + with patch.object(agent, "WebSocket", Lost), patch.object( + agent, "cdp_targets", return_value=[{"title": "SharedJSContext", "webSocketDebuggerUrl": "ws://127.0.0.1:1/x"}]): + with self.assertRaises(agent.AgentError) as caught: + agent.cdp_eval(str(self.dir), "1") + self.assertEqual("DEVTOOLS_UNREACHABLE", caught.exception.code) + def test_cdp_without_a_port(self): os.environ.pop("DD_CDP_PORT", None) self.assertEqual("NO_DEVTOOLS", self.ask({"kind": "cdp", "expression": "1"})["error"]["code"]) @@ -368,6 +385,22 @@ class AgentTest(unittest.TestCase): missing = self.ask({"kind": "cdp", "expression": "1", "target": "Nope"}) self.assertEqual("NO_TARGET", missing["error"]["code"]) + def test_cdp_eval_on_a_secret_inspector_url(self): + server = FakeDevTools({"result": {"result": {"type": "string", "value": "ok"}}}) + server.start() + self.addCleanup(server.server.close) + os.environ.pop("DD_CDP_PORT", None) + url = "ws://127.0.0.1:%d/0f8fad5b-d9cb-469f-a165-70867728950e" % server.port + answer = self.ask({"kind": "cdp", "expression": "require('electron')", "inspector": url, "commandLineApi": True}) + self.assertTrue(answer["ok"], answer) + self.assertEqual("inspector", answer["target"]) + self.assertTrue(server.seen[0]["params"]["includeCommandLineAPI"]) + + def test_cdp_refuses_inspector_urls_without_a_session_id(self): + for url in ("ws://127.0.0.1:9229/", "ws://127.0.0.1:9229/json/list", "ws://10.0.0.2:9229/0f8fad5b-d9cb-469f-a165-70867728950e", + "ws://127.0.0.1:80/0f8fad5b-d9cb-469f-a165-70867728950e", "ws://127.0.0.1:9229/0f8fad5b-d9cb-469f-a165-70867728950e/x", 9229): + self.assertEqual("INVALID_REQUEST", self.ask({"kind": "cdp", "expression": "1", "inspector": url})["error"]["code"]) + def test_steam_selection(self): with patch.object(agent, "cdp_eval", return_value={"value": "3180310"}) as evaluate: answer = self.ask({"kind": "steam-selection"}) diff --git a/tools/tests/test_hdr_live_switch.py b/tools/tests/test_hdr_live_switch.py index 4468be5048..41e30ebc76 100644 --- a/tools/tests/test_hdr_live_switch.py +++ b/tools/tests/test_hdr_live_switch.py @@ -43,11 +43,15 @@ class HdrLiveSwitchTest(unittest.TestCase): def test_the_gate_follows_the_display_not_the_setting(self): text = (APP / "SessionActivity.kt").read_text() start = text.index("val attached = CompositorHost.isStarted") - block = text[start:text.index("DriverSetupLog.write", start)] + block = text[start:text.index("CompositorHost.start(", start)] request = block[block.index("nativeSetHdrRequest("):block.index("Log.i", block.index("nativeSetHdrRequest("))] - self.assertNotIn("SessionPrefs.hdr", block[:block.index("if (!SessionState.running)")]) + self.assertNotIn("SessionPrefs.hdr", block) self.assertIn("capable, false", request) - self.assertIn("SessionState.hdrCapable && SessionPrefs.hdr(this, mode)", block) + self.assertIn("if (!SessionState.running) CompositorHost.applyHdr(this, mode)", block) + host = (APP / "wayland/CompositorHost.kt").read_text() + gate = host[host.index("fun applyHdr("):] + gate = gate[:gate.index("\n }")] + self.assertIn("SessionState.hdrCapable && SessionPrefs.hdr(context, mode)", gate) def test_both_switches_apply_to_the_running_session(self): helper = (APP / "session/SessionHdr.kt").read_text() From 00525cde1520367d49fa98ca290c2cf6b022722b Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:07:23 -0500 Subject: [PATCH 046/141] fix(session): picking a bottom-screen mode clears the menu restore left by a teardown (#3007) --- .../main/java/com/droiddeck/launcher/SessionActivity.kt | 1 + .../launcher/input/SecondScreenProfileMigrationTest.kt | 9 +++++++++ 2 files changed, 10 insertions(+) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 1d51cd2a88..dbbe76ac95 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -4447,6 +4447,7 @@ 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) } diff --git a/app/src/test/java/com/droiddeck/launcher/input/SecondScreenProfileMigrationTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SecondScreenProfileMigrationTest.kt index ba688bcbd5..d32edcdd8d 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/SecondScreenProfileMigrationTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/SecondScreenProfileMigrationTest.kt @@ -108,6 +108,15 @@ class SecondScreenProfileMigrationTest { } } + @Test fun pickingAnotherModeClearsTheMenuRestoreLeftByATeardown() { + customLibrary(desktop = false) + SessionState.bottomMenu = true + ReflectionHelpers.callInstanceMethod(activity, "pickSecondScreenMode", + ReflectionHelpers.ClassParameter.from(SecondScreenMode::class.java, SecondScreenMode.KEYBOARD_TRACKPAD)) + assertFalse(SessionState.bottomMenu) + assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD.id, SessionPrefs.secondScreenPanel(activity, false)) + } + private fun customLibrary(desktop: Boolean): InputLibrary { session(desktop) return InputLibraries.update(activity) { library -> From 6ef8e2274ed3f9dfe1cb465ff46405239b80cc9f Mon Sep 17 00:00:00 2001 From: DeathKhan Date: Sun, 22 Nov 2026 16:11:29 -0600 Subject: [PATCH 047/141] fix(ui): focused cards keep their solid ground under the highlight tint (#2909) --- app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt | 2 +- app/src/main/java/com/droiddeck/launcher/ui/DesktopPage.kt | 2 +- app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt | 2 +- app/src/main/java/com/droiddeck/launcher/ui/MorePage.kt | 2 +- app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt | 2 +- .../java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt | 4 ++-- app/src/main/java/com/droiddeck/launcher/ui/StorePage.kt | 2 +- 7 files changed, 8 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt index 0bdba211ad..73073cdf8f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt @@ -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(if (hot) pal.signal.copy(alpha = 0.14f) else colors.surface) + .background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.14f)) else Modifier) .glideBorder(hot, shape, pal.signal, pal.line) .hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Button, onClick = open) .controllerConfirm(onClick = open) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DesktopPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/DesktopPage.kt index 9d3a84e7a5..523dfb5d65 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DesktopPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DesktopPage.kt @@ -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(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface) + .clip(shape).background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier) .glideBorder(hot, shape, pal.signal, pal.line) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button) { onClick(artAt) } .controllerConfirm { onClick(artAt) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt index bb299cc06b..70c49a5518 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -1166,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(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)) + .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)) .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) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/MorePage.kt b/app/src/main/java/com/droiddeck/launcher/ui/MorePage.kt index a2dad0a54c..bdb28f6fa7 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/MorePage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/MorePage.kt @@ -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(if (hot) pal.signal.copy(alpha = 0.12f) else colors.surface) + .background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.12f)) else Modifier) .glideBorder(hot, shape, pal.signal, pal.line) .hoverable(src) .clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt index f34161f6aa..34ebbbf9f8 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt @@ -453,7 +453,7 @@ private fun BucketCard( modifier = modifier.paneItem("storage:${bucket.name}") .graphicsLayer { scaleX = scale; scaleY = scale } .clip(Shape14) - .background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface) + .background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier) .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) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt index 5d9adf2cbf..2d6e37753c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt @@ -174,7 +174,7 @@ internal fun AchievementRow(a: Achievement, compact: Boolean, modifier: Modifier Row( verticalAlignment = Alignment.CenterVertically, modifier = modifier.fillMaxWidth().clip(shape) - .background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface) + .background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier) .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?, modifier: Modifier verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = modifier.fillMaxWidth().height(44.dp).clip(shape) - .background(if (hot) pal.signal.copy(alpha = 0.14f) else colors.surface) + .background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.14f)) else Modifier) .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) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StorePage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StorePage.kt index e3724dd83d..356b69af9c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StorePage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StorePage.kt @@ -533,7 +533,7 @@ private fun AppCard(app: CardApp, size: Dp, first: Boolean, cards: HashMap Date: Sun, 22 Nov 2026 20:40:30 -0500 Subject: [PATCH 048/141] fix(fex): signal return restores syscall state; CurseForge runs headless (#3040) * fix(fex): signal return restores the interrupted syscall state A guest rt_sigreturn goes through FEX's syscall stub, which marks every static register as spilled. Returning to unchanged JIT code skipped the stub's reset, so later asynchronous signals skipped the register spill and guest handlers read stale registers. CoreCLR's GC suspension reads and redirects that context, which made x86-64 .NET programs fail with random access violations. Restore the value saved at signal entry. * fix(addons): run CurseForge headless from the addon browser, without a session - The CurseForge source starts the app in its own headless gamescope (droiddeck-headless, shared with the Battle.net Agent) instead of a hidden session: no SessionService, compositor output or ImageReader. - The helper's start keeps running until the app exits, so the app lives for as long as the addon browser holds that guest command; closing the dialog asks the app to quit, stops its process group and cancels the command, which ends the app, its gamescope and the guest. - An app the user already has open is reported busy and left alone. - Removes BackgroundSession and the CompositorHost start path it shared with SessionActivity, with their tests. * fix(addons): bind each CurseForge stop to its launch and keep the inspector URL out of logs A stop now only acts on the launch that registered it, so a late stop from a closed browser cannot end a newer launch, and the browser stops once. Command logs redact the inspector URL. The signal probe reports a sender thread that cannot start, sets ECX before the measured region and its test accepts a valid overshoot of the target count. * fix(fex): unblock the probe signal before sampling --- .../com/droiddeck/launcher/SessionActivity.kt | 37 +++- .../launcher/runtime/CurseForgeApp.kt | 101 ++++++--- .../launcher/runtime/GuestCommand.kt | 8 +- .../launcher/session/BackgroundSession.kt | 119 ----------- .../launcher/session/SessionFiles.kt | 1 + .../stores/gog/GogDownloadManager.java | 2 +- .../com/droiddeck/launcher/ui/AddonBrowser.kt | 44 +--- .../launcher/wayland/CompositorHost.kt | 48 ----- .../launcher/runtime/CurseForgeAppTest.kt | 142 ++++++++++++- docs/development/x86-64-steam-client.md | 10 + ...signal-return-restores-syscall-state.patch | 12 ++ tools/fex/probes/async-signal-context.c | 84 ++++++++ .../overlay/usr/local/bin/droiddeck-agent | 23 +- .../overlay/usr/local/bin/droiddeck-battlenet | 31 +-- .../usr/local/bin/droiddeck-curseforge | 65 ++---- .../overlay/usr/local/bin/droiddeck-headless | 24 +++ tools/tests/test_battlenet.py | 19 +- tools/tests/test_curseforge_helper.py | 200 +++++++++++------- tools/tests/test_droiddeck_agent.py | 22 ++ tools/tests/test_fex_signal_syscall_state.py | 76 +++++++ tools/tests/test_hdr_live_switch.py | 10 +- 21 files changed, 663 insertions(+), 415 deletions(-) delete mode 100644 app/src/main/java/com/droiddeck/launcher/session/BackgroundSession.kt create mode 100644 tools/fex/patches/0008-signal-return-restores-syscall-state.patch create mode 100644 tools/fex/probes/async-signal-context.c create mode 100755 tools/linuxfs/overlay/usr/local/bin/droiddeck-headless create mode 100644 tools/tests/test_fex_signal_syscall_state.py diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index dbbe76ac95..96aeb08be3 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -2846,7 +2846,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (!SessionState.running) { SessionEvents.transition(SessionPhase.STARTING_COMPOSITOR, "compositor.starting") } - val output = CompositorHost.prepare(this) + val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() } + FileUtils.copyAsset(this, "wayland/keymap.xkb", File(runtimeDir, "keymap.xkb")) + com.droiddeck.launcher.input.VrControllers.publish(this) + + val turnip = TurnipDriver(this) + com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "surface.driver-setup") + if (!CompositorHost.isStarted) { + CompositorHost.displayChoice = SessionPrefs.androidDriver(this) + com.droiddeck.launcher.gpu.AutoDriverTrial.displayStarting(this, SessionPrefs.androidDriver(this)) + } + val driverId = if (CompositorHost.isStarted) null else turnip.install() val previous = SessionState.outputSize val live = windowOutputSize(holder.surfaceFrame.width(), holder.surfaceFrame.height()) @@ -2873,7 +2883,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde pushCardboard(activeCardboard) WaylandCompositor.nativeSetCardboardPoseFile(File(filesDir, ".wayland-rt/droiddeck-headpose").path) com.droiddeck.launcher.glasses.SpatialTracking.attachPublisher(File(filesDir, ".wayland-rt/droiddeck-spatialpose").path) - if (!SessionState.running) CompositorHost.logToSession(this) + if (!SessionState.running) { + val waylandLog = File(SessionPaths.beginOrCurrent(this), "wayland.log") + WaylandCompositor.setSessionLogFile(waylandLog) + try { + android.system.Os.setenv("DD_WAYLAND_LOG", waylandLog.path, true) + } catch (e: Exception) { + Log.w(TAG, "could not point the compositor's log at $waylandLog", e) + } + } val mode = hdrPrefMode() if (probe != null) { WaylandCompositor.nativeSetHdrDisplay( @@ -2893,8 +2911,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde ) Log.i(TAG, "hdr: " + (if (tonemap) "tone-mapped (${probe.reason})" else if (capable) "available" else "unavailable") + " · display ${probe.formats.ifEmpty { "SDR" }}") } - if (!SessionState.running) CompositorHost.applyHdr(this, mode) - CompositorHost.start(this, output, holder.surface, size, refreshHz(holder), outputFpsLimit()) + if (!SessionState.running) { + val on = SessionState.hdrCapable && SessionPrefs.hdr(this, mode) + SessionState.hdr = on + WaylandCompositor.nativeSetHdrOutput(on) + WaylandCompositor.nativeSetZeroCopy(on || SessionPrefs.zeroCopy(this, mode)) + Log.i(TAG, "hdr: " + (if (on) "on" else "off") + " for this $mode session") + } + com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "compositor.start driver=$driverId") + CompositorHost.startOrAttach( + this, holder.surface, runtimeDir.path, + driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) }, + applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(holder), outputFpsLimit(), + ) onOutputAttached(holder) if (SessionState.running && size != previous) { Log.i(TAG, "output resized: ${previous.first}x${previous.second} -> ${size.first}x${size.second} on a new surface") diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt b/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt index 5477c8ede1..adc2119889 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt @@ -1,25 +1,29 @@ package com.droiddeck.launcher.runtime import android.content.Context -import com.droiddeck.launcher.agent.AgentException -import com.droiddeck.launcher.agent.AgentGuest +import com.droiddeck.launcher.stores.battlenet.BattleNetInstall import org.json.JSONArray import org.json.JSONObject 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 - enum class Start { READY, BUSY, NO_DISPLAY, FAILED } + enum class Start { READY, BUSY, FAILED } class Started(val state: Start, val inspector: String? = null) - private 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}") + 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" @@ -31,14 +35,19 @@ object CurseForgeApp { internal fun dir(app: UserApps.App): String? = app.args.firstOrNull()?.takeIf { it.startsWith("/") } - fun holdArgs(app: UserApps.App): List? = dir(app)?.let { listOf("hold", it) } + internal fun helperArgv(command: String, dir: String): List = listOf(HELPER, command, dir) + + internal fun evalArgv(inspector: String, expression: String, timeoutMs: Long): List = + listOf(AGENT, "--cdp-inspector", inspector, (timeoutMs / 1000.0).toString(), expression) + + internal fun lastJson(lines: List): 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 - 4 -> Start.NO_DISPLAY else -> Start.FAILED } @@ -137,47 +146,75 @@ object CurseForgeApp { return (0 until list.length()).mapNotNull { list.opt(it)?.toString()?.takeIf { id -> id.isNotBlank() && id != "null" } }.toSet() } - private fun call(context: Context, inspector: String, service: String, method: String, args: JSONArray?, timeoutMs: Long, pick: String = "r => r"): Any? { - val request = JSONObject().put("kind", "cdp").put("inspector", inspector).put("commandLineApi", true) - .put("expression", expression(service, method, args, pick)).put("timeout", timeoutMs / 1000.0) - return unwrap(AgentGuest.call(context, request, timeoutMs + 3_000, trusted = true)) + internal var guest: (Context, List, 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 fun helper(context: Context, command: String, dir: String, timeoutMs: Long): JSONObject? { - val request = JSONObject().put("kind", "exec").put("argv", JSONArray(listOf(HELPER, command, dir))).put("timeout", timeoutMs / 1000.0) - return runCatching { AgentGuest.call(context, request, timeoutMs + 5_000, trusted = true) }.getOrNull() + private val holds = ConcurrentHashMap() + + private fun lines(context: Context, argv: List): List { + val out = ArrayList() + guest(context, argv, null) { out += it } + return out } - fun start(context: Context, app: UserApps.App): Started { + 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() + 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) - val answer = helper(context, "start", dir, 90_000) - if (answer == null || !answer.optBoolean("ok") || answer.optBoolean("timedOut")) { - stop(context, app, null) - 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 state = startState(answer.optInt("exitCode", -1)) - if (state == Start.BUSY || state == Start.NO_DISPLAY) return Started(state) - val inspector = inspectorUrl(answer.optJSONObject("stdout")?.optString("text").orEmpty()) - if (state != Start.READY || inspector == null) { - stop(context, app, null) + 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) { - val ready = runCatching { call(context, inspector, "InstalledProjectsAppService", "installAddon", null, 10_000) } - if (ready.isSuccess) return Started(Start.READY, inspector) - val error = ready.exceptionOrNull() - if (error is AgentException && error.code == "NO_ACTIVE_SESSION") break + 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) + stop(context, app, inspector, hold) return Started(Start.FAILED) } - fun stop(context: Context, app: UserApps.App, inspector: String?) { + 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") } - helper(context, "stop", dir, 30_000) + hold.set(true) + if (holds.remove(dir, hold)) runCatching { lines(context, helperArgv("stop", dir)) } } private fun connect(context: Context, inspector: String) { @@ -207,7 +244,7 @@ object CurseForgeApp { while (System.currentTimeMillis() < deadline) { val listed = runCatching { installed(context, inspector, guid) } val error = listed.exceptionOrNull() - if (error is Failure && error.gone || error is AgentException && error.code == "NO_ACTIVE_SESSION") throw error + if (error is Failure && error.gone) throw error if (projectId in listed.getOrDefault(emptySet())) return true Thread.sleep(1_000) } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt b/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt index 95ea5b13c9..2c5fbad51e 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt @@ -14,20 +14,22 @@ import java.util.concurrent.atomic.AtomicBoolean object GuestCommand { fun run(context: Context, argv: List, fakeRoot: Boolean = false, logName: String? = null, linkDir: File? = null, extraBinds: List? = null, fastPath: Boolean = false, cancelled: AtomicBoolean? = null, - onLine: (String) -> Unit): Int { + redact: Regex? = null, 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()} ${argv.joinToString(" ")}") + log?.println("== ${java.util.Date()} ${redacted(argv.joinToString(" "), redact)}") try { - return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath, cancelled) { line -> log?.println(line); log?.flush(); onLine(line) } + return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath, cancelled) { line -> log?.println(redacted(line, redact)); log?.flush(); onLine(line) } } finally { log?.close() } } + internal fun redacted(text: String, redact: Regex?): String = redact?.replace(text, "") ?: text + private fun runLogged(context: Context, argv: List, fakeRoot: Boolean, linkDir: File?, extraBinds: List?, fastPath: Boolean, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int { val root = LinuxRuntime.rootDir(context) diff --git a/app/src/main/java/com/droiddeck/launcher/session/BackgroundSession.kt b/app/src/main/java/com/droiddeck/launcher/session/BackgroundSession.kt deleted file mode 100644 index 50c60f5747..0000000000 --- a/app/src/main/java/com/droiddeck/launcher/session/BackgroundSession.kt +++ /dev/null @@ -1,119 +0,0 @@ -package com.droiddeck.launcher.session - -import android.content.Context -import android.graphics.PixelFormat -import android.media.ImageReader -import android.os.Handler -import android.os.Looper -import android.util.Log -import com.droiddeck.launcher.agent.AgentGuest -import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller -import com.droiddeck.launcher.storage.StorageState -import com.droiddeck.launcher.wayland.CompositorHost -import java.util.concurrent.CountDownLatch -import java.util.concurrent.TimeUnit -import java.util.concurrent.atomic.AtomicBoolean - -object BackgroundSession { - private const val TAG = "BackgroundSession" - private const val WIDTH = 1280 - private const val HEIGHT = 720 - private const val REFRESH_HZ = 60f - private const val BEGIN_MS = 30_000L - private const val AGENT_MS = 120_000L - private const val STOP_MS = 30_000L - private val ended = setOf(SessionPhase.IDLE, SessionPhase.FAILED) - private val main by lazy { Handler(Looper.getMainLooper()) } - private var reader: ImageReader? = null - - fun start(context: Context, program: String, args: List): String? { - val app = context.applicationContext - val claim = AtomicBoolean(false) - val began = CountDownLatch(1) - var own: String? = null - main.post { - if (claim.compareAndSet(false, true)) { - own = runCatching { begin(app, program, args) } - .onFailure { Log.w(TAG, "could not start a hidden session for $program", it) } - .getOrNull() - } - began.countDown() - } - if (!began.await(BEGIN_MS, TimeUnit.MILLISECONDS) && claim.compareAndSet(false, true)) return null - began.await() - val session = own ?: return null - val deadline = System.currentTimeMillis() + AGENT_MS - val settle = System.currentTimeMillis() + 5_000 - while (System.currentTimeMillis() < deadline) { - if (SessionState.sessionId != session) return null - if (SessionState.running && AgentGuest.hello(app) != null && SessionState.sessionId == session) return session - if (SessionState.phase == SessionPhase.FAILED) break - if (!SessionState.running && SessionState.phase in ended && System.currentTimeMillis() > settle) break - Thread.sleep(250) - } - stop(app, session) - return null - } - - fun stop(context: Context, session: String) { - val app = context.applicationContext - if (SessionState.sessionId != session) return - main.post { if (SessionState.sessionId == session) SessionService.stop(app) } - val deadline = System.currentTimeMillis() + STOP_MS - while (live(session) && System.currentTimeMillis() < deadline) Thread.sleep(250) - if (!live(session)) { - main.post { release() } - return - } - Thread { - while (live(session)) Thread.sleep(1_000) - main.post { release() } - }.start() - } - - private fun live(session: String) = - SessionState.sessionId == session && (SessionState.running || SessionState.phase !in ended) - - private fun begin(context: Context, program: String, args: List): String? { - if (SessionState.running || SessionState.phase !in ended || LinuxRuntimeInstaller.isBusy() || - SessionState.installing != null || StorageState.cleaning) return null - release() - SessionEvents.begin(context, SessionService.MODE_RUN, SessionPaths.label(SessionService.MODE_RUN, program)) - val session = SessionState.sessionId ?: return null - SessionState.stopRequested = false - SessionEvents.transition(SessionPhase.STARTING_COMPOSITOR, "compositor.starting") - var requested = false - try { - val output = CompositorHost.prepare(context) - val size = WIDTH to HEIGHT - SessionState.outputSize = size - SessionState.refreshHz = REFRESH_HZ - CompositorHost.logToSession(context) - CompositorHost.applyHdr(context, SessionPrefs.prefMode(SessionService.MODE_RUN)) - val offscreen = ImageReader.newInstance(WIDTH, HEIGHT, PixelFormat.RGBA_8888, 2) - reader = offscreen - offscreen.setOnImageAvailableListener({ it.acquireLatestImage()?.close() }, main) - CompositorHost.start(context, output, offscreen.surface, size, REFRESH_HZ, 0) - CompositorHost.detach(offscreen.surface) - SessionEvents.record("compositor.started") - SessionEvents.transition(SessionPhase.STARTING_GUEST, "guest.starting") - requested = true - SessionService.start(context, SessionService.MODE_RUN, program, programArgs = args.toTypedArray()) - return session - } catch (e: Exception) { - if (requested) SessionService.stop(context) - if (!SessionState.running) { - reader?.close() - reader = null - SessionEvents.transition(SessionPhase.FAILED, "hidden.failed", mapOf("error" to e.toString())) - } - throw e - } - } - - private fun release() { - if (SessionState.running) return - reader?.close() - reader = null - } -} diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index afb8fcb8d4..34d96eab4b 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -181,6 +181,7 @@ object SessionFiles { "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", diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogDownloadManager.java b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogDownloadManager.java index a09629bc4c..8864bdaf75 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogDownloadManager.java +++ b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogDownloadManager.java @@ -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, + false, "gog-innoextract", null, null, false, cancelled, null, 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()); diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt index b8fa6c6278..514677364c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt @@ -67,14 +67,13 @@ 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.BackgroundSession -import com.droiddeck.launcher.session.SessionService import com.droiddeck.launcher.session.SessionState import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File +import java.util.concurrent.atomic.AtomicBoolean private class AddonResults { val items = mutableStateListOf() @@ -95,10 +94,7 @@ private class CurseLink(val app: UserApps.App) { private val lock = Object() @Volatile private var closed = false - private var held = false - private var ownSession: String? = null - private var started = false - @Volatile private var launching = false + @Volatile private var hold: AtomicBoolean? = null @Volatile private var inspector: String? = null private val guids = HashMap() @@ -119,29 +115,13 @@ private class CurseLink(val app: UserApps.App) { private fun link(context: Context, target: WowAddons.Target): Linked { if (closed) throw CurseState() - if (!SessionState.running) { - started = false - launching = false - held = false - ownSession = null - inspector = null - guids.clear() - val args = CurseForgeApp.holdArgs(app) ?: throw CurseState() - ownSession = BackgroundSession.start(context, CurseForgeApp.HELPER, args) ?: throw CurseState() - } - if (closed) throw CurseState() - if (!held) { - held = true - SessionService.holdForSignIn(context, true) - } - val awake = System.currentTimeMillis() + 30_000 - while ((SessionState.suspended || SessionState.suspending) && System.currentTimeMillis() < awake) Thread.sleep(250) val url = inspector ?: run { - launching = true - val done = CurseForgeApp.start(context, app) + val launch = AtomicBoolean(false) + hold = launch + if (closed) throw CurseState() + val done = CurseForgeApp.start(context, app, launch) when (done.state) { CurseForgeApp.Start.READY -> { - started = true inspector = done.inspector done.inspector ?: throw CurseState() } @@ -160,17 +140,11 @@ private class CurseLink(val app: UserApps.App) { fun close(context: Context) { closed = true + val launch = hold ?: return Thread { - if (launching) CurseForgeApp.stop(context, app, inspector) + CurseForgeApp.stop(context, app, inspector, launch) synchronized(lock) { - if (started) CurseForgeApp.stop(context, app, inspector) - val owned = ownSession - if (owned != null) BackgroundSession.stop(context, owned) - else if (held) SessionService.holdForSignIn(context, false) - started = false - launching = false - ownSession = null - held = false + hold = null inspector = null } }.start() diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt index 89ae2b1cb3..8d43d09c7b 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt @@ -10,8 +10,6 @@ import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.SessionState object CompositorHost { - private const val TAG = "DroidDeck" - @Volatile private var started = false @@ -57,52 +55,6 @@ object CompositorHost { } } - class Output internal constructor( - internal val runtimeDir: java.io.File, - internal val turnip: com.droiddeck.launcher.gpu.TurnipDriver, - internal val driverId: String?, - ) - - fun prepare(context: android.content.Context): Output { - val runtimeDir = java.io.File(context.filesDir, ".wayland-rt").apply { mkdirs() } - com.droiddeck.launcher.core.FileUtils.copyAsset(context, "wayland/keymap.xkb", java.io.File(runtimeDir, "keymap.xkb")) - com.droiddeck.launcher.input.VrControllers.publish(context) - val turnip = com.droiddeck.launcher.gpu.TurnipDriver(context) - com.droiddeck.launcher.gpu.DriverSetupLog.write(context, "surface.driver-setup") - if (!started) { - displayChoice = SessionPrefs.androidDriver(context) - com.droiddeck.launcher.gpu.AutoDriverTrial.displayStarting(context, SessionPrefs.androidDriver(context)) - } - return Output(runtimeDir, turnip, if (started) null else turnip.install()) - } - - fun logToSession(context: android.content.Context) { - val waylandLog = java.io.File(com.droiddeck.launcher.session.SessionPaths.beginOrCurrent(context), "wayland.log") - WaylandCompositor.setSessionLogFile(waylandLog) - try { - android.system.Os.setenv("DD_WAYLAND_LOG", waylandLog.path, true) - } catch (e: Exception) { - android.util.Log.w(TAG, "could not point the compositor's log at $waylandLog", e) - } - } - - fun applyHdr(context: android.content.Context, mode: String) { - val on = SessionState.hdrCapable && SessionPrefs.hdr(context, mode) - SessionState.hdr = on - WaylandCompositor.nativeSetHdrOutput(on) - WaylandCompositor.nativeSetZeroCopy(on || SessionPrefs.zeroCopy(context, mode)) - android.util.Log.i(TAG, "hdr: " + (if (on) "on" else "off") + " for this $mode session") - } - - fun start(context: android.content.Context, output: Output, surface: Surface, size: Pair, refreshHz: Float, fpsLimit: Int): Boolean { - com.droiddeck.launcher.gpu.DriverSetupLog.write(context, "compositor.start driver=${output.driverId}") - return startOrAttach( - context, surface, output.runtimeDir.path, - output.driverId?.let { output.turnip.driverPath(it) }, output.driverId?.let { output.turnip.libraryName(it) }, - context.applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz, fpsLimit, - ) - } - @Synchronized fun startOrAttach( context: android.content.Context, diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt index 98cdd9376f..e3cb7ef501 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt @@ -8,6 +8,7 @@ import org.junit.Assert.assertFalse import org.junit.Assert.assertNull import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue +import org.junit.After import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder @@ -21,6 +22,47 @@ import java.io.File class CurseForgeAppTest { @get:Rule val temp = TemporaryFolder() + private val original = CurseForgeApp.guest + private val url = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e" + private val app = UserApps.App("appimage:c", UserApps.Kind.APPIMAGE, "CurseForge", null, null, AppImageManager.LAUNCHER, listOf("/root/apps/curseforge"), feed = CurseForgeApp.FEED) + + @After + fun restoreGuest() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + launches.forEach { CurseForgeApp.stop(context, app, null, it) } + holder.get()?.set(true) + CurseForgeApp.guest = original + } + + private val launches = mutableListOf() + + private fun launch(): java.util.concurrent.atomic.AtomicBoolean = java.util.concurrent.atomic.AtomicBoolean(false).also { launches += it } + + private val holder = java.util.concurrent.atomic.AtomicReference() + private val released = java.util.concurrent.CountDownLatch(1) + + private fun fakeGuest(startExit: Int, ready: Boolean = true): MutableList> { + val calls = java.util.Collections.synchronizedList(mutableListOf>()) + CurseForgeApp.guest = { _, argv, cancelled, onLine -> + calls += argv + when { + argv[0] == CurseForgeApp.HELPER && argv[1] == "start" -> { + if (startExit == 0) { + holder.set(cancelled) + onLine(url) + while (cancelled?.get() != true) Thread.sleep(10) + released.countDown() + } else onLine("busy") + startExit + } + argv[0] == CurseForgeApp.HELPER -> 0 + ready -> { onLine(JSONObject().put("ok", true).put("value", """{"value":true}""").toString()); 0 } + else -> { onLine(JSONObject().put("ok", false).put("error", JSONObject().put("code", "DEVTOOLS_UNREACHABLE").put("message", "no")).toString()); 0 } + } + } + return calls + } + private val search = """{"success":true,"injectedCount":0, "pagination":{"index":0,"pageSize":20,"resultCount":20,"totalCount":150}, "mods":[ @@ -129,7 +171,7 @@ class CurseForgeAppTest { assertEquals(emptySet(), CurseForgeApp.projectIds(JSONObject())) assertEquals(CurseForgeApp.Start.READY, CurseForgeApp.startState(0)) assertEquals(CurseForgeApp.Start.BUSY, CurseForgeApp.startState(3)) - assertEquals(CurseForgeApp.Start.NO_DISPLAY, CurseForgeApp.startState(4)) + assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.startState(4)) assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.startState(5)) } @@ -158,4 +200,102 @@ class CurseForgeAppTest { assertEquals(File(root, target.flavor), WowAddons.flavorDir(target)) } } + + @Test + fun theAppStartsInTheGuestWithoutASessionAndIsAskedThroughItsInspector() { + val calls = fakeGuest(0) + val started = CurseForgeApp.start(org.robolectric.RuntimeEnvironment.getApplication(), app, launch()) + assertEquals(CurseForgeApp.Start.READY, started.state) + assertEquals(url, started.inspector) + assertEquals(listOf(CurseForgeApp.HELPER, "start", "/root/apps/curseforge"), calls.first()) + val probe = calls[1] + assertEquals(listOf(CurseForgeApp.AGENT, "--cdp-inspector", url), probe.take(3)) + assertEquals("10.0", probe[3]) + assertTrue(probe[4].contains("InstalledProjectsAppService")) + } + + @Test + fun theLaunchLivesUntilItIsStopped() { + fakeGuest(0) + val context = org.robolectric.RuntimeEnvironment.getApplication() + val hold = launch() + assertEquals(CurseForgeApp.Start.READY, CurseForgeApp.start(context, app, hold).state) + assertEquals(false, holder.get()?.get()) + assertEquals(1L, released.count) + CurseForgeApp.stop(context, app, url, hold) + assertTrue(released.await(5, java.util.concurrent.TimeUnit.SECONDS)) + } + + @Test + fun anAppThatIsAlreadyOpenIsNeitherUsedNorStopped() { + val calls = fakeGuest(3) + assertEquals(CurseForgeApp.Start.BUSY, CurseForgeApp.start(org.robolectric.RuntimeEnvironment.getApplication(), app, launch()).state) + assertEquals(listOf(listOf(CurseForgeApp.HELPER, "start", "/root/apps/curseforge")), calls) + } + + @Test + fun stoppingAsksTheAppToQuitThenStopsItsHeadlessLaunchOnce() { + val calls = fakeGuest(0) + val context = org.robolectric.RuntimeEnvironment.getApplication() + val hold = launch() + CurseForgeApp.start(context, app, hold) + calls.clear() + CurseForgeApp.stop(context, app, url, hold) + assertEquals(CurseForgeApp.AGENT, calls[0][0]) + assertTrue(calls[0][4].contains("shutdown")) + assertEquals(listOf(CurseForgeApp.HELPER, "stop", "/root/apps/curseforge"), calls[1]) + assertTrue(hold.get()) + calls.clear() + CurseForgeApp.stop(context, app, url, hold) + assertTrue(calls.isEmpty()) + } + + @Test + fun aLateStopLeavesTheNewerLaunchRunning() { + val calls = fakeGuest(0) + val context = org.robolectric.RuntimeEnvironment.getApplication() + val old = launch() + val newer = launch() + CurseForgeApp.start(context, app, old) + CurseForgeApp.start(context, app, newer) + assertTrue(old.get()) + calls.clear() + CurseForgeApp.stop(context, app, url, old) + assertTrue(calls.isEmpty()) + assertEquals(false, newer.get()) + CurseForgeApp.stop(context, app, null, newer) + assertEquals(listOf(listOf(CurseForgeApp.HELPER, "stop", "/root/apps/curseforge")), calls) + } + + @Test + fun aStoppedLaunchNeverStarts() { + val calls = fakeGuest(0) + val hold = launch().apply { set(true) } + assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.start(org.robolectric.RuntimeEnvironment.getApplication(), app, hold).state) + assertTrue(calls.isEmpty()) + } + + @Test + fun anAppWithoutADirectoryIsNeverLaunched() { + val calls = fakeGuest(0) + val bare = UserApps.App("appimage:d", UserApps.Kind.APPIMAGE, "CurseForge", null, null, AppImageManager.LAUNCHER, emptyList(), feed = CurseForgeApp.FEED) + val hold = launch() + assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.start(org.robolectric.RuntimeEnvironment.getApplication(), bare, hold).state) + CurseForgeApp.stop(org.robolectric.RuntimeEnvironment.getApplication(), bare, url, hold) + assertTrue(calls.isEmpty()) + } + + @Test + fun theInspectorUrlIsRedactedFromCommandLogs() { + val line = CurseForgeApp.evalArgv(url, "x", 1_000).joinToString(" ") + assertTrue(line.contains(url)) + assertTrue(!GuestCommand.redacted(line, CurseForgeApp.INSPECTOR).contains("127.0.0.1")) + assertTrue(!GuestCommand.redacted(url, CurseForgeApp.INSPECTOR).contains(url)) + } + + @Test + fun theAgentAnswerIsTheLastJsonLine() { + assertEquals("a", CurseForgeApp.lastJson(listOf("noise", """{"v":"a"}""", "== done"))?.getString("v")) + assertNull(CurseForgeApp.lastJson(listOf("noise"))) + } } diff --git a/docs/development/x86-64-steam-client.md b/docs/development/x86-64-steam-client.md index 87b92e5ac5..3d7876c2f5 100644 --- a/docs/development/x86-64-steam-client.md +++ b/docs/development/x86-64-steam-client.md @@ -219,6 +219,16 @@ alone would then read as an installed client. - `0007-cmake-install-code-without-depends`: CMake 4.5 rejects the `DEPENDS` argument FEX passes to `install(CODE ...)` for the guest thunk libraries, so builds with host thunks stopped at configure. The guest libraries are external projects in the default build, which `install` already follows. + - `0008-signal-return-restores-syscall-state`: a guest `rt_sigreturn` is a system call, so FEX's + syscall stub marks every static register as spilled (`InSyscallInfo = 0xFFFF`). When the handler + left RIP alone, the return resumed the interrupted JIT code without passing the stub's reset, and + the mark stayed. Every asynchronous signal after that (until the next system call ended) skipped the + register spill and handed the guest handler stale registers from the last system call: only RIP was + right. CoreCLR suspends threads for the GC with such signals and reads or redirects the interrupted + context, so x86-64 .NET programs failed at random (`AccessViolationException` in whatever code ran + next, then SIGABRT). `tools/fex/probes/async-signal-context.c` shows it: under FEX-2611.1 one signal in + 2000 carried the interrupted registers, natively all of them. The return now restores the value saved + when the signal arrived. - **Building and publishing.** Droid-Deck/DroidDeck-Components' `build-fex.yml` builds `tools/fex` from this repository at a chosen ref (default `main`) with host thunks, in the same Arch Linux ARM container with a read-only token, then a separate job replaces `fex.tzst` on Components' single `fex` release, diff --git a/tools/fex/patches/0008-signal-return-restores-syscall-state.patch b/tools/fex/patches/0008-signal-return-restores-syscall-state.patch new file mode 100644 index 0000000000..6a8e14e1d0 --- /dev/null +++ b/tools/fex/patches/0008-signal-return-restores-syscall-state.patch @@ -0,0 +1,12 @@ +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +index b4c7b24..e6777aa 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +@@ -262,6 +262,7 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr + + if (Context->UContextLocation) { + auto Frame = Thread->CurrentFrame; ++ Frame->InSyscallInfo = Context->InSyscallInfo; + + if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) { + // XXX: Unsupported since it needs state reconstruction diff --git a/tools/fex/probes/async-signal-context.c b/tools/fex/probes/async-signal-context.c new file mode 100644 index 0000000000..9c2c262a5b --- /dev/null +++ b/tools/fex/probes/async-signal-context.c @@ -0,0 +1,84 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include + +volatile long base; +static volatile long hits, matched, stale, stop; +static long want; +static pid_t target; +extern char probe_loop_start[], probe_loop_end[]; + +static void handler(int sig, siginfo_t *info, void *context) { + greg_t *g = ((ucontext_t *)context)->uc_mcontext.gregs; + (void)sig; + (void)info; + if (g[REG_RIP] >= (greg_t)probe_loop_start && g[REG_RIP] < (greg_t)probe_loop_end) { + long below = base - g[REG_RSP]; + if (g[REG_RBX] == 0x1111111111111111L && g[REG_R12] == 0x2222222222222222L && g[REG_R13] == 0x3333333333333333L && + g[REG_R14] == 0x4444444444444444L && g[REG_R15] == 0x5555555555555555L && (unsigned long)g[REG_RCX] <= 4096 && + (below == 0 || below == 8)) + matched++; + else + stale++; + } + hits++; +} + +static void *sender(void *arg) { + (void)arg; + while (!stop) { + syscall(SYS_tgkill, getpid(), target, SIGUSR1); + usleep(50); + } + return NULL; +} + +int main(int argc, char **argv) { + struct sigaction action = {0}; + pthread_t thread; + want = argc > 1 ? atol(argv[1]) : 2000; + action.sa_sigaction = handler; + action.sa_flags = SA_SIGINFO | SA_RESTART; + sigaction(SIGUSR1, &action, NULL); + sigset_t usr1; + sigemptyset(&usr1); + sigaddset(&usr1, SIGUSR1); + pthread_sigmask(SIG_UNBLOCK, &usr1, NULL); + target = syscall(SYS_gettid); + if (pthread_create(&thread, NULL, sender, NULL) != 0) { + fprintf(stderr, "cannot start the signal sender\n"); + return 2; + } + while (matched + stale < want) { + __asm__ volatile("mov $0x1111111111111111, %%rbx\n" + "mov $0x2222222222222222, %%r12\n" + "mov $0x3333333333333333, %%r13\n" + "mov $0x4444444444444444, %%r14\n" + "mov $0x5555555555555555, %%r15\n" + "mov %%rsp, base(%%rip)\n" + "mov $4096, %%ecx\n" + ".globl probe_loop_start\n" + "probe_loop_start:\n" + "push %%rax\n" + "1: dec %%ecx\n" + "jnz 1b\n" + "pop %%rax\n" + "mov $4096, %%ecx\n" + "2: dec %%ecx\n" + "jnz 2b\n" + ".globl probe_loop_end\n" + "probe_loop_end:\n" + : + : + : "rbx", "rcx", "r12", "r13", "r14", "r15", "memory"); + } + stop = 1; + pthread_join(thread, NULL); + printf("signals=%ld matched=%ld stale=%ld\n", hits, matched, stale); + return stale ? 1 : 0; +} diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent b/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent index 4edfc22cb0..df0f4cedf1 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent @@ -1206,6 +1206,15 @@ def handle(agent_dir, req): raise AgentError("UNKNOWN_REQUEST", "Unknown agent request '%s'" % kind) +def reply(agent_dir, req): + try: + return dict(handle(agent_dir, req), ok=True) + except AgentError as e: + return {"ok": False, "error": {"code": e.code, "message": str(e)}} + except Exception as e: + return {"ok": False, "error": {"code": "AGENT_FAILED", "message": "%s: %s" % (type(e).__name__, e)}} + + def answer(agent_dir, path): rid = path.stem try: @@ -1225,12 +1234,7 @@ def answer(agent_dir, path): except OSError: pass if req is not None: - try: - result = dict(handle(agent_dir, req), ok=True) - except AgentError as e: - result = {"ok": False, "error": {"code": e.code, "message": str(e)}} - except Exception as e: - result = {"ok": False, "error": {"code": "AGENT_FAILED", "message": "%s: %s" % (type(e).__name__, e)}} + result = reply(agent_dir, req) write_json(agent_dir / "resp" / (rid + ".json"), result) @@ -1257,6 +1261,13 @@ def serve(agent_dir, focus=True, poll=0.1): def main(argv): + if argv and argv[0] == "--cdp-inspector": + if len(argv) != 4: + print("usage: droiddeck-agent --cdp-inspector ", file=sys.stderr) + return 2 + print(json.dumps(reply(Path("/"), {"kind": "cdp", "inspector": argv[1], "timeout": argv[2], + "expression": argv[3], "commandLineApi": True}))) + return 0 base = os.environ.get("DD_LAUNCH_DIR") if not base: print("DD_LAUNCH_DIR is not set", file=sys.stderr) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet b/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet index 0cddb3fb4b..d24ead6eb5 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet @@ -79,8 +79,7 @@ AGENT_START = 90 AGENT_HELPER = "agent.js" AGENT_RUNTIME = "agent-runtime" AGENT_LOG = "agent.log" -AGENT_LOG_LIMIT = 4 << 20 -HEADLESS = ["--backend", "headless", "-w", "640", "-h", "480"] +HEADLESS = "/usr/local/bin/droiddeck-headless" PRODUCT = re.compile(r"[a-z0-9_]{1,32}") LOCALE = re.compile(r"[a-z]{2}[A-Z]{2}") COUNTRY = re.compile(r"[A-Z]{3}") @@ -1416,33 +1415,23 @@ def agent_job(root, action, uid, product="", folder="", locale="enUS", country=" windows = install_path(root, folder) emit("STATE", "starting") base = os.path.join(CACHE, "agent-%s" % uid) + os.makedirs(CACHE, exist_ok=True) for suffix in (".json", ".game", ".form", ".error"): try: os.unlink(base + suffix) except OSError: pass - runtime = os.path.join(CACHE, AGENT_RUNTIME) - os.makedirs(runtime, mode=0o700, exist_ok=True) env = agent_env() - for name in ("DISPLAY", "WAYLAND_DISPLAY"): - env.pop(name, None) - env["XDG_RUNTIME_DIR"] = runtime - cmd = ["gamescope"] + HEADLESS + ["--", os.path.abspath(sys.argv[0]), "agent-serve", action, uid, product or "-", - windows or "-", locale, country, region, "Z:" + base.replace("/", "\\")] + cmd = [HEADLESS, os.path.join(CACHE, AGENT_RUNTIME), "--log", os.path.join(CACHE, AGENT_LOG), "--", + os.path.abspath(sys.argv[0]), "agent-serve", action, uid, product or "-", + windows or "-", locale, country, region, "Z:" + base.replace("/", "\\")] say("%s %s through the Agent: %s" % (action, uid, " ".join(cmd))) - output = os.path.join(CACHE, AGENT_LOG) - try: - if os.path.getsize(output) > AGENT_LOG_LIMIT: - os.replace(output, output + ".1") - except OSError: - pass before = {pid for pid, _ in wine_processes(pfx)} - with open(output, "ab") as log: - try: - child = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=log, stderr=log, env=env) - except OSError as error: - emit("ERROR", "stopped gamescope: %s" % error) - return 1 + try: + child = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env) + except OSError as error: + emit("ERROR", "stopped gamescope: %s" % error) + return 1 seen = None mark = None moved = time.monotonic() diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-curseforge b/tools/linuxfs/overlay/usr/local/bin/droiddeck-curseforge index a329c15862..de334b7453 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-curseforge +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-curseforge @@ -5,39 +5,17 @@ self=${BASH_SOURCE[0]} proc=${DD_PROC:-/proc} state=${DD_CURSEFORGE_STATE:-${XDG_RUNTIME_DIR:-/tmp}/droiddeck-curseforge} runner=${DD_APPIMAGE_RUN:-${self%/*}/droiddeck-appimage-run} +headless=${DD_HEADLESS_RUN:-${self%/*}/droiddeck-headless} wait_s=${DD_CURSEFORGE_WAIT:-60} cmd=${1:-} dir=${2:-} flag=--inspect-publish-uid=stderr -case $cmd in start|hold|stop|display) ;; *) echo "usage: droiddeck-curseforge start|hold|stop|display " >&2; exit 2 ;; esac -if [ "$cmd" != display ] && [ ! -d "$dir/app" ]; then +case $cmd in start|stop) ;; *) echo "usage: droiddeck-curseforge start|stop " >&2; exit 2 ;; esac +if [ ! -d "$dir/app" ]; then echo "droiddeck-curseforge: $dir is not an imported AppImage" >&2 exit 2 fi -x_display() { - if [ -n "${DISPLAY:-}" ]; then - printf '%s\n%s\n' "$DISPLAY" "${XAUTHORITY:-}" - return 0 - fi - local p name a prev display auth - for p in "$proc"/[0-9]*; do - name=$(tr '\0' '\n' 2>/dev/null < "$p/cmdline" | head -n 1) - case ${name##*/} in Xwayland|Xorg|Xvfb) ;; *) continue ;; esac - display= auth= prev= - while IFS= read -r a; do - case $a in :[0-9]*) [ -z "$display" ] && display=$a ;; esac - [ "$prev" = -auth ] && auth=$a - prev=$a - done < <(tr '\0' '\n' 2>/dev/null < "$p/cmdline") - if [ -n "$display" ]; then - printf '%s\n%s\n' "$display" "$auth" - return 0 - fi - done - return 1 -} - running() { local p for p in "$proc"/[0-9]*; do @@ -79,7 +57,7 @@ inspector() { } start() { - local shown display auth url pid + local url pid child= lock || { echo "droiddeck-curseforge: cannot lock $state" >&2; return 5; } if ! ours >/dev/null; then if tracked >/dev/null || running; then @@ -87,18 +65,18 @@ start() { echo busy return 3 fi - shown=$(x_display) || { exec 9>&-; echo "no X display" >&2; return 4; } - display=$(sed -n 1p <<<"$shown") - auth=$(sed -n 2p <<<"$shown") - env -u DBUS_SESSION_BUS_ADDRESS -u WAYLAND_DISPLAY -u GAMESCOPE_WAYLAND_DISPLAY DISPLAY="$display" ${auth:+XAUTHORITY="$auth"} \ - setsid "$runner" "$dir" --minimized --inspect=127.0.0.1:0 "$flag" "$state/log" 2>&1 9>&- & + mv -f "$state/log" "$state/log.1" 2>/dev/null + env -u DBUS_SESSION_BUS_ADDRESS setsid "$headless" "$state/runtime" --log "$state/log" -- \ + "$runner" "$dir" --minimized --inspect=127.0.0.1:0 "$flag" /dev/null 2>&1 9>&- & pid=$! + child=$pid printf '%s %s %s\n' "$pid" "$(started_at "$pid")" "$dir" > "$state/pid" fi exec 9>&- for _ in $(seq 1 $((wait_s * 2))); do if url=$(inspector); then echo "$url" + hold "$child" return 0 fi ours >/dev/null || break @@ -108,6 +86,18 @@ start() { return 5 } +hold() { + local pid + if [ -n "$1" ]; then + wait "$1" + return 0 + fi + pid=$(ours) || return 0 + while kill -0 "$pid" 2>/dev/null && [ "$(ours)" = "$pid" ]; do + sleep 1 + done +} + stop() { local pid p lock || return 1 @@ -118,6 +108,7 @@ stop() { sleep 0.5 done kill -KILL -- "-$pid" 2>/dev/null + kill -KILL "$pid" 2>/dev/null for p in "$proc"/[0-9]*; do tr '\0' '\n' 2>/dev/null < "$p/cmdline" | grep -qF -- "$dir/app/" && kill -KILL "${p##*/}" 2>/dev/null done @@ -127,22 +118,10 @@ stop() { } case $cmd in - display) - x_display || exit 4 - ;; start) start exit $? ;; - hold) - start >/dev/null || exit $? - trap 'stop; exit 0' TERM INT HUP - while ours >/dev/null; do - sleep 1 & - wait $! - done - exit 0 - ;; stop) stop exit 0 diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-headless b/tools/linuxfs/overlay/usr/local/bin/droiddeck-headless new file mode 100755 index 0000000000..c8bc6cee0b --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-headless @@ -0,0 +1,24 @@ +#!/bin/bash +set -u +runtime=${1:-} +shift +log= +if [ "${1:-}" = --log ]; then + log=${2:-} + shift 2 +fi +if [ -z "$runtime" ] || [ "${1:-}" != -- ] || [ $# -lt 2 ]; then + echo "usage: droiddeck-headless [--log ] -- [args...]" >&2 + exit 2 +fi +shift +umask 077 +mkdir -p "$runtime" && chmod 700 "$runtime" || exit 1 +if [ -n "$log" ]; then + size=$(stat -c %s "$log" 2>/dev/null || echo 0) + [ "$size" -gt "${DD_HEADLESS_LOG_LIMIT:-4194304}" ] && mv -f "$log" "$log.1" + exec >>"$log" 2>&1 +fi +unset DISPLAY WAYLAND_DISPLAY GAMESCOPE_WAYLAND_DISPLAY XAUTHORITY +export XDG_RUNTIME_DIR=$runtime +exec gamescope --backend headless -w 640 -h 480 -- "$@" diff --git a/tools/tests/test_battlenet.py b/tools/tests/test_battlenet.py index 52ba9e8d46..b7bbafa3b4 100644 --- a/tools/tests/test_battlenet.py +++ b/tools/tests/test_battlenet.py @@ -1413,7 +1413,8 @@ class AgentJobTest(Harness): self.assertEqual(code, 0) self.assertTrue(os.path.isdir(folder)) cmd = self.started[0] - self.assertEqual(cmd[:6], ["gamescope", "--backend", "headless", "-w", "640", "-h"]) + self.assertEqual(cmd[:4], ["/usr/local/bin/droiddeck-headless", str(self.tmp / "cache" / "agent-runtime"), "--log", + str(self.tmp / "cache" / "agent.log")]) self.assertEqual(cmd[cmd.index("--") + 2:-1], ["agent-serve", "install", "gryphon", "gryphon", "Z:" + folder, "enUS", "USA", "US"]) self.assertEqual([kind for kind, _ in self.lines], ["STATE", "PROGRESS", "DONE"]) self.assertEqual(json.loads(self.lines[-1][1]), {"install_dir": "Z:" + folder, "exe": "WarcraftRumble.exe", "version": "16.1.2.119725"}) @@ -1641,16 +1642,6 @@ class AgentJobTest(Harness): path.write_bytes(json.dumps({"state": 1004}).encode("utf-8")) self.assertEqual(BNET["read_status"](str(path)), {"state": 1004}) - def test_a_large_agent_log_is_rotated_before_a_job(self): - self.install() - os.makedirs(self.tmp / "cache") - log = self.tmp / "cache" / "agent.log" - log.write_bytes(b"x" * (BNET["AGENT_LOG_LIMIT"] + 1)) - self.files = {".game": json.dumps({"installed": False})} - BNET["agent_job"](self.root, "uninstall", "gryphon", poll=0) - self.assertEqual((self.tmp / "cache" / "agent.log.1").stat().st_size, BNET["AGENT_LOG_LIMIT"] + 1) - self.assertEqual(log.stat().st_size, 0) - def test_it_queues_behind_another_battle_net_job(self): self.install() self.files = {".game": json.dumps({"installed": False})} @@ -1681,13 +1672,11 @@ class AgentJobTest(Harness): self.assertEqual(self.lines[0], ("STATE", "waiting")) self.assertEqual(self.lines[1], ("STATE", "starting")) - def test_gamescope_gets_no_display_but_the_agent_keeps_the_one_gamescope_gives_it(self): + def test_the_agent_keeps_the_display_gamescope_gives_it_and_launches_through_the_shared_headless_helper(self): self.install() - os.environ.update(DISPLAY=":5", WAYLAND_DISPLAY="wayland-1") self.files = {".game": json.dumps({"installed": False})} BNET["agent_job"](self.root, "uninstall", "gryphon", poll=0) - self.assertNotIn("DISPLAY", self.envs[0]) - self.assertNotIn("WAYLAND_DISPLAY", self.envs[0]) + self.assertEqual(self.started[0][0], BNET["HEADLESS"]) self.assertEqual(self.envs[0]["PROTON_USE_XALIA"], "0") os.environ["DISPLAY"] = ":0" self.assertEqual(BNET["agent_env"]()["DISPLAY"], ":0") diff --git a/tools/tests/test_curseforge_helper.py b/tools/tests/test_curseforge_helper.py index 4dd25790db..e65388405d 100644 --- a/tools/tests/test_curseforge_helper.py +++ b/tools/tests/test_curseforge_helper.py @@ -1,17 +1,67 @@ import os import shlex import shutil -import signal import subprocess import tempfile import time import unittest from pathlib import Path -HELPER = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-curseforge" +BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin" +HELPER = BIN / "droiddeck-curseforge" +HEADLESS = BIN / "droiddeck-headless" URL = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e" +class HeadlessTest(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.tmp, True) + self.bin = self.tmp / "bin" + self.bin.mkdir() + self.seen = self.tmp / "seen" + gamescope = self.bin / "gamescope" + gamescope.write_text( + "#!/bin/bash\n" + "printf '%%s\\n' \"DISPLAY=${DISPLAY-}\" \"WAYLAND=${WAYLAND_DISPLAY-}\" \"GAMESCOPE=${GAMESCOPE_WAYLAND_DISPLAY-}\" " + "\"XAUTH=${XAUTHORITY-}\" \"RUNTIME=$XDG_RUNTIME_DIR\" \"$@\" > %s\n" + "echo logged-by-gamescope\n" % shlex.quote(str(self.seen))) + gamescope.chmod(0o755) + + def env(self, extra=None): + base = dict(os.environ, PATH="%s:%s" % (self.bin, os.environ["PATH"]), DISPLAY=":0", WAYLAND_DISPLAY="wayland-0", + GAMESCOPE_WAYLAND_DISPLAY="gamescope-0", XAUTHORITY="/run/xauth") + base.update(extra or {}) + return base + + def run_headless(self, *args, env=None): + return subprocess.run(["bash", str(HEADLESS), *args], env=self.env(env), capture_output=True, text=True, timeout=30) + + def test_it_runs_the_command_in_headless_gamescope_with_a_private_runtime_and_no_session_display(self): + runtime = self.tmp / "runtime" + out = self.run_headless(str(runtime), "--", "prog", "arg one") + self.assertEqual(0, out.returncode, out.stderr) + self.assertEqual(["DISPLAY=", "WAYLAND=", "GAMESCOPE=", "XAUTH=", "RUNTIME=%s" % runtime, "--backend", "headless", + "-w", "640", "-h", "480", "--", "prog", "arg one"], self.seen.read_text().splitlines()) + self.assertEqual(0o700, runtime.stat().st_mode & 0o777) + + def test_output_goes_to_the_log_which_rotates_when_large(self): + log = self.tmp / "agent.log" + log.write_bytes(b"x" * 100) + self.assertEqual(0, self.run_headless(str(self.tmp / "r"), "--log", str(log), "--", "prog").returncode) + self.assertTrue(log.read_text().endswith("logged-by-gamescope\n")) + self.assertEqual(100, log.stat().st_size - len("logged-by-gamescope\n")) + self.assertFalse((self.tmp / "agent.log.1").exists()) + self.run_headless(str(self.tmp / "r"), "--log", str(log), "--", "prog", env={"DD_HEADLESS_LOG_LIMIT": "50"}) + self.assertEqual(100 + len("logged-by-gamescope\n"), (self.tmp / "agent.log.1").stat().st_size) + self.assertEqual("logged-by-gamescope\n", log.read_text()) + + def test_bad_arguments_are_refused(self): + self.assertEqual(2, self.run_headless(str(self.tmp / "r"), "prog").returncode) + self.assertEqual(2, self.run_headless(str(self.tmp / "r"), "--").returncode) + self.assertEqual(2, self.run_headless().returncode) + + class CurseForgeHelperTest(unittest.TestCase): def setUp(self): self.tmp = Path(tempfile.mkdtemp()) @@ -21,18 +71,23 @@ class CurseForgeHelperTest(unittest.TestCase): self.dir = self.tmp / "curseforge" (self.dir / "app").mkdir(parents=True) self.state = self.tmp / "state" + self.bin = self.tmp / "bin" + self.bin.mkdir() self.runner = self.tmp / "runner" self.seen = self.tmp / "seen" self.runner.write_text( "#!/bin/bash\n" - "printf '%%s\\n' \"DISPLAY=$DISPLAY\" \"XAUTHORITY=${XAUTHORITY-}\" \"WAYLAND=${WAYLAND_DISPLAY-}\" " - "\"DBUS=${DBUS_SESSION_BUS_ADDRESS-}\" \"$@\" > %s\n" + "printf '%%s\\n' \"DISPLAY=${DISPLAY-}\" \"WAYLAND=${WAYLAND_DISPLAY-}\" \"DBUS=${DBUS_SESSION_BUS_ADDRESS-}\" " + "\"RUNTIME=$XDG_RUNTIME_DIR\" \"$@\" > %s\n" "mkdir -p %s/$$ && printf '%%s\\0' bash \"$0\" \"$@\" > %s/$$/cmdline\n" - "echo 'Debugger listening on %s'\n" - "echo 'For help, see: https://nodejs.org/en/docs/inspector'\n" - "exec sleep 60\n" + "echo 'Debugger listening on %s' >&2\n" + "echo 'For help, see: https://nodejs.org/en/docs/inspector' >&2\n" + "sleep 60\n" % (shlex.quote(str(self.seen)), shlex.quote(str(self.proc)), shlex.quote(str(self.proc)), URL)) self.runner.chmod(0o755) + gamescope = self.bin / "gamescope" + gamescope.write_text('#!/bin/bash\nwhile [ "$1" != -- ]; do shift; done\nshift\n"$@"\n') + gamescope.chmod(0o755) def fake(self, pid, *argv): d = self.proc / str(pid) @@ -40,15 +95,27 @@ class CurseForgeHelperTest(unittest.TestCase): (d / "cmdline").write_bytes(b"".join(a.encode() + b"\0" for a in argv)) def env(self, extra=None): - base = {k: v for k, v in os.environ.items() if k not in ("DISPLAY", "XAUTHORITY")} - base.update(DD_PROC=str(self.proc), DD_CURSEFORGE_STATE=str(self.state), DD_APPIMAGE_RUN=str(self.runner), - DD_CURSEFORGE_WAIT="10", WAYLAND_DISPLAY="wayland-0", DBUS_SESSION_BUS_ADDRESS="unix:path=/x") + base = dict(os.environ, PATH="%s:%s" % (self.bin, os.environ["PATH"]), DD_PROC=str(self.proc), + DD_CURSEFORGE_STATE=str(self.state), DD_APPIMAGE_RUN=str(self.runner), DD_HEADLESS_RUN=str(HEADLESS), + DD_CURSEFORGE_WAIT="10", DISPLAY=":0", WAYLAND_DISPLAY="wayland-0", XDG_RUNTIME_DIR="/run/user/session", + DBUS_SESSION_BUS_ADDRESS="unix:path=/x") base.update(extra or {}) return base def run_helper(self, *args, env=None): return subprocess.run(["bash", str(HELPER), *args], env=self.env(env), capture_output=True, text=True, timeout=60) + def launch(self, directory=None): + holder = subprocess.Popen(["bash", str(HELPER), "start", str(directory or self.dir)], env=self.env(), + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + self.addCleanup(self.finish, holder) + return holder, holder.stdout.readline().strip() + + def finish(self, holder): + if holder.poll() is None: + holder.kill() + holder.communicate() + def stop(self): self.run_helper("stop", str(self.dir)) @@ -64,86 +131,56 @@ class CurseForgeHelperTest(unittest.TestCase): time.sleep(0.1) return False - def test_the_desktop_x_display_is_found_from_xwayland(self): - self.fake(40, "/usr/bin/kwin_wayland", ":9") - self.fake(41, "/usr/bin/Xwayland", ":0", "-rootless", "-auth", "/run/droiddeck/xauth_abc", "-listenfd", "5") - out = self.run_helper("display", "") - self.assertEqual(0, out.returncode, out.stderr) - self.assertEqual([":0", "/run/droiddeck/xauth_abc"], out.stdout.splitlines()) - - def test_the_session_display_wins(self): - self.fake(41, "/usr/bin/Xwayland", ":3") - out = self.run_helper("display", "", env={"DISPLAY": ":0"}) - self.assertEqual(":0", out.stdout.splitlines()[0]) - - def test_no_display_is_reported(self): - out = self.run_helper("start", str(self.dir)) - self.assertEqual(4, out.returncode) - def test_a_running_instance_without_the_inspector_is_busy(self): self.fake(50, "/usr/bin/FEX", str(self.dir) + "/app/curseforge", "--no-sandbox") - out = self.run_helper("start", str(self.dir), env={"DISPLAY": ":0"}) + out = self.run_helper("start", str(self.dir)) self.assertEqual(3, out.returncode) self.assertEqual("busy", out.stdout.strip()) self.stop() self.assertTrue((self.proc / "50").exists()) - def test_start_uses_a_random_port_and_a_secret_inspector_url_kept_private(self): - self.fake(41, "/usr/bin/Xwayland", ":0", "-auth", "/run/droiddeck/xauth_abc") - out = self.run_helper("start", str(self.dir)) + def test_start_runs_the_app_in_headless_gamescope_with_a_secret_inspector_and_no_session_display(self): + holder, url = self.launch() self.addCleanup(self.stop) - self.assertEqual(0, out.returncode, out.stderr) - self.assertEqual(URL, out.stdout.strip()) + self.assertEqual(URL, url) seen = self.seen.read_text().splitlines() - self.assertEqual(["DISPLAY=:0", "XAUTHORITY=/run/droiddeck/xauth_abc", "WAYLAND=", "DBUS=", str(self.dir), - "--minimized", "--inspect=127.0.0.1:0", "--inspect-publish-uid=stderr"], seen) + self.assertEqual(["DISPLAY=", "WAYLAND=", "DBUS=", "RUNTIME=%s/runtime" % self.state, str(self.dir), "--minimized", + "--inspect=127.0.0.1:0", "--inspect-publish-uid=stderr"], seen) self.assertEqual(0o700, self.state.stat().st_mode & 0o777) + self.assertEqual(0o700, (self.state / "runtime").stat().st_mode & 0o777) self.assertEqual(0o600, (self.state / "log").stat().st_mode & 0o777) - again = self.run_helper("start", str(self.dir)) - self.assertEqual(URL, again.stdout.strip()) - pid = self.pid() + _, again = self.launch() + self.assertEqual(URL, again) + + def test_start_holds_the_app_until_it_is_stopped(self): + holder, url = self.launch() + self.assertEqual(URL, url) + app = self.pid() + time.sleep(1) + self.assertIsNone(holder.poll()) + os.kill(app, 0) + self.stop() + self.assertEqual(0, holder.wait(timeout=30)) + self.assertTrue(self.gone(app), "the app is still running") + + def test_stop_ends_the_app_and_the_gamescope_it_ran_in(self): + (self.bin / "gamescope").write_text('#!/bin/bash\nwhile [ "$1" != -- ]; do shift; done\nshift\n"$@" &\nwait\n') + self.assertEqual(URL, self.launch()[1]) + gamescope = self.pid() + app = int(next(self.proc.iterdir()).name) + self.assertNotEqual(gamescope, app) + os.kill(app, 0) self.stop() self.assertFalse((self.state / "pid").exists()) - self.assertTrue(self.gone(pid), "the started instance is still running") + self.assertTrue(self.gone(gamescope), "gamescope is still running") + self.assertTrue(self.gone(app), "the app is still running") - def test_hold_keeps_the_app_until_it_is_signalled(self): - held = subprocess.Popen(["bash", str(HELPER), "hold", str(self.dir)], env=self.env({"DISPLAY": ":0"}), - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - self.addCleanup(self.end, held) - for _ in range(100): - if (self.state / "pid").exists() and self.seen.exists(): - break - time.sleep(0.1) - pid = self.pid() - time.sleep(1) - self.assertIsNone(held.poll()) - held.send_signal(signal.SIGTERM) - self.assertEqual(0, held.wait(timeout=30)) - self.assertTrue(self.gone(pid), "hold left the app running") - self.assertFalse((self.state / "pid").exists()) - - def end(self, held): - if held.poll() is None: - held.send_signal(signal.SIGTERM) - try: - held.wait(timeout=15) - except subprocess.TimeoutExpired: - held.kill() - held.wait() - record = self.state / "pid" - if record.exists(): - try: - os.killpg(self.pid(), signal.SIGKILL) - except (ProcessLookupError, PermissionError): - pass - - def test_a_launch_for_another_directory_is_busy(self): + def test_a_launch_for_another_directory_is_busy_and_left_alone(self): other = self.tmp / "other" (other / "app").mkdir(parents=True) - first = self.run_helper("start", str(self.dir), env={"DISPLAY": ":0"}) self.addCleanup(self.stop) - self.assertEqual(0, first.returncode, first.stderr) - out = self.run_helper("start", str(other), env={"DISPLAY": ":0"}) + self.assertEqual(URL, self.launch()[1]) + out = self.run_helper("start", str(other)) self.assertEqual(3, out.returncode) self.assertEqual("busy", out.stdout.strip()) pid = self.pid() @@ -151,22 +188,25 @@ class CurseForgeHelperTest(unittest.TestCase): self.assertEqual(pid, self.pid()) os.kill(pid, 0) - def test_hold_ends_when_the_app_exits(self): - proc = shlex.quote(str(self.proc)) - self.runner.write_text("#!/bin/bash\nmkdir -p %s/$$ && printf '%%s\\0' bash \"$0\" \"$@\" > %s/$$/cmdline\n" - "echo 'Debugger listening on %s'\nsleep 2\nrm -r %s/$$\n" % (proc, proc, URL, proc)) - out = subprocess.run(["bash", str(HELPER), "hold", str(self.dir)], env=self.env({"DISPLAY": ":0"}), - capture_output=True, text=True, timeout=60) - self.assertEqual(0, out.returncode, out.stderr) + def test_each_launch_starts_a_fresh_log(self): + first, _ = self.launch() + self.stop() + first.wait(timeout=30) + self.addCleanup(self.stop) + self.assertEqual(URL, self.launch()[1]) + self.assertEqual(1, (self.state / "log").read_text().count("Debugger listening")) + self.assertTrue((self.state / "log.1").exists()) def test_stop_without_a_launch_is_quiet(self): out = self.run_helper("stop", str(self.dir)) self.assertEqual(0, out.returncode) self.assertEqual("", out.stderr) + self.assertEqual("", out.stdout) def test_bad_arguments_are_refused(self): self.assertEqual(2, self.run_helper("start", str(self.tmp / "missing")).returncode) self.assertEqual(2, self.run_helper("launch", str(self.dir)).returncode) + self.assertEqual(2, self.run_helper("hold", str(self.dir)).returncode) if __name__ == "__main__": diff --git a/tools/tests/test_droiddeck_agent.py b/tools/tests/test_droiddeck_agent.py index 6bf1b0da8c..72931860b7 100644 --- a/tools/tests/test_droiddeck_agent.py +++ b/tools/tests/test_droiddeck_agent.py @@ -348,6 +348,28 @@ class AgentTest(unittest.TestCase): self.assertEqual("INVALID_TARGET", caught.exception.code) connect.assert_not_called() + def test_one_shot_inspector_eval_prints_the_session_answer_without_a_launch_dir(self): + import contextlib + import io + url = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e" + seen = {} + + def evaluate(agent_dir, expression, target=None, await_promise=True, timeout=15, inspector=None, command_line_api=False): + seen.update(expression=expression, timeout=timeout, inspector=inspector, api=command_line_api) + return {"target": "inspector", "type": "string", "value": "ok", "description": None} + + out = io.StringIO() + with patch.dict(os.environ, {}, clear=False), patch.object(agent, "cdp_eval", evaluate), contextlib.redirect_stdout(out): + os.environ.pop("DD_LAUNCH_DIR", None) + self.assertEqual(0, agent.main(["--cdp-inspector", url, "12.5", "1 + 1"])) + self.assertEqual({"target": "inspector", "type": "string", "value": "ok", "description": None, "ok": True}, json.loads(out.getvalue())) + self.assertEqual({"expression": "1 + 1", "timeout": 12.5, "inspector": url, "api": True}, seen) + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.assertEqual(0, agent.main(["--cdp-inspector", "ws://example.com:9229/x", "5", "1"])) + self.assertEqual("INVALID_REQUEST", json.loads(out.getvalue())["error"]["code"]) + self.assertEqual(2, agent.main(["--cdp-inspector", url])) + def test_a_devtools_endpoint_lost_while_sending_is_reported_as_gone(self): class Lost: def __init__(self, *args, **kwargs): diff --git a/tools/tests/test_fex_signal_syscall_state.py b/tools/tests/test_fex_signal_syscall_state.py new file mode 100644 index 0000000000..1aaa03feb3 --- /dev/null +++ b/tools/tests/test_fex_signal_syscall_state.py @@ -0,0 +1,76 @@ +import platform +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +FEX = Path(__file__).resolve().parents[1] / "fex" +PATCH = FEX / "patches/0008-signal-return-restores-syscall-state.patch" +PROBE = FEX / "probes/async-signal-context.c" +RESTORE = "Frame->InSyscallInfo = Context->InSyscallInfo;" + + +def hunks(): + text = PATCH.read_text() + files = re.findall(r"^diff --git a/(\S+) ", text, re.M) + return files, re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", text, re.M) + + +class SignalReturnSyscallStateTest(unittest.TestCase): + def test_only_the_signal_delegator_changes(self): + files, found = hunks() + self.assertEqual(files, ["Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp"]) + self.assertEqual(len(found), 1) + + def test_every_guest_frame_return_restores_the_interrupted_syscall_state(self): + _, found = hunks() + function, body = found[0] + self.assertIn("SignalDelegator::RestoreThreadState", function) + lines = body.splitlines() + added = [line[1:].strip() for line in lines if line.startswith("+")] + removed = [line for line in lines if line.startswith("-")] + self.assertEqual(added, [RESTORE]) + self.assertEqual(removed, []) + context = [line[1:].strip() for line in lines] + guest_frame = context.index("if (Context->UContextLocation) {") + self.assertEqual(context[guest_frame + 1], "auto Frame = Thread->CurrentFrame;") + self.assertEqual(context[guest_frame + 2], RESTORE) + self.assertLess(context.index(RESTORE), context.index("if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {")) + + def test_thread_pause_returns_are_untouched(self): + _, found = hunks() + body = found[0][1] + self.assertNotIn("TYPE_PAUSE", "".join(line for line in body.splitlines() if line.startswith("+"))) + + def test_patch_is_applied_to_every_release(self): + self.assertNotIn("Fixed-upstream", PATCH.read_text()) + self.assertIn("tools/fex/patches/*.patch", (FEX / "build-in-arch.sh").read_text()) + + +@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code") +class AsyncSignalContextProbeTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang") + if not compiler: + raise unittest.SkipTest("no C compiler") + cls.tmp = Path(tempfile.mkdtemp(prefix="fex-async-signal-")) + cls.binary = cls.tmp / "probe" + subprocess.run([compiler, "-O2", "-pthread", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def test_native_kernel_reports_the_interrupted_registers(self): + result = subprocess.run([str(self.binary), "500"], capture_output=True, text=True, timeout=120) + self.assertEqual(result.returncode, 0, result.stdout) + counts = dict(part.split("=") for part in result.stdout.split()) + self.assertGreaterEqual(int(counts["matched"]), 500) + self.assertEqual(counts["stale"], "0") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_hdr_live_switch.py b/tools/tests/test_hdr_live_switch.py index 41e30ebc76..4468be5048 100644 --- a/tools/tests/test_hdr_live_switch.py +++ b/tools/tests/test_hdr_live_switch.py @@ -43,15 +43,11 @@ class HdrLiveSwitchTest(unittest.TestCase): def test_the_gate_follows_the_display_not_the_setting(self): text = (APP / "SessionActivity.kt").read_text() start = text.index("val attached = CompositorHost.isStarted") - block = text[start:text.index("CompositorHost.start(", start)] + block = text[start:text.index("DriverSetupLog.write", start)] request = block[block.index("nativeSetHdrRequest("):block.index("Log.i", block.index("nativeSetHdrRequest("))] - self.assertNotIn("SessionPrefs.hdr", block) + self.assertNotIn("SessionPrefs.hdr", block[:block.index("if (!SessionState.running)")]) self.assertIn("capable, false", request) - self.assertIn("if (!SessionState.running) CompositorHost.applyHdr(this, mode)", block) - host = (APP / "wayland/CompositorHost.kt").read_text() - gate = host[host.index("fun applyHdr("):] - gate = gate[:gate.index("\n }")] - self.assertIn("SessionState.hdrCapable && SessionPrefs.hdr(context, mode)", gate) + self.assertIn("SessionState.hdrCapable && SessionPrefs.hdr(this, mode)", block) def test_both_switches_apply_to_the_running_session(self): helper = (APP / "session/SessionHdr.kt").read_text() From 101139ec9912e6f92676eb0a91dbdb1287dde969 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:44:14 -0500 Subject: [PATCH 049/141] feat(runtime): run the Linux side without proot by default (#3041) --- app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt | 2 +- .../main/java/com/droiddeck/launcher/session/SessionPrefs.kt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index eb9d67c1e4..6f09160282 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -187,7 +187,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(false) + private var nativeUserland by mutableStateOf(true) private var cursorComposite by mutableStateOf(false) private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME) private var phantomWarning by mutableStateOf(null) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 0ff3d76e38..1928588c13 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -1011,7 +1011,7 @@ object SessionPrefs { prefs(context).edit().putBoolean("prootNoSeccomp", on).apply() } - fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", false) + fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", true) fun setNativeUserland(context: Context, on: Boolean) { prefs(context).edit().putBoolean("nativeUserland", on).apply() From f43cc43d05d80a90341e3f1412cb2302bc24d709 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:27:28 -0500 Subject: [PATCH 050/141] fix(ui): the empty Steam page's ball bounces edge to edge, and the logo traces in around it on the slam (#3050) --- .../droiddeck/launcher/ui/LauncherPreviews.kt | 1 + .../com/droiddeck/launcher/ui/EmptyLibrary.kt | 103 +++++++++++------- .../com/droiddeck/launcher/ui/LiftSheet.kt | 3 +- .../com/droiddeck/launcher/ui/SteamHome.kt | 4 +- 4 files changed, 69 insertions(+), 42 deletions(-) diff --git a/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt b/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt index e0003e1348..681b32a10b 100644 --- a/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt +++ b/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt @@ -15,6 +15,7 @@ private fun Launcher(tab: String, games: List Unit)? = null, fade: @Composable () -> Unit) { - val clock = rememberMarkClock(avoid) - Box(Modifier.fillMaxSize().onSizeChanged { clock.page = Size(it.width.toFloat(), it.height.toFloat()) }) { + 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()) }, + ) { 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 @@ -82,8 +93,7 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock { val haptics = LocalHapticFeedback.current val keepOff by rememberUpdatedState(avoid) val speed = with(LocalDensity.current) { 64.dp.toPx() } - val inset = with(LocalDensity.current) { 10.dp.toPx() } - val clearance = with(LocalDensity.current) { 16.dp.toPx() } + val clearance = with(LocalDensity.current) { 4.dp.toPx() } LaunchedEffect(clock) { var last = -1L var vx = speed * 0.8f @@ -109,16 +119,28 @@ 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.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) } + 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) } keepOff?.inflate(clearance)?.let { r -> - 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) + 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 (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) } } @@ -294,30 +316,33 @@ private fun Mark(clock: MarkClock) { } else 0f translate(0f, shake) { - 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)) + 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)) + } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt b/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt index 88b32cf5de..920bb7f7f0 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt @@ -189,6 +189,7 @@ 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 = {}, ) { @@ -573,7 +574,7 @@ internal fun LiftHero( } } - Column(Modifier.align(Alignment.BottomStart).padding(start = start, bottom = bottom, end = 20.dp)) { + Column(Modifier.align(Alignment.BottomStart).padding(start = start, bottom = bottom, end = 20.dp).onGloballyPositioned { onTextBounds(it.boundsInRoot()) }) { Box(Modifier.graphicsLayer { alpha = 1f - wallSink() }) { words() } Spacer(Modifier.height(18.dp)) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt index 20dd2c2807..f9c81f4e42 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt @@ -140,6 +140,7 @@ 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( @@ -160,13 +161,12 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier) IntegrationSuggestion(s.integration, { a.onSteamIntegration(null) }, a.onDismissIntegration) } if (narrow) Column( - verticalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.onPlaced { words = it.boundsInParent() }, + verticalArrangement = Arrangement.spacedBy(12.dp), ) { Wordmark(30.dp) runtimeStatus() } else Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), - modifier = Modifier.onPlaced { words = it.boundsInParent() }, ) { Wordmark(if (narrow) 30.dp else 40.dp) runtimeStatus() From 84c877813f4fb41865e84dbd11653fcf0738a632 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Mon, 23 Nov 2026 03:15:53 -0500 Subject: [PATCH 051/141] fix(addons): CurseForge rows follow CurseForge's own installed list (#3042) * fix(addons): CurseForge rows follow CurseForge's own installed list The CurseForge source reads installed state and available updates from CurseForge's installed projects after asking it to rescan the game instance, so addons removed from disk show Install again and out of date ones show Update, which updates through CurseForge. Deleting an addon from the addon list uninstalls it through CurseForge when CurseForge manages it, so its list and the files stay in step. * Delete addons through CurseForge only while it is already linked * Link CurseForge on the Addons tab and give its rows Update and Uninstall * Match WoWInterface addons to the AddOns folders on disk The WoWInterface source now reads each addon's folder list and marks it installed when every folder is on disk, whichever source installed it. Deletes from that source go through CurseForge while it is linked. * Fix Compose tests hanging after a dropped UI dispatch and stop CurseForge on tab dispose A non-Compose test that runs the real App after a Compose test in the same Robolectric sandbox leaves AndroidUiDispatcher flagged as scheduled while its looper message is dropped by the sandbox reset, so global snapshot changes are never applied and every later Compose test times out waiting for idle. The shared compose rule now detects that state and re-arms the dispatcher. CurseLink.close runs the stop on a job owned by the link, so the tab test can join it and prove no CurseForge work remains after the tab is disposed. * Match add-on folders by case, offer only real updates, settle deletes on disk A delete that CurseForge finished before its link dropped now counts as done when the folder is already gone. Managed uninstalls only consider projects whose folders are all present, and folder names resolve case-insensitively everywhere. Update is offered only for a newer version, falling back to the source's current file when versions do not compare. The test compose rule also re-posts a dropped frame dispatch. --- .../droiddeck/launcher/FrontEndActivity.kt | 2 +- .../launcher/runtime/CurseForgeApp.kt | 68 ++++- .../launcher/runtime/WowAddonCatalog.kt | 36 ++- .../droiddeck/launcher/runtime/WowAddons.kt | 7 + .../com/droiddeck/launcher/ui/AddonBrowser.kt | 217 +++++++++++--- .../com/droiddeck/launcher/ui/GameDetail.kt | 43 ++- .../launcher/runtime/CurseForgeAppTest.kt | 275 +++++++++++++++++- .../launcher/runtime/WowAddonCatalogTest.kt | 34 ++- .../com/droiddeck/launcher/ui/AddonRowTest.kt | 94 ++++++ .../droiddeck/launcher/ui/CurseLinkTabTest.kt | 193 ++++++++++++ .../launcher/ui/RobolectricComposeRule.kt | 45 +++ .../launcher/ui/RobolectricComposeRuleTest.kt | 90 ++++++ 12 files changed, 1029 insertions(+), 75 deletions(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/ui/AddonRowTest.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/ui/RobolectricComposeRuleTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index 6f09160282..1c0d4f8ef9 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -1531,7 +1531,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.runtime.WowAddons.delete(target, name) + com.droiddeck.launcher.ui.deleteAddon(this, target, name) getString(R.string.main_addons_deleted, name) } }, diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt b/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt index adc2119889..a5fb9a4a40 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt @@ -4,6 +4,7 @@ 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 @@ -18,11 +19,14 @@ object CurseForgeApp { 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, 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) { @@ -141,9 +145,23 @@ object CurseForgeApp { return detected?.takeIf { it.isNotBlank() } } - internal fun projectIds(value: Any?): Set { - val list = value as? JSONArray ?: return emptySet() - return (0 until list.length()).mapNotNull { list.opt(it)?.toString()?.takeIf { id -> id.isNotBlank() && id != "null" } }.toSet() + internal fun parseProjects(value: Any?): List { + 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, folder: String): Project? = + projects.firstOrNull { project -> project.folders.any { it.equals(folder, ignoreCase = true) } } + + internal fun byFolder(projects: List): Map = projects.flatMap { project -> project.folders.map { it.lowercase() to project } }.toMap() + + internal fun onDisk(projects: List, addOns: File): List { + 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, AtomicBoolean?, (String) -> Unit) -> Int = { context, argv, cancelled, onLine -> @@ -232,22 +250,44 @@ object CurseForgeApp { 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 installed(context: Context, inspector: String, guid: String): Set { + fun projects(context: Context, inspector: String, guid: String, rescan: Boolean = false): List { connect(context, inspector) - return projectIds(call(context, inspector, "InstalledProjectsAppService", "getProjects", JSONArray().put(guid), 30_000, "r => (r || []).map(p => String(p.id))")) + 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) -> Boolean): Boolean { + 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 true } + Thread.sleep(1_000) + } + return false } fun install(context: Context, inspector: String, guid: String, projectId: String): Boolean { connect(context, inspector) if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return false - val deadline = System.currentTimeMillis() + INSTALL_MS - while (System.currentTimeMillis() < deadline) { - val listed = runCatching { installed(context, inspector, guid) } - val error = listed.exceptionOrNull() - if (error is Failure && error.gone) throw error - if (projectId in listed.getOrDefault(emptySet())) return true - Thread.sleep(1_000) - } - return false + return settle(context, inspector, guid) { list -> list.any { it.id == projectId } } + } + + fun update(context: Context, inspector: String, guid: String, projectId: String): Boolean { + connect(context, inspector) + if (call(context, inspector, "InstalledProjectsAppService", "updateMod", JSONArray().put(guid).put(projectId.toLong()), 300_000) != true) return false + return settle(context, inspector, guid) { list -> list.any { it.id == projectId && !it.update } } + } + + fun uninstall(context: Context, inspector: String, guid: String, project: Project): Boolean { + 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 false + return settle(context, inspector, guid) { list -> list.none { it.id == project.id } } } } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddonCatalog.kt b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddonCatalog.kt index bca0627bec..5a0cf0bb98 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddonCatalog.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddonCatalog.kt @@ -29,6 +29,7 @@ object WowAddonCatalog { val downloads: Long, val updated: Long, val thumb: String?, + val folders: List = emptyList(), ) class Page(val items: List, val more: Boolean) @@ -114,9 +115,11 @@ 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, + o.optString("UIDownloadTotal").toLongOrNull() ?: 0L, o.optLong("UIDate"), thumb, folders, ) out.add(Entry(addon, o.optString("UICATID"), flavors, o.optString("UIDownloadMonthly").toLongOrNull() ?: 0L)) } @@ -241,9 +244,32 @@ object WowAddonCatalog { return details.version } - 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) + 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, 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 findUpdates(entries: List, installed: List): Map { @@ -253,7 +279,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 (sameVersion(version, latest.summary) || !seen.add(id)) null else item.name to latest + if (!offersUpdate(version, latest.summary, sameSource = true) || !seen.add(id)) null else item.name to latest }.toMap() } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt index 799cfe7717..b8a9367947 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt @@ -69,6 +69,13 @@ object WowAddons { target.addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") } .map { it.name }.sortedBy { it.lowercase() } + fun present(folders: List, 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 { val origins = origins(target) return installed(target).map { name -> diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt index 514677364c..ee4f5eb1db 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt @@ -37,6 +37,7 @@ 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 @@ -53,6 +54,7 @@ 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 @@ -60,6 +62,8 @@ 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 @@ -68,12 +72,16 @@ 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.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicReference private class AddonResults { val items = mutableStateListOf() @@ -83,23 +91,40 @@ private class AddonResults { var more by mutableStateOf(false) } -private enum class AddonStatus { INSTALL, UPDATE, INSTALLED } +internal enum class AddonStatus { INSTALL, UPDATE, INSTALLED } private enum class AddonSource { WOWI, CURSE } -private class CurseState(val notice: Int? = null) : Exception() +internal class CurseState(val notice: Int? = null) : Exception() -private class CurseLink(val app: UserApps.App) { +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() + private val scanLock = Object() + private val scans = HashMap>>() + var generation by mutableIntStateOf(0) + private set - fun call(context: Context, target: WowAddons.Target, block: (Linked) -> T): T { - val linked = synchronized(lock) { link(context, target) } + fun refresh() { + generation++ + } + + fun installed(context: Context, target: WowAddons.Target, key: Any): List = CurseForgeApp.onDisk( + synchronized(scanLock) { + scans[target.addOns.path]?.takeIf { it.first == key }?.second + ?: call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid, rescan = true) }.also { scans[target.addOns.path] = key to it } + }, + target.addOns, + ) + + fun 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) { @@ -107,22 +132,25 @@ private class CurseLink(val app: UserApps.App) { if (inspector == linked.inspector) { inspector = null guids.clear() + current.compareAndSet(this, null) } } throw e } } - private fun link(context: Context, target: WowAddons.Target): Linked { + private fun link(context: Context, target: WowAddons.Target, launch: Boolean): Linked { if (closed) throw CurseState() val url = inspector ?: run { - val launch = AtomicBoolean(false) - hold = launch + if (!launch) throw CurseState() + val hold = AtomicBoolean(false) + this.hold = hold if (closed) throw CurseState() - val done = CurseForgeApp.start(context, app, launch) + 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) @@ -138,23 +166,66 @@ private class CurseLink(val app: UserApps.App) { return Linked(url, guid) } - fun close(context: Context) { + fun uninstall(context: Context, target: WowAddons.Target, folder: String): Boolean = call(context, target, launch = false) { linked -> + val projects = CurseForgeApp.onDisk(CurseForgeApp.projects(context, linked.inspector, linked.guid), target.addOns) + val project = CurseForgeApp.owner(projects, folder) ?: return@call false + if (!CurseForgeApp.uninstall(context, linked.inspector, linked.guid, project)) throw CurseState() + true + } + + internal val stopped: Job get() = work + + fun close(context: Context): Job { closed = true - val launch = hold ?: return - Thread { - CurseForgeApp.stop(context, app, inspector, launch) + 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 } - }.start() + }.also { work.complete() } + } + + companion object { + private val current = AtomicReference() + + fun live(): CurseLink? = current.get() } } 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 = emptyMap(), val disk: Map = emptyMap()) @Composable -internal fun AddonBrowserDialog(targets: List, initial: WowAddons.Target, curseForge: UserApps.App?, onDismiss: () -> Unit) { +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, initial: WowAddons.Target, curseForge: UserApps.App?, link: CurseLink?, onDismiss: () -> Unit) { val context = LocalContext.current.applicationContext val scope = rememberCoroutineScope() val shown = rememberShown(onDismiss) @@ -164,11 +235,8 @@ internal fun AddonBrowserDialog(targets: List, initial: WowAdd var category by remember { mutableStateOf(null) } var sort by remember { mutableStateOf(WowAddonCatalog.Sort.POPULAR) } var source by remember { mutableStateOf(AddonSource.WOWI) } - val curse = if (source == AddonSource.CURSE) curseForge else null - val link = remember(curseForge?.key) { curseForge?.let(::CurseLink) } - DisposableEffect(link) { - onDispose { link?.close(context) } - } + val curse = if (source == AddonSource.CURSE && link != null) curseForge else null + LaunchedEffect(link) { link?.refresh() } var notice by remember { mutableStateOf(null) } var curseInstalls by remember { mutableIntStateOf(0) } val results = remember(text, category, sort, target, curse) { AddonResults() } @@ -178,20 +246,22 @@ internal fun AddonBrowserDialog(targets: List, initial: WowAdd value = withContext(Dispatchers.IO) { runCatching { WowAddonCatalog.categories(context) }.getOrDefault(emptyList()) } } val presentKey = curse to target.addOns - val snapshot by produceState(presentKey to emptyMap(), target.addOns, WowAddons.imports, curse, curseInstalls, results.items.isEmpty()) { + 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 value = key to withContext(Dispatchers.IO) { - if (curse != null && link != null) runCatching { link.call(context, into) { CurseForgeApp.installed(context, it.inspector, it.guid) }.associateWith { null } }.getOrDefault(emptyMap()) - else WowAddons.details(into).mapNotNull { item -> item.wowiId?.let { it to item.version } }.toMap() + if (curse != null && link != null) Present(curse = runCatching { + link.installed(context, into, scanKey).associate { it.id to curseMark(it) } + }.getOrDefault(emptyMap())) + else Present(disk = WowAddons.details(into).associateBy { it.name.lowercase() }) } } - val present = snapshot.second.takeIf { snapshot.first == presentKey } ?: emptyMap() + val present = snapshot.second.takeIf { snapshot.first == presentKey } ?: Present() fun status(addon: WowAddonCatalog.Addon): AddonStatus { - if (addon.id !in present) return AddonStatus.INSTALL - val have = present[addon.id] + 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 val latest = installed[installKey(addon, target)]?.takeIf { it.first == addon.summary }?.second ?: addon.summary - return if (have == null || latest.isBlank() || WowAddonCatalog.sameVersion(have, latest)) AddonStatus.INSTALLED else AddonStatus.UPDATE + return diskStatus(addon.folders, present.disk, latest, addon.id) } fun load(page: Int) { if (results.loading) return @@ -230,16 +300,23 @@ internal fun AddonBrowserDialog(targets: List, initial: WowAdd 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.call(context, into) { CurseForgeApp.install(context, it.inspector, it.guid, addon.id) } } } + val done = withContext(Dispatchers.IO) { + runCatching { + via.call(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 - if (ok) { - WowAddons.changed() - curseInstalls++ - } + 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) @@ -261,6 +338,32 @@ internal fun AddonBrowserDialog(targets: List, 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) via.call(context, into) { linked -> + CurseForgeApp.projects(context, linked.inspector, linked.guid).firstOrNull { it.id == addon.id }?.folders.orEmpty() + } else addon.folders + folders.forEach { name -> WowAddons.folder(into.addOns, name)?.let { deleteAddon(context, into, it.name, 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 grid = rememberLazyGridState() LaunchedEffect(results, grid) { @@ -342,7 +445,7 @@ internal fun AddonBrowserDialog(targets: List, 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) { install(addon) } + AddonRow(addon, status(addon), installing[key], if (addon.id == results.items.firstOrNull()?.id) Modifier.focusRequester(firstAction) else Modifier, { uninstall(addon) }) { install(addon) } } item(span = { GridItemSpan(maxLineSpan) }) { Column(Modifier.fillMaxWidth().padding(vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) { @@ -365,7 +468,22 @@ internal fun AddonBrowserDialog(targets: List, initial: WowAdd } @Composable -private fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progress: Int?, action: Modifier, onInstall: () -> Unit) { +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) val colors = MaterialTheme.colorScheme val pal = LocalPalette.current Row( @@ -383,13 +501,24 @@ private fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progress fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, ) } - val size = action + val uninstall = stringResource(R.string.common_uninstall) when { - 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) + 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 } + } } } + 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 { @@ -438,4 +567,16 @@ internal fun installAddon(context: Context, addon: WowAddonCatalog.Addon, target } } +internal fun diskStatus(folders: List, onDisk: Map, 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 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 diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt index 447d3ef73f..5f9d6d0ebc 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt @@ -295,7 +295,7 @@ internal fun GameDetail( 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.ADDONS -> if (game != null) AddonsTab(game, addonTargets, s.sessionRunning, a) GameTab.INSTALL -> InstallTab(game, installed, item, store) } } @@ -1047,9 +1047,11 @@ private fun SavesTab(g: Library.SteamGame, prefix: File, a: FrontEndActions) { } @Composable -private fun AddonsTab(g: Library.SteamGame, targets: List, a: FrontEndActions) { +private fun AddonsTab(g: Library.SteamGame, targets: List, sessionRunning: Boolean, a: FrontEndActions) { var browsing by remember(g.gameId) { mutableStateOf(null) } - browsing?.let { AddonBrowserDialog(targets, it, CurseForgeApp.find(UserAppsState.items)) { browsing = null } } + val curseForge = CurseForgeApp.find(UserAppsState.items) + val link = rememberCurseLink(curseForge, sessionRunning) + browsing?.let { AddonBrowserDialog(targets, it, curseForge, link) { browsing = null } } Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) { CurseForgeEntry(a) targets.forEach { target -> @@ -1060,6 +1062,12 @@ private fun AddonsTab(g: Library.SteamGame, targets: List, a: val updates by produceState(emptyMap(), names) { value = withContext(Dispatchers.IO) { WowAddonCatalog.updates(context, names, target) } } + val scanKey = link?.generation to WowAddons.imports + val managed by produceState(emptyMap(), 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( @@ -1070,7 +1078,7 @@ private fun AddonsTab(g: Library.SteamGame, targets: List, a: target.addOns.mkdirs() a.onBrowseFiles(target.addOns) } - names.forEach { item -> key(target.addOns, item.name) { AddonRow(item, updates[item.name], target, a) } } + 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 } }) } } } } } @@ -1124,8 +1132,10 @@ private fun CurseForgeEntry(a: FrontEndActions) { } @Composable -private fun AddonRow(item: WowAddons.Installed, update: WowAddonCatalog.Addon?, target: WowAddons.Target, a: FrontEndActions) { +internal fun AddonRow(item: WowAddons.Installed, wowiUpdate: WowAddonCatalog.Addon?, target: WowAddons.Target, a: FrontEndActions, curse: Pair? = null) { 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(null) } val context = LocalContext.current @@ -1135,26 +1145,33 @@ private fun AddonRow(item: WowAddons.Installed, update: WowAddonCatalog.Addon?, 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, update?.let { stringResource(R.string.upd_available) }).joinToString(" · ") + val detail = listOfNotNull(item.version, if (outdated) stringResource(R.string.upd_available) else null).joinToString(" · ") if (detail.isNotEmpty()) Text( progress?.let { stringResource(R.string.ctrl_percent, it) } ?: detail, fontSize = 12.sp, - color = if (update != null) LocalPalette.current.signal else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, + color = if (outdated) LocalPalette.current.signal else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, ) } - if (update != null && !SessionState.running) IconAction(Icons.Outlined.Download, stringResource(R.string.common_update), "addon:update:${target.flavor}:$name", enabled = progress == null) { + if (outdated && !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) { installAddon(context, update, target) { pct -> scope.launch { progress = pct } } } + val message = withContext(Dispatchers.IO) { + if (curse != null) { + val (project, link) = curse + val done = runCatching { link.call(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 } + } progress = null - android.widget.Toast.makeText(context, message.first, android.widget.Toast.LENGTH_LONG).show() + if (message != null) android.widget.Toast.makeText(context, message, android.widget.Toast.LENGTH_LONG).show() } } - if (!SessionState.running) IconAction(Icons.Outlined.Delete, delete, "addon:delete:${target.flavor}:$name", danger = true) { asking = true } + 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 (asking) ConfirmDialog( - title = stringResource(R.string.games_delete_addon_title, name), + title = if (curse != null) stringResource(R.string.stores_uninstall_title, name) else stringResource(R.string.games_delete_addon_title, name), text = stringResource(R.string.games_delete_addon_body), - confirm = delete, + confirm = if (curse != null) stringResource(R.string.common_uninstall) else delete, onConfirm = { a.onAddonDelete(target, name) }, onDismiss = { asking = false }, ) diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt index e3cb7ef501..47d892993b 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt @@ -166,9 +166,16 @@ class CurseForgeAppTest { } @Test - fun installedIdsAndExitCodes() { - assertEquals(setOf("486246", "2"), CurseForgeApp.projectIds(JSONArray("""["486246","2",null]"""))) - assertEquals(emptySet(), CurseForgeApp.projectIds(JSONObject())) + fun installedProjectsAndExitCodes() { + val projects = CurseForgeApp.parseProjects(JSONArray("""[ + {"id":"486246","installedModId":"a_486246","status":3,"locked":false,"folders":["RXPGuides","RXPGuides_Extra"]}, + {"id":"2","installedModId":"b_2","status":2,"locked":true,"folders":[]}, + {"id":null}]""")) + assertEquals(listOf("486246", "2"), projects.map { it.id }) + assertEquals("486246", CurseForgeApp.owner(projects, "RXPGuides_Extra")?.id) + assertNull(CurseForgeApp.owner(projects, "TomTom")) + assertFalse(projects[1].update) + assertTrue(CurseForgeApp.parseProjects(JSONObject()).isEmpty()) assertEquals(CurseForgeApp.Start.READY, CurseForgeApp.startState(0)) assertEquals(CurseForgeApp.Start.BUSY, CurseForgeApp.startState(3)) assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.startState(4)) @@ -293,6 +300,268 @@ class CurseForgeAppTest { assertTrue(!GuestCommand.redacted(url, CurseForgeApp.INSPECTOR).contains(url)) } + private class Curse(val addOns: File, val flavor: String = "") { + val projects = java.util.concurrent.CopyOnWriteArrayList() + val methods = java.util.Collections.synchronizedList(mutableListOf()) + @Volatile var unreachableAfterDelete = false + @Volatile var unreachable = false + + fun add(id: String, folder: String, status: Int) = add(id, listOf(folder), status) + + fun add(id: String, folders: List, status: Int, onDisk: List = folders) { + onDisk.forEach { File(addOns, it).mkdirs() } + projects += JSONObject().put("id", id).put("installedModId", "m_$id").put("status", status).put("locked", false).put("folders", JSONArray(folders)) + } + + private fun folders(p: JSONObject) = (0 until p.getJSONArray("folders").length()).map { p.getJSONArray("folders").getString(it) } + + fun answer(expression: String): Any? { + val method = Regex("s\\[\\\\\"(\\w+)\\\\\"\\]").find(expression)?.groupValues?.get(1) ?: return true + methods += method + return when (method) { + "scanGameInstance" -> { + projects.removeAll { p -> !File(addOns, p.getJSONArray("folders").getString(0)).isDirectory } + true + } + "getProjects" -> JSONArray(projects.map { JSONObject(it.toString()) }) + "updateMod" -> { + projects.forEach { it.put("status", 1) } + true + } + "detectGameFromPath" -> JSONObject().put("gameInstanceGuid", "g") + "getGameInstances" -> JSONArray().put(JSONObject().put("guid", "g").put("installPath", flavor)) + "deleteMods" -> { + projects.removeAll { p -> + (p.getString("installedModId") in expression).also { gone -> + if (gone) folders(p).forEach { name -> WowAddons.folder(addOns, name)?.deleteRecursively() } + } + } + if (unreachableAfterDelete) unreachable = true + JSONArray() + } + else -> true + } + } + } + + private fun fakeCurse(addOns: File = temp.newFolder("AddOns"), flavor: String = "", calls: MutableList> = mutableListOf()): Curse { + val curse = Curse(addOns, flavor) + CurseForgeApp.guest = { _, argv, cancelled, onLine -> + calls += argv + when { + argv[0] == CurseForgeApp.HELPER && argv[1] == "start" -> { + onLine(url) + while (cancelled?.get() != true) Thread.sleep(10) + 0 + } + argv[0] == CurseForgeApp.HELPER -> 0 + curse.unreachable -> { + onLine(JSONObject().put("ok", false).put("error", JSONObject().put("code", "DEVTOOLS_UNREACHABLE").put("message", "gone")).toString()) + 0 + } + else -> { + val value = JSONObject().put("value", curse.answer(argv[4]) ?: JSONObject.NULL) + onLine(JSONObject().put("ok", true).put("value", value.toString()).toString()) + 0 + } + } + } + return curse + } + + private fun wow(): WowAddons.Target { + val context = org.robolectric.RuntimeEnvironment.getApplication() + val games = temp.newFolder("Games") + val addOns = File(games, "World of Warcraft/_retail_/Interface/AddOns").apply { mkdirs() } + com.droiddeck.launcher.session.SessionPrefs.setGameFolderBinds(context, listOf(games.absolutePath to "/root/Games")) + return WowAddons.Target("_retail_", addOns) + } + + @Test + fun anEntryCurseForgeStillListsShowsAsNotInstalledOnceItsFolderIsGone() { + val curse = fakeCurse() + val context = org.robolectric.RuntimeEnvironment.getApplication() + curse.add("298842", "Leatrix_Maps", 1) + curse.add("18808", "TomTom", 1) + assertTrue(File(curse.addOns, "Leatrix_Maps").deleteRecursively()) + val listed = CurseForgeApp.projects(context, url, "g") + assertEquals(listOf("298842", "18808"), listed.map { it.id }) + assertEquals(listOf("18808"), CurseForgeApp.onDisk(listed, curse.addOns).map { it.id }) + } + + @Test + fun aProjectWithAnyFolderMissingOrNoFoldersIsNotInstalled() { + val addOns = temp.newFolder("Split") + File(addOns, "DBM-Core").mkdirs() + val split = CurseForgeApp.Project("3358", "m_3358", listOf("DBM-Core", "DBM-StatusBarTimers"), false) + val bare = CurseForgeApp.Project("1", "m_1", emptyList(), false) + assertTrue(CurseForgeApp.onDisk(listOf(split, bare), addOns).isEmpty()) + File(addOns, "DBM-StatusBarTimers").mkdirs() + assertEquals(listOf("3358"), CurseForgeApp.onDisk(listOf(split, bare), addOns).map { it.id }) + } + + @Test + fun aDeleteWhileCurseForgeIsLinkedGoesThroughItsUninstall() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + val target = wow() + val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_") + curse.add("298842", "Leatrix_Maps", 1) + curse.add("18808", "TomTom", 1) + val link = com.droiddeck.launcher.ui.CurseLink(app) + try { + link.call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid) } + assertTrue(com.droiddeck.launcher.ui.CurseLink.live() === link) + com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps") + assertTrue("deleteMods" in curse.methods) + assertFalse(File(target.addOns, "Leatrix_Maps").exists()) + assertEquals(listOf("18808"), CurseForgeApp.projects(context, url, "g").map { it.id }) + } finally { + link.close(context) + } + assertNull(com.droiddeck.launcher.ui.CurseLink.live()) + } + + @Test + fun aDeleteWithoutALiveLinkRemovesTheFolderAtOnceWithoutStartingCurseForge() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + val target = wow() + val calls = java.util.Collections.synchronizedList(mutableListOf>()) + val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_", calls) + curse.add("298842", "Leatrix_Maps", 1) + assertNull(com.droiddeck.launcher.ui.CurseLink.live()) + com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps") + assertFalse(File(target.addOns, "Leatrix_Maps").exists()) + assertTrue(calls.isEmpty()) + assertTrue(CurseForgeApp.projects(context, url, "g", rescan = true).none { it.id == "298842" }) + } + + @Test + fun aLinkThatNeverStartedIsNotUsedToDelete() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + val target = wow() + val calls = java.util.Collections.synchronizedList(mutableListOf>()) + val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_", calls) + curse.add("298842", "Leatrix_Maps", 1) + com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps", com.droiddeck.launcher.ui.CurseLink(app)) + assertFalse(File(target.addOns, "Leatrix_Maps").exists()) + assertTrue(calls.isEmpty()) + } + + @Test + fun anAddonWhoseFolderWasDeletedShowsAsNotInstalledAfterTheRescan() { + val curse = fakeCurse() + val context = org.robolectric.RuntimeEnvironment.getApplication() + curse.add("298842", "Leatrix_Maps", 1) + assertEquals(listOf("298842"), CurseForgeApp.projects(context, url, "g", rescan = true).map { it.id }) + assertTrue(File(curse.addOns, "Leatrix_Maps").deleteRecursively()) + assertTrue(CurseForgeApp.projects(context, url, "g").isNotEmpty()) + assertTrue(CurseForgeApp.projects(context, url, "g", rescan = true).isEmpty()) + assertTrue("scanGameInstance" in curse.methods) + } + + @Test + fun aNewerFileShowsAsAnUpdateUntilCurseForgeUpdatesIt() { + val curse = fakeCurse() + val context = org.robolectric.RuntimeEnvironment.getApplication() + curse.add("298842", "Leatrix_Maps", 2) + curse.add("18808", "TomTom", 1) + val before = CurseForgeApp.projects(context, url, "g", rescan = true).associate { it.id to it.update } + assertEquals(mapOf("298842" to true, "18808" to false), before) + assertTrue(CurseForgeApp.update(context, url, "g", "298842")) + assertTrue("updateMod" in curse.methods) + assertTrue(CurseForgeApp.projects(context, url, "g").none { it.update }) + } + + @Test + fun uninstallingThroughCurseForgeClearsItsListAndTheFolder() { + val curse = fakeCurse() + val context = org.robolectric.RuntimeEnvironment.getApplication() + curse.add("298842", "Leatrix_Maps", 1) + curse.add("18808", "TomTom", 1) + val project = CurseForgeApp.owner(CurseForgeApp.projects(context, url, "g"), "Leatrix_Maps")!! + assertTrue(CurseForgeApp.uninstall(context, url, "g", project)) + assertEquals(listOf("18808"), CurseForgeApp.projects(context, url, "g").map { it.id }) + assertFalse(File(curse.addOns, "Leatrix_Maps").exists()) + assertTrue(File(curse.addOns, "TomTom").isDirectory) + } + + @Test + fun anUninstallThatRemovedTheFolderBeforeCurseForgeWentAwayCountsAsDeleted() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + val target = wow() + val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_") + curse.add("298842", "Leatrix_Maps", 1) + curse.unreachableAfterDelete = true + val link = com.droiddeck.launcher.ui.CurseLink(app) + try { + link.call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid) } + val before = WowAddons.imports + com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps") + assertTrue("deleteMods" in curse.methods) + assertFalse(File(target.addOns, "Leatrix_Maps").exists()) + assertTrue(WowAddons.imports > before) + } finally { + kotlinx.coroutines.runBlocking { link.close(context).join() } + } + } + + @Test + fun aLocalDeleteInAProjectWithAMissingFolderKeepsItsOtherFolders() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + val target = wow() + val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_") + curse.add("3358", listOf("DBM-Core", "DBM-GUI", "DBM-StatusBarTimers"), 1, onDisk = listOf("DBM-Core", "DBM-GUI")) + curse.add("298842", "Leatrix_Maps", 1) + val link = com.droiddeck.launcher.ui.CurseLink(app) + try { + link.call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid) } + com.droiddeck.launcher.ui.deleteAddon(context, target, "DBM-Core") + assertFalse("deleteMods" in curse.methods) + assertFalse(File(target.addOns, "DBM-Core").exists()) + assertTrue(File(target.addOns, "DBM-GUI").isDirectory) + com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps") + assertTrue("deleteMods" in curse.methods) + assertFalse(File(target.addOns, "Leatrix_Maps").exists()) + } finally { + kotlinx.coroutines.runBlocking { link.close(context).join() } + } + } + + @Test + fun foldersMatchCurseForgesNamesWhateverTheirCase() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + val target = wow() + val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_") + curse.add("12345", listOf("Questie"), 1, onDisk = listOf("questie")) + val listed = CurseForgeApp.projects(context, url, "g") + assertEquals(listOf("12345"), CurseForgeApp.onDisk(listed, target.addOns).map { it.id }) + assertEquals("12345", CurseForgeApp.byFolder(listed)["questie"]?.id) + assertEquals("questie", WowAddons.folder(target.addOns, "Questie")?.name) + val link = com.droiddeck.launcher.ui.CurseLink(app) + try { + link.call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid) } + com.droiddeck.launcher.ui.deleteAddon(context, target, "Questie") + assertTrue("deleteMods" in curse.methods) + assertNull(WowAddons.folder(target.addOns, "Questie")) + } finally { + kotlinx.coroutines.runBlocking { link.close(context).join() } + } + } + + @Test + fun aLocalDeleteFindsTheFolderWhateverItsCaseAndAnAbsentFolderIsAlreadyDeleted() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + val target = wow() + File(target.addOns, "questie").mkdirs() + File(target.addOns, "TomTom").mkdirs() + com.droiddeck.launcher.ui.deleteAddon(context, target, "Questie", null) + assertNull(WowAddons.folder(target.addOns, "Questie")) + assertTrue(File(target.addOns, "TomTom").isDirectory) + val before = WowAddons.imports + com.droiddeck.launcher.ui.deleteAddon(context, target, "Gone", null) + assertTrue(WowAddons.imports > before) + } + @Test fun theAgentAnswerIsTheLastJsonLine() { assertEquals("a", CurseForgeApp.lastJson(listOf("noise", """{"v":"a"}""", "== done"))?.getString("v")) diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonCatalogTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonCatalogTest.kt index 451ec81bc3..e298c39822 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonCatalogTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonCatalogTest.kt @@ -15,7 +15,7 @@ class WowAddonCatalogTest { private val context get() = RuntimeEnvironment.getApplication() private val files = """[ - {"UID":"1","UICATID":"19","UIVersion":"1.0","UIDate":300,"UIName":"Bartender","UIAuthorName":"Nevcairiel","UIDownloadTotal":"500","UICompatibility":[{"version":"12.0.0","name":"Midnight"}],"UIIMG_Thumbs":["https://cdn.example/a.jpg"]}, + {"UID":"1","UICATID":"19","UIVersion":"1.0","UIDate":300,"UIName":"Bartender","UIAuthorName":"Nevcairiel","UIDownloadTotal":"500","UICompatibility":[{"version":"12.0.0","name":"Midnight"}],"UIIMG_Thumbs":["https://cdn.example/a.jpg"],"UIDir":["Bartender4"," Bartender4_Options "]}, {"UID":"2","UICATID":"20","UIVersion":"2.0","UIDate":100,"UIName":"Zygor","UIAuthorName":"Kappa","UIDownloadTotal":"900","UICompatibility":[{"version":"1.15.7","name":"Classic"},{"version":"4.4.2","name":"Cataclysm Classic"}],"UIIMG_Thumbs":null}, {"UID":"3","UICATID":"21","UIVersion":"3.0","UIDate":200,"UIName":"Alpha","UIAuthorName":"bartuser","UIDownloadTotal":"10","UIDownloadMonthly":"9","UICompatibility":null}, {"UID":"4","UICATID":"19","UIVersion":"4.0","UIDate":400,"UIName":"TBCOnly","UIAuthorName":"x","UIDownloadTotal":"20","UIDownloadMonthly":"5","UICompatibility":[{"version":"2.5.4","name":"The Burning Crusade Classic"}]} @@ -44,6 +44,12 @@ class WowAddonCatalogTest { assertEquals("19", e[0].category) } + @Test fun fileListEntriesCarryTheirAddonFolders() { + val e = WowAddonCatalog.parseWowiFiles(files) + assertEquals(listOf("Bartender4", "Bartender4_Options"), e[0].addon.folders) + assertEquals(emptyList(), e[1].addon.folders) + } + @Test fun versionsMapToFlavors() { assertEquals("_retail_", WowAddonCatalog.flavorOf("12.1.0")) assertEquals("_retail_", WowAddonCatalog.flavorOf("11.0.5")) @@ -198,6 +204,32 @@ us|1|aa|bb|cc||tpr/wow|h|s|t||1|12.1.0.65000|kk|wowf assertFalse(WowAddonCatalog.sameVersion("1.2.3", "1.2.4")) } + @Test fun versionsCompareNumericSegmentsFirst() { + assertEquals(true, WowAddonCatalog.newer("v4.11.38-7-ge56e9d8", "4.11.39")) + assertEquals(true, WowAddonCatalog.newer("1.9", "1.10")) + assertEquals(true, WowAddonCatalog.newer("2", "2.0.1")) + assertEquals(false, WowAddonCatalog.newer("11.2.0", "6.2.5")) + assertEquals(false, WowAddonCatalog.newer("2.0", "2")) + assertNull(WowAddonCatalog.newer("11.4.10-beta1", "11.4.10")) + assertNull(WowAddonCatalog.newer("release", "1.0")) + } + + @Test fun anUpdateIsOfferedOnlyForANewerVersionOrTheSameSourcesCurrentFile() { + assertTrue(WowAddonCatalog.offersUpdate("1.9", "1.10", sameSource = false)) + assertFalse(WowAddonCatalog.offersUpdate("11.2.0", "6.2.5", sameSource = true)) + assertFalse(WowAddonCatalog.offersUpdate("v1.2", "1.2", sameSource = true)) + assertTrue(WowAddonCatalog.offersUpdate("11.4.10-beta1", "11.4.10", sameSource = true)) + assertFalse(WowAddonCatalog.offersUpdate("11.4.10-beta1", "11.4.10", sameSource = false)) + assertFalse(WowAddonCatalog.offersUpdate(null, "1.0", sameSource = true)) + assertFalse(WowAddonCatalog.offersUpdate("1.0", "", sameSource = true)) + } + + @Test fun findUpdatesNeverOffersADowngrade() { + val installed = listOf(WowAddons.Installed("Ahead", "3.0", "10"), WowAddons.Installed("Tagged", "r55-alpha", "20")) + val updates = WowAddonCatalog.findUpdates(listOf(entry("10", "2.9"), entry("20", "r56")), installed) + assertEquals(setOf("Tagged"), updates.keys) + } + @Test fun md5Check() { val f = File(context.cacheDir, "wowaddon-md5-test.zip") f.writeText("hello") diff --git a/app/src/test/java/com/droiddeck/launcher/ui/AddonRowTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/AddonRowTest.kt new file mode 100644 index 0000000000..20ccd9c069 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/AddonRowTest.kt @@ -0,0 +1,94 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.assertCountEquals +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import com.droiddeck.launcher.R +import com.droiddeck.launcher.runtime.WowAddonCatalog +import com.droiddeck.launcher.runtime.WowAddons +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], qualifiers = "w960dp-h540dp-land", application = android.app.Application::class) +class AddonRowTest { + @get:Rule val compose = createRobolectricComposeRule() + + private val addon = WowAddonCatalog.Addon("298842", "Leatrix Maps", "Leatrix", "", 0, 0, null) + private fun text(id: Int) = RuntimeEnvironment.getApplication().getString(id) + + private fun show(status: AddonStatus, uninstalls: MutableList = mutableListOf(), installs: MutableList = mutableListOf()) { + val state = mutableStateOf(status) + compose.setContent { + DroidDeckTheme { + AddonRow(addon, state.value, null, Modifier, { uninstalls += addon.id }) { installs += addon.id } + } + } + } + + @Test fun aMissingAddonOffersOnlyInstall() { + val installs = mutableListOf() + show(AddonStatus.INSTALL, installs = installs) + compose.onAllNodesWithText(text(R.string.common_uninstall)).assertCountEquals(0) + compose.onAllNodesWithText(text(R.string.common_update)).assertCountEquals(0) + compose.onNodeWithText(text(R.string.store_install)).performClick() + assertEquals(listOf("298842"), installs) + } + + @Test fun aCurrentAddonOffersOnlyUninstallAfterAConfirm() { + val uninstalls = mutableListOf() + show(AddonStatus.INSTALLED, uninstalls) + compose.onAllNodesWithText(text(R.string.store_install)).assertCountEquals(0) + compose.onAllNodesWithText(text(R.string.common_update)).assertCountEquals(0) + compose.onAllNodesWithText(text(R.string.stores_installed_chip)).assertCountEquals(0) + compose.onNodeWithText(text(R.string.common_uninstall)).performClick() + assertEquals(emptyList(), uninstalls) + compose.onAllNodesWithText(text(R.string.common_uninstall))[1].performClick() + assertEquals(listOf("298842"), uninstalls) + } + + @Test fun anOutdatedAddonOffersUpdateAndUninstall() { + val installs = mutableListOf() + show(AddonStatus.UPDATE, installs = installs) + compose.onAllNodesWithText(text(R.string.common_uninstall)).assertCountEquals(1) + compose.onNodeWithText(text(R.string.common_update)).performClick() + assertEquals(listOf("298842"), installs) + } + + private fun disk(vararg addons: WowAddons.Installed) = addons.associateBy { it.name.lowercase() } + + @Test fun anotherSourcesAddonOnDiskIsUpdatableOnlyToANewerVersion() { + val onDisk = disk(WowAddons.Installed("Questie", "11.2.0", null), WowAddons.Installed("QuestieDB", null, null)) + assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("Questie"), onDisk, "6.2.5", "1")) + assertEquals(AddonStatus.UPDATE, diskStatus(listOf("Questie"), onDisk, "11.3.0", "1")) + assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("Questie"), onDisk, "v11.2.0", "1")) + assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("QuestieDB"), onDisk, "1.0", "1")) + } + + @Test fun anIncomparableVersionIsAnUpdateOnlyFromTheSameSource() { + val onDisk = disk(WowAddons.Installed("TomTom", "v4.0.1-release", "12")) + assertEquals(AddonStatus.UPDATE, diskStatus(listOf("TomTom"), onDisk, "v4.0.1-beta", "12")) + assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("TomTom"), onDisk, "v4.0.1-beta", "99")) + assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("TomTom"), onDisk, "4.0.0", "12")) + } + + @Test fun foldersOnDiskMatchWhateverTheirCase() { + val onDisk = disk(WowAddons.Installed("questie", "11.2.0", null)) + assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("Questie"), onDisk, "11.2.0", "1")) + } + + @Test fun anAddonCountsAsInstalledOnlyWhenEveryFolderIsOnDisk() { + val onDisk = disk(WowAddons.Installed("Bartender4", "4.19.2", null)) + assertEquals(AddonStatus.INSTALL, diskStatus(listOf("Bartender4", "Bartender4_Options"), onDisk, "4.19.2", "1")) + assertEquals(AddonStatus.INSTALL, diskStatus(emptyList(), onDisk, "4.19.2", "1")) + assertEquals(AddonStatus.INSTALL, diskStatus(listOf("TomTom"), onDisk, "4.4.1", "1")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt new file mode 100644 index 0000000000..39eb286fea --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt @@ -0,0 +1,193 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.test.assertCountEquals +import androidx.compose.ui.test.onAllNodesWithContentDescription +import com.droiddeck.launcher.R +import com.droiddeck.launcher.runtime.AppImageManager +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.SessionPrefs +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.withContext +import org.json.JSONArray +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import java.io.File +import java.util.Collections + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], qualifiers = "w960dp-h540dp-land", application = android.app.Application::class) +class CurseLinkTabTest { + @get:Rule val compose = createRobolectricComposeRule() + @get:Rule val temp = TemporaryFolder() + + private val original = CurseForgeApp.guest + private val url = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e" + private val app = UserApps.App("appimage:c", UserApps.Kind.APPIMAGE, "CurseForge", null, null, AppImageManager.LAUNCHER, listOf("/root/apps/curseforge"), feed = CurseForgeApp.FEED) + private val helper = Collections.synchronizedList(mutableListOf()) + private val methods = Collections.synchronizedList(mutableListOf()) + private val context get() = RuntimeEnvironment.getApplication() + + @After + fun restore() { + CurseForgeApp.guest = original + } + + private fun text(id: Int) = context.getString(id) + + private fun wow(): WowAddons.Target { + val games = temp.newFolder("Games") + val addOns = File(games, "World of Warcraft/_retail_/Interface/AddOns").apply { mkdirs() } + File(addOns, "Leatrix_Maps").mkdirs() + SessionPrefs.setGameFolderBinds(context, listOf(games.absolutePath to "/root/Games")) + CurseForgeApp.guest = { _, argv, cancelled, onLine -> + if (argv[0] == CurseForgeApp.HELPER) { + helper += argv[1] + if (argv[1] == "start") { + onLine(url) + while (cancelled?.get() != true) Thread.sleep(10) + } + 0 + } else { + val method = Regex("s\\[\\\\\"(\\w+)\\\\\"\\]").find(argv[4])?.groupValues?.get(1) + method?.let { methods += it } + val answer: Any = when (method) { + "detectGameFromPath" -> JSONObject().put("gameInstanceGuid", "g") + "getGameInstances" -> JSONArray().put(JSONObject().put("guid", "g").put("installPath", "/root/Games/World of Warcraft/_retail_")) + "getProjects" -> JSONArray().put(JSONObject().put("id", "298842").put("installedModId", "m").put("status", 1).put("locked", false).put("folders", JSONArray().put("Leatrix_Maps"))) + else -> true + } + onLine(JSONObject().put("ok", true).put("value", JSONObject().put("value", answer).toString()).toString()) + 0 + } + } + return WowAddons.Target("_retail_", addOns) + } + + @Test + fun theTabAndItsDialogShareOneCurseForgeThatStopsWhenTheTabLeaves() { + val target = wow() + val shown = mutableStateOf(true) + val seen = Collections.synchronizedList(mutableListOf>()) + var opened: CurseLink? = null + compose.setContent { + if (shown.value) { + val link = rememberCurseLink(app, sessionRunning = false) + opened = link + LaunchedEffect(link) { withContext(Dispatchers.IO) { link?.let { seen += it.installed(context, target, 0).map { p -> p.id } } } } + LaunchedEffect(link) { withContext(Dispatchers.IO) { link?.let { seen += it.installed(context, target, 0).map { p -> p.id } } } } + } + } + compose.waitUntil(20_000) { seen.size == 2 } + assertEquals(listOf(listOf("298842"), listOf("298842")), seen.toList()) + assertEquals(listOf("start"), helper.toList()) + assertEquals(1, methods.count { it == "scanGameInstance" }) + assertTrue(CurseLink.live() != null) + compose.runOnIdle { shown.value = false } + compose.waitForIdle() + compose.waitUntil(20_000) { "stop" in helper } + assertNull(CurseLink.live()) + assertTrue("shutdown" in methods) + assertEquals(1, helper.count { it == "start" }) + runBlocking { withTimeout(20_000) { opened!!.stopped.join() } } + compose.waitUntil(5_000) { Thread.getAllStackTraces().keys.none { it.isAlive && it.name.startsWith("curseforge") } } + val calls = helper.size + methods.size + Thread.sleep(1_500) + assertEquals(calls, helper.size + methods.size) + } + + @Test + fun aNewGenerationRescansButReusesTheRunningCurseForge() { + val target = wow() + val link = CurseLink(app) + try { + link.installed(context, target, 0) + link.installed(context, target, 0) + link.refresh() + link.installed(context, target, link.generation) + assertEquals(2, methods.count { it == "scanGameInstance" }) + assertEquals(1, helper.count { it == "start" }) + } finally { + runBlocking { link.close(context).join() } + } + } + + @Test + fun noCurseForgeStartsWhileASessionRuns() { + wow() + var link: CurseLink? = CurseLink(app) + compose.setContent { link = rememberCurseLink(app, sessionRunning = true) } + compose.waitForIdle() + assertNull(link) + assertTrue(helper.isEmpty()) + } + + @Test + fun aStaleEntryWhoseFolderIsGoneIsNotManaged() { + val target = wow() + assertTrue(File(target.addOns, "Leatrix_Maps").deleteRecursively()) + val link = CurseLink(app) + try { + assertTrue(link.installed(context, target, 0).isEmpty()) + } finally { + runBlocking { link.close(context).join() } + } + } + + private val actions = FrontEndActions( + onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, + onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, + onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, + onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, + onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, + onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, + ) + + private fun row(update: Boolean?, wowi: Boolean) { + val target = WowAddons.Target("_retail_", temp.newFolder("AddOns")) + val item = WowAddons.Installed("Leatrix_Maps", "1.60.35", null) + val newer = WowAddonCatalog.Addon("1", "Leatrix Maps", "Leatrix", "1.60.36", 0, 0, null).takeIf { wowi } + val curse = update?.let { CurseForgeApp.Project("298842", "m", listOf("Leatrix_Maps"), it) to CurseLink(app) } + compose.setContent { DroidDeckTheme { AddonRow(item, newer, target, actions, curse) } } + } + + @Test + fun aManagedRowWithAnUpdateOffersUpdateAndUninstall() { + row(update = true, wowi = false) + compose.onAllNodesWithContentDescription(text(R.string.common_update)).assertCountEquals(1) + compose.onAllNodesWithContentDescription(text(R.string.common_uninstall)).assertCountEquals(1) + compose.onAllNodesWithContentDescription(text(R.string.common_delete)).assertCountEquals(0) + } + + @Test + fun aCurrentManagedRowIgnoresOtherSourcesAndOffersOnlyUninstall() { + row(update = false, wowi = true) + compose.onAllNodesWithContentDescription(text(R.string.common_update)).assertCountEquals(0) + compose.onAllNodesWithContentDescription(text(R.string.common_uninstall)).assertCountEquals(1) + } + + @Test + fun anUnmanagedRowKeepsTheLocalUpdateAndDelete() { + row(update = null, wowi = true) + compose.onAllNodesWithContentDescription(text(R.string.common_update)).assertCountEquals(1) + compose.onAllNodesWithContentDescription(text(R.string.common_delete)).assertCountEquals(1) + compose.onAllNodesWithContentDescription(text(R.string.common_uninstall)).assertCountEquals(0) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/RobolectricComposeRule.kt b/app/src/test/java/com/droiddeck/launcher/ui/RobolectricComposeRule.kt index a26973f87e..ebe743b644 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/RobolectricComposeRule.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/RobolectricComposeRule.kt @@ -1,11 +1,15 @@ package com.droiddeck.launcher.ui import android.content.ComponentName +import android.os.Handler +import android.view.Choreographer import androidx.activity.ComponentActivity +import androidx.compose.ui.platform.AndroidUiDispatcher import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.runtime.snapshots.Snapshot import org.robolectric.RuntimeEnvironment import org.robolectric.Shadows.shadowOf +import kotlin.coroutines.ContinuationInterceptor fun createRobolectricComposeRule() = createComposeRule().also { RingVeil.reset() @@ -13,5 +17,46 @@ fun createRobolectricComposeRule() = createComposeRule().also { shadowOf(context.packageManager).addActivityIfNotPresent( ComponentName(context, ComponentActivity::class.java), ) + resumeDroppedUiDispatch() Snapshot.sendApplyNotifications() } + +internal class UiDispatch { + private val type = AndroidUiDispatcher::class.java + private val dispatcher = AndroidUiDispatcher.Main[ContinuationInterceptor] as AndroidUiDispatcher + private fun field(name: String) = type.getDeclaredField(name).apply { isAccessible = true } + val lock: Any = field("lock").get(dispatcher)!! + val handler = field("handler").get(dispatcher) as Handler + val choreographer = field("choreographer").get(dispatcher) as Choreographer + val callback: Any = field("dispatchCallback").get(dispatcher)!! + private val trampolineFlag = field("scheduledTrampolineDispatch") + private val frameFlag = field("scheduledFrameDispatch") + + fun trampolineDropped() = trampolineFlag.getBoolean(dispatcher) && !handler.hasMessages(0) + + fun frameDropped() = frameFlag.getBoolean(dispatcher) && !frameQueued() + + private fun frameQueued(): Boolean { + val queues = Choreographer::class.java.getDeclaredField("mCallbackQueues").apply { isAccessible = true }.get(choreographer) as Array<*> + return queues.any { queue -> + var record = queue?.let { q -> q.javaClass.getDeclaredField("mHead").apply { isAccessible = true }.get(q) } + var found = false + while (record != null && !found) { + val recordType = record.javaClass + found = recordType.getDeclaredField("action").apply { isAccessible = true }.get(record) === callback + record = recordType.getDeclaredField("next").apply { isAccessible = true }.get(record) + } + found + } + } +} + +internal fun uiDispatchDropped(): Boolean = UiDispatch().run { synchronized(lock) { trampolineDropped() || frameDropped() } } + +internal fun resumeDroppedUiDispatch() { + val ui = UiDispatch() + synchronized(ui.lock) { + if (ui.trampolineDropped()) ui.handler.post(ui.callback as Runnable) + if (ui.frameDropped()) ui.choreographer.postFrameCallback(ui.callback as Choreographer.FrameCallback) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/RobolectricComposeRuleTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/RobolectricComposeRuleTest.kt new file mode 100644 index 0000000000..22ee813a5b --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/RobolectricComposeRuleTest.kt @@ -0,0 +1,90 @@ +package com.droiddeck.launcher.ui + +import android.os.Looper +import android.view.Choreographer +import androidx.compose.runtime.MutableIntState +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.withFrameNanos +import androidx.compose.ui.platform.AndroidUiDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.launch +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import java.time.Duration + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], application = android.app.Application::class) +class RobolectricComposeRuleTest { + private fun dropPendingUiDispatch() { + val ui = UiDispatch() + ui.handler.removeCallbacksAndMessages(null) + dropPendingFrame() + } + + private fun dropPendingFrame() { + val ui = UiDispatch() + ui.choreographer.removeFrameCallback(ui.callback as Choreographer.FrameCallback) + } + + private fun awaitFrameAfterTrampoline(ran: MutableIntState) { + CoroutineScope(AndroidUiDispatcher.Main).launch { withFrameNanos { ran.intValue++ } } + shadowOf(Looper.getMainLooper()).runOneTask() + } + + @Test + fun uiWorkDroppedByAnEarlierTestsLooperResetRunsAgainForTheNextComposeTest() { + val ran = mutableIntStateOf(0) + CoroutineScope(AndroidUiDispatcher.Main).launch { ran.intValue++ } + dropPendingUiDispatch() + shadowOf(Looper.getMainLooper()).idle() + assertEquals(0, ran.intValue) + assertTrue(uiDispatchDropped()) + createRobolectricComposeRule() + shadowOf(Looper.getMainLooper()).idle() + assertEquals(1, ran.intValue) + assertFalse(uiDispatchDropped()) + } + + @Test + fun aDispatchStillQueuedIsLeftAlone() { + val ran = mutableIntStateOf(0) + CoroutineScope(AndroidUiDispatcher.Main).launch { ran.intValue++ } + assertFalse(uiDispatchDropped()) + resumeDroppedUiDispatch() + shadowOf(Looper.getMainLooper()).idle() + assertEquals(1, ran.intValue) + assertFalse(uiDispatchDropped()) + } + + @Test + fun aFrameDroppedAfterTheTrampolineDrainedRunsAgainForTheNextComposeTest() { + val ran = mutableIntStateOf(0) + awaitFrameAfterTrampoline(ran) + dropPendingFrame() + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(1)) + assertEquals(0, ran.intValue) + assertTrue(uiDispatchDropped()) + createRobolectricComposeRule() + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(1)) + assertEquals(1, ran.intValue) + assertFalse(uiDispatchDropped()) + } + + @Test + fun aFrameStillQueuedIsLeftAlone() { + val ran = mutableIntStateOf(0) + awaitFrameAfterTrampoline(ran) + assertEquals(0, ran.intValue) + assertFalse(uiDispatchDropped()) + resumeDroppedUiDispatch() + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(1)) + assertEquals(1, ran.intValue) + assertFalse(uiDispatchDropped()) + } +} From 43b17483fb63e8c636b11fe6ede4d490d95ce816 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Mon, 23 Nov 2026 04:00:04 -0500 Subject: [PATCH 052/141] fix(addons): read only the needed .toc fields instead of the whole file (#3056) Some addons keep their data as metadata lines in the .toc (one has a 57 MB .toc with 400k "## X-..." lines). Opening the Addons tab read the whole file into one string and kept every metadata line in a map, so each opening allocated 220-270 MB for a moment and could push the app past its heap limit. Stream the .toc line by line, keep only Version and X-WoWI-ID, and stop once both are found. --- .../droiddeck/launcher/runtime/WowAddons.kt | 15 +++++++---- .../launcher/runtime/WowAddonsTest.kt | 27 ++++++++++++++++++- 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt index b8a9367947..fcdb6525e6 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt @@ -45,6 +45,9 @@ object WowAddons { 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 val TOC_KEYS = setOf(TOC_VERSION, TOC_WOWI_ID) internal const val MAX_EXPANDED_BYTES = 4L * 1024 * 1024 * 1024 @@ -81,18 +84,20 @@ object WowAddons { return installed(target).map { name -> val toc = toc(File(target.addOns, name)) val origin = origins[name] - Installed(name, origin?.version ?: toc["Version"], origin?.id ?: toc["X-WoWI-ID"]) + Installed(name, origin?.version ?: toc[TOC_VERSION], origin?.id ?: toc[TOC_WOWI_ID]) } } - internal fun tocFields(text: String): Map { + internal fun tocFields(lines: Sequence, keys: Set = TOC_KEYS): Map { val out = LinkedHashMap() - for (raw in text.lineSequence()) { + for (raw in lines) { 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 (key.isNotEmpty() && value.isNotEmpty() && '@' !in value) out.putIfAbsent(key, value) + if (value.isNotEmpty() && '@' !in value) out[key] = value + if (out.size == keys.size) break } return out } @@ -102,7 +107,7 @@ object WowAddons { 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()) + return runCatching { main.bufferedReader().useLines { tocFields(it) } }.getOrDefault(emptyMap()) } internal fun parseOrigins(text: String): Map = text.lineSequence().mapNotNull { line -> diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsTest.kt index d64880e0d6..f1cee3d958 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsTest.kt @@ -220,12 +220,37 @@ class WowAddonsTest { } @Test fun tocFieldsReadVersionAndSourceIds() { - val fields = WowAddons.tocFields("\uFEFF## Interface: 110002\n## Title: Foo\n## Version: 1.4.2\n## X-WoWI-ID: 1234\n## Version: 9\n## X-Curse-Project-ID: @curse-id@\nFoo.lua\n") + val fields = WowAddons.tocFields("\uFEFF## Interface: 110002\n## Title: Foo\n## Version: 1.4.2\n## X-WoWI-ID: 1234\n## Version: 9\n## X-Curse-Project-ID: @curse-id@\nFoo.lua\n".lineSequence(), setOf("Version", "X-WoWI-ID", "X-Curse-Project-ID")) assertEquals("1.4.2", fields["Version"]) assertEquals("1234", fields["X-WoWI-ID"]) assertEquals(null, fields["X-Curse-Project-ID"]) } + @Test fun tocFieldsKeepOnlyTheRequestedKeysAndStopOnceFound() { + var read = 0 + val lines = sequence { + yield("## Version: 2.0") + yield("## X-WoWI-ID: 5") + repeat(100_000) { read++; yield("## X-Data-$it: payload") } + } + val fields = WowAddons.tocFields(lines) + assertEquals(mapOf("Version" to "2.0", "X-WoWI-ID" to "5"), fields) + assertEquals(0, read) + } + + @Test fun detailsSkipDataRowsInLargeTocs() { + val target = target() + val db = File(target.addOns, "BigDB").apply { mkdirs() } + File(db, "BigDB_Mists.toc").bufferedWriter().use { w -> + w.write("## Title: BigDB\nsrc\\main.lua\n") + repeat(50_000) { w.write("## X-Data-$it: ${"x".repeat(200)}\n") } + w.write("## Version: 3.1\n") + } + val details = WowAddons.details(target).single() + assertEquals("3.1", details.version) + assertEquals(null, details.wowiId) + } + @Test fun detailsUseTheTocAndTheRecordedSource() { val target = target() val foo = File(target.addOns, "Foo").apply { mkdirs() } From c78adda7ca3ec758aac73c219c9f4dec58fd8283 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Mon, 23 Nov 2026 05:57:05 -0500 Subject: [PATCH 053/141] fix(addons): show installed addons as installed while the manager rescans (#3057) * fix(addons): show installed addons as installed while the manager rescans Opening the download dialog starts a fresh scan of the addon manager's installed projects, and every row showed Install until it answered (about 20 s). Rows now start from the manager's last report, kept only for projects whose folders are all still on disk, and its new report takes over, Update state included. * fix(addons): match installed addons by their toc project id before the first report Before the addon manager has reported at all, a search row whose project id matches an installed addon's X-Curse-Project-ID shows as installed. Placeholder ids are ignored and the manager's report always takes over. * fix(addons): read toc fields from flavour tocs and keep known state when a scan fails An addon whose main toc is a stub keeps its version and project id in the flavour tocs, so missing fields are now filled from the next toc in order. A failed manager scan now falls back to the last known installed state instead of clearing it. --- .../droiddeck/launcher/runtime/WowAddons.kt | 27 +++++--- .../com/droiddeck/launcher/ui/AddonBrowser.kt | 24 +++++-- .../launcher/runtime/WowAddonsTest.kt | 29 +++++++- .../launcher/ui/CurseLinkReportTest.kt | 68 +++++++++++++++++++ .../droiddeck/launcher/ui/CurseLinkTabTest.kt | 14 ++++ 5 files changed, 148 insertions(+), 14 deletions(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/ui/CurseLinkReportTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt index fcdb6525e6..35536449ac 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt @@ -40,14 +40,15 @@ object WowAddons { class Addon(val name: String, val root: String) - class Installed(val name: String, val version: String?, val wowiId: String?) + class Installed(val name: String, val version: String?, val wowiId: String?, val curseId: String? = null) 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 val TOC_KEYS = setOf(TOC_VERSION, TOC_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 @@ -84,7 +85,7 @@ object WowAddons { 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]) + Installed(name, origin?.version ?: toc[TOC_VERSION], origin?.id ?: toc[TOC_WOWI_ID], toc[TOC_CURSE_ID]) } } @@ -103,11 +104,21 @@ object WowAddons { } private fun toc(folder: File): Map { - 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 { main.bufferedReader().useLines { tocFields(it) } }.getOrDefault(emptyMap()) + val tocs = folder.listFiles().orEmpty().filter { it.isFile && it.name.endsWith(".toc", ignoreCase = true) }.sortedWith( + compareBy( + { !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() + 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 } internal fun parseOrigins(text: String): Map = text.lineSequence().mapNotNull { line -> diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt index ee4f5eb1db..de9322f069 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt @@ -80,6 +80,7 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File +import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicReference @@ -118,11 +119,17 @@ internal class CurseLink(val app: UserApps.App) { fun installed(context: Context, target: WowAddons.Target, key: Any): List = CurseForgeApp.onDisk( synchronized(scanLock) { scans[target.addOns.path]?.takeIf { it.first == key }?.second - ?: call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid, rescan = true) }.also { scans[target.addOns.path] = key to it } + ?: 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 = + runCatching { installed(context, target, key).associate { it.id to curseMark(it) } }.getOrElse { lastReported(target) } + fun call(context: Context, target: WowAddons.Target, launch: Boolean = true, block: (Linked) -> T): T { val linked = synchronized(lock) { link(context, target, launch) } try { @@ -190,6 +197,16 @@ internal class CurseLink(val app: UserApps.App) { companion object { private val current = AtomicReference() + private val reported = ConcurrentHashMap>() + + fun lastReported(target: WowAddons.Target, disk: () -> List = { WowAddons.details(target) }): Map { + 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) { + reported[target.addOns.path] = projects + } fun live(): CurseLink? = current.get() } @@ -250,10 +267,9 @@ internal fun AddonBrowserDialog(targets: List, initial: WowAdd 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 = runCatching { - link.installed(context, into, scanKey).associate { it.id to curseMark(it) } - }.getOrDefault(emptyMap())) + if (curse != null && link != null) Present(curse = link.marks(context, into, scanKey)) else Present(disk = WowAddons.details(into).associateBy { it.name.lowercase() }) } } diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsTest.kt index f1cee3d958..6ea502407e 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsTest.kt @@ -231,10 +231,11 @@ class WowAddonsTest { val lines = sequence { yield("## Version: 2.0") yield("## X-WoWI-ID: 5") + yield("## X-Curse-Project-ID: 9") repeat(100_000) { read++; yield("## X-Data-$it: payload") } } val fields = WowAddons.tocFields(lines) - assertEquals(mapOf("Version" to "2.0", "X-WoWI-ID" to "5"), fields) + assertEquals(mapOf("Version" to "2.0", "X-WoWI-ID" to "5", "X-Curse-Project-ID" to "9"), fields) assertEquals(0, read) } @@ -254,15 +255,39 @@ class WowAddonsTest { @Test fun detailsUseTheTocAndTheRecordedSource() { val target = target() val foo = File(target.addOns, "Foo").apply { mkdirs() } - File(foo, "Foo_Mainline.toc").writeText("## Version: 1.0\n## X-WoWI-ID: 77\n") + File(foo, "Foo_Mainline.toc").writeText("## Version: 1.0\n## X-WoWI-ID: 77\n## X-Curse-Project-ID: 334372\n") File(target.addOns, "Bar").mkdirs() val details = WowAddons.details(target).associateBy { it.name } assertEquals(setOf("Bar", "Foo"), details.keys) assertEquals("1.0", details.getValue("Foo").version) assertEquals("77", details.getValue("Foo").wowiId) + assertEquals("334372", details.getValue("Foo").curseId) + assertEquals(null, details.getValue("Bar").curseId) assertEquals(null, details.getValue("Bar").version) } + @Test fun detailsFillFieldsTheMainTocLacksFromTheFlavourTocs() { + val target = target() + val questie = File(target.addOns, "Questie").apply { mkdirs() } + File(questie, "Questie.toc").writeText("## Interface: 00000\n## Title: Questie\n") + File(questie, "Questie_Vanilla.toc").writeText("## Version: 12.6.4\n## X-Curse-Project-ID: 334372\n") + File(questie, "Questie_Wrath.toc").writeText("## Version: 12.6.4\n") + val questieDetails = WowAddons.details(target).single() + assertEquals("12.6.4", questieDetails.version) + assertEquals("334372", questieDetails.curseId) + } + + @Test fun detailsKeepTheMainTocWhenItHasTheFields() { + val target = target() + val foo = File(target.addOns, "Foo").apply { mkdirs() } + File(foo, "Foo.toc").writeText("## Version: 2.0\n## X-Curse-Project-ID: 5\n") + File(foo, "Foo_Classic.toc").writeText("## Version: 1.0\n## X-Curse-Project-ID: 6\n## X-WoWI-ID: 7\n") + val fooDetails = WowAddons.details(target).single() + assertEquals("2.0", fooDetails.version) + assertEquals("5", fooDetails.curseId) + assertEquals("7", fooDetails.wowiId) + } + @Test fun importRecordsTheSourceAndPlainImportsClearIt() { val target = target() WowAddons.import(zip("Foo/Foo.toc" to "## Version: 1.0\n"), target, WowAddons.Origin("55", "2.0")) diff --git a/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkReportTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkReportTest.kt new file mode 100644 index 0000000000..7fee7a4f87 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkReportTest.kt @@ -0,0 +1,68 @@ +package com.droiddeck.launcher.ui + +import com.droiddeck.launcher.runtime.CurseForgeApp +import com.droiddeck.launcher.runtime.WowAddons +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class CurseLinkReportTest { + @get:Rule val temp = TemporaryFolder() + + private fun target(vararg folders: String): WowAddons.Target { + val addOns = temp.newFolder("AddOns") + folders.forEach { java.io.File(addOns, it).mkdirs() } + return WowAddons.Target("_retail_", addOns) + } + + private fun project(id: String, vararg folders: String, update: Boolean = false) = CurseForgeApp.Project(id, "m$id", folders.toList(), update) + + @Test fun beforeAnyReportNothingIsKnown() { + assertEquals(emptyMap(), CurseLink.lastReported(target("Questie"))) + } + + @Test fun beforeCurseForgeReportsAddonsWhoseFoldersAreAllOnDiskShowAsInstalled() { + val target = target("questie", "QuestieDB", "Auctionator") + CurseLink.report(target, listOf( + project("334372", "Questie", "QuestieDB", update = true), + project("1", "Auctionator"), + project("2", "Details", "Details_Streamer"), + project("3", "Auctionator", "Auctionator_Extra"), + )) + assertEquals(mapOf("334372" to null, "1" to null), CurseLink.lastReported(target)) + } + + @Test fun anAddonRemovedFromDiskSinceTheLastReportIsNotInstalled() { + val target = target("Questie") + CurseLink.report(target, listOf(project("334372", "Questie"))) + java.io.File(target.addOns, "Questie").delete() + assertEquals(emptyMap(), CurseLink.lastReported(target)) + } + + private fun toc(target: WowAddons.Target, folder: String, curseId: String) { + val dir = java.io.File(target.addOns, folder).apply { mkdirs() } + java.io.File(dir, "$folder.toc").writeText("## Interface: 110207\n## Title: $folder\n## X-Curse-Project-ID: $curseId\n$folder.lua\n") + } + + @Test fun beforeAnyReportAnAddonWhoseTocNamesTheProjectShowsAsInstalled() { + val target = target() + toc(target, "Questie", "334372") + toc(target, "Auctionator", "@project-id@") + assertEquals(mapOf("334372" to null), CurseLink.lastReported(target)) + } + + @Test fun aPlaceholderProjectIdIsIgnored() { + val target = target() + toc(target, "Auctionator", "@project-id@") + assertEquals(emptyMap(), CurseLink.lastReported(target)) + } + + @Test fun curseForgesReportOverridesTheTocProjectId() { + val target = target() + toc(target, "Questie", "334372") + toc(target, "Auctionator", "1") + CurseLink.report(target, listOf(project("1", "Auctionator", update = true))) + assertEquals(mapOf("1" to null), CurseLink.lastReported(target)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt index 39eb286fea..16d4c35e9c 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt @@ -128,6 +128,20 @@ class CurseLinkTabTest { } } + @Test + fun aFailedScanKeepsTheLastReportInsteadOfClearingIt() { + val target = wow() + val link = CurseLink(app) + try { + val reported = link.marks(context, target, 0) + assertTrue(reported.isNotEmpty()) + runBlocking { link.close(context).join() } + assertEquals(reported.mapValues { null }, link.marks(context, target, 1)) + } finally { + runBlocking { link.close(context).join() } + } + } + @Test fun noCurseForgeStartsWhileASessionRuns() { wow() From 6400a9ef098d2cd583e830e4ae1b07857c263522 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Mon, 23 Nov 2026 06:47:25 -0500 Subject: [PATCH 054/141] fix(addons): uninstall addons the manager has not listed yet (#3060) A row shown as installed by its toc project id before the manager's first report had nothing to delete when the manager did not list the project, and the dialog reported success. The dialog now falls back to the folders whose toc names the project, deletes them through the existing addon delete, and shows the delete error when no folder matches. --- .../com/droiddeck/launcher/ui/AddonBrowser.kt | 16 +++++-- .../droiddeck/launcher/ui/CurseLinkTabTest.kt | 46 +++++++++++++++++++ 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt index de9322f069..5251fb12bf 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt @@ -80,6 +80,7 @@ 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 @@ -367,10 +368,10 @@ internal fun AddonBrowserDialog(targets: List, initial: WowAdd scope.launch { val done = withContext(Dispatchers.IO) { runCatching { - val folders = if (via != null) via.call(context, into) { linked -> + 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 - folders.forEach { name -> WowAddons.folder(into.addOns, name)?.let { deleteAddon(context, into, it.name, link) } } + }) else addon.folders + deleteAddons(context, into, folders, link) } } installing.remove(key) @@ -589,6 +590,15 @@ internal fun diskStatus(folders: List, onDisk: Map): List = + listed.ifEmpty { WowAddons.details(target).filter { it.curseId == id }.map { it.name } } + +internal fun deleteAddons(context: Context, target: WowAddons.Target, folders: List, 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) diff --git a/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt index 16d4c35e9c..0ea4048e3a 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt @@ -19,7 +19,9 @@ import org.json.JSONArray import org.json.JSONObject import org.junit.After import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test @@ -29,6 +31,9 @@ import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config import java.io.File +import java.io.IOException +import java.nio.file.Files +import java.nio.file.LinkOption import java.util.Collections @RunWith(RobolectricTestRunner::class) @@ -142,6 +147,47 @@ class CurseLinkTabTest { } } + private fun tocFolder(addOns: File, name: String, curseId: String) = + File(addOns, name).apply { mkdirs(); File(this, "$name.toc").writeText("## X-Curse-Project-ID: $curseId\n") } + + @Test + fun anAddonTheManagerDoesNotListIsFoundByItsTocProjectId() { + val target = WowAddons.Target("_retail_", temp.newFolder("AddOns")) + tocFolder(target.addOns, "Questie", "334372") + tocFolder(target.addOns, "Other", "1") + assertEquals(listOf("Questie"), curseFolders(target, "334372", emptyList())) + assertEquals(listOf("Listed"), curseFolders(target, "334372", listOf("Listed"))) + } + + @Test + fun uninstallingByTocProjectIdDeletesOnlyTheMatchedFolders() { + val target = WowAddons.Target("_retail_", temp.newFolder("AddOns")) + tocFolder(target.addOns, "Questie", "334372") + tocFolder(target.addOns, "Other", "1") + deleteAddons(context, target, curseFolders(target, "334372", emptyList()), null) + assertEquals(listOf("Other"), WowAddons.installed(target)) + } + + @Test + fun uninstallingALinkedAddonLeavesTheLinkTargetAlone() { + val target = WowAddons.Target("_retail_", temp.newFolder("AddOns")) + val outside = tocFolder(temp.newFolder("outside"), "Questie", "334372") + File(outside, "keep.lua").writeText("keep") + Files.createSymbolicLink(File(target.addOns, "Questie").toPath(), outside.toPath()) + deleteAddons(context, target, curseFolders(target, "334372", emptyList()), null) + assertFalse(Files.exists(File(target.addOns, "Questie").toPath(), LinkOption.NOFOLLOW_LINKS)) + assertEquals("keep", File(outside, "keep.lua").readText()) + assertTrue(File(outside, "Questie.toc").isFile) + } + + @Test + fun uninstallingWithNothingToDeleteFails() { + val target = WowAddons.Target("_retail_", temp.newFolder("AddOns")) + tocFolder(target.addOns, "Other", "1") + assertThrows(IOException::class.java) { deleteAddons(context, target, curseFolders(target, "334372", emptyList()), null) } + assertEquals(listOf("Other"), WowAddons.installed(target)) + } + @Test fun noCurseForgeStartsWhileASessionRuns() { wow() From 2478c449482d247b0663a633f61db979b35cc784 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Mon, 23 Nov 2026 07:20:33 -0500 Subject: [PATCH 055/141] fix(fex): free host signal state when a guest leaves its handler (#3052) * fix(fex): free host signal state when a guest leaves its handler FEX keeps each signal's host context on the host stack and frees it only on rt_sigreturn. A guest that leaves its handler another way (siglongjmp, or CoreCLR resuming a catch after a NullReferenceException) left about 2 KB of host stack and one SignalHandlerRefCounter count behind. Some 3500 such exceptions on one thread overran the guard-less 8 MB host stack, and the CurseForge agent died with "Internal CLR error. (0x80131506)" and "Stack overflow occurred on the same thread again!" at the start of its second addon scan. 0009 chains each thread's signal frames with the guest frame range and alternate stack they used. A signal that arrives in JIT code at the host level of the newest frame, after the guest stack pointer has left that frame, drops the left frames and stores its context where the newest live frame (or the dispatcher entry) left the host stack. rt_sigreturn pops its frame and any newer ones it skips; thread stop clears the chain. Signals inside system calls or thunk callbacks are left alone. This follows the approach suggested in FEX-Emu/FEX#2487. 0008 now restores InSyscallInfo only for signals that interrupted JIT code, the only case that saves it. Restoring 0 for a signal that interrupted a system call cleared the mark while the call was still running; an itimer loop around time() crashed in 15 of 15 runs. Pocket FIT Elite: siglongjmp out of a SIGSEGV handler died after about 3500 iterations under FEX-2611.1 with and without 0008 and finishes 200000 with 0009; the new probe (350000 escapes on and off the alternate stack, mixed with returning handlers and nested handlers) finishes under 0009 and crashes before 2000 iterations without it. The 0008 probe still reports no stale registers. * test(fex): check every delivery hunk of the 0009 patch * fix(fex): reset the host stack when a system call ends a block * fix(fex): thunk calls mark the guest state as spilled * fix(fex): signal returns apply the handler's register changes * docs(fex): describe patches 0010 to 0012 and credit the upstream fix * test(fex): require AVX2 for the ymm probe and keep vdso canaries live --- README.md | 2 +- docs/development/x86-64-steam-client.md | 64 ++++++- ...signal-return-restores-syscall-state.patch | 16 +- ...gnal-handler-escape-frees-host-stack.patch | 174 ++++++++++++++++++ .../0010-syscall-exit-resets-host-stack.patch | 23 +++ .../0011-thunk-calls-mark-spilled-state.patch | 109 +++++++++++ ...ignal-return-applies-guest-registers.patch | 112 +++++++++++ tools/fex/probes/signal-handler-escape.c | 90 +++++++++ tools/fex/probes/signal-register-update.c | 88 +++++++++ tools/fex/probes/syscall-host-stack.c | 65 +++++++ tools/fex/probes/vdso-signal-state.c | 49 +++++ tools/tests/test_fex_signal_handler_escape.py | 117 ++++++++++++ .../tests/test_fex_signal_register_update.py | 134 ++++++++++++++ tools/tests/test_fex_signal_syscall_state.py | 12 +- tools/tests/test_fex_syscall_host_stack.py | 67 +++++++ tools/tests/test_fex_thunk_signal_state.py | 124 +++++++++++++ 16 files changed, 1234 insertions(+), 12 deletions(-) create mode 100644 tools/fex/patches/0009-signal-handler-escape-frees-host-stack.patch create mode 100644 tools/fex/patches/0010-syscall-exit-resets-host-stack.patch create mode 100644 tools/fex/patches/0011-thunk-calls-mark-spilled-state.patch create mode 100644 tools/fex/patches/0012-signal-return-applies-guest-registers.patch create mode 100644 tools/fex/probes/signal-handler-escape.c create mode 100644 tools/fex/probes/signal-register-update.c create mode 100644 tools/fex/probes/syscall-host-stack.c create mode 100644 tools/fex/probes/vdso-signal-state.c create mode 100644 tools/tests/test_fex_signal_handler_escape.py create mode 100644 tools/tests/test_fex_signal_register_update.py create mode 100644 tools/tests/test_fex_syscall_host_stack.py create mode 100644 tools/tests/test_fex_thunk_signal_state.py diff --git a/README.md b/README.md index b6f80f6220..a1094c8d14 100644 --- a/README.md +++ b/README.md @@ -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. +- [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). - 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//mem` the way [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` did before Wine 11. diff --git a/docs/development/x86-64-steam-client.md b/docs/development/x86-64-steam-client.md index 3d7876c2f5..d4b99759d5 100644 --- a/docs/development/x86-64-steam-client.md +++ b/docs/development/x86-64-steam-client.md @@ -228,7 +228,69 @@ alone would then read as an installed client. context, so x86-64 .NET programs failed at random (`AccessViolationException` in whatever code ran next, then SIGABRT). `tools/fex/probes/async-signal-context.c` shows it: under FEX-2611.1 one signal in 2000 carried the interrupted registers, natively all of them. The return now restores the value saved - when the signal arrived. + when the signal arrived, and only when the signal interrupted JIT code, which is the only case that + saves it. Restoring it for a signal that interrupted a system call cleared the mark while that call + was still running, so the next signal in the call's return path spilled clobbered registers: + `setitimer` at 100 Hz around `time()` crashed in 15 of 15 runs, and with the guard as often as the + same build without the patch (about half; a separate crash that FEX-2611.1 also shows). + - `0009-signal-handler-escape-frees-host-stack`: FEX keeps each signal's host context on the host + stack and frees it only on `rt_sigreturn`. A guest that leaves its handler another way (`siglongjmp`, + or CoreCLR resuming a `catch` after a NullReferenceException) left that 2 KB block and one + `SignalHandlerRefCounter` count behind. About 3500 such exceptions on one thread overran the 8 MB + host stack, which has no guard page, and the CurseForge agent died with "Internal CLR error. + (0x80131506)" and "Stack overflow occurred on the same thread again!" at the start of its second + addon scan. FEX now chains each thread's signal frames with the guest frame range and alternate + stack they used. When a signal arrives in JIT code that runs at the host level of the newest frame + and the guest stack pointer shows the guest has left that frame (above its frame, or back off the + alternate stack above where the outermost frame on it interrupted), the left frames are dropped and + the new context is stored where the newest live frame (or the dispatcher entry) left the host stack. + `rt_sigreturn` pops its frame and any newer ones it skips. Signals that arrive inside system calls or + thunk callbacks are left alone. `tools/fex/probes/signal-handler-escape.c` leaves handlers on and + off the alternate stack, mixes them with handlers that return, and leaves nested handlers: FEX-2611.1 + with 0001 to 0008 crashed (SIGSEGV) before 2000 iterations of it, and `siglongjmp` out of a SIGSEGV + handler died after about 3500; with this patch 350000 escapes and 200000 straight `siglongjmp`s + finish, as natively. The approach is the one suggested in FEX-Emu/FEX#2487. + - `0010-syscall-exit-resets-host-stack` (`Fixed-upstream: FEX-2612`): a backport of FEX's + "JIT: Ensure IR ops that jump out of the JIT reset the stack" (FEX-Emu/FEX#6122). A system call or + code-entry removal that ends a block jumps to the dispatcher without dropping the block's spill + slots, and the syscall handler's fast path branches straight into the next block, so every such + exit leaked up to 32 bytes per spill slot of host stack. AVX and MMX code keeps enough values live to + spill, and `tools/fex/probes/syscall-host-stack.c` overran the 8 MB host stack after about 65000 + system calls; with the patch 2000000 finish, as natively. The CPUID hunk of the upstream commit is + left out, since CPUID returns to the JIT in 2611. + - `0011-thunk-calls-mark-spilled-state`: a thunk call (every vDSO `clock_gettime`, `gettimeofday` + and `time`, and the host library thunks) spills the static registers to the guest frame and calls + host code, which clobbers the caller-saved host registers. A signal that arrived in the JIT code + after the host call returned and before the registers were refilled took the interrupted state from + those clobbered host registers: the guest handler got garbage registers, and the interrupted code + resumed with them, or FEX built the signal frame at a garbage stack pointer and crashed. The thunk + call now marks every static register as spilled (`InSyscallInfo = 0xFFFF`, as the system call + handler does) until the refill ends, and a fully spilled mark takes only RIP from the host PC and + leaves the frame's GPRs, vector registers and flags alone (the 16-bit mask could not name the + x16/x17 and v16 to v31 registers the host call clobbers). Every guest signal now saves and clears the + mark, so guest handlers and nested signals never inherit it, and every return puts back the value it + saved; 0008 restored it only for JIT code because the other paths saved none. A handler that changes + RIP restarts at the dispatcher with no mark, and thunk callbacks into guest code run with none. + `tools/fex/probes/vdso-signal-state.c` calls `clock_gettime` under a 1 kHz `SIGALRM` and checks the + values held across each call: FEX-2611 crashed in 3 of 8 runs, with 0001 to 0010 in 7 of 8; with + this patch 0 of 28, as natively. This was the "separate crash" noted under 0008. + - `0012-signal-return-applies-guest-registers`: a signal return that kept RIP threw away every + register change the guest handler made in its `ucontext`; only a changed RIP made FEX reload the + guest state from it. CoreCLR suspends threads for garbage collection with a signal and, in fully + interruptible code, runs the collection from that handler and writes the moved object references + back into the interrupted registers, so under FEX the thread resumed with pointers into the old heap. + The CurseForge agent's crashes during parallel addon scans (an `AccessViolationException` in + `Curse.Hashing.MurmurHash2.ComputeHash` or `RegexInterpreter`, or "Internal CLR error. (0x80131506)" + with a stack overflow) look like this, but they still happen with this patch, so it is not a fix for + them. When RIP is + unchanged, each guest GPR the handler changed is now written where the resumed code reads it: the + guest frame for registers the interrupted code had spilled (all of them inside a system call or + thunk call), otherwise the static host register. Unchanged registers are left alone, signals that + interrupted code outside the JIT (and not inside a system call or thunk call) keep the old + behaviour, and 32-bit frames compare and write only the low 32 bits. `tools/fex/probes/signal-register-update.c` + spins until a `SIGALRM` handler sets a register (R12, or ESI in 32-bit `rt` and legacy frames): + FEX-2611.1 with 0001 to 0011 never sees it in any of the three frame types, with this patch all + three see it on the first signal, as natively. - **Building and publishing.** Droid-Deck/DroidDeck-Components' `build-fex.yml` builds `tools/fex` from this repository at a chosen ref (default `main`) with host thunks, in the same Arch Linux ARM container with a read-only token, then a separate job replaces `fex.tzst` on Components' single `fex` release, diff --git a/tools/fex/patches/0008-signal-return-restores-syscall-state.patch b/tools/fex/patches/0008-signal-return-restores-syscall-state.patch index 6a8e14e1d0..6592a94550 100644 --- a/tools/fex/patches/0008-signal-return-restores-syscall-state.patch +++ b/tools/fex/patches/0008-signal-return-restores-syscall-state.patch @@ -1,12 +1,18 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp -index b4c7b24..e6777aa 100644 +index b4c7b24..643185d 100644 --- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp -@@ -262,6 +262,7 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr - - if (Context->UContextLocation) { +@@ -264,12 +264,13 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr auto Frame = Thread->CurrentFrame; -+ Frame->InSyscallInfo = Context->InSyscallInfo; if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) { // XXX: Unsupported since it needs state reconstruction + // If we are in the JIT then SRA might need to be restored to values from the context + // We can't currently support this since it might result in tearing without real state reconstruction ++ Frame->InSyscallInfo = Context->InSyscallInfo; + } + + if (Is64BitMode) { + RestoreFrame_x64(Thread, Context, Frame, ucontext); + } else { + if (Type == RestoreType::TYPE_NONREALTIME) { diff --git a/tools/fex/patches/0009-signal-handler-escape-frees-host-stack.patch b/tools/fex/patches/0009-signal-handler-escape-frees-host-stack.patch new file mode 100644 index 0000000000..fbeec5ec96 --- /dev/null +++ b/tools/fex/patches/0009-signal-handler-escape-frees-host-stack.patch @@ -0,0 +1,174 @@ +diff --git a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h +index 02bb6bf..2e72492 100644 +--- a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h ++++ b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h +@@ -49,6 +49,11 @@ struct X86ContextBackup { + uint64_t FPStateLocation; + uint64_t UContextLocation; + uint64_t SigInfoLocation; ++ uint64_t PrevGuestFrame; ++ uint64_t GuestFrameEnd; ++ uint64_t GuestInterruptedSP; ++ uint64_t GuestAltBase; ++ uint64_t GuestAltEnd; + FEXCore::Core::CPUState GuestState; + static constexpr int RedZoneSize = 128; + }; +@@ -76,6 +81,11 @@ struct ArmContextBackup { + uint64_t FPStateLocation; + uint64_t UContextLocation; + uint64_t SigInfoLocation; ++ uint64_t PrevGuestFrame; ++ uint64_t GuestFrameEnd; ++ uint64_t GuestInterruptedSP; ++ uint64_t GuestAltBase; ++ uint64_t GuestAltEnd; + FEXCore::Core::CPUState GuestState; + + // Arm64 doesn't have a red zone +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +index 643185d..53179c4 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +@@ -136,6 +136,31 @@ void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void* + #endif + } + ++namespace { ++ bool OnGuestAltStack(const ArchHelpers::Context::ContextBackup* Backup, uint64_t SP) { ++ return Backup->GuestAltEnd != 0 && SP >= Backup->GuestAltBase && SP <= Backup->GuestAltEnd; ++ } ++ ++ bool GuestLeftFrame(const ArchHelpers::Context::ContextBackup* Backup, uint64_t GuestSP, uint32_t Limit) { ++ const bool SPOnAlt = OnGuestAltStack(Backup, GuestSP); ++ if (SPOnAlt == OnGuestAltStack(Backup, Backup->GuestFrameEnd)) { ++ return GuestSP >= Backup->GuestFrameEnd; ++ } ++ if (SPOnAlt) { ++ return false; ++ } ++ auto Entry = Backup; ++ while (OnGuestAltStack(Backup, Entry->GuestInterruptedSP)) { ++ if (--Limit == 0 || !Entry->PrevGuestFrame) { ++ return false; ++ } ++ Entry = reinterpret_cast(Entry->PrevGuestFrame); ++ } ++ return OnGuestAltStack(Backup, Entry->GuestFrameEnd) && Entry->GuestAltBase == Backup->GuestAltBase && ++ Entry->GuestAltEnd == Backup->GuestAltEnd && GuestSP >= Entry->GuestInterruptedSP; ++ } ++} ++ + ArchHelpers::Context::ContextBackup* SignalDelegator::StoreThreadState(FEXCore::Core::InternalThreadState* Thread, int Signal, void* ucontext) { + // We can end up getting a signal at any point in our host state + // Jump to a handler that saves all state so we can safely return +@@ -249,6 +274,19 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr + } + + OldSP = *reinterpret_cast(GuestSP); ++ ++ auto& SignalInfo = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->SignalInfo; ++ uint64_t Entry = SignalInfo.GuestFrames; ++ for (uint32_t Depth = 1; Entry && Depth <= SignalInfo.GuestFrameCount; ++Depth) { ++ auto EntryBackup = reinterpret_cast(Entry); ++ if (Entry == OldSP) { ++ SignalInfo.GuestFrames = EntryBackup->PrevGuestFrame; ++ SignalInfo.GuestFrameCount -= Depth; ++ Thread->CurrentFrame->SignalHandlerRefCounter -= Depth - 1; ++ break; ++ } ++ Entry = EntryBackup->PrevGuestFrame; ++ } + } + + uintptr_t NewSP = OldSP; +@@ -287,6 +325,7 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS + auto ContextBackup = StoreThreadState(Thread, Signal, ucontext); + + auto Frame = Thread->CurrentFrame; ++ auto& SignalInfo = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->SignalInfo; + + // Ref count our faults + // We use this to track if it is safe to clear cache +@@ -336,6 +375,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS + + uint64_t OldGuestSP = Frame->State.gregs[FEXCore::X86State::REG_RSP]; + uint64_t NewGuestSP = OldGuestSP; ++ uint64_t GuestAltBase = 0; ++ uint64_t GuestAltEnd = 0; + + // altstack is only used if the signal handler was setup with SA_ONSTACK + if (GuestAction->sa_flags & SA_ONSTACK) { +@@ -345,6 +386,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS + // Then that means we are hitting recursive signals and we need to walk back the stack correctly + uint64_t AltStackBase = reinterpret_cast(GuestStack->ss_sp); + uint64_t AltStackEnd = AltStackBase + GuestStack->ss_size; ++ GuestAltBase = AltStackBase; ++ GuestAltEnd = AltStackEnd; + if (OldGuestSP >= AltStackBase && OldGuestSP <= AltStackEnd) { + // We are already in the alt stack, the rest of the code will handle adjusting this + } else { +@@ -353,6 +396,40 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS + } + } + ++#ifdef ARCHITECTURE_arm64 ++ auto Newest = reinterpret_cast(SignalInfo.GuestFrames); ++ if (WasInJIT && Newest && ContextBackup->PrevSP == SignalInfo.GuestFrames && ++ Frame->SignalHandlerRefCounter == SignalInfo.GuestFrameCount + 1 && GuestLeftFrame(Newest, OldGuestSP, SignalInfo.GuestFrameCount)) { ++ uint32_t LeftFrames = 0; ++ while (Newest && LeftFrames < SignalInfo.GuestFrameCount && ++ GuestLeftFrame(Newest, OldGuestSP, SignalInfo.GuestFrameCount - LeftFrames)) { ++ Newest = reinterpret_cast(Newest->PrevGuestFrame); ++ ++LeftFrames; ++ } ++ ++ const uint64_t HostTop = Newest ? reinterpret_cast(Newest) : Frame->ReturningStackLocation; ++ const uint64_t MovedBackup = FEXCore::AlignDown( ++ HostTop - ArchHelpers::Context::ContextBackup::RedZoneSize - sizeof(ArchHelpers::Context::ContextBackup), 16); ++ if (MovedBackup > reinterpret_cast(ContextBackup)) { ++ memmove(reinterpret_cast(MovedBackup), ContextBackup, sizeof(ArchHelpers::Context::ContextBackup)); ++ ContextBackup = reinterpret_cast(MovedBackup); ++ ContextBackup->PrevSP = HostTop; ++ ArchHelpers::Context::SetSp(ucontext, MovedBackup); ++ SignalInfo.GuestFrames = reinterpret_cast(Newest); ++ SignalInfo.GuestFrameCount -= LeftFrames; ++ Frame->SignalHandlerRefCounter -= LeftFrames; ++ } ++ } ++#endif ++ ++ ContextBackup->GuestFrameEnd = NewGuestSP; ++ ContextBackup->GuestInterruptedSP = OldGuestSP; ++ ContextBackup->GuestAltBase = GuestAltBase; ++ ContextBackup->GuestAltEnd = GuestAltEnd; ++ ContextBackup->PrevGuestFrame = SignalInfo.GuestFrames; ++ SignalInfo.GuestFrames = reinterpret_cast(ContextBackup); ++ ++SignalInfo.GuestFrameCount; ++ + // siginfo_t + siginfo_t* HostSigInfo = reinterpret_cast(info); + +@@ -491,6 +568,8 @@ bool SignalDelegator::HandleSignalPause(FEXCore::Core::InternalThreadState* Thre + + // Our ref counting doesn't matter anymore + Thread->CurrentFrame->SignalHandlerRefCounter = 0; ++ ThreadObject->SignalInfo.GuestFrames = 0; ++ ThreadObject->SignalInfo.GuestFrameCount = 0; + + // Set the new PC + if (CTX->IsAddressInCodeBuffer(Thread, ArchHelpers::Context::GetPc(ucontext))) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +index dfcd4b0..e4a86a9 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +@@ -83,6 +83,9 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators { + // Queue of thread local signal frames that have been deferred. + // Async signals aren't guaranteed to be delivered in any particular order, but FEX treats them as FILO. + fextl::vector DeferredSignalFrames; ++ ++ uint64_t GuestFrames {}; ++ uint32_t GuestFrameCount {}; + } SignalInfo {}; + + // Seccomp thread specific data. diff --git a/tools/fex/patches/0010-syscall-exit-resets-host-stack.patch b/tools/fex/patches/0010-syscall-exit-resets-host-stack.patch new file mode 100644 index 0000000000..790a5390d8 --- /dev/null +++ b/tools/fex/patches/0010-syscall-exit-resets-host-stack.patch @@ -0,0 +1,23 @@ +Fixed-upstream: FEX-2612 +diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp +index c2b1d8e287..fcdf261484 100644 +--- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp ++++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp +@@ -285,6 +285,8 @@ DEF_OP(CondJump) { + DEF_OP(Syscall) { + SpillStaticRegs(TMP1); + ++ ResetStack(); ++ + // Jump to the syscall dispatch handler. We won't return after this. + ldr(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, Pointers.ThreadDispatchSyscallHandler)); + br(TMP1); +@@ -376,6 +378,8 @@ DEF_OP(ThreadRemoveCodeEntry) { + + SpillStaticRegs(TMP1); + ++ ResetStack(); ++ + // Store the new RIP to go to. + str(GetReg(Op->NewRIP).X(), STATE, offsetof(FEXCore::Core::CpuStateFrame, State.rip)); + diff --git a/tools/fex/patches/0011-thunk-calls-mark-spilled-state.patch b/tools/fex/patches/0011-thunk-calls-mark-spilled-state.patch new file mode 100644 index 0000000000..626c726b59 --- /dev/null +++ b/tools/fex/patches/0011-thunk-calls-mark-spilled-state.patch @@ -0,0 +1,109 @@ +diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/Core/Core.cpp +--- a/FEXCore/Source/Interface/Core/Core.cpp ++++ b/FEXCore/Source/Interface/Core/Core.cpp +@@ -383,7 +383,11 @@ + } + + void ContextImpl::HandleCallback(FEXCore::Core::InternalThreadState* Thread, uint64_t RIP) { +- static_cast(Thread->CTX)->Dispatcher->ExecuteJITCallback(Thread->CurrentFrame, RIP); ++ auto Frame = Thread->CurrentFrame; ++ const auto InSyscallInfo = Frame->InSyscallInfo; ++ Frame->InSyscallInfo = 0; ++ static_cast(Thread->CTX)->Dispatcher->ExecuteJITCallback(Frame, RIP); ++ Frame->InSyscallInfo = InSyscallInfo; + } + + void ContextImpl::ExecuteThread(FEXCore::Core::InternalThreadState* Thread) { +diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp +--- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp ++++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp +@@ -305,6 +305,9 @@ + + PushDynamicRegs(TMP1); + ++ LoadConstant(ARMEmitter::Size::i64Bit, TMP1, 0xFFFF); ++ str(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo)); ++ + mov(ARMEmitter::Size::i64Bit, ARMEmitter::Reg::r0, GetReg(Op->ArgPtr)); + + InsertNamedThunkRelocation(ARMEmitter::Reg::r2, Op->ThunkNameHash); +@@ -320,6 +323,8 @@ + FillStaticRegs({ + .NZCV = false, + }); ++ ++ str(ARMEmitter::XReg::zr, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo)); + } + + DEF_OP(ValidateCode) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +@@ -107,6 +107,10 @@ + #ifdef ARCHITECTURE_arm64 + Thread->CurrentFrame->State.rip = CTX->RestoreRIPFromHostPC(Thread, ArchHelpers::Context::GetPc(ucontext)); + ++ if ((IgnoreMask & 0xFFFF) == 0xFFFF) { ++ return; ++ } ++ + for (size_t i = 0; i < Config.SRAGPRCount; i++) { + const uint8_t SRAIdxMap = Config.SRAGPRMapping[i]; + if (IgnoreMask & (1U << SRAIdxMap)) { +@@ -301,12 +305,10 @@ + if (Context->UContextLocation) { + auto Frame = Thread->CurrentFrame; + +- if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) { +- // XXX: Unsupported since it needs state reconstruction +- // If we are in the JIT then SRA might need to be restored to values from the context +- // We can't currently support this since it might result in tearing without real state reconstruction +- Frame->InSyscallInfo = Context->InSyscallInfo; +- } ++ // XXX: Unsupported since it needs state reconstruction ++ // If we are in the JIT then SRA might need to be restored to values from the context ++ // We can't currently support this since it might result in tearing without real state reconstruction ++ Frame->InSyscallInfo = Context->InSyscallInfo; + + if (Is64BitMode) { + RestoreFrame_x64(Thread, Context, Frame, ucontext); +@@ -361,6 +363,9 @@ + ContextBackup->InSyscallInfo = Thread->CurrentFrame->InSyscallInfo; + Thread->CurrentFrame->InSyscallInfo = 0; + } else { ++ ContextBackup->InSyscallInfo = Frame->InSyscallInfo; ++ Frame->InSyscallInfo = 0; ++ + if (!IsAddressInDispatcher(OldPC)) { + // This is likely to cause issues but in some cases it isn't fatal + // This can also happen if we have put a signal on hold, then we just reenabled the signal +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +@@ -131,7 +131,7 @@ + if (Context->OriginalRIP != guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] || Context->FaultToTopAndGeneratedException) { + + // Restore previous `InSyscallInfo` structure. +- Frame->InSyscallInfo = Context->InSyscallInfo; ++ Frame->InSyscallInfo = 0; + + // Hack! Go back to the top of the dispatcher top + // This is only safe inside the JIT rather than anything outside of it +@@ -211,7 +211,7 @@ + // If the guest modified the RIP then we need to take special precautions here + if (Context->OriginalRIP != guest_uctx->sc.ip || Context->FaultToTopAndGeneratedException) { + // Restore previous `InSyscallInfo` structure. +- Frame->InSyscallInfo = Context->InSyscallInfo; ++ Frame->InSyscallInfo = 0; + + // Hack! Go back to the top of the dispatcher top + // This is only safe inside the JIT rather than anything outside of it +@@ -290,7 +290,7 @@ + if (Context->OriginalRIP != guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] || Context->FaultToTopAndGeneratedException) { + + // Restore previous `InSyscallInfo` structure. +- Frame->InSyscallInfo = Context->InSyscallInfo; ++ Frame->InSyscallInfo = 0; + + // Hack! Go back to the top of the dispatcher top + // This is only safe inside the JIT rather than anything outside of it diff --git a/tools/fex/patches/0012-signal-return-applies-guest-registers.patch b/tools/fex/patches/0012-signal-return-applies-guest-registers.patch new file mode 100644 index 0000000000..d97a75bee3 --- /dev/null +++ b/tools/fex/patches/0012-signal-return-applies-guest-registers.patch @@ -0,0 +1,112 @@ +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h +@@ -263,6 +263,8 @@ + FEXCore::Core::CpuStateFrame* Frame, void* ucontext); + void RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* Context, + FEXCore::Core::CpuStateFrame* Frame, void* ucontext); ++ void ResumeWithGuestGPRs(ArchHelpers::Context::ContextBackup* Context, FEXCore::Core::CpuStateFrame* Frame, void* ucontext, ++ const uint64_t* GuestGPRs, size_t Count, uint64_t Mask); + + ///< Setup the signal frame for x64. + uint64_t SetupFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* ContextBackup, +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +@@ -122,6 +122,32 @@ + } + } + ++void SignalDelegator::ResumeWithGuestGPRs(ArchHelpers::Context::ContextBackup* Context, FEXCore::Core::CpuStateFrame* Frame, void* ucontext, ++ const uint64_t* GuestGPRs, size_t Count, uint64_t Mask) { ++#ifdef ARCHITECTURE_arm64 ++ const uint32_t Spilled = Context->InSyscallInfo & 0xFFFF; ++ const bool AllSpilled = Spilled == 0xFFFF; ++ if (!AllSpilled && !(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) { ++ return; ++ } ++ ++ for (size_t i = 0; i < Count && i < Config.SRAGPRCount; i++) { ++ const uint8_t HostReg = Config.SRAGPRMapping[i]; ++ const bool InFrame = AllSpilled || (Spilled & (1U << HostReg)); ++ const uint64_t Delivered = InFrame ? Frame->State.gregs[i] : ArchHelpers::Context::GetArmReg(ucontext, HostReg); ++ if (((Delivered ^ GuestGPRs[i]) & Mask) == 0) { ++ continue; ++ } ++ ++ if (InFrame) { ++ Frame->State.gregs[i] = GuestGPRs[i]; ++ } else { ++ ArchHelpers::Context::SetArmReg(ucontext, HostReg, GuestGPRs[i]); ++ } ++ } ++#endif ++} ++ + void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* Context, + FEXCore::Core::CpuStateFrame* Frame, void* ucontext) { + auto* guest_uctx = reinterpret_cast(Context->UContextLocation); +@@ -202,6 +228,27 @@ + const auto modulo_i = (i + CurrentOffset) % 8; + memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], sizeof(Frame->State.mm[0])); + } ++ } else { ++ uint64_t GuestGPRs[FEXCore::Core::CPUState::NUM_GPRS]; ++#define COPY_REG(x) GuestGPRs[FEXCore::X86State::REG_##x] = guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_##x]; ++ COPY_REG(R8); ++ COPY_REG(R9); ++ COPY_REG(R10); ++ COPY_REG(R11); ++ COPY_REG(R12); ++ COPY_REG(R13); ++ COPY_REG(R14); ++ COPY_REG(R15); ++ COPY_REG(RDI); ++ COPY_REG(RSI); ++ COPY_REG(RBP); ++ COPY_REG(RBX); ++ COPY_REG(RDX); ++ COPY_REG(RAX); ++ COPY_REG(RCX); ++ COPY_REG(RSP); ++#undef COPY_REG ++ ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, FEXCore::Core::CPUState::NUM_GPRS, ~0ULL); + } + } + +@@ -280,6 +327,17 @@ + const auto modulo_i = (i + CurrentOffset) % 8; + memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10); + } ++ } else { ++ uint64_t GuestGPRs[8]; ++ GuestGPRs[FEXCore::X86State::REG_RAX] = guest_uctx->sc.ax; ++ GuestGPRs[FEXCore::X86State::REG_RCX] = guest_uctx->sc.cx; ++ GuestGPRs[FEXCore::X86State::REG_RDX] = guest_uctx->sc.dx; ++ GuestGPRs[FEXCore::X86State::REG_RBX] = guest_uctx->sc.bx; ++ GuestGPRs[FEXCore::X86State::REG_RSP] = guest_uctx->sc.sp; ++ GuestGPRs[FEXCore::X86State::REG_RBP] = guest_uctx->sc.bp; ++ GuestGPRs[FEXCore::X86State::REG_RSI] = guest_uctx->sc.si; ++ GuestGPRs[FEXCore::X86State::REG_RDI] = guest_uctx->sc.di; ++ ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL); + } + } + +@@ -359,6 +417,17 @@ + const auto modulo_i = (i + CurrentOffset) % 8; + memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10); + } ++ } else { ++ uint64_t GuestGPRs[8]; ++ GuestGPRs[FEXCore::X86State::REG_RAX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RAX]; ++ GuestGPRs[FEXCore::X86State::REG_RCX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RCX]; ++ GuestGPRs[FEXCore::X86State::REG_RDX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RDX]; ++ GuestGPRs[FEXCore::X86State::REG_RBX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RBX]; ++ GuestGPRs[FEXCore::X86State::REG_RSP] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RSP]; ++ GuestGPRs[FEXCore::X86State::REG_RBP] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RBP]; ++ GuestGPRs[FEXCore::X86State::REG_RSI] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RSI]; ++ GuestGPRs[FEXCore::X86State::REG_RDI] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RDI]; ++ ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL); + } + } + diff --git a/tools/fex/probes/signal-handler-escape.c b/tools/fex/probes/signal-handler-escape.c new file mode 100644 index 0000000000..71e1a12fca --- /dev/null +++ b/tools/fex/probes/signal-handler-escape.c @@ -0,0 +1,90 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include + +static sigjmp_buf main_env, inner_env; +static volatile int depth, nested_mode; +static volatile long escapes, nested, returns, wrong; + +static void fault(long i) { + *(volatile int *)(long)(8 + (i & 7)) = 1; +} + +static void segv(int sig, siginfo_t *info, void *context) { + (void)sig; + (void)info; + (void)context; + if (!nested_mode) { + escapes++; + siglongjmp(main_env, 1); + } + if (depth == 1) { + nested++; + siglongjmp(inner_env, 1); + } + depth = 1; + for (volatile int k = 0; k < 3; k++) + if (sigsetjmp(inner_env, 0) == 0) + fault(k); + depth = 0; + escapes++; + siglongjmp(main_env, 1); +} + +static void trap(int sig, siginfo_t *info, void *context) { + (void)sig; + (void)info; + (void)context; + returns++; +} + +static void install(int onstack) { + struct sigaction action; + memset(&action, 0, sizeof(action)); + action.sa_sigaction = segv; + action.sa_flags = SA_SIGINFO | SA_NODEFER | (onstack ? SA_ONSTACK : 0); + sigaction(SIGSEGV, &action, NULL); +} + +static long run(long count, int with_trap) { + long start = escapes; + for (volatile long i = 0; i < count; i++) { + if (with_trap) { + volatile long before = i * 3; + __asm__ volatile("int3" ::: "memory"); + if (before != i * 3) + wrong++; + } + if (sigsetjmp(main_env, 1) == 0) + fault(i); + } + return escapes - start; +} + +int main(int argc, char **argv) { + long want = argc > 1 ? atol(argv[1]) : 50000; + stack_t ss = {.ss_sp = malloc(262144), .ss_size = 262144}; + struct sigaction action; + sigaltstack(&ss, NULL); + memset(&action, 0, sizeof(action)); + action.sa_sigaction = trap; + action.sa_flags = SA_SIGINFO; + sigaction(SIGTRAP, &action, NULL); + + install(1); + long onstack = run(want, 0); + install(0); + long offstack = run(want, 0); + install(1); + long mixed = run(want, 1); + nested_mode = 1; + long outer = run(want, 0); + + printf("onstack=%ld offstack=%ld mixed=%ld returns=%ld outer=%ld nested=%ld wrong=%ld\n", onstack, offstack, mixed, returns, + outer, nested, wrong); + return onstack == want && offstack == want && mixed == want && returns == want && outer == want && nested == 3 * want && !wrong ? 0 + : 1; +} diff --git a/tools/fex/probes/signal-register-update.c b/tools/fex/probes/signal-register-update.c new file mode 100644 index 0000000000..a1fdaec4d5 --- /dev/null +++ b/tools/fex/probes/signal-register-update.c @@ -0,0 +1,88 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include + +#define MARK 0x5eed + +static volatile sig_atomic_t alarms; +static volatile sig_atomic_t give_up; + +static void count_alarm(void) { + if (++alarms > 100) { + give_up = 1; + } +} + +static void on_alarm(int sig, siginfo_t *si, void *ctx) { + (void)sig; + (void)si; + ucontext_t *uc = ctx; + count_alarm(); +#ifdef __x86_64__ + uc->uc_mcontext.gregs[REG_R12] = MARK; +#else + uc->uc_mcontext.gregs[REG_ESI] = MARK; +#endif +} + +#ifdef __i386__ +static void on_alarm_legacy(int sig, struct sigcontext sc) { + (void)sig; + count_alarm(); + ((volatile struct sigcontext *)&sc)->esi = MARK; +} +#endif + +int main(int argc, char **argv) { + int legacy = argc > 1 && strcmp(argv[1], "legacy") == 0; + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_flags = SA_RESTART; +#ifdef __i386__ + if (legacy) { + sa.sa_handler = (void (*)(int))on_alarm_legacy; + } else +#endif + { + legacy = 0; + sa.sa_sigaction = on_alarm; + sa.sa_flags |= SA_SIGINFO; + } + sigaction(SIGALRM, &sa, NULL); + struct itimerval it = {{0, 20000}, {0, 20000}}; + setitimer(ITIMER_REAL, &it, NULL); + + unsigned long spins, seen; +#ifdef __x86_64__ + __asm__ volatile("xor %%r12, %%r12\n" + "xor %0, %0\n" + "1: inc %0\n" + "test %%r12, %%r12\n" + "jnz 2f\n" + "cmpl $0, %2\n" + "je 1b\n" + "2: mov %%r12, %1\n" + : "=&r"(spins), "=&r"(seen) + : "m"(give_up) + : "r12", "cc"); +#else + __asm__ volatile("xor %%esi, %%esi\n" + "xor %0, %0\n" + "1: inc %0\n" + "test %%esi, %%esi\n" + "jnz 2f\n" + "cmpl $0, %2\n" + "je 1b\n" + "2: mov %%esi, %1\n" + : "=&r"(spins), "=&r"(seen) + : "m"(give_up) + : "esi", "cc"); +#endif + struct itimerval off = {{0, 0}, {0, 0}}; + setitimer(ITIMER_REAL, &off, NULL); + printf("frame=%s seen=%d alarms=%d spins=%lu\n", legacy ? "legacy" : "rt", seen == MARK, (int)alarms, spins); + return seen == MARK ? 0 : 1; +} diff --git a/tools/fex/probes/syscall-host-stack.c b/tools/fex/probes/syscall-host-stack.c new file mode 100644 index 0000000000..bd348fcfd3 --- /dev/null +++ b/tools/fex/probes/syscall-host-stack.c @@ -0,0 +1,65 @@ +#define _GNU_SOURCE +#include +#include +#include +#include + +#define YMM_STEP(a, b) "vpaddq %%ymm" #b ", %%ymm" #a ", %%ymm" #a "\n" +#define MMX_STEP(a, b) "paddq %%mm" #b ", %%mm" #a "\n" + +static int has_avx2(void) { + unsigned a, b, c, d; + if (!__get_cpuid(1, &a, &b, &c, &d) || !(c & bit_AVX) || !(c & bit_OSXSAVE)) + return 0; + unsigned lo, hi; + __asm__ volatile("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0)); + if ((lo & 6) != 6 || !__get_cpuid_count(7, 0, &a, &b, &c, &d)) + return 0; + return (b & bit_AVX2) != 0; +} + +static long ymm_round(long n) { + long pid = 0; + for (long i = 0; i < n; i++) { + __asm__ volatile( + YMM_STEP(0, 1) YMM_STEP(1, 2) YMM_STEP(2, 3) YMM_STEP(3, 4) YMM_STEP(4, 5) YMM_STEP(5, 6) YMM_STEP(6, 7) YMM_STEP(7, 8) + YMM_STEP(8, 9) YMM_STEP(9, 10) YMM_STEP(10, 11) YMM_STEP(11, 12) YMM_STEP(12, 13) YMM_STEP(13, 14) YMM_STEP(14, 15) + YMM_STEP(15, 0) YMM_STEP(0, 15) YMM_STEP(1, 14) YMM_STEP(2, 13) YMM_STEP(3, 12) YMM_STEP(4, 11) YMM_STEP(5, 10) + YMM_STEP(6, 9) YMM_STEP(7, 8) + "mov %1, %%eax\n" + "syscall\n" + : "=a"(pid) + : "i"(SYS_getpid) + : "rcx", "r11", "memory", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", "xmm8", "xmm9", "xmm10", + "xmm11", "xmm12", "xmm13", "xmm14", "xmm15"); + } + __asm__ volatile("vzeroupper" ::: "memory"); + return pid; +} + +static long mmx_round(long n) { + long pid = 0; + for (long i = 0; i < n; i++) { + __asm__ volatile( + MMX_STEP(0, 1) MMX_STEP(1, 2) MMX_STEP(2, 3) MMX_STEP(3, 4) MMX_STEP(4, 5) MMX_STEP(5, 6) MMX_STEP(6, 7) MMX_STEP(7, 0) + "mov %1, %%eax\n" + "syscall\n" + : "=a"(pid) + : "i"(SYS_getpid) + : "rcx", "r11", "memory", "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7"); + } + __asm__ volatile("emms" ::: "memory"); + return pid; +} + +int main(int argc, char **argv) { + long want = argc > 1 ? atol(argv[1]) : 2000000; + int avx = has_avx2(); + long done = 0; + for (; done < want; done += 1000) { + if (avx ? ymm_round(1000) <= 0 : mmx_round(1000) <= 0) + return 2; + } + printf("mode=%s syscalls=%ld\n", avx ? "avx" : "mmx", done); + return 0; +} diff --git a/tools/fex/probes/vdso-signal-state.c b/tools/fex/probes/vdso-signal-state.c new file mode 100644 index 0000000000..56057594c3 --- /dev/null +++ b/tools/fex/probes/vdso-signal-state.c @@ -0,0 +1,49 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include + +static volatile sig_atomic_t alarms; + +static void on_alarm(int sig) { + (void)sig; + alarms++; +} + +int main(int argc, char **argv) { + int seconds = argc > 1 ? atoi(argv[1]) : 3; + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = on_alarm; + sa.sa_flags = SA_RESTART; + sigaction(SIGALRM, &sa, NULL); + struct itimerval it = {{0, 1000}, {0, 1000}}; + setitimer(ITIMER_REAL, &it, NULL); + + struct timespec start, now, last; + clock_gettime(CLOCK_MONOTONIC, &start); + last = start; + unsigned long calls = 0, bad = 0; + unsigned long a = 1, b = 3, c = 1 ^ 0x5a5a5a5a5a5a5a5aUL; + do { + clock_gettime(CLOCK_MONOTONIC, &now); + calls++; + __asm__ volatile("" : "+r"(a), "+r"(b), "+r"(c)); + if (b != a * 3 || c != (a ^ 0x5a5a5a5a5a5a5a5aUL)) + bad++; + if (now.tv_sec < last.tv_sec || (now.tv_sec == last.tv_sec && now.tv_nsec < last.tv_nsec)) + bad++; + last = now; + a = a * 6364136223846793005UL + 1442695040888963407UL; + b = a * 3; + c = a ^ 0x5a5a5a5a5a5a5a5aUL; + } while ((now.tv_sec - start.tv_sec) * 1000000000L + (now.tv_nsec - start.tv_nsec) < seconds * 1000000000L); + + struct itimerval off = {{0, 0}, {0, 0}}; + setitimer(ITIMER_REAL, &off, NULL); + printf("calls=%lu alarms=%d bad=%lu\n", calls, (int)alarms, bad); + return bad || alarms == 0; +} diff --git a/tools/tests/test_fex_signal_handler_escape.py b/tools/tests/test_fex_signal_handler_escape.py new file mode 100644 index 0000000000..c208b874bf --- /dev/null +++ b/tools/tests/test_fex_signal_handler_escape.py @@ -0,0 +1,117 @@ +import platform +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +FEX = Path(__file__).resolve().parents[1] / "fex" +PATCH = FEX / "patches/0009-signal-handler-escape-frees-host-stack.patch" +PROBE = FEX / "probes/signal-handler-escape.c" +DELEGATOR = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp" +CONTEXT = "Source/Tools/LinuxEmulation/ArchHelpers/MContext.h" +THREADS = "Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h" +FIELDS = ["PrevGuestFrame", "GuestFrameEnd", "GuestInterruptedSP", "GuestAltBase", "GuestAltEnd"] + + +def files(): + sections = re.split(r"^diff --git a/(\S+) \S+\n", PATCH.read_text(), flags=re.M) + return {sections[i]: sections[i + 1] for i in range(1, len(sections), 2)} + + +def hunks(section): + return re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", section, re.M) + + +def added(body): + return [line[1:].strip() for line in body.splitlines() if line.startswith("+") and not line.startswith("+++")] + + +def removed(body): + return [line for line in body.splitlines() if line.startswith("-") and not line.startswith("---")] + + +class SignalHandlerEscapeTest(unittest.TestCase): + def test_only_signal_state_files_change(self): + self.assertEqual(sorted(files()), sorted([CONTEXT, DELEGATOR, THREADS])) + + def test_nothing_is_removed(self): + for name, section in files().items(): + self.assertEqual(removed(section), [], name) + + def test_added_code_has_no_comments(self): + for name, section in files().items(): + for line in added(section): + self.assertFalse("//" in line or "/*" in line, f"{name}: {line}") + + def test_both_context_backups_record_the_guest_frame(self): + lines = added(files()[CONTEXT]) + self.assertEqual(lines, [f"uint64_t {field};" for field in FIELDS] * 2) + + def test_each_thread_keeps_its_frame_chain(self): + self.assertEqual([line for line in added(files()[THREADS]) if line], ["uint64_t GuestFrames {};", "uint32_t GuestFrameCount {};"]) + + def test_delivery_pushes_and_reclaims_only_left_frames_at_the_dispatch_level(self): + found = hunks(files()[DELEGATOR]) + delivery = "".join(body for function, body in found if "HandleDispatcherGuestSignal" in function) + lines = added(delivery) + self.assertIn("#ifdef ARCHITECTURE_arm64", lines) + gate = " ".join(lines) + self.assertIn("WasInJIT && Newest && ContextBackup->PrevSP == SignalInfo.GuestFrames", gate) + self.assertIn("Frame->SignalHandlerRefCounter == SignalInfo.GuestFrameCount + 1", gate) + self.assertIn("GuestLeftFrame(Newest, OldGuestSP", gate) + self.assertIn("ContextBackup->PrevSP = HostTop;", lines) + self.assertIn("Frame->SignalHandlerRefCounter -= LeftFrames;", lines) + self.assertIn("SignalInfo.GuestFrames = reinterpret_cast(ContextBackup);", lines) + self.assertIn("++SignalInfo.GuestFrameCount;", lines) + self.assertLess(lines.index("#endif"), lines.index("ContextBackup->PrevGuestFrame = SignalInfo.GuestFrames;")) + + def test_signal_return_pops_its_frame_and_any_newer_ones(self): + found = hunks(files()[DELEGATOR]) + restore = "".join(body for function, body in found if "RestoreThreadState" in function) + lines = added(restore) + self.assertIn("if (Entry == OldSP) {", lines) + self.assertIn("SignalInfo.GuestFrames = EntryBackup->PrevGuestFrame;", lines) + self.assertIn("Thread->CurrentFrame->SignalHandlerRefCounter -= Depth - 1;", lines) + self.assertNotIn("TYPE_PAUSE", " ".join(lines)) + + def test_thread_stop_clears_the_chain(self): + found = hunks(files()[DELEGATOR]) + pause = "".join(body for function, body in found if "HandleSignalPause" in function) + self.assertEqual(added(pause), ["ThreadObject->SignalInfo.GuestFrames = 0;", "ThreadObject->SignalInfo.GuestFrameCount = 0;"]) + + def test_patch_follows_the_syscall_state_patch_on_every_release(self): + names = sorted(path.name for path in (FEX / "patches").glob("*.patch")) + self.assertEqual(names[names.index(PATCH.name) - 1], "0008-signal-return-restores-syscall-state.patch") + self.assertNotIn("Fixed-upstream", PATCH.read_text()) + self.assertIn("tools/fex/patches/*.patch", (FEX / "build-in-arch.sh").read_text()) + + +@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code") +class SignalHandlerEscapeProbeTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang") + if not compiler: + raise unittest.SkipTest("no C compiler") + cls.tmp = Path(tempfile.mkdtemp(prefix="fex-signal-escape-")) + cls.binary = cls.tmp / "probe" + subprocess.run([compiler, "-O2", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def test_native_kernel_survives_every_escape(self): + result = subprocess.run([str(self.binary), "20000"], capture_output=True, text=True, timeout=120) + self.assertEqual(result.returncode, 0, result.stdout) + counts = dict(part.split("=") for part in result.stdout.split()) + for phase in ("onstack", "offstack", "mixed", "returns", "outer"): + self.assertEqual(counts[phase], "20000", phase) + self.assertEqual(counts["nested"], "60000") + self.assertEqual(counts["wrong"], "0") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_fex_signal_register_update.py b/tools/tests/test_fex_signal_register_update.py new file mode 100644 index 0000000000..dabc5afff3 --- /dev/null +++ b/tools/tests/test_fex_signal_register_update.py @@ -0,0 +1,134 @@ +import platform +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +FEX = Path(__file__).resolve().parents[1] / "fex" +PATCH = FEX / "patches/0012-signal-return-applies-guest-registers.patch" +PROBE = FEX / "probes/signal-register-update.c" +HEADER = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h" +FRAMES = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp" +X64_ORDER = ["RAX", "RCX", "RDX", "RBX", "RSP", "RBP", "RSI", "RDI", "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15"] + + +def files(): + sections = re.split(r"^diff --git a/(\S+) \S+\n", PATCH.read_text(), flags=re.M) + return {sections[i]: sections[i + 1] for i in range(1, len(sections), 2)} + + +def added(section): + return [line[1:].strip() for line in section.splitlines() if line.startswith("+") and not line.startswith("+++")] + + +def removed(section): + return [line[1:].strip() for line in section.splitlines() if line.startswith("-") and not line.startswith("---")] + + +def helper(): + lines = added(files()[FRAMES]) + start = next(i for i, line in enumerate(lines) if line.startswith("void SignalDelegator::ResumeWithGuestGPRs(")) + end = lines.index("#endif", start) + return lines[start:end + 1] + + +class SignalRegisterUpdateTest(unittest.TestCase): + def test_only_signal_frame_files_change(self): + self.assertEqual(sorted(files()), sorted([FRAMES, HEADER])) + + def test_patch_only_adds_code(self): + for name, section in files().items(): + self.assertEqual(removed(section), [], name) + + def test_added_code_has_no_comments(self): + for name, section in files().items(): + for line in added(section): + self.assertNotIn("//", line, name) + self.assertNotIn("/*", line, name) + + def test_helper_is_declared_once(self): + self.assertEqual(sum(line.startswith("void ResumeWithGuestGPRs(") for line in added(files()[HEADER])), 1) + + def test_only_changed_registers_are_written_back(self): + body = helper() + self.assertIn("if (((Delivered ^ GuestGPRs[i]) & Mask) == 0) {", body) + self.assertEqual(body[body.index("if (((Delivered ^ GuestGPRs[i]) & Mask) == 0) {") + 1], "continue;") + + def test_spilled_registers_go_to_the_frame_and_live_ones_to_host_registers(self): + body = helper() + self.assertIn("const bool InFrame = AllSpilled || (Spilled & (1U << HostReg));", body) + self.assertIn("Frame->State.gregs[i] = GuestGPRs[i];", body) + self.assertIn("ArchHelpers::Context::SetArmReg(ucontext, HostReg, GuestGPRs[i]);", body) + self.assertIn("for (size_t i = 0; i < Count && i < Config.SRAGPRCount; i++) {", body) + + def test_signals_outside_jit_code_are_left_alone(self): + body = helper() + guard = body.index("if (!AllSpilled && !(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) {") + self.assertEqual(body[guard + 1], "return;") + self.assertEqual(body[2], "#ifdef ARCHITECTURE_arm64") + + def test_every_frame_type_applies_registers_when_rip_is_unchanged(self): + lines = added(files()[FRAMES]) + calls = [line for line in lines if line.startswith("ResumeWithGuestGPRs(")] + self.assertEqual(calls, [ + "ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, FEXCore::Core::CPUState::NUM_GPRS, ~0ULL);", + "ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL);", + "ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL);", + ]) + branches = [lines[i + 1] for i, line in enumerate(lines[:-1]) if line == "} else {" and lines[i + 1].startswith("uint64_t GuestGPRs[")] + self.assertEqual(branches, ["uint64_t GuestGPRs[FEXCore::Core::CPUState::NUM_GPRS];", "uint64_t GuestGPRs[8];", "uint64_t GuestGPRs[8];"]) + + def test_registers_are_stored_by_guest_register_index(self): + lines = added(files()[FRAMES]) + x64 = [m.group(1) for line in lines for m in [re.fullmatch(r"COPY_REG\((\w+)\);", line)] if m] + self.assertEqual(sorted(x64), sorted(X64_ORDER)) + self.assertIn("#define COPY_REG(x) GuestGPRs[FEXCore::X86State::REG_##x] = guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_##x];", lines) + legacy = re.findall(r"GuestGPRs\[FEXCore::X86State::REG_(\w+)\] = guest_uctx->sc\.(\w+);", "\n".join(lines)) + self.assertEqual(sorted(legacy), sorted((r, r[1:].lower()) for r in X64_ORDER[:8])) + rt = re.findall(r"GuestGPRs\[FEXCore::X86State::REG_(\w+)\] = guest_uctx->uc\.uc_mcontext\.gregs\[FEXCore::x86::FEX_REG_(\w+)\];", "\n".join(lines)) + self.assertEqual(sorted(rt), sorted((r, r) for r in X64_ORDER[:8])) + + def test_patch_follows_the_thunk_patch_on_every_release(self): + names = sorted(path.name for path in (FEX / "patches").glob("*.patch")) + self.assertEqual(names[names.index(PATCH.name) - 1], "0011-thunk-calls-mark-spilled-state.patch") + self.assertNotIn("Fixed-upstream", PATCH.read_text()) + + +@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86 code") +class SignalRegisterUpdateProbeTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang") + if not cls.compiler: + raise unittest.SkipTest("no C compiler") + cls.tmp = Path(tempfile.mkdtemp(prefix="fex-signal-regs-")) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def build(self, *flags): + binary = self.tmp / ("probe" + "".join(flags)) + result = subprocess.run([self.compiler, "-O2", *flags, "-o", str(binary), str(PROBE)], capture_output=True, text=True) + return binary if result.returncode == 0 else None + + def check(self, binary, *args): + result = subprocess.run([str(binary), *args], capture_output=True, text=True, timeout=60) + self.assertEqual(result.returncode, 0, result.stdout) + self.assertIn("seen=1", result.stdout) + + def test_native_kernel_applies_handler_register_changes(self): + self.check(self.build()) + + def test_native_kernel_applies_handler_register_changes_in_32_bit_frames(self): + binary = self.build("-m32") + if binary is None: + self.skipTest("no 32-bit toolchain") + self.check(binary) + self.check(binary, "legacy") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_fex_signal_syscall_state.py b/tools/tests/test_fex_signal_syscall_state.py index 1aaa03feb3..5638a41fea 100644 --- a/tools/tests/test_fex_signal_syscall_state.py +++ b/tools/tests/test_fex_signal_syscall_state.py @@ -24,7 +24,7 @@ class SignalReturnSyscallStateTest(unittest.TestCase): self.assertEqual(files, ["Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp"]) self.assertEqual(len(found), 1) - def test_every_guest_frame_return_restores_the_interrupted_syscall_state(self): + def test_only_returns_to_jit_code_restore_the_saved_syscall_state(self): _, found = hunks() function, body = found[0] self.assertIn("SignalDelegator::RestoreThreadState", function) @@ -34,10 +34,12 @@ class SignalReturnSyscallStateTest(unittest.TestCase): self.assertEqual(added, [RESTORE]) self.assertEqual(removed, []) context = [line[1:].strip() for line in lines] - guest_frame = context.index("if (Context->UContextLocation) {") - self.assertEqual(context[guest_frame + 1], "auto Frame = Thread->CurrentFrame;") - self.assertEqual(context[guest_frame + 2], RESTORE) - self.assertLess(context.index(RESTORE), context.index("if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {")) + self.assertEqual(context[0], "auto Frame = Thread->CurrentFrame;") + in_jit = context.index("if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {") + restore = context.index(RESTORE) + self.assertLess(in_jit, restore) + self.assertEqual(context[restore + 1], "}") + self.assertLess(restore, context.index("RestoreFrame_x64(Thread, Context, Frame, ucontext);")) def test_thread_pause_returns_are_untouched(self): _, found = hunks() diff --git a/tools/tests/test_fex_syscall_host_stack.py b/tools/tests/test_fex_syscall_host_stack.py new file mode 100644 index 0000000000..018863cf59 --- /dev/null +++ b/tools/tests/test_fex_syscall_host_stack.py @@ -0,0 +1,67 @@ +import platform +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +FEX = Path(__file__).resolve().parents[1] / "fex" +PATCH = FEX / "patches/0010-syscall-exit-resets-host-stack.patch" +PROBE = FEX / "probes/syscall-host-stack.c" +BRANCH_OPS = "FEXCore/Source/Interface/Core/JIT/BranchOps.cpp" + + +def hunks(): + text = PATCH.read_text() + files = re.findall(r"^diff --git a/(\S+) ", text, re.M) + return files, re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", text, re.M) + + +class SyscallHostStackTest(unittest.TestCase): + def test_only_the_branch_ops_change(self): + files, found = hunks() + self.assertEqual(files, [BRANCH_OPS]) + self.assertEqual(len(found), 2) + + def test_both_ops_that_leave_the_block_reset_the_stack_after_spilling(self): + _, found = hunks() + for (function, body), op in zip(found, ("DEF_OP(Syscall)", "DEF_OP(ThreadRemoveCodeEntry)")): + lines = body.splitlines() + added = [line[1:].strip() for line in lines if line.startswith("+")] + self.assertEqual([line for line in added if line], ["ResetStack();"], op) + self.assertEqual([line for line in lines if line.startswith("-")], [], op) + context = [line[1:].strip() for line in lines] + self.assertIn(op, function + " " + " ".join(context)) + self.assertLess(context.index("SpillStaticRegs(TMP1);"), context.index("ResetStack();"), op) + + def test_patch_is_skipped_once_upstream_ships_it(self): + self.assertEqual(PATCH.read_text().splitlines()[0], "Fixed-upstream: FEX-2612") + self.assertIn("Fixed-upstream: FEX-", (FEX / "build-in-arch.sh").read_text()) + + +@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code") +class SyscallHostStackProbeTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang") + if not compiler: + raise unittest.SkipTest("no C compiler") + cls.tmp = Path(tempfile.mkdtemp(prefix="fex-syscall-stack-")) + cls.binary = cls.tmp / "probe" + subprocess.run([compiler, "-O2", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def test_native_kernel_runs_every_syscall(self): + result = subprocess.run([str(self.binary), "200000"], capture_output=True, text=True, timeout=120) + self.assertEqual(result.returncode, 0, result.stdout) + counts = dict(part.split("=") for part in result.stdout.split()) + self.assertIn(counts["mode"], ("avx", "mmx")) + self.assertEqual(counts["syscalls"], "200000") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_fex_thunk_signal_state.py b/tools/tests/test_fex_thunk_signal_state.py new file mode 100644 index 0000000000..83d6008589 --- /dev/null +++ b/tools/tests/test_fex_thunk_signal_state.py @@ -0,0 +1,124 @@ +import platform +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +FEX = Path(__file__).resolve().parents[1] / "fex" +PATCH = FEX / "patches/0011-thunk-calls-mark-spilled-state.patch" +PROBE = FEX / "probes/vdso-signal-state.c" +CORE = "FEXCore/Source/Interface/Core/Core.cpp" +BRANCH_OPS = "FEXCore/Source/Interface/Core/JIT/BranchOps.cpp" +DELEGATOR = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp" +FRAMES = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp" +MARK = "str(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo));" +CLEAR = "str(ARMEmitter::XReg::zr, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo));" +RESTORE = "Frame->InSyscallInfo = Context->InSyscallInfo;" + + +def files(): + sections = re.split(r"^diff --git a/(\S+) \S+\n", PATCH.read_text(), flags=re.M) + return {sections[i]: sections[i + 1] for i in range(1, len(sections), 2)} + + +def hunks(section): + return re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", section, re.M) + + +def added(body): + return [line[1:].strip() for line in body.splitlines() if line.startswith("+") and not line.startswith("+++")] + + +def removed(body): + return [line[1:].strip() for line in body.splitlines() if line.startswith("-") and not line.startswith("---")] + + +def context(body): + return [line[1:].strip() for line in body.splitlines() if line[:1] in (" ", "+")] + + +class ThunkSignalStateTest(unittest.TestCase): + def test_only_signal_state_files_change(self): + self.assertEqual(sorted(files()), sorted([BRANCH_OPS, CORE, DELEGATOR, FRAMES])) + + def test_added_code_has_no_new_comments(self): + for name, section in files().items(): + moved = set(removed(section)) + for line in added(section): + if "//" in line or "/*" in line: + self.assertIn(line, moved, f"{name}: {line}") + + def test_thunk_call_marks_all_state_spilled_until_the_refill(self): + section = files()[BRANCH_OPS] + lines = context(section) + self.assertEqual([line for line in added(section) if line], ["LoadConstant(ARMEmitter::Size::i64Bit, TMP1, 0xFFFF);", MARK, CLEAR]) + self.assertEqual(removed(section), []) + self.assertLess(lines.index("PushDynamicRegs(TMP1);"), lines.index(MARK)) + self.assertLess(lines.index(MARK), lines.index("InsertNamedThunkRelocation(ARMEmitter::Reg::r2, Op->ThunkNameHash);")) + refill = lines.index("FillStaticRegs({") + self.assertEqual(lines[refill + 1:refill + 3], [".NZCV = false,", "});"]) + self.assertLess(refill, lines.index(CLEAR)) + + def test_fully_spilled_state_is_never_respilled_from_host_registers(self): + found = hunks(files()[DELEGATOR]) + spill = "".join(body for function, body in found if "SpillSRA" in function or "IgnoreMask" in body) + lines = context(spill) + guard = lines.index("if ((IgnoreMask & 0xFFFF) == 0xFFFF) {") + self.assertIn("RestoreRIPFromHostPC", lines[guard - 2]) + self.assertEqual(lines[guard + 1], "return;") + self.assertIn("for (size_t i = 0; i < Config.SRAGPRCount; i++) {", lines[guard + 2:guard + 5]) + + def test_every_guest_signal_saves_and_clears_the_mark(self): + section = files()[DELEGATOR] + lines = added(section) + self.assertIn("ContextBackup->InSyscallInfo = Frame->InSyscallInfo;", lines) + self.assertIn("Frame->InSyscallInfo = 0;", lines) + self.assertIn(RESTORE, lines) + self.assertIn("if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {", removed(section)) + self.assertNotIn("TYPE_PAUSE", " ".join(lines)) + + def test_redirected_returns_restart_with_no_mark(self): + section = files()[FRAMES] + self.assertEqual(added(section), ["Frame->InSyscallInfo = 0;"] * 3) + self.assertEqual(removed(section), [RESTORE] * 3) + + def test_guest_callbacks_run_with_no_mark(self): + lines = added(files()[CORE]) + self.assertEqual(lines[1:3], ["const auto InSyscallInfo = Frame->InSyscallInfo;", "Frame->InSyscallInfo = 0;"]) + self.assertEqual(lines[-1], "Frame->InSyscallInfo = InSyscallInfo;") + self.assertIn("ExecuteJITCallback(Frame, RIP);", lines[-2]) + + def test_patch_follows_the_host_stack_patch_on_every_release(self): + names = sorted(path.name for path in (FEX / "patches").glob("*.patch")) + self.assertEqual(names[names.index(PATCH.name) - 1], "0010-syscall-exit-resets-host-stack.patch") + self.assertNotIn("Fixed-upstream", PATCH.read_text()) + + +@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code") +class VdsoSignalStateProbeTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang") + if not compiler: + raise unittest.SkipTest("no C compiler") + cls.tmp = Path(tempfile.mkdtemp(prefix="fex-vdso-signal-")) + cls.binary = cls.tmp / "probe" + subprocess.run([compiler, "-O2", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def test_native_kernel_keeps_registers_across_interrupted_clock_calls(self): + result = subprocess.run([str(self.binary), "1"], capture_output=True, text=True, timeout=60) + self.assertEqual(result.returncode, 0, result.stdout) + counts = dict(part.split("=") for part in result.stdout.split()) + self.assertGreater(int(counts["calls"]), 0) + self.assertGreater(int(counts["alarms"]), 0) + self.assertEqual(counts["bad"], "0") + + +if __name__ == "__main__": + unittest.main() From d5b9cf5b41d0c282d17f3b213f7f75d4da1d0072 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:18:06 -0500 Subject: [PATCH 056/141] feat(ui): the Updates icon shows the build you're on (#3064) --- .../com/droiddeck/launcher/ui/FrontEndRail.kt | 3 +- .../droiddeck/launcher/ui/FrontEndScreen.kt | 1 + .../droiddeck/launcher/ui/UpdatesRailIcon.kt | 49 +++++++++++++++++++ .../launcher/ui/UpdatesRailIconTest.kt | 22 +++++++++ 4 files changed, 73 insertions(+), 2 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/ui/UpdatesRailIcon.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/ui/UpdatesRailIconTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt index 5503ef22a1..65dc828be8 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt @@ -58,7 +58,6 @@ import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.filled.SdStorage 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 @@ -208,7 +207,7 @@ internal fun railLabelIcon(key: String): Pair = when (key) { "storage" -> R.string.rail_storage to Icons.Filled.SdStorage "sync" -> R.string.rail_sync to Icons.Filled.Sync NavTabs.MORE -> R.string.rail_more to Icons.Filled.MoreHoriz - else -> R.string.rail_updates to Icons.Filled.SystemUpdate + else -> R.string.rail_updates to updatesIcon(RunningBuild.kind()) } internal fun setupNeedsAttention(s: FrontEndState): Boolean = !s.ready || (s.available != null && s.available != s.installed) || diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt index 0fa75a5855..c2f49c2ef2 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -454,6 +454,7 @@ 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) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/UpdatesRailIcon.kt b/app/src/main/java/com/droiddeck/launcher/ui/UpdatesRailIcon.kt new file mode 100644 index 0000000000..8206bb035e --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/UpdatesRailIcon.kt @@ -0,0 +1,49 @@ +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 +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/UpdatesRailIconTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/UpdatesRailIconTest.kt new file mode 100644 index 0000000000..d96dc487b6 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/UpdatesRailIconTest.kt @@ -0,0 +1,22 @@ +package com.droiddeck.launcher.ui + +import com.droiddeck.launcher.update.AppUpdates +import com.droiddeck.launcher.update.AppUpdates.Channel +import org.junit.Assert.assertEquals +import org.junit.Test + +class UpdatesRailIconTest { + private fun me(pr: Int = 0, ci: Boolean = true) = AppUpdates.Installed("abc", pr, "1.0", 1, ci, ciBuild = ci) + + @Test + fun releaseBuildsFollowTheirChannel() { + assertEquals(BuildKind.STABLE, RunningBuild.kind(me(), Channel.STABLE)) + assertEquals(BuildKind.PREVIEW, RunningBuild.kind(me(), Channel.NIGHTLY)) + } + + @Test + fun prBuildsAreTestAndNonCiBuildsAreLocal() { + assertEquals(BuildKind.TEST, RunningBuild.kind(me(pr = 12), Channel.TEST)) + assertEquals(BuildKind.LOCAL, RunningBuild.kind(me(ci = false), Channel.STABLE)) + } +} From 3e558ab33e3311d4c74a66a6f864f90286ca8213 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:59:58 -0500 Subject: [PATCH 057/141] feat(ui): Decky and Boot movies get their own tabs, with a Decky plugin store (#3068) --- .../java/com/droiddeck/launcher/DeckyMenu.kt | 55 ++++ .../droiddeck/launcher/FrontEndActivity.kt | 7 +- .../droiddeck/launcher/runtime/DeckyStore.kt | 102 ++++++++ .../droiddeck/launcher/ui/BootMovieSection.kt | 2 +- .../com/droiddeck/launcher/ui/DeckyIcon.kt | 16 ++ .../com/droiddeck/launcher/ui/DeckyPage.kt | 245 ++++++++++++++++++ .../droiddeck/launcher/ui/FrontEndContent.kt | 4 + .../com/droiddeck/launcher/ui/FrontEndRail.kt | 3 + .../com/droiddeck/launcher/ui/LiftSheet.kt | 2 + .../launcher/ui/ModeSettingsDialog.kt | 80 +----- .../java/com/droiddeck/launcher/ui/NavTabs.kt | 6 +- .../launcher/ui/RailSettingsPages.kt | 13 + .../droiddeck/launcher/ui/SettingsIndex.kt | 2 + app/src/main/res/values-ar/strings.xml | 5 - app/src/main/res/values-b+es+419/strings.xml | 5 - app/src/main/res/values-bg/strings.xml | 5 - app/src/main/res/values-cs/strings.xml | 5 - app/src/main/res/values-da/strings.xml | 5 - app/src/main/res/values-de/strings.xml | 5 - app/src/main/res/values-el/strings.xml | 5 - app/src/main/res/values-es/strings.xml | 5 - app/src/main/res/values-fi/strings.xml | 5 - app/src/main/res/values-fr/strings.xml | 5 - app/src/main/res/values-hi/strings.xml | 5 - app/src/main/res/values-hu/strings.xml | 5 - app/src/main/res/values-in/strings.xml | 5 - app/src/main/res/values-it/strings.xml | 5 - app/src/main/res/values-ja/strings.xml | 5 - app/src/main/res/values-ko/strings.xml | 5 - app/src/main/res/values-ms/strings.xml | 5 - app/src/main/res/values-nb/strings.xml | 5 - app/src/main/res/values-nl/strings.xml | 5 - app/src/main/res/values-pl/strings.xml | 5 - app/src/main/res/values-pt-rPT/strings.xml | 5 - app/src/main/res/values-pt/strings.xml | 5 - app/src/main/res/values-ro/strings.xml | 5 - app/src/main/res/values-ru/strings.xml | 5 - app/src/main/res/values-sv/strings.xml | 5 - app/src/main/res/values-th/strings.xml | 5 - app/src/main/res/values-tr/strings.xml | 5 - app/src/main/res/values-uk/strings.xml | 5 - app/src/main/res/values-vi/strings.xml | 5 - app/src/main/res/values-zh-rCN/strings.xml | 5 - app/src/main/res/values-zh-rHK/strings.xml | 5 - app/src/main/res/values-zh-rTW/strings.xml | 5 - app/src/main/res/values/strings.xml | 26 +- .../launcher/runtime/DeckyStoreTest.kt | 47 ++++ .../com/droiddeck/launcher/ui/NavTabsTest.kt | 14 +- docs/settings-map.md | 2 + 49 files changed, 538 insertions(+), 248 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/runtime/DeckyStore.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/ui/DeckyIcon.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/ui/DeckyPage.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/runtime/DeckyStoreTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/DeckyMenu.kt b/app/src/main/java/com/droiddeck/launcher/DeckyMenu.kt index 240202daec..983eea5ea0 100644 --- a/app/src/main/java/com/droiddeck/launcher/DeckyMenu.kt +++ b/app/src/main/java/com/droiddeck/launcher/DeckyMenu.kt @@ -6,6 +6,7 @@ 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 @@ -21,6 +22,59 @@ internal class DeckyMenu(private val activity: android.app.Activity, private val var deckySupervisor by mutableStateOf(false) var deckyPendingZip by mutableStateOf(null) var deckyReleaseRequest = 0 + var deckyPlugins by mutableStateOf>(emptyList()) + var deckyStore by mutableStateOf?>(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 @@ -90,6 +144,7 @@ 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() } diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index 1c0d4f8ef9..af3eddf8e7 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -921,7 +921,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")) section + navRequest = if (section in setOf("storage", "sync", "downloads", "decky", "boot-movies")) section else "settings:" + (com.droiddeck.launcher.ui.SettingsSection.of(section) ?: com.droiddeck.launcher.ui.SettingsSection.OVERVIEW).key request.data = null gameLinkReading = false @@ -2690,6 +2690,7 @@ 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, @@ -2800,6 +2801,9 @@ 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))) }, @@ -3090,6 +3094,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet decky.deckyInstalled = deckyInstalled decky.deckySupervisor = deckySupervisor decky.refreshDecky() + decky.refreshPlugins() } fetchAddedGameArt() } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/DeckyStore.kt b/app/src/main/java/com/droiddeck/launcher/runtime/DeckyStore.kt new file mode 100644 index 0000000000..451c5c2f82 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/runtime/DeckyStore.kt @@ -0,0 +1,102 @@ +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, val downloads: Long, val imageUrl: String, val versions: List) { + 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 { + 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? { + 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 = + 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 + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BootMovieSection.kt b/app/src/main/java/com/droiddeck/launcher/ui/BootMovieSection.kt index 2db14a9d74..077ba8a2cf 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BootMovieSection.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BootMovieSection.kt @@ -117,7 +117,7 @@ private fun rememberMovies(refresh: Int, onSelectionChanged: () -> Unit): MovieS } @Composable -private fun TabChip(label: String, selected: Boolean, modifier: Modifier = Modifier, onClick: () -> Unit) { +internal fun TabChip(label: String, selected: Boolean, modifier: Modifier = Modifier, onClick: () -> Unit) { val pal = LocalPalette.current val src = remember { MutableInteractionSource() } val hot = rememberHot(src) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DeckyIcon.kt b/app/src/main/java/com/droiddeck/launcher/ui/DeckyIcon.kt new file mode 100644 index 0000000000..aaa36f8ad0 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/DeckyIcon.kt @@ -0,0 +1,16 @@ +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() diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DeckyPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/DeckyPage.kt new file mode 100644 index 0000000000..0535e4a8eb --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/DeckyPage.kt @@ -0,0 +1,245 @@ +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, query: String): List { + 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(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() } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt index 73782db2ed..bc55af594e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt @@ -263,6 +263,10 @@ 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 diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt index 65dc828be8..2322e93827 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt @@ -56,6 +56,7 @@ 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.automirrored.outlined.ArrowBack @@ -206,6 +207,8 @@ internal fun railLabelIcon(key: String): Pair = 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()) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt b/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt index 920bb7f7f0..f58ee90807 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt @@ -126,6 +126,8 @@ 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 = diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt index fc611d6ca6..e931c7ec7a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -113,6 +113,9 @@ class ModeSettings( val deckyDownloadingBinary: Boolean = false, val deckyEnabled: Boolean = false, val deckySessionRunning: Boolean = false, + val deckyPlugins: List = emptyList(), + val deckyStore: List? = null, + val deckyStoreFailed: Boolean = false, ) class ModeSettingsActions( @@ -171,6 +174,9 @@ 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, ) @@ -220,6 +226,8 @@ 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 @@ -509,75 +517,6 @@ 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), @@ -607,7 +546,6 @@ 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) } @@ -669,7 +607,7 @@ internal fun DeckyZipWarningDialog(onConfirm: () -> Unit, onCancel: () -> Unit) private const val DECKY_ZIP_WARNING_SECONDS = 5 @Composable -private fun DeckyUninstall(enabled: Boolean, onUninstall: () -> Unit) { +internal 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) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt b/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt index 1a674da7f6..99785c488a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt @@ -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", "android-apps", "agent") - val DEFAULT_SHELVED = setOf("stores", "soundtracks", "components", "storage", "sync", "android-apps", "agent") + val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent") + val DEFAULT_SHELVED = setOf("stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent") val DEFAULT_HIDDEN = setOf("android-apps", "agent") - private val SHELVED_WHEN_NEW = setOf("storage", "sync", "android-apps", "agent") + private val SHELVED_WHEN_NEW = setOf("storage", "sync", "decky", "boot-movies", "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 diff --git a/app/src/main/java/com/droiddeck/launcher/ui/RailSettingsPages.kt b/app/src/main/java/com/droiddeck/launcher/ui/RailSettingsPages.kt index d25f723651..19af4ed03b 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/RailSettingsPages.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/RailSettingsPages.kt @@ -75,6 +75,19 @@ 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 diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt index cda181d501..b95dd6ae1b 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt @@ -93,6 +93,8 @@ 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"), diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index f8217b0fd5..018c08995c 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -332,7 +332,6 @@ بدء التشغيل الفتح عند التشغيل يبدأ هذه الجلسة عند تشغيل DroidDeck. - Decky جارٍ البحث عن إصدارات… جاهز لتثبيت %1$s. لم يتم العثور على إصدار متوافق. حاول مرة أخرى لاحقًا. @@ -341,14 +340,10 @@ محدَّث · %1$s المُحمِّل تثبيت أحدث إصدار - قناة التحديث - إصدارات Decky Loader التي تُثبَّت. يستخدم مُحدِّث Decky نفسه القناة ذاتها. مستقرة إصدار تجريبي مسبق اختبار تعذّر حفظ قناة تحديث Decky - يبدأ مع Steam. أثناء تفعيله، قد تتمكن التطبيقات الأخرى على هذا الجهاز من التحكم في Steam. - متوقف. يبقى منفذ تصحيح الأخطاء عن بُعد في Steam مغلقًا. هل تريد إلغاء تثبيت Decky Loader؟ يزيل المُحمِّل. يتم الاحتفاظ بالمكونات الإضافية والإعدادات. العميل diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 8b0e2378e3..2f30d0ba67 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -332,7 +332,6 @@ Inicio Abrir al iniciar Inicia esta sesión cuando se abre DroidDeck. - Decky Buscando versiones… Listo para instalar %1$s. No se encontró ninguna versión compatible. Inténtalo más tarde. @@ -341,14 +340,10 @@ Al día · %1$s Loader Instalar la última - Canal de actualizaciones - Qué versiones de Decky Loader se instalan. El actualizador propio de Decky usa el mismo canal. Estable Preliminar Pruebas No se pudo guardar el canal de actualizaciones de Decky - Se inicia con Steam. Mientras esté activado, otras apps de este dispositivo podrían controlar Steam. - Desactivado. El puerto de depuración remota de Steam permanece cerrado. ¿Desinstalar Decky Loader? Elimina el loader. Tus plugins y ajustes se conservan. Cliente diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index 8531a5dab1..3a2428fbfb 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -332,7 +332,6 @@ Стартиране Отваряне при стартиране Стартира тази сесия, когато DroidDeck се стартира. - Decky Проверка за издания… Готово за инсталиране на %1$s. Не е намерена съвместима версия. Опитайте по-късно. @@ -341,14 +340,10 @@ Актуално · %1$s Зареждач Инсталиране на последната версия - Канал за актуализации - Кои издания на Decky Loader да се инсталират. Собственият актуализатор на Decky използва същия канал. Стабилен Предварителен Тестов Каналът за актуализации на Decky не можа да бъде запазен - Стартира заедно със Steam. Докато е включено, други приложения на това устройство може да могат да контролират Steam. - Изключено. Портът за отдалечено дебъгване на Steam остава затворен. Деинсталиране на Decky Loader? Премахва зареждащия модул. Плъгините и настройките ви се запазват. Клиент diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index e8d2dc5c94..4c920c1cf0 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -332,7 +332,6 @@ Spouštění Otevřít při spuštění Spustí tuto relaci při spuštění DroidDeck. - Decky Hledání vydání… Připraveno k instalaci %1$s. Nenalezeno žádné kompatibilní sestavení. Zkuste to později. @@ -341,14 +340,10 @@ Aktuální · %1$s Loader Nainstalovat nejnovější - Kanál aktualizací - Která vydání Decky Loader instalovat. Vlastní aktualizátor Decky používá stejný kanál. Stabilní Předběžné vydání Testovací Kanál aktualizací Decky se nepodařilo uložit - Spouští se se Steamem. Když je zapnuto, jiné aplikace na tomto zařízení mohou mít možnost ovládat Steam. - Vypnuto. Port pro vzdálené ladění Steamu zůstává zavřený. Odinstalovat Decky Loader? Odstraní loader. Vaše pluginy a nastavení zůstanou zachovány. Klient diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 043a52c4b8..c34b855e74 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -332,7 +332,6 @@ Opstart Åbn ved start Starter denne session, når DroidDeck startes. - Decky Søger efter udgivelser… Klar til at installere %1$s. Ingen kompatibel build fundet. Prøv igen senere. @@ -341,14 +340,10 @@ Opdateret · %1$s Loader Installer nyeste - Opdateringskanal - Hvilke Decky Loader-udgivelser der installeres. Deckys egen opdatering bruger samme kanal. Stabil Forhåndsudgivelse Test Kunne ikke gemme Decky-opdateringskanalen - Starter med Steam. Mens den er til, kan andre apps på denne enhed muligvis styre Steam. - Fra. Steams fjerndebugport forbliver lukket. Afinstaller Decky Loader? Fjerner loaderen. Dine plugins og indstillinger bevares. Klient diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 4d52b46b32..8715f4b3a3 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -332,7 +332,6 @@ Start Beim Start öffnen Startet diese Sitzung, wenn DroidDeck startet. - Decky Suche nach Releases… Bereit zur Installation von %1$s. Kein kompatibler Build gefunden. Versuch es später noch einmal. @@ -341,14 +340,10 @@ Aktuell · %1$s Loader Neueste Version installieren - Update-Kanal - Welche Decky-Loader-Releases installiert werden. Deckys eigener Updater nutzt denselben Kanal. Stabil Vorabversion Test Decky-Update-Kanal konnte nicht gespeichert werden - Startet mit Steam. Solange aktiv, können andere Apps auf diesem Gerät Steam möglicherweise steuern. - Aus. Der Remote-Debugging-Port von Steam bleibt geschlossen. Decky Loader deinstallieren? Entfernt den Loader. Deine Plugins und Einstellungen bleiben erhalten. Client diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 826d8680e6..93b0438ef5 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -332,7 +332,6 @@ Εκκίνηση Άνοιγμα κατά την εκκίνηση Ξεκινά αυτή τη συνεδρία όταν ανοίγει το DroidDeck. - Decky Έλεγχος για εκδόσεις… Έτοιμο για εγκατάσταση %1$s. Δεν βρέθηκε συμβατό build. Δοκιμάστε ξανά αργότερα. @@ -341,14 +340,10 @@ Ενημερωμένο · %1$s Φορτωτής Εγκατάσταση τελευταίας έκδοσης - Κανάλι ενημερώσεων - Ποιες εκδόσεις του Decky Loader θα εγκατασταθούν. Το πρόγραμμα ενημέρωσης του Decky χρησιμοποιεί το ίδιο κανάλι. Σταθερό Προέκδοση Δοκιμαστικό Δεν ήταν δυνατή η αποθήκευση του καναλιού ενημερώσεων του Decky - Ξεκινά με το Steam. Όσο είναι ενεργό, άλλες εφαρμογές σε αυτή τη συσκευή μπορεί να είναι σε θέση να ελέγξουν το Steam. - Ανενεργό. Η θύρα απομακρυσμένου εντοπισμού σφαλμάτων του Steam παραμένει κλειστή. Κατάργηση εγκατάστασης του Decky Loader; Καταργεί τον loader. Τα plugins και οι ρυθμίσεις σας διατηρούνται. Πελάτης diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 3dcc0a4d1e..a8a7525c87 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -332,7 +332,6 @@ Inicio Abrir al iniciar Inicia esta sesión cuando se abre DroidDeck. - Decky Buscando versiones… Listo para instalar %1$s. No se encontró ninguna versión compatible. Inténtalo más tarde. @@ -341,14 +340,10 @@ Al día · %1$s Loader Instalar la última - Canal de actualizaciones - Qué versiones de Decky Loader se instalan. El actualizador propio de Decky usa el mismo canal. Estable Preliminar Pruebas No se ha podido guardar el canal de actualizaciones de Decky - Se inicia con Steam. Mientras esté activado, otras apps de este dispositivo podrían controlar Steam. - Desactivado. El puerto de depuración remota de Steam permanece cerrado. ¿Desinstalar Decky Loader? Elimina el loader. Tus plugins y ajustes se conservan. Cliente diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index ebe843786e..084d781755 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -332,7 +332,6 @@ Käynnistys Avaa käynnistyksessä Käynnistää tämän istunnon, kun DroidDeck avataan. - Decky Tarkistetaan julkaisuja… Valmiina asentamaan %1$s. Yhteensopivaa versiota ei löytynyt. Yritä myöhemmin uudelleen. @@ -341,14 +340,10 @@ Ajan tasalla · %1$s Lataaja Asenna uusin - Päivityskanava - Mitkä Decky Loader -julkaisut asennetaan. Deckyn oma päivitysohjelma käyttää samaa kanavaa. Vakaa Esijulkaisu Testaus Deckyn päivityskanavaa ei voitu tallentaa - Käynnistyy Steamin kanssa. Päällä ollessaan muut tämän laitteen sovellukset voivat pystyä ohjaamaan Steamia. - Pois. Steamin etävianmääritysportti pysyy suljettuna. Poistetaanko Decky Loader? Poistaa loaderin. Laajennuksesi ja asetuksesi säilyvät. Asiakasohjelma diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index bd5525aa28..c12f0c8afe 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -332,7 +332,6 @@ Démarrage Ouvrir au démarrage Lance cette session au démarrage de DroidDeck. - Decky Vérification des versions… Prêt à installer %1$s. Aucune version compatible trouvée. Veuillez réessayer plus tard. @@ -341,14 +340,10 @@ À jour · %1$s Chargeur Installer la dernière version - Canal de mise à jour - Les versions de Decky Loader à installer. Le programme de mise à jour de Decky utilise le même canal. Stable Préversion Test Impossible d\'enregistrer le canal de mise à jour de Decky - Démarre avec Steam. Une fois activé, d\'autres applications sur cet appareil peuvent contrôler Steam. - Désactivé. Le port de débogage distant de Steam reste fermé. Désinstaller Decky Loader ? Supprime le chargeur. Vos plugins et paramètres seront conservés. Client diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 7cd6bf3050..b2f2633475 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -332,7 +332,6 @@ स्टार्टअप लॉन्च पर खोलें DroidDeck खुलने पर यह सेशन शुरू करता है। - Decky रिलीज़ देखी जा रही हैं… %1$s इंस्टॉल करने के लिए तैयार। कोई कम्पैटिबल बिल्ड नहीं मिला। बाद में फिर कोशिश करें। @@ -341,14 +340,10 @@ नवीनतम · %1$s लोडर नवीनतम इंस्टॉल करें - अपडेट चैनल - कौन-सी Decky Loader रिलीज़ इंस्टॉल करनी हैं। Decky का अपना अपडेटर भी यही चैनल इस्तेमाल करता है। स्टेबल प्री-रिलीज़ टेस्टिंग Decky अपडेट चैनल सेव नहीं हो सका - Steam के साथ शुरू होता है। चालू रहते हुए, इस डिवाइस के दूसरे ऐप Steam को नियंत्रित कर सकते हैं। - बंद। Steam का रिमोट डिबगिंग पोर्ट बंद रहता है। Decky Loader अनइंस्टॉल करें? लोडर हटाता है। आपके प्लगइन और सेटिंग बनी रहती हैं। क्लाइंट diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index d4c46656d6..b9d15f6725 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -332,7 +332,6 @@ Indítás Megnyitás indításkor A DroidDeck indulásakor elindítja ezt a munkamenetet. - Decky Kiadások keresése… Készen áll a %1$s telepítésére. Nem található kompatibilis build. Próbálja újra később. @@ -341,14 +340,10 @@ Naprakész · %1$s Betöltő Legújabb telepítése - Frissítési csatorna - Mely Decky Loader-kiadások települjenek. A Decky saját frissítője ugyanezt a csatornát használja. Stabil Előzetes kiadás Tesztelés Nem sikerült menteni a Decky frissítési csatornáját - A Steammel együtt indul. Amíg be van kapcsolva, az eszközön lévő más alkalmazások is irányíthatják a Steamet. - Ki. A Steam távoli hibakeresési portja zárva marad. Eltávolítja a Decky Loadert? Eltávolítja a betöltőt. A bővítményei és beállításai megmaradnak. Kliens diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 53c9708ecc..56dd216a98 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -332,7 +332,6 @@ Mulai Buka saat peluncuran Memulai sesi ini saat DroidDeck diluncurkan. - Decky Memeriksa rilis… Siap menginstal %1$s. Tidak ditemukan build yang kompatibel. Coba lagi nanti. @@ -341,14 +340,10 @@ Terbaru · %1$s Loader Instal versi terbaru - Saluran Pembaruan - Rilis Decky Loader mana yang akan diinstal. Pembaru bawaan Decky menggunakan saluran yang sama. Stabil Prarilis Pengujian Tidak dapat menyimpan saluran pembaruan Decky - Dimulai bersama Steam. Saat aktif, aplikasi lain di perangkat ini mungkin dapat mengendalikan Steam. - Nonaktif. Port debugging jarak jauh Steam tetap tertutup. Hapus instalasi Decky Loader? Menghapus loader. Plugin dan setelan Anda tetap disimpan. Klien diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 78a9ae250a..9d574d4ba4 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -332,7 +332,6 @@ Avvio Apri all\'avvio Avvia questa sessione all\'avvio di DroidDeck. - Decky Ricerca di release… Pronto per installare %1$s. Nessuna build compatibile trovata. Riprova più tardi. @@ -341,14 +340,10 @@ Ultima versione · %1$s Loader Installa l\'ultima versione - Canale di aggiornamento - Quali release di Decky Loader installare. Anche l\'aggiornamento integrato di Decky usa lo stesso canale. Stabile Pre-release Test Impossibile salvare il canale di aggiornamento di Decky - Si avvia con Steam. Quando è attivo, altre app su questo dispositivo potrebbero controllare Steam. - Disattivato. La porta di debug remoto di Steam resta chiusa. Disinstallare Decky Loader? Rimuove il loader. I tuoi plugin e le impostazioni vengono mantenuti. Client diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index a7f1d18d19..f09bbbff7a 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -332,7 +332,6 @@ 起動 起動時に開く DroidDeck の起動時にこのセッションを開始します。 - Decky リリースを確認中… %1$sをインストールする準備ができました。 互換性のあるバージョンが見つかりません。後でもう一度お試しください。 @@ -341,14 +340,10 @@ 最新です · %1$s ローダー 最新バージョンをインストール - アップデートチャンネル - インストールするDecky Loaderのリリースです。Decky自身のアップデーターも同じチャンネルを使用します。 安定版 プレリリース版 テスト版 Deckyのアップデートチャンネルを保存できませんでした - Steamと共に起動します。有効にすると、このデバイス上の他のアプリがSteamを制御できる場合があります。 - オフ。Steamのリモートデバッグポートは閉じたままになります。 Decky Loaderをアンインストールしますか? ローダーを削除します。プラグインと設定は保持されます。 クライアント diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index f97db37e65..d7b6c044a1 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -332,7 +332,6 @@ 시작 실행 시 열기 DroidDeck을 실행할 때 이 세션을 시작합니다. - Decky 릴리스 확인 중… %1$s을(를) 설치할 준비가 되었습니다. 호환되는 버전을 찾을 수 없습니다. 나중에 다시 시도하세요. @@ -341,14 +340,10 @@ 최신 버전 · %1$s 로더 최신 버전 설치 - 업데이트 채널 - 설치할 Decky Loader 릴리스입니다. Decky 자체 업데이터도 같은 채널을 사용합니다. 안정판 사전 출시판 테스트판 Decky 업데이트 채널을 저장할 수 없습니다 - Steam과 함께 시작됩니다. 활성화하면 이 기기의 다른 앱이 Steam을 제어할 수 있습니다. - 끔. Steam의 원격 디버깅 포트가 닫힌 상태로 유지됩니다. Decky Loader를 제거하시겠습니까? 로더를 제거합니다. 플러그인과 설정은 유지됩니다. 클라이언트 diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index 9d2d102625..c4c67b0b6f 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -332,7 +332,6 @@ Permulaan Buka semasa pelancaran Memulakan sesi ini apabila DroidDeck dilancarkan. - Decky Menyemak keluaran… Sedia untuk memasang %1$s. Tiada binaan serasi ditemui. Cuba lagi kemudian. @@ -341,14 +340,10 @@ Terkini · %1$s Loader Pasang yang terbaharu - Saluran Kemas Kini - Keluaran Decky Loader yang hendak dipasang. Pengemas kini Decky sendiri menggunakan saluran yang sama. Stabil Prakeluaran Pengujian Tidak dapat menyimpan saluran kemas kini Decky - Bermula bersama Steam. Semasa dihidupkan, apl lain pada peranti ini mungkin boleh mengawal Steam. - Mati. Port debug jauh Steam kekal tertutup. Nyahpasang Decky Loader? Mengalih keluar loader. Plugin dan tetapan anda dikekalkan. Klien diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index a09d35a922..633b16d02e 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -332,7 +332,6 @@ Oppstart Åpne ved oppstart Starter denne økten når DroidDeck starter. - Decky Ser etter utgivelser… Klar til å installere %1$s. Ingen kompatibel build funnet. Prøv igjen senere. @@ -341,14 +340,10 @@ Oppdatert · %1$s Loader Installer nyeste - Oppdateringskanal - Hvilke Decky Loader-utgivelser som installeres. Deckys egen oppdatering bruker samme kanal. Stabil Forhåndsutgivelse Testing Kunne ikke lagre oppdateringskanalen for Decky - Starter med Steam. Mens på, kan andre apper på denne enheten kanskje styre Steam. - Av. Steams fjernsøkeport for feilsøking forblir stengt. Avinstaller Decky Loader? Fjerner loaderen. Programtilleggene og innstillingene dine beholdes. Klient diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 023fe7bb97..5f51dc1cd4 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -332,7 +332,6 @@ Opstarten Openen bij start Start deze sessie wanneer DroidDeck start. - Decky Zoeken naar releases… Klaar om %1$s te installeren. Geen compatibele build gevonden. Probeer het later opnieuw. @@ -341,14 +340,10 @@ Up-to-date · %1$s Loader Nieuwste installeren - Updatekanaal - Welke Decky Loader-releases worden geïnstalleerd. De eigen updater van Decky gebruikt hetzelfde kanaal. Stabiel Voorlopige release Testversie Kan het Decky-updatekanaal niet opslaan - Start met Steam. Zolang dit aan staat, kunnen andere apps op dit apparaat Steam mogelijk bedienen. - Uit. De poort voor foutopsporing op afstand van Steam blijft dicht. Decky Loader verwijderen? Verwijdert de loader. Je plug-ins en instellingen blijven behouden. Client diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 3ff4e06620..65a0f62751 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -332,7 +332,6 @@ Uruchamianie Otwórz przy uruchomieniu Uruchamia tę sesję po uruchomieniu DroidDeck. - Decky Sprawdzanie wydań… Gotowe do instalacji: %1$s. Nie znaleziono zgodnej wersji. Spróbuj ponownie później. @@ -341,14 +340,10 @@ Aktualna · %1$s Program ładujący Zainstaluj najnowszą - Kanał aktualizacji - Które wydania Decky Loader instalować. Wbudowany aktualizator Decky używa tego samego kanału. Stabilny Przedpremierowy Testowy Nie udało się zapisać kanału aktualizacji Decky - Uruchamia się ze Steam. Gdy jest włączony, inne aplikacje na tym urządzeniu mogą sterować Steam. - Wyłączony. Port zdalnego debugowania Steam pozostaje zamknięty. Odinstalować Decky Loader? Usuwa program ładujący. Twoje wtyczki i ustawienia zostaną zachowane. Klient diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 15c7cb206c..df9839df35 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -332,7 +332,6 @@ Arranque Abrir ao iniciar Inicia esta sessão quando o DroidDeck é aberto. - Decky A procurar versões… Pronto para instalar %1$s. Nenhuma versão compatível encontrada. Tente novamente mais tarde. @@ -341,14 +340,10 @@ Atualizado · %1$s Carregador Instalar a versão mais recente - Canal de atualização - Que versões do Decky Loader instalar. O atualizador do próprio Decky utiliza o mesmo canal. Estável Pré-lançamento Testes Não foi possível guardar o canal de atualização do Decky - Inicia com o Steam. Enquanto estiver ligado, outras apps neste dispositivo poderão controlar o Steam. - Desligado. A porta de depuração remota do Steam mantém-se fechada. Desinstalar o Decky Loader? Remove o carregador. Os seus plugins e definições são mantidos. Cliente diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 1e291f316b..47b370a046 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -332,7 +332,6 @@ Inicialização Abrir ao iniciar Inicia esta sessão quando o DroidDeck é aberto. - Decky Procurando versões… Pronto para instalar %1$s. Nenhuma versão compatível encontrada. Tente novamente mais tarde. @@ -341,14 +340,10 @@ Atualizado · %1$s Loader Instalar a mais recente - Canal de atualização - Quais versões do Decky Loader instalar. O atualizador do próprio Decky usa o mesmo canal. Estável Pré-lançamento Testes Não foi possível salvar o canal de atualização do Decky - Inicia com a Steam. Enquanto estiver ativado, outros apps neste dispositivo podem conseguir controlar a Steam. - Desativado. A porta de depuração remota da Steam fica fechada. Desinstalar o Decky Loader? Remove o loader. Seus plugins e configurações são mantidos. Cliente diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index f5868d56e5..69a16f1cf2 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -332,7 +332,6 @@ Pornire Deschide la pornire Pornește această sesiune când se lansează DroidDeck. - Decky Se verifică versiunile… Pregătit pentru instalarea %1$s. Nu s-a găsit o versiune compatibilă. Încearcă din nou mai târziu. @@ -341,14 +340,10 @@ Actualizat · %1$s Loader Instalează cea mai recentă versiune - Canal de actualizare - Ce versiuni Decky Loader se instalează. Actualizatorul propriu al Decky folosește același canal. Stabil Pre-lansare Testare Canalul de actualizare Decky nu a putut fi salvat - Pornește odată cu Steam. Cât timp este activ, alte aplicații de pe acest dispozitiv pot fi capabile să controleze Steam. - Dezactivat. Portul de depanare la distanță al Steam rămâne închis. Dezinstalezi Decky Loader? Elimină loader-ul. Pluginurile și setările tale sunt păstrate. Client diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index da7e65b3f6..e45c8af9a0 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -332,7 +332,6 @@ Запуск Открывать при запуске Запускает этот сеанс при запуске DroidDeck. - Decky Проверка выпусков… Готово к установке %1$s. Совместимая версия не найдена. Повторите попытку позже. @@ -341,14 +340,10 @@ Актуально · %1$s Загрузчик Установить последнюю - Канал обновлений - Какие выпуски Decky Loader устанавливать. Встроенное средство обновления Decky использует тот же канал. Стабильный Предварительный Тестовый Не удалось сохранить канал обновлений Decky - Запускается вместе со Steam. Пока включено, другие приложения на этом устройстве могут управлять Steam. - Выкл. Порт удаленной отладки Steam остается закрытым. Удалить Decky Loader? Удаляет загрузчик. Ваши плагины и настройки сохранятся. Клиент diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 58be1afa71..afa62b8e4a 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -332,7 +332,6 @@ Uppstart Öppna vid start Startar den här sessionen när DroidDeck startar. - Decky Söker efter utgåvor… Redo att installera %1$s. Inget kompatibelt bygge hittades. Försök igen senare. @@ -341,14 +340,10 @@ Senaste versionen · %1$s Loader Installera senaste - Uppdateringskanal - Vilka Decky Loader-utgåvor som installeras. Deckys egen uppdaterare använder samma kanal. Stabil Förhandsversion Test Det gick inte att spara Deckys uppdateringskanal - Startar med Steam. Medan det är på kan andra appar på enheten eventuellt styra Steam. - Av. Steams fjärrfelsökningsport förblir stängd. Avinstallera Decky Loader? Tar bort inläsaren. Dina tillägg och inställningar behålls. Klient diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index d8ec6f41e1..14a813ab5b 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -332,7 +332,6 @@ การเริ่มทำงาน เปิดเมื่อเริ่มต้น เริ่มเซสชันนี้เมื่อเปิด DroidDeck - Decky กำลังค้นหารุ่นที่เผยแพร่… พร้อมติดตั้ง %1$s ไม่พบบิลด์ที่เข้ากันได้ ลองใหม่อีกครั้งในหลัง @@ -341,14 +340,10 @@ เป็นรุ่นล่าสุดแล้ว · %1$s ตัวโหลด ติดตั้งรุ่นล่าสุด - ช่องทางอัปเดต - รุ่นของ Decky Loader ที่จะติดตั้ง ตัวอัปเดตของ Decky เองก็ใช้ช่องทางเดียวกัน เสถียร ก่อนเปิดตัว ทดสอบ บันทึกช่องทางอัปเดตของ Decky ไม่ได้ - เริ่มพร้อมกับ Steam เมื่อเปิดใช้งาน แอปอื่นบนอุปกรณ์นี้อาจสามารถควบคุม Steam ได้ - ปิดอยู่ พอร์ตดีบักระยะไกลของ Steam ยังคงปิดอยู่ ถอนการติดตั้ง Decky Loader? ลบตัวโหลดออก พลักอินและการตั้งค่าของคุณจะยังคงอยู่ ไคลเอนต์ diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 6bec3f37b5..9e67af3366 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -332,7 +332,6 @@ Başlangıç Açılışta başlat DroidDeck açıldığında bu oturumu başlatır. - Decky Sürümler kontrol ediliyor… %1$s yüklenmeye hazır. Uyumlu derleme bulunamadı. Daha sonra tekrar deneyin. @@ -341,14 +340,10 @@ Güncel · %1$s Yükleyici En yenisini yükle - Güncelleme kanalı - Hangi Decky Loader sürümlerinin yükleneceği. Decky\'nin kendi güncelleyicisi de aynı kanalı kullanır. Kararlı Ön sürüm Test Decky güncelleme kanalı kaydedilemedi - Steam ile başlar. Açıkken bu cihazdaki diğer uygulamalar Steam\'i kontrol edebilir. - Kapalı. Steam\'in uzaktan hata ayıklama bağlantı noktası kapalı kalır. Decky Loader kaldırılsın mı? Yükleyiciyi kaldırır. Eklentileriniz ve ayarlarınız korunur. İstemci diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 472a1d8050..8609b09b5d 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -332,7 +332,6 @@ Запуск Відкривати під час запуску Запускає цей сеанс під час запуску DroidDeck. - Decky Пошук випусків… Можна встановити %1$s. Сумісну збірку не знайдено. Спробуйте пізніше. @@ -341,14 +340,10 @@ Актуальна версія · %1$s Завантажувач Установити останню версію - Канал оновлень - Які випуски Decky Loader встановлювати. Власний засіб оновлення Decky використовує той самий канал. Стабільний Попередній Тестовий Не вдалося зберегти канал оновлень Decky - Запускається разом зі Steam. Поки його ввімкнено, інші додатки на цьому пристрої можуть керувати Steam. - Вимкнено. Порт віддаленого налагодження Steam залишається закритим. Видалити Decky Loader? Видаляє завантажувач. Ваші плагіни й налаштування зберігаються. Клієнт diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index fbf6432863..fd23d10b90 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -332,7 +332,6 @@ Khởi động Mở khi khởi chạy Bắt đầu phiên này khi DroidDeck khởi chạy. - Decky Đang kiểm tra bản phát hành… Sẵn sàng cài %1$s. Không tìm thấy bản build tương thích. Hãy thử lại sau. @@ -341,14 +340,10 @@ Đã mới nhất · %1$s Loader Cài bản mới nhất - Kênh cập nhật - Các bản phát hành Decky Loader sẽ cài. Trình cập nhật riêng của Decky dùng cùng kênh này. Ổn định Tiền phát hành Thử nghiệm Không thể lưu kênh cập nhật Decky - Khởi động cùng Steam. Khi đang bật, các ứng dụng khác trên thiết bị này có thể điều khiển được Steam. - Tắt. Cổng gỡ lỗi từ xa của Steam luôn đóng. Gỡ cài đặt Decky Loader? Gỡ bỏ loader. Plugin và thiết lập của bạn được giữ lại. Client diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 4446a1fb81..aa46013f4a 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -332,7 +332,6 @@ 启动 启动时打开 DroidDeck 启动时开始此会话。 - Decky 正在检查发布版本… 已就绪,可安装 %1$s。 未找到兼容的构建。请稍后重试。 @@ -341,14 +340,10 @@ 已是最新 · %1$s 加载器 安装最新版 - 更新通道 - 要安装哪种 Decky Loader 版本。Decky 自带的更新程序也使用相同的通道。 稳定版 预发布版 测试版 无法保存 Decky 更新通道 - 随 Steam 启动。开启期间,本设备上的其他应用可能可以控制 Steam。 - 已关闭。Steam 的远程调试端口保持关闭。 卸载 Decky Loader? 移除加载器。你的插件和设置会保留。 客户端 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index daa483e57d..1bec44cc0a 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -332,7 +332,6 @@ 啟動 啟動時開啟 DroidDeck 啟動時開始此工作階段。 - Decky 正在檢查發佈版本… 可安裝 %1$s。 找不到兼容的版本,請稍後再試。 @@ -341,14 +340,10 @@ 已是最新 · %1$s 載入器 安裝最新版本 - 更新頻道 - 要安裝哪一種 Decky Loader 版本。Decky 本身的更新程式也會使用相同的頻道。 穩定版 預發佈版 測試版 無法儲存 Decky 更新頻道 - 隨 Steam 啟動。啟用時,此裝置上的其他應用程式可能可以控制 Steam。 - 已關閉。Steam 的遠端偵錯連接埠保持關閉。 解除安裝 Decky Loader? 移除載入器,你的插件和設定會保留。 用戶端 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 18805781c2..d484813b1e 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -332,7 +332,6 @@ 啟動 啟動時開啟 DroidDeck 啟動時開始此工作階段。 - Decky 正在檢查發行版本… 已準備好安裝 %1$s。 未找到相容版本。請稍後再試。 @@ -341,14 +340,10 @@ 已是最新 · %1$s 載入器 安裝最新版本 - 更新頻道 - 要安裝哪一種 Decky Loader 版本。Decky 本身的更新程式也會使用相同的頻道。 穩定版 預先發行版 測試版 無法儲存 Decky 更新頻道 - 隨 Steam 啟動。啟用後,此裝置上的其他應用程式可能可以控制 Steam。 - 關閉。Steam 的遠端偵錯連接埠保持關閉。 解除安裝 Decky Loader? 移除載入器。你的外掛程式和設定會保留。 用戶端 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ad2bdfe362..3e52b58b21 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -362,7 +362,6 @@ Startup Open at launch Starts this session when DroidDeck launches. - Decky Checking for releases… Ready to install %1$s. No compatible build found. Try again later. @@ -371,14 +370,10 @@ Up to date · %1$s Loader Install latest - Update Channel - Which Decky Loader releases to install. Decky\'s own updater uses the same channel. Stable Prerelease Testing Could not save the Decky update channel - Starts with Steam. While on, other apps on this device may be able to control Steam. - Off. Steam\'s remote debugging port stays closed. Uninstall Decky Loader? Removes the loader. Your plugins and settings are kept. Client @@ -4324,6 +4319,27 @@ In-game menu In-game menu preview · Back to close Tabs + Status + Enable + Release channel + Decky + Boot movies + Installed · %1$d + Store + From ZIP + No plugins installed. Browse the Store or install a ZIP. + Update to %1$s + Remove + Remove %1$s? + Deletes the plugin from Decky. Its settings are kept. + Plugin changes apply the next time Steam starts. + Search plugins + Could not reach the Decky plugin store + No plugins found + Show %1$d more + Downloading %1$s… + Could not download %1$s + Could not remove the plugin Storage Syncthing Download settings diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/DeckyStoreTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/DeckyStoreTest.kt new file mode 100644 index 0000000000..67bf7d8614 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/runtime/DeckyStoreTest.kt @@ -0,0 +1,47 @@ +package com.droiddeck.launcher.runtime + +import com.droiddeck.launcher.ui.deckyStoreMatches +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class) +@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class) +class DeckyStoreTest { + private val hash = "a".repeat(64) + private val listing = """[ + {"id":1,"name":"Alpha","author":"Ann","description":"Does alpha things","tags":["audio"],"image_url":"https://cdn.example/a.png", + "versions":[{"name":"2.0.0","hash":"$hash","downloads":10},{"name":"1.0.0","hash":"${"b".repeat(64)}","downloads":5}]}, + {"id":2,"name":"Beta","author":"Bob","description":"Themes","tags":["css"],"versions":[{"name":"1.0.0","hash":"${"c".repeat(64)}","downloads":100}]}, + {"id":3,"name":"NoVersions","author":"X","description":"","tags":[],"versions":[]}, + {"id":4,"name":"BadHash","author":"X","description":"","tags":[],"versions":[{"name":"1","hash":"nope","downloads":1}]} + ]""" + + @Test fun listingKeepsOnlyPluginsWithAUsableVersionAndSumsDownloads() { + val plugins = DeckyStore.parseListing(listing) + assertEquals(listOf("Alpha", "Beta"), plugins.map { it.name }) + assertEquals("2.0.0", plugins[0].latest?.name) + assertEquals(15L, plugins[0].downloads) + assertEquals("https://cdn.example/a.png", plugins[0].imageUrl) + assertEquals("", plugins[1].imageUrl) + } + + @Test fun searchMatchesNameAuthorDescriptionAndTagsAndSortsByDownloads() { + val plugins = DeckyStore.parseListing(listing) + assertEquals(listOf("Beta", "Alpha"), deckyStoreMatches(plugins, "").map { it.name }) + assertEquals(listOf("Alpha"), deckyStoreMatches(plugins, "ann audio").map { it.name }) + assertEquals(listOf("Beta"), deckyStoreMatches(plugins, "THEMES").map { it.name }) + assertTrue(deckyStoreMatches(plugins, "missing").isEmpty()) + } + + @Test fun anUpdateNeedsAKnownInstalledVersionThatDiffersFromTheLatest() { + val alpha = DeckyStore.parseListing(listing).first() + assertTrue(DeckyStore.updateAvailable(DeckyStore.Installed("Alpha", "Alpha", "Ann", "1.0.0"), alpha)) + assertFalse(DeckyStore.updateAvailable(DeckyStore.Installed("Alpha", "Alpha", "Ann", "2.0.0"), alpha)) + assertFalse(DeckyStore.updateAvailable(DeckyStore.Installed("Alpha", "Alpha", "Ann", ""), alpha)) + assertFalse(DeckyStore.updateAvailable(DeckyStore.Installed("Alpha", "Alpha", "Ann", "1.0.0"), null)) + assertNull(DeckyStore.parseListing("[]").firstOrNull()) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt index 1736382512..8e9fcad74a 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt @@ -41,7 +41,7 @@ class NavTabsTest { @Test fun aFreshInstallShowsTheDefaultBarMoreAndHiddenTabs() { assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", NavTabs.MORE), navigationKeys(state())) - assertEquals(listOf("stores", "soundtracks", "components", "storage", "sync"), NavTabs.more(state())) + assertEquals(listOf("stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(state())) assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "android-apps")) assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "agent")) assertFalse(com.droiddeck.launcher.agent.AgentTab.shown) @@ -57,7 +57,7 @@ class NavTabsTest { @Test fun shelvedTabsLeaveTheBarAndAddMoreAtTheEnd() { place("desktop", TabPlace.MORE) val s = state() - assertEquals(listOf("desktop", "stores", "soundtracks", "components", "storage", "sync"), NavTabs.more(s)) + assertEquals(listOf("desktop", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(s)) assertEquals(NavTabs.MORE, navigationKeys(s).last()) assertFalse("desktop" in navigationKeys(s)) } @@ -86,7 +86,7 @@ class NavTabsTest { NavTabs.load(ctx) val s = state() assertEquals(listOf("steam", "games", "desktop", "components", "setup", "updates", NavTabs.MORE), navigationKeys(s)) - assertEquals(listOf("storage", "sync"), NavTabs.more(s)) + assertEquals(listOf("storage", "sync", "decky", "boot-movies"), NavTabs.more(s)) listOf("stores", "downloads", "soundtracks", "android-apps", "agent").forEach { assertEquals(it, TabPlace.HIDDEN, NavTabs.place(s, it)) } val prefs = ctx.getSharedPreferences("session", Context.MODE_PRIVATE) assertFalse(prefs.contains("gameStoresEnabled")) @@ -108,7 +108,7 @@ class NavTabsTest { assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "stores")) assertEquals(TabPlace.MORE, NavTabs.place(state(), "components")) assertEquals(TabPlace.BAR, NavTabs.place(state(), "downloads")) - assertEquals(listOf("components", "storage", "sync"), NavTabs.more(state())) + assertEquals(listOf("components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(state())) } @Test fun movingSwapsWithTheNextVisibleTabAndPersists() { @@ -119,9 +119,9 @@ class NavTabsTest { } @Test fun tabsMissingFromASavedOrderSlotInAfterTheirDefaultNeighbour() { - assertEquals(listOf("updates", "stores", "soundtracks", "components", "storage", "sync", "android-apps", "agent", "steam", "desktop", "games", "downloads", "setup"), + assertEquals(listOf("updates", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent", "steam", "desktop", "games", "downloads", "setup"), NavTabs.arrange(listOf("updates", "steam"))) - assertEquals(listOf("games", "downloads", "steam", "setup", "stores", "soundtracks", "desktop", "components", "storage", "sync", "android-apps", "agent", "updates"), + assertEquals(listOf("games", "downloads", "steam", "setup", "stores", "soundtracks", "desktop", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent", "updates"), NavTabs.arrange(listOf("games", "steam", "setup", "stores", "desktop", "components", "android-apps", "updates", "bogus"))) } @@ -130,7 +130,7 @@ class NavTabsTest { .putString("navTabOrder", "steam,games,soundtracks,stores,desktop,agent,components,android-apps,setup,updates") .putString("navTabShelved", "soundtracks").commit() NavTabs.load(ctx) - assertEquals(listOf("soundtracks", "storage", "sync"), NavTabs.more(state())) + assertEquals(listOf("soundtracks", "storage", "sync", "decky", "boot-movies"), NavTabs.more(state())) place("sync", TabPlace.BAR) NavTabs.load(ctx) assertTrue("sync" in navigationKeys(state())) diff --git a/docs/settings-map.md b/docs/settings-map.md index 6b13633780..bcef3a25c3 100644 --- a/docs/settings-map.md +++ b/docs/settings-map.md @@ -65,6 +65,8 @@ Links of the form `droiddeck://settings/
` open a Settings section direc | --- | --- | --- | | Storage | Tabs › Storage | sd card, space, uninstall, disk | | Syncthing | Tabs › Syncthing | syncthing, saves | +| Decky | Tabs › Decky | plugins, plugin store, homebrew, loader | +| Boot movies | Tabs › Boot movies | startup movie, boot video, animation, steamdeckrepo | | Download speed tier | Tabs › Downloads | download, speed, bandwidth, slow | | Downloads at a time | Tabs › Downloads | download, parallel, queue, at once | | Tabs | Tabs › More | tabs, hide, reorder, agent, stores, edit tabs | From a305a91c66eb72c4b51cf65e34ea63d1e4737bd5 Mon Sep 17 00:00:00 2001 From: Dantalian Date: Mon, 23 Nov 2026 23:16:39 +0800 Subject: [PATCH 058/141] feat(files): add a plain text editor to the file manager (#2980) * feat(files): add a plain text editor to the file manager * fix(files): address CodeRabbit review on the text editor - compose the editor instead of the toolbar so EXIT can't bypass the unsaved-changes guard - read through a capped stream, keep undecodable files read-only, and preserve POSIX permissions via staging-file rename with no direct-write fallback - serialize saves, keep dirty consistent across concurrent edits, reset match index on text change, fix empty-state counter and read-only replace buttons - scroll match into view horizontally; ignore cursor-only edits for dirty - add tests for literal U+FFFD files and the capped reader * fix(files): treat rename failure as save error and follow symbolic links * test(files): assert the resolved save target without canonicalizing it --------- Co-authored-by: Dantalian --- app/src/main/AndroidManifest.xml | 1 + .../launcher/files/FileManagerItems.kt | 15 + .../launcher/files/FileManagerScreen.kt | 17 +- .../launcher/files/TextEditorScreen.kt | 726 ++++++++++++++++++ app/src/main/res/values/strings.xml | 17 + .../launcher/files/TextEditorLogicTest.kt | 143 ++++ 6 files changed, 918 insertions(+), 1 deletion(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/files/TextEditorScreen.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/files/TextEditorLogicTest.kt diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 30650081fc..55b75d36df 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -232,6 +232,7 @@ android:exported="false" android:screenOrientation="user" android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density" + android:windowSoftInputMode="adjustResize" android:theme="@style/AppTheme" /> 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) }, @@ -180,6 +191,7 @@ internal fun FileItemRow( onCut: () -> Unit, onDelete: () -> Unit, onRename: () -> Unit, + onOpen: () -> Unit = {}, isFavorite: Boolean = false, onToggleFavorite: () -> Unit = {}, onProperties: () -> Unit = {}, @@ -291,6 +303,7 @@ internal fun FileItemRow( file = file, isFavorite = isFavorite, onSelect = onSelect, + onOpen = onOpen, onRename = onRename, onCopy = onCopy, onCut = onCut, @@ -517,6 +530,7 @@ internal fun FileGridTile( isFavorite: Boolean = false, onSelect: () -> Unit = {}, onRename: () -> Unit = {}, + onOpen: () -> Unit = {}, onCopy: () -> Unit = {}, onCut: () -> Unit = {}, onDelete: () -> Unit = {}, @@ -605,6 +619,7 @@ internal fun FileGridTile( file = file, isFavorite = isFavorite, onSelect = onSelect, + onOpen = onOpen, onRename = onRename, onCopy = onCopy, onCut = onCut, diff --git a/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt b/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt index 9945083226..7025769d87 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt @@ -191,6 +191,7 @@ fun FileManagerScreen( var compactRows by remember { mutableStateOf(browsePrefs.getBoolean("fmCompactRows", false)) } var showNewFolderDialog by remember { mutableStateOf(false) } var renameTarget by remember { mutableStateOf(null) } + var editingTarget by remember { mutableStateOf(null) } var propertiesTarget by remember { mutableStateOf(null) } var isOperationRunning by remember { mutableStateOf(false) } var operationLabel by remember { mutableStateOf("") } @@ -294,7 +295,7 @@ fun FileManagerScreen( if (isOperationActive()) pendingNavigation = action else navigate(action) } - BackHandler(enabled = operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot || history.isNotEmpty()) { + BackHandler(enabled = editingTarget == null && (operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot || history.isNotEmpty())) { requestNavigation(FileManagerNavigation.BACK) } @@ -696,6 +697,14 @@ 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, @@ -1194,6 +1203,8 @@ fun FileManagerScreen( pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply() onPick?.invoke(file) } + } else { + editingTarget = file } }, onMenu = { showMenuFor = file }, @@ -1205,6 +1216,7 @@ 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 }, @@ -1273,6 +1285,8 @@ fun FileManagerScreen( pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply() onPick?.invoke(file) } + } else { + editingTarget = file } }, onMenu = { showMenuFor = file }, @@ -1286,6 +1300,7 @@ 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 = { diff --git a/app/src/main/java/com/droiddeck/launcher/files/TextEditorScreen.kt b/app/src/main/java/com/droiddeck/launcher/files/TextEditorScreen.kt new file mode 100644 index 0000000000..2d9c0a3fea --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/files/TextEditorScreen.kt @@ -0,0 +1,726 @@ +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 { + if (query.isEmpty()) return emptyList() + val out = ArrayList() + 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, 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(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), + ) + } + } +} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 3e52b58b21..68940091f6 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -2216,6 +2216,23 @@ Removed \"%1$s\" from Favorites Empty directory Up one level + Open + Save + Read only + Binary + Modified + Ln %1$d, Col %2$d + Find + Find previous + Find next + Replace + All + Discard changes? + Changes to \"%1$s\" will be lost. + Discard + Couldn\'t save \"%1$s\" + Couldn\'t open \"%1$s\" + Too large to open (%1$s) Choose a folder Choose a file Steam blue diff --git a/app/src/test/java/com/droiddeck/launcher/files/TextEditorLogicTest.kt b/app/src/test/java/com/droiddeck/launcher/files/TextEditorLogicTest.kt new file mode 100644 index 0000000000..7fb3a7a68b --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/files/TextEditorLogicTest.kt @@ -0,0 +1,143 @@ +package com.droiddeck.launcher.files + +import java.io.ByteArrayInputStream +import java.io.File +import java.nio.charset.Charset +import java.nio.file.Files +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class TextEditorLogicTest { + + @Test + fun nulByteMarksBinary() { + val clean = "hello world".toByteArray() + assertFalse(editorIsBinary(clean)) + val withNul = byteArrayOf(1, 2, 0, 3) + assertTrue(editorIsBinary(withNul)) + } + + @Test + fun binaryScanStopsAtSampleLimit() { + val bytes = ByteArray(9000) { if (it == 8999) 0 else 65 } + assertFalse(editorIsBinary(bytes)) + assertTrue(editorIsBinary(bytes, sample = 9000)) + } + + @Test + fun utf8TextDecodesAsUtf8() { + val decoded = decodeEditorText("你好, world".toByteArray(Charsets.UTF_8)) + assertEquals(EditorCharset.UTF8, decoded.charset) + assertFalse(decoded.lossy) + assertEquals("你好, world", decoded.text) + } + + @Test + fun gbkBytesFallBackToGb18030() { + val gbk = "你好".toByteArray(Charset.forName("GBK")) + val decoded = decodeEditorText(gbk) + assertEquals(EditorCharset.GB18030, decoded.charset) + assertFalse(decoded.lossy) + assertEquals("你好", decoded.text) + } + + @Test + fun undecodableBytesStayLossyUtf8() { + val decoded = decodeEditorText(byteArrayOf(0xFF.toByte())) + assertEquals(EditorCharset.UTF8, decoded.charset) + assertTrue(decoded.lossy) + } + + @Test + fun literalReplacementCharStaysCleanUtf8() { + val decoded = decodeEditorText("�A".toByteArray(Charsets.UTF_8)) + assertEquals(EditorCharset.UTF8, decoded.charset) + assertFalse(decoded.lossy) + } + + @Test + fun readCappedRefusesOverLimit() { + val data = ByteArray(100) { 65 } + assertArrayEquals(data, readCapped(ByteArrayInputStream(data), 100L)) + assertNull(readCapped(ByteArrayInputStream(data), 99L)) + } + + @Test + fun tabsExpandToTabStops() { + assertEquals("ab c", expandEditorTabs("ab\tc")) + assertEquals(" x", expandEditorTabs("\tx")) + assertEquals("abcd e", expandEditorTabs("abcd\te")) + assertEquals("abc def g", expandEditorTabs("abc\tdef\tg")) + assertEquals("a \n b", expandEditorTabs("a\t\n\tb")) + assertEquals("plain text", expandEditorTabs("plain text")) + } + + @Test + fun lineCountCountsTrailingEmptyLine() { + assertEquals(1, lineCountOf("")) + assertEquals(1, lineCountOf("abc")) + assertEquals(2, lineCountOf("a\nb")) + assertEquals(2, lineCountOf("a\n")) + } + + @Test + fun offsetMapsToZeroBasedLineAndOneBasedColumn() { + val text = "ab\ncd" + assertEquals(0, lineIndexOfOffset(text, 0)) + assertEquals(0, lineIndexOfOffset(text, 2)) + assertEquals(1, lineIndexOfOffset(text, 3)) + assertEquals(1, lineIndexOfOffset(text, 5)) + assertEquals(1, columnOfOffset(text, 0)) + assertEquals(3, columnOfOffset(text, 2)) + assertEquals(2, columnOfOffset(text, 4)) + assertEquals(3, columnOfOffset(text, 5)) + } + + @Test + fun findMatchesHonorsCaseAndLimit() { + val text = "abcABCabc" + val all = findEditorMatches(text, "abc", matchCase = false) + assertEquals(listOf(0..2, 3..5, 6..8), all) + val exact = findEditorMatches(text, "abc", matchCase = true) + assertEquals(listOf(0..2, 6..8), exact) + assertEquals(2, findEditorMatches(text, "abc", matchCase = false, limit = 2).size) + assertEquals(emptyList(), findEditorMatches(text, "")) + assertEquals(listOf(0..1), findEditorMatches("aaa", "aa")) + } + + @Test + fun replaceSpansEveryMatch() { + val text = "one two one" + val matches = findEditorMatches(text, "one", matchCase = true) + assertEquals("1 two 1", replaceEditorMatches(text, matches, "1")) + assertEquals(text, replaceEditorMatches(text, emptyList(), "x")) + } + + @Test + fun saveTargetResolvesSymbolicLink() { + val dir = Files.createTempDirectory("editor-link").toFile() + try { + val target = File(dir, "real.txt").apply { writeText("hi") } + val link = File(dir, "link.txt") + Files.createSymbolicLink(link.toPath(), target.toPath()) + assertEquals(target.canonicalFile, resolveEditorSaveTarget(link)) + } finally { + dir.deleteRecursively() + } + } + + @Test + fun saveTargetKeepsRegularFile() { + val dir = Files.createTempDirectory("editor-plain").toFile() + try { + val plain = File(dir, "plain.txt").apply { writeText("hi") } + assertEquals(plain, resolveEditorSaveTarget(plain)) + } finally { + dir.deleteRecursively() + } + } +} From 3b8b14b06c21c97c190a888a939848056702b51a Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Mon, 23 Nov 2026 10:27:47 -0500 Subject: [PATCH 059/141] fix(session): FEX and AppImage extraction no longer hang at start-up (#3070) The clock pause preload opened its control file on the first monotonic clock read. A program whose allocator reads the clock while holding its own lock, as FEX does while it starts, re-entered that allocator through the open wrappers and deadlocked. The control file is now opened only in the preload's constructor, so a clock read never opens a file. --- tools/linuxfs/preload/clockpause.c | 16 +------ tools/tests/test_clock_pause_preload.py | 57 +++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 14 deletions(-) diff --git a/tools/linuxfs/preload/clockpause.c b/tools/linuxfs/preload/clockpause.c index 8fe0b7ce77..70b4179329 100644 --- a/tools/linuxfs/preload/clockpause.c +++ b/tools/linuxfs/preload/clockpause.c @@ -25,7 +25,6 @@ #define CP_FDS 65536 static const int64_t *cp_shift; -static int cp_state; static size_t cp_cond_byte; static unsigned char cp_cond_mask; static unsigned char cp_fds[CP_FDS / 8]; @@ -94,25 +93,14 @@ static void cp_init(void) { } static int64_t cp_offset(void) { - const int64_t *shift; - int state = __atomic_load_n(&cp_state, __ATOMIC_ACQUIRE); - if (state == 0) { - int expected = 0; - if (__atomic_compare_exchange_n(&cp_state, &expected, 1, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) { - cp_init(); - __atomic_store_n(&cp_state, 2, __ATOMIC_RELEASE); - } - return 0; - } - if (state != 2) return 0; - shift = __atomic_load_n(&cp_shift, __ATOMIC_ACQUIRE); + const int64_t *shift = __atomic_load_n(&cp_shift, __ATOMIC_ACQUIRE); if (!shift) return 0; int64_t value = __atomic_load_n(shift, __ATOMIC_RELAXED); return value > 0 ? value : 0; } __attribute__((constructor)) static void cp_start(void) { - cp_offset(); + cp_init(); } static int cp_mono(clockid_t clock) { diff --git a/tools/tests/test_clock_pause_preload.py b/tools/tests/test_clock_pause_preload.py index 3d3f0dd76b..7b92a444bc 100644 --- a/tools/tests/test_clock_pause_preload.py +++ b/tools/tests/test_clock_pause_preload.py @@ -107,6 +107,51 @@ int main(void) { } """ +EARLY_LIBRARY = r""" +#include +#include + +pthread_mutex_t early_lock = PTHREAD_MUTEX_INITIALIZER; + +__attribute__((constructor)) static void early_start(void) { + struct timespec ts; + pthread_mutex_lock(&early_lock); + clock_gettime(CLOCK_MONOTONIC, &ts); + pthread_mutex_unlock(&early_lock); +} +""" + +EARLY_PROGRAM = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include + +extern pthread_mutex_t early_lock; + +int open(const char *path, int flags, ...) { + va_list args; + va_start(args, flags); + mode_t mode = (mode_t)va_arg(args, int); + va_end(args); + pthread_mutex_lock(&early_lock); + pthread_mutex_unlock(&early_lock); + return (int)syscall(SYS_openat, AT_FDCWD, path, flags, mode); +} + +int main(void) { + struct timespec mono, boot; + clock_gettime(CLOCK_MONOTONIC, &mono); + clock_gettime(CLOCK_BOOTTIME, &boot); + printf("gap %lld\n", (long long)(((boot.tv_sec - mono.tv_sec) * 1000000000LL + boot.tv_nsec - mono.tv_nsec) / 1000000LL)); + return 0; +} +""" + SHIFT_MS = 10000 @@ -128,6 +173,13 @@ class ClockPausePreloadTest(unittest.TestCase): subprocess.run(["cc", "-O2", "-pthread", "-o", str(cls.shell), str(build / "program.c")], check=True) cls.other = build / "kwin_wayland" shutil.copy(cls.shell, cls.other) + (build / "early.c").write_text(EARLY_LIBRARY) + (build / "early_program.c").write_text(EARLY_PROGRAM) + subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-pthread", "-o", str(build / "libearly.so"), + str(build / "early.c")], check=True) + cls.early = build / "early_program" + subprocess.run(["cc", "-O2", "-pthread", "-o", str(cls.early), str(build / "early_program.c"), + "-L", str(build), "-learly", "-Wl,-rpath," + str(build)], check=True) @classmethod def tearDownClass(cls): @@ -153,6 +205,11 @@ class ClockPausePreloadTest(unittest.TestCase): self.assertGreaterEqual(paused[name], 50, name) self.assertLess(paused[name], 1000, name) + def test_clock_read_inside_a_library_constructor_does_not_reenter_the_program(self): + plain = self.run_program(self.early, 0) + paused = self.run_program(self.early, SHIFT_MS) + self.assertAlmostEqual(paused["gap"] - plain["gap"], SHIFT_MS, delta=50) + def test_program_without_preload_keeps_the_real_clock(self): plain = self.run_program(self.other, 0, preload=False) paused = self.run_program(self.other, SHIFT_MS, preload=False) From bf7f7ecda79754e8cc51f67484629b4e04801844 Mon Sep 17 00:00:00 2001 From: The412Banner <205237651+The412Banner@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:40:16 -0500 Subject: [PATCH 060/141] fix(nativeguest): a spawned "ld.so --list PROGRAM" loads the program from the rootfs (#3054) * fix(nativeguest): a spawned "ld.so --list PROGRAM" loads the program from the rootfs * fix(nativeguest): keep the existing ld.so start comments --------- Co-authored-by: maxjivi05 --- tools/nativeguest/hook/exec.c | 130 ++++++++++-------- tools/tests/test_native_hook_ldso_spawn.py | 147 +++++++++++++++++++++ 2 files changed, 220 insertions(+), 57 deletions(-) create mode 100644 tools/tests/test_native_hook_ldso_spawn.py diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index ce91b699b5..3f316fc3b3 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -263,6 +263,60 @@ static int is_ldconfig_name(const char *name) { return strcmp(name, "ldconfig") == 0 || strcmp(name, "ldconfig.real") == 0; } +struct ldso_direct { + char prog[PATH_MAX]; + char lib_path[PATH_MAX * 6]; +}; + +// ld.so started directly (ldd, "ld.so --list PROGRAM", "ld.so PROGRAM"): the program it loads +// gets the --library-path a start of its own gets, or ldd reports its libraries as not found, +// and its path mapped into the rootfs, since ld.so opens it without the hook +static char **ldso_direct_argv(char *const argv[], char *const envp[], struct ldso_direct *buf, int *err) { + *err = 0; + int caller_lib_path = 0; + int pi = ldso_program_index(argv, &caller_lib_path); + if (pi <= 0) return NULL; + int argc = 0; + while (argv[argc]) argc++; + const char *prog = argv[pi]; + if (caller_lib_path) { + // the caller's own --library-path stays as it is; only the program is mapped (when it is + // in the rootfs: a caller can also name a file by its real path) + if (prog[0] == '/') { + const char *mapped = rewrite_path(prog, buf->prog, sizeof(buf->prog)); + int fd = mapped != prog ? (int)syscall(SYS_openat, AT_FDCWD, mapped, O_PATH | O_CLOEXEC) : -1; + if (fd >= 0) { + syscall(SYS_close, fd); + prog = mapped; + } + } + char **out = (char **)malloc(sizeof(char *) * (size_t)(argc + 1)); + if (!out) { + *err = ENOMEM; + return NULL; + } + for (int i = 0; i <= argc; i++) out[i] = argv[i]; + out[pi] = (char *)prog; + return out; + } + if (prog[0] == '/') prog = rewrite_path(prog, buf->prog, sizeof(buf->prog)); + struct exec_probe prog_probe; + probe_exec_file(prog, &prog_probe); + build_ld_library_path(envp, prog_probe.runpath, prog_probe.runpath_is_rpath, + prog[0] == '/' ? prog : NULL, buf->lib_path, sizeof(buf->lib_path)); + char **out = (char **)malloc(sizeof(char *) * (size_t)(argc + 3)); + if (!out) { + *err = ENOMEM; + return NULL; + } + out[0] = argv[0]; + out[1] = (char *)"--library-path"; + out[2] = buf->lib_path; + for (int i = 1; i <= argc; i++) out[i + 2] = argv[i]; + out[pi + 2] = (char *)prog; // ld.so opens it itself: "ldd /usr/bin/adb" as well + return out; +} + static int ddnatv_execve(const char *filename, char *const argv[], char *const envp[], int depth) { orig_execve_f_type orig_execve = real_execve(); if (!orig_execve) { @@ -388,63 +442,15 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e } } - // ld.so started directly (ldd, "ld.so --list PROGRAM", "ld.so PROGRAM"): the program it loads - // gets the --library-path a start of its own gets, or ldd reports its libraries as not found, - // and its path mapped into the rootfs, since ld.so opens it without the hook if (probe.is_elf && !probe.is_dynamic && is_ld_linux(elf_target)) { - int caller_lib_path = 0; - int pi = ldso_program_index(argv, &caller_lib_path); - if (pi > 0 && caller_lib_path) { - // the caller's own --library-path stays as it is; only the program is mapped (when it is - // in the rootfs: a caller can also name a file by its real path) - char prog_buf[PATH_MAX]; - const char *prog = argv[pi]; - if (prog[0] == '/') { - const char *mapped = rewrite_path(prog, prog_buf, sizeof(prog_buf)); - int fd = mapped != prog ? (int)syscall(SYS_openat, AT_FDCWD, mapped, O_PATH | O_CLOEXEC) : -1; - if (fd >= 0) { - syscall(SYS_close, fd); - prog = mapped; - } - } - int argc = 0; - while (argv[argc]) argc++; - char **new_argv = (char **)malloc(sizeof(char *) * (size_t)(argc + 1)); - if (!new_argv) { - errno = ENOMEM; - return -1; - } - for (int i = 0; i <= argc; i++) new_argv[i] = argv[i]; - new_argv[pi] = (char *)prog; - prepare_static_program(static_elf); // ld.so is a static program itself - char **ddnatv_env = prepare_ddnatv_env(envp, target); - int ret = run_execve(orig_execve, target, new_argv, ddnatv_env); - int saved_errno = errno; - free_modified_env(ddnatv_env, envp); - free(new_argv); - errno = saved_errno; - return ret; + struct ldso_direct direct; + int err; + char **new_argv = ldso_direct_argv(argv, envp, &direct, &err); + if (err) { + errno = err; + return -1; } - if (pi > 0) { - char prog_buf[PATH_MAX]; - const char *prog = argv[pi][0] == '/' ? rewrite_path(argv[pi], prog_buf, sizeof(prog_buf)) : argv[pi]; - struct exec_probe prog_probe; - probe_exec_file(prog, &prog_probe); - char ld_lib_path[PATH_MAX * 6]; - build_ld_library_path(envp, prog_probe.runpath, prog_probe.runpath_is_rpath, - prog[0] == '/' ? prog : NULL, ld_lib_path, sizeof(ld_lib_path)); - int argc = 0; - while (argv[argc]) argc++; - char **new_argv = (char **)malloc(sizeof(char *) * (size_t)(argc + 3)); - if (!new_argv) { - errno = ENOMEM; - return -1; - } - new_argv[0] = argv[0]; - new_argv[1] = (char *)"--library-path"; - new_argv[2] = ld_lib_path; - for (int i = 1; i <= argc; i++) new_argv[i + 2] = argv[i]; - new_argv[pi + 2] = (char *)prog; // ld.so opens it itself: "ldd /usr/bin/adb" as well + if (new_argv) { prepare_static_program(static_elf); // ld.so is a static program itself char **ddnatv_env = prepare_ddnatv_env(envp, target); int ret = run_execve(orig_execve, target, new_argv, ddnatv_env); @@ -968,9 +974,19 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path, } } else { if (in_root && probe.is_elf && !probe.is_dynamic) prepare_static_program(elf_target); - if (orig_posix_spawn) { - ret = run_spawn(orig_posix_spawn, pid, target, file_actions, attrp, argv, new_envp); + char **spawn_argv = (char **)argv; + int err = 0; + struct ldso_direct direct; + if (in_root && probe.is_elf && !probe.is_dynamic && is_ld_linux(elf_target)) { + char **direct_argv = ldso_direct_argv(argv, orig_ep, &direct, &err); + if (direct_argv) spawn_argv = direct_argv; } + if (err) { + ret = err; + } else if (orig_posix_spawn) { + ret = run_spawn(orig_posix_spawn, pid, target, file_actions, attrp, spawn_argv, new_envp); + } + if (spawn_argv != argv) free(spawn_argv); } if (!orig_posix_spawn) { diff --git a/tools/tests/test_native_hook_ldso_spawn.py b/tools/tests/test_native_hook_ldso_spawn.py new file mode 100644 index 0000000000..48ed15b2fb --- /dev/null +++ b/tools/tests/test_native_hook_ldso_spawn.py @@ -0,0 +1,147 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" +GUEST_LDSO = "/usr/lib/ld-linux-aarch64.so.1" +GUEST_TOOL = "/usr/local/bin/tool" + +RECORDER = r""" +#define _GNU_SOURCE +#include +#include +#include + +static void show(const char *path, char *const argv[]) { + printf("call\t%s", path); + for (int i = 0; argv[i]; i++) printf("\t%s", argv[i]); + printf("\n"); + fflush(stdout); +} + +int posix_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *actions, + const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) { + show(path, argv); + if (pid) *pid = 1; + return 0; +} + +int execve(const char *path, char *const argv[], char *const envp[]) { + show(path, argv); + _exit(0); +} +""" + +PROBE = r""" +#include +#include +#include +#include + +extern char **environ; + +int main(int argc, char **argv) { + if (argc < 3) return 2; + if (strcmp(argv[1], "spawn") == 0) { + pid_t pid; + posix_spawn_file_actions_t actions; + posix_spawn_file_actions_init(&actions); + posix_spawn_file_actions_adddup2(&actions, 1, 1); + int ret = posix_spawn(&pid, argv[2], &actions, NULL, argv + 2, environ); + posix_spawn_file_actions_destroy(&actions); + printf("ret\t%d\n", ret); + return 0; + } + execve(argv[2], argv + 2, environ); + printf("ret\t-1\n"); + return 1; +} +""" + + +def guest_loader(prefix): + roots = [Path(prefix[prefix.index("-L") + 1])] if prefix and "-L" in prefix else [Path("/")] + for root in roots: + for name in ("lib/ld-linux-aarch64.so.1", "lib64/ld-linux-aarch64.so.1", "usr/lib/ld-linux-aarch64.so.1"): + if (root / name).exists(): + return root / name + return None + + +class NativeHookLdsoSpawnTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + loader = guest_loader(cls.prefix) + if loader is None: + raise unittest.SkipTest("no aarch64 glibc loader to put in the rootfs") + cls.tmp = tempfile.TemporaryDirectory() + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "recorder.c").write_text(RECORDER) + cls.recorder = tmp / "recorder.so" + subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.recorder), str(tmp / "recorder.c")], check=True) + (tmp / "probe.c").write_text(PROBE) + cls.probe = tmp / "probe" + subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True) + cls.root = tmp / "root" + for guest, source in ((GUEST_LDSO, loader), (GUEST_TOOL, cls.probe)): + host = cls.root / guest.lstrip("/") + host.parent.mkdir(parents=True, exist_ok=True) + shutil.copy(source, host) + host.chmod(0o755) + (cls.root / "usr/lib/aarch64-linux-gnu").mkdir(parents=True, exist_ok=True) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def call(self, how, *argv): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook}:{self.recorder}"} + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_EXEC", "LD_LIBRARY_PATH")} + if self.prefix: + cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] + else: + cmd = [] + env.update(hook_env) + out = subprocess.run(cmd + [str(self.probe), how, *argv], env=env, capture_output=True, text=True, timeout=120) + calls = [line.split("\t")[1:] for line in out.stdout.splitlines() if line.startswith("call\t")] + self.assertEqual(1, len(calls), out.stdout + out.stderr) + if how == "spawn": + self.assertIn("ret\t0", out.stdout.splitlines(), out.stdout + out.stderr) + return calls[0] + + def test_spawned_ldso_list_loads_the_program_from_the_rootfs(self): + call = self.call("spawn", GUEST_LDSO, "--list", GUEST_TOOL) + argv = call[1:] + self.assertEqual(str(self.root / GUEST_TOOL.lstrip("/")), argv[-1]) + self.assertEqual("--list", argv[-2]) + self.assertIn("--library-path", argv[:-2]) + + def test_spawn_and_exec_start_ldso_with_the_same_arguments(self): + for args in (("--list", GUEST_TOOL), (GUEST_TOOL, "x"), ("--library-path", "/opt/own", "--list", GUEST_TOOL)): + with self.subTest(args=args): + self.assertEqual(self.call("exec", GUEST_LDSO, *args), self.call("spawn", GUEST_LDSO, *args)) + + def test_a_callers_own_library_path_is_kept(self): + call = self.call("spawn", GUEST_LDSO, "--library-path", "/opt/own", "--list", GUEST_TOOL) + self.assertEqual([GUEST_LDSO, "--library-path", "/opt/own", "--list", str(self.root / GUEST_TOOL.lstrip("/"))], call[1:]) + + def test_ldso_without_a_program_is_spawned_unchanged(self): + call = self.call("spawn", GUEST_LDSO, "--version") + self.assertEqual([GUEST_LDSO, "--version"], call[1:]) + + def test_spawn_and_exec_start_a_dynamic_program_the_same_way(self): + self.assertEqual(self.call("exec", GUEST_TOOL, "x"), self.call("spawn", GUEST_TOOL, "x")) + + +if __name__ == "__main__": + unittest.main() From 823f70320f12af555fd6e3b3b2015d5bc627834e Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Mon, 23 Nov 2026 11:11:10 -0500 Subject: [PATCH 061/141] fix(nativeguest): x86-64 path calls, SIGSYS handlers and re-execs stay inside the rootfs hook (#3074) * fix(nativeguest): x86-64 path system calls and SIGSYS handlers stay inside the rootfs hook FEX passed most guest path system calls to the kernel with an inline svc, so the native path hook never mapped them, and it mirrored guest SIGSYS handlers with a raw rt_sigaction that replaced the hook's own handler, after which the next blocked system call killed the program. Path calls now go through libc's syscall(), which the hook maps (guarded until the hook is initialised so an early allocator cannot deadlock), and a SIGSYS handler set through syscall() is recorded and chained like one set through sigaction(). * fix(ddexec): a program that re-execs itself keeps the rootfs hook A re-exec through /proc/self/exe starts the program through the guest ld.so again but left out the hook, so the child saw host paths. Steam's reaper then recorded host install folders, and Battle.net games moved to a mapped drive the Library could not resolve. The re-exec now preloads the hook of the root the same way the first start does. --- app/src/main/cpp/ddexec/ddexec.c | 152 +++++++++++++--- docs/development/x86-64-steam-client.md | 12 ++ .../0013-path-syscalls-through-libc.patch | 130 ++++++++++++++ tools/nativeguest/hook/env.c | 14 +- tools/nativeguest/hook/exec.c | 28 +-- tools/nativeguest/hook/privileged.c | 126 ++++++++++++-- tools/tests/test_ddexec_reexec.py | 154 +++++++++++++++++ tools/tests/test_fex_path_syscalls.py | 49 ++++++ tools/tests/test_native_hook_ldso_spawn.py | 22 ++- tools/tests/test_native_hook_path_syscalls.py | 163 ++++++++++++++++++ tools/tests/test_native_hook_sigsys_mask.py | 144 ++++++++++++++++ 11 files changed, 942 insertions(+), 52 deletions(-) create mode 100644 tools/fex/patches/0013-path-syscalls-through-libc.patch create mode 100644 tools/tests/test_ddexec_reexec.py create mode 100644 tools/tests/test_fex_path_syscalls.py create mode 100644 tools/tests/test_native_hook_path_syscalls.py create mode 100644 tools/tests/test_native_hook_sigsys_mask.py diff --git a/app/src/main/cpp/ddexec/ddexec.c b/app/src/main/cpp/ddexec/ddexec.c index c7e4384ce3..b4a1db085d 100644 --- a/app/src/main/cpp/ddexec/ddexec.c +++ b/app/src/main/cpp/ddexec/ddexec.c @@ -21,6 +21,7 @@ #define SYS_munmap 215 #define SYS_mmap 222 #define SYS_mprotect 226 +#define SYS_getpid 172 #define AT_FDCWD_ (-100) #define O_RDONLY_ 0 @@ -52,6 +53,21 @@ 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) { @@ -112,19 +128,43 @@ 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 load(const char *path, struct image *im, uintptr_t page) { +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) { 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); - 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) + 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]; - 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); + 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); uintptr_t lo = UINTPTR_MAX, hi = 0; for (int i = 0; i < eh.e_phnum; i++) { @@ -173,16 +213,9 @@ 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; - im->interp[0] = 0; - for (int i = 0; i < eh.e_phnum; i++) { + read_interp(fd, ph, eh.e_phnum, im->interp, sizeof(im->interp), path); + 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]; @@ -202,6 +235,36 @@ 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); @@ -211,25 +274,66 @@ __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++; - if (argc < 3) die("usage: libddexec.so [args...]", 0, 0); + 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 [args...]", 0, 0); + } else { + path = argv[1]; + } 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(prog.interp, &interp, page); + if (has_interp) load(reexec ? guest_interp(envp, prog.interp, interp_buf, sizeof(interp_buf)) : 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 = argc - 2; + long new_argc = nargs; long words = 1 + (new_argc + 1) + (nenv + 1) + (naux + nreplaced + 1) * 2; - uintptr_t *nsp = (uintptr_t *)(((uintptr_t)sp - STACK_GAP - (uintptr_t)words * sizeof(uintptr_t)) & ~(uintptr_t)15); + 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 *w = nsp; *w++ = (uintptr_t)new_argc; - for (long i = 0; i < new_argc; i++) *w++ = (uintptr_t)argv[i + 2]; + for (long i = 0; i < new_argc; i++) *w++ = (uintptr_t)args[i]; *w++ = 0; for (long i = 0; i < nenv; i++) *w++ = (uintptr_t)envp[i]; *w++ = 0; diff --git a/docs/development/x86-64-steam-client.md b/docs/development/x86-64-steam-client.md index d4b99759d5..1a02e3420f 100644 --- a/docs/development/x86-64-steam-client.md +++ b/docs/development/x86-64-steam-client.md @@ -291,6 +291,18 @@ alone would then read as an installed client. spins until a `SIGALRM` handler sets a register (R12, or ESI in 32-bit `rt` and legacy frames): FEX-2611.1 with 0001 to 0011 never sees it in any of the three frame types, with this patch all three see it on the first signal, as natively. + - `0013-path-syscalls-through-libc`: FEX passes most path system calls of the guest (`mkdirat`, + `unlinkat`, `renameat`, `renameat2`, `symlinkat`, `linkat`, `mknodat`, `fchmodat`, `fchmodat2`, + `fchownat`, `utimensat`, `truncate`, `chdir`, `chroot`, `inotify_add_watch`) straight to the kernel + with an inline `svc`, which the native userland's path hook never sees, so an x86-64 program wrote + `/opt/...` or `/root/...` to the Android root instead of the rootfs, and `cd` into a rootfs folder + failed. They now go through libc's `syscall()`, which the hook maps like every other path; without + the hook it is the same system call. `tools/tests/test_native_hook_path_syscalls.py` checks the hook + side, including that an allocator which opens files before the hook has started does not hang. + FEX also mirrors each guest signal handler with `syscall(SYS_rt_sigaction, ...)`; for `SIGSYS` the + hook records the guest handler as it does for `sigaction()` and keeps its own installed, so a + program that sets a crash handler is no longer killed by the next blocked system call + (`tools/tests/test_native_hook_sigsys_mask.py`). - **Building and publishing.** Droid-Deck/DroidDeck-Components' `build-fex.yml` builds `tools/fex` from this repository at a chosen ref (default `main`) with host thunks, in the same Arch Linux ARM container with a read-only token, then a separate job replaces `fex.tzst` on Components' single `fex` release, diff --git a/tools/fex/patches/0013-path-syscalls-through-libc.patch b/tools/fex/patches/0013-path-syscalls-through-libc.patch new file mode 100644 index 0000000000..122f7654d2 --- /dev/null +++ b/tools/fex/patches/0013-path-syscalls-through-libc.patch @@ -0,0 +1,130 @@ +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp +index 11ff163..085a621 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp +@@ -209,6 +209,41 @@ uint64_t SyscallPassthrough7(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, + } + #endif + ++template ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough1(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1) { ++ uint64_t Result = ::syscall(syscall_num, arg1); ++ SYSCALL_ERRNO(); ++} ++ ++template ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough2(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, uint64_t arg2) { ++ uint64_t Result = ::syscall(syscall_num, arg1, arg2); ++ SYSCALL_ERRNO(); ++} ++ ++template ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough3(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, uint64_t arg2, uint64_t arg3) { ++ uint64_t Result = ::syscall(syscall_num, arg1, arg2, arg3); ++ SYSCALL_ERRNO(); ++} ++ ++template ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough4(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, uint64_t arg2, uint64_t arg3, uint64_t arg4) { ++ uint64_t Result = ::syscall(syscall_num, arg1, arg2, arg3, arg4); ++ SYSCALL_ERRNO(); ++} ++ ++template ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough5(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, uint64_t arg2, uint64_t arg3, uint64_t arg4, uint64_t arg5) { ++ uint64_t Result = ::syscall(syscall_num, arg1, arg2, arg3, arg4, arg5); ++ SYSCALL_ERRNO(); ++} ++ + static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(read, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(write, SyscallPassthrough3); +@@ -238,9 +273,9 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(flock, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(fsync, SyscallPassthrough1); + REGISTER_SYSCALL_IMPL(fdatasync, SyscallPassthrough1); +- REGISTER_SYSCALL_IMPL(truncate, SyscallPassthrough2); ++ REGISTER_SYSCALL_IMPL(truncate, SyscallPathPassthrough2); + REGISTER_SYSCALL_IMPL(getcwd, SyscallPassthrough2); +- REGISTER_SYSCALL_IMPL(chdir, SyscallPassthrough1); ++ REGISTER_SYSCALL_IMPL(chdir, SyscallPathPassthrough1); + REGISTER_SYSCALL_IMPL(fchdir, SyscallPassthrough1); + REGISTER_SYSCALL_IMPL(fchmod, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(fchown, SyscallPassthrough3); +@@ -280,7 +315,7 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(mlock, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(munlock, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(pivot_root, SyscallPassthrough2); +- REGISTER_SYSCALL_IMPL(chroot, SyscallPassthrough1); ++ REGISTER_SYSCALL_IMPL(chroot, SyscallPathPassthrough1); + REGISTER_SYSCALL_IMPL(sync, SyscallPassthrough0); + REGISTER_SYSCALL_IMPL(acct, SyscallPassthrough1); + REGISTER_SYSCALL_IMPL(mount, SyscallPassthrough5); +@@ -312,17 +347,17 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(keyctl, SyscallPassthrough5); + REGISTER_SYSCALL_IMPL(ioprio_set, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(ioprio_get, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL(inotify_add_watch, SyscallPassthrough3); ++ REGISTER_SYSCALL_IMPL(inotify_add_watch, SyscallPathPassthrough3); + REGISTER_SYSCALL_IMPL(inotify_rm_watch, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(migrate_pages, SyscallPassthrough4); +- REGISTER_SYSCALL_IMPL(mkdirat, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL(mknodat, SyscallPassthrough4); +- REGISTER_SYSCALL_IMPL(fchownat, SyscallPassthrough5); +- REGISTER_SYSCALL_IMPL(unlinkat, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL(renameat, SyscallPassthrough4); +- REGISTER_SYSCALL_IMPL(linkat, SyscallPassthrough5); +- REGISTER_SYSCALL_IMPL(symlinkat, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL(fchmodat, SyscallPassthrough3); ++ REGISTER_SYSCALL_IMPL(mkdirat, SyscallPathPassthrough3); ++ REGISTER_SYSCALL_IMPL(mknodat, SyscallPathPassthrough4); ++ REGISTER_SYSCALL_IMPL(fchownat, SyscallPathPassthrough5); ++ REGISTER_SYSCALL_IMPL(unlinkat, SyscallPathPassthrough3); ++ REGISTER_SYSCALL_IMPL(renameat, SyscallPathPassthrough4); ++ REGISTER_SYSCALL_IMPL(linkat, SyscallPathPassthrough5); ++ REGISTER_SYSCALL_IMPL(symlinkat, SyscallPathPassthrough3); ++ REGISTER_SYSCALL_IMPL(fchmodat, SyscallPathPassthrough3); + REGISTER_SYSCALL_IMPL(unshare, SyscallPassthrough1); + REGISTER_SYSCALL_IMPL(splice, SyscallPassthrough6); + REGISTER_SYSCALL_IMPL(tee, SyscallPassthrough4); +@@ -343,7 +378,7 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(kcmp, SyscallPassthrough5); + REGISTER_SYSCALL_IMPL(sched_setattr, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(sched_getattr, SyscallPassthrough4); +- REGISTER_SYSCALL_IMPL(renameat2, SyscallPassthrough5); ++ REGISTER_SYSCALL_IMPL(renameat2, SyscallPathPassthrough5); + REGISTER_SYSCALL_IMPL(getrandom, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(memfd_create, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(membarrier, SyscallPassthrough2); +@@ -468,7 +503,7 @@ namespace x64 { + REGISTER_SYSCALL_IMPL_X64(get_robust_list, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL_X64(sync_file_range, SyscallPassthrough4); + REGISTER_SYSCALL_IMPL_X64(vmsplice, SyscallPassthrough4); +- REGISTER_SYSCALL_IMPL_X64(utimensat, SyscallPassthrough4); ++ REGISTER_SYSCALL_IMPL_X64(utimensat, SyscallPathPassthrough4); + REGISTER_SYSCALL_IMPL_X64(fallocate, SyscallPassthrough4); + REGISTER_SYSCALL_IMPL_X64(timerfd_settime, SyscallPassthrough4); + REGISTER_SYSCALL_IMPL_X64(timerfd_gettime, SyscallPassthrough2); +@@ -492,7 +527,7 @@ namespace x64 { + REGISTER_SYSCALL_IMPL_X64(cachestat, UnimplementedSyscallSafe); + } + if (Handler->IsHostKernelVersionAtLeast(6, 6, 0)) { +- REGISTER_SYSCALL_IMPL_X64(fchmodat2, SyscallPassthrough4); ++ REGISTER_SYSCALL_IMPL_X64(fchmodat2, SyscallPathPassthrough4); + } else { + REGISTER_SYSCALL_IMPL_X64(fchmodat2, UnimplementedSyscallSafe); + } +@@ -529,7 +564,7 @@ namespace x32 { + REGISTER_SYSCALL_IMPL_X32(timer_settime64, SyscallPassthrough4); + REGISTER_SYSCALL_IMPL_X32(timerfd_gettime64, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL_X32(timerfd_settime64, SyscallPassthrough4); +- REGISTER_SYSCALL_IMPL_X32(utimensat_time64, SyscallPassthrough4); ++ REGISTER_SYSCALL_IMPL_X32(utimensat_time64, SyscallPathPassthrough4); + REGISTER_SYSCALL_IMPL_X32(ppoll_time64, SyscallPassthrough5); + REGISTER_SYSCALL_IMPL_X32(io_pgetevents_time64, SyscallPassthrough6); + REGISTER_SYSCALL_IMPL_X32(mq_timedsend_time64, SyscallPassthrough5); diff --git a/tools/nativeguest/hook/env.c b/tools/nativeguest/hook/env.c index e881ba1f71..8f3daf8086 100644 --- a/tools/nativeguest/hook/env.c +++ b/tools/nativeguest/hook/env.c @@ -72,7 +72,7 @@ static char *map_preload_paths(const char *value) { return out; } -static char **prepare_ddnatv_env(char *const envp[], const char *real_exe) { +static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const char *lib_path) { init_ddnatv_hook(); int count = 0; int has_preload = 0; @@ -164,6 +164,9 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe) { if (chosen_real_exe && envp[i][0] == 'D' && strncmp(envp[i], "DDNATV_REAL_EXE=", 16) == 0) { continue; } + if (chosen_real_exe && envp[i][0] == 'D' && strncmp(envp[i], "DDNATV_LIBRARY_PATH=", 20) == 0) { + continue; + } new_env[dst++] = envp[i]; } @@ -178,6 +181,15 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe) { new_env[dst++] = str; } } + if (chosen_real_exe && lib_path && lib_path[0] != '\0') { + size_t len = strlen(lib_path); + char *str = malloc(20 + len + 1); + if (str) { + memcpy(str, "DDNATV_LIBRARY_PATH=", 20); + memcpy(str + 20, lib_path, len + 1); + new_env[dst++] = str; + } + } char hook_buf[PATH_MAX]; const char *hook = (!has_preload && g_ddnatv_root[0] != '\0') ? ddnatv_hook_library(hook_buf, sizeof(hook_buf)) : NULL; diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index 3f316fc3b3..664b0beedf 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -44,8 +44,8 @@ static void resolve_symlinks(const char *path, char *out, size_t out_size, int d resolve_symlinks(next_path, out, out_size, depth + 1); } -static char **ensure_hook_in_envp(char *const envp[], const char *real_exe) { - return prepare_ddnatv_env(envp, real_exe); +static char **ensure_hook_in_envp(char *const envp[], const char *real_exe, const char *lib_path) { + return prepare_ddnatv_env(envp, real_exe, lib_path); } // The file whose header decides how to start `target`: the symlink-resolved ELF (so ld.so and @@ -162,7 +162,7 @@ static int exec_interp_missing(int fd) { syscall(SYS_pread64, fd, interp, ph.p_filesz, (long)ph.p_offset) != (long)ph.p_filesz) return ENOEXEC; interp[ph.p_filesz] = 0; - int ifd = (int)syscall(SYS_openat, AT_FDCWD, interp, O_RDONLY | O_CLOEXEC | O_NONBLOCK); + int ifd = (int)call_orig_syscall(SYS_openat, AT_FDCWD, (unsigned long)interp, O_RDONLY | O_CLOEXEC | O_NONBLOCK, 0, 0, 0); if (ifd < 0) return errno; syscall(SYS_close, ifd); return 0; @@ -174,7 +174,7 @@ static int exec_interp_missing(int fd) { // a shell walking $PATH moves on at ENOENT and EACCES, and runs a file without "#!" as a script at // ENOEXEC. static int exec_preflight(const char *path) { - int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC | O_NONBLOCK); + int fd = (int)call_orig_syscall(SYS_openat, AT_FDCWD, (unsigned long)path, O_RDONLY | O_CLOEXEC | O_NONBLOCK, 0, 0, 0); if (fd < 0) return errno; struct stat st; int err = 0; @@ -428,7 +428,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e errno = ENOMEM; return -1; } - char **new_env = ensure_hook_in_envp(envp, elf_target); + char **new_env = ensure_hook_in_envp(envp, elf_target, ld_lib_path); int ret = run_execve(orig_execve, ld_so, new_argv, new_env); if (errno == EACCES && chmod(ld_so, 0755) == 0) { // ld.so without its exec bit (an unusual restore): fix it once and retry @@ -452,7 +452,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e } if (new_argv) { prepare_static_program(static_elf); // ld.so is a static program itself - char **ddnatv_env = prepare_ddnatv_env(envp, target); + char **ddnatv_env = prepare_ddnatv_env(envp, target, NULL); int ret = run_execve(orig_execve, target, new_argv, ddnatv_env); int saved_errno = errno; free_modified_env(ddnatv_env, envp); @@ -486,7 +486,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e errno = ELOOP; ret = -1; } else { - char **ddnatv_env = prepare_ddnatv_env(envp, NULL); + char **ddnatv_env = prepare_ddnatv_env(envp, NULL, NULL); ret = ddnatv_execve(rewritten_interp, new_argv, ddnatv_env, depth + 1); int saved_errno = errno; free_modified_env(ddnatv_env, envp); @@ -506,7 +506,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e } if (static_elf) prepare_static_program(static_elf); - char **ddnatv_env = prepare_ddnatv_env(envp, target); + char **ddnatv_env = prepare_ddnatv_env(envp, target, NULL); int ret = run_execve(orig_execve, target, argv, ddnatv_env); int saved_errno = errno; free_modified_env(ddnatv_env, envp); @@ -948,17 +948,21 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path, // Android programs get Android's environment, as execve() gives them: the glibc hook in // LD_PRELOAD crashes them. - char **new_envp = in_root ? ensure_hook_in_envp(orig_ep, elf_target) : clean_env_for_system(orig_ep); + int via_ld_so = has_ld_so && strcmp(elf_target, ld_so) != 0; + char ld_lib_path[PATH_MAX * 6]; + ld_lib_path[0] = '\0'; + if (via_ld_so) + build_ld_library_path(orig_ep, probe.runpath, probe.runpath_is_rpath, elf_target, ld_lib_path, sizeof(ld_lib_path)); + char **new_envp = in_root ? ensure_hook_in_envp(orig_ep, elf_target, via_ld_so ? ld_lib_path : NULL) + : clean_env_for_system(orig_ep); int ret = -1; - if (has_ld_so && strcmp(elf_target, ld_so) != 0) { + if (via_ld_so) { ensure_exec_bit(elf_target, probe.mode); if (probe.android_interp) prepare_static_program_ex(elf_target, 1); // a Go program built for Android (#42) char hook_buf[PATH_MAX]; const char *hook_so = ddnatv_hook_library(hook_buf, sizeof(hook_buf)); - char ld_lib_path[PATH_MAX * 6]; - build_ld_library_path(orig_ep, probe.runpath, probe.runpath_is_rpath, elf_target, ld_lib_path, sizeof(ld_lib_path)); char **new_argv = build_ldso_argv(ld_so, hook_so, ld_lib_path, elf_target, prog_name, argv); if (!new_argv) { ret = ENOMEM; diff --git a/tools/nativeguest/hook/privileged.c b/tools/nativeguest/hook/privileged.c index 7bf0a8b692..09a1074b86 100644 --- a/tools/nativeguest/hook/privileged.c +++ b/tools/nativeguest/hook/privileged.c @@ -519,6 +519,13 @@ static int close_range_all(unsigned int first, unsigned int last, int flags) { static __thread int t_syscall_redirect = 0; +static long nested_path_syscall(long number, unsigned long dirfd, unsigned long pathname, unsigned long arg3, unsigned long arg4) { + char nested_buf[PATH_MAX]; + const char *path = (const char *)pathname; + if (path && path[0] == '/') path = rewrite_path(path, nested_buf, sizeof(nested_buf)); + return call_orig_syscall(number, dirfd, (unsigned long)path, arg3, arg4, 0, 0); +} + long syscall(long number, ...) { va_list ap; va_start(ap, number); @@ -563,6 +570,38 @@ long syscall(long number, ...) { } #endif +#ifdef __NR_rt_sigprocmask + if (number == __NR_rt_sigprocmask && arg2 && (arg1 == SIG_BLOCK || arg1 == SIG_SETMASK) && arg4 == sizeof(uint64_t)) { + uint64_t mask; + memcpy(&mask, (const void *)arg2, sizeof(mask)); + mask &= ~(1ULL << (SIGSYS - 1)); + return call_orig_syscall(number, arg1, (unsigned long)&mask, arg3, arg4, 0, 0); + } +#endif + +#ifdef __NR_rt_sigaction + if (number == __NR_rt_sigaction && arg1 == SIGSYS && arg4 == sizeof(uint64_t)) { + struct { void *handler; unsigned long flags; void *restorer; uint64_t mask; } kact, kold; + struct sigaction act, old; + memset(&act, 0, sizeof(act)); + if (arg2) { + memcpy(&kact, (const void *)arg2, sizeof(kact)); + act.sa_sigaction = (void (*)(int, siginfo_t *, void *))kact.handler; + act.sa_flags = (int)kact.flags; + memcpy(&act.sa_mask, &kact.mask, sizeof(kact.mask)); + } + remember_app_sigsys(arg2 ? &act : NULL, arg3 ? &old : NULL); + if (arg3) { + memset(&kold, 0, sizeof(kold)); + kold.handler = (void *)old.sa_sigaction; + kold.flags = (unsigned long)(unsigned int)old.sa_flags; + memcpy(&kold.mask, &old.sa_mask, sizeof(kold.mask)); + memcpy((void *)arg3, &kold, sizeof(kold)); + } + return 0; + } +#endif + #ifdef __NR_seccomp if (number == __NR_seccomp) { return (long)seccomp((unsigned int)arg1, (unsigned int)arg2, (void *)arg3); @@ -618,16 +657,84 @@ long syscall(long number, ...) { } #endif + if (g_initialized) { +#ifdef __NR_openat + if (number == __NR_openat) { + if (t_syscall_redirect) return nested_path_syscall(number, arg1, arg2, arg3, arg4); + t_syscall_redirect++; + long ret = (long)openat((int)arg1, (const char *)arg2, (int)arg3, (mode_t)arg4); + t_syscall_redirect--; + return ret; + } +#endif +#if defined(__NR_mkdirat) + if (number == __NR_mkdirat) { + return (long)mkdirat((int)arg1, (const char *)arg2, (mode_t)arg3); + } +#endif +#if defined(__NR_unlinkat) + if (number == __NR_unlinkat) { + return (long)unlinkat((int)arg1, (const char *)arg2, (int)arg3); + } +#endif +#if defined(__NR_renameat) + if (number == __NR_renameat) { + return (long)renameat((int)arg1, (const char *)arg2, (int)arg3, (const char *)arg4); + } +#endif +#if defined(__NR_renameat2) + if (number == __NR_renameat2) { + return (long)renameat2((int)arg1, (const char *)arg2, (int)arg3, (const char *)arg4, (unsigned int)arg5); + } +#endif +#if defined(__NR_symlinkat) + if (number == __NR_symlinkat) { + return (long)symlinkat((const char *)arg1, (int)arg2, (const char *)arg3); + } +#endif +#if defined(__NR_fchmodat) + if (number == __NR_fchmodat) { + return (long)fchmodat((int)arg1, (const char *)arg2, (mode_t)arg3, 0); + } +#endif +#if defined(__NR_fchownat) + if (number == __NR_fchownat) { + return (long)fchownat((int)arg1, (const char *)arg2, (uid_t)arg3, (gid_t)arg4, (int)arg5); + } +#endif +#if defined(__NR_utimensat) + if (number == __NR_utimensat) { + if (!arg2) return call_orig_syscall(number, arg1, arg2, arg3, arg4, 0, 0); + return (long)utimensat((int)arg1, (const char *)arg2, (const struct timespec *)arg3, (int)arg4); + } +#endif +#if defined(__NR_truncate) + if (number == __NR_truncate) { + return (long)truncate((const char *)arg1, (off_t)arg2); + } +#endif +#if defined(__NR_chdir) + if (number == __NR_chdir) { + return (long)chdir((const char *)arg1); + } +#endif +#if defined(__NR_chroot) + if (number == __NR_chroot) { + return (long)chroot((const char *)arg1); + } +#endif +#if defined(__NR_inotify_add_watch) + if (number == __NR_inotify_add_watch) { + return (long)inotify_add_watch((int)arg1, (const char *)arg2, (uint32_t)arg3); + } +#endif + } + #ifdef __NR_openat2 if (number == __NR_openat2) { // libddsession's openat2() calls syscall() again (an endless loop until the stack ran out): the nested // call maps the path and goes straight to the kernel - if (t_syscall_redirect) { - char nested_buf[PATH_MAX]; - const char *path = (const char *)arg2; - if (path && path[0] == '/') path = rewrite_path(path, nested_buf, sizeof(nested_buf)); - return call_orig_syscall(number, arg1, (unsigned long)path, arg3, arg4, 0, 0); - } + if (t_syscall_redirect) return nested_path_syscall(number, arg1, arg2, arg3, arg4); t_syscall_redirect++; long ret = (long)openat2((int)arg1, (const char *)arg2, (struct ddnatv_open_how *)arg3, (size_t)arg4); t_syscall_redirect--; @@ -649,12 +756,7 @@ long syscall(long number, ...) { #if defined(__NR_faccessat) if (number == __NR_faccessat) { - if (t_syscall_redirect) { - char nested_buf[PATH_MAX]; - const char *path = (const char *)arg2; - if (path && path[0] == '/') path = rewrite_path(path, nested_buf, sizeof(nested_buf)); - return call_orig_syscall(number, arg1, (unsigned long)path, arg3, 0, 0, 0); - } + if (t_syscall_redirect) return nested_path_syscall(number, arg1, arg2, arg3, 0); t_syscall_redirect++; long ret = (long)faccessat((int)arg1, (const char *)arg2, (int)arg3, 0); t_syscall_redirect--; diff --git a/tools/tests/test_ddexec_reexec.py b/tools/tests/test_ddexec_reexec.py new file mode 100644 index 0000000000..640db1706c --- /dev/null +++ b/tools/tests/test_ddexec_reexec.py @@ -0,0 +1,154 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +REPO = Path(__file__).resolve().parents[2] +SOURCE = REPO / "app/src/main/cpp/ddexec/ddexec.c" +SYSROOT = Path("/usr/aarch64-linux-gnu") + +LIBRARY = r""" +int dd_probe_value(void) { return 7; } +""" + +HOOK = r""" +#include + +__attribute__((constructor)) static void hooked(void) { write(1, "hooked\n", 7); } +""" + +PROGRAM = r""" +#include +#include +#include +#include +#include + +int dd_probe_value(void); + +int main(int argc, char **argv, char **envp) { + if (dd_probe_value() != 7) return 4; + if (argc > 1 && strcmp(argv[1], "again") == 0) { + for (int i = 0; i < argc; i++) printf("%s%s", i ? "|" : "", argv[i]); + printf("\n%s\n", (char *)getauxval(AT_EXECFN)); + return 0; + } + char *next[] = {"first", "again", "x y", NULL}; + syscall(SYS_execveat, -100, "/proc/self/exe", next, envp, 0); + return 3; +} +""" + + +def ndk_clang(): + sdk = Path(os.environ.get("ANDROID_HOME") or os.environ.get("ANDROID_SDK_ROOT") or Path.home() / "Android/Sdk") + for ndk in sorted((sdk / "ndk").glob("*"), reverse=True): + clang = ndk / "toolchains/llvm/prebuilt/linux-x86_64/bin/clang" + if clang.exists(): + return str(clang) + return shutil.which("clang") + + +class DdexecReexecTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cc, prefix = runner() + clang = ndk_clang() + if cc is None or clang is None or not shutil.which("bwrap") or not SYSROOT.is_dir(): + raise unittest.SkipTest("no aarch64 toolchain, runner or bwrap") + cls.qemu = list(prefix[:3]) if prefix else [] + cls.tmp = tempfile.TemporaryDirectory() + tmp = Path(cls.tmp.name) + cls.loader = tmp / "libddexec.so" + subprocess.run([clang, "--target=aarch64-linux-android29", "-shared", "-fPIC", "-O2", "-ffreestanding", + "-fno-builtin", "-fno-stack-protector", "-fno-asynchronous-unwind-tables", "-nostdlib", + "-Wl,-e,_start", "-Wl,-z,noexecstack", "-Wl,--no-undefined", "-Wl,-Bsymbolic", + "-Wl,-z,max-page-size=16384", "-o", str(cls.loader), str(SOURCE)], check=True) + cls.libdir = tmp / "own-lib" + cls.libdir.mkdir() + (tmp / "lib.c").write_text(LIBRARY) + subprocess.run([cc, "-shared", "-fPIC", "-O1", "-o", str(cls.libdir / "libddprobe.so"), str(tmp / "lib.c")], + check=True) + (tmp / "prog.c").write_text(PROGRAM) + cls.program = tmp / "prog" + subprocess.run([cc, "-O1", "-o", str(cls.program), str(tmp / "prog.c"), "-L", str(cls.libdir), "-lddprobe"], + check=True) + cls.root = tmp / "root" + (cls.root / "usr/lib").mkdir(parents=True) + (cls.root / "lib").mkdir() + shutil.copy2(SYSROOT / "lib/ld-linux-aarch64.so.1", cls.root / "lib/ld-linux-aarch64.so.1") + (tmp / "hook.c").write_text(HOOK) + subprocess.run([cc, "-shared", "-fPIC", "-O1", "-o", str(cls.root / "usr/lib/libddnatv-hook.so"), str(tmp / "hook.c")], + check=True) + probe = subprocess.run(["bwrap", "--dev-bind", "/", "/", "true"], capture_output=True) + if probe.returncode != 0: + raise unittest.SkipTest("bwrap cannot create a namespace here") + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def env(self, real_exe, library_path=None, root=SYSROOT): + env = {k: v for k, v in os.environ.items() if not k.startswith(("DDNATV_", "LD_", "QEMU_"))} + env["DDNATV_ROOT"] = str(root) + env["LD_LIBRARY_PATH"] = f"{SYSROOT / 'lib'}:{self.libdir}" if library_path is None else str(SYSROOT / "lib") + if real_exe: + env["DDNATV_REAL_EXE"] = str(real_exe) + if library_path: + env["DDNATV_LIBRARY_PATH"] = library_path + return env + + def reexec(self, execfn, real_exe, library_path=None, root=SYSROOT): + jail = ["bwrap", "--dev-bind", "/", "/", "--tmpfs", "/proc"] + parent = str(Path(execfn).parent) + jail += ["--dir", parent, "--ro-bind", str(self.loader), execfn] + start = self.qemu + ["-0", "first", execfn] if self.qemu else ["bash", "-c", 'exec -a first "$0" "$@"', execfn] + cmd = jail + start + ["again", "x y"] + return subprocess.run(cmd, env=self.env(real_exe, library_path, root), capture_output=True, text=True, timeout=120) + + def test_reexec_through_proc_self_exe_runs_the_guest_program(self): + out = self.reexec("/proc/self/exe", self.program) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual(["first|again|x y", str(self.program)], out.stdout.splitlines()) + + def test_reexec_through_thread_self_exe_runs_the_guest_program(self): + out = self.reexec("/proc/thread-self/exe", self.program) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual(["first|again|x y", str(self.program)], out.stdout.splitlines()) + + def test_reexec_finds_libraries_through_the_recorded_library_path(self): + out = self.reexec("/proc/self/exe", self.program, f"{self.libdir}:{SYSROOT / 'lib'}") + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual(["first|again|x y", str(self.program)], out.stdout.splitlines()) + + def test_reexec_through_ld_so_preloads_the_hook_of_the_root(self): + out = self.reexec("/proc/self/exe", self.program, f"{self.libdir}:{SYSROOT / 'lib'}", self.root) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual(["hooked", "first|again|x y", str(self.program)], out.stdout.splitlines()) + + def test_reexec_without_a_known_program_fails_cleanly(self): + out = self.reexec("/proc/self/exe", None) + self.assertEqual(127, out.returncode) + self.assertIn("DDNATV_REAL_EXE", out.stderr) + + def test_a_started_program_keeps_its_own_arguments(self): + ldso = SYSROOT / "lib/ld-linux-aarch64.so.1" + cmd = self.qemu + [str(self.loader), str(ldso), "ld.so", "--library-path", f"{SYSROOT / 'lib'}:{self.libdir}", + str(self.program), "again", "a"] + out = subprocess.run(cmd, env=self.env(self.program), capture_output=True, text=True, timeout=120) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual([f"{self.program}|again|a", str(self.program)], out.stdout.splitlines()) + + def test_the_usage_check_still_applies_outside_a_reexec(self): + out = subprocess.run(self.qemu + [str(self.loader), str(self.program)], env=self.env(self.program), + capture_output=True, text=True, timeout=120) + self.assertEqual(127, out.returncode) + self.assertIn("usage", out.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_fex_path_syscalls.py b/tools/tests/test_fex_path_syscalls.py new file mode 100644 index 0000000000..203f2eaac1 --- /dev/null +++ b/tools/tests/test_fex_path_syscalls.py @@ -0,0 +1,49 @@ +import re +import unittest +from pathlib import Path + +REPO = Path(__file__).resolve().parents[2] +PATCH = REPO / "tools/fex/patches/0013-path-syscalls-through-libc.patch" +HOOK = REPO / "tools/nativeguest/hook/privileged.c" +PASSTHROUGH = "Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp" +REGISTER = re.compile(r"REGISTER_SYSCALL_IMPL(?:_X64|_X32)?\((\w+), (\w+?)(\d)\);") + + +def changed(): + removed, added = {}, {} + for line in PATCH.read_text().splitlines(): + found = REGISTER.search(line) + if found and line[:1] in "+-": + (added if line[0] == "+" else removed)[found.group(1)] = found.groups()[1:] + return removed, added + + +class FexPathSyscallsTest(unittest.TestCase): + def test_only_the_passthrough_table_changes(self): + self.assertEqual(re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M), [PASSTHROUGH]) + + def test_each_path_syscall_keeps_its_arity_and_goes_through_libc(self): + removed, added = changed() + self.assertEqual(sorted(removed), sorted(added)) + self.assertGreater(len(added), 10) + for name, (template, arity, number) in added.items(): + with self.subTest(name=name): + self.assertEqual(("SyscallPassthrough", arity, number), removed[name]) + self.assertEqual("SyscallPathPassthrough", template) + + def test_the_new_templates_call_the_libc_syscall(self): + added = [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")] + calls = [line for line in added if "syscall(" in line and "Result" in line] + self.assertEqual(5, len(calls)) + self.assertTrue(all("::syscall(syscall_num" in line for line in calls)) + self.assertFalse([line for line in added if line.strip().startswith(("//", "/*"))]) + + def test_every_routed_syscall_is_rewritten_by_the_hook(self): + hook = HOOK.read_text() + for name, (_, _, number) in changed()[1].items(): + with self.subTest(name=name): + self.assertIn(f"number == __NR_{number})", hook) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_native_hook_ldso_spawn.py b/tools/tests/test_native_hook_ldso_spawn.py index 48ed15b2fb..43b810344a 100644 --- a/tools/tests/test_native_hook_ldso_spawn.py +++ b/tools/tests/test_native_hook_ldso_spawn.py @@ -15,24 +15,27 @@ RECORDER = r""" #define _GNU_SOURCE #include #include +#include #include -static void show(const char *path, char *const argv[]) { +static void show(const char *path, char *const argv[], char *const envp[]) { printf("call\t%s", path); for (int i = 0; argv[i]; i++) printf("\t%s", argv[i]); printf("\n"); + for (int i = 0; envp && envp[i]; i++) + if (strncmp(envp[i], "DDNATV_LIBRARY_PATH=", 20) == 0) printf("libpath\t%s\n", envp[i] + 20); fflush(stdout); } int posix_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *actions, const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) { - show(path, argv); + show(path, argv, envp); if (pid) *pid = 1; return 0; } int execve(const char *path, char *const argv[], char *const envp[]) { - show(path, argv); + show(path, argv, envp); _exit(0); } """ @@ -114,6 +117,7 @@ class NativeHookLdsoSpawnTest(unittest.TestCase): env.update(hook_env) out = subprocess.run(cmd + [str(self.probe), how, *argv], env=env, capture_output=True, text=True, timeout=120) calls = [line.split("\t")[1:] for line in out.stdout.splitlines() if line.startswith("call\t")] + self.library_paths = [line.split("\t", 1)[1] for line in out.stdout.splitlines() if line.startswith("libpath\t")] self.assertEqual(1, len(calls), out.stdout + out.stderr) if how == "spawn": self.assertIn("ret\t0", out.stdout.splitlines(), out.stdout + out.stderr) @@ -142,6 +146,18 @@ class NativeHookLdsoSpawnTest(unittest.TestCase): def test_spawn_and_exec_start_a_dynamic_program_the_same_way(self): self.assertEqual(self.call("exec", GUEST_TOOL, "x"), self.call("spawn", GUEST_TOOL, "x")) + def test_a_program_started_through_ldso_records_its_library_path(self): + for how in ("exec", "spawn"): + with self.subTest(how=how): + argv = self.call(how, GUEST_TOOL, "x")[1:] + self.assertEqual([argv[argv.index("--library-path") + 1]], self.library_paths) + + def test_ldso_started_by_name_records_no_library_path(self): + for how in ("exec", "spawn"): + with self.subTest(how=how): + self.call(how, GUEST_LDSO, "--list", GUEST_TOOL) + self.assertEqual([], self.library_paths) + if __name__ == "__main__": unittest.main() diff --git a/tools/tests/test_native_hook_path_syscalls.py b/tools/tests/test_native_hook_path_syscalls.py new file mode 100644 index 0000000000..ab69fc3c83 --- /dev/null +++ b/tools/tests/test_native_hook_path_syscalls.py @@ -0,0 +1,163 @@ +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" + +PROBE = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include + +static void show(const char *name, long ret) { printf("%s\t%d\n", name, ret >= 0); } + +int main(int argc, char **argv) { + const char *dir = argv[1]; + char p[PATH_MAX], q[PATH_MAX], cwd[PATH_MAX]; + snprintf(p, sizeof(p), "%s/made", dir); + show("mkdirat", syscall(SYS_mkdirat, AT_FDCWD, p, 0755)); + snprintf(p, sizeof(p), "%s/made/file", dir); + long fd = syscall(SYS_openat, AT_FDCWD, p, O_WRONLY | O_CREAT | O_CLOEXEC, 0644); + show("openat", fd); + if (fd >= 0) close((int)fd); + show("truncate", syscall(SYS_truncate, p, 4)); + show("fchmodat", syscall(SYS_fchmodat, AT_FDCWD, p, 0600)); + show("utimensat", syscall(SYS_utimensat, AT_FDCWD, p, NULL, 0)); + fd = syscall(SYS_openat, AT_FDCWD, p, O_RDONLY | O_CLOEXEC); + show("futimens", fd >= 0 ? syscall(SYS_utimensat, (int)fd, NULL, NULL, 0) : -1); + if (fd >= 0) close((int)fd); + snprintf(q, sizeof(q), "%s/made/moved", dir); + show("renameat", syscall(SYS_renameat, AT_FDCWD, p, AT_FDCWD, q)); + show("renameat2", syscall(SYS_renameat2, AT_FDCWD, q, AT_FDCWD, p, 0)); + snprintf(q, sizeof(q), "%s/made/link", dir); + show("symlinkat", syscall(SYS_symlinkat, "file", AT_FDCWD, q)); + show("unlinkat", syscall(SYS_unlinkat, AT_FDCWD, q, 0)); + snprintf(q, sizeof(q), "%s/made", dir); + show("chdir", syscall(SYS_chdir, q)); + show("cwd", getcwd(cwd, sizeof(cwd)) && strstr(cwd, "/made") ? 0 : -1); + show("unlinkat-file", syscall(SYS_unlinkat, AT_FDCWD, p, 0)); + show("unlinkat-dir", syscall(SYS_unlinkat, AT_FDCWD, q, AT_REMOVEDIR)); + return 0; +} +""" + +ALLOCATOR = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include + +extern void *__libc_malloc(size_t); +static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; +static int ready; + +void *malloc(size_t size) { + if (!ready) { + pthread_mutex_lock(&lock); + if (!ready) { + long fd = syscall(SYS_openat, AT_FDCWD, "/proc/self/stat", O_RDONLY | O_CLOEXEC); + if (fd >= 0) close((int)fd); + ready = 1; + } + pthread_mutex_unlock(&lock); + } + return __libc_malloc(size); +} + +int main(void) { + puts("ready"); + return 0; +} +""" + +EARLY = r""" +#include + +__attribute__((constructor)) static void early(void) { free(malloc(1)); } +""" + +CALLS = ("mkdirat", "openat", "truncate", "fchmodat", "utimensat", "futimens", "renameat", "renameat2", "symlinkat", "unlinkat", + "chdir", "cwd", "unlinkat-file", "unlinkat-dir") + + +class NativeHookPathSyscallsTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + cls.tmp = tempfile.TemporaryDirectory() + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "probe.c").write_text(PROBE) + cls.probe = tmp / "probe" + subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True) + cls.root = tmp / "root" + (cls.root / "opt").mkdir(parents=True) + (tmp / "allocator.c").write_text(ALLOCATOR) + cls.allocator = tmp / "allocator" + subprocess.run([cls.cc, "-O1", "-rdynamic", "-pthread", "-o", str(cls.allocator), str(tmp / "allocator.c")], check=True) + (tmp / "early.c").write_text(EARLY) + cls.early = tmp / "early.so" + subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.early), str(tmp / "early.c")], check=True) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def run_program(self, argv, hook_env): + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")} + if self.prefix: + cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] + else: + cmd = [] + env.update(hook_env) + return subprocess.run(cmd + argv, env=env, capture_output=True, text=True, timeout=120) + + def run_probe(self, guest_dir, hook=True): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} if hook else {} + out = self.run_program([str(self.probe), guest_dir], hook_env) + self.assertEqual(out.returncode, 0, out.stderr) + return {line.split("\t")[0]: int(line.split("\t")[1]) for line in out.stdout.splitlines()} + + def test_guest_paths_through_syscall_land_in_the_root(self): + results = self.run_probe("/opt") + for call in CALLS: + with self.subTest(call=call): + self.assertEqual(1, results[call]) + self.assertEqual([], list((self.root / "opt").iterdir())) + + def test_paths_already_in_the_root_are_kept(self): + results = self.run_probe(str(self.root / "opt")) + for call in CALLS: + with self.subTest(call=call): + self.assertEqual(1, results[call]) + + def test_without_the_hook_guest_paths_reach_the_host(self): + results = self.run_probe("/opt/droiddeck-hook-probe-missing", hook=False) + self.assertEqual(0, results["mkdirat"]) + self.assertEqual(0, results["openat"]) + self.assertEqual(0, results["chdir"]) + + def test_an_allocator_opening_files_before_the_hook_starts_does_not_hang(self): + hook_env = {"DDNATV_ROOT": str(self.root), "DDNATV_BINDS": "/proc:/proc", + "LD_PRELOAD": f"{self.hook}:{self.early}"} + out = self.run_program([str(self.allocator)], hook_env) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual("ready", out.stdout.strip()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_native_hook_sigsys_mask.py b/tools/tests/test_native_hook_sigsys_mask.py new file mode 100644 index 0000000000..2d28c2954d --- /dev/null +++ b/tools/tests/test_native_hook_sigsys_mask.py @@ -0,0 +1,144 @@ +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" + +PROBE = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include + +static uint64_t current(void) { + uint64_t mask = 0; + syscall(SYS_rt_sigprocmask, SIG_SETMASK, NULL, &mask, sizeof(mask)); + return mask; +} + +struct kact { void *handler; unsigned long flags; void *restorer; uint64_t mask; }; + +static void own(int sig, siginfo_t *info, void *ctx) { (void)sig; (void)info; (void)ctx; } + +static long raw_sigaction(int sig, const struct kact *act, struct kact *old) { + register long x8 __asm__("x8") = SYS_rt_sigaction; + register long x0 __asm__("x0") = sig; + register long x1 __asm__("x1") = (long)act; + register long x2 __asm__("x2") = (long)old; + register long x3 __asm__("x3") = 8; + __asm__ volatile("svc #0" : "+r"(x0) : "r"(x8), "r"(x1), "r"(x2), "r"(x3) : "memory"); + return x0; +} + +static void handlers(void) { + struct kact act = { (void *)own, SA_SIGINFO, NULL, 0 }, seen, kernel; + syscall(SYS_rt_sigaction, SIGSYS, &act, NULL, 8); + syscall(SYS_rt_sigaction, SIGSYS, NULL, &seen, 8); + raw_sigaction(SIGSYS, NULL, &kernel); + printf("sigaction\t%d\t%d\n", seen.handler == (void *)own, kernel.handler == (void *)own); + struct kact usr1 = { (void *)own, SA_SIGINFO, NULL, 0 }; + syscall(SYS_rt_sigaction, SIGUSR1, &usr1, NULL, 8); + raw_sigaction(SIGUSR1, NULL, &kernel); + printf("sigaction-usr1\t%d\n", kernel.handler == (void *)own); +} + +static void show(const char *how) { + uint64_t mask = current(); + printf("%s\t%d\t%d\n", how, !!(mask & (1ULL << (SIGSYS - 1))), !!(mask & (1ULL << (SIGUSR1 - 1)))); + uint64_t none = 0; + syscall(SYS_rt_sigprocmask, SIG_SETMASK, &none, NULL, sizeof(none)); +} + +int main(int argc, char **argv) { + uint64_t all = ~0ULL; + sigset_t set; + sigfillset(&set); + for (int i = 1; i < argc; i++) { + if (strcmp(argv[i], "syscall-setmask") == 0) syscall(SYS_rt_sigprocmask, SIG_SETMASK, &all, NULL, sizeof(all)); + else if (strcmp(argv[i], "syscall-block") == 0) syscall(SYS_rt_sigprocmask, SIG_BLOCK, &all, NULL, sizeof(all)); + else if (strcmp(argv[i], "syscall-unblock") == 0) { + syscall(SYS_rt_sigprocmask, SIG_BLOCK, &all, NULL, sizeof(all)); + uint64_t usr1 = 1ULL << (SIGUSR1 - 1); + syscall(SYS_rt_sigprocmask, SIG_UNBLOCK, &usr1, NULL, sizeof(usr1)); + } + else if (strcmp(argv[i], "sigprocmask") == 0) sigprocmask(SIG_SETMASK, &set, NULL); + else if (strcmp(argv[i], "pthread_sigmask") == 0) pthread_sigmask(SIG_SETMASK, &set, NULL); + else if (strcmp(argv[i], "sigaction") == 0) { + handlers(); + continue; + } + show(argv[i]); + } + return 0; +} +""" + +WAYS = ("syscall-setmask", "syscall-block", "sigprocmask", "pthread_sigmask") + + +class NativeHookSigsysMaskTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + cls.tmp = tempfile.TemporaryDirectory() + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "probe.c").write_text(PROBE) + cls.probe = tmp / "probe" + subprocess.run([cls.cc, "-O1", "-pthread", "-o", str(cls.probe), str(tmp / "probe.c")], check=True) + cls.root = tmp / "root" + cls.root.mkdir() + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def masks(self, *ways, hook=True): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} if hook else {} + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")} + if self.prefix: + cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] + else: + cmd = [] + env.update(hook_env) + out = subprocess.run(cmd + [str(self.probe), *ways], env=env, capture_output=True, text=True, timeout=120) + self.assertEqual(out.returncode, 0, out.stderr) + return {line.split("\t")[0]: tuple(int(v) for v in line.split("\t")[1:]) for line in out.stdout.splitlines()} + + def test_blocking_every_signal_leaves_sigsys_open(self): + masks = self.masks(*WAYS) + for way in WAYS: + with self.subTest(way=way): + self.assertEqual((0, 1), masks[way]) + + def test_unblocking_is_unchanged(self): + self.assertEqual((0, 0), self.masks("syscall-unblock")["syscall-unblock"]) + + def test_a_sigsys_handler_set_through_syscall_keeps_the_hooks(self): + seen = self.masks("sigaction") + self.assertEqual((1, 0), seen["sigaction"]) + self.assertEqual((1,), seen["sigaction-usr1"]) + + def test_without_the_hook_a_sigsys_handler_reaches_the_kernel(self): + self.assertEqual((1, 1), self.masks("sigaction", hook=False)["sigaction"]) + + def test_without_the_hook_every_signal_is_blocked(self): + masks = self.masks(*WAYS, hook=False) + for way in WAYS: + with self.subTest(way=way): + self.assertEqual((1, 1), masks[way]) + + +if __name__ == "__main__": + unittest.main() From 2151db38834662c36e34b424f11f30d03c522605 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Mon, 23 Nov 2026 11:11:15 -0500 Subject: [PATCH 062/141] fix(battlenet): offer World of Warcraft: Forever in the store (#3075) Forever has its own launch code and installs headlessly through its product code like the other titles, but the store hid it. It is now listed and hidden once installed. --- .../main/java/com/droiddeck/launcher/runtime/BattleNet.kt | 2 +- .../java/com/droiddeck/launcher/runtime/BattleNetTest.kt | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt b/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt index 7fb5cdc04b..4362c9308c 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt @@ -56,7 +56,7 @@ object BattleNet { Title("aqua", "Avowed", "AQUA", 2457220, shop = "avowed", product = "aqua"), ) - val STORE: List get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" && it.code != "WoWF" } + val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" } // 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") diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt index ea0c471faa..2ada13c310 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt @@ -354,13 +354,15 @@ class BattleNetTest { assertEquals(codes.distinct(), codes) assertTrue("Fen" in codes && "OSI" in codes && "WTCG" in codes) assertFalse(BattleNet.STORE.any { it.uid == "d3cn" || it.uid == "fen" }) - assertFalse(BattleNet.STORE.any { it.code == "WoWC" || it.code == "WoWF" }) + assertFalse(BattleNet.STORE.any { it.code == "WoWC" }) + assertEquals("wow_forever", BattleNet.STORE.first { it.code == "WoWF" }.uid) assertEquals("fenris", BattleNet.STORE.first { it.code == "Fen" }.uid) assertTrue(BattleNet.STORE.all { it.uid.matches(Regex("[a-z0-9_]{1,32}")) }) val installed = listOf("fenris", "diablo3_enus", null) val offered = BattleNet.STORE.filter { BattleNet.notInstalled(it, installed) }.map { it.code } assertFalse("Fen" in offered || "D3" in offered) - assertTrue("OSI" in offered) + assertTrue("OSI" in offered && "WoWF" in offered) + assertFalse("WoWF" in BattleNet.STORE.filter { BattleNet.notInstalled(it, listOf("wow_forever")) }.map { it.code }) } @Test fun aBattleNetGameStartsWithoutSteamThroughItsShortcutUntilThatIsSwitchedOff() { From 4b8c3b158d70fdc538a0723a1e26028376f1009a Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:33:13 -0500 Subject: [PATCH 063/141] fix(ui): compact chat in the session drawer stays usable on short or narrow panels (#3078) --- .../com/droiddeck/launcher/ui/AgentPage.kt | 41 ++++++++++++------- 1 file changed, 26 insertions(+), 15 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt index f447b15686..267964b052 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt @@ -11,6 +11,7 @@ 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 @@ -228,8 +229,14 @@ private fun AgentPageContent( } val topBar: @Composable () -> Unit = { AgentTopBar(panel, togglePanel, inputModifier, menu) } val inlineControls: (@Composable () -> Unit)? = if (inline) ({ - ModelChip(panel, togglePanel, inputModifier, compact = true) - ContextRing("agent-usage", onClick = { togglePanel(AgentPanel.USAGE) }) + // 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) }) + } + } menu() }) else null // A host with a title bar shows the top bar there. @@ -245,8 +252,11 @@ 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() @@ -269,8 +279,8 @@ private fun AgentPageContent( else -> { if (menuSlot == null && !inline) Box(Modifier.padding(bottom = 6.dp)) { topBar() } when (panel) { - AgentPanel.MODEL -> Box(Modifier.padding(bottom = 8.dp)) { AgentModelPicker() } - AgentPanel.USAGE -> Box(Modifier.padding(bottom = 8.dp)) { AgentUsage() } + 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() } else -> Unit } val list = rememberLazyListState() @@ -322,11 +332,12 @@ 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) + AgentComposer(composer, draft, visible && started, inlineControls, onPanel = { panel = it }, onSent = toLatest, hideAttach = inline && menuOpen) } } } } + } } /** Whether the editor has the cursor; [open] puts it there. */ @@ -400,7 +411,7 @@ private fun AgentMenu(open: Boolean, onOpen: (Boolean) -> Unit, onPanel: (AgentP Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.clip(Shape16).background(colors.surface.copy(alpha = if (open) 0.97f else 0.88f)) - .border(1.dp, pal.line, Shape16).padding(end = 2.dp), + .border(1.dp, pal.line, Shape16).padding(top = 3.dp, bottom = 3.dp, end = 4.dp), ) { androidx.compose.animation.AnimatedVisibility(open, enter = expandHorizontally(expandFrom = Alignment.End) + fadeIn(), exit = shrinkHorizontally(shrinkTowards = Alignment.End) + fadeOut()) { @@ -715,7 +726,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, + onPanel: (AgentPanel) -> Unit, onSent: () -> Unit, hideAttach: Boolean = false, ) { val context = LocalContext.current var draft by draftState @@ -747,13 +758,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) + AgentEditor(composer, draftState, visible, controls, send, hideAttach) } } /** 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) { +private fun AgentEditor(composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?, send: () -> Unit, hideAttach: Boolean = false) { val context = LocalContext.current val colors = MaterialTheme.colorScheme val pal = LocalPalette.current @@ -852,14 +863,14 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String if (stacked) Column { text(Modifier.fillMaxWidth()) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) { - if (attach) AttachButton() - if (AgentAttachments.gameFrame != null) GameFrameButton() - Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f).height(42.dp)) { if (controls != null && !focused) controls() } + 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() } actions() } } else Row(verticalAlignment = Alignment.Bottom) { - if (attach) AttachButton() - if (AgentAttachments.gameFrame != null) GameFrameButton() + AnimatedVisibility(attach && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton() } + AnimatedVisibility(AgentAttachments.gameFrame != null && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { GameFrameButton() } text(Modifier.weight(1f)) if (controls != null && !focused) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.height(42.dp)) { controls() } actions() From 3502b43cea35f27ce298df0188b3985e25d2e077 Mon Sep 17 00:00:00 2001 From: Tushar Gandhe <19225304+2-Shar@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:37:14 +0530 Subject: [PATCH 064/141] fix(ui): the controller focus ring follows each corner of the focused shape (#3036) --- .../com/droiddeck/launcher/ui/FocusGlide.kt | 57 +++++++++++-------- 1 file changed, 32 insertions(+), 25 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FocusGlide.kt b/app/src/main/java/com/droiddeck/launcher/ui/FocusGlide.kt index 92a6d0b365..c45baa29f1 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FocusGlide.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FocusGlide.kt @@ -33,6 +33,8 @@ 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 @@ -109,13 +111,21 @@ internal fun VeilRing() { } } -private fun cornerOf(shape: Shape, size: Size, dir: LayoutDirection, density: Density): Float = +private fun cornersOf(shape: Shape, size: Size, dir: LayoutDirection, density: Density): FloatArray = when (val o = shape.createOutline(size, dir, density)) { - is Outline.Rounded -> o.roundRect.topLeftCornerRadius.x - is Outline.Rectangle -> 0f - is Outline.Generic -> minOf(size.width, size.height) / 2f + 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 } } +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, @@ -190,7 +200,7 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier { val density = LocalDensity.current val dir = LocalLayoutDirection.current val edges = remember { List(4) { Animatable(0f) } } - val corner = remember { Animatable(0f) } + val corners = remember { List(4) { Animatable(0f) } } val solid = remember { Animatable(0f) } val alpha = remember { Animatable(0f) } val scope = rememberCoroutineScope() @@ -259,14 +269,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 endCorner = cornerOf(s.shape, size, dir, density) + val endCorners = cornersOf(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)) } - launch { corner.animateTo(r, Motion.tw(90)) } + corners.forEach { c -> launch { c.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 @@ -281,7 +291,9 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier { flight.cancel() val at = glide.boundsOf(s) ?: b launch { solid.animateTo(0f, Motion.tw(150)) } - launch { corner.animateTo(endCorner, Motion.sp(0.8f, 600f)) } + // 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)) } } } listOf(at.left, at.top, at.right, at.bottom).forEachIndexed { i, v -> jobs[i] = launch { edges[i].animateTo(v, Motion.sp(0.7f, 750f)) } } @@ -289,9 +301,11 @@ 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 = cornerOf(s.shape, size, dir, density) + val r = cornersOf(s.shape, size, dir, density) jobs[4]?.cancel() - jobs[4] = scope.launch { if (snap) corner.snapTo(r) else corner.animateTo(r, Motion.sp(0.8f, 500f)) } + 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)) } } + } } snapshotFlow { Triple(glide.current, glide.moves, glide.hidden || RingVeil.count > 0) }.collectLatest { (src, _, hidden) -> if (Motion.scale == 0f) { @@ -302,7 +316,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 - corner.snapTo(cornerOf(src.shape, size, dir, density)) + cornersOf(src.shape, size, dir, density).forEachIndexed { i, v -> corners[i].snapTo(v) } alpha.snapTo(1f) } shown = src @@ -343,10 +357,11 @@ 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 @@ -394,21 +409,13 @@ 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 rad = (corner.value - w / 2f).coerceIn(0f, minOf(sw, sh) / 2f) + val radii = FloatArray(4) { corners[it].value } val f = solid.value - 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.01f) drawPath(ringRect(l, t, r - l, b - t, radii, 0f), color, alpha = a * f) if (f < 0.99f) { - 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, - ) + 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) } } } From 5df25c77cad4b0d02ebb9fb24199fb2cd5647de2 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:49:10 -0500 Subject: [PATCH 065/141] feat(ui): resize the session menu by its edge, and set dual screen from the menu (#3080) * feat(ui): resize the session menu by its edge handle, and set dual screen to auto, on or off from the menu * fix(ui): the session menu resize handle follows the finger across several moves per frame * fix(ui): the closed agent menu button has no gap inside its outline * feat(ui): the session menu's resize handle hovers just past its left edge * fix(session): turning dual screen on from the menu moves the menu itself to the second screen * fix(ui): keep the menu width bounds current and restore a pinned second-screen menu after backgrounding --- .../com/droiddeck/launcher/SessionActivity.kt | 31 ++++- .../launcher/session/SessionPrefs.kt | 7 ++ .../launcher/session/SettingsReset.kt | 2 +- .../com/droiddeck/launcher/ui/AgentPage.kt | 13 ++- .../droiddeck/launcher/ui/SessionOverlay.kt | 109 +++++++++++++++++- app/src/main/res/values/strings.xml | 1 + 6 files changed, 153 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 96aeb08be3..9de836682f 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -594,6 +594,7 @@ 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) @@ -1535,6 +1536,8 @@ 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,6 +2662,7 @@ 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) @@ -4396,6 +4400,27 @@ 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_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 @@ -5958,7 +5983,11 @@ 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 openDualScreenControls() + } else { + if (SessionState.bottomMenu && !menuShownOnBottom()) pinDockedMenu() + SessionState.bottomMenu = false + if (!menuShownOnBottom()) openDualScreenControls() + } startedScreens++ SessionService.setActivityVisible(this, true, sessionActivityDisplayId) Glasses.rescan() diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 1928588c13..422db659f6 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -63,6 +63,13 @@ 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() diff --git a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt index 5a61619d12..caa78440a0 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt @@ -13,7 +13,7 @@ object SettingsReset { internal val SESSION_KEYS = setOf( "orientation", "launcherFullscreen", "controllerHaptics", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt", - "dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard", + "drawerWidthDp", "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", diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt index 267964b052..429db30258 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt @@ -408,10 +408,12 @@ 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(Shape16).background(colors.surface.copy(alpha = if (open) 0.97f else 0.88f)) - .border(1.dp, pal.line, Shape16).padding(top = 3.dp, bottom = 3.dp, end = 4.dp), + 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), ) { androidx.compose.animation.AnimatedVisibility(open, enter = expandHorizontally(expandFrom = Alignment.End) + fadeIn(), exit = shrinkHorizontally(shrinkTowards = Alignment.End) + fadeOut()) { @@ -434,7 +436,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") { onOpen(!open) } + 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) } } } @@ -448,12 +450,13 @@ 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, onClick: () -> Unit, + icon: ImageVector, label: String, enabled: Boolean = true, selected: Boolean = false, tag: String? = null, size: Dp = 44.dp, + startPadding: Dp? = null, onClick: () -> Unit, ) { val pal = LocalPalette.current Box( contentAlignment = Alignment.Center, - modifier = Modifier.padding(start = if (size < 44.dp) 4.dp else 8.dp).size(size).clip(Shape12) + modifier = Modifier.padding(start = startPadding ?: 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), diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index ffca74a17f..228c8ad8bb 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -95,6 +95,14 @@ 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 @@ -261,6 +269,8 @@ 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, @@ -418,6 +428,8 @@ 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) { @@ -506,17 +518,22 @@ 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 - val sheetWidth = if (docked) maxWidth else minOf(420.dp, maxWidth * 0.92f) + // 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 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(sheetWidth)) { Box(Modifier.fillMaxSize().onGloballyPositioned { sheetCoords = it }) { + FocusGlideHost(Modifier.fillMaxHeight().width(if (docked) sheetWidth else sheetWidth + DRAWER_HANDLE_STRIP)) { 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() @@ -965,6 +982,12 @@ 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) } }, @@ -1338,12 +1361,92 @@ 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 - if (!choosesDisplay && !swapsGame) return + val hasSecondScreen = a.secondScreenDisplays.isNotEmpty() + if (!hasSecondScreen && !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_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)), diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 68940091f6..28cfbc2d65 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -864,6 +864,7 @@ <string name="drawer_pc_keyboard">PC keyboard</string> <string name="drawer_android_keyboard">Android</string> <string name="drawer_second_screen">Second screen</string> + <string name="drawer_resize">Resize the menu</string> <string name="drawer_second_screen_shows">Shows</string> <string name="drawer_android_apps">Android apps</string> <string name="drawer_launch_app">Launch an app</string> From f683e97172d0f28d890b35e4ca386ddd15846594 Mon Sep 17 00:00:00 2001 From: The412Banner <205237651+The412Banner@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:28:33 -0500 Subject: [PATCH 066/141] fix(xbox): read a GameCore package from its config beside the generated AppxManifest (#3029) --- .../launcher/stores/xbox/XboxInstaller.kt | 4 ++- .../launcher/stores/xbox/XboxManifest.kt | 5 ++-- .../launcher/stores/xbox/XboxManifestTest.kt | 28 +++++++++++++++++++ 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxInstaller.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxInstaller.kt index 85ea9fad69..fab04097d3 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxInstaller.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxInstaller.kt @@ -103,7 +103,9 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog XboxContent.complete(app, item, folder) return folder.path } - val exe = executable(folder) + val exe = runCatching { executable(folder) }.onFailure { + StoresState.logLine("Xbox: install folder holds ${folder.list().orEmpty().sorted().take(MAX_ERROR_LINES).joinToString()}") + }.getOrThrow() 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))) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt index d966dea1e8..b33d1d0d77 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt @@ -21,8 +21,9 @@ 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 } - require(config.size + legacy.size == 1) { "Missing or ambiguous game manifest." } - val manifest = (config + legacy).single() + val manifests = config.ifEmpty { legacy } + require(manifests.size == 1) { "Missing or ambiguous game manifest." } + val manifest = manifests.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) } diff --git a/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxManifestTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxManifestTest.kt index d23072471a..cb0a7bf0cc 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxManifestTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxManifestTest.kt @@ -87,6 +87,34 @@ class XboxManifestTest { assertEquals(listOf("Retail.exe"), info.executables) assertEquals("Retail.exe", XboxManifest.executable(root)) } + @Test fun aGameCorePackageIsReadFromItsConfigBesideTheGeneratedAppxManifest() { + val root = temporary.newFolder() + java.io.File(root, "Game.exe").writeText("encrypted") + java.io.File(root, "Other.exe").writeText("encrypted") + java.io.File(root, "MicrosoftGame.config").writeText("""<Game configVersion="1"><Identity Name="Test.Game" Publisher="CN=Test" Version="1.2.3.0"/> + <ExecutableList><Executable Name="Game.exe" TargetDeviceFamily="PC"/></ExecutableList><StoreId>9AAAAAAAAAAA</StoreId></Game>""") + java.io.File(root, "appxmanifest.xml").writeText("""<?xml version="1.0" encoding="utf-8"?> + <Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"> + <Identity Name="Generated.Game" Publisher="CN=Generated" Version="9.9.9.0"/> + <Applications><Application Id="Game" Executable="Other.exe" EntryPoint="Game.App"/></Applications></Package>""") + val info = XboxManifest.read(root) + assertEquals("Test.Game", info.name) + assertEquals("1.2.3.0", info.version) + assertEquals("9AAAAAAAAAAA", info.storeId) + assertEquals("Game.exe", XboxInstaller.executable(root)) + assertFalse(XboxManifest.needsAppModel(root)) + } + @Test fun aFolderWithoutOneManifestIsStillRefused() { + val empty = temporary.newFolder() + java.io.File(empty, "Game.exe").writeText("encrypted") + assertThrows(IllegalArgumentException::class.java) { XboxManifest.read(empty) } + val twice = temporary.newFolder() + java.io.File(twice, "Game.exe").writeText("encrypted") + java.io.File(twice, "MicrosoftGame.config").writeText("<Game><Executable Name=\"Game.exe\"/></Game>") + java.io.File(twice, "microsoftgame.CONFIG").writeText("<Game><Executable Name=\"Game.exe\"/></Game>") + org.junit.Assume.assumeTrue(twice.list().orEmpty().size == 3) + assertThrows(IllegalArgumentException::class.java) { XboxManifest.read(twice) } + } @Test fun legacyPackageManifestNamesItsExecutableTheSameWay() { // A legacy EAppx package carries AppxManifest.xml and has no config; the // launcher must still find the identity and the launch path, or an install From 963af6df8eabb1d132d913a4ea3b87d05d993d28 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:32:39 -0500 Subject: [PATCH 067/141] fix(ui): Reset tabs popover takes controller focus in the Edit tabs sheet (#3082) --- .../java/com/droiddeck/launcher/ui/ManageStores.kt | 4 ++-- .../main/java/com/droiddeck/launcher/ui/StepOut.kt | 11 +++++++++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt b/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt index 39c4badb7e..2b3a4a5413 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt @@ -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) return@LaunchedEffect + if (holds || !open || Steps.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) FocusRequester.Cancel else FocusRequester.Default } } + .focusProperties { exit = { if (open && !Steps.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), diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StepOut.kt b/app/src/main/java/com/droiddeck/launcher/ui/StepOut.kt index 73e68986de..b888f08065 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StepOut.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StepOut.kt @@ -45,6 +45,7 @@ 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 @@ -174,6 +175,7 @@ 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) @@ -241,8 +243,12 @@ internal fun StepOut( LaunchedEffect(open, measured) { if (!open || measured == null || inputMode.inputMode != InputMode.Keyboard) return@LaunchedEffect delay(Motion.ms(300).toLong()) - withFrameNanos { } - runCatching { first.requestFocus() } + // 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() } + } } LaunchedEffect(open, grown, inputMode.inputMode) { @@ -289,6 +295,7 @@ 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()) From 6ecc5a22d3258da4d95fec6e608fd937c0cc4352 Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Mon, 23 Nov 2026 13:33:29 -0500 Subject: [PATCH 068/141] fix(addons): CurseForge connects once, reuses its game instance and skips rescans after its own changes (#3081) * fix(addons): CurseForge connects once, reuses its game instance and skips rescans after its own changes * fix(addons): a settled list is dropped by a refresh, a later change or a newer change * fix(curseforge): publish the report under the same lock as the turn check An older change could report its list after a newer one had already reported, so the fallback marks could miss add-ons the newer change installed. --- .../launcher/runtime/CurseForgeApp.kt | 36 +++++--- .../runtime/LinuxNetworkLinkComponent.kt | 15 ++-- .../com/droiddeck/launcher/ui/AddonBrowser.kt | 33 ++++++-- .../com/droiddeck/launcher/ui/GameDetail.kt | 2 +- .../launcher/runtime/CurseForgeAppTest.kt | 45 +++++++++- .../runtime/LinuxNetworkLinkComponentTest.kt | 33 ++++++++ .../droiddeck/launcher/ui/CurseLinkTabTest.kt | 82 +++++++++++++++++++ 7 files changed, 217 insertions(+), 29 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt b/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt index a5fb9a4a40..af25344b77 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt @@ -72,6 +72,8 @@ object CurseForgeApp { 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) => { @@ -91,7 +93,8 @@ object CurseForgeApp { 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 inner = "(async () => { const s = $SERVICES[${JSONObject.quote(service)}]; " + + 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()" + @@ -170,6 +173,7 @@ object CurseForgeApp { } 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>() @@ -232,19 +236,25 @@ object CurseForgeApp { } 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 - val instances = call(context, inspector, "GameAppService", "getGameInstances", JSONArray().put(WOW), 30_000, - "r => (r || []).map(i => ({ guid: i.guid, installPath: i.installPath }))") - return instanceFor(instances, flavorDir, detected?.optString("gameInstanceGuid")) ?: throw Failure("CurseForge did not find $flavorDir") + 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 = @@ -260,34 +270,34 @@ object CurseForgeApp { "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): Boolean { + 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 true } + listed.getOrNull()?.let { if (done(it)) return it } Thread.sleep(1_000) } - return false + return null } - fun install(context: Context, inspector: String, guid: String, projectId: String): Boolean { + 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 false + 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): Boolean { + 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 false + 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): Boolean { + 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 false + if (failed == null || failed.length() > 0) return null return settle(context, inspector, guid) { list -> list.none { it.id == project.id } } } } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponent.kt b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponent.kt index 40cdd0e471..b76172edb1 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponent.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponent.kt @@ -275,12 +275,15 @@ 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) { - val staged = File(file.path + ".staged") - java.io.FileOutputStream(staged).use { out -> - out.write(text.toByteArray()) - out.fd.sync() + 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") } - if (!staged.renameTo(file)) throw IOException("Could not replace $file") } private fun writeResolver(properties: LinkProperties?) { @@ -333,6 +336,8 @@ 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() diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt index 5251fb12bf..052241a8b9 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt @@ -110,6 +110,9 @@ internal class CurseLink(val app: UserApps.App) { 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 @@ -120,7 +123,7 @@ internal class CurseLink(val app: UserApps.App) { 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 - ?: call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid, rescan = true) }.also { + ?: (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) } @@ -131,6 +134,26 @@ internal class CurseLink(val app: UserApps.App) { 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 { @@ -174,11 +197,9 @@ internal class CurseLink(val app: UserApps.App) { return Linked(url, guid) } - fun uninstall(context: Context, target: WowAddons.Target, folder: String): Boolean = call(context, target, launch = false) { linked -> + 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) - val project = CurseForgeApp.owner(projects, folder) ?: return@call false - if (!CurseForgeApp.uninstall(context, linked.inspector, linked.guid, project)) throw CurseState() - true + CurseForgeApp.owner(projects, folder)?.let { CurseForgeApp.uninstall(context, linked.inspector, linked.guid, it) ?: throw CurseState() } } internal val stopped: Job get() = work @@ -322,7 +343,7 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd scope.launch { val done = withContext(Dispatchers.IO) { runCatching { - via.call(context, into) { + 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) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt index 5f9d6d0ebc..bb4cc867cf 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt @@ -1157,7 +1157,7 @@ internal fun AddonRow(item: WowAddons.Installed, wowiUpdate: WowAddonCatalog.Add val message = withContext(Dispatchers.IO) { if (curse != null) { val (project, link) = curse - val done = runCatching { link.call(context, target) { CurseForgeApp.update(context, it.inspector, it.guid, project.id) } }.getOrDefault(false) + 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 } diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt index 47d892993b..6400c0162e 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt @@ -5,6 +5,7 @@ import org.json.JSONArray import org.json.JSONObject import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue @@ -158,6 +159,7 @@ class CurseForgeAppTest { assertTrue(text.startsWith("(() => { const w = require('electron').BrowserWindow.getAllWindows()")) assertTrue(text.contains("desktop.html")) assertTrue(text.contains("executeJavaScript(")) + assertTrue(text.contains("let m = globalThis.__droiddeckServices; if (!m || !m[\\\"ProjectAppService\\\"]) m = globalThis.__droiddeckServices = ")) assertFalse(text.contains("show()")) val probe = CurseForgeApp.expression("InstalledProjectsAppService", "installAddon", null) assertFalse(probe.contains("await s[")) @@ -292,6 +294,37 @@ class CurseForgeAppTest { assertTrue(calls.isEmpty()) } + @Test + fun aGameFolderCurseForgeAlreadyKnowsSkipsTheFolderDetection() { + val flavor = "/root/Games/World of Warcraft/_retail_" + val curse = fakeCurse(flavor = flavor) + val context = org.robolectric.RuntimeEnvironment.getApplication() + assertEquals("g", CurseForgeApp.instance(context, url, "/root/Games/World of Warcraft", flavor)) + assertFalse("detectGameFromPath" in curse.methods) + } + + @Test + fun aGameFolderCurseForgeDoesNotKnowIsDetectedOnce() { + val flavor = "/root/Games/World of Warcraft/_retail_" + val curse = fakeCurse(flavor = flavor) + curse.known = false + val context = org.robolectric.RuntimeEnvironment.getApplication() + assertEquals("g", CurseForgeApp.instance(context, url, "/root/Games/World of Warcraft", flavor)) + assertEquals(1, curse.methods.count { it == "detectGameFromPath" }) + assertEquals(listOf("getGameInstances", "detectGameFromPath", "getGameInstances"), curse.methods.filter { it != "connect" }) + } + + @Test + fun curseForgeConnectsOncePerLaunch() { + val curse = fakeCurse() + val context = org.robolectric.RuntimeEnvironment.getApplication() + val launched = "ws://127.0.0.1:43118/${java.util.UUID.randomUUID()}" + CurseForgeApp.projects(context, launched, "g") + CurseForgeApp.projects(context, launched, "g") + CurseForgeApp.instance(context, launched, "/root", "") + assertEquals(1, curse.methods.count { it == "connect" }) + } + @Test fun theInspectorUrlIsRedactedFromCommandLogs() { val line = CurseForgeApp.evalArgv(url, "x", 1_000).joinToString(" ") @@ -305,6 +338,7 @@ class CurseForgeAppTest { val methods = java.util.Collections.synchronizedList(mutableListOf<String>()) @Volatile var unreachableAfterDelete = false @Volatile var unreachable = false + @Volatile var known = true fun add(id: String, folder: String, status: Int) = add(id, listOf(folder), status) @@ -328,8 +362,11 @@ class CurseForgeAppTest { projects.forEach { it.put("status", 1) } true } - "detectGameFromPath" -> JSONObject().put("gameInstanceGuid", "g") - "getGameInstances" -> JSONArray().put(JSONObject().put("guid", "g").put("installPath", flavor)) + "detectGameFromPath" -> { + known = true + JSONObject().put("gameInstanceGuid", "g") + } + "getGameInstances" -> if (known) JSONArray().put(JSONObject().put("guid", "g").put("installPath", flavor)) else JSONArray() "deleteMods" -> { projects.removeAll { p -> (p.getString("installedModId") in expression).also { gone -> @@ -467,7 +504,7 @@ class CurseForgeAppTest { curse.add("18808", "TomTom", 1) val before = CurseForgeApp.projects(context, url, "g", rescan = true).associate { it.id to it.update } assertEquals(mapOf("298842" to true, "18808" to false), before) - assertTrue(CurseForgeApp.update(context, url, "g", "298842")) + assertNotNull(CurseForgeApp.update(context, url, "g", "298842")) assertTrue("updateMod" in curse.methods) assertTrue(CurseForgeApp.projects(context, url, "g").none { it.update }) } @@ -479,7 +516,7 @@ class CurseForgeAppTest { curse.add("298842", "Leatrix_Maps", 1) curse.add("18808", "TomTom", 1) val project = CurseForgeApp.owner(CurseForgeApp.projects(context, url, "g"), "Leatrix_Maps")!! - assertTrue(CurseForgeApp.uninstall(context, url, "g", project)) + assertNotNull(CurseForgeApp.uninstall(context, url, "g", project)) assertEquals(listOf("18808"), CurseForgeApp.projects(context, url, "g").map { it.id }) assertFalse(File(curse.addOns, "Leatrix_Maps").exists()) assertTrue(File(curse.addOns, "TomTom").isDirectory) diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponentTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponentTest.kt index ee745b7d14..dea3a46859 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponentTest.kt @@ -155,4 +155,37 @@ class LinuxNetworkLinkComponentTest { }) assertEquals(before, link) } + + @Test fun parallelPublishersFromSeparateComponentsAllLandAndLeaveNoStagedCopy() { + val context = ApplicationProvider.getApplicationContext<Context>() + val link = properties("10.0.0.1/24").route("1.0.0.0", 8).route("128.0.0.0", 1) + val failures = java.util.concurrent.atomic.AtomicInteger() + val threads = (0 until 8).map { + Thread { + val component = LinuxNetworkLinkComponent(context, temporary.root) + repeat(25) { + runCatching { + ReflectionHelpers.callInstanceMethod<Unit>(component, "replace", + from(java.io.File::class.java, temporary.root.resolve("etc/droiddeck-net").apply { parentFile!!.mkdirs() }), + from(String::class.java, "if tun0 $it\n")) + }.onFailure { failures.incrementAndGet() } + } + }.apply { start() } + } + threads.forEach { it.join() } + assertEquals(0, failures.get()) + assertFalse(temporary.root.resolve("etc/droiddeck-net.staged").exists()) + assertEquals("if tun0 24\n", temporary.root.resolve("etc/droiddeck-net").readText()) + } + + @Test fun anUnchangedFileIsNotRewritten() { + val context = ApplicationProvider.getApplicationContext<Context>() + val component = LinuxNetworkLinkComponent(context, temporary.root) + val file = temporary.root.resolve("etc/resolv.conf").apply { parentFile!!.mkdirs(); writeText("nameserver 1.1.1.1\n") } + assertTrue(file.setLastModified(1_000_000L)) + ReflectionHelpers.callInstanceMethod<Unit>(component, "replace", from(java.io.File::class.java, file), from(String::class.java, "nameserver 1.1.1.1\n")) + assertEquals(1_000_000L, file.lastModified()) + ReflectionHelpers.callInstanceMethod<Unit>(component, "replace", from(java.io.File::class.java, file), from(String::class.java, "nameserver 8.8.8.8\n")) + assertEquals("nameserver 8.8.8.8\n", file.readText()) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt index 0ea4048e3a..2811284d0e 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt @@ -133,6 +133,88 @@ class CurseLinkTabTest { } } + @Test + fun anInstallHandsCurseForgesSettledListToTheNextReadWithoutARescan() { + val target = wow() + val link = CurseLink(app) + try { + link.installed(context, target, 0) + assertTrue(link.change(context, target) { CurseForgeApp.install(context, it.inspector, it.guid, "298842") }) + assertEquals(listOf("298842"), link.installed(context, target, 1).map { it.id }) + assertEquals(1, methods.count { it == "scanGameInstance" }) + link.installed(context, target, 2) + assertEquals(2, methods.count { it == "scanGameInstance" }) + } finally { + runBlocking { link.close(context).join() } + } + } + + @Test + fun aFailedInstallLeavesTheNextReadToRescan() { + val target = wow() + val link = CurseLink(app) + try { + link.installed(context, target, 0) + assertFalse(link.change(context, target) { null }) + link.installed(context, target, 1) + assertEquals(2, methods.count { it == "scanGameInstance" }) + } finally { + runBlocking { link.close(context).join() } + } + } + + @Test + fun aRefreshAfterAnInstallStillRescans() { + val target = wow() + val link = CurseLink(app) + try { + link.installed(context, target, 0) + assertTrue(link.change(context, target) { CurseForgeApp.install(context, it.inspector, it.guid, "298842") }) + link.refresh() + link.installed(context, target, 1) + assertEquals(2, methods.count { it == "scanGameInstance" }) + } finally { + runBlocking { link.close(context).join() } + } + } + + @Test + fun aFailedChangeDropsAnEarlierSettledList() { + val target = wow() + val link = CurseLink(app) + try { + link.installed(context, target, 0) + assertTrue(link.change(context, target) { CurseForgeApp.install(context, it.inspector, it.guid, "298842") }) + assertFalse(link.change(context, target) { null }) + link.installed(context, target, 1) + assertEquals(2, methods.count { it == "scanGameInstance" }) + } finally { + runBlocking { link.close(context).join() } + } + } + + @Test + fun anOlderChangeFinishingLastDoesNotReplaceTheNewerList() { + val target = wow() + tocFolder(target.addOns, "Older", "1") + tocFolder(target.addOns, "Newer", "2") + val older = CurseForgeApp.Project("1", "11", listOf("Older"), false) + val newer = CurseForgeApp.Project("2", "22", listOf("Newer"), false) + val link = CurseLink(app) + try { + link.installed(context, target, 0) + assertTrue(link.change(context, target) { + assertTrue(link.change(context, target) { listOf(older, newer) }) + listOf(older) + }) + assertEquals(setOf("1", "2"), CurseLink.lastReported(target).keys) + assertEquals(listOf("1", "2"), link.installed(context, target, 1).map { it.id }) + assertEquals(1, methods.count { it == "scanGameInstance" }) + } finally { + runBlocking { link.close(context).join() } + } + } + @Test fun aFailedScanKeepsTheLastReportInsteadOfClearingIt() { val target = wow() From db80e7592a3b323637b7389a69590f9a64cbc97d Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:34:27 -0500 Subject: [PATCH 069/141] tools: quick_deploy skips lint vital (#3085) --- tools/quick_deploy.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tools/quick_deploy.sh b/tools/quick_deploy.sh index 1166feaa6b..559670ce99 100755 --- a/tools/quick_deploy.sh +++ b/tools/quick_deploy.sh @@ -23,7 +23,8 @@ while IFS= read -r dir; do done < <(ls -d "${sdk_dir}"/build-tools/* 2>/dev/null | sort -rV) [[ -n "${build_tools}" ]] || { echo "No build-tools with aapt, zipalign and apksigner under ${sdk_dir}." >&2; exit 1; } -./gradlew -q -PallowStaleRuntime=true :app:assembleRelease +# Lint vital is most of an incremental build and CI runs it. +./gradlew -q -PallowStaleRuntime=true :app:assembleRelease -x lintVitalAnalyzeRelease ( cd "$(dirname "${signing_env}")" set -a; . "${signing_env}"; set +a From 86ad1544a6a02954230269549839da98d82a86dd Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:08:17 -0500 Subject: [PATCH 070/141] feat(ui): a More tab in the session menu for rarely used pages (#3084) * feat(ui): a More tab in the session menu keeps the pages you use least, and holds the way to arrange them * fix(ui): bumpers walk only the strip, and back leaves a page kept inside More * feat(ui): a Back to More row at the top of pages kept inside More * refactor(ui): the arrange pages editor reuses the Edit tabs More divider * feat(ui): the Session page can be kept inside More * fix(ui): the on-screen bumpers step across the strip like the physical ones --- .../com/droiddeck/launcher/SessionActivity.kt | 7 +- .../com/droiddeck/launcher/ui/DevPreview.kt | 2 +- .../launcher/ui/ManageDrawerPages.kt | 4 +- .../launcher/ui/SessionDrawerPage.kt | 21 ++++- .../droiddeck/launcher/ui/SessionOverlay.kt | 92 +++++++++++++++++-- .../com/droiddeck/launcher/ui/TabsSettings.kt | 4 +- app/src/main/res/values/strings.xml | 3 + .../launcher/ui/SessionDrawerPageTest.kt | 38 +++++++- 8 files changed, 150 insertions(+), 21 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 9de836682f..a209bac123 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -154,6 +154,8 @@ 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 @@ -3668,8 +3670,9 @@ 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) { - drawerPage = sessionDrawerPages(glasses.present) - .step(drawerPage, if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1) + // 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) releaseDrawerDirection() } return true diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt b/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt index 21057d1dea..46ea147324 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt @@ -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().step(page, if (code == android.view.KeyEvent.KEYCODE_BUTTON_R1) 1 else -1) + page = sessionDrawerPages().let { it.strip().step(it.tabFor(page), if (code == android.view.KeyEvent.KEYCODE_BUTTON_R1) 1 else -1) } } true } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ManageDrawerPages.kt b/app/src/main/java/com/droiddeck/launcher/ui/ManageDrawerPages.kt index 30a9c554f9..c1c918ef32 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ManageDrawerPages.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ManageDrawerPages.kt @@ -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 = { true }, + movable = { it != SessionDrawerPage.MORE.name }, rowHeight = STORE_ROW, handleWidth = STORE_HANDLE, releaseSignal = releaseSignal, onGrab = { before -> DrawerPages.heldFrom = before?.mapNotNull { n -> current.firstOrNull { it.name == n } } }, @@ -66,6 +66,8 @@ 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) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt index 5dd8ba682f..b2bc10c8a4 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt @@ -12,10 +12,11 @@ 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 { @@ -27,7 +28,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 + fun hideable(page: SessionDrawerPage) = page != SessionDrawerPage.SESSION && page != SessionDrawerPage.MORE fun load(context: Context) { order = arrange(SessionPrefs.drawerPageOrder(context)) @@ -81,6 +82,22 @@ 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)] diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index 228c8ad8bb..b84a27be75 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -39,6 +39,7 @@ 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 @@ -182,6 +183,7 @@ 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) { @@ -194,6 +196,7 @@ 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 { @@ -440,11 +443,17 @@ 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) { - if (host.open != null) host.open = null else a.onClose() + when { + host.open != null -> host.open = null + insideMore -> onPageChange(SessionDrawerPage.MORE) + else -> a.onClose() + } } BackHandler(enabled = open && confirmStop) { confirmStop = false } - val layerOpen = open && (host.open != null || appToChooseDisplay != null || confirmStop) + val layerOpen = open && (host.open != null || appToChooseDisplay != null || confirmStop || insideMore) LaunchedEffect(layerOpen) { onLayerChange(layerOpen) } var seenBackRequest by remember { mutableStateOf(backRequest) } LaunchedEffect(backRequest) { @@ -454,9 +463,10 @@ 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 } + LaunchedEffect(page) { host.open = null; appToChooseDisplay = null; managing = false } LaunchedEffect(a.selectedGameProfileId) { if (host.open == "fex") host.open = null } @@ -544,6 +554,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont DrawerPages.rearrange(drawerContext, held) releaseSignal++ } ?: run { managing = false } + insideMore -> onPageChange(SessionDrawerPage.MORE) else -> a.onClose() } } @@ -621,16 +632,14 @@ 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.step(page, -1)) + host.open = null; onPageChange(pages.strip().step(pages.tabFor(page), -1)) } - DrawerPageTabs(page = page, pages = pages, compact = true, modifier = Modifier.weight(1f)) { index -> host.open = null; onPageChange(index) } + DrawerPageTabs(page = pages.tabFor(page), pages = pages.strip(), 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.step(page, 1)) + host.open = null; onPageChange(pages.strip().step(pages.tabFor(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), @@ -905,6 +914,7 @@ 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)) { @@ -1175,6 +1185,70 @@ 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, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt b/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt index 0e081d5cda..391957cf58 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt @@ -213,10 +213,10 @@ internal fun SortableRows( } @Composable -private fun MoreLine() { +internal fun MoreLine(height: androidx.compose.ui.unit.Dp = TAB_ROW) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current - Column(Modifier.fillMaxWidth().height(TAB_ROW).testTag("tab-more-line")) { + Column(Modifier.fillMaxWidth().height(height).testTag("tab-more-line")) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 28cfbc2d65..1b57e5b281 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -704,6 +704,9 @@ <string name="drawer_prev_page">Previous page</string> <string name="drawer_next_page">Next page</string> <string name="drawer_manage_pages">Arrange pages</string> + <string name="drawer_page_more">More</string> + <string name="drawer_more_back">Back to %1$s</string> + <string name="drawer_more_empty">Nothing is kept here. Arrange pages and move one below the More row.</string> <string name="drawer_pages_reset">Reset</string> <string name="drawer_pages_done">Done</string> <string name="drawer_hud">Performance HUD</string> diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt index 019f47784c..18911a3521 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt @@ -8,15 +8,45 @@ class SessionDrawerPageTest { val pages = sessionDrawerPages(hasAgent = false) assertEquals(SessionDrawerPage.CONTROLLER, pages.first()) assertEquals(SessionDrawerPage.DISPLAY, pages.step(SessionDrawerPage.CONTROLLER, 1)) - assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.CONTROLLER, -1)) - assertEquals(SessionDrawerPage.CONTROLLER, pages.step(SessionDrawerPage.SESSION, 1)) + assertEquals(SessionDrawerPage.VR, pages.step(SessionDrawerPage.CONTROLLER, -1)) assertEquals(SessionDrawerPage.HUD, pages.step(SessionDrawerPage.DISPLAY, 1)) assertEquals(SessionDrawerPage.EFFECTS, pages.step(SessionDrawerPage.HUD, 1)) - assertEquals(SessionDrawerPage.VR, pages.step(SessionDrawerPage.EFFECTS, 1)) - assertEquals(SessionDrawerPage.GAMES, pages.step(SessionDrawerPage.VR, 1)) + assertEquals(SessionDrawerPage.GAMES, pages.step(SessionDrawerPage.EFFECTS, 1)) assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.GAMES, 1)) } + @Test fun moreKeepsSteamVrByDefaultAndStandsInForThePagesInsideIt() { + val pages = sessionDrawerPages(hasAgent = false) + assertEquals(listOf(SessionDrawerPage.VR), pages.inMore()) + assertEquals(SessionDrawerPage.MORE, pages.strip().last()) + assertFalse(SessionDrawerPage.VR in pages.strip()) + assertEquals(SessionDrawerPage.MORE, pages.tabFor(SessionDrawerPage.VR)) + assertEquals(SessionDrawerPage.GAMES, pages.tabFor(SessionDrawerPage.GAMES)) + val strip = pages.strip() + assertEquals(SessionDrawerPage.MORE, strip.step(SessionDrawerPage.SESSION, 1)) + assertEquals(SessionDrawerPage.CONTROLLER, strip.step(SessionDrawerPage.MORE, 1)) + assertEquals(SessionDrawerPage.SESSION, strip.step(pages.tabFor(SessionDrawerPage.VR), -1)) + } + + @Test fun anOlderSavedOrderKeepsItsPagesAndGetsAMoreTabAfterSession() { + val saved = listOf("CONTROLLER", "DISPLAY", "HUD", "EFFECTS", "VR", "GAMES", "AGENT", "SESSION") + val out = DrawerPages.arrange(saved) + assertEquals(SessionDrawerPage.MORE, out[out.indexOf(SessionDrawerPage.SESSION) + 1]) + assertTrue(out.indexOf(SessionDrawerPage.VR) < out.indexOf(SessionDrawerPage.EFFECTS) + 2) + assertTrue(out.inMore().isEmpty()) + } + + @Test fun sessionCanBeKeptInsideMore() { + val saved = listOf("CONTROLLER", "DISPLAY", "HUD", "EFFECTS", "GAMES", "AGENT", "MORE", "SESSION", "VR") + val out = DrawerPages.arrange(saved) + assertEquals(listOf(SessionDrawerPage.SESSION, SessionDrawerPage.VR), out.inMore()) + assertFalse(SessionDrawerPage.SESSION in out.strip()) + } + + @Test fun moreAndSessionCannotBeHidden() { + assertFalse(DrawerPages.hideable(SessionDrawerPage.MORE)) + } + @Test fun glassesAddTheirPageAfterController() { val pages = sessionDrawerPages(hasGlasses = true, hasAgent = false) assertEquals(SessionDrawerPage.GLASSES, pages.step(SessionDrawerPage.CONTROLLER, 1)) From e3b1b60914f7c539ff5ac1e0c890508f8e789b02 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:16:51 -0500 Subject: [PATCH 071/141] feat(steam): first-run defaults for big art and the bouncing logo screensaver (#3087) * feat(steam): first-run defaults for big art on Library home and the bouncing logo screensaver * fix(steam): seeded keys land in the root store when nested stores close on its last line --- .../launcher/session/SessionFiles.kt | 14 ++++++++++--- .../launcher/session/SteamUserDefaultsTest.kt | 21 +++++++++++++++++++ .../usr/local/bin/droiddeck-steam-ui-scale | 12 ++++++++++- tools/tests/test_steam_ui_scale.py | 12 +++++++++++ 4 files changed, 55 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index 34d96eab4b..1645851229 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -660,6 +660,7 @@ 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}" /** @@ -709,7 +710,12 @@ 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)) } - return seedRecentSort(out, 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 } // The library sort lives inside a JSON string; Steam writes bSortedByRecent:false until the player picks a sort, @@ -729,9 +735,11 @@ 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 indent = text.substring(lineStart, parent.close).takeWhile { it == '\t' || it == ' ' } + "\t" + val before = text.substring(lineStart, parent.close) + val indent = before.takeWhile { it == '\t' || it == ' ' } + "\t" val section = lines.joinToString(newline) { indent + it } + newline - return text.substring(0, lineStart) + section + text.substring(lineStart) + if (before.isBlank()) return text.substring(0, lineStart) + section + text.substring(lineStart) + return text.substring(0, parent.close) + newline + section + text.substring(parent.close) } private val IDLE_SLEEP_TIMERS = listOf("IdleSuspendBatterySeconds", "IdleSuspendACSeconds") diff --git a/app/src/test/java/com/droiddeck/launcher/session/SteamUserDefaultsTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SteamUserDefaultsTest.kt index 468b5728f8..9d5d76fa92 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SteamUserDefaultsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SteamUserDefaultsTest.kt @@ -59,6 +59,27 @@ class SteamUserDefaultsTest { assertFalse(File(home, "userdata/123/config/droiddeck-user-defaults-initialized").exists()) } + @Test fun libraryHomeUsesBigArtUnlessChosenOtherwise() { + val fresh = home("") + SessionFiles.seedUserDefaults(fresh) + assertTrue(text(fresh).contains("\"LibraryHomeBigArt\"\t\t\"1\"")) + val chosen = home("\t\"LibraryHomeBigArt\"\t\t\"0\"\n") + SessionFiles.seedUserDefaults(chosen) + assertTrue(text(chosen).contains("\"LibraryHomeBigArt\"\t\t\"0\"")) + assertEquals(1, Regex("LibraryHomeBigArt").findAll(text(chosen)).count()) + } + + @Test fun bigArtLandsInTheRootWhenNestedStoresCloseOnItsLastLine() { + val home = home("") + File(home, "userdata/123/config/localconfig.vdf").writeText( + "\"UserLocalConfigStore\"\n{\n\t\"WebStorage\"\n\t{\n\t\t\"Other\"\t\t\"x\"\n\t}}\n") + SessionFiles.seedUserDefaults(home) + val t = text(home) + val beforeBigArt = t.substring(0, t.indexOf("\"LibraryHomeBigArt\"")) + assertEquals(beforeBigArt.count { it == '{' }, beforeBigArt.count { it == '}' } + 1) + assertTrue(t.indexOf("\"CachedBatteryPreferences\"") < t.indexOf("\"LibraryHomeBigArt\"")) + } + @Test fun librarySortsByRecentlyPlayed() { val fresh = home("") SessionFiles.seedUserDefaults(fresh) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-ui-scale b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-ui-scale index c1c2cc6ebc..2a9585efe7 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-ui-scale +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-ui-scale @@ -10,6 +10,7 @@ import tempfile DISPLAY = "External: gamescope|||Windowed" NATIVE_RESOLUTION = "EnableSteamNativeExternalResolution" SCREENSAVER_IN_GAME = ("Customization", "Screensaver", "WhileInGame") +SCREENSAVER_CURRENT = ("Customization", "Screensaver", "CurrentScreensaver") TOKEN = re.compile(r'\s+|//[^\n]*|"(?:\\.|[^"\\])*"|[{}]') @@ -137,6 +138,10 @@ def seed_no_screensaver_in_game(text): return seed_value(text, SCREENSAVER_IN_GAME, '0') +def seed_bouncing_logo(text): + return seed_value(text, SCREENSAVER_CURRENT, 'steam-bouncinglogo') + + def atomic_write(path, text): path.parent.mkdir(parents=True, exist_ok=True) fd, temporary = tempfile.mkstemp(prefix='.' + path.name, dir=path.parent) @@ -179,6 +184,11 @@ def initialize_screensaver(steam_root): '== steam: no screensaver over a running game') +def initialize_screensaver_choice(steam_root): + return seed_once(steam_root, 'droiddeck-screensaver-choice-initialized', seed_bouncing_logo, + '== steam: bouncing logo screensaver') + + if __name__ == '__main__': status = 0 try: @@ -186,7 +196,7 @@ if __name__ == '__main__': except (OSError, ValueError, RecursionError) as error: print('== steam: left UI scale unchanged: ' + str(error), file=sys.stderr) status = 1 - for what, step in (('native resolution', initialize_native_resolution), ('screensaver', initialize_screensaver)): + for what, step in (('native resolution', initialize_native_resolution), ('screensaver', initialize_screensaver), ('screensaver choice', initialize_screensaver_choice)): try: step(sys.argv[1]) except (OSError, ValueError, RecursionError) as error: diff --git a/tools/tests/test_steam_ui_scale.py b/tools/tests/test_steam_ui_scale.py index 5440dcd497..9a65305e2b 100644 --- a/tools/tests/test_steam_ui_scale.py +++ b/tools/tests/test_steam_ui_scale.py @@ -16,6 +16,8 @@ initialize_native_resolution = MODULE['initialize_native_resolution'] NATIVE_RESOLUTION = MODULE['NATIVE_RESOLUTION'] seed_no_screensaver_in_game = MODULE['seed_no_screensaver_in_game'] initialize_screensaver = MODULE['initialize_screensaver'] +seed_bouncing_logo = MODULE['seed_bouncing_logo'] +initialize_screensaver_choice = MODULE['initialize_screensaver_choice'] class SteamUiScaleTest(unittest.TestCase): @@ -182,6 +184,16 @@ class SteamScreensaverTest(unittest.TestCase): self.assertEqual('0', screensaver.get('WhileInGame')) self.assertIn('\t\t\t"WhileInGame"\t\t"0"\n\t\t}\n', updated) + def test_fresh_client_gets_the_bouncing_logo(self): + self.assertTrue(initialize_screensaver_choice(self.root)) + screensaver = parse(self.config.read_text()).get('InstallConfigStore').get('Customization').get('Screensaver') + self.assertEqual('steam-bouncinglogo', screensaver.get('CurrentScreensaver')) + self.assertTrue(self.config.with_name('droiddeck-screensaver-choice-initialized').exists()) + + def test_a_screensaver_already_picked_is_kept(self): + text = '"InstallConfigStore" { "Customization" { "Screensaver" { "CurrentScreensaver" "other" } } }' + self.assertEqual((text, False), seed_bouncing_logo(text)) + def test_users_choice_is_kept(self): text = '"InstallConfigStore" { "Customization" { "Screensaver" { "WhileInGame" "1" } } }' self.assertEqual((text, False), seed_no_screensaver_in_game(text)) From b0a8c0898ed4c9d046c575bc1377eaacc0622a12 Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Mon, 23 Nov 2026 15:24:05 -0500 Subject: [PATCH 072/141] ci: keep unit-test scratch out of the runner's shared /tmp (#3083) * ci: keep unit-test scratch out of the runner's shared /tmp Test JVMs now write temp files under the test task's build folder, which checkout wipes on every job, so a killed run no longer leaves Robolectric and JUnit folders behind in /tmp. Self-hosted runners also clear stale test folders they own in /tmp, drop the regenerable Gradle build cache when the workspace has under 20 GB free, and log disk use so a full disk is visible in the job. * test(agent): size check no longer depends on the temp path's length A symlink's own size is the length of its target path, so the old 100-byte bound failed once the temp dir moved under the build folder. * ci: never remove a mount point while clearing runner scratch * ci: keep a scratch folder that anything inside it touched recently * ci: keep a scratch folder the freshness scan could not read --- .github/workflows/build.yml | 7 +++++++ app/build.gradle | 3 +++ .../droiddeck/launcher/agent/AgentStorageTest.kt | 4 ++-- tools/ci/clear-runner-scratch.sh | 14 ++++++++++++++ 4 files changed, 26 insertions(+), 2 deletions(-) create mode 100755 tools/ci/clear-runner-scratch.sh diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index c3b3f50cf6..60f8882401 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -164,6 +164,9 @@ 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: @@ -367,6 +370,10 @@ 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 }} diff --git a/app/build.gradle b/app/build.gradle index 634a41eec0..b32bc078a9 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -232,6 +232,9 @@ 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 } diff --git a/app/src/test/java/com/droiddeck/launcher/agent/AgentStorageTest.kt b/app/src/test/java/com/droiddeck/launcher/agent/AgentStorageTest.kt index dc12206545..bdb58b2a39 100644 --- a/app/src/test/java/com/droiddeck/launcher/agent/AgentStorageTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/agent/AgentStorageTest.kt @@ -11,13 +11,13 @@ class AgentStorageTest { @Test fun removingAFolderKeepsWhatItsLinksPointAt() { val base = Files.createTempDirectory("agent-storage") val outside = Files.createDirectories(base.resolve("sdcard")) - Files.write(outside.resolve("save.dat"), ByteArray(100)) + Files.write(outside.resolve("save.dat"), ByteArray(1 shl 20)) val item = Files.createDirectories(base.resolve("rootfs/android-sdk")) Files.write(item.resolve("a.jar"), ByteArray(10)) val linked = runCatching { Files.createSymbolicLink(item.resolve("saves"), outside) }.isSuccess assumeTrue("symbolic links need privileges on this OS", linked) - assertTrue(AgentStorage.size(item) < 100) + assertTrue(AgentStorage.size(item) < 1 shl 20) AgentStorage.delete(item) assertFalse(Files.exists(item)) assertTrue(Files.exists(outside.resolve("save.dat"))) diff --git a/tools/ci/clear-runner-scratch.sh b/tools/ci/clear-runner-scratch.sh new file mode 100755 index 0000000000..aab34a2e92 --- /dev/null +++ b/tools/ci/clear-runner-scratch.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -uo pipefail +workspace="${1:?}" +find /tmp -maxdepth 1 -user "$(id -u)" \( -name 'robolectric-*' -o -name 'junit*' -o -name 'gradle-*' -o -name 'kotlin-*' \) -mmin +180 -print0 | + while IFS= read -r -d '' entry; do + recent=$(find "$entry" -xdev -mmin -180 -print -quit 2>/dev/null) && [ -z "$recent" ] && rm -rf --one-file-system --preserve-root=all -- "$entry" + done +free=$(df --output=avail -k "$workspace" | tail -1) +if [ "$free" -lt 20971520 ]; then + rm -rf --one-file-system --preserve-root=all -- "${HOME:?}/.gradle/caches/build-cache-1" "${HOME:?}/.gradle/.tmp" +fi +df -h /tmp "$workspace" +du -xsh /tmp "${HOME:?}/.gradle" "${HOME:?}/.cargo" "${HOME:?}/.m2" "$(dirname "$workspace")" 2>/dev/null | sort -h +exit 0 From 15b1e196afa1208d32bb53a7739867b2c1a8bfc9 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:31:13 -0500 Subject: [PATCH 073/141] fix(remote-play): the decoder reports a changed stream size, so fullscreen streams are not cropped to a corner (#3095) * fix(remote-play): the decoder reports a changed stream size, so fullscreen streams are not cropped to a corner * fix(remote-play): capture buffers are sized for large streams up front and a size change reopens only the app decoder * fix(remote-play): reject out-of-range scaling deltas and an SPS that ends before its frame flag --- tools/linuxfs/preload/vdec.c | 197 ++++++++++++++++++++++++++- tools/tests/test_vdec_emulator.py | 12 +- tools/tests/test_vdec_stream_size.py | 140 +++++++++++++++++++ 3 files changed, 338 insertions(+), 11 deletions(-) create mode 100644 tools/tests/test_vdec_stream_size.py diff --git a/tools/linuxfs/preload/vdec.c b/tools/linuxfs/preload/vdec.c index 7d3761e290..3bd38f3bc9 100644 --- a/tools/linuxfs/preload/vdec.c +++ b/tools/linuxfs/preload/vdec.c @@ -29,6 +29,8 @@ #define VDEC_BITSTREAM_SIZE (4u << 20) #define VDEC_PADDING 64 #define VDEC_DUMB 64 +#define VDEC_CAP_MIN_WIDTH 4096u +#define VDEC_CAP_MIN_HEIGHT 2304u struct vd_dma_heap_alloc { uint64_t len; @@ -135,6 +137,8 @@ struct vdec { uint32_t n_cap_done; int out_on, cap_on; int sock, hw, hw_failed; + int resizing; + uint32_t stream_w, stream_h; int64_t pts; void *ctx, *packet, *frame; uint8_t *packet_data; @@ -318,7 +322,8 @@ static int vd_open_hardware(struct vdec *v) { if (sock < 0) return -1; struct vdec_config c = { .type = VDEC_CONFIG, .codec = v->fourcc == V4L2_PIX_FMT_HEVC ? VENC_HEVC : VENC_H264, - .width = v->width ? v->width : v->cap_width, .height = v->height ? v->height : v->cap_height, + .width = v->stream_w ? v->stream_w : v->width ? v->width : v->cap_width, + .height = v->stream_h ? v->stream_h : v->height ? v->height : v->cap_height, .stride = v->bpl, .rows = v->cap_height, .bitstreams = v->out_count, .bitstream_size = VDEC_BITSTREAM_SIZE, }; struct vdec_result r; @@ -563,8 +568,12 @@ static int vd_set_format(struct vdec *v, struct v4l2_format *f, int apply) { t.fourcc = p->pixelformat; t.width = p->width; t.height = p->height; + t.stream_w = p->width; + t.stream_h = p->height; } else { uint32_t w = p->width > t.width ? p->width : t.width, h = p->height > t.height ? p->height : t.height; + if (w < VDEC_CAP_MIN_WIDTH) w = VDEC_CAP_MIN_WIDTH; + if (h < VDEC_CAP_MIN_HEIGHT) h = VDEC_CAP_MIN_HEIGHT; if (w < 16 || h < 16 || w > 8192 || h > 8192) return -EINVAL; t.cap_width = (w + 15) & ~15u; t.cap_height = (h + 15) & ~15u; @@ -574,6 +583,7 @@ static int vd_set_format(struct vdec *v, struct v4l2_format *f, int apply) { if (apply) { if (t.fourcc != v->fourcc || (t.hw && (t.bpl != v->bpl || t.cap_height != v->cap_height))) vd_close_decoder(&t); *v = t; + if (v->cap_width >= v->width && v->cap_height >= v->height) v->resizing = 0; } vd_fill_format(&t, f); return 0; @@ -615,13 +625,184 @@ static int vd_querybuf(struct vdec *v, struct v4l2_buffer *b) { return 0; } +struct vd_bits { + const uint8_t *data; + size_t size, pos; +}; + +static uint32_t vd_get_bits(struct vd_bits *b, unsigned count) { + uint32_t value = 0; + while (count--) { + size_t byte = b->pos >> 3; + value = value << 1 | (byte < b->size ? (b->data[byte] >> (7 - (b->pos & 7))) & 1u : 0u); + b->pos++; + } + return value; +} + +static uint32_t vd_get_ue(struct vd_bits *b) { + unsigned zeros = 0; + while (zeros < 32 && vd_get_bits(b, 1) == 0 && (b->pos >> 3) < b->size) zeros++; + if (zeros >= 32) return 0; + return ((1u << zeros) - 1) + (zeros ? vd_get_bits(b, zeros) : 0); +} + +static int32_t vd_get_se(struct vd_bits *b) { + uint32_t k = vd_get_ue(b); + return (k & 1) ? (int32_t)((k + 1) / 2) : -(int32_t)(k / 2); +} + +static int vd_skip_scaling_list(struct vd_bits *b, unsigned size) { + int32_t last = 8, next = 8; + for (unsigned i = 0; i < size; i++) { + if (next != 0) { + int32_t delta = vd_get_se(b); + if (delta < -128 || delta > 127) return -1; + next = (last + delta + 256) % 256; + } + last = next == 0 ? last : next; + } + return 0; +} + +/* The coded size an H.264 SPS announces, rounded up to whole macroblocks, as a V4L2 decoder reports it. */ +static int vd_parse_sps_h264(const uint8_t *rbsp, size_t size, uint32_t *width, uint32_t *height) { + uint8_t buf[512]; + size_t n = 0; + for (size_t i = 0; i < size && n < sizeof buf; i++) { + if (i >= 2 && rbsp[i] == 3 && rbsp[i - 1] == 0 && rbsp[i - 2] == 0) continue; + buf[n++] = rbsp[i]; + } + struct vd_bits b = { buf, n, 0 }; + uint32_t profile = vd_get_bits(&b, 8); + vd_get_bits(&b, 16); + vd_get_ue(&b); + uint32_t chroma = 1; + if (profile == 100 || profile == 110 || profile == 122 || profile == 244 || profile == 44 || profile == 83 || + profile == 86 || profile == 118 || profile == 128 || profile == 138 || profile == 139 || profile == 134 || profile == 135) { + chroma = vd_get_ue(&b); + if (chroma == 3) vd_get_bits(&b, 1); + vd_get_ue(&b); + vd_get_ue(&b); + vd_get_bits(&b, 1); + if (vd_get_bits(&b, 1)) { + for (unsigned i = 0; i < (chroma != 3 ? 8u : 12u); i++) + if (vd_get_bits(&b, 1) && vd_skip_scaling_list(&b, i < 6 ? 16 : 64) != 0) return -1; + } + } + vd_get_ue(&b); + uint32_t poc = vd_get_ue(&b); + if (poc == 0) { + vd_get_ue(&b); + } else if (poc == 1) { + vd_get_bits(&b, 1); + vd_get_se(&b); + vd_get_se(&b); + uint32_t cycle = vd_get_ue(&b); + for (uint32_t i = 0; i < cycle && i < 256; i++) vd_get_se(&b); + } + vd_get_ue(&b); + vd_get_bits(&b, 1); + uint32_t mbs_wide = vd_get_ue(&b) + 1, map_units_high = vd_get_ue(&b) + 1; + if (b.pos > b.size * 8 || mbs_wide > 1024 || map_units_high > 1024) return -1; + uint32_t frame_mbs_only = vd_get_bits(&b, 1); + if (b.pos > b.size * 8) return -1; + *width = mbs_wide * 16; + *height = map_units_high * 16 * (2 - frame_mbs_only); + return 0; +} + +/* Finds the first SPS in an Annex B access unit; returns its size in the stream through the out parameters. */ +static int vd_stream_size_h264(const uint8_t *data, size_t size, uint32_t *width, uint32_t *height) { + for (size_t i = 0; i + 4 < size; i++) { + if (data[i] != 0 || data[i + 1] != 0 || data[i + 2] != 1 || (data[i + 3] & 0x1f) != 7) continue; + size_t start = i + 4, end = start; + while (end + 2 < size && !(data[end] == 0 && data[end + 1] == 0 && (data[end + 2] == 1 || data[end + 2] == 0))) end++; + if (end + 2 >= size) end = size; + return vd_parse_sps_h264(data + start, end - start, width, height); + } + return -1; +} + +/* The same for an H.265 SPS: the luma size in samples, rounded up to 16 as the client asks for it. */ +static int vd_parse_sps_h265(const uint8_t *rbsp, size_t size, uint32_t *width, uint32_t *height) { + uint8_t buf[512]; + size_t n = 0; + for (size_t i = 0; i < size && n < sizeof buf; i++) { + if (i >= 2 && rbsp[i] == 3 && rbsp[i - 1] == 0 && rbsp[i - 2] == 0) continue; + buf[n++] = rbsp[i]; + } + struct vd_bits b = { buf, n, 0 }; + vd_get_bits(&b, 4); + uint32_t sub_layers = vd_get_bits(&b, 3); + vd_get_bits(&b, 1); + for (unsigned i = 0; i < 88; i += 8) vd_get_bits(&b, 8); + vd_get_bits(&b, 8); + uint32_t profile_present = 0, level_present = 0; + for (uint32_t i = 0; i < sub_layers && i < 8; i++) { + profile_present |= vd_get_bits(&b, 1) << i; + level_present |= vd_get_bits(&b, 1) << i; + } + if (sub_layers > 0) for (uint32_t i = sub_layers; i < 8; i++) vd_get_bits(&b, 2); + for (uint32_t i = 0; i < sub_layers && i < 8; i++) { + if (profile_present >> i & 1) for (unsigned k = 0; k < 88; k += 8) vd_get_bits(&b, 8); + if (level_present >> i & 1) vd_get_bits(&b, 8); + } + vd_get_ue(&b); + if (vd_get_ue(&b) == 3) vd_get_bits(&b, 1); + uint32_t w = vd_get_ue(&b), h = vd_get_ue(&b); + if (b.pos > b.size * 8 || w < 16 || h < 16 || w > 16384 || h > 16384) return -1; + *width = (w + 15) & ~15u; + *height = (h + 15) & ~15u; + return 0; +} + +static int vd_stream_size_h265(const uint8_t *data, size_t size, uint32_t *width, uint32_t *height) { + for (size_t i = 0; i + 5 < size; i++) { + if (data[i] != 0 || data[i + 1] != 0 || data[i + 2] != 1 || ((data[i + 3] >> 1) & 0x3f) != 33) continue; + size_t start = i + 5, end = start; + while (end + 2 < size && !(data[end] == 0 && data[end + 1] == 0 && (data[end + 2] == 1 || data[end + 2] == 0))) end++; + if (end + 2 >= size) end = size; + return vd_parse_sps_h265(data + start, end - start, width, height); + } + return -1; +} + +/* + * A stream can change its picture size without telling the client: the host switches games or the window + * becomes fullscreen. A V4L2 decoder reports the new size through the format of its bitstream queue, which + * the client polls; the capture buffers it already allocated stay at the old size until it reconfigures. + */ +static int vd_follow_stream_size(struct vdec *v, const uint8_t *data, size_t size) { + uint32_t width, height; + int found = v->fourcc == V4L2_PIX_FMT_HEVC ? vd_stream_size_h265(data, size, &width, &height) + : vd_stream_size_h264(data, size, &width, &height); + if (found != 0) return 0; + uint32_t known_w = v->stream_w ? v->stream_w : v->width, known_h = v->stream_h ? v->stream_h : v->height; + if (width == known_w && height == known_h) return 0; + vd_log("the stream is now %ux%u, was %ux%u", width, height, known_w, known_h); + if (width <= v->cap_width && height <= v->cap_height) { + /* The client's capture buffers already hold the new size, so only the app decoder is reopened for it. */ + v->stream_w = width; + v->stream_h = height; + if (v->hw) vd_close_decoder(v); + return 1; + } + v->width = v->stream_w = width; + v->height = v->stream_h = height; + v->resizing = 1; + v->n_cap_done = 0; + return 1; +} + static int vd_qbuf(struct vdec *v, struct v4l2_buffer *b) { if (b->m.planes == NULL || b->length < 1) return -EINVAL; if (b->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) { if (b->index >= v->out_count || v->n_out_done >= VDEC_BUFFERS) return -EINVAL; uint32_t bytes = b->m.planes[0].bytesused; if (bytes > VDEC_BITSTREAM_SIZE) bytes = VDEC_BITSTREAM_SIZE; - if (v->out_on && bytes) vd_decode(v, b->index, bytes, b->timestamp); + if (v->out_on && v->bitstream && bytes) vd_follow_stream_size(v, v->bitstream + (size_t)b->index * VDEC_BITSTREAM_SIZE, bytes); + if (v->out_on && bytes && !v->resizing) vd_decode(v, b->index, bytes, b->timestamp); v->out_done[v->n_out_done++] = b->index; } else if (b->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) { if (b->index >= v->cap_count || v->cap_size == 0) return -EINVAL; @@ -652,9 +833,15 @@ static int vd_dqbuf(struct vdec *v, struct v4l2_buffer *b) { return 0; } if (b->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) return -EINVAL; - if (v->n_cap_done == 0) return -EAGAIN; - struct vd_done d = v->cap_done[0]; - memmove(v->cap_done, v->cap_done + 1, --v->n_cap_done * sizeof d); + struct vd_done d; + for (;;) { + if (v->n_cap_done == 0) return -EAGAIN; + d = v->cap_done[0]; + memmove(v->cap_done, v->cap_done + 1, --v->n_cap_done * sizeof d); + struct stat st; + struct vd_capture *c = &v->cap[d.index]; + if (c->map && c->fd >= 0 && fstat(c->fd, &st) == 0 && st.st_ino == c->ino) break; + } b->index = d.index; b->memory = V4L2_MEMORY_DMABUF; b->flags = V4L2_BUF_FLAG_DONE | V4L2_BUF_FLAG_TIMESTAMP_COPY; diff --git a/tools/tests/test_vdec_emulator.py b/tools/tests/test_vdec_emulator.py index bf16a3fc39..3fd3091542 100644 --- a/tools/tests/test_vdec_emulator.py +++ b/tools/tests/test_vdec_emulator.py @@ -113,12 +113,12 @@ int main(void) { f.fmt.pix_mp.width = 1280; f.fmt.pix_mp.height = 736; f.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12; if (call(VIDIOC_S_FMT, &f) || f.fmt.pix_mp.num_planes != 1) return 14; uint32_t bpl = f.fmt.pix_mp.plane_fmt[0].bytesperline, size = f.fmt.pix_mp.plane_fmt[0].sizeimage; - if (bpl != 1280 || size != 1280 * 736 * 3 / 2) return 15; + if (bpl != 4096 || size != 4096 * 2304 * 3 / 2) return 15; r = (struct v4l2_requestbuffers){ .count = 3, .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, .memory = V4L2_MEMORY_DMABUF }; if (call(VIDIOC_REQBUFS, &r) || r.count != 3) return 16; int out[3]; for (int i = 0; i < 3; i++) { - struct create_dumb c = { .height = 736, .width = 1280, .bpp = 16 }; + struct create_dumb c = { .height = 2304, .width = 4096, .bpp = 16 }; if (drm_ioctl(card, 0xc02064b2, &c) || !c.handle || c.size < size) return 17; struct prime_handle h = { .handle = c.handle, .flags = O_CLOEXEC }; if (drm_ioctl(card, 0xc00c642d, &h)) return 18; @@ -148,7 +148,7 @@ int main(void) { struct v4l2_buffer cb = { .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &cp }; if (call(VIDIOC_DQBUF, &cb)) return 25; unsigned char *m = mmap(NULL, size, PROT_READ, MAP_SHARED, out[cb.index], 0); - printf("%ld %u %c%c %u\n", (long)cb.timestamp.tv_usec, cb.index, m[0], m[(size_t)bpl * 736], cp.bytesused == size); + printf("%ld %u %c%c %u\n", (long)cb.timestamp.tv_usec, cb.index, m[0], m[(size_t)bpl * 2304], cp.bytesused == size); munmap(m, size); pf = (struct pollfd){ .fd = vfd, .events = 0x306 }; if (poll(&pf, 1, 0) != 1) return 26; @@ -166,7 +166,7 @@ int main(void) { size = f.fmt.pix_mp.plane_fmt[0].sizeimage; r = (struct v4l2_requestbuffers){ .count = 1, .type = types[1], .memory = V4L2_MEMORY_DMABUF }; if (call(VIDIOC_REQBUFS, &r)) return 31; - struct create_dumb big = { .height = 1088, .width = 1920, .bpp = 16 }; + struct create_dumb big = { .height = 2304, .width = 4096, .bpp = 16 }; if (drm_ioctl(card, 0xc02064b2, &big)) return 32; struct prime_handle bh = { .handle = big.handle, .flags = O_CLOEXEC }; if (drm_ioctl(card, 0xc00c642d, &bh)) return 33; @@ -183,7 +183,7 @@ int main(void) { struct v4l2_buffer db = { .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &dp }; if (call(VIDIOC_DQBUF, &db)) return 37; unsigned char *m = mmap(NULL, size, PROT_READ, MAP_SHARED, bh.fd, 0); - printf("%ld %u %c%c\n", (long)db.timestamp.tv_usec, db.index, m[0], m[(size_t)1920 * 1088]); + printf("%ld %u %c%c\n", (long)db.timestamp.tv_usec, db.index, m[0], m[(size_t)4096 * 2304]); dd_vdec_closed(vfd); return 0; } @@ -261,7 +261,7 @@ class VdecEmulatorTest(unittest.TestCase): self.assertEqual(done.stdout.split('\n')[:6], ['1 0 bu 1', '2 1 cu 1', '3 2 du 1', '4 0 eu 1', '5 1 fu 1', '6 0 zu']) self.assertEqual([c[1:6] for c in server.configs], - [(1, 1280, 720, 1280, 736), (1, 1280, 720, 1920, 1088)]) + [(1, 1280, 720, 4096, 2304), (1, 1280, 720, 4096, 2304)]) self.assertEqual([p[:3] for p in server.packets], [(1, 101, 0), (2, 102, 1), (3, 103, 2), (0, 104, 0), (1, 105, 1), (2, 50, 0)]) diff --git a/tools/tests/test_vdec_stream_size.py b/tools/tests/test_vdec_stream_size.py new file mode 100644 index 0000000000..4bf5fca3f3 --- /dev/null +++ b/tools/tests/test_vdec_stream_size.py @@ -0,0 +1,140 @@ +import subprocess +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +VDEC = ROOT / 'tools/linuxfs/preload/vdec.c' + + +class Bits: + def __init__(self): + self.bits = [] + + def u(self, value, count): + self.bits += [(value >> (count - 1 - i)) & 1 for i in range(count)] + + def ue(self, value): + value += 1 + length = value.bit_length() + self.u(0, length - 1) + self.u(value, length) + + def bytes(self): + bits = self.bits + [1] + while len(bits) % 8: + bits.append(0) + raw = bytes(int(''.join(map(str, bits[i:i + 8])), 2) for i in range(0, len(bits), 8)) + out = bytearray() + for i, byte in enumerate(raw): + if len(out) >= 2 and out[-1] == 0 and out[-2] == 0 and byte <= 3: + out.append(3) + out.append(byte) + return bytes(out) + + +def sps(width_mbs, height_units, profile=100, frame_mbs_only=1, poc_type=2): + b = Bits() + b.u(profile, 8) + b.u(0, 8) + b.u(51, 8) + b.ue(0) + if profile in (100, 110, 122, 244): + b.ue(1) + b.ue(0) + b.ue(0) + b.u(0, 1) + b.u(0, 1) + b.ue(0) + b.ue(poc_type) + if poc_type == 0: + b.ue(4) + b.ue(1) + b.u(0, 1) + b.ue(width_mbs - 1) + b.ue(height_units - 1) + b.u(frame_mbs_only, 1) + if not frame_mbs_only: + b.u(0, 1) + b.u(1, 1) + b.u(0, 1) + return b'\x00\x00\x00\x01\x67' + b.bytes() + b'\x00\x00\x00\x01\x65\x88\x84\x00' + + +def hevc_sps(width, height, sub_layers_minus1=0): + b = Bits() + b.u(0, 4) + b.u(sub_layers_minus1, 3) + b.u(1, 1) + b.u(0, 88) + b.u(93, 8) + for _ in range(sub_layers_minus1): + b.u(0, 2) + if sub_layers_minus1: + for _ in range(sub_layers_minus1, 8): + b.u(0, 2) + b.ue(0) + b.ue(1) + b.ue(width) + b.ue(height) + b.u(0, 1) + return b'\x00\x00\x00\x01\x42\x01' + b.bytes() + b'\x00\x00\x00\x01\x26\x01\xaf' + + +DRIVER = r''' +#include "vdec.c" +#include <stdio.h> + +int main(int argc, char **argv) { + FILE *f = fopen(argv[1], "rb"); + static uint8_t data[4096]; + size_t n = fread(data, 1, sizeof data, f); + uint32_t w = 0, h = 0; + int rc = argc > 2 ? vd_stream_size_h265(data, n, &w, &h) : vd_stream_size_h264(data, n, &w, &h); + printf("%d %u %u\n", rc, w, h); + return 0; +} +''' + + +class StreamSizeTest(unittest.TestCase): + def run_driver(self, data, hevc=False): + with tempfile.TemporaryDirectory() as tmp: + tmp = Path(tmp) + (tmp / 'driver.c').write_text(DRIVER) + (tmp / 'stream.bin').write_bytes(data) + exe = tmp / 'driver' + subprocess.run(['gcc', '-std=gnu11', '-DDD_VDEC_ANY_ARCH', '-I', str(VDEC.parent), '-o', str(exe), str(tmp / 'driver.c'), str(VDEC.parent / 'venc.c'), '-ldl', '-lpthread'], + check=True, capture_output=True, text=True) + return subprocess.run([str(exe), str(tmp / 'stream.bin')] + (['h265'] if hevc else []), check=True, capture_output=True, text=True).stdout.split() + + def test_reads_an_ultrawide_stream_size(self): + self.assertEqual(['0', '3440', '1440'], self.run_driver(sps(215, 90))) + + def test_reads_a_small_stream_size(self): + self.assertEqual(['0', '800', '464'], self.run_driver(sps(50, 29))) + + def test_interlaced_streams_double_the_height(self): + self.assertEqual(['0', '1920', '1088'], self.run_driver(sps(120, 34, frame_mbs_only=0))) + + def test_baseline_profile_has_no_chroma_fields(self): + self.assertEqual(['0', '1280', '720'], self.run_driver(sps(80, 45, profile=66))) + + def test_emulation_prevention_bytes_are_removed(self): + self.assertEqual(['0', '256', '256'], self.run_driver(sps(16, 16, profile=66))) + + def test_reads_an_h265_stream_size(self): + self.assertEqual(['0', '3440', '1440'], self.run_driver(hevc_sps(3440, 1440), hevc=True)) + + def test_h265_sizes_round_up_to_sixteen(self): + self.assertEqual(['0', '1920', '1088'], self.run_driver(hevc_sps(1920, 1080, sub_layers_minus1=2), hevc=True)) + + def test_a_truncated_sps_is_rejected(self): + self.assertEqual('-1', self.run_driver(b'\x00\x00\x00\x01\x67\x64\x00\x33\xac\xb4\x02\x80\x2d')[0]) + + def test_a_stream_without_an_sps_is_left_alone(self): + self.assertEqual('-1', self.run_driver(b'\x00\x00\x00\x01\x65\x88\x84\x00\x00\x01')[0]) + + +if __name__ == '__main__': + unittest.main() From 59e98afae7223f40b97f38e319836f8cd01f79ed Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:31:24 -0500 Subject: [PATCH 074/141] feat(onboarding): background first-run downloads, one setup card, no wait for Steam (#3091) * feat(onboarding): one setup card, Steam client and Proton downloaded in the background, no component toast * feat(onboarding): an optional Bluetooth controllers row in the setup card asks for the permission up front * feat(onboarding): prefetch Steam's whole package cache, one foreground notification, child-process setup while downloads run * test(steam): the cache pass keeps packages under Steam's names and is not repeated * feat(onboarding): unpack the whole Steam client ahead of time and record it as installed, downloads no longer wait for a cool device * feat(onboarding): setup progress on the Steam home page, Bluetooth asked only from the setup card, Steam unpacks its own files * fix(onboarding): review fixes: removal does not report setup progress, cancel stops the whole prefetch, cache files are verified, no resume toast * fix(onboarding): a cancelled prefetch is never a setup failure * fix(onboarding): the Steam fact is updated atomically * feat(onboarding): Bluetooth controllers moves into the Steam integration list --- .../main/java/com/droiddeck/launcher/App.kt | 1 + .../com/droiddeck/launcher/ComponentsMenu.kt | 2 +- .../droiddeck/launcher/FrontEndActivity.kt | 30 +++-- .../java/com/droiddeck/launcher/ProtonMenu.kt | 41 ++++++- .../com/droiddeck/launcher/SessionActivity.kt | 5 - .../launcher/core/SteamIntegration.kt | 10 +- .../launcher/frontend/AutoComponents.kt | 5 + .../droiddeck/launcher/session/Onboarding.kt | 102 +++++++++++++++++ .../launcher/session/ProtonExtras.kt | 52 ++++++--- .../launcher/session/SessionFiles.kt | 6 +- .../launcher/session/SessionService.kt | 1 + .../launcher/session/SteamClientPrefetch.kt | 104 ++++++++++++++++++ .../droiddeck/launcher/ui/FrontEndSetup.kt | 64 +++++++++++ .../com/droiddeck/launcher/ui/SteamHome.kt | 21 +++- .../launcher/ui/SteamIntegrationGroup.kt | 5 + app/src/main/res/values/strings.xml | 19 +++- .../droiddeck/launcher/ProtonMenuAutoTest.kt | 3 + .../launcher/session/OnboardingTest.kt | 44 ++++++++ .../session/SteamClientPrefetchTest.kt | 22 ++++ .../launcher/ui/SteamIntegrationGroupTest.kt | 6 +- .../usr/local/bin/droiddeck-steam-install | 44 +++++++- tools/tests/test_steam_install.py | 40 +++++++ 22 files changed, 590 insertions(+), 37 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/session/Onboarding.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/session/SteamClientPrefetch.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/session/OnboardingTest.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/session/SteamClientPrefetchTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt index be2deadbed..58e7e12b2c 100644 --- a/app/src/main/java/com/droiddeck/launcher/App.kt +++ b/app/src/main/java/com/droiddeck/launcher/App.kt @@ -21,6 +21,7 @@ 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) diff --git a/app/src/main/java/com/droiddeck/launcher/ComponentsMenu.kt b/app/src/main/java/com/droiddeck/launcher/ComponentsMenu.kt index e5e74f791f..79e2017962 100644 --- a/app/src/main/java/com/droiddeck/launcher/ComponentsMenu.kt +++ b/app/src/main/java/com/droiddeck/launcher/ComponentsMenu.kt @@ -79,7 +79,7 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat checkAgain = null checkComponentUpdates(again) } - if (notes.isNotEmpty()) android.widget.Toast.makeText(activity, notes.joinToString("\n"), android.widget.Toast.LENGTH_LONG).show() + if (notes.isNotEmpty()) Log.i(TAG, notes.joinToString("; ")) refreshComponents() } }, "component-updates").start() diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index af3eddf8e7..9497fe0a68 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -254,6 +254,12 @@ 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) } @@ -375,6 +381,10 @@ 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) + } } } @@ -2166,9 +2176,7 @@ 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()) ui.post { - android.widget.Toast.makeText(this, updated.joinToString("\n"), android.widget.Toast.LENGTH_LONG).show() - } + if (updated.isNotEmpty()) android.util.Log.i("ComponentUpdater", updated.joinToString("; ")) } ui.post { componentsQueueBusy = false @@ -3209,6 +3217,7 @@ 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) @@ -3430,18 +3439,24 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private fun install(release: LinuxRuntimeInstaller.Release) { com.droiddeck.launcher.runtime.RuntimeInstallService.start(this, release) - followRuntimeOperation { listener -> LinuxRuntimeInstaller.install(this, release, listener) } + followRuntimeOperation(onboarding = true) { listener -> LinuxRuntimeInstaller.install(this, release, listener) } } - private fun followRuntimeOperation(run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) { + private fun followRuntimeOperation(onboarding: Boolean = false, 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 @@ -3450,7 +3465,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() + if (ok == true && LinuxRuntime.isInstalled(this)) { protons.checkUpdates(); protons.ensureSteamClient() } } }, "runtime-operation").start() } @@ -3461,9 +3476,10 @@ 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.unfavourable(this))) return + !com.droiddeck.launcher.frontend.AutoComponents.online(this) || com.droiddeck.launcher.frontend.AutoComponents.firstRunHeldBack(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) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt b/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt index aaaa2cf34f..bb12dd31af 100644 --- a/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt +++ b/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt @@ -8,7 +8,9 @@ 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 @@ -60,10 +62,15 @@ 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 @@ -170,16 +177,46 @@ 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 || SessionState.running || LinuxRuntimeInstaller.isBusy() || + ProtonExtras.installInProgress || ProtonExtras.prefetching || SessionState.running || LinuxRuntimeInstaller.isBusy() || SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) || - !LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity) || AutoComponents.unfavourable(activity)) return + !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 if (ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size > 1) { protonBusyId = ProtonExtras.OWN protonProblem = null diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index a209bac123..dc0559251b 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -936,11 +936,6 @@ 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 diff --git a/app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt b/app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt index cd10300f4f..f284c98d36 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt @@ -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 } + enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS, BLUETOOTH } data class State( val wifi: Boolean = false, @@ -28,6 +28,7 @@ object SteamIntegration { val shortcuts: Boolean = false, val shortcutsRestricted: Boolean = false, val shortcutsTried: Boolean = false, + val bluetooth: Boolean = false, val suggested: Boolean = true, ) @@ -39,9 +40,16 @@ 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 { diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/AutoComponents.kt b/app/src/main/java/com/droiddeck/launcher/frontend/AutoComponents.kt index d6fe58ad7f..4da77ee6d7 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/AutoComponents.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/AutoComponents.kt @@ -47,6 +47,7 @@ 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 @@ -533,6 +534,10 @@ 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 diff --git a/app/src/main/java/com/droiddeck/launcher/session/Onboarding.kt b/app/src/main/java/com/droiddeck/launcher/session/Onboarding.kt new file mode 100644 index 0000000000..5a3fb555dd --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/Onboarding.kt @@ -0,0 +1,102 @@ +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 + + fun attach(context: Context) { + appContext = context.applicationContext + } + + /** 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), + ) + } + + 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 } + + /** The aggregate fraction of the whole first-run work, weighting each step by what it downloads. */ + fun overall(rows: List<Row>): Int { + val weights = mapOf(Step.RUNTIME to 60, Step.PROTON to 15, Step.STEAM to 25) + 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 + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt b/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt index 0d0e20c41d..f5a01d984d 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt @@ -23,6 +23,7 @@ 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 @@ -217,24 +218,12 @@ object ProtonExtras { @Synchronized fun install(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? { - if (installInProgress) return context.getString(R.string.pextra_busy) + if (installInProgress || prefetching) return context.getString(R.string.pextra_busy) installInProgress = true return try { installNow(context, tool, onProgress) } finally { installInProgress = false } } - 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) - } - + private fun fetchArchive(context: Context, tool: Tool, asset: Asset, archive: File, onProgress: (String, Int) -> Unit): String? { val downloading = context.getString(R.string.pextra_downloading, tool.name, asset.tag) onProgress(downloading, 0) var downloaded = false @@ -252,6 +241,41 @@ 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() diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index 1645851229..9ec5f5cba4 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -95,7 +95,11 @@ object SessionFiles { return all } - fun stage(context: Context, root: File, startsSession: Boolean = false) { + 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) { 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) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index 15d2844d34..144fad8894 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -2705,6 +2705,7 @@ 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) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SteamClientPrefetch.kt b/app/src/main/java/com/droiddeck/launcher/session/SteamClientPrefetch.kt new file mode 100644 index 0000000000..fecdc8e0b8 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/SteamClientPrefetch.kt @@ -0,0 +1,104 @@ +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) } + }, "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" + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt index 70c49a5518..c99bee629d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -51,6 +51,7 @@ 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 @@ -248,6 +249,7 @@ 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 -> @@ -1273,3 +1275,65 @@ 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 settling = 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) + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt index f9c81f4e42..2d995dda2f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt @@ -31,6 +31,7 @@ import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.PlayArrow import androidx.compose.material3.MaterialTheme 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 @@ -154,8 +155,24 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier) scrim = { if (games.size >= WALL_MIN_GAMES) WallFade() }, words = { val runtimeStatus: @Composable () -> Unit = { - 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, + 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 settling = onboardingActive.isNotEmpty() && com.droiddeck.launcher.session.Onboarding.pending(onboardingRows) + if (settling || s.busy || (s.available != null && s.available != s.installed)) { + if (settling) { + val overall = com.droiddeck.launcher.session.Onboarding.overall(onboardingRows) + Chip( + stringResource(R.string.onboarding_chip, overall, onboardingRows.firstOrNull { it.state == com.droiddeck.launcher.session.Onboarding.State.ACTIVE }?.label.orEmpty()), + ok = false, fraction = overall / 100f, + ) + } else RuntimeChip(s) + if (com.droiddeck.launcher.core.PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)) { + SecondaryButton(stringResource(R.string.onboarding_limit_while_waiting), compact = true, + modifier = Modifier.testTag("setup-while-waiting"), onClick = a.onShowPhantomGate) + } + } 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 (s.integration.suggested && signedIn && !com.droiddeck.launcher.core.PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)) IntegrationSuggestion(s.integration, { a.onSteamIntegration(null) }, a.onDismissIntegration) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SteamIntegrationGroup.kt b/app/src/main/java/com/droiddeck/launcher/ui/SteamIntegrationGroup.kt index 2827e3c7cd..e7b6a09b19 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SteamIntegrationGroup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SteamIntegrationGroup.kt @@ -23,6 +23,7 @@ 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 @@ -61,6 +62,7 @@ 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) } @@ -116,6 +118,7 @@ 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( @@ -164,6 +167,7 @@ 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) { @@ -171,6 +175,7 @@ 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 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 1b57e5b281..44bdf9c825 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -36,7 +36,7 @@ <string name="wall_settings_match" translatable="false">Match screen</string> <string name="wall_settings_speed" translatable="false">Scroll speed</string> <string-array name="loading_hints"> - <item>First run downloads Steam. This may take a few minutes.</item> + <item>DroidDeck downloads Steam in the background while you set up, so your first launch is quicker.</item> <item>Your controller shows up to Steam as a Steam Deck controller. Switch it to a Steam Controller, DualShock 4, DualSense or Xbox 360 pad in the session settings; it applies next session.</item> <item>Hold Back on your controller to open Steam\'s Quick Access menu. Hold Back for Steam shortcuts must be on in the session settings.</item> <item>Background behavior decides what happens when you leave the app: Native readies Steam for sleep, Auto pauses it, Manual waits for Resume, Never keeps it running.</item> @@ -4152,6 +4152,8 @@ <string name="integration_wifi_denied">Location denied · allow it in App info</string> <string name="integration_brightness_hint">Steam’s slider sets screen brightness</string> <string name="integration_home_hint">Home opens the Steam menu in a session</string> + <string name="integration_bluetooth">Bluetooth controllers</string> + <string name="integration_bluetooth_hint">Lets DroidDeck connect to Steam Controllers and other Bluetooth pads</string> <string name="integration_shortcuts_hint">Alt+Tab, Win key and Home button stay in the session</string> <string name="integration_shortcuts_maybe_restricted">Greyed out in Android? App info → ⋮ → Allow restricted settings</string> <string name="integration_shortcuts_install_failed">System keys didn\'t install</string> @@ -4399,4 +4401,19 @@ <string name="tabs_reset_title">Reset tabs</string> <string name="tabs_reset_hint">Steam, Desktop, Library, Downloads, Settings and Updates on the bar, the rest under More.</string> <string name="tabs_reset_body">Your tab order and what sits under More or is hidden go back to the defaults.</string> + <string name="onboarding_title">Getting DroidDeck ready</string> + <string name="onboarding_summary">%1$d%% · you can keep using the app</string> + <string name="onboarding_step_runtime">Linux runtime</string> + <string name="onboarding_step_proton">DroidDeck Proton</string> + <string name="onboarding_step_steam">Steam client</string> + <string name="onboarding_waiting">Waiting</string> + <string name="onboarding_done">Ready</string> + <string name="onboarding_failed">Will retry</string> + <string name="onboarding_steam_downloading">Downloading the Steam client</string> + <string name="onboarding_steam_downloading_mb">Downloading the Steam client (%1$d MB)</string> + <string name="onboarding_steam_failed">The Steam client download will retry</string> + <string name="onboarding_limit_reason">Android can close Steam’s helper processes. Turn that off now, while the downloads run, and Play is ready the moment they finish.</string> + <string name="onboarding_limit_action">Do it for me</string> + <string name="onboarding_limit_while_waiting">Set up while you wait</string> + <string name="onboarding_chip">Getting ready · %1$d%% · %2$s</string> </resources> diff --git a/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt b/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt index 2e06a6d8fe..4ea0a52d7f 100644 --- a/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt @@ -35,6 +35,7 @@ import java.util.concurrent.atomic.AtomicInteger class ProtonMenuAutoTest { private val online = AutoComponents.online private val constrained = AutoComponents.unfavourable + private val firstRunHeldBack = AutoComponents.firstRunHeldBack private lateinit var activity: Activity private lateinit var menu: ProtonMenu private lateinit var root: File @@ -49,6 +50,7 @@ class ProtonMenuAutoTest { } AutoComponents.online = { true } AutoComponents.unfavourable = { false } + AutoComponents.firstRunHeldBack = { false } SessionState.running = false SessionState.phase = SessionPhase.IDLE SessionState.stopRequested = false @@ -77,6 +79,7 @@ class ProtonMenuAutoTest { menu.protonPercent = -1 AutoComponents.online = online AutoComponents.unfavourable = constrained + AutoComponents.firstRunHeldBack = firstRunHeldBack SessionState.running = false SessionState.phase = SessionPhase.IDLE SessionState.stopRequested = false diff --git a/app/src/test/java/com/droiddeck/launcher/session/OnboardingTest.kt b/app/src/test/java/com/droiddeck/launcher/session/OnboardingTest.kt new file mode 100644 index 0000000000..dc2b0b5e10 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/OnboardingTest.kt @@ -0,0 +1,44 @@ +package com.droiddeck.launcher.session + +import com.droiddeck.launcher.session.Onboarding.Facts +import com.droiddeck.launcher.session.Onboarding.Progress +import com.droiddeck.launcher.session.Onboarding.State +import com.droiddeck.launcher.session.Onboarding.Step +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class OnboardingTest { + private val none = Facts(runtime = false, proton = false, steam = false) + + @Test fun everythingReadyShowsNothing() { + val rows = Onboarding.rows(emptyMap(), emptyMap(), Facts()) + assertFalse(Onboarding.pending(rows)) + assertEquals(100, Onboarding.overall(rows)) + } + + @Test fun stepsAreActiveFailedOrWaiting() { + val rows = Onboarding.rows(mapOf(Step.RUNTIME to Progress("x", 50)), mapOf(Step.PROTON to "no"), none) + assertEquals(listOf(State.ACTIVE, State.FAILED, State.WAITING), rows.map { it.state }) + assertTrue(Onboarding.pending(rows)) + } + + @Test fun anActiveStepStaysActiveWhenItsFactIsAlreadyTrue() { + val rows = Onboarding.rows(mapOf(Step.STEAM to Progress("x", -1)), emptyMap(), Facts()) + assertEquals(State.ACTIVE, rows.first { it.step == Step.STEAM }.state) + } + + @Test fun overallWeighsDownloadsBySize() { + val rows = Onboarding.rows(mapOf(Step.RUNTIME to Progress("x", 50)), emptyMap(), Facts(runtime = false)) + assertEquals(30 + 15 + 25, Onboarding.overall(rows)) + } + + @Test fun reportingClearsAPriorFailure() { + Onboarding.fail(Step.STEAM, "boom") + Onboarding.report(Step.STEAM, "again", 3) + assertTrue(Onboarding.failed.value[Step.STEAM] == null) + Onboarding.finish(Step.STEAM) + assertTrue(Onboarding.active.value[Step.STEAM] == null) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/SteamClientPrefetchTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SteamClientPrefetchTest.kt new file mode 100644 index 0000000000..7b73b81e91 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/SteamClientPrefetchTest.kt @@ -0,0 +1,22 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class SteamClientPrefetchTest { + @Test fun readsPercentAndTotalFromTheInstallersStepLine() { + val line = "== STEP 14:21:07 downloading Steam: bins_linuxarm64.zip (2/5), 120 of 480 MB" + assertEquals(25 to 480, SteamClientPrefetch.parse(line)) + } + + @Test fun aRetryNoteDoesNotChangeTheReading() { + val line = "== STEP 14:21:07 downloading Steam: x.zip (1/3), 10 of 40 MB - retrying in 5s" + assertEquals(25 to 40, SteamClientPrefetch.parse(line)) + } + + @Test fun otherLinesAreIgnored() { + assertNull(SteamClientPrefetch.parse("== STEP 14:21:07 the Steam client now follows steamdeck_stable")) + assertNull(SteamClientPrefetch.parse("downloading Steam: x (1/1), 5 of 0 MB")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SteamIntegrationGroupTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SteamIntegrationGroupTest.kt index 807b729f6d..76be29b5da 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SteamIntegrationGroupTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SteamIntegrationGroupTest.kt @@ -41,7 +41,8 @@ class SteamIntegrationGroupTest { compose.onNodeWithTag("integration-action-brightness").performClick() compose.onNodeWithTag("integration-action-home").performClick() compose.onNodeWithTag("integration-action-shortcuts").performClick() - assertEquals(listOf(Feature.BRIGHTNESS, Feature.HOME, Feature.SHORTCUTS), requests) + compose.onNodeWithTag("integration-action-bluetooth").performClick() + assertEquals(listOf(Feature.BRIGHTNESS, Feature.HOME, Feature.SHORTCUTS, Feature.BLUETOOTH), requests) } @Test fun switchesReflectAndroidGrants() { @@ -50,7 +51,8 @@ class SteamIntegrationGroupTest { compose.onNodeWithTag("integration-action-brightness").assert(stateIs("On")) compose.onNodeWithTag("integration-action-shortcuts").assert(stateIs("On")) compose.onNodeWithTag("integration-action-wifi").assert(stateIs("Off")) - compose.onNodeWithText("3 of 4 on").assertExists() + compose.onNodeWithTag("integration-action-bluetooth").assert(stateIs("Off")) + compose.onNodeWithText("3 of 5 on").assertExists() } @Test fun shortcutsDoNotNeedHome() { diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install index c58790f87a..642cc7a836 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install @@ -65,12 +65,14 @@ if [ -n "$repair" ]; then [ "$(sha1sum "$part" | cut -d' ' -f1)" = "$sum" ] || rm -f "$part" done fi +cache_only= +[ "${1:-}" = --cache ] && cache_only=1 sync= if [ "${1:-}" = --sync ]; then case "${2:-}" in publicbeta|steamdeck_publicbeta) sync=$2 ;; *) sync=$steam_channel ;; esac manifest=steam_client_${sync}_linuxarm64 fi -[ -z "$sync" ] && [ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0 +[ -z "$sync" ] && [ -z "$cache_only" ] && [ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0 work=$(mktemp -d) trap 'rm -rf "$work"' EXIT @@ -167,6 +169,46 @@ if ! fetch_manifest; then fallback=1 fetch_manifest || exit 1 fi +if [ -n "$cache_only" ]; then + cache=$steam_root/package + cached=$cache/droiddeck-cached + [ "$(cat "$cached" 2>/dev/null)" = "$version" ] && exit 0 + awk -F'"' ' + /^\t"/ && NF >= 3 && $4 == "" { block = $2 } + $2 == "file" { file[block] = $4 } + $2 == "sha2" { sha[block] = $4 } + $2 == "size" { size[block] = $4 } + $2 == "zipvz" { vz[block] = $4 } + $2 == "sha2vz" { vzsha[block] = $4 } + END { + for (b in file) { + f = file[b]; h = sha[b]; n = size[b] + 0 + if (b in vz) { f = vz[b]; h = vzsha[b]; k = split(f, bits, "_"); n = bits[k] + 0 } + print b, f, h, n + } + } + ' "$work/manifest" | sort > "$work/cache" + mkdir -p "$cache" + total=$(grep -c . "$work/cache" 2>/dev/null || echo 0) + total_bytes=$(awk '{ n += $4 } END { print n + 0 }' "$work/cache") + done_bytes=0 + i=0 + while read -r block file sum size; do + i=$((i + 1)) + progress "$cache/$file" "$block" + fetched="" + for host in "${cdn_order[@]}"; do + if fetch "$host/$file" "$cache/$file" "$size" "$sum" "$block"; then + fetched=$host + break + fi + done + [ -n "$fetched" ] || { echo "droiddeck-steam-install: $file failed on every CDN" >&2; exit 1; } + done_bytes=$((done_bytes + size)) + done < "$work/cache" + echo "$version" > "$cached" + exit 0 +fi if [ -n "$sync" ]; then installed=$(awk -F'"' '$2 == "version" { print $4; exit }' "$steam_root/package/$manifest.manifest" 2>/dev/null || true) if [ -x "$steam_root/steamrtarm64/steam" ] && [ "$installed" = "$version" ]; then diff --git a/tools/tests/test_steam_install.py b/tools/tests/test_steam_install.py index f888b7ed13..4af6d09dd1 100644 --- a/tools/tests/test_steam_install.py +++ b/tools/tests/test_steam_install.py @@ -314,6 +314,46 @@ done(28 if end < len(data) else 0) def download(self): return self.steam / 'package/droiddeck-download' + def cache_manifest(self): + plain = b'plain-package' + packed = b'packed-package' + (self.cdn / 'a.zip.1111').write_bytes(plain) + (self.cdn / 'b.zip.vz.2222_14').write_bytes(packed) + (self.cdn / 'steam_client_steamdeck_publicbeta_linuxarm64').write_text( + '"linuxarm64"\n{\n\t"version" "123456"\n' + '\t"a_all"\n\t{\n' + f'\t\t"file" "a.zip.1111"\n\t\t"size" "{len(plain)}"\n\t\t"sha2" "{hashlib.sha256(plain).hexdigest()}"\n' + '\t}\n' + '\t"b_all"\n\t{\n' + '\t\t"file" "b.zip.9999"\n\t\t"size" "99"\n\t\t"sha2" "00"\n' + '\t\t"zipvz" "b.zip.vz.2222_14"\n' + f'\t\t"sha2vz" "{hashlib.sha256(packed).hexdigest()}"\n' + '\t}\n}\n') + + def test_the_cache_pass_keeps_every_package_under_the_names_steam_looks_for(self): + self.cache_manifest() + result = self.install(None, '--cache') + self.assertEqual(0, result.returncode, result.stderr) + package = self.steam / 'package' + self.assertEqual(b'plain-package', (package / 'a.zip.1111').read_bytes()) + self.assertEqual(b'packed-package', (package / 'b.zip.vz.2222_14').read_bytes()) + self.assertFalse((package / 'b.zip.9999').exists()) + self.assertEqual('123456\n', (package / 'droiddeck-cached').read_text()) + + def test_the_cache_pass_is_not_repeated_for_the_same_client_version(self): + self.cache_manifest() + self.assertEqual(0, self.install(None, '--cache').returncode) + requests = len(self.requests.read_text().splitlines()) + self.assertEqual(0, self.install(None, '--cache').returncode) + self.assertEqual(requests + 1, len(self.requests.read_text().splitlines())) + + def test_a_cached_package_is_not_fetched_again(self): + self.cache_manifest() + (self.steam / 'package').mkdir(parents=True) + (self.steam / 'package/a.zip.1111').write_bytes(b'plain-package') + self.assertEqual(0, self.install(None, '--cache').returncode) + self.assertNotIn('a.zip.1111', self.requests.read_text()) + def test_progress_is_counted_in_megabytes_across_parts(self): self.two_parts() result = self.install() From ec31c9e2b6e37c96890e1d9865061f29f76e232d Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Mon, 23 Nov 2026 18:36:48 -0500 Subject: [PATCH 075/141] fix(nativeguest): load glibc locales and iconv modules without proot (#3096) * fix(nativeguest): load glibc locales and iconv modules without proot glibc opens its locale files and gconv modules with its own internal open(), which the hook never sees, so every program ran in the C locale and iconv knew only built-in charsets: Qt warned it could not switch to UTF-8, setlocale() failed for C.UTF-8 and the app's language, and iconv -t latin1 was unsupported. The hook now points LOCPATH and GCONV_PATH at the rootfs; droiddeck-fex keeps x86 guests on their own gconv modules. * test(nativeguest): the locale default test ignores the developer's own paths --- tools/linuxfs/overlay/usr/local/bin/droiddeck-fex | 2 ++ tools/nativeguest/hook/setup.c | 13 +++++++++++++ tools/tests/test_droiddeck_fex.py | 6 ++++++ tools/tests/test_native_hook_mounts.py | 13 ++++++++++++- 4 files changed, 33 insertions(+), 1 deletion(-) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex index e8edb67d5e..df14d93f7e 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex @@ -670,6 +670,8 @@ def guest_environment(fex, env): result.setdefault("FEX_SILENTLOG", "0") result.setdefault("FEX_OUTPUTLOG", "stderr") result.pop("GLIBC_TUNABLES", None) + if "aarch64" in result.get("GCONV_PATH", ""): + result["GCONV_PATH"] = "" result.setdefault("GC_DISABLE_INCREMENTAL", "1") if fex["portable"]: result["FEX_PORTABLE"] = "1" diff --git a/tools/nativeguest/hook/setup.c b/tools/nativeguest/hook/setup.c index 24f8a81317..bce43c5ad4 100644 --- a/tools/nativeguest/hook/setup.c +++ b/tools/nativeguest/hook/setup.c @@ -84,6 +84,19 @@ static void init_ddnatv_hook(void) { setenv("TZDIR", tzdir_buf, 0); } + const char *curr_locpath = getenv("LOCPATH"); + if (!curr_locpath || curr_locpath[0] == '\0') { + char locpath_buf[PATH_MAX]; + snprintf(locpath_buf, sizeof(locpath_buf), "%s/usr/lib/locale", g_ddnatv_root); + setenv("LOCPATH", locpath_buf, 1); + } + + if (!getenv("GCONV_PATH")) { + char gconv_buf[PATH_MAX]; + snprintf(gconv_buf, sizeof(gconv_buf), "%s/usr/lib/aarch64-linux-gnu/gconv", g_ddnatv_root); + setenv("GCONV_PATH", gconv_buf, 0); + } + const char *curr_cert = getenv("SSL_CERT_FILE"); if (!curr_cert || curr_cert[0] == '\0' || strcmp(curr_cert, "/etc/ssl/certs/ca-certificates.crt") == 0) { char cert_buf[PATH_MAX]; diff --git a/tools/tests/test_droiddeck_fex.py b/tools/tests/test_droiddeck_fex.py index 825cd8b8d4..22e5017d2d 100644 --- a/tools/tests/test_droiddeck_fex.py +++ b/tools/tests/test_droiddeck_fex.py @@ -1055,6 +1055,12 @@ class LaunchTest(FexTestCase): guest = FEX["guest_environment"]({"portable": True}, {"GLIBC_TUNABLES": "glibc.pthread.rseq=0"}) self.assertNotIn("GLIBC_TUNABLES", guest) + def test_host_iconv_modules_stay_on_the_host(self): + guest = FEX["guest_environment"]({"portable": True}, {"GCONV_PATH": "/r/usr/lib/aarch64-linux-gnu/gconv"}) + self.assertEqual(guest["GCONV_PATH"], "") + own = FEX["guest_environment"]({"portable": True}, {"GCONV_PATH": "/opt/gconv"}) + self.assertEqual(own["GCONV_PATH"], "/opt/gconv") + def test_proton_runs_in_the_runtime_its_manifest_requires(self): self.fex_tool() self.runtime() diff --git a/tools/tests/test_native_hook_mounts.py b/tools/tests/test_native_hook_mounts.py index ff46a0fa18..eaed2dded7 100644 --- a/tools/tests/test_native_hook_mounts.py +++ b/tools/tests/test_native_hook_mounts.py @@ -12,6 +12,7 @@ PROBE = r""" #include <dirent.h> #include <fcntl.h> #include <stdio.h> +#include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> @@ -20,6 +21,11 @@ int main(int argc, char **argv) { char cwd[4096]; for (int i = 1; i < argc; i++) { struct stat st; + if (strncmp(argv[i], "env:", 4) == 0) { + const char *value = getenv(argv[i] + 4); + printf("%s\t%s\n", argv[i], value ? value : "-"); + continue; + } if (strncmp(argv[i], "cd:", 3) == 0) { int ok = chdir(argv[i] + 3) == 0 && getcwd(cwd, sizeof(cwd)) != NULL; printf("%s\t%s\n", argv[i], ok ? cwd : "-"); @@ -120,7 +126,7 @@ class NativeHookMountTest(unittest.TestCase): def run_probe(self, *args): binds = f"{self.library}:/mnt/library|{self.private}:/mnt/private|{self.eqlen_src}:{self.eqlen_dst}" hook_env = {"DDNATV_ROOT": str(self.root), "DDNATV_BINDS": binds, "LD_PRELOAD": str(self.hook)} - env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"} + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "LOCPATH", "GCONV_PATH")} if self.prefix: cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] else: @@ -147,6 +153,11 @@ class NativeHookMountTest(unittest.TestCase): path = f"/pfx/guest/dosdevices/z:{GAME}/game.txt" self.assertEqual(self.run_probe(path)[path], ["1", "library"]) + def test_glibc_locale_and_iconv_data_come_from_the_rootfs(self): + result = self.run_probe("env:LOCPATH", "env:GCONV_PATH") + self.assertEqual(result["env:LOCPATH"], [f"{self.root}/usr/lib/locale"]) + self.assertEqual(result["env:GCONV_PATH"], [f"{self.root}/usr/lib/aarch64-linux-gnu/gconv"]) + def test_rootfs_paths_outside_mounts_are_unchanged(self): paths = ["/pfx/native/dosdevices/z:/etc/hostname", f"{self.root}/etc/hostname", "/etc/hostname"] result = self.run_probe(*paths) From ba3f840b8d22af43d9f3f9ac988a23fcbc39c396 Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Mon, 23 Nov 2026 18:48:52 -0500 Subject: [PATCH 076/141] fix(fex): x86 programs reach Unix sockets inside the rootfs (#3097) * fix(fex): x86 programs reach Unix sockets inside the rootfs * fix(nativeguest): bind uses only the socket path length the caller gives --- .../0013-path-syscalls-through-libc.patch | 16 +++++++++- tools/nativeguest/hook/privileged.c | 10 +++++++ tools/nativeguest/hook/sockets.c | 16 ++++++---- tools/tests/test_native_hook_path_syscalls.py | 30 +++++++++++++++++-- 4 files changed, 64 insertions(+), 8 deletions(-) diff --git a/tools/fex/patches/0013-path-syscalls-through-libc.patch b/tools/fex/patches/0013-path-syscalls-through-libc.patch index 122f7654d2..1aa641b311 100644 --- a/tools/fex/patches/0013-path-syscalls-through-libc.patch +++ b/tools/fex/patches/0013-path-syscalls-through-libc.patch @@ -1,5 +1,5 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp -index 11ff163..085a621 100644 +index 11ff163..4c3be85 100644 --- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp +++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp @@ -209,6 +209,41 @@ uint64_t SyscallPassthrough7(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, @@ -44,6 +44,20 @@ index 11ff163..085a621 100644 static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { REGISTER_SYSCALL_IMPL(read, SyscallPassthrough3<SYSCALL_DEF(read)>); REGISTER_SYSCALL_IMPL(write, SyscallPassthrough3<SYSCALL_DEF(write)>); +@@ -220,11 +255,11 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(shmctl, SyscallPassthrough3<SYSCALL_DEF(shmctl)>); + REGISTER_SYSCALL_IMPL(getpid, SyscallPassthrough0<SYSCALL_DEF(getpid)>); + REGISTER_SYSCALL_IMPL(socket, SyscallPassthrough3<SYSCALL_DEF(socket)>); +- REGISTER_SYSCALL_IMPL(connect, SyscallPassthrough3<SYSCALL_DEF(connect)>); ++ REGISTER_SYSCALL_IMPL(connect, SyscallPathPassthrough3<SYSCALL_DEF(connect)>); + REGISTER_SYSCALL_IMPL(sendto, SyscallPassthrough6<SYSCALL_DEF(sendto)>); + REGISTER_SYSCALL_IMPL(recvfrom, SyscallPassthrough6<SYSCALL_DEF(recvfrom)>); + REGISTER_SYSCALL_IMPL(shutdown, SyscallPassthrough2<SYSCALL_DEF(shutdown)>); +- REGISTER_SYSCALL_IMPL(bind, SyscallPassthrough3<SYSCALL_DEF(bind)>); ++ REGISTER_SYSCALL_IMPL(bind, SyscallPathPassthrough3<SYSCALL_DEF(bind)>); + REGISTER_SYSCALL_IMPL(listen, SyscallPassthrough2<SYSCALL_DEF(listen)>); + REGISTER_SYSCALL_IMPL(getsockname, SyscallPassthrough3<SYSCALL_DEF(getsockname)>); + REGISTER_SYSCALL_IMPL(getpeername, SyscallPassthrough3<SYSCALL_DEF(getpeername)>); @@ -238,9 +273,9 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { REGISTER_SYSCALL_IMPL(flock, SyscallPassthrough2<SYSCALL_DEF(flock)>); REGISTER_SYSCALL_IMPL(fsync, SyscallPassthrough1<SYSCALL_DEF(fsync)>); diff --git a/tools/nativeguest/hook/privileged.c b/tools/nativeguest/hook/privileged.c index 09a1074b86..d5639b450e 100644 --- a/tools/nativeguest/hook/privileged.c +++ b/tools/nativeguest/hook/privileged.c @@ -708,6 +708,16 @@ long syscall(long number, ...) { return (long)utimensat((int)arg1, (const char *)arg2, (const struct timespec *)arg3, (int)arg4); } #endif +#if defined(__NR_connect) + if (number == __NR_connect) { + return (long)connect((int)arg1, (const struct sockaddr *)arg2, (socklen_t)arg3); + } +#endif +#if defined(__NR_bind) + if (number == __NR_bind) { + return (long)bind((int)arg1, (const struct sockaddr *)arg2, (socklen_t)arg3); + } +#endif #if defined(__NR_truncate) if (number == __NR_truncate) { return (long)truncate((const char *)arg1, (off_t)arg2); diff --git a/tools/nativeguest/hook/sockets.c b/tools/nativeguest/hook/sockets.c index 2903505f9b..b4b12f8005 100644 --- a/tools/nativeguest/hook/sockets.c +++ b/tools/nativeguest/hook/sockets.c @@ -94,6 +94,13 @@ int listen(int sockfd, int backlog) { return ret; } +static void copy_unix_path(const struct sockaddr_un *sun, socklen_t addrlen, char *out) { + size_t max = addrlen - offsetof(struct sockaddr_un, sun_path); + if (max > sizeof(sun->sun_path)) max = sizeof(sun->sun_path); + memcpy(out, sun->sun_path, max); + out[max] = '\0'; +} + int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen) { static int (*orig_bind)(int, const struct sockaddr *, socklen_t) = NULL; if (!orig_bind) orig_bind = (int (*)(int, const struct sockaddr *, socklen_t))dlsym(RTLD_NEXT, "bind"); @@ -104,7 +111,9 @@ int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen) { struct sockaddr_un mod_sun; memset(&mod_sun, 0, sizeof(mod_sun)); mod_sun.sun_family = AF_UNIX; - rewrite_unix_socket_path(sun->sun_path, mod_sun.sun_path, sizeof(mod_sun.sun_path)); + char guest[sizeof(sun->sun_path) + 1]; + copy_unix_path(sun, addrlen, guest); + rewrite_unix_socket_path(guest, mod_sun.sun_path, sizeof(mod_sun.sun_path)); return orig_bind ? orig_bind(sockfd, (struct sockaddr *)&mod_sun, sizeof(mod_sun)) : -1; } } @@ -133,10 +142,7 @@ int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen) { memset(&mod_sun, 0, sizeof(mod_sun)); mod_sun.sun_family = AF_UNIX; char guest[sizeof(sun->sun_path) + 1]; - size_t max = addrlen - offsetof(struct sockaddr_un, sun_path); - if (max > sizeof(sun->sun_path)) max = sizeof(sun->sun_path); - memcpy(guest, sun->sun_path, max); - guest[max] = '\0'; + copy_unix_path(sun, addrlen, guest); char followed[PATH_MAX]; const char *path = guest[0] == '/' ? follow_guest_link(guest, followed, sizeof(followed)) : guest; rewrite_unix_socket_path(path, mod_sun.sun_path, sizeof(mod_sun.sun_path)); diff --git a/tools/tests/test_native_hook_path_syscalls.py b/tools/tests/test_native_hook_path_syscalls.py index ab69fc3c83..be0967cbb0 100644 --- a/tools/tests/test_native_hook_path_syscalls.py +++ b/tools/tests/test_native_hook_path_syscalls.py @@ -12,9 +12,12 @@ PROBE = r""" #define _GNU_SOURCE #include <fcntl.h> #include <limits.h> +#include <stddef.h> #include <stdio.h> #include <string.h> +#include <sys/socket.h> #include <sys/syscall.h> +#include <sys/un.h> #include <unistd.h> static void show(const char *name, long ret) { printf("%s\t%d\n", name, ret >= 0); } @@ -40,6 +43,29 @@ int main(int argc, char **argv) { snprintf(q, sizeof(q), "%s/made/link", dir); show("symlinkat", syscall(SYS_symlinkat, "file", AT_FDCWD, q)); show("unlinkat", syscall(SYS_unlinkat, AT_FDCWD, q, 0)); + snprintf(q, sizeof(q), "%s/made/sock", dir); + struct sockaddr_un addr = {.sun_family = AF_UNIX}, extra = {.sun_family = AF_UNIX}; + size_t len = strlen(q); + int fits = len + sizeof("-extra") <= sizeof(addr.sun_path); + if (fits) { + memcpy(addr.sun_path, q, len); + memcpy(extra.sun_path, q, len); + memcpy(extra.sun_path + len, "-extra", sizeof("-extra")); + } + int server = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0), client = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + show("bind", fits ? syscall(SYS_bind, server, &addr, sizeof(addr)) : -1); + listen(server, 1); + show("connect", fits ? syscall(SYS_connect, client, &addr, sizeof(addr)) : -1); + close(client); + close(server); + syscall(SYS_unlinkat, AT_FDCWD, q, 0); + server = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0), client = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + show("bind-length", fits ? syscall(SYS_bind, server, &extra, offsetof(struct sockaddr_un, sun_path) + len) : -1); + listen(server, 1); + show("connect-length", fits ? syscall(SYS_connect, client, &addr, sizeof(addr)) : -1); + close(client); + close(server); + syscall(SYS_unlinkat, AT_FDCWD, q, 0); snprintf(q, sizeof(q), "%s/made", dir); show("chdir", syscall(SYS_chdir, q)); show("cwd", getcwd(cwd, sizeof(cwd)) && strstr(cwd, "/made") ? 0 : -1); @@ -88,7 +114,7 @@ __attribute__((constructor)) static void early(void) { free(malloc(1)); } """ CALLS = ("mkdirat", "openat", "truncate", "fchmodat", "utimensat", "futimens", "renameat", "renameat2", "symlinkat", "unlinkat", - "chdir", "cwd", "unlinkat-file", "unlinkat-dir") + "bind", "connect", "bind-length", "connect-length", "chdir", "cwd", "unlinkat-file", "unlinkat-dir") class NativeHookPathSyscallsTest(unittest.TestCase): @@ -97,7 +123,7 @@ class NativeHookPathSyscallsTest(unittest.TestCase): cls.cc, cls.prefix = runner() if cls.cc is None: raise unittest.SkipTest("no aarch64 compiler and runner") - cls.tmp = tempfile.TemporaryDirectory() + cls.tmp = tempfile.TemporaryDirectory(dir="/tmp") tmp = Path(cls.tmp.name) cls.hook = tmp / "hook.so" subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) From f5396606505a38d90236a10fb33392d936a9ea50 Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Mon, 23 Nov 2026 18:55:37 -0500 Subject: [PATCH 077/141] fix(nativeguest): keep parent lookups inside the guest root (#3094) * fix(nativeguest): keep the parent of the guest root inside the rootfs * fix(nativeguest): keep every .. walk inside the guest root and its mounts Absolute paths that climb above /, relative paths from the working directory or any descriptor, and paths that climb out of a mount were resolved by the kernel from the rootfs folder or the mount's real place, so /.., chdir("..") from / and fstatat(fd, "../..") listed the app's files folder. The walk is now resolved in the guest's view first. * fix(nativeguest): .. from a linked mount ancestor follows the real directory --------- Co-authored-by: maxjivi05 <6025299+maxjivi05@users.noreply.github.com> --- tools/nativeguest/hook/paths.c | 80 +++++++++++++++++++------- tools/nativeguest/hook/setup.c | 7 ++- tools/tests/test_native_hook_mounts.py | 51 +++++++++++++++- 3 files changed, 114 insertions(+), 24 deletions(-) diff --git a/tools/nativeguest/hook/paths.c b/tools/nativeguest/hook/paths.c index fc6c49e507..fcfe12cc43 100644 --- a/tools/nativeguest/hook/paths.c +++ b/tools/nativeguest/hook/paths.c @@ -188,6 +188,25 @@ static __thread int t_bind_link_depth = 0; static void normalize_path(char *path); +static int climbs_past_root(const char *dir, const char *target) { + long depth = 0; + for (const char *p = dir; *p; p++) + if (*p != '/' && (p == dir || p[-1] == '/')) depth++; + for (const char *p = target; *p;) { + while (*p == '/') p++; + const char *end = p; + while (*end && *end != '/') end++; + size_t len = (size_t)(end - p); + if (len == 2 && p[0] == '.' && p[1] == '.') { + if (--depth < 0) return 1; + } else if (len > 0 && !(len == 1 && p[0] == '.')) { + depth++; + } + p = end; + } + return 0; +} + #if defined(__aarch64__) static long raw_link_dir(const char *link, char *out, size_t size) { const char *slash = strrchr(link, '/'); @@ -215,25 +234,6 @@ static long raw_link_dir(const char *link, char *out, size_t size) { return n; } -static int climbs_past_root(const char *dir, const char *target) { - long depth = 0; - for (const char *p = dir; *p; p++) - if (*p != '/' && (p == dir || p[-1] == '/')) depth++; - for (const char *p = target; *p;) { - while (*p == '/') p++; - const char *end = p; - while (*end && *end != '/') end++; - size_t len = (size_t)(end - p); - if (len == 2 && p[0] == '.' && p[1] == '.') { - if (--depth < 0) return 1; - } else if (len > 0 && !(len == 1 && p[0] == '.')) { - depth++; - } - p = end; - } - return 0; -} - static size_t guest_path_of_mount_source(char *buf, size_t len, size_t cap, int *converted); static const char *guest_path_of_host_dir(const char *dir, char *out, size_t size) { @@ -335,6 +335,15 @@ static const char *resolve_drive_links(const char *host, char *buffer, size_t bu // Maps an absolute Ubuntu path into the rootfs. Returns `path` (possibly advanced past // redundant leading "/" and "/." components) when it needs no change, else `buffer`. +static const char *rewrite_normalized_in_root(const char *path, char *buffer, size_t bufsize) { + char normalized[PATH_MAX]; + ddnatv_copy_cstr(normalized, sizeof(normalized), path); + normalize_path(normalized); + const char *mapped = rewrite_path_in_root(normalized, buffer, bufsize); + if (mapped != buffer) ddnatv_copy_cstr(buffer, bufsize, mapped); + return buffer; +} + static const char *rewrite_path_in_root(const char *path, char *buffer, size_t bufsize) { if (!path) return NULL; if (path[0] != '/' || g_ddnatv_root_len == 0) return path; @@ -354,6 +363,8 @@ static const char *rewrite_path_in_root(const char *path, char *buffer, size_t b } } + if (strstr(path, "/..") && climbs_past_root("", path)) return rewrite_normalized_in_root(path, buffer, bufsize); + // Root directory if (path[1] == '\0') { ddnatv_append(buffer, bufsize, 0, g_ddnatv_root, g_ddnatv_root_len); @@ -364,6 +375,8 @@ static const char *rewrite_path_in_root(const char *path, char *buffer, size_t b const struct ddnatv_bind *b = &g_binds[i]; if (path[1] == b->dst[1] && is_path_prefix(path, b->dst, b->dst_len)) { if (b->identity) return path; + if (strstr(path + b->dst_len, "/..") && climbs_past_root("", path + b->dst_len)) + return rewrite_normalized_in_root(path, buffer, bufsize); size_t n = ddnatv_append(buffer, bufsize, 0, b->src, b->src_len); ddnatv_append(buffer, bufsize, n, path + b->dst_len, strlen(path + b->dst_len)); return resolve_bind_links(buffer, b->src_len, buffer, bufsize); @@ -806,10 +819,36 @@ static void ddnatv_build_at_dirs(void) { } } +#if defined(__aarch64__) +static const char *map_parent_walk(int dirfd, const char *rel, char *buf, size_t size) { + char link[32], host[PATH_MAX], dir_buf[PATH_MAX], guest[PATH_MAX]; + if (dirfd == AT_FDCWD) ddnatv_copy_cstr(link, sizeof(link), "/proc/self/cwd"); + else snprintf(link, sizeof(link), "/proc/self/fd/%d", dirfd); + long n = raw_readlinkat(AT_FDCWD, link, host, sizeof(host) - 1); + if (n <= 0 || host[0] != '/') return NULL; + host[n] = '\0'; + const char *dir = guest_path_of_host_dir(host, dir_buf, sizeof(dir_buf)); + if (!dir || strcmp(dir, host) == 0) return NULL; + if (get_rootfs_subpath(host) && !climbs_past_root(dir, rel)) return NULL; + size_t used = ddnatv_append(guest, sizeof(guest), 0, dir, strlen(dir)); + used = ddnatv_append(guest, sizeof(guest), used, "/", 1); + used = ddnatv_append(guest, sizeof(guest), used, rel, strlen(rel)); + if (used + 1 >= sizeof(guest)) return NULL; + const char *mapped = rewrite_path_in_root(guest, buf, size); + if (mapped != buf) ddnatv_copy_cstr(buf, size, mapped); + return buf; +} +#endif + // The absolute host path for `rel` given relative to `dirfd`, or NULL when the call needs no change. static const char *map_at(int dirfd, const char *rel, char *buf, size_t size) { #if defined(__aarch64__) - if (dirfd == AT_FDCWD || !rel || rel[0] == '\0' || rel[0] == '/' || g_nbinds == 0) return NULL; + if (!rel || rel[0] == '\0' || rel[0] == '/') return NULL; + if (strstr(rel, "..")) { + const char *walked = map_parent_walk(dirfd, rel, buf, size); + if (walked || dirfd == AT_FDCWD) return walked; + } + if (dirfd == AT_FDCWD || g_nbinds == 0) return NULL; pthread_once(&g_at_once, ddnatv_build_at_dirs); if (g_n_at_dirs == 0) return NULL; struct stat st; @@ -818,6 +857,7 @@ static const char *map_at(int dirfd, const char *rel, char *buf, size_t size) { if (g_at_dirs[i].ino != (unsigned long)st.st_ino || g_at_dirs[i].dev != (unsigned long)st.st_dev) continue; char guest[PATH_MAX]; const char *base = g_at_dirs[i].guest; + if (base[1] && climbs_past_root(base, rel)) return NULL; size_t used = ddnatv_append(guest, sizeof(guest), 0, base, strlen(base)); if (used > 1) used = ddnatv_append(guest, sizeof(guest), used, "/", 1); ddnatv_append(guest, sizeof(guest), used, rel, strlen(rel)); diff --git a/tools/nativeguest/hook/setup.c b/tools/nativeguest/hook/setup.c index bce43c5ad4..e0587d0b4f 100644 --- a/tools/nativeguest/hook/setup.c +++ b/tools/nativeguest/hook/setup.c @@ -363,8 +363,11 @@ static ssize_t handle_proc_exe_at(int dirfd, const char *pathname, char *buf, si static const char *rewrite_path(const char *path, char *buffer, size_t bufsize) { if (!path) return NULL; // Relative paths must NEVER be rewritten to rootfs root - if (path[0] != '/') return path; init_ddnatv_hook(); + if (path[0] != '/') { + const char *walked = map_at(AT_FDCWD, path, buffer, bufsize); + return walked ? walked : path; + } return rewrite_path_in_root(path, buffer, bufsize); } @@ -374,7 +377,7 @@ static const char *rewrite_path(const char *path, char *buffer, size_t bufsize) // followed in the guest's view first. The rootfs's own links were made relative already. static const char *rewrite_path_follow(const char *path, char *buffer, size_t bufsize) { if (!path) return NULL; - if (path[0] != '/') return path; + if (path[0] != '/') return rewrite_path(path, buffer, bufsize); init_ddnatv_hook(); int moved = 0; for (int i = 0; i < g_nbinds; i++) { diff --git a/tools/tests/test_native_hook_mounts.py b/tools/tests/test_native_hook_mounts.py index eaed2dded7..9f82bb0149 100644 --- a/tools/tests/test_native_hook_mounts.py +++ b/tools/tests/test_native_hook_mounts.py @@ -26,6 +26,19 @@ int main(int argc, char **argv) { printf("%s\t%s\n", argv[i], value ? value : "-"); continue; } + if (strncmp(argv[i], "parent:", 7) == 0) { + char dir[4096]; + snprintf(dir, sizeof(dir), "%s", argv[i] + 7); + char *rel = strchr(dir, '|'), *want = NULL; + if (rel) *rel++ = 0; + if (rel && (want = strchr(rel, '|'))) *want++ = 0; + int fd = open(dir, O_RDONLY | O_DIRECTORY); + struct stat expected; + int ok = fd >= 0 && fstatat(fd, rel ? rel : "..", &st, 0) == 0 && stat(want ? want : "/", &expected) == 0; + printf("%s\t%d\n", argv[i], ok && st.st_dev == expected.st_dev && st.st_ino == expected.st_ino); + if (fd >= 0) close(fd); + continue; + } if (strncmp(argv[i], "cd:", 3) == 0) { int ok = chdir(argv[i] + 3) == 0 && getcwd(cwd, sizeof(cwd)) != NULL; printf("%s\t%s\n", argv[i], ok ? cwd : "-"); @@ -82,6 +95,8 @@ class NativeHookMountTest(unittest.TestCase): cls.root = tmp / "root" cls.library = tmp / "storage/PC GAMES" (cls.root / "etc").mkdir(parents=True) + (cls.root / "deep/er/est").mkdir(parents=True) + (cls.root / "linked").symlink_to("deep/er/est") (cls.root / "etc/hostname").write_text("rootfs") (cls.root / "mnt/library/Some Game").mkdir(parents=True) (cls.root / "mnt/library/Some Game/game.txt").write_text("mount point") @@ -123,8 +138,9 @@ class NativeHookMountTest(unittest.TestCase): def tearDownClass(cls): cls.tmp.cleanup() - def run_probe(self, *args): - binds = f"{self.library}:/mnt/library|{self.private}:/mnt/private|{self.eqlen_src}:{self.eqlen_dst}" + def run_probe(self, *args, binds=None): + if binds is None: + binds = f"{self.library}:/mnt/library|{self.private}:/mnt/private|{self.eqlen_src}:{self.eqlen_dst}" hook_env = {"DDNATV_ROOT": str(self.root), "DDNATV_BINDS": binds, "LD_PRELOAD": str(self.hook)} env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "LOCPATH", "GCONV_PATH")} if self.prefix: @@ -158,6 +174,37 @@ class NativeHookMountTest(unittest.TestCase): self.assertEqual(result["env:LOCPATH"], [f"{self.root}/usr/lib/locale"]) self.assertEqual(result["env:GCONV_PATH"], [f"{self.root}/usr/lib/aarch64-linux-gnu/gconv"]) + def test_parent_of_root_stays_at_root(self): + self.assertEqual(self.run_probe("parent:/")["parent:/"], ["1"]) + + def test_parent_of_root_without_mounts_stays_at_root(self): + self.assertEqual(self.run_probe("parent:/", binds="")["parent:/"], ["1"]) + + def test_parent_of_mount_ancestor_is_guest_root(self): + self.assertEqual(self.run_probe("parent:/mnt")["parent:/mnt"], ["1"]) + + def test_parent_walks_from_any_directory_stay_at_root(self): + cases = ["parent:/etc|../..", "parent:/mnt/library|../../..", "parent:/|../etc/.."] + self.assertEqual(self.run_probe(*cases), {case: ["1"] for case in cases}) + + def test_parent_walk_from_a_linked_mount_ancestor_follows_the_real_directory(self): + binds = f"{self.library}:/linked/library" + case = "parent:/linked|../..|/deep" + self.assertEqual(self.run_probe(case, binds=binds)[case], ["1"]) + + def test_absolute_paths_above_root_stay_at_root(self): + result = self.run_probe("cd:/..", "cd:/etc/../..", "/../etc/hostname") + self.assertEqual(result["cd:/.."], [str(self.root)]) + self.assertEqual(result["cd:/etc/../.."], [str(self.root)]) + self.assertEqual(result["/../etc/hostname"], ["1", "rootfs"]) + + def test_relative_parent_of_cwd_stays_in_guest(self): + result = self.run_probe("cd:/", "cd:..", "cd:./../..", "../etc/hostname", f"cd:{GAME}", "cd:../..") + self.assertEqual(result["cd:.."], [str(self.root)]) + self.assertEqual(result["cd:./../.."], [str(self.root)]) + self.assertEqual(result["cd:../.."], [str(self.root / "mnt")]) + self.assertEqual(result["../etc/hostname"], ["1", "rootfs"]) + def test_rootfs_paths_outside_mounts_are_unchanged(self): paths = ["/pfx/native/dosdevices/z:/etc/hostname", f"{self.root}/etc/hostname", "/etc/hostname"] result = self.run_probe(*paths) From 8576652fb61c7f76be4895fdbbb12a497a0c4a6c Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Mon, 23 Nov 2026 19:09:23 -0500 Subject: [PATCH 078/141] fix(fex): thunk libOpenGL with the host GL library (#3099) * fix(fex): x86 programs that use libOpenGL load again * fix(fex): thunk libOpenGL with the host GL library --- .../0015-gl-thunk-overlays-libopengl.patch | 15 ++++++++++ .../overlay/usr/local/bin/droiddeck-fex | 2 +- tools/tests/test_droiddeck_fex.py | 15 ++++++++++ tools/tests/test_fex_gl_thunk_overlay.py | 29 +++++++++++++++++++ 4 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 tools/fex/patches/0015-gl-thunk-overlays-libopengl.patch create mode 100644 tools/tests/test_fex_gl_thunk_overlay.py diff --git a/tools/fex/patches/0015-gl-thunk-overlays-libopengl.patch b/tools/fex/patches/0015-gl-thunk-overlays-libopengl.patch new file mode 100644 index 0000000000..b1557d3c39 --- /dev/null +++ b/tools/fex/patches/0015-gl-thunk-overlays-libopengl.patch @@ -0,0 +1,15 @@ +diff --git a/Data/ThunksDB.json b/Data/ThunksDB.json +index d52ff04..886379a 100644 +--- a/Data/ThunksDB.json ++++ b/Data/ThunksDB.json +@@ -6,7 +6,9 @@ + "@PREFIX_LIB@/libGL.so", + "@PREFIX_LIB@/libGL.so.1", + "@PREFIX_LIB@/libGL.so.1.2.0", +- "@PREFIX_LIB@/libGL.so.1.7.0" ++ "@PREFIX_LIB@/libGL.so.1.7.0", ++ "@PREFIX_LIB@/libOpenGL.so.0", ++ "@PREFIX_LIB@/libOpenGL.so.0.0.0" + ] + }, + "Vulkan": { diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex index df14d93f7e..7c1dd3176f 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex @@ -51,7 +51,7 @@ PROVIDED = frozenset(( "libssl.so.3", "libcrypto.so.3", "libfreetype.so.6", "libpng16.so.16", "libbrotlidec.so.1", "libbrotlicommon.so.1", "libbz2.so.1.0", "libz.so.1", "libwayland-client.so.0", "libwayland-egl.so.1", "libwayland-server.so.0", "libffi.so.8", - "libgbm.so.1", "libdrm.so.2", "libexpat.so.1", + "libgbm.so.1", "libdrm.so.2", "libexpat.so.1", "libOpenGL.so.0", )) PROVIDED_NEEDS = { "libwayland-client.so.0": ("libffi.so.8",), diff --git a/tools/tests/test_droiddeck_fex.py b/tools/tests/test_droiddeck_fex.py index 22e5017d2d..ce474de509 100644 --- a/tools/tests/test_droiddeck_fex.py +++ b/tools/tests/test_droiddeck_fex.py @@ -526,6 +526,21 @@ class PrepareTest(FexTestCase): for name in names: self.assertEqual((Path(fex["rootfs"]) / "lib" / arch / name).read_bytes(), b"new ABI " + name.encode()) + def test_opengl_dispatch_library_comes_from_the_newer_runtime_when_the_base_lacks_it(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + provider = self.graphics(sniper) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + self.write(sniper / "files/lib" / arch / "libGLdispatch.so.0", b"base dispatch") + self.write(provider / "files/lib" / arch / "libOpenGL.so.0.0.0", b"opengl " + arch.encode()) + os.symlink("libOpenGL.so.0.0.0", provider / "files/lib" / arch / "libOpenGL.so.0") + fex, _ = self.quiet(FEX["prepare"]) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + root = Path(fex["rootfs"]) / "lib" / arch + self.assertEqual((root / "libOpenGL.so.0").read_bytes(), b"opengl " + arch.encode()) + self.assertEqual((root / "libGLdispatch.so.0").read_bytes(), b"base dispatch") + def test_gbm_requires_usable_provider_dependencies_on_both_architectures(self): self.fex_tool() sniper = self.runtime() diff --git a/tools/tests/test_fex_gl_thunk_overlay.py b/tools/tests/test_fex_gl_thunk_overlay.py new file mode 100644 index 0000000000..e06d59e632 --- /dev/null +++ b/tools/tests/test_fex_gl_thunk_overlay.py @@ -0,0 +1,29 @@ +from pathlib import Path +import re +import unittest + +PATCH = Path(__file__).resolve().parents[1] / "fex/patches/0015-gl-thunk-overlays-libopengl.patch" + + +def hunk(sign): + lines = [line for line in PATCH.read_text().splitlines() if not line.startswith(("diff ", "index ", "--- ", "+++ ", "@@"))] + return re.findall(r'"([^"]+)"', "\n".join(line[1:] for line in lines if line[:1] in (" ", sign))) + + +class FexGlThunkOverlayTest(unittest.TestCase): + def test_libopengl_joins_the_gl_overlay(self): + before, after = hunk("-"), hunk("+") + self.assertNotIn("@PREFIX_LIB@/libOpenGL.so.0", before) + self.assertIn("@PREFIX_LIB@/libOpenGL.so.0", after) + self.assertIn("@PREFIX_LIB@/libOpenGL.so.0.0.0", after) + self.assertEqual([path for path in before if path.startswith("@PREFIX_LIB@/libGL.")], + [path for path in after if path.startswith("@PREFIX_LIB@/libGL.")]) + self.assertLess(after.index("@PREFIX_LIB@/libGL.so.1.7.0"), after.index("Vulkan")) + self.assertLess(after.index("@PREFIX_LIB@/libOpenGL.so.0.0.0"), after.index("Vulkan")) + + def test_patch_touches_only_the_thunks_database(self): + self.assertEqual(["Data/ThunksDB.json"], re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M)) + + +if __name__ == "__main__": + unittest.main() From 78f942313db3684c498ad766ad7d649ab715b361 Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Mon, 23 Nov 2026 20:02:08 -0500 Subject: [PATCH 079/141] fix(fex): x86 programs no longer see the host's arm64 preload libraries (#3098) * fix(fex): x86 programs no longer see the host's arm64 preload libraries * test(fex): build the x86 preload fixtures with an x86-64 compiler --- ...4-guest-preload-drops-host-libraries.patch | 51 ++++++++ tools/tests/test_fex_guest_preload.py | 120 ++++++++++++++++++ 2 files changed, 171 insertions(+) create mode 100644 tools/fex/patches/0014-guest-preload-drops-host-libraries.patch create mode 100644 tools/tests/test_fex_guest_preload.py diff --git a/tools/fex/patches/0014-guest-preload-drops-host-libraries.patch b/tools/fex/patches/0014-guest-preload-drops-host-libraries.patch new file mode 100644 index 0000000000..204c5c5dc6 --- /dev/null +++ b/tools/fex/patches/0014-guest-preload-drops-host-libraries.patch @@ -0,0 +1,51 @@ +diff --git a/Source/Tools/FEXInterpreter/ELFCodeLoader.h b/Source/Tools/FEXInterpreter/ELFCodeLoader.h +index e1f601b..cebf1f5 100644 +--- a/Source/Tools/FEXInterpreter/ELFCodeLoader.h ++++ b/Source/Tools/FEXInterpreter/ELFCodeLoader.h +@@ -222,6 +222,32 @@ class ELFCodeLoader final : public FEX::CodeLoader { + + public: + ++ static fextl::string GuestPreload(const char* List, const fextl::string& RootFS) { ++ fextl::string Result; ++ for (const char* Start = List; *Start; Start += *Start ? 1 : 0) { ++ size_t Length = strcspn(Start, ": "); ++ fextl::string Entry(Start, Length); ++ Start += Length; ++ if (Entry.empty()) { ++ continue; ++ } ++ if (Entry[0] == '/') { ++ auto Type = ::ELFLoader::ELFContainer::GetELFType(ResolveRootfsFile(Entry, RootFS)); ++ if (Type == ::ELFLoader::ELFContainer::TYPE_NONE) { ++ Type = ::ELFLoader::ELFContainer::GetELFType(Entry); ++ } ++ if (Type == ::ELFLoader::ELFContainer::TYPE_OTHER_ELF) { ++ continue; ++ } ++ } ++ if (!Result.empty()) { ++ Result += ':'; ++ } ++ Result += Entry; ++ } ++ return Result; ++ } ++ + static fextl::string ResolveRootfsFile(const fextl::string& File, fextl::string RootFS) { + // If the path is relative then just run that + if (File[0] != '/') { +@@ -330,6 +356,13 @@ public: + if (envp[i] == nullptr) { + break; + } ++ if (strncmp(envp[i], "LD_PRELOAD=", 11) == 0) { ++ auto Preload = GuestPreload(envp[i] + 11, RootFS); ++ if (!Preload.empty()) { ++ EnvironmentVariables.emplace_back("LD_PRELOAD=" + Preload); ++ } ++ continue; ++ } + EnvironmentVariables.emplace_back(envp[i]); + } + } diff --git a/tools/tests/test_fex_guest_preload.py b/tools/tests/test_fex_guest_preload.py new file mode 100644 index 0000000000..4b2f200bc0 --- /dev/null +++ b/tools/tests/test_fex_guest_preload.py @@ -0,0 +1,120 @@ +from pathlib import Path +import re +import shutil +import subprocess +import tempfile +import unittest + +PATCH = Path(__file__).resolve().parents[1] / "fex/patches/0014-guest-preload-drops-host-libraries.patch" + +HARNESS = r""" +#include <cstdio> +#include <cstring> +#include <elf.h> +#include <fcntl.h> +#include <string> +#include <unistd.h> +namespace fextl { using string = std::string; } +namespace ELFLoader { +struct ELFContainer { + enum ELFType { TYPE_NONE, TYPE_X86_64, TYPE_X86_32, TYPE_OTHER_ELF }; + static ELFType GetELFType(const std::string& Filename) { + int FD = open(Filename.c_str(), O_RDONLY | O_CLOEXEC); + if (FD == -1) return TYPE_NONE; + Elf64_Ehdr Header {}; + ssize_t Read = pread(FD, &Header, sizeof(Header), 0); + close(FD); + if (Read < (ssize_t)sizeof(Header) || memcmp(Header.e_ident, ELFMAG, SELFMAG) != 0) return TYPE_NONE; + if (Header.e_machine == EM_X86_64) return TYPE_X86_64; + if (Header.e_machine == EM_386) return TYPE_X86_32; + return TYPE_OTHER_ELF; + } +}; +} +struct Loader { + static fextl::string ResolveRootfsFile(const fextl::string& File, fextl::string RootFS) { return RootFS + File; } + GUEST_PRELOAD +}; +int main(int argc, char** argv) { + std::printf("%s", Loader::GuestPreload(argv[1], argv[2]).c_str()); +} +""" + + +def x86_compiler(): + for name in ("x86_64-linux-gnu-gcc", "gcc"): + path = shutil.which(name) + if path and subprocess.run([path, "-dumpmachine"], capture_output=True, text=True).stdout.startswith("x86_64"): + return path + return None + + +X86_CC = x86_compiler() + + +def patch_function(): + lines = [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")] + body = "\n".join(lines) + first = body.index(" static fextl::string GuestPreload(") + last = body.index("\n }\n", first) + len("\n }\n") + return body[first:last] + + +@unittest.skipUnless(shutil.which("g++") and X86_CC and shutil.which("aarch64-linux-gnu-gcc"), "needs g++, an x86-64 gcc and aarch64-linux-gnu-gcc") +class FexGuestPreloadTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tmp = tempfile.TemporaryDirectory() + cls.dir = Path(cls.tmp.name) + source = cls.dir / "harness.cpp" + source.write_text(HARNESS.replace("GUEST_PRELOAD", patch_function())) + cls.binary = cls.dir / "harness" + subprocess.run(["g++", "-std=c++20", "-O1", "-o", str(cls.binary), str(source)], check=True) + stub = cls.dir / "stub.c" + stub.write_text("int stub(void) { return 0; }\n") + cls.host = cls.dir / "host" + cls.rootfs = cls.dir / "rootfs" + cls.shadow = cls.host / "lib/libshadow.so" + cls.rootfs_shadow = Path(str(cls.rootfs) + str(cls.shadow)) + for folder in (cls.host / "lib", cls.rootfs_shadow.parent): + folder.mkdir(parents=True) + cls.compile("aarch64-linux-gnu-gcc", stub, cls.host / "lib/libhost.so") + cls.compile(X86_CC, stub, cls.host / "lib/libguest.so") + cls.compile("aarch64-linux-gnu-gcc", stub, cls.shadow) + cls.compile(X86_CC, stub, cls.rootfs_shadow) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + @staticmethod + def compile(compiler, source, output): + subprocess.run([compiler, "-shared", "-fPIC", "-o", str(output), str(source)], check=True) + + def preload(self, value, rootfs=None): + root = str(self.rootfs) if rootfs is None else rootfs + return subprocess.run([str(self.binary), value, root], check=True, capture_output=True, text=True).stdout + + def test_host_libraries_leave_the_guest_list(self): + host, guest = self.host / "lib/libhost.so", self.host / "lib/libguest.so" + self.assertEqual(str(guest), self.preload(f"{host}:{guest}")) + self.assertEqual("", self.preload(str(host))) + + def test_rootfs_copy_decides_before_the_host_path(self): + self.assertEqual(str(self.shadow), self.preload(str(self.shadow))) + self.assertEqual("", self.preload(str(self.shadow), "")) + + def test_names_missing_files_and_separators_are_kept(self): + missing = str(self.dir / "missing.so") + guest = str(self.host / "lib/libguest.so") + self.assertEqual(f"libgamemodeauto.so.0:{missing}:{guest}", + self.preload(f" libgamemodeauto.so.0::{missing} {guest}:")) + + def test_patch_adds_no_comments(self): + added = [line[1:].strip() for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")] + self.assertFalse([line for line in added if line.startswith(("//", "/*"))]) + self.assertEqual(["Source/Tools/FEXInterpreter/ELFCodeLoader.h"], re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M)) + + +if __name__ == "__main__": + unittest.main() From 8ee80aa20f2cc1e7a445d0db5ac43b5a32174ba0 Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Mon, 23 Nov 2026 20:02:13 -0500 Subject: [PATCH 080/141] fix(appimage): arm64 programs use the session's GL libraries over bundled copies (#3103) --- .../usr/local/bin/droiddeck-appimage-run | 11 ++++++++++- tools/tests/test_appimage_run.py | 18 ++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-appimage-run b/tools/linuxfs/overlay/usr/local/bin/droiddeck-appimage-run index b4a1910f24..d0d33c595e 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-appimage-run +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-appimage-run @@ -45,11 +45,20 @@ if [ "$qt" = wayland ] && [ -n "$wayland" ]; then elif [ "$qt" = xcb ] && [ -n "${DISPLAY:-}" ]; then export QT_QPA_PLATFORM=xcb fi +arch=$(cat "$dir/arch" 2>/dev/null) +if [ "$arch" = arm64 ]; then + find -H "$APPDIR" -maxdepth 6 ! -type d \( -name libGL.so.1 -o -name libGLX.so.0 -o -name libEGL.so.1 -o -name libGLESv2.so.2 \ + -o -name libOpenGL.so.0 -o -name libGLdispatch.so.0 \) -print 2>/dev/null | + while IFS= read -r lib; do + kept=$dir/bundled-gl/${lib#"$APPDIR"/} + mkdir -p "${kept%/*}" && mv -f "$lib" "$kept" && echo "== appimage: the session's ${lib##*/} replaces the bundled one" + done +fi fex=$(cat "$dir/fex" 2>/dev/null) case $fex in on|off) ;; *) fex=auto ;; esac run=("$APPDIR/AppRun") if [ -x /usr/local/bin/droiddeck-fex ]; then - case $fex:$(cat "$dir/arch" 2>/dev/null) in + case $fex:$arch in auto:x86_64|auto:i386) run=(/usr/local/bin/droiddeck-fex run --mode on -- "$APPDIR/AppRun") ;; auto:arm64) ;; *) run=(/usr/local/bin/droiddeck-fex run --mode "$fex" --for "$APPDIR" -- "$APPDIR/AppRun") ;; diff --git a/tools/tests/test_appimage_run.py b/tools/tests/test_appimage_run.py index 14ac8ad676..84c92f49b8 100644 --- a/tools/tests/test_appimage_run.py +++ b/tools/tests/test_appimage_run.py @@ -146,6 +146,24 @@ class AppImageRunTest(unittest.TestCase): env, _ = self.launch(dict(RUN_MODE, TU_DEBUG="sysmem")) self.assertEqual("sysmem", env["TU_DEBUG"]) + def test_an_arm64_app_uses_the_sessions_gl_libraries(self): + (self.dir / "arch").write_text("arm64") + self.bundle("usr/lib/libGLESv2.so.2", "usr/lib/libEGL.so.1", "usr/lib/libglfw.so.3", "usr/lib/libGLESv2.so.2.1.0") + _, log = self.launch(RUN_MODE) + lib = self.dir / "app/usr/lib" + self.assertEqual(["libGLESv2.so.2.1.0", "libglfw.so.3"], sorted(p.name for p in lib.iterdir())) + self.assertEqual(["libEGL.so.1", "libGLESv2.so.2"], sorted(p.name for p in (self.dir / "bundled-gl/usr/lib").iterdir())) + self.assertIn("the session's libGLESv2.so.2 replaces the bundled one", log) + _, log = self.launch(RUN_MODE) + self.assertNotIn("replaces the bundled one", log) + + def test_other_architectures_keep_their_gl_libraries(self): + (self.dir / "arch").write_text("x86_64") + self.bundle("usr/lib/libGLESv2.so.2") + self.launch(RUN_MODE) + self.assertTrue((self.dir / "app/usr/lib/libGLESv2.so.2").exists()) + self.assertFalse((self.dir / "bundled-gl").exists()) + if __name__ == "__main__": unittest.main() From 5cb8e7fdf3859288ef342286d9aa5d570f40d366 Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Mon, 23 Nov 2026 21:17:13 -0500 Subject: [PATCH 081/141] fix(hook): /dev/fd in a forked process names that process's own descriptors (#3105) * fix(hook): /dev/fd in a forked process names that process's own descriptors The /dev/fd and /dev/std* binds point at /proc/self/fd. Their sources were resolved with realpath when the binds were loaded, which turned /proc/self into the loading process's pid. A child that forks without exec, such as a bash subshell running cat < <(...), then opened its parent's descriptors and failed with ENOENT. Sources under /proc keep their own path. * fix(hook): keep canonical bind sources for /proc paths that name no process * fix(hook): only /proc bind sources that name a process keep their form --- tools/nativeguest/hook/paths.c | 2 +- tools/tests/test_native_hook_mounts.py | 33 ++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/tools/nativeguest/hook/paths.c b/tools/nativeguest/hook/paths.c index fcfe12cc43..94e2ad336f 100644 --- a/tools/nativeguest/hook/paths.c +++ b/tools/nativeguest/hook/paths.c @@ -82,7 +82,7 @@ static void ddnatv_load_binds(const char *spec) { char kernel_src[PATH_MAX]; if (strcmp(src, dst) != 0) { ddnatv_kernel_path(src, strlen(src), kernel_src, sizeof(kernel_src)); - src = kernel_src; + if (strncmp(kernel_src, "/proc/", 6) != 0 || kernel_src[6] < '0' || kernel_src[6] > '9') src = kernel_src; } b->src = strdup(src); b->dst = strdup(dst); diff --git a/tools/tests/test_native_hook_mounts.py b/tools/tests/test_native_hook_mounts.py index 9f82bb0149..ca56256aa7 100644 --- a/tools/tests/test_native_hook_mounts.py +++ b/tools/tests/test_native_hook_mounts.py @@ -15,6 +15,7 @@ PROBE = r""" #include <stdlib.h> #include <string.h> #include <sys/stat.h> +#include <sys/wait.h> #include <unistd.h> int main(int argc, char **argv) { @@ -39,6 +40,26 @@ int main(int argc, char **argv) { if (fd >= 0) close(fd); continue; } + if (strncmp(argv[i], "fork:", 5) == 0) { + fflush(stdout); + pid_t pid = fork(); + if (pid == 0) { + int p[2]; + char path[64], data[8] = "-"; + if (pipe(p) == 0 && write(p[1], "x", 1) == 1 && dup2(p[0], 63) == 63) { + snprintf(path, sizeof(path), "%s/63", argv[i] + 5); + int fd = open(path, O_RDONLY); + ssize_t n = fd >= 0 ? read(fd, data, sizeof(data) - 1) : -1; + if (n > 0) data[n] = 0; + if (fd >= 0) close(fd); + } + printf("%s\t%s\n", argv[i], data); + fflush(stdout); + _exit(0); + } + waitpid(pid, NULL, 0); + continue; + } if (strncmp(argv[i], "cd:", 3) == 0) { int ok = chdir(argv[i] + 3) == 0 && getcwd(cwd, sizeof(cwd)) != NULL; printf("%s\t%s\n", argv[i], ok ? cwd : "-"); @@ -153,6 +174,18 @@ class NativeHookMountTest(unittest.TestCase): self.assertEqual(out.returncode, 0, out.stderr) return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()} + def test_dev_fd_in_a_forked_child_names_the_child_descriptors(self): + out = self.run_probe("fork:/dev/fd", binds="/proc/self/fd:/dev/fd") + self.assertEqual(["x"], out["fork:/dev/fd"]) + + def test_a_mount_named_through_proc_self_root_reports_its_guest_path(self): + arg = f"cd:{GAME}/" + self.assertEqual(self.run_probe(arg, binds=f"/proc/self/root{self.library}:/mnt/library")[arg], [GAME]) + + def test_a_proc_mount_that_names_no_process_reports_its_guest_path(self): + arg = "cd:/mnt/sys/kernel/" + self.assertEqual(self.run_probe(arg, binds="/proc/self/root/proc/sys:/mnt/sys")[arg], ["/mnt/sys/kernel"]) + def test_drive_link_stored_as_rootfs_path_reaches_the_mount(self): path = f"/pfx/native/dosdevices/z:{GAME}/game.txt" self.assertEqual(self.run_probe(path)[path], ["1", "library"]) From 366afa6b734191663d2a99b38ad5c426fa750369 Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Mon, 23 Nov 2026 21:17:17 -0500 Subject: [PATCH 082/141] fix(desktop): an arm64 AppImage started directly runs like one opened from the file manager (#3108) * fix(desktop): an arm64 AppImage started directly runs like one opened from the file manager Without proot a guest program starts through the dynamic loader, which refuses the nonzero ABI version byte that marks every type 2 AppImage, so running an arm64 AppImage from a terminal or from a menu entry that names the image failed with "ELF file ABI version invalid". The preload already hands foreign programs to droiddeck-open; AppImages now go there too, where they are unpacked and started as the file manager does. * fix(desktop): hand off only AppImages that carry a filesystem, never a bare runtime --- tools/linuxfs/preload/binfmt.c | 13 +++++++++++-- tools/tests/test_binfmt_preload.py | 21 +++++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/tools/linuxfs/preload/binfmt.c b/tools/linuxfs/preload/binfmt.c index 94cecdeb86..50b5dd616f 100644 --- a/tools/linuxfs/preload/binfmt.c +++ b/tools/linuxfs/preload/binfmt.c @@ -32,17 +32,26 @@ static int handing_off(void) { return flag("DD_DESKTOP") || flag("DD_BINFMT"); } +static int appimage(int fd, const unsigned char *head, ssize_t n) { + Elf64_Ehdr eh; + if (n < (ssize_t)sizeof eh || head[EI_CLASS] != ELFCLASS64 || memcmp(head + EI_ABIVERSION, "AI\x02", 3)) return 0; + memcpy(&eh, head, sizeof eh); + char magic[6]; + off_t at = (off_t)eh.e_shoff + (off_t)eh.e_shentsize * eh.e_shnum; + return pread(fd, magic, sizeof magic, at) == (ssize_t)sizeof magic && (!memcmp(magic, "hsqs", 4) || !memcmp(magic, "DWARFS", 6)); +} + static int foreign(const char *path, int error) { if (!path || !strcmp(path, BINFMT_HANDLER)) return 0; int fd = open(path, O_RDONLY | O_CLOEXEC); if (fd < 0) return 0; struct stat st; - unsigned char head[20]; + unsigned char head[sizeof(Elf64_Ehdr)]; ssize_t n = fstat(fd, &st) == 0 && S_ISREG(st.st_mode) ? read(fd, head, sizeof head) : -1; int kind = 0; if (n >= 20 && !memcmp(head, ELFMAG, SELFMAG)) { unsigned machine = head[EI_DATA] == ELFDATA2MSB ? (unsigned)head[18] << 8 | head[19] : head[18] | (unsigned)head[19] << 8; - kind = machine == EM_X86_64 || machine == EM_386 || error == EACCES ? 1 : 0; + kind = machine == EM_X86_64 || machine == EM_386 || appimage(fd, head, n) || error == EACCES ? 1 : 0; } else if (n >= 2 && head[0] == 'M' && head[1] == 'Z') { kind = 2; } else if (n >= 2 && head[0] == '#' && head[1] == '!' && error == EACCES) { diff --git a/tools/tests/test_binfmt_preload.py b/tools/tests/test_binfmt_preload.py index e207b5c9ca..04b21b6021 100644 --- a/tools/tests/test_binfmt_preload.py +++ b/tools/tests/test_binfmt_preload.py @@ -138,6 +138,27 @@ class BinfmtPreloadTest(unittest.TestCase): program = self.file("arm64", bytes(arm64)) self.assertEqual(self.run_program("execve", program), (3, "errno %d" % errno.ENOEXEC, None)) + def arm64_appimage(self, name, filesystem): + image = bytearray(128) + image[0:4], image[4], image[5], image[8:11], image[18] = b"\x7fELF", 2, 1, b"AI\x02", 183 + image[0x28:0x30] = (64).to_bytes(8, "little") + image[0x3A:0x3C], image[0x3C:0x3E] = (32).to_bytes(2, "little"), (1).to_bytes(2, "little") + image[96:102] = filesystem + return self.file(name, bytes(image)) + + def test_an_arm64_appimage_goes_to_the_handler(self): + program = self.arm64_appimage("App.AppImage", b"hsqs\0\0") + for how in ("execve", "execvp"): + self.log.unlink(missing_ok=True) + target = program if how == "execve" else program.name + self.assertEqual(self.run_program(how, target, "--x"), (7, "", ["--exec", str(program), "--x"])) + self.log.unlink() + self.assertEqual(self.run_program("spawn", program, "y"), (0, "exit 7", ["--exec", str(program), "y"])) + + def test_an_appimage_runtime_without_a_filesystem_keeps_its_error(self): + runtime = self.arm64_appimage("uruntime", bytes(6)) + self.assertEqual(self.run_program("execve", runtime), (3, "errno %d" % errno.ENOEXEC, None)) + def test_a_script_runs_as_itself(self): script = self.file("script.sh", b"#!/bin/sh\nexit 5\n") self.assertEqual(self.run_program("execve", script), (5, "", None)) From d967dd03a3bc852bcdd82438aee83a334b4950bc Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Mon, 23 Nov 2026 21:23:56 -0500 Subject: [PATCH 083/141] fix(desktop): Electron and Chromium apps start however they are launched (#3106) * fix(desktop): Electron and Chromium apps start however they are launched The session preload only added --no-sandbox when the program path itself sat beside chrome-sandbox, so a PATH link such as /usr/bin/vesktop was missed and the app aborted on the setuid sandbox. It now resolves the path and also checks the parent folder, and adds --ozone-platform=x11 when an X display is set, since Wayland cannot open the GPU stand-in. The desktop menu overrides that added the same flags are removed: they covered only menu launches made after the desktop started, and the preload now covers every launch. Stale overrides are cleaned up by the existing marker check. * fix(preload): execvp checks the program found on PATH for the Chromium flags * fix(preload): the PATH lookup prefers the program execvp would run --- tools/linuxfs/desktop/droiddeck-desktop-gpu | 51 +-------------- tools/linuxfs/preload/binfmt.c | 46 +++++++------ tools/linuxfs/preload/net.c | 4 +- tools/linuxfs/preload/webhelper.c | 72 ++++++++++++++------- tools/tests/test_binfmt_preload.py | 18 ++++++ tools/tests/test_desktop_chromium_apps.py | 44 +++---------- tools/tests/test_webhelper_preload.py | 41 ++++++++++-- 7 files changed, 144 insertions(+), 132 deletions(-) diff --git a/tools/linuxfs/desktop/droiddeck-desktop-gpu b/tools/linuxfs/desktop/droiddeck-desktop-gpu index a0173f7b6d..a25e21e366 100644 --- a/tools/linuxfs/desktop/droiddeck-desktop-gpu +++ b/tools/linuxfs/desktop/droiddeck-desktop-gpu @@ -1,7 +1,6 @@ #!/usr/bin/python3 import os import re -import shutil HOME = os.environ.get("HOME", "/root") SYSTEM_DIR = "/usr/share/applications" @@ -10,8 +9,6 @@ FLATPAK_DIR = os.path.join(HOME, ".local/share/flatpak/exports/share/application USER_DIR = os.path.join(HOME, ".local/share/applications") MARK = "X-DroidDeck-GPU=1" SKIP = re.compile(r"^(steam|droiddeck-game-|droiddeck-steam|steamdeck-)", re.I) -CHROMIUM_ENV = "env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 ELECTRON_DISABLE_SANDBOX=1 " -CHROMIUM_FLAGS = " --no-sandbox --ozone-platform=x11" def enabled(): @@ -27,33 +24,6 @@ def main_group(text): return lines[:start + 1], lines[start + 1:end], lines[end:] -def split_program(exec_line): - if exec_line.startswith('"'): - end = exec_line.find('"', 1) - if end < 0: - return None, None - return exec_line[:end + 1], exec_line[end + 1:] - program, _, rest = exec_line.partition(" ") - return program, (" " + rest) if rest else "" - - -def chromium(exec_line): - program, _ = split_program(exec_line) - if not program: - return False - program = program.strip('"') - path = program if os.path.isabs(program) else shutil.which(program) - if not path: - return False - here = os.path.dirname(os.path.realpath(path)) - return any(os.path.exists(os.path.join(d, "chrome-sandbox")) for d in (here, os.path.dirname(here))) - - -def chromium_exec(exec_line): - program, rest = split_program(exec_line) - return CHROMIUM_ENV + program + CHROMIUM_FLAGS + rest - - def gpu_exec(exec_line): if exec_line.startswith("/usr/bin/flatpak run ") or exec_line.startswith("flatpak run "): exec_line = "/usr/local/bin/droiddeck-flatpak-run " + exec_line.split(" run ", 1)[1] @@ -75,24 +45,8 @@ def wrap(text, gpu_on=True): if not exec_line or exec_line.startswith("droiddeck-gpu "): return None cats = set(filter(None, keys.get("Categories", "").split(";"))) - gpu = gpu_on and bool(cats & {"Game", "Emulator"}) - browser = chromium(exec_line) - if not gpu and not browser: + if not (gpu_on and cats & {"Game", "Emulator"}): return None - if browser: - exec_line = chromium_exec(exec_line) - if not gpu: - def fix(lines): - return ["Exec=" + chromium_exec(l[5:].strip()) if l.startswith("Exec=") and chromium(l[5:].strip()) else l - for l in lines] - out_group = fix(group) - while out_group and not out_group[-1].strip(): - out_group.pop() - out_group.append(MARK) - out_rest = fix(rest) - if out_rest and out_rest[0].strip(): - out_rest.insert(0, "") - return "\n".join(head + out_group + out_rest) + "\n" out_group = [] actions = keys.get("Actions", "") for l in group: @@ -111,8 +65,7 @@ def wrap(text, gpu_on=True): wrapped_rest = [] for l in rest: if l.startswith("Exec=") and not l[5:].startswith("droiddeck-gpu "): - action = l[5:].strip() - l = "Exec=" + gpu_exec(chromium_exec(action) if chromium(action) else action) + l = "Exec=" + gpu_exec(l[5:].strip()) wrapped_rest.append(l) if wrapped_rest and wrapped_rest[0].strip(): wrapped_rest.insert(0, "") diff --git a/tools/linuxfs/preload/binfmt.c b/tools/linuxfs/preload/binfmt.c index 50b5dd616f..484a81094b 100644 --- a/tools/linuxfs/preload/binfmt.c +++ b/tools/linuxfs/preload/binfmt.c @@ -21,6 +21,29 @@ typedef int (*spawn_fn)(pid_t *, const char *, const posix_spawn_file_actions_t __attribute__((visibility("hidden"))) char *const *dd_webhelper_argv(const char *path, char *const argv[], char *const envp[]); +__attribute__((visibility("hidden"))) int dd_program_lookup(const char *file, char *out, size_t size) { + if (!file || !*file) return 0; + if (strchr(file, '/')) return snprintf(out, size, "%s", file) < (int)size; + const char *paths = getenv("PATH"); + if (!paths) paths = "/bin:/usr/bin"; + char candidate[PATH_MAX]; + int found = 0; + for (const char *p = paths;; ) { + const char *end = strchrnul(p, ':'); + int n = end > p ? snprintf(candidate, sizeof candidate, "%.*s/%s", (int)(end - p), p, file) + : snprintf(candidate, sizeof candidate, "%s", file); + struct stat st; + if (n > 0 && n < (int)sizeof candidate && n < (int)size && stat(candidate, &st) == 0 && S_ISREG(st.st_mode)) { + int runs = access(candidate, X_OK) == 0; + if (runs || !found) memcpy(out, candidate, (size_t)n + 1); + found = 1; + if (runs) return 1; + } + if (!*end) return found; + p = end + 1; + } +} + #if defined(__aarch64__) || defined(BINFMT_TEST) static int flag(const char *name) { @@ -67,21 +90,6 @@ static int wanted(const char *path, int error) { return (error == ENOEXEC || error == ENOENT || error == EACCES) && handing_off() && foreign(path, error); } -static int lookup(const char *file, char *out, size_t size) { - if (!file || !*file) return 0; - if (strchr(file, '/')) return snprintf(out, size, "%s", file) < (int)size; - const char *paths = getenv("PATH"); - if (!paths) paths = "/bin:/usr/bin"; - for (const char *p = paths;; ) { - const char *end = strchrnul(p, ':'); - int n = end > p ? snprintf(out, size, "%.*s/%s", (int)(end - p), p, file) : snprintf(out, size, "%s", file); - struct stat st; - if (n > 0 && n < (int)size && stat(out, &st) == 0 && S_ISREG(st.st_mode)) return 1; - if (!*end) return 0; - p = end + 1; - } -} - static int count(char *const argv[]) { int n = 0; while (argv && argv[n]) n++; @@ -126,12 +134,12 @@ __attribute__((visibility("hidden"))) int dd_binfmt_retry(const char *path, char __attribute__((visibility("hidden"))) void dd_binfmt_before_search(const char *file, char *const argv[], char *const envp[]) { char path[PATH_MAX]; - if (handing_off() && lookup(file, path, sizeof path)) dd_binfmt_before(path, argv, envp); + if (handing_off() && dd_program_lookup(file, path, sizeof path)) dd_binfmt_before(path, argv, envp); } __attribute__((visibility("hidden"))) int dd_binfmt_after_search(const char *file, char *const argv[], char *const envp[], int error) { char path[PATH_MAX]; - if (handing_off() && lookup(file, path, sizeof path)) return dd_binfmt_retry(path, argv, envp, error); + if (handing_off() && dd_program_lookup(file, path, sizeof path)) return dd_binfmt_retry(path, argv, envp, error); errno = error; return -1; } @@ -153,7 +161,7 @@ __attribute__((visibility("hidden"))) int dd_binfmt_spawn(pid_t *pid, const char int execvpe(const char *file, char *const argv[], char *const envp[]) { char resolved[PATH_MAX]; - const char *path = lookup(file, resolved, sizeof resolved) ? resolved : file; + const char *path = dd_program_lookup(file, resolved, sizeof resolved) ? resolved : file; char *const *adjusted = dd_webhelper_argv(path, argv, envp); static int (*real)(const char *, char *const[], char *const[]); if (!real) real = (int (*)(const char *, char *const[], char *const[]))dlsym(RTLD_NEXT, "execvpe"); @@ -165,7 +173,7 @@ int execvpe(const char *file, char *const argv[], char *const envp[]) { int posix_spawnp(pid_t *pid, const char *file, const posix_spawn_file_actions_t *fa, const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) { char path[PATH_MAX]; - int found = lookup(file, path, sizeof path); + int found = dd_program_lookup(file, path, sizeof path); char *const *adjusted = dd_webhelper_argv(found ? path : file, argv, envp); static spawn_fn real, spawn; if (!real) real = (spawn_fn)dlsym(RTLD_NEXT, "posix_spawnp"); diff --git a/tools/linuxfs/preload/net.c b/tools/linuxfs/preload/net.c index de3cfdaee7..388b92da6a 100644 --- a/tools/linuxfs/preload/net.c +++ b/tools/linuxfs/preload/net.c @@ -277,6 +277,7 @@ __attribute__((visibility("hidden"))) void dd_binfmt_before_search(const char *f __attribute__((visibility("hidden"))) int dd_binfmt_after_search(const char *file, char *const argv[], char *const envp[], int error); __attribute__((visibility("hidden"))) char *const *dd_webhelper_argv(const char *path, char *const argv[], char *const envp[]); +__attribute__((visibility("hidden"))) int dd_program_lookup(const char *file, char *out, size_t size); __attribute__((visibility("hidden"))) int dd_binfmt_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *fa, const posix_spawnattr_t *attr, char *const argv[], char *const envp[], spawn_fn real); @@ -377,7 +378,8 @@ static int answer_lsof_via_spawn(const char *path, char *const argv[], pid_t *pi } int execvp(const char *file, char *const argv_in[]) { - char *const *argv = dd_webhelper_argv(file, argv_in, environ); + char resolved[PATH_MAX]; + char *const *argv = dd_webhelper_argv(dd_program_lookup(file, resolved, sizeof resolved) ? resolved : file, argv_in, environ); static int (*real)(const char *, char *const[]); if (!real) real = (int (*)(const char *, char *const[]))dlsym(RTLD_NEXT, "execvp"); maybe_answer_lsof(file, argv); diff --git a/tools/linuxfs/preload/webhelper.c b/tools/linuxfs/preload/webhelper.c index 81aba8e8a5..5263b0f464 100644 --- a/tools/linuxfs/preload/webhelper.c +++ b/tools/linuxfs/preload/webhelper.c @@ -26,40 +26,64 @@ static char *join_features(const char *have, const char *add) { return strcat(out, add); } -static int electron_node_mode(char *const envp[]) { - static const char variable[] = "ELECTRON_RUN_AS_NODE="; +static const char *env_value(char *const envp[], const char *variable) { + size_t n = strlen(variable); for (int i = 0; envp && envp[i]; i++) - if (!strncmp(envp[i], variable, sizeof variable - 1)) - return envp[i][sizeof variable - 1] != 0; - return 0; + if (!strncmp(envp[i], variable, n) && envp[i][n] == '=') return envp[i] + n + 1; + return NULL; } -static char *const *chromium_argv(const char *path, char *const argv[]) { - const char *slash = path ? strrchr(path, '/') : NULL; - if (!slash || !argv || !argv[0]) return argv; - int argc = 0; - for (; argv[argc]; argc++) - if (argc && (!strncmp(argv[argc], "--type=", 7) || !strcmp(argv[argc], "--no-sandbox"))) return argv; - size_t dir = (size_t)(slash - path) + 1; - char *sandbox = malloc(dir + sizeof "chrome-sandbox"); - if (!sandbox) return argv; - memcpy(sandbox, path, dir); - strcpy(sandbox + dir, "chrome-sandbox"); - int chromium = access(sandbox, F_OK) == 0; - free(sandbox); - if (!chromium) return argv; - char **out = calloc((size_t)argc + 2, sizeof *out); +static int electron_node_mode(char *const envp[]) { + const char *mode = env_value(envp, "ELECTRON_RUN_AS_NODE"); + return mode && *mode; +} + +static int beside_chrome_sandbox(const char *path) { + char *real = realpath(path, NULL); + if (!real) return 0; + int found = 0; + for (int up = 0; up < 2 && !found; up++) { + char *slash = strrchr(real, '/'); + if (!slash) break; + *slash = 0; + size_t dir = strlen(real); + char *sandbox = malloc(dir + sizeof "/chrome-sandbox"); + if (!sandbox) break; + memcpy(sandbox, real, dir); + strcpy(sandbox + dir, "/chrome-sandbox"); + found = access(sandbox, F_OK) == 0; + free(sandbox); + } + free(real); + return found; +} + +static char *const *chromium_argv(const char *path, char *const argv[], char *const envp[]) { + if (!path || !argv || !argv[0]) return argv; + int argc = 0, sandbox = 1, ozone = 0; + for (; argv[argc]; argc++) { + if (!argc) continue; + if (!strncmp(argv[argc], "--type=", 7)) return argv; + if (!strcmp(argv[argc], "--no-sandbox")) sandbox = 0; + if (!strncmp(argv[argc], "--ozone-platform=", 17)) ozone = 1; + } + const char *display = env_value(envp, "DISPLAY"); + int x11 = !ozone && display && *display; + if ((!sandbox && !x11) || !beside_chrome_sandbox(path)) return argv; + char **out = calloc((size_t)argc + 3, sizeof *out); if (!out) return argv; - out[0] = argv[0]; - out[1] = (char *)"--no-sandbox"; - for (int i = 1; i < argc; i++) out[i + 1] = argv[i]; + int n = 0; + out[n++] = argv[0]; + if (sandbox) out[n++] = (char *)"--no-sandbox"; + if (x11) out[n++] = (char *)"--ozone-platform=x11"; + for (int i = 1; i < argc; i++) out[n++] = argv[i]; return out; } __attribute__((visibility("hidden"))) char *const *dd_webhelper_argv(const char *path, char *const argv[], char *const envp[]) { if (electron_node_mode(envp)) return argv; - if (!is_webhelper_browser(path, argv)) return chromium_argv(path, argv); + if (!is_webhelper_browser(path, argv)) return chromium_argv(path, argv, envp); const char *spec = getenv("DD_WEBHELPER_ARGS"); if (!spec || !*spec) spec = WEBHELPER_DEFAULT; if (!strcmp(spec, "stock")) return argv; diff --git a/tools/tests/test_binfmt_preload.py b/tools/tests/test_binfmt_preload.py index 04b21b6021..38c2dc4038 100644 --- a/tools/tests/test_binfmt_preload.py +++ b/tools/tests/test_binfmt_preload.py @@ -209,6 +209,24 @@ class BinfmtPreloadTest(unittest.TestCase): code = self.chromium_script() self.assertEqual(self.run_program("execve", code, "--version"), (0, "--no-sandbox\n--version", None)) + def test_a_chromium_app_named_on_path_receives_no_sandbox(self): + (self.dir / "code").symlink_to(self.chromium_script()) + for how in ("execvp", "execvpe", "spawnp"): + out = self.run_program(how, "code", "--version") + self.assertEqual(out[1].splitlines()[:2], ["--no-sandbox", "--version"], how) + + def test_a_path_match_that_cannot_run_does_not_decide_the_flags(self): + stale = self.dir / "stale" + stale.mkdir() + (stale / "util").write_text("#!/bin/sh\n") + (stale / "chrome-sandbox").touch() + util = self.dir / "util" + util.write_text("#!/bin/sh\nprintf '%s\\n' \"$@\"\n") + util.chmod(0o755) + for how in ("execvp", "execvpe", "spawnp"): + out = self.run_program(how, "util", "--version", PATH=f"{stale}:{self.dir}:/usr/bin:/bin") + self.assertEqual(out[1].splitlines()[:1], ["--version"], how) + def test_the_hand_off_switch_works_without_the_desktop(self): tool = self.x86() for how in ("execve", "execvp"): diff --git a/tools/tests/test_desktop_chromium_apps.py b/tools/tests/test_desktop_chromium_apps.py index f8d6056d21..8f5525d6d3 100644 --- a/tools/tests/test_desktop_chromium_apps.py +++ b/tools/tests/test_desktop_chromium_apps.py @@ -1,11 +1,8 @@ -import os from pathlib import Path import tempfile import unittest SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/desktop/droiddeck-desktop-gpu" -PREFIX = "env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 ELECTRON_DISABLE_SANDBOX=1 " -FLAGS = " --no-sandbox --ozone-platform=x11" def load(): @@ -24,12 +21,6 @@ class DesktopChromiumAppsTest(unittest.TestCase): self.gpu = load() self.electron = self.app("lib/chat/chat", sandbox=True) self.plain = self.app("lib/editor/editor", sandbox=False) - bin_dir = self.root / "bin" - bin_dir.mkdir() - (bin_dir / "chat").symlink_to(self.electron) - old_path = os.environ.get("PATH", "") - os.environ["PATH"] = "%s:%s" % (bin_dir, old_path) - self.addCleanup(os.environ.__setitem__, "PATH", old_path) def app(self, relative, sandbox): path = self.root / relative @@ -49,34 +40,17 @@ class DesktopChromiumAppsTest(unittest.TestCase): def exec_lines(self, text): return [l[5:] for l in text.splitlines() if l.startswith("Exec=")] - def test_an_electron_app_starts_without_the_sandbox_on_x11(self): - out = self.gpu["wrap"](self.entry("%s %%U" % self.electron, actions="%s --new" % self.electron)) - self.assertEqual(self.exec_lines(out), [PREFIX + str(self.electron) + FLAGS + " %U", - PREFIX + str(self.electron) + FLAGS + " --new"]) - self.assertIn("X-DroidDeck-GPU=1", out) - self.assertIn("Actions=new;", out) - self.assertNotIn("droiddeck-window", out) + def test_electron_apps_keep_their_own_entries(self): + self.assertIsNone(self.gpu["wrap"](self.entry("%s %%U" % self.electron, actions="%s --new" % self.electron))) + self.assertIsNone(self.gpu["wrap"](self.entry(str(self.plain)))) - def test_a_command_on_the_path_is_followed_to_its_install_folder(self): - out = self.gpu["wrap"](self.entry("chat %U")) - self.assertEqual(self.exec_lines(out), [PREFIX + "chat" + FLAGS + " %U"]) + def test_an_electron_game_goes_to_the_gpu_as_installed(self): + out = self.gpu["wrap"](self.entry(str(self.electron), categories="Game;", actions="%s --new" % self.electron)) + self.assertEqual(self.exec_lines(out), ["droiddeck-gpu " + str(self.electron), str(self.electron), + "droiddeck-gpu %s --new" % self.electron]) - def test_a_quoted_program_keeps_its_quotes(self): - out = self.gpu["wrap"](self.entry('"%s" %%U' % self.electron)) - self.assertEqual(self.exec_lines(out), [PREFIX + '"%s"' % self.electron + FLAGS + " %U"]) - - def test_other_apps_are_left_alone(self): - self.assertIsNone(self.gpu["wrap"](self.entry("%s %%F" % self.plain))) - self.assertIsNone(self.gpu["wrap"](self.entry("missing-program %F"))) - - def test_an_electron_game_goes_to_the_gpu_and_keeps_a_window_action(self): - out = self.gpu["wrap"](self.entry(str(self.electron), categories="Game;")) - fixed = PREFIX + str(self.electron) + FLAGS - self.assertEqual(self.exec_lines(out), ["droiddeck-gpu " + fixed, fixed]) - - def test_with_the_gpu_off_electron_apps_are_still_fixed(self): - out = self.gpu["wrap"](self.entry(str(self.electron), categories="Game;"), False) - self.assertEqual(self.exec_lines(out), [PREFIX + str(self.electron) + FLAGS]) + def test_with_the_gpu_off_no_entry_is_written(self): + self.assertIsNone(self.gpu["wrap"](self.entry(str(self.electron), categories="Game;"), False)) self.assertIsNone(self.gpu["wrap"](self.entry(str(self.plain), categories="Game;"), False)) def test_games_that_are_not_chromium_are_unchanged(self): diff --git a/tools/tests/test_webhelper_preload.py b/tools/tests/test_webhelper_preload.py index 3847e9988f..24e854dbb8 100644 --- a/tools/tests/test_webhelper_preload.py +++ b/tools/tests/test_webhelper_preload.py @@ -15,8 +15,11 @@ int main(int argc, char **argv) { const char *mode = getenv("TEST_NODE_MODE_CHILD"); static char node[64]; snprintf(node, sizeof node, "ELECTRON_RUN_AS_NODE=%s", mode ? mode : ""); - char *node_env[] = {node, NULL}; - char *plain_env[] = {"PATH=/usr/bin", NULL}; + const char *x = getenv("TEST_DISPLAY"); + static char display[64]; + snprintf(display, sizeof display, "DISPLAY=%s", x ? x : ""); + char *node_env[] = {node, x ? display : NULL, NULL}; + char *plain_env[] = {"PATH=/usr/bin", x ? display : NULL, NULL}; char *const *envp = mode ? node_env : plain_env; char *const *out = dd_webhelper_argv(argv[1], argv + 1, (char *const *)envp); for (int i = 0; out[i]; i++) printf("%s\n", out[i]); @@ -42,8 +45,10 @@ class WebhelperPreloadTest(unittest.TestCase): def tearDownClass(cls): shutil.rmtree(cls.tmp, ignore_errors=True) - def argv(self, *args, spec=None, node_child=False, parent_node=False): - env = {k: v for k, v in os.environ.items() if k != "DD_WEBHELPER_ARGS"} + def argv(self, *args, spec=None, node_child=False, parent_node=False, display=None): + env = {k: v for k, v in os.environ.items() if k not in ("DD_WEBHELPER_ARGS", "TEST_DISPLAY")} + if display is not None: + env["TEST_DISPLAY"] = display env.pop("ELECTRON_RUN_AS_NODE", None) if spec is not None: env["DD_WEBHELPER_ARGS"] = spec @@ -104,6 +109,34 @@ class WebhelperPreloadTest(unittest.TestCase): chrome = self.chromium("chromium-parent-mode", "chrome") self.assertEqual(self.argv(chrome, parent_node=True), [chrome, "--no-sandbox"]) + def test_a_link_to_an_electron_app_gets_the_sandbox_flag(self): + app = self.chromium("vesktop", "vesktop") + link = self.tmp / "bin-vesktop" + link.symlink_to(app) + self.assertEqual(self.argv(str(link), "%U"), [str(link), "--no-sandbox", "%U"]) + + def test_an_app_whose_sandbox_helper_is_one_folder_up_gets_the_flag(self): + root = self.tmp / "nested" + (root / "bin").mkdir(parents=True) + (root / "chrome-sandbox").touch() + (root / "bin/app").touch() + self.assertEqual(self.argv(str(root / "bin/app")), [str(root / "bin/app"), "--no-sandbox"]) + + def test_with_an_x_display_chromium_apps_use_x11(self): + chrome = self.chromium("chromium-x11", "chrome") + self.assertEqual(self.argv(chrome, "--new-window", display=":0"), + [chrome, "--no-sandbox", "--ozone-platform=x11", "--new-window"]) + self.assertEqual(self.argv(chrome, "--no-sandbox", display=":0"), + [chrome, "--ozone-platform=x11", "--no-sandbox"]) + + def test_an_explicit_platform_and_sandbox_choice_is_kept(self): + chrome = self.chromium("chromium-own-flags", "chrome") + own = [chrome, "--no-sandbox", "--ozone-platform=wayland"] + self.assertEqual(self.argv(*own, display=":0"), own) + + def test_other_programs_with_an_x_display_are_left_alone(self): + self.assertEqual(self.argv("/usr/bin/steam", display=":0"), ["/usr/bin/steam"]) + def test_stock_turns_it_off(self): args = [WEBHELPER, "--enable-features=A"] self.assertEqual(self.argv(*args, spec="stock"), args) From fcaaf4dde003898f1862d2fb12365948d29907e3 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:36:14 -0500 Subject: [PATCH 084/141] docs(agents): hints for the build loop, worktrees, device control and CI failures (#3113) * docs(agents): hints for the build loop, worktrees, device control and CI failures * docs(agents): run the tests that cover changed code --- AGENTS.md | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 447807615b..2997ceb10d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,7 +2,40 @@ - Comments should be rare, factual, and explain only non-obvious external constraints or business invariants. -# Working on the device +# 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. +- `verifyRuntimeInputs` fails the fast build with "Missing or changed runtime input" or "Runtime sources changed since preparation" after you pull main or edit `tools/linuxfs` (overlay scripts, preloads). Run `tools/build_local.sh` once. Do not revert scripts or copy `app/build` from another checkout to get past it. +- CI builds with the NDK in `tools/ci/toolchains.env` and runs `testReleaseUnitTest`. Local builds default to `gradle.properties`' NDK and `testDebugUnitTest`. Pass `-PndkVersion=` and run the release variant when a failure only shows up in CI. +- 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 + +- 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. - `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. From 95aab3703fa24de87fae5c6bf3af9fea17c4d8cc Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:55:27 -0500 Subject: [PATCH 085/141] fix(build): helper script edits no longer invalidate the prepared runtime, and every build uses CI's NDK (#3116) * fix(build): helper script edits no longer invalidate the prepared runtime, and every build uses CI's NDK * docs(agents): helper script edits no longer need build_local.sh --- AGENTS.md | 4 +-- app/build.gradle | 11 ++++----- gradle.properties | 1 - tools/build_local.sh | 5 ++++ tools/release/check_session_assets.py | 12 +++++++++ tools/release/runtime_inputs.py | 25 ++++++++++++++++++- tools/seed_worktree.sh | 9 +++++-- tools/tests/test_runtime_inputs.py | 35 +++++++++++++++++++++++++++ tools/tests/test_session_assets.py | 7 ++++++ 9 files changed, 97 insertions(+), 12 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2997ceb10d..4832415479 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -5,8 +5,8 @@ # 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. -- `verifyRuntimeInputs` fails the fast build with "Missing or changed runtime input" or "Runtime sources changed since preparation" after you pull main or edit `tools/linuxfs` (overlay scripts, preloads). Run `tools/build_local.sh` once. Do not revert scripts or copy `app/build` from another checkout to get past it. -- CI builds with the NDK in `tools/ci/toolchains.env` and runs `testReleaseUnitTest`. Local builds default to `gradle.properties`' NDK and `testDebugUnitTest`. Pass `-PndkVersion=` and run the release variant when a failure only shows up in CI. +- 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*'`. diff --git a/app/build.gradle b/app/build.gradle index b32bc078a9..f2cb40169b 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -125,7 +125,8 @@ def variantSuffixes = rootProject.file('tools/release/variants.txt').readLines() android { namespace 'com.droiddeck.launcher' compileSdk 34 - ndkVersion project.findProperty('ndkVersion') ?: '27.3.13750724' + 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() defaultConfig { applicationId "com.droiddeck.launcher" @@ -264,11 +265,9 @@ if (vitureSdkDir) { tasks.named('preBuild').configure { dependsOn(stageVitureNotices) } } -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')) +def stageSessionScripts = tasks.register('stageSessionScripts', Exec) { + workingDir rootProject.projectDir + commandLine pythonExecutable, 'tools/release/check_session_assets.py', '--stage' } tasks.named('preBuild').configure { dependsOn(stageSessionScripts) } diff --git a/gradle.properties b/gradle.properties index 3289cc4c5d..16bca3f56d 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,6 +4,5 @@ org.gradle.configuration-cache=true org.gradle.parallel=true android.useAndroidX=true android.nonTransitiveRClass=true -ndkVersion=27.3.13750724 org.gradle.tooling.parallel=true diff --git a/tools/build_local.sh b/tools/build_local.sh index d90a458d2c..ea3ebebbcf 100755 --- a/tools/build_local.sh +++ b/tools/build_local.sh @@ -63,6 +63,11 @@ fi ndk_version=${DROIDDECK_NDK_VERSION:-} if [[ -z "${ndk_version}" ]]; then + . "${repo_root}/tools/ci/toolchains.env" + [[ -d "${sdk_dir}/ndk/${CI_ANDROID_NDK_VERSION}" ]] && ndk_version=${CI_ANDROID_NDK_VERSION} +fi +if [[ -z "${ndk_version}" ]]; then + echo "NDK ${CI_ANDROID_NDK_VERSION} (tools/ci/toolchains.env) is not installed; using the newest NDK instead, so native caches will not match CI." >&2 ndk_path=$(find "${sdk_dir}/ndk" -mindepth 2 -maxdepth 2 -name source.properties -print | xargs -n1 dirname | sort -V | tail -1) ndk_version=${ndk_path##*/} fi diff --git a/tools/release/check_session_assets.py b/tools/release/check_session_assets.py index 940e722481..8a87e1af9d 100644 --- a/tools/release/check_session_assets.py +++ b/tools/release/check_session_assets.py @@ -1,6 +1,7 @@ from pathlib import Path import importlib.util import re +import shutil import sys from zipfile import ZipFile @@ -34,6 +35,14 @@ def source_assets(overlay=OVERLAY): return result +def stage(target=OVERLAY.parents[2] / 'app/src/main', overlay=OVERLAY): + for source, asset in source_assets(overlay).items(): + path = target / asset + if not path.is_file() or path.read_bytes() != source.read_bytes(): + path.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, path) + + def check(apk, overlay=OVERLAY): errors = check_extraction(overlay, SESSION_FILES.read_text()) if overlay == OVERLAY else [] with ZipFile(apk) as package: @@ -60,6 +69,9 @@ def check(apk, overlay=OVERLAY): if __name__ == '__main__': + if sys.argv[1:] == ['--stage']: + stage() + sys.exit() errors = check(sys.argv[1]) if errors: sys.exit('\n'.join(errors)) diff --git a/tools/release/runtime_inputs.py b/tools/release/runtime_inputs.py index 89488e1ba5..440c682cd8 100644 --- a/tools/release/runtime_inputs.py +++ b/tools/release/runtime_inputs.py @@ -48,8 +48,19 @@ def digest(path): return result.hexdigest() +def copied(root): + # Helper scripts are staged verbatim on every Gradle build and checked against the APK by + # check_session_assets.py, so they are neither preparation inputs nor prepared outputs. + if str(Path(__file__).resolve().parent) not in sys.path: + sys.path.insert(0, str(Path(__file__).resolve().parent)) + from check_session_assets import OVERLAY, source_assets + found = source_assets() if root == ROOT else source_assets(root / OVERLAY.relative_to(ROOT)) + return {source.relative_to(root).as_posix(): 'app/src/main/' + asset for source, asset in found.items()} + + def sources(root): files, builds = [], set() + skipped = set(copied(root)) for name in SOURCE_PATHS: path = root / name files.extend(path.rglob('*') if path.is_dir() else [path]) @@ -57,14 +68,18 @@ def sources(root): builds.update(manifest.parent / 'target' for manifest in path.rglob('Cargo.toml')) return {path.relative_to(root).as_posix(): digest(path) for path in sorted(set(files)) if path.is_file() and '__pycache__' not in path.parts and path.suffix != '.pyc' + and path.relative_to(root).as_posix() not in skipped and not any(build in path.parents for build in builds)} def outputs(root): result = {} + skipped = set(copied(root).values()) for tree in ['linuxfs', 'directaudio', 'droiddeck-esync', 'desktop-removal', 'hybris']: base = root / 'app/src/main/assets' / tree for path in base.rglob('*'): + if path.relative_to(root).as_posix() in skipped: + continue if path.is_file() and not any(part.startswith('.') for part in path.relative_to(base).parts): result['assets/' + tree + '/' + path.relative_to(base).as_posix()] = path.relative_to(root).as_posix() for library in ['libproot.so', 'libproot-loader.so', 'libdirectaudiorelay.so']: @@ -84,7 +99,6 @@ def required(): for name in ['turnip26.3.0-a6xx', 'turnip26.3.0-quest2']] paths += ['assets/linuxfs/' + name for name in ['libfakeinput.so', 'libddsession.so', 'libddfastpath.so', 'libddnatv-hook.so', 'libssbs.so', 'usr/local/bin/droiddeck-clipboard', - 'usr/local/bin/droiddeck-gog-maintenance', 'usr/local/bin/gamescope', 'usr/local/lib/droiddeck/uruntime', 'usr/local/lib/droiddeck-pipewire.tzst']] for arch in ['x86_64', 'i386']: @@ -178,6 +192,10 @@ def verify(root=ROOT, stale_sources_ok=False): raise ValueError('Runtime inputs have not been prepared. Run tools/build_local.sh.') if data.get('version') != 1: raise ValueError('Runtime sources changed since preparation. Run tools/build_local.sh.') + copies = copied(root) + data['sources'] = {name: value for name, value in (data.get('sources') or {}).items() if name not in copies} + data['outputs'] = {name: output for name, output in (data.get('outputs') or {}).items() + if output.get('path') not in copies.values()} current = sources(root) if data.get('sources') != current: if not stale_sources_ok: @@ -195,6 +213,11 @@ def verify(root=ROOT, stale_sources_ok=False): raise ValueError('Missing or changed runtime input: ' + name + '. Run tools/build_local.sh.') if outputs(root) != {name: output['path'] for name, output in data['outputs'].items()}: raise ValueError('Runtime file set changed. Run tools/build_local.sh.') + for source, asset in copies.items(): + path = root / asset + if not path.is_file() or path.read_bytes() != (root / source).read_bytes(): + raise ValueError(asset + ' is not a current copy of ' + source + + '. Run python3 tools/release/check_session_assets.py --stage.') return data diff --git a/tools/seed_worktree.sh b/tools/seed_worktree.sh index e5079e7111..45bbc56bed 100755 --- a/tools/seed_worktree.sh +++ b/tools/seed_worktree.sh @@ -10,14 +10,19 @@ paths=( app/build/packs app/build/localPackAssets app/build/packs-local-aside app/build/quest-inputs app/build/rustJniLibs app/build/vkbridgeJniLibs app/src/main/assets/directaudio app/src/main/assets/droiddeck-esync app/src/main/assets/linuxfs - app/src/main/assets/desktop-removal + app/src/main/assets/desktop-removal app/src/main/assets/hybris app/src/main/jniLibs/arm64-v8a app/src/main/rust/stores/target ) for path in "${paths[@]}"; do [[ -e "${main_root}/${path}" ]] || continue if [[ -d "${main_root}/${path}" ]]; then - [[ -z "$(ls -A "${repo_root}/${path}" 2>/dev/null)" ]] || continue + if [[ -n "$(ls -A "${repo_root}/${path}" 2>/dev/null)" ]]; then + # A directory holding only tracked files (jniLibs) still lacks every built library. + [[ -z "$(git -C "${repo_root}" ls-files --others -- "${path}")" ]] || continue + cp -Rn "${main_root}/${path}/." "${repo_root}/${path}/" + continue + fi mkdir -p "$(dirname "${repo_root}/${path}")" staged=$(mktemp -d "${repo_root}/${path}.seed.XXXXXX") trap 'rm -rf "${staged}"' EXIT diff --git a/tools/tests/test_runtime_inputs.py b/tools/tests/test_runtime_inputs.py index 92f2ae1c79..2bfbfb4dc3 100644 --- a/tools/tests/test_runtime_inputs.py +++ b/tools/tests/test_runtime_inputs.py @@ -1,6 +1,7 @@ import importlib.util import gzip import io +import json from pathlib import Path, PureWindowsPath import subprocess import tarfile @@ -122,6 +123,40 @@ class RuntimeInputsTest(unittest.TestCase): runtime.verify(self.root, stale_sources_ok=True) self.assertIn('tools/linuxfs/preload/test.c', stderr.getvalue()) + def helper(self, content): + source = self.root / 'tools/linuxfs/overlay/usr/local/bin/droiddeck-test-helper' + source.parent.mkdir(parents=True, exist_ok=True) + source.write_text(content) + staged = self.root / 'app/src/main/assets/linuxfs/usr/local/bin/droiddeck-test-helper' + staged.parent.mkdir(parents=True, exist_ok=True) + staged.write_text(content) + return source, staged + + def test_an_edited_helper_script_needs_no_new_preparation(self): + self.helper('old helper') + runtime.record(self.root) + self.helper('new helper') + runtime.verify(self.root) + + def test_a_staged_helper_that_lags_its_source_is_rejected(self): + source, _ = self.helper('old helper') + runtime.record(self.root) + source.write_text('new helper') + with self.assertRaisesRegex(ValueError, 'not a current copy'): + runtime.verify(self.root, stale_sources_ok=True) + + def test_a_manifest_that_hashed_helper_scripts_still_verifies(self): + source, staged = self.helper('old helper') + runtime.record(self.root) + manifest = self.root / runtime.MANIFEST + data = json.loads(manifest.read_text()) + data['sources']['tools/linuxfs/overlay/usr/local/bin/droiddeck-test-helper'] = 'old' + data['outputs']['assets/linuxfs/usr/local/bin/droiddeck-test-helper'] = { + 'path': 'app/src/main/assets/linuxfs/usr/local/bin/droiddeck-test-helper', 'sha256': 'old'} + manifest.write_text(json.dumps(data)) + self.helper('new helper') + runtime.verify(self.root) + def test_dev_loop_still_rejects_changed_outputs(self): runtime.record(self.root) (self.root / 'app/src/main/jniLibs/arm64-v8a/libproot.so').write_bytes(b'old APK binary') diff --git a/tools/tests/test_session_assets.py b/tools/tests/test_session_assets.py index 5f7f8675d1..563ea1212e 100644 --- a/tools/tests/test_session_assets.py +++ b/tools/tests/test_session_assets.py @@ -50,3 +50,10 @@ class SessionAssetsTest(unittest.TestCase): mapping = '"usr/local/bin/droiddeck-login1" to "usr/local/bin/sub/login1"' self.assertEqual(['not extracted at session start: usr/local/bin/droiddeck-login1'], assets.check_extraction(self.overlay, mapping)) + + def test_stage_refreshes_a_changed_helper(self): + target = self.root / 'main' + assets.stage(target, self.overlay) + self.helper.write_bytes(b'new helper') + assets.stage(target, self.overlay) + self.assertEqual(b'new helper', (target / self.name).read_bytes()) From f9304f41c759dbb2e3b9c977482214f0744b50ba Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:09:28 -0500 Subject: [PATCH 086/141] fix(ci): remove the three main unit test flakes (#3117) * fix(test): ProtonMenuAutoTest no longer fetches Proton releases from GitHub aCachedCheckUpdatesOnlyInstalledFamiliesAndReplacesOlderDroidDeckProton left experimentalRefresh at its default, which downloads the release list with 10 s connect and 15 s read timeouts, so a slow or rate-limited network blew the test's 5 s wait. * fix(test): a background-thread error no longer halts the unit test JVM Every Robolectric test runs App.onCreate, which chains CrashHandler onto the default uncaught-exception handler. A plain JVM has none, so the first test's handler halts with exit 2 on any later uncaught error, and the chain grows by one layer per test. A Robolectric lifecycle plugin now resets the default handler to a printing one before each test. --- .../droiddeck/launcher/ProtonMenuAutoTest.kt | 1 + .../session/TestJvmUncaughtHandler.kt | 16 ++++++++++++++ .../session/UncaughtBackgroundErrorTest.kt | 21 +++++++++++++++++++ ...c.pluginapi.TestEnvironmentLifecyclePlugin | 1 + 4 files changed, 39 insertions(+) create mode 100644 app/src/test/java/com/droiddeck/launcher/session/TestJvmUncaughtHandler.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/session/UncaughtBackgroundErrorTest.kt create mode 100644 app/src/test/resources/META-INF/services/org.robolectric.pluginapi.TestEnvironmentLifecyclePlugin diff --git a/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt b/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt index 4ea0a52d7f..dacf38c34c 100644 --- a/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt @@ -65,6 +65,7 @@ class ProtonMenuAutoTest { menu.protonProblem = null menu.protonStage = null menu.protonPercent = -1 + menu.experimentalRefresh = { emptyList() } menu.installer = { tool, progress -> progress("Installing ${tool.name}", 50) install("${tool.prefix}-11-12") diff --git a/app/src/test/java/com/droiddeck/launcher/session/TestJvmUncaughtHandler.kt b/app/src/test/java/com/droiddeck/launcher/session/TestJvmUncaughtHandler.kt new file mode 100644 index 0000000000..c95873aa2d --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/TestJvmUncaughtHandler.kt @@ -0,0 +1,16 @@ +package com.droiddeck.launcher.session + +import org.robolectric.pluginapi.TestEnvironmentLifecyclePlugin + +/** + * A plain JVM has no default uncaught-exception handler, so CrashHandler's fallback halts the test JVM (exit 2) + * on any background-thread error. Each test starts from a handler that only prints, like the JVM's own. + */ +class TestJvmUncaughtHandler : TestEnvironmentLifecyclePlugin { + override fun onSetupApplicationState() { + Thread.setDefaultUncaughtExceptionHandler { thread, error -> + System.err.print("Exception in thread \"${thread.name}\" ") + error.printStackTrace(System.err) + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/UncaughtBackgroundErrorTest.kt b/app/src/test/java/com/droiddeck/launcher/session/UncaughtBackgroundErrorTest.kt new file mode 100644 index 0000000000..d1409cce25 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/UncaughtBackgroundErrorTest.kt @@ -0,0 +1,21 @@ +package com.droiddeck.launcher.session + +import com.droiddeck.launcher.App +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class UncaughtBackgroundErrorTest { + @Test fun anUncaughtErrorOnABackgroundThreadDoesNotEndTheTestRun() { + assertTrue(RuntimeEnvironment.getApplication() is App) + Thread({ throw IllegalStateException("expected by the test") }, "uncaught-background-error").apply { + start() + join() + } + } +} diff --git a/app/src/test/resources/META-INF/services/org.robolectric.pluginapi.TestEnvironmentLifecyclePlugin b/app/src/test/resources/META-INF/services/org.robolectric.pluginapi.TestEnvironmentLifecyclePlugin new file mode 100644 index 0000000000..d6d0a4d676 --- /dev/null +++ b/app/src/test/resources/META-INF/services/org.robolectric.pluginapi.TestEnvironmentLifecyclePlugin @@ -0,0 +1 @@ +com.droiddeck.launcher.session.TestJvmUncaughtHandler From cd87718ac295a4b98451248ba0f81a1e5b929bdd Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Mon, 23 Nov 2026 22:53:19 -0500 Subject: [PATCH 087/141] fix(hook): named semaphores live where the session maps /dev/shm (#3110) * fix(hook): named semaphores live where the session maps /dev/shm * fix(hook): a semaphore opened twice is one mapping, mapped before its name is published * fix(nativeguest): a fork while another thread opens a semaphore leaves the child a usable registry * Native hook: register the semaphore fork handlers at load --- tools/nativeguest/ddnatv-hook.c | 1 + tools/nativeguest/hook/posix_shm.c | 134 ++++++++++++++- .../test_native_hook_named_semaphores.py | 159 ++++++++++++++++++ 3 files changed, 285 insertions(+), 9 deletions(-) create mode 100644 tools/tests/test_native_hook_named_semaphores.py diff --git a/tools/nativeguest/ddnatv-hook.c b/tools/nativeguest/ddnatv-hook.c index 58f688da4c..4070f55c85 100644 --- a/tools/nativeguest/ddnatv-hook.c +++ b/tools/nativeguest/ddnatv-hook.c @@ -41,6 +41,7 @@ #include <elf.h> #include <sys/sendfile.h> #include <sys/mman.h> +#include <semaphore.h> #include <sched.h> #include <time.h> #include <sys/xattr.h> diff --git a/tools/nativeguest/hook/posix_shm.c b/tools/nativeguest/hook/posix_shm.c index afd8a6f655..95ac489157 100644 --- a/tools/nativeguest/hook/posix_shm.c +++ b/tools/nativeguest/hook/posix_shm.c @@ -1,32 +1,148 @@ // Part of libddnatv-hook.so, included by ddnatv-hook.c. // -// shm_open() and shm_unlink() of glibc open /dev/shm/NAME with a system call of their own, which -// the path hooks never see and Android has no /dev/shm for. They go through open() and unlink() -// here, which map /dev/shm. +// shm_open(), shm_unlink() and the named semaphores of glibc open /dev/shm/NAME with system calls +// of their own, which the path hooks never see and Android has no /dev/shm for. They go through +// open(), renameat2() and unlink() here, which map /dev/shm. #ifndef DDNATV_HOST_TEST -static int posix_shm_path(const char *name, char *path, size_t size) { +static int posix_shm_path(const char *name, const char *prefix, char *path, size_t size) { if (!name) { errno = EINVAL; return -1; } while (*name == '/') name++; - size_t len = strlen(name); - if (len == 0 || len > NAME_MAX || strchr(name, '/') || strcmp(name, ".") == 0 || strcmp(name, "..") == 0) { + size_t len = strlen(name) + strlen(prefix); + if (len == strlen(prefix) || len > NAME_MAX || strchr(name, '/') || strcmp(name, ".") == 0 || strcmp(name, "..") == 0) { errno = len > NAME_MAX ? ENAMETOOLONG : EINVAL; return -1; } - if (snprintf(path, size, "/dev/shm/%s", name) >= (int)size) { errno = ENAMETOOLONG; return -1; } + if (snprintf(path, size, "/dev/shm/%s%s", prefix, name) >= (int)size) { errno = ENAMETOOLONG; return -1; } return 0; } int shm_open(const char *name, int oflag, mode_t mode) { char path[PATH_MAX]; - if (posix_shm_path(name, path, sizeof(path)) < 0) return -1; + if (posix_shm_path(name, "", path, sizeof(path)) < 0) return -1; return open(path, (oflag & (O_ACCMODE | O_CREAT | O_EXCL | O_TRUNC)) | O_NOFOLLOW | O_CLOEXEC, mode); } int shm_unlink(const char *name) { char path[PATH_MAX]; - if (posix_shm_path(name, path, sizeof(path)) < 0) return -1; + if (posix_shm_path(name, "", path, sizeof(path)) < 0) return -1; + return unlink(path); +} + +struct posix_sem { + dev_t dev; + ino_t ino; + sem_t *addr; + unsigned int refs; + struct posix_sem *next; +}; +static struct posix_sem *g_posix_sems; +static pthread_mutex_t g_posix_sems_lock = PTHREAD_MUTEX_INITIALIZER; + +static void posix_sems_unlock(void) { pthread_mutex_unlock(&g_posix_sems_lock); } + +static void posix_sems_hold(void) { pthread_mutex_lock(&g_posix_sems_lock); } + +__attribute__((constructor)) static void posix_sems_across_fork(void) { + pthread_atfork(posix_sems_hold, posix_sems_unlock, posix_sems_unlock); +} + +static void close_keeping_errno(int fd) { + int saved = errno; + close(fd); + errno = saved; +} + +static sem_t *posix_sem_map(int fd) { + struct stat st; + if (fstat(fd, &st) < 0) return SEM_FAILED; + sem_t *sem = SEM_FAILED; + posix_sems_hold(); + struct posix_sem *e = g_posix_sems; + while (e && (e->dev != st.st_dev || e->ino != st.st_ino)) e = e->next; + if (e) { + e->refs++; + sem = e->addr; + } else { + void *addr = mmap(NULL, sizeof(sem_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + e = addr == MAP_FAILED ? NULL : malloc(sizeof(*e)); + if (e) { + *e = (struct posix_sem){st.st_dev, st.st_ino, addr, 1, g_posix_sems}; + g_posix_sems = e; + sem = addr; + } else if (addr != MAP_FAILED) { + munmap(addr, sizeof(sem_t)); + errno = ENOMEM; + } + } + posix_sems_unlock(); + return sem; +} + +static sem_t *posix_sem_open_fd(int fd) { + if (fd < 0) return SEM_FAILED; + sem_t *sem = posix_sem_map(fd); + close_keeping_errno(fd); + return sem; +} + +sem_t *sem_open(const char *name, int oflag, ...) { + char path[PATH_MAX]; + if (posix_shm_path(name, "sem.", path, sizeof(path)) < 0) return SEM_FAILED; + if (!(oflag & O_CREAT)) return posix_sem_open_fd(open(path, O_RDWR | O_NOFOLLOW | O_CLOEXEC)); + va_list args; + va_start(args, oflag); + mode_t mode = va_arg(args, mode_t); + unsigned int value = va_arg(args, unsigned int); + va_end(args); + static unsigned int serial; + for (;;) { + if (!(oflag & O_EXCL)) { + int fd = open(path, O_RDWR | O_NOFOLLOW | O_CLOEXEC); + if (fd >= 0 || errno != ENOENT) return posix_sem_open_fd(fd); + } + if (value > SEM_VALUE_MAX) { errno = EINVAL; return SEM_FAILED; } + sem_t initial; + memset(&initial, 0, sizeof(initial)); + sem_init(&initial, 1, value); + char temp[PATH_MAX]; + int fd; + do { + snprintf(temp, sizeof(temp), "/dev/shm/.sem-%d-%u", (int)getpid(), __atomic_fetch_add(&serial, 1, __ATOMIC_RELAXED)); + fd = open(temp, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, mode); + } while (fd < 0 && errno == EEXIST); + if (fd < 0) return SEM_FAILED; + errno = EIO; + sem_t *sem = write(fd, &initial, sizeof(initial)) == (ssize_t)sizeof(initial) ? posix_sem_map(fd) : SEM_FAILED; + close_keeping_errno(fd); + if (sem != SEM_FAILED && renameat2(AT_FDCWD, temp, AT_FDCWD, path, RENAME_NOREPLACE) == 0) return sem; + int saved = errno; + if (sem != SEM_FAILED) sem_close(sem); + unlink(temp); + errno = saved; + if (errno != EEXIST || (oflag & O_EXCL)) return SEM_FAILED; + } +} + +int sem_close(sem_t *sem) { + posix_sems_hold(); + struct posix_sem **link = &g_posix_sems; + while (*link && (*link)->addr != sem) link = &(*link)->next; + struct posix_sem *e = *link; + if (e && --e->refs == 0) { + *link = e->next; + munmap(e->addr, sizeof(sem_t)); + free(e); + } + posix_sems_unlock(); + if (!e) { errno = EINVAL; return -1; } + return 0; +} + +int sem_unlink(const char *name) { + char path[PATH_MAX]; + if (posix_shm_path(name, "sem.", path, sizeof(path)) < 0) return -1; return unlink(path); } diff --git a/tools/tests/test_native_hook_named_semaphores.py b/tools/tests/test_native_hook_named_semaphores.py new file mode 100644 index 0000000000..09abea076b --- /dev/null +++ b/tools/tests/test_native_hook_named_semaphores.py @@ -0,0 +1,159 @@ +from pathlib import Path +import os +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" + +PROBE = r""" +#include <errno.h> +#include <fcntl.h> +#include <limits.h> +#include <semaphore.h> +#include <stdio.h> +#include <sys/wait.h> +#include <unistd.h> + +static void show(const char *name, int ok) { printf("%s\t%d\n", name, ok); fflush(stdout); } + +int main(int argc, char **argv) { + const char *name = argv[1]; + sem_t *sem = sem_open(name, O_CREAT | O_EXCL, 0600, 1); + show("create", sem != SEM_FAILED); + show("exclusive", sem_open(name, O_CREAT | O_EXCL, 0600, 1) == SEM_FAILED && errno == EEXIST); + sem_t *again = sem_open(name, O_CREAT, 0600, (unsigned int)SEM_VALUE_MAX + 1); + int value = -1; + show("existing", again == sem && sem_getvalue(again, &value) == 0 && value == 1); + show("too-large", sem_open("/ddsem-absent", O_CREAT, 0600, (unsigned int)SEM_VALUE_MAX + 1) == SEM_FAILED && errno == EINVAL); + show("wait", sem_wait(sem) == 0 && sem_trywait(again) == -1 && errno == EAGAIN); + pid_t child = fork(); + if (child == 0) { + sem_t *other = sem_open(name, 0); + _exit(other != SEM_FAILED && sem_post(other) == 0 && sem_close(other) == 0 ? 0 : 1); + } + int status = 0; + waitpid(child, &status, 0); + show("shared", WIFEXITED(status) && WEXITSTATUS(status) == 0 && sem_trywait(sem) == 0); + show("close", sem_close(again) == 0 && sem_post(sem) == 0 && sem_close(sem) == 0 && sem_close(sem) == -1 && errno == EINVAL); + show("unlink", sem_unlink(name) == 0); + show("gone", sem_open(name, 0) == SEM_FAILED && errno == ENOENT); + return 0; +} +""" + +KEEP = r""" +#include <fcntl.h> +#include <semaphore.h> +int main(int argc, char **argv) { return sem_open(argv[1], O_CREAT | O_EXCL, 0640, 3) == SEM_FAILED; } +""" + +FORKER = r""" +#include <fcntl.h> +#include <pthread.h> +#include <semaphore.h> +#include <stdio.h> +#include <sys/wait.h> +#include <unistd.h> + +static const char *name; +static _Atomic int done; + +static void *churn(void *arg) { + while (!done) { + sem_t *sem = sem_open(name, O_CREAT, 0600, 0); + if (sem != SEM_FAILED) sem_close(sem); + } + return arg; +} + +int main(int argc, char **argv) { + name = argv[1]; + pthread_t thread; + if (pthread_create(&thread, NULL, churn, NULL) != 0) return 1; + int finished = 0; + for (int i = 0; i < 200; i++) { + pid_t pid = fork(); + if (pid < 0) break; + if (pid == 0) { + alarm(10); + sem_t *sem = sem_open(name, O_CREAT, 0600, 0); + _exit(sem == SEM_FAILED || sem_close(sem) != 0); + } + int status; + if (waitpid(pid, &status, 0) == pid && WIFEXITED(status) && WEXITSTATUS(status) == 0) finished++; + } + done = 1; + pthread_join(thread, NULL); + sem_unlink(name); + printf("finished\t%d\n", finished); + return 0; +} +""" + +CALLS = ("create", "exclusive", "existing", "too-large", "wait", "shared", "close", "unlink", "gone") + + +class NativeHookNamedSemaphoresTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + cls.tmp = tempfile.TemporaryDirectory(dir="/tmp") + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "probe.c").write_text(PROBE) + cls.probe = tmp / "probe" + subprocess.run([cls.cc, "-O1", "-pthread", "-o", str(cls.probe), str(tmp / "probe.c")], check=True) + cls.shm = tmp / "root/tmp/shm" + cls.shm.mkdir(parents=True) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def run_hooked(self, program, *args): + hook_env = {"DDNATV_ROOT": str(self.shm.parent.parent), "LD_PRELOAD": str(self.hook)} + env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"} + if self.prefix: + cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] + else: + cmd = [] + env.update(hook_env) + out = subprocess.run(cmd + [str(program), *args], env=env, capture_output=True, text=True, timeout=120) + self.assertEqual(out.returncode, 0, out.stderr) + return dict(line.split("\t") for line in out.stdout.splitlines()) + + def test_a_named_semaphore_lives_in_the_rootfs_and_is_shared_between_processes(self): + name = f"/ddsem-{os.getpid()}" + self.assertEqual({call: "1" for call in CALLS}, self.run_hooked(self.probe, name)) + self.assertFalse(Path(f"/dev/shm/sem.{name[1:]}").exists()) + self.assertEqual([], list(self.shm.iterdir())) + + def test_a_child_forked_while_another_thread_opens_a_semaphore_can_open_one(self): + source = self.probe.with_name("forker.c") + source.write_text(FORKER) + forker = self.probe.with_name("forker") + subprocess.run([self.cc, "-O1", "-pthread", "-o", str(forker), str(source)], check=True) + self.assertEqual({"finished": "200"}, self.run_hooked(forker, f"/ddsem-fork-{os.getpid()}")) + + def test_a_created_semaphore_keeps_its_name_and_mode(self): + name = f"ddsem-kept-{os.getpid()}" + source = self.probe.with_name("keep.c") + source.write_text(KEEP) + keep = self.probe.with_name("keep") + subprocess.run([self.cc, "-O1", "-pthread", "-o", str(keep), str(source)], check=True) + self.run_hooked(keep, name) + made = self.shm / f"sem.{name}" + self.addCleanup(made.unlink) + umask = os.umask(0) + os.umask(umask) + self.assertEqual([made.name], [p.name for p in self.shm.iterdir()]) + self.assertEqual(0o640 & ~umask, made.stat().st_mode & 0o777) + +if __name__ == "__main__": + unittest.main() From 5f2699e56b59d7abccb396d830e7e39e262c5f10 Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Mon, 23 Nov 2026 23:41:42 -0500 Subject: [PATCH 088/141] fix(fex): x86 programs see the session's identity from getuid and its relatives (#3104) * fix(fex): x86 programs see the session's identity from getuid and its relatives * fix(hook): getresuid and getresgid keep EFAULT for a missing pointer * fix(hook): getresuid and getresgid return EFAULT for any pointer the kernel cannot write * fix(hook): getgroups returns EFAULT for a list the kernel cannot write --- .../0016-identity-syscalls-through-libc.patch | 106 +++++++++++++ tools/nativeguest/hook/identity.c | 2 +- tools/nativeguest/hook/privileged.c | 52 ++---- tools/tests/test_fex_identity_syscalls.py | 148 ++++++++++++++++++ 4 files changed, 271 insertions(+), 37 deletions(-) create mode 100644 tools/fex/patches/0016-identity-syscalls-through-libc.patch create mode 100644 tools/tests/test_fex_identity_syscalls.py diff --git a/tools/fex/patches/0016-identity-syscalls-through-libc.patch b/tools/fex/patches/0016-identity-syscalls-through-libc.patch new file mode 100644 index 0000000000..3823e28e1d --- /dev/null +++ b/tools/fex/patches/0016-identity-syscalls-through-libc.patch @@ -0,0 +1,106 @@ +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp +index 4c3be85..e287cd2 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp +@@ -209,6 +209,13 @@ uint64_t SyscallPassthrough7(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, + } + #endif + ++template<int syscall_num> ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough0(FEXCore::Core::CpuStateFrame* Frame) { ++ uint64_t Result = ::syscall(syscall_num); ++ SYSCALL_ERRNO(); ++} ++ + template<int syscall_num> + requires (syscall_num != -1) + uint64_t SyscallPathPassthrough1(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1) { +@@ -278,29 +285,29 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(chdir, SyscallPathPassthrough1<SYSCALL_DEF(chdir)>); + REGISTER_SYSCALL_IMPL(fchdir, SyscallPassthrough1<SYSCALL_DEF(fchdir)>); + REGISTER_SYSCALL_IMPL(fchmod, SyscallPassthrough2<SYSCALL_DEF(fchmod)>); +- REGISTER_SYSCALL_IMPL(fchown, SyscallPassthrough3<SYSCALL_DEF(fchown)>); ++ REGISTER_SYSCALL_IMPL(fchown, SyscallPathPassthrough3<SYSCALL_DEF(fchown)>); + REGISTER_SYSCALL_IMPL(umask, SyscallPassthrough1<SYSCALL_DEF(umask)>); +- REGISTER_SYSCALL_IMPL(getuid, SyscallPassthrough0<SYSCALL_DEF(getuid)>); ++ REGISTER_SYSCALL_IMPL(getuid, SyscallPathPassthrough0<SYSCALL_DEF(getuid)>); + REGISTER_SYSCALL_IMPL(syslog, SyscallPassthrough3<SYSCALL_DEF(syslog)>); +- REGISTER_SYSCALL_IMPL(getgid, SyscallPassthrough0<SYSCALL_DEF(getgid)>); +- REGISTER_SYSCALL_IMPL(setuid, SyscallPassthrough1<SYSCALL_DEF(setuid)>); +- REGISTER_SYSCALL_IMPL(setgid, SyscallPassthrough1<SYSCALL_DEF(setgid)>); +- REGISTER_SYSCALL_IMPL(geteuid, SyscallPassthrough0<SYSCALL_DEF(geteuid)>); +- REGISTER_SYSCALL_IMPL(getegid, SyscallPassthrough0<SYSCALL_DEF(getegid)>); ++ REGISTER_SYSCALL_IMPL(getgid, SyscallPathPassthrough0<SYSCALL_DEF(getgid)>); ++ REGISTER_SYSCALL_IMPL(setuid, SyscallPathPassthrough1<SYSCALL_DEF(setuid)>); ++ REGISTER_SYSCALL_IMPL(setgid, SyscallPathPassthrough1<SYSCALL_DEF(setgid)>); ++ REGISTER_SYSCALL_IMPL(geteuid, SyscallPathPassthrough0<SYSCALL_DEF(geteuid)>); ++ REGISTER_SYSCALL_IMPL(getegid, SyscallPathPassthrough0<SYSCALL_DEF(getegid)>); + REGISTER_SYSCALL_IMPL(setpgid, SyscallPassthrough2<SYSCALL_DEF(setpgid)>); + REGISTER_SYSCALL_IMPL(getppid, SyscallPassthrough0<SYSCALL_DEF(getppid)>); + REGISTER_SYSCALL_IMPL(setsid, SyscallPassthrough0<SYSCALL_DEF(setsid)>); +- REGISTER_SYSCALL_IMPL(setreuid, SyscallPassthrough2<SYSCALL_DEF(setreuid)>); +- REGISTER_SYSCALL_IMPL(setregid, SyscallPassthrough2<SYSCALL_DEF(setregid)>); +- REGISTER_SYSCALL_IMPL(getgroups, SyscallPassthrough2<SYSCALL_DEF(getgroups)>); +- REGISTER_SYSCALL_IMPL(setgroups, SyscallPassthrough2<SYSCALL_DEF(setgroups)>); +- REGISTER_SYSCALL_IMPL(setresuid, SyscallPassthrough3<SYSCALL_DEF(setresuid)>); +- REGISTER_SYSCALL_IMPL(getresuid, SyscallPassthrough3<SYSCALL_DEF(getresuid)>); +- REGISTER_SYSCALL_IMPL(setresgid, SyscallPassthrough3<SYSCALL_DEF(setresgid)>); +- REGISTER_SYSCALL_IMPL(getresgid, SyscallPassthrough3<SYSCALL_DEF(getresgid)>); ++ REGISTER_SYSCALL_IMPL(setreuid, SyscallPathPassthrough2<SYSCALL_DEF(setreuid)>); ++ REGISTER_SYSCALL_IMPL(setregid, SyscallPathPassthrough2<SYSCALL_DEF(setregid)>); ++ REGISTER_SYSCALL_IMPL(getgroups, SyscallPathPassthrough2<SYSCALL_DEF(getgroups)>); ++ REGISTER_SYSCALL_IMPL(setgroups, SyscallPathPassthrough2<SYSCALL_DEF(setgroups)>); ++ REGISTER_SYSCALL_IMPL(setresuid, SyscallPathPassthrough3<SYSCALL_DEF(setresuid)>); ++ REGISTER_SYSCALL_IMPL(getresuid, SyscallPathPassthrough3<SYSCALL_DEF(getresuid)>); ++ REGISTER_SYSCALL_IMPL(setresgid, SyscallPathPassthrough3<SYSCALL_DEF(setresgid)>); ++ REGISTER_SYSCALL_IMPL(getresgid, SyscallPathPassthrough3<SYSCALL_DEF(getresgid)>); + REGISTER_SYSCALL_IMPL(getpgid, SyscallPassthrough1<SYSCALL_DEF(getpgid)>); +- REGISTER_SYSCALL_IMPL(setfsuid, SyscallPassthrough1<SYSCALL_DEF(setfsuid)>); +- REGISTER_SYSCALL_IMPL(setfsgid, SyscallPassthrough1<SYSCALL_DEF(setfsgid)>); ++ REGISTER_SYSCALL_IMPL(setfsuid, SyscallPathPassthrough1<SYSCALL_DEF(setfsuid)>); ++ REGISTER_SYSCALL_IMPL(setfsgid, SyscallPathPassthrough1<SYSCALL_DEF(setfsgid)>); + REGISTER_SYSCALL_IMPL(getsid, SyscallPassthrough1<SYSCALL_DEF(getsid)>); + REGISTER_SYSCALL_IMPL(capget, SyscallPassthrough2<SYSCALL_DEF(capget)>); + REGISTER_SYSCALL_IMPL(capset, SyscallPassthrough2<SYSCALL_DEF(capset)>); +@@ -537,23 +544,23 @@ namespace x64 { + namespace x32 { + void RegisterPassthrough(FEX::HLE::SyscallHandler* Handler) { + RegisterCommon(Handler); +- REGISTER_SYSCALL_IMPL_X32(getuid32, SyscallPassthrough0<SYSCALL_DEF(getuid)>); +- REGISTER_SYSCALL_IMPL_X32(getgid32, SyscallPassthrough0<SYSCALL_DEF(getgid)>); +- REGISTER_SYSCALL_IMPL_X32(geteuid32, SyscallPassthrough0<SYSCALL_DEF(geteuid)>); +- REGISTER_SYSCALL_IMPL_X32(getegid32, SyscallPassthrough0<SYSCALL_DEF(getegid)>); +- REGISTER_SYSCALL_IMPL_X32(setreuid32, SyscallPassthrough2<SYSCALL_DEF(setreuid)>); +- REGISTER_SYSCALL_IMPL_X32(setregid32, SyscallPassthrough2<SYSCALL_DEF(setregid)>); +- REGISTER_SYSCALL_IMPL_X32(getgroups32, SyscallPassthrough2<SYSCALL_DEF(getgroups)>); +- REGISTER_SYSCALL_IMPL_X32(setgroups32, SyscallPassthrough2<SYSCALL_DEF(setgroups)>); +- REGISTER_SYSCALL_IMPL_X32(fchown32, SyscallPassthrough3<SYSCALL_DEF(fchown)>); +- REGISTER_SYSCALL_IMPL_X32(setresuid32, SyscallPassthrough3<SYSCALL_DEF(setresuid)>); +- REGISTER_SYSCALL_IMPL_X32(getresuid32, SyscallPassthrough3<SYSCALL_DEF(getresuid)>); +- REGISTER_SYSCALL_IMPL_X32(setresgid32, SyscallPassthrough3<SYSCALL_DEF(setresgid)>); +- REGISTER_SYSCALL_IMPL_X32(getresgid32, SyscallPassthrough3<SYSCALL_DEF(getresgid)>); +- REGISTER_SYSCALL_IMPL_X32(setuid32, SyscallPassthrough1<SYSCALL_DEF(setuid)>); +- REGISTER_SYSCALL_IMPL_X32(setgid32, SyscallPassthrough1<SYSCALL_DEF(setgid)>); +- REGISTER_SYSCALL_IMPL_X32(setfsuid32, SyscallPassthrough1<SYSCALL_DEF(setfsuid)>); +- REGISTER_SYSCALL_IMPL_X32(setfsgid32, SyscallPassthrough1<SYSCALL_DEF(setfsgid)>); ++ REGISTER_SYSCALL_IMPL_X32(getuid32, SyscallPathPassthrough0<SYSCALL_DEF(getuid)>); ++ REGISTER_SYSCALL_IMPL_X32(getgid32, SyscallPathPassthrough0<SYSCALL_DEF(getgid)>); ++ REGISTER_SYSCALL_IMPL_X32(geteuid32, SyscallPathPassthrough0<SYSCALL_DEF(geteuid)>); ++ REGISTER_SYSCALL_IMPL_X32(getegid32, SyscallPathPassthrough0<SYSCALL_DEF(getegid)>); ++ REGISTER_SYSCALL_IMPL_X32(setreuid32, SyscallPathPassthrough2<SYSCALL_DEF(setreuid)>); ++ REGISTER_SYSCALL_IMPL_X32(setregid32, SyscallPathPassthrough2<SYSCALL_DEF(setregid)>); ++ REGISTER_SYSCALL_IMPL_X32(getgroups32, SyscallPathPassthrough2<SYSCALL_DEF(getgroups)>); ++ REGISTER_SYSCALL_IMPL_X32(setgroups32, SyscallPathPassthrough2<SYSCALL_DEF(setgroups)>); ++ REGISTER_SYSCALL_IMPL_X32(fchown32, SyscallPathPassthrough3<SYSCALL_DEF(fchown)>); ++ REGISTER_SYSCALL_IMPL_X32(setresuid32, SyscallPathPassthrough3<SYSCALL_DEF(setresuid)>); ++ REGISTER_SYSCALL_IMPL_X32(getresuid32, SyscallPathPassthrough3<SYSCALL_DEF(getresuid)>); ++ REGISTER_SYSCALL_IMPL_X32(setresgid32, SyscallPathPassthrough3<SYSCALL_DEF(setresgid)>); ++ REGISTER_SYSCALL_IMPL_X32(getresgid32, SyscallPathPassthrough3<SYSCALL_DEF(getresgid)>); ++ REGISTER_SYSCALL_IMPL_X32(setuid32, SyscallPathPassthrough1<SYSCALL_DEF(setuid)>); ++ REGISTER_SYSCALL_IMPL_X32(setgid32, SyscallPathPassthrough1<SYSCALL_DEF(setgid)>); ++ REGISTER_SYSCALL_IMPL_X32(setfsuid32, SyscallPathPassthrough1<SYSCALL_DEF(setfsuid)>); ++ REGISTER_SYSCALL_IMPL_X32(setfsgid32, SyscallPathPassthrough1<SYSCALL_DEF(setfsgid)>); + REGISTER_SYSCALL_IMPL_X32(sendfile64, SyscallPassthrough4<SYSCALL_DEF(sendfile)>); + REGISTER_SYSCALL_IMPL_X32(clock_gettime64, SyscallPassthrough2<SYSCALL_DEF(clock_gettime)>); + REGISTER_SYSCALL_IMPL_X32(clock_settime64, SyscallPassthrough2<SYSCALL_DEF(clock_settime)>); diff --git a/tools/nativeguest/hook/identity.c b/tools/nativeguest/hook/identity.c index 9599d7e0b2..ab48039d9d 100644 --- a/tools/nativeguest/hook/identity.c +++ b/tools/nativeguest/hook/identity.c @@ -21,7 +21,7 @@ int setresuid(uid_t ruid, uid_t euid, uid_t suid) { (void)ruid; (void)euid; (voi int setresgid(gid_t rgid, gid_t egid, gid_t sgid) { (void)rgid; (void)egid; (void)sgid; return 0; } int getgroups(int size, gid_t list[]) { - if (size > 0 && list != NULL) list[0] = 0; + if (size > 0 && list != NULL && syscall(__NR_getresgid, list, list, list) != 0) return -1; return 1; } // What programs built with _FORTIFY_SOURCE call when the buffer's size is known (the check is diff --git a/tools/nativeguest/hook/privileged.c b/tools/nativeguest/hook/privileged.c index d5639b450e..159f330716 100644 --- a/tools/nativeguest/hook/privileged.c +++ b/tools/nativeguest/hook/privileged.c @@ -526,6 +526,12 @@ static long nested_path_syscall(long number, unsigned long dirfd, unsigned long return call_orig_syscall(number, dirfd, (unsigned long)path, arg3, arg4, 0, 0); } +static long fake_root_ids(long number, unsigned int *real, unsigned int *effective, unsigned int *saved) { + long rc = call_orig_syscall(number, (unsigned long)real, (unsigned long)effective, (unsigned long)saved, 0, 0, 0); + if (rc == 0) *real = *effective = *saved = 0; + return rc; +} + long syscall(long number, ...) { va_list ap; va_start(ap, number); @@ -877,48 +883,22 @@ long syscall(long number, ...) { if (number == __NR_getegid32) return 0; #endif #if defined(__NR_getresuid) - if (number == __NR_getresuid) { - uid_t *ruid = (uid_t *)arg1; - uid_t *euid = (uid_t *)arg2; - uid_t *suid = (uid_t *)arg3; - if (ruid) *ruid = 0; - if (euid) *euid = 0; - if (suid) *suid = 0; - return 0; - } + if (number == __NR_getresuid) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3); #endif #if defined(__NR_getresuid32) - if (number == __NR_getresuid32) { - uid_t *ruid = (uid_t *)arg1; - uid_t *euid = (uid_t *)arg2; - uid_t *suid = (uid_t *)arg3; - if (ruid) *ruid = 0; - if (euid) *euid = 0; - if (suid) *suid = 0; - return 0; - } + if (number == __NR_getresuid32) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3); #endif #if defined(__NR_getresgid) - if (number == __NR_getresgid) { - gid_t *rgid = (gid_t *)arg1; - gid_t *egid = (gid_t *)arg2; - gid_t *sgid = (gid_t *)arg3; - if (rgid) *rgid = 0; - if (egid) *egid = 0; - if (sgid) *sgid = 0; - return 0; - } + if (number == __NR_getresgid) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3); #endif #if defined(__NR_getresgid32) - if (number == __NR_getresgid32) { - gid_t *rgid = (gid_t *)arg1; - gid_t *egid = (gid_t *)arg2; - gid_t *sgid = (gid_t *)arg3; - if (rgid) *rgid = 0; - if (egid) *egid = 0; - if (sgid) *sgid = 0; - return 0; - } + if (number == __NR_getresgid32) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3); +#endif +#if defined(__NR_getgroups) + if (number == __NR_getgroups) return (long)getgroups((int)arg1, (gid_t *)arg2); +#endif +#if defined(__NR_fchown) + if (number == __NR_fchown) return (long)fchown((int)arg1, (uid_t)arg2, (gid_t)arg3); #endif return call_orig_syscall(number, arg1, arg2, arg3, arg4, arg5, arg6); diff --git a/tools/tests/test_fex_identity_syscalls.py b/tools/tests/test_fex_identity_syscalls.py new file mode 100644 index 0000000000..3c2101c824 --- /dev/null +++ b/tools/tests/test_fex_identity_syscalls.py @@ -0,0 +1,148 @@ +import os +import re +import subprocess +import tempfile +import unittest +from pathlib import Path + +from tools.tests.test_usr2_preload import runner + +REPO = Path(__file__).resolve().parents[2] +PATCH = REPO / "tools/fex/patches/0016-identity-syscalls-through-libc.patch" +HOOK = REPO / "tools/nativeguest/hook/privileged.c" +HOOK_BUILD = REPO / "tools/nativeguest/build.sh" +PASSTHROUGH = "Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp" +REGISTER = re.compile(r"REGISTER_SYSCALL_IMPL(?:_X64|_X32)?\((\w+), (\w+?)(\d)<SYSCALL_DEF\((\w+)\)>\);") +IDENTITY = {"getuid", "getgid", "geteuid", "getegid", "setuid", "setgid", "setreuid", "setregid", "getgroups", + "setgroups", "setresuid", "getresuid", "setresgid", "getresgid", "setfsuid", "setfsgid", "fchown"} + + +def changed(): + removed, added = {}, {} + for line in PATCH.read_text().splitlines(): + found = REGISTER.search(line) + if found and line[:1] in "+-": + (added if line[0] == "+" else removed)[found.group(1)] = found.groups()[1:] + return removed, added + + +class FexIdentitySyscallsTest(unittest.TestCase): + def test_only_the_passthrough_table_changes(self): + self.assertEqual(re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M), [PASSTHROUGH]) + + def test_each_identity_syscall_keeps_its_arity_and_goes_through_libc(self): + removed, added = changed() + self.assertEqual(sorted(removed), sorted(added)) + self.assertEqual(IDENTITY, {number for _, _, number in added.values()}) + for name, (template, arity, number) in added.items(): + with self.subTest(name=name): + self.assertEqual(("SyscallPassthrough", arity, number), removed[name]) + self.assertEqual("SyscallPathPassthrough", template) + + def test_the_new_template_calls_the_libc_syscall(self): + added = [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")] + self.assertEqual([" uint64_t Result = ::syscall(syscall_num);"], [line for line in added if "Result =" in line]) + self.assertFalse([line for line in added if line.strip().startswith(("//", "/*"))]) + + def test_every_routed_syscall_is_answered_by_the_hook(self): + hook = HOOK.read_text() + for number in IDENTITY: + with self.subTest(number=number): + self.assertIn(f"number == __NR_{number})", hook) + + +PROBE = r""" +#include <errno.h> +#include <fcntl.h> +#include <stdio.h> +#include <sys/mman.h> +#include <sys/syscall.h> +#include <unistd.h> + +int main(int argc, char **argv) { + unsigned int r = 7, e = 7, s = 7; + long rc = syscall(SYS_getresuid, &r, &e, &s); + printf("getresuid %ld %u %u %u\n", rc, r, e, s); + errno = 0; + rc = syscall(SYS_getresuid, NULL, &e, &s); + printf("getresuid-null %ld %d\n", rc, errno); + r = e = s = 7; + rc = syscall(SYS_getresgid, &r, &e, &s); + printf("getresgid %ld %u %u %u\n", rc, r, e, s); + errno = 0; + rc = syscall(SYS_getresgid, &r, NULL, &s); + printf("getresgid-null %ld %d\n", rc, errno); + unsigned int *locked = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + errno = 0; + rc = syscall(SYS_getresuid, &r, &e, locked); + printf("getresuid-readonly %ld %d\n", rc, errno); + errno = 0; + rc = syscall(SYS_getresgid, locked, &e, &s); + printf("getresgid-readonly %ld %d\n", rc, errno); + gid_t groups[8]; + rc = syscall(SYS_getgroups, 8, groups); + printf("getgroups %ld %u\n", rc, rc > 0 ? groups[0] : 99u); + errno = 0; + rc = syscall(SYS_getgroups, 8, locked); + printf("getgroups-readonly %ld %d\n", rc, errno); + int fd = open(argv[1], O_RDONLY); + printf("fchown %ld\n", syscall(SYS_fchown, fd, 4321, 4321)); + printf("getuid %ld\n", syscall(SYS_getuid)); + return 0; +} +""" + + +class NativeHookIdentityTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + cls.tmp = tempfile.TemporaryDirectory() + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "probe.c").write_text(PROBE) + subprocess.run([cls.cc, "-O1", "-o", str(tmp / "probe"), str(tmp / "probe.c")], check=True) + (tmp / "root").mkdir() + cls.file = tmp / "owned" + cls.file.write_text("") + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def probe(self): + hook_env = {"DDNATV_ROOT": str(Path(self.tmp.name) / "root"), "LD_PRELOAD": str(self.hook)} + env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"} + if self.prefix: + cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] + else: + cmd = [] + env.update(hook_env) + out = subprocess.run(cmd + [str(Path(self.tmp.name) / "probe"), str(self.file)], env=env, + capture_output=True, text=True, timeout=120) + self.assertEqual(0, out.returncode, out.stderr) + return {line.split(" ", 1)[0]: line.split(" ", 1)[1] for line in out.stdout.splitlines()} + + def test_the_hook_answers_identity_syscalls_as_root(self): + result = self.probe() + self.assertEqual("0 0 0 0", result["getresuid"]) + self.assertEqual("0 0 0 0", result["getresgid"]) + self.assertEqual("1 0", result["getgroups"]) + self.assertEqual("-1 14", result["getgroups-readonly"]) + self.assertEqual("0", result["fchown"]) + self.assertEqual("0", result["getuid"]) + + def test_a_missing_pointer_still_faults(self): + result = self.probe() + self.assertEqual("-1 14", result["getresuid-null"]) + self.assertEqual("-1 14", result["getresgid-null"]) + self.assertEqual("-1 14", result["getresuid-readonly"]) + self.assertEqual("-1 14", result["getresgid-readonly"]) + self.assertEqual(os.stat(self.file).st_uid, os.getuid()) + + +if __name__ == "__main__": + unittest.main() From e349d2544e44c7368310f8a90f3ef4b32d85137d Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Mon, 23 Nov 2026 23:42:04 -0500 Subject: [PATCH 089/141] fix(nativeguest): a script interpreter reached through a bind runs as a guest program (#3112) * fix(nativeguest): a script interpreter reached through a bind runs as a guest program A Flatpak runtime binds its own /usr outside the sandbox root, so the hook took #!/usr/bin/bash there for an Android program and handed it to the kernel, which failed with "bad interpreter". An interpreter whose guest path is a bind now starts like any guest program. * Native hook: keep Android interpreters a bind reaches on the host * Native hook: match the root of an interpreter on a folder boundary --- tools/nativeguest/hook/exec.c | 4 +-- tools/nativeguest/hook/exec_probe.c | 12 ++++--- tools/tests/test_native_hook_ldso_spawn.py | 41 +++++++++++++++++++++- 3 files changed, 50 insertions(+), 7 deletions(-) diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index 664b0beedf..e9c115d477 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -476,7 +476,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e return -1; } int ret; - if (is_host_interpreter(rewritten_interp)) { + if (is_host_interpreter(interp, rewritten_interp)) { char **sys_env = clean_env_for_system(envp); ret = run_execve(orig_execve, rewritten_interp, new_argv, sys_env); int saved_errno = errno; @@ -829,7 +829,7 @@ static int spawn_script(pid_t *pid, const char *script, struct exec_probe *probe char **new_argv = build_script_argv(rewritten_interp, interp_arg, script, argv); if (!new_argv) return ENOMEM; int ret; - if (is_host_interpreter(rewritten_interp)) { + if (is_host_interpreter(interp, rewritten_interp)) { orig_posix_spawn_f_type orig_posix_spawn = real_posix_spawn(); char **sys_env = clean_env_for_system(envp); ret = orig_posix_spawn ? orig_posix_spawn(pid, rewritten_interp, file_actions, attrp, new_argv, sys_env) : ENOSYS; diff --git a/tools/nativeguest/hook/exec_probe.c b/tools/nativeguest/hook/exec_probe.c index f877175e58..74e0c2875c 100644 --- a/tools/nativeguest/hook/exec_probe.c +++ b/tools/nativeguest/hook/exec_probe.c @@ -966,10 +966,14 @@ static void parse_shebang(char *hdr, char **interp, char **interp_arg) { *interp_arg = arg; } -// Interpreters outside the rootfs (Android's /system/bin/sh) run with Android's environment. -static int is_host_interpreter(const char *interp) { - return strncmp(interp, "/system", 7) == 0 || - (g_ddnatv_root[0] != '\0' && strncmp(interp, g_ddnatv_root, g_ddnatv_root_len) != 0); +// Interpreters outside the rootfs and its binds (Android's /system/bin/sh) run with Android's environment. +static int is_host_interpreter(const char *interp, const char *rewritten) { + if (strncmp(rewritten, "/system", 7) == 0) return 1; + if (g_ddnatv_root[0] == '\0' || get_rootfs_subpath(rewritten)) return 0; + if (!is_mapped_guest_path(interp)) return 1; + struct exec_probe probe; + probe_exec_file(rewritten, &probe); + return probe.android_interp; } // argv for running `script` with its interpreter: interp [arg] script args... (the script's own diff --git a/tools/tests/test_native_hook_ldso_spawn.py b/tools/tests/test_native_hook_ldso_spawn.py index 43b810344a..8c1ad2575e 100644 --- a/tools/tests/test_native_hook_ldso_spawn.py +++ b/tools/tests/test_native_hook_ldso_spawn.py @@ -10,6 +10,9 @@ from tools.tests.test_usr2_preload import runner HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" GUEST_LDSO = "/usr/lib/ld-linux-aarch64.so.1" GUEST_TOOL = "/usr/local/bin/tool" +BOUND_DIR = "/opt/runtime" +ANDROID_DIR = "/opt/android" +HOST_SHELL = "/data/local/tmp/droiddeck-hook-probe-sh" RECORDER = r""" #define _GNU_SOURCE @@ -102,13 +105,29 @@ class NativeHookLdsoSpawnTest(unittest.TestCase): shutil.copy(source, host) host.chmod(0o755) (cls.root / "usr/lib/aarch64-linux-gnu").mkdir(parents=True, exist_ok=True) + cls.runtime = tmp / "runtime" + cls.runtime.mkdir() + shutil.copy(cls.probe, cls.runtime / "bash") + (cls.runtime / "bash").chmod(0o755) + cls.android = tmp / "root-android" + cls.android.mkdir() + subprocess.run([cls.cc, "-O1", "-Wl,--dynamic-linker=/system/bin/linker64", "-o", str(cls.android / "sh"), + str(tmp / "probe.c")], check=True) + for name, interpreter in (("bound.sh", f"{BOUND_DIR}/bash"), ("host.sh", HOST_SHELL), + ("android.sh", f"{ANDROID_DIR}/sh")): + script = cls.root / "opt" / name + script.parent.mkdir(exist_ok=True) + script.write_text(f"#!{interpreter}\n") + script.chmod(0o755) @classmethod def tearDownClass(cls): cls.tmp.cleanup() - def call(self, how, *argv): + def call(self, how, *argv, binds=None): hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook}:{self.recorder}"} + if binds: + hook_env["DDNATV_BINDS"] = binds env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_EXEC", "LD_LIBRARY_PATH")} if self.prefix: cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] @@ -158,6 +177,26 @@ class NativeHookLdsoSpawnTest(unittest.TestCase): self.call(how, GUEST_LDSO, "--list", GUEST_TOOL) self.assertEqual([], self.library_paths) + def test_a_script_interpreter_from_a_bind_runs_as_a_guest_program(self): + for how in ("exec", "spawn"): + with self.subTest(how=how): + call = self.call(how, "/opt/bound.sh", "x", binds=f"{self.runtime}:{BOUND_DIR}") + self.assertEqual(str(self.root / GUEST_LDSO.lstrip("/")), call[0]) + self.assertEqual([str(self.runtime / "bash"), str(self.root / "opt/bound.sh"), "x"], call[-3:]) + + def test_a_script_interpreter_outside_the_rootfs_and_its_binds_stays_on_the_host(self): + for how in ("exec", "spawn"): + with self.subTest(how=how): + call = self.call(how, "/opt/host.sh", "x", binds=f"{self.runtime}:{BOUND_DIR}") + self.assertEqual([HOST_SHELL, HOST_SHELL, str(self.root / "opt/host.sh"), "x"], call) + + def test_an_android_interpreter_reached_through_a_bind_stays_on_the_host(self): + sh = str(self.android / "sh") + for how in ("exec", "spawn"): + with self.subTest(how=how): + call = self.call(how, "/opt/android.sh", "x", binds=f"{self.android}:{ANDROID_DIR}") + self.assertEqual([sh, sh, str(self.root / "opt/android.sh"), "x"], call) + if __name__ == "__main__": unittest.main() From a03ec8eb5717ecae2d98f19d7186a3858e445a60 Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Tue, 24 Nov 2026 00:12:02 -0500 Subject: [PATCH 090/141] Session preload: leave programs a Chromium app starts from its own folder alone (#3121) The browser flags were added to every program beside chrome-sandbox that had no --type switch. Chrome's crash handler is such a program, so it was started with --no-sandbox, rejected it and exited. A Chromium app that starts a program from its own folder already passes that program the arguments it needs, so those programs are left unchanged. Another Chromium app started from it still gets the flags. --- tools/linuxfs/preload/webhelper.c | 21 ++++++++++++++++++++- tools/tests/test_webhelper_preload.py | 16 ++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/tools/linuxfs/preload/webhelper.c b/tools/linuxfs/preload/webhelper.c index 5263b0f464..bbccd890b1 100644 --- a/tools/linuxfs/preload/webhelper.c +++ b/tools/linuxfs/preload/webhelper.c @@ -58,6 +58,25 @@ static int beside_chrome_sandbox(const char *path) { return found; } +static char *folder_of(const char *path) { + char *real = realpath(path, NULL); + char *slash = real ? strrchr(real, '/') : NULL; + if (slash) *slash = 0; + return real; +} + +static int started_by_its_own_app(const char *path) { + char self[4096]; + ssize_t n = readlink("/proc/self/exe", self, sizeof self - 1); + if (n <= 0) return 0; + self[n] = 0; + char *mine = folder_of(self), *theirs = folder_of(path); + int same = mine && theirs && !strcmp(mine, theirs) && beside_chrome_sandbox(self); + free(mine); + free(theirs); + return same; +} + static char *const *chromium_argv(const char *path, char *const argv[], char *const envp[]) { if (!path || !argv || !argv[0]) return argv; int argc = 0, sandbox = 1, ozone = 0; @@ -69,7 +88,7 @@ static char *const *chromium_argv(const char *path, char *const argv[], char *co } const char *display = env_value(envp, "DISPLAY"); int x11 = !ozone && display && *display; - if ((!sandbox && !x11) || !beside_chrome_sandbox(path)) return argv; + if ((!sandbox && !x11) || !beside_chrome_sandbox(path) || started_by_its_own_app(path)) return argv; char **out = calloc((size_t)argc + 3, sizeof *out); if (!out) return argv; int n = 0; diff --git a/tools/tests/test_webhelper_preload.py b/tools/tests/test_webhelper_preload.py index 24e854dbb8..5b530566c1 100644 --- a/tools/tests/test_webhelper_preload.py +++ b/tools/tests/test_webhelper_preload.py @@ -122,6 +122,22 @@ class WebhelperPreloadTest(unittest.TestCase): (root / "bin/app").touch() self.assertEqual(self.argv(str(root / "bin/app")), [str(root / "bin/app"), "--no-sandbox"]) + def test_a_chromium_app_starting_a_program_from_its_own_folder_leaves_it_alone(self): + handler = self.chromium("chrome-app", "chrome_crashpad_handler") + browser = self.tmp / "chrome-app/chrome" + shutil.copy(self.program, browser) + out = subprocess.run([str(browser), handler, "--database=/tmp/x"], env={"TEST_DISPLAY": ":0"}, + capture_output=True, text=True, check=True).stdout.splitlines() + self.assertEqual([handler, "--database=/tmp/x"], out) + + def test_a_chromium_app_starting_another_chromium_app_still_flags_it(self): + other = self.chromium("other-app", "chrome") + editor = self.tmp / "editor-app/code" + self.chromium("editor-app", "code") + shutil.copy(self.program, editor) + out = subprocess.run([str(editor), other], env={}, capture_output=True, text=True, check=True).stdout.splitlines() + self.assertEqual([other, "--no-sandbox"], out) + def test_with_an_x_display_chromium_apps_use_x11(self): chrome = self.chromium("chromium-x11", "chrome") self.assertEqual(self.argv(chrome, "--new-window", display=":0"), From 9b800ceb5ec06fb794a31fdf201e55af83c44acd Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:21:26 -0500 Subject: [PATCH 091/141] feat(build): build_local.sh reuses main CI's prepared components when this tree would prepare the same (#3118) * feat(build): build_local.sh reuses main CI's prepared components when this tree would prepare the same * docs(agents): build_local.sh reuses CI's prepared components * fix(build): reuse only this repository's main artifacts, keyed by artifact id * fix(build): CI reuse verifies before replacing, and declines other NDKs, PulseAudio sources, unregistered inputs and edited submodules * fix(build): CI reuse also declines a VK_INCLUDE override * fix(build): CI reuse also declines a custom build image --- AGENTS.md | 1 + tools/build_local.sh | 539 ++++++++++++++++------------ tools/components/reuse.py | 150 ++++++++ tools/tests/test_component_reuse.py | 93 +++++ 4 files changed, 547 insertions(+), 236 deletions(-) create mode 100644 tools/components/reuse.py create mode 100644 tools/tests/test_component_reuse.py diff --git a/AGENTS.md b/AGENTS.md index 4832415479..494b630d9c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -5,6 +5,7 @@ # 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. diff --git a/tools/build_local.sh b/tools/build_local.sh index ea3ebebbcf..2c76362956 100755 --- a/tools/build_local.sh +++ b/tools/build_local.sh @@ -24,6 +24,7 @@ java_dir="${JAVA_HOME:-/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents [[ -x "$java_dir/bin/java" ]] || java_dir="${HOME}/.local/share/mise/installs/java/temurin-17" [[ "$java_dir" == */homebrew/* ]] && echo "using homebrew java path: $java_dir" [[ "$java_dir" == */mise/* ]] && echo "using mise java path: $java_dir" +requested_image=${DROIDDECK_BUILD_IMAGE:-} . "${repo_root}/tools/docker_platform.sh" image_name=${DROIDDECK_BUILD_IMAGE} build_variant=${DROIDDECK_BUILD_VARIANT:-release} @@ -117,101 +118,6 @@ save_step() { python3 "${repo_root}/tools/docker_preflight.py" "${image_name}" image_id=$(docker image inspect --format '{{.Id}}' "${image_name}") -rm -rf -- "${linuxfs_dir}" -mkdir -p "${linuxfs_dir}" - -git_common=$(git -C "${repo_root}" rev-parse --path-format=absolute --git-common-dir) -docker run --rm --platform "${docker_platform}" \ - --user "$(id -u):$(id -g)" \ - -v "${repo_root}:/src" -v "${git_common}:${git_common}" -w /src "${image_name}" bash -lc ' - set -euo pipefail - d=app/src/main/assets/linuxfs - mkdir -p "$d" - put() { mkdir -p "$(dirname "$2")" && cat "$1" > "$2"; } - aarch64-linux-gnu-g++ -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \ - -pthread -std=c++17 -static-libstdc++ -static-libgcc -Wl,--exclude-libs,ALL \ - -o "$d/libfakeinput.so" app/src/main/cpp/fakeinput_steam.cpp -ldl - aarch64-linux-gnu-strip --strip-unneeded "$d/libfakeinput.so" - aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \ - -o "$d/libddsession.so" tools/linuxfs/preload/*.c -ldl - aarch64-linux-gnu-strip --strip-unneeded "$d/libddsession.so" - aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \ - -o "$d/libddfastpath.so" tools/proot/fastpath/fastpath.c -ldl - aarch64-linux-gnu-strip --strip-unneeded "$d/libddfastpath.so" - bash tools/nativeguest/build.sh "$d/libddnatv-hook.so" - aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -nostdlib -ffreestanding -fno-stack-protector \ - -fno-tree-loop-distribute-patterns -Wl,-z,defs -o "$d/libddaudit.so" tools/proot/fastpath/audit.c - aarch64-linux-gnu-strip --strip-unneeded "$d/libddaudit.so" - aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \ - -o "$d/libssbs.so" tools/linuxfs/ssbs/ssbs_adapter.c -ldl - aarch64-linux-gnu-strip --strip-unneeded "$d/libssbs.so" - mkdir -p "$d/usr/local/lib/droiddeck-xclipse" - aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wextra -Wno-unused-parameter -fvisibility=hidden -pthread \ - -o "$d/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so" tools/linuxfs/xclipse-layer/xclipse_layer.c -ldl - aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so" - install -m644 tools/linuxfs/xclipse-layer/VkLayer_droiddeck_xclipse.json "$d/usr/local/lib/droiddeck-xclipse/" - mkdir -p "$d/usr/local/bin" - external/MaliBridge/scripts/build-client-linux.sh "$d" aarch64-linux-gnu-gcc - aarch64-linux-gnu-gcc -O2 -Wall -o "$d/usr/local/bin/droiddeck-glprobe" tools/venus/glprobe.c -ldl - aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-glprobe" - aarch64-linux-gnu-gcc -O2 -Wall -Wextra -o "$d/usr/local/bin/droiddeck-clipboard" tools/linuxfs/clipboard/clipboard.c -ldl - aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-clipboard" - for script in tools/linuxfs/overlay/usr/local/bin/droiddeck-* tools/linuxfs/overlay/usr/local/bin/steam-compatibility; do - put "$script" "$d/usr/local/bin/$(basename "$script")" - done - for f in tools/linuxfs/overlay/usr/bin/* tools/linuxfs/overlay/usr/bin/steamos-polkit-helpers/*; do - [ -f "$f" ] && put "$f" "$d/${f#tools/linuxfs/overlay/}" - done - put tools/linuxfs/desktop/droiddeck-desktop "$d/usr/local/bin/droiddeck-desktop" - put tools/linuxfs/desktop/droiddeck-gpu "$d/usr/local/bin/droiddeck-gpu" - put tools/linuxfs/desktop/droiddeck-desktop-gpu "$d/usr/local/bin/droiddeck-desktop-gpu" - put tools/linuxfs/desktop/kwin_wayland_wrapper "$d/usr/local/bin/kwin_wayland_wrapper" - put tools/linuxfs/desktop/firefox-droiddeck.js \ - "$d/usr/lib/firefox/defaults/pref/droiddeck.js" - - READELF=aarch64-linux-gnu-readelf bash tools/linuxfs/check-preloads.sh "$d" - ' - -x86_key=$(inputs_hash bullseye tools/linuxfs/build-x86-preloads.sh tools/linuxfs/preload tools/linuxfs/fex \ - app/src/main/cpp/fakeinput_steam.cpp) -x86_stage="${staging_dir}/x86-preloads" -if restore_step x86-preloads "${x86_key}" "${linuxfs_dir}"; then :; else - x86_platform=linux/amd64 - x86_packages="gcc g++ gcc-multilib g++-multilib binutils" - x86_cross=0 - if [[ "${docker_platform}" == linux/arm64 ]]; then - x86_platform=linux/arm64 - x86_packages="gcc-x86-64-linux-gnu g++-x86-64-linux-gnu gcc-i686-linux-gnu g++-i686-linux-gnu libc6-dev-amd64-cross libc6-dev-i386-cross binutils-x86-64-linux-gnu binutils-i686-linux-gnu" - x86_cross=1 - fi - docker run --rm --platform "${x86_platform}" -e X86_CROSS="${x86_cross}" -e X86_PACKAGES="${x86_packages}" \ - -v "${repo_root}:/src" -v "${git_common}:${git_common}" -w /src public.ecr.aws/docker/library/debian:bullseye bash -c ' - set -euo pipefail - printf "deb http://archive.debian.org/debian bullseye main\ndeb http://archive.debian.org/debian-security bullseye-security main\n" > /etc/apt/sources.list - apt-get -o Acquire::Check-Valid-Until=false update -qq - DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends $X86_PACKAGES >/dev/null - tools/linuxfs/build-x86-preloads.sh app/src/main/assets/linuxfs - chown -R '"$(id -u):$(id -g)"' app/src/main/assets/linuxfs - ' - mkdir -p "${x86_stage}" - cp -R "${linuxfs_dir}/x86_64" "${linuxfs_dir}/i386" "${x86_stage}/" - save_step x86-preloads "${x86_key}" "${x86_stage}" -fi - -vr_out="${linuxfs_dir}/usr/local/lib/droiddeck-vr" -vr_key=$(inputs_hash "${image_id} ${ndk_version} ${VK_INCLUDE:-}" tools/vr app/src/main/cpp/waylandcomp/generated/xdg-shell-protocol.c) -if ! restore_step vr "${vr_key}" "${vr_out}"; then - DROIDDECK_BUILD_IMAGE="${image_name}" "${repo_root}/tools/vr/build.sh" "${vr_out}" - save_step vr "${vr_key}" "${vr_out}" -fi - -gpuload_out="${linuxfs_dir}/usr/local/lib/droiddeck-gpuload" -gpuload_key=$(inputs_hash "${image_id} ${ndk_version} ${VK_INCLUDE:-}" tools/gpuload) -if ! restore_step gpuload "${gpuload_key}" "${gpuload_out}"; then - DROIDDECK_BUILD_IMAGE="${image_name}" "${repo_root}/tools/gpuload/build.sh" "${gpuload_out}" - save_step gpuload "${gpuload_key}" "${gpuload_out}" -fi - github_repo=${DROIDDECK_GITHUB_REPOSITORY:-} if [[ -z "${github_repo}" ]]; then origin_url=$(git -C "${repo_root}" remote get-url origin) @@ -228,46 +134,289 @@ if [[ -z "${github_repo}" ]]; then github_repo=${github_repo%.git} fi -cached() { - local sha=$1 name=$2 out - shift 2 - out="${cache_dir}/${sha}-${name}" - if [[ -f "${out}" ]] && printf '%s %s\n' "${sha}" "${out}" | shasum -a 256 -c - >/dev/null 2>&1; then - echo "${out}" - return 0 +ci_components=0 +ci_run= +ci_cache="${cache_dir}/ci-components" +reuse_ci_components() { + [[ "${DROIDDECK_CI_COMPONENTS:-1}" == 1 ]] && command -v gh >/dev/null 2>&1 || return 1 + # CI prepares with the pinned NDK, its own build image and PulseAudio source, and the system Vulkan headers. + . "${repo_root}/tools/ci/toolchains.env" + [[ "${ndk_version}" == "${CI_ANDROID_NDK_VERSION}" && -z "${DROIDDECK_PA13_SOURCE_DIR:-}" && -z "${VK_INCLUDE:-}" \ + && -z "${requested_image}" ]] || return 1 + local base candidates run artifact archive part + base=$(git -C "${repo_root}" merge-base HEAD origin/main 2>/dev/null || true) + # Only runs of this repository's own main: a fork's pull request can also name its branch main. + candidates=$(gh api "repos/${github_repo}/actions/artifacts?name=prepared-components&per_page=100" \ + -q "[.artifacts[] | select(.expired | not) | select(.workflow_run.head_branch == \"main\") + | select(.workflow_run.head_repository_id == .workflow_run.repository_id)] + | sort_by(.workflow_run.head_sha != \"${base}\") | .[:3][] | \"\(.workflow_run.id):\(.id)\"" 2>/dev/null) || return 1 + mkdir -p "${ci_cache}" + # CI keeps these artifacts for 14 days. + find "${ci_cache}" -mindepth 1 -maxdepth 1 -mtime +14 -exec rm -rf {} + + for candidate in ${candidates}; do + run=${candidate%%:*} + artifact=${candidate#*:} + archive="${ci_cache}/${artifact}.tar.gz" + if [[ ! -f "${archive}" ]]; then + part=$(mktemp -d "${ci_cache}/${run}.part.XXXXXX") + if gh run download "${run}" -R "${github_repo}" -n prepared-components -D "${part}" >/dev/null 2>&1; then + mv "${part}/prepared-components.tar.gz" "${archive}" + fi + rm -rf "${part}" + [[ -f "${archive}" ]] || continue + fi + if python3 "${repo_root}/tools/components/reuse.py" "${archive}"; then + ci_run=${run} + return 0 + fi + done + return 1 +} +fetch_ci_xbox() { + local stored="${ci_cache}/${ci_run}-xbox" part + if [[ ! -d "${stored}" ]]; then + part=$(mktemp -d "${ci_cache}/${ci_run}-xbox.part.XXXXXX") + gh run download "${ci_run}" -R "${github_repo}" -n xbox-arm64 -D "${part}" >/dev/null 2>&1 || { rm -rf "${part}"; return 1; } + # rename(2) refuses a non-empty destination, so a copy another build published first wins. + python3 -c 'import os, sys; os.rename(sys.argv[1], sys.argv[2])' "${part}" "${stored}" 2>/dev/null || rm -rf "${part}" fi - rm -f "${out}.part" - out="${out}.part" "$@" >&2 - printf '%s %s\n' "${sha}" "${out}.part" | shasum -a 256 -c - >&2 - mv "${out}.part" "${out}" - echo "${out}" + rm -rf "${xbox_out}" && mkdir -p "${xbox_out}" && cp -R "${stored}/." "${xbox_out}/" } -if [[ -f "${repo_root}/tools/gamescope/release.env" ]]; then - . "${repo_root}/tools/gamescope/release.env" - gamescope_archive=$(cached "${GAMESCOPE_SHA256}" gamescope.tzst \ - bash -c 'gh release download "$0" -R "$1" -p gamescope.tzst -O "$out"' "${GAMESCOPE_TAG}" "${GAMESCOPE_REPO:-${github_repo}}") - zstd -dc "${gamescope_archive}" | tar -xf - -C "${linuxfs_dir}" - test -f "${linuxfs_dir}/usr/local/bin/gamescope" -fi +git_common=$(git -C "${repo_root}" rev-parse --path-format=absolute --git-common-dir) +proot_out="${repo_root}/app/src/main/jniLibs/arm64-v8a" +if reuse_ci_components; then + ci_components=1 + echo "components: every recipe identity matches main CI run ${ci_run}; reusing its prepared components (DROIDDECK_CI_COMPONENTS=0 builds them here)" +else + rm -rf -- "${linuxfs_dir}" + mkdir -p "${linuxfs_dir}" -. "${repo_root}/tools/linuxfs/uruntime.env" -uruntime_binary=$(cached "${URUNTIME_SHA256}" "${URUNTIME_ASSET}" \ - bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "https://github.com/VHSgunzo/uruntime/releases/download/${URUNTIME_VERSION}/${URUNTIME_ASSET}") -mkdir -p "${linuxfs_dir}/usr/local/lib/droiddeck" "${linuxfs_dir}/usr/local/share/licenses/uruntime" -install -m644 "${uruntime_binary}" "${linuxfs_dir}/usr/local/lib/droiddeck/uruntime" -install -m644 "${repo_root}/tools/linuxfs/licenses/uruntime-LICENSE" "${linuxfs_dir}/usr/local/share/licenses/uruntime/LICENSE" + docker run --rm --platform "${docker_platform}" \ + --user "$(id -u):$(id -g)" \ + -v "${repo_root}:/src" -v "${git_common}:${git_common}" -w /src "${image_name}" bash -lc ' + set -euo pipefail + d=app/src/main/assets/linuxfs + mkdir -p "$d" + put() { mkdir -p "$(dirname "$2")" && cat "$1" > "$2"; } + aarch64-linux-gnu-g++ -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \ + -pthread -std=c++17 -static-libstdc++ -static-libgcc -Wl,--exclude-libs,ALL \ + -o "$d/libfakeinput.so" app/src/main/cpp/fakeinput_steam.cpp -ldl + aarch64-linux-gnu-strip --strip-unneeded "$d/libfakeinput.so" + aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \ + -o "$d/libddsession.so" tools/linuxfs/preload/*.c -ldl + aarch64-linux-gnu-strip --strip-unneeded "$d/libddsession.so" + aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \ + -o "$d/libddfastpath.so" tools/proot/fastpath/fastpath.c -ldl + aarch64-linux-gnu-strip --strip-unneeded "$d/libddfastpath.so" + bash tools/nativeguest/build.sh "$d/libddnatv-hook.so" + aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -nostdlib -ffreestanding -fno-stack-protector \ + -fno-tree-loop-distribute-patterns -Wl,-z,defs -o "$d/libddaudit.so" tools/proot/fastpath/audit.c + aarch64-linux-gnu-strip --strip-unneeded "$d/libddaudit.so" + aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \ + -o "$d/libssbs.so" tools/linuxfs/ssbs/ssbs_adapter.c -ldl + aarch64-linux-gnu-strip --strip-unneeded "$d/libssbs.so" + mkdir -p "$d/usr/local/lib/droiddeck-xclipse" + aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wextra -Wno-unused-parameter -fvisibility=hidden -pthread \ + -o "$d/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so" tools/linuxfs/xclipse-layer/xclipse_layer.c -ldl + aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so" + install -m644 tools/linuxfs/xclipse-layer/VkLayer_droiddeck_xclipse.json "$d/usr/local/lib/droiddeck-xclipse/" + mkdir -p "$d/usr/local/bin" + external/MaliBridge/scripts/build-client-linux.sh "$d" aarch64-linux-gnu-gcc + aarch64-linux-gnu-gcc -O2 -Wall -o "$d/usr/local/bin/droiddeck-glprobe" tools/venus/glprobe.c -ldl + aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-glprobe" + aarch64-linux-gnu-gcc -O2 -Wall -Wextra -o "$d/usr/local/bin/droiddeck-clipboard" tools/linuxfs/clipboard/clipboard.c -ldl + aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-clipboard" + for script in tools/linuxfs/overlay/usr/local/bin/droiddeck-* tools/linuxfs/overlay/usr/local/bin/steam-compatibility; do + put "$script" "$d/usr/local/bin/$(basename "$script")" + done + for f in tools/linuxfs/overlay/usr/bin/* tools/linuxfs/overlay/usr/bin/steamos-polkit-helpers/*; do + [ -f "$f" ] && put "$f" "$d/${f#tools/linuxfs/overlay/}" + done + put tools/linuxfs/desktop/droiddeck-desktop "$d/usr/local/bin/droiddeck-desktop" + put tools/linuxfs/desktop/droiddeck-gpu "$d/usr/local/bin/droiddeck-gpu" + put tools/linuxfs/desktop/droiddeck-desktop-gpu "$d/usr/local/bin/droiddeck-desktop-gpu" + put tools/linuxfs/desktop/kwin_wayland_wrapper "$d/usr/local/bin/kwin_wayland_wrapper" + put tools/linuxfs/desktop/firefox-droiddeck.js \ + "$d/usr/lib/firefox/defaults/pref/droiddeck.js" + + READELF=aarch64-linux-gnu-readelf bash tools/linuxfs/check-preloads.sh "$d" + ' + + x86_key=$(inputs_hash bullseye tools/linuxfs/build-x86-preloads.sh tools/linuxfs/preload tools/linuxfs/fex \ + app/src/main/cpp/fakeinput_steam.cpp) + x86_stage="${staging_dir}/x86-preloads" + if restore_step x86-preloads "${x86_key}" "${linuxfs_dir}"; then :; else + x86_platform=linux/amd64 + x86_packages="gcc g++ gcc-multilib g++-multilib binutils" + x86_cross=0 + if [[ "${docker_platform}" == linux/arm64 ]]; then + x86_platform=linux/arm64 + x86_packages="gcc-x86-64-linux-gnu g++-x86-64-linux-gnu gcc-i686-linux-gnu g++-i686-linux-gnu libc6-dev-amd64-cross libc6-dev-i386-cross binutils-x86-64-linux-gnu binutils-i686-linux-gnu" + x86_cross=1 + fi + docker run --rm --platform "${x86_platform}" -e X86_CROSS="${x86_cross}" -e X86_PACKAGES="${x86_packages}" \ + -v "${repo_root}:/src" -v "${git_common}:${git_common}" -w /src public.ecr.aws/docker/library/debian:bullseye bash -c ' + set -euo pipefail + printf "deb http://archive.debian.org/debian bullseye main\ndeb http://archive.debian.org/debian-security bullseye-security main\n" > /etc/apt/sources.list + apt-get -o Acquire::Check-Valid-Until=false update -qq + DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends $X86_PACKAGES >/dev/null + tools/linuxfs/build-x86-preloads.sh app/src/main/assets/linuxfs + chown -R '"$(id -u):$(id -g)"' app/src/main/assets/linuxfs + ' + mkdir -p "${x86_stage}" + cp -R "${linuxfs_dir}/x86_64" "${linuxfs_dir}/i386" "${x86_stage}/" + save_step x86-preloads "${x86_key}" "${x86_stage}" + fi + + vr_out="${linuxfs_dir}/usr/local/lib/droiddeck-vr" + vr_key=$(inputs_hash "${image_id} ${ndk_version} ${VK_INCLUDE:-}" tools/vr app/src/main/cpp/waylandcomp/generated/xdg-shell-protocol.c) + if ! restore_step vr "${vr_key}" "${vr_out}"; then + DROIDDECK_BUILD_IMAGE="${image_name}" "${repo_root}/tools/vr/build.sh" "${vr_out}" + save_step vr "${vr_key}" "${vr_out}" + fi + + gpuload_out="${linuxfs_dir}/usr/local/lib/droiddeck-gpuload" + gpuload_key=$(inputs_hash "${image_id} ${ndk_version} ${VK_INCLUDE:-}" tools/gpuload) + if ! restore_step gpuload "${gpuload_key}" "${gpuload_out}"; then + DROIDDECK_BUILD_IMAGE="${image_name}" "${repo_root}/tools/gpuload/build.sh" "${gpuload_out}" + save_step gpuload "${gpuload_key}" "${gpuload_out}" + fi + + cached() { + local sha=$1 name=$2 out + shift 2 + out="${cache_dir}/${sha}-${name}" + if [[ -f "${out}" ]] && printf '%s %s\n' "${sha}" "${out}" | shasum -a 256 -c - >/dev/null 2>&1; then + echo "${out}" + return 0 + fi + rm -f "${out}.part" + out="${out}.part" "$@" >&2 + printf '%s %s\n' "${sha}" "${out}.part" | shasum -a 256 -c - >&2 + mv "${out}.part" "${out}" + echo "${out}" + } + + if [[ -f "${repo_root}/tools/gamescope/release.env" ]]; then + . "${repo_root}/tools/gamescope/release.env" + gamescope_archive=$(cached "${GAMESCOPE_SHA256}" gamescope.tzst \ + bash -c 'gh release download "$0" -R "$1" -p gamescope.tzst -O "$out"' "${GAMESCOPE_TAG}" "${GAMESCOPE_REPO:-${github_repo}}") + zstd -dc "${gamescope_archive}" | tar -xf - -C "${linuxfs_dir}" + test -f "${linuxfs_dir}/usr/local/bin/gamescope" + fi + + . "${repo_root}/tools/linuxfs/uruntime.env" + uruntime_binary=$(cached "${URUNTIME_SHA256}" "${URUNTIME_ASSET}" \ + bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "https://github.com/VHSgunzo/uruntime/releases/download/${URUNTIME_VERSION}/${URUNTIME_ASSET}") + mkdir -p "${linuxfs_dir}/usr/local/lib/droiddeck" "${linuxfs_dir}/usr/local/share/licenses/uruntime" + install -m644 "${uruntime_binary}" "${linuxfs_dir}/usr/local/lib/droiddeck/uruntime" + install -m644 "${repo_root}/tools/linuxfs/licenses/uruntime-LICENSE" "${linuxfs_dir}/usr/local/share/licenses/uruntime/LICENSE" + + sync_assets="${repo_root}/app/src/main/assets/droiddeck-esync" + if [[ -f "${repo_root}/tools/droiddeck-esync/release.env" ]]; then + . "${repo_root}/tools/droiddeck-esync/release.env" + sync_archive=$(cached "${SYNC_BUNDLE_SHA256}" "${SYNC_BUNDLE_ASSET}" \ + bash -c 'gh release download "$0" -R "$2" -p "$1" -O "$out"' "${SYNC_BUNDLE_TAG}" "${SYNC_BUNDLE_ASSET}" "${SYNC_BUNDLE_REPO}") + rm -rf "${sync_assets}" + mkdir -p "${sync_assets}" + zstd -dc "${sync_archive}" | tar -xf - -C "${sync_assets}" + test -f "${sync_assets}/index.json" + test -f "${sync_assets}/index.json.sig" + elif [[ -d "${sync_assets}" ]]; then + echo "No tools/droiddeck-esync/release.env: the APK bundles the droiddeck-esync packs already in ${sync_assets}." >&2 + fi + + msi_pkgs="${staging_dir}/msi-pkgs" + msi_dir="${linuxfs_dir}/usr/local/lib/droiddeck-msitools" + mkdir -p "${msi_pkgs}" "${msi_dir}" + while read -r package_sha256 package_url; do + [[ -n "${package_url}" ]] || continue + package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \ + bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}") + tar -xJf "${package_archive}" -C "${msi_pkgs}" + done < <(grep -v '^#' "${repo_root}/tools/msitools/packages.txt") + for tool in msiinfo cabextract; do install -m644 "${msi_pkgs}/usr/bin/${tool}" "${msi_dir}/${tool}"; done + for tool in 7z 7z.so; do install -m644 "${msi_pkgs}/usr/lib/7zip/${tool}" "${msi_dir}/${tool}"; done + for library in libmsi-1.0.so.0 libgsf-1.so.114 libgcab-1.0.so.0; do + cp -L "${msi_pkgs}/usr/lib/${library}" "${msi_dir}/${library}" + done + mkdir -p "${linuxfs_dir}/usr/local/share/licenses/droiddeck-msitools" + for license in NOTICE GPL-2 GPL-3 LGPL-2.1 7zip-License 7zip-unRarLicense; do + install -m644 "${repo_root}/tools/msitools/licenses/${license}" \ + "${linuxfs_dir}/usr/local/share/licenses/droiddeck-msitools/${license}" + done + + mango_dir="${linuxfs_dir}/usr/local/lib/mangoapp" + mango_pkgs="${staging_dir}/mango-pkgs" + mkdir -p "${mango_dir}" "${mango_pkgs}" + while read -r package_sha256 package_url; do + [[ -n "${package_url}" ]] || continue + package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \ + bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}") + zstd -dc "${package_archive}" | tar -xf - -C "${mango_pkgs}" + done < <(grep -v '^#' "${repo_root}/tools/mangoapp/packages.txt") + install -m644 "${mango_pkgs}/usr/bin/mangoapp" "${mango_dir}/mangoapp" + for library in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1; do + cp -L "${mango_pkgs}/usr/lib/${library}" "${mango_dir}/${library}" + done + docker run --rm --platform "${docker_platform}" --user "$(id -u):$(id -g)" -v "${repo_root}:/src" -w /src "${image_name}" \ + aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wl,-soname,libtracefs.so.1 \ + -o app/src/main/assets/linuxfs/usr/local/lib/mangoapp/libtracefs.so.1 tools/mangoapp/libtracefs-shim.c + mkdir -p "${linuxfs_dir}/usr/local/bin" + install -m644 "${repo_root}/tools/mangoapp/mangoapp" "${linuxfs_dir}/usr/local/bin/mangoapp" + + pw_pkgs="${staging_dir}/pw-pkgs" + mkdir -p "${pw_pkgs}" + while read -r package_sha256 package_url; do + [[ -n "${package_url}" ]] || continue + package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \ + bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}") + zstd -dc "${package_archive}" | tar -xf - -C "${pw_pkgs}" + done < <(grep -v '^#' "${repo_root}/tools/pipewire/packages.txt") + "${repo_root}/tools/pipewire/assemble.sh" "${pw_pkgs}" "${linuxfs_dir}/usr/local/lib/droiddeck-pipewire.tzst" + + pa_source=${DROIDDECK_PA13_SOURCE_DIR:-"${staging_dir}/pulseaudio-13.0"} + if [[ -z "${DROIDDECK_PA13_SOURCE_DIR:-}" ]]; then + pa_tarball="${cache_dir}/pulseaudio-13.0.tar.gz" + if [[ ! -s "${pa_tarball}" ]] || ! tar -tzf "${pa_tarball}" >/dev/null 2>&1; then + curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "${pa_tarball}.part" \ + https://github.com/pulseaudio/pulseaudio/archive/refs/tags/v13.0.tar.gz + mv "${pa_tarball}.part" "${pa_tarball}" + fi + mkdir -p "${pa_source}" + tar -xzf "${pa_tarball}" -C "${pa_source}" --strip-components=1 + fi + if [[ ! -f "${pa_source}/src/pulse/version.h.in" ]]; then + echo "PulseAudio 13.0 source not found at ${pa_source}; set DROIDDECK_PA13_SOURCE_DIR." >&2 + exit 1 + fi + + sink_output="${staging_dir}/sink-out" + "${repo_root}/tools/directaudio/fetch.sh" "${repo_root}" "${sink_output}" + "${repo_root}/tools/aaudio-sink/build.sh" "${pa_source}" "${sink_output}" + proot_sources=$(cd "${repo_root}/tools/proot" && find . -type f ! -name '*.pyc' | LC_ALL=C sort | xargs shasum -a 256 | shasum -a 256 | cut -d' ' -f1) + proot_inputs=$(printf '%s\n' "${proot_sources}" "${ndk_version}" | shasum -a 256 | cut -d' ' -f1) + if [[ -f "${proot_out}/libproot.so" && -f "${proot_out}/libproot-loader.so" \ + && "$(cat "${proot_out}/.proot-inputs" 2>/dev/null)" = "${proot_inputs}" ]] \ + && (cd "${proot_out}" && shasum -a 256 -c .proot-outputs >/dev/null 2>&1); then + echo "proot: sources unchanged, keeping ${proot_out}/libproot.so" + else + proot_stage="${staging_dir}/proot" + if ! restore_step proot "${proot_inputs}" "${proot_stage}"; then + "${repo_root}/tools/proot/build.sh" "${proot_stage}" + save_step proot "${proot_inputs}" "${proot_stage}" + fi + install -m755 "${proot_stage}/libproot.so" "${proot_stage}/libproot-loader.so" "${proot_out}/" + echo "${proot_inputs}" > "${proot_out}/.proot-inputs" + (cd "${proot_out}" && shasum -a 256 libproot.so libproot-loader.so > .proot-outputs) + fi +fi sync_assets="${repo_root}/app/src/main/assets/droiddeck-esync" if [[ -f "${repo_root}/tools/droiddeck-esync/release.env" ]]; then + # Packs revoked after a bundle was published are dropped from local and CI-prepared bundles alike. . "${repo_root}/tools/droiddeck-esync/release.env" - sync_archive=$(cached "${SYNC_BUNDLE_SHA256}" "${SYNC_BUNDLE_ASSET}" \ - bash -c 'gh release download "$0" -R "$2" -p "$1" -O "$out"' "${SYNC_BUNDLE_TAG}" "${SYNC_BUNDLE_ASSET}" "${SYNC_BUNDLE_REPO}") - rm -rf "${sync_assets}" - mkdir -p "${sync_assets}" - zstd -dc "${sync_archive}" | tar -xf - -C "${sync_assets}" - test -f "${sync_assets}/index.json" - test -f "${sync_assets}/index.json.sig" sync_index=$(mktemp) gh release download "${SYNC_BUNDLE_TAG}" -R "${SYNC_BUNDLE_REPO}" -p index.json -O "${sync_index}" --clobber revoked=$(python3 -c 'import json, sys; print(" ".join(p["id"] for p in json.load(open(sys.argv[1]))["packs"] if p.get("revoked") is True))' "${sync_index}") @@ -278,94 +427,6 @@ if [[ -f "${repo_root}/tools/droiddeck-esync/release.env" ]]; then fi done rm -f "${sync_index}" -elif [[ -d "${sync_assets}" ]]; then - echo "No tools/droiddeck-esync/release.env: the APK bundles the droiddeck-esync packs already in ${sync_assets}." >&2 -fi - -msi_pkgs="${staging_dir}/msi-pkgs" -msi_dir="${linuxfs_dir}/usr/local/lib/droiddeck-msitools" -mkdir -p "${msi_pkgs}" "${msi_dir}" -while read -r package_sha256 package_url; do - [[ -n "${package_url}" ]] || continue - package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \ - bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}") - tar -xJf "${package_archive}" -C "${msi_pkgs}" -done < <(grep -v '^#' "${repo_root}/tools/msitools/packages.txt") -for tool in msiinfo cabextract; do install -m644 "${msi_pkgs}/usr/bin/${tool}" "${msi_dir}/${tool}"; done -for tool in 7z 7z.so; do install -m644 "${msi_pkgs}/usr/lib/7zip/${tool}" "${msi_dir}/${tool}"; done -for library in libmsi-1.0.so.0 libgsf-1.so.114 libgcab-1.0.so.0; do - cp -L "${msi_pkgs}/usr/lib/${library}" "${msi_dir}/${library}" -done -mkdir -p "${linuxfs_dir}/usr/local/share/licenses/droiddeck-msitools" -for license in NOTICE GPL-2 GPL-3 LGPL-2.1 7zip-License 7zip-unRarLicense; do - install -m644 "${repo_root}/tools/msitools/licenses/${license}" \ - "${linuxfs_dir}/usr/local/share/licenses/droiddeck-msitools/${license}" -done - -mango_dir="${linuxfs_dir}/usr/local/lib/mangoapp" -mango_pkgs="${staging_dir}/mango-pkgs" -mkdir -p "${mango_dir}" "${mango_pkgs}" -while read -r package_sha256 package_url; do - [[ -n "${package_url}" ]] || continue - package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \ - bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}") - zstd -dc "${package_archive}" | tar -xf - -C "${mango_pkgs}" -done < <(grep -v '^#' "${repo_root}/tools/mangoapp/packages.txt") -install -m644 "${mango_pkgs}/usr/bin/mangoapp" "${mango_dir}/mangoapp" -for library in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1; do - cp -L "${mango_pkgs}/usr/lib/${library}" "${mango_dir}/${library}" -done -docker run --rm --platform "${docker_platform}" --user "$(id -u):$(id -g)" -v "${repo_root}:/src" -w /src "${image_name}" \ - aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wl,-soname,libtracefs.so.1 \ - -o app/src/main/assets/linuxfs/usr/local/lib/mangoapp/libtracefs.so.1 tools/mangoapp/libtracefs-shim.c -mkdir -p "${linuxfs_dir}/usr/local/bin" -install -m644 "${repo_root}/tools/mangoapp/mangoapp" "${linuxfs_dir}/usr/local/bin/mangoapp" - -pw_pkgs="${staging_dir}/pw-pkgs" -mkdir -p "${pw_pkgs}" -while read -r package_sha256 package_url; do - [[ -n "${package_url}" ]] || continue - package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \ - bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}") - zstd -dc "${package_archive}" | tar -xf - -C "${pw_pkgs}" -done < <(grep -v '^#' "${repo_root}/tools/pipewire/packages.txt") -"${repo_root}/tools/pipewire/assemble.sh" "${pw_pkgs}" "${linuxfs_dir}/usr/local/lib/droiddeck-pipewire.tzst" - -pa_source=${DROIDDECK_PA13_SOURCE_DIR:-"${staging_dir}/pulseaudio-13.0"} -if [[ -z "${DROIDDECK_PA13_SOURCE_DIR:-}" ]]; then - pa_tarball="${cache_dir}/pulseaudio-13.0.tar.gz" - if [[ ! -s "${pa_tarball}" ]] || ! tar -tzf "${pa_tarball}" >/dev/null 2>&1; then - curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "${pa_tarball}.part" \ - https://github.com/pulseaudio/pulseaudio/archive/refs/tags/v13.0.tar.gz - mv "${pa_tarball}.part" "${pa_tarball}" - fi - mkdir -p "${pa_source}" - tar -xzf "${pa_tarball}" -C "${pa_source}" --strip-components=1 -fi -if [[ ! -f "${pa_source}/src/pulse/version.h.in" ]]; then - echo "PulseAudio 13.0 source not found at ${pa_source}; set DROIDDECK_PA13_SOURCE_DIR." >&2 - exit 1 -fi - -sink_output="${staging_dir}/sink-out" -"${repo_root}/tools/directaudio/fetch.sh" "${repo_root}" "${sink_output}" -"${repo_root}/tools/aaudio-sink/build.sh" "${pa_source}" "${sink_output}" -proot_out="${repo_root}/app/src/main/jniLibs/arm64-v8a" -proot_sources=$(cd "${repo_root}/tools/proot" && find . -type f ! -name '*.pyc' | LC_ALL=C sort | xargs shasum -a 256 | shasum -a 256 | cut -d' ' -f1) -proot_inputs=$(printf '%s\n' "${proot_sources}" "${ndk_version}" | shasum -a 256 | cut -d' ' -f1) -if [[ -f "${proot_out}/libproot.so" && -f "${proot_out}/libproot-loader.so" \ - && "$(cat "${proot_out}/.proot-inputs" 2>/dev/null)" = "${proot_inputs}" ]] \ - && (cd "${proot_out}" && shasum -a 256 -c .proot-outputs >/dev/null 2>&1); then - echo "proot: sources unchanged, keeping ${proot_out}/libproot.so" -else - proot_stage="${staging_dir}/proot" - if ! restore_step proot "${proot_inputs}" "${proot_stage}"; then - "${repo_root}/tools/proot/build.sh" "${proot_stage}" - save_step proot "${proot_inputs}" "${proot_stage}" - fi - install -m755 "${proot_stage}/libproot.so" "${proot_stage}/libproot-loader.so" "${proot_out}/" - echo "${proot_inputs}" > "${proot_out}/.proot-inputs" - (cd "${proot_out}" && shasum -a 256 libproot.so libproot-loader.so > .proot-outputs) fi syncthing_src="${repo_root}/tools/syncthing/syncthing-android/syncthing/src/github.com/syncthing/syncthing" @@ -389,21 +450,23 @@ else echo "${syncthing_inputs}" > "${proot_out}/.syncthing-inputs" fi -bundle_dir="${staging_dir}/pulseaudio-bundle" -mkdir -p "${bundle_dir}" -zstd -dc "${bundle_asset}" | tar -xf - -C "${bundle_dir}" -if [[ -e "${bundle_dir}/modules/arm64/module-aaudio-sink.so" \ - || -e "${bundle_dir}/modules/arm64/module-directaudio-native-sink.so" ]]; then - echo "The committed audio bundle already contains a built ARM64 sink." >&2 - exit 1 +if [[ "${ci_components}" != 1 ]]; then + bundle_dir="${staging_dir}/pulseaudio-bundle" + mkdir -p "${bundle_dir}" + zstd -dc "${bundle_asset}" | tar -xf - -C "${bundle_dir}" + if [[ -e "${bundle_dir}/modules/arm64/module-aaudio-sink.so" \ + || -e "${bundle_dir}/modules/arm64/module-directaudio-native-sink.so" ]]; then + echo "The committed audio bundle already contains a built ARM64 sink." >&2 + exit 1 + fi + install -m755 "${sink_output}/module-aaudio-sink.so" \ + "${bundle_dir}/modules/arm64/module-aaudio-sink.so" + install -m755 "${sink_output}/module-directaudio-native-sink.so" \ + "${bundle_dir}/modules/arm64/module-directaudio-native-sink.so" + tar -cf - -C "${bundle_dir}" . | zstd -19 -T0 -c > "${staging_dir}/pulseaudio.tzst" + mkdir -p "${repo_root}/app/build/prepared-assets" + mv "${staging_dir}/pulseaudio.tzst" "${repo_root}/app/build/prepared-assets/pulseaudio.tzst" fi -install -m755 "${sink_output}/module-aaudio-sink.so" \ - "${bundle_dir}/modules/arm64/module-aaudio-sink.so" -install -m755 "${sink_output}/module-directaudio-native-sink.so" \ - "${bundle_dir}/modules/arm64/module-directaudio-native-sink.so" -tar -cf - -C "${bundle_dir}" . | zstd -19 -T0 -c > "${staging_dir}/pulseaudio.tzst" -mkdir -p "${repo_root}/app/build/prepared-assets" -mv "${staging_dir}/pulseaudio.tzst" "${repo_root}/app/build/prepared-assets/pulseaudio.tzst" gradle_rust_arg="" if [[ "${DROIDDECK_SKIP_RUST:-0}" == 1 ]]; then @@ -424,19 +487,23 @@ else fi cd "${repo_root}" -python3 tools/quest/build-driver.py "${NDK}" +[[ "${ci_components}" == 1 ]] || python3 tools/quest/build-driver.py "${NDK}" xbox_out="${linuxfs_dir}/usr/local/lib/droiddeck-xbox" xbox_key=$(inputs_hash "native-arm64-ubuntu24.04" tools/xbox) -if ! restore_step xbox "${xbox_key}" "${xbox_out}"; then +if [[ "${ci_components}" == 1 ]] && fetch_ci_xbox; then + echo "xbox: reused main CI run ${ci_run}" +elif ! restore_step xbox "${xbox_key}" "${xbox_out}"; then bash tools/xbox/build-local.sh save_step xbox "${xbox_key}" "${xbox_out}" fi -comet_out="${linuxfs_dir}/usr/local/lib/droiddeck-comet" -comet_key=$(inputs_hash "${image_id}" tools/comet) -if ! restore_step comet "${comet_key}" "${comet_out}"; then - DROIDDECK_BUILD_IMAGE="${image_name}" bash tools/comet/build-local.sh - save_step comet "${comet_key}" "${comet_out}" +if [[ "${ci_components}" != 1 ]]; then + comet_out="${linuxfs_dir}/usr/local/lib/droiddeck-comet" + comet_key=$(inputs_hash "${image_id}" tools/comet) + if ! restore_step comet "${comet_key}" "${comet_out}"; then + DROIDDECK_BUILD_IMAGE="${image_name}" bash tools/comet/build-local.sh + save_step comet "${comet_key}" "${comet_out}" + fi fi if [[ "${DROIDDECK_SKIP_RUST:-0}" != 1 ]]; then upc_out="${linuxfs_dir}/usr/local/lib/droiddeck-ubisoft" diff --git a/tools/components/reuse.py b/tools/components/reuse.py new file mode 100644 index 0000000000..1eb02dca9d --- /dev/null +++ b/tools/components/reuse.py @@ -0,0 +1,150 @@ +"""Install the components a main CI run prepared when they match this tree. + +The run's prepared-components archive is used only when every recipe identity it records equals +the identity of the local tree, the inputs CI builds outside the recipes are unchanged from the +run's source tree, and no recipe submodule has local edits. Files are verified in a staging +directory before any local output is replaced. +""" +import argparse +from contextlib import contextmanager +import hashlib +import json +import os +from pathlib import Path, PurePosixPath +import shutil +import subprocess +import sys +import tarfile +import tempfile + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import prepare # noqa: E402 + +# CI records identities under its runner labels and pinned NDK, not this host's. +RUNNER_ARCHITECTURES = ('X64', 'ARM64') +# The components job builds these outside the recipe registry. +UNREGISTERED_INPUTS = ['.github/workflows/build.yml', 'tools/linuxfs/xclipse-layer', 'tools/venus/glprobe.c', + 'tools/quest'] + + +def ci_environment(architecture, root): + ndk = next(line.split('=', 1)[1].strip() + for line in (root / 'tools/ci/toolchains.env').read_text().splitlines() + if line.startswith('CI_ANDROID_NDK_VERSION=')) + return dict(RUNNER_OS='Linux', RUNNER_ARCH=architecture, NDK_VERSION=ndk) + + +@contextmanager +def environ(values): + saved = {key: os.environ.get(key) for key in values} + os.environ.update(values) + try: + yield + finally: + for key, value in saved.items(): + if value is None: + os.environ.pop(key, None) + else: + os.environ[key] = value + + +def identities(environment, root): + with environ(environment): + return {name: prepare.identity(name, root) for name in prepare.registry(root)} + + +def git(root, *args): + return subprocess.run(['git', *args], cwd=root, capture_output=True, text=True) + + +def unregistered_changes(source_tree, root): + if git(root, 'cat-file', '-e', source_tree + '^{tree}').returncode: + return ['source tree ' + source_tree + ' (fetch origin main)'] + changed = git(root, 'diff', '--name-only', source_tree, '--', *UNREGISTERED_INPUTS).stdout.split() + changed += git(root, 'ls-files', '--others', '--exclude-standard', '--', *UNREGISTERED_INPUTS).stdout.split() + return sorted(set(changed)) + + +def edited_submodules(root): + inputs = [path for spec in prepare.registry(root).values() + for path in spec.get('inputs', []) + spec.get('source_inputs', [])] + staged = git(root, 'ls-files', '--stage', '--', *inputs).stdout.splitlines() + links = [line.split('\t', 1)[1] for line in staged if line.startswith('160000 ')] + return [link for link in links + if git(root, 'diff', '--quiet', '--ignore-submodules=none', '--', link).returncode] + + +def extract(archive_path, stage): + allowed = set(prepare.LIBRARIES + [prepare.MANIFEST]) + total = 0 + with tarfile.open(archive_path, mode='r:gz') as archive: + for entry in archive: + name = PurePosixPath(entry.name) + total += entry.size + if (not entry.isfile() or name.is_absolute() or '..' in name.parts or '\\' in entry.name + or name.as_posix() != entry.name or total > 2 * 1024**3 + or not (entry.name in allowed or any(entry.name.startswith(t + '/') for t in prepare.TREES))): + raise ValueError('Unsafe prepared component archive: ' + entry.name) + path = stage / entry.name + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('xb') as output: + shutil.copyfileobj(archive.extractfile(entry), output) + path.chmod(entry.mode & 0o777) + + +def digest(path): + with path.open('rb') as stream: + return hashlib.file_digest(stream, 'sha256').hexdigest() + + +def install(stage, root): + for name in prepare.TREES: + shutil.rmtree(root / name, ignore_errors=True) + (root / name).parent.mkdir(parents=True, exist_ok=True) + os.replace(stage / name, root / name) + for name in prepare.LIBRARIES + [prepare.MANIFEST]: + (root / name).parent.mkdir(parents=True, exist_ok=True) + os.replace(stage / name, root / name) + + +def reuse(archive_path, root=prepare.ROOT): + with tarfile.open(archive_path, mode='r:gz') as archive: + data = json.load(archive.extractfile(prepare.MANIFEST)) + if data.get('version') != 1: + raise ValueError('Unknown prepared component archive version') + recorded = data.get('recipes') or {} + environment = next((ci_environment(a, root) for a in RUNNER_ARCHITECTURES + if identities(ci_environment(a, root), root) == recorded), None) + if environment is None: + local = identities(ci_environment(RUNNER_ARCHITECTURES[0], root), root) + changed = sorted(name for name in local.keys() | recorded.keys() if local.get(name) != recorded.get(name)) + print('CI run ' + str(data.get('run')) + ' prepared different components: ' + ', '.join(changed)) + return False + differences = unregistered_changes(data['source_tree'], root) + edited_submodules(root) + if differences: + print('CI run ' + str(data.get('run')) + ' built from other sources: ' + ', '.join(differences)) + return False + (root / 'app/build').mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(dir=root / 'app/build', prefix='.reuse-') as stage: + stage = Path(stage) + extract(archive_path, stage) + files = sorted(path.relative_to(stage).as_posix() for path in stage.rglob('*') + if path.is_file() and path.relative_to(stage).as_posix() != prepare.MANIFEST) + if data.get('files') != {name: digest(stage / name) for name in files}: + raise ValueError('Prepared components do not match their recorded file hashes') + missing = [name for name in prepare.TREES if not (stage / name).is_dir()] + missing += [name for name in prepare.LIBRARIES + [prepare.MANIFEST] if not (stage / name).is_file()] + if missing: + raise ValueError('Prepared component archive is missing ' + ', '.join(missing)) + install(stage, root) + return True + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('archive', type=Path) + args = parser.parse_args() + try: + sys.exit(0 if reuse(args.archive) else 3) + except (ValueError, OSError, KeyError, tarfile.TarError) as error: + sys.exit('Cannot reuse CI components: ' + str(error)) diff --git a/tools/tests/test_component_reuse.py b/tools/tests/test_component_reuse.py new file mode 100644 index 0000000000..5d67e34c1a --- /dev/null +++ b/tools/tests/test_component_reuse.py @@ -0,0 +1,93 @@ +import hashlib +import importlib.util +import io +import json +from pathlib import Path +import sys +import tarfile +import tempfile +import unittest +from unittest import mock + +COMPONENTS = Path(__file__).resolve().parents[1] / 'components' +sys.path.insert(0, str(COMPONENTS)) +spec = importlib.util.spec_from_file_location('component_reuse', COMPONENTS / 'reuse.py') +reuse = importlib.util.module_from_spec(spec) +spec.loader.exec_module(reuse) +prepare = reuse.prepare + + +class ComponentReuseTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + (self.root / 'tools/ci').mkdir(parents=True) + (self.root / 'tools/ci/toolchains.env').write_text('CI_ANDROID_NDK_VERSION=30.0.1\n') + self.local = {'runtime': 'a', 'proot': 'b'} + self.unregistered, self.submodules = [], [] + for patcher in [mock.patch.object(prepare, 'registry', lambda root: dict.fromkeys(self.local)), + mock.patch.object(prepare, 'identity', lambda name, root: self.local[name]), + mock.patch.object(reuse, 'unregistered_changes', lambda tree, root: self.unregistered), + mock.patch.object(reuse, 'edited_submodules', lambda root: self.submodules)]: + patcher.start() + self.addCleanup(patcher.stop) + self.archive = self.root / 'prepared-components.tar.gz' + self.contents = {name + '/file': name.encode() for name in prepare.TREES} + self.contents.update({name: b'library' for name in prepare.LIBRARIES}) + + def write_archive(self, recipes, contents=None): + contents = contents or self.contents + manifest = dict(version=1, source_tree='tree', run='42', recipes=recipes, + files={name: hashlib.sha256(data).hexdigest() for name, data in self.contents.items()}) + with tarfile.open(self.archive, 'w:gz') as archive: + for name, data in list(contents.items()) + [(prepare.MANIFEST, json.dumps(manifest).encode())]: + entry = tarfile.TarInfo(name) + entry.size = len(data) + entry.mode = 0o644 + archive.addfile(entry, io.BytesIO(data)) + + def test_matching_components_replace_local_ones(self): + stale = self.root / prepare.TREES[0] / 'left-over' + stale.parent.mkdir(parents=True) + stale.write_text('from an older local build') + self.write_archive(dict(self.local)) + self.assertTrue(reuse.reuse(self.archive, self.root)) + self.assertEqual(b'library', (self.root / prepare.LIBRARIES[0]).read_bytes()) + self.assertFalse(stale.exists()) + + def test_a_changed_component_is_not_reused(self): + self.write_archive(dict(self.local, proot='other')) + with mock.patch('sys.stdout', new_callable=io.StringIO) as stdout: + self.assertFalse(reuse.reuse(self.archive, self.root)) + self.assertIn('proot', stdout.getvalue()) + self.assertFalse((self.root / prepare.LIBRARIES[0]).exists()) + + def test_a_tampered_file_is_rejected_and_local_outputs_survive(self): + local = self.root / prepare.LIBRARIES[0] + local.parent.mkdir(parents=True) + local.write_bytes(b'local build') + self.write_archive(dict(self.local), dict(self.contents, **{prepare.LIBRARIES[0]: b'tampered'})) + with self.assertRaisesRegex(ValueError, 'do not match'): + reuse.reuse(self.archive, self.root) + self.assertEqual(b'local build', local.read_bytes()) + + def test_changed_sources_ci_builds_outside_recipes_are_not_reused(self): + self.unregistered = ['tools/linuxfs/xclipse-layer/xclipse_layer.c'] + self.write_archive(dict(self.local)) + with mock.patch('sys.stdout', new_callable=io.StringIO) as stdout: + self.assertFalse(reuse.reuse(self.archive, self.root)) + self.assertIn('xclipse_layer.c', stdout.getvalue()) + + def test_an_edited_submodule_is_not_reused(self): + self.submodules = ['external/MaliBridge'] + self.write_archive(dict(self.local)) + with mock.patch('sys.stdout', new_callable=io.StringIO): + self.assertFalse(reuse.reuse(self.archive, self.root)) + + def test_identities_use_the_ci_runner_and_ndk(self): + seen = {} + with mock.patch.object(prepare, 'identity', lambda name, root: seen.update( + arch=reuse.os.environ['RUNNER_ARCH'], ndk=reuse.os.environ['NDK_VERSION']) or 'x'): + reuse.identities(reuse.ci_environment('X64', self.root), self.root) + self.assertEqual({'arch': 'X64', 'ndk': '30.0.1'}, seen) From 309893b722cda4494b82e9d056a182dd8f76eac5 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:46:03 -0500 Subject: [PATCH 092/141] fix(ci): cache Robolectric's Android jars so Maven Central 429s stop failing unit tests (#3127) --- .github/workflows/build.yml | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 60f8882401..abb5207142 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -692,6 +692,16 @@ 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. + - name: Cache Robolectric's Android jars + uses: actions/cache@v4 + with: + path: ~/.m2/repository/org/robolectric/android-all-instrumented + key: robolectric-android-all-${{ steps.robolectric.outputs.version }} - name: Unit tests id: unit-tests env: From f6c6e73a6bed5697abef0a6d539662f19ab29e8d Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Tue, 24 Nov 2026 01:06:17 -0500 Subject: [PATCH 093/141] Native hook: start a program again through /proc/self/exe as itself (#3120) * Native hook: start a program again through /proc/self/exe as itself A program that execs /proc/self/exe (Chromium's network and utility services, Electron apps) reached the kernel link, which names ld.so, so the child was started without ld.so and saw libddexec as its own program. Chromium then looked for its ICU data beside libddexec and the network service crashed in a loop. The exec path now resolves /proc/self/exe to the program the hook knows it runs, so it is routed like any other guest program, and readlink of the exe link names a program from a bind by its guest path. * fix(hook): keep the host path of a running program a nested bind shadows --- tools/nativeguest/hook/exec_probe.c | 7 ++++++ tools/nativeguest/hook/setup.c | 13 ++++------- tools/tests/test_native_hook_ldso_spawn.py | 20 ++++++++++++++++- tools/tests/test_native_hook_proc_exe.py | 25 +++++++++++++++++++++- 4 files changed, 54 insertions(+), 11 deletions(-) diff --git a/tools/nativeguest/hook/exec_probe.c b/tools/nativeguest/hook/exec_probe.c index 74e0c2875c..be708e9158 100644 --- a/tools/nativeguest/hook/exec_probe.c +++ b/tools/nativeguest/hook/exec_probe.c @@ -10,6 +10,13 @@ // PT_INTERP) literally and failed with "bad interpreter: No such file or directory". // getcwd() is not virtualised, so cwd + path is a real path that starts with DDNATV_ROOT. static const char *absolutize_exec_path(const char *path, char *buffer, size_t bufsize) { + if (is_proc_self_exe(path)) { + ssize_t n = handle_proc_self_exe(buffer, bufsize - 1); + if (n > 0 && buffer[0] == '/') { + buffer[n] = '\0'; + return buffer; + } + } if (!path || path[0] == '\0' || path[0] == '/') return path; char cwd[PATH_MAX]; static char *(*real_getcwd)(char *, size_t) = NULL; diff --git a/tools/nativeguest/hook/setup.c b/tools/nativeguest/hook/setup.c index e0587d0b4f..9befbed47e 100644 --- a/tools/nativeguest/hook/setup.c +++ b/tools/nativeguest/hook/setup.c @@ -203,15 +203,10 @@ static void exe_from_cmdline(const char *cmdline_path, char *out, size_t outsz) } static ssize_t copy_guest_exe(const char *real_exe, char *buf, size_t bufsiz) { - const char *out_path = real_exe; - if (g_ddnatv_root[0] != '\0') { - size_t rlen = g_ddnatv_root_len; - if (strncmp(real_exe, g_ddnatv_root, rlen) == 0 && - (real_exe[rlen] == '/' || real_exe[rlen] == '\0')) { - out_path = real_exe + rlen; - if (out_path[0] == '\0') out_path = "/"; - } - } + char guest[PATH_MAX]; + char back[PATH_MAX]; + const char *out_path = guest_path_of_host_dir(real_exe, guest, sizeof(guest)); + if (!out_path || strcmp(rewrite_path_in_root(out_path, back, sizeof(back)), real_exe) != 0) out_path = real_exe; size_t len = strlen(out_path); size_t copy_len = (len < bufsiz) ? len : bufsiz; memcpy(buf, out_path, copy_len); diff --git a/tools/tests/test_native_hook_ldso_spawn.py b/tools/tests/test_native_hook_ldso_spawn.py index 8c1ad2575e..d7c861085d 100644 --- a/tools/tests/test_native_hook_ldso_spawn.py +++ b/tools/tests/test_native_hook_ldso_spawn.py @@ -124,10 +124,12 @@ class NativeHookLdsoSpawnTest(unittest.TestCase): def tearDownClass(cls): cls.tmp.cleanup() - def call(self, how, *argv, binds=None): + def call(self, how, *argv, binds=None, real_exe=None): hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook}:{self.recorder}"} if binds: hook_env["DDNATV_BINDS"] = binds + if real_exe: + hook_env["DDNATV_REAL_EXE"] = real_exe env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_EXEC", "LD_LIBRARY_PATH")} if self.prefix: cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] @@ -177,6 +179,22 @@ class NativeHookLdsoSpawnTest(unittest.TestCase): self.call(how, GUEST_LDSO, "--list", GUEST_TOOL) self.assertEqual([], self.library_paths) + def test_a_program_from_a_bind_starts_itself_again_through_proc_self_exe(self): + bash = str(self.runtime / "bash") + for how in ("exec", "spawn"): + with self.subTest(how=how): + call = self.call(how, "/proc/self/exe", "x", binds=f"/proc:/proc|{self.runtime}:{BOUND_DIR}", real_exe=bash) + self.assertEqual(str(self.root / GUEST_LDSO.lstrip("/")), call[0]) + self.assertEqual([bash, "x"], call[-2:]) + + def test_a_rootfs_program_starts_itself_again_through_proc_self_exe(self): + tool = str(self.root / GUEST_TOOL.lstrip("/")) + for how in ("exec", "spawn"): + with self.subTest(how=how): + call = self.call(how, "/proc/self/exe", "x", binds="/proc:/proc", real_exe=tool) + self.assertEqual(str(self.root / GUEST_LDSO.lstrip("/")), call[0]) + self.assertEqual([tool, "x"], call[-2:]) + def test_a_script_interpreter_from_a_bind_runs_as_a_guest_program(self): for how in ("exec", "spawn"): with self.subTest(how=how): diff --git a/tools/tests/test_native_hook_proc_exe.py b/tools/tests/test_native_hook_proc_exe.py index fdf6e615ab..59b60d9af4 100644 --- a/tools/tests/test_native_hook_proc_exe.py +++ b/tools/tests/test_native_hook_proc_exe.py @@ -57,6 +57,16 @@ class NativeHookProcExeTest(unittest.TestCase): (cls.root / "usr/bin").mkdir(parents=True) cls.kwin = cls.root / "usr/bin/kwin_wayland" shutil.copy(tmp / "sleeper", cls.kwin) + cls.runtime = tmp / "runtime" + cls.runtime.mkdir() + cls.bound = cls.runtime / "chrome" + shutil.copy(tmp / "sleeper", cls.bound) + cls.shadowed = cls.runtime / "bin/chrome" + cls.shadowed.parent.mkdir() + shutil.copy(tmp / "sleeper", cls.shadowed) + cls.override = tmp / "override" + cls.override.mkdir() + shutil.copy(tmp / "sleeper", cls.override / "chrome") # The child's /proc/<pid>/exe must name the loader, as DroidDeck's libddexec.so does. cls.loader = tmp / "lib/libddexec.so" cls.loader.parent.mkdir() @@ -85,8 +95,10 @@ class NativeHookProcExeTest(unittest.TestCase): self.assertEqual("ready", child.stdout.readline().strip()) return child.pid - def readlink(self, *paths): + def readlink(self, *paths, binds=None): hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} + if binds: + hook_env["DDNATV_BINDS"] = binds env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"} if self.prefix: cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] @@ -108,6 +120,17 @@ class NativeHookProcExeTest(unittest.TestCase): at = f"at:/proc/{pid}" self.assertEqual("/usr/bin/kwin_wayland", self.readlink(at)[at]) + def test_a_guest_program_from_a_bind_is_named_by_its_guest_path(self): + pid = self.start(loader=True, real_exe=str(self.bound), program=self.bound) + link = f"/proc/{pid}/exe" + self.assertEqual("/app/extra/chrome", self.readlink(link, binds=f"/proc:/proc|{self.runtime}:/app/extra")[link]) + + def test_a_guest_program_shadowed_by_a_nested_bind_keeps_its_own_path(self): + pid = self.start(loader=True, real_exe=str(self.shadowed), program=self.shadowed) + link = f"/proc/{pid}/exe" + binds = f"/proc:/proc|{self.runtime}:/app|{self.override}:/app/bin" + self.assertEqual(str(self.shadowed), self.readlink(link, binds=binds)[link]) + def test_a_program_named_only_in_the_environment_is_not_believed(self): pid = self.start(loader=True, real_exe=str(self.kwin)) link = f"/proc/{pid}/exe" From 7905e2f8ba4671401cde649ef51d2a5b3cd3dc3e Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Tue, 24 Nov 2026 01:24:39 -0500 Subject: [PATCH 094/141] fix(ui): Stores is back on the bar by default (#3115) The tab layout from #2798 moved Stores into More for anyone who never arranged their tabs, so the Battle.net and Epic launchers on the Stores page looked gone after updating from Stable. A layout someone saved is kept. --- .../main/java/com/droiddeck/launcher/ui/NavTabs.kt | 2 +- .../java/com/droiddeck/launcher/ui/NavTabsTest.kt | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt b/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt index 99785c488a..c9c469dad0 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt @@ -27,7 +27,7 @@ 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("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 DEFAULT_HIDDEN = setOf("android-apps", "agent") private val SHELVED_WHEN_NEW = setOf("storage", "sync", "decky", "boot-movies", "android-apps", "agent") private val OLD_ORDER = listOf("steam", "games", "soundtracks", "stores", "downloads", "desktop", "agent", "components", "android-apps", "storage", "sync", "setup", "updates") diff --git a/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt index 8e9fcad74a..84bdf7ad49 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt @@ -40,8 +40,8 @@ class NavTabsTest { } @Test fun aFreshInstallShowsTheDefaultBarMoreAndHiddenTabs() { - assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", NavTabs.MORE), navigationKeys(state())) - assertEquals(listOf("stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(state())) + assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", NavTabs.MORE), navigationKeys(state())) + assertEquals(listOf("soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(state())) assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "android-apps")) assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "agent")) assertFalse(com.droiddeck.launcher.agent.AgentTab.shown) @@ -51,13 +51,13 @@ class NavTabsTest { @Test fun showingMusicOnceKeepsItShownAfterReload() { place("soundtracks", TabPlace.BAR) NavTabs.load(ctx) - assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "soundtracks", NavTabs.MORE), navigationKeys(state())) + assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", NavTabs.MORE), navigationKeys(state())) } @Test fun shelvedTabsLeaveTheBarAndAddMoreAtTheEnd() { place("desktop", TabPlace.MORE) val s = state() - assertEquals(listOf("desktop", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(s)) + assertEquals(listOf("desktop", "soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(s)) assertEquals(NavTabs.MORE, navigationKeys(s).last()) assertFalse("desktop" in navigationKeys(s)) } @@ -70,14 +70,14 @@ class NavTabsTest { } @Test fun resettingPutsBackTheDefaultLayout() { - place("stores", TabPlace.BAR) + place("stores", TabPlace.MORE) place("updates", TabPlace.HIDDEN) moveTab("downloads", -1) assertFalse(NavTabs.isDefault()) NavTabs.reset(ctx) NavTabs.load(ctx) assertTrue(NavTabs.isDefault()) - assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", NavTabs.MORE), navigationKeys(state())) + assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", NavTabs.MORE), navigationKeys(state())) } @Test fun anOldLayoutKeepsWhatItsSwitchesShowed() { From 627344ea306edfb48b571baf81cdb16336411233 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:49:49 -0500 Subject: [PATCH 095/141] fix(ci): Robolectric's jar cache restores on every runner (#3134) --- .github/workflows/build.yml | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index abb5207142..f3d1132a1b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -697,11 +697,27 @@ jobs: 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: ~/.m2/repository/org/robolectric/android-all-instrumented - key: robolectric-android-all-${{ steps.robolectric.outputs.version }} + path: ../robolectric-jars + key: robolectric-android-all-v2-${{ steps.robolectric.outputs.version }} - name: Unit tests id: unit-tests env: From 1534cf1c9304dbb1b95ddf8cd0ff975988582ae5 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:08:14 -0500 Subject: [PATCH 096/141] fix(ci): cache the Windows launcher services so hosted runners finish within the job limit (#3139) * fix(ci): cache the Windows launcher services so hosted runners finish within the job limit * fix(ci): save each launcher build as soon as it finishes, and install both linkers for Rockstar --- .github/workflows/build.yml | 42 +++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f3d1132a1b..43d90e5d17 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -572,23 +572,65 @@ 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: From e2d87c50839e4dc62a926c00cd77df863a9b8526 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:45:54 -0500 Subject: [PATCH 097/141] feat(tools): pre_pr.sh runs the CI checks the fast loop skips, for what the branch changes (#3119) * feat(tools): pre_pr.sh runs the CI checks the fast loop skips, for what the branch changes * fix(tools): pre_pr.sh checks authorship with no file changes and skips deleted tests * docs(agents): pre_pr.sh picks tests by name * docs(agents): pre_pr.sh compiles and lints only for app changes --- AGENTS.md | 1 + tools/pre_pr.sh | 84 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100755 tools/pre_pr.sh diff --git a/AGENTS.md b/AGENTS.md index 494b630d9c..97930d6563 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,6 +27,7 @@ # 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. diff --git a/tools/pre_pr.sh b/tools/pre_pr.sh new file mode 100755 index 0000000000..dc493f7aac --- /dev/null +++ b/tools/pre_pr.sh @@ -0,0 +1,84 @@ +#!/usr/bin/env bash +# Runs the CI checks the fast deploy loop skips, limited to what this branch changes. +set -euo pipefail +repo_root=$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd) +cd "${repo_root}" +base_ref=${1:-origin/main} + +git fetch -q origin main 2>/dev/null || echo "Could not fetch origin/main; comparing with the local copy." >&2 +base=$(git merge-base "${base_ref}" HEAD) +changed=() +while IFS= read -r path; do changed+=("${path}"); done \ + < <({ git diff --name-only "${base}"; git ls-files --others --exclude-standard; } | sort -u) +failed=() +run() { + local name=$1 + shift + echo "== ${name}" + if "$@"; then echo "ok: ${name}"; else failed+=("${name}"); echo "FAILED: ${name}"; fi +} + +run "human authorship" python3 tools/release/check_authorship.py "${base}..HEAD" +if [[ ${#changed[@]} -eq 0 ]]; then + [[ ${#failed[@]} -eq 0 ]] || exit 1 + echo "No files differ from ${base_ref}." + exit 0 +fi + +behind=$(git rev-list --count "HEAD..${base_ref}") +if [[ "${behind}" != 0 ]]; then + echo "== merge onto ${base_ref}" + if git merge-tree --write-tree HEAD "${base_ref}" >/dev/null 2>&1; then + echo "${behind} commits behind ${base_ref}. CI compiles the merge, so rebase before pushing if they touch code you use." + else + failed+=("merge onto ${base_ref}") + echo "FAILED: the branch conflicts with ${base_ref}; CI cannot merge it." + fi +fi + +app=0 settings=0 +tests=() python_tests=() +for path in "${changed[@]}"; do + case "${path}" in + app/src/main/*|app/build.gradle|gradle.properties|gradle/*) app=1 ;; + app/src/test/*Test.kt) app=1; [[ ! -f "${path}" ]] || tests+=("$(basename "${path}" .kt)") ;; + esac + case "${path}" in + */SettingsIndex.kt) settings=1 ;; + esac + if [[ "${path}" == app/src/main/java/*.kt && -f "${path}" ]]; then + while IFS= read -r test; do tests+=("$(basename "${test}" .kt)"); done \ + < <(find app/src/test -name "$(basename "${path}" .kt)*Test.kt") + fi + if [[ "${path}" == tools/tests/test_*.py ]]; then + [[ ! -f "${path}" ]] || python_tests+=("${path}") + elif [[ "${path}" == tools/* && "${path}" != tools/tests/* ]]; then + while IFS= read -r test; do python_tests+=("${test}"); done \ + < <(grep -lF "${path#tools/}" tools/tests/test_*.py 2>/dev/null || true) + fi +done +[[ "${settings}" == 0 ]] || tests+=(SettingsMapTest) + +if [[ "${app}" == 1 ]]; then + gradle_tasks=(:app:compileReleaseKotlin :app:lintVitalRelease) + test_args=() + if [[ ${#tests[@]} -gt 0 ]]; then + gradle_tasks+=(:app:testReleaseUnitTest) + for test in $(printf '%s\n' "${tests[@]}" | sort -u); do test_args+=(--tests "*.${test}"); done + fi + run "Kotlin, lint and $((${#test_args[@]} / 2)) unit test classes" \ + ./gradlew -q -PskipRust=true -PallowStaleRuntime=true "${gradle_tasks[@]}" ${test_args[@]+"${test_args[@]}"} +fi + +if [[ ${#python_tests[@]} -gt 0 ]]; then + modules=() + while IFS= read -r test; do modules+=("tools.tests.$(basename "${test}" .py)"); done \ + < <(printf '%s\n' "${python_tests[@]}" | sort -u) + run "${#modules[@]} Python test modules" python3 -m unittest "${modules[@]}" +fi + +if [[ ${#failed[@]} -gt 0 ]]; then + printf 'Failed: %s\n' "${failed[@]}" >&2 + exit 1 +fi +echo "Pre-PR checks passed. CI still runs the full suites." From 46ec222fa55fd66655cbbb6ae6ebed5d97884df9 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:11:13 -0500 Subject: [PATCH 098/141] fix(ui): apps launched to either screen open where you chose (#3093) --- .../droiddeck/launcher/FrontEndActivity.kt | 32 +++++++---- .../com/droiddeck/launcher/SessionActivity.kt | 9 ++- .../droiddeck/launcher/input/DualScreen.kt | 5 +- .../droiddeck/launcher/ui/DualScreenPanel.kt | 57 +++++++++++++++++++ .../droiddeck/launcher/ui/FrontEndScreen.kt | 5 +- .../droiddeck/launcher/ui/FrontEndSetup.kt | 2 +- .../droiddeck/launcher/ui/SessionOverlay.kt | 1 + app/src/main/res/values/strings.xml | 3 +- .../launcher/input/DualScreenTest.kt | 12 ++++ 9 files changed, 108 insertions(+), 18 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index 9497fe0a68..c1da6a958a 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -717,6 +717,7 @@ 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) @@ -1355,6 +1356,7 @@ 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, @@ -2316,6 +2318,9 @@ 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) @@ -2336,17 +2341,24 @@ 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) - 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) + 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() } - android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_SHORT).show() + } + if (displayId != null && displayId == com.droiddeck.launcher.ui.DualScreenPanel.shownOn) { + com.droiddeck.launcher.ui.DualScreenPanel.makeRoomForApp(this, displayId, open) + } else { + open() } } diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index dc0559251b..7fef8a136c 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -850,8 +850,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde SessionState.bottomMenu = false SessionState.secondScreenProvisional = false SessionState.secondScreenAutomatic = false - SessionState.gameOnBottom = false - gameOnBottom = false + SessionState.gameOnBottom = SessionPrefs.dualScreenSessionMode(this) == com.droiddeck.launcher.input.DualScreen.MODE_SWAPPED + gameOnBottom = SessionState.gameOnBottom } if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) { SessionState.program = intent.getStringExtra(SessionService.EXTRA_PROGRAM) @@ -4405,6 +4405,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde 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) diff --git a/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt b/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt index a4de922ca7..277a7b5d11 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt @@ -14,7 +14,8 @@ object DualScreen { const val MODE_AUTO = "auto" const val MODE_ON = "on" const val MODE_OFF = "off" - val modes = listOf(MODE_AUTO, MODE_ON, MODE_OFF) + const val MODE_SWAPPED = "swapped" + val modes = listOf(MODE_AUTO, MODE_ON, MODE_SWAPPED, MODE_OFF) private const val TYPE_INTERNAL = 1 private const val TYPE_EXTERNAL = 2 private val knownModels = setOf("retroid pocket duo", "ayn thor") @@ -99,7 +100,7 @@ object DualScreen { fun display(context: Context, displayManager: DisplayManager, primaryDisplayId: Int, mode: String = SessionPrefs.dualScreenMode(context)): Display? = when (mode) { MODE_OFF -> null - MODE_ON -> internalDisplay(displayManager, primaryDisplayId) ?: anyDisplay(displayManager, primaryDisplayId) + MODE_ON, MODE_SWAPPED -> internalDisplay(displayManager, primaryDisplayId) ?: anyDisplay(displayManager, primaryDisplayId) else -> if (dockedToDisplay(displayManager, primaryDisplayId)) null else builtInDisplay(displayManager, primaryDisplayId) }?.takeUnless { taken(it.displayId) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DualScreenPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/DualScreenPanel.kt index 3ea7950600..43b50251b0 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DualScreenPanel.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DualScreenPanel.kt @@ -148,7 +148,61 @@ 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 @@ -169,6 +223,9 @@ 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 } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt index c2f49c2ef2..5ed7ab881e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -143,6 +143,7 @@ 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, @@ -802,7 +803,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com }, { selected = it }, onAndroidAppClick = { app -> - if (s.secondScreenDisplays.isEmpty()) a.onAndroidApp(app, null) + if (s.secondScreenDisplays.isEmpty() && s.ownScreen == null) a.onAndroidApp(app, null) else appToChooseDisplay = app }, onOpenDeveloperOptions = requestChildProcessToggle, @@ -823,7 +824,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com SessionDrawerPreview(s.secondScreenDisplays) appToChooseDisplay?.let { app -> - val secondaryDisplay = s.secondScreenDisplays.firstOrNull() + val secondaryDisplay = s.secondScreenDisplays.firstOrNull() ?: s.ownScreen ChooseAppDisplayDialog( app = app, secondaryDisplay = secondaryDisplay, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt index c99bee629d..66f1b24d65 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -542,7 +542,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, s.dualScreenSessions, onPick = a.onDualScreenSessions, + 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, ) if (s.dualScreenSessions != com.droiddeck.launcher.input.DualScreen.MODE_OFF) { ToggleRow(host, "dual-screen-controls", stringResource(R.string.setup_dual_screen_controls), diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index b84a27be75..401ca5face 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -1519,6 +1519,7 @@ private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String) 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, diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 44bdf9c825..d02b7a955d 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1041,10 +1041,11 @@ <string name="setup_dual_screen_launcher">Dual screen launcher</string> <string name="setup_dual_screen_launcher_hint">Automatic puts the launcher sections (Steam, Library, Stores and the rest) on the second screen of handhelds with a built-in one. On uses any second display. Off keeps the launcher on one screen.</string> <string name="setup_dual_screen_sessions">Dual screen sessions</string> - <string name="setup_dual_screen_sessions_hint">Automatic docks the in-game menu on the built-in second screen instead of a pop-over. On uses any second display. Off keeps the menu on the game screen; you can still pick a second screen from it.</string> + <string name="setup_dual_screen_sessions_hint">Automatic docks the in-game menu on the built-in second screen instead of a pop-over. On uses any second display. On, game on second screen runs the game there and keeps the menu and controls on this screen, for a phone driving a monitor or TV. Off keeps the menu on the game screen; you can still pick a second screen from it.</string> <string name="setup_dual_screen_auto">Automatic</string> <string name="setup_dual_screen_on">On</string> <string name="setup_dual_screen_off">Off</string> + <string name="setup_dual_screen_swapped">On, game on second screen</string> <string name="setup_dual_screen_controls">Bottom screen controls in games</string> <string name="setup_android_text_field_keyboard">Android keyboard for text fields</string> <string name="setup_dual_screen_controls_hint">Opens a panel on the second screen when a session starts: the Deck buttons and trackpads with a Steam Deck or Steam Controller, otherwise the one you used last.</string> diff --git a/app/src/test/java/com/droiddeck/launcher/input/DualScreenTest.kt b/app/src/test/java/com/droiddeck/launcher/input/DualScreenTest.kt index 02380b0f25..078b3e3fdc 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/DualScreenTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/DualScreenTest.kt @@ -187,6 +187,18 @@ class DualScreenTest { assertEquals(DualScreen.MODE_OFF, SessionPrefs.dualScreenMode(context)) } + @Test @Config(sdk = [34]) fun gameOnSecondScreenUsesTheSameDisplayAsOn() { + withDisplay(EXTERNAL, "HDMI Screen") { monitor -> + assertEquals(monitor.displayId, DualScreen.display(context, displays, Display.DEFAULT_DISPLAY, DualScreen.MODE_SWAPPED)?.displayId) + assertNull(DualScreen.display(context, displays, Display.DEFAULT_DISPLAY, DualScreen.MODE_AUTO)) + } + } + + @Test fun gameOnSecondScreenIsASavedSessionMode() { + SessionPrefs.setDualScreenSessionMode(context, DualScreen.MODE_SWAPPED) + assertEquals(DualScreen.MODE_SWAPPED, SessionPrefs.dualScreenSessionMode(context)) + } + @Test fun launcherAndSessionsKeepSeparateModes() { SessionPrefs.setDualScreenMode(context, DualScreen.MODE_OFF) assertEquals(DualScreen.MODE_OFF, SessionPrefs.dualScreenMode(context)) From 39debda0b01f9ddb081c900910d91834ac0aa295 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:56:08 -0500 Subject: [PATCH 099/141] fix(onboarding): a smoother first run, from the child-process setting to the Steam sign-in (#3114) The child-process fix always uses the guided pairing flow, Finish setup opens the setting directly and queues the Steam launch, the Play button carries the first-run progress, the setup bar weighs each download by its real size, and the Steam client packages download over four connections and unpack one at a time under a flock. --- .../droiddeck/launcher/ui/PreviewSupport.kt | 2 +- .../droiddeck/launcher/FrontEndActivity.kt | 116 +++- .../launcher/PairingGuideActivity.kt | 8 + .../core/WirelessAdbPairingService.kt | 41 +- .../launcher/session/LoadingState.kt | 13 +- .../droiddeck/launcher/session/Onboarding.kt | 61 +- .../launcher/session/QueuedLaunch.kt | 38 ++ .../launcher/session/QueuedLaunchRunner.kt | 51 ++ .../launcher/session/SteamClientPrefetch.kt | 1 + .../com/droiddeck/launcher/ui/AdbTextField.kt | 239 +++++++ .../droiddeck/launcher/ui/FrontEndScreen.kt | 71 +- .../droiddeck/launcher/ui/FrontEndSetup.kt | 3 +- .../droiddeck/launcher/ui/FrontEndWidgets.kt | 7 + .../launcher/ui/PhantomProcessGatePage.kt | 30 +- .../com/droiddeck/launcher/ui/SteamHome.kt | 61 +- .../launcher/ui/WirelessAdbFixPage.kt | 631 ------------------ app/src/main/res/values-ar/strings.xml | 39 -- app/src/main/res/values-b+es+419/strings.xml | 39 -- app/src/main/res/values-bg/strings.xml | 39 -- app/src/main/res/values-cs/strings.xml | 39 -- app/src/main/res/values-da/strings.xml | 39 -- app/src/main/res/values-de/strings.xml | 39 -- app/src/main/res/values-el/strings.xml | 39 -- app/src/main/res/values-es/strings.xml | 39 -- app/src/main/res/values-fi/strings.xml | 39 -- app/src/main/res/values-fr/strings.xml | 39 -- app/src/main/res/values-hi/strings.xml | 39 -- app/src/main/res/values-hu/strings.xml | 39 -- app/src/main/res/values-in/strings.xml | 39 -- app/src/main/res/values-it/strings.xml | 39 -- app/src/main/res/values-ja/strings.xml | 39 -- app/src/main/res/values-ko/strings.xml | 39 -- app/src/main/res/values-ms/strings.xml | 39 -- app/src/main/res/values-nb/strings.xml | 39 -- app/src/main/res/values-nl/strings.xml | 39 -- app/src/main/res/values-pl/strings.xml | 39 -- app/src/main/res/values-pt-rPT/strings.xml | 39 -- app/src/main/res/values-pt/strings.xml | 39 -- app/src/main/res/values-ro/strings.xml | 39 -- app/src/main/res/values-ru/strings.xml | 39 -- app/src/main/res/values-sv/strings.xml | 39 -- app/src/main/res/values-th/strings.xml | 39 -- app/src/main/res/values-tr/strings.xml | 39 -- app/src/main/res/values-uk/strings.xml | 39 -- app/src/main/res/values-vi/strings.xml | 39 -- app/src/main/res/values-zh-rCN/strings.xml | 39 -- app/src/main/res/values-zh-rHK/strings.xml | 39 -- app/src/main/res/values-zh-rTW/strings.xml | 39 -- app/src/main/res/values/strings.xml | 47 +- .../launcher/session/OnboardingTest.kt | 31 +- .../session/QueuedLaunchRunnerTest.kt | 116 ++++ .../launcher/session/QueuedLaunchTest.kt | 49 ++ .../droiddeck/launcher/ui/CurseLinkTabTest.kt | 2 +- .../launcher/ui/DesktopUninstallTest.kt | 2 +- .../droiddeck/launcher/ui/FlathubFocusTest.kt | 2 +- .../launcher/ui/GamesClientTagTest.kt | 2 +- .../launcher/ui/GlobalGlassesSettingsTest.kt | 2 +- .../launcher/ui/InputUiLayoutTest.kt | 2 +- .../ui/LaunchSettingsComponentsTest.kt | 2 +- .../launcher/ui/LibraryVisibilityTest.kt | 2 +- .../com/droiddeck/launcher/ui/NavTabsTest.kt | 2 +- .../launcher/ui/NavigationSelectionTest.kt | 2 +- .../launcher/ui/PortraitLayoutTest.kt | 2 +- .../launcher/ui/SteamHomeHeadsetTest.kt | 2 +- .../launcher/ui/StoreRestorationTest.kt | 2 +- .../usr/local/bin/droiddeck-steam-install | 140 ++++ tools/tests/test_steam_install.py | 199 +++++- 67 files changed, 1151 insertions(+), 2078 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/session/QueuedLaunch.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/session/QueuedLaunchRunner.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/ui/AdbTextField.kt delete mode 100644 app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/session/QueuedLaunchRunnerTest.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/session/QueuedLaunchTest.kt diff --git a/app/src/debug/java/com/droiddeck/launcher/ui/PreviewSupport.kt b/app/src/debug/java/com/droiddeck/launcher/ui/PreviewSupport.kt index fc83727e11..96a958e719 100644 --- a/app/src/debug/java/com/droiddeck/launcher/ui/PreviewSupport.kt +++ b/app/src/debug/java/com/droiddeck/launcher/ui/PreviewSupport.kt @@ -61,7 +61,7 @@ internal val sampleActions: FrontEndActions = FrontEndActions( onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, onSetPhantomProcessLimit = { _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, ) /** The in-game menu's actions with settled sample values; its switches do nothing. */ diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index c1da6a958a..1324603ef1 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -1255,6 +1255,10 @@ 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) @@ -1404,6 +1408,9 @@ 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( @@ -1775,31 +1782,6 @@ 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) } @@ -1816,18 +1798,14 @@ 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 = { showPhantomGate = false }, + onDismissPhantomGate = { queuedLaunch.clear(); showPhantomGate = false }, onShowPhantomGate = { refreshPhantomStatus() showPhantomGate = true }, - onStartWirelessAdbPairing = { WirelessAdbPairingService.start(this) }, + onStartWirelessAdbPairing = { enabled -> WirelessAdbPairingService.start(this, enabled) }, onStartPairingGuide = { displayId, toggleOnly -> PairingGuideActivity.start(this, displayId, toggleOnly) }, - onOpenNotificationSettings = { - startActivity(Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS) - .putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, packageName) - .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) - }, + onEnsureNotifications = { done -> ensureNotifications(done) }, updates = updates.actions(), controller = ControllerActions( onMapping = { showPerformance = false; showComponents = false; showMapping = true }, @@ -2007,7 +1985,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) + startSession(Intent(this, SessionActivity::class.java).putExtra(SessionActivity.EXTRA_STEAMVR, steamVr), steamSession = true, queueIfBlocked = !steamVr) } @Suppress("OVERRIDE_DEPRECATION") @@ -2230,6 +2208,10 @@ 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) } @@ -2256,6 +2238,8 @@ 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() @@ -3355,7 +3339,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet install(release) } - private fun startSession(intent: Intent, steamSession: Boolean = false): Boolean { + private fun startSession(intent: Intent, steamSession: Boolean = false, queueIfBlocked: 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() @@ -3367,6 +3351,7 @@ 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 } @@ -3376,8 +3361,64 @@ 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( @@ -3389,7 +3430,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) null else "toggle_adb_wireless" + WirelessAdbPairingService.stage.value == WirelessAdbPairingService.Stage.Idle) "disable_phantom_process_monitor" 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) } @@ -3508,7 +3549,12 @@ 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" diff --git a/app/src/main/java/com/droiddeck/launcher/PairingGuideActivity.kt b/app/src/main/java/com/droiddeck/launcher/PairingGuideActivity.kt index 5632c08546..8347bb65c4 100644 --- a/app/src/main/java/com/droiddeck/launcher/PairingGuideActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/PairingGuideActivity.kt @@ -93,6 +93,14 @@ 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 diff --git a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt index 2d6adb902b..f7097dce7c 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt @@ -38,6 +38,8 @@ 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 @@ -50,12 +52,15 @@ class WirelessAdbPairingService : Service() { onCode(code) } ACTION_CANCEL -> finish(Stage.Idle) - else -> begin() + else -> begin(intent?.getBooleanExtra(EXTRA_ENABLE_LIMIT, false) == true) } return START_NOT_STICKY } - private fun begin() { + private fun begin(enableLimit: Boolean) { + if (working) return + session++ + limitEnabled = enableLimit pairingHost = null pairingPort = null working = false @@ -68,12 +73,13 @@ 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()) } + runCatching { manager.resolveService(serviceInfo, resolveListener(owner)) } } override fun onServiceLost(serviceInfo: NsdServiceInfo) = Unit override fun onDiscoveryStopped(serviceType: String) = Unit @@ -87,18 +93,20 @@ class WirelessAdbPairingService : Service() { .onFailure { finish(Stage.Failed(getString(R.string.adbpair_discovery_failed, it.localizedMessage.toString()))) } } - private fun resolveListener() = object : NsdManager.ResolveListener { + private fun resolveListener(owner: Int): NsdManager.ResolveListener { + return 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 (working || current.value == Stage.Done) return@post + if (owner != session || 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) { @@ -114,29 +122,34 @@ 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 { show(Stage.Working(getString(R.string.adbpair_applying))) } - WirelessAdbFix.setChildProcessLimit(this, WirelessAdbFix.LOOPBACK, connectPort, false) + main.post { if (owner == session) show(Stage.Working(getString(R.string.adbpair_applying))) } + WirelessAdbFix.setChildProcessLimit(this, WirelessAdbFix.LOOPBACK, connectPort, enable) } 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() @@ -148,6 +161,7 @@ class WirelessAdbPairingService : Service() { } private fun finish(stage: Stage) { + session++ main.removeCallbacks(timeout) stopDiscovery() publish(stage) @@ -248,6 +262,7 @@ 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) @@ -255,10 +270,10 @@ class WirelessAdbPairingService : Service() { private fun publish(stage: Stage) { current.value = stage } - fun start(context: Context) { + fun start(context: Context, enableLimit: Boolean = false) { context.getSystemService(NotificationManager::class.java)?.cancel(NOTIFICATION_ID) publish(Stage.Waiting) - val intent = Intent(context, WirelessAdbPairingService::class.java) + val intent = Intent(context, WirelessAdbPairingService::class.java).putExtra(EXTRA_ENABLE_LIMIT, enableLimit) if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) else context.startService(intent) } @@ -271,6 +286,12 @@ class WirelessAdbPairingService : Service() { } fun notificationsEnabled(context: Context): Boolean = - context.getSystemService(NotificationManager::class.java)?.areNotificationsEnabled() != false + 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 } } diff --git a/app/src/main/java/com/droiddeck/launcher/session/LoadingState.kt b/app/src/main/java/com/droiddeck/launcher/session/LoadingState.kt index 7487b98798..6e6cfdac61 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/LoadingState.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/LoadingState.kt @@ -11,7 +11,15 @@ import java.io.RandomAccessFile import java.nio.charset.StandardCharsets class LoadingState(context: Context, private val steam: Boolean = true) { - var visible by mutableStateOf(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 step by mutableStateOf(context.getString(com.droiddeck.launcher.R.string.loadstate_starting)) private set var topic by mutableStateOf(Topic.SESSION) @@ -33,7 +41,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 = hints[((seconds / 8) % hints.size).toInt()] + hint = if (firstRun) res.getString(com.droiddeck.launcher.R.string.loading_first_run) else hints[((seconds / 8) % hints.size).toInt()] } fun say(line: String, topic: Topic, readable: Boolean) { @@ -126,6 +134,7 @@ 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 { diff --git a/app/src/main/java/com/droiddeck/launcher/session/Onboarding.kt b/app/src/main/java/com/droiddeck/launcher/session/Onboarding.kt index 5a3fb555dd..2d18a84a30 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/Onboarding.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/Onboarding.kt @@ -26,8 +26,34 @@ object Onboarding { @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. */ @@ -52,6 +78,15 @@ object Onboarding { 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) { @@ -85,9 +120,29 @@ object Onboarding { fun pending(rows: List<Row>): Boolean = rows.any { it.state != State.DONE } - /** The aggregate fraction of the whole first-run work, weighting each step by what it downloads. */ - fun overall(rows: List<Row>): Int { - val weights = mapOf(Step.RUNTIME to 60, Step.PROTON to 15, Step.STEAM to 25) + /** 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) diff --git a/app/src/main/java/com/droiddeck/launcher/session/QueuedLaunch.kt b/app/src/main/java/com/droiddeck/launcher/session/QueuedLaunch.kt new file mode 100644 index 0000000000..b4d1f97054 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/QueuedLaunch.kt @@ -0,0 +1,38 @@ +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 +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/QueuedLaunchRunner.kt b/app/src/main/java/com/droiddeck/launcher/session/QueuedLaunchRunner.kt new file mode 100644 index 0000000000..ab2939a481 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/QueuedLaunchRunner.kt @@ -0,0 +1,51 @@ +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 + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/SteamClientPrefetch.kt b/app/src/main/java/com/droiddeck/launcher/session/SteamClientPrefetch.kt index fecdc8e0b8..66db50355a 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SteamClientPrefetch.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SteamClientPrefetch.kt @@ -61,6 +61,7 @@ object SteamClientPrefetch { 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() } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AdbTextField.kt b/app/src/main/java/com/droiddeck/launcher/ui/AdbTextField.kt new file mode 100644 index 0000000000..ad0efcec36 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/AdbTextField.kt @@ -0,0 +1,239 @@ +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 +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt index 5ed7ab881e..74bd115145 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -314,16 +314,14 @@ 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: () -> Unit = {}, + val onStartWirelessAdbPairing: (Boolean) -> Unit = {}, val onStartPairingGuide: (Int?, Boolean) -> Boolean = { _, _ -> false }, val onShowPhantomGate: () -> Unit = {}, - val onOpenNotificationSettings: () -> Unit = {}, + val onQueuePlaySteam: () -> Unit = {}, + val onEnsureNotifications: ((Boolean) -> Unit) -> Unit = { it(true) }, val controller: ControllerActions? = null, val updates: UpdatesActions = UpdatesActions(), ) @@ -509,17 +507,16 @@ 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 wirelessAdbDesiredEnabled by rememberSaveable { mutableStateOf(false) } + var guidedLimitEnabled 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 || showWirelessAdbFix || showDeveloperDisplayChoice + val processSettingsPageVisible = phantomGateVisible || showDeveloperDisplayChoice val requestDeveloperOptions = { developerChoiceGuided = false developerChoiceToggle = false @@ -527,7 +524,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com else showDeveloperDisplayChoice = true } val openDeveloperOptionsOn: (Int?) -> Unit = { displayId -> - if (developerChoiceGuided) a.onStartWirelessAdbPairing() + if (developerChoiceGuided) a.onStartWirelessAdbPairing(guidedLimitEnabled) val guided = developerChoiceGuided || developerChoiceToggle if (!guided || !a.onStartPairingGuide(displayId, developerChoiceToggle)) a.onOpenDeveloperOptions(displayId) developerChoiceGuided = false @@ -543,31 +540,35 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com 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 startGuidedPairing: (Boolean) -> Unit = { enabled -> + a.onEnsureNotifications { granted -> + if (granted) { + guidedLimitEnabled = enabled + 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() + if (!s.adbPaired || !com.droiddeck.launcher.core.GlobalSettings.wirelessDebuggingOn(ctx)) startGuidedPairing(false) else if (!applyingSavedPairing) { applyingSavedPairing = true a.onSetPhantomProcessLimit(false) { error -> applyingSavedPairing = false - if (error != null) startGuidedPairing() + if (error != null) startGuidedPairing(false) } } } - val requestWirelessAdbFix: (Boolean) -> Unit = { enabled -> - wirelessAdbDesiredEnabled = enabled - showWirelessAdbFix = true - } LaunchedEffect(s.showPhantomGate, s.phantomProcessStatus) { if (phantomGateVisible) { while (true) { @@ -807,8 +808,8 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com else appToChooseDisplay = app }, onOpenDeveloperOptions = requestChildProcessToggle, - onRequestWirelessAdb = requestWirelessAdbFix, - onPairWirelessDebugging = startGuidedPairing, + onPairWirelessDebugging = { startGuidedPairing(false) }, + onRequestWirelessAdb = startGuidedPairing, ) } @@ -839,7 +840,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com onDismiss = { appToChooseDisplay = null }, ) } - if (phantomGateVisible && !showWirelessAdbFix) { + if (phantomGateVisible) { Box(Modifier.fillMaxSize().background(colors.background)) { PhantomProcessGatePage( status = s.phantomProcessStatus, @@ -847,21 +848,7 @@ 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, ) } } @@ -907,6 +894,10 @@ 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 } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt index 66f1b24d65..0062c67b24 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -1282,7 +1282,8 @@ internal fun OnboardingCard(limitBlocks: Boolean = false, onSetUpLimit: () -> Un 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 settling = com.droiddeck.launcher.session.Onboarding.pending(rows) + 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 diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt index faa4667306..4245236747 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt @@ -205,10 +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 @@ -234,6 +236,11 @@ 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) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt b/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt index 7f633fcf4f..2b07301b9a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt @@ -50,9 +50,7 @@ fun PhantomProcessGatePage( onDismiss: () -> Unit, onOpenDeveloperOptions: () -> Unit, onFixWithWirelessDebugging: () -> Unit, - onEnterAddressManually: () -> Unit, onCopyCommand: () -> Unit, - onOpenNotificationSettings: () -> Unit, ) { BackHandler(onBack = onDismiss) val context = LocalContext.current @@ -82,11 +80,11 @@ fun PhantomProcessGatePage( val fix: @Composable ColumnScope.() -> Unit = { if (sideQuest) SideQuestGroup(compact, onCopyCommand) else FixGroup(hasToggle, stage, environment, compact, applyingSavedPairing, onOpenDeveloperOptions, onFixWithWirelessDebugging, - onOpenNotificationSettings, onCancel = { WirelessAdbPairingService.cancel(context) }) + onCancel = { WirelessAdbPairingService.cancel(context) }) } val side: @Composable ColumnScope.() -> Unit = { StatusGroup(status, compact) - if (!sideQuest) OtherWays(hasToggle, compact, onOpenDeveloperOptions, onFixWithWirelessDebugging, onEnterAddressManually, onCopyCommand) + if (!sideQuest) OtherWays(hasToggle, compact, onOpenDeveloperOptions, onFixWithWirelessDebugging, onCopyCommand) } if (wide) { Row(horizontalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.widthIn(max = 900.dp).fillMaxWidth()) { @@ -104,15 +102,16 @@ fun PhantomProcessGatePage( } } -private data class GateEnvironment(val onWifi: Boolean, val notifications: Boolean) { +private data class GateEnvironment(val onWifi: Boolean) { companion object { fun read(context: Context): GateEnvironment { val connectivity = context.getSystemService(ConnectivityManager::class.java) val wifi = runCatching { - connectivity?.getNetworkCapabilities(connectivity.activeNetwork) - ?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true + connectivity?.allNetworks?.any { network -> + connectivity.getNetworkCapabilities(network)?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true + } == true }.getOrDefault(true) - return GateEnvironment(wifi, WirelessAdbPairingService.notificationsEnabled(context)) + return GateEnvironment(wifi) } } } @@ -126,7 +125,6 @@ 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 @@ -144,6 +142,7 @@ 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)) @@ -151,7 +150,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 && environment.notifications, + enabled = environment.onWifi, onClick = onFixWithWirelessDebugging, ) } @@ -160,10 +159,6 @@ 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) - } } } } @@ -224,7 +219,6 @@ private fun OtherWays( compact: Boolean, onOpenDeveloperOptions: () -> Unit, onFixWithWirelessDebugging: () -> Unit, - onEnterAddressManually: () -> Unit, onCopyCommand: () -> Unit, ) { var open by rememberSaveable { mutableStateOf(false) } @@ -240,14 +234,10 @@ private fun OtherWays( modifier = Modifier.fillMaxWidth().padding(start = 14.dp, end = 14.dp, bottom = 14.dp), verticalArrangement = Arrangement.spacedBy(8.dp), ) { - if (hasToggle) { - SecondaryButton(stringResource(R.string.gate_use_wireless_instead), compact = true, onClick = onFixWithWirelessDebugging) - } else { + if (!hasToggle) { 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) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt index 2d995dda2f..b966257c08 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt @@ -29,7 +29,11 @@ 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 @@ -154,43 +158,56 @@ 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 = { - 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 settling = onboardingActive.isNotEmpty() && com.droiddeck.launcher.session.Onboarding.pending(onboardingRows) - if (settling || s.busy || (s.available != null && s.available != s.installed)) { - if (settling) { - val overall = com.droiddeck.launcher.session.Onboarding.overall(onboardingRows) - Chip( - stringResource(R.string.onboarding_chip, overall, onboardingRows.firstOrNull { it.state == com.droiddeck.launcher.session.Onboarding.State.ACTIVE }?.label.orEmpty()), - ok = false, fraction = overall / 100f, - ) - } else RuntimeChip(s) - if (com.droiddeck.launcher.core.PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)) { - SecondaryButton(stringResource(R.string.onboarding_limit_while_waiting), compact = true, - modifier = Modifier.testTag("setup-while-waiting"), onClick = a.onShowPhantomGate) - } - } else if (setupNeedsAttention(s)) SecondaryButton(stringResource(R.string.play_needs_you), compact = true, + 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, modifier = Modifier.testTag("play-needs-you")) { SetupTabs.openSection = SettingsSection.OVERVIEW } - else if (s.integration.suggested && signedIn && !com.droiddeck.launcher.core.PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)) + else if (!settling && s.integration.suggested && signedIn && !limitBlocks) IntegrationSuggestion(s.integration, { a.onSteamIntegration(null) }, a.onDismissIntegration) } if (narrow) Column( verticalArrangement = Arrangement.spacedBy(12.dp), ) { - Wordmark(30.dp) + mark() runtimeStatus() } else Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), ) { - Wordmark(if (narrow) 30.dp else 40.dp) + mark() runtimeStatus() } }, button = { 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) + 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) }, rows = { tab -> a.modeSheet(mode, tab, extras) }, ) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt deleted file mode 100644 index c2e79b9c86..0000000000 --- a/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt +++ /dev/null @@ -1,631 +0,0 @@ -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, - 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)) - } - }, - ) - } - } -} - -@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 -} diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 018c08995c..36430b35d4 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1304,8 +1304,6 @@ <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> @@ -1322,48 +1320,13 @@ <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> @@ -1675,8 +1638,6 @@ <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> diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 2f30d0ba67..abb112b05f 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1310,8 +1310,6 @@ <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> @@ -1328,48 +1326,13 @@ <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> @@ -1706,8 +1669,6 @@ <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> diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index 3a2428fbfb..6efc4eff37 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -1276,8 +1276,6 @@ <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> @@ -1294,48 +1292,13 @@ <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> @@ -1623,8 +1586,6 @@ <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> diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 4c920c1cf0..9e689b9291 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1290,8 +1290,6 @@ <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> @@ -1308,48 +1306,13 @@ <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> @@ -1649,8 +1612,6 @@ <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> diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index c34b855e74..202d607a56 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -1276,8 +1276,6 @@ <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> @@ -1294,48 +1292,13 @@ <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> @@ -1623,8 +1586,6 @@ <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> diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 8715f4b3a3..13c2bee2f1 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1268,8 +1268,6 @@ <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> @@ -1286,48 +1284,13 @@ <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> @@ -1615,8 +1578,6 @@ <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> diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 93b0438ef5..e77d35a7e1 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1276,8 +1276,6 @@ <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> @@ -1294,48 +1292,13 @@ <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 προσθέτουν τον διακόπτη ούτως ή άλλως. Αναζητήστε «θυγατρική διαδικασία» στις Επιλογές προγραμματιστή.</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">Συνδέστε το headset σε υπολογιστή και ανοίξτε το 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> @@ -1623,8 +1586,6 @@ <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> diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index a8a7525c87..ee13434fb1 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1283,8 +1283,6 @@ <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 ordenador.</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> @@ -1301,48 +1299,13 @@ <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 ordenador</string> - <string name="gate_other_no_toggle">Dirección manual, ADB desde ordenador, 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 añaden el interruptor de todos modos. Busca “procesos secundarios” en Opciones de desarrollador.</string> - <string name="gate_manual_hint">Si la notificación no funciona, introduce manualmente la dirección y el código de la ventana.</string> - <string name="gate_enter_manually">Introducir dirección manualmente</string> <string name="gate_from_computer">Desde un ordenador con ADB:</string> <string name="gate_copy_command">Copiar comando</string> <string name="gate_sidequest_steps">Conecta el visor a un ordenador 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. Introduce 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 ordenador (ú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 ordenador (último recurso)</string> <string name="ctrl_color">Color</string> <string name="ctrl_custom">Personalizado</string> <string name="ctrl_opacity">Opacidad</string> @@ -1636,8 +1599,6 @@ <item quantity="many">Se borraron %1$d carpetas de registros de sesión.</item> <item quantity="other">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> diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 084d781755..9a29a70aa0 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -1276,8 +1276,6 @@ <string name="gate_open_dev">Avaa Kehittäjäasetukset</string> <string name="gate_no_toggle">Tässä Android-versiossa ei ole kytkintä tälle, niin DroidDeck muuttaa sen Langattoman virheenkorjauksen kautta. Kestää noin minuutin, ei tarvita tietokonetta.</string> <string name="gate_needs_wifi">Langaton virheenkorjaus vaatii Wi-Fi-yhteyden. Mikä tahansa verkko käy; internet-yhteyttä ei tarvita.</string> - <string name="gate_needs_notifications">Pariutuskoodi tulee ilmoitukseen. Salli ilmoitukset DroidDeckille, tai käytä Muita tapoja.</string> - <string name="gate_allow_notifications">Salli ilmoitukset</string> <string name="gate_step1">Avaa Asetukset → Kehittäjäasetukset → Langaton virheenkorjaus ja kytke se päälle</string> <string name="gate_step2">Napauta ”Pariuta laite pariutuskoodilla”</string> <string name="gate_step3">Kirjoita koodi DroidDeckin ilmoitukseen</string> @@ -1294,48 +1292,13 @@ <string name="gate_status">Tila</string> <string name="gate_polling">Tarkistetaan 2 sekunnin välein. Tämä sivu sulkeutuu, kun se on pois päältä.</string> <string name="gate_other_ways">Muita tapoja</string> - <string name="gate_other_toggle">Langaton virheenkorjaus, manuaalinen osoite, tietokoneen ADB</string> - <string name="gate_other_no_toggle">Manuaalinen osoite, tietokoneen ADB, Kehittäjäasetukset</string> <string name="gate_use_wireless_instead">Käytä sen sijaan Langatonta virheenkorjausta</string> <string name="gate_some_roms">Jotkin ROM-versiot lisäävät kytkimen joka tapauksessa. Etsi ”child process” Kehittäjäasetuksista.</string> - <string name="gate_manual_hint">Jos ilmoitus ei toimi, syötä ponnahdusikkunan osoite ja koodi itse.</string> - <string name="gate_enter_manually">Syötä osoite manuaalisesti</string> <string name="gate_from_computer">Tietokoneelta ADB:llä:</string> <string name="gate_copy_command">Kopioi komento</string> <string name="gate_sidequest_steps">Liitä lasit tietokoneeseen ja avaa SideQuest. Valitse ”Run ADB Command” ja sitten ”Custom Command”, kirjoita alla näkyvä komento ja valitse ”Run Command”.</string> <string name="gate_choose_display">Valitse, millä näytöllä Android-asetukset avataan.</string> <string name="gate_main_screen">Päänäyttö</string> - <string name="wadb_finding_port">Pariutui. Etsitään Langattoman virheenkorjauksen porttia…</string> - <string name="wadb_enter_port">Pariutui. Syötä portti Asetuksista.</string> - <string name="wadb_applying">Laite löytyi. Otetaan asetus käyttöön…</string> - <string name="wadb_apply_failed">Automaattinen käyttöönotto epäonnistui. Tarkista alla oleva osoite ja yritä uudelleen. %1$s</string> - <string name="wadb_title_wireless">Langaton virheenkorjaus</string> - <string name="wadb_title_done">Lapsiprosessien raja päivitetty</string> - <string name="wadb_title">Muuta lapsiprosessien rajaa</string> - <string name="wadb_lede_compact0">Jos asetus puuttuu, pariuta Langattoman virheenkorjauksen kautta.</string> - <string name="wadb_lede_compact1">Pariutui. Tarkista IP-osoite ja portti Langattomasta virheenkorjauksesta.</string> - <string name="wadb_lede_done">Lapsiprosessien raja päivitettiin.</string> - <string name="wadb_lede0">Käytä vaihetta 2, jos Kehittäjäasetuksissa ei ole lapsiprosessiasetusta. Avaa Kehittäjäasetukset → Langaton virheenkorjaus → Pariuta laite pariutuskoodilla.</string> - <string name="wadb_lede1">Pariutui. Käytä alla olevaa osoitetta, tai päivitä se Langaton virheenkorjaus → IP-osoite ja portti -kohdasta.</string> - <string name="wadb_lede_done_long">Lapsiprosessien raja päivitettiin Langattoman virheenkorjauksen kautta.</string> - <string name="wadb_confirmed_on">Android vahvisti, että raja on päällä.</string> - <string name="wadb_confirmed_off">Android vahvisti, että raja on pois päältä.</string> - <string name="wadb_pair_group">2 · Pariuta Langaton virheenkorjaus</string> - <string name="wadb_pair_address">Pariutuksen ponnahdusikkunan IP-osoite ja portti</string> - <string name="wadb_pin">Pariutuskoodi (PIN)</string> - <string name="wadb_pin_placeholder">6 numeroa</string> - <string name="wadb_pair">Pariuta</string> - <string name="wadb_apply_group">2 · Ota käyttöön Langattoman virheenkorjauksen kautta</string> - <string name="wadb_connect_address">Yhteyden IP-osoite ja portti</string> - <string name="wadb_pair_again">Pariuta uudelleen</string> - <string name="wadb_turn_off">Kytke raja pois päältä</string> - <string name="wadb_other_ways">Muita tapoja muuttaa sitä</string> - <string name="wadb_dev_try_first">1 · Kehittäjäasetukset (kokeile ensin)</string> - <string name="wadb_restrict_on">Aseta ”Poista käytöstä alatason prosessirajoitukset” pois päältä.</string> - <string name="wadb_restrict_off">Aseta ”Poista käytöstä alatason prosessirajoitukset” päälle.</string> - <string name="wadb_computer_last">3 · Tietokoneen ADB (viimeinen keino)</string> - <string name="wadb_only_if">Vain jos Langaton virheenkorjaus ei ole käytettävissä.</string> - <string name="wadb_computer_group">3 · Tietokoneen ADB (viimeinen keino)</string> <string name="ctrl_color">Väri</string> <string name="ctrl_custom">Mukautettu</string> <string name="ctrl_opacity">Peittävyys</string> @@ -1623,8 +1586,6 @@ <item quantity="one">Tyhjennettiin %1$d istuntolokikansio.</item> <item quantity="other">Tyhjennettiin %1$d istuntolokikansiota.</item> </plurals> - <string name="main_wadb_pair_failed">Langattoman virheenkorjauksen laitepariutus epäonnistui</string> - <string name="main_wadb_command_failed">Langattoman virheenkorjauksen komento epäonnistui</string> <string name="main_wadb_unavailable">Langaton virheenkorjaus ei ole käytettävissä</string> <string name="main_adb_copied">ADB-komento kopioitu</string> <string name="main_pick_roms">Valitse ROMs-kansio</string> diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index c12f0c8afe..7f06925d9c 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1282,8 +1282,6 @@ <string name="gate_open_dev">Ouvrir les options pour les développeurs</string> <string name="gate_no_toggle">Cette version d\'Android ne dispose pas de cet interrupteur, DroidDeck effectuera donc la modification via le débogage sans fil. Cela prend environ une minute, sans ordinateur.</string> <string name="gate_needs_wifi">Le débogage sans fil nécessite un Wi-Fi. N\'importe quel réseau convient, Internet n\'est pas nécessaire.</string> - <string name="gate_needs_notifications">Le code d\'appairage s\'affichera dans une notification. Veuillez autoriser DroidDeck à envoyer des notifications, ou utilisez « Autre méthode ».</string> - <string name="gate_allow_notifications">Autoriser les notifications</string> <string name="gate_step1">Ouvrez Paramètres → Options pour les développeurs → Débogage sans fil, et activez-le</string> <string name="gate_step2">Appuyez sur « Associer l\'appareil avec un code d\'appairage »</string> <string name="gate_step3">Saisissez le code d\'appairage dans la notification DroidDeck</string> @@ -1300,48 +1298,13 @@ <string name="gate_status">État</string> <string name="gate_polling">Vérification toutes les 2 secondes. Cette page se fermera automatiquement une fois cet interrupteur désactivé.</string> <string name="gate_other_ways">Autres méthodes</string> - <string name="gate_other_toggle">Débogage sans fil, saisie manuelle de l\'adresse, ADB sur PC</string> - <string name="gate_other_no_toggle">Saisie manuelle de l\'adresse, ADB sur PC, options pour les développeurs</string> <string name="gate_use_wireless_instead">Utiliser plutôt le débogage sans fil</string> <string name="gate_some_roms">Certaines ROM proposent encore cet interrupteur. Recherchez « processus enfants » dans les options pour les développeurs.</string> - <string name="gate_manual_hint">Si la méthode par notification ne fonctionne pas, saisissez manuellement l\'adresse et le code d\'appairage de la fenêtre.</string> - <string name="gate_enter_manually">Saisir l\'adresse manuellement</string> <string name="gate_from_computer">Utiliser ADB depuis un ordinateur :</string> <string name="gate_copy_command">Copier la commande</string> <string name="gate_sidequest_steps">Branchez le casque à un ordinateur et ouvrez SideQuest. Choisissez « Run ADB Command », puis « Custom Command », saisissez la commande affichée ci-dessous et sélectionnez « Run Command ».</string> <string name="gate_choose_display">Choisissez l\'écran sur lequel ouvrir les paramètres Android.</string> <string name="gate_main_screen">Écran principal</string> - <string name="wadb_finding_port">Appairé. Recherche du port de débogage sans fil…</string> - <string name="wadb_enter_port">Appairé. Veuillez saisir le port indiqué dans les paramètres.</string> - <string name="wadb_applying">Appareil trouvé. Application des paramètres…</string> - <string name="wadb_apply_failed">Impossible d\'appliquer automatiquement. Veuillez vérifier l\'adresse ci-dessous et réessayer. %1$s</string> - <string name="wadb_title_wireless">Débogage sans fil</string> - <string name="wadb_title_done">Limite des processus enfants mise à jour</string> - <string name="wadb_title">Modifier la limite des processus enfants</string> - <string name="wadb_lede_compact0">Si cette option n\'est pas disponible, appairez via le débogage sans fil.</string> - <string name="wadb_lede_compact1">Appairé. Veuillez vérifier l\'adresse IP et le port dans le débogage sans fil.</string> - <string name="wadb_lede_done">La limite des processus enfants a été mise à jour.</string> - <string name="wadb_lede0">Si l\'option de processus enfants n\'est pas disponible dans les options pour les développeurs, utilisez l\'étape 2. Ouvrez Options pour les développeurs → Débogage sans fil → Associer l\'appareil avec un code d\'appairage.</string> - <string name="wadb_lede1">Appairé. Utilisez l\'adresse ci-dessous, ou mettez-la à jour dans Débogage sans fil → Adresse IP et port.</string> - <string name="wadb_lede_done_long">Limite des processus enfants mise à jour via le débogage sans fil.</string> - <string name="wadb_confirmed_on">Android a confirmé que la limite est activée.</string> - <string name="wadb_confirmed_off">Android a confirmé que la limite est désactivée.</string> - <string name="wadb_pair_group">2 · Appairer le débogage sans fil</string> - <string name="wadb_pair_address">Adresse IP et port dans la fenêtre d\'appairage</string> - <string name="wadb_pin">Code d\'appairage (PIN)</string> - <string name="wadb_pin_placeholder">6 chiffres</string> - <string name="wadb_pair">Appairer</string> - <string name="wadb_apply_group">2 · Appliquer via le débogage sans fil</string> - <string name="wadb_connect_address">Adresse IP et port de connexion</string> - <string name="wadb_pair_again">Réappairer</string> - <string name="wadb_turn_off">Désactiver la limite</string> - <string name="wadb_other_ways">Autres méthodes de modification</string> - <string name="wadb_dev_try_first">1 · Options pour les développeurs (à essayer en premier)</string> - <string name="wadb_restrict_on">Désactivez « Désactiver les limites pour les processus enfant ».</string> - <string name="wadb_restrict_off">Activez « Désactiver les limites pour les processus enfant ».</string> - <string name="wadb_computer_last">3 · ADB sur PC (en dernier recours)</string> - <string name="wadb_only_if">À utiliser uniquement si le débogage sans fil n\'est pas disponible.</string> - <string name="wadb_computer_group">3 · ADB sur PC (en dernier recours)</string> <string name="ctrl_color">Couleur</string> <string name="ctrl_custom">Personnalisée</string> <string name="ctrl_opacity">Opacité</string> @@ -1635,8 +1598,6 @@ <item quantity="many">%1$d dossiers de journaux de session effacés.</item> <item quantity="other">%1$d dossiers de journaux de session effacés.</item> </plurals> - <string name="main_wadb_pair_failed">Échec de l\'appairage du débogage sans fil</string> - <string name="main_wadb_command_failed">Échec de la commande de débogage sans fil</string> <string name="main_wadb_unavailable">Le débogage sans fil n\'est pas disponible</string> <string name="main_adb_copied">Commande ADB copiée</string> <string name="main_pick_roms">Choisir le dossier ROM</string> diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index b2f2633475..0edc2352e2 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -1276,8 +1276,6 @@ <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">Settings → डेवलपर विकल्प → वायरलेस डीबगिंग खोलें और उसे चालू करें</string> <string name="gate_step2">“Pair device with pairing code” पर टैप करें</string> <string name="gate_step3">DroidDeck नोटिफ़िकेशन में कोड टाइप करें</string> @@ -1294,48 +1292,13 @@ <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 Settings किस डिस्प्ले पर खोलना है चुनें।</string> <string name="gate_main_screen">मुख्य स्क्रीन</string> - <string name="wadb_finding_port">पेयर हो गया। वायरलेस डीबगिंग का पोर्ट खोजा जा रहा है…</string> - <string name="wadb_enter_port">पेयर हो गया। Settings से पोर्ट डालें।</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 इस्तेमाल करें। डेवलपर विकल्प → वायरलेस डीबगिंग → Pair device with pairing code खोलें।</string> - <string name="wadb_lede1">पेयर हो गया। नीचे दिया एड्रेस इस्तेमाल करें, या इसे वायरलेस डीबगिंग → IP address & Port से अपडेट करें।</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> @@ -1623,8 +1586,6 @@ <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">ROM फ़ोल्डर चुनें</string> diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index b9d15f6725..3f5cb395ab 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -1276,8 +1276,6 @@ <string name="gate_open_dev">Fejlesztői beállítások megnyitása</string> <string name="gate_no_toggle">Ehhez az Android-verzióhoz nincs kapcsoló, ezért a DroidDeck a vezeték nélküli hibakeresésen keresztül módosítja. Körülbelül egy percet vesz igénybe, számítógép nélkül.</string> <string name="gate_needs_wifi">A vezeték nélküli hibakereséshez Wi-Fi szükséges. Bármelyik hálózat megfelel; internetkapcsolat nem szükséges.</string> - <string name="gate_needs_notifications">A párosítási kód egy értesítésben jelenik meg. Engedélyezze az értesítéseket a DroidDecknek, vagy használja az Egyéb módokat.</string> - <string name="gate_allow_notifications">Értesítések engedélyezése</string> <string name="gate_step1">Nyissa meg: Beállítások → Fejlesztői beállítások → Vezeték nélküli hibakeresés, és kapcsolja be</string> <string name="gate_step2">Koppintson az „Eszköz párosítása párosítási kóddal” lehetőségre</string> <string name="gate_step3">Írja be a kódot a DroidDeck értesítésébe</string> @@ -1294,48 +1292,13 @@ <string name="gate_status">Állapot</string> <string name="gate_polling">Ellenőrzés 2 másodpercenként. Ez az oldal bezárul, amikor kikapcsol.</string> <string name="gate_other_ways">Egyéb módok</string> - <string name="gate_other_toggle">Vezeték nélküli hibakeresés, manuális cím, számítógépes ADB</string> - <string name="gate_other_no_toggle">Manuális cím, számítógépes ADB, Fejlesztői beállítások</string> <string name="gate_use_wireless_instead">Vezeték nélküli hibakeresés használata helyette</string> <string name="gate_some_roms">Néhány ROM mindenképpen hozzáadja a kapcsolót. Keresse a „gyermekfolyamat” kifejezést a Fejlesztői beállításokban.</string> - <string name="gate_manual_hint">Ha az értesítés nem működik, írja be saját kezűleg a felugró ablak címét és kódját.</string> - <string name="gate_enter_manually">Cím kézi megadása</string> <string name="gate_from_computer">Egy ADB-vel rendelkező számítógépről:</string> <string name="gate_copy_command">Parancs másolása</string> <string name="gate_sidequest_steps">Csatlakoztasd a headsetet egy számítógéphez, és nyisd meg a SideQuestet. Válaszd a „Run ADB Command”, majd a „Custom Command” lehetőséget, írd be az alább látható parancsot, és válaszd a „Run Command” gombot.</string> <string name="gate_choose_display">Válassza ki, melyik kijelzőn nyíljon meg az Android Beállítások.</string> <string name="gate_main_screen">Fő képernyő</string> - <string name="wadb_finding_port">Párosítva. A vezeték nélküli hibakeresés portjának keresése…</string> - <string name="wadb_enter_port">Párosítva. Adja meg a portot a Beállításokból.</string> - <string name="wadb_applying">Eszköz megtalálva. A beállítás alkalmazása…</string> - <string name="wadb_apply_failed">Nem sikerült automatikusan alkalmazni. Ellenőrizze az alábbi címet, és próbálja újra. %1$s</string> - <string name="wadb_title_wireless">Vezeték nélküli hibakeresés</string> - <string name="wadb_title_done">A gyermekfolyamat-korlát frissítve</string> - <string name="wadb_title">A gyermekfolyamat-korlát módosítása</string> - <string name="wadb_lede_compact0">Ha a beállítás hiányzik, párosítson a vezeték nélküli hibakeresésen keresztül.</string> - <string name="wadb_lede_compact1">Párosítva. Ellenőrizze az IP-címet és a portot a vezeték nélküli hibakeresésben.</string> - <string name="wadb_lede_done">A gyermekfolyamat-korlát frissítve.</string> - <string name="wadb_lede0">Használja a 2. lépést, ha a Fejlesztői beállításokban nincs gyermekfolyamat-beállítás. Nyissa meg: Fejlesztői beállítások → Vezeték nélküli hibakeresés → Eszköz párosítása párosítási kóddal.</string> - <string name="wadb_lede1">Párosítva. Használja az alábbi címet, vagy frissítse a Vezeték nélküli hibakeresés → IP-cím és port menüből.</string> - <string name="wadb_lede_done_long">A gyermekfolyamat-korlát frissítve a vezeték nélküli hibakeresésen keresztül.</string> - <string name="wadb_confirmed_on">Az Android megerősítette, hogy a korlát be van kapcsolva.</string> - <string name="wadb_confirmed_off">Az Android megerősítette, hogy a korlát ki van kapcsolva.</string> - <string name="wadb_pair_group">2 · Vezeték nélküli hibakeresés párosítása</string> - <string name="wadb_pair_address">A párosítási felugró ablak IP-címe és portja</string> - <string name="wadb_pin">Párosítási kód (PIN)</string> - <string name="wadb_pin_placeholder">6 számjegy</string> - <string name="wadb_pair">Párosítás</string> - <string name="wadb_apply_group">2 · Alkalmazás vezeték nélküli hibakeresésen keresztül</string> - <string name="wadb_connect_address">Kapcsolat IP-címe és portja</string> - <string name="wadb_pair_again">Párosítás újra</string> - <string name="wadb_turn_off">Korlát kikapcsolása</string> - <string name="wadb_other_ways">Egyéb módok a módosítására</string> - <string name="wadb_dev_try_first">1 · Fejlesztői beállítások (próbálja ezt először)</string> - <string name="wadb_restrict_on">Kapcsolja ki az „Alárendelt folyamatok korlátozásának kikapcsolása” lehetőséget.</string> - <string name="wadb_restrict_off">Kapcsolja be az „Alárendelt folyamatok korlátozásának kikapcsolása” lehetőséget.</string> - <string name="wadb_computer_last">3 · Számítógépes ADB (végső megoldás)</string> - <string name="wadb_only_if">Csak ha a vezeték nélküli hibakeresés nem elérhető.</string> - <string name="wadb_computer_group">3 · Számítógépes ADB (végső megoldás)</string> <string name="ctrl_color">Szín</string> <string name="ctrl_custom">Egyéni</string> <string name="ctrl_opacity">Átlátszatlanság</string> @@ -1623,8 +1586,6 @@ <item quantity="one">%1$d munkamenet-naplómappa törölve.</item> <item quantity="other">%1$d munkamenet-naplómappa törölve.</item> </plurals> - <string name="main_wadb_pair_failed">A vezeték nélküli hibakeresés párosítása sikertelen</string> - <string name="main_wadb_command_failed">A vezeték nélküli hibakeresés parancsa sikertelen</string> <string name="main_wadb_unavailable">A vezeték nélküli hibakeresés nem áll rendelkezésre</string> <string name="main_adb_copied">ADB-parancs másolva</string> <string name="main_pick_roms">ROMs mappa kiválasztása</string> diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 56dd216a98..6f1b647f52 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -1270,8 +1270,6 @@ <string name="gate_open_dev">Buka Opsi pengembang</string> <string name="gate_no_toggle">Versi Android ini tidak memiliki sakelar untuk itu, sehingga DroidDeck mengubahnya melalui Debugging nirkabel. Membutuhkan waktu sekitar satu menit, tanpa komputer.</string> <string name="gate_needs_wifi">Debugging nirkabel memerlukan Wi-Fi. Jaringan apa pun berfungsi; tidak perlu internet.</string> - <string name="gate_needs_notifications">Kode pemasangan muncul di notifikasi. Izinkan notifikasi untuk DroidDeck, atau gunakan Cara lain.</string> - <string name="gate_allow_notifications">Izinkan notifikasi</string> <string name="gate_step1">Buka Setelan → Opsi pengembang → Debugging nirkabel dan aktifkan</string> <string name="gate_step2">Ketuk “Pasangkan perangkat dengan kode pemasangan”</string> <string name="gate_step3">Masukkan kode ke notifikasi DroidDeck</string> @@ -1288,48 +1286,13 @@ <string name="gate_status">Status</string> <string name="gate_polling">Memeriksa setiap 2 detik. Halaman ini akan tertutup saat statusnya nonaktif.</string> <string name="gate_other_ways">Cara lain</string> - <string name="gate_other_toggle">Debugging nirkabel, alamat manual, ADB komputer</string> - <string name="gate_other_no_toggle">Alamat manual, ADB komputer, Opsi pengembang</string> <string name="gate_use_wireless_instead">Gunakan Debugging nirkabel sebagai gantinya</string> <string name="gate_some_roms">Beberapa ROM menambahkan sakelar ini juga. Cari “child process” di Opsi pengembang.</string> - <string name="gate_manual_hint">Jika notifikasinya tidak berfungsi, masukkan sendiri alamat dan kode dari jendela pemasangan.</string> - <string name="gate_enter_manually">Masukkan alamat secara manual</string> <string name="gate_from_computer">Dari komputer dengan ADB:</string> <string name="gate_copy_command">Salin perintah</string> <string name="gate_sidequest_steps">Hubungkan headset ke komputer dan buka SideQuest. Pilih “Run ADB Command”, lalu “Custom Command”, ketik perintah yang ditampilkan di bawah, dan pilih “Run Command”.</string> <string name="gate_choose_display">Pilih tampilan tempat membuka Setelan Android.</string> <string name="gate_main_screen">Layar utama</string> - <string name="wadb_finding_port">Berhasil dipasangkan. Mencari port Debugging nirkabel…</string> - <string name="wadb_enter_port">Berhasil dipasangkan. Masukkan port dari Setelan.</string> - <string name="wadb_applying">Perangkat ditemukan. Menerapkan setelan…</string> - <string name="wadb_apply_failed">Tidak dapat menerapkan secara otomatis. Periksa alamat di bawah dan coba lagi. %1$s</string> - <string name="wadb_title_wireless">Debugging nirkabel</string> - <string name="wadb_title_done">Batas proses turunan diperbarui</string> - <string name="wadb_title">Ubah batas proses turunan</string> - <string name="wadb_lede_compact0">Jika opsinya tidak ada, pasangkan melalui Debugging nirkabel.</string> - <string name="wadb_lede_compact1">Berhasil dipasangkan. Periksa alamat IP dan port di Debugging nirkabel.</string> - <string name="wadb_lede_done">Batas proses turunan telah diperbarui.</string> - <string name="wadb_lede0">Gunakan langkah 2 jika Opsi pengembang tidak memiliki setelan proses turunan. Buka Opsi pengembang → Debugging nirkabel → Pasangkan perangkat dengan kode pemasangan.</string> - <string name="wadb_lede1">Berhasil dipasangkan. Gunakan alamat di bawah, atau perbarui dari Debugging nirkabel → Alamat IP & Port.</string> - <string name="wadb_lede_done_long">Batas proses turunan telah diperbarui melalui Debugging nirkabel.</string> - <string name="wadb_confirmed_on">Android mengonfirmasi batas ini aktif.</string> - <string name="wadb_confirmed_off">Android mengonfirmasi batas ini nonaktif.</string> - <string name="wadb_pair_group">2 · Pasangkan Debugging nirkabel</string> - <string name="wadb_pair_address">Alamat IP & port jendela pemasangan</string> - <string name="wadb_pin">Kode pemasangan (PIN)</string> - <string name="wadb_pin_placeholder">6 digit</string> - <string name="wadb_pair">Pasangkan</string> - <string name="wadb_apply_group">2 · Terapkan melalui Debugging nirkabel</string> - <string name="wadb_connect_address">Alamat IP & port koneksi</string> - <string name="wadb_pair_again">Pasangkan lagi</string> - <string name="wadb_turn_off">Nonaktifkan batas</string> - <string name="wadb_other_ways">Cara lain untuk mengubahnya</string> - <string name="wadb_dev_try_first">1 · Opsi pengembang (coba dahulu)</string> - <string name="wadb_restrict_on">Nonaktifkan “Nonaktifkan batasan proses turunan”.</string> - <string name="wadb_restrict_off">Aktifkan “Nonaktifkan batasan proses turunan”.</string> - <string name="wadb_computer_last">3 · ADB komputer (upaya terakhir)</string> - <string name="wadb_only_if">Hanya jika Debugging nirkabel tidak tersedia.</string> - <string name="wadb_computer_group">3 · ADB komputer (upaya terakhir)</string> <string name="ctrl_color">Warna</string> <string name="ctrl_custom">Khusus</string> <string name="ctrl_opacity">Opasitas</string> @@ -1611,8 +1574,6 @@ <plurals name="main_logs_cleared"> <item quantity="other">%1$d folder log sesi dihapus.</item> </plurals> - <string name="main_wadb_pair_failed">Penyambungan debugging nirkabel gagal</string> - <string name="main_wadb_command_failed">Perintah debugging nirkabel gagal</string> <string name="main_wadb_unavailable">Debugging nirkabel tidak tersedia</string> <string name="main_adb_copied">Perintah ADB disalin</string> <string name="main_pick_roms">Pilih folder ROMs</string> diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 9d574d4ba4..0473d4aa17 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1274,8 +1274,6 @@ <string name="gate_open_dev">Apri Opzioni sviluppatore</string> <string name="gate_no_toggle">Questa versione di Android non ha un interruttore per questo, quindi DroidDeck lo cambia tramite il Debug wireless. Richiede circa un minuto, senza bisogno di un computer.</string> <string name="gate_needs_wifi">Il Debug wireless richiede il Wi-Fi. Va bene qualsiasi rete; non serve l\'accesso a internet.</string> - <string name="gate_needs_notifications">Il codice di accoppiamento arriva in una notifica. Consenti le notifiche per DroidDeck, oppure usa Altri modi.</string> - <string name="gate_allow_notifications">Consenti notifiche</string> <string name="gate_step1">Apri Impostazioni → Opzioni sviluppatore → Debug wireless e attivalo</string> <string name="gate_step2">Tocca “Accoppia dispositivo con codice di accoppiamento”</string> <string name="gate_step3">Digita il codice nella notifica di DroidDeck</string> @@ -1292,48 +1290,13 @@ <string name="gate_status">Stato</string> <string name="gate_polling">Controllo ogni 2 secondi. Questa pagina si chiude quando è disattivato.</string> <string name="gate_other_ways">Altri modi</string> - <string name="gate_other_toggle">Debug wireless, indirizzo manuale, ADB da computer</string> - <string name="gate_other_no_toggle">Indirizzo manuale, ADB da computer, Opzioni sviluppatore</string> <string name="gate_use_wireless_instead">Usa invece il Debug wireless</string> <string name="gate_some_roms">Alcune ROM aggiungono comunque l\'interruttore. Cerca “processi figlio” nelle Opzioni sviluppatore.</string> - <string name="gate_manual_hint">Se la notifica non funziona, inserisci tu l\'indirizzo e il codice del popup.</string> - <string name="gate_enter_manually">Inserisci l\'indirizzo manualmente</string> <string name="gate_from_computer">Da un computer con ADB:</string> <string name="gate_copy_command">Copia comando</string> <string name="gate_sidequest_steps">Collega il visore a un computer e apri SideQuest. Scegli “Run ADB Command”, poi “Custom Command”, digita il comando mostrato sotto e seleziona “Run Command”.</string> <string name="gate_choose_display">Scegli su quale schermo aprire le Impostazioni di Android.</string> <string name="gate_main_screen">Schermo principale</string> - <string name="wadb_finding_port">Accoppiato. Ricerca della porta del Debug wireless…</string> - <string name="wadb_enter_port">Accoppiato. Inserisci la porta dalle Impostazioni.</string> - <string name="wadb_applying">Dispositivo trovato. Applicazione dell\'impostazione…</string> - <string name="wadb_apply_failed">Impossibile applicare automaticamente. Controlla l\'indirizzo qui sotto e riprova. %1$s</string> - <string name="wadb_title_wireless">Debug wireless</string> - <string name="wadb_title_done">Limite dei processi figlio aggiornato</string> - <string name="wadb_title">Cambia il limite dei processi figlio</string> - <string name="wadb_lede_compact0">Se l\'opzione non è presente, accoppia tramite il Debug wireless.</string> - <string name="wadb_lede_compact1">Accoppiato. Controlla l\'indirizzo IP e la porta nel Debug wireless.</string> - <string name="wadb_lede_done">Il limite dei processi figlio è stato aggiornato.</string> - <string name="wadb_lede0">Usa il passaggio 2 se le Opzioni sviluppatore non hanno un\'impostazione per i processi figlio. Apri Opzioni sviluppatore → Debug wireless → Accoppia dispositivo con codice di accoppiamento.</string> - <string name="wadb_lede1">Accoppiato. Usa l\'indirizzo qui sotto, oppure aggiornalo da Debug wireless → Indirizzo IP e porta.</string> - <string name="wadb_lede_done_long">Il limite dei processi figlio è stato aggiornato tramite il Debug wireless.</string> - <string name="wadb_confirmed_on">Android ha confermato che il limite è attivo.</string> - <string name="wadb_confirmed_off">Android ha confermato che il limite è disattivato.</string> - <string name="wadb_pair_group">2 · Accoppia il Debug wireless</string> - <string name="wadb_pair_address">Indirizzo IP e porta del popup di accoppiamento</string> - <string name="wadb_pin">Codice di accoppiamento (PIN)</string> - <string name="wadb_pin_placeholder">6 cifre</string> - <string name="wadb_pair">Accoppia</string> - <string name="wadb_apply_group">2 · Applica tramite il Debug wireless</string> - <string name="wadb_connect_address">Indirizzo IP e porta di connessione</string> - <string name="wadb_pair_again">Accoppia di nuovo</string> - <string name="wadb_turn_off">Disattiva il limite</string> - <string name="wadb_other_ways">Altri modi per cambiarlo</string> - <string name="wadb_dev_try_first">1 · Opzioni sviluppatore (da provare prima)</string> - <string name="wadb_restrict_on">Disattiva “Disattiva limitazioni per i processi secondari”.</string> - <string name="wadb_restrict_off">Attiva “Disattiva limitazioni per i processi secondari”.</string> - <string name="wadb_computer_last">3 · ADB da computer (ultima risorsa)</string> - <string name="wadb_only_if">Solo se il Debug wireless non è disponibile.</string> - <string name="wadb_computer_group">3 · ADB da computer (ultima risorsa)</string> <string name="ctrl_color">Colore</string> <string name="ctrl_custom">Personalizzato</string> <string name="ctrl_opacity">Opacità</string> @@ -1627,8 +1590,6 @@ <item quantity="many">%1$d cartelle di log di sessione cancellate.</item> <item quantity="other">%1$d cartelle di log di sessione cancellate.</item> </plurals> - <string name="main_wadb_pair_failed">Accoppiamento per il debug wireless non riuscito</string> - <string name="main_wadb_command_failed">Comando di debug wireless non riuscito</string> <string name="main_wadb_unavailable">Il debug wireless non è disponibile</string> <string name="main_adb_copied">Comando ADB copiato</string> <string name="main_pick_roms">Scegli la cartella delle ROM</string> diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index f09bbbff7a..c4f0e9b7db 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -1270,8 +1270,6 @@ <string name="gate_open_dev">開発者向けオプションを開く</string> <string name="gate_no_toggle">このAndroidバージョンにはこのスイッチがないため、DroidDeckはワイヤレスデバッグを介して変更します。約1分かかり、PCは不要です。</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> @@ -1288,48 +1286,13 @@ <string name="gate_status">ステータス</string> <string name="gate_polling">2秒ごとに確認します。このスイッチをオフにすると、このページは自動的に閉じます。</string> <string name="gate_other_ways">他の方法</string> - <string name="gate_other_toggle">ワイヤレスデバッグ、手動でアドレス入力、PC ADB</string> - <string name="gate_other_no_toggle">手動でアドレス入力、PC 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">PCで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 · PC ADB(最終手段)</string> - <string name="wadb_only_if">ワイヤレスデバッグが利用できない場合にのみ使用してください。</string> - <string name="wadb_computer_group">3 · PC ADB(最終手段)</string> <string name="ctrl_color">色</string> <string name="ctrl_custom">カスタム</string> <string name="ctrl_opacity">不透明度</string> @@ -1611,8 +1574,6 @@ <plurals name="main_logs_cleared"> <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">ROMフォルダを選択</string> diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index d7b6c044a1..132894ed53 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -1270,8 +1270,6 @@ <string name="gate_open_dev">개발자 옵션 열기</string> <string name="gate_no_toggle">이 Android 버전에는 해당 스위치가 없으므로 DroidDeck이 무선 디버깅을 통해 수정합니다. 약 1분이 걸리며 PC가 필요하지 않습니다.</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> @@ -1288,48 +1286,13 @@ <string name="gate_status">상태</string> <string name="gate_polling">2초마다 확인합니다. 이 스위치를 끄면 이 페이지가 자동으로 닫힙니다.</string> <string name="gate_other_ways">다른 방법</string> - <string name="gate_other_toggle">무선 디버깅, 수동 주소 입력, PC ADB</string> - <string name="gate_other_no_toggle">수동 주소 입력, PC 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">PC에서 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 · PC ADB(최후의 수단)</string> - <string name="wadb_only_if">무선 디버깅을 사용할 수 없을 때만 사용하세요.</string> - <string name="wadb_computer_group">3 · PC ADB(최후의 수단)</string> <string name="ctrl_color">색상</string> <string name="ctrl_custom">사용자 정의</string> <string name="ctrl_opacity">불투명도</string> @@ -1611,8 +1574,6 @@ <plurals name="main_logs_cleared"> <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">ROM 폴더 선택</string> diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index c4c67b0b6f..4acd4c0156 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -1270,8 +1270,6 @@ <string name="gate_open_dev">Buka Pilihan pembangun</string> <string name="gate_no_toggle">Versi Android ini tidak mempunyai suis untuknya, jadi DroidDeck menukarnya melalui Debugging Wayarles. Mengambil masa kira-kira seminit, tanpa komputer diperlukan.</string> <string name="gate_needs_wifi">Debugging Wayarles memerlukan Wi-Fi. Mana-mana rangkaian berfungsi; ia tidak memerlukan internet.</string> - <string name="gate_needs_notifications">Kod gandingan dihantar dalam pemberitahuan. Benarkan pemberitahuan untuk DroidDeck, atau gunakan Cara lain.</string> - <string name="gate_allow_notifications">Benarkan pemberitahuan</string> <string name="gate_step1">Buka Tetapan → Pilihan pembangun → Debugging Wayarles dan hidupkannya</string> <string name="gate_step2">Ketik “Gandingkan peranti dengan kod gandingan”</string> <string name="gate_step3">Taip kod itu ke dalam pemberitahuan DroidDeck</string> @@ -1288,48 +1286,13 @@ <string name="gate_status">Status</string> <string name="gate_polling">Menyemak setiap 2 saat. Halaman ini ditutup apabila ia mati.</string> <string name="gate_other_ways">Cara lain</string> - <string name="gate_other_toggle">Debugging Wayarles, alamat manual, ADB komputer</string> - <string name="gate_other_no_toggle">Alamat manual, ADB komputer, Pilihan pembangun</string> <string name="gate_use_wireless_instead">Gunakan Debugging Wayarles sebaliknya</string> <string name="gate_some_roms">Sesetengah ROM turut menambah suis itu. Cari “proses anak” dalam Pilihan pembangun.</string> - <string name="gate_manual_hint">Jika pemberitahuan tidak berfungsi, masukkan alamat dan kod tetingkap timbul itu sendiri.</string> - <string name="gate_enter_manually">Masukkan alamat secara manual</string> <string name="gate_from_computer">Daripada komputer dengan ADB:</string> <string name="gate_copy_command">Salin arahan</string> <string name="gate_sidequest_steps">Sambungkan set kepala ke komputer dan buka SideQuest. Pilih “Run ADB Command”, kemudian “Custom Command”, taip perintah yang dipaparkan di bawah dan pilih “Run Command”.</string> <string name="gate_choose_display">Pilih paparan mana untuk membuka Tetapan Android.</string> <string name="gate_main_screen">Skrin utama</string> - <string name="wadb_finding_port">Digandingkan. Mencari port Debugging Wayarles…</string> - <string name="wadb_enter_port">Digandingkan. Masukkan port daripada Tetapan.</string> - <string name="wadb_applying">Peranti dijumpai. Menggunakan tetapan…</string> - <string name="wadb_apply_failed">Tidak dapat digunakan secara automatik. Semak alamat di bawah dan cuba lagi. %1$s</string> - <string name="wadb_title_wireless">Debugging Wayarles</string> - <string name="wadb_title_done">Had proses anak dikemas kini</string> - <string name="wadb_title">Tukar had proses anak</string> - <string name="wadb_lede_compact0">Jika pilihan itu tiada, gandingkan melalui Debugging Wayarles.</string> - <string name="wadb_lede_compact1">Digandingkan. Semak alamat IP dan port dalam Debugging Wayarles.</string> - <string name="wadb_lede_done">Had proses anak telah dikemas kini.</string> - <string name="wadb_lede0">Gunakan langkah 2 jika Pilihan pembangun tidak mempunyai tetapan proses anak. Buka Pilihan pembangun → Debugging Wayarles → Gandingkan peranti dengan kod gandingan.</string> - <string name="wadb_lede1">Digandingkan. Gunakan alamat di bawah, atau kemas kini daripada Debugging Wayarles → Alamat IP & Port.</string> - <string name="wadb_lede_done_long">Had proses anak telah dikemas kini melalui Debugging Wayarles.</string> - <string name="wadb_confirmed_on">Android mengesahkan had itu hidup.</string> - <string name="wadb_confirmed_off">Android mengesahkan had itu mati.</string> - <string name="wadb_pair_group">2 · Gandingkan Debugging Wayarles</string> - <string name="wadb_pair_address">Alamat IP & port tetingkap timbul gandingan</string> - <string name="wadb_pin">Kod gandingan (PIN)</string> - <string name="wadb_pin_placeholder">6 digit</string> - <string name="wadb_pair">Gandingkan</string> - <string name="wadb_apply_group">2 · Gunakan melalui Debugging Wayarles</string> - <string name="wadb_connect_address">Alamat IP & port sambungan</string> - <string name="wadb_pair_again">Gandingkan semula</string> - <string name="wadb_turn_off">Matikan had</string> - <string name="wadb_other_ways">Cara lain untuk menukarnya</string> - <string name="wadb_dev_try_first">1 · Pilihan pembangun (cuba dahulu)</string> - <string name="wadb_restrict_on">Tetapkan “Lumpuhkan sekatan proses anak” mati.</string> - <string name="wadb_restrict_off">Tetapkan “Lumpuhkan sekatan proses anak” hidup.</string> - <string name="wadb_computer_last">3 · ADB komputer (pilihan akhir)</string> - <string name="wadb_only_if">Hanya jika Debugging Wayarles tidak tersedia.</string> - <string name="wadb_computer_group">3 · ADB komputer (pilihan akhir)</string> <string name="ctrl_color">Warna</string> <string name="ctrl_custom">Tersuai</string> <string name="ctrl_opacity">Kelegapan</string> @@ -1611,8 +1574,6 @@ <plurals name="main_logs_cleared"> <item quantity="other">%1$d folder log sesi dikosongkan.</item> </plurals> - <string name="main_wadb_pair_failed">Gandingan Debugging Wayarles gagal</string> - <string name="main_wadb_command_failed">Arahan Debugging Wayarles gagal</string> <string name="main_wadb_unavailable">Debugging Wayarles tidak tersedia</string> <string name="main_adb_copied">Arahan ADB disalin</string> <string name="main_pick_roms">Pilih folder ROM</string> diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index 633b16d02e..9922d36712 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -1276,8 +1276,6 @@ <string name="gate_open_dev">Åpne Utvikleralternativer</string> <string name="gate_no_toggle">Denne Android-versjonen har ingen bryter for det, så DroidDeck endrer det via trådløs feilsøking. Tar omtrent ett minutt, ingen datamaskin nødvendig.</string> <string name="gate_needs_wifi">Trådløs feilsøking krever Wi-Fi. Hvilket nettverk som helst fungerer; det krever ikke internett.</string> - <string name="gate_needs_notifications">Koblingskoden kommer i en varsling. Tillat varslinger for DroidDeck, eller bruk Andre måter.</string> - <string name="gate_allow_notifications">Tillat varslinger</string> <string name="gate_step1">Åpne Innstillinger → Utvikleralternativer → Trådløs feilsøking og slå det på</string> <string name="gate_step2">Trykk på «Par enhet med koblingskode»</string> <string name="gate_step3">Skriv koden inn i DroidDeck-varslingen</string> @@ -1294,48 +1292,13 @@ <string name="gate_status">Status</string> <string name="gate_polling">Kontrollerer hvert 2. sekund. Denne siden lukkes når det er av.</string> <string name="gate_other_ways">Andre måter</string> - <string name="gate_other_toggle">Trådløs feilsøking, manuell adresse, ADB fra datamaskin</string> - <string name="gate_other_no_toggle">Manuell adresse, ADB fra datamaskin, Utvikleralternativer</string> <string name="gate_use_wireless_instead">Bruk trådløs feilsøking i stedet</string> <string name="gate_some_roms">Noen ROM-er legger til bryteren likevel. Se etter «child process» i Utvikleralternativer.</string> - <string name="gate_manual_hint">Hvis varslingen ikke fungerer, skriv inn varselets adresse og kode selv.</string> - <string name="gate_enter_manually">Skriv inn adresse manuelt</string> <string name="gate_from_computer">Fra en datamaskin med ADB:</string> <string name="gate_copy_command">Kopier kommando</string> <string name="gate_sidequest_steps">Koble headsettet til en datamaskin og åpne SideQuest. Velg «Run ADB Command», deretter «Custom Command», skriv inn kommandoen vist nedenfor og velg «Run Command».</string> <string name="gate_choose_display">Velg hvilken skjerm Android-innstillinger skal åpnes på.</string> <string name="gate_main_screen">Hovedskjerm</string> - <string name="wadb_finding_port">Koblet sammen. Finner porten for trådløs feilsøking…</string> - <string name="wadb_enter_port">Koblet sammen. Skriv inn porten fra Innstillinger.</string> - <string name="wadb_applying">Enhet funnet. Bruker innstillingen…</string> - <string name="wadb_apply_failed">Kunne ikke bruke den automatisk. Kontroller adressen under og prøv igjen. %1$s</string> - <string name="wadb_title_wireless">Trådløs feilsøking</string> - <string name="wadb_title_done">Grensen for underprosesser er oppdatert</string> - <string name="wadb_title">Endre grensen for underprosesser</string> - <string name="wadb_lede_compact0">Hvis alternativet er borte, par over trådløs feilsøking.</string> - <string name="wadb_lede_compact1">Koblet sammen. Kontroller IP-adressen og porten i Trådløs feilsøking.</string> - <string name="wadb_lede_done">Grensen for underprosesser ble oppdatert.</string> - <string name="wadb_lede0">Bruk steg 2 hvis Utvikleralternativer ikke har en innstilling for underprosesser. Åpne Utvikleralternativer → Trådløs feilsøking → Par enhet med koblingskode.</string> - <string name="wadb_lede1">Koblet sammen. Bruk adressen under, eller oppdater den fra Trådløs feilsøking → IP-adresse og port.</string> - <string name="wadb_lede_done_long">Grensen for underprosesser ble oppdatert via trådløs feilsøking.</string> - <string name="wadb_confirmed_on">Android bekreftet at grensen er på.</string> - <string name="wadb_confirmed_off">Android bekreftet at grensen er av.</string> - <string name="wadb_pair_group">2 · Koble sammen trådløs feilsøking</string> - <string name="wadb_pair_address">IP-adresse og port for koblingsvarsel</string> - <string name="wadb_pin">Koblingskode (PIN)</string> - <string name="wadb_pin_placeholder">6 tall</string> - <string name="wadb_pair">Koble sammen</string> - <string name="wadb_apply_group">2 · Bruk via trådløs feilsøking</string> - <string name="wadb_connect_address">IP-adresse og port for tilkobling</string> - <string name="wadb_pair_again">Koble sammen igjen</string> - <string name="wadb_turn_off">Slå av grensen</string> - <string name="wadb_other_ways">Andre måter å endre det</string> - <string name="wadb_dev_try_first">1 · Utvikleralternativer (prøv først)</string> - <string name="wadb_restrict_on">Slå av «Slå av begrensninger for underordnede prosesser».</string> - <string name="wadb_restrict_off">Slå på «Slå av begrensninger for underordnede prosesser».</string> - <string name="wadb_computer_last">3 · ADB fra datamaskin (siste utvei)</string> - <string name="wadb_only_if">Bare hvis trådløs feilsøking ikke er tilgjengelig.</string> - <string name="wadb_computer_group">3 · ADB fra datamaskin (siste utvei)</string> <string name="ctrl_color">Farge</string> <string name="ctrl_custom">Egendefinert</string> <string name="ctrl_opacity">Opasitet</string> @@ -1623,8 +1586,6 @@ <item quantity="one">Tømte %1$d sesjonsloggmappe.</item> <item quantity="other">Tømte %1$d sesjonsloggmapper.</item> </plurals> - <string name="main_wadb_pair_failed">Kobling for trådløs feilsøking mislyktes</string> - <string name="main_wadb_command_failed">Kommando for trådløs feilsøking mislyktes</string> <string name="main_wadb_unavailable">Trådløs feilsøking er ikke tilgjengelig</string> <string name="main_adb_copied">ADB-kommando kopiert</string> <string name="main_pick_roms">Velg ROM-mappen</string> diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 5f51dc1cd4..719c86894a 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1276,8 +1276,6 @@ <string name="gate_open_dev">Opties voor ontwikkelaars openen</string> <string name="gate_no_toggle">Deze Android-versie heeft hiervoor geen schakelaar, dus wijzigt DroidDeck dit via Draadloos debuggen. Duurt ongeveer een minuut, geen computer nodig.</string> <string name="gate_needs_wifi">Draadloos debuggen heeft Wi-Fi nodig. Elk netwerk werkt; internet is niet vereist.</string> - <string name="gate_needs_notifications">De koppelingscode komt in een melding. Sta meldingen toe voor DroidDeck, of gebruik Andere manieren.</string> - <string name="gate_allow_notifications">Meldingen toestaan</string> <string name="gate_step1">Open Instellingen → Opties voor ontwikkelaars → Draadloos debuggen en zet het aan</string> <string name="gate_step2">Tik op “Apparaat koppelen met koppelingscode”</string> <string name="gate_step3">Voer de code in bij de melding van DroidDeck</string> @@ -1294,48 +1292,13 @@ <string name="gate_status">Status</string> <string name="gate_polling">Controleert elke 2 seconden. Deze pagina sluit zodra het uit staat.</string> <string name="gate_other_ways">Andere manieren</string> - <string name="gate_other_toggle">Draadloos debuggen, handmatig adres, computer-ADB</string> - <string name="gate_other_no_toggle">Handmatig adres, computer-ADB, Opties voor ontwikkelaars</string> <string name="gate_use_wireless_instead">Gebruik Draadloos debuggen in plaats daarvan</string> <string name="gate_some_roms">Sommige ROMs voegen de schakelaar toch toe. Zoek naar “subproces” in Opties voor ontwikkelaars.</string> - <string name="gate_manual_hint">Als de melding niet werkt, voer je het adres en de code van de pop-up zelf in.</string> - <string name="gate_enter_manually">Adres handmatig invoeren</string> <string name="gate_from_computer">Vanaf een computer met ADB:</string> <string name="gate_copy_command">Opdracht kopiëren</string> <string name="gate_sidequest_steps">Sluit de headset aan op een computer en open SideQuest. Kies ‘Run ADB Command’ en dan ‘Custom Command’, typ de hieronder getoonde opdracht en selecteer ‘Run Command’.</string> <string name="gate_choose_display">Kies op welk scherm Android-instellingen wordt geopend.</string> <string name="gate_main_screen">Hoofdscherm</string> - <string name="wadb_finding_port">Gekoppeld. Poort van Draadloos debuggen zoeken…</string> - <string name="wadb_enter_port">Gekoppeld. Voer de poort uit Instellingen in.</string> - <string name="wadb_applying">Apparaat gevonden. Instelling toepassen…</string> - <string name="wadb_apply_failed">Kan niet automatisch worden toegepast. Controleer het adres hieronder en probeer het opnieuw. %1$s</string> - <string name="wadb_title_wireless">Draadloos debuggen</string> - <string name="wadb_title_done">Limiet voor subprocessen bijgewerkt</string> - <string name="wadb_title">De limiet voor subprocessen wijzigen</string> - <string name="wadb_lede_compact0">Als de optie ontbreekt, koppel dan via Draadloos debuggen.</string> - <string name="wadb_lede_compact1">Gekoppeld. Controleer het IP-adres en de poort in Draadloos debuggen.</string> - <string name="wadb_lede_done">De limiet voor subprocessen is bijgewerkt.</string> - <string name="wadb_lede0">Gebruik stap 2 als Opties voor ontwikkelaars geen instelling voor subprocessen heeft. Open Opties voor ontwikkelaars → Draadloos debuggen → Apparaat koppelen met koppelingscode.</string> - <string name="wadb_lede1">Gekoppeld. Gebruik het adres hieronder, of werk het bij via Draadloos debuggen → IP-adres & Poort.</string> - <string name="wadb_lede_done_long">De limiet voor subprocessen is bijgewerkt via Draadloos debuggen.</string> - <string name="wadb_confirmed_on">Android heeft bevestigd dat de limiet aan staat.</string> - <string name="wadb_confirmed_off">Android heeft bevestigd dat de limiet uit staat.</string> - <string name="wadb_pair_group">2 · Draadloos debuggen koppelen</string> - <string name="wadb_pair_address">IP-adres & poort van de koppelingspop-up</string> - <string name="wadb_pin">Koppelingscode (pincode)</string> - <string name="wadb_pin_placeholder">6 cijfers</string> - <string name="wadb_pair">Koppelen</string> - <string name="wadb_apply_group">2 · Toepassen via Draadloos debuggen</string> - <string name="wadb_connect_address">IP-adres & poort van de verbinding</string> - <string name="wadb_pair_again">Opnieuw koppelen</string> - <string name="wadb_turn_off">Limiet uitschakelen</string> - <string name="wadb_other_ways">Andere manieren om dit te wijzigen</string> - <string name="wadb_dev_try_first">1 · Opties voor ontwikkelaars (probeer dit eerst)</string> - <string name="wadb_restrict_on">Zet “Beperkingen voor onderliggende processen uitzetten” uit.</string> - <string name="wadb_restrict_off">Zet “Beperkingen voor onderliggende processen uitzetten” aan.</string> - <string name="wadb_computer_last">3 · Computer-ADB (laatste redmiddel)</string> - <string name="wadb_only_if">Alleen als Draadloos debuggen niet beschikbaar is.</string> - <string name="wadb_computer_group">3 · Computer-ADB (laatste redmiddel)</string> <string name="ctrl_color">Kleur</string> <string name="ctrl_custom">Aangepast</string> <string name="ctrl_opacity">Transparantie</string> @@ -1623,8 +1586,6 @@ <item quantity="one">%1$d map met sessielogs gewist.</item> <item quantity="other">%1$d mappen met sessielogs gewist.</item> </plurals> - <string name="main_wadb_pair_failed">Koppelen voor draadloze foutopsporing mislukt</string> - <string name="main_wadb_command_failed">Opdracht voor draadloze foutopsporing mislukt</string> <string name="main_wadb_unavailable">Draadloze foutopsporing is niet beschikbaar</string> <string name="main_adb_copied">ADB-opdracht gekopieerd</string> <string name="main_pick_roms">Kies de ROM-map</string> diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 65a0f62751..25a9f59672 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1290,8 +1290,6 @@ <string name="gate_open_dev">Otwórz Opcje programisty</string> <string name="gate_no_toggle">Ta wersja Androida nie ma dla tego przełącznika, więc DroidDeck zmienia go przez debugowanie bezprzewodowe. Zajmuje to około minuty, bez potrzeby komputera.</string> <string name="gate_needs_wifi">Debugowanie bezprzewodowe wymaga Wi-Fi. Działa każda sieć; nie musi mieć internetu.</string> - <string name="gate_needs_notifications">Kod parowania pojawia się w powiadomieniu. Zezwól DroidDeck na powiadomienia albo użyj sekcji „Inne sposoby”.</string> - <string name="gate_allow_notifications">Zezwól na powiadomienia</string> <string name="gate_step1">Otwórz Ustawienia → Opcje programisty → Debugowanie bezprzewodowe i włącz je</string> <string name="gate_step2">Dotknij „Sparuj urządzenie za pomocą kodu parowania”</string> <string name="gate_step3">Wpisz kod w powiadomieniu DroidDeck</string> @@ -1308,48 +1306,13 @@ <string name="gate_status">Stan</string> <string name="gate_polling">Sprawdzanie co 2 sekundy. Ta strona zamknie się, gdy przełącznik będzie wyłączony.</string> <string name="gate_other_ways">Inne sposoby</string> - <string name="gate_other_toggle">Debugowanie bezprzewodowe, adres ręczny, komputer z ADB</string> - <string name="gate_other_no_toggle">Adres ręczny, komputer z ADB, Opcje programisty</string> <string name="gate_use_wireless_instead">Użyj za to debugowania bezprzewodowego</string> <string name="gate_some_roms">Niektóre ROM-y dodają ten przełącznik mimo to. Poszukaj „child process” w Opcjach programisty.</string> - <string name="gate_manual_hint">Jeśli powiadomienie nie działa, wpisz adres i kod z okienka samodzielnie.</string> - <string name="gate_enter_manually">Wpisz adres ręcznie</string> <string name="gate_from_computer">Z komputera z ADB:</string> <string name="gate_copy_command">Kopiuj polecenie</string> <string name="gate_sidequest_steps">Podłącz gogle do komputera i otwórz SideQuest. Wybierz „Run ADB Command”, potem „Custom Command”, wpisz polecenie widoczne poniżej i wybierz „Run Command”.</string> <string name="gate_choose_display">Wybierz, na którym ekranie otworzyć Ustawienia Androida.</string> <string name="gate_main_screen">Ekran główny</string> - <string name="wadb_finding_port">Sparowano. Wyszukiwanie portu debugowania bezprzewodowego…</string> - <string name="wadb_enter_port">Sparowano. Wpisz port z Ustawień.</string> - <string name="wadb_applying">Znaleziono urządzenie. Stosowanie ustawienia…</string> - <string name="wadb_apply_failed">Nie udało się zastosować automatycznie. Sprawdź adres poniżej i spróbuj ponownie. %1$s</string> - <string name="wadb_title_wireless">Debugowanie bezprzewodowe</string> - <string name="wadb_title_done">Limit procesów podrzędnych zmieniony</string> - <string name="wadb_title">Zmień limit procesów podrzędnych</string> - <string name="wadb_lede_compact0">Jeśli opcja jest niedostępna, sparuj przez debugowanie bezprzewodowe.</string> - <string name="wadb_lede_compact1">Sparowano. Sprawdź adres IP i port w Debugowaniu bezprzewodowym.</string> - <string name="wadb_lede_done">Limit procesów podrzędnych został zmieniony.</string> - <string name="wadb_lede0">Użyj kroku 2, jeśli Opcje programisty nie mają ustawienia procesów podrzędnych. Otwórz Opcje programisty → Debugowanie bezprzewodowe → Sparuj urządzenie za pomocą kodu parowania.</string> - <string name="wadb_lede1">Sparowano. Użyj adresu poniżej lub zaktualizuj go z Debugowanie bezprzewodowe → Adres IP i port.</string> - <string name="wadb_lede_done_long">Limit procesów podrzędnych został zmieniony przez debugowanie bezprzewodowe.</string> - <string name="wadb_confirmed_on">Android potwierdził, że limit jest włączony.</string> - <string name="wadb_confirmed_off">Android potwierdził, że limit jest wyłączony.</string> - <string name="wadb_pair_group">2 · Sparuj debugowanie bezprzewodowe</string> - <string name="wadb_pair_address">Adres IP i port okienka parowania</string> - <string name="wadb_pin">Kod parowania (PIN)</string> - <string name="wadb_pin_placeholder">6 cyfr</string> - <string name="wadb_pair">Sparuj</string> - <string name="wadb_apply_group">2 · Zastosuj przez debugowanie bezprzewodowe</string> - <string name="wadb_connect_address">Adres IP i port połączenia</string> - <string name="wadb_pair_again">Sparuj ponownie</string> - <string name="wadb_turn_off">Wyłącz limit</string> - <string name="wadb_other_ways">Inne sposoby na zmianę tego</string> - <string name="wadb_dev_try_first">1 · Opcje programisty (spróbuj najpierw)</string> - <string name="wadb_restrict_on">Ustaw „Wyłącz ograniczenia procesów podrzędnych aplikacji” na wyłączone.</string> - <string name="wadb_restrict_off">Ustaw „Wyłącz ograniczenia procesów podrzędnych aplikacji” na włączone.</string> - <string name="wadb_computer_last">3 · Komputer z ADB (ostatnia opcja)</string> - <string name="wadb_only_if">Tylko jeśli debugowanie bezprzewodowe jest niedostępne.</string> - <string name="wadb_computer_group">3 · Komputer z ADB (ostatnia opcja)</string> <string name="ctrl_color">Kolor</string> <string name="ctrl_custom">Własny</string> <string name="ctrl_opacity">Przezroczystość</string> @@ -1649,8 +1612,6 @@ <item quantity="many">Wyczyszczono %1$d folderów logów sesji.</item> <item quantity="other">Wyczyszczono %1$d folderu logów sesji.</item> </plurals> - <string name="main_wadb_pair_failed">Parowanie przez debugowanie bezprzewodowe nie powiodło się</string> - <string name="main_wadb_command_failed">Polecenie debugowania bezprzewodowego nie powiodło się</string> <string name="main_wadb_unavailable">Debugowanie bezprzewodowe jest niedostępne</string> <string name="main_adb_copied">Skopiowano polecenie ADB</string> <string name="main_pick_roms">Wybierz folder ROM-ów</string> diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index df9839df35..42e604bfaa 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -1274,8 +1274,6 @@ <string name="gate_open_dev">Abrir Opções de programador</string> <string name="gate_no_toggle">Esta versão do Android não tem um interruptor para isto, por isso o DroidDeck altera-o através da Depuração sem fios. Demora cerca de um minuto e não é preciso computador.</string> <string name="gate_needs_wifi">A Depuração sem fios requer Wi-Fi. Qualquer rede serve; não precisa de Internet.</string> - <string name="gate_needs_notifications">O código de sincronização é introduzido numa notificação. Permita as notificações do DroidDeck ou utilize Outras formas.</string> - <string name="gate_allow_notifications">Permitir notificações</string> <string name="gate_step1">Abra Definições → Opções de programador → Depuração sem fios e ative-a</string> <string name="gate_step2">Toque em “Sincronizar dispositivo com código de sincronização”</string> <string name="gate_step3">Escreva o código na notificação do DroidDeck</string> @@ -1292,48 +1290,13 @@ <string name="gate_status">Estado</string> <string name="gate_polling">A verificar a cada 2 segundos. Esta página fecha-se quando estiver desativado.</string> <string name="gate_other_ways">Outras formas</string> - <string name="gate_other_toggle">Depuração sem fios, endereço manual, ADB num computador</string> - <string name="gate_other_no_toggle">Endereço manual, ADB num computador, Opções de programador</string> <string name="gate_use_wireless_instead">Utilizar antes a Depuração sem fios</string> <string name="gate_some_roms">Algumas ROMs adicionam o interruptor mesmo assim. Procure “processos secundários” nas Opções de programador.</string> - <string name="gate_manual_hint">Se a notificação não funcionar, introduza manualmente o endereço e o código da janela.</string> - <string name="gate_enter_manually">Introduzir endereço manualmente</string> <string name="gate_from_computer">A partir de um computador com ADB:</string> <string name="gate_copy_command">Copiar comando</string> <string name="gate_sidequest_steps">Ligue os óculos a um computador e abra o SideQuest. Escolha “Run ADB Command”, depois “Custom Command”, escreva o comando apresentado abaixo e selecione “Run Command”.</string> <string name="gate_choose_display">Escolha em que ecrã abrir as Definições do Android.</string> <string name="gate_main_screen">Ecrã principal</string> - <string name="wadb_finding_port">Sincronizado. A procurar a porta da Depuração sem fios…</string> - <string name="wadb_enter_port">Sincronizado. Introduza a porta indicada nas Definições.</string> - <string name="wadb_applying">Dispositivo encontrado. A aplicar a definição…</string> - <string name="wadb_apply_failed">Não foi possível aplicar automaticamente. Verifique o endereço abaixo e tente novamente. %1$s</string> - <string name="wadb_title_wireless">Depuração sem fios</string> - <string name="wadb_title_done">Limite de processos secundários atualizado</string> - <string name="wadb_title">Alterar o limite de processos secundários</string> - <string name="wadb_lede_compact0">Se a opção não existir, sincronize através da Depuração sem fios.</string> - <string name="wadb_lede_compact1">Sincronizado. Verifique o endereço IP e a porta na Depuração sem fios.</string> - <string name="wadb_lede_done">O limite de processos secundários foi atualizado.</string> - <string name="wadb_lede0">Utilize o passo 2 se as Opções de programador não tiverem a definição de processos secundários. Abra Opções de programador → Depuração sem fios → Sincronizar dispositivo com código de sincronização.</string> - <string name="wadb_lede1">Sincronizado. Utilize o endereço abaixo ou atualize-o em Depuração sem fios → Endereço IP e porta.</string> - <string name="wadb_lede_done_long">O limite de processos secundários foi atualizado através da Depuração sem fios.</string> - <string name="wadb_confirmed_on">O Android confirmou que o limite está ativado.</string> - <string name="wadb_confirmed_off">O Android confirmou que o limite está desativado.</string> - <string name="wadb_pair_group">2 · Sincronizar a Depuração sem fios</string> - <string name="wadb_pair_address">Endereço IP e porta da janela de sincronização</string> - <string name="wadb_pin">Código de sincronização (PIN)</string> - <string name="wadb_pin_placeholder">6 dígitos</string> - <string name="wadb_pair">Sincronizar</string> - <string name="wadb_apply_group">2 · Aplicar através da Depuração sem fios</string> - <string name="wadb_connect_address">Endereço IP e porta de ligação</string> - <string name="wadb_pair_again">Sincronizar novamente</string> - <string name="wadb_turn_off">Desativar limite</string> - <string name="wadb_other_ways">Outras formas de o alterar</string> - <string name="wadb_dev_try_first">1 · Opções de programador (tente primeiro)</string> - <string name="wadb_restrict_on">Desative “Desativar restrições de processos secundários”.</string> - <string name="wadb_restrict_off">Ative “Desativar restrições de processos secundários”.</string> - <string name="wadb_computer_last">3 · ADB num computador (último recurso)</string> - <string name="wadb_only_if">Apenas se a Depuração sem fios não estiver disponível.</string> - <string name="wadb_computer_group">3 · ADB num computador (último recurso)</string> <string name="ctrl_color">Cor</string> <string name="ctrl_custom">Personalizada</string> <string name="ctrl_opacity">Opacidade</string> @@ -1627,8 +1590,6 @@ <item quantity="many">Foram limpas %1$d pastas de registos de sessão.</item> <item quantity="other">Foram limpas %1$d pastas de registos de sessão.</item> </plurals> - <string name="main_wadb_pair_failed">Falha na sincronização da depuração sem fios</string> - <string name="main_wadb_command_failed">Falha no comando de depuração sem fios</string> <string name="main_wadb_unavailable">A depuração sem fios não está disponível</string> <string name="main_adb_copied">Comando ADB copiado</string> <string name="main_pick_roms">Escolha a pasta de ROMs</string> diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 47b370a046..00b2f03508 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1282,8 +1282,6 @@ <string name="gate_open_dev">Abrir as Opções do desenvolvedor</string> <string name="gate_no_toggle">Esta versão do Android não tem uma chave para isso, então o DroidDeck faz a mudança pela Depuração por Wi-Fi. Leva cerca de um minuto, sem precisar de computador.</string> <string name="gate_needs_wifi">A Depuração por Wi-Fi requer Wi-Fi. Qualquer rede serve; não precisa de internet.</string> - <string name="gate_needs_notifications">O código de pareamento é digitado em uma notificação. Permita notificações do DroidDeck ou use Outras formas.</string> - <string name="gate_allow_notifications">Permitir notificações</string> <string name="gate_step1">Abra Configurações → Opções do desenvolvedor → Depuração por Wi-Fi e ative</string> <string name="gate_step2">Toque em “Parear o dispositivo com um código de pareamento”</string> <string name="gate_step3">Digite o código na notificação do DroidDeck</string> @@ -1300,48 +1298,13 @@ <string name="gate_status">Status</string> <string name="gate_polling">Verificando a cada 2 segundos. Esta página fecha quando o limite for desativado.</string> <string name="gate_other_ways">Outras formas</string> - <string name="gate_other_toggle">Depuração por Wi-Fi, endereço manual, ADB pelo computador</string> - <string name="gate_other_no_toggle">Endereço manual, ADB pelo computador, Opções do desenvolvedor</string> <string name="gate_use_wireless_instead">Usar a Depuração por Wi-Fi</string> <string name="gate_some_roms">Algumas ROMs adicionam a chave mesmo assim. Procure “processos filhos” nas Opções do desenvolvedor.</string> - <string name="gate_manual_hint">Se a notificação não funcionar, digite você mesmo o endereço e o código do pop-up.</string> - <string name="gate_enter_manually">Digitar endereço manualmente</string> <string name="gate_from_computer">De um computador com ADB:</string> <string name="gate_copy_command">Copiar comando</string> <string name="gate_sidequest_steps">Conecte o headset a um computador e abra o SideQuest. Escolha “Run ADB Command”, depois “Custom Command”, digite o comando mostrado abaixo e selecione “Run Command”.</string> <string name="gate_choose_display">Escolha em qual tela abrir as Configurações do Android.</string> <string name="gate_main_screen">Tela principal</string> - <string name="wadb_finding_port">Pareado. Procurando a porta da Depuração por Wi-Fi…</string> - <string name="wadb_enter_port">Pareado. Digite a porta mostrada nas Configurações.</string> - <string name="wadb_applying">Dispositivo encontrado. Aplicando a configuração…</string> - <string name="wadb_apply_failed">Não foi possível aplicar automaticamente. Verifique o endereço abaixo e tente de novo. %1$s</string> - <string name="wadb_title_wireless">Depuração por Wi-Fi</string> - <string name="wadb_title_done">Limite de processos filhos atualizado</string> - <string name="wadb_title">Alterar o limite de processos filhos</string> - <string name="wadb_lede_compact0">Se a opção não existir, pareie pela Depuração por Wi-Fi.</string> - <string name="wadb_lede_compact1">Pareado. Verifique o endereço IP e a porta na Depuração por Wi-Fi.</string> - <string name="wadb_lede_done">O limite de processos filhos foi atualizado.</string> - <string name="wadb_lede0">Use a etapa 2 se as Opções do desenvolvedor não tiverem a configuração de processos filhos. Abra Opções do desenvolvedor → Depuração por Wi-Fi → Parear o dispositivo com um código de pareamento.</string> - <string name="wadb_lede1">Pareado. Use o endereço abaixo ou atualize-o em Depuração por Wi-Fi → Endereço IP e porta.</string> - <string name="wadb_lede_done_long">O limite de processos filhos foi atualizado pela Depuração por Wi-Fi.</string> - <string name="wadb_confirmed_on">O Android confirmou que o limite está ativado.</string> - <string name="wadb_confirmed_off">O Android confirmou que o limite está desativado.</string> - <string name="wadb_pair_group">2 · Parear pela Depuração por Wi-Fi</string> - <string name="wadb_pair_address">Endereço IP e porta do pop-up de pareamento</string> - <string name="wadb_pin">Código de pareamento (PIN)</string> - <string name="wadb_pin_placeholder">6 dígitos</string> - <string name="wadb_pair">Parear</string> - <string name="wadb_apply_group">2 · Aplicar pela Depuração por Wi-Fi</string> - <string name="wadb_connect_address">Endereço IP e porta de conexão</string> - <string name="wadb_pair_again">Parear de novo</string> - <string name="wadb_turn_off">Desativar o limite</string> - <string name="wadb_other_ways">Outras formas de alterar</string> - <string name="wadb_dev_try_first">1 · Opções do desenvolvedor (tente primeiro)</string> - <string name="wadb_restrict_on">Desative “Desativar restrições de processos filhos”.</string> - <string name="wadb_restrict_off">Ative “Desativar restrições de processos filhos”.</string> - <string name="wadb_computer_last">3 · ADB pelo computador (último recurso)</string> - <string name="wadb_only_if">Só se a Depuração por Wi-Fi não estiver disponível.</string> - <string name="wadb_computer_group">3 · ADB pelo computador (último recurso)</string> <string name="ctrl_color">Cor</string> <string name="ctrl_custom">Personalizada</string> <string name="ctrl_opacity">Opacidade</string> @@ -1635,8 +1598,6 @@ <item quantity="many">%1$d pastas de logs de sessão limpas.</item> <item quantity="other">%1$d pastas de logs de sessão limpas.</item> </plurals> - <string name="main_wadb_pair_failed">Falha no pareamento da depuração por Wi-Fi</string> - <string name="main_wadb_command_failed">Falha no comando de depuração por Wi-Fi</string> <string name="main_wadb_unavailable">A depuração por Wi-Fi não está disponível</string> <string name="main_adb_copied">Comando ADB copiado</string> <string name="main_pick_roms">Escolha a pasta de ROMs</string> diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index 69a16f1cf2..3e3e6e6aaa 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -1283,8 +1283,6 @@ <string name="gate_open_dev">Deschide Opțiunile pentru dezvoltatori</string> <string name="gate_no_toggle">Această versiune de Android nu are un comutator pentru asta, așa că DroidDeck o schimbă prin Depanarea wireless. Durează circa un minut, fără a avea nevoie de un computer.</string> <string name="gate_needs_wifi">Depanarea wireless are nevoie de Wi-Fi. Orice rețea funcționează; nu are nevoie de internet.</string> - <string name="gate_needs_notifications">Codul de asociere apare într-o notificare. Permite notificările pentru DroidDeck, sau folosește Alte moduri.</string> - <string name="gate_allow_notifications">Permite notificările</string> <string name="gate_step1">Deschide Setări → Opțiuni pentru dezvoltatori → Depanare wireless și activează-o</string> <string name="gate_step2">Apasă „Asociază dispozitivul cu un cod de asociere”</string> <string name="gate_step3">Introdu codul în notificarea DroidDeck</string> @@ -1301,48 +1299,13 @@ <string name="gate_status">Stare</string> <string name="gate_polling">Se verifică la fiecare 2 secunde. Această pagină se închide când este dezactivată.</string> <string name="gate_other_ways">Alte moduri</string> - <string name="gate_other_toggle">Depanare wireless, adresă manuală, ADB pe computer</string> - <string name="gate_other_no_toggle">Adresă manuală, ADB pe computer, Opțiuni pentru dezvoltatori</string> <string name="gate_use_wireless_instead">Folosește Depanarea wireless în schimb</string> <string name="gate_some_roms">Unele ROM-uri adaugă comutatorul oricum. Caută „procese-copil” în Opțiuni pentru dezvoltatori.</string> - <string name="gate_manual_hint">Dacă notificarea nu funcționează, introdu tu adresa și codul din fereastră.</string> - <string name="gate_enter_manually">Introdu adresa manual</string> <string name="gate_from_computer">De pe un computer cu ADB:</string> <string name="gate_copy_command">Copiază comanda</string> <string name="gate_sidequest_steps">Conectează căștile la un computer și deschide SideQuest. Alege „Run ADB Command”, apoi „Custom Command”, scrie comanda afișată mai jos și selectează „Run Command”.</string> <string name="gate_choose_display">Alege pe care afișaj se deschid Setările Android.</string> <string name="gate_main_screen">Ecranul principal</string> - <string name="wadb_finding_port">Asociat. Se caută portul de Depanare wireless…</string> - <string name="wadb_enter_port">Asociat. Introdu portul din Setări.</string> - <string name="wadb_applying">Dispozitiv găsit. Se aplică setarea…</string> - <string name="wadb_apply_failed">Nu s-a putut aplica automat. Verifică adresa de mai jos și încearcă din nou. %1$s</string> - <string name="wadb_title_wireless">Depanare wireless</string> - <string name="wadb_title_done">Limita proceselor-copil a fost actualizată</string> - <string name="wadb_title">Schimbă limita proceselor-copil</string> - <string name="wadb_lede_compact0">Dacă opțiunea lipsește, asociază-te prin Depanare wireless.</string> - <string name="wadb_lede_compact1">Asociat. Verifică adresa IP și portul în Depanare wireless.</string> - <string name="wadb_lede_done">Limita proceselor-copil a fost actualizată.</string> - <string name="wadb_lede0">Folosește pasul 2 dacă Opțiunile pentru dezvoltatori nu au o setare pentru procese-copil. Deschide Opțiuni pentru dezvoltatori → Depanare wireless → Asociază dispozitivul cu un cod de asociere.</string> - <string name="wadb_lede1">Asociat. Folosește adresa de mai jos, sau actualizeaz-o din Depanare wireless → Adresă IP și port.</string> - <string name="wadb_lede_done_long">Limita proceselor-copil a fost actualizată prin Depanarea wireless.</string> - <string name="wadb_confirmed_on">Android a confirmat că limita este activă.</string> - <string name="wadb_confirmed_off">Android a confirmat că limita este dezactivată.</string> - <string name="wadb_pair_group">2 · Asociază Depanarea wireless</string> - <string name="wadb_pair_address">Adresa IP și portul ferestrei de asociere</string> - <string name="wadb_pin">Cod de asociere (PIN)</string> - <string name="wadb_pin_placeholder">6 cifre</string> - <string name="wadb_pair">Asociază</string> - <string name="wadb_apply_group">2 · Aplică prin Depanarea wireless</string> - <string name="wadb_connect_address">Adresa IP și portul de conexiune</string> - <string name="wadb_pair_again">Asociază din nou</string> - <string name="wadb_turn_off">Dezactivează limita</string> - <string name="wadb_other_ways">Alte moduri de a o schimba</string> - <string name="wadb_dev_try_first">1 · Opțiuni pentru dezvoltatori (încearcă mai întâi)</string> - <string name="wadb_restrict_on">Dezactivează „Dezactivează restricțiile pentru procese secundare”.</string> - <string name="wadb_restrict_off">Activează „Dezactivează restricțiile pentru procese secundare”.</string> - <string name="wadb_computer_last">3 · ADB pe computer (ultima soluție)</string> - <string name="wadb_only_if">Doar dacă Depanarea wireless nu este disponibilă.</string> - <string name="wadb_computer_group">3 · ADB pe computer (ultima soluție)</string> <string name="ctrl_color">Culoare</string> <string name="ctrl_custom">Personalizat</string> <string name="ctrl_opacity">Opacitate</string> @@ -1636,8 +1599,6 @@ <item quantity="few">S-au șters %1$d foldere de jurnal de sesiune.</item> <item quantity="other">S-au șters %1$d de foldere de jurnal de sesiune.</item> </plurals> - <string name="main_wadb_pair_failed">Asocierea Depanării wireless a eșuat</string> - <string name="main_wadb_command_failed">Comanda Depanării wireless a eșuat</string> <string name="main_wadb_unavailable">Depanarea wireless nu este disponibilă</string> <string name="main_adb_copied">Comanda ADB copiată</string> <string name="main_pick_roms">Alege folderul ROMs</string> diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index e45c8af9a0..3327a46be1 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1290,8 +1290,6 @@ <string name="gate_open_dev">Открыть «Для разработчиков»</string> <string name="gate_no_toggle">В этой версии Android нет такого переключателя, поэтому DroidDeck внесет изменения через отладку по Wi-Fi. Это займет около минуты, компьютер не нужен.</string> <string name="gate_needs_wifi">Для отладки по Wi-Fi требуется Wi-Fi. Подойдет любая сеть, интернет не нужен.</string> - <string name="gate_needs_notifications">Код сопряжения придет в уведомлении. Разрешите DroidDeck отправлять уведомления или используйте «Другие способы».</string> - <string name="gate_allow_notifications">Разрешить уведомления</string> <string name="gate_step1">Откройте Настройки → Для разработчиков → Отладка по Wi-Fi и включите ее</string> <string name="gate_step2">Нажмите «Подключить устройство с помощью кода подключения»</string> <string name="gate_step3">Введите код сопряжения в уведомлении DroidDeck</string> @@ -1308,48 +1306,13 @@ <string name="gate_status">Статус</string> <string name="gate_polling">Проверка каждые 2 секунды. После отключения этого переключателя страница закроется автоматически.</string> <string name="gate_other_ways">Другие способы</string> - <string name="gate_other_toggle">Отладка по Wi-Fi, ручной ввод адреса, ADB на ПК</string> - <string name="gate_other_no_toggle">Ручной ввод адреса, ADB на ПК, «Для разработчиков»</string> <string name="gate_use_wireless_instead">Использовать отладку по Wi-Fi</string> <string name="gate_some_roms">В некоторых прошивках переключатель все же есть. Поищите «дочерние процессы» в разделе «Для разработчиков».</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">Сопряжено. Поиск порта отладки по Wi-Fi…</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">Отладка по Wi-Fi</string> - <string name="wadb_title_done">Ограничение дочерних процессов обновлено</string> - <string name="wadb_title">Изменить ограничение дочерних процессов</string> - <string name="wadb_lede_compact0">Если опции нет, выполните сопряжение через отладку по Wi-Fi.</string> - <string name="wadb_lede_compact1">Сопряжено. Проверьте IP-адрес и порт в отладке по Wi-Fi.</string> - <string name="wadb_lede_done">Ограничение дочерних процессов обновлено.</string> - <string name="wadb_lede0">Если в параметрах разработчика нет настройки дочерних процессов, используйте шаг 2. Откройте Для разработчиков → Отладка по Wi-Fi → Сопряжение устройства с помощью кода.</string> - <string name="wadb_lede1">Сопряжено. Используйте адрес ниже или обновите его в разделе Отладка по Wi-Fi → IP-адрес и порт.</string> - <string name="wadb_lede_done_long">Ограничение дочерних процессов обновлено через отладку по Wi-Fi.</string> - <string name="wadb_confirmed_on">Android подтвердил, что ограничение включено.</string> - <string name="wadb_confirmed_off">Android подтвердил, что ограничение отключено.</string> - <string name="wadb_pair_group">2 · Сопряжение отладки по Wi-Fi</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 · Применение через отладку по Wi-Fi</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">Используйте только если отладка по Wi-Fi недоступна.</string> - <string name="wadb_computer_group">3 · ADB на ПК (крайняя мера)</string> <string name="ctrl_color">Цвет</string> <string name="ctrl_custom">Пользовательский</string> <string name="ctrl_opacity">Непрозрачность</string> @@ -1649,8 +1612,6 @@ <item quantity="many">Очищено %1$d папок журналов сессии.</item> <item quantity="other">Очищено %1$d папки журналов сессии.</item> </plurals> - <string name="main_wadb_pair_failed">Ошибка сопряжения для отладки по Wi-Fi</string> - <string name="main_wadb_command_failed">Ошибка команды отладки по Wi-Fi</string> <string name="main_wadb_unavailable">Отладка по Wi-Fi недоступна</string> <string name="main_adb_copied">Команда ADB скопирована</string> <string name="main_pick_roms">Выберите папку ROM</string> diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index afa62b8e4a..7793dcc901 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -1276,8 +1276,6 @@ <string name="gate_open_dev">Öppna Utvecklaralternativ</string> <string name="gate_no_toggle">Den här Android-versionen har ingen omkopplare för det, så DroidDeck ändrar det via Trådlös felsökning. Tar ungefär en minut, ingen dator behövs.</string> <string name="gate_needs_wifi">Trådlös felsökning kräver Wi-Fi. Alla nätverk fungerar; det behöver inte internet.</string> - <string name="gate_needs_notifications">Ihopkopplingskoden skickas i en avisering. Tillåt aviseringar för DroidDeck, eller använd Andra sätt.</string> - <string name="gate_allow_notifications">Tillåt aviseringar</string> <string name="gate_step1">Öppna Inställningar → Utvecklaralternativ → Trådlös felsökning och slå på det</string> <string name="gate_step2">Tryck på ”Para ihop enhet med ihopkopplingskod”</string> <string name="gate_step3">Skriv in koden i DroidDeck-aviseringen</string> @@ -1294,48 +1292,13 @@ <string name="gate_status">Status</string> <string name="gate_polling">Kontrollerar var 2 sekunder. Den här sidan stängs när det är av.</string> <string name="gate_other_ways">Andra sätt</string> - <string name="gate_other_toggle">Trådlös felsökning, manuell adress, dator-ADB</string> - <string name="gate_other_no_toggle">Manuell adress, dator-ADB, Utvecklaralternativ</string> <string name="gate_use_wireless_instead">Använd Trådlös felsökning i stället</string> <string name="gate_some_roms">Vissa ROM:ar lägger till omkopplaren trots allt. Leta efter ”underprocess” i Utvecklaralternativ.</string> - <string name="gate_manual_hint">Om aviseringen inte fungerar, ange popup-fönstrets adress och kod själv.</string> - <string name="gate_enter_manually">Ange adress manuellt</string> <string name="gate_from_computer">Från en dator med ADB:</string> <string name="gate_copy_command">Kopiera kommando</string> <string name="gate_sidequest_steps">Anslut headsetet till en dator och öppna SideQuest. Välj ”Run ADB Command” och sedan ”Custom Command”, skriv in kommandot som visas nedan och välj ”Run Command”.</string> <string name="gate_choose_display">Välj vilken skärm Android-inställningar ska öppnas på.</string> <string name="gate_main_screen">Huvudskärm</string> - <string name="wadb_finding_port">Ihopkopplad. Letar efter porten för Trådlös felsökning…</string> - <string name="wadb_enter_port">Ihopkopplad. Ange porten från Inställningar.</string> - <string name="wadb_applying">Enhet hittad. Tillämpar inställningen…</string> - <string name="wadb_apply_failed">Kunde inte tillämpas automatiskt. Kontrollera adressen nedan och försök igen. %1$s</string> - <string name="wadb_title_wireless">Trådlös felsökning</string> - <string name="wadb_title_done">Gränsen för underprocesser har uppdaterats</string> - <string name="wadb_title">Ändra gränsen för underprocesser</string> - <string name="wadb_lede_compact0">Om alternativet saknas, para ihop via Trådlös felsökning.</string> - <string name="wadb_lede_compact1">Ihopkopplad. Kontrollera IP-adressen och porten i Trådlös felsökning.</string> - <string name="wadb_lede_done">Gränsen för underprocesser har uppdaterats.</string> - <string name="wadb_lede0">Använd steg 2 om Utvecklaralternativ inte har någon inställning för underprocesser. Öppna Utvecklaralternativ → Trådlös felsökning → Para ihop enhet med ihopkopplingskod.</string> - <string name="wadb_lede1">Ihopkopplad. Använd adressen nedan, eller uppdatera den från Trådlös felsökning → IP-adress & port.</string> - <string name="wadb_lede_done_long">Gränsen för underprocesser uppdaterades via Trådlös felsökning.</string> - <string name="wadb_confirmed_on">Android bekräftade att gränsen är på.</string> - <string name="wadb_confirmed_off">Android bekräftade att gränsen är av.</string> - <string name="wadb_pair_group">2 · Para ihop Trådlös felsökning</string> - <string name="wadb_pair_address">Ihopkopplingsrutans IP-adress & port</string> - <string name="wadb_pin">Ihopkopplingskod (PIN)</string> - <string name="wadb_pin_placeholder">6 siffror</string> - <string name="wadb_pair">Para ihop</string> - <string name="wadb_apply_group">2 · Tillämpa via Trådlös felsökning</string> - <string name="wadb_connect_address">Anslutningens IP-adress & port</string> - <string name="wadb_pair_again">Para ihop igen</string> - <string name="wadb_turn_off">Stäng av gränsen</string> - <string name="wadb_other_ways">Andra sätt att ändra det</string> - <string name="wadb_dev_try_first">1 · Utvecklaralternativ (prova först)</string> - <string name="wadb_restrict_on">Slå av ”Inaktivera begränsningar på underordnade processer”.</string> - <string name="wadb_restrict_off">Slå på ”Inaktivera begränsningar på underordnade processer”.</string> - <string name="wadb_computer_last">3 · Dator-ADB (sista utväg)</string> - <string name="wadb_only_if">Bara om Trådlös felsökning inte är tillgänglig.</string> - <string name="wadb_computer_group">3 · Dator-ADB (sista utväg)</string> <string name="ctrl_color">Färg</string> <string name="ctrl_custom">Anpassad</string> <string name="ctrl_opacity">Opacitet</string> @@ -1623,8 +1586,6 @@ <item quantity="one">Rensade %1$d sessionsloggmapp.</item> <item quantity="other">Rensade %1$d sessionsloggmappar.</item> </plurals> - <string name="main_wadb_pair_failed">Parkopplingen för trådlös felsökning misslyckades</string> - <string name="main_wadb_command_failed">Kommandot för trådlös felsökning misslyckades</string> <string name="main_wadb_unavailable">Trådlös felsökning är inte tillgänglig</string> <string name="main_adb_copied">ADB-kommandot har kopierats</string> <string name="main_pick_roms">Välj ROM-mappen</string> diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 14a813ab5b..6f7186b7b8 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -1270,8 +1270,6 @@ <string name="gate_open_dev">เปิดตัวเลือกสำหรับนักพัฒนา</string> <string name="gate_no_toggle">Android รุ่นนี้ไม่มีสวิตช์สำหรับสิ่งนี้ ดังนั้น DroidDeck จะเปลี่ยนค่าผ่าน Wireless debugging ใช้เวลาประมาณหนึ่งนาที ไม่ต้องใช้คอมพิวเตอร์</string> <string name="gate_needs_wifi">Wireless debugging ต้องใช้ Wi-Fi เครือข่ายใดก็ได้ ไม่จำเป็นต้องมีอินเทอร์เน็ต</string> - <string name="gate_needs_notifications">รหัสจับคู่จะแสดงในการแจ้งเตือน อนุญาตการแจ้งเตือนสำหรับ DroidDeck หรือใช้วิธีอื่น</string> - <string name="gate_allow_notifications">อนุญาตการแจ้งเตือน</string> <string name="gate_step1">เปิดการตั้งค่า → ตัวเลือกสำหรับนักพัฒนา → Wireless debugging แล้วเปิดใช้งาน</string> <string name="gate_step2">แตะ “Pair device with pairing code”</string> <string name="gate_step3">พิมพ์รหัสลงในการแจ้งเตือนของ DroidDeck</string> @@ -1288,48 +1286,13 @@ <string name="gate_status">สถานะ</string> <string name="gate_polling">กำลังตรวจสอบทุก 2 วินาที หน้านี้จะปิดเมื่อปิดใช้งานแล้ว</string> <string name="gate_other_ways">วิธีอื่น</string> - <string name="gate_other_toggle">Wireless debugging, ที่อยู่แบบกำหนดเอง, ADB จากคอมพิวเตอร์</string> - <string name="gate_other_no_toggle">ที่อยู่แบบกำหนดเอง, ADB จากคอมพิวเตอร์, ตัวเลือกสำหรับนักพัฒนา</string> <string name="gate_use_wireless_instead">ใช้ Wireless debugging แทน</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">จับคู่แล้ว กำลังค้นหาพอร์ตของ Wireless debugging…</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">หากไม่พบตัวเลือกนี้ ให้จับคู่ผ่าน Wireless debugging</string> - <string name="wadb_lede_compact1">จับคู่แล้ว ตรวจสอบที่อยู่ IP และพอร์ตใน Wireless debugging</string> - <string name="wadb_lede_done">อัปเดตขีดจำกัดโพรเซสลูกแล้ว</string> - <string name="wadb_lede0">ใช้ขั้นตอนที่ 2 หากตัวเลือกสำหรับนักพัฒนาไม่มีการตั้งค่าโพรเซสลูก เปิดตัวเลือกสำหรับนักพัฒนา → Wireless debugging → Pair device with pairing code</string> - <string name="wadb_lede1">จับคู่แล้ว ใช้ที่อยู่ด้านล่าง หรืออัปเดตจาก Wireless debugging → IP address & Port</string> - <string name="wadb_lede_done_long">อัปเดตขีดจำกัดโพรเซสลูกผ่าน Wireless debugging แล้ว</string> - <string name="wadb_confirmed_on">Android ยืนยันแล้วว่าขีดจำกัดเปิดอยู่</string> - <string name="wadb_confirmed_off">Android ยืนยันแล้วว่าขีดจำกัดปิดอยู่</string> - <string name="wadb_pair_group">2 · จับคู่ Wireless debugging</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 · ปรับใช้ผ่าน Wireless debugging</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">ใช้เฉพาะเมื่อ Wireless debugging ใช้งานไม่ได้</string> - <string name="wadb_computer_group">3 · ADB จากคอมพิวเตอร์ (ทางเลือกสุดท้าย)</string> <string name="ctrl_color">สี</string> <string name="ctrl_custom">กำหนดเอง</string> <string name="ctrl_opacity">ความโปร่งใส</string> @@ -1611,8 +1574,6 @@ <plurals name="main_logs_cleared"> <item quantity="other">ล้างโฟลเดอร์ล็อกเซสชัน %1$d โฟลเดอร์แล้ว</item> </plurals> - <string name="main_wadb_pair_failed">การจับคู่ Wireless debugging ล้มเหลว</string> - <string name="main_wadb_command_failed">คำสั่ง Wireless debugging ล้มเหลว</string> <string name="main_wadb_unavailable">Wireless debugging ไม่พร้อมใช้งาน</string> <string name="main_adb_copied">คัดลอกคำสั่ง ADB แล้ว</string> <string name="main_pick_roms">เลือกโฟลเดอร์ ROM</string> diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 9e67af3366..cfa1424b2e 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -1268,8 +1268,6 @@ <string name="gate_open_dev">Geliştirici seçeneklerini aç</string> <string name="gate_no_toggle">Bu Android sürümünde bunun için bir anahtar yok, bu yüzden DroidDeck bunu Kablosuz hata ayıklama üzerinden değiştirir. Yaklaşık bir dakika sürer, bilgisayar gerekmez.</string> <string name="gate_needs_wifi">Kablosuz hata ayıklama Wi-Fi gerektirir. Herhangi bir ağ işe yarar; internet gerekmez.</string> - <string name="gate_needs_notifications">Eşleştirme kodu bir bildirime gelir. DroidDeck için bildirimlere izin verin veya Diğer yollar\'ı kullanın.</string> - <string name="gate_allow_notifications">Bildirimlere izin ver</string> <string name="gate_step1">Ayarlar → Geliştirici seçenekleri → Kablosuz hata ayıklama\'yı açın</string> <string name="gate_step2">“Eşleştirme koduyla cihaz eşle” seçeneğine dokunun</string> <string name="gate_step3">Kodu DroidDeck bildirimine yazın</string> @@ -1286,48 +1284,13 @@ <string name="gate_status">Durum</string> <string name="gate_polling">Her 2 saniyede bir kontrol ediliyor. Kapandığında bu sayfa kapanır.</string> <string name="gate_other_ways">Diğer yollar</string> - <string name="gate_other_toggle">Kablosuz hata ayıklama, elle adres girme, bilgisayardan ADB</string> - <string name="gate_other_no_toggle">Elle adres girme, bilgisayardan ADB, Geliştirici seçenekleri</string> <string name="gate_use_wireless_instead">Bunun yerine Kablosuz hata ayıklamayı kullan</string> <string name="gate_some_roms">Bazı ROM\'lar bu anahtarı yine de ekler. Geliştirici seçenekleri\'nde “alt süreç” ifadesini arayın.</string> - <string name="gate_manual_hint">Bildirim işe yaramazsa açılır penceredeki adresi ve kodu kendiniz girin.</string> - <string name="gate_enter_manually">Adresi elle girin</string> <string name="gate_from_computer">ADB\'li bir bilgisayardan:</string> <string name="gate_copy_command">Komutu kopyala</string> <string name="gate_sidequest_steps">Başlığı bir bilgisayara bağlayın ve SideQuest’i açın. “Run ADB Command”, ardından “Custom Command” seçin, aşağıda gösterilen komutu yazın ve “Run Command” seçin.</string> <string name="gate_choose_display">Android Ayarları\'nın hangi ekranda açılacağını seçin.</string> <string name="gate_main_screen">Ana ekran</string> - <string name="wadb_finding_port">Eşleşti. Kablosuz hata ayıklama bağlantı noktası bulunuyor…</string> - <string name="wadb_enter_port">Eşleşti. Bağlantı noktasını Ayarlar\'dan girin.</string> - <string name="wadb_applying">Cihaz bulundu. Ayar uygulanıyor…</string> - <string name="wadb_apply_failed">Otomatik olarak uygulanamadı. Aşağıdaki adresi kontrol edip yeniden deneyin. %1$s</string> - <string name="wadb_title_wireless">Kablosuz hata ayıklama</string> - <string name="wadb_title_done">Alt süreç sınırı güncellendi</string> - <string name="wadb_title">Alt süreç sınırını değiştir</string> - <string name="wadb_lede_compact0">Seçenek yoksa Kablosuz hata ayıklama üzerinden eşleyin.</string> - <string name="wadb_lede_compact1">Eşleşti. IP adresini ve bağlantı noktasını Kablosuz hata ayıklama\'da kontrol edin.</string> - <string name="wadb_lede_done">Alt süreç sınırı güncellendi.</string> - <string name="wadb_lede0">Geliştirici seçenekleri\'nde alt süreç ayarı yoksa 2. adımı kullanın. Geliştirici seçenekleri → Kablosuz hata ayıklama → Eşleştirme koduyla cihaz eşle\'yi açın.</string> - <string name="wadb_lede1">Eşleşti. Aşağıdaki adresi kullanın veya Kablosuz hata ayıklama → IP adresi ve bağlantı noktası\'ndan güncelleyin.</string> - <string name="wadb_lede_done_long">Alt süreç sınırı Kablosuz hata ayıklama üzerinden güncellendi.</string> - <string name="wadb_confirmed_on">Android sınırın açık olduğunu onayladı.</string> - <string name="wadb_confirmed_off">Android sınırın kapalı olduğunu onayladı.</string> - <string name="wadb_pair_group">2 · Kablosuz hata ayıklamayı eşle</string> - <string name="wadb_pair_address">Eşleştirme açılır penceresinin IP adresi ve bağlantı noktası</string> - <string name="wadb_pin">Eşleştirme kodu (PIN)</string> - <string name="wadb_pin_placeholder">6 hane</string> - <string name="wadb_pair">Eşle</string> - <string name="wadb_apply_group">2 · Kablosuz hata ayıklama üzerinden uygula</string> - <string name="wadb_connect_address">Bağlantı IP adresi ve bağlantı noktası</string> - <string name="wadb_pair_again">Yeniden eşle</string> - <string name="wadb_turn_off">Sınırı kapat</string> - <string name="wadb_other_ways">Değiştirmenin diğer yolları</string> - <string name="wadb_dev_try_first">1 · Geliştirici seçenekleri (önce bunu deneyin)</string> - <string name="wadb_restrict_on">“Alt işlem kısıtlamalarını devre dışı bırak” seçeneğini kapalı olarak ayarlayın.</string> - <string name="wadb_restrict_off">“Alt işlem kısıtlamalarını devre dışı bırak” seçeneğini açık olarak ayarlayın.</string> - <string name="wadb_computer_last">3 · Bilgisayardan ADB (son yöntem)</string> - <string name="wadb_only_if">Yalnızca Kablosuz hata ayıklama kullanılamıyorsa.</string> - <string name="wadb_computer_group">3 · Bilgisayardan ADB (son yöntem)</string> <string name="ctrl_color">Renk</string> <string name="ctrl_custom">Özel</string> <string name="ctrl_opacity">Opaklık</string> @@ -1615,8 +1578,6 @@ <item quantity="one">%1$d oturum günlüğü klasörü temizlendi.</item> <item quantity="other">%1$d oturum günlüğü klasörü temizlendi.</item> </plurals> - <string name="main_wadb_pair_failed">Kablosuz hata ayıklama eşlemesi başarısız oldu</string> - <string name="main_wadb_command_failed">Kablosuz hata ayıklama komutu başarısız oldu</string> <string name="main_wadb_unavailable">Kablosuz hata ayıklama kullanılamıyor</string> <string name="main_adb_copied">ADB komutu kopyalandı</string> <string name="main_pick_roms">ROM klasörünü seçin</string> diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 8609b09b5d..378f1aaf1a 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -1290,8 +1290,6 @@ <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> @@ -1308,48 +1306,13 @@ <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">Деякі прошивки все одно додають цей перемикач. Пошукайте «дочірній процес» у параметрах розробника.</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> @@ -1649,8 +1612,6 @@ <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> diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index fd23d10b90..3f1ed9d6bc 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -1270,8 +1270,6 @@ <string name="gate_open_dev">Mở Tùy chọn cho nhà phát triển</string> <string name="gate_no_toggle">Phiên bản Android này không có công tắc cho việc đó, nên DroidDeck thay đổi nó qua Gỡ lỗi qua mạng không dây. Mất khoảng một phút, không cần máy tính.</string> <string name="gate_needs_wifi">Gỡ lỗi qua mạng không dây cần Wi-Fi. Mạng nào cũng được; không cần Internet.</string> - <string name="gate_needs_notifications">Mã ghép nối nằm trong một thông báo. Hãy cho phép thông báo cho DroidDeck, hoặc dùng Cách khác.</string> - <string name="gate_allow_notifications">Cho phép thông báo</string> <string name="gate_step1">Mở Settings → Developer options → Wireless debugging và bật nó lên</string> <string name="gate_step2">Nhấn “Pair device with pairing code”</string> <string name="gate_step3">Nhập mã vào thông báo của DroidDeck</string> @@ -1288,48 +1286,13 @@ <string name="gate_status">Trạng thái</string> <string name="gate_polling">Đang kiểm tra mỗi 2 giây. Trang này sẽ đóng khi nó tắt.</string> <string name="gate_other_ways">Cách khác</string> - <string name="gate_other_toggle">Gỡ lỗi qua mạng không dây, địa chỉ thủ công, ADB từ máy tính</string> - <string name="gate_other_no_toggle">Địa chỉ thủ công, ADB từ máy tính, Tùy chọn cho nhà phát triển</string> <string name="gate_use_wireless_instead">Dùng Gỡ lỗi qua mạng không dây thay vào đó</string> <string name="gate_some_roms">Một số ROM vẫn thêm công tắc này. Tìm “child process” trong Tùy chọn cho nhà phát triển.</string> - <string name="gate_manual_hint">Nếu thông báo không hoạt động, hãy tự nhập địa chỉ và mã của cửa sổ bật lên.</string> - <string name="gate_enter_manually">Nhập địa chỉ thủ công</string> <string name="gate_from_computer">Từ một máy tính có ADB:</string> <string name="gate_copy_command">Sao chép lệnh</string> <string name="gate_sidequest_steps">Kết nối kính với máy tính và mở SideQuest. Chọn “Run ADB Command”, rồi “Custom Command”, nhập lệnh hiển thị bên dưới và chọn “Run Command”.</string> <string name="gate_choose_display">Chọn màn hình để mở Android Settings.</string> <string name="gate_main_screen">Màn hình chính</string> - <string name="wadb_finding_port">Đã ghép nối. Đang tìm cổng Gỡ lỗi qua mạng không dây…</string> - <string name="wadb_enter_port">Đã ghép nối. Nhập cổng từ Settings.</string> - <string name="wadb_applying">Đã tìm thấy thiết bị. Đang áp dụng thiết lập…</string> - <string name="wadb_apply_failed">Không thể áp dụng tự động. Kiểm tra địa chỉ dưới đây và thử lại. %1$s</string> - <string name="wadb_title_wireless">Gỡ lỗi qua mạng không dây</string> - <string name="wadb_title_done">Đã cập nhật giới hạn tiến trình con</string> - <string name="wadb_title">Đổi giới hạn tiến trình con</string> - <string name="wadb_lede_compact0">Nếu thiếu tùy chọn này, hãy ghép nối qua Gỡ lỗi qua mạng không dây.</string> - <string name="wadb_lede_compact1">Đã ghép nối. Kiểm tra địa chỉ IP và cổng trong Gỡ lỗi qua mạng không dây.</string> - <string name="wadb_lede_done">Giới hạn tiến trình con đã được cập nhật.</string> - <string name="wadb_lede0">Dùng bước 2 nếu Tùy chọn cho nhà phát triển không có thiết lập tiến trình con. Mở Developer options → Wireless debugging → Pair device with pairing code.</string> - <string name="wadb_lede1">Đã ghép nối. Dùng địa chỉ dưới đây, hoặc cập nhật nó từ Wireless debugging → IP address & Port.</string> - <string name="wadb_lede_done_long">Giới hạn tiến trình con đã được cập nhật qua Gỡ lỗi qua mạng không dây.</string> - <string name="wadb_confirmed_on">Android xác nhận giới hạn đang bật.</string> - <string name="wadb_confirmed_off">Android xác nhận giới hạn đang tắt.</string> - <string name="wadb_pair_group">2 · Ghép nối Gỡ lỗi qua mạng không dây</string> - <string name="wadb_pair_address">Địa chỉ IP & cổng của cửa sổ bật lên ghép nối</string> - <string name="wadb_pin">Mã ghép nối (PIN)</string> - <string name="wadb_pin_placeholder">6 số</string> - <string name="wadb_pair">Ghép nối</string> - <string name="wadb_apply_group">2 · Áp dụng qua Gỡ lỗi qua mạng không dây</string> - <string name="wadb_connect_address">Địa chỉ IP & cổng kết nối</string> - <string name="wadb_pair_again">Ghép nối lại</string> - <string name="wadb_turn_off">Tắt giới hạn</string> - <string name="wadb_other_ways">Cách khác để đổi nó</string> - <string name="wadb_dev_try_first">1 · Tùy chọn cho nhà phát triển (thử trước)</string> - <string name="wadb_restrict_on">Đặt “Tắt các mục hạn chế đối với tiến trình con” thành tắt.</string> - <string name="wadb_restrict_off">Đặt “Tắt các mục hạn chế đối với tiến trình con” thành bật.</string> - <string name="wadb_computer_last">3 · ADB từ máy tính (phương án cuối)</string> - <string name="wadb_only_if">Chỉ khi Gỡ lỗi qua mạng không dây không khả dụng.</string> - <string name="wadb_computer_group">3 · ADB từ máy tính (phương án cuối)</string> <string name="ctrl_color">Màu</string> <string name="ctrl_custom">Tùy chỉnh</string> <string name="ctrl_opacity">Độ mờ</string> @@ -1611,8 +1574,6 @@ <plurals name="main_logs_cleared"> <item quantity="other">Đã xóa %1$d thư mục log phiên.</item> </plurals> - <string name="main_wadb_pair_failed">Ghép nối Gỡ lỗi qua mạng không dây thất bại</string> - <string name="main_wadb_command_failed">Lệnh Gỡ lỗi qua mạng không dây thất bại</string> <string name="main_wadb_unavailable">Gỡ lỗi qua mạng không dây không khả dụng</string> <string name="main_adb_copied">Đã sao chép lệnh ADB</string> <string name="main_pick_roms">Chọn thư mục ROM</string> diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index aa46013f4a..246333f875 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -1353,8 +1353,6 @@ <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> @@ -1371,48 +1369,13 @@ <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">部分 Android 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> @@ -1694,8 +1657,6 @@ <plurals name="main_logs_cleared"> <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">选择 ROM 文件夹</string> diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 1bec44cc0a..8c7484f22d 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -1269,8 +1269,6 @@ <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> @@ -1287,48 +1285,13 @@ <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 仍會提供此開關。請在開發人員選項中尋找「子進程」。</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> @@ -1610,8 +1573,6 @@ <plurals name="main_logs_cleared"> <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">選擇 ROM 資料夾</string> diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index d484813b1e..fa10f937d0 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -1269,8 +1269,6 @@ <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">開啟「Android 設定」→「開發人員選項」→「無線偵錯」,並將其開啟</string> <string name="gate_step2">點擊「使用配對碼配對裝置」</string> <string name="gate_step3">將配對碼輸入 DroidDeck 通知中</string> @@ -1287,48 +1285,13 @@ <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 仍會提供此開關。請在開發人員選項中搜尋「子處理程序」。</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> @@ -1610,8 +1573,6 @@ <plurals name="main_logs_cleared"> <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">選擇 ROM 資料夾</string> diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index d02b7a955d..f6c126ca1e 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -35,6 +35,7 @@ <string name="wall_settings_fps" translatable="false">Frame rate (fps)</string> <string name="wall_settings_match" translatable="false">Match screen</string> <string name="wall_settings_speed" translatable="false">Scroll speed</string> + <string name="loading_first_run">First launch also downloads Proton Experimental (about 400 MB) and sets Steam up. After this it starts much faster.</string> <string-array name="loading_hints"> <item>DroidDeck downloads Steam in the background while you set up, so your first launch is quicker.</item> <item>Your controller shows up to Steam as a Steam Deck controller. Switch it to a Steam Controller, DualShock 4, DualSense or Xbox 360 pad in the session settings; it applies next session.</item> @@ -1421,13 +1422,12 @@ <string name="gate_title">One Android setting to change</string> <string name="gate_eyebrow">Steam</string> <string name="gate_lede">Android stops apps that start many background processes, and Steam starts dozens. Until this changes, games close without an error.</string> + <string name="gate_notifications_toast">The pairing code goes in a notification. Turn on notifications for DroidDeck, then try again.</string> <string name="gate_fix_for_me">Fix it for me</string> <string name="gate_toggle_steps">Turn on “Disable child process restrictions”, then come back. Leave Developer options on, or the switch turns off again.</string> <string name="gate_open_dev">Open Developer options</string> <string name="gate_no_toggle">This Android version has no switch for it, so DroidDeck changes it over Wireless debugging. Takes about a minute, no computer needed.</string> <string name="gate_needs_wifi">Wireless debugging needs Wi-Fi. Any network works; it doesn\'t need internet.</string> - <string name="gate_needs_notifications">The pairing code goes in a notification. Allow notifications for DroidDeck, or use Other ways.</string> - <string name="gate_allow_notifications">Allow notifications</string> <string name="gate_step1">Open Settings → Developer options → Wireless debugging and turn it on</string> <string name="gate_step2">Tap “Pair device with pairing code”</string> <string name="gate_step3">Type the code into the DroidDeck notification</string> @@ -1444,49 +1444,16 @@ <string name="gate_status">Status</string> <string name="gate_polling">Checking every 2 seconds. This page closes when it\'s off.</string> <string name="gate_other_ways">Other ways</string> - <string name="gate_other_toggle">Wireless debugging, manual address, computer ADB</string> - <string name="gate_other_no_toggle">Manual address, computer ADB, Developer options</string> + <string name="gate_other_toggle">Computer ADB</string> + <string name="gate_other_no_toggle">Computer ADB, Developer options</string> <string name="gate_use_wireless_instead">Use Wireless debugging instead</string> <string name="gate_some_roms">Some ROMs add the switch anyway. Look for “child process” in Developer options.</string> - <string name="gate_manual_hint">If the notification doesn\'t work, enter the pop-up\'s address and code yourself.</string> - <string name="gate_enter_manually">Enter address manually</string> <string name="gate_from_computer">From a computer with ADB:</string> <string name="gate_copy_command">Copy command</string> <string name="gate_sidequest" translatable="false">SideQuest</string> <string name="gate_sidequest_steps">Connect the headset to a computer and open SideQuest. Choose “Run ADB Command”, then “Custom Command”, type the command shown below and select “Run Command”.</string> <string name="gate_choose_display">Choose which display to open Android Settings on.</string> <string name="gate_main_screen">Main screen</string> - <string name="wadb_finding_port">Paired. Finding the Wireless debugging port…</string> - <string name="wadb_enter_port">Paired. Enter the port from Settings.</string> - <string name="wadb_applying">Device found. Applying the setting…</string> - <string name="wadb_apply_failed">Couldn\'t apply automatically. Check the address below and retry. %1$s</string> - <string name="wadb_title_wireless">Wireless debugging</string> - <string name="wadb_title_done">Child-process limit updated</string> - <string name="wadb_title">Change the child-process limit</string> - <string name="wadb_lede_compact0">If the option is missing, pair over Wireless debugging.</string> - <string name="wadb_lede_compact1">Paired. Check the IP address and port in Wireless debugging.</string> - <string name="wadb_lede_done">The child-process limit was updated.</string> - <string name="wadb_lede0">Use step 2 if Developer options has no child-process setting. Open Developer options → Wireless debugging → Pair device with pairing code.</string> - <string name="wadb_lede1">Paired. Use the address below, or update it from Wireless debugging → IP address & Port.</string> - <string name="wadb_lede_done_long">The child-process limit was updated over Wireless debugging.</string> - <string name="wadb_confirmed_on">Android confirmed the limit is on.</string> - <string name="wadb_confirmed_off">Android confirmed the limit is off.</string> - <string name="wadb_pair_group">2 · Pair Wireless debugging</string> - <string name="wadb_pair_address">Pairing pop-up IP address & port</string> - <string name="wadb_pin">Pairing code (PIN)</string> - <string name="wadb_pin_placeholder">6 digits</string> - <string name="wadb_pair">Pair</string> - <string name="wadb_apply_group">2 · Apply over Wireless debugging</string> - <string name="wadb_connect_address">Connection IP address & port</string> - <string name="wadb_pair_again">Pair again</string> - <string name="wadb_turn_off">Turn limit off</string> - <string name="wadb_other_ways">Other ways to change it</string> - <string name="wadb_dev_try_first">1 · Developer options (try first)</string> - <string name="wadb_restrict_on">Turn off “Disable child process restrictions”.</string> - <string name="wadb_restrict_off">Turn on “Disable child process restrictions”.</string> - <string name="wadb_computer_last">3 · Computer ADB (last resort)</string> - <string name="wadb_only_if">Only if Wireless debugging is unavailable.</string> - <string name="wadb_computer_group">3 · Computer ADB (last resort)</string> <string name="ctrl_color">Color</string> <string name="ctrl_custom">Custom</string> <string name="ctrl_opacity">Opacity</string> @@ -1838,8 +1805,6 @@ <item quantity="one">Cleared %1$d session log folder.</item> <item quantity="other">Cleared %1$d session log folders.</item> </plurals> - <string name="main_wadb_pair_failed">Wireless debugging pairing failed</string> - <string name="main_wadb_command_failed">Wireless debugging command failed</string> <string name="main_wadb_unavailable">Wireless debugging is unavailable</string> <string name="main_adb_copied">ADB command copied</string> <string name="main_pick_roms">Choose the ROMs folder</string> @@ -4415,6 +4380,6 @@ <string name="onboarding_steam_failed">The Steam client download will retry</string> <string name="onboarding_limit_reason">Android can close Steam’s helper processes. Turn that off now, while the downloads run, and Play is ready the moment they finish.</string> <string name="onboarding_limit_action">Do it for me</string> - <string name="onboarding_limit_while_waiting">Set up while you wait</string> - <string name="onboarding_chip">Getting ready · %1$d%% · %2$s</string> + <string name="onboarding_button_getting_ready">Getting ready · %1$d%%</string> + <string name="onboarding_button_finish">Finish setup · %1$d%%</string> </resources> diff --git a/app/src/test/java/com/droiddeck/launcher/session/OnboardingTest.kt b/app/src/test/java/com/droiddeck/launcher/session/OnboardingTest.kt index dc2b0b5e10..748b0a96e6 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/OnboardingTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/OnboardingTest.kt @@ -7,11 +7,14 @@ import com.droiddeck.launcher.session.Onboarding.Step import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue +import org.junit.Before import org.junit.Test class OnboardingTest { private val none = Facts(runtime = false, proton = false, steam = false) + @Before fun fresh() = Onboarding.resetProgress() + @Test fun everythingReadyShowsNothing() { val rows = Onboarding.rows(emptyMap(), emptyMap(), Facts()) assertFalse(Onboarding.pending(rows)) @@ -31,7 +34,33 @@ class OnboardingTest { @Test fun overallWeighsDownloadsBySize() { val rows = Onboarding.rows(mapOf(Step.RUNTIME to Progress("x", 50)), emptyMap(), Facts(runtime = false)) - assertEquals(30 + 15 + 25, Onboarding.overall(rows)) + assertEquals(10 + 30 + 50, Onboarding.overall(rows)) + } + + @Test fun overallNeverGoesBackwardsWhileStepsHandOver() { + val prefetched = Onboarding.rows(mapOf(Step.PROTON to Progress("x", 100)), emptyMap(), Facts(runtime = true, proton = false, steam = false)) + val before = Onboarding.overall(prefetched) + val handover = Onboarding.rows(mapOf(Step.STEAM to Progress("y", 4)), emptyMap(), Facts(runtime = true, proton = false, steam = false)) + assertTrue(Onboarding.overall(handover) >= before) + val installing = Onboarding.rows(mapOf(Step.PROTON to Progress("z", 0), Step.STEAM to Progress("y", 4)), emptyMap(), Facts(runtime = true, proton = false, steam = false)) + assertTrue(Onboarding.overall(installing) >= before) + } + + @Test fun overallStartsOverOnceEverythingIsReady() { + Onboarding.overall(Onboarding.rows(mapOf(Step.RUNTIME to Progress("x", 90)), emptyMap(), Facts(runtime = false))) + assertEquals(100, Onboarding.overall(Onboarding.rows(emptyMap(), emptyMap(), Facts()))) + val again = Onboarding.rows(mapOf(Step.RUNTIME to Progress("x", 10)), emptyMap(), Facts(runtime = false)) + assertEquals(2 + 30 + 50, Onboarding.overall(again)) + } + + @Test fun settlingWithEverythingReadyStartsTheNextAttemptFromZero() { + Onboarding.overall(Onboarding.rows(mapOf(Step.RUNTIME to Progress("x", 90)), emptyMap(), Facts(runtime = false))) + Onboarding.active.value = emptyMap() + Onboarding.failed.value = emptyMap() + Onboarding.facts.value = Facts() + Onboarding.settle() + val again = Onboarding.rows(mapOf(Step.RUNTIME to Progress("x", 10)), emptyMap(), Facts(runtime = false)) + assertEquals(2 + 30 + 50, Onboarding.overall(again)) } @Test fun reportingClearsAPriorFailure() { diff --git a/app/src/test/java/com/droiddeck/launcher/session/QueuedLaunchRunnerTest.kt b/app/src/test/java/com/droiddeck/launcher/session/QueuedLaunchRunnerTest.kt new file mode 100644 index 0000000000..d5f851a7f4 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/QueuedLaunchRunnerTest.kt @@ -0,0 +1,116 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class QueuedLaunchRunnerTest { + private class Clock { + var now = 0L + private class Task(val at: Long, val run: Runnable) + private val tasks = mutableListOf<Task>() + fun schedule(delay: Long, run: Runnable) { tasks += Task(now + delay, run) } + fun cancel(run: Runnable) { tasks.removeAll { it.run === run } } + /** Moves time forward and runs what is due, as the main thread would. */ + fun advance(ms: Long) { + val end = now + ms + while (true) { + val next = tasks.filter { it.at <= end }.minByOrNull { it.at } ?: break + tasks.remove(next) + now = maxOf(now, next.at) + next.run.run() + } + now = end + } + } + + private class Owner(clock: Clock, queue: QueuedLaunch<String>, val state: State) { + class State { var blocked = true; var busy = false } + val started = mutableListOf<String>() + val runner = QueuedLaunchRunner( + queue = queue, now = { clock.now }, blocked = { state.blocked }, busy = { state.busy }, + schedule = clock::schedule, unschedule = clock::cancel, start = { started += it }, retryMs = 2_000, + ) + } + + private val minute = 60_000L + + @Test fun aLaunchWaitsWhileTheSettingBlocksItAndStartsOnceItDoesNot() { + val clock = Clock() + val owner = Owner(clock, QueuedLaunch<String>(15 * minute).also { it.queue("steam", 0) }, Owner.State()) + owner.runner.poke() + clock.advance(5_000) + assertEquals(emptyList<String>(), owner.started) + owner.state.blocked = false + owner.runner.poke() + clock.advance(1) + assertEquals(listOf("steam"), owner.started) + } + + @Test fun aBusyRuntimeIsRetriedEveryTwoSecondsUntilItIsFree() { + val clock = Clock() + val state = Owner.State().apply { blocked = false; busy = true } + val owner = Owner(clock, QueuedLaunch<String>(15 * minute).also { it.queue("steam", 0) }, state) + owner.runner.poke() + clock.advance(7_000) + assertEquals(emptyList<String>(), owner.started) + state.busy = false + clock.advance(2_001) + assertEquals(listOf("steam"), owner.started) + clock.advance(10_000) + assertEquals(listOf("steam"), owner.started) + } + + @Test fun aLaunchThatWaitsPastItsLifetimeIsNeverStarted() { + val clock = Clock() + val state = Owner.State().apply { blocked = false; busy = true } + val owner = Owner(clock, QueuedLaunch<String>(15 * minute).also { it.queue("steam", 0) }, state) + owner.runner.poke() + clock.advance(16 * minute) + state.busy = false + clock.advance(10_000) + assertEquals(emptyList<String>(), owner.started) + } + + @Test fun onlyTheRestoredOwnerStartsAfterTheFirstOneIsDestroyedMidRetry() { + val clock = Clock() + val state = Owner.State().apply { blocked = false; busy = true } + val firstQueue = QueuedLaunch<String>(15 * minute).also { it.queue("steam", 0) } + val first = Owner(clock, firstQueue, state) + first.runner.poke() + clock.advance(3_000) + + val saved = firstQueue.launch + val savedAt = firstQueue.queuedAt + first.runner.destroy() + val secondQueue = QueuedLaunch<String>(15 * minute).also { it.restore(saved, savedAt, clock.now) } + val second = Owner(clock, secondQueue, state) + second.runner.poke() + + state.busy = false + clock.advance(10_000) + assertEquals(emptyList<String>(), first.started) + assertEquals(listOf("steam"), second.started) + assertNull(firstQueue.launch) + } + + @Test fun aDestroyedOwnerNeverStartsEvenIfItsRetryWasAlreadyDue() { + val clock = Clock() + val state = Owner.State().apply { blocked = false } + val owner = Owner(clock, QueuedLaunch<String>(15 * minute).also { it.queue("steam", 0) }, state) + owner.runner.poke() + owner.runner.destroy() + clock.advance(10_000) + assertEquals(emptyList<String>(), owner.started) + } + + @Test fun pokingTwiceBeforeTheFirstAttemptStartsTheLaunchOnce() { + val clock = Clock() + val state = Owner.State().apply { blocked = false } + val owner = Owner(clock, QueuedLaunch<String>(15 * minute).also { it.queue("steam", 0) }, state) + owner.runner.poke() + owner.runner.poke() + clock.advance(1) + assertEquals(listOf("steam"), owner.started) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/QueuedLaunchTest.kt b/app/src/test/java/com/droiddeck/launcher/session/QueuedLaunchTest.kt new file mode 100644 index 0000000000..60fbb430eb --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/QueuedLaunchTest.kt @@ -0,0 +1,49 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Test + +class QueuedLaunchTest { + private val minute = 60_000L + + @Test fun aQueuedLaunchIsWantedUntilItsLifetimeEnds() { + val queue = QueuedLaunch<String>(15 * minute) + queue.queue("steam", now = 100) + assertEquals("steam", queue.current(100 + 14 * minute)) + assertNull(queue.current(100 + 16 * minute)) + assertNull(queue.launch) + } + + @Test fun aRestoredLaunchKeepsTheTimeItWasQueued() { + val queue = QueuedLaunch<String>(15 * minute) + queue.restore("steam", queuedAt = 0, now = 14 * minute) + assertEquals("steam", queue.current(14 * minute)) + assertEquals(0L, queue.queuedAt) + assertNull(queue.current(16 * minute)) + } + + @Test fun aLaunchRestoredAfterItsLifetimeIsDropped() { + val queue = QueuedLaunch<String>(15 * minute) + queue.restore("steam", queuedAt = 0, now = 20 * minute) + assertNull(queue.launch) + } + + @Test fun aLaunchRestoredWithoutAValidTimeIsDropped() { + val queue = QueuedLaunch<String>(15 * minute) + queue.restore("steam", queuedAt = 0, now = -1) + assertNull(queue.launch) + queue.restore(null, queuedAt = 5, now = 10) + assertNull(queue.launch) + } + + @Test fun clearingForgetsTheLaunchSoAnOldCallbackDoesNotMatchIt() { + val queue = QueuedLaunch<Any>(15 * minute) + val launch = Any() + queue.queue(launch, now = 0) + assertSame(launch, queue.current(1)) + queue.clear() + assertNull(queue.current(1)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt index 2811284d0e..a64e56383f 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt @@ -298,7 +298,7 @@ class CurseLinkTabTest { onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, ) diff --git a/app/src/test/java/com/droiddeck/launcher/ui/DesktopUninstallTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/DesktopUninstallTest.kt index 3f76cac3ba..641de899ac 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/DesktopUninstallTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/DesktopUninstallTest.kt @@ -87,7 +87,7 @@ class DesktopUninstallTest { onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, onRemoveDesktop = { removals++ }, ), Modifier.fillMaxSize(), onSelect = {}) StepsLayer(Offset.Zero) diff --git a/app/src/test/java/com/droiddeck/launcher/ui/FlathubFocusTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/FlathubFocusTest.kt index a268c46a80..b685aac7ec 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/FlathubFocusTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/FlathubFocusTest.kt @@ -67,7 +67,7 @@ class FlathubFocusTest { onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, )) } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/GamesClientTagTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/GamesClientTagTest.kt index a86bf350f8..97d1d95094 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/GamesClientTagTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/GamesClientTagTest.kt @@ -58,7 +58,7 @@ class GamesClientTagTest { onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, ), selected = "games", onSelect = {}, modifier = Modifier.fillMaxSize()) } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/GlobalGlassesSettingsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/GlobalGlassesSettingsTest.kt index 62c90ce94a..aadb56e753 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/GlobalGlassesSettingsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/GlobalGlassesSettingsTest.kt @@ -142,7 +142,7 @@ class GlobalGlassesSettingsTest { onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, ), onOpenDeveloperOptions = {}, onRequestWirelessAdb = {}, onPairWirelessDebugging = {}) } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/InputUiLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/InputUiLayoutTest.kt index 9f28c9ccc1..508e2ed4b6 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/InputUiLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputUiLayoutTest.kt @@ -100,7 +100,7 @@ class InputUiLayoutTest { onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, controller = ControllerActions({}), ), onOpenDeveloperOptions = {}, onRequestWirelessAdb = {}, onPairWirelessDebugging = {}) } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LaunchSettingsComponentsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LaunchSettingsComponentsTest.kt index 37544588f3..65eef5d38f 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/LaunchSettingsComponentsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/LaunchSettingsComponentsTest.kt @@ -66,7 +66,7 @@ class LaunchSettingsComponentsTest { onImportLossless = {}, onProtons = {}, onComponents = { defaultOpens++ }, onGameComponents = { openedGame = it }, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, ), rememberMenuHost(), diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt index 2630a3314d..4123ac826c 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt @@ -230,7 +230,7 @@ class LibraryVisibilityTest { onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, ) } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt index 84bdf7ad49..b919b8688a 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt @@ -262,7 +262,7 @@ class NavTabsTest { onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, onRemoveDesktop = {}, ) } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/NavigationSelectionTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/NavigationSelectionTest.kt index 5332c83ab0..004fe8cd64 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/NavigationSelectionTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/NavigationSelectionTest.kt @@ -94,7 +94,7 @@ class NavigationSelectionTest { onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, ) } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/PortraitLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/PortraitLayoutTest.kt index 1f6a4b7073..f5988c0b80 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/PortraitLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/PortraitLayoutTest.kt @@ -152,7 +152,7 @@ class PortraitLayoutTest { onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, ) } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SteamHomeHeadsetTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SteamHomeHeadsetTest.kt index 14aed407ea..f4c4688f4a 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SteamHomeHeadsetTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SteamHomeHeadsetTest.kt @@ -101,7 +101,7 @@ class SteamHomeHeadsetTest { onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, ), Modifier.fillMaxSize()) } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/StoreRestorationTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/StoreRestorationTest.kt index 1f214aba0c..97f5c16ae9 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/StoreRestorationTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/StoreRestorationTest.kt @@ -145,7 +145,7 @@ class StoreRestorationTest { onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, ) } diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install index 642cc7a836..7da018df54 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install @@ -132,6 +132,138 @@ fetch() { done } +# The same decisions as fetch for the parallel workers, with curl in the foreground and a plain sleep between tries: +# the shell here cannot open /dev/fd for process substitution from a background job. +fetch_one() { + local url=$1 dest=$2 size=$3 sum=$4 part=$5 failures=0 bad=0 finished=0 before rc http wait + while :; do + if [ -f "$dest" ] && { [ "$finished" = 1 ] || { [ "$size" -gt 0 ] && [ "$(size_of "$dest")" -ge "$size" ]; }; }; then + echo "$sum $dest" | sha256sum -c --quiet 2>/dev/null && return 0 + rm -f "$dest" + finished=0 bad=$((bad + 1)) + [ "$bad" -lt 3 ] || { echo "droiddeck-steam-install: $part does not match its checksum" >&2; return 1; } + fi + before=$(size_of "$dest") + http=$(curl -fsSL "${limits[@]}" -w '%{http_code}' -C - -o "$dest" "$url") && rc=0 || rc=$? + if [ "$rc" = 0 ]; then finished=1; continue; fi + case "$rc:${http:-}" in + 22:416 | 33:*) rm -f "$dest" ;; + 22:4??) + echo "droiddeck-steam-install: $part: HTTP $http from ${url%/*}" >&2 + return 1 + ;; + esac + if [ "$(size_of "$dest")" -gt "$before" ]; then failures=0; else failures=$((failures + 1)); fi + if [ "$failures" -gt "${#delays[@]}" ]; then + echo "droiddeck-steam-install: could not download $part (curl exit $rc); what arrived is kept for the next try" >&2 + return 1 + fi + wait=${delays[$((failures > 0 ? failures - 1 : 0))]} + step "downloading Steam: $part - interrupted (curl exit $rc), trying again in ${wait} s" + sleep "$wait" + done +} + +parallel=${DD_STEAM_PARALLEL:-4} +case $parallel in ''|*[!0-9]*|0) parallel=1 ;; esac +flock_command=${DD_STEAM_FLOCK:-flock} +command -v "$flock_command" > /dev/null 2>&1 || parallel=1 + +# unzip creates parent directories without guarding against another unzip doing the same, so two packages unpacked into +# one tree at once fail now and then. Unpacking is quick next to downloading, so the workers take turns on a flock: the +# kernel hands it on when its holder ends, however it ends, so there is no stale lock to recover. +unzip_alone() { + local rc + ( "$flock_command" 9 && unzip -qo "$1" -d "$steam_root" ) 9> "$state/unzip.lock" && rc=0 || rc=$? + return $rc +} + +# Fetches every line of a list ("block file sum size") into $dir with up to $parallel connections. With a third +# argument each package is also unpacked into the client as it lands. One connection tops out near half of what a +# Wi-Fi link carries, so the packages arrive about twice as fast. Workers take the next unclaimed line themselves +# (mkdir is atomic) and only plain background jobs and wait on a pid are used, so nothing depends on job control. +run_parallel() { + local list=$1 dir=$2 unpack=${3:-} state index=0 block file sum size + local -a blocks=() files=() sums=() sizes=() pids=() + state=$work/parallel + rm -rf "$state" + mkdir -p "$state" + while read -r block file sum size; do + index=$((index + 1)) + blocks[index]=$block files[index]=$file sums[index]=$sum sizes[index]=$size + if [ -n "$unpack" ] && [ -f "$dir/$file.unpacked" ]; then + : > "$state/$index.done" + : > "$state/claim.$index" + fi + done < "$list" + local count=$index total_bytes=0 + for index in $(seq 1 "$count"); do total_bytes=$((total_bytes + sizes[index])); done + local slot + for slot in $(seq 1 "$parallel"); do + ( + trap ': > "$state/exit.$slot"' EXIT + while [ ! -e "$state/failed" ]; do + index=0 + for n in $(seq 1 "$count"); do + if mkdir "$state/claim.$n" 2>/dev/null; then index=$n; break; fi + done + [ "$index" -gt 0 ] || exit 0 + file=${files[index]} + fetched="" + for host in "${cdn_order[@]}"; do + if fetch_one "$host/$file" "$dir/$file" "${sizes[index]}" "${sums[index]}" "${blocks[index]}"; then + fetched=$host + break + fi + done + if [ -z "$fetched" ]; then + echo "droiddeck-steam-install: $file failed on every CDN" >&2 + : > "$state/failed" + exit 1 + fi + if [ -n "$unpack" ]; then + unzip_alone "$dir/$file" || { : > "$state/failed"; exit 1; } + : > "$dir/$file.unpacked" + rm -f "$dir/$file" + fi + : > "$state/$index.done" + done + ) & + pids+=($!) + done + local shown="" got n alive mark current last="" since=$SECONDS stall=${DD_STEAM_STALL:-90} + while :; do + alive=0 + for slot in $(seq 1 "$parallel"); do [ -e "$state/exit.$slot" ] || alive=1; done + got=0 n=0 current="" + for index in $(seq 1 "$count"); do + if [ -e "$state/$index.done" ]; then + got=$((got + sizes[index])) n=$((n + 1)) + elif [ -e "$state/claim.$index" ]; then + current=$index + [ -f "$dir/${files[index]}" ] && got=$((got + $(size_of "$dir/${files[index]}"))) + fi + done + mark=$((got / 1000000)) + if [ -n "$current" ] && [ "$mark" != "$shown" ]; then + shown=$mark + step "downloading Steam: ${blocks[current]} ($((n + 1))/$count), $mark of $((total_bytes / 1000000)) MB" + fi + [ "$n" -lt "$count" ] || alive=0 + if [ "$got" != "$last" ]; then last=$got since=$SECONDS; fi + # A worker killed from outside never writes its exit marker. Stop reporting once nothing has moved for a while + # and wait on the workers: wait returns the killed one's status, so the install fails instead of hanging. + [ $((SECONDS - since)) -lt "$stall" ] || alive=0 + [ "$alive" = 1 ] || break + sleep 1 + done + local failed="" + for slot in "${pids[@]}"; do wait "$slot" || failed=1; done + [ ! -e "$state/failed" ] || failed=1 + rm -rf "$state" + [ -z "$failed" ] +} + fetch_manifest() { cdn="" for candidate in $cdn_list; do @@ -193,6 +325,9 @@ if [ -n "$cache_only" ]; then total_bytes=$(awk '{ n += $4 } END { print n + 0 }' "$work/cache") done_bytes=0 i=0 + if [ "$parallel" -gt 1 ]; then + run_parallel "$work/cache" "$cache" || exit 1 + else while read -r block file sum size; do i=$((i + 1)) progress "$cache/$file" "$block" @@ -206,6 +341,7 @@ if [ -n "$cache_only" ]; then [ -n "$fetched" ] || { echo "droiddeck-steam-install: $file failed on every CDN" >&2; exit 1; } done_bytes=$((done_bytes + size)) done < "$work/cache" + fi echo "$version" > "$cached" exit 0 fi @@ -228,6 +364,9 @@ for left in "$parts"/*; do grep -qF " $name " "$work/parts" || rm -rf "$left" done done_bytes=0 +if [ "$parallel" -gt 1 ]; then + run_parallel "$work/parts" "$parts" unpack || exit 1 +else while read -r block file sum size; do i=$((${i:-0} + 1)) if [ -f "$parts/$file.unpacked" ]; then @@ -248,6 +387,7 @@ while read -r block file sum size; do rm -f "$parts/$file" done_bytes=$((done_bytes + size)) done < "$work/parts" +fi find "$steam_root" -depth -name '*\\*' | while read -r odd; do fixed=${odd//\\//} mkdir -p "$(dirname "$fixed")" diff --git a/tools/tests/test_steam_install.py b/tools/tests/test_steam_install.py index 4af6d09dd1..2a74968c00 100644 --- a/tools/tests/test_steam_install.py +++ b/tools/tests/test_steam_install.py @@ -2,8 +2,10 @@ import hashlib import os from pathlib import Path import shutil +import signal import subprocess import tempfile +import time import unittest import zipfile @@ -12,6 +14,8 @@ SCRIPT = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/dr class SteamInstallTest(unittest.TestCase): + parallel = '1' + def setUp(self): self.temp = tempfile.TemporaryDirectory() self.addCleanup(self.temp.cleanup) @@ -47,19 +51,29 @@ if host_fail and host_fail in url: action = [] plan = os.environ.get('TEST_PLAN') if plan and os.path.exists(plan): - lines = open(plan).read().splitlines() - for n, line in enumerate(lines): - if line.split()[0] == name: - action = line.split()[1:] - del lines[n] - open(plan, 'w').write(''.join(l + '\\n' for l in lines)) - break + import fcntl + with open(plan + '.lock', 'w') as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + lines = open(plan).read().splitlines() + for n, line in enumerate(lines): + if line.split()[0] == name: + action = line.split()[1:] + del lines[n] + open(plan, 'w').write(''.join(l + '\\n' for l in lines)) + break if action[:1] == ['fail']: done(int(action[1]), '000') if action[:1] == ['http']: done(22, action[1]) +if action[:1] == ['killworker']: + import signal + os.kill(os.getppid(), signal.SIGKILL) + import time + time.sleep(6) if action[:1] == ['norange'] and offset: done(33) +import time +time.sleep(float(os.environ.get('TEST_SLEEP', '0'))) data = open(os.path.join(os.environ['TEST_CDN'], name), 'rb').read() end = int(action[1]) if action[:1] == ['cut'] else len(data) with open(out, 'ab' if offset else 'wb') as target: @@ -79,7 +93,8 @@ done(28 if end < len(data) else 0) self.env = dict(os.environ, HOME=str(self.home), XDG_DATA_HOME=str(self.data), PATH=str(self.bin) + os.pathsep + os.environ['PATH'], TEST_CDN=str(self.cdn), TEST_REQUESTS=str(self.requests), - TEST_PLAN=str(self.plan), DD_STEAM_RETRY_DELAYS='0 0 0') + TEST_PLAN=str(self.plan), DD_STEAM_RETRY_DELAYS='0 0 0', + DD_STEAM_PARALLEL=self.parallel) for channel in ('steamdeck_publicbeta', 'steamdeck_stable'): archive = self.cdn / (channel + '.zip') with zipfile.ZipFile(archive, 'w') as package: @@ -92,9 +107,13 @@ done(28 if end < len(data) else 0) f'\t\t"file" "{archive.name}"\n\t\t"sha2" "{digest}"\n' '\t}\n}\n') - def install(self, fail_host=None, *args, **extra): + def install(self, fail_host=None, *args, timeout=None, **extra): env = self.env if fail_host is None else dict(self.env, TEST_FAIL_HOST=fail_host) - return subprocess.run(['bash', str(SCRIPT), *args], env=dict(env, **extra), text=True, capture_output=True) + try: + return subprocess.run(['bash', str(SCRIPT), *args], env=dict(env, **extra), text=True, capture_output=True, + timeout=timeout) + except subprocess.TimeoutExpired: + self.fail(f'the installer did not finish within {timeout} s') def channel(self, **extra): result = self.install(None, '--channel', **extra) @@ -455,5 +474,165 @@ done(28 if end < len(data) else 0) self.assertFalse(self.download.exists()) +class SteamInstallParallelTest(SteamInstallTest): + """The same behaviour with several connections at once.""" + parallel = '4' + test_progress_is_counted_in_megabytes_across_parts = None + + def many_parts(self, count=10): + return self.publish(**{f'p{i}_all': 300_000 for i in range(count)}) + + def test_many_parts_arrive_and_unpack_together(self): + self.many_parts() + result = self.install() + self.assertEqual(0, result.returncode, result.stderr) + for i in range(10): + self.assertTrue((self.steam / f'parts/p{i}_all').is_file(), i) + self.assertEqual('123456\n', (self.steam / 'package/droiddeck-installed').read_text()) + self.assertFalse(self.download.exists()) + + def test_every_part_is_requested_once_when_several_arrive_together(self): + files = self.many_parts() + self.assertEqual(0, self.install().returncode) + requested = self.requested() + for name in files.values(): + self.assertEqual(1, requested.count(name), name) + + def test_one_part_that_no_cdn_has_fails_the_install_and_leaves_no_ready_marker(self): + files = self.many_parts() + missing = files['p4_all'] + self.plan_for(missing, 'http 404', 'http 404', 'http 404') + result = self.install() + self.assertNotEqual(0, result.returncode) + self.assertFalse((self.steam / 'package/droiddeck-installed').exists()) + self.assertIn('failed on every CDN', result.stderr) + + def test_a_retry_after_a_failure_finishes_what_is_left(self): + files = self.many_parts() + self.plan_for(files['p4_all'], 'http 404', 'http 404', 'http 404') + self.assertNotEqual(0, self.install().returncode) + self.assertEqual(0, self.install().returncode) + self.assertTrue((self.steam / 'parts/p4_all').is_file()) + self.assertEqual('123456\n', (self.steam / 'package/droiddeck-installed').read_text()) + + def test_progress_is_reported_while_several_parts_arrive(self): + self.many_parts() + result = self.install(TEST_SLEEP='1.2', **{}) + self.assertEqual(0, result.returncode, result.stderr) + lines = [line for line in result.stdout.splitlines() if 'downloading Steam:' in line and ' of ' in line] + self.assertGreaterEqual(len(lines), 2, result.stdout) + self.assertIn(' MB', lines[-1]) + + def test_packages_are_unpacked_one_at_a_time(self): + source = SCRIPT.read_text() + region = source[source.index('run_parallel() {'):source.index('fetch_manifest() {')] + self.assertNotIn('unzip -qo', region) + self.assertIn('unzip_alone', region) + self.assertIn('"$flock_command" 9', source) + + def unzip_alone_script(self): + source = SCRIPT.read_text() + start = source.index('unzip_alone() {') + function = source[start:source.index('\n}\n', start) + 3] + return 'state=$1\nsteam_root=$2\nflock_command=flock\n' + function + '\nunzip_alone "$3"\n' + + def unzip_alone_archive(self, name='one.zip', entry='steamrtarm64/steam'): + archive = self.root / name + with zipfile.ZipFile(archive, 'w') as package: + package.writestr(entry, 'client') + self.steam.mkdir(parents=True, exist_ok=True) + (self.root / 'state').mkdir(exist_ok=True) + return archive + + def run_unzip_alone(self, archive, timeout, env=None): + arguments = ['bash', '-c', self.unzip_alone_script(), 'bash', str(self.root / 'state'), str(self.steam), str(archive)] + try: + return subprocess.run(arguments, text=True, capture_output=True, timeout=timeout, env=env) + except subprocess.TimeoutExpired: + return None + + def hold_the_lock(self): + """Starts a process that holds the unzip lock and returns once it says it has it.""" + ready = self.root / 'holder-ready' + holder = subprocess.Popen( + ['flock', str(self.root / 'state/unzip.lock'), 'sh', '-c', f'touch {ready}; sleep 60'], start_new_session=True) + self.addCleanup(lambda: os.killpg(holder.pid, signal.SIGKILL) if holder.poll() is None else None) + deadline = time.monotonic() + 10 + while not ready.exists(): + self.assertLess(time.monotonic(), deadline, 'the holder never took the lock') + time.sleep(0.05) + return holder + + @unittest.skipUnless(shutil.which('flock'), 'needs flock') + def test_a_package_waits_for_a_worker_that_is_unpacking(self): + archive = self.unzip_alone_archive() + self.hold_the_lock() + self.assertIsNone(self.run_unzip_alone(archive, timeout=4), 'unzip_alone did not wait for the holder') + self.assertFalse((self.steam / 'steamrtarm64/steam').exists()) + + @unittest.skipUnless(shutil.which('flock'), 'needs flock') + def test_a_worker_killed_while_unpacking_hands_the_lock_on(self): + archive = self.unzip_alone_archive() + holder = self.hold_the_lock() + os.killpg(holder.pid, signal.SIGKILL) + holder.wait() + result = self.run_unzip_alone(archive, timeout=20) + self.assertIsNotNone(result, 'the lock of a killed worker was never handed on') + self.assertEqual(0, result.returncode, result.stderr) + self.assertTrue((self.steam / 'steamrtarm64/steam').is_file()) + + @unittest.skipUnless(shutil.which('flock'), 'needs flock') + def test_several_workers_never_unpack_at_the_same_moment(self): + log = self.root / 'unzip.log' + fake = self.bin / 'unzip' + fake.write_text('''#!/usr/bin/env python3 +import os, sys, time +log = os.environ['TEST_UNZIP_LOG'] +with open(log, 'a') as out: + out.write(f'start {os.getpid()}\\n') +time.sleep(0.3) +with open(log, 'a') as out: + out.write(f'end {os.getpid()}\\n') +''') + fake.chmod(0o755) + archive = self.unzip_alone_archive() + env = dict(self.env, TEST_UNZIP_LOG=str(log)) + arguments = ['bash', '-c', self.unzip_alone_script(), 'bash', str(self.root / 'state'), str(self.steam), str(archive)] + workers = [subprocess.Popen(arguments, env=env) for _ in range(8)] + for worker in workers: + self.assertEqual(0, worker.wait(timeout=60)) + lines = log.read_text().split() + events = lines[0::2] + self.assertEqual(['start', 'end'] * 8, events, 'two workers unpacked at the same time') + + def test_without_flock_the_downloads_go_one_at_a_time(self): + self.two_parts() + result = self.install(DD_STEAM_FLOCK='flock-that-is-not-installed') + self.assertEqual(0, result.returncode, result.stderr) + # Only the sequential path counts parts as (1/2) and (2/2). + self.assertIn('downloading Steam: a_all (1/2), 0 of 2 MB\n', result.stdout) + self.assertIn('downloading Steam: client_linuxarm64_linuxarm64 (2/2), 1 of 2 MB\n', result.stdout) + + def test_the_parallel_workers_use_no_process_substitution(self): + source = SCRIPT.read_text() + region = source[source.index('fetch_one() {'):source.index('fetch_manifest() {')] + self.assertNotIn('<(', region) + reporter = source[source.index('run_parallel() {'):source.index('fetch_manifest() {')] + self.assertNotIn('kill -0', reporter) + + def test_a_worker_killed_from_outside_fails_the_install_instead_of_hanging_it(self): + files = self.many_parts() + self.plan_for(files['p3_all'], 'killworker') + result = self.install(timeout=40, DD_STEAM_STALL='3') + self.assertNotEqual(0, result.returncode) + self.assertFalse((self.steam / 'package/droiddeck-installed').exists()) + + def test_the_cache_pass_with_several_connections_keeps_every_package(self): + self.cache_manifest() + result = self.install(None, '--cache') + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual('123456\n', (self.steam / 'package/droiddeck-cached').read_text()) + + if __name__ == '__main__': unittest.main() From cf44aaed145327b0bfd94b10bd33c0d511a82656 Mon Sep 17 00:00:00 2001 From: The412Banner <205237651+The412Banner@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:37:09 -0500 Subject: [PATCH 100/141] fix(appimage): catalog AppImages start without proot (#3077) * fix(appimage): catalog AppImages start without proot * fix(appimage): cache cleanup does not follow symlinked entries * fix(appimage): keep unpacked copies in use and track subsecond changes * fix(appimage): extract native images through an open descriptor --------- Co-authored-by: maxjivi05 <maxjividen@gmail.com> --- .../usr/local/bin/droiddeck-appimage-exec | 34 +++++ .../overlay/usr/local/bin/droiddeck-fex | 20 ++- tools/tests/test_droiddeck_fex.py | 67 +++++++++ tools/tests/test_session_appimage.py | 130 +++++++++++++++++- 4 files changed, 246 insertions(+), 5 deletions(-) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-appimage-exec b/tools/linuxfs/overlay/usr/local/bin/droiddeck-appimage-exec index 454333efa9..5bcbacbdd8 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-appimage-exec +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-appimage-exec @@ -9,6 +9,40 @@ if [ -x /usr/local/bin/droiddeck-fex ]; then 3|62) exec /usr/local/bin/droiddeck-fex run --mode on -- "$image" "$@" ;; esac fi +if [ -n "${DDNATV_ROOT:-}" ]; then + image=$(realpath -- "$image") || exit 127 + cache=${XDG_CACHE_HOME:-${HOME:-/root}/.cache}/droiddeck-appimage + mkdir -p "$cache" || exit 1 + exec 9>"$cache/.lock" + flock 9 || exit 1 + state() { printf '%s\n%s' "$1" "$(TZ=UTC0 stat -Lc '%s %y' -- "$1" 2>/dev/null)"; } + for dir in "$cache"/*/; do + dir=${dir%/} + [ ! -L "$dir" ] && [ -f "$dir/source" ] || continue + [ "$(cat "$dir/source")" = "$(state "$(head -n 1 "$dir/source")")" ] && continue + (flock -n 7 && rm -rf -- "${dir:?}") 7<"$dir/source" + done + find "$cache" -mindepth 1 -maxdepth 1 -name '.unpack.*' -mmin +60 -exec rm -rf -- {} + 2>/dev/null + source=$(state "$image") + unpacked=$cache/$(printf '%s' "$source" | md5sum | cut -c1-16) + if [ "$(cat "$unpacked/source" 2>/dev/null)" != "$source" ] || [ ! -e "$unpacked/squashfs-root/AppRun" ]; then + echo "== appimage: unpacking $image" + work=$(mktemp -d "$cache/.unpack.XXXXXX") || exit 1 + if ! (cd "$work" && /usr/local/bin/droiddeck-fex extract "$image") || [ ! -e "$work/squashfs-root/AppRun" ]; then + rm -rf -- "${work:?}" + echo "droiddeck-appimage-exec: could not unpack $image" >&2 + exit 1 + fi + printf '%s\n' "$source" > "$work/source" + rm -rf -- "${unpacked:?}" + mv -- "$work" "$unpacked" || exit 1 + fi + exec 8<"$unpacked/source" + flock -s 8 || exit 1 + exec 9>&- + export APPIMAGE=$image APPDIR=$unpacked/squashfs-root ARGV0=$image OWD=$PWD + exec "$APPDIR/AppRun" "$@" +fi if [ -x /usr/local/lib/droiddeck/uruntime ]; then export TARGET_APPIMAGE=$image exec /usr/local/lib/droiddeck/uruntime "$@" diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex index 7c1dd3176f..a25b755cee 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex @@ -851,8 +851,12 @@ def extract(image): clear_extracted() x86 = elf_arch(image) in X86.values() if os.access(URUNTIME, os.X_OK): - run = subprocess.run([URUNTIME, "--appimage-extract"], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, - env=dict(os.environ, TARGET_APPIMAGE=image)) + with open(image, "rb") as source: + native = bool(os.environ.get("DDNATV_ROOT")) + target = "/proc/self/fd/%d" % source.fileno() if native else image + run = subprocess.run([URUNTIME, "--appimage-extract"], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, + env=dict(os.environ, TARGET_APPIMAGE=target), + pass_fds=(source.fileno(),) if native else ()) errors = run.stderr.decode("utf-8", "replace") sys.stderr.write(errors) status = run.returncode @@ -882,7 +886,17 @@ def extract(image): want_fex() return 0 say("unsquashfs could not extract it (status %d)" % status) - elif fex is None: + seven = shutil.which("7z") + if seven: + clear_extracted() + status = subprocess.call([seven, "x", "-tSquashFS", "-y", "-osquashfs-root", image], stdout=subprocess.DEVNULL) + if status == 0 and extracted(): + if x86: + want_fex() + return 0 + say("7-Zip could not extract it (status %d)" % status) + clear_extracted() + elif fex is None and not unsquashfs: say("this AppImage could not be unpacked here: no AppImage runtime for ARM64, no FEX yet and no unsquashfs") return 1 diff --git a/tools/tests/test_droiddeck_fex.py b/tools/tests/test_droiddeck_fex.py index ce474de509..993d668d95 100644 --- a/tools/tests/test_droiddeck_fex.py +++ b/tools/tests/test_droiddeck_fex.py @@ -1023,6 +1023,73 @@ class ExtractTest(FexTestCase): self.assertIn("-no-xattrs", commands[-1]) self.assertTrue(Path("squashfs-root/AppRun").is_file()) + def seven_zip(self, tool, which, works=True): + commands = [] + + def call(argv, **kwargs): + commands.append(argv) + if argv[0] != "/usr/bin/7z" or not works: + return 2 + (self.work / "squashfs-root").mkdir() + (self.work / "squashfs-root/AppRun").touch() + return 0 + + with mock.patch.dict(G, { + "URUNTIME": tool, + "prepare": lambda: None, + "fex_install": lambda: None, + "steam_running": lambda: False, + "want_fex": lambda: None, + }), mock.patch("shutil.which", side_effect=lambda name: which.get(name)), \ + mock.patch("subprocess.call", side_effect=call): + status, said = self.quiet(FEX["extract"], "image.AppImage") + return status, said, commands + + def test_without_proot_the_shipped_runtime_reads_the_open_image(self): + self.write(self.image, elf(183) + b"payload", 0o755) + tool = self.uruntime('cmp "$TARGET_APPIMAGE" "%s" || exit 9\nmkdir -p AppDir && touch AppDir/AppRun\n' % self.image) + with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(self.tmp / "rootfs")}): + status, said, commands = self.seven_zip(tool, {"7z": "/usr/bin/7z"}) + self.assertEqual((status, said), (0, "")) + self.assertEqual([], commands) + self.assertTrue(Path("squashfs-root/AppRun").is_file()) + + def test_without_proot_runtime_failure_falls_back_to_7zip(self): + self.write(self.image, elf(183) + b"payload", 0o755) + tool = self.uruntime("exit 1\n") + with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(self.tmp / "rootfs")}): + status, said, commands = self.seven_zip(tool, {"7z": "/usr/bin/7z"}) + self.assertEqual(status, 0) + self.assertIn("uruntime could not extract it (status 1)", said) + self.assertEqual("/usr/bin/7z", commands[-1][0]) + self.assertTrue(Path("squashfs-root/AppRun").is_file()) + + def test_with_proot_the_shipped_runtime_is_still_tried_first(self): + ran = self.tmp / "uruntime-ran" + tool = self.uruntime("touch %s\nexit 1\n" % ran) + env = {k: v for k, v in os.environ.items() if k != "DDNATV_ROOT"} + with mock.patch.dict(os.environ, env, clear=True): + status, said, commands = self.seven_zip(tool, {"7z": "/usr/bin/7z"}) + self.assertEqual(status, 0) + self.assertTrue(ran.exists()) + self.assertIn("uruntime could not extract it (status 1)", said) + self.assertEqual("/usr/bin/7z", commands[-1][0]) + + def test_unsquashfs_is_preferred_over_7zip(self): + tool = self.uruntime("exit 1\n") + status, said, commands = self.seven_zip(tool, {"unsquashfs": "/usr/bin/unsquashfs", "7z": "/usr/bin/7z"}) + self.assertEqual(status, 0) + self.assertIn("unsquashfs could not extract it (status 2)", said) + self.assertEqual(["/usr/bin/unsquashfs", "/usr/bin/7z"], [c[0] for c in commands]) + + def test_a_7zip_failure_leaves_nothing_unpacked(self): + tool = self.uruntime("exit 1\n") + status, said, _ = self.seven_zip(tool, {"7z": "/usr/bin/7z"}, works=False) + self.assertEqual(status, 1) + self.assertIn("7-Zip could not extract it (status 2)", said) + self.assertNotIn("no unsquashfs", said) + self.assertFalse(os.path.lexists("squashfs-root")) + class LaunchTest(FexTestCase): def test_the_guest_environment(self): diff --git a/tools/tests/test_session_appimage.py b/tools/tests/test_session_appimage.py index 3fc5352427..295e73da3b 100644 --- a/tools/tests/test_session_appimage.py +++ b/tools/tests/test_session_appimage.py @@ -1,3 +1,4 @@ +import fcntl import os import re import shutil @@ -37,13 +38,28 @@ class AppImageExecTest(unittest.TestCase): path.chmod(0o755) return path - def launch(self): + def launch(self, **extra): script = self.dir / "exec" script.write_text(EXEC.read_text().replace(URUNTIME, str(self.uruntime)).replace(FEX, str(self.fex))) - env = {k: v for k, v in os.environ.items() if k not in ("TARGET_APPIMAGE", "APPIMAGE_EXTRACT_AND_RUN")} + env = {k: v for k, v in os.environ.items() if k not in ("TARGET_APPIMAGE", "APPIMAGE_EXTRACT_AND_RUN", "DDNATV_ROOT")} + env.update(extra) return subprocess.run(["bash", str(script), str(self.image), "--no-gui"], env=env, capture_output=True, text=True, timeout=30).stdout.splitlines() + def native(self, **extra): + return self.launch(DDNATV_ROOT=str(self.dir / "rootfs"), XDG_CACHE_HOME=str(self.cache), **extra) + + def unpacker(self, works=True, apprun=None): + self.cache = self.dir / "cache" + self.unpacks = self.dir / "unpacks" + apprun = apprun or "#!/bin/sh\nprintf '%s\\n' \"APPIMAGE=$APPIMAGE APPDIR=$APPDIR TARGET=${TARGET_APPIMAGE:-}\" apprun \"$@\"\n" + self.fex.write_text( + "#!/bin/sh\n[ \"$1\" = extract ] || exit 9\necho \"$2\" >> %s\n" % self.unpacks + + ("mkdir -p squashfs-root\ncat > squashfs-root/AppRun <<'EOF'\n%sEOF\nchmod +x squashfs-root/AppRun\n" % apprun if works else "exit 1\n")) + + def unpacked_dirs(self): + return [d for d in self.cache.glob("droiddeck-appimage/*") if d.is_dir()] + def test_an_arm64_image_runs_through_the_shipped_runtime(self): self.assertEqual(["TARGET=%s EXTRACT=1" % self.image, "uruntime", "--no-gui"], self.launch()) @@ -61,6 +77,116 @@ class AppImageExecTest(unittest.TestCase): self.fex.unlink() self.assertEqual(["TARGET=%s EXTRACT=1" % self.image, "uruntime", "--no-gui"], self.launch()) + def test_without_proot_an_arm64_image_is_unpacked_once_and_runs_from_its_apprun(self): + self.unpacker() + expected = ["== appimage: unpacking %s" % self.image] + ran = ["APPIMAGE=%s APPDIR=%s/squashfs-root TARGET=" % (self.image, "%s"), "apprun", "--no-gui"] + first = self.native() + self.assertEqual(expected, first[:1]) + [unpacked] = self.unpacked_dirs() + ran[0] = ran[0] % unpacked + self.assertEqual(ran, first[1:]) + self.assertEqual(ran, self.native()) + self.assertEqual([str(self.image)], self.unpacks.read_text().splitlines()) + + def test_without_proot_a_changed_image_is_unpacked_again(self): + self.unpacker() + self.native() + os.utime(self.image, (1, 1)) + self.assertEqual("apprun", self.native()[2]) + self.assertEqual(2, len(self.unpacks.read_text().splitlines())) + self.assertEqual(1, len(self.unpacked_dirs())) + + def test_without_proot_a_same_size_change_within_one_second_is_unpacked_again(self): + self.unpacker() + os.utime(self.image, ns=(1_000_000_100_000_000, 1_000_000_100_000_000)) + self.native() + os.utime(self.image, ns=(1_000_000_900_000_000, 1_000_000_900_000_000)) + self.assertEqual("apprun", self.native()[2]) + self.assertEqual(2, len(self.unpacks.read_text().splitlines())) + self.assertEqual(1, len(self.unpacked_dirs())) + + def hold(self, unpacked): + handle = open(unpacked / "source") + self.addCleanup(handle.close) + fcntl.flock(handle, fcntl.LOCK_SH) + return handle + + def test_without_proot_a_running_copy_survives_an_update_until_it_exits(self): + self.unpacker() + self.native() + [old] = self.unpacked_dirs() + running = self.hold(old) + os.utime(self.image, (1, 1)) + self.assertEqual("apprun", self.native()[2]) + self.assertTrue((old / "squashfs-root/AppRun").exists()) + [new] = [d for d in self.unpacked_dirs() if d != old] + running.close() + self.assertEqual("apprun", self.native()[1]) + self.assertEqual([new], self.unpacked_dirs()) + + def test_without_proot_a_running_copy_of_a_removed_image_is_kept(self): + self.unpacker() + self.native() + [old] = self.unpacked_dirs() + self.hold(old) + self.image.unlink() + self.image = self.dir / "dolphin.AppImage" + self.machine(183) + self.native() + self.assertTrue((old / "squashfs-root/AppRun").exists()) + self.assertEqual(2, len(self.unpacked_dirs())) + + def test_without_proot_the_running_application_holds_its_copy(self): + self.unpacker(apprun="#!/bin/sh\nflock -n -x \"$APPDIR/../source\" true && echo free || echo held\n") + self.assertEqual(["held"], self.native()[1:]) + + def test_without_proot_nothing_runs_when_the_cache_cannot_be_locked(self): + self.unpacker() + tools = self.dir / "tools" + tools.mkdir() + (tools / "flock").write_text("#!/bin/sh\nexit 1\n") + (tools / "flock").chmod(0o755) + self.assertEqual([], self.native(PATH="%s:%s" % (tools, os.environ["PATH"]))) + self.assertFalse(self.unpacks.exists()) + + def test_without_proot_the_unpacked_copy_of_a_removed_image_is_dropped(self): + self.unpacker() + self.native() + [old] = self.unpacked_dirs() + self.image.unlink() + self.image = self.dir / "dolphin.AppImage" + self.machine(183) + self.native() + self.assertFalse(old.exists()) + self.assertEqual(1, len(self.unpacked_dirs())) + + def test_without_proot_a_linked_cache_entry_and_its_target_survive(self): + self.unpacker() + outside = self.dir / "outside" + outside.mkdir() + (outside / "source").write_text("%s\n" % (self.dir / "gone.AppImage")) + (outside / "keep").write_text("data") + link = self.cache / "droiddeck-appimage" / "linked" + link.parent.mkdir(parents=True) + link.symlink_to(outside, target_is_directory=True) + self.assertEqual("apprun", self.native()[2]) + self.assertTrue(link.is_symlink()) + self.assertEqual("data", (outside / "keep").read_text()) + + def test_without_proot_an_image_that_cannot_be_unpacked_runs_nothing(self): + self.unpacker(works=False) + out = self.native() + self.assertNotIn("uruntime", out) + self.assertNotIn("apprun", out) + self.assertEqual([], self.unpacked_dirs()) + self.assertEqual([], list(self.cache.glob("droiddeck-appimage/.unpack.*"))) + + def test_without_proot_an_x86_image_still_starts_under_fex(self): + self.machine(62) + self.cache = self.dir / "cache" + self.assertEqual(["TARGET= EXTRACT=1", "fex", "run", "--mode", "on", "--", str(self.image), "--no-gui"], self.native()) + def test_the_session_starts_images_through_the_shared_launcher(self): script = ("set -u\n" "run_program() { printf '%%s\\n' \"$@\"; exit 0; }\n" From c1dd542f97b3102953153468db36eb0c77282454 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:51:16 -0500 Subject: [PATCH 101/141] fix(steam): the parallel installer claims packages under a flock (#3145) The parallel workers claimed packages with mkdir, which is not atomic in the app's guest shell: two workers sometimes took the same package and about 3 installs in 8 failed on a device. Claims now come from a counter under a flock, and a counter that cannot be read or written fails the worker. --- .../usr/local/bin/droiddeck-steam-install | 29 +++++++++++--- tools/tests/test_steam_install.py | 40 +++++++++++++++++++ 2 files changed, 63 insertions(+), 6 deletions(-) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install index 7da018df54..8990abf3dc 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install @@ -178,22 +178,42 @@ unzip_alone() { return $rc } +# Takes the next unclaimed line number from a counter under a flock, and prints 0 when none is left. mkdir was tried for this +# and handed the same line to two workers now and then in the app's guest shell, so only the kernel's lock is trusted here. +claim_next() { + local n + while :; do + # A counter that cannot be read or written must fail the worker: a stale or empty number would give a package to two workers or to none. + n=$( { flock 8 || exit 1 + n=$(cat "$state/next") || exit 1 + case $n in ''|*[!0-9]*) exit 1 ;; esac + echo $((n + 1)) > "$state/next" || exit 1 + echo "$n"; } 8> "$state/claim.lock" ) || return 1 + [ "$n" -le "$count" ] || { echo 0; return; } + if [ ! -e "$state/$n.done" ]; then + : > "$state/claim.$n" + echo "$n" + return + fi + done +} + # Fetches every line of a list ("block file sum size") into $dir with up to $parallel connections. With a third # argument each package is also unpacked into the client as it lands. One connection tops out near half of what a # Wi-Fi link carries, so the packages arrive about twice as fast. Workers take the next unclaimed line themselves -# (mkdir is atomic) and only plain background jobs and wait on a pid are used, so nothing depends on job control. +# (claim_next) and only plain background jobs and wait on a pid are used, so nothing depends on job control. run_parallel() { local list=$1 dir=$2 unpack=${3:-} state index=0 block file sum size local -a blocks=() files=() sums=() sizes=() pids=() state=$work/parallel rm -rf "$state" mkdir -p "$state" + echo 1 > "$state/next" while read -r block file sum size; do index=$((index + 1)) blocks[index]=$block files[index]=$file sums[index]=$sum sizes[index]=$size if [ -n "$unpack" ] && [ -f "$dir/$file.unpacked" ]; then : > "$state/$index.done" - : > "$state/claim.$index" fi done < "$list" local count=$index total_bytes=0 @@ -203,10 +223,7 @@ run_parallel() { ( trap ': > "$state/exit.$slot"' EXIT while [ ! -e "$state/failed" ]; do - index=0 - for n in $(seq 1 "$count"); do - if mkdir "$state/claim.$n" 2>/dev/null; then index=$n; break; fi - done + index=$(claim_next) [ "$index" -gt 0 ] || exit 0 file=${files[index]} fetched="" diff --git a/tools/tests/test_steam_install.py b/tools/tests/test_steam_install.py index 2a74968c00..3364729efb 100644 --- a/tools/tests/test_steam_install.py +++ b/tools/tests/test_steam_install.py @@ -613,6 +613,46 @@ with open(log, 'a') as out: self.assertIn('downloading Steam: a_all (1/2), 0 of 2 MB\n', result.stdout) self.assertIn('downloading Steam: client_linuxarm64_linuxarm64 (2/2), 1 of 2 MB\n', result.stdout) + def test_workers_do_not_claim_packages_with_mkdir(self): + source = SCRIPT.read_text() + region = source[source.index('run_parallel() {'):source.index('fetch_manifest() {')] + self.assertNotIn('mkdir "$state/claim', region) + self.assertIn('claim_next', region) + + @unittest.skipUnless(shutil.which('flock'), 'needs flock') + def test_racing_workers_never_get_the_same_package(self): + source = SCRIPT.read_text() + start = source.index('claim_next() {') + function = source[start:source.index('\n}\n', start) + 3] + state = self.root / 'claims' + state.mkdir() + (state / 'next').write_text('1\n') + script = 'state=$1\ncount=$2\n' + function + 'while :; do n=$(claim_next); [ "$n" -gt 0 ] || exit 0; echo "$n"; done\n' + workers = [subprocess.Popen(['bash', '-c', script, 'bash', str(state), '300'], stdout=subprocess.PIPE, text=True) + for _ in range(8)] + claimed = [] + for worker in workers: + out, _ = worker.communicate(timeout=120) + self.assertEqual(0, worker.returncode) + claimed += [int(n) for n in out.split()] + self.assertEqual(sorted(claimed), list(range(1, 301)), 'a package was claimed twice or never') + + @unittest.skipUnless(shutil.which('flock'), 'needs flock') + def test_a_counter_that_cannot_be_used_fails_the_claim(self): + source = SCRIPT.read_text() + start = source.index('claim_next() {') + function = source[start:source.index('\n}\n', start) + 3] + for broken in ('directory', 'empty', 'text'): + state = self.root / f'claims-{broken}' + state.mkdir() + if broken == 'directory': + (state / 'next').mkdir() + else: + (state / 'next').write_text('' if broken == 'empty' else 'abc\n') + script = 'state=$1\ncount=5\n' + function + 'n=$(claim_next) && echo "claimed $n" || echo failed\n' + result = subprocess.run(['bash', '-c', script, 'bash', str(state)], text=True, capture_output=True, timeout=30) + self.assertEqual('failed', result.stdout.strip(), f'{broken}: {result.stdout!r} {result.stderr!r}') + def test_the_parallel_workers_use_no_process_substitution(self): source = SCRIPT.read_text() region = source[source.index('fetch_one() {'):source.index('fetch_manifest() {')] From caf16c8aa5c42dec6f908ac36d9545672d136875 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:15:38 -0500 Subject: [PATCH 102/141] fix(steam): a failed package claim fails the install (#3149) run_parallel is called in an || list, which switches set -e off inside it and inside its workers, so a failed claim left the worker's index empty and the worker exited successfully with packages unclaimed. The worker now checks the claim itself and marks the run failed, and claim_next uses the same flock command as the unpack lock. --- .../overlay/usr/local/bin/droiddeck-steam-install | 5 +++-- tools/tests/test_steam_install.py | 11 +++++++++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install index 8990abf3dc..1578b24042 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install @@ -184,7 +184,7 @@ claim_next() { local n while :; do # A counter that cannot be read or written must fail the worker: a stale or empty number would give a package to two workers or to none. - n=$( { flock 8 || exit 1 + n=$( { "$flock_command" 8 || exit 1 n=$(cat "$state/next") || exit 1 case $n in ''|*[!0-9]*) exit 1 ;; esac echo $((n + 1)) > "$state/next" || exit 1 @@ -223,7 +223,8 @@ run_parallel() { ( trap ': > "$state/exit.$slot"' EXIT while [ ! -e "$state/failed" ]; do - index=$(claim_next) + # run_parallel is called in an || list, which switches set -e off in here: a failed claim has to be checked by hand. + index=$(claim_next) || { : > "$state/failed"; exit 1; } [ "$index" -gt 0 ] || exit 0 file=${files[index]} fetched="" diff --git a/tools/tests/test_steam_install.py b/tools/tests/test_steam_install.py index 3364729efb..836372c29c 100644 --- a/tools/tests/test_steam_install.py +++ b/tools/tests/test_steam_install.py @@ -627,7 +627,7 @@ with open(log, 'a') as out: state = self.root / 'claims' state.mkdir() (state / 'next').write_text('1\n') - script = 'state=$1\ncount=$2\n' + function + 'while :; do n=$(claim_next); [ "$n" -gt 0 ] || exit 0; echo "$n"; done\n' + script = 'state=$1\ncount=$2\nflock_command=flock\n' + function + 'while :; do n=$(claim_next); [ "$n" -gt 0 ] || exit 0; echo "$n"; done\n' workers = [subprocess.Popen(['bash', '-c', script, 'bash', str(state), '300'], stdout=subprocess.PIPE, text=True) for _ in range(8)] claimed = [] @@ -649,10 +649,17 @@ with open(log, 'a') as out: (state / 'next').mkdir() else: (state / 'next').write_text('' if broken == 'empty' else 'abc\n') - script = 'state=$1\ncount=5\n' + function + 'n=$(claim_next) && echo "claimed $n" || echo failed\n' + script = 'state=$1\ncount=5\nflock_command=flock\n' + function + 'n=$(claim_next) && echo "claimed $n" || echo failed\n' result = subprocess.run(['bash', '-c', script, 'bash', str(state)], text=True, capture_output=True, timeout=30) self.assertEqual('failed', result.stdout.strip(), f'{broken}: {result.stdout!r} {result.stderr!r}') + def test_a_claim_that_fails_fails_the_install_instead_of_leaving_packages_unclaimed(self): + self.many_parts() + # false is found like a flock would be, but it never takes the lock, so every claim fails. + result = self.install(DD_STEAM_FLOCK='false', timeout=60) + self.assertNotEqual(0, result.returncode, result.stdout) + self.assertFalse((self.steam / 'package/droiddeck-installed').exists()) + def test_the_parallel_workers_use_no_process_substitution(self): source = SCRIPT.read_text() region = source[source.index('fetch_one() {'):source.index('fetch_manifest() {')] From c298da6f60ad301755e715449de682dbff3d85d9 Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Tue, 24 Nov 2026 10:30:54 -0500 Subject: [PATCH 103/141] fix(nativeguest): keep loader paths out of guest environment (#3147) * fix(nativeguest): keep loader paths out of guest environment * fix(nativeguest): preserve caller library search paths * fix(nativeguest): preserve empty caller library path components --- .../droiddeck/launcher/runtime/NativeGuest.kt | 10 +++--- .../launcher/runtime/NativeGuestTest.kt | 32 ++++++++++++++++++- tools/nativeguest/hook/env.c | 15 --------- tools/nativeguest/hook/paths.c | 5 --- tools/tests/test_native_hook_ldso_spawn.py | 14 +++++++- 5 files changed, 49 insertions(+), 27 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt b/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt index 3cd7d4370f..c609fe7c4b 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt @@ -76,7 +76,6 @@ 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() } @@ -84,10 +83,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>): List<String> { + fun command(root: File, program: String, args: List<String>, libraryPath: String = libraryPath(root)): List<String> { val loader = checkNotNull(loader(root)) { "no glibc loader in ${root.path}" } val host = File(root, program.removePrefix("/")) - val launch = listOf(loader.path, "--argv0", host.name, host.path) + args + val launch = listOf(loader.path, "--library-path", libraryPath, "--argv0", host.name, host.path) + args return simulator(root)?.let { it + launch } ?: (execPrefix(loader.path) + launch) } @@ -100,7 +99,6 @@ 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() } } @@ -273,7 +271,9 @@ 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 cmd = command(root, program, argv.drop(1)) + 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 builder = ProcessBuilder(cmd).redirectErrorStream(false) builder.directory(File(root, cwd.removePrefix("/")).takeIf { it.isDirectory } ?: root) builder.environment().apply { diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt index 3188eb4e62..4fe7a60dc0 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt @@ -44,7 +44,36 @@ class NativeGuestTest { val root = rootWithLoader() val command = NativeGuest.command(root, "/usr/bin/env", listOf("-i", "A=1")) assertEquals(File(root, "usr/lib/ld-linux-aarch64.so.1").path, command[0]) - assertEquals(listOf("--argv0", "env", File(root, "usr/bin/env").path, "-i", "A=1"), command.drop(1)) + assertEquals(listOf("--library-path", NativeGuest.libraryPath(root), "--argv0", "env", File(root, "usr/bin/env").path, "-i", "A=1"), command.drop(1)) + assertTrue("LD_LIBRARY_PATH" !in NativeGuest.environment(root)) + } + + @Test + fun builderKeepsCallerLibraryPathAheadOfRootfsDirectories() { + val root = rootWithLoader() + val rootDirs = NativeGuest.libraryPath(root).split(':') + val callerPath = "/custom/lib:${rootDirs[1]}:/other/lib" + val builder = NativeGuest.builder(root, "/", listOf("/usr/bin/env"), mapOf("LD_LIBRARY_PATH" to callerPath)) + val command = builder.command() + assertEquals(listOf("/custom/lib", rootDirs[1], "/other/lib") + rootDirs.filterNot { it == rootDirs[1] }, + command[command.indexOf("--library-path") + 1].split(':')) + assertEquals(callerPath, builder.environment()["LD_LIBRARY_PATH"]) + } + + @Test + fun builderPreservesEmptyCallerLibraryPathComponents() { + val root = rootWithLoader() + val rootPath = NativeGuest.libraryPath(root) + for (callerPath in listOf(":/custom/lib", "/custom/lib:", ":/custom/lib::")) { + val builder = NativeGuest.builder(root, "/", listOf("/usr/bin/env"), mapOf("LD_LIBRARY_PATH" to callerPath)) + val command = builder.command() + assertEquals("$callerPath:$rootPath", command[command.indexOf("--library-path") + 1]) + assertEquals(callerPath, builder.environment()["LD_LIBRARY_PATH"]) + } + for (env in listOf(emptyMap(), mapOf("LD_LIBRARY_PATH" to ""))) { + val command = NativeGuest.builder(root, "/", listOf("/usr/bin/env"), env).command() + assertEquals(rootPath, command[command.indexOf("--library-path") + 1]) + } } @Test @@ -53,6 +82,7 @@ class NativeGuestTest { val env = NativeGuest.sessionEnvironment(root, listOf("/dev", "/a:/b")) assertEquals("/dev:/dev|/a:/b", env["DDNATV_BINDS"]) assertEquals(root.path, env["DDNATV_ROOT"]) + assertTrue("LD_LIBRARY_PATH" !in env) assertTrue(env.getValue("LD_PRELOAD").replace(File.separatorChar, '/').endsWith("usr/lib/libddnatv-hook.so")) } diff --git a/tools/nativeguest/hook/env.c b/tools/nativeguest/hook/env.c index 8f3daf8086..fd6824d3b7 100644 --- a/tools/nativeguest/hook/env.c +++ b/tools/nativeguest/hook/env.c @@ -76,7 +76,6 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const init_ddnatv_hook(); int count = 0; int has_preload = 0; - int has_ld_library_path = 0; int has_root = 0; int has_tunables = 0; int has_path = 0; @@ -104,7 +103,6 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const switch (e[0]) { case 'L': if (strncmp(e, "LD_PRELOAD=", 11) == 0) { has_preload = 1; preload_value = e + 11; } - else if (strncmp(e, "LD_LIBRARY_PATH=", 16) == 0) has_ld_library_path = 1; break; case 'G': if (strncmp(e, "GLIBC_TUNABLES=", 15) == 0) has_tunables = 1; @@ -217,19 +215,6 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const new_env[dst++] = str; } } - if (!has_ld_library_path && g_ddnatv_root[0] != '\0') { - size_t size = 16 + 1; - for (size_t i = 0; i < sizeof(k_rootfs_lib_dirs) / sizeof(k_rootfs_lib_dirs[0]); i++) { - char dir[PATH_MAX]; - size += 1 + strlen(rewrite_path_in_root(k_rootfs_lib_dirs[i], dir, sizeof(dir))); - } - char *str = malloc(size); - if (str) { - size_t n = ddnatv_append(str, size, 0, "LD_LIBRARY_PATH=", 16); - append_rootfs_lib_dirs(str, size, n, 0); - new_env[dst++] = str; - } - } if (!has_root && g_ddnatv_root[0] != '\0') { char *str = malloc(PATH_MAX + 16); if (str) { diff --git a/tools/nativeguest/hook/paths.c b/tools/nativeguest/hook/paths.c index 94e2ad336f..6e347b3296 100644 --- a/tools/nativeguest/hook/paths.c +++ b/tools/nativeguest/hook/paths.c @@ -755,11 +755,6 @@ static size_t append_rootfs_lib_dirs_missing_from(char *out, size_t outsz, size_ return used; } -// All of them. -static size_t append_rootfs_lib_dirs(char *out, size_t outsz, size_t used, int separate) { - return append_rootfs_lib_dirs_missing_from(out, outsz, used, separate, NULL); -} - #ifndef DDNATV_HOST_TEST // Relative *at() calls. A program that walks a path one component at a time (systemd's chase(), used // by libudev; fts) opens "/" and then "sys", "class", ... relative to the last descriptor, and those diff --git a/tools/tests/test_native_hook_ldso_spawn.py b/tools/tests/test_native_hook_ldso_spawn.py index d7c861085d..8d8b417f82 100644 --- a/tools/tests/test_native_hook_ldso_spawn.py +++ b/tools/tests/test_native_hook_ldso_spawn.py @@ -27,6 +27,7 @@ static void show(const char *path, char *const argv[], char *const envp[]) { printf("\n"); for (int i = 0; envp && envp[i]; i++) if (strncmp(envp[i], "DDNATV_LIBRARY_PATH=", 20) == 0) printf("libpath\t%s\n", envp[i] + 20); + else if (strncmp(envp[i], "LD_LIBRARY_PATH=", 16) == 0) printf("envpath\t%s\n", envp[i] + 16); fflush(stdout); } @@ -124,12 +125,14 @@ class NativeHookLdsoSpawnTest(unittest.TestCase): def tearDownClass(cls): cls.tmp.cleanup() - def call(self, how, *argv, binds=None, real_exe=None): + def call(self, how, *argv, binds=None, real_exe=None, ld_library_path=None): hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook}:{self.recorder}"} if binds: hook_env["DDNATV_BINDS"] = binds if real_exe: hook_env["DDNATV_REAL_EXE"] = real_exe + if ld_library_path is not None: + hook_env["LD_LIBRARY_PATH"] = ld_library_path env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_EXEC", "LD_LIBRARY_PATH")} if self.prefix: cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] @@ -139,6 +142,7 @@ class NativeHookLdsoSpawnTest(unittest.TestCase): out = subprocess.run(cmd + [str(self.probe), how, *argv], env=env, capture_output=True, text=True, timeout=120) calls = [line.split("\t")[1:] for line in out.stdout.splitlines() if line.startswith("call\t")] self.library_paths = [line.split("\t", 1)[1] for line in out.stdout.splitlines() if line.startswith("libpath\t")] + self.env_paths = [line.split("\t", 1)[1] for line in out.stdout.splitlines() if line.startswith("envpath\t")] self.assertEqual(1, len(calls), out.stdout + out.stderr) if how == "spawn": self.assertIn("ret\t0", out.stdout.splitlines(), out.stdout + out.stderr) @@ -167,6 +171,14 @@ class NativeHookLdsoSpawnTest(unittest.TestCase): def test_spawn_and_exec_start_a_dynamic_program_the_same_way(self): self.assertEqual(self.call("exec", GUEST_TOOL, "x"), self.call("spawn", GUEST_TOOL, "x")) + def test_guest_library_environment_is_preserved(self): + for how in ("exec", "spawn"): + for value in (None, "", "/custom/lib:/other/lib"): + with self.subTest(how=how, value=value): + argv = self.call(how, GUEST_TOOL, ld_library_path=value)[1:] + self.assertEqual([] if value is None else [value], self.env_paths) + self.assertIn(str(self.root / "usr/lib/aarch64-linux-gnu"), argv[argv.index("--library-path") + 1]) + def test_a_program_started_through_ldso_records_its_library_path(self): for how in ("exec", "spawn"): with self.subTest(how=how): From 5f8655b13ed010192f62465eee371d50b1c0d8db Mon Sep 17 00:00:00 2001 From: The412Banner <205237651+The412Banner@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:39:52 -0500 Subject: [PATCH 104/141] fix(flatpak): find sandbox sources named by their kernel path when the session runs without proot (#3059) Co-authored-by: maxjivi05 <maxjividen@gmail.com> --- .../launcher/runtime/BwrapSpawner.kt | 14 ++++++++-- .../launcher/runtime/BwrapSpawnerTest.kt | 26 +++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt b/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt index ca408e3b36..d8e8e47729 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt @@ -112,9 +112,16 @@ object BwrapSpawner { return out } + internal fun withKernelPaths(sessionBinds: List<Bind>, canonical: (String) -> String): List<Bind> = + sessionBinds + sessionBinds.filter { it.host == it.guest }.mapNotNull { bind -> + runCatching { canonical(bind.host) }.getOrNull() + ?.takeIf { it != bind.guest && sessionBinds.none { other -> other.guest == it } } + ?.let { Bind(bind.host, it) } + } + internal fun plan(context: Context, request: JSONObject, dir: File): Plan { val rootfs = LinuxRuntime.rootDir(context).path - val session = LinuxRuntime.lastBinds(context).map { Bind.parse(it) } + val session = withKernelPaths(LinuxRuntime.lastBinds(context).map { Bind.parse(it) }) { File(it).canonicalPath } val root = File(dir, "root").apply { mkdirs() } val binds = ArrayList<Bind>() var scratch = 0 @@ -537,6 +544,9 @@ object BwrapSpawner { return f } + internal fun prootEnvironment(plan: Plan, startsThroughEnvTool: Boolean): Map<String, String> = + if (startsThroughEnvTool) emptyMap() else plan.env - "LD_PRELOAD" + private fun run(context: Context, plan: Plan, client: LocalSocket, out: DataOutputStream, id: Int) { val verbose = plan.env["DROIDDECK_PROOT_VERBOSE"]?.toIntOrNull() val native = if (NativeGuest.forSession(context)) nativeLaunch(context, plan) else null @@ -558,7 +568,7 @@ object BwrapSpawner { ProcessBuilder(cmd).redirectErrorStream(true).directory(plan.root).also { b -> b.environment().apply { clear() - if (!envTool) putAll(plan.env) + putAll(prootEnvironment(plan, envTool)) put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path) put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path) if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1") diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt index cf78bed84f..05ab89a2c4 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt @@ -75,6 +75,32 @@ class BwrapSpawnerTest { assertEquals("x11", x11["SDL_VIDEODRIVER"]) } + @Test fun sourcesNamedByTheirKernelPathReachTheSessionsMounts() { + val files = "/data/user/0/com.droiddeck.launcher/files" + val kernel = "/data/data/com.droiddeck.launcher/files" + val binds = session + Bind(files, files) + val aliased = BwrapSpawner.withKernelPaths(binds) { it.replace("/data/user/0/", "/data/data/") } + val runtime = "/linuxfs/root/.local/share/flatpak/runtime/org.example.Platform/aarch64/1/abc/files" + assertEquals("$files$runtime", BwrapSpawner.hostPath(aliased, "$files/linuxfs", "$kernel$runtime")) + assertEquals("$files$runtime", BwrapSpawner.hostPath(aliased, "$files/linuxfs", "$files$runtime")) + assertEquals("$files/linuxfs/usr/bin/env", BwrapSpawner.hostPath(aliased, "$files/linuxfs", "/usr/bin/env")) + } + + @Test fun kernelPathsLeaveOtherMountsAlone() { + assertEquals(session, BwrapSpawner.withKernelPaths(session) { it }) + val renamed = listOf(Bind("/data/user/0/x", "/mnt/x"), Bind("/data/user/0/y", "/data/user/0/y"), Bind("/elsewhere", "/data/data/y")) + assertEquals(renamed, BwrapSpawner.withKernelPaths(renamed) { it.replace("/data/user/0/", "/data/data/") }) + assertEquals(session, BwrapSpawner.withKernelPaths(session) { throw java.io.IOException(it) }) + } + + @Test fun prootGetsNoGuestPreloadOfItsOwn() { + val plan = BwrapSpawner.Plan(File("/sandbox"), emptyList(), "/", listOf("/app/bin/apply_extra"), + mapOf("LD_PRELOAD" to "/run/droiddeck-preload/libddsession.so", "FLATPAK_ID" to "org.example.Ext")) + assertEquals(mapOf("FLATPAK_ID" to "org.example.Ext"), BwrapSpawner.prootEnvironment(plan, false)) + assertTrue(BwrapSpawner.prootEnvironment(plan, true).isEmpty()) + assertEquals("/run/droiddeck-preload/libddsession.so", plan.env["LD_PRELOAD"]) + } + @Test fun normalizeResolvesDotsLexically() { assertEquals("/usr/lib/x", BwrapSpawner.normalize("/usr/lib/GL/../x")) assertEquals("/", BwrapSpawner.normalize("/../..")) From e709e1c45465bd7ed245460a0e7a082e5a8171ea Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Tue, 24 Nov 2026 14:07:01 -0500 Subject: [PATCH 105/141] fix(desktop): Go programs see the session's identity and paths (#3154) * fix(desktop): Go programs see the session's identity and paths Static Go programs now get the session's root identity from getuid and its relatives, and set*id calls succeed, as C and x86 programs already do. The added code also takes over Go's second raw system call function (and its golang.org/x/sys copy), which getuid goes through. Go programs that link the C library (snapd, gocryptfs, ipp-usb) get the same code: their Go note is found past the other notes, and the code fits before a data segment that does not start on a page boundary. snap now reaches the session's snapd and installs snaps. * fix(desktop): read every Go note and retry Go programs after a failed scan --- tools/nativeguest/gosys/gosys.c | 16 ++- tools/nativeguest/gosys/gosys_abi.h | 2 +- tools/nativeguest/hook/exec.c | 4 +- tools/nativeguest/hook/go_programs.c | 123 +++++++++------- tools/nativeguest/hook/static_programs.c | 12 +- tools/tests/test_native_hook_go_identity.py | 147 ++++++++++++++++++++ 6 files changed, 250 insertions(+), 54 deletions(-) create mode 100644 tools/tests/test_native_hook_go_identity.py diff --git a/tools/nativeguest/gosys/gosys.c b/tools/nativeguest/gosys/gosys.c index fb8230ce4a..4a38cf4364 100644 --- a/tools/nativeguest/gosys/gosys.c +++ b/tools/nativeguest/gosys/gosys.c @@ -37,7 +37,10 @@ enum { NR_CHDIR = 49, NR_CHROOT = 51, NR_FCHMODAT = 53, NR_FCHOWNAT = 54, NR_OPENAT = 56, NR_READLINKAT = 78, NR_NEWFSTATAT = 79, NR_UTIMENSAT = 88, NR_BIND = 200, NR_CONNECT = 203, NR_EXECVE = 221, NR_NAME_TO_HANDLE_AT = 264, NR_RENAMEAT2 = 276, NR_STATX = 291, - NR_OPENAT2 = 437, NR_FACCESSAT2 = 439, NR_FCHMODAT2 = 452, + NR_OPENAT2 = 437, NR_FACCESSAT2 = 439, NR_FCHMODAT2 = 452, NR_SETREGID = 143, NR_SETGID = 144, + NR_SETREUID = 145, NR_SETUID = 146, NR_SETRESUID = 147, NR_GETRESUID = 148, NR_SETRESGID = 149, + NR_GETRESGID = 150, NR_SETGROUPS = 159, NR_GETUID = 174, NR_GETEUID = 175, NR_GETGID = 176, + NR_GETEGID = 177, }; __attribute__((section(".hdr"), used)) @@ -459,6 +462,9 @@ static i64 handle(const struct gosys_hdr *h, u32 *held, i64 nr, i64 a0, i64 a1, case NR_SETXATTR: case NR_LSETXATTR: case NR_GETXATTR: case NR_LGETXATTR: case NR_LISTXATTR: case NR_LLISTXATTR: case NR_REMOVEXATTR: case NR_LREMOVEXATTR: case NR_RENAMEAT: case NR_RENAMEAT2: case NR_LINKAT: case NR_SYMLINKAT: case NR_GETCWD: case NR_BIND: case NR_CONNECT: case NR_EXECVE: + case NR_GETUID: case NR_GETEUID: case NR_GETGID: case NR_GETEGID: case NR_GETRESUID: case NR_GETRESGID: + case NR_SETUID: case NR_SETGID: case NR_SETREUID: case NR_SETREGID: case NR_SETRESUID: case NR_SETRESGID: + case NR_SETGROUPS: // The calls that carry paths: not mapped where the rootfs is not in its own place (above) if (!rewriting(h)) return sc(nr, a0, a1, a2, a3, a4, a5); break; @@ -483,6 +489,14 @@ static i64 handle(const struct gosys_hdr *h, u32 *held, i64 nr, i64 a0, i64 a1, i64 r = sc(nr, a0, a1, 0, 0, 0, 0); return r > 0 ? unmap_prefix(h, (char *)a0, r, 1) : r; } + case NR_GETUID: case NR_GETEUID: case NR_GETGID: case NR_GETEGID: case NR_SETUID: case NR_SETGID: + case NR_SETREUID: case NR_SETREGID: case NR_SETRESUID: case NR_SETRESGID: case NR_SETGROUPS: + return 0; + case NR_GETRESUID: case NR_GETRESGID: { + i64 r = sc(nr, a0, a1, a2, 0, 0, 0); + if (r == 0) *(u32 *)a0 = *(u32 *)a1 = *(u32 *)a2 = 0; + return r; + } case NR_BIND: case NR_CONNECT: return with_sockaddr(h, held, nr, a0, a1, a2); case NR_EXECVE: { diff --git a/tools/nativeguest/gosys/gosys_abi.h b/tools/nativeguest/gosys/gosys_abi.h index e0c4807d34..d06a4f5c8b 100644 --- a/tools/nativeguest/gosys/gosys_abi.h +++ b/tools/nativeguest/gosys/gosys_abi.h @@ -15,7 +15,7 @@ #include <stdint.h> #ifndef GOSYS_VERSION -#define GOSYS_VERSION 3u // raised when the code or its header changes: patched programs are patched again +#define GOSYS_VERSION 4u // raised when the code or its header changes: patched programs are patched again #endif // The scratch memory for rewritten paths: a small state area and 64 slots, in zero-filled memory the diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index e9c115d477..555ce7fc21 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -407,7 +407,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e if (probe.is_elf && !probe.is_dynamic) static_elf = elf_target; // A Go program built for Android asks for Android's linker, so it is started like the dynamic // ones, but it makes its own system calls: it gets the code of the static Go programs (#42) - if (probe.is_dynamic && probe.android_interp) prepare_static_program_ex(elf_target, 1); + if (probe.is_dynamic) prepare_static_program_ex(elf_target, 1); // 1. Transparently route dynamically linked glibc ELF binaries through ld.so // Note: Statically linked binaries (PT_INTERP absent, e.g. Meta Muse Code) must execute directly! @@ -959,7 +959,7 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path, int ret = -1; if (via_ld_so) { ensure_exec_bit(elf_target, probe.mode); - if (probe.android_interp) prepare_static_program_ex(elf_target, 1); // a Go program built for Android (#42) + prepare_static_program_ex(elf_target, 1); // a Go program built for Android (#42) char hook_buf[PATH_MAX]; const char *hook_so = ddnatv_hook_library(hook_buf, sizeof(hook_buf)); diff --git a/tools/nativeguest/hook/go_programs.c b/tools/nativeguest/hook/go_programs.c index 987d0132ee..5bb6f627f6 100644 --- a/tools/nativeguest/hook/go_programs.c +++ b/tools/nativeguest/hook/go_programs.c @@ -70,14 +70,20 @@ static int go_read_phdrs(int fd, struct go_ph *ph, uint16_t *etype, uint16_t *ma static const uint32_t k_go_syscall6[7] = { 0xf94007e8u, 0xf9400be0u, 0xf9400fe1u, 0xf94013e2u, 0xf94017e3u, 0xf9401be4u, 0xf9401fe5u, }; +static const uint32_t k_go_raw_no_error[7] = { + 0xf9400be0u, 0xf9400fe1u, 0xf94013e2u, 0xaa1f03e3u, 0xaa1f03e4u, 0xaa1f03e5u, 0xf94007e8u, +}; #define GO_SVC 0xd4000001u #define GO_CMN_X0_4095 0xb13ffc1fu +#define GO_STR_X0_SP40 0xf90017e0u +#define GO_THUNK_STRIDE 32u +#define GO_QUIET_MAX 4 +_Static_assert(GO_THUNK_STRIDE * (GO_QUIET_MAX + 1) <= GOSYS_THUNK_BYTES, "the thunks fit"); // Where Syscall6 makes its call: the file offset of the instruction after the seven loads (the // "svc #0", or the branch that replaced it). *found counts the places; the first is returned. -static int64_t go_find_syscall6(int fd, const struct go_ph *ph, int n, int *found) { - int64_t first = -1; - *found = 0; +static int go_find_calls(int fd, const struct go_ph *ph, int n, const uint32_t *code, uint32_t after, int64_t *at, int max) { + int found = 0; enum { CHUNK = 1 << 20, KEEP = 36 }; unsigned char *buf = (unsigned char *)malloc(CHUNK + KEEP); if (!buf) return -1; @@ -90,19 +96,19 @@ static int64_t go_find_syscall6(int fd, const struct go_ph *ph, int n, int *foun ssize_t got = pread(fd, buf, (size_t)want, (off_t)(ph[i].offset + pos)); if (got <= KEEP) break; for (ssize_t o = 0; o + 36 <= got; o += 4) { - if (rd32(buf + o) != k_go_syscall6[0]) continue; + if (rd32(buf + o) != code[0]) continue; int same = 1; - for (int k = 1; k < 7 && same; k++) same = rd32(buf + o + 4 * k) == k_go_syscall6[k]; - if (!same || rd32(buf + o + 32) != GO_CMN_X0_4095) continue; - if (*found == 0) first = (int64_t)(ph[i].offset + pos + (uint64_t)o + 28); - (*found)++; + for (int k = 1; k < 7 && same; k++) same = rd32(buf + o + 4 * k) == code[k]; + if (!same || rd32(buf + o + 32) != after) continue; + if (found < max) at[found] = (int64_t)(ph[i].offset + pos + (uint64_t)o + 28); + found++; } if (pos + (uint64_t)got >= ph[i].filesz) break; pos += (uint64_t)got - (KEEP - 4); // the next chunk starts where the last place of this could begin, no place is split or counted twice } } free(buf); - return first; + return found; } // "b <delta>" / "bl <delta>" for a distance in bytes, or 0 when it does not fit @@ -179,13 +185,7 @@ static int go_open_for_write(int fd, const struct stat *st, const char *path, in // The bytes of the added code for a given place: the code with its header (the strings, and where // the scratch memory is), the instructions that connect the call site to it, and the trailer that // says what was changed to put it there. -static void go_build_image(unsigned char *img, const struct gosys_hdr *strings, uint64_t cave_v, uint64_t scratch_v, - uint32_t to_entry, uint32_t back, const struct gosys_trailer *info) { - memcpy(img, gosys_blob, GOSYS_BLOB_SIZE); - struct gosys_hdr h = *strings; - h.scratch_rel = (int64_t)scratch_v - (int64_t)cave_v; - memcpy(img, &h, sizeof(h)); - unsigned char *th = img + GOSYS_THUNKS_OFF; +static void go_write_thunk(unsigned char *th, uint32_t to_entry, uint32_t back) { wr32(th + 0, 0xd10043ffu); // sub sp, sp, #16 wr32(th + 4, 0xf90003feu); // str x30, [sp] wr32(th + 8, 0xaa0803e7u); // mov x7, x8 (the number is the eighth argument) @@ -193,6 +193,15 @@ static void go_build_image(unsigned char *img, const struct gosys_hdr *strings, wr32(th + 16, 0xf94003feu); // ldr x30, [sp] wr32(th + 20, 0x910043ffu); // add sp, sp, #16 wr32(th + 24, back); // b <the instruction after the call> +} + +static void go_build_image(unsigned char *img, const struct gosys_hdr *strings, uint64_t cave_v, uint64_t scratch_v, + const uint32_t *to_entry, const uint32_t *back, int sites, const struct gosys_trailer *info) { + memcpy(img, gosys_blob, GOSYS_BLOB_SIZE); + struct gosys_hdr h = *strings; + h.scratch_rel = (int64_t)scratch_v - (int64_t)cave_v; + memcpy(img, &h, sizeof(h)); + for (int k = 0; k < sites; k++) go_write_thunk(img + GOSYS_THUNKS_OFF + GO_THUNK_STRIDE * (uint64_t)k, to_entry[k], back[k]); struct gosys_trailer t; memcpy(&t, img + GOSYS_BLOB_SIZE - sizeof(t), sizeof(t)); t.version = GOSYS_VERSION; @@ -220,11 +229,12 @@ static uint32_t go_blob_fingerprint(void) { // Gives the program its old segments and call back: the added code is zeroed, the data segment // is shortened, the instruction is a "svc #0" again. -static int go_undo(int wfd, struct go_ph *ph, int cave_seg, const struct gosys_trailer *tr, int64_t site_off) { +static int go_undo(int wfd, struct go_ph *ph, int cave_seg, const struct gosys_trailer *tr, const int64_t *site_off, int sites) { uint64_t cave_off = ph[cave_seg].offset + ph[cave_seg].filesz - tr->total_size; unsigned char word[4]; wr32(word, GO_SVC); - if (go_pwrite_all(wfd, word, 4, (uint64_t)site_off) != 0) return -1; + for (int k = sites - 1; k >= 0; k--) + if (go_pwrite_all(wfd, word, 4, (uint64_t)site_off[k]) != 0) return -1; unsigned char sz[16]; go_wr64(sz, tr->text_orig_filesz); go_wr64(sz + 8, tr->text_orig_filesz); @@ -253,14 +263,30 @@ static int go_disabled(void) { // The three branches that connect the call site and the code: site -> thunk, thunk -> entry (bl), // thunk -> the instruction after the site. 0 when one of them is too far. -static int go_branches(uint64_t cave_v, uint64_t site_v, uint32_t *to_thunk, uint32_t *to_entry, uint32_t *back) { - uint64_t thunk_v = cave_v + GOSYS_THUNKS_OFF; +static int go_branches(uint64_t cave_v, uint64_t site_v, int k, uint32_t *to_thunk, uint32_t *to_entry, uint32_t *back) { + uint64_t thunk_v = cave_v + GOSYS_THUNKS_OFF + GO_THUNK_STRIDE * (uint64_t)k; *to_thunk = go_branch(0x14000000u, (int64_t)thunk_v - (int64_t)site_v); *to_entry = go_branch(0x94000000u, (int64_t)(cave_v + GOSYS_ENTRY_OFF) - (int64_t)(thunk_v + 12)); *back = go_branch(0x14000000u, (int64_t)(site_v + 4) - (int64_t)(thunk_v + 24)); return *to_thunk && *to_entry && *back; } +static int go_links(uint64_t cave_v, const uint64_t *site_v, int sites, uint32_t *to_thunk, uint32_t *to_entry, uint32_t *back) { + if (!go_branches(cave_v, site_v[0], 0, &to_thunk[0], &to_entry[0], &back[0])) return 0; + for (int k = 1; k < sites; k++) + if (!go_branches(cave_v, site_v[k], k, &to_thunk[k], &to_entry[k], &back[k])) return 1; + return sites; +} + +static int go_write_sites(int wfd, const int64_t *site_off, const uint32_t *to_thunk, int sites) { + unsigned char word[4]; + for (int k = sites - 1; k >= 0; k--) { + wr32(word, to_thunk[k]); + if (go_pwrite_all(wfd, word, 4, (uint64_t)site_off[k]) != 0) return -1; + } + return 0; +} + // Adds the code to the program, or brings it up to date. Returns 1 when it changed the file, 0 when // there was nothing to do (not a Go program of a kind the code can serve, or already done), -1 when // the file could not be changed (it is started as it is). @@ -271,9 +297,11 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { if (n < 0) return -1; if (machine != EM_AARCH64 || (etype != GO_ET_EXEC && etype != GO_ET_DYN)) return 0; - int found = 0; - int64_t site_off = go_find_syscall6(fd, ph, n, &found); - if (found != 1) return 0; // not a Go of 1.19 or newer (or its function is not there once) + int64_t site_off[GO_QUIET_MAX + 1]; + if (go_find_calls(fd, ph, n, k_go_syscall6, GO_CMN_X0_4095, site_off, 1) != 1) return 0; // not a Go of 1.19 or newer (or its function is not there once) + int quiet = go_find_calls(fd, ph, n, k_go_raw_no_error, GO_STR_X0_SP40, site_off + 1, GO_QUIET_MAX); + if (quiet < 0) return -1; + int sites = 1 + (quiet <= GO_QUIET_MAX ? quiet : 0); // The loadable segments, by address int order[GO_MAX_PH], nl = 0; @@ -289,13 +317,16 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { if (nl < 2) return 0; // The call site must be in a segment that is mapped as code - uint64_t site_v = 0; - for (int i = 0; i < nl; i++) { - const struct go_ph *s = &ph[order[i]]; - if ((s->flags & GO_PF_X) && (uint64_t)site_off >= s->offset && (uint64_t)site_off < s->offset + s->filesz) - site_v = s->vaddr + ((uint64_t)site_off - s->offset); + uint64_t site_v[GO_QUIET_MAX + 1] = { 0 }; + for (int k = 0; k < sites; k++) { + for (int i = 0; i < nl; i++) { + const struct go_ph *s = &ph[order[i]]; + if ((s->flags & GO_PF_X) && (uint64_t)site_off[k] >= s->offset && (uint64_t)site_off[k] < s->offset + s->filesz) + site_v[k] = s->vaddr + ((uint64_t)site_off[k] - s->offset); + } + if (site_v[k] == 0) sites = k; } - if (site_v == 0) return 0; + if (sites == 0) return 0; struct gosys_hdr strings; memset(&strings, 0, sizeof(strings)); @@ -333,7 +364,7 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { if (wfd < 0) { rc = -1; } else { - rc = go_undo(wfd, ph, cave_seg, &tr, site_off); + rc = go_undo(wfd, ph, cave_seg, &tr, site_off, sites); changed = rc == 0; } } @@ -343,19 +374,20 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { if (cave_seg >= 0) { uint64_t cave_off = ph[cave_seg].offset + ph[cave_seg].filesz - tr.total_size; uint64_t cave_v = ph[cave_seg].vaddr + (cave_off - ph[cave_seg].offset); - int same = 0, site_ok = 0; - uint32_t to_thunk = 0, to_entry = 0, back = 0; + int same = 0, site_ok = 0, linked = 0; + uint32_t to_thunk[GO_QUIET_MAX + 1], to_entry[GO_QUIET_MAX + 1], back[GO_QUIET_MAX + 1]; // Is it what would be put there now? (the code of an older The native userland differs) if (tr.total_size == GOSYS_BLOB_SIZE && tr.rw_index < (uint32_t)n && ph[tr.rw_index].type == 1 && - go_branches(cave_v, site_v, &to_thunk, &to_entry, &back)) { + (linked = go_links(cave_v, site_v, sites, to_thunk, to_entry, back)) > 0) { uint64_t scratch_v = go_align_up(ph[tr.rw_index].vaddr + tr.rw_orig_memsz, 64); - go_build_image(img, &strings, cave_v, scratch_v, to_entry, back, &tr); + go_build_image(img, &strings, cave_v, scratch_v, to_entry, back, linked, &tr); same = pread(fd, have, GOSYS_BLOB_SIZE, (off_t)cave_off) == (ssize_t)GOSYS_BLOB_SIZE && memcmp(have, img, GOSYS_BLOB_SIZE) == 0 && ph[tr.rw_index].memsz == scratch_v - ph[tr.rw_index].vaddr + GOSYS_SCRATCH_SIZE; } unsigned char cur[4]; - site_ok = same && pread(fd, cur, 4, (off_t)site_off) == 4 && rd32(cur) == to_thunk; + site_ok = same; + for (int k = 0; k < linked && site_ok; k++) site_ok = pread(fd, cur, 4, (off_t)site_off[k]) == 4 && rd32(cur) == to_thunk[k]; if (same && site_ok) goto done; wfd = go_open_for_write(fd, st, path, &made_writable); @@ -365,13 +397,12 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { } if (same) { // The code is there, only the branch is not (a patch that was cut short) - wr32(word, to_thunk); - rc = go_pwrite_all(wfd, word, 4, (uint64_t)site_off); + rc = go_write_sites(wfd, site_off, to_thunk, linked); changed = rc == 0; goto done; } // An older code, or other strings: back to the plain program, then patch again - if (go_undo(wfd, ph, cave_seg, &tr, site_off) != 0) { + if (go_undo(wfd, ph, cave_seg, &tr, site_off, sites) != 0) { rc = -1; goto done; } @@ -394,7 +425,7 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { if (s->memsz != s->filesz || s->filesz == 0) continue; uint64_t v = go_align_up(s->vaddr + s->filesz, 64); uint64_t off = s->offset + (v - s->vaddr); - if (v + total > nx->vaddr || (nx->vaddr & 0x3fff) != 0) continue; + if (v + total > (nx->vaddr & ~0x3fffull)) continue; if (off + total > nx->offset || off + total > (uint64_t)st->st_size) continue; // Only padding may be written over uint64_t pad_from = s->offset + s->filesz, pad_len = off + total - pad_from; @@ -410,8 +441,9 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { } } int rw = order[nl - 1]; - uint32_t to_thunk = 0, to_entry = 0, back = 0; - if (text < 0 || !(ph[rw].flags & GO_PF_W) || rw == text || !go_branches(cave_v, site_v, &to_thunk, &to_entry, &back)) goto done; + uint32_t to_thunk[GO_QUIET_MAX + 1], to_entry[GO_QUIET_MAX + 1], back[GO_QUIET_MAX + 1]; + int linked = text < 0 ? 0 : go_links(cave_v, site_v, sites, to_thunk, to_entry, back); + if (text < 0 || !(ph[rw].flags & GO_PF_W) || rw == text || linked == 0) goto done; uint64_t scratch_v = go_align_up(ph[rw].vaddr + ph[rw].memsz, 64); struct gosys_trailer info; @@ -421,8 +453,8 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { info.rw_orig_memsz = ph[rw].memsz; info.text_index = (uint32_t)text; info.rw_index = (uint32_t)rw; - info.site_file_off = (uint64_t)site_off; - go_build_image(img, &strings, cave_v, scratch_v, to_entry, back, &info); + info.site_file_off = (uint64_t)site_off[0]; + go_build_image(img, &strings, cave_v, scratch_v, to_entry, back, linked, &info); wfd = go_open_for_write(fd, st, path, &made_writable); if (wfd < 0) { @@ -442,10 +474,7 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { wr32(word, ph[text].flags | GO_PF_X); rc = go_pwrite_all(wfd, word, 4, ph[text].pos + 4); } - if (rc == 0) { - wr32(word, to_thunk); - rc = go_pwrite_all(wfd, word, 4, (uint64_t)site_off); - } + if (rc == 0) rc = go_write_sites(wfd, site_off, to_thunk, linked); changed = rc == 0; done: diff --git a/tools/nativeguest/hook/static_programs.c b/tools/nativeguest/hook/static_programs.c index 406fca0da9..0e10cd6ad7 100644 --- a/tools/nativeguest/hook/static_programs.c +++ b/tools/nativeguest/hook/static_programs.c @@ -212,9 +212,15 @@ static int read_elf_phdrs(int fd, uint16_t *machine, struct ddnatv_phdr *ph, int static int elf_is_go(int fd, const struct ddnatv_phdr *ph, int n) { for (int i = 0; i < n; i++) { if (ph[i].type != 4 /* PT_NOTE */ || ph[i].filesz < 16) continue; - unsigned char note[16]; - if (pread(fd, note, sizeof(note), (off_t)ph[i].offset) != sizeof(note)) continue; - if (rd32(note) == 4 && memcmp(note + 12, "Go\0\0", 4) == 0) return 1; + for (uint64_t at = 0; at + 16 <= ph[i].filesz;) { + unsigned char note[16]; + if (pread(fd, note, sizeof(note), (off_t)(ph[i].offset + at)) != (ssize_t)sizeof(note)) break; + uint32_t namesz = rd32(note), descsz = rd32(note + 4); + if (namesz == 4 && memcmp(note + 12, "Go\0\0", 4) == 0) return 1; + uint64_t next = at + 12 + (((uint64_t)namesz + 3) & ~3ull) + (((uint64_t)descsz + 3) & ~3ull); + if (next <= at || next > ph[i].filesz) break; + at = next; + } } return 0; } diff --git a/tools/tests/test_native_hook_go_identity.py b/tools/tests/test_native_hook_go_identity.py new file mode 100644 index 0000000000..3ebc1d53df --- /dev/null +++ b/tools/tests/test_native_hook_go_identity.py @@ -0,0 +1,147 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" + +MAIN = r""" +package main + +import ( + "fmt" + "probe/quiet" + "syscall" +) + +func main() { + _, _, errno := syscall.RawSyscall(syscall.SYS_SETREUID, ^uintptr(0), 0, 0) + euid, _ := quiet.Call(syscall.SYS_GETEUID, 0, 0, 0) + fmt.Println(syscall.Getuid(), syscall.Getgid(), int(euid), errno == 0) +} +""" + +QUIET = """#include "textflag.h" + +TEXT ·Call(SB),NOSPLIT,$0-48 +\tMOVD\ta1+8(FP), R0 +\tMOVD\ta2+16(FP), R1 +\tMOVD\ta3+24(FP), R2 +\tMOVD\t$0, R3 +\tMOVD\t$0, R4 +\tMOVD\t$0, R5 +\tMOVD\ttrap+0(FP), R8 +\tSVC +\tMOVD\tR0, r1+32(FP) +\tMOVD\tR1, r2+40(FP) +\tRET +""" + +QUIET_GO = """package quiet + +func Call(trap, a1, a2, a3 uintptr) (r1, r2 uintptr) +""" + +CGO = """package main + +import "C" +""" + +LAUNCHER = r""" +#include <unistd.h> + +int main(int argc, char **argv) { + execv(argv[1], argv + 1); + return 0; +} +""" + + +class NativeHookGoIdentityTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + if not shutil.which("go"): + raise unittest.SkipTest("no Go toolchain") + cls.tmp = tempfile.TemporaryDirectory(dir="/tmp") + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "launcher.c").write_text(LAUNCHER) + cls.launcher = tmp / "launcher" + subprocess.run([cls.cc, "-O1", "-o", str(cls.launcher), str(tmp / "launcher.c")], check=True) + src = tmp / "src" + src.mkdir() + (src / "go.mod").write_text("module probe\n\ngo 1.19\n") + (src / "main.go").write_text(MAIN) + (src / "quiet").mkdir() + (src / "quiet/quiet.go").write_text(QUIET_GO) + (src / "quiet/quiet_arm64.s").write_text(QUIET) + (src / "cgo.go").write_text(CGO) + cls.root = tmp / "root" + (cls.root / "usr/bin").mkdir(parents=True) + cls.go_env = {**os.environ, "GOOS": "linux", "GOARCH": "arm64", "GOCACHE": str(tmp / "gocache"), + "GOPATH": str(tmp / "gopath"), "GOFLAGS": "-buildvcs=false", "GOTOOLCHAIN": "local"} + cls.static = cls.root / "usr/bin/go-static" + subprocess.run(["go", "build", "-o", str(cls.static), "."], cwd=src, check=True, capture_output=True, + env={**cls.go_env, "CGO_ENABLED": "0"}) + cls.dynamic = cls.root / "usr/bin/go-dynamic" + built = subprocess.run(["go", "build", "-o", str(cls.dynamic), "."], cwd=src, capture_output=True, + env={**cls.go_env, "CGO_ENABLED": "1", "CC": cls.cc}) + if built.returncode != 0: + cls.dynamic = None + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def prepare(self, program): + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")} + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} + if self.prefix: + cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] + else: + cmd = [] + env.update(hook_env) + subprocess.run(cmd + [str(self.launcher), str(program)], env=env, capture_output=True, timeout=120) + return b"CXGOSYS1" in program.read_bytes() + + def run_go(self, program): + cmd = list(self.prefix) + [str(program)] + result = subprocess.run(cmd, capture_output=True, text=True, timeout=120) + self.assertEqual(result.returncode, 0, result.stderr) + return result.stdout.split() + + def check_identity(self, program): + before = self.run_go(program) + if os.getuid() != 0: + self.assertNotEqual(before[0], "0") + self.assertEqual(before[3], "false") + self.assertTrue(self.prepare(program)) + self.assertEqual(self.run_go(program), ["0", "0", "0", "true"]) + moved = self.root.with_name("root-away") + self.root.rename(moved) + try: + away = self.run_go(moved / program.relative_to(self.root)) + finally: + moved.rename(self.root) + if os.getuid() != 0: + self.assertEqual(away, before) + + def test_static_go_program_sees_the_session_identity(self): + self.check_identity(self.static) + + def test_dynamic_go_program_sees_the_session_identity(self): + if self.dynamic is None: + self.skipTest("no cgo cross build") + self.check_identity(self.dynamic) + + +if __name__ == "__main__": + unittest.main() From f920aad1046aee9bf143272fc7861c5b5844aebd Mon Sep 17 00:00:00 2001 From: LunaDL <91587464+EnzoDLofi@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:19:42 -0400 Subject: [PATCH 106/141] Feat: toggle to show hud only in a game (#2970) * Add HUD visibility toggle for active games * Add HUD visibility translations for all languages * Fix HUD game visibility and Turkish strings * Support compositor-only HUD game detection * Fix HUD activity reconciliation and Steam focus * Clear stale Gamescope focus metadata * Clear stale Steam focus when metadata is unavailable * Prevent HUD flicker on metadata read failures * Prevent HUD visibility flicker * Fix HUD visibility during compositor activity * Fix HUD visibility during compositor activity * Prevent Steam SHM frames activating HUD * Fix HUD activity detection when Steam is focused * Remove HUD detection comments * Fix HUD game activity detection * Fix HUD compositor activity detection * Use Gamescope frames for HUD activity detection * Restore fullscreen SHM frame statistics callback * Restore fullscreen SHM frame statistics callback * Fix HUD SHM frame reporting * Prevent Steam focus from activating game-only HUD * Fix SHM frame freshness guard and test harness * Used suggestion code from rabbit * Ignore Steam UI frames for game-only HUD * Keep default HUD stats updating over Steam UI * Isolate Steam fallback frame statistics * Isolate Steam fallback frame statistics * Trigger HUD APK build --- app/src/main/cpp/waylandcomp/src/compositor.c | 17 +++++- .../cpp/waylandcomp/src/waylandcomp_jni.c | 9 +++ .../com/droiddeck/launcher/SessionActivity.kt | 4 ++ .../launcher/hud/DroidDeckHudHost.kt | 60 +++++++++++++++++-- .../com/droiddeck/launcher/hud/GameFrames.kt | 15 ++++- .../launcher/session/SessionPrefs.kt | 7 +++ .../launcher/ui/DroidDeckHudSettings.kt | 10 ++++ .../droiddeck/launcher/ui/SessionOverlay.kt | 1 + .../launcher/wayland/WaylandCompositor.java | 7 +++ app/src/main/res/values-ar/strings.xml | 2 + app/src/main/res/values-b+es+419/strings.xml | 2 + app/src/main/res/values-bg/strings.xml | 2 + app/src/main/res/values-cs/strings.xml | 2 + app/src/main/res/values-da/strings.xml | 2 + app/src/main/res/values-de/strings.xml | 2 + app/src/main/res/values-el/strings.xml | 2 + app/src/main/res/values-es/strings.xml | 2 + app/src/main/res/values-fi/strings.xml | 2 + app/src/main/res/values-fr/strings.xml | 2 + app/src/main/res/values-hi/strings.xml | 2 + app/src/main/res/values-hu/strings.xml | 2 + app/src/main/res/values-in/strings.xml | 2 + app/src/main/res/values-it/strings.xml | 2 + app/src/main/res/values-ja/strings.xml | 2 + app/src/main/res/values-ko/strings.xml | 2 + app/src/main/res/values-ms/strings.xml | 2 + app/src/main/res/values-nb/strings.xml | 2 + app/src/main/res/values-nl/strings.xml | 2 + app/src/main/res/values-pl/strings.xml | 2 + app/src/main/res/values-pt-rPT/strings.xml | 2 + app/src/main/res/values-pt/strings.xml | 2 + app/src/main/res/values-ro/strings.xml | 2 + app/src/main/res/values-ru/strings.xml | 2 + app/src/main/res/values-sv/strings.xml | 2 + app/src/main/res/values-th/strings.xml | 2 + app/src/main/res/values-tr/strings.xml | 2 + app/src/main/res/values-uk/strings.xml | 2 + app/src/main/res/values-vi/strings.xml | 2 + app/src/main/res/values-zh-rCN/strings.xml | 2 + app/src/main/res/values-zh-rHK/strings.xml | 2 + app/src/main/res/values-zh-rTW/strings.xml | 2 + app/src/main/res/values/strings.xml | 4 ++ tools/tests/vk_terminal_callers_test.c | 3 +- 43 files changed, 190 insertions(+), 11 deletions(-) diff --git a/app/src/main/cpp/waylandcomp/src/compositor.c b/app/src/main/cpp/waylandcomp/src/compositor.c index 38c13055be..461a0d6798 100644 --- a/app/src/main/cpp/waylandcomp/src/compositor.c +++ b/app/src/main/cpp/waylandcomp/src/compositor.c @@ -737,6 +737,11 @@ static void describe(const struct surface *s, char *out, size_t size) { else snprintf(out, size, "window %#x (%s)", w->hwnd, prog); } +static int is_steam_client_surface(const struct surface *s) { + const char *name = client_name(wl_resource_get_client(s->resource)); + return strcmp(name, "steam") == 0 || strstr(name, "steamwebhelper") != NULL; +} + static struct surface *toplevel_by_hwnd(uint32_t hwnd) { struct surface *s; wl_list_for_each(s, &g_toplevels, toplevel_link) @@ -894,6 +899,7 @@ int droiddeck_hud_frame_times(float *out, int len, int64_t *total) { static uint64_t g_game_frames; extern void droiddeck_on_game_surface(const char *window, const char *gpu); extern void droiddeck_on_game_frame(void); +extern void droiddeck_on_compositor_frame(void); extern void droiddeck_on_content_rate(int fps); static int64_t g_cadence_ns; static int64_t g_cadence_frames; @@ -949,9 +955,10 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res g_hud_shm = s; g_hud_shm_ns = now; g_hud_new = 1; - droiddeck_on_game_frame(); } } + if (s == g_hud_shm && (!g_hud_surface || now_ns() - g_hud_last_ns > 1000000000LL)) + droiddeck_on_compositor_frame(); } static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resource *buffer) { @@ -1025,7 +1032,8 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re droiddeck_log("error", "could not import GPU frames from %s (%dx%d, modifier %#llx)", name, b->width, b->height, (unsigned long long)b->modifier); } - if (s != g_hud_surface && (b->img || ahb_swapchain_has_ahb(b)) && + if (s != g_hud_surface && !is_steam_client_surface(s) && + (b->img || ahb_swapchain_has_ahb(b)) && (!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL || (!repeat && below_surface(s, g_hud_surface)) || (announced_now && !below_surface(g_hud_surface, s) && (int64_t)b->width * b->height >= (int64_t)g_hud_surface->buf_w * g_hud_surface->buf_h))) { @@ -1050,9 +1058,12 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re : "the compositor's driver could NOT import it (nothing can show it)"); s->hdr_fmt_logged = b->format; } - if (s == g_hud_surface) { + if (s == g_hud_surface && !is_steam_client_surface(s)) { g_hud_alive_ns = now_ns(); if (!repeat) { g_hud_last_ns = g_hud_alive_ns; g_hud_fresh = 1; g_hud_new = 1; g_game_frames++; note_game_frame_gap(); droiddeck_on_game_frame(); } + } else if (is_steam_client_surface(s) && !repeat && + (!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL)) { + droiddeck_on_compositor_frame(); } } diff --git a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c index 4dc2f2c08c..308332f9b1 100644 --- a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c +++ b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c @@ -63,6 +63,7 @@ static jclass g_compositor_cls; static jmethodID g_on_first_frame; static jmethodID g_on_game_surface; static jmethodID g_on_game_frame; +static jmethodID g_on_compositor_frame; static jmethodID g_on_game_program; static jmethodID g_on_pointer_lock; static jmethodID g_on_clipboard; @@ -84,6 +85,7 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { g_on_game_surface = (*env)->GetStaticMethodID(env, g_compositor_cls, "onGameSurface", "(Ljava/lang/String;Ljava/lang/String;)V"); g_on_game_frame = (*env)->GetStaticMethodID(env, g_compositor_cls, "onGameFrame", "()V"); + g_on_compositor_frame = (*env)->GetStaticMethodID(env, g_compositor_cls, "onCompositorFrame", "()V"); g_on_game_program = (*env)->GetStaticMethodID(env, g_compositor_cls, "onGameProgram", "(ILjava/lang/String;)V"); if ((*env)->ExceptionCheck(env)) { (*env)->ExceptionClear(env); g_on_game_program = NULL; } @@ -154,6 +156,13 @@ void droiddeck_on_game_frame(void) { if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env); } +void droiddeck_on_compositor_frame(void) { + JNIEnv *env; + if (!g_compositor_cls || !g_on_compositor_frame || !(env = thread_env())) return; + (*env)->CallStaticVoidMethod(env, g_compositor_cls, g_on_compositor_frame); + if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env); +} + void droiddeck_on_refresh_target(int refresh, int frame_rate) { JNIEnv *env; if (!g_compositor_cls || !g_on_refresh_target || !(env = thread_env())) return; diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 7fef8a136c..556606b77a 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -1545,6 +1545,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde secondScreenDisplays = secondScreenDisplays, selectedSecondScreenDisplay = selectedSecondScreenDisplay, onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() }, + onHudOnlyDuringGame = { on -> + SessionPrefs.setHudOnlyDuringGame(this@SessionActivity, on) + hud.refresh() + }, onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this@SessionActivity, on) gpuClockPin = on diff --git a/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudHost.kt b/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudHost.kt index 59f8a5e6eb..7a96f0b6ac 100644 --- a/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudHost.kt @@ -44,6 +44,35 @@ class DroidDeckHudHost(context: Context) { private var protonPid = 0 private var proton = "" @Volatile private var lastWindow: String? = null + @Volatile private var lastCompositorFrameNanos = 0L + @Volatile private var lastVisibilityGameActive = false + private var candidateGameActive = false + private var candidateGameActiveSinceNs = 0L + private var stableGameActive = false + + private fun isGameActive(): Boolean { + val now = System.nanoTime() + val compositorLive = lastCompositorFrameNanos > 0L && + now - lastCompositorFrameNanos <= 1_000_000_000L + val detected = if (feed.live) { + feed.steamFocusKnown && !feed.steamFocused + } else { + compositorLive + } + + if (detected != candidateGameActive) { + candidateGameActive = detected + candidateGameActiveSinceNs = now + } + + if (detected != stableGameActive && + now - candidateGameActiveSinceNs >= GAME_ACTIVITY_STABLE_NS + ) { + stableGameActive = detected + } + + return stableGameActive + } var onPresentingWindowChanged: (() -> Unit)? = null @@ -66,6 +95,12 @@ class DroidDeckHudHost(context: Context) { } override fun onGameFrame() { + if (feed.live && (!feed.steamFocusKnown || feed.steamFocused)) return + lastCompositorFrameNanos = System.nanoTime() + feed.onCompositorFrame(lastCompositorFrameNanos) + } + + override fun onCompositorFrame() { feed.onCompositorFrame(System.nanoTime()) } } @@ -73,7 +108,9 @@ class DroidDeckHudHost(context: Context) { private val frameCallback = object : Choreographer.FrameCallback { override fun doFrame(frameTimeNanos: Long) { if (!running || !polling) return + reconcileGameActivity() if (feed.poll(System.nanoTime())) view?.onFrames() + reconcileGameActivity() Choreographer.getInstance().postFrameCallback(this) } } @@ -151,7 +188,7 @@ class DroidDeckHudHost(context: Context) { fun refresh() { applyConfig() - if (!enabled) stop() else if (!running) start() + if (!enabled) stop() else if (!running) start() else applyShown() } fun start() { @@ -181,14 +218,26 @@ class DroidDeckHudHost(context: Context) { applyShown() } + private fun reconcileGameActivity() { + if (!SessionPrefs.hudOnlyDuringGame(context)) { + lastVisibilityGameActive = isGameActive() + return + } + if (isGameActive() != lastVisibilityGameActive) applyShown() + } + private fun applyShown() { if (!running) return - val show = !hidden && !backgrounded + val onlyDuringGame = SessionPrefs.hudOnlyDuringGame(context) + val gameActive = isGameActive() + val show = !hidden && !backgrounded && (!onlyDuringGame || gameActive) view?.visibility = if (show) View.VISIBLE else View.GONE showing = show - if (show != polling) { - polling = show - if (show) Choreographer.getInstance().postFrameCallback(frameCallback) + lastVisibilityGameActive = gameActive + val shouldPoll = !hidden && !backgrounded && (show || onlyDuringGame) + if (shouldPoll != polling) { + polling = shouldPoll + if (shouldPoll) Choreographer.getInstance().postFrameCallback(frameCallback) else Choreographer.getInstance().removeFrameCallback(frameCallback) } } @@ -532,6 +581,7 @@ class DroidDeckHudHost(context: Context) { } companion object { + private const val GAME_ACTIVITY_STABLE_NS = 350_000_000L private const val DOCK_OVERHANG = 0.4f private const val PREVIEW_FROM = 0.55f private const val STRIP_PULL_ACROSS_DP = 360f diff --git a/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt b/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt index 3c996a03f0..e8967d944d 100644 --- a/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt +++ b/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt @@ -183,6 +183,8 @@ internal class GameFrameFeed( private set @Volatile var steamFocused = false private set + @Volatile var steamFocusKnown = false + private set @Volatile var pid = 0 private set @Volatile var outputWidth = 0 @@ -198,10 +200,16 @@ internal class GameFrameFeed( val compositorAdded = compositorFrames != seenCompositorFrames seenCompositorFrames = compositorFrames if (handle == 0L) { - if (nowNs < nextOpenNs) return compositorAdded + if (nowNs < nextOpenNs) { + + return compositorAdded + } nextOpenNs = nowNs + REOPEN_NS handle = runCatching { HudFrames.nativeOpen(file.path) }.getOrDefault(0L) - if (handle == 0L) return compositorAdded + if (handle == 0L) { + + return compositorAdded + } HudFrames.nativePoll(handle, frametimes, times) } val n = HudFrames.nativePoll(handle, frametimes, times) @@ -219,6 +227,7 @@ internal class GameFrameFeed( fromGamescope = false } if (n <= 0 && nowNs - maxOf(lastRingFrameNs, nextOpenNs - REOPEN_NS) > STALE_NS) close() + if (nowNs - lastInfoNs >= INFO_NS) { lastInfoNs = nowNs readInfo() @@ -250,6 +259,7 @@ internal class GameFrameFeed( } fun close() { + fromGamescope = false if (handle != 0L) HudFrames.nativeClose(handle) handle = 0L } @@ -265,6 +275,7 @@ internal class GameFrameFeed( outputHeight = info[2] refreshMilliHz = info[3] steamFocused = info[4] != 0 + steamFocusKnown = true engine = engineLabel(name) } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 422db659f6..9645c411cc 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -502,6 +502,13 @@ object SessionPrefs { fun hudEnabled(context: Context): Boolean = prefs(context).getBoolean(hudKey(context), false) + fun hudOnlyDuringGame(context: Context): Boolean = + prefs(context).getBoolean("hudOnlyDuringGame", false) + + fun setHudOnlyDuringGame(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("hudOnlyDuringGame", on).apply() + } + fun setHudEnabled(context: Context, on: Boolean) { prefs(context).edit().putBoolean(hudKey(context), on).apply() } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DroidDeckHudSettings.kt b/app/src/main/java/com/droiddeck/launcher/ui/DroidDeckHudSettings.kt index 5e86cf489e..d14086ffc5 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DroidDeckHudSettings.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DroidDeckHudSettings.kt @@ -21,11 +21,21 @@ import com.droiddeck.launcher.session.StripMetric @Composable internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) { val cfg = a.hudConfig + val context = LocalContext.current + var onlyDuringGame by remember { mutableStateOf(SessionPrefs.hudOnlyDuringGame(context)) } fun on(key: String) = cfg[key] == "1" fun int(key: String, fallback: Int) = cfg[key]?.toIntOrNull() ?: fallback SettingsGroup(stringResource(R.string.drawer_hud)) { ToggleRow(host, "hud", stringResource(R.string.drawer_hud), null, a.hudOn, chipModifier = track("hud"), onChange = a.onHud) + if (a.hudOn) ToggleRow( + host, "hud-only-during-game", stringResource(R.string.hud_only_during_game), + stringResource(R.string.hud_only_during_game_hint), onlyDuringGame, + chipModifier = track("hud-only-during-game") + ) { on -> + onlyDuringGame = on + a.onHudOnlyDuringGame(on) + } if (!a.hudOn) return@SettingsGroup val size = DroidDeckHudSize.from(cfg["hudSize"]) ChoiceRow(host, "hud-size", stringResource(R.string.hud_size), stringResource(R.string.hud_size_hint), diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index 401ca5face..ae1dd01b77 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -283,6 +283,7 @@ class DrawerActions( val secondScreenDisplays: List<SecondScreenDisplay>, val selectedSecondScreenDisplay: Int, val onHud: (Boolean) -> Unit, + val onHudOnlyDuringGame: (Boolean) -> Unit = {}, val onHudSetting: (String, String) -> Unit = { _, _ -> }, val onGpuClockPin: (Boolean) -> Unit = {}, val onHudOrder: (Map<String, Boolean>, List<String>) -> Unit = { _, _ -> }, diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java index 81543e6d1c..4e824f6dba 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java +++ b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java @@ -26,6 +26,7 @@ public final class WaylandCompositor { public interface GameListener { void onGameSurface(String window, String gpuName); void onGameFrame(); + default void onCompositorFrame() {} default void onGameProgram(int pid, String program) {} } @@ -70,6 +71,12 @@ public final class WaylandCompositor { if (l != null) l.onGameFrame(); } + @SuppressWarnings("unused") + static void onCompositorFrame() { + GameListener l = gameListener; + if (l != null) l.onCompositorFrame(); + } + @SuppressWarnings("unused") static void onGameProgram(int pid, String program) { GameListener l = gameListener; diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 36430b35d4..c87512c701 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -4237,4 +4237,6 @@ <string name="theme_custom_signal">الإبرازات</string> <string name="theme_custom_good">نجاح</string> <string name="theme_custom_error">خطأ</string> + <string name="hud_only_during_game">عرض HUD أثناء اللعب فقط</string> + <string name="hud_only_during_game_hint">إخفاء HUD عند عدم اكتشاف إطارات اللعبة.</string> </resources> diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index abb112b05f..ef65eef2f4 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -4117,4 +4117,6 @@ <string name="theme_custom_signal">Destacados</string> <string name="theme_custom_good">Éxito</string> <string name="theme_custom_error">Error</string> + <string name="hud_only_during_game">Mostrar el HUD solo durante una partida</string> + <string name="hud_only_during_game_hint">Ocultar el HUD cuando no se detecten fotogramas del juego.</string> </resources> diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index 6efc4eff37..c6bd2d6bb4 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -4077,4 +4077,6 @@ <string name="theme_custom_signal">Акценти</string> <string name="theme_custom_good">Успех</string> <string name="theme_custom_error">Грешка</string> + <string name="hud_only_during_game">Показвай HUD само по време на игра</string> + <string name="hud_only_during_game_hint">Скривай HUD, когато не се засичат кадри от играта.</string> </resources> diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 9e689b9291..27f25f40eb 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -4157,4 +4157,6 @@ <string name="theme_custom_signal">Zvýraznění</string> <string name="theme_custom_good">Úspěch</string> <string name="theme_custom_error">Chyba</string> + <string name="hud_only_during_game">Zobrazovat HUD pouze během hry</string> + <string name="hud_only_during_game_hint">Skrýt HUD, když nejsou detekovány snímky hry.</string> </resources> diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 202d607a56..c2027f4344 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -4077,4 +4077,6 @@ <string name="theme_custom_signal">Fremhævninger</string> <string name="theme_custom_good">Succes</string> <string name="theme_custom_error">Fejl</string> + <string name="hud_only_during_game">Vis kun HUD under spil</string> + <string name="hud_only_during_game_hint">Skjul HUD, når der ikke registreres spilbilleder.</string> </resources> diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 13c2bee2f1..ae9f0288dc 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -4077,4 +4077,6 @@ <string name="theme_custom_signal">Hervorhebungen</string> <string name="theme_custom_good">Erfolg</string> <string name="theme_custom_error">Fehler</string> + <string name="hud_only_during_game">HUD nur während eines Spiels anzeigen</string> + <string name="hud_only_during_game_hint">HUD ausblenden, wenn keine Spielframes erkannt werden.</string> </resources> diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index e77d35a7e1..d20cee1822 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -4077,4 +4077,6 @@ <string name="theme_custom_signal">Επισημάνσεις</string> <string name="theme_custom_good">Επιτυχία</string> <string name="theme_custom_error">Σφάλμα</string> + <string name="hud_only_during_game">Εμφάνιση HUD μόνο κατά τη διάρκεια παιχνιδιού</string> + <string name="hud_only_during_game_hint">Απόκρυψη HUD όταν δεν ανιχνεύονται καρέ παιχνιδιού.</string> </resources> diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index ee13434fb1..c387ac6ef1 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -4117,4 +4117,6 @@ <string name="theme_custom_signal">Destacados</string> <string name="theme_custom_good">Éxito</string> <string name="theme_custom_error">Error</string> + <string name="hud_only_during_game">Mostrar el HUD solo durante una partida</string> + <string name="hud_only_during_game_hint">Ocultar el HUD cuando no se detecten fotogramas del juego.</string> </resources> diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 9a29a70aa0..745c743f15 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -4077,4 +4077,6 @@ <string name="theme_custom_signal">Korostukset</string> <string name="theme_custom_good">Onnistuminen</string> <string name="theme_custom_error">Virhe</string> + <string name="hud_only_during_game">Näytä HUD vain pelin aikana</string> + <string name="hud_only_during_game_hint">Piilota HUD, kun pelin ruutuja ei havaita.</string> </resources> diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 7f06925d9c..0ea39e6371 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -4116,4 +4116,6 @@ <string name="theme_custom_signal">Mises en évidence</string> <string name="theme_custom_good">Succès</string> <string name="theme_custom_error">Erreur</string> + <string name="hud_only_during_game">Afficher le HUD uniquement pendant une partie</string> + <string name="hud_only_during_game_hint">Masquer le HUD lorsqu’aucune image du jeu n’est détectée.</string> </resources> diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 0edc2352e2..748ae53427 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -4077,4 +4077,6 @@ <string name="theme_custom_signal">हाइलाइट</string> <string name="theme_custom_good">सफलता</string> <string name="theme_custom_error">त्रुटि</string> + <string name="hud_only_during_game">HUD केवल गेम के दौरान दिखाएँ</string> + <string name="hud_only_during_game_hint">गेम के फ़्रेम का पता न चलने पर HUD छिपाएँ।</string> </resources> diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 3f5cb395ab..b941ca7036 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -4077,4 +4077,6 @@ <string name="theme_custom_signal">Kiemelések</string> <string name="theme_custom_good">Siker</string> <string name="theme_custom_error">Hiba</string> + <string name="hud_only_during_game">HUD megjelenítése csak játék közben</string> + <string name="hud_only_during_game_hint">HUD elrejtése, ha nem észlelhetők játék képkockái.</string> </resources> diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 6f1b647f52..a64e7a8f82 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -4047,4 +4047,6 @@ <string name="theme_custom_signal">Sorotan</string> <string name="theme_custom_good">Berhasil</string> <string name="theme_custom_error">Kesalahan</string> + <string name="hud_only_during_game">Tampilkan HUD hanya saat bermain</string> + <string name="hud_only_during_game_hint">Sembunyikan HUD saat tidak ada frame game yang terdeteksi.</string> </resources> diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 0473d4aa17..917a683301 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -4116,4 +4116,6 @@ <string name="theme_custom_signal">Evidenziazioni</string> <string name="theme_custom_good">Successo</string> <string name="theme_custom_error">Errore</string> + <string name="hud_only_during_game">Mostra l’HUD solo durante il gioco</string> + <string name="hud_only_during_game_hint">Nascondi l’HUD quando non vengono rilevati fotogrammi del gioco.</string> </resources> diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index c4f0e9b7db..83165c7ccc 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -4047,4 +4047,6 @@ <string name="theme_custom_signal">強調表示</string> <string name="theme_custom_good">成功</string> <string name="theme_custom_error">エラー</string> + <string name="hud_only_during_game">ゲーム中のみHUDを表示</string> + <string name="hud_only_during_game_hint">ゲームのフレームが検出されないときはHUDを非表示にする。</string> </resources> diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 132894ed53..975138121c 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -4047,4 +4047,6 @@ <string name="theme_custom_signal">강조 표시</string> <string name="theme_custom_good">성공</string> <string name="theme_custom_error">오류</string> + <string name="hud_only_during_game">게임 중에만 HUD 표시</string> + <string name="hud_only_during_game_hint">게임 프레임이 감지되지 않으면 HUD 숨기기.</string> </resources> diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index 4acd4c0156..c2a3e5634b 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -4047,4 +4047,6 @@ <string name="theme_custom_signal">Sorotan</string> <string name="theme_custom_good">Berjaya</string> <string name="theme_custom_error">Ralat</string> + <string name="hud_only_during_game">Paparkan HUD hanya semasa bermain</string> + <string name="hud_only_during_game_hint">Sembunyikan HUD apabila bingkai permainan tidak dikesan.</string> </resources> diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index 9922d36712..9e7c805abb 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -4077,4 +4077,6 @@ <string name="theme_custom_signal">Uthevinger</string> <string name="theme_custom_good">Suksess</string> <string name="theme_custom_error">Feil</string> + <string name="hud_only_during_game">Vis HUD bare mens du spiller</string> + <string name="hud_only_during_game_hint">Skjul HUD når ingen spillbilder registreres.</string> </resources> diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 719c86894a..7387841e29 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -4077,4 +4077,6 @@ <string name="theme_custom_signal">Accenten</string> <string name="theme_custom_good">Geslaagd</string> <string name="theme_custom_error">Fout</string> + <string name="hud_only_during_game">HUD alleen tijdens een game weergeven</string> + <string name="hud_only_during_game_hint">Verberg de HUD wanneer er geen gameframes worden gedetecteerd.</string> </resources> diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 25a9f59672..39ed9658ef 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -4157,4 +4157,6 @@ <string name="theme_custom_signal">Wyróżnienia</string> <string name="theme_custom_good">Sukces</string> <string name="theme_custom_error">Błąd</string> + <string name="hud_only_during_game">Pokazuj HUD tylko podczas gry</string> + <string name="hud_only_during_game_hint">Ukryj HUD, gdy nie wykryto klatek gry.</string> </resources> diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 42e604bfaa..b4202d6bef 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -4116,4 +4116,6 @@ <string name="display_scaling_integer">Inteiro</string> <string name="display_scaling_fit">Ajustar</string> <string name="drawer_antialiasing">Suavização de serrilhado</string> + <string name="hud_only_during_game">Mostrar o HUD apenas durante um jogo</string> + <string name="hud_only_during_game_hint">Ocultar o HUD quando não forem detetados fotogramas do jogo.</string> </resources> diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 00b2f03508..be543f1960 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -4124,4 +4124,6 @@ <string name="display_scaling_integer">Inteiro</string> <string name="display_scaling_fit">Ajustar</string> <string name="drawer_antialiasing">Suavização de serrilhado</string> + <string name="hud_only_during_game">Mostrar o HUD somente durante o jogo</string> + <string name="hud_only_during_game_hint">Ocultar o HUD quando nenhum quadro do jogo for detectado.</string> </resources> diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index 3e3e6e6aaa..a56231bf01 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -4117,4 +4117,6 @@ <string name="theme_custom_signal">Evidențieri</string> <string name="theme_custom_good">Succes</string> <string name="theme_custom_error">Eroare</string> + <string name="hud_only_during_game">Afișează HUD-ul doar în timpul jocului</string> + <string name="hud_only_during_game_hint">Ascunde HUD-ul când nu sunt detectate cadre ale jocului.</string> </resources> diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 3327a46be1..5ab0146628 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -4157,4 +4157,6 @@ <string name="theme_custom_signal">Выделения</string> <string name="theme_custom_good">Успех</string> <string name="theme_custom_error">Ошибка</string> + <string name="hud_only_during_game">Показывать HUD только во время игры</string> + <string name="hud_only_during_game_hint">Скрывать HUD, когда кадры игры не обнаруживаются.</string> </resources> diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 7793dcc901..52148d23fa 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -4077,4 +4077,6 @@ <string name="theme_custom_signal">Markeringar</string> <string name="theme_custom_good">Lyckades</string> <string name="theme_custom_error">Fel</string> + <string name="hud_only_during_game">Visa HUD endast under spel</string> + <string name="hud_only_during_game_hint">Dölj HUD när inga spelbildrutor upptäcks.</string> </resources> diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 6f7186b7b8..c3fdeeaecd 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -4047,4 +4047,6 @@ <string name="theme_custom_signal">จุดเน้น</string> <string name="theme_custom_good">สำเร็จ</string> <string name="theme_custom_error">ข้อผิดพลาด</string> + <string name="hud_only_during_game">แสดง HUD เฉพาะขณะเล่นเกม</string> + <string name="hud_only_during_game_hint">ซ่อน HUD เมื่อไม่พบเฟรมของเกม</string> </resources> diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index cfa1424b2e..caf7177e66 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -4077,4 +4077,6 @@ <string name="theme_custom_signal">Vurgular</string> <string name="theme_custom_good">Başarılı</string> <string name="theme_custom_error">Hata</string> + <string name="hud_only_during_game">HUD\'yi yalnızca oyun sırasında göster</string> + <string name="hud_only_during_game_hint">Oyun kareleri algılanmadığında HUD\'yi gizle.</string> </resources> diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 378f1aaf1a..866823452d 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -4157,4 +4157,6 @@ <string name="theme_custom_signal">Виділення</string> <string name="theme_custom_good">Успіх</string> <string name="theme_custom_error">Помилка</string> + <string name="hud_only_during_game">Показувати HUD лише під час гри</string> + <string name="hud_only_during_game_hint">Приховувати HUD, коли кадри гри не виявляються.</string> </resources> diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 3f1ed9d6bc..d59ef76086 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -4047,4 +4047,6 @@ <string name="theme_custom_signal">Điểm nhấn</string> <string name="theme_custom_good">Thành công</string> <string name="theme_custom_error">Lỗi</string> + <string name="hud_only_during_game">Chỉ hiển thị HUD khi đang chơi</string> + <string name="hud_only_during_game_hint">Ẩn HUD khi không phát hiện khung hình trò chơi.</string> </resources> diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 246333f875..36465dc7c6 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -4047,4 +4047,6 @@ <string name="theme_custom_signal">高亮</string> <string name="theme_custom_good">成功</string> <string name="theme_custom_error">错误</string> + <string name="hud_only_during_game">仅在游戏期间显示 HUD</string> + <string name="hud_only_during_game_hint">未检测到游戏帧时隐藏 HUD。</string> </resources> diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 8c7484f22d..0a476b26f1 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -4047,4 +4047,6 @@ <string name="theme_custom_signal">重點標示</string> <string name="theme_custom_good">成功</string> <string name="theme_custom_error">錯誤</string> + <string name="hud_only_during_game">只在遊戲期間顯示 HUD</string> + <string name="hud_only_during_game_hint">未偵測到遊戲畫面時隱藏 HUD。</string> </resources> diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index fa10f937d0..9836945224 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -4047,4 +4047,6 @@ <string name="theme_custom_signal">醒目標示</string> <string name="theme_custom_good">成功</string> <string name="theme_custom_error">錯誤</string> + <string name="hud_only_during_game">僅在遊戲期間顯示 HUD</string> + <string name="hud_only_during_game_hint">未偵測到遊戲畫面時隱藏 HUD。</string> </resources> diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index f6c126ca1e..3837d5f16f 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -4380,6 +4380,10 @@ <string name="onboarding_steam_failed">The Steam client download will retry</string> <string name="onboarding_limit_reason">Android can close Steam’s helper processes. Turn that off now, while the downloads run, and Play is ready the moment they finish.</string> <string name="onboarding_limit_action">Do it for me</string> + <string name="onboarding_limit_while_waiting">Set up while you wait</string> + <string name="onboarding_chip">Getting ready · %1$d%% · %2$s</string> + <string name="hud_only_during_game">Show HUD only during a game</string> + <string name="hud_only_during_game_hint">Hide the HUD when no game frames are detected.</string> <string name="onboarding_button_getting_ready">Getting ready · %1$d%%</string> <string name="onboarding_button_finish">Finish setup · %1$d%%</string> </resources> diff --git a/tools/tests/vk_terminal_callers_test.c b/tools/tests/vk_terminal_callers_test.c index ebf8fbf096..374c049a6f 100644 --- a/tools/tests/vk_terminal_callers_test.c +++ b/tools/tests/vk_terminal_callers_test.c @@ -123,7 +123,8 @@ static int64_t now_ns(void) { return 0; } static struct surface *g_hud_surface, *g_hud_shm; static int64_t g_hud_shm_ns, g_hud_last_ns; static int g_hud_new; -static void droiddeck_on_game_frame(void) {} +static void __attribute__((unused)) droiddeck_on_game_frame(void) {} +static void __attribute__((unused)) droiddeck_on_compositor_frame(void) {} struct client_info { int asked_feedback, shm_frames; }; struct wl_shm_buffer { int w, h, stride; const void *data; }; #define WL_SHM_FORMAT_ARGB8888 0 From 9db80cebd9607fe359b38f5b3ac83aa5420789e8 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:26:23 -0500 Subject: [PATCH 107/141] chore: add EnzoDLofi to trusted-test-builds.txt (#3156) --- .github/trusted-test-builds.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/trusted-test-builds.txt b/.github/trusted-test-builds.txt index 4f94e6c268..99d73b6ac9 100644 --- a/.github/trusted-test-builds.txt +++ b/.github/trusted-test-builds.txt @@ -6,3 +6,4 @@ KeegantheVeganat0r kingokksa ovurrsl KeegantheVeganat0r +EnzoDLofi From 2e3b69e9ff2e275172f6c226966b159430af8c25 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:18:41 -0500 Subject: [PATCH 108/141] perf(steam): setup applies Steam's client update so the first launch has nothing to unpack (#3152) * perf(steam): setup applies Steam's client update itself so the first launch has nothing to unpack The setup already downloads every package of Steam's client update. droiddeck-steam-preapply now extracts them and writes the .installed and .manifest records the way Steam's updater does, so the first launch verifies and starts instead of unpacking for about half a minute and restarting. When it cannot, the packages stay and Steam updates itself as before. * perf(setup): the Steam stage skips the plain packages it just applied, and Proton's install trusts the prefetch's checksum With the whole client update applied from the cached packages, the separate 362 MB plain-package install is redundant: the cache pass applies the update and finishes the install, and the plain install stays as the fallback. DroidDeck Proton's archive was hashed twice more at install time after the prefetch had already verified it; the install now reuses that result while the file is unchanged. * fix(steam): a failed or cancelled apply leaves nothing stale, extraction stays inside the Steam root, and a cache failure still installs A failed apply removes its record and the cache marker so the next run retries; cancelling stops the helper; entries that leave the Steam root, directly or through a symlink, are refused; the plain install still runs when the cache pass fails; Proton's install reuses the prefetch's verification only for the same digest. * fix(steam): a cancelled apply clears the cache marker too --- .../launcher/session/ProtonExtras.kt | 14 +- .../launcher/session/SessionFiles.kt | 1 + .../launcher/session/SteamClientPrefetch.kt | 8 +- .../usr/local/bin/droiddeck-steam-install | 21 ++- .../usr/local/bin/droiddeck-steam-preapply | 92 ++++++++++ tools/tests/test_steam_install.py | 84 ++++++++++ tools/tests/test_steam_preapply.py | 157 ++++++++++++++++++ 7 files changed, 369 insertions(+), 8 deletions(-) create mode 100755 tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-preapply create mode 100644 tools/tests/test_steam_preapply.py diff --git a/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt b/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt index f5a01d984d..c68ecd3ba1 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt @@ -25,6 +25,10 @@ object ProtonExtras { var installInProgress = false @Volatile var prefetching = false private set + @Volatile private var checkedArchive: Triple<String, Long, Long>? = null + @Volatile private var checkedDigest: String? = null + + private fun fingerprint(archive: File) = Triple(archive.path, archive.length(), archive.lastModified()) @Volatile private var replacing = false @@ -259,7 +263,10 @@ object ProtonExtras { 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) + val problem = fetchArchive(context, tool, asset, archive, onProgress) + checkedArchive = if (problem == null && asset.sha256 != null && asset.size > 0 && archive.length() == asset.size) fingerprint(archive) else null + checkedDigest = if (checkedArchive != null) asset.sha256 else null + return problem } private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? { @@ -275,7 +282,9 @@ object ProtonExtras { return context.getString(R.string.pextra_no_space, tool.name) } - fetchArchive(context, tool, asset, archive, onProgress)?.let { return it } + val checked = asset.sha256 != null && asset.size > 0 && checkedArchive == fingerprint(archive) && + checkedDigest.equals(asset.sha256, ignoreCase = true) + if (!checked) fetchArchive(context, tool, asset, archive, onProgress)?.let { return it } if (asset.size > 0 && archive.length() != asset.size) { if (archive.length() > asset.size) { archive.delete() @@ -286,6 +295,7 @@ object ProtonExtras { onProgress(context.getString(R.string.pextra_verifying), -1) val verified = when { + checked -> true asset.sha256 != null -> asset.sha256.equals(Hashes.sha256(archive), ignoreCase = true) asset.sha512 != null -> { val expected = Downloader.downloadDirect(asset.sha512)?.let { Regex("(?i)\\b[0-9a-f]{128}\\b").find(it)?.value } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index 9ec5f5cba4..101e413933 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -130,6 +130,7 @@ object SessionFiles { "usr/local/bin/droiddeck-desktop-clipboard" to "usr/local/bin/droiddeck-desktop-clipboard", "usr/local/bin/droiddeck-gpu-window" to "usr/local/bin/droiddeck-gpu-window", "usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install", + "usr/local/bin/droiddeck-steam-preapply" to "usr/local/bin/droiddeck-steam-preapply", "usr/local/bin/droiddeck-steam-ui-scale" to "usr/local/bin/droiddeck-steam-ui-scale", "usr/local/bin/droiddeck-steam-language" to "usr/local/bin/droiddeck-steam-language", "usr/local/bin/droiddeck-steam-shaders" to "usr/local/bin/droiddeck-steam-shaders", diff --git a/app/src/main/java/com/droiddeck/launcher/session/SteamClientPrefetch.kt b/app/src/main/java/com/droiddeck/launcher/session/SteamClientPrefetch.kt index 66db50355a..8f96cf7a4e 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SteamClientPrefetch.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SteamClientPrefetch.kt @@ -71,11 +71,9 @@ object SteamClientPrefetch { 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) + val cacheProblem = script(context, listOf("--cache"), label, 0, if (install) 90 else 100) + if (cacheProblem == CANCELLED || !install) return cacheProblem + return script(context, emptyList(), label, 90, 100) } private fun script(context: Context, args: List<String>, label: (Int) -> String, from: Int, to: Int): String? { diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install index 1578b24042..bbacb7652f 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install @@ -66,6 +66,7 @@ if [ -n "$repair" ]; then done fi cache_only= +applied= [ "${1:-}" = --cache ] && cache_only=1 sync= if [ "${1:-}" = --sync ]; then @@ -360,8 +361,24 @@ if [ -n "$cache_only" ]; then done_bytes=$((done_bytes + size)) done < "$work/cache" fi + applier= + trap 'kill "$applier" 2>/dev/null || :; wait "$applier" 2>/dev/null || :; rm -f "$cache/$manifest.installed" "$cached"; exit 143' TERM INT HUP echo "$version" > "$cached" - exit 0 + preapply=${DD_STEAM_PREAPPLY:-/usr/local/bin/droiddeck-steam-preapply} + if [ -x "$preapply" ] && command -v python3 >/dev/null 2>&1; then + python3 "$preapply" "$cache" "$steam_root" "$work/manifest" "$manifest" & + applier=$! + if wait "$applier"; then + cp -f "$work/manifest" "$cache/$manifest.manifest" + chmod -R a+x "$steam_root/steamrtarm64" "$steam_root/linuxarm64" 2>/dev/null || true + while read -r _ file _; do rm -f "$cache/$file"; done < "$work/cache" + [ -f "$stamp" ] || applied=1 + else + rm -f "$cache/$manifest.installed" "$cached" + fi + fi + trap - TERM INT HUP + [ -n "$applied" ] || exit 0 fi if [ -n "$sync" ]; then installed=$(awk -F'"' '$2 == "version" { print $4; exit }' "$steam_root/package/$manifest.manifest" 2>/dev/null || true) @@ -371,6 +388,7 @@ if [ -n "$sync" ]; then fi echo "== STEP $(date -u +%H:%M:%S) updating the arm64 Steam client to $version (was ${installed:-none}) for the x86-64 client" fi +if [ -z "$applied" ]; then total=$(grep -c . "$work/parts" 2>/dev/null || echo 0) total_bytes=$(awk '{ n += $4 } END { print n + 0 }' "$work/parts") @@ -406,6 +424,7 @@ while read -r block file sum size; do done_bytes=$((done_bytes + size)) done < "$work/parts" fi +fi find "$steam_root" -depth -name '*\\*' | while read -r odd; do fixed=${odd//\\//} mkdir -p "$(dirname "$fixed")" diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-preapply b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-preapply new file mode 100755 index 0000000000..841111af21 --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-preapply @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""Extract Steam's cached update packages and record them the way Steam's own updater does.""" +import hashlib, lzma, os, re, stat, struct, sys, time, zipfile, io, zlib, calendar + +OSVER = "-184" +MTIME_OFFSET = 28800 + + +def blocks(manifest): + out, cur, depth = {}, None, 0 + for line in manifest.splitlines(): + m = re.match(r'^(\t+)"([^"]+)"\s*(?:"([^"]*)")?\s*$', line) + if m and m.group(3) is None and len(m.group(1)) == 1: + cur = m.group(2) + out[cur] = {} + elif m and m.group(3) is not None and len(m.group(1)) == 2 and cur: + out[cur][m.group(2)] = m.group(3) + return out + + +def unvz(d): + if d[:3] != b"VZa" or d[-2:] != b"zv": + raise ValueError("not a VZip") + props = d[7] + dict_size = struct.unpack("<I", d[8:12])[0] + crc, size = struct.unpack("<II", d[-10:-2]) + f = [{"id": lzma.FILTER_LZMA1, "dict_size": dict_size, + "lc": props % 9, "lp": (props // 9) % 5, "pb": props // 45}] + out = lzma.LZMADecompressor(format=lzma.FORMAT_RAW, filters=f).decompress(d[12:-10], max_length=size) + if len(out) != size or zlib.crc32(out) & 0xFFFFFFFF != crc: + raise ValueError("bad VZip") + return out + + +def inside(root, path): + return os.path.commonpath([root, path]) == root + + +def main(package_dir, steam_root, manifest_path, name): + steam_root = os.path.realpath(steam_root) + manifest = open(manifest_path, encoding="utf-8", errors="replace").read() + rows = {} + for block, attrs in blocks(manifest).items(): + for key in ("zipvz", "file"): + f = attrs.get(key) + if f and os.path.isfile(os.path.join(package_dir, f)): + break + else: + raise SystemExit(f"missing package for {block}") + data = open(os.path.join(package_dir, f), "rb").read() + zdata = unvz(data) if key == "zipvz" else data + del data + with zipfile.ZipFile(io.BytesIO(zdata)) as z: + for info in z.infolist(): + rel = info.filename.replace("\\", "/") + if rel.startswith("/") or ".." in rel.split("/"): + raise SystemExit(f"unsafe path in {block}: {rel}") + dest = os.path.join(steam_root, rel) + if not inside(steam_root, os.path.realpath(os.path.dirname(dest.rstrip("/")))): + raise SystemExit(f"path leaves the Steam root in {block}: {rel}") + mode = (info.external_attr >> 16) & 0xFFFF + mtime = calendar.timegm(info.date_time + (0, 0, 0)) + MTIME_OFFSET + if rel.endswith("/"): + os.makedirs(dest, exist_ok=True) + rows[rel] = (-1, mtime, 0) + continue + os.makedirs(os.path.dirname(dest), exist_ok=True) + if stat.S_ISLNK(mode): + if os.path.lexists(dest): + os.unlink(dest) + os.symlink(z.read(info).decode(), dest) + rows[rel] = (-2, mtime, info.CRC) + continue + with open(dest + ".dd-tmp", "wb") as out: + out.write(z.read(info)) + os.chmod(dest + ".dd-tmp", (mode & 0o777) | 0o644 if mode else 0o644) + os.replace(dest + ".dd-tmp", dest) + rows[rel] = (info.file_size, mtime, info.CRC) + del zdata + body = "".join(f"{p},{s};{m};{c}\n" for p, (s, m, c) in sorted(rows.items(), key=lambda kv: kv[0].upper())) + body += f"OSVER={OSVER}\nVERSION=3\n" + sha = hashlib.sha1(body.encode()).hexdigest().upper() + pkg = os.path.join(steam_root, "package") + os.makedirs(pkg, exist_ok=True) + tmp = os.path.join(pkg, name + ".installed.dd-tmp") + with open(tmp, "w", encoding="utf-8") as f: + f.write(body + f"SHA1={sha}\n") + os.replace(tmp, os.path.join(pkg, name + ".installed")) + + +if __name__ == "__main__": + main(*sys.argv[1:5]) diff --git a/tools/tests/test_steam_install.py b/tools/tests/test_steam_install.py index 836372c29c..b575a81d22 100644 --- a/tools/tests/test_steam_install.py +++ b/tools/tests/test_steam_install.py @@ -359,6 +359,90 @@ done(28 if end < len(data) else 0) self.assertFalse((package / 'b.zip.9999').exists()) self.assertEqual('123456\n', (package / 'droiddeck-cached').read_text()) + PREAPPLY = SCRIPT.with_name('droiddeck-steam-preapply') + + def real_cache_manifest(self): + import io + out = io.BytesIO() + with zipfile.ZipFile(out, 'w') as z: + z.writestr('steamrtarm64/steam', b'client') + data = out.getvalue() + (self.cdn / 'a.zip.1111').write_bytes(data) + (self.cdn / 'steam_client_steamdeck_publicbeta_linuxarm64').write_text( + '"linuxarm64"\n{\n\t"version" "123456"\n\t"a_all"\n\t{\n' + f'\t\t"file" "a.zip.1111"\n\t\t"size" "{len(data)}"\n\t\t"sha2" "{hashlib.sha256(data).hexdigest()}"\n' + '\t}\n}\n') + + def test_the_cache_pass_applies_the_update_so_steam_has_nothing_to_extract(self): + self.real_cache_manifest() + result = self.install(None, '--cache', DD_STEAM_PREAPPLY=str(self.PREAPPLY)) + self.assertEqual(0, result.returncode, result.stderr) + package = self.steam / 'package' + name = 'steam_client_steamdeck_publicbeta_linuxarm64' + self.assertEqual(b'client', (self.steam / 'steamrtarm64/steam').read_bytes()) + self.assertTrue(os.access(self.steam / 'steamrtarm64/steam', os.X_OK)) + self.assertIn('steamrtarm64/steam,6;', (package / (name + '.installed')).read_text()) + self.assertEqual((self.cdn / name).read_text(), (package / (name + '.manifest')).read_text()) + self.assertFalse((package / 'a.zip.1111').exists()) + self.assertEqual('123456\n', (package / 'droiddeck-cached').read_text()) + + def test_an_applied_update_finishes_the_install_without_fetching_the_plain_packages_again(self): + self.real_cache_manifest() + result = self.install(None, '--cache', DD_STEAM_PREAPPLY=str(self.PREAPPLY)) + self.assertEqual(0, result.returncode, result.stderr) + package = self.steam / 'package' + self.assertEqual('123456\n', (package / 'droiddeck-installed').read_text()) + self.assertEqual('steamdeck_publicbeta\n', (package / 'beta').read_text()) + self.assertEqual((self.steam / 'linuxarm64').resolve(), (self.home / '.steam/sdkarm64').resolve()) + self.assertEqual(['steam_client_steamdeck_publicbeta_linuxarm64', 'a.zip.1111'], self.requested()) + again = self.install(None) + self.assertEqual(0, again.returncode, again.stderr) + self.assertEqual(2, len(self.requested())) + + def test_a_failed_apply_clears_the_cache_marker_and_the_old_record_so_it_is_retried(self): + self.real_cache_manifest() + package = self.steam / 'package' + package.mkdir(parents=True) + name = 'steam_client_steamdeck_publicbeta_linuxarm64' + (package / (name + '.installed')).write_text('old\n') + failing = self.root / 'failing-apply' + failing.write_text('import sys\nsys.exit(1)\n') + failing.chmod(0o755) + result = self.install(None, '--cache', DD_STEAM_PREAPPLY=str(failing)) + self.assertEqual(0, result.returncode, result.stderr) + self.assertFalse((package / (name + '.installed')).exists()) + self.assertFalse((package / 'droiddeck-cached').exists()) + self.assertEqual((self.cdn / 'a.zip.1111').read_bytes(), (package / 'a.zip.1111').read_bytes()) + + def test_cancelling_the_cache_pass_stops_the_apply_helper(self): + self.real_cache_manifest() + pidfile = self.root / 'apply.pid' + slow = self.root / 'slow-apply' + slow.write_text(f'import os, time\nopen({str(pidfile)!r}, "w").write(str(os.getpid()))\ntime.sleep(30)\n') + slow.chmod(0o755) + process = subprocess.Popen(['bash', str(SCRIPT), '--cache'], env=dict(self.env, DD_STEAM_PREAPPLY=str(slow)), + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + for _ in range(100): + if pidfile.exists() and pidfile.read_text().strip(): + break + time.sleep(0.1) + helper = int(pidfile.read_text()) + process.terminate() + process.wait(timeout=10) + time.sleep(0.3) + with self.assertRaises(ProcessLookupError): + os.kill(helper, 0) + self.assertFalse((self.steam / 'package/droiddeck-cached').exists()) + + def test_a_cache_pass_that_cannot_apply_the_update_keeps_the_packages_for_steam(self): + self.cache_manifest() + result = self.install(None, '--cache', DD_STEAM_PREAPPLY=str(self.PREAPPLY)) + self.assertEqual(0, result.returncode, result.stderr) + package = self.steam / 'package' + self.assertEqual(b'plain-package', (package / 'a.zip.1111').read_bytes()) + self.assertFalse(list(package.glob('*.installed'))) + self.assertFalse(list(package.glob('*.manifest'))) + def test_the_cache_pass_is_not_repeated_for_the_same_client_version(self): self.cache_manifest() self.assertEqual(0, self.install(None, '--cache').returncode) diff --git a/tools/tests/test_steam_preapply.py b/tools/tests/test_steam_preapply.py new file mode 100644 index 0000000000..9300b1bcce --- /dev/null +++ b/tools/tests/test_steam_preapply.py @@ -0,0 +1,157 @@ +import hashlib +import io +import lzma +from pathlib import Path +import os +import struct +import subprocess +import sys +import tempfile +import unittest +import zipfile +import zlib + + +SCRIPT = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-steam-preapply' +NAME = 'steam_client_steamdeck_publicbeta_linuxarm64' + + +def zip_bytes(entries): + out = io.BytesIO() + with zipfile.ZipFile(out, 'w') as z: + for name, data, mode, stamp in entries: + info = zipfile.ZipInfo(name, stamp) + info.external_attr = mode << 16 + z.writestr(info, data) + return out.getvalue() + + +def vzip(data): + packer = lzma.LZMACompressor(lzma.FORMAT_RAW, filters=[ + {'id': lzma.FILTER_LZMA1, 'dict_size': 1 << 20, 'lc': 3, 'lp': 0, 'pb': 2}]) + body = packer.compress(data) + packer.flush() + props = (2 * 5 + 0) * 9 + 3 + return (b'VZa' + b'\0\0\0\0' + bytes([props]) + struct.pack('<I', 1 << 20) + body + + struct.pack('<II', zlib.crc32(data) & 0xFFFFFFFF, len(data)) + b'zv') + + +class SteamPreapplyTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + root = Path(self.temp.name) + self.packages = root / 'packages' + self.packages.mkdir() + self.steam = root / 'Steam' + self.manifest = root / 'manifest' + + def write_manifest(self, blocks): + text = '"linuxarm64"\n{\n\t"version"\t\t"42"\n' + for block, attrs in blocks.items(): + text += f'\t"{block}"\n\t{{\n' + for key, value in attrs.items(): + text += f'\t\t"{key}"\t\t"{value}"\n' + text += '\t}\n' + self.manifest.write_text(text + '}\n') + + def run_script(self): + return subprocess.run([sys.executable, '-I', str(SCRIPT), str(self.packages), str(self.steam), + str(self.manifest), NAME], text=True, capture_output=True) + + def installed(self): + return (self.steam / 'package' / (NAME + '.installed')).read_text().split('\n') + + def prepare(self): + stamp = (2025, 5, 17, 10, 30, 0) + plain = zip_bytes([ + ('bin/', b'', 0o40755, stamp), + ('bin/Tool', b'tool', 0o100755, stamp), + ('bin\\Backslash.txt', b'bs', 0o100644, stamp), + ('lib/libx.so.1', b'libx', 0o100644, stamp), + ('lib/libx.so', b'libx.so.1', 0o120777, stamp), + ]) + packed = zip_bytes([('data/z_file', b'zed', 0o100644, stamp), ('data/A_file', b'aaa', 0o100644, stamp)]) + (self.packages / 'a.zip.1111').write_bytes(plain) + (self.packages / 'b.zip.vz.2222_14').write_bytes(vzip(packed)) + self.write_manifest({ + 'a_all': {'file': 'a.zip.1111', 'size': len(plain), 'sha2': '00'}, + 'b_all': {'file': 'b.zip.9999', 'size': 99, 'sha2': '00', 'zipvz': 'b.zip.vz.2222_14', 'sha2vz': '00'}, + }) + + def test_extracts_every_package_including_packed_ones(self): + self.prepare() + result = self.run_script() + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual(b'tool', (self.steam / 'bin/Tool').read_bytes()) + self.assertTrue(os.access(self.steam / 'bin/Tool', os.X_OK)) + self.assertEqual(b'bs', (self.steam / 'bin/Backslash.txt').read_bytes()) + self.assertEqual('libx.so.1', os.readlink(self.steam / 'lib/libx.so')) + self.assertEqual(b'zed', (self.steam / 'data/z_file').read_bytes()) + + def test_records_what_steams_updater_records(self): + self.prepare() + self.assertEqual(0, self.run_script().returncode) + stamp = 1747477800 + 28800 + crc = lambda data: zlib.crc32(data) & 0xFFFFFFFF + lines = self.installed() + self.assertEqual([ + f'bin/,-1;{stamp};0', + f'bin/Backslash.txt,2;{stamp};{crc(b"bs")}', + f'bin/Tool,4;{stamp};{crc(b"tool")}', + f'data/A_file,3;{stamp};{crc(b"aaa")}', + f'data/z_file,3;{stamp};{crc(b"zed")}', + f'lib/libx.so,-2;{stamp};{crc(b"libx.so.1")}', + f'lib/libx.so.1,4;{stamp};{crc(b"libx")}', + 'OSVER=-184', + 'VERSION=3', + ], lines[:-2]) + body = ''.join(line + '\n' for line in lines[:-2]) + self.assertEqual('SHA1=' + hashlib.sha1(body.encode()).hexdigest().upper(), lines[-2]) + self.assertEqual('', lines[-1]) + + def test_a_missing_package_leaves_no_record_so_steam_extracts_for_itself(self): + self.prepare() + (self.packages / 'b.zip.vz.2222_14').unlink() + result = self.run_script() + self.assertNotEqual(0, result.returncode) + self.assertFalse((self.steam / 'package' / (NAME + '.installed')).exists()) + + def test_a_corrupt_package_leaves_no_record(self): + self.prepare() + packed = (self.packages / 'b.zip.vz.2222_14').read_bytes() + (self.packages / 'b.zip.vz.2222_14').write_bytes(packed[:-12] + b'\0' * 12) + self.assertNotEqual(0, self.run_script().returncode) + self.assertFalse((self.steam / 'package' / (NAME + '.installed')).exists()) + + + def package_with(self, entries): + (self.packages / 'a.zip.1111').write_bytes(zip_bytes(entries)) + self.write_manifest({'a_all': {'file': 'a.zip.1111', 'size': 1, 'sha2': '00'}}) + + def test_a_path_that_leaves_the_steam_root_is_refused(self): + stamp = (2025, 5, 17, 10, 30, 0) + for name in ('../outside', '/abs/outside', 'a/../../outside'): + with self.subTest(name=name): + self.package_with([(name, b'x', 0o100644, stamp)]) + self.assertNotEqual(0, self.run_script().returncode) + self.assertFalse((self.steam / 'package' / (NAME + '.installed')).exists()) + self.assertFalse((Path(self.temp.name) / 'outside').exists()) + + def test_a_file_cannot_be_written_through_a_symlink_that_leaves_the_steam_root(self): + stamp = (2025, 5, 17, 10, 30, 0) + target = Path(self.temp.name) / 'elsewhere' + target.mkdir() + self.package_with([('link', str(target).encode(), 0o120777, stamp), ('link/file', b'x', 0o100644, stamp)]) + self.assertNotEqual(0, self.run_script().returncode) + self.assertFalse((target / 'file').exists()) + + def test_a_symlink_inside_the_steam_root_still_carries_files(self): + stamp = (2025, 5, 17, 10, 30, 0) + self.package_with([('real/', b'', 0o40755, stamp), ('alias', b'real', 0o120777, stamp), + ('alias/file', b'x', 0o100644, stamp)]) + self.assertEqual(0, self.run_script().returncode) + self.assertEqual(b'x', (self.steam / 'real/file').read_bytes()) + + +if __name__ == '__main__': + unittest.main() From fbeefc9c9a22c0a51b6c14de4daa7d95264adf1e Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Tue, 24 Nov 2026 15:33:49 -0500 Subject: [PATCH 109/141] fix(desktop): programs started by name run scripts without a shebang line (#3155) --- tools/nativeguest/hook/exec.c | 127 +++++++++++----------- tools/tests/test_native_hook_execvp.py | 140 +++++++++++++++++++++++++ 2 files changed, 204 insertions(+), 63 deletions(-) create mode 100644 tools/tests/test_native_hook_execvp.py diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index 555ce7fc21..5bf75ae4aa 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -712,81 +712,82 @@ int execle(const char *path, const char *arg0, ...) { return ret; } -int execvp(const char *file, char *const argv[]) { +static int exec_or_script(const char *path, char *const argv[], char *const envp[]) { + execve(path, argv, envp); + if (errno != ENOEXEC) return -1; + int argc = 0; + while (argv && argv[argc]) argc++; + char **script = (char **)malloc(sizeof(char *) * (size_t)(argc + 3)); + if (!script) { + errno = ENOMEM; + return -1; + } + script[0] = (char *)"/bin/sh"; + script[1] = (char *)path; + int n = 2; + for (int i = 1; i < argc; i++) script[n++] = argv[i]; + script[n] = NULL; + execve(script[0], script, envp); + int saved_errno = errno; + free(script); + errno = saved_errno; + return -1; +} + +static int exec_search_dir(const char *dir, size_t len, const char *file, char *const argv[], char *const envp[], int *denied) { + char candidate[PATH_MAX]; + int n = len ? snprintf(candidate, sizeof(candidate), "%.*s/%s", (int)len, dir, file) + : snprintf(candidate, sizeof(candidate), "%s", file); + if (n < 0 || n >= (int)sizeof(candidate)) { + errno = ENAMETOOLONG; + return 0; + } + exec_or_script(candidate, argv, envp); + switch (errno) { + case EACCES: + *denied = 1; + return 0; + case ENOENT: case ENOTDIR: case ESTALE: case ENODEV: case ETIMEDOUT: case ENAMETOOLONG: + return 0; + default: + return 1; + } +} + +static int exec_search(const char *file, char *const argv[], char *const envp[], const char *path_env) { if (!file || !*file) { errno = ENOENT; return -1; } - if (strchr(file, '/')) { - return execve(file, argv, environ); - } - const char *path_env = getenv("PATH"); + if (strchr(file, '/')) return exec_or_script(file, argv, envp); if (!path_env) path_env = "/usr/bin:/bin"; - char path_copy[4096]; - strncpy(path_copy, path_env, sizeof(path_copy) - 1); - path_copy[sizeof(path_copy) - 1] = '\0'; - char *saveptr = NULL; - char *token = strtok_r(path_copy, ":", &saveptr); - while (token) { - char candidate[PATH_MAX]; - snprintf(candidate, sizeof(candidate), "%s/%s", token, file); - if (access(candidate, F_OK) == 0) { - return execve(candidate, argv, environ); - } - token = strtok_r(NULL, ":", &saveptr); + int denied = 0; + for (const char *p = path_env;; ) { + const char *end = strchrnul(p, ':'); + if (exec_search_dir(p, (size_t)(end - p), file, argv, envp, &denied)) return -1; + if (!*end) break; + p = end + 1; } - const char *standard_paths[] = {"/usr/bin", "/bin", "/usr/sbin", "/sbin", "/usr/local/bin", NULL}; - for (int i = 0; standard_paths[i] != NULL; i++) { - char candidate[PATH_MAX]; - snprintf(candidate, sizeof(candidate), "%s/%s", standard_paths[i], file); - if (access(candidate, F_OK) == 0) { - return execve(candidate, argv, environ); - } - } - return execve(file, argv, environ); + static const char *const standard_paths[] = {"/usr/bin", "/bin", "/usr/sbin", "/sbin", "/usr/local/bin"}; + for (size_t i = 0; i < sizeof(standard_paths) / sizeof(standard_paths[0]); i++) + if (exec_search_dir(standard_paths[i], strlen(standard_paths[i]), file, argv, envp, &denied)) return -1; + errno = denied ? EACCES : ENOENT; + return -1; +} + +int execvp(const char *file, char *const argv[]) { + return exec_search(file, argv, environ, getenv("PATH")); } int execvpe(const char *file, char *const argv[], char *const envp[]) { - if (!file || !*file) { - errno = ENOENT; - return -1; - } - if (strchr(file, '/')) { - return execve(file, argv, envp); - } const char *path_env = NULL; - if (envp) { - for (char *const *ep = envp; *ep; ep++) { - if (strncmp(*ep, "PATH=", 5) == 0) { - path_env = *ep + 5; - break; - } + for (char *const *ep = envp; ep && *ep; ep++) { + if (strncmp(*ep, "PATH=", 5) == 0) { + path_env = *ep + 5; + break; } } - if (!path_env) path_env = getenv("PATH"); - if (!path_env) path_env = "/usr/bin:/bin"; - char path_copy[4096]; - strncpy(path_copy, path_env, sizeof(path_copy) - 1); - path_copy[sizeof(path_copy) - 1] = '\0'; - char *saveptr = NULL; - char *token = strtok_r(path_copy, ":", &saveptr); - while (token) { - char candidate[PATH_MAX]; - snprintf(candidate, sizeof(candidate), "%s/%s", token, file); - if (access(candidate, F_OK) == 0) { - return execve(candidate, argv, envp); - } - token = strtok_r(NULL, ":", &saveptr); - } - const char *standard_paths[] = {"/usr/bin", "/bin", "/usr/sbin", "/sbin", "/usr/local/bin", NULL}; - for (int i = 0; standard_paths[i] != NULL; i++) { - char candidate[PATH_MAX]; - snprintf(candidate, sizeof(candidate), "%s/%s", standard_paths[i], file); - if (access(candidate, F_OK) == 0) { - return execve(candidate, argv, envp); - } - } - return execve(file, argv, envp); + return exec_search(file, argv, envp, path_env ? path_env : getenv("PATH")); } typedef int (*orig_posix_spawn_f_type)(pid_t *, const char *, const posix_spawn_file_actions_t *, diff --git a/tools/tests/test_native_hook_execvp.py b/tools/tests/test_native_hook_execvp.py new file mode 100644 index 0000000000..6fa37c4664 --- /dev/null +++ b/tools/tests/test_native_hook_execvp.py @@ -0,0 +1,140 @@ +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" + +RECORDER = r""" +#include <stdio.h> +#include <string.h> +#include <unistd.h> +#include <errno.h> +#include <fcntl.h> + +int execve(const char *path, char *const argv[], char *const envp[]) { + if (access(path, F_OK) != 0) { errno = ENOENT; return -1; } + if (access(path, X_OK) != 0) { errno = EACCES; return -1; } + char head[2] = {0}; + int fd = open(path, O_RDONLY); + if (fd >= 0) { if (read(fd, head, 2) < 0) head[0] = 0; close(fd); } + if (memcmp(head, "#!", 2) != 0 && memcmp(head, "\177E", 2) != 0) { + errno = ENOEXEC; + return -1; + } + printf("call"); + for (int i = 0; argv[i]; i++) printf("\t%s", argv[i]); + printf("\n"); + fflush(stdout); + _exit(0); +} +""" + +PROBE = r""" +#define _GNU_SOURCE +#include <errno.h> +#include <stdio.h> +#include <string.h> +#include <unistd.h> + +int main(int argc, char **argv) { + int ret; + if (strcmp(argv[1], "vpe") == 0) { + char path[4096]; + snprintf(path, sizeof(path), "PATH=%s", argv[2]); + char *envp[] = {path, NULL}; + ret = execvpe(argv[3], argv + 3, envp); + } else { + ret = execvp(argv[2], argv + 2); + } + printf("ret\t%d\t%s\n", ret, strerror(errno)); + return 1; +} +""" + + +class NativeHookExecvpTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + cls.tmp = tempfile.TemporaryDirectory(dir="/tmp") + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "recorder.c").write_text(RECORDER) + cls.recorder = tmp / "recorder.so" + subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.recorder), str(tmp / "recorder.c")], check=True) + (tmp / "probe.c").write_text(PROBE) + cls.probe = tmp / "probe" + subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True) + cls.root = tmp / "root" + cls.dirs = Path("/opt/probe") + for name in ("bin", "opt/probe/locked", "opt/probe/open", "opt/probe/work"): + (cls.root / name).mkdir(parents=True) + (tmp / "sh.c").write_text("int main(void) { return 0; }\n") + subprocess.run([cls.cc, "-static", "-O1", "-o", str(cls.root / "bin/sh"), str(tmp / "sh.c")], check=True) + cls.script("locked/tool", 0o644) + cls.script("open/tool", 0o755, "#!/bin/sh\n") + cls.script("open/plain", 0o755) + cls.script("work/here", 0o755) + + @classmethod + def script(cls, name, mode, text="echo plain\n"): + path = cls.root / "opt/probe" / name + path.write_text(text) + path.chmod(mode) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def call(self, *argv, cwd=None): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook}:{self.recorder}"} + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")} + if self.prefix: + cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] + else: + cmd = [] + env.update(hook_env) + out = subprocess.run(cmd + [str(self.probe), *argv], env=env, cwd=cwd, capture_output=True, text=True, + timeout=120) + for line in out.stdout.splitlines(): + if line.startswith("call\t"): + return line.split("\t")[1:] + if line.startswith("ret\t"): + return line.split("\t")[1:] + self.fail(out.stdout + out.stderr) + + def test_a_script_without_a_shebang_runs_through_sh(self): + plain = str(self.dirs / "open/plain") + self.assertEqual(["/bin/sh", plain, "a"], self.call("vp", plain, "a")) + + def test_path_search_runs_a_script_without_a_shebang_through_sh(self): + plain = str(self.dirs / "open/plain") + self.assertEqual(["/bin/sh", plain, "a"], self.call("vpe", str(self.dirs / "open"), "plain", "a")) + + def test_a_denied_entry_earlier_in_path_is_skipped(self): + path = f"{self.dirs / 'locked'}:{self.dirs / 'open'}" + call = self.call("vpe", path, "tool", "x") + self.assertTrue(call[-2].endswith("/opt/probe/open/tool"), call) + self.assertEqual("x", call[-1]) + + def test_only_denied_entries_report_permission_denied(self): + self.assertEqual(["-1", os.strerror(13)], self.call("vpe", str(self.dirs / "locked"), "tool")) + + def test_an_empty_path_entry_means_the_current_directory(self): + here = self.call("vpe", f"{self.dirs / 'open'}:", "here", cwd=self.root / "opt/probe/work") + self.assertEqual(["/bin/sh", "here"], here) + + def test_a_bare_name_is_not_run_from_the_current_directory_without_an_empty_entry(self): + missing = self.call("vpe", str(self.dirs / "open"), "here", cwd=self.root / "opt/probe/work") + self.assertEqual(["-1", os.strerror(2)], missing) + + +if __name__ == "__main__": + unittest.main() From 1f82db66ac19840b76b52f1b26817138e4502881 Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Tue, 24 Nov 2026 15:33:53 -0500 Subject: [PATCH 110/141] fix(desktop): flatpaks that point Vulkan at their GL extension still get the session's driver (#3159) --- .../launcher/runtime/BwrapSpawner.kt | 21 +++++++++++++++---- .../launcher/runtime/BwrapSpawnerTest.kt | 14 +++++++++++++ 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt b/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt index d8e8e47729..7ce94fc93b 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt @@ -191,7 +191,10 @@ object BwrapSpawner { request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> env[k] = e.getString(k) } } withoutRootfsSettings(env, rootfs) val envTool = request.optString("envTool").takeIf { it.startsWith("/") } - if (envTool == null && binds.any { it.guest == "/dev" }) gpu(rootfs, root, env)?.forEach { addBind(it) } + if (envTool == null && binds.any { it.guest == "/dev" }) { + val glIcd = coveringBind(GL_ICD_DIR) != null && File(hostPath(binds, root.path, GL_ICD_DIR)).isDirectory + gpu(rootfs, root, env, glIcd = glIcd)?.forEach { addBind(it) } + } val libc = listOf("/usr/lib/aarch64-linux-gnu/libc.so.6", "/lib/aarch64-linux-gnu/libc.so.6").map { hostPath(binds, root.path, it) } if (envTool == null && preloadFits(rootfs, libc.firstOrNull { File(it).isFile } ?: libc.first())) preload(session, rootfs, env).forEach { addBind(it) } zypakShims(binds, root, dir).forEach { addBind(it) } @@ -218,6 +221,7 @@ object BwrapSpawner { } private const val GPU_DIR = "/run/droiddeck-gpu" + private const val GL_ICD_DIR = "/usr/lib/aarch64-linux-gnu/GL/vulkan/icd.d" private val LIB_DIRS = listOf("usr/lib/aarch64-linux-gnu", "usr/lib") private val GPU_LIBS = listOf("libdisplay-info.so.3", "libdisplay-info.so.2", "libSPIRV-Tools.so", "libSPIRV-Tools-opt.so") @@ -227,9 +231,9 @@ object BwrapSpawner { internal fun gpu( rootfs: String, root: File, env: MutableMap<String, String>, - kgslAvailable: Boolean = File("/dev/kgsl-3d0").exists(), + kgslAvailable: Boolean = File("/dev/kgsl-3d0").exists(), glIcd: Boolean = false, ): List<Bind>? { - env["VKBRIDGE_SOCKET"]?.let { sock -> if (File(sock).exists()) return bridgeGpu(rootfs, root, env, sock) } + env["VKBRIDGE_SOCKET"]?.let { sock -> if (File(sock).exists()) return bridgeGpu(rootfs, root, env, sock, glIcd) } val driver = runtimeLib(rootfs, "libvulkan_freedreno.so") if (driver == null || !kgslAvailable) return null if (env.containsKey("VK_ICD_FILENAMES") || env.containsKey("VK_DRIVER_FILES")) return null @@ -242,6 +246,7 @@ object BwrapSpawner { val icd = File(root.parentFile, "freedreno_icd.json") icd.writeText("{\"file_format_version\": \"1.0.0\", \"ICD\": {\"library_path\": \"$GPU_DIR/libvulkan_freedreno.so\", \"api_version\": \"1.4.0\"}}\n") binds.add(Bind(icd.path, "$GPU_DIR/freedreno_icd.json")) + if (glIcd) binds.add(icdDir(root, icd)) env["VK_DRIVER_FILES"] = "$GPU_DIR/freedreno_icd.json" env["VK_ICD_FILENAMES"] = "$GPU_DIR/freedreno_icd.json" if (!env.containsKey("MESA_LOADER_DRIVER_OVERRIDE") && !env.containsKey("GALLIUM_DRIVER")) { @@ -252,7 +257,14 @@ object BwrapSpawner { return binds } - private fun bridgeGpu(rootfs: String, root: File, env: MutableMap<String, String>, socket: String): List<Bind>? { + private fun icdDir(root: File, icd: File): Bind { + val dir = File(root.parentFile, "icd.d") + dir.mkdirs() + icd.copyTo(File(dir, icd.name), overwrite = true) + return Bind(dir.path, GL_ICD_DIR) + } + + private fun bridgeGpu(rootfs: String, root: File, env: MutableMap<String, String>, socket: String, glIcd: Boolean): List<Bind>? { val driver = File(rootfs, "usr/local/lib/vkbridge/libvulkan_droidbridge.so") if (!driver.isFile) { Log.w(TAG, "gpu: vkbridge session but no bridge ICD in the runtime"); return null } val binds = ArrayList<Bind>() @@ -265,6 +277,7 @@ object BwrapSpawner { }.getOrNull() ?: run { Log.w(TAG, "gpu: vkbridge session but the runtime's bridge manifest is unreadable"); return null } icd.writeText("{\"file_format_version\": \"1.0.0\", \"ICD\": {\"library_path\": \"$GPU_DIR/libvulkan_droidbridge.so\", \"api_version\": \"$api\"}}\n") binds.add(Bind(icd.path, "$GPU_DIR/vkbridge_icd.json")) + if (glIcd) binds.add(icdDir(root, icd)) env["VK_DRIVER_FILES"] = "$GPU_DIR/vkbridge_icd.json" env["VK_ICD_FILENAMES"] = "$GPU_DIR/vkbridge_icd.json" if (!env.containsKey("MESA_LOADER_DRIVER_OVERRIDE") && !env.containsKey("GALLIUM_DRIVER")) { diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt index 05ab89a2c4..5bf02cacc9 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt @@ -172,6 +172,20 @@ class BwrapSpawnerPlanTest { assertEquals(mapOf("DD_DESKTOP" to "1"), unavailable) } + @Test fun theRuntimeGlExtensionVulkanDirectoryListsOnlyTheSessionDriver() { + val lib = File(runtime, "usr/lib/aarch64-linux-gnu/libvulkan_freedreno.so") + lib.parentFile!!.mkdirs() + lib.writeText("") + val root = File(dir, "root").apply { mkdirs() } + val glIcd = "/usr/lib/aarch64-linux-gnu/GL/vulkan/icd.d" + val binds = BwrapSpawner.gpu(runtime.path, root, mutableMapOf("DD_DESKTOP" to "1"), true, glIcd = true)!! + val listed = File(binds.single { it.guest == glIcd }.host).listFiles()!!.map { it.name } + assertEquals(listOf("freedreno_icd.json"), listed) + assertTrue(File(binds.single { it.guest == glIcd }.host, "freedreno_icd.json").readText().contains("/run/droiddeck-gpu/libvulkan_freedreno.so")) + assertTrue(BwrapSpawner.gpu(runtime.path, root, mutableMapOf("DD_DESKTOP" to "1"), true)!!.none { it.guest == glIcd }) + assertEquals(null, BwrapSpawner.gpu(runtime.path, root, mutableMapOf("VK_DRIVER_FILES" to "/custom/icd.json"), true, glIcd = true)) + } + @Test fun buildsTheTreeFlatpakAsksFor() { val context = RuntimeEnvironment.getApplication() val info = Base64.encodeToString("[Application]\nname=org.example.Game\n".toByteArray(), Base64.NO_WRAP) From 6e252ea3adcd4b0d50faf2b4a76f5f733b003e1a Mon Sep 17 00:00:00 2001 From: LarzVader <118484383+LarzVader@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:16:19 +0100 Subject: [PATCH 111/141] fix(venus): destroying a null handle no longer grows the Mali layer's maps (#3101) The handle maps use key 0 for an empty slot. vkDestroyBuffer, vkFreeMemory and the other destroy calls accept VK_NULL_HANDLE, and map_remove(0) matched the first empty slot it reached, so every such call lowered count without removing anything. Once count wrapped below zero, every map_put saw a full table and doubled it, and each rehash took twice as long as the one before. Steam's web helper frees null buffers about 50,000 times in a few minutes. On a Mali-G610 its UI stalled periodically for 0.2 s, 0.37 s, 0.75 s, 1.5 s and then 3 s, and the buffer map reported a count of 4294967295. map_get, map_put and map_remove now ignore key 0. On a Nothing Phone (2a) running 0.7.1 with this change, the buffer map stayed at 256 slots after 115,000 frees and the stalls were gone. --- tools/tests/mali_compat_layer_test.c | 20 ++++++++++++++++++++ tools/venus/layer/layer.c | 8 ++++++-- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/tools/tests/mali_compat_layer_test.c b/tools/tests/mali_compat_layer_test.c index 640460685c..3584a66000 100644 --- a/tools/tests/mali_compat_layer_test.c +++ b/tools/tests/mali_compat_layer_test.c @@ -182,6 +182,25 @@ static void test_spirv(const char *directory) assert(!spirv_strip_dual_source(truncated, 5, &out)); } +static void test_handle_map_null_key(void) +{ + struct handle_map map = {0}; + int first, second; + map_put(&map, 0x1000, &first); + map_put(&map, 0x2000, &second); + for (int i = 0; i < 1000; i++) + assert(!map_remove(&map, 0)); + map_put(&map, 0, &first); + assert(map.count == 2 && !map_get(&map, 0)); + for (uint64_t key = 1; key <= 30; key++) { + map_put(&map, 0x100000 + key, &first); + assert(map_remove(&map, 0x100000 + key) == &first); + } + assert(map.count == 2 && map.capacity == 64); + assert(map_get(&map, 0x1000) == &first && map_get(&map, 0x2000) == &second); + map_free(&map); +} + static VkResult VKAPI_CALL mock_create_instance(const VkInstanceCreateInfo *info, const VkAllocationCallbacks *allocator, VkInstance *instance) { @@ -464,6 +483,7 @@ static void test_capable_device(void) int main(int argc, char **argv) { test_spirv(argc > 1 ? argv[1] : NULL); + test_handle_map_null_key(); setenv("WINEPREFIX", "/nonexistent", 1); unsetenv("DROIDDECK_MALI_COMPAT"); diff --git a/tools/venus/layer/layer.c b/tools/venus/layer/layer.c index a4e35e0a32..21778b859e 100644 --- a/tools/venus/layer/layer.c +++ b/tools/venus/layer/layer.c @@ -60,9 +60,11 @@ static uint64_t hash(uint64_t key) return key; } +/* Key 0 marks an empty slot, so VK_NULL_HANDLE is never looked up, stored or removed. Destroying a + * null handle is valid Vulkan, and map_remove(0) would otherwise match an empty slot and drop count. */ void *map_get(const struct handle_map *map, uint64_t key) { - if (!map->capacity) + if (!map->capacity || !key) return NULL; for (uint32_t i = hash(key) & (map->capacity - 1);; i = (i + 1) & (map->capacity - 1)) { if (map->keys[i] == key) @@ -90,6 +92,8 @@ static void map_grow(struct handle_map *map) void map_put(struct handle_map *map, uint64_t key, void *value) { + if (!key) + return; if ((map->count + 1) * 4 > map->capacity * 3) map_grow(map); uint32_t i = hash(key) & (map->capacity - 1); @@ -103,7 +107,7 @@ void map_put(struct handle_map *map, uint64_t key, void *value) void *map_remove(struct handle_map *map, uint64_t key) { - if (!map->capacity) + if (!map->capacity || !key) return NULL; uint32_t mask = map->capacity - 1; uint32_t i = hash(key) & mask; From ae47876386703658a5b70981d80b44f986db2563 Mon Sep 17 00:00:00 2001 From: LarzVader <118484383+LarzVader@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:16:26 +0100 Subject: [PATCH 112/141] fix(venus): Zink draws on Mali-G610 when the depth test is off (#3102) With depthTestEnable off, Vulkan ignores depthCompareOp. The Mali-G610 driver behind Venus (Nothing Phone (2a), Dimensity 7200 Pro) applies it anyway, even without a depth attachment. Zink leaves the op at VK_COMPARE_OP_NEVER whenever GL has the depth test off, so every fragment Zink draws is thrown away: clears and copies work, draws never show. This is the black Steam UI when it renders through Zink and the black picture of OpenGL games such as Stardew Valley. DXVK sets ALWAYS in the same case, which is why D3D games drew. The layer now hands the driver ALWAYS while the depth test is off: - vkCmdSetDepthTestEnable and vkCmdSetDepthCompareOp keep the state per command buffer, which vkBeginCommandBuffer clears. While the test is off the driver gets ALWAYS; turning it on again restores the application's op. - A pipeline with the depth test off and neither state dynamic is created with ALWAYS. It is on for every device with gaps. ALWAYS for a disabled depth test changes nothing on a driver that follows the spec. --- tools/tests/mali_compat_layer_test.c | 88 ++++++++++++++++++++++++++++ tools/venus/layer/bc.c | 6 +- tools/venus/layer/draw.c | 48 +++++++++++++++ tools/venus/layer/layer.c | 11 +++- tools/venus/layer/mali_compat.h | 12 +++- tools/venus/layer/pipeline.c | 14 +++++ 6 files changed, 175 insertions(+), 4 deletions(-) diff --git a/tools/tests/mali_compat_layer_test.c b/tools/tests/mali_compat_layer_test.c index 3584a66000..9b29e5c734 100644 --- a/tools/tests/mali_compat_layer_test.c +++ b/tools/tests/mali_compat_layer_test.c @@ -21,6 +21,8 @@ static VkPipelineColorBlendAttachmentState driver_attachments[4]; static uint32_t driver_attachment_count; static VkColorBlendEquationEXT driver_equations[4]; static uint32_t driver_equation_count; +static VkCompareOp driver_depth_op, driver_pipeline_depth_op; +static VkBool32 driver_depth_test; #define MAIN 1 #define VOID 2 @@ -305,10 +307,27 @@ static VkResult VKAPI_CALL mock_create_graphics_pipelines(VkDevice device, VkPip const VkShaderModuleCreateInfo *module = infos[0].pStages[0].pNext; assert(module && module->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO); capture_code(module->pCode, module->codeSize); + if (infos[0].pDepthStencilState) + driver_pipeline_depth_op = infos[0].pDepthStencilState->depthCompareOp; pipelines[0] = (VkPipeline)0x2000; return VK_SUCCESS; } +static VkResult VKAPI_CALL mock_begin_command_buffer(VkCommandBuffer cmd, const VkCommandBufferBeginInfo *info) +{ + return VK_SUCCESS; +} + +static void VKAPI_CALL mock_set_depth_test(VkCommandBuffer cmd, VkBool32 enable) +{ + driver_depth_test = enable; +} + +static void VKAPI_CALL mock_set_depth_op(VkCommandBuffer cmd, VkCompareOp op) +{ + driver_depth_op = op; +} + static void VKAPI_CALL mock_set_blend_equation(VkCommandBuffer cmd, uint32_t first, uint32_t count, const VkColorBlendEquationEXT *equations) { @@ -342,6 +361,9 @@ static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL mock_gdpa(VkDevice device, const MOCK("vkDestroyShaderModule", mock_destroy_shader_module); MOCK("vkCreateGraphicsPipelines", mock_create_graphics_pipelines); MOCK("vkCmdSetColorBlendEquationEXT", mock_set_blend_equation); + MOCK("vkBeginCommandBuffer", mock_begin_command_buffer); + MOCK("vkCmdSetDepthTestEnable", mock_set_depth_test); + MOCK("vkCmdSetDepthCompareOp", mock_set_depth_op); return NULL; } @@ -480,6 +502,71 @@ static void test_capable_device(void) destroy_device(device); } +static void create_depth_pipeline(VkDevice device, const VkPipelineDepthStencilStateCreateInfo *depth, + const VkDynamicState *dynamic, uint32_t dynamic_count) +{ + struct spirv plain; + fragment_shader(&plain, 0x00010000, false); + VkShaderModuleCreateInfo module = {VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, NULL, 0, + plain.n * sizeof(uint32_t), plain.w}; + VkPipelineShaderStageCreateInfo stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, &module, 0, + VK_SHADER_STAGE_FRAGMENT_BIT, VK_NULL_HANDLE, "main", NULL}; + VkPipelineColorBlendStateCreateInfo blend = {VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, NULL, 0, + VK_FALSE, VK_LOGIC_OP_COPY, 1, &plain_attachment, {0}}; + VkPipelineDynamicStateCreateInfo states = {VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, NULL, 0, + dynamic_count, dynamic}; + VkGraphicsPipelineCreateInfo info = {.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, .stageCount = 1, + .pStages = &stage, .pDepthStencilState = depth, .pColorBlendState = &blend, + .pDynamicState = dynamic_count ? &states : NULL}; + VkPipeline pipeline; + driver_pipeline_depth_op = VK_COMPARE_OP_MAX_ENUM; + PFN_vkCreateGraphicsPipelines create = + (PFN_vkCreateGraphicsPipelines)layer_gdpa(device, "vkCreateGraphicsPipelines"); + assert(create(device, VK_NULL_HANDLE, 1, &info, NULL, &pipeline) == VK_SUCCESS); +} + +static void test_depth_compare_op(void) +{ + VkDevice device; + VkPhysicalDeviceFeatures enabled = {.dualSrcBlend = VK_TRUE}; + assert(create_device((VkPhysicalDevice)&mock_lacking, NULL, &enabled, &device) == VK_SUCCESS); + PFN_vkBeginCommandBuffer begin = (PFN_vkBeginCommandBuffer)layer_gdpa(device, "vkBeginCommandBuffer"); + PFN_vkCmdSetDepthTestEnable set_test = + (PFN_vkCmdSetDepthTestEnable)layer_gdpa(device, "vkCmdSetDepthTestEnable"); + PFN_vkCmdSetDepthCompareOp set_op = (PFN_vkCmdSetDepthCompareOp)layer_gdpa(device, "vkCmdSetDepthCompareOp"); + assert((PFN_vkVoidFunction)set_test != (PFN_vkVoidFunction)mock_set_depth_test); + assert((PFN_vkVoidFunction)set_op != (PFN_vkVoidFunction)mock_set_depth_op); + + VkCommandBuffer cmd = (VkCommandBuffer)&mock_command_buffer; + VkCommandBufferBeginInfo begin_info = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + assert(begin(cmd, &begin_info) == VK_SUCCESS); + set_op(cmd, VK_COMPARE_OP_LESS); + assert(driver_depth_op == VK_COMPARE_OP_LESS); + set_test(cmd, VK_FALSE); + assert(!driver_depth_test && driver_depth_op == VK_COMPARE_OP_ALWAYS); + set_op(cmd, VK_COMPARE_OP_NEVER); + assert(driver_depth_op == VK_COMPARE_OP_ALWAYS); + set_test(cmd, VK_TRUE); + assert(driver_depth_test && driver_depth_op == VK_COMPARE_OP_NEVER); + set_test(cmd, VK_FALSE); + assert(begin(cmd, &begin_info) == VK_SUCCESS); + set_op(cmd, VK_COMPARE_OP_GREATER); + assert(driver_depth_op == VK_COMPARE_OP_GREATER); + + VkPipelineDepthStencilStateCreateInfo depth = {.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO, + .depthCompareOp = VK_COMPARE_OP_NEVER}; + create_depth_pipeline(device, &depth, NULL, 0); + assert(driver_pipeline_depth_op == VK_COMPARE_OP_ALWAYS && depth.depthCompareOp == VK_COMPARE_OP_NEVER); + const VkDynamicState dynamic[] = {VK_DYNAMIC_STATE_DEPTH_COMPARE_OP}; + create_depth_pipeline(device, &depth, dynamic, 1); + assert(driver_pipeline_depth_op == VK_COMPARE_OP_NEVER); + depth.depthTestEnable = VK_TRUE; + depth.depthCompareOp = VK_COMPARE_OP_LESS; + create_depth_pipeline(device, &depth, NULL, 0); + assert(driver_pipeline_depth_op == VK_COMPARE_OP_LESS); + destroy_device(device); +} + int main(int argc, char **argv) { test_spirv(argc > 1 ? argv[1] : NULL); @@ -502,6 +589,7 @@ int main(int argc, char **argv) test_lacking_device(); test_capable_device(); + test_depth_compare_op(); ((PFN_vkDestroyInstance)layer_gipa(instance, "vkDestroyInstance"))(instance, NULL); free(driver_code); diff --git a/tools/venus/layer/bc.c b/tools/venus/layer/bc.c index 328b68169d..3948126fd1 100644 --- a/tools/venus/layer/bc.c +++ b/tools/venus/layer/bc.c @@ -799,7 +799,11 @@ static void recycle_command_buffer(struct device *dev, VkCommandBuffer cmd) VKAPI_ATTR VkResult VKAPI_CALL BeginCommandBuffer(VkCommandBuffer cmd, const VkCommandBufferBeginInfo *info) { struct device *dev = device_from_handle(cmd); - recycle_command_buffer(dev, cmd); + if (dev->emulated & GAP_BC) + recycle_command_buffer(dev, cmd); + /* Dynamic state does not carry over from one recording to the next. */ + if (dev->emulated & GAP_DEPTH_OP) + depth_state_forget(dev, cmd); return dev->BeginCommandBuffer(cmd, info); } diff --git a/tools/venus/layer/draw.c b/tools/venus/layer/draw.c index f3621355b2..5d0dc4a13e 100644 --- a/tools/venus/layer/draw.c +++ b/tools/venus/layer/draw.c @@ -8,6 +8,8 @@ * stand-ins the layer owns. robustBufferAccess2 itself maps to robustBufferAccess (layer.c). * A null texel-buffer view gets an RGBA8 (uniform) or R32_UINT (storage) view of the stand-in * buffer: its format is not known here, but Zink leaves them unbound and never reads them. + * - depthCompareOp with the depth test off (GAP_DEPTH_OP): the driver is given ALWAYS while a + * command buffer has the test off, and the application's op again once it turns the test on. */ #include <stdlib.h> #include <string.h> @@ -450,3 +452,49 @@ VKAPI_ATTR void VKAPI_CALL CmdBindVertexBuffers2(VkCommandBuffer cmd, uint32_t f } dev->CmdBindVertexBuffers2(cmd, first, count, fixed, fixed_offsets, sizes ? fixed_sizes : NULL, strides); } + +/* --- depthCompareOp while the depth test is off --- */ + +/* Per command buffer, packed into the map's value pointer so it is never NULL: bit 0 always set, + * bit 1 the test enable is known, bit 2 the test is on, bit 3 an op was set, bits 4 and up that op. */ +enum { DEPTH_VALID = 1, DEPTH_KNOWN = 2, DEPTH_ON = 4, DEPTH_OP = 8 }; + +static uintptr_t depth_state(struct device *dev, VkCommandBuffer cmd) +{ + uintptr_t state = (uintptr_t)map_get(&dev->depth_states, (uint64_t)(uintptr_t)cmd); + return state ? state : DEPTH_VALID; +} + +void depth_state_forget(struct device *dev, VkCommandBuffer cmd) +{ + pthread_mutex_lock(&dev->lock); + map_remove(&dev->depth_states, (uint64_t)(uintptr_t)cmd); + pthread_mutex_unlock(&dev->lock); +} + +VKAPI_ATTR void VKAPI_CALL CmdSetDepthTestEnable(VkCommandBuffer cmd, VkBool32 enable) +{ + struct device *dev = device_from_handle(cmd); + dev->CmdSetDepthTestEnable(cmd, enable); + pthread_mutex_lock(&dev->lock); + uintptr_t state = depth_state(dev, cmd); + uintptr_t next = (state & ~(uintptr_t)DEPTH_ON) | DEPTH_KNOWN | (enable ? DEPTH_ON : 0); + map_put(&dev->depth_states, (uint64_t)(uintptr_t)cmd, (void *)next); + pthread_mutex_unlock(&dev->lock); + if (!enable) + dev->CmdSetDepthCompareOp(cmd, VK_COMPARE_OP_ALWAYS); + else if (state & DEPTH_OP) + dev->CmdSetDepthCompareOp(cmd, (VkCompareOp)(state >> 4)); +} + +VKAPI_ATTR void VKAPI_CALL CmdSetDepthCompareOp(VkCommandBuffer cmd, VkCompareOp op) +{ + struct device *dev = device_from_handle(cmd); + pthread_mutex_lock(&dev->lock); + uintptr_t state = depth_state(dev, cmd); + uintptr_t next = (state & (uintptr_t)(DEPTH_VALID | DEPTH_KNOWN | DEPTH_ON)) | DEPTH_OP | ((uintptr_t)op << 4); + map_put(&dev->depth_states, (uint64_t)(uintptr_t)cmd, (void *)next); + pthread_mutex_unlock(&dev->lock); + bool off = (state & DEPTH_KNOWN) && !(state & DEPTH_ON); + dev->CmdSetDepthCompareOp(cmd, off ? VK_COMPARE_OP_ALWAYS : op); +} diff --git a/tools/venus/layer/layer.c b/tools/venus/layer/layer.c index 21778b859e..9aeb0bcf0e 100644 --- a/tools/venus/layer/layer.c +++ b/tools/venus/layer/layer.c @@ -606,7 +606,7 @@ static VKAPI_ATTR VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice physical_dev dev->key = dispatch_key(*device); dev->handle = *device; dev->gdpa = gdpa; - dev->emulated = requested; + dev->emulated = requested | (gaps ? GAP_DEPTH_OP : 0); pthread_mutex_init(&dev->lock, NULL); #define LOAD(name) \ dev->name = (PFN_vk##name)gdpa(*device, "vk" #name); \ @@ -642,6 +642,8 @@ static VKAPI_ATTR VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice physical_dev (requested & GAP_NULL_DESCRIPTOR) ? " nullDescriptor" : "", (requested & GAP_DUAL_SRC_BLEND) ? " dualSrcBlend" : "", properties.deviceName); } + if (dev->emulated & GAP_DEPTH_OP) + layer_log("depthCompareOp becomes ALWAYS while the depth test is off"); return VK_SUCCESS; } @@ -669,6 +671,7 @@ static VKAPI_ATTR void VKAPI_CALL DestroyDevice(VkDevice device, const VkAllocat } } map_free(&dev->shader_modules); + map_free(&dev->depth_states); pthread_mutex_destroy(&dev->lock); free(dev); } @@ -696,6 +699,10 @@ static const struct hook device_hooks[] = { HOOK(CmdSetScissorWithCount, GAP_MULTI_VIEWPORT), HOOK_ALIAS(CmdSetScissorWithCount, CmdSetScissorWithCountEXT, GAP_MULTI_VIEWPORT), HOOK(CmdSetColorBlendEquationEXT, GAP_DUAL_SRC_BLEND), + HOOK(CmdSetDepthTestEnable, GAP_DEPTH_OP), + HOOK_ALIAS(CmdSetDepthTestEnable, CmdSetDepthTestEnableEXT, GAP_DEPTH_OP), + HOOK(CmdSetDepthCompareOp, GAP_DEPTH_OP), + HOOK_ALIAS(CmdSetDepthCompareOp, CmdSetDepthCompareOpEXT, GAP_DEPTH_OP), HOOK(CreateImage, GAP_BC), HOOK(DestroyImage, GAP_BC), HOOK(CreateImageView, GAP_BC), @@ -727,7 +734,7 @@ static const struct hook device_hooks[] = { HOOK_ALIAS(UnmapMemory2, UnmapMemory2KHR, GAP_BC), HOOK(AllocateCommandBuffers, GAP_BC), HOOK(FreeCommandBuffers, GAP_BC), - HOOK(BeginCommandBuffer, GAP_BC), + HOOK(BeginCommandBuffer, GAP_BC | GAP_DEPTH_OP), HOOK(ResetCommandBuffer, GAP_BC), HOOK(ResetCommandPool, GAP_BC), HOOK(DestroyCommandPool, GAP_BC), diff --git a/tools/venus/layer/mali_compat.h b/tools/venus/layer/mali_compat.h index eb171bb6f9..073907f41a 100644 --- a/tools/venus/layer/mali_compat.h +++ b/tools/venus/layer/mali_compat.h @@ -30,6 +30,10 @@ enum gap { GAP_DEPTH_CLIP = 1u << 7, /* VK_EXT_depth_clip_enable: depthClipEnable off becomes depth clamp */ GAP_NULL_DESCRIPTOR = 1u << 8, /* VK_EXT_robustness2 missing entirely: nullDescriptor stand-ins */ GAP_DUAL_SRC_BLEND = 1u << 9, + /* A driver bug, not a missing feature: the Mali-G610 driver behind Venus applies depthCompareOp + * with the depth test off, so Zink's NEVER discards every fragment. On for every device with + * gaps; ALWAYS for a disabled test changes nothing on a driver that follows the spec. */ + GAP_DEPTH_OP = 1u << 10, }; #define GAPS_SHADER (GAP_CLIP_DISTANCE | GAP_CULL_DISTANCE) @@ -138,7 +142,9 @@ struct instance { X(CmdPushDescriptorSetWithTemplate) \ X(CmdBindVertexBuffers) \ X(CmdBindVertexBuffers2) \ - X(CmdSetColorBlendEquationEXT) + X(CmdSetColorBlendEquationEXT) \ + X(CmdSetDepthTestEnable) \ + X(CmdSetDepthCompareOp) struct staging_block; @@ -163,6 +169,7 @@ struct device { struct handle_map command_buffers; /* VkCommandBuffer -> struct command_buffer */ struct staging_block *free_staging; struct handle_map templates; /* VkDescriptorUpdateTemplate -> struct template_info (draw.c) */ + struct handle_map depth_states; /* VkCommandBuffer -> packed depth test state (draw.c) */ /* nullDescriptor stand-ins (draw.c): 0 not made yet, 1 ready, -1 failed. */ int null_ready; VkBuffer null_buffer; @@ -311,4 +318,7 @@ VKAPI_ATTR void VKAPI_CALL CmdPushDescriptorSetWithTemplate(VkCommandBuffer cmd, VKAPI_ATTR void VKAPI_CALL CmdBindVertexBuffers(VkCommandBuffer cmd, uint32_t first, uint32_t count, const VkBuffer *buffers, const VkDeviceSize *offsets); VKAPI_ATTR void VKAPI_CALL CmdBindVertexBuffers2(VkCommandBuffer cmd, uint32_t first, uint32_t count, const VkBuffer *buffers, const VkDeviceSize *offsets, const VkDeviceSize *sizes, const VkDeviceSize *strides); void null_resources_destroy(struct device *dev); +VKAPI_ATTR void VKAPI_CALL CmdSetDepthTestEnable(VkCommandBuffer cmd, VkBool32 enable); +VKAPI_ATTR void VKAPI_CALL CmdSetDepthCompareOp(VkCommandBuffer cmd, VkCompareOp op); +void depth_state_forget(struct device *dev, VkCommandBuffer cmd); #endif diff --git a/tools/venus/layer/pipeline.c b/tools/venus/layer/pipeline.c index 95c0ccd1ee..01236be5b7 100644 --- a/tools/venus/layer/pipeline.c +++ b/tools/venus/layer/pipeline.c @@ -143,6 +143,7 @@ struct pipeline_rewrite { /* VK_EXT_depth_clip_enable's state, taken out of the application's chain for the call. */ VkBaseOutStructure *clip_prev, *clip_node; VkPipelineViewportStateCreateInfo viewport; + VkPipelineDepthStencilStateCreateInfo depth_stencil; VkPipelineShaderStageCreateInfo stages[MAX_STAGES]; VkShaderModuleCreateInfo modules[MAX_STAGES]; struct spirv_code code[MAX_STAGES]; @@ -401,6 +402,19 @@ static void rewrite_pipeline(struct device *dev, VkGraphicsPipelineCreateInfo *i rw->viewport.scissorCount = 1; info->pViewportState = &rw->viewport; } + if ((dev->emulated & GAP_DEPTH_OP) && info->pDepthStencilState && !info->pDepthStencilState->depthTestEnable && + info->pDepthStencilState->depthCompareOp != VK_COMPARE_OP_ALWAYS) { + bool dynamic = false; + for (uint32_t i = 0; info->pDynamicState && i < info->pDynamicState->dynamicStateCount; i++) { + VkDynamicState state = info->pDynamicState->pDynamicStates[i]; + dynamic |= state == VK_DYNAMIC_STATE_DEPTH_TEST_ENABLE || state == VK_DYNAMIC_STATE_DEPTH_COMPARE_OP; + } + if (!dynamic) { + rw->depth_stencil = *info->pDepthStencilState; + rw->depth_stencil.depthCompareOp = VK_COMPARE_OP_ALWAYS; + info->pDepthStencilState = &rw->depth_stencil; + } + } if (dev->emulated & GAP_DUAL_SRC_BLEND) { rewrite_blend(info, rw); if (rw->attachments) From 8bb189570264b64eca88aa42d0b6dfc4bf73da2c Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Tue, 24 Nov 2026 16:16:31 -0500 Subject: [PATCH 113/141] fix(gog): skip saves GOG Cloud marks deleted (#3025) * fix(gog): skip saves GOG Cloud marks deleted GOG keeps a deleted cloud save in the listing as an empty gzip object (hash aadd86936a80ee8a369579c3926f1b3c). The listing was read as plain names without hashes, so every deleted save was downloaded again as an empty file. Ask for the JSON listing, keep each object's hash, treat deletion markers as absent, and only send a marked save back once it changed locally. Local files are never removed. * docs: credit gogdl and Lutris for the GOG cloud deletion marker --- README.md | 2 +- .../droiddeck/launcher/stores/CloudPlan.kt | 3 +- .../droiddeck/launcher/stores/CloudSaves.kt | 16 +++++--- .../launcher/stores/CloudTransport.kt | 8 +++- .../launcher/stores/CloudPlanTest.kt | 9 +++++ .../launcher/stores/CloudSavesTest.kt | 38 ++++++++++++++++++- .../launcher/stores/GogCloudKeysTest.kt | 23 +++++++++++ 7 files changed, 89 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index a1094c8d14..066136eab3 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V <details> <summary><b>Stores</b></summary> -- Epic Games and GOG build on [Phobos](https://github.com/phobos665)'s adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl). GOG install script registry entries are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher) (GPL-3.0) reads them. GOG cloud storage requests send the Galaxy communication-service User-Agent that gogdl and [Lutris](https://github.com/lutris/lutris) (GPL-3.0) send. +- Epic Games and GOG build on [Phobos](https://github.com/phobos665)'s adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl). GOG install script registry entries are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher) (GPL-3.0) reads them. GOG cloud storage requests send the Galaxy communication-service User-Agent that gogdl and [Lutris](https://github.com/lutris/lutris) (GPL-3.0) send. Deleted GOG cloud saves are recognised by the empty-gzip deletion hash gogdl and Lutris skip. - Epic's official Linux launcher preview runs through FEX. That setup is outside Epic's listed Linux support. - The launcher's .deb gets the WebKitGTK and GTK 3 libraries it needs from unmodified [Debian](https://www.debian.org) 13 packages, following [@zooluis](https://github.com/zooluis)'s research in [#2268](https://github.com/Droid-Deck/DroidDeck/pull/2268). - Battle.net is by [@kayakyakr](https://github.com/kayakyakr). It runs Blizzard's own client in Proton (downloaded from Blizzard, not included) and shows key art from the [Battle.net Shop](https://shop.battle.net). Without Steam, its games see the pad as an Xbox 360 controller via `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`. diff --git a/app/src/main/java/com/droiddeck/launcher/stores/CloudPlan.kt b/app/src/main/java/com/droiddeck/launcher/stores/CloudPlan.kt index d3c63b203a..940d1eee71 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/CloudPlan.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/CloudPlan.kt @@ -36,13 +36,14 @@ object CloudPlan { return Plan(transfer, conflicts, same) } - fun up(local: Map<String, Local>, remote: Map<String, Remote>, baseline: Map<String, Entry>?): Plan { + fun up(local: Map<String, Local>, remote: Map<String, Remote>, baseline: Map<String, Entry>?, deleted: Set<String> = emptySet()): Plan { if (baseline == null) return Plan(emptyList(), emptyList(), emptyList(), refused = "no-baseline") val transfer = ArrayList<String>(); val conflicts = ArrayList<String>(); val same = ArrayList<String>() for ((name, l) in local) { val r = remote[name] val b = baseline[name] when { + r == null && name in deleted && !localChanged(l, b) -> Unit r == null -> transfer += name same(l, r) -> same += name localChanged(l, b) && cloudChanged(r, b) -> conflicts += name diff --git a/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt b/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt index c2fd9890d5..5923cd6e44 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt @@ -430,17 +430,20 @@ object CloudSaves { internal fun md5(data: ByteArray): String = MessageDigest.getInstance("MD5").digest(data).joinToString("") { "%02x".format(it) } - private fun remote(cloud: CloudTransport, wanted: (String) -> Boolean): Map<String, CloudFile> { + private class Listing(val live: Map<String, CloudFile>, val deleted: Set<String>) + + private fun remote(cloud: CloudTransport, wanted: (String) -> Boolean): Listing { val files = cloud.list() val pool = Executors.newFixedThreadPool(PARALLEL, com.droiddeck.launcher.stores.download.DownloadQueue.workerFactory("cloud")) for (f in files) if (wanted(f.name)) pool.execute { runCatching { cloud.details(f) } } pool.shutdown(); pool.awaitTermination(2, TimeUnit.MINUTES) - return files.associateBy { it.name } + val (gone, live) = files.partition(cloud::deleted) + return Listing(live.associateBy { it.name }, gone.mapTo(HashSet()) { it.name }) } internal fun downWith(context: Context, store: Store, id: String, dir: File, cloud: CloudTransport, force: Boolean, claim: () -> Boolean = { true }): Result { val files = localFiles(dir).filterKeys(cloud::wants) - val remote = remote(cloud) { it in files } + val remote = remote(cloud) { it in files }.live val local = files.mapValues { CloudPlan.Local(md5(it.value)) } val key = scope(store, id, dir) val base = baseline(context, store, key) @@ -498,9 +501,10 @@ object CloudSaves { val base = baseline(context, store, key) ?: return Result("skipped", 0, 0, "no-baseline") val files = localFiles(dir).filterKeys(cloud::wants).let { all -> if (cloud is UbisoftCloudTransport) all.filterValues(::markUbisoftSave) else all } if (files.isEmpty()) return Result("skipped", 0, 0, "nothing-local") - val remote = remote(cloud) { it in files } + val listing = remote(cloud) { it in files } + val remote = listing.live val local = files.mapValues { CloudPlan.Local(md5(it.value)) } - val planned = CloudPlan.up(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base) + val planned = CloudPlan.up(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base, listing.deleted) val alike = alike(cloud, planned.conflicts, local, remote) val plan = settled(planned, alike) val saved = savedConflicts(context, store, key).filter { it !in alike && it !in plan.same } @@ -547,7 +551,7 @@ object CloudSaves { send = send.filter { it in stamped } for ((name, t) in stamped) if (t > 0) files[name]?.setLastModified(t) } - val after = if (send.all { cloud.committed(it) != null }) emptyMap() else remote(cloud) { it in send && cloud.committed(it) == null } + val after = if (send.all { cloud.committed(it) != null }) emptyMap() else remote(cloud) { it in send && cloud.committed(it) == null }.live for (name in send) { val r = cloud.committed(name) ?: after[name] next[name] = CloudPlan.Entry(sentMd5.getValue(name), r?.md5, r?.modifiedMs ?: stamped[name] ?: -1L) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/CloudTransport.kt b/app/src/main/java/com/droiddeck/launcher/stores/CloudTransport.kt index 9e0ad99196..efb79d8543 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/CloudTransport.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/CloudTransport.kt @@ -31,6 +31,7 @@ interface CloudTransport { val contentDigests: Boolean get() = true fun committed(name: String): CloudFile? = null fun wants(name: String): Boolean = true + fun deleted(file: CloudFile): Boolean = false fun list(): List<CloudFile> fun details(file: CloudFile) {} fun get(file: CloudFile): Pair<ByteArray, Long> @@ -252,6 +253,8 @@ private fun gzipFile(src: File, dst: File): GzipFile { } } +internal const val GOG_DELETED_MD5 = "aadd86936a80ee8a369579c3926f1b3c" + internal const val GOG_CLOUD_UA = "GOGGalaxyCommunicationService/2.0.13.27 (Windows_32bit) dont_sync_marker/true installation_source/gog" /** GOG Galaxy parses `X-Object-Meta-LocalLastModified`; objects without it fail as "invalid data". */ @@ -276,8 +279,11 @@ class GogCloud( private fun cloudKey(name: String) = key((prefix ?: "") + name) + override fun deleted(file: CloudFile): Boolean = file.md5.equals(GOG_DELETED_MD5, ignoreCase = true) + override fun list(): List<CloudFile> { val c = open(base, "GET", token, ua) + c.setRequestProperty("Accept", "application/json") val code = c.responseCode if (code == 404) { c.disconnect(); return emptyList() } if (code !in 200..299) { @@ -300,7 +306,7 @@ class GogCloud( lm > 0 -> lm * 1000 iso > 0 -> iso else -> -1L - }) + }, o.optString("hash").trim().ifEmpty { null }) } } else { text.lines().map { it.trim() }.filter { it.isNotEmpty() }.map { CloudFile(it, -1L) } diff --git a/app/src/test/java/com/droiddeck/launcher/stores/CloudPlanTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/CloudPlanTest.kt index 1979bece2b..c2ef81ac04 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/CloudPlanTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/CloudPlanTest.kt @@ -48,6 +48,15 @@ class CloudPlanTest { assertEquals(listOf("s"), CloudPlan.up(mapOf("s" to Local("c")), mapOf("s" to Remote("c", 9000)), base).same) } + @Test fun aSaveDeletedInTheCloudGoesUpOnlyOnceItChangesLocally() { + val base = mapOf("s" to Entry("a", "a", 1000), "t" to Entry("x", "x", 1000)) + val gone = setOf("s") + val idle = CloudPlan.up(mapOf("s" to Local("a"), "t" to Local("y"), "n" to Local("new")), mapOf("t" to Remote("x", 1000)), base, gone) + assertEquals(setOf("t", "n"), idle.transfer.toSet()) + assertEquals(listOf("s"), CloudPlan.up(mapOf("s" to Local("b")), emptyMap(), base, gone).transfer) + assertEquals(listOf("s"), CloudPlan.up(mapOf("s" to Local("a")), emptyMap(), base).transfer) + } + @Test fun timesAloneDecideWhenTheServiceGivesNoHash() { val base = mapOf("s" to Entry("a", null, 1000)) assertEquals(listOf("s"), CloudPlan.down(mapOf("s" to Local("a")), mapOf("s" to Remote(null, 60_000)), base).transfer) diff --git a/app/src/test/java/com/droiddeck/launcher/stores/CloudSavesTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/CloudSavesTest.kt index f3944a8034..c2decf0879 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/CloudSavesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/CloudSavesTest.kt @@ -25,7 +25,9 @@ class CloudSavesTest { val puts = ArrayList<String>() var onGet: (CloudFile) -> Unit = {} var raceAfter = Int.MAX_VALUE - override fun list() = files.map { (k, v) -> CloudFile(k, v.second, CloudSaves.md5(v.first)) } + val gone = HashSet<String>() + override fun deleted(file: CloudFile) = file.md5 == GOG_DELETED_MD5 + override fun list() = files.map { (k, v) -> CloudFile(k, v.second, CloudSaves.md5(v.first)) } + gone.map { CloudFile(it, 5000L, GOG_DELETED_MD5) } override fun get(file: CloudFile) = files.getValue(file.name).also { onGet(file) } override fun put(files: Map<String, ByteArray>, modifiedMs: Map<String, Long>): Map<String, Long> { val sent = LinkedHashMap<String, Long>() @@ -40,6 +42,40 @@ class CloudSavesTest { private fun dir() = File(app.filesDir, "saves-${System.nanoTime()}").apply { mkdirs() } private val id get() = "g${System.nanoTime()}" + @Test fun savesTheCloudMarksDeletedAreNotDownloaded() { + val dir = dir() + val cloud = Memory().apply { + files["save1.ess"] = "kept".toByteArray() to 1000L + gone += listOf("save2.ess", "save3.ess", "save3.skse") + } + val r = CloudSaves.downWith(app, Store.GOG, id, dir, cloud, force = true) + assertEquals("ok", r.result); assertEquals(1, r.files) + assertEquals(listOf("save1.ess"), dir.list()!!.sorted()) + } + + @Test fun aLocalSaveTheCloudMarksDeletedIsLeftAlone() { + val dir = dir(); File(dir, "save2.ess").writeText("mine") + val cloud = Memory().apply { files["save1.ess"] = "kept".toByteArray() to 1000L; gone += "save2.ess" } + assertEquals("ok", CloudSaves.downWith(app, Store.GOG, id, dir, cloud, force = false).result) + assertEquals("mine", File(dir, "save2.ess").readText()) + assertEquals("kept", File(dir, "save1.ess").readText()) + } + + @Test fun anUnchangedSaveDeletedInTheCloudIsNotSentBackButANewerOneIs() { + val game = id; val dir = dir() + val cloud = Memory().apply { files["save1.ess"] = "a".toByteArray() to 1000L; files["save2.ess"] = "b".toByteArray() to 1000L } + assertEquals("ok", CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false).result) + cloud.files.remove("save2.ess"); cloud.gone += "save2.ess" + val idle = CloudSaves.upWith(app, Store.GOG, game, dir, cloud, force = false) + assertEquals("up-to-date", idle.reason) + assertTrue(cloud.puts.isEmpty()) + File(dir, "save2.ess").writeText("b played again") + val r = CloudSaves.upWith(app, Store.GOG, game, dir, cloud, force = false) + assertEquals(listOf("save2.ess"), cloud.puts) + assertEquals("b played again", String(cloud.files.getValue("save2.ess").first)) + assertEquals(1, r.files) + } + @Test fun anUploadBeforeAnyDownloadIsRefused() { val dir = dir(); File(dir, "slot0.sav").writeText("fresh profile") val cloud = Memory().apply { files["slot0.sav"] = "real save".toByteArray() to 1000L } diff --git a/app/src/test/java/com/droiddeck/launcher/stores/GogCloudKeysTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/GogCloudKeysTest.kt index d6667e2a12..554948f49e 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/GogCloudKeysTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/GogCloudKeysTest.kt @@ -8,7 +8,12 @@ import org.junit.Assert.assertFalse import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) class GogCloudKeysTest { @Test fun defaultLocationIsStrippedLikeAnyNamedLocation() { val files = listOf(CloudFile("__default/savegame0.sav", 1L), CloudFile("saves/slot0.sav", 2L)) @@ -183,6 +188,24 @@ class GogCloudKeysTest { requests.forEach { assertEquals("Bearer token", it.headers["authorization"]) } } + @Test fun listAsksForJsonAndCarriesGalaxyDeletionMarks() { + val body = "[{\"name\":\"saves/save1.ess\",\"hash\":\"0123456789abcdef0123456789abcdef\",\"last_modified\":\"2026-11-17T22:58:55.038000+00:00\"}," + + "{\"name\":\"saves/save2.ess\",\"hash\":\"$GOG_DELETED_MD5\",\"last_modified\":\"2026-11-17T22:59:00+00:00\"}]" + lateinit var files: List<CloudFile> + lateinit var cloud: GogCloud + val requests = serve(1, { "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: ${body.length}\r\nConnection: close\r\n\r\n$body" }) { url -> + cloud = GogCloud("user", "client", "token", "saves", url) + files = cloud.list() + } + assertEquals("application/json", requests.single().headers["accept"]) + assertEquals(listOf("save1.ess", "save2.ess"), files.map { it.name }) + assertEquals("0123456789abcdef0123456789abcdef", files[0].md5) + assertEquals(1_794_956_335_038L, files[0].modifiedMs) + assertFalse(cloud.deleted(files[0])) + assertTrue(cloud.deleted(files[1])) + assertFalse(cloud.deleted(CloudFile("save3.ess", 1L))) + } + @Test fun rejectedListKeepsTheServerErrorInTheDetail() { val body = "{\"error\":\"invalid_version\",\"error_description\":\"not supported with this version\"}" val failure = runCatching { From 64647e0d992f6758fdd38e71a41d7e22fb9b856a Mon Sep 17 00:00:00 2001 From: Ouse <2216528769@qq.com> Date: Tue, 24 Nov 2026 17:16:35 -0400 Subject: [PATCH 114/141] fix(input): normalize hardware Escape before Back handlers (#2976) --- .../com/droiddeck/launcher/SessionActivity.kt | 9 ++++ .../com/droiddeck/launcher/input/GuestKeys.kt | 6 +++ .../droiddeck/launcher/input/GuestKeysTest.kt | 52 +++++++++++++++++++ 3 files changed, 67 insertions(+) create mode 100644 app/src/test/java/com/droiddeck/launcher/input/GuestKeysTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 556606b77a..98cabab689 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -3552,6 +3552,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde override fun dispatchKeyEvent(event: KeyEvent): Boolean { + val normalized = com.droiddeck.launcher.input.GuestKeys.normalizeKeyboardEscape(event) + if (normalized === event) return dispatchSessionKeyEvent(event) + if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) { + Log.i(TAG, "hardware Esc normalized from Back device=${event.deviceId} scan=${event.scanCode}") + } + return dispatchSessionKeyEvent(normalized) + } + + private fun dispatchSessionKeyEvent(event: KeyEvent): Boolean { if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true when (event.keyCode) { KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> { diff --git a/app/src/main/java/com/droiddeck/launcher/input/GuestKeys.kt b/app/src/main/java/com/droiddeck/launcher/input/GuestKeys.kt index 191760003d..ab626a4246 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/GuestKeys.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/GuestKeys.kt @@ -3,6 +3,12 @@ package com.droiddeck.launcher.input import android.view.KeyEvent object GuestKeys { + fun normalizeKeyboardEscape(event: KeyEvent): KeyEvent { + if (!isKeyboardEscape(event.keyCode, event.scanCode)) return event + return KeyEvent(event.downTime, event.eventTime, event.action, KeyEvent.KEYCODE_ESCAPE, + event.repeatCount, event.metaState, event.deviceId, event.scanCode, event.flags, event.source) + } + /** Sends [event] as evdev presses, with Shift around characters typed by a keyboard that has no Shift key; false when it has no evdev code. */ fun send(event: KeyEvent, sendKey: (code: Int, down: Boolean) -> Unit): Boolean { val down = event.action == KeyEvent.ACTION_DOWN diff --git a/app/src/test/java/com/droiddeck/launcher/input/GuestKeysTest.kt b/app/src/test/java/com/droiddeck/launcher/input/GuestKeysTest.kt new file mode 100644 index 0000000000..28e300aa33 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/GuestKeysTest.kt @@ -0,0 +1,52 @@ +package com.droiddeck.launcher.input + +import android.view.InputDevice +import android.view.KeyEvent +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], manifest = Config.NONE) +class GuestKeysTest { + @Test fun hardwareEscapeBypassesBackMenuAndReachesGuestWithMatchingRelease() { + val taps = mutableListOf<Boolean>() + val menu = BackQamInput({}, taps::add) + val guest = mutableListOf<Pair<Int, Boolean>>() + for (action in listOf(KeyEvent.ACTION_DOWN, KeyEvent.ACTION_UP)) { + val event = KeyEvent(10, 20, action, KeyEvent.KEYCODE_BACK, 0, + KeyEvent.META_SHIFT_ON, 43, 1, 0, InputDevice.SOURCE_KEYBOARD) + val normalized = GuestKeys.normalizeKeyboardEscape(event) + assertEquals(KeyEvent.KEYCODE_ESCAPE, normalized.keyCode) + assertEquals(event.action, normalized.action) + assertEquals(event.metaState, normalized.metaState) + assertEquals(event.deviceId, normalized.deviceId) + assertEquals(event.scanCode, normalized.scanCode) + assertEquals(event.source, normalized.source) + assertFalse(menu.onKeyEvent(normalized, true)) + assertTrue(GuestKeys.send(normalized) { code, down -> guest += code to down }) + } + assertEquals(listOf(1 to true, 1 to false), guest) + assertTrue(taps.isEmpty()) + } + + @Test fun navigationBackAndOtherPhysicalBackKeysAreUnchanged() { + for (scan in listOf(0, 158)) { + val event = KeyEvent(10, 20, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK, + 0, 0, 43, scan, 0, InputDevice.SOURCE_KEYBOARD) + assertSame(event, GuestKeys.normalizeKeyboardEscape(event)) + } + } + + @Test fun normalizedEscapePreservesRepeatAndCancellation() { + val event = KeyEvent(10, 20, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK, + 3, 0, 43, 1, KeyEvent.FLAG_CANCELED, InputDevice.SOURCE_KEYBOARD) + val normalized = GuestKeys.normalizeKeyboardEscape(event) + assertEquals(event.repeatCount, normalized.repeatCount) + assertEquals(event.flags, normalized.flags) + assertEquals(event.downTime, normalized.downTime) + assertEquals(event.eventTime, normalized.eventTime) + } +} From 76e04600649d0374424fee7856709ab4e8704e19 Mon Sep 17 00:00:00 2001 From: Dennis Zabolotny <zdennisz@gmail.com> Date: Tue, 24 Nov 2026 23:16:40 +0200 Subject: [PATCH 115/141] fix(storage): warn when game storage is formatted as FAT32 (#2883) * fix(storage): warn when game storage is formatted as FAT32 FAT32 cannot hold files over 4 GB, so Steam games with larger files fail to install and Steam reports 'Not enough disk space'. Warn when such a card is chosen as game storage. * fix(storage): translate the FAT32 warning into Russian * fix(storage): warn about FAT32 for Automatic, extra libraries and store folders Show the FAT32 note in the Second library menu while the effective card is FAT32, so the default Automatic choice is covered, and warn when an additional Steam library or a store install folder is added. * fix(storage): shorten the FAT32 warning and warn on reselecting a saved folder * fix(storage): warn for the resolved store target and keep the SD note --------- Co-authored-by: Dennis Zabolotny <15849186+zdennisz@users.noreply.github.com> --- .../com/droiddeck/launcher/FrontEndActivity.kt | 8 ++++++++ .../com/droiddeck/launcher/session/GameStorage.kt | 11 +++++++++++ .../droiddeck/launcher/ui/ModeSettingsDialog.kt | 3 ++- .../java/com/droiddeck/launcher/ui/StoragePage.kt | 14 +++++++++++++- app/src/main/res/values-ru/strings.xml | 1 + app/src/main/res/values/strings.xml | 1 + .../droiddeck/launcher/session/GameStorageTest.kt | 14 ++++++++++++++ 7 files changed, 50 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index 1324603ef1..664f9db4c1 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -637,6 +637,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } private var storageDiagnostics by mutableStateOf(false) private var storageOptions by mutableStateOf<List<GameStorage.Option>>(emptyList()) + private var storageFat32 by mutableStateOf(false) private val pickGameStorage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path -> setGameStorage(path, GameStorage.labelFor(this, path)) } } @@ -652,6 +653,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private fun addSteamLibrary(path: String) { Thread({ val result = SteamLibraries.add(this, path) + val fat32 = result is SteamLibraries.AddResult.Added && GameStorage.isFat32(result.entry.path) ui.post { steamLibraries = SteamLibraries.list(this) refreshFoundSteamLibraries() @@ -662,6 +664,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet result is SteamLibraries.AddResult.Added && result.entry.path != path -> android.widget.Toast.makeText(this, getString(R.string.libraries_used_inner, result.entry.label), android.widget.Toast.LENGTH_LONG).show() } + if (fat32) android.widget.Toast.makeText(this, R.string.main_storage_fat32, android.widget.Toast.LENGTH_LONG).show() } }, "steam-library-add").start() } @@ -2668,6 +2671,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet mic = if (mode == SessionService.MODE_STEAM) mic else null, gameStorage = if (mode == SessionService.MODE_STEAM) gameStorage else null, storageOptions = storageOptions, + storageFat32 = storageFat32, steamLibraries = steamLibraries, foundSteamLibraries = foundSteamLibraries, allFilesAccessMissing = allFilesAccessMissing, @@ -3090,10 +3094,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet Thread({ drivers.refreshDrivers() val storage = GameStorage.options(this) + val fat32 = GameStorage.effective(this)?.path?.let(GameStorage::isFat32) == true val deckyInstalled = if (mode == SessionService.MODE_STEAM) DeckyManager.installed(this) else null val deckySupervisor = mode == SessionService.MODE_STEAM && DeckyManager.supervisorEnabled(this) ui.post { storageOptions = storage + storageFat32 = fat32 if (mode == SessionService.MODE_STEAM) { decky.deckyInstalled = deckyInstalled decky.deckySupervisor = deckySupervisor @@ -3115,6 +3121,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } SessionPrefs.setGameStorage(this, path, label) gameStorage = path + storageFat32 = GameStorage.effective(this)?.path?.let(GameStorage::isFat32) == true + if (storageFat32) android.widget.Toast.makeText(this, R.string.main_storage_fat32, android.widget.Toast.LENGTH_LONG).show() checkUsbLink() if (settingsMode == SessionService.MODE_STEAM) refreshFoundSteamLibraries() } diff --git a/app/src/main/java/com/droiddeck/launcher/session/GameStorage.kt b/app/src/main/java/com/droiddeck/launcher/session/GameStorage.kt index e9ecb7443c..263860334c 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/GameStorage.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/GameStorage.kt @@ -43,6 +43,17 @@ object GameStorage { } } + fun isFat32(path: String): Boolean = runCatching { isFat32(path, File("/proc/mounts").readText()) }.getOrDefault(false) + + /** Android mounts FAT32 as vfat and exFAT as exfat; /storage is a FUSE view, so the lookup uses the raw mount. */ + internal fun isFat32(path: String, mounts: String): Boolean { + val raw = UsbLink.rawPath(path) + return mounts.lineSequence().map { it.split(' ') } + .filter { it.size >= 3 } + .filter { val point = it[1].replace("\\040", " "); raw == point || raw.startsWith("${point.trimEnd('/')}/") } + .maxByOrNull { it[1].length }?.get(2) == "vfat" + } + fun effective(context: Context): Option? { val pref = SessionPrefs.gameStorage(context) return when { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt index e931c7ec7a..3f561cae09 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -78,6 +78,7 @@ class ModeSettings( val mic: Boolean?, val gameStorage: String? = null, val storageOptions: List<com.droiddeck.launcher.session.GameStorage.Option> = emptyList(), + val storageFat32: Boolean = false, val steamLibraries: List<com.droiddeck.launcher.session.SteamLibraries.Entry> = emptyList(), val foundSteamLibraries: List<com.droiddeck.launcher.session.SteamLibraries.Found> = emptyList(), val allFilesAccessMissing: Boolean = false, @@ -455,7 +456,7 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: ValueChip(options.firstOrNull { it.path == s.gameStorage }?.chip ?: "-", open) { host.open = if (open) null else "storage" } AnchoredMenu( open, onDismiss = { if (host.open == "storage") host.open = null }, title = stringResource(R.string.mode_second_library), - note = stringResource(R.string.mode_storage_note), + note = stringResource(R.string.mode_storage_note).let { if (s.storageFat32) stringResource(R.string.main_storage_fat32) + "\n" + it else it }, ) { firstItemFocus -> options.forEachIndexed { index, choice -> MenuItem(choice.label, checked = choice.path == s.gameStorage, focusRequester = if (index == 0) firstItemFocus else null) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt index 34ebbbf9f8..00b09f2145 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt @@ -83,6 +83,7 @@ import androidx.compose.ui.unit.sp import coil.compose.AsyncImage import com.droiddeck.launcher.R import com.droiddeck.launcher.files.InAppFilePicker +import com.droiddeck.launcher.session.GameStorage import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.storage.Bucket import com.droiddeck.launcher.storage.CleanItem @@ -179,6 +180,10 @@ private fun DefaultStorageGroup() { val customLabel = SessionPrefs.defaultStorageFolderLabel(ctx).ifBlank { customPath.takeIf { it.isNotBlank() }?.let { File(it).name }.orEmpty() } + fun warnIfFat32() { + val target = StoreInstallRoot.externalTarget(ctx) ?: return + if (GameStorage.isFat32(target.root.path)) Toast.makeText(ctx, R.string.main_storage_fat32, Toast.LENGTH_LONG).show() + } val pickFolder = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if (result.resultCode != Activity.RESULT_OK) return@rememberLauncherForActivityResult val path = InAppFilePicker.pickedPath(result.data) ?: return@rememberLauncherForActivityResult @@ -192,6 +197,7 @@ private fun DefaultStorageGroup() { value = SessionPrefs.DEFAULT_STORAGE_EXTERNAL revision++ open = false + warnIfFat32() } fun chooseFolder() { open = false @@ -250,6 +256,7 @@ private fun DefaultStorageGroup() { SessionPrefs.clearDefaultStorageFolder(ctx) pick(SessionPrefs.DEFAULT_STORAGE_EXTERNAL) revision++ + warnIfFat32() } } if (customPath.isNotBlank()) { @@ -261,7 +268,12 @@ private fun DefaultStorageGroup() { if (free >= 0) stringResource(R.string.storage_default_folder_free, gb(free)) else stringResource(R.string.storage_default_folder_missing) } ?: stringResource(R.string.storage_default_folder_missing), - ) { if (customTarget != null) pick(SessionPrefs.DEFAULT_STORAGE_EXTERNAL) else chooseFolder() } + ) { + if (customTarget != null) { + pick(SessionPrefs.DEFAULT_STORAGE_EXTERNAL) + warnIfFat32() + } else chooseFolder() + } } MenuItem( stringResource(R.string.storage_default_choose_folder), checked = false, diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 5ab0146628..39808f8cbe 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1648,6 +1648,7 @@ <string name="main_pick_game_storage">Выберите папку хранилища игр</string> <string name="main_pick_decky_zip">Выберите ZIP-файл плагина Decky</string> <string name="main_storage_not_usable">Нельзя использовать: %1$s</string> + <string name="main_storage_fat32">FAT32 не поддерживает файлы больше 4 ГБ, поэтому часть игр не установится. Отформатируйте в exFAT.</string> <string name="main_running_program">Программа</string> <string name="main_removing_runtime">Удаление среды выполнения Linux</string> <string name="main_settings_main_screen">Не удалось открыть настройки на нижнем экране; они открыты на главном экране.</string> diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 3837d5f16f..2e9ab89a0e 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1841,6 +1841,7 @@ <string name="main_pick_game_storage">Choose the game storage folder</string> <string name="main_pick_decky_zip">Choose a Decky plugin ZIP</string> <string name="main_storage_not_usable">Not usable: %1$s</string> + <string name="main_storage_fat32">FAT32 cannot hold files over 4 GB, so some games will fail to install. Reformat as exFAT.</string> <string name="main_running_program">Program</string> <string name="main_removing_runtime">Removing Linux runtime</string> <string name="main_settings_main_screen">Could not open Settings on the bottom screen; opened it on the main screen.</string> diff --git a/app/src/test/java/com/droiddeck/launcher/session/GameStorageTest.kt b/app/src/test/java/com/droiddeck/launcher/session/GameStorageTest.kt index b5060392a5..a6b50eb1cc 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/GameStorageTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/GameStorageTest.kt @@ -113,4 +113,18 @@ class GameStorageTest { SessionPrefs.setGameStorage(app, tmp.newFolder("plugged").path, "USB drive") assertFalse(GameStorage.disconnected(app)) } + + @Test fun onlyAVfatMountCountsAsFat32() { + val mounts = """ + /dev/fuse /storage/emulated fuse rw 0 0 + /dev/block/vold/public:179,65 /mnt/media_rw/8C5A-1F23 vfat rw 0 0 + /dev/block/vold/public:8,1 /mnt/media_rw/1111-2222 exfat rw 0 0 + /dev/fuse /storage/8C5A-1F23 fuse rw 0 0 + """.trimIndent() + assertTrue(GameStorage.isFat32("/storage/8C5A-1F23/Android/data/com.droiddeck.launcher/files/steam", mounts)) + assertTrue(GameStorage.isFat32("/mnt/media_rw/8C5A-1F23/Games", mounts)) + assertFalse(GameStorage.isFat32("/storage/1111-2222/Android/data/com.droiddeck.launcher/files/steam", mounts)) + assertFalse(GameStorage.isFat32("/storage/emulated/0/Android/data/com.droiddeck.launcher/files/steam", mounts)) + assertFalse(GameStorage.isFat32("/storage/8C5A-1F230/Games", mounts)) + } } From 86ea861818b137e9fb41011dfc033fdb7b0581f0 Mon Sep 17 00:00:00 2001 From: xlulx <92148312+xlulx@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:16:45 +0300 Subject: [PATCH 116/141] fix(frontend): turn on native DirectX shader compilers for Warband, Don't Starve Together and EU4 (#2998) * fix: turn on d3dx9 and D3DCompiler 42 for Mount & Blade Warband Warband compiles its postFX effects at launch through d3dx9_42. With Wine's built-in d3dcompiler_42 the launch stops on an error dialog (E5017 'Write pass assignments', then E5033 'Unknown target profile __fx_2_0__'). The native d3dx9 and D3DCompiler 42 components fix it, but nothing picked them: Steam's list for the game does not name them and the folder scan only recommends d3dx9. * fix: turn on D3DCompiler 43 for Don't Starve Together Don't Starve Together renders through its bundled ANGLE, which compiles vs_3_0/ps_3_0 shaders with d3dcompiler_43. With Wine's built-in compiler the bytecode trips DXVK's SM3 parser (`m_info.kind == OperandKind::eSrcReg` in sm3_parser.h), the render thread stops after "Renderer initialize: Okay" and the game sits on a black screen. The native D3DCompiler 43 component fixes it, but Steam's list for the game does not name it. * fix: turn on D3DCompiler 43 for Europa Universalis IV EU4 builds its map effects at launch through native d3dx9_43, which compiles them with d3dcompiler_43. Wine's built-in d3dcompiler_43 fails the terrain, border, map name and bloom shaders with E5005 ('No compatible 2 parameter declaration for GetFoWColor'), so the map draws black and province names show as white blocks. Steam's list for the game names only d3dx9; turning on the native D3DCompiler 43 component as well fixes the map. * test: keep one per-game redist test, the one that also covers Steam's d3dx9 pick The Warband and Don't Starve Together tests only restated their SCRIPTED rows; Skyrim's test already covers how SCRIPTED picks are added. --- .../com/droiddeck/launcher/frontend/SteamRedists.kt | 6 ++++++ .../launcher/frontend/WinComponentDetectorsTest.kt | 10 ++++++++++ 2 files changed, 16 insertions(+) diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/SteamRedists.kt b/app/src/main/java/com/droiddeck/launcher/frontend/SteamRedists.kt index 17a2e8b6c8..342bfa9b37 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/SteamRedists.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/SteamRedists.kt @@ -20,6 +20,12 @@ object SteamRedists { val SCRIPTED = mapOf( 72850 to listOf("xact" to "DirectX XACT audio"), 489830 to listOf("xact_x64" to "DirectX XACT audio (64-bit)"), + // Warband compiles its postFX .fx effects at launch through d3dx9_42; Wine's own d3dcompiler_42 stops with E5017/E5033 on fx_2_0. + 48700 to listOf("d3dx9" to "DirectX 9 (d3dx9)", "d3dcompiler_42" to "D3DCompiler 42"), + // DST's bundled ANGLE compiles SM3 shaders through d3dcompiler_43; DXVK's SM3 parser asserts on what Wine's own one emits. + 322330 to listOf("d3dcompiler_43" to "D3DCompiler 43"), + // EU4 builds its map effects through native d3dx9_43, which calls d3dcompiler_43; Wine's own one fails them with E5005, so the map draws black. + 236850 to listOf("d3dx9" to "DirectX 9 (d3dx9)", "d3dcompiler_43" to "D3DCompiler 43"), ) private val BLOCK = Regex("\"SharedDepots\"\\s*\\{([^}]*)\\}", RegexOption.IGNORE_CASE) private val ENTRY = Regex("\"(\\d+)\"\\s+\"\\d+\"") diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/WinComponentDetectorsTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/WinComponentDetectorsTest.kt index cdad5c09b7..d8b1ab708a 100644 --- a/app/src/test/java/com/droiddeck/launcher/frontend/WinComponentDetectorsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/frontend/WinComponentDetectorsTest.kt @@ -54,6 +54,16 @@ class WinComponentDetectorsTest { assertEquals(emptyList<String?>(), WinCompSources.steamList(context, game, 409710, "Other", auto = true).map { it.component }) } + @Test fun eu4GetsTheNativeShaderCompilerItsMapEffectsNeed() { + val steamapps = tmp.newFolder("steamapps") + val game = File(steamapps, "common/Europa Universalis IV").apply { mkdirs() } + File(steamapps, "appmanifest_236850.acf").writeText("\"AppState\"\n{\n\t\"SharedDepots\"\n\t{\n\t\t\"228983\"\t\t\"228980\"\n\t\t\"228990\"\t\t\"228980\"\n\t}\n}\n") + val context = androidx.test.core.app.ApplicationProvider.getApplicationContext<android.content.Context>() + val found = WinCompSources.steamList(context, game, 236850, "Europa Universalis IV", auto = true) + assertEquals(listOf("vcredist2010_dll", "d3dx9", "d3dcompiler_43"), found.map { it.component }) + assertTrue(found.all { it.auto && it.origin == WinCompSources.Origin.STEAM }) + } + @Test fun theGamesInstallScriptRedistsAreInstalledAsSteamWould() { val steamapps = tmp.newFolder("steamapps") val game = File(steamapps, "common/DiRT 3 Complete Edition").apply { mkdirs() } From bcd4e0d99fa87de39e02d040f5904f7cb1d90ff3 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:16:50 -0500 Subject: [PATCH 117/141] fix(agent): the setup install retries on transient source errors and no longer accepts a held-back package (#2904) --- app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt index df90f6f86b..573814f00c 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt @@ -143,9 +143,9 @@ object AgentSetup { listOf("sh", "-c", "set -e; export DEBIAN_FRONTEND=noninteractive; " + "apt() { apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 \"\$@\"; }; " + "dpkg --configure -a || echo 'Some packages are not configured yet; repairing dependencies'; " + - "for i in 1 2 3; do apt update -q && break; echo 'Some package sources could not be refreshed; retrying'; sleep 3; done; " + + "for i in 1 2 3; do apt -o APT::Update::Error-Mode=any update -q && break; echo 'Some package sources could not be refreshed; retrying'; sleep 3; done; " + "apt -f install -y --fix-missing; " + - "apt install -y --fix-missing --no-install-recommends git gh adb curl ca-certificates python3; ${harness.install}") + "apt install -y --no-install-recommends git gh adb curl ca-certificates python3; ${harness.install}") } Step.SIGN_IN -> harness.signIn Step.GITHUB -> listOf("dd-gh-login") From 0a27c8bb98a17eafd79e5f6f9868106d72dfd3d5 Mon Sep 17 00:00:00 2001 From: JM Lambo <jmlambo0517@gmail.com> Date: Tue, 24 Nov 2026 16:16:55 -0500 Subject: [PATCH 118/141] fix(desktop): Firefox renders in software on the system PowerVR driver (#2839) * fix(desktop): Firefox draws on the system PowerVR driver Under the nested KWin on the system PowerVR driver, Firefox's Wayland window stops updating partway through drawing and repaints only where the pointer moves. Through Xwayland it draws normally, so Desktop runs Firefox on X11 on that path. * fix(desktop): Firefox renders in software on the system PowerVR driver The Xwayland workaround only worked because Firefox fell back to software WebRender there. The breakage follows hardware WebRender on zink, not the Wayland window: with MOZ_ACCELERATED=0 Firefox draws correctly on Wayland, so it keeps native Wayland features such as fractional scaling. --------- Co-authored-by: Jacob Lambert <183008808+JMLambo@users.noreply.github.com> --- tools/linuxfs/desktop/droiddeck-desktop | 3 ++ tools/tests/test_desktop_firefox_software.py | 40 ++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 tools/tests/test_desktop_firefox_software.py diff --git a/tools/linuxfs/desktop/droiddeck-desktop b/tools/linuxfs/desktop/droiddeck-desktop index f715ad18d7..64a809b7c9 100644 --- a/tools/linuxfs/desktop/droiddeck-desktop +++ b/tools/linuxfs/desktop/droiddeck-desktop @@ -115,6 +115,9 @@ fi if [ "$(cat /usr/share/droiddeck/kwin-compositor 2>/dev/null)" = opengl ]; then unset LIBGL_ALWAYS_SOFTWARE QT_QUICK_BACKEND export KWIN_COMPOSE=O2 MESA_LOADER_DRIVER_OVERRIDE=zink GALLIUM_DRIVER=zink LIBGL_KOPPER_DRI2=true + # On the system PowerVR driver, Firefox's hardware WebRender on zink leaves stale, half-drawn + # frames; its software renderer draws correctly. + [ "${DD_STEAM_GL_PRESENT:-}" = 1 ] && export MOZ_ACCELERATED=0 if [ -z "${KWIN_RENDER_NODES:-}" ]; then for node in /dev/dri/renderD0 /dev/dri/renderD307 /dev/dri/renderD*; do if [ -c "$node" ]; then export KWIN_RENDER_NODES="$node"; break; fi diff --git a/tools/tests/test_desktop_firefox_software.py b/tools/tests/test_desktop_firefox_software.py new file mode 100644 index 0000000000..b2b839edd3 --- /dev/null +++ b/tools/tests/test_desktop_firefox_software.py @@ -0,0 +1,40 @@ +import os +from pathlib import Path +import subprocess +import unittest + + +DESKTOP = (Path(__file__).resolve().parents[1] / 'linuxfs/desktop/droiddeck-desktop').read_text() +START = 'if [ "$(cat /usr/share/droiddeck/kwin-compositor 2>/dev/null)" = opengl ]; then' +LINE = '\n [ "${DD_STEAM_GL_PRESENT:-}" = 1 ] && export MOZ_ACCELERATED=0\n' + + +class DesktopFirefoxSoftwareTest(unittest.TestCase): + def firefox_environment(self, gl_present): + head = DESKTOP[:DESKTOP.index('\n', DESKTOP.index('export MOZ_ENABLE_WAYLAND=1'))] + head = head[head.rindex('\n') + 1:] + block = DESKTOP[DESKTOP.index(START):] + block = block[block.index('\n') + 1:block.index('\n if [ -z "${KWIN_RENDER_NODES:-}" ]')] + environment = {key: value for key, value in os.environ.items() + if key not in ('DD_STEAM_GL_PRESENT', 'MOZ_ENABLE_WAYLAND', 'MOZ_ACCELERATED')} + if gl_present is not None: + environment['DD_STEAM_GL_PRESENT'] = gl_present + script = head + '\n' + block + '\nsh -c \'echo "wayland:${MOZ_ENABLE_WAYLAND:-unset} accelerated:${MOZ_ACCELERATED:-unset}"\'' + result = subprocess.run(['bash', '-c', script], env=environment, capture_output=True, + text=True, timeout=5) + self.assertEqual(0, result.returncode, result.stderr) + return result.stdout.strip().splitlines()[-1] + + def test_system_powervr_desktop_runs_firefox_on_wayland_with_software_rendering(self): + self.assertEqual('wayland:1 accelerated:0', self.firefox_environment('1')) + + def test_other_drivers_keep_firefox_hardware_rendering(self): + self.assertEqual('wayland:1 accelerated:unset', self.firefox_environment(None)) + self.assertEqual('wayland:1 accelerated:unset', self.firefox_environment('0')) + + def test_override_is_set_before_plasma(self): + self.assertLess(DESKTOP.index(LINE), DESKTOP.index('dbus-run-session -- startplasma-wayland')) + + +if __name__ == '__main__': + unittest.main() From ab023667a0a144b06e403fd720e7997b1a715335 Mon Sep 17 00:00:00 2001 From: Shawn Montgomery <107059169+KvFxKaido@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:17:00 -0600 Subject: [PATCH 119/141] fix(xbox): a bundle's own packaging files don't stop the legacy install (#3003) Halo Wars: Definitive Edition's EAppx bundle leaves AppxBlockmap.xml at the top of the game folder, and its one package folder has its own, so hoist refused the install with "Extraction would overwrite ...". The files a package container carries about itself (AppxBlockMap.xml, AppxSignature.p7x, [Content_Types].xml, AppxMetadata) now replace the bundle's copies, found by name regardless of letter casing. A game file in the way still stops a fresh install. --- tools/xbox/droiddeck-legacy-install.patch | 105 ++++++++++++++++++++-- 1 file changed, 96 insertions(+), 9 deletions(-) diff --git a/tools/xbox/droiddeck-legacy-install.patch b/tools/xbox/droiddeck-legacy-install.patch index 2d34e91679..8de0ebded6 100644 --- a/tools/xbox/droiddeck-legacy-install.patch +++ b/tools/xbox/droiddeck-legacy-install.patch @@ -154,7 +154,7 @@ new file mode 100755 index 0000000..d43c5fc --- /dev/null +++ b/crates/xodus-cli/src/commands/legacy_install.rs -@@ -0,0 +1,1198 @@ +@@ -0,0 +1,1285 @@ +//! Installs a legacy Store title: resolve, license, download, extract. +//! +//! `streaming` only understands MSIXVC, where the container *is* the game and @@ -1119,15 +1119,30 @@ index 0000000..d43c5fc + .map_err(|error| format!("Could not list the package folder: {error}"))? + .filter_map(Result::ok) + { -+ let target = destination.join(entry.file_name()); -+ if target.exists() { -+ if !updating { -+ return Err(format!("Extraction would overwrite {}", target.display())); -+ } -+ let replaced = if target.is_dir() { -+ std::fs::remove_dir_all(&target) ++ let name = entry.file_name(); ++ let target = destination.join(&name); ++ let metadata = is_package_metadata(&name); ++ // The bundle may have written its copy of a packaging file in other letter casing. ++ let existing: Vec<PathBuf> = if metadata { ++ std::fs::read_dir(destination) ++ .map_err(|error| format!("Could not list the game folder: {error}"))? ++ .filter_map(Result::ok) ++ .filter(|other| other.file_name().eq_ignore_ascii_case(&name)) ++ .map(|other| other.path()) ++ .collect() ++ } else if target.exists() { ++ vec![target.clone()] ++ } else { ++ Vec::new() ++ }; ++ if !existing.is_empty() && !updating && !metadata { ++ return Err(format!("Extraction would overwrite {}", target.display())); ++ } ++ for old in existing { ++ let replaced = if old.is_dir() { ++ std::fs::remove_dir_all(&old) + } else { -+ std::fs::remove_file(&target) ++ std::fs::remove_file(&old) + }; + replaced.map_err(|error| format!("Could not replace an installed file: {error}"))?; + } @@ -1138,6 +1153,14 @@ index 0000000..d43c5fc + Ok(()) +} + ++/// Files a package container carries about itself. A bundle leaves its own copies at ++/// the top of the game folder, so the lifted package's copies replace them. ++fn is_package_metadata(name: &std::ffi::OsStr) -> bool { ++ ["AppxBlockMap.xml", "AppxSignature.p7x", "[Content_Types].xml", "AppxMetadata"] ++ .iter() ++ .any(|known| name.eq_ignore_ascii_case(known)) ++} ++ +/// Folders below [root] that carry a manifest, at the depth a nested bundle can +/// write one. A bundle of a bundle is the deepest the extractor produces. +fn nested_packages(root: &Path) -> Vec<PathBuf> { @@ -1261,6 +1284,70 @@ index 0000000..d43c5fc + } + + #[test] ++ fn hoist_replaces_the_bundles_own_packaging_files() { ++ // Halo Wars: Definitive Edition: the bundle leaves AppxBlockmap.xml at the top and ++ // its one package folder has its own. ++ let root = scratch("bundle-metadata"); ++ std::fs::write(root.join("AppxBlockmap.xml"), b"bundle").unwrap(); ++ std::fs::write(root.join("AppxSignature.p7x"), b"bundle").unwrap(); ++ std::fs::create_dir_all(root.join("AppxMetadata")).unwrap(); ++ std::fs::write(root.join("AppxMetadata").join("AppxBundleManifest.xml"), b"bundle").unwrap(); ++ let inner = root.join("Bulldog"); ++ std::fs::create_dir_all(&inner).unwrap(); ++ std::fs::write(inner.join("AppxBlockmap.xml"), b"package").unwrap(); ++ std::fs::write(inner.join("AppxSignature.p7x"), b"package").unwrap(); ++ std::fs::create_dir_all(inner.join("AppxMetadata")).unwrap(); ++ std::fs::write(inner.join("AppxMetadata").join("CodeIntegrity.cat"), b"package").unwrap(); ++ std::fs::write(inner.join(LEGACY_MANIFEST), "<Package/>").unwrap(); ++ std::fs::write(inner.join("xgameFinal.exe"), b"MZ").unwrap(); ++ ++ hoist(&root).unwrap(); ++ ++ assert!(root.join(LEGACY_MANIFEST).is_file()); ++ assert!(root.join("xgameFinal.exe").is_file()); ++ assert_eq!(std::fs::read(root.join("AppxBlockmap.xml")).unwrap(), b"package"); ++ assert_eq!(std::fs::read(root.join("AppxSignature.p7x")).unwrap(), b"package"); ++ // The package's AppxMetadata replaces the bundle's whole; nothing of the bundle's is merged in. ++ assert_eq!(std::fs::read(root.join("AppxMetadata").join("CodeIntegrity.cat")).unwrap(), b"package"); ++ assert!(!root.join("AppxMetadata").join("AppxBundleManifest.xml").exists()); ++ assert!(!inner.exists()); ++ std::fs::remove_dir_all(&root).ok(); ++ } ++ ++ #[test] ++ fn hoist_replaces_a_packaging_file_the_bundle_wrote_in_other_casing() { ++ let root = scratch("metadata-casing"); ++ std::fs::write(root.join("AppxBlockmap.xml"), b"bundle").unwrap(); ++ let inner = root.join("Game"); ++ std::fs::create_dir_all(&inner).unwrap(); ++ std::fs::write(inner.join("AppxBlockMap.xml"), b"package").unwrap(); ++ std::fs::write(inner.join(LEGACY_MANIFEST), "<Package/>").unwrap(); ++ ++ hoist(&root).unwrap(); ++ ++ let maps: Vec<_> = std::fs::read_dir(&root).unwrap().filter_map(Result::ok) ++ .filter(|entry| entry.file_name().eq_ignore_ascii_case("AppxBlockMap.xml")) ++ .collect(); ++ assert_eq!(maps.len(), 1, "the bundle's copy is gone on a case-sensitive filesystem too"); ++ assert_eq!(std::fs::read(maps[0].path()).unwrap(), b"package"); ++ std::fs::remove_dir_all(&root).ok(); ++ } ++ ++ #[test] ++ fn hoist_still_refuses_to_overwrite_a_game_file_on_a_fresh_install() { ++ let root = scratch("fresh-collision"); ++ std::fs::write(root.join("Game.exe"), b"other").unwrap(); ++ let inner = root.join("Game"); ++ std::fs::create_dir_all(&inner).unwrap(); ++ std::fs::write(inner.join(LEGACY_MANIFEST), "<Package/>").unwrap(); ++ std::fs::write(inner.join("Game.exe"), b"MZ").unwrap(); ++ ++ assert!(hoist(&root).unwrap_err().contains("would overwrite")); ++ assert_eq!(std::fs::read(root.join("Game.exe")).unwrap(), b"other"); ++ std::fs::remove_dir_all(&root).ok(); ++ } ++ ++ #[test] + fn hoist_finds_a_manifest_inside_a_nested_bundle() { + let root = scratch("deep"); + let inner = root.join("bundle").join("Microsoft.SunriseBaseGame"); From 2a51b044c5828940842b425e64256fa681e2beb8 Mon Sep 17 00:00:00 2001 From: Moroni Granja <moronigranja@gmail.com> Date: Tue, 24 Nov 2026 18:17:04 -0300 Subject: [PATCH 120/141] fix: a Steam target whose file is gone goes back to the app's exe (#2411) * fix: a Steam target whose file is gone goes back to the app's exe A shortcut Target edited in Steam is kept across the client's restart on purpose, but it was kept even after the file it names disappeared. When the app's own exe already equalled the recorded proposal, nothing replaced the dead target: Steam started `System/launcher.exe`, Wine answered `err:steam:run_process Failed to create process ...: 2`, and the game never ran (#694, after #1644 and #2022 removed the two real causes). The merge now treats a target that is not a file as no edit at all and writes the listing's exe and StartIn. The check runs in the guest, where the shortcut's paths live. Fixes #694 * fix: keep a Steam target whose card is not mounted - The app recreates /mnt/droiddeck-sd and /mnt/bannerlator-sd before binding the card, so the mountpoint outlives a removed card. A target directly under one had an existing parent, so the missing-file repair overwrote the edited Exe and Start In and kept them overwritten. - The repair now needs the target's storage to be there: a card mountpoint that lists nothing is a card that is not in the device, and the edit is kept for when it returns. Extra Steam libraries under /mnt/droiddeck-lib/<id> get the same check. - test_a_steam_target_under_a_bare_card_mountpoint_is_kept fails without the check and asserts both fields; test_a_steam_target_under_a_mounted_card_goes_back_to_the_apps keeps the repair. * fix: repair a Steam target removed with its folder - A missing target is gone when its storage is mounted and either its folder is still there or it lives in a tree the app always has (internal store installs, the internal Steam library). An update that removes the whole game folder now repairs the shortcut. - Store volumes and added game folders are removable mounts too: /mnt/droiddeck-stores/<id> and /root/Games/<name> are checked for content before a target under them is treated as gone, so an unplugged volume keeps the edited Exe and Start In. - Tests: internal folder removed repairs both fields; a bare store mountpoint and a card mountpoint keep both; a mounted card still repairs. 84 tests pass. * fix: classify a Steam target by its resolved path - A target such as /root/Games/Stores/../../../mnt/droiddeck-sd/Other.exe matched the internal prefix and was repaired while the card was out. internal_target and removable_mount now normalize the path before choosing the storage class, so the decision follows the file the target resolves to; the kept text is unchanged. - test_a_steam_target_is_classified_by_its_resolved_path fails before the normalization (the edit is replaced) and keeps both fields after it. 85 tests pass. --- docs/development/stores.md | 7 ++ .../usr/local/bin/droiddeck-steam-shortcuts | 59 ++++++++++- tools/tests/test_steam_shortcuts.py | 97 ++++++++++++++++++- 3 files changed, 160 insertions(+), 3 deletions(-) diff --git a/docs/development/stores.md b/docs/development/stores.md index 9776ac8c4c..16fdf66bc5 100644 --- a/docs/development/stores.md +++ b/docs/development/stores.md @@ -197,6 +197,13 @@ The appid Steam derives (CRC32 of the quoted exe plus the name, high bit set) is listing carries, so the live add and the writer never disagree. Uninstall removes the folder and the listing drops the entry; the live client is asked to remove it too. +`droiddeck-steam-shortcuts` merges each entry against the one Steam holds: a Target or Start In +edited in Steam survives the client's restart. A target whose file is gone is not an edit to keep - +it can only fail before the game starts - so the listing's exe replaces it, checked in the guest +where the shortcut's paths live, as long as the folder holding it exists (a missing folder can be an +unmounted card). #694 was a hand-typed Target that outlived the game update that removed its file, +so every launch died with Wine's `Failed to create process ...: 2` before the game ran. + `Library.SteamGame.source` is `steam`, `gog`, `epic`, `amazon` or `added`; the Library shows it as a chip on every tile and in the hero, and filters by it. diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-shortcuts b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-shortcuts index 4cb3301d41..fc35c0fec3 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-shortcuts +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-shortcuts @@ -125,6 +125,14 @@ RECORD = ".droiddeck-shortcuts.json" AWAY_LIMIT = 256 FIELDS = ("AppName", "Exe", "StartDir", "icon", "LaunchOptions") FOLLOWED = ("StartDir", "LaunchOptions") +# Guest mountpoints whose contents live on storage the user can unplug. The app creates +# the mountpoint before binding it, so it outlives a removed card; libraries, store +# volumes and added game folders get one mountpoint each under these families. +REMOVABLE_ROOTS = ("/mnt/droiddeck-sd", "/mnt/bannerlator-sd") +REMOVABLE_FAMILIES = ("/mnt/droiddeck-lib", "/mnt/droiddeck-stores", "/root/Games") +# Guest trees the app always has, whatever storage is in the device. A target that is +# missing from one of these is gone even when its whole folder was removed. +INTERNAL_ROOTS = ("/root/Games/Stores", "/root/.local/share/Steam") def unquoted(value): @@ -146,6 +154,46 @@ def read_record(path): } +def under(path, root): + return path == root or path.startswith(root + "/") + + +def internal_target(target): + path = os.path.normpath(target) + return any(under(path, root) for root in INTERNAL_ROOTS) + + +def removable_mount(target): + """The guest mountpoint holding target, when it is storage the user can unplug.""" + path = os.path.normpath(target) + for root in REMOVABLE_ROOTS: + if under(path, root): + return root + for family in REMOVABLE_FAMILIES: + prefix = family + "/" + if path.startswith(prefix): + return prefix + path[len(prefix):].split("/", 1)[0] + return None + + +def storage_mounted(target): + """Whether the storage holding target is there this session. + + The app creates a guest mountpoint before binding storage to it, so a mountpoint that + lists nothing is one a removed card or volume left behind. A target under it may work + again when that storage returns, so its absence is not proof the file is gone. + """ + if internal_target(target): + return True + mount = removable_mount(target) + if mount is None: + return True + try: + return bool(os.listdir(mount)) + except OSError: + return False + + def merge(fresh, current, state, seen): state = state if isinstance(state, dict) else {} rev = state.get("rev") if isinstance(state.get("rev"), int) else 0 @@ -158,7 +206,16 @@ def merge(fresh, current, state, seen): entry = dict(current) entry["appid"] = fresh["appid"] exe = unquoted(fresh["Exe"]) - if exe != unquoted(current.get("Exe")) and (exe != unquoted(base.get("Exe")) or seen == rev): + target = unquoted(current.get("Exe")) + # A target Steam still points at after the file is gone starts nothing, so it is not + # an edit to keep: the app's own exe replaces it (#694: a hand-typed Target outlived + # the game update that removed the file, and every launch died before the game ran). + # Only when its storage is mounted and it is missing from a tree the app always has or + # from a folder that is still there. An absent folder under a mountpoint can equally be + # unplugged storage, and that target may work again next session. + gone = (bool(target) and not os.path.isfile(target) and storage_mounted(target) and + (internal_target(target) or os.path.isdir(os.path.dirname(target)))) + if exe != target and (gone or exe != unquoted(base.get("Exe")) or seen == rev): entry["Exe"], entry["StartDir"] = fresh["Exe"], fresh["StartDir"] for field in ("AppName", "icon"): if current.get(field) == base.get(field): diff --git a/tools/tests/test_steam_shortcuts.py b/tools/tests/test_steam_shortcuts.py index a927d4db07..74396e3221 100644 --- a/tools/tests/test_steam_shortcuts.py +++ b/tools/tests/test_steam_shortcuts.py @@ -1,6 +1,7 @@ import importlib.machinery import importlib.util import json +import os from pathlib import Path import subprocess import tempfile @@ -20,7 +21,15 @@ def load(name): shortcuts = load('droiddeck-steam-shortcuts') APPID = 0x87654321 -GUEST = '/root/Games/PC/Example' +GUEST = os.path.join(tempfile.mkdtemp(prefix='droiddeck-shortcuts-'), 'Games/PC/Example') + + +def installed(*paths): + """Creates the files the writer checks, so a Steam edit to one of them is kept.""" + for path in paths: + Path(path).parent.mkdir(parents=True, exist_ok=True) + Path(path).touch() + return paths[0] class ShortcutsTest(unittest.TestCase): @@ -34,7 +43,7 @@ class ShortcutsTest(unittest.TestCase): self.listing = self.root / 'added-games.json' def game(self, exe='Example.exe', seen=0, appid=APPID, name='Example'): - path = GUEST + '/' + exe + path = installed(GUEST + '/' + exe) return dict(name=name, exe=path, folder=GUEST, dir=path.rsplit('/', 1)[0], appid=appid, seen=seen) def run_writer(self, *games): @@ -54,10 +63,32 @@ class ShortcutsTest(unittest.TestCase): if value['appid'] & 0xFFFFFFFF == appid: value.update(fields) path.write_bytes(shortcuts.write({'shortcuts': data})) + if fields.get('Exe'): + target = Path(shortcuts.unquoted(fields['Exe'])) + target.parent.mkdir(parents=True, exist_ok=True) + target.touch() def record(self): return json.loads((self.config / shortcuts.RECORD).read_text()) + def patched(self, **constants): + for name, value in constants.items(): + old = getattr(shortcuts, name) + setattr(shortcuts, name, value) + self.addCleanup(setattr, shortcuts, name, old) + + def merge_target(self, exe, **edits): + """Runs merge against a Steam-edited target, with the app's exe recorded as the base.""" + fresh = shortcuts.shortcut(self.game()) + current = dict(fresh, Exe=exe, **edits) + state = { + 'app': {field: fresh[field] for field in shortcuts.FIELDS}, + 'steam': {field: current.get(field, '') for field in ('AppName', 'Exe', 'StartDir', 'LaunchOptions')}, + 'rev': 1, + } + entry, _ = shortcuts.merge(fresh, current, state, 0) + return entry + def test_settings_changed_in_steam_survive_its_restart(self): self.run_writer(self.game()) edits = dict(Exe='"%s/bin/Other.exe"' % GUEST, StartDir='"%s"' % GUEST, LaunchOptions='DXVK_HUD=1 %command%', @@ -82,6 +113,68 @@ class ShortcutsTest(unittest.TestCase): self.run_writer(self.game()) self.assertEqual(1, self.record()['games'][str(APPID)]['rev']) + def test_a_steam_target_whose_file_is_gone_goes_back_to_the_apps(self): + self.run_writer(self.game()) + self.steam_edits(Exe='"%s/bin/Other.exe"' % GUEST, StartDir='"%s/data"' % GUEST) + Path(shortcuts.unquoted('"%s/bin/Other.exe"' % GUEST)).unlink() + entry = self.run_writer(self.game())[APPID] + self.assertEqual('"%s/Example.exe"' % GUEST, entry['Exe']) + self.assertEqual('"%s"' % GUEST, entry['StartDir']) + self.assertEqual('"%s/Example.exe"' % GUEST, self.record()['games'][str(APPID)]['steam']['Exe']) + + def test_a_steam_target_whose_internal_folder_is_gone_goes_back_to_the_apps(self): + games = self.root / 'games' + (games / 'Stores').mkdir(parents=True) + self.patched(INTERNAL_ROOTS=(str(games / 'Stores'),)) + entry = self.merge_target('"%s/old-version/Other.exe"' % (games / 'Stores'), StartDir='"%s/data"' % GUEST) + self.assertEqual('"%s/Example.exe"' % GUEST, entry['Exe']) + self.assertEqual('"%s"' % GUEST, entry['StartDir']) + + def test_a_steam_target_on_an_unmounted_card_is_kept(self): + card = self.root / 'card' + card.mkdir() + self.patched(REMOVABLE_ROOTS=(str(card),)) + entry = self.merge_target('"%s/steamapps/common/Other.exe"' % card) + self.assertEqual('"%s/steamapps/common/Other.exe"' % card, entry['Exe']) + self.assertEqual('"%s"' % GUEST, entry['StartDir']) + + def test_a_steam_target_under_a_bare_card_mountpoint_is_kept(self): + card = self.root / 'card' + card.mkdir() + self.patched(REMOVABLE_ROOTS=(str(card),)) + entry = self.merge_target('"%s/Other.exe"' % card, StartDir='"%s/data"' % GUEST) + self.assertEqual('"%s/Other.exe"' % card, entry['Exe']) + self.assertEqual('"%s/data"' % GUEST, entry['StartDir']) + + def test_a_steam_target_is_classified_by_its_resolved_path(self): + games = self.root / 'games' + stores = games / 'Stores' + stores.mkdir(parents=True) + card = self.root / 'card' + card.mkdir() + self.patched(INTERNAL_ROOTS=(str(stores),), REMOVABLE_ROOTS=(str(card),)) + target = '"%s/../../card/Other.exe"' % stores + entry = self.merge_target(target, StartDir='"%s/data"' % GUEST) + self.assertEqual(target, entry['Exe']) + self.assertEqual('"%s/data"' % GUEST, entry['StartDir']) + + def test_a_steam_target_under_a_bare_store_mountpoint_is_kept(self): + stores = self.root / 'stores' + mount = stores / 'abcd1234' + mount.mkdir(parents=True) + self.patched(REMOVABLE_FAMILIES=(str(stores),)) + entry = self.merge_target('"%s/Other.exe"' % mount, StartDir='"%s/data"' % GUEST) + self.assertEqual('"%s/Other.exe"' % mount, entry['Exe']) + self.assertEqual('"%s/data"' % GUEST, entry['StartDir']) + + def test_a_steam_target_under_a_mounted_card_goes_back_to_the_apps(self): + card = self.root / 'card' + (card / 'steamapps').mkdir(parents=True) + self.patched(REMOVABLE_ROOTS=(str(card),)) + entry = self.merge_target('"%s/Other.exe"' % card, StartDir='"%s/data"' % GUEST) + self.assertEqual('"%s/Example.exe"' % GUEST, entry['Exe']) + self.assertEqual('"%s"' % GUEST, entry['StartDir']) + def test_the_app_taking_steams_target_keeps_steams_start_in(self): self.run_writer(self.game()) self.steam_edits(Exe='"%s/bin/Other.exe"' % GUEST, StartDir='"%s/data"' % GUEST) From ee6cf20ae4698dffbf3482b3c5cb7ce939eb4822 Mon Sep 17 00:00:00 2001 From: informalTechCode <informaltechyt@gmail.com> Date: Tue, 24 Nov 2026 14:17:12 -0700 Subject: [PATCH 121/141] fix(glasses): correct One Pro+ tracking and enable verified controls (#2680) * fix(glasses): correct One Pro+ tracking and enable verified controls * fix(i18n): translate current XREAL family guidance --- .../droiddeck/launcher/glasses/XrealLink.kt | 17 ++-- .../droiddeck/launcher/glasses/XrealModel.kt | 19 ++-- .../glasses/XrealOrientationFilter.kt | 9 +- app/src/main/res/values-ar/strings.xml | 2 +- app/src/main/res/values-b+es+419/strings.xml | 2 +- app/src/main/res/values-bg/strings.xml | 2 +- app/src/main/res/values-cs/strings.xml | 2 +- app/src/main/res/values-da/strings.xml | 2 +- app/src/main/res/values-de/strings.xml | 2 +- app/src/main/res/values-el/strings.xml | 2 +- app/src/main/res/values-es/strings.xml | 2 +- app/src/main/res/values-fi/strings.xml | 2 +- app/src/main/res/values-fr/strings.xml | 2 +- app/src/main/res/values-hi/strings.xml | 2 +- app/src/main/res/values-hu/strings.xml | 2 +- app/src/main/res/values-in/strings.xml | 2 +- app/src/main/res/values-it/strings.xml | 2 +- app/src/main/res/values-ja/strings.xml | 2 +- app/src/main/res/values-ko/strings.xml | 2 +- app/src/main/res/values-ms/strings.xml | 2 +- app/src/main/res/values-nb/strings.xml | 2 +- app/src/main/res/values-nl/strings.xml | 2 +- app/src/main/res/values-pl/strings.xml | 2 +- app/src/main/res/values-pt-rPT/strings.xml | 2 +- app/src/main/res/values-pt/strings.xml | 2 +- app/src/main/res/values-ro/strings.xml | 2 +- app/src/main/res/values-ru/strings.xml | 2 +- app/src/main/res/values-sv/strings.xml | 2 +- app/src/main/res/values-th/strings.xml | 2 +- app/src/main/res/values-tr/strings.xml | 2 +- app/src/main/res/values-uk/strings.xml | 2 +- app/src/main/res/values-vi/strings.xml | 2 +- app/src/main/res/values-zh-rCN/strings.xml | 2 +- app/src/main/res/values-zh-rHK/strings.xml | 2 +- app/src/main/res/values-zh-rTW/strings.xml | 2 +- app/src/main/res/values/strings.xml | 2 +- .../launcher/glasses/GlassesUsbTest.kt | 28 ++++++ .../launcher/glasses/XrealLinkTest.kt | 25 ++++- .../glasses/XrealOrientationFilterTest.kt | 93 ++++++++++++++++++- .../launcher/glasses/XrealProtocolTest.kt | 67 ++++++++++--- docs/development/xreal-investigation.md | 62 +++++++++++++ docs/smart-glasses-support.md | 7 +- 42 files changed, 325 insertions(+), 68 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/glasses/XrealLink.kt b/app/src/main/java/com/droiddeck/launcher/glasses/XrealLink.kt index d2ea72d4d4..530b315828 100644 --- a/app/src/main/java/com/droiddeck/launcher/glasses/XrealLink.kt +++ b/app/src/main/java/com/droiddeck/launcher/glasses/XrealLink.kt @@ -45,9 +45,8 @@ internal class XrealLink internal constructor( if (msgId == VitureProtocol.MSG_GET_IMU) return true val valid = when (msgId) { VitureProtocol.MSG_GET_DISPLAY -> true - VitureProtocol.MSG_DISPLAY -> if (model.stereoOnlyControl) value == 5 || value == XrealModel.NATIVE_60HZ - else value in 2..5 || value == XrealModel.NATIVE_60HZ - VitureProtocol.MSG_BRIGHTNESS -> !model.stereoOnlyControl && value in 0..9 + VitureProtocol.MSG_DISPLAY -> model.supportsDisplayMode(value) + VitureProtocol.MSG_BRIGHTNESS -> model.hardwareControls && value in 0..model.brightnessMax VitureProtocol.MSG_FILM -> !model.stereoOnlyControl && value in 0..1 else -> false } @@ -64,12 +63,12 @@ internal class XrealLink internal constructor( channels = connector.connect() connection.set(channels) if (!running) break - val control = XrealControl(channels, stereoOnly = model.stereoOnlyControl) + val control = XrealControl(channels, model = model) listener.onValue(VitureProtocol.MSG_GET_DISPLAY, control.display()) val current = channels reports = Thread({ try { - var filter = XrealOrientationFilter(model.flipsYz) + var filter = XrealOrientationFilter(model) var wasTracking = false var lastSensor = System.nanoTime() while (running && connection.get() === current) { @@ -78,7 +77,7 @@ internal class XrealLink internal constructor( if (sample != null) { lastSensor = System.nanoTime() val enabled = tracking - if (enabled && !wasTracking) filter = XrealOrientationFilter(model.flipsYz) + if (enabled && !wasTracking) filter = XrealOrientationFilter(model) wasTracking = enabled if (enabled) filter.update(sample)?.let { if (running && ready && tracking && connection.get() === current) @@ -155,8 +154,9 @@ internal class XrealLink internal constructor( internal class XrealControl( private val channels: XrealChannels, private val settleDelayMs: Long = 150, - private val stereoOnly: Boolean = false, + private val model: XrealModel = XrealModel.ONE_S, ) { + private val stereoOnly get() = model.stereoOnlyControl private var transaction = 0 private fun exchange(command: Int, value: Int? = null): ByteArray { transaction = if (transaction == Int.MAX_VALUE) 1 else transaction + 1 @@ -172,7 +172,7 @@ internal class XrealControl( fun display(): Int { if (stereoOnly) return stereoDisplay() val reply = exchange(XrealProtocol.GET_DISPLAY) - return XrealProtocol.numeric(reply)?.takeIf { it in 2..5 || it == XrealModel.NATIVE_60HZ } + return XrealProtocol.numeric(reply)?.takeIf(model::supportsDisplayMode) ?: throw IOException("Unsupported XREAL display response: ${reply.take(32).joinToString("") { "%02x".format(it) }}") } private fun stereoDisplay(): Int { @@ -187,6 +187,7 @@ internal class XrealControl( } } fun changeDisplay(mode: Int): Int { + require(model.supportsDisplayMode(mode)) val stereo = mode == 5 set(XrealProtocol.SET_INPUT, if (stereo) 1 else 0) val current = awaitDisplay { (it == 5) == stereo } diff --git a/app/src/main/java/com/droiddeck/launcher/glasses/XrealModel.kt b/app/src/main/java/com/droiddeck/launcher/glasses/XrealModel.kt index 70b81995e1..0bb7b7379a 100644 --- a/app/src/main/java/com/droiddeck/launcher/glasses/XrealModel.kt +++ b/app/src/main/java/com/droiddeck/launcher/glasses/XrealModel.kt @@ -4,6 +4,7 @@ internal class XrealModel private constructor( override val name: String, val family: Family, override val diagonalFovDeg: Float, + private val native60Hz: Int = NATIVE_60HZ, ) : GlassesModel { enum class Family { ONE_S, @@ -14,23 +15,25 @@ internal class XrealModel private constructor( override val controllable = true override val brightnessMax = 9 override val volumeMax = 0 - override val hasSunblock get() = family == Family.ONE_S - override val hardwareControls get() = family == Family.ONE_S + override val hasSunblock get() = !stereoOnlyControl + override val hardwareControls get() = !stereoOnlyControl override val sbs90 = false - override val rates2d get() = if (family == Family.ONE_S) super.rates2d else listOf(60) + override val rates2d get() = if (stereoOnlyControl) listOf(60) else super.rates2d - // Only the 1S has been exercised with SET_DISPLAY; the Aura is known to reboot on an unexpected index. - val stereoOnlyControl get() = family != Family.ONE_S + val stereoOnlyControl get() = family != Family.ONE_S && this !== ONE_PRO_PLUS + + internal fun supportsDisplayMode(mode: Int) = if (stereoOnlyControl) mode == 5 || mode == native60Hz + else mode in 3..5 || mode == native60Hz || (this === ONE_S && mode == 2) // The Aura reports x right, y up, z back; the rest of the One family is a half turn about x from it. val flipsYz get() = family != Family.AURA override fun mode(hz: Int, sbs: Boolean) = when { sbs -> 5 - stereoOnlyControl -> NATIVE_60HZ + stereoOnlyControl -> native60Hz hz >= 120 -> 4 hz >= 90 -> 3 - else -> NATIVE_60HZ + else -> native60Hz } override fun modeForStep(step: Int): Int? = null @@ -44,7 +47,7 @@ internal class XrealModel private constructor( val ONE_S = XrealModel("XREAL 1S", Family.ONE_S, 52f) val ONE = XrealModel("XREAL One", Family.ONE, 50f) val ONE_PRO = XrealModel("XREAL One Pro", Family.ONE, 57f) - val ONE_PRO_PLUS = XrealModel("XREAL One Pro+", Family.ONE, 57f) + val ONE_PRO_PLUS = XrealModel("XREAL One Pro+", Family.ONE, 57f, 9) val AURA = XrealModel("XREAL Aura", Family.AURA, 70f) // The odd product ids one below these are the glasses' recovery mode. diff --git a/app/src/main/java/com/droiddeck/launcher/glasses/XrealOrientationFilter.kt b/app/src/main/java/com/droiddeck/launcher/glasses/XrealOrientationFilter.kt index 8bf8dd30e7..ac8e7172c5 100644 --- a/app/src/main/java/com/droiddeck/launcher/glasses/XrealOrientationFilter.kt +++ b/app/src/main/java/com/droiddeck/launcher/glasses/XrealOrientationFilter.kt @@ -2,13 +2,18 @@ package com.droiddeck.launcher.glasses import kotlin.math.abs -internal class XrealOrientationFilter(private val flipYz: Boolean = true) { +internal class XrealOrientationFilter(private val model: XrealModel = XrealModel.ONE_S) { private val fusion = ImuFusion() + private val sensorToDisplay = if (model === XrealModel.ONE_PRO_PLUS) + Quaternion.fromAxisAngle(Vec3(1f, 0f, 0f), Math.toRadians(35.0).toFloat()) else null fun update(sample: XrealProtocol.Sample): FloatArray? = fusion.update(sample.timeNs, sample.accel.headAxes(), sample.gyro.headAxes()) - private fun Vec3.headAxes() = if (flipYz) Vec3(x, -y, -z) else this + private fun Vec3.headAxes(): Vec3 { + val display = sensorToDisplay?.rotate(this) ?: this + return if (model.flipsYz) Vec3(display.x, -display.y, -display.z) else display + } } internal class ImuFusion { diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index c87512c701..973c8bb6c0 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -3218,7 +3218,7 @@ <string name="hand_camera_done">تم</string> <string name="glasses_xreal_network_missing">في انتظار اتصال USB Ethernet الخاص بالنظارة. قد لا يتيحه هذا الهاتف للتطبيقات.</string> <string name="glasses_xreal_connection_failed">انقطع اتصال XREAL أو أعاد استجابة غير مدعومة. جارٍ إعادة المحاولة…</string> - <string name="glasses_xreal_experimental">دعم تجريبي لـ 1S. استخدم وضع Follow وعطّل تثبيت الصورة من قائمة النظارة. لا تزال اتجاهات التتبّع وأوضاع العرض بحاجة إلى اختبار على الجهاز.</string> + <string name="glasses_xreal_experimental">دعم تجريبي لـ XREAL 1S وOne وOne Pro وOne Pro+ وAura. استخدم وضع Follow وأوقف تثبيت الصورة في قائمة النظارة؛ وعلى Aura، أوقف Spatial Anchor أيضًا. تم اختبار تتبع الرأس والتبديل بين 2D/3D على Aura وOne Pro+.</string> <string name="glasses_pro2_experimental">تتبّع تجريبي لحركة الرأس لنظارة Pro 2. لا يُدعم بعد ضبط السطوع ومستوى الصوت أو تبديل وضع العرض.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">وضع Cardboard</string> diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index ef65eef2f4..540eec6450 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1387,7 +1387,7 @@ <string name="hand_camera_done">Hecho</string> <string name="glasses_xreal_network_missing">Esperando la conexión Ethernet por USB de las gafas. Puede que este teléfono no la ofrezca a las apps.</string> <string name="glasses_xreal_connection_failed">La conexión con las XREAL se interrumpió o devolvió una respuesta no compatible. Reintentando…</string> - <string name="glasses_xreal_experimental">Compatibilidad experimental con las 1S. Usa el modo Follow y desactiva la estabilización en el menú de las gafas. Aún falta probar en el dispositivo las direcciones del seguimiento y los modos de pantalla.</string> + <string name="glasses_xreal_experimental">Compatibilidad experimental con XREAL 1S, One, One Pro, One Pro+ y Aura. Usa el modo Follow y desactiva la estabilización en el menú de las gafas; en Aura, desactiva también Spatial Anchor. El seguimiento de cabeza y el cambio entre 2D/3D se han probado en Aura y One Pro+.</string> <string name="glasses_pro2_experimental">Seguimiento de cabeza experimental para Pro 2. Los ajustes de brillo y volumen y el cambio de modo de pantalla aún no son compatibles.</string> <string name="setup_animations">Animaciones</string> <string name="setup_low_storage_warning">Avisar cuando queda poco almacenamiento</string> diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index c6bd2d6bb4..340f2d8467 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -3098,7 +3098,7 @@ <string name="hand_camera_done">Готово</string> <string name="glasses_xreal_network_missing">Изчаква се USB Ethernet връзката на очилата. Този телефон може да не я предоставя на приложенията.</string> <string name="glasses_xreal_connection_failed">Връзката с XREAL беше прекъсната или върна неподдържан отговор. Нов опит…</string> - <string name="glasses_xreal_experimental">Експериментална поддръжка на 1S. Използвайте режим Follow и изключете стабилизацията в менюто на очилата. Посоките на проследяване и режимите на показване все още трябва да се тестват на устройство.</string> + <string name="glasses_xreal_experimental">Експериментална поддръжка на XREAL 1S, One, One Pro, One Pro+ и Aura. Използвайте режим Follow и изключете стабилизацията в менюто на очилата; при Aura изключете и Spatial Anchor. Проследяването на главата и превключването между 2D/3D са тествани на Aura и One Pro+.</string> <string name="glasses_pro2_experimental">Експериментално проследяване на движенията на главата за Pro 2. Регулирането на яркостта и силата на звука и превключването на режима на показване все още не се поддържат.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Режим Cardboard</string> diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 27f25f40eb..9cae733f68 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -3158,7 +3158,7 @@ <string name="hand_camera_done">Hotovo</string> <string name="glasses_xreal_network_missing">Čeká se na připojení USB Ethernet brýlí. Tento telefon ho možná aplikacím nezpřístupňuje.</string> <string name="glasses_xreal_connection_failed">Připojení XREAL bylo přerušeno nebo vrátilo nepodporovanou odpověď. Zkouší se to znovu…</string> - <string name="glasses_xreal_experimental">Experimentální podpora 1S. V nabídce brýlí použijte režim Follow a vypněte stabilizaci. Směry sledování a režimy zobrazení je ještě třeba otestovat na zařízení.</string> + <string name="glasses_xreal_experimental">Experimentální podpora XREAL 1S, One, One Pro, One Pro+ a Aura. V nabídce brýlí použijte režim Follow a vypněte stabilizaci; u modelu Aura vypněte také Spatial Anchor. Sledování hlavy a přepínání 2D/3D bylo otestováno na modelech Aura a One Pro+.</string> <string name="glasses_pro2_experimental">Experimentální sledování pohybu hlavy pro Pro 2. Nastavení jasu, hlasitosti a přepínání režimů zobrazení zatím nejsou podporovány.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Režim Cardboard</string> diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index c2027f4344..59329a1f9e 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -3098,7 +3098,7 @@ <string name="hand_camera_done">Udført</string> <string name="glasses_xreal_network_missing">Venter på brillens USB-Ethernet-forbindelse. Denne telefon gør den muligvis ikke tilgængelig for apps.</string> <string name="glasses_xreal_connection_failed">XREAL-forbindelsen blev afbrudt eller returnerede et svar, der ikke understøttes. Prøver igen…</string> - <string name="glasses_xreal_experimental">Eksperimentel understøttelse af 1S. Brug Follow-tilstand, og slå stabilisering fra i brillens menu. Sporingsretninger og visningstilstande mangler stadig test på enheden.</string> + <string name="glasses_xreal_experimental">Eksperimentel understøttelse af XREAL 1S, One, One Pro, One Pro+ og Aura. Brug Follow-tilstand, og slå stabilisering fra i brillernes menu; på Aura skal du også slå Spatial Anchor fra. Hovedsporing og skift mellem 2D/3D er testet på Aura og One Pro+.</string> <string name="glasses_pro2_experimental">Eksperimentel hovedsporing til Pro 2. Justering af lysstyrke og lydstyrke samt skift af visningstilstand understøttes endnu ikke.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Cardboard-tilstand</string> diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index ae9f0288dc..3559dcecec 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -3087,7 +3087,7 @@ <string name="hand_camera_done">Fertig</string> <string name="glasses_xreal_network_missing">Warte auf die USB-Ethernet-Verbindung der Brille. Dieses Smartphone stellt sie Apps möglicherweise nicht bereit.</string> <string name="glasses_xreal_connection_failed">Die XREAL-Verbindung wurde unterbrochen oder hat eine nicht unterstützte Antwort geliefert. Neuer Versuch …</string> - <string name="glasses_xreal_experimental">Experimentelle Unterstützung für die 1S. Nutze den Follow-Modus und deaktiviere die Stabilisierung im Menü der Brille. Tracking-Richtungen und Anzeigemodi müssen noch auf Geräten getestet werden.</string> + <string name="glasses_xreal_experimental">Experimentelle Unterstützung für XREAL 1S, One, One Pro, One Pro+ und Aura. Nutze den Follow-Modus und deaktiviere die Stabilisierung im Menü der Brille; deaktiviere bei der Aura auch Spatial Anchor. Kopftracking und 2D/3D-Umschaltung wurden auf der Aura und der One Pro+ getestet.</string> <string name="glasses_pro2_experimental">Experimentelles Kopftracking für Pro 2. Das Einstellen von Helligkeit und Lautstärke sowie das Umschalten des Anzeigemodus werden noch nicht unterstützt.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Cardboard-Modus</string> diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index d20cee1822..50903050c4 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -3098,7 +3098,7 @@ <string name="hand_camera_done">Τέλος</string> <string name="glasses_xreal_network_missing">Αναμονή για τη σύνδεση USB Ethernet των γυαλιών. Αυτό το τηλέφωνο ίσως δεν τη διαθέτει στις εφαρμογές.</string> <string name="glasses_xreal_connection_failed">Η σύνδεση XREAL διακόπηκε ή επέστρεψε μη υποστηριζόμενη απόκριση. Νέα προσπάθεια…</string> - <string name="glasses_xreal_experimental">Πειραματική υποστήριξη για 1S. Χρησιμοποιήστε τη λειτουργία Follow και απενεργοποιήστε τη σταθεροποίηση στο μενού των γυαλιών. Οι κατευθύνσεις παρακολούθησης και οι λειτουργίες οθόνης χρειάζονται ακόμα δοκιμή σε συσκευή.</string> + <string name="glasses_xreal_experimental">Πειραματική υποστήριξη για XREAL 1S, One, One Pro, One Pro+ και Aura. Χρησιμοποιήστε τη λειτουργία Follow και απενεργοποιήστε τη σταθεροποίηση στο μενού των γυαλιών· στα Aura απενεργοποιήστε επίσης το Spatial Anchor. Η παρακολούθηση κεφαλής και η εναλλαγή 2D/3D έχουν δοκιμαστεί στα Aura και One Pro+.</string> <string name="glasses_pro2_experimental">Πειραματική παρακολούθηση κεφαλής για Pro 2. Η ρύθμιση της φωτεινότητας και της έντασης ήχου και η αλλαγή λειτουργίας οθόνης δεν υποστηρίζονται ακόμη.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Λειτουργία Cardboard</string> diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index c387ac6ef1..3138760ebe 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -3114,7 +3114,7 @@ <string name="hand_camera_done">Hecho</string> <string name="glasses_xreal_network_missing">Esperando la conexión Ethernet por USB de las gafas. Puede que este teléfono no la ofrezca a las apps.</string> <string name="glasses_xreal_connection_failed">La conexión con las XREAL se interrumpió o devolvió una respuesta no compatible. Reintentando…</string> - <string name="glasses_xreal_experimental">Compatibilidad experimental con las 1S. Usa el modo Follow y desactiva la estabilización en el menú de las gafas. Aún falta probar en el dispositivo las direcciones del seguimiento y los modos de pantalla.</string> + <string name="glasses_xreal_experimental">Compatibilidad experimental con XREAL 1S, One, One Pro, One Pro+ y Aura. Usa el modo Follow y desactiva la estabilización en el menú de las gafas; en Aura, desactiva también Spatial Anchor. El seguimiento de cabeza y el cambio entre 2D/3D se han probado en Aura y One Pro+.</string> <string name="glasses_pro2_experimental">Seguimiento de cabeza experimental para Pro 2. Los ajustes de brillo y volumen y el cambio de modo de pantalla aún no son compatibles.</string> <string name="stores_fact_developer">Desarrollador</string> <string name="stores_fact_publisher">Distribuidor</string> diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 745c743f15..f551a03c7e 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -3098,7 +3098,7 @@ <string name="hand_camera_done">Valmis</string> <string name="glasses_xreal_network_missing">Odotetaan lasien USB-Ethernet-yhteyttä. Tämä puhelin ei ehkä tarjoa sitä sovelluksille.</string> <string name="glasses_xreal_connection_failed">XREAL-yhteys katkesi tai palautti vastauksen, jota ei tueta. Yritetään uudelleen…</string> - <string name="glasses_xreal_experimental">Kokeellinen 1S-tuki. Käytä Follow-tilaa ja poista vakautus käytöstä lasien valikosta. Seurannan suunnat ja näyttötilat vaativat vielä testausta laitteella.</string> + <string name="glasses_xreal_experimental">Kokeellinen tuki XREAL 1S-, One-, One Pro-, One Pro+- ja Aura-laseille. Käytä Follow-tilaa ja poista vakautus käytöstä lasien valikosta. Poista Aura-laseissa myös Spatial Anchor käytöstä. Päänseuranta ja 2D/3D-vaihto on testattu Aura- ja One Pro+ -laseilla.</string> <string name="glasses_pro2_experimental">Kokeellinen päänliikkeiden seuranta Pro 2:lle. Kirkkauden ja äänenvoimakkuuden säätöä sekä näyttötilan vaihtamista ei vielä tueta.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Cardboard-tila</string> diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 0ea39e6371..8a93091282 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -3124,7 +3124,7 @@ <string name="hand_camera_done">Terminé</string> <string name="glasses_xreal_network_missing">En attente de la connexion Ethernet USB des lunettes. Ce téléphone ne la rend peut-être pas accessible aux applications.</string> <string name="glasses_xreal_connection_failed">La connexion XREAL a été interrompue ou a renvoyé une réponse non prise en charge. Nouvelle tentative…</string> - <string name="glasses_xreal_experimental">Prise en charge expérimentale des 1S. Utilisez le mode Follow et désactivez la stabilisation dans le menu des lunettes. Le sens du suivi et les modes d\'affichage restent à tester sur l\'appareil.</string> + <string name="glasses_xreal_experimental">Prise en charge expérimentale des XREAL 1S, One, One Pro, One Pro+ et Aura. Utilisez le mode Follow et désactivez la stabilisation dans le menu des lunettes ; sur les Aura, désactivez aussi Spatial Anchor. Le suivi de la tête et le passage entre 2D/3D ont été testés sur les Aura et les One Pro+.</string> <string name="glasses_pro2_experimental">Suivi expérimental des mouvements de la tête pour Pro 2. Le réglage de la luminosité et du volume ainsi que le changement de mode d\'affichage ne sont pas encore pris en charge.</string> <string name="stores_fact_developer">Développeur</string> <string name="stores_fact_publisher">Éditeur</string> diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 748ae53427..3b76665f48 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -3098,7 +3098,7 @@ <string name="hand_camera_done">हो गया</string> <string name="glasses_xreal_network_missing">चश्मे के USB Ethernet कनेक्शन का इंतज़ार है। हो सकता है यह फ़ोन इसे ऐप्स को उपलब्ध न कराए।</string> <string name="glasses_xreal_connection_failed">XREAL कनेक्शन टूट गया या उसने ऐसा जवाब दिया जो समर्थित नहीं है। फिर से कोशिश हो रही है…</string> - <string name="glasses_xreal_experimental">1S के लिए प्रायोगिक सपोर्ट। चश्मे के मेनू में Follow मोड चुनें और स्टेबिलाइज़ेशन बंद करें। ट्रैकिंग की दिशाएं और डिस्प्ले मोड अभी डिवाइस पर टेस्ट होने बाकी हैं।</string> + <string name="glasses_xreal_experimental">XREAL 1S, One, One Pro, One Pro+ और Aura के लिए प्रायोगिक सपोर्ट। चश्मे के मेनू में Follow मोड चुनें और स्टेबिलाइज़ेशन बंद करें; Aura पर Spatial Anchor भी बंद करें। Aura और One Pro+ पर हेड ट्रैकिंग और 2D/3D स्विचिंग का परीक्षण किया गया है।</string> <string name="glasses_pro2_experimental">Pro 2 के लिए प्रायोगिक हेड ट्रैकिंग। चमक और वॉल्यूम बदलना और डिस्प्ले मोड स्विच करना अभी समर्थित नहीं है।</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Cardboard मोड</string> diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index b941ca7036..ea47bab819 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -3098,7 +3098,7 @@ <string name="hand_camera_done">Kész</string> <string name="glasses_xreal_network_missing">Várakozás a szemüveg USB-s Ethernet-kapcsolatára. Lehet, hogy ez a telefon nem teszi elérhetővé az alkalmazások számára.</string> <string name="glasses_xreal_connection_failed">Az XREAL-kapcsolat megszakadt, vagy nem támogatott választ adott. Újrapróbálkozás…</string> - <string name="glasses_xreal_experimental">Kísérleti 1S-támogatás. Használja a Follow módot, és kapcsolja ki a stabilizálást a szemüveg menüjében. A követési irányokat és a megjelenítési módokat még tesztelni kell az eszközön.</string> + <string name="glasses_xreal_experimental">Az XREAL 1S, One, One Pro, One Pro+ és Aura kísérleti támogatása. Használja a Follow módot, és kapcsolja ki a stabilizálást a szemüveg menüjében; az Aura esetén a Spatial Anchor funkciót is kapcsolja ki. A fejkövetést és a 2D/3D-váltást az Aura és a One Pro+ modelleken teszteltük.</string> <string name="glasses_pro2_experimental">Kísérleti fejkövetés a Pro 2-höz. A fényerő és a hangerő beállítása, valamint a megjelenítési mód váltása még nem támogatott.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Cardboard mód</string> diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index a64e7a8f82..110833e35e 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -3069,7 +3069,7 @@ <string name="hand_camera_done">Selesai</string> <string name="glasses_xreal_network_missing">Menunggu koneksi Ethernet USB dari kacamata. Ponsel ini mungkin tidak menyediakannya untuk aplikasi.</string> <string name="glasses_xreal_connection_failed">Koneksi XREAL terputus atau memberikan respons yang tidak didukung. Mencoba lagi…</string> - <string name="glasses_xreal_experimental">Dukungan 1S eksperimental. Gunakan mode Follow dan nonaktifkan stabilisasi di menu kacamata. Arah pelacakan dan mode tampilan masih perlu diuji di perangkat.</string> + <string name="glasses_xreal_experimental">Dukungan eksperimental untuk XREAL 1S, One, One Pro, One Pro+, dan Aura. Gunakan mode Follow dan nonaktifkan stabilisasi di menu kacamata; pada Aura, nonaktifkan juga Spatial Anchor. Pelacakan kepala dan peralihan 2D/3D telah diuji pada Aura dan One Pro+.</string> <string name="glasses_pro2_experimental">Pelacakan kepala Pro 2 eksperimental. Pengaturan kecerahan, volume, dan pergantian mode tampilan belum didukung.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Mode Cardboard</string> diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 917a683301..8ec37be21e 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -3116,7 +3116,7 @@ <string name="hand_camera_done">Fine</string> <string name="glasses_xreal_network_missing">In attesa della connessione USB Ethernet degli occhiali. Questo telefono potrebbe non renderla disponibile alle app.</string> <string name="glasses_xreal_connection_failed">La connessione XREAL si è interrotta o ha restituito una risposta non supportata. Nuovo tentativo…</string> - <string name="glasses_xreal_experimental">Supporto sperimentale per 1S. Usa la modalità Follow e disattiva la stabilizzazione nel menu degli occhiali. Direzioni del tracciamento e modalità di visualizzazione devono ancora essere testate sul dispositivo.</string> + <string name="glasses_xreal_experimental">Supporto sperimentale per XREAL 1S, One, One Pro, One Pro+ e Aura. Usa la modalità Follow e disattiva la stabilizzazione nel menu degli occhiali; su Aura, disattiva anche Spatial Anchor. Il tracciamento della testa e il passaggio tra 2D/3D sono stati testati su Aura e One Pro+.</string> <string name="glasses_pro2_experimental">Tracciamento sperimentale della testa per Pro 2. La regolazione di luminosità e volume e il cambio della modalità di visualizzazione non sono ancora supportati.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Modalità Cardboard</string> diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 83165c7ccc..e012fed66b 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -3069,7 +3069,7 @@ <string name="hand_camera_done">完了</string> <string name="glasses_xreal_network_missing">グラスの USB Ethernet 接続を待っています。このスマートフォンでは、アプリがこの接続を利用できない場合があります。</string> <string name="glasses_xreal_connection_failed">XREAL との接続が中断されたか、サポートされていない応答が返されました。再試行しています…</string> - <string name="glasses_xreal_experimental">1S のサポートは試験運用中です。グラスのメニューで Follow モードを使い、安定化をオフにしてください。トラッキングの方向と表示モードは、まだ実機でのテストが必要です。</string> + <string name="glasses_xreal_experimental">XREAL 1S、One、One Pro、One Pro+、Auraの試験的なサポートです。グラスのメニューでFollowモードを使用し、安定化をオフにしてください。AuraではSpatial Anchorもオフにしてください。ヘッドトラッキングと2D/3D切り替えは、AuraとOne Pro+でテスト済みです。</string> <string name="glasses_pro2_experimental">Pro 2 のヘッドトラッキングは試験運用中です。明るさと音量の調整、および表示モードの切り替えにはまだ対応していません。</string> <string name="stores_fact_developer">開発元</string> <string name="stores_fact_publisher">パブリッシャー</string> diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 975138121c..337c0d437e 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -3069,7 +3069,7 @@ <string name="hand_camera_done">완료</string> <string name="glasses_xreal_network_missing">안경의 USB Ethernet 연결을 기다리는 중입니다. 이 휴대폰은 앱에 이 연결을 제공하지 않을 수 있습니다.</string> <string name="glasses_xreal_connection_failed">XREAL 연결이 중단되었거나 지원되지 않는 응답을 받았습니다. 다시 시도하는 중…</string> - <string name="glasses_xreal_experimental">1S 지원은 실험 단계입니다. 안경 메뉴에서 Follow 모드를 사용하고 안정화를 끄세요. 트래킹 방향과 디스플레이 모드는 아직 기기에서 테스트가 필요합니다.</string> + <string name="glasses_xreal_experimental">XREAL 1S, One, One Pro, One Pro+ 및 Aura의 실험적 지원입니다. 안경 메뉴에서 Follow 모드를 사용하고 안정화를 끄세요. Aura에서는 Spatial Anchor도 끄세요. 헤드 트래킹과 2D/3D 전환은 Aura와 One Pro+에서 테스트되었습니다.</string> <string name="glasses_pro2_experimental">Pro 2 헤드 트래킹은 실험 단계입니다. 밝기와 음량 조절 및 디스플레이 모드 전환은 아직 지원되지 않습니다.</string> <string name="stores_fact_developer">개발사</string> <string name="stores_fact_publisher">배급사</string> diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index c2a3e5634b..ef8393e099 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -3069,7 +3069,7 @@ <string name="hand_camera_done">Selesai</string> <string name="glasses_xreal_network_missing">Menunggu sambungan USB Ethernet cermin mata. Telefon ini mungkin tidak mendedahkannya kepada apl.</string> <string name="glasses_xreal_connection_failed">Sambungan XREAL terganggu atau memberikan respons yang tidak disokong. Mencuba semula…</string> - <string name="glasses_xreal_experimental">Sokongan eksperimen untuk 1S. Gunakan mod Follow dan matikan penstabilan dalam menu cermin mata. Arah penjejakan dan mod paparan masih perlu diuji pada peranti.</string> + <string name="glasses_xreal_experimental">Sokongan eksperimen untuk XREAL 1S, One, One Pro, One Pro+ dan Aura. Gunakan mod Follow dan matikan penstabilan dalam menu cermin mata; pada Aura, matikan juga Spatial Anchor. Penjejakan kepala dan pertukaran 2D/3D telah diuji pada Aura dan One Pro+.</string> <string name="glasses_pro2_experimental">Penjejakan kepala Pro 2 secara eksperimen. Pelarasan kecerahan, kelantangan dan pertukaran mod paparan belum disokong.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Mod Cardboard</string> diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index 9e7c805abb..81e2cfd0ba 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -3098,7 +3098,7 @@ <string name="hand_camera_done">Ferdig</string> <string name="glasses_xreal_network_missing">Venter på USB Ethernet-tilkoblingen til brillene. Denne telefonen gjør den kanskje ikke tilgjengelig for apper.</string> <string name="glasses_xreal_connection_failed">XREAL-tilkoblingen ble avbrutt eller ga et svar som ikke støttes. Prøver igjen…</string> - <string name="glasses_xreal_experimental">Eksperimentell støtte for 1S. Bruk Follow-modus og slå av stabilisering i brillemenyen. Sporingsretninger og visningsmoduser må fortsatt testes på enheten.</string> + <string name="glasses_xreal_experimental">Eksperimentell støtte for XREAL 1S, One, One Pro, One Pro+ og Aura. Bruk Follow-modus og slå av stabilisering i brillemenyen; på Aura må du også slå av Spatial Anchor. Hodesporing og bytte mellom 2D/3D er testet på Aura og One Pro+.</string> <string name="glasses_pro2_experimental">Eksperimentell hodesporing for Pro 2. Justering av lysstyrke og volum samt bytte av visningsmodus støttes ikke ennå.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Cardboard-modus</string> diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 7387841e29..2a8fb73b58 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -3098,7 +3098,7 @@ <string name="hand_camera_done">Klaar</string> <string name="glasses_xreal_network_missing">Wachten op de USB Ethernet-verbinding van de bril. Deze telefoon maakt die mogelijk niet beschikbaar voor apps.</string> <string name="glasses_xreal_connection_failed">De XREAL-verbinding is onderbroken of gaf een niet-ondersteund antwoord. Opnieuw proberen…</string> - <string name="glasses_xreal_experimental">Experimentele ondersteuning voor 1S. Gebruik de Follow-modus en schakel stabilisatie uit in het menu van de bril. Trackingrichtingen en weergavemodi moeten nog op een apparaat worden getest.</string> + <string name="glasses_xreal_experimental">Experimentele ondersteuning voor XREAL 1S, One, One Pro, One Pro+ en Aura. Gebruik de Follow-modus en schakel stabilisatie uit in het menu van de bril; schakel op de Aura ook Spatial Anchor uit. Hoofdtracking en schakelen tussen 2D/3D zijn getest op de Aura en One Pro+.</string> <string name="glasses_pro2_experimental">Experimentele hoofdtracking voor Pro 2. Het aanpassen van helderheid en volume en het wisselen van weergavemodus worden nog niet ondersteund.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Cardboard-modus</string> diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 39ed9658ef..4fcc9f537b 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -3158,7 +3158,7 @@ <string name="hand_camera_done">Gotowe</string> <string name="glasses_xreal_network_missing">Oczekiwanie na połączenie USB Ethernet okularów. Ten telefon może nie udostępniać go aplikacjom.</string> <string name="glasses_xreal_connection_failed">Połączenie z XREAL zostało przerwane lub zwróciło nieobsługiwaną odpowiedź. Ponawianie…</string> - <string name="glasses_xreal_experimental">Eksperymentalna obsługa 1S. Użyj trybu Follow i wyłącz stabilizację w menu okularów. Kierunki śledzenia i tryby wyświetlania wymagają jeszcze testów na urządzeniu.</string> + <string name="glasses_xreal_experimental">Eksperymentalna obsługa XREAL 1S, One, One Pro, One Pro+ i Aura. Użyj trybu Follow i wyłącz stabilizację w menu okularów; na Aura wyłącz też Spatial Anchor. Śledzenie głowy i przełączanie między 2D/3D przetestowano na Aura i One Pro+.</string> <string name="glasses_pro2_experimental">Eksperymentalne śledzenie ruchów głowy dla Pro 2. Regulacja jasności i głośności oraz przełączanie trybu wyświetlania nie są jeszcze obsługiwane.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Tryb Cardboard</string> diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index b4202d6bef..12267238f7 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -3130,7 +3130,7 @@ <string name="hand_camera_done">Concluído</string> <string name="glasses_xreal_network_missing">A aguardar a ligação Ethernet por USB dos óculos. Este telemóvel pode não a disponibilizar às apps.</string> <string name="glasses_xreal_connection_failed">A ligação aos óculos XREAL foi interrompida ou devolveu uma resposta não suportada. A tentar novamente…</string> - <string name="glasses_xreal_experimental">Suporte experimental para os 1S. Utilize o modo Follow e desative a estabilização no menu dos óculos. As direções de seguimento e os modos de ecrã ainda têm de ser testados no dispositivo.</string> + <string name="glasses_xreal_experimental">Suporte experimental para XREAL 1S, One, One Pro, One Pro+ e Aura. Utilize o modo Follow e desative a estabilização no menu dos óculos; no Aura, desative também Spatial Anchor. O seguimento da cabeça e a alternância entre 2D/3D foram testados nos modelos Aura e One Pro+.</string> <string name="glasses_pro2_experimental">Seguimento experimental dos movimentos da cabeça para Pro 2. O ajuste do brilho e do volume e a mudança do modo de ecrã ainda não são suportados.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Modo Cardboard</string> diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index be543f1960..e51abbbead 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -3138,7 +3138,7 @@ <string name="hand_camera_done">Concluído</string> <string name="glasses_xreal_network_missing">Aguardando a conexão Ethernet por USB dos óculos. Este celular pode não disponibilizá-la para os apps.</string> <string name="glasses_xreal_connection_failed">A conexão com os óculos XREAL foi interrompida ou retornou uma resposta incompatível. Tentando novamente…</string> - <string name="glasses_xreal_experimental">Suporte experimental ao 1S. Use o modo Follow e desative a estabilização no menu dos óculos. As direções do rastreamento e os modos de exibição ainda precisam de testes no dispositivo.</string> + <string name="glasses_xreal_experimental">Suporte experimental a XREAL 1S, One, One Pro, One Pro+ e Aura. Use o modo Follow e desative a estabilização no menu dos óculos; no Aura, desative também Spatial Anchor. O rastreamento de cabeça e a alternância entre 2D/3D foram testados nos modelos Aura e One Pro+.</string> <string name="glasses_pro2_experimental">Rastreamento experimental da cabeça para Pro 2. Os ajustes de brilho e volume e a troca do modo de exibição ainda não são compatíveis.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Modo Cardboard</string> diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index a56231bf01..89e8d30b85 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -3128,7 +3128,7 @@ <string name="hand_camera_done">Gata</string> <string name="glasses_xreal_network_missing">Se așteaptă conexiunea USB Ethernet a ochelarilor. Este posibil ca acest telefon să nu o expună aplicațiilor.</string> <string name="glasses_xreal_connection_failed">Conexiunea XREAL a fost întreruptă sau a returnat un răspuns neacceptat. Se reîncearcă…</string> - <string name="glasses_xreal_experimental">Suport experimental pentru 1S. Folosește modul Follow și dezactivează stabilizarea din meniul ochelarilor. Direcțiile de urmărire și modurile de afișare trebuie încă testate pe dispozitiv.</string> + <string name="glasses_xreal_experimental">Suport experimental pentru XREAL 1S, One, One Pro, One Pro+ și Aura. Folosește modul Follow și dezactivează stabilizarea din meniul ochelarilor; pe Aura, dezactivează și Spatial Anchor. Urmărirea capului și comutarea între 2D/3D au fost testate pe Aura și One Pro+.</string> <string name="glasses_pro2_experimental">Urmărire experimentală a mișcărilor capului pentru Pro 2. Reglarea luminozității și a volumului și schimbarea modului de afișare nu sunt încă acceptate.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Mod Cardboard</string> diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 39808f8cbe..09bb9155f6 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -3156,7 +3156,7 @@ <string name="hand_camera_done">Готово</string> <string name="glasses_xreal_network_missing">Ожидание подключения очков по USB Ethernet. Этот телефон может не предоставлять его приложениям.</string> <string name="glasses_xreal_connection_failed">Подключение к XREAL прервано или получен неподдерживаемый ответ. Повторная попытка…</string> - <string name="glasses_xreal_experimental">Экспериментальная поддержка 1S. Включите режим Follow и отключите стабилизацию в меню очков. Направления отслеживания и режимы отображения ещё нужно проверить на устройстве.</string> + <string name="glasses_xreal_experimental">Экспериментальная поддержка XREAL 1S, One, One Pro, One Pro+ и Aura. Используйте режим Follow и отключите стабилизацию в меню очков; на Aura также отключите Spatial Anchor. Отслеживание головы и переключение между 2D/3D проверены на Aura и One Pro+.</string> <string name="glasses_pro2_experimental">Экспериментальное отслеживание движений головы для Pro 2. Настройка яркости и громкости и переключение режимов отображения пока не поддерживаются.</string> <string name="stores_fact_developer">Разработчик</string> <string name="stores_fact_publisher">Издатель</string> diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 52148d23fa..69960f0a1b 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -3098,7 +3098,7 @@ <string name="hand_camera_done">Klar</string> <string name="glasses_xreal_network_missing">Väntar på glasögonens USB Ethernet-anslutning. Telefonen kanske inte gör den tillgänglig för appar.</string> <string name="glasses_xreal_connection_failed">XREAL-anslutningen avbröts eller gav ett svar som inte stöds. Försöker igen…</string> - <string name="glasses_xreal_experimental">Experimentellt stöd för 1S. Använd Follow-läget och stäng av stabiliseringen i glasögonens meny. Spårningsriktningar och visningslägen behöver fortfarande testas på enheten.</string> + <string name="glasses_xreal_experimental">Experimentellt stöd för XREAL 1S, One, One Pro, One Pro+ och Aura. Använd Follow-läget och stäng av stabiliseringen i glasögonens meny; på Aura ska du även stänga av Spatial Anchor. Huvudspårning och växling mellan 2D/3D har testats på Aura och One Pro+.</string> <string name="glasses_pro2_experimental">Experimentell huvudspårning för Pro 2. Justering av ljusstyrka och volym samt byte av visningsläge stöds inte ännu.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Cardboard-läge</string> diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index c3fdeeaecd..924715aad9 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -3069,7 +3069,7 @@ <string name="hand_camera_done">เสร็จสิ้น</string> <string name="glasses_xreal_network_missing">กำลังรอการเชื่อมต่อ USB Ethernet ของแว่นตา โทรศัพท์นี้อาจไม่เปิดให้แอปเข้าถึงการเชื่อมต่อนี้</string> <string name="glasses_xreal_connection_failed">การเชื่อมต่อ XREAL ขาดหายหรือได้รับการตอบกลับที่ไม่รองรับ กำลังลองใหม่…</string> - <string name="glasses_xreal_experimental">รองรับ 1S แบบทดลอง ใช้โหมด Follow และปิดการกันสั่นในเมนูของแว่นตา ทิศทางการติดตามและโหมดการแสดงผลยังต้องทดสอบกับอุปกรณ์จริง</string> + <string name="glasses_xreal_experimental">รองรับ XREAL 1S, One, One Pro, One Pro+ และ Aura แบบทดลอง ใช้โหมด Follow และปิดการกันสั่นในเมนูของแว่นตา สำหรับ Aura ให้ปิด Spatial Anchor ด้วย การติดตามศีรษะและการสลับ 2D/3D ผ่านการทดสอบบน Aura และ One Pro+ แล้ว</string> <string name="glasses_pro2_experimental">การติดตามศีรษะแบบทดลองสำหรับ Pro 2 ยังไม่รองรับการปรับความสว่าง ระดับเสียง และการสลับโหมดการแสดงผล</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">โหมด Cardboard</string> diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index caf7177e66..0056965a36 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -3087,7 +3087,7 @@ <string name="hand_camera_done">Bitti</string> <string name="glasses_xreal_network_missing">Gözlüğün USB Ethernet bağlantısı bekleniyor. Bu telefon bu bağlantıyı uygulamalara açmıyor olabilir.</string> <string name="glasses_xreal_connection_failed">XREAL bağlantısı kesildi veya desteklenmeyen bir yanıt döndü. Yeniden deneniyor…</string> - <string name="glasses_xreal_experimental">Deneysel 1S desteği. Gözlük menüsünde Follow modunu kullanın ve görüntü sabitlemeyi kapatın. Takip yönlerinin ve ekran modlarının hâlâ cihazda test edilmesi gerekiyor.</string> + <string name="glasses_xreal_experimental">Deneysel XREAL 1S, One, One Pro, One Pro+ ve Aura desteği. Gözlük menüsünde Follow modunu kullanın ve görüntü sabitlemeyi kapatın; Aura üzerinde Spatial Anchor özelliğini de kapatın. Kafa takibi ve 2D/3D geçişi Aura ve One Pro+ üzerinde test edilmiştir.</string> <string name="glasses_pro2_experimental">Pro 2 için deneysel baş takibi. Parlaklık ve ses düzeyi ayarı ile ekran modu değiştirme henüz desteklenmiyor.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Cardboard modu</string> diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 866823452d..3505527050 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -3158,7 +3158,7 @@ <string name="hand_camera_done">Готово</string> <string name="glasses_xreal_network_missing">Очікування з’єднання USB Ethernet від окулярів. Цей телефон може не надавати його додаткам.</string> <string name="glasses_xreal_connection_failed">З’єднання з XREAL перервалося або повернуло непідтримувану відповідь. Повторна спроба…</string> - <string name="glasses_xreal_experimental">Експериментальна підтримка 1S. Увімкніть режим Follow і вимкніть стабілізацію в меню окулярів. Напрямки відстеження й режими відображення ще потрібно перевірити на пристрої.</string> + <string name="glasses_xreal_experimental">Експериментальна підтримка XREAL 1S, One, One Pro, One Pro+ та Aura. Використовуйте режим Follow і вимкніть стабілізацію в меню окулярів; на Aura також вимкніть Spatial Anchor. Відстеження голови та перемикання між 2D/3D перевірено на Aura й One Pro+.</string> <string name="glasses_pro2_experimental">Експериментальне відстеження рухів голови для Pro 2. Налаштування яскравості й гучності та перемикання режимів відображення ще не підтримуються.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Режим Cardboard</string> diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index d59ef76086..5598b9b8f2 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -3069,7 +3069,7 @@ <string name="hand_camera_done">Xong</string> <string name="glasses_xreal_network_missing">Đang chờ kết nối USB Ethernet của kính. Điện thoại này có thể không cho ứng dụng truy cập kết nối đó.</string> <string name="glasses_xreal_connection_failed">Kết nối XREAL bị gián đoạn hoặc trả về phản hồi không được hỗ trợ. Đang thử lại…</string> - <string name="glasses_xreal_experimental">Hỗ trợ 1S thử nghiệm. Dùng chế độ Follow và tắt ổn định hình ảnh trong menu của kính. Hướng theo dõi và các chế độ hiển thị vẫn cần thử nghiệm trên thiết bị.</string> + <string name="glasses_xreal_experimental">Hỗ trợ thử nghiệm cho XREAL 1S, One, One Pro, One Pro+ và Aura. Dùng chế độ Follow và tắt ổn định hình ảnh trong menu của kính; trên Aura, hãy tắt cả Spatial Anchor. Tính năng theo dõi đầu và chuyển đổi 2D/3D đã được thử nghiệm trên Aura và One Pro+.</string> <string name="glasses_pro2_experimental">Theo dõi chuyển động đầu thử nghiệm cho Pro 2. Chưa hỗ trợ điều chỉnh độ sáng, âm lượng và chuyển chế độ hiển thị.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Chế độ Cardboard</string> diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 36465dc7c6..7df9807375 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -3069,7 +3069,7 @@ <string name="hand_camera_done">完成</string> <string name="glasses_xreal_network_missing">正在等待眼镜的 USB Ethernet 连接。这部手机可能不向应用开放此连接。</string> <string name="glasses_xreal_connection_failed">XREAL 连接中断或返回了不受支持的响应。正在重试…</string> - <string name="glasses_xreal_experimental">实验性 1S 支持。请在眼镜菜单中使用跟随模式并关闭防抖。追踪方向和显示模式仍需在设备上测试。</string> + <string name="glasses_xreal_experimental">实验性支持 XREAL 1S、One、One Pro、One Pro+ 和 Aura。请在眼镜菜单中使用 Follow 模式并关闭防抖;在 Aura 上还需关闭 Spatial Anchor。头部追踪和 2D/3D 切换已在 Aura 和 One Pro+ 上测试。</string> <string name="glasses_pro2_experimental">Pro 2 实验性头部追踪。暂不支持亮度、音量调节和显示模式切换。</string> <string name="stores_fact_developer">开发商</string> <string name="stores_fact_publisher">发行商</string> diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 0a476b26f1..6eb5d1a6dd 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -3066,7 +3066,7 @@ <string name="hand_camera_done">完成</string> <string name="glasses_xreal_network_missing">正在等候眼鏡的 USB Ethernet 連線。這部手機可能不會向應用程式開放此連線。</string> <string name="glasses_xreal_connection_failed">XREAL 連線中斷或傳回不支援的回應。正在重試…</string> - <string name="glasses_xreal_experimental">實驗性 1S 支援。請在眼鏡選單中使用跟隨模式並關閉畫面穩定。追蹤方向和顯示模式仍需在裝置上測試。</string> + <string name="glasses_xreal_experimental">實驗性支援 XREAL 1S、One、One Pro、One Pro+ 和 Aura。請在眼鏡選單中使用 Follow 模式並關閉畫面穩定;在 Aura 上亦需關閉 Spatial Anchor。頭部追蹤和 2D/3D 切換已在 Aura 和 One Pro+ 上測試。</string> <string name="glasses_pro2_experimental">Pro 2 實驗性頭部追蹤。暫不支援亮度、音量調整及顯示模式切換。</string> <string name="stores_fact_developer">開發商</string> <string name="stores_fact_publisher">發行商</string> diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 9836945224..a678d12b2c 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -3066,7 +3066,7 @@ <string name="hand_camera_done">完成</string> <string name="glasses_xreal_network_missing">正在等待眼鏡的 USB Ethernet 連線。這支手機可能不會向應用程式開放此連線。</string> <string name="glasses_xreal_connection_failed">XREAL 連線中斷或傳回不支援的回應。正在重試…</string> - <string name="glasses_xreal_experimental">實驗性 1S 支援。請在眼鏡選單中使用跟隨模式並關閉畫面穩定。追蹤方向和顯示模式仍需在實機上測試。</string> + <string name="glasses_xreal_experimental">實驗性支援 XREAL 1S、One、One Pro、One Pro+ 和 Aura。請在眼鏡選單中使用 Follow 模式並關閉畫面穩定;在 Aura 上還需關閉 Spatial Anchor。頭部追蹤和 2D/3D 切換已在 Aura 和 One Pro+ 上測試。</string> <string name="glasses_pro2_experimental">Pro 2 實驗性頭部追蹤。尚不支援亮度、音量調整及顯示模式切換。</string> <string name="stores_fact_developer">開發商</string> <string name="stores_fact_publisher">發行商</string> diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 2e9ab89a0e..844524c2f0 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -3452,7 +3452,7 @@ <string name="hand_camera_done">Done</string> <string name="glasses_xreal_network_missing">Waiting for the glasses’ USB Ethernet connection. This phone may not expose it to apps.</string> <string name="glasses_xreal_connection_failed">The XREAL connection was interrupted or returned an unsupported response. Retrying…</string> - <string name="glasses_xreal_experimental">Experimental XREAL 1S, One, One Pro, One Pro+ and Aura support. Use Follow mode and turn off stabilization in the glasses menu; on the Aura, also turn off Spatial Anchor. Head tracking and 2D/3D switching are tested on the Aura.</string> + <string name="glasses_xreal_experimental">Experimental XREAL 1S, One, One Pro, One Pro+ and Aura support. Use Follow mode and turn off stabilization in the glasses menu; on the Aura, also turn off Spatial Anchor. Head tracking and 2D/3D switching are tested on the Aura and One Pro+.</string> <string name="glasses_pro2_experimental">Experimental Pro 2 head tracking. Brightness, volume, and display switching are not supported yet.</string> <string name="display_picture_position">Picture position</string> <string name="display_position_top">Top</string> diff --git a/app/src/test/java/com/droiddeck/launcher/glasses/GlassesUsbTest.kt b/app/src/test/java/com/droiddeck/launcher/glasses/GlassesUsbTest.kt index ba2d444afd..0f475b5b86 100644 --- a/app/src/test/java/com/droiddeck/launcher/glasses/GlassesUsbTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/glasses/GlassesUsbTest.kt @@ -265,6 +265,34 @@ class GlassesUsbTest { assertEquals(null, Glasses.deviceModel(device(0x043e, 0x1234, "XREAL 1S"))) } + @Test fun xrealProPlusUsesEthernetPermissionAndItsOwnOptics() { + val pro = device(0x0444, 0x3318, "XREAL 1 Pro+") + manager.devices[pro.deviceName] = pro + field("linkDevice").set(null, pro) + field("link").set(null, object : GlassesLink { + override val hasImu = true + override fun send(msgId: Int, payload: ByteArray) = true + override fun close() {} + }) + try { + refresh(ask = true) + assertEquals("XREAL One Pro+", state.value.model) + assertEquals(Glasses.Permission.GRANTED, state.value.permission) + assertTrue(manager.requests.isEmpty()) + assertTrue(state.value.canControl) + assertTrue(state.value.hardwareControls) + assertTrue(state.value.supportsScreen3dof) + assertFalse(state.value.supportsSpatial) + assertEquals(57f, state.value.diagonalFovDeg, 0f) + assertEquals(9, state.value.brightnessMax) + assertEquals(0, state.value.volumeMax) + } finally { + field("link").set(null, null) + field("linkDevice").set(null, null) + (field("handler").get(null) as Handler).removeCallbacksAndMessages(null) + } + } + @Test fun rokidMaxRoutesThroughItsOwnModelAndSharedVendorIdNeedsTheName() { val max = Glasses.deviceModel(device(0x162f, 0x04d2, "Rokid Max")) assertTrue(max is RokidModel) diff --git a/app/src/test/java/com/droiddeck/launcher/glasses/XrealLinkTest.kt b/app/src/test/java/com/droiddeck/launcher/glasses/XrealLinkTest.kt index 9273dfb4b9..9ba23d976a 100644 --- a/app/src/test/java/com/droiddeck/launcher/glasses/XrealLinkTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/glasses/XrealLinkTest.kt @@ -38,7 +38,7 @@ class XrealLinkTest { override fun close() { closed = true; bytes.clear(); bytes.offer(-1) } } - private class Channels : XrealChannels { + private class Channels(private val displayMode: Int = 2) : XrealChannels { override val controlInput = Input() override val reports = Input() val wrote = LinkedBlockingQueue<Int>() @@ -53,7 +53,7 @@ class XrealLinkTest { val id = ByteBuffer.wrap(request.body).int and Int.MAX_VALUE wrote.offer(request.command) if (acknowledge) controlInput.add(XrealProtocolTest.response(request.command, id, - if (request.command == XrealProtocol.GET_DISPLAY) byteArrayOf(0x22, 2, 0x10, 2) else byteArrayOf(0x22, 0))) + if (request.command == XrealProtocol.GET_DISPLAY) byteArrayOf(0x22, 2, 0x10, displayMode.toByte()) else byteArrayOf(0x22, 0))) } } override fun close() { controlInput.close(); reports.close(); closed.countDown() } @@ -113,6 +113,27 @@ class XrealLinkTest { } finally { link.close() } } + @Test fun proPlusRejects1sOnlyModesAndKeepsBrightnessWithinTheSupportedRange() { + val channels = Channels(9) + val listener = Listener() + val link = XrealLink(object : XrealConnector { + override fun connect() = channels + override fun close() = channels.close() + }, listener, XrealModel.ONE_PRO_PLUS) + try { + assertTrue(listener.ready.await(2, TimeUnit.SECONDS)) + assertEquals(VitureProtocol.MSG_GET_DISPLAY to 9, listener.values.poll(2, TimeUnit.SECONDS)) + assertEquals(XrealProtocol.GET_DISPLAY, channels.wrote.poll(2, TimeUnit.SECONDS)) + assertFalse(link.send(VitureProtocol.MSG_DISPLAY, byteArrayOf(29))) + assertFalse(link.send(VitureProtocol.MSG_DISPLAY, byteArrayOf(2))) + assertFalse(link.send(VitureProtocol.MSG_BRIGHTNESS, byteArrayOf(10))) + assertTrue(channels.wrote.isEmpty()) + assertTrue(link.send(VitureProtocol.MSG_BRIGHTNESS, byteArrayOf(9))) + assertEquals(VitureProtocol.MSG_BRIGHTNESS to 9, listener.values.poll(2, TimeUnit.SECONDS)) + assertEquals(XrealProtocol.SET_BRIGHTNESS, channels.wrote.poll(2, TimeUnit.SECONDS)) + } finally { link.close() } + } + @Test fun missingNetworkIsReportedAndCloseCancelsRetry() { val listener = Listener() val closed = AtomicBoolean() diff --git a/app/src/test/java/com/droiddeck/launcher/glasses/XrealOrientationFilterTest.kt b/app/src/test/java/com/droiddeck/launcher/glasses/XrealOrientationFilterTest.kt index abd38d30bf..1d1f945767 100644 --- a/app/src/test/java/com/droiddeck/launcher/glasses/XrealOrientationFilterTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/glasses/XrealOrientationFilterTest.kt @@ -61,9 +61,9 @@ class XrealOrientationFilterTest { } @Test fun auraAxesAreNotFlippedLikeTheRestOfTheOneFamily() { - val aura = XrealOrientationFilter(flipYz = false).update(sample(1000000, accel = Vec3(0f, 9.81f, 0f)))!! + val aura = XrealOrientationFilter(XrealModel.AURA).update(sample(1000000, accel = Vec3(0f, 9.81f, 0f)))!! assertTrue(matrix(aura)[7] > 0.99f) - assertNull(XrealOrientationFilter(flipYz = false).update(sample(1000000, accel = Vec3(0f, 0f, 0f)))) + assertNull(XrealOrientationFilter(XrealModel.AURA).update(sample(1000000, accel = Vec3(0f, 0f, 0f)))) } @Test fun capturedNeutralGravityStartsUprightBeforeRecenter() { @@ -73,4 +73,93 @@ class XrealOrientationFilterTest { val screen = matrix(pose) assertTrue(screen[7] > 0.99f) } + + @Test fun proPlusMountStartsUprightBeforeRecenter() { + val neutral = sample(1000000) + val expected = matrix(XrealOrientationFilter().update(neutral)!!) + val actual = matrix(XrealOrientationFilter(XrealModel.ONE_PRO_PLUS).update(proPlusSample(neutral))!!) + assertArrayEquals(expected, actual, 0.0001f) + assertEquals(1f, actual[7], 0.0001f) + } + + @Test fun proPlusMountKeepsBothDirectionsOfEveryAxisCorrectThroughBothRecenterModes() { + for (axis in listOf("pitch", "yaw", "roll")) for (direction in listOf(-1, 1)) { + val ideal = XrealOrientationFilter() + val mounted = XrealOrientationFilter(XrealModel.ONE_PRO_PLUS) + val initial = sample(1000000) + val firstIdeal = matrix(ideal.update(initial)!!) + val firstMounted = matrix(mounted.update(proPlusSample(initial))!!) + var middleIdeal = firstIdeal + var middleMounted = firstMounted + var lastIdeal = firstIdeal + var lastMounted = firstMounted + val rate = direction * (Math.PI / 6).toFloat() + repeat(1000) { + val angle = rate * (it + 1) / 1000f + val accel = when (axis) { + "pitch" -> Vec3(0f, -9.81f * cos(angle), 9.81f * sin(angle)) + "yaw" -> Vec3(0f, -9.81f, 0f) + else -> Vec3(-9.81f * sin(angle), -9.81f * cos(angle), 0f) + } + val gyro = when (axis) { + "pitch" -> Vec3(rate, 0f, 0f) + "yaw" -> Vec3(0f, -rate, 0f) + else -> Vec3(0f, 0f, rate) + } + val frame = sample((it + 2) * 1000000L, gyro, accel) + lastIdeal = matrix(ideal.update(frame)!!) + lastMounted = matrix(mounted.update(proPlusSample(frame))!!) + if (it == 499) { + middleIdeal = lastIdeal + middleMounted = lastMounted + } + } + for (centerView in listOf(false, true)) { + val label = "$axis $direction centerView=$centerView" + val idealView = HeadPose.relative(HeadPose.recenter(firstIdeal, centerView), lastIdeal) + val mountedView = HeadPose.relative(HeadPose.recenter(firstMounted, centerView), lastMounted) + assertArrayEquals(label, axisMatrix(axis, rate), mountedView, 0.002f) + assertArrayEquals(label, idealView, mountedView, 0.0001f) + + val idealRecentered = HeadPose.relative(HeadPose.recenter(middleIdeal, centerView), lastIdeal) + val mountedRecentered = HeadPose.relative(HeadPose.recenter(middleMounted, centerView), lastMounted) + val recenteredAngle = if (centerView || axis == "yaw") rate / 2 else rate + assertArrayEquals("$label after mid-turn recenter", axisMatrix(axis, recenteredAngle), mountedRecentered, 0.002f) + assertArrayEquals("$label after mid-turn recenter", idealRecentered, mountedRecentered, 0.0001f) + } + } + } + + @Test fun recordedProPlusTurnAxesStayOnYawAndRoll() { + val recordedAxes = mapOf("yaw" to Vec3(0.052f, 0.867f, -0.496f), "roll" to Vec3(0.033f, 0.625f, 0.780f)) + for ((label, gyro) in recordedAxes) { + val filter = XrealOrientationFilter(XrealModel.ONE_PRO_PLUS) + val first = matrix(filter.update(sample(1000000))!!) + var last = first + repeat(100) { + last = matrix(filter.update(sample((it + 2) * 1000000L, gyro, Vec3(0f, 0f, 0f)))!!) + } + val view = HeadPose.relative(HeadPose.recenter(first, centerView = true), last) + val axis = Vec3(view[7] - view[5], view[2] - view[6], view[3] - view[1]).normalized() + val projection = if (label == "yaw") -axis.y else -axis.z + assertTrue("Recorded $label axis should be within 10 degrees of the display axis", + projection > cos(Math.toRadians(10.0).toFloat())) + } + } + + private fun proPlusSample(sample: XrealProtocol.Sample): XrealProtocol.Sample { + val angle = Math.toRadians(-35.0).toFloat() + fun mounted(v: Vec3) = Vec3(v.x, cos(angle) * v.y - sin(angle) * v.z, sin(angle) * v.y + cos(angle) * v.z) + return XrealProtocol.Sample(sample.timeNs, mounted(sample.gyro), mounted(sample.accel)) + } + + private fun axisMatrix(axis: String, angle: Float): FloatArray { + val c = cos(angle) + val s = sin(angle) + return when (axis) { + "pitch" -> floatArrayOf(1f, 0f, 0f, 0f, c, -s, 0f, s, c) + "yaw" -> floatArrayOf(c, 0f, s, 0f, 1f, 0f, -s, 0f, c) + else -> floatArrayOf(c, s, 0f, -s, c, 0f, 0f, 0f, 1f) + } + } } diff --git a/app/src/test/java/com/droiddeck/launcher/glasses/XrealProtocolTest.kt b/app/src/test/java/com/droiddeck/launcher/glasses/XrealProtocolTest.kt index 23f4f5af1c..901bcfeed0 100644 --- a/app/src/test/java/com/droiddeck/launcher/glasses/XrealProtocolTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/glasses/XrealProtocolTest.kt @@ -70,17 +70,24 @@ class XrealProtocolTest { } @Test fun stereoOnlyControlSwitches3dWithoutDisplayModeCommands() { - val output = ByteArrayOutputStream() - val replies = response(XrealProtocol.GET_INPUT, 1, byteArrayOf(0x22, 0)) + - response(XrealProtocol.SET_INPUT, 2, byteArrayOf(0x22, 0)) + - response(XrealProtocol.GET_INPUT, 3, byteArrayOf(0x22, 2, 0x10, 1)) - val control = XrealControl(channels(replies.inputStream(), output), stereoOnly = true, settleDelayMs = 0) - assertEquals(XrealModel.NATIVE_60HZ, control.display()) - assertEquals(5, control.changeDisplay(5)) - val written = output.toByteArray().inputStream() - val commands = List(3) { XrealProtocol.read(written).command } - assertEquals(listOf(XrealProtocol.GET_INPUT, XrealProtocol.SET_INPUT, XrealProtocol.GET_INPUT), commands) - assertFalse(commands.any { it == XrealProtocol.GET_DISPLAY || it == XrealProtocol.SET_DISPLAY }) + for (model in listOf(XrealModel.ONE, XrealModel.ONE_PRO, XrealModel.AURA)) { + assertFalse(model.hardwareControls) + assertFalse(model.hasSunblock) + assertEquals(listOf(60), model.rates2d) + assertFalse(model.supportsDisplayMode(9)) + assertFalse(model.supportsDisplayMode(3)) + val output = ByteArrayOutputStream() + val replies = response(XrealProtocol.GET_INPUT, 1, byteArrayOf(0x22, 0)) + + response(XrealProtocol.SET_INPUT, 2, byteArrayOf(0x22, 0)) + + response(XrealProtocol.GET_INPUT, 3, byteArrayOf(0x22, 2, 0x10, 1)) + val control = XrealControl(channels(replies.inputStream(), output), model = model, settleDelayMs = 0) + assertEquals(XrealModel.NATIVE_60HZ, control.display()) + assertEquals(5, control.changeDisplay(5)) + val written = output.toByteArray().inputStream() + val commands = List(3) { XrealProtocol.read(written).command } + assertEquals(listOf(XrealProtocol.GET_INPUT, XrealProtocol.SET_INPUT, XrealProtocol.GET_INPUT), commands) + assertFalse(commands.any { it == XrealProtocol.GET_DISPLAY || it == XrealProtocol.SET_DISPLAY }) + } } @Test fun unrelatedResponsesCannotKeepControlWaitingForever() { @@ -125,6 +132,44 @@ class XrealProtocolTest { assertThrows(IOException::class.java) { control.changeDisplay(5) } } + @Test fun proPlusKeeps1080pModesSeparateFrom1sNative1200p() { + val pro = XrealModel.ONE_PRO_PLUS + assertEquals(9, pro.mode(60, false)) + assertEquals(3, pro.mode(90, false)) + assertEquals(4, pro.mode(120, false)) + assertEquals(5, pro.mode(120, true)) + assertFalse(pro.sbs90) + assertEquals(listOf(60, 90, 120), pro.rates2d) + assertEquals(57f, pro.diagonalFovDeg, 0f) + assertEquals(29, XrealModel.ONE_S.mode(60, false)) + assertEquals(52f, XrealModel.ONE_S.diagonalFovDeg, 0f) + } + + @Test fun proPlusRejects1sOnlyDisplayResponsesAndCommands() { + for (mode in listOf(2, 29)) { + val response = response(XrealProtocol.GET_DISPLAY, 1, byteArrayOf(0x22, 2, 0x10, mode.toByte())) + val output = ByteArrayOutputStream() + val control = XrealControl(channels(response.inputStream(), output), model = XrealModel.ONE_PRO_PLUS) + assertThrows(IOException::class.java) { control.display() } + output.reset() + assertThrows(IllegalArgumentException::class.java) { control.changeDisplay(mode) } + assertEquals(0, output.size()) + } + } + + @Test fun proPlusCanReturnFromStereoToIts1080p60HzMode() { + val output = ByteArrayOutputStream() + val replies = response(XrealProtocol.SET_INPUT, 1, byteArrayOf(0x22, 0)) + + response(XrealProtocol.GET_DISPLAY, 2, byteArrayOf(0x22, 0)) + + response(XrealProtocol.GET_DISPLAY, 3, byteArrayOf(0x22, 2, 0x10, 9)) + val control = XrealControl(channels(replies.inputStream(), output), 0, XrealModel.ONE_PRO_PLUS) + assertEquals(9, control.changeDisplay(XrealModel.ONE_PRO_PLUS.mode(60, false))) + val requests = output.toByteArray().inputStream() + assertEquals(XrealProtocol.SET_INPUT, XrealProtocol.read(requests).command) + repeat(2) { assertEquals(XrealProtocol.GET_DISPLAY, XrealProtocol.read(requests).command) } + assertEquals(0, requests.available()) + } + companion object { fun sensor(time: Long = 123456789L): ByteArray = ByteBuffer.allocate(128).order(ByteOrder.LITTLE_ENDIAN) .putLong(8, time).putInt(24, 11).putFloat(32, 0.5f).putFloat(44, 9.81f).array() diff --git a/docs/development/xreal-investigation.md b/docs/development/xreal-investigation.md index bcad031461..8e75819b60 100644 --- a/docs/development/xreal-investigation.md +++ b/docs/development/xreal-investigation.md @@ -240,3 +240,65 @@ extended gameplay stability need hardware validation. One successful view/motion check does not establish long-session stability. Users must select Follow mode and disable the glasses' own stabilization. Factory calibration and XREAL Eye/6DoF are not implemented. One Pro is not enabled or claimed as tested. + +## Native 1 Pro+ implementation and hardware validation — 2026-11-13 + +The attached device identifies as USB `3318:0444`, product `XREAL 1 Pro+`. This exact +identity enables the experimental 1 Pro+ profile alongside the existing 1S profile. +The [official specifications](https://tutorials.xreal.com/docs/glasses/pro-plus/specifications/) +give 1920×1080 per eye and a 57° diagonal field of view. The direct Kotlin driver +uses the USB-Ethernet control and IMU services; it requires no XREAL SDK or +ControlGlasses installation and includes no vendor SDK binaries or headers. + +Verified on the connected phone and glasses: + +| Observation | Result | +| --- | --- | +| Control and IMU transport | Individually bound Android Ethernet sockets reach `169.254.2.1:52999` and `:52998` without replacing the default Internet network. | +| Native display | `GET_DISPLAY` (`0x275e`) returns **9**, with Android reporting **1920×1080 at 60 Hz**. This profile preserves mode 9 for native 60 Hz instead of the 1S's mode 29. | +| Legacy 60 Hz command | Setting mode **2** is rejected with status **10001**. A rejected command does not count as a successful display switch. | +| Higher refresh commands | Setting modes **3** and **4** through DroidDeck selects physical **1920×1080 at 90/120 Hz**, confirmed through Android's active display mode. | +| Full SBS | `SET_INPUT` (`0x2822`) with value **1** settles at display mode **5** and Android **3840×1080 at 60 Hz**. Value **0** restores native mode **9**; DroidDeck then restores the saved 90 Hz preference. Tracking resumed after both switches. | +| IMU | Type **11** raw sensor reports arrive at approximately **1,000 Hz**, using the existing 128-byte body layout. | + +Mode 9 is an observed native display configuration, not a general mapping from +EDID number to the physical refresh rate selected by every host. The older +[xr-tools enum](https://github.com/0xcaff/xr-tools/blob/main/packages/xreal_one_driver/src/proto/net/dp_get_current_edid_dsp.rs) +contains only modes 2–5. The independent +[one-xr investigation](https://github.com/Skarian/one-xr/blob/main/docs/UNRESOLVED.md) +also records mode 9 and mode-2 rejection status 10001 on other firmware. This +supports keeping display mappings per model and confirming output through Android. + +The Pro+ profile applies a nominal **+35° rotation around X** to both gyro and +acceleration before fusion, inverting the factory display-to-IMU mounting +direction. Directed wearer captures separately establish the sign: horizontal +turns primarily rotate around corrected Y, and shoulder tilts around corrected Z. +The initial opposite-sign correction mixed these axes; a stationary capture alone +could not distinguish sensor mounting from the physical angle of the glasses. +This is a model mounting correction, not individually calibrated tracking. Device +calibration data and serial numbers are not stored in the repository. After the +corrected build was installed, the wearer confirmed all three rotation directions +and the horizon were correct. The existing 1S mapping stays unchanged. + +The initial APK build and 621 targeted glasses/UI tests completed with zero failures +and one skipped test. After correcting the mounting direction, all 73 focused +XREAL/routing tests passed, including a regression using the measured movement +axes. Native dependency checks passed and the APK contains no vendor +SDK libraries. On this phone, background network restrictions interrupted the +glasses sockets while DroidDeck was away from the foreground; foreground operation +recovered. Sustained background use needs separate validation. + +Brightness remains limited to the known protocol values **0–9**. XREAL's +[display guide](https://tutorials.xreal.com/docs/glasses/pro-plus/display-sound/) +documents 14 physical levels in Follow mode with Stabilizer off and 10 in Anchor +or Spatial Anchor. Those counts do not establish a 0–13 direct-protocol range. +The wearer confirmed that DroidDeck's brightness and dimming controls work on the +Pro+. The wider brightness API mapping remains unverified. + +Use **Follow** with **Stabilizer off** in the glasses' own menu before using +DroidDeck tracking, following the official +[display-mode](https://tutorials.xreal.com/docs/glasses/pro-plus/spatial-screen/display-modes/) +and [Stabilizer](https://tutorials.xreal.com/docs/glasses/pro-plus/spatial-screen/stabilizer-transparency/) +descriptions. The built-in tracking must not be layered over host tracking. +XREAL Eye, camera capture, and 6DoF are not implemented. Long-session stability +remains an outstanding hardware check. diff --git a/docs/smart-glasses-support.md b/docs/smart-glasses-support.md index 123c1451c7..36137c9aa7 100644 --- a/docs/smart-glasses-support.md +++ b/docs/smart-glasses-support.md @@ -22,7 +22,7 @@ This describes the integrations implemented in DroidDeck as of 2026-10-24. A rec | **VITURE Luma Ultra** | SDK-dependent Carina transport | Yes | **Experimental, opt-in** | **Experimental, opt-in** | | Recognized RayNeo / TCL Air-series devices | Integrated RayNeo USB transport | Yes, with orientation calibration controls | No | No | | RayNeo GT-series devices matching the supported USB identity, including GT Max identification | Integrated GT USB/IMU path | Yes, with orientation calibration controls | No | No | -| **XREAL 1S, One, One Pro, One Pro+, Aura** | **Experimental**; exact USB identity plus the device's USB-Ethernet control/IMU connection. Head tracking and 2D/3D switching are tested on the Aura | Yes, when that connection is ready | No | No | +| **XREAL 1S, One, One Pro, One Pro+, Aura** | **Experimental**; exact USB identity plus the device's USB-Ethernet control/IMU connection. Head tracking and 2D/3D switching are tested on the Aura and One Pro+ | Yes, when that connection is ready | No | No | | Rokid Max / Max 2; Rokid Air under the Max USB identity | Integrated Rokid USB transport (vendor control requests and HID IMU reports) | Yes | No | No | | Other XREAL models (Air family and others); unrecognized glasses; display adapters and docks | Display-only where Android exposes a usable display; automatic glasses routing also requires display recognition | No supported app tracking connection | No | No | @@ -43,7 +43,8 @@ All display modes depend on the phone's video output, the cable/adapter, and And | VITURE Pro 2 | 1080p per eye; 2D and SBS | Brightness and volume; no electrochromic-film control | | RayNeo Air/GT | 2D/SBS switching; resolution and refresh follow available Android modes | Orientation calibration; no app brightness, volume, or dimming commands | | XREAL 1S | Supported 1S display-mode commands, including native 1200p/60 Hz and SBS | Brightness and dimming toggle; no app volume command | -| XREAL One, One Pro, One Pro+, Aura | 2D and SBS only, switched with the glasses' 3D input command; the display-mode set command is never sent (an unexpected index reboots the Aura) | No app brightness, dimming or volume commands | +| XREAL One Pro+ | Verified 1920×1080 at 60/90/120 Hz; 3840×1080 SBS at 60 Hz. Native 60 Hz uses mode 9; 1S-only modes 2/29 are rejected | Brightness 0–9 and dimming toggle verified; no app volume command | +| XREAL One, One Pro, Aura | 2D and SBS only, switched with the glasses' 3D input command; the display-mode set command is never sent (an unexpected index reboots the Aura) | No app brightness, dimming or volume commands | | Rokid Max / Max 2 | 1080p at 60 or 120 Hz in 2D; SBS at 1080p/60, 1200p/60, or 1200p/90 | Brightness; volume follows Android's USB audio volume; no dimming film | | Rokid Air | 1080p/60 in 2D and SBS | Brightness; volume follows Android's USB audio volume | @@ -55,6 +56,8 @@ With **game on glasses** the compositor draws the guest pointer into its own sce The pointer is left out of the picture when it cannot be drawn where the game is: while a game holds the pointer lock (it draws its own), and for a game the compositor cannot import — an AHardwareBuffer-only surface, or HDR frames it has no texture for. Those games stay on their own display layer, because composing the scene would drop the game itself. An importable HDR game that would otherwise stay on its own layer is composed through the screen swapchain, so there the pointer does fit. +The One Pro+ uses a verified sensor mounting correction for both gyro and acceleration. The wearer confirmed all three tracking axes, a level horizon, brightness and dimming on a Fold7. Use Follow mode with Stabilizer off. These checks do not establish long-session stability; see the [hardware validation](development/xreal-investigation.md#native-1-pro-implementation-and-hardware-validation--2026-11-13). + ## Setup and app-wide behavior 1. Connect the glasses through a compatible video/data connection. Accept USB access when requested. For XREAL 1S, One, One Pro, One Pro+ and Aura, Android must also expose the glasses' USB-Ethernet network; the app leaves Steam's Internet connection on its normal network. From 4399db47164555b57d505491bb173a7a556a97ad Mon Sep 17 00:00:00 2001 From: guohaomin1995-dev <guohaomin1995@gmail.com> Date: Wed, 25 Nov 2026 05:17:17 +0800 Subject: [PATCH 122/141] fix(loading): show the arm64 Steam client's update progress in every language (#2651) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(loading): show the arm64 Steam client's update progress in every language The arm64 bootstrapper writes its progress straight into session.log in the client's language and with thousands separators, e.g. "正在下载更新 (已下载 184,557,共 573,070 KB)" or "Downloading update (184,557 of 573,070 KB)". UPDATE_PROGRESS only matched the forwarded x86-64 form without separators, so the loading screen stayed on "Waiting for Steam's first frame" with no percentage for the whole ~570 MB first update. Users took that for a hang and cancelled; after two starts the installer's repair wiped the partial download, so it started over each time. Accept separators, and fall back to the bootstrapper's language-independent "Set percent complete: N" line. * chore: drop the added comment * fix(loading): a zero or post-extract percent line no longer reads as a download * fix(loading): an unknown percent ends the earlier download percent * fix(session): ignore out-of-range percents and clear a percent after an unknown one --------- Co-authored-by: guohaomin1995-dev <321670510+guohaomin1995-dev@users.noreply.github.com> Co-authored-by: maxjivi05 <maxjividen@gmail.com> --- .../launcher/session/LoadingState.kt | 35 +++++++-- .../session/LoadingStateUpdateTest.kt | 74 +++++++++++++++++++ 2 files changed, 102 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/session/LoadingState.kt b/app/src/main/java/com/droiddeck/launcher/session/LoadingState.kt index 6e6cfdac61..453e2c4ecd 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/LoadingState.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/LoadingState.kt @@ -67,6 +67,8 @@ class LoadingState(context: Context, private val steam: Boolean = true) { private class Line(val line: String, val percent: Int, val topic: Topic, val readable: Boolean) + private var scriptStep: Line? = null + private fun read(context: Context, log: File?): Line? { if (log == null || !log.isFile) return null val text = try { @@ -89,6 +91,7 @@ class LoadingState(context: Context, private val steam: Boolean = true) { var clientDownloadAt = -1 var clientDownload: String? = null var clientPercent = -1 + var unknownAt = -1 var offset = 0 for (line in text.split('\n')) { val at = offset @@ -103,16 +106,34 @@ class LoadingState(context: Context, private val steam: Boolean = true) { } } else { val m = UPDATE_PROGRESS.find(line) + val p = if (m == null && steam) UPDATE_PERCENT.find(line) else null if (m != null) { downloadAt = at - val done = m.groupValues[1].toLong() - val total = maxOf(1L, m.groupValues[2].toLong()) + val done = m.groupValues[1].replace(",", "").toLong() + val total = maxOf(1L, m.groupValues[2].replace(",", "").toLong()) downloadPercent = (done * 100 / total).toInt() + } else if (p != null) { + val percent = p.groupValues[1].toIntOrNull() ?: continue + if (percent < 0) { + downloadAt = -1 + unknownAt = at + } else if (percent > 0 && applyingAt <= stepAt) { + downloadAt = at + downloadPercent = percent.coerceAtMost(100) + } } else if (steam && UPDATE_APPLYING.matches(line)) { applyingAt = at } } } + val stepLine = when { + clientDownloadAt == stepAt && clientDownload != null -> Line( + context.getString(com.droiddeck.launcher.R.string.loadstate_steam_client, clientDownload), clientPercent, + Topic.STEAM, readable = true, + ) + stepText != null -> Line(stepText, -1, topicOf(stepText, steam), readableScriptStep(stepText)) + else -> null + }?.also { scriptStep = it } return when { applyingAt > stepAt && applyingAt > downloadAt -> Line( context.getString(com.droiddeck.launcher.R.string.loadstate_steam_update_applying), -1, @@ -122,11 +143,10 @@ class LoadingState(context: Context, private val steam: Boolean = true) { context.getString(com.droiddeck.launcher.R.string.loadstate_steam_update, downloadPercent), downloadPercent, Topic.STEAM, readable = true, ) - clientDownloadAt == stepAt && clientDownload != null -> Line( - context.getString(com.droiddeck.launcher.R.string.loadstate_steam_client, clientDownload), clientPercent, - Topic.STEAM, readable = true, + stepLine != null -> stepLine + unknownAt >= 0 -> scriptStep ?: Line( + context.getString(com.droiddeck.launcher.R.string.loadstate_starting), -1, Topic.SESSION, readable = false, ) - stepText != null -> Line(stepText, -1, topicOf(stepText, steam), readableScriptStep(stepText)) else -> null } } @@ -166,7 +186,8 @@ class LoadingState(context: Context, private val steam: Boolean = true) { } private const val TAIL_BYTES = 48L * 1024 - private val UPDATE_PROGRESS = Regex("""Downloading update \((\d+) of (\d+) KB\)""") + private val UPDATE_PROGRESS = Regex("""Downloading update \(([\d,]+) of ([\d,]+) KB\)""") + private val UPDATE_PERCENT = Regex("""^\[[^\]]+\] Set percent complete: (-?\d+)\s*$""") private val UPDATE_APPLYING = Regex("""^\s*(?:\[[^\]]+\]\s*)*(?:Extracting package|Installing update)\.\.\.\s*$""") private val INSTALL_COUNT = Regex("""downloading Steam: (\S+) \((\d+)/(\d+)\)""") private val INSTALL_MEGABYTES = Regex("""^, (\d+) of (\d+) MB""") diff --git a/app/src/test/java/com/droiddeck/launcher/session/LoadingStateUpdateTest.kt b/app/src/test/java/com/droiddeck/launcher/session/LoadingStateUpdateTest.kt index 0ef4ebaeeb..30c273969c 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/LoadingStateUpdateTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/LoadingStateUpdateTest.kt @@ -76,6 +76,80 @@ class LoadingStateUpdateTest { assertEquals(LoadingState.Topic.DESKTOP, state.topic) } + @Test fun bootstrapperProgressWithThousandsSeparatorsIsRead() { + val state = read("[2026-11-15 11:58:51] Downloading update (184,557 of 573,070 KB)...") + assertEquals(32, state.percent) + assertEquals("Downloading the Steam client update · 32%", state.step) + } + + @Test fun translatedBootstrapperProgressUsesItsPercentLine() { + val state = read( + "[2026-11-15 11:58:51] 正在下载更新 (已下载 184,557,共 573,070 KB)...", + "[2026-11-15 11:58:51] Set status message: 正在下载更新 (已下载 184,557,共 573,070 KB)...", + "[2026-11-15 11:58:51] Set percent complete: 32", + ) + assertEquals(32, state.percent) + assertEquals(LoadingState.Topic.STEAM, state.topic) + assertTrue(state.readable) + } + + @Test fun anUnknownPercentDoesNotLookLikeProgress() { + val state = read("[2026-11-15 11:53:37] Set percent complete: -1") + assertEquals(-1, state.percent) + } + + @Test fun aVerificationOnlyPassKeepsTheScriptStep() { + val state = read( + "[2026-11-15 11:53:36] Set percent complete: 0", + "[2026-11-15 11:53:37] Set percent complete: -1", + "[2026-11-15 11:53:37] Verifying installation...", + ) + assertEquals("starting the Steam client", state.step) + assertEquals(-1, state.percent) + } + + @Test fun aPercentLineDoesNotReplaceApplyingInTheSameStep() { + assertApplying(read("Extracting package...", "[2026-11-15 11:58:52] Set percent complete: 100")) + } + + @Test fun anUnknownPercentEndsAnEarlierPercent() { + val state = read( + "[2026-11-15 11:58:51] Set percent complete: 40", + "[2026-11-15 11:58:52] Set percent complete: -1", + ) + assertEquals("starting the Steam client", state.step) + assertEquals(-1, state.percent) + } + + @Test fun aPercentLineCountsAgainAfterANewStep() { + val state = read( + "Installing update...", + "== STEP 12:00:03 starting the Steam client", + "[2026-11-15 11:58:51] Set percent complete: 40", + ) + assertEquals(40, state.percent) + } + + @Test fun aPercentOutsideTheIntRangeIsIgnored() { + val state = read( + "[2026-11-15 11:58:51] Set percent complete: 40", + "[2026-11-15 11:58:52] Set percent complete: 2147483648", + ) + assertEquals(40, state.percent) + } + + @Test fun anUnknownPercentClearsTheDisplayedPercentAfterTheStepLeavesTheTail() { + val context = RuntimeEnvironment.getApplication() + val log = log("[2026-11-15 11:58:51] Set percent complete: 40") + val state = LoadingState(context) + state.update(context, log) + assertEquals(40, state.percent) + log.appendText("\n" + "Loading cached metrics\n".repeat(4096) + "[2026-11-15 11:58:52] Set percent complete: -1") + state.update(context, log) + assertEquals(-1, state.percent) + assertEquals("starting the Steam client", state.step) + } + @Test fun anExistingLoadingStateFollowsUpdatesAcrossPolls() { val context = RuntimeEnvironment.getApplication() val log = log("Downloading update (100 of 100 KB)") From 46206b3e1602b248031694007a133041927e0c80 Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Tue, 24 Nov 2026 16:18:05 -0500 Subject: [PATCH 123/141] fix(desktop): links read into a buffer sized from lstat show their guest target (#3157) * fix(desktop): links read into a buffer sized from lstat show their guest target lstat reports the guest length of a link stored with a rootfs target, and dpkg's update-alternatives then reads it with exactly that many bytes. readlink filled the buffer with the start of the host path, which could no longer be mapped back, so every alternative looked dangling ("current alternative /data/dat is unknown"). The whole target is read first, mapped, then copied into the caller's buffer. * fix(desktop): a zero-sized readlink buffer still fails with EINVAL * test(desktop): read errno before printing the zero-size readlink result --- tools/nativeguest/hook/fileops.c | 25 ++++-- tools/tests/test_native_hook_readlink.py | 106 +++++++++++++++++++++++ 2 files changed, 125 insertions(+), 6 deletions(-) create mode 100644 tools/tests/test_native_hook_readlink.py diff --git a/tools/nativeguest/hook/fileops.c b/tools/nativeguest/hook/fileops.c index 2632f0eefb..b20c07f814 100644 --- a/tools/nativeguest/hook/fileops.c +++ b/tools/nativeguest/hook/fileops.c @@ -418,6 +418,13 @@ int renameat2(int olddirfd, const char *oldpath, int newdirfd, const char *newpa return ret; } +static ssize_t copy_readlink_result(char *buf, size_t bufsiz, const char *out, ssize_t ret) { + if (ret <= 0 || out == buf) return ret; + size_t n = (size_t)ret < bufsiz ? (size_t)ret : bufsiz; + memcpy(buf, out, n); + return (ssize_t)n; +} + // Hook readlink ssize_t readlink(const char *pathname, char *buf, size_t bufsiz) { if (is_proc_self_exe(pathname)) { @@ -431,13 +438,16 @@ ssize_t readlink(const char *pathname, char *buf, size_t bufsiz) { if (!orig_readlink) orig_readlink = (ssize_t (*)(const char *, char *, size_t))dlsym(RTLD_NEXT, "readlink"); char pbuf[PATH_MAX]; const char *target = rewrite_path(pathname, pbuf, sizeof(pbuf)); - ssize_t ret = orig_readlink ? orig_readlink(target, buf, bufsiz) : -1; + char whole[PATH_MAX]; + char *out = bufsiz && bufsiz < sizeof(whole) ? whole : buf; + size_t outsiz = out == whole ? sizeof(whole) : bufsiz; + ssize_t ret = orig_readlink ? orig_readlink(target, out, outsiz) : -1; if (ret < 0 && errno == ENOENT) { char alt[PATH_MAX]; const char *retry = usrmerge_retry_path(target, alt, sizeof(alt)); - if (retry) ret = orig_readlink(retry, buf, bufsiz); + if (retry) ret = orig_readlink(retry, out, outsiz); } - return postprocess_readlink(pathname, buf, ret, bufsiz); + return copy_readlink_result(buf, bufsiz, out, postprocess_readlink(pathname, out, ret, outsiz)); } // Hook readlinkat @@ -459,13 +469,16 @@ ssize_t readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz) { } char pbuf[PATH_MAX]; const char *target = (pathname && pathname[0] == '/') ? rewrite_path(pathname, pbuf, sizeof(pbuf)) : pathname; - ssize_t ret = orig_readlinkat ? orig_readlinkat(dirfd, target, buf, bufsiz) : -1; + char whole[PATH_MAX]; + char *out = bufsiz && bufsiz < sizeof(whole) ? whole : buf; + size_t outsiz = out == whole ? sizeof(whole) : bufsiz; + ssize_t ret = orig_readlinkat ? orig_readlinkat(dirfd, target, out, outsiz) : -1; if (ret < 0 && errno == ENOENT && pathname && pathname[0] == '/') { char alt[PATH_MAX]; const char *retry = usrmerge_retry_path(target, alt, sizeof(alt)); - if (retry) ret = orig_readlinkat(dirfd, retry, buf, bufsiz); + if (retry) ret = orig_readlinkat(dirfd, retry, out, outsiz); } - return postprocess_readlink(pathname, buf, ret, bufsiz); + return copy_readlink_result(buf, bufsiz, out, postprocess_readlink(pathname, out, ret, outsiz)); } // Fortified readlink variants used by dpkg / update-alternatives diff --git a/tools/tests/test_native_hook_readlink.py b/tools/tests/test_native_hook_readlink.py new file mode 100644 index 0000000000..ed594f6365 --- /dev/null +++ b/tools/tests/test_native_hook_readlink.py @@ -0,0 +1,106 @@ +import errno +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" + +PROBE = r""" +#include <errno.h> +#include <fcntl.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/stat.h> +#include <unistd.h> + +static void show(const char *name, ssize_t len, const char *buf) { + printf("%s\t%zd\t%.*s\n", name, len, len > 0 ? (int)len : 0, buf); +} + +int main(int argc, char **argv) { + const char *link = argv[1]; + struct stat st; + if (lstat(link, &st) != 0) return 2; + char *exact = malloc((size_t)st.st_size + 1); + show("sized", readlink(link, exact, (size_t)st.st_size), exact); + char full[4096]; + show("full", readlink(link, full, sizeof(full)), full); + char small[4]; + show("small", readlink(link, small, sizeof(small)), small); + show("sized-at", readlinkat(AT_FDCWD, link, exact, (size_t)st.st_size), exact); + errno = 0; + ssize_t zero = readlink(link, full, 0); + int zero_errno = errno; + printf("zero\t%zd\t%d\n", zero, zero_errno); + errno = 0; + zero = readlinkat(AT_FDCWD, link, full, 0); + zero_errno = errno; + printf("zero-at\t%zd\t%d\n", zero, zero_errno); + return 0; +} +""" + + +class NativeHookReadlinkTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + cls.tmp = tempfile.TemporaryDirectory(dir="/tmp") + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "probe.c").write_text(PROBE) + cls.probe = tmp / "probe" + subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True) + cls.root = tmp / "root" + (cls.root / "bin").mkdir(parents=True) + (cls.root / "etc/alternatives").mkdir(parents=True) + (cls.root / "bin/nano").write_text("") + os.symlink(cls.root / "bin/nano", cls.root / "etc/alternatives/editor") + os.symlink("/bin/nano", cls.root / "etc/alternatives/guest") + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def read(self, link): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")} + if self.prefix: + cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] + else: + cmd = [] + env.update(hook_env) + out = subprocess.run(cmd + [str(self.probe), link], env=env, capture_output=True, text=True, timeout=120) + self.assertEqual(0, out.returncode, out.stdout + out.stderr) + return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()} + + def test_a_buffer_sized_from_lstat_gets_the_guest_target(self): + result = self.read("/etc/alternatives/editor") + self.assertEqual(["9", "/bin/nano"], result["sized"]) + self.assertEqual(["9", "/bin/nano"], result["sized-at"]) + self.assertEqual(["9", "/bin/nano"], result["full"]) + + def test_a_short_buffer_gets_the_start_of_the_guest_target(self): + self.assertEqual(["4", "/bin"], self.read("/etc/alternatives/editor")["small"]) + + def test_a_guest_target_is_unchanged(self): + result = self.read("/etc/alternatives/guest") + self.assertEqual(["9", "/bin/nano"], result["sized"]) + self.assertEqual(["4", "/bin"], result["small"]) + + def test_a_zero_sized_buffer_is_rejected(self): + result = self.read("/etc/alternatives/editor") + self.assertEqual(["-1", str(errno.EINVAL)], result["zero"]) + self.assertEqual(["-1", str(errno.EINVAL)], result["zero-at"]) + + +if __name__ == "__main__": + unittest.main() From 31c475d5e16f6bd167ee4690520afff8d96e5b43 Mon Sep 17 00:00:00 2001 From: xlulx <92148312+xlulx@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:18:10 +0300 Subject: [PATCH 124/141] fix(session): run game thread hints on the SM8750P Snapdragon 8 Elite (#2914) * fix: run game thread hints on the SM8750P Snapdragon 8 Elite * fix: gate game thread hints on the SoC model SocNames resolves * fix: skip unknown SoC model properties --- app/src/main/java/com/droiddeck/launcher/gpu/SocNames.kt | 6 ++++-- .../java/com/droiddeck/launcher/session/GameThreadHints.kt | 4 ++-- .../test/java/com/droiddeck/launcher/gpu/SocNamesTest.kt | 2 ++ .../com/droiddeck/launcher/session/GameThreadHintsTest.kt | 1 + 4 files changed, 9 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/SocNames.kt b/app/src/main/java/com/droiddeck/launcher/gpu/SocNames.kt index c1f2966b6d..586950f9d0 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/SocNames.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/SocNames.kt @@ -7,7 +7,8 @@ object SocNames { "SM8150" to "Snapdragon 855", "SM8250" to "Snapdragon 865", "SM8250-AC" to "Snapdragon 870", "SM8350" to "Snapdragon 888", "SM8450" to "Snapdragon 8 Gen 1", "SM8475" to "Snapdragon 8+ Gen 1", "SM8550" to "Snapdragon 8 Gen 2", "QCS8550" to "Snapdragon 8 Gen 2", "SM8650" to "Snapdragon 8 Gen 3", - "SM8750" to "Snapdragon 8 Elite", "SM8850" to "Snapdragon 8 Elite Gen 5", + "SM8750" to "Snapdragon 8 Elite", "SM8750P" to "Snapdragon 8 Elite", + "SM8850" to "Snapdragon 8 Elite Gen 5", "SM8975" to "Snapdragon 8 Elite Extreme Gen 6", "SM7325" to "Snapdragon 778G", "SM7450" to "Snapdragon 7 Gen 1", "SM7550" to "Snapdragon 7 Gen 3", "SM6375" to "Snapdragon 695", @@ -23,7 +24,8 @@ object SocNames { val sdk = if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL.takeIf { it != Build.UNKNOWN }.orEmpty() else "" return listOf(prop("ro.soc.model"), prop("ro.vendor.qti.soc_model"), sdk, prop("ro.fota.platform")) .map { it.trim() } - .firstOrNull { it.isNotEmpty() && !Regex("(?i)^msm_\\d").containsMatchIn(it) }.orEmpty() + .firstOrNull { it.isNotEmpty() && !it.equals(Build.UNKNOWN, ignoreCase = true) && !Regex("(?i)^msm_\\d").containsMatchIn(it) } + .orEmpty() } internal fun normalizedModel(model: String): String = model.trim().uppercase().removePrefix("QTI ").trim() diff --git a/app/src/main/java/com/droiddeck/launcher/session/GameThreadHints.kt b/app/src/main/java/com/droiddeck/launcher/session/GameThreadHints.kt index 0f2b2273f8..1a0449890e 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/GameThreadHints.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/GameThreadHints.kt @@ -27,14 +27,14 @@ object GameThreadHints { private const val PACE_TOLERANCE = 0.08 private val NOT_GAMES = setOf("steam", "steamwebhelper") - private val SOCS = setOf("CQ8725S", "SM8750") + private val SOCS = setOf("CQ8725S", "SM8750", "SM8750P") private var worker: Thread? = null @Synchronized fun start(context: Context): String { if (!SessionPrefs.gameThreadHints(context)) return "game thread hints: off" - if (Build.VERSION.SDK_INT < 31 || !supported(Build.SOC_MODEL)) return "game thread hints: Snapdragon 8 Elite only" + if (Build.VERSION.SDK_INT < 31 || !supported(SocNames.model())) return "game thread hints: Snapdragon 8 Elite only" val hm = context.getSystemService(PerformanceHintManager::class.java) ?: return "game thread hints: no PerformanceHintManager" val pm = context.getSystemService(PowerManager::class.java) diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/SocNamesTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/SocNamesTest.kt index 963f9f739c..5dd2aa383e 100644 --- a/app/src/test/java/com/droiddeck/launcher/gpu/SocNamesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/gpu/SocNamesTest.kt @@ -11,6 +11,7 @@ class SocNamesTest { assertEquals("SG8350P", SocNames.model(props("ro.vendor.qti.soc_model" to "SG8350P", "ro.fota.platform" to "MSM_13.0"))) assertEquals("QCS8550", SocNames.model(props("ro.soc.model" to "QCS8550", "ro.vendor.qti.soc_model" to "other"))) assertEquals("", SocNames.model(props("ro.fota.platform" to "MSM_13.0"))) + assertEquals("QTI SM8750P", SocNames.model(props("ro.soc.model" to "unknown", "ro.vendor.qti.soc_model" to "QTI SM8750P"))) } @Test fun knownModelsAndPlatformsGetTheirNames() { @@ -26,6 +27,7 @@ class SocNamesTest { assertEquals("Snapdragon 8 Elite Extreme Gen 6", SocNames.name("QTI SM8975", "")) assertEquals("Snapdragon 8 Elite Extreme Gen 6", SocNames.name(" qti sm8975 ", "")) assertEquals("Snapdragon 8 Elite Extreme Gen 6 (QTI SM8975)", SocNames.label("QTI SM8975", "")) + assertEquals("Snapdragon 8 Elite", SocNames.name("QTI SM8750P", "")) assertNull(SocNames.name("SM89750", "")) assertNull(SocNames.name("SM8975-PRO", "")) assertNull(SocNames.name("Qualcomm SM8975", "")) diff --git a/app/src/test/java/com/droiddeck/launcher/session/GameThreadHintsTest.kt b/app/src/test/java/com/droiddeck/launcher/session/GameThreadHintsTest.kt index ff5867d4c2..6482177c0a 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/GameThreadHintsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/GameThreadHintsTest.kt @@ -10,6 +10,7 @@ class GameThreadHintsTest { assertTrue(GameThreadHints.supported("CQ8725S")) assertTrue(GameThreadHints.supported("SM8750")) assertTrue(GameThreadHints.supported("QTI SM8750")) + assertTrue(GameThreadHints.supported("QTI SM8750P")) assertFalse(GameThreadHints.supported("SM8650")) assertFalse(GameThreadHints.supported("SM8850")) assertFalse(GameThreadHints.supported("")) From 8f0e124b5d10dba283e827bef0120c7f07aca82e Mon Sep 17 00:00:00 2001 From: Tapuuk <timur2012.baranov@gmail.com> Date: Tue, 24 Nov 2026 22:18:15 +0100 Subject: [PATCH 125/141] fix(runtime): fetch the KDE language-pack index directly from GitHub (#2845) The index carries the sha256 of every language pack, so loading it through a download mirror let the mirror pick both the hash and the pack that gets extracted into the Linux runtime. The index now always comes straight from GitHub; pack bodies can still use mirrors since their hash is trusted. Co-authored-by: Tapuuk <177422350+Tapuuk@users.noreply.github.com> --- .../launcher/runtime/DesktopLanguage.kt | 5 +- .../runtime/DesktopLanguageIndexSourceTest.kt | 62 +++++++++++++++++++ 2 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/runtime/DesktopLanguageIndexSourceTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/DesktopLanguage.kt b/app/src/main/java/com/droiddeck/launcher/runtime/DesktopLanguage.kt index 83bfa6748a..3cd0c01e0e 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/DesktopLanguage.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/DesktopLanguage.kt @@ -32,6 +32,9 @@ object DesktopLanguage { internal fun baseUrl(desktopUrl: String) = desktopUrl.substringBeforeLast('/') + "/" + /** The index carries every pack's sha256, so it never goes through a download mirror. */ + internal fun fetchIndex(base: String): Map<String, Pack>? = Downloader.downloadDirect(base + INDEX)?.let(::parseIndex) + private fun marker(root: File, tag: String, name: String) = File(root, ".droiddeck-i18n-$tag-$name") /** Installs the desktop's translations for [locale]; false when a download failed and is worth retrying. */ @@ -44,7 +47,7 @@ object DesktopLanguage { val pending = candidates(locale).filterNot { marker(root, tag, it).isFile } if (pending.isEmpty()) return true val base = baseUrl(BuildConfig.DESKTOP_KDE_URL) - val index = parseIndex(Downloader.downloadString(base + INDEX) ?: return false) + val index = fetchIndex(base) ?: return false var complete = true for (name in pending) { val pack = index[name] diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/DesktopLanguageIndexSourceTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/DesktopLanguageIndexSourceTest.kt new file mode 100644 index 0000000000..3b4b008c50 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/runtime/DesktopLanguageIndexSourceTest.kt @@ -0,0 +1,62 @@ +package com.droiddeck.launcher.runtime + +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import com.droiddeck.launcher.core.DownloadSource +import com.droiddeck.launcher.core.Downloader +import java.net.ServerSocket +import java.util.concurrent.CopyOnWriteArrayList +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class DesktopLanguageIndexSourceTest { + private val base = "https://github.com/Droid-Deck/desktop/releases/download/t/" + private val tunnels = CopyOnWriteArrayList<String>() + private lateinit var context: Context + private lateinit var proxy: ServerSocket + + @Before fun setUp() { + proxy = ServerSocket(0) + Thread { + try { + while (!proxy.isClosed) { + proxy.accept().use { socket -> + val line = socket.getInputStream().bufferedReader().readLine() ?: return@use + tunnels += line.removePrefix("CONNECT ").substringBefore(':') + socket.getOutputStream().write("HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n".toByteArray()) + } + } + } catch (_: Exception) { + } + }.apply { isDaemon = true }.start() + context = ApplicationProvider.getApplicationContext() + DownloadSource.init(context) + DownloadSource.setMode(context, DownloadSource.MODE_MIRROR) + DownloadSource.setProxy(context, "127.0.0.1:${proxy.localPort}") + } + + @After fun tearDown() { + DownloadSource.setMode(context, DownloadSource.MODE_AUTO) + DownloadSource.setProxy(context, "") + proxy.close() + } + + @Test fun mirrorModeWouldOtherwiseSendTheIndexThroughAMirror() { + Downloader.downloadString(base + "desktop-kde.i18n.txt") + assertTrue(tunnels.toString(), tunnels.any { host -> DownloadSource.MIRRORS.any { it.host == host } }) + } + + @Test fun indexIsFetchedOnlyFromGithubInMirrorMode() { + assertNull(DesktopLanguage.fetchIndex(base)) + assertEquals(listOf("github.com"), tunnels.toList()) + } +} From 9e405ec92cfa02747a908cb0d090d22972ffbe4f Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:18:20 -0500 Subject: [PATCH 126/141] fix(game-env): run Hades II at D3D12 feature level 12_2 (#2855) --- .../linuxfs/overlay/usr/local/bin/droiddeck-game-env | 6 ++++++ tools/tests/test_game_environment.py | 12 ++++++++++++ 2 files changed, 18 insertions(+) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env index a465a93859..e620d47b2f 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env @@ -164,6 +164,12 @@ def ff7_rebirth_feature_level(game): return {"VKD3D_FEATURE_LEVEL": "12_2"}, [], "Final Fantasy VII Rebirth: D3D12 feature level 12_2 (the device-reported level fails its DX12 check)" +@fix +def hades2_feature_level(game): + if game.stem == "hades2": + return {"VKD3D_FEATURE_LEVEL": "12_2"}, [], "Hades II: D3D12 feature level 12_2 (on Adreno 6xx/7xx it finds no D3D12 adapter at the detected level)" + + @fix def kcd2_feature_level(game): if game.app_id == "1771300": diff --git a/tools/tests/test_game_environment.py b/tools/tests/test_game_environment.py index e2a6d85385..d17fc737b7 100644 --- a/tools/tests/test_game_environment.py +++ b/tools/tests/test_game_environment.py @@ -1866,6 +1866,18 @@ class GameEnvironmentTest(unittest.TestCase): self.assertEqual(MODULE["apply_config"]({}, config, "1771300", env), {"VKD3D_FEATURE_LEVEL": "12_1", "VKD3D_SHADER_MODEL": "6_9"}) self.assertEqual(MODULE["engine_fixes"](str(exe), [], "42")[0], {}) + def test_hades_ii_runs_at_feature_level_12_2_from_steam_and_xbox_unless_the_game_overrides_it(self): + with tempfile.TemporaryDirectory() as tmp: + for exe in (Path(tmp) / "Hades II/Ship/Hades2.exe", Path(tmp) / "Xbox/Hades II/Hades2.exe"): + exe.parent.mkdir(parents=True) + exe.touch() + env, extra, notes = MODULE["engine_fixes"](str(exe), []) + self.assertEqual(env, {"VKD3D_FEATURE_LEVEL": "12_2"}, str(exe)) + self.assertTrue(notes) + config = {"version": 1, "shared": {}, "games": {"42": {"VKD3D_FEATURE_LEVEL": "12_1"}}} + self.assertEqual(MODULE["apply_config"]({}, config, "42", env), {"VKD3D_FEATURE_LEVEL": "12_1"}) + self.assertEqual(MODULE["engine_fixes"]("/game/Hades/x64/Hades.exe", [])[0], {}) + def test_unity_players_keep_tso_over_the_preset(self): with tempfile.TemporaryDirectory() as tmp: def game(*names): From 5ca0575e679e368bd7d7aca51fd6c87c344125fe Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Tue, 24 Nov 2026 16:18:24 -0500 Subject: [PATCH 127/141] fix(gog): resolve exact-path depot overlays before validation (#2720) --- .../launcher/stores/gog/GogContent.kt | 10 +++- .../launcher/stores/gog/GogMaintenanceTest.kt | 52 +++++++++++++++++ .../resources/gog/gen2-overlay-excerpt.json | 58 +++++++++++++++++++ 3 files changed, 118 insertions(+), 2 deletions(-) create mode 100644 app/src/test/resources/gog/gen2-overlay-excerpt.json diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogContent.kt b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogContent.kt index 8ab48333e7..bd6f7a42f6 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogContent.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogContent.kt @@ -100,6 +100,7 @@ internal object GogContent { val manifest = metadata(build.link, token) onManifest(manifest) val files = JSONArray() + val overlayPositions = HashMap<String, Int>() val depots = if (build.generation == 1) manifest.optJSONObject("product")?.optJSONArray("depots") ?: manifest.optJSONArray("depot") else manifest.optJSONArray("depots") check(depots != null) { "GOG build has no depot list" } val resolvedLanguage = StoreLanguage.pick(StoreLanguage.codesFromDepots(depots), old.language) @@ -132,10 +133,15 @@ internal object GogContent { val directory = type == "DepotDirectory" || entry.has("directory") val chunks = entry.optJSONArray("chunks") ?: JSONArray() val size = if (build.generation == 2) chunks.objects().sumOf { it.optLong("size") } else entry.optLong("size") - files.put(JSONObject().put("path", path).put("size", size).put("directory", directory) + val file = JSONObject().put("path", path).put("size", size).put("directory", directory) .put("md5", entry.optString("md5").ifBlank { entry.optString("hash") }.takeIf { it.matches(Regex("[a-fA-F0-9]{32}")) }.orEmpty()) .put("sha256", entry.optString("sha256")).put("chunks", chunks).put("product", product) - .put("offset", entry.optLong("offset")).put("remotePath", entry.optString("url").substringBefore('?'))) + .put("offset", entry.optLong("offset")).put("remotePath", entry.optString("url").substringBefore('?')) + val position = if (build.generation == 2) overlayPositions.putIfAbsent(path, files.length()) else null + if (position == null) files.put(file) else { + require(files.getJSONObject(position).getBoolean("directory") == directory) + files.put(position, file) + } } } check(files.length() > 0) { "GOG build contains no matching files" } diff --git a/app/src/test/java/com/droiddeck/launcher/stores/gog/GogMaintenanceTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/gog/GogMaintenanceTest.kt index c98c1da30e..bad390d94e 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/gog/GogMaintenanceTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/gog/GogMaintenanceTest.kt @@ -291,6 +291,58 @@ class GogMaintenanceTest { assertEquals("patch_(52404)+special.exe", GogContent.downloadFilename("https://example.invalid/patch_%2852404%29+special.exe?token=temporary")) } + private fun overlaySnapshot(base: JSONArray, dlc: JSONArray, owned: Set<String> = setOf("2")): GogInstallRecord { + val manifest = JSONObject().put("depots", JSONArray().put(JSONObject().put("productId", "1") + .put("languages", JSONArray().put("*")).put("files", base).put("items", base)).put(JSONObject().put("productId", "2") + .put("languages", JSONArray().put("*")).put("files", dlc).put("items", dlc))) + return GogContent.snapshot(GogInstallRecord("1", "depot"), GogBuild("build", "", 2, "", "https://example.invalid/manifest"), + "unused", ownership = { owned }, metadata = { _, _ -> manifest }) + } + + @Test fun generationTwoOwnedDepotOverlaysReplaceExactPathsBeforeValidation() { + val fixture = JSONObject(javaClass.classLoader!!.getResource("gog/gen2-overlay-excerpt.json")!!.readText()) + val base = fixture.getJSONArray("base") + val dlc = fixture.getJSONArray("dlc") + base.put(JSONObject().put("path", "unique.bin").put("type", "DepotFile").put("chunks", JSONArray())) + val snapshot = overlaySnapshot(base, dlc) + assertEquals(3, snapshot.files.length()) + assertEquals(listOf("gog.dat", "gog.idx", "unique.bin"), snapshot.files.objects().map { it.getString("path") }) + for (i in 0..1) { + val file = snapshot.files.getJSONObject(i) + assertEquals("2", file.getString("product")) + assertEquals(dlc.getJSONObject(i).getJSONArray("chunks").toString(), file.getJSONArray("chunks").toString()) + assertEquals(dlc.getJSONObject(i).getJSONArray("chunks").getJSONObject(0).getLong("size"), file.getLong("size")) + } + assertEquals("1", snapshot.files.getJSONObject(2).getString("product")) + GogFiles.validate(snapshot.files, temporary.newFolder()) + val baseOnly = overlaySnapshot(base, dlc, emptySet()) + assertEquals(base.getJSONObject(0).getJSONArray("chunks").toString(), baseOnly.files.getJSONObject(0).getJSONArray("chunks").toString()) + assertTrue(baseOnly.files.objects().all { it.getString("product") == "1" }) + GogFiles.validate(baseOnly.files, temporary.newFolder()) + } + + @Test fun overlaysDoNotHideCaseAliasesTraversalLinksOrPathTypeChanges() { + fun entry(path: String, type: String = "DepotFile") = JSONObject().put("path", path).put("type", type) + for (path in listOf("game.bin", "../Game.bin", "Data/../Game.bin", ".droiddeck-store.json")) { + val snapshot = overlaySnapshot(JSONArray().put(entry("Game.bin")), JSONArray().put(entry(path))) + assertThrows(IllegalArgumentException::class.java) { GogFiles.validate(snapshot.files, temporary.newFolder()) } + } + assertThrows(IllegalArgumentException::class.java) { + overlaySnapshot(JSONArray().put(entry("Game.bin")), JSONArray().put(entry("Game.bin", "DepotDirectory"))) + } + assertThrows(IllegalStateException::class.java) { + overlaySnapshot(JSONArray().put(entry("Game.bin")), JSONArray().put(entry("Game.bin", "DepotLink"))) + } + val identical = JSONArray().put(entry("Game.bin")) + assertEquals(1, overlaySnapshot(identical, identical).files.length()) + val directories = JSONArray().put(entry("Data", "DepotDirectory")) + val merged = overlaySnapshot(directories, JSONArray().put(entry("Data", "DepotDirectory")).put(entry("Data/game.bin"))) + assertEquals(2, merged.files.length()) + GogFiles.validate(merged.files, temporary.newFolder()) + val aliases = overlaySnapshot(JSONArray().put(entry("Data/a")), JSONArray().put(entry("data/b"))) + assertThrows(IllegalArgumentException::class.java) { GogFiles.validate(aliases.files, temporary.newFolder()) } + } + @Test fun pathsRejectTraversalSymlinksCaseCollisionsAndMetadataOverlap() { val folder = temporary.newFolder() for (path in listOf("../escape", "/absolute", "C:/file", "a/./file", "a//file")) { diff --git a/app/src/test/resources/gog/gen2-overlay-excerpt.json b/app/src/test/resources/gog/gen2-overlay-excerpt.json new file mode 100644 index 0000000000..87cb615f9b --- /dev/null +++ b/app/src/test/resources/gog/gen2-overlay-excerpt.json @@ -0,0 +1,58 @@ +{ + "base": [ + { + "path": "gog.dat", + "chunks": [ + { + "md5": "63b62221caca352670bec591f0e4ed7a", + "size": 65664, + "compressedMd5": "c5695c2838aa020b028334cda81c89e6", + "compressedSize": 34046 + } + ], + "type": "DepotFile" + }, + { + "path": "gog.idx", + "chunks": [ + { + "md5": "0a1f9d90b61039cb3f4f2952f47aeea7", + "size": 28, + "compressedMd5": "7a7f3c3d18c10a3890426ed3f11f6220", + "compressedSize": 24 + } + ], + "type": "DepotFile", + "sfcRef": { + "offset": 11, + "size": 28 + } + } + ], + "dlc": [ + { + "path": "gog.dat", + "chunks": [ + { + "md5": "dac36aea47f5de743d0e0ca10c79ad58", + "size": 16777344, + "compressedMd5": "a27cd9af6e5183a6392c25c973fc367c", + "compressedSize": 3992002 + } + ], + "type": "DepotFile" + }, + { + "path": "gog.idx", + "chunks": [ + { + "md5": "ae818b813bd3585c47846cf1e288b2e5", + "size": 28, + "compressedMd5": "869fd5dd8c9ad554ca8bccb0317a9757", + "compressedSize": 26 + } + ], + "type": "DepotFile" + } + ] +} \ No newline at end of file From afe81ea69fffd624f95c09b9d2a01bb0efa6abeb Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Tue, 24 Nov 2026 16:21:40 -0500 Subject: [PATCH 128/141] fix(fex): x86-64 DwarFS AppImages start and GLib programs reach D-Bus (#3162) * fix(fex): a program run from a descriptor keeps its argv[0] and an absolute /proc/self/exe * fix(fex): 64-bit programs send their socket credentials through the hook D-Bus clients fill SCM_CREDENTIALS with getuid(), which is 0 under the guest. FEX sent x86-64 sendmsg straight to the kernel, which refused the fake root uid with EPERM, so GLib programs lost the session bus and every portal. sendmsg, recvmsg and getsockopt now go through libc like the identity calls, so the hook puts in the real ids and shows the peer as root. --- .../0017-fd-exec-keeps-argv0-and-path.patch | 26 ++++ ...0018-socket-credentials-through-libc.patch | 18 +++ tools/nativeguest/hook/privileged.c | 15 ++ tools/tests/test_fex_fd_exec.py | 35 +++++ tools/tests/test_fex_socket_credentials.py | 147 ++++++++++++++++++ 5 files changed, 241 insertions(+) create mode 100644 tools/fex/patches/0017-fd-exec-keeps-argv0-and-path.patch create mode 100644 tools/fex/patches/0018-socket-credentials-through-libc.patch create mode 100644 tools/tests/test_fex_fd_exec.py create mode 100644 tools/tests/test_fex_socket_credentials.py diff --git a/tools/fex/patches/0017-fd-exec-keeps-argv0-and-path.patch b/tools/fex/patches/0017-fd-exec-keeps-argv0-and-path.patch new file mode 100644 index 0000000000..2192b9b0af --- /dev/null +++ b/tools/fex/patches/0017-fd-exec-keeps-argv0-and-path.patch @@ -0,0 +1,26 @@ +diff --git a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp +index 2881ad9..abc84f3 100644 +--- a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp ++++ b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp +@@ -518,7 +518,7 @@ int main(int argc, char** argv, char** const envp) { + FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_CONFIG_NAME, Program.ProgramName); + } else { + // Anonymous program. +- FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_FILENAME, "<Anonymous>"); ++ FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_FILENAME, Program.ProgramPath); + FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_CONFIG_NAME, "<Anonymous>"); + } + } else { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp +index a7a432b..4a77d87 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp +@@ -441,7 +441,7 @@ uint64_t ExecveHandler(FEXCore::Core::CpuStateFrame* Frame, const char* pathname + if (*OldArgv) { + // The direct fallback uses the executable path as argv[0]. An FD-backed load uses the + // binfmt preserve-argv0 layout, so the caller-supplied argv[0] has to stay in the vector. +- if (!NeedsLoaderFD) { ++ if (!NeedsLoaderFD && !IsFDExec) { + ++OldArgv; + } + while (*OldArgv) { diff --git a/tools/fex/patches/0018-socket-credentials-through-libc.patch b/tools/fex/patches/0018-socket-credentials-through-libc.patch new file mode 100644 index 0000000000..d7ac6a2b12 --- /dev/null +++ b/tools/fex/patches/0018-socket-credentials-through-libc.patch @@ -0,0 +1,18 @@ +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp +index e287cd2..2181667 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp +@@ -469,10 +469,10 @@ namespace x64 { + REGISTER_SYSCALL_IMPL_X64(setitimer, SyscallPassthrough3<SYSCALL_DEF(setitimer)>); + REGISTER_SYSCALL_IMPL_X64(sendfile, SyscallPassthrough4<SYSCALL_DEF(sendfile)>); + REGISTER_SYSCALL_IMPL_X64(accept, SyscallPassthrough3<SYSCALL_DEF(accept)>); +- REGISTER_SYSCALL_IMPL_X64(sendmsg, SyscallPassthrough3<SYSCALL_DEF(sendmsg)>); +- REGISTER_SYSCALL_IMPL_X64(recvmsg, SyscallPassthrough3<SYSCALL_DEF(recvmsg)>); ++ REGISTER_SYSCALL_IMPL_X64(sendmsg, SyscallPathPassthrough3<SYSCALL_DEF(sendmsg)>); ++ REGISTER_SYSCALL_IMPL_X64(recvmsg, SyscallPathPassthrough3<SYSCALL_DEF(recvmsg)>); + REGISTER_SYSCALL_IMPL_X64(setsockopt, SyscallPassthrough5<SYSCALL_DEF(setsockopt)>); +- REGISTER_SYSCALL_IMPL_X64(getsockopt, SyscallPassthrough5<SYSCALL_DEF(getsockopt)>); ++ REGISTER_SYSCALL_IMPL_X64(getsockopt, SyscallPathPassthrough5<SYSCALL_DEF(getsockopt)>); + REGISTER_SYSCALL_IMPL_X64(wait4, SyscallPassthrough4<SYSCALL_DEF(wait4)>); + REGISTER_SYSCALL_IMPL_X64(semop, SyscallPassthrough3<SYSCALL_DEF(semop)>); + REGISTER_SYSCALL_IMPL_X64(getrlimit, SyscallPassthrough2<SYSCALL_DEF(getrlimit)>); diff --git a/tools/nativeguest/hook/privileged.c b/tools/nativeguest/hook/privileged.c index 159f330716..d2a84c7a23 100644 --- a/tools/nativeguest/hook/privileged.c +++ b/tools/nativeguest/hook/privileged.c @@ -724,6 +724,21 @@ long syscall(long number, ...) { return (long)bind((int)arg1, (const struct sockaddr *)arg2, (socklen_t)arg3); } #endif +#if defined(__NR_sendmsg) + if (number == __NR_sendmsg) { + return (long)sendmsg((int)arg1, (const struct msghdr *)arg2, (int)arg3); + } +#endif +#if defined(__NR_recvmsg) + if (number == __NR_recvmsg) { + return (long)recvmsg((int)arg1, (struct msghdr *)arg2, (int)arg3); + } +#endif +#if defined(__NR_getsockopt) + if (number == __NR_getsockopt) { + return (long)getsockopt((int)arg1, (int)arg2, (int)arg3, (void *)arg4, (socklen_t *)arg5); + } +#endif #if defined(__NR_truncate) if (number == __NR_truncate) { return (long)truncate((const char *)arg1, (off_t)arg2); diff --git a/tools/tests/test_fex_fd_exec.py b/tools/tests/test_fex_fd_exec.py new file mode 100644 index 0000000000..4b917ec539 --- /dev/null +++ b/tools/tests/test_fex_fd_exec.py @@ -0,0 +1,35 @@ +import re +import unittest +from pathlib import Path + +REPO = Path(__file__).resolve().parents[2] +PATCH = REPO / "tools/fex/patches/0017-fd-exec-keeps-argv0-and-path.patch" +SYSCALLS = "Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp" +INTERPRETER = "Source/Tools/FEXInterpreter/FEXInterpreter.cpp" + + +def lines(sign): + return [line[1:].strip() for line in PATCH.read_text().splitlines() if line.startswith(sign) and not line.startswith(sign * 3)] + + +class FexFdExecTest(unittest.TestCase): + def test_only_the_execve_handler_and_the_interpreter_change(self): + self.assertEqual([INTERPRETER, SYSCALLS], re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M)) + + def test_a_descriptor_exec_keeps_the_callers_argv0(self): + self.assertIn("if (!NeedsLoaderFD) {", lines("-")) + self.assertIn("if (!NeedsLoaderFD && !IsFDExec) {", lines("+")) + + def test_an_anonymous_program_reports_its_recovered_path(self): + self.assertIn('FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_FILENAME, "<Anonymous>");', lines("-")) + self.assertIn("FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_FILENAME, Program.ProgramPath);", lines("+")) + + def test_the_config_name_stays_anonymous(self): + self.assertNotIn('FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_CONFIG_NAME, "<Anonymous>");', lines("-")) + + def test_no_comments_are_added(self): + self.assertFalse([line for line in lines("+") if line.startswith(("//", "/*"))]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_fex_socket_credentials.py b/tools/tests/test_fex_socket_credentials.py new file mode 100644 index 0000000000..c8e13ea688 --- /dev/null +++ b/tools/tests/test_fex_socket_credentials.py @@ -0,0 +1,147 @@ +import os +import re +import subprocess +import tempfile +import unittest +from pathlib import Path + +from tools.tests.test_usr2_preload import runner + +REPO = Path(__file__).resolve().parents[2] +PATCH = REPO / "tools/fex/patches/0018-socket-credentials-through-libc.patch" +HOOK = REPO / "tools/nativeguest/hook/privileged.c" +HOOK_BUILD = REPO / "tools/nativeguest/build.sh" +PASSTHROUGH = "Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp" +REGISTER = re.compile(r"REGISTER_SYSCALL_IMPL_X64\((\w+), (\w+?)(\d)<SYSCALL_DEF\((\w+)\)>\);") +ROUTED = {"sendmsg", "recvmsg", "getsockopt"} + + +def changed(): + removed, added = {}, {} + for line in PATCH.read_text().splitlines(): + found = REGISTER.search(line) + if found and line[:1] in "+-": + (added if line[0] == "+" else removed)[found.group(1)] = found.groups()[1:] + return removed, added + + +class FexSocketCredentialsTest(unittest.TestCase): + def test_only_the_passthrough_table_changes(self): + self.assertEqual([PASSTHROUGH], re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M)) + + def test_each_socket_call_keeps_its_arity_and_goes_through_libc(self): + removed, added = changed() + self.assertEqual(ROUTED, set(removed)) + self.assertEqual(ROUTED, set(added)) + for name, (template, arity, number) in added.items(): + with self.subTest(name=name): + self.assertEqual(name, number) + self.assertEqual(("SyscallPassthrough", arity, number), removed[name]) + self.assertEqual("SyscallPathPassthrough", template) + + def test_every_routed_call_is_answered_by_the_hook(self): + hook = HOOK.read_text() + for number in ROUTED: + with self.subTest(number=number): + self.assertIn(f"number == __NR_{number})", hook) + + +PROBE = r""" +#define _GNU_SOURCE +#include <errno.h> +#include <stdio.h> +#include <string.h> +#include <sys/socket.h> +#include <sys/syscall.h> +#include <unistd.h> + +int main(void) { + int sv[2], on = 1; + if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0) return 2; + setsockopt(sv[1], SOL_SOCKET, SO_PASSCRED, &on, sizeof(on)); + struct ucred sent = {getpid(), (uid_t)syscall(SYS_getuid), (gid_t)syscall(SYS_getgid)}; + char byte = 0, ctrl[CMSG_SPACE(sizeof(struct ucred))]; + struct iovec iov = {&byte, 1}; + struct msghdr msg = {0}; + msg.msg_iov = &iov; + msg.msg_iovlen = 1; + msg.msg_control = ctrl; + msg.msg_controllen = sizeof(ctrl); + struct cmsghdr *c = CMSG_FIRSTHDR(&msg); + c->cmsg_level = SOL_SOCKET; + c->cmsg_type = SCM_CREDENTIALS; + c->cmsg_len = CMSG_LEN(sizeof(sent)); + memcpy(CMSG_DATA(c), &sent, sizeof(sent)); + errno = 0; + long rc = syscall(SYS_sendmsg, sv[0], &msg, 0); + printf("sendmsg %ld %d %u\n", rc, errno, sent.uid); + char in_ctrl[CMSG_SPACE(sizeof(struct ucred))]; + struct msghdr in = {0}; + in.msg_iov = &iov; + in.msg_iovlen = 1; + in.msg_control = in_ctrl; + in.msg_controllen = sizeof(in_ctrl); + rc = syscall(SYS_recvmsg, sv[1], &in, MSG_DONTWAIT); + struct ucred got = {0, 99, 99}; + for (c = CMSG_FIRSTHDR(&in); c; c = CMSG_NXTHDR(&in, c)) + if (c->cmsg_type == SCM_CREDENTIALS) memcpy(&got, CMSG_DATA(c), sizeof(got)); + printf("recvmsg %ld %u\n", rc, got.uid); + struct ucred peer = {0, 99, 99}; + socklen_t len = sizeof(peer); + rc = syscall(SYS_getsockopt, sv[1], SOL_SOCKET, SO_PEERCRED, &peer, &len); + printf("peercred %ld %u\n", rc, peer.uid); + return 0; +} +""" + + +class NativeHookSocketCredentialsTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + if os.getuid() == 0: + raise unittest.SkipTest("root may send any credentials") + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + cls.tmp = tempfile.TemporaryDirectory() + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "probe.c").write_text(PROBE) + subprocess.run([cls.cc, "-O1", "-o", str(tmp / "probe"), str(tmp / "probe.c")], check=True) + (tmp / "root").mkdir() + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def probe(self, hooked): + hook_env = {"DDNATV_ROOT": str(Path(self.tmp.name) / "root")} + if hooked: + hook_env["LD_PRELOAD"] = str(self.hook) + env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"} + if self.prefix: + cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] + else: + cmd = [] + env.update(hook_env) + out = subprocess.run(cmd + [str(Path(self.tmp.name) / "probe")], env=env, capture_output=True, text=True, + timeout=120) + self.assertEqual(0, out.returncode, out.stderr) + return {line.split(" ", 1)[0]: line.split(" ", 1)[1] for line in out.stdout.splitlines()} + + def test_root_credentials_sent_through_the_raw_call_reach_the_peer_as_root(self): + result = self.probe(hooked=True) + self.assertEqual("1 0 0", result["sendmsg"]) + self.assertEqual("1 0", result["recvmsg"]) + self.assertEqual("0 0", result["peercred"]) + + def test_without_the_hook_the_kernel_keeps_the_real_ids(self): + result = self.probe(hooked=False) + self.assertEqual(f"1 0 {os.getuid()}", result["sendmsg"]) + self.assertEqual(f"1 {os.getuid()}", result["recvmsg"]) + self.assertEqual(f"0 {os.getuid()}", result["peercred"]) + + +if __name__ == "__main__": + unittest.main() From 14b130500f11a8f0ff6ed4a7d7d5defc6cfc9277 Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Tue, 24 Nov 2026 16:23:06 -0500 Subject: [PATCH 129/141] fix(desktop): a program started through a directory link knows its real path (#3158) * fix(desktop): a program started through a directory link knows its real path * fix(desktop): a missing or non-directory component still fails the lookup --- tools/nativeguest/hook/exec.c | 72 ++++++++++-- tools/tests/test_native_hook_exec_target.py | 116 ++++++++++++++++++++ 2 files changed, 178 insertions(+), 10 deletions(-) create mode 100644 tools/tests/test_native_hook_exec_target.py diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index 5bf75ae4aa..8d18c2d394 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -9,17 +9,73 @@ // Runs before every exec, mostly in a child a shell has just forked: the copies write only the // string (ddnatv_copy_cstr), not the whole PATH_MAX buffer, since each page written there is a // copy-on-write fault. +static int follow_link(const char *path, char *target, size_t size) { + ssize_t len = readlink(path, target, size - 1); + if (len < 0) return 0; + target[len] = '\0'; + // proot's link2symlink leaves hard links as ".l2s.*" files that programs must not see by name + const char *base = strrchr(target, '/'); + return strncmp(base ? base + 1 : target, ".l2s.", 5) != 0; +} + static void resolve_symlinks(const char *path, char *out, size_t out_size, int depth) { if (!path || !out || out_size == 0) return; ddnatv_copy_cstr(out, out_size, path); if (depth > 8) return; - char link_target[PATH_MAX]; - ssize_t len = readlink(path, link_target, sizeof(link_target) - 1); - if (len < 0) return; - link_target[len] = '\0'; - char next_path[PATH_MAX]; + if (g_ddnatv_root_len > 0 && strncmp(path, g_ddnatv_root, g_ddnatv_root_len) == 0 && path[g_ddnatv_root_len] == '/') { + char done[PATH_MAX]; + char todo[PATH_MAX]; + size_t used = ddnatv_append(done, sizeof(done), 0, g_ddnatv_root, g_ddnatv_root_len); + ddnatv_copy_cstr(todo, sizeof(todo), path + g_ddnatv_root_len); + int links = 0; + char *rest = todo; + while (*rest) { + while (*rest == '/') rest++; + if (!*rest) break; + char *end = strchr(rest, '/'); + size_t n = end ? (size_t)(end - rest) : strlen(rest); + if (n == 1 && rest[0] == '.') { + rest += n; + continue; + } + if (n == 2 && rest[0] == '.' && rest[1] == '.') { + char *slash = strrchr(done + g_ddnatv_root_len, '/'); + if (slash) used = (size_t)(slash - done); + done[used] = '\0'; + rest += n; + continue; + } + size_t before = used; + used = ddnatv_append(done, sizeof(done), used, "/", 1); + used = ddnatv_append(done, sizeof(done), used, rest, n); + rest += n; + if (used >= sizeof(done) - 1) return; + if (!follow_link(done, link_target, sizeof(link_target))) { + struct stat st; + if (rest[strspn(rest, "/")] && (syscall(SYS_newfstatat, AT_FDCWD, done, &st, 0) != 0 || !S_ISDIR(st.st_mode))) return; + continue; + } + if (++links > 40) return; + size_t m = ddnatv_append(next_path, sizeof(next_path), 0, link_target, strlen(link_target)); + m = ddnatv_append(next_path, sizeof(next_path), m, "/", 1); + m = ddnatv_append(next_path, sizeof(next_path), m, rest, strlen(rest)); + if (m >= sizeof(next_path) - 1) return; + if (link_target[0] == '/') { + char rw_buf[PATH_MAX]; + resolve_symlinks(rewrite_path(next_path, rw_buf, sizeof(rw_buf)), out, out_size, depth + 1); + return; + } + used = before; + done[used] = '\0'; + ddnatv_copy_cstr(todo, sizeof(todo), next_path); + rest = todo; + } + if (used > g_ddnatv_root_len) ddnatv_copy_cstr(out, out_size, done); + return; + } + if (!follow_link(path, link_target, sizeof(link_target))) return; if (link_target[0] == '/') { char rw_buf[PATH_MAX]; const char *rewritten = rewrite_path(link_target, rw_buf, sizeof(rw_buf)); @@ -32,15 +88,11 @@ static void resolve_symlinks(const char *path, char *out, size_t out_size, int d memcpy(next_path, path, dir_len); next_path[dir_len] = '\0'; size_t n = ddnatv_append(next_path, sizeof(next_path), dir_len, "/", 1); - ddnatv_append(next_path, sizeof(next_path), n, link_target, (size_t)len); + ddnatv_append(next_path, sizeof(next_path), n, link_target, strlen(link_target)); } else { ddnatv_copy_cstr(next_path, sizeof(next_path), link_target); } } - // proot's link2symlink leaves hard links as ".l2s.*" files that programs must not see by name - const char *next_base = strrchr(next_path, '/'); - next_base = next_base ? next_base + 1 : next_path; - if (strncmp(next_base, ".l2s.", 5) == 0) return; resolve_symlinks(next_path, out, out_size, depth + 1); } diff --git a/tools/tests/test_native_hook_exec_target.py b/tools/tests/test_native_hook_exec_target.py new file mode 100644 index 0000000000..29c7b10cac --- /dev/null +++ b/tools/tests/test_native_hook_exec_target.py @@ -0,0 +1,116 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" + +RECORDER = r""" +#include <stdio.h> +#include <string.h> +#include <unistd.h> + +int execve(const char *path, char *const argv[], char *const envp[]) { + const char *exe = "-"; + for (int i = 0; envp && envp[i]; i++) + if (strncmp(envp[i], "DDNATV_REAL_EXE=", 16) == 0) exe = envp[i] + 16; + printf("exe\t%s\n", exe); + fflush(stdout); + _exit(0); +} +""" + +PROBE = r""" +#include <stdio.h> +#include <unistd.h> + +int main(int argc, char **argv) { + if (argc < 2) return 0; + char *args[] = {argv[1], NULL}; + execv(argv[1], args); + perror("execv"); + return 1; +} +""" + + +class NativeHookExecTargetTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + cls.tmp = tempfile.TemporaryDirectory() + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "recorder.c").write_text(RECORDER) + cls.recorder = tmp / "recorder.so" + subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.recorder), str(tmp / "recorder.c")], check=True) + (tmp / "probe.c").write_text(PROBE) + cls.probe = tmp / "probe" + subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True) + cls.root = tmp / "root" + opt = cls.root / "opt" + (opt / "real").mkdir(parents=True) + (opt / "nest").mkdir() + (cls.root / "lib").mkdir() + (cls.root / "lib/ld-linux-aarch64.so.1").write_bytes(b"") + shutil.copy(cls.probe, opt / "real/prog") + shutil.copy(cls.probe, opt / "real/.l2s.prog0001") + os.symlink("./real", opt / "rel") + os.symlink("/opt/real", opt / "abs") + os.symlink("../rel", opt / "nest/sub") + os.symlink("rel/prog", opt / "link") + os.symlink(".l2s.prog0001", opt / "real/hard") + cls.real = str(opt / "real/prog") + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def exe(self, program): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook}:{self.recorder}"} + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT", "DDNATV_REAL_EXE")} + if self.prefix: + cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] + else: + cmd = [] + env.update(hook_env) + out = subprocess.run(cmd + [str(self.probe), program], env=env, capture_output=True, text=True, timeout=120) + for line in out.stdout.splitlines(): + if line.startswith("exe\t"): + return line.split("\t", 1)[1] + self.fail(out.stdout + out.stderr) + + def test_a_program_reached_through_a_relative_directory_link_is_named_by_its_real_path(self): + self.assertEqual(self.real, self.exe("/opt/rel/prog")) + + def test_a_program_reached_through_a_guest_absolute_directory_link_is_named_by_its_real_path(self): + self.assertEqual(self.real, self.exe("/opt/abs/prog")) + + def test_links_that_climb_with_dot_dot_resolve_like_the_kernel(self): + self.assertEqual(self.real, self.exe("/opt/nest/sub/./prog")) + + def test_a_link_to_the_program_itself_still_resolves(self): + self.assertEqual(self.real, self.exe("/opt/link")) + + def test_a_plain_path_is_unchanged(self): + self.assertEqual(self.real, self.exe("/opt/real/prog")) + + def test_a_missing_directory_is_not_skipped_by_dot_dot(self): + self.assertNotEqual(self.real, self.exe("/opt/missing/../real/prog")) + + def test_a_file_is_not_used_as_a_directory(self): + self.assertNotEqual(self.real, self.exe("/opt/real/prog/../prog")) + + def test_a_proot_hard_link_keeps_its_own_name(self): + self.assertEqual(str(self.root / "opt/real/hard"), self.exe("/opt/real/hard")) + + +if __name__ == "__main__": + unittest.main() From 7c8f5c27077ec83494bf939b55367bf79827ce1b Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:26:55 -0500 Subject: [PATCH 130/141] fix(ui): changing the language restarts the launcher instead of leaving it frozen (#3163) * fix(ui): changing the language restarts the launcher instead of leaving it frozen * fix(ui): a launcher restart no longer starts the startup session * fix(ui): a stopping launcher no longer clears the hooks its replacement set * fix(ui): a launcher restart keeps a pending session switch * fix(ui): a launcher restart hands its state over in-process, not through intent extras --- .../droiddeck/launcher/FrontEndActivity.kt | 60 +++++++++++++------ .../com/droiddeck/launcher/HomeWidgets.kt | 6 ++ .../com/droiddeck/launcher/LauncherHandoff.kt | 27 +++++++++ 3 files changed, 75 insertions(+), 18 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/LauncherHandoff.kt diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index 664f9db4c1..b281adf4c2 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -923,12 +923,24 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet LauncherIcon.set(this, style) launcherIcon = LauncherIcon.current(this) if (launcherIcon == before) return false + restartLauncher() + return true + } + + // recreate() leaves this activity's window drawing nothing and ignoring input on some devices (#2668). + private fun restartLauncher() { + LauncherHandoff.put(Bundle().also(::saveLauncherState)) + switchPoll?.let { ui.removeCallbacks(it) } + switchPoll = null + switchingTo = null + queuedLaunch.clear() + cancelCompatLaunch() startActivity(Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER) .setComponent(LauncherIcon.activity(this)) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK) - .putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, "setup:launcher")) + .putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, "setup:launcher") + .putExtra(EXTRA_RESTARTED, true)) finishAndRemoveTask() - return true } private fun readGameIntent(request: Intent) { @@ -1257,13 +1269,15 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet super.onCreate(savedInstanceState) drivers.restartBlocked = ::runtimeChangesBlocked drivers.loadTpUbwcMode() - pendingSessionLogExport = savedInstanceState?.getString(KEY_PENDING_SESSION_LOG_EXPORT)?.let(::File) + val handoff = if (savedInstanceState == null && intent.getBooleanExtra(EXTRA_RESTARTED, false)) LauncherHandoff.take() else null + val saved = savedInstanceState ?: handoff + pendingSessionLogExport = saved?.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(), + saved?.let { androidx.core.os.BundleCompat.getParcelable(it, STATE_PENDING_GATE_LAUNCH, Intent::class.java) }, + saved?.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 + homeChoiceOpen = saved?.getBoolean(STATE_HOME_CHOICE_OPEN) == true + gameSpaceOffered = saved?.getBoolean(STATE_GAME_SPACE_OFFERED) == true if (savedInstanceState == null) readIntegrationIntent(intent) val shortcutsFilter = android.content.IntentFilter(SteamIntegration.SHORTCUTS_STATUS) if (android.os.Build.VERSION.SDK_INT >= 33) registerReceiver(shortcutsInstallStatus, shortcutsFilter, RECEIVER_NOT_EXPORTED) @@ -1688,7 +1702,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet onLanguage = { tag -> if (tag != com.droiddeck.launcher.core.AppLanguage.chosen(this)) { com.droiddeck.launcher.core.AppLanguage.setChosen(this, tag) - recreate() + restartLauncher() } }, onAppScale = { percent -> @@ -1904,10 +1918,11 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet !SessionPrefs.allFilesAsked(this) if (savedInstanceState == null) { if (!askAllFiles) ui.post { startSteamAtStartupIfEnabled(cold = true) } - } else { - restoreCompatLaunch(savedInstanceState) - pendingSwitch = savedIntent(savedInstanceState, KEY_PENDING_SWITCH) - savedIntent(savedInstanceState, KEY_SWITCHING_TO)?.let { awaitSessionEnd(it, savedInstanceState.getLong(KEY_SWITCH_DEADLINE)) } + } + saved?.let { state -> + restoreCompatLaunch(state) + pendingSwitch = savedIntent(state, KEY_PENDING_SWITCH) + savedIntent(state, KEY_SWITCHING_TO)?.let { awaitSessionEnd(it, state.getLong(KEY_SWITCH_DEADLINE)) } } val wanted = ArrayList<String>() @@ -1960,8 +1975,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private var soundtrackLaunch = false + // A restarted launcher starts before the old one stops, so each clears the hooks only if they are still its own. + private val libraryHook: () -> Unit = { refreshAddedGames(); refresh() } + private val battleNetHook: (List<String>) -> Unit = { args -> openBattleNet(args) } + private fun startSteamAtStartupIfEnabled(cold: Boolean = false) { - if (soundtrackLaunch) return + if (soundtrackLaunch || intent.getBooleanExtra(EXTRA_RESTARTED, false)) return if (intent.action != Intent.ACTION_MAIN && !(cold && intent.action == null)) return if (isFinishing || isDestroyed) return when (SessionPrefs.startupSession(this)) { @@ -2136,8 +2155,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet homePage = com.droiddeck.launcher.core.AppUiPrefs.homePage(this) refreshWifiDiscovery() com.droiddeck.launcher.stores.StoresState.refresh(this) - com.droiddeck.launcher.stores.StoresState.libraryListener = { refreshAddedGames(); refresh() } - com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = { args -> openBattleNet(args) } + com.droiddeck.launcher.stores.StoresState.libraryListener = libraryHook + com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = battleNetHook com.droiddeck.launcher.ui.Motion.refresh(this) com.droiddeck.launcher.ui.QuitFlood.take()?.let { c -> returning = ReturningFlood(c, com.droiddeck.launcher.ui.LaunchOrigin.takeReturn()) @@ -2208,6 +2227,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) + saveLauncherState(outState) + } + + private fun saveLauncherState(outState: Bundle) { 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) } @@ -2264,8 +2287,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet getSystemService(android.content.pm.LauncherApps::class.java).unregisterCallback(packageCallback) HomeWidgets.stopListening(this) ui.removeCallbacks(mediaRefresh) - com.droiddeck.launcher.stores.StoresState.libraryListener = null - com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = null + if (com.droiddeck.launcher.stores.StoresState.libraryListener === libraryHook) com.droiddeck.launcher.stores.StoresState.libraryListener = null + if (com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener === battleNetHook) com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = null displayManager.unregisterDisplayListener(secondScreenDisplayListener) com.droiddeck.launcher.input.DualScreen.unwatchTaken(bottomScreenListener) getSystemService(android.hardware.input.InputManager::class.java)?.unregisterInputDeviceListener(secondScreenTouchListener) @@ -3484,7 +3507,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet com.droiddeck.launcher.ui.Motion.refresh(this) com.droiddeck.launcher.ui.DeveloperTools.load(this) com.droiddeck.launcher.ui.NavTabs.load(this) - if (!switchLauncherIcon(LauncherIcon.DARK)) recreate() + if (!switchLauncherIcon(LauncherIcon.DARK)) restartLauncher() } }, "reset-settings").start() } @@ -3558,6 +3581,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet companion object { private const val REQUEST_NOTIFICATIONS = 7103 + private const val EXTRA_RESTARTED = "com.droiddeck.launcher.extra.RESTARTED" 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" diff --git a/app/src/main/java/com/droiddeck/launcher/HomeWidgets.kt b/app/src/main/java/com/droiddeck/launcher/HomeWidgets.kt index 886f5f0e89..967ba6ee47 100644 --- a/app/src/main/java/com/droiddeck/launcher/HomeWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/HomeWidgets.kt @@ -118,12 +118,18 @@ object HomeWidgets { if (live.size != parsed.size) save(context) } + private val listeners: MutableSet<Any> = java.util.Collections.newSetFromMap(java.util.IdentityHashMap()) + fun startListening(context: Context) { + listeners.add(context) load(context) runCatching { host(context).startListening() } } + // A restarted launcher starts before the old one stops; the host keeps listening until the last owner stops. fun stopListening(context: Context) { + listeners.remove(context) + if (listeners.isNotEmpty()) return runCatching { host(context).stopListening() } } diff --git a/app/src/main/java/com/droiddeck/launcher/LauncherHandoff.kt b/app/src/main/java/com/droiddeck/launcher/LauncherHandoff.kt new file mode 100644 index 0000000000..2284a531c8 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/LauncherHandoff.kt @@ -0,0 +1,27 @@ +package com.droiddeck.launcher + +import android.os.Bundle +import android.os.SystemClock + +/** + * State a restarting launcher passes to its replacement inside this process. Intent extras are not used + * because FrontEndActivity is exported and any app could fill them. + */ +internal object LauncherHandoff { + private const val LIFETIME_MS = 10_000L + private var state: Bundle? = null + private var at = 0L + + @Synchronized + fun put(carried: Bundle) { + state = carried + at = SystemClock.elapsedRealtime() + } + + @Synchronized + fun take(): Bundle? { + val carried = state + state = null + return carried?.takeIf { SystemClock.elapsedRealtime() - at <= LIFETIME_MS } + } +} From 9a7cb7096923322b083d6f9c2d0a98902a874853 Mon Sep 17 00:00:00 2001 From: visail <visail@126.com> Date: Wed, 25 Nov 2026 06:14:35 +0800 Subject: [PATCH 131/141] fix(session): serialize launch requests in a coordinator (#3044) * fix(session): serialize launch requests in a coordinator Replace the gameLaunchRequest counter and the single pendingGameLink field with a LaunchCoordinator. A launch is now identified by a ticket, so a stale callback can only act on its own request, and a game link is superseded by any newer launch. Launching is also refused while a package install stage is in progress. * fix(frontend): a replacement intent supersedes uncommitted launch state A game link that resolved while the launcher was not resumed stayed pending, so opening Settings, following a notification or picking a shortcut left it in the coordinator and the next library refresh launched the old game over the new screen. The same gap let an ACTION_SETUP intent leave an accepted launch current, so a late Xbox manifest check could start the game after the user had moved on. A replacement activity intent now cancels every ticket this activity has not dispatched, and the refresh path may only finish a link owned by the intent the activity shows. The toast for a superseded store lookup is gated on its ticket, and the coordinator test now proves cancelAll() invalidates a link ticket. The deferred Proton-compat launch is untouched: its ordering still predates this change and has its own follow-up. --- .../droiddeck/launcher/FrontEndActivity.kt | 150 +++++++++++++----- .../launcher/session/LaunchCoordinator.kt | 82 ++++++++++ .../launcher/FrontEndIntentSupersedeTest.kt | 85 ++++++++++ .../launcher/session/LaunchCoordinatorTest.kt | 121 ++++++++++++++ 4 files changed, 402 insertions(+), 36 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/session/LaunchCoordinator.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/FrontEndIntentSupersedeTest.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/session/LaunchCoordinatorTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index b281adf4c2..a26bb5d81e 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -53,6 +53,8 @@ import com.droiddeck.launcher.session.SessionLogShare import com.droiddeck.launcher.session.SessionPaths import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.SteamRepair +import com.droiddeck.launcher.session.LaunchCoordinator +import com.droiddeck.launcher.session.LaunchTicket import com.droiddeck.launcher.core.CpuCores import com.droiddeck.launcher.core.DownloadSource import com.droiddeck.launcher.core.PhantomProcessLimit @@ -215,7 +217,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private var soundtracksLoaded by mutableStateOf(false) private var gameStoresSpeedTier by mutableStateOf("fast") private var navRequest by mutableStateOf<String?>(null) - private val gameLaunchRequest = java.util.concurrent.atomic.AtomicLong() + private val launchCoordinator = LaunchCoordinator<Intent, com.droiddeck.launcher.frontend.GameRequest>() private var preparingGames by mutableStateOf(emptySet<String>()) private var storesShowMature by mutableStateOf(false) private var storesSort by mutableStateOf(SessionPrefs.STORES_SORTS.first()) @@ -897,7 +899,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet runCatching { com.droiddeck.launcher.frontend.AutoComponents.restoreMissing(this) }.onFailure { Log.w(TAG, "components: restore failed", it) } }, "components-restore").start() } - private var pendingGameLink: com.droiddeck.launcher.frontend.GameRequest? = null private var gameLinkReading = false private var gameLinkTried = false private var gameSyncFolder by mutableStateOf<String?>(null) @@ -951,7 +952,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet else "settings:" + (com.droiddeck.launcher.ui.SettingsSection.of(section) ?: com.droiddeck.launcher.ui.SettingsSection.OVERVIEW).key request.data = null gameLinkReading = false - pendingGameLink = null syncDualPanel() return } @@ -964,7 +964,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet steamGames = emptyList() shortcutLibraryScanning = true } else shortcutLibraryScanning = false - pendingGameLink = null gameLinkReading = false gameLinkTried = false soundtrackLaunch = false @@ -977,6 +976,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet return } if (GameLaunchIntent.accepts(request.action)) { + val ticket = launchCoordinator.beginLink(request) gameLinkReading = true com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId) val copy = Intent(request) @@ -985,12 +985,17 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet ui.post { if (intent === request && !isDestroyed) { gameLinkReading = false - pendingGameLink = game + if (!launchCoordinator.resolve(ticket, game)) { + clearGameLinkIntent(request) + syncDualPanel() + return@post + } if (game == null) { + launchCoordinator.consume(ticket) syncDualPanel() android.widget.Toast.makeText(this, R.string.game_link_invalid, android.widget.Toast.LENGTH_LONG).show() } else { - handleGameLink(steamGames, scanned = false) + handleGameLink(steamGames, scanned = false, ticket = ticket) refresh() } } @@ -999,37 +1004,66 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } } - private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false, onHandled: () -> Unit = {}, onSettled: () -> Unit = {}) { - val request = gameLaunchRequest.incrementAndGet() + private fun beginUiLaunch(): LaunchTicket { + val dropped = launchCoordinator.pendingLink() + val ticket = launchCoordinator.beginLaunch() + dropped?.let { if (intent === it.owner) clearGameLinkIntent(it.owner) } + return ticket + } + + private fun clearGameLinkIntent(link: Intent) { + link.data = null + link.action = Intent.ACTION_MAIN + link.removeExtra(GameLaunchIntent.EXTRA_APP_ID) + } + + private fun launchGame( + game: Library.SteamGame, + returnHome: Boolean = false, + onHandled: () -> Unit = {}, + onSettled: () -> Unit = {}, + ticket: LaunchTicket? = null, + ) { if (!SessionPrefs.soundtracksIngame(this)) com.droiddeck.launcher.playback.SoundtrackController.pause(this) if (pkgStage != null) { + ticket?.let(launchCoordinator::releaseHandling) onHandled() android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show() return } + val request = ticket ?: beginUiLaunch() + if (!launchCoordinator.isCurrent(request)) { + onHandled() + return + } val files = game.gameFiles if (game.source != com.droiddeck.launcher.stores.Store.XBOX.id || files == null) { - if (startGame(game, returnHome, onHandled)) onSettled() + if (startGame(game, returnHome, onHandled, request)) onSettled() + else launchCoordinator.releaseHandling(request) return } Thread({ val refused = com.droiddeck.launcher.stores.xbox.XboxManifest.needsAppModel(files) ui.post { when { - request != gameLaunchRequest.get() || isFinishing || isDestroyed -> onHandled() + !launchCoordinator.isCurrent(request) || isFinishing || isDestroyed -> { + launchCoordinator.releaseHandling(request) + onHandled() + } refused -> { onHandled() android.widget.Toast.makeText(this, getString(R.string.game_needs_app_model, game.name), android.widget.Toast.LENGTH_LONG).show() onSettled() } - startGame(game, returnHome, onHandled) -> onSettled() + startGame(game, returnHome, onHandled, request) -> onSettled() + else -> launchCoordinator.releaseHandling(request) } } }, "xbox-app-model").start() } - private fun startGame(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit): Boolean { - if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome, onHandled) + private fun startGame(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit, ticket: LaunchTicket): Boolean { + if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome, onHandled, ticket) onHandled() if (SessionState.running) { if (SessionState.mode != SessionService.MODE_STEAM || SessionState.stopRequested) { @@ -1074,15 +1108,34 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet .apply { if (returnHome) putExtra(SessionActivity.EXTRA_LINK_TASK, task) } } - private fun launchWithoutSteam(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit = {}): Boolean { + private fun launchWithoutSteam( + game: Library.SteamGame, + returnHome: Boolean, + onHandled: () -> Unit = {}, + ticket: LaunchTicket? = null, + ): Boolean { + if (pkgStage != null) { + onHandled() + android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show() + return false + } val app = applicationContext + val request = ticket ?: beginUiLaunch() + if (!launchCoordinator.isCurrent(request)) { + onHandled() + return false + } Thread({ val added = if (com.droiddeck.launcher.session.NoSteamLaunch.needsAddedGame(game)) runCatching { com.droiddeck.launcher.session.NoSteamLaunch.addedGame(app, game) }.getOrNull() else null val command = com.droiddeck.launcher.session.NoSteamLaunch.command(game, added) ui.post { onHandled() - if (isDestroyed) return@post + if (!launchCoordinator.isCurrent(request) || isFinishing || isDestroyed) { + launchCoordinator.releaseHandling(request) + return@post + } if (command == null) { + launchCoordinator.releaseHandling(request) android.widget.Toast.makeText(this, R.string.game_link_failed, android.widget.Toast.LENGTH_LONG).show() return@post } @@ -1234,22 +1287,27 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet ui.postDelayed(poll, SESSION_SWITCH_POLL_MS) } - private fun handleGameLink(games: List<Library.SteamGame>, scanned: Boolean = true) { + private fun handleGameLink(games: List<Library.SteamGame>, scanned: Boolean = true, ticket: LaunchTicket? = null) { if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) return - val request = pendingGameLink ?: return + val link = launchCoordinator.pendingLink() ?: return + if (ticket != null && link.ticket !== ticket) return + val request = link.request ?: return + if (launchCoordinator.isHandling(link.ticket)) return + if (ticket == null && !link.ownedBy(intent)) { + // A refresh may only finish the link that belongs to the intent this activity shows. + launchCoordinator.consume(link.ticket) + return + } val game = request.find(games, byTitle = scanned) if (!scanned && game == null) return gameLinkTried = true ui.postDelayed({ if (!isDestroyed && lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) syncDualPanel() }, LINK_PANEL_MS) - val link = intent + val linkIntent = link.owner fun consume() { - if (intent !== link || pendingGameLink !== request) return - pendingGameLink = null - link.data = null - link.action = Intent.ACTION_MAIN - link.removeExtra(GameLaunchIntent.EXTRA_APP_ID) + if (!launchCoordinator.consume(link.ticket)) return + if (intent === linkIntent) clearGameLinkIntent(linkIntent) } if (game == null) { consume() @@ -1257,7 +1315,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet android.widget.Toast.makeText(this, if (request.program != null) R.string.game_link_program_unknown else R.string.game_link_missing, android.widget.Toast.LENGTH_LONG).show() - } else launchGame(game, returnHome = true, onSettled = ::consume) + } else { + if (!launchCoordinator.beginHandling(link.ticket)) return + launchGame(game, returnHome = true, onSettled = ::consume, ticket = link.ticket) + } } private fun chooseGameShortcut(game: Library.SteamGame) { @@ -1448,16 +1509,20 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet }, onStoreGame = { store, id -> val key = "${store.id}:$id" - if (key !in preparingGames) { + if (pkgStage != null) { + android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show() + } else if (key !in preparingGames) { preparingGames = preparingGames + key + val ticket = beginUiLaunch() val app = applicationContext Thread({ val g = runCatching { com.droiddeck.launcher.stores.StoreLaunch.installedGame(app, store, id) }.getOrNull() runOnUiThread { - if (g != null && !isFinishing && !isDestroyed) prepareAndLaunch(g, key) - else { + if (g != null && launchCoordinator.isCurrent(ticket) && !isFinishing && !isDestroyed) { + prepareAndLaunch(g, key, ticket) + } else { preparingGames = preparingGames - key - if (g == null && !isFinishing && !isDestroyed) android.widget.Toast.makeText(this, R.string.stores_launch_not_registered, android.widget.Toast.LENGTH_LONG).show() + if (g == null && launchCoordinator.isCurrent(ticket) && !isFinishing && !isDestroyed) android.widget.Toast.makeText(this, R.string.stores_launch_not_registered, android.widget.Toast.LENGTH_LONG).show() } } }, "store-play").start() @@ -1960,10 +2025,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) setIntent(intent) - gameLaunchRequest.incrementAndGet() + supersedeUncommittedLaunch() if (intent.action == SteamIntegration.ACTION_SETUP) { gameLinkReading = false - pendingGameLink = null syncDualPanel() readIntegrationIntent(intent) return @@ -1973,6 +2037,11 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet startSteamAtStartupIfEnabled() } + /** A replacement activity intent supersedes anything this activity has not dispatched yet. */ + private fun supersedeUncommittedLaunch() { + launchCoordinator.cancelAll() + } + private var soundtrackLaunch = false // A restarted launcher starts before the old one stops, so each clears the hooks only if they are still its own. @@ -2251,13 +2320,22 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet if (Build.VERSION.SDK_INT >= 33) state.getParcelable(key, Intent::class.java) else @Suppress("DEPRECATION") state.getParcelable(key) - private fun prepareAndLaunch(g: Library.SteamGame, key: String) { - val request = gameLaunchRequest.incrementAndGet() + private fun prepareAndLaunch(g: Library.SteamGame, key: String, ticket: LaunchTicket? = null) { + if (pkgStage != null) { + preparingGames = preparingGames - key + android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show() + return + } + val request = ticket ?: beginUiLaunch() + if (!launchCoordinator.isCurrent(request)) { + preparingGames = preparingGames - key + return + } val done = { preparingGames = preparingGames - key } com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g, onBlocked = done) { - if (request != gameLaunchRequest.get() || isFinishing || isDestroyed) { done(); return@beforeLaunch } + if (!launchCoordinator.isCurrent(request) || isFinishing || isDestroyed) { done(); return@beforeLaunch } com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) { - if (request == gameLaunchRequest.get() && !isFinishing && !isDestroyed) launchGame(g, onHandled = done) + if (launchCoordinator.isCurrent(request) && !isFinishing && !isDestroyed) launchGame(g, onHandled = done, ticket = request) else done() } } @@ -2267,7 +2345,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet // 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() + launchCoordinator.cancelAll() cancelCompatLaunch() updates.unregister() runCatching { unregisterReceiver(shortcutsInstallStatus) } @@ -2346,7 +2424,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet else com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId) } - private fun launchPending(): Boolean = gameLinkReading || (pendingGameLink != null && !gameLinkTried) + private fun launchPending(): Boolean = gameLinkReading || (launchCoordinator.hasPending() && !gameLinkTried) private fun launchAndroidApp(app: HomeApp.LaunchableApp, displayId: Int?) { val onOwnScreen = displayId == null || displayId == (display?.displayId ?: Display.DEFAULT_DISPLAY) diff --git a/app/src/main/java/com/droiddeck/launcher/session/LaunchCoordinator.kt b/app/src/main/java/com/droiddeck/launcher/session/LaunchCoordinator.kt new file mode 100644 index 0000000000..d989f4bc88 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/LaunchCoordinator.kt @@ -0,0 +1,82 @@ +package com.droiddeck.launcher.session + +/** + * Orders launch attempts and at most one pending game link. + * + * This is main-thread state: call it from the UI thread. A ticket is an identity, + * not a counter comparison, so a stale callback can only act on its own request. + */ +internal class LaunchTicket internal constructor(val serial: Long) + +internal class LaunchCoordinator<O : Any, R : Any> { + internal class Link<O : Any, R : Any> internal constructor( + val ticket: LaunchTicket, + val owner: O, + val request: R?, + ) { + /** Only the activity intent that delivered this link may finish it by a refresh. */ + fun ownedBy(owner: O?): Boolean = this.owner === owner + } + + private var next = 0L + private var current: LaunchTicket? = null + private var pending: Link<O, R>? = null + private var handling: LaunchTicket? = null + + /** A launch that is allowed to proceed; it supersedes any pending link. */ + fun beginLaunch(): LaunchTicket { + val ticket = LaunchTicket(++next) + current = ticket + pending = null + handling = null + return ticket + } + + /** A game-link intent; it supersedes any earlier launch or link. */ + fun beginLink(owner: O): LaunchTicket { + val ticket = LaunchTicket(++next) + current = ticket + pending = Link(ticket, owner, null) + handling = null + return ticket + } + + /** The asynchronous link read returned; false means a newer request won. */ + fun resolve(ticket: LaunchTicket, request: R?): Boolean { + val link = pending ?: return false + if (link.ticket !== ticket) return false + pending = Link(ticket, link.owner, request) + return true + } + + fun beginHandling(ticket: LaunchTicket): Boolean { + val link = pending ?: return false + if (link.ticket !== ticket || link.request == null) return false + handling = ticket + return true + } + + fun releaseHandling(ticket: LaunchTicket) { + if (handling === ticket) handling = null + } + + fun isHandling(ticket: LaunchTicket): Boolean = handling === ticket + fun isCurrent(ticket: LaunchTicket): Boolean = current === ticket + fun hasPending(): Boolean = pending != null + fun pendingLink(): Link<O, R>? = pending + + fun consume(ticket: LaunchTicket): Boolean { + val link = pending ?: return false + if (link.ticket !== ticket) return false + pending = null + handling = null + return true + } + + fun cancelAll() { + next++ + current = null + pending = null + handling = null + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/FrontEndIntentSupersedeTest.kt b/app/src/test/java/com/droiddeck/launcher/FrontEndIntentSupersedeTest.kt new file mode 100644 index 0000000000..0eba5d4667 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/FrontEndIntentSupersedeTest.kt @@ -0,0 +1,85 @@ +package com.droiddeck.launcher + +import android.content.Intent +import com.droiddeck.launcher.core.SteamIntegration +import com.droiddeck.launcher.frontend.GameRequest +import com.droiddeck.launcher.session.LaunchCoordinator +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.util.ReflectionHelpers + +/** + * A replacement activity intent invalidates everything this activity has not dispatched yet: a + * resolved but unhandled game link, and an accepted launch that is still waiting for its session. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class FrontEndIntentSupersedeTest { + private lateinit var activity: FrontEndActivity + private lateinit var coordinator: LaunchCoordinator<Intent, GameRequest> + + @Before + fun setUp() { + activity = Robolectric.buildActivity(FrontEndActivity::class.java).get() + coordinator = ReflectionHelpers.getField(activity, "launchCoordinator") + } + + @Test + fun aReplacementIntentDropsAResolvedPendingLink() { + val owner = Intent(activity, FrontEndActivity::class.java) + val ticket = coordinator.beginLink(owner) + assertTrue(coordinator.resolve(ticket, GameRequest(id = "app"))) + + supersede() + + assertFalse(coordinator.hasPending()) + assertNull(coordinator.pendingLink()) + } + + @Test + fun aReplacementIntentInvalidatesAnAcceptedLaunch() { + val ticket = coordinator.beginLaunch() + assertTrue(coordinator.isCurrent(ticket)) + + supersede() + + assertFalse(coordinator.isCurrent(ticket)) + assertNull(shadowOf(activity).nextStartedActivity) + } + + @Test + fun anActionSetupIntentSupersedesTheGameLinkItReplaced() { + val owner = Intent(activity, FrontEndActivity::class.java) + val ticket = coordinator.beginLink(owner) + assertTrue(coordinator.resolve(ticket, GameRequest(id = "app"))) + + deliver(Intent(activity, FrontEndActivity::class.java).setAction(SteamIntegration.ACTION_SETUP)) + + assertFalse(coordinator.hasPending()) + assertFalse(coordinator.isCurrent(ticket)) + assertNull(shadowOf(activity).nextStartedActivity) + } + + private fun supersede() { + ReflectionHelpers.callInstanceMethod<Void>(activity, "supersedeUncommittedLaunch") + } + + /** onNewIntent() is protected, which is exactly how the platform delivers a replacement intent. */ + private fun deliver(intent: Intent) { + val method = FrontEndActivity::class.java.getDeclaredMethod("onNewIntent", Intent::class.java) + method.isAccessible = true + try { + method.invoke(activity, intent) + } finally { + method.isAccessible = false + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/LaunchCoordinatorTest.kt b/app/src/test/java/com/droiddeck/launcher/session/LaunchCoordinatorTest.kt new file mode 100644 index 0000000000..0a2feeed36 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/LaunchCoordinatorTest.kt @@ -0,0 +1,121 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test + +class LaunchCoordinatorTest { + @Test + fun aNewLaunchSupersedesAnOlderLaunch() { + val coordinator = LaunchCoordinator<String, String>() + val first = coordinator.beginLaunch() + val second = coordinator.beginLaunch() + assertFalse(coordinator.isCurrent(first)) + assertTrue(coordinator.isCurrent(second)) + } + + @Test + fun anAllowedLaunchDropsThePendingLink() { + val coordinator = LaunchCoordinator<String, String>() + coordinator.beginLink("link") + coordinator.beginLaunch() + assertFalse(coordinator.hasPending()) + } + + @Test + fun aLinkReadResolvesAndIsConsumed() { + val coordinator = LaunchCoordinator<String, String>() + val ticket = coordinator.beginLink("link") + assertTrue(coordinator.resolve(ticket, "game")) + assertEquals("game", coordinator.pendingLink()?.request) + assertTrue(coordinator.consume(ticket)) + assertFalse(coordinator.hasPending()) + } + + @Test + fun aStaleLinkReadCannotReplaceTheNewLink() { + val coordinator = LaunchCoordinator<String, String>() + val first = coordinator.beginLink("first") + val second = coordinator.beginLink("second") + assertFalse(coordinator.resolve(first, "old")) + assertTrue(coordinator.resolve(second, "new")) + assertEquals("new", coordinator.pendingLink()?.request) + } + + @Test + fun handlingNeedsAResolvedLink() { + val coordinator = LaunchCoordinator<String, String>() + val ticket = coordinator.beginLink("link") + assertFalse(coordinator.beginHandling(ticket)) + coordinator.resolve(ticket, "game") + assertTrue(coordinator.beginHandling(ticket)) + assertTrue(coordinator.isHandling(ticket)) + } + + @Test + fun aStaleCompletionCannotConsumeTheNewLink() { + val coordinator = LaunchCoordinator<String, String>() + val first = coordinator.beginLink("first") + val second = coordinator.beginLink("second") + coordinator.resolve(second, "new") + assertFalse(coordinator.consume(first)) + assertTrue(coordinator.hasPending()) + } + + @Test + fun aUiLaunchDropsThePendingLinkBeforeItLaunches() { + val coordinator = LaunchCoordinator<String, String>() + coordinator.beginLink("link") + val launch = coordinator.beginLaunch() + assertNull(coordinator.pendingLink()) + assertTrue(coordinator.isCurrent(launch)) + } + + @Test + fun aSecondLinkReplacesTheFirst() { + val coordinator = LaunchCoordinator<String, String>() + val first = coordinator.beginLink("first") + val second = coordinator.beginLink("second") + assertFalse(coordinator.isCurrent(first)) + assertTrue(coordinator.isCurrent(second)) + assertEquals("second", coordinator.pendingLink()?.owner) + } + + @Test + fun aLinkKeepsItsOwnerForIntentCleanup() { + val coordinator = LaunchCoordinator<String, String>() + val ticket = coordinator.beginLink("intent-a") + coordinator.resolve(ticket, "game") + assertSame("intent-a", coordinator.pendingLink()?.owner) + } + + @Test + fun aLinkIsOwnedOnlyByItsIntent() { + val coordinator = LaunchCoordinator<String, String>() + val ticket = coordinator.beginLink("intent-a") + coordinator.resolve(ticket, "game") + val link = requireNotNull(coordinator.pendingLink()) + assertTrue(link.ownedBy("intent-a")) + assertFalse(link.ownedBy("intent-b")) + assertFalse(link.ownedBy(null)) + assertTrue(coordinator.consume(ticket)) + assertNull(coordinator.pendingLink()) + } + + @Test + fun cancelAllInvalidatesEveryOutstandingTicket() { + val coordinator = LaunchCoordinator<String, String>() + coordinator.beginLaunch() + val link = coordinator.beginLink("link") + assertTrue(coordinator.isCurrent(link)) + coordinator.cancelAll() + assertFalse(coordinator.isCurrent(link)) + assertFalse(coordinator.hasPending()) + assertNull(coordinator.pendingLink()) + assertFalse(coordinator.resolve(link, "late")) + assertFalse(coordinator.consume(link)) + } +} From da0a01a25b2bdd26eb5ade14abe9f57f6d1040d2 Mon Sep 17 00:00:00 2001 From: The412Banner <205237651+The412Banner@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:14:40 -0500 Subject: [PATCH 132/141] fix(input): pace stick-only pad reports to the guest at 250 Hz (#2902) * fix(input): pace stick-only pad reports to the guest at 250 Hz * fix(input): drop stale paced pad callbacks and time the interval from the flush --- .../droiddeck/launcher/input/AxisPacing.kt | 39 +++++++ .../launcher/input/FakeInputWriter.java | 80 ++++++++++++-- .../launcher/input/AxisPacingTest.kt | 102 ++++++++++++++++++ 3 files changed, 215 insertions(+), 6 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/input/AxisPacing.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/input/AxisPacingTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/input/AxisPacing.kt b/app/src/main/java/com/droiddeck/launcher/input/AxisPacing.kt new file mode 100644 index 0000000000..2170ab5030 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/AxisPacing.kt @@ -0,0 +1,39 @@ +package com.droiddeck.launcher.input + +internal class AxisPacing(private val intervalMs: Long) { + private var lastWriteAt = 0L + private var written = false + private var heldUntil = NOT_HELD + + fun dueAt(now: Long, axesOnly: Boolean): Long = + if (axesOnly && written && now - lastWriteAt < intervalMs) lastWriteAt + intervalMs else now + + fun wrote(at: Long) { + lastWriteAt = at + written = true + } + + fun hold(due: Long): Boolean { + if (heldUntil != NOT_HELD) return false + heldUntil = due + return true + } + + fun release(now: Long): Boolean { + if (heldUntil == NOT_HELD || now < heldUntil) return false + heldUntil = NOT_HELD + return true + } + + fun cancel(): Boolean { + if (heldUntil == NOT_HELD) return false + heldUntil = NOT_HELD + return true + } + + companion object { + private const val NOT_HELD = Long.MIN_VALUE + + @JvmStatic fun keepsMoving(before: Int, after: Int): Boolean = before == after || (before != 0 && after != 0) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/FakeInputWriter.java b/app/src/main/java/com/droiddeck/launcher/input/FakeInputWriter.java index 4675546d61..dc847e90ad 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/FakeInputWriter.java +++ b/app/src/main/java/com/droiddeck/launcher/input/FakeInputWriter.java @@ -1,5 +1,9 @@ package com.droiddeck.launcher.input; +import android.os.Handler; +import android.os.HandlerThread; +import android.os.Process; +import android.os.SystemClock; import android.util.Log; import java.io.File; @@ -128,6 +132,16 @@ public class FakeInputWriter { private static final Object RING_LOCK = new Object(); private static final RingSlot[] RING_SLOTS = new RingSlot[MAX_FAKE_INPUT_SLOTS]; + private static final long AXIS_REPORT_INTERVAL_MS = 4; + + private static final class Pacing { + static final Handler HANDLER; + static { + HandlerThread thread = new HandlerThread("pad-pacing", Process.THREAD_PRIORITY_DISPLAY); + thread.start(); + HANDLER = new Handler(thread.getLooper()); + } + } static { System.loadLibrary("sdnative"); @@ -156,6 +170,9 @@ public class FakeInputWriter { private boolean hasChanges = false; private boolean pendingFullResend = false; private boolean forceResend = false; + private final AxisPacing axisPacing = new AxisPacing(AXIS_REPORT_INTERVAL_MS); + private final PadState pacedPad = new PadState(); + private final Runnable pacedWrite = this::writePacedPad; public FakeInputWriter(String fakeInputPath, int slot) { this.slot = slot; @@ -711,10 +728,12 @@ public class FakeInputWriter { } public synchronized void close() { + cancelPacedWrite(); isOpen = false; } public synchronized void reset() { + cancelPacedWrite(); if (!isOpen && !open()) return; @@ -822,6 +841,53 @@ public class FakeInputWriter { } public synchronized void writePad(PadState state) { + long now = SystemClock.uptimeMillis(); + long due = axisPacing.dueAt(now, !pendingFullResend && onlyAxesMove(state)); + if (due > now) { + pacedPad.copyFrom(state); + if (axisPacing.hold(due)) + Pacing.HANDLER.postAtTime(pacedWrite, due); + return; + } + cancelPacedWrite(); + writePadNow(state); + } + + private synchronized void writePacedPad() { + if (axisPacing.release(SystemClock.uptimeMillis())) + writePadNow(pacedPad); + } + + private void cancelPacedWrite() { + if (axisPacing.cancel()) + Pacing.HANDLER.removeCallbacks(pacedWrite); + } + + private boolean onlyAxesMove(PadState state) { + for (int i = 0; i < 10; i++) { + if (prevButtonStates[i] != state.isDown(i)) + return false; + } + return prevButtonStates[SNAPSHOT_IDX_MODE] == state.isDown(PadState.GUIDE) + && prevQam == state.isDown(PadState.QAM) + && prevHatX == state.hatX() && prevHatY == state.hatY() + && AxisPacing.keepsMoving(prevThumbLX, stickValue(state.leftX)) + && AxisPacing.keepsMoving(prevThumbLY, stickValue(state.leftY)) + && AxisPacing.keepsMoving(prevThumbRX, stickValue(state.rightX)) + && AxisPacing.keepsMoving(prevThumbRY, stickValue(state.rightY)) + && AxisPacing.keepsMoving(prevTriggerL, triggerValue(state.leftTrigger)) + && AxisPacing.keepsMoving(prevTriggerR, triggerValue(state.rightTrigger)); + } + + private static int stickValue(float value) { + return (int) (value * 32767); + } + + private static int triggerValue(float value) { + return (int) (value * 255); + } + + private void writePadNow(PadState state) { if (!isOpen && !open()) return; @@ -845,10 +911,10 @@ public class FakeInputWriter { hasChanges = true; } - int lx = (int) (state.leftX * 32767); - int ly = (int) (state.leftY * 32767); - int rx = (int) (state.rightX * 32767); - int ry = (int) (state.rightY * 32767); + int lx = stickValue(state.leftX); + int ly = stickValue(state.leftY); + int rx = stickValue(state.rightX); + int ry = stickValue(state.rightY); if (forceResend || lx != prevThumbLX) { prevThumbLX = lx; @@ -867,8 +933,8 @@ public class FakeInputWriter { writeEvent(EV_ABS, ABS_RY, ry); } - int tl = (int) (state.leftTrigger * 255); - int tr = (int) (state.rightTrigger * 255); + int tl = triggerValue(state.leftTrigger); + int tr = triggerValue(state.rightTrigger); if (forceResend || tl != prevTriggerL) { prevTriggerL = tl; writeEvent(EV_ABS, ABS_BRAKE, tl); @@ -895,6 +961,8 @@ public class FakeInputWriter { if (!flushBuffer()) { Log.e(TAG, "Gamepad write error: fake input mmap ring unavailable"); pendingFullResend = true; + } else { + axisPacing.wrote(SystemClock.uptimeMillis()); } } forceResend = false; diff --git a/app/src/test/java/com/droiddeck/launcher/input/AxisPacingTest.kt b/app/src/test/java/com/droiddeck/launcher/input/AxisPacingTest.kt new file mode 100644 index 0000000000..d88a9e7964 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/AxisPacingTest.kt @@ -0,0 +1,102 @@ +package com.droiddeck.launcher.input + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class AxisPacingTest { + @Test fun theFirstReportIsWrittenAtOnce() { + assertEquals(100L, AxisPacing(4).dueAt(100, true)) + } + + @Test fun stickMotionInsideTheIntervalWaitsForItsEnd() { + val pacing = AxisPacing(4) + pacing.wrote(100) + assertEquals(104L, pacing.dueAt(101, true)) + assertEquals(104L, pacing.dueAt(103, true)) + assertEquals(104L, pacing.dueAt(104, true)) + assertEquals(110L, pacing.dueAt(110, true)) + } + + @Test fun buttonsAndRestTransitionsAreNeverHeldBack() { + val pacing = AxisPacing(4) + pacing.wrote(100) + assertEquals(101L, pacing.dueAt(101, false)) + } + + @Test fun onlyMotionThatStaysOffRestIsPaced() { + assertTrue(AxisPacing.keepsMoving(0, 0)) + assertTrue(AxisPacing.keepsMoving(1200, 1300)) + assertTrue(AxisPacing.keepsMoving(-40, 25)) + assertFalse(AxisPacing.keepsMoving(0, 900)) + assertFalse(AxisPacing.keepsMoving(900, 0)) + } + + @Test fun theIntervalRunsFromTheFlushNotFromTheRequest() { + val pacing = AxisPacing(4) + assertEquals(100L, pacing.dueAt(100, true)) + pacing.wrote(110) + assertEquals(114L, pacing.dueAt(111, true)) + } + + @Test fun aHeldReportIsReleasedOnlyAtItsDeadline() { + val pacing = AxisPacing(4) + assertTrue(pacing.hold(104)) + assertFalse(pacing.hold(104)) + assertFalse(pacing.release(103)) + assertTrue(pacing.release(104)) + assertFalse(pacing.release(105)) + } + + @Test fun aCallbackFromACancelledHoldCannotPublishTheNextHoldEarly() { + val pacing = AxisPacing(4) + assertTrue(pacing.hold(104)) + assertTrue(pacing.cancel()) + pacing.wrote(104) + assertTrue(pacing.hold(pacing.dueAt(105, true))) + assertFalse(pacing.release(105)) + assertTrue(pacing.release(108)) + } + + @Test fun cancellingWithNothingHeldRemovesNoCallback() { + val pacing = AxisPacing(4) + assertFalse(pacing.cancel()) + assertTrue(pacing.hold(104)) + assertTrue(pacing.release(104)) + assertFalse(pacing.cancel()) + } + + @Test fun aThousandHertzPadReachesTheGuestAtTheIntervalRate() { + val writes = feed(AxisPacing(4), sampleMs = 1, durationMs = 1000) + assertTrue("$writes writes", writes in 249..251) + } + + @Test fun aPadSlowerThanTheIntervalIsNeverDelayed() { + val pacing = AxisPacing(4) + for (now in 0L until 1000L step 5) { + assertEquals(now, pacing.dueAt(now, true)) + pacing.wrote(now) + } + } + + private fun feed(pacing: AxisPacing, sampleMs: Long, durationMs: Long): Int { + var writes = 0 + var pendingAt = -1L + for (now in 0L until durationMs step sampleMs) { + if (pendingAt in 0..now) { + pacing.wrote(pendingAt) + writes++ + pendingAt = -1 + } + val due = pacing.dueAt(now, true) + if (due <= now) { + pacing.wrote(now) + writes++ + } else if (pendingAt < 0) { + pendingAt = due + } + } + return writes + } +} From 7d942367fdbca67244c723802e2b360da93d57f2 Mon Sep 17 00:00:00 2001 From: DeathKhan <jfoh96@gmail.com> Date: Tue, 24 Nov 2026 16:14:45 -0600 Subject: [PATCH 133/141] fix(apps): Up and Down in the app grid follow fast presses and keep the row in view (#2906) * fix(apps): Up and Down in the app grid follow fast presses and keep the row in view The grid composes rows ahead of the view without placing them. Down focused a tile there directly, so focus moved into rows that never scrolled in, and the next Down searched from a tile with no place on screen and landed on the first tile, sending the list back to the top. Up used the grid's own search, which works from where tiles are drawn at that moment: with presses faster than the scroll it skipped the first row or drifted a column. And presses aimed from the last settled focus, so fast ones were lost. Up and Down now aim from the tile a move is already heading to, scroll that row fully into view, then focus it. At the first or last row a press leaves the grid as before, unless a move has not landed yet, in which case it waits. * fix(apps): a newer Up/Down move cancels the one still on its way, and a cancelled reveal frees the edge rows A move whose target was not yet attached kept retrying its focus after a newer press, so the older tile could take focus back. Each press now cancels the move before it. The pending target is also cleared when the reveal scroll is cancelled (for example by a touch scroll), so Down on the last row and Up on the first no longer stay blocked. * Apps: an Up/Down move holds its target tile by id and clears it only if it is still the latest move A list update that shifts the tiles no longer leaves the next press aiming from the old index, and a target that left the list drops its move. A cancelled move finishing late no longer clears the target of a newer move to the same tile. --- .../droiddeck/launcher/ui/AndroidAppsPage.kt | 69 ++++++++++++++++--- 1 file changed, 59 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt index 8904f2c2d4..4d4ac7adc0 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt @@ -117,6 +117,7 @@ import com.droiddeck.launcher.IconPack import android.content.pm.ShortcutInfo import android.graphics.Bitmap import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job import kotlinx.coroutines.flow.drop import kotlinx.coroutines.withContext import com.droiddeck.launcher.HomeWidgets @@ -388,21 +389,49 @@ internal fun AndroidAppsPage(s: FrontEndState, a: FrontEndActions, modifier: Mod } val front = LocalFrontFocus.current val steer = rememberCoroutineScope() - // Down goes to the tile straight below. The grid's own search only sees the tiles laid out so far, so above a short or + // The tile a move is heading to, by its id so that a list update cannot shift it, and the number of the latest move. + val aim = remember { arrayOfNulls<String>(1) } + val moves = remember { intArrayOf(0) } + val move = remember { arrayOfNulls<Job>(1) } + // Up and Down go to the tile straight above or below. The grid's own search works from where the tiles are drawn at that + // moment, so while a scroll is still catching up with fast presses it skips a row or drifts a column, and above a short or // unseen last row it lands on a tile further left; above a gap in a short last row the row's last tile takes it. + // Presses aim from the tile a move is already heading to, so none is lost before the focus lands. Box(Modifier.weight(1f).fillMaxWidth().onPreviewKeyEvent { event -> val k = event.nativeKeyEvent - if (k.keyCode != KeyEvent.KEYCODE_DPAD_DOWN || front == null) return@onPreviewKeyEvent false - val from = entries.indexOfFirst { tileId(it) == front.last } + val down = k.keyCode == KeyEvent.KEYCODE_DPAD_DOWN + if ((!down && k.keyCode != KeyEvent.KEYCODE_DPAD_UP) || front == null) return@onPreviewKeyEvent false + val aimed = aim[0]?.let { id -> entries.indexOfFirst { tileId(it) == id } } ?: -1 + if (aim[0] != null && aimed < 0) { + // The tile a move was heading to has left the list: that move is dropped and the press aims from the focus. + move[0]?.cancel() + aim[0] = null + } + val from = aimed.takeIf { it >= 0 } ?: entries.indexOfFirst { tileId(it) == front.last } val columns = (grid.layoutInfo.visibleItemsInfo.maxOfOrNull { it.column } ?: 0) + 1 - if (from < 0 || from / columns == entries.lastIndex / columns) return@onPreviewKeyEvent false + if (from < 0) return@onPreviewKeyEvent false + // At the first or last row the press leaves the grid, unless a move has not landed yet: then it waits for it. + val edge = if (down) from / columns == entries.lastIndex / columns else from < columns + if (edge) return@onPreviewKeyEvent aim[0] != null if (k.action == KeyEvent.ACTION_DOWN) { - val id = tileId(entries[minOf(from + columns, entries.lastIndex)]) - val shown = (front.attached[id] ?: 0) > 0 - if (!shown || runCatching { front.items.getValue(id).requestFocus() }.isFailure) steer.launch { - // The row below is not laid out yet: bring it in, then take it. - if (!shown) grid.scrollBy((grid.layoutInfo.visibleItemsInfo.firstOrNull { it.index == from + leadItems }?.size?.height ?: 0).toFloat()) - focusSoon { front.items.getValue(id) } + val to = if (down) minOf(from + columns, entries.lastIndex) else from - columns + val id = tileId(entries[to]) + aim[0] = id + val mine = ++moves[0] + // A newer move replaces the one still on its way, so an older target cannot take focus after it lands. + move[0]?.cancel() + move[0] = steer.launch { + try { + // Show the row before it takes focus. The grid composes rows ahead of the view without placing them, and a + // tile focused there neither scrolls in nor has a place for the next search to start from. + grid.reveal(to + leadItems) + if (moves[0] != mine) return@launch + focusSoon { front.items.getValue(id) } + } finally { + // Also when a touch scroll cancels the reveal, so the edge rows do not keep waiting for a move that ended. + // Only the latest move clears it: a cancelled one finishing late must not clear a newer move's target. + if (moves[0] == mine) aim[0] = null + } } } true @@ -558,6 +587,26 @@ private fun HeaderChoiceButton( } } +/** Scrolls the least that shows item [index] whole inside the padding, a row at a time while it is still outside the laid out items. */ +private suspend fun LazyGridState.reveal(index: Int) { + repeat(4) { + val info = layoutInfo + val shown = info.visibleItemsInfo + val item = shown.firstOrNull { it.index == index } + val by = when { + item != null -> { + val bottom = item.offset.y + item.size.height - (info.viewportEndOffset - info.afterContentPadding) + if (item.offset.y < 0) item.offset.y else maxOf(bottom, 0) + } + index > (shown.lastOrNull() ?: return).index -> shown.last().size.height + index < shown.first().index -> -shown.first().size.height + else -> return + } + if (by == 0) return + scrollBy(by.toFloat()) + } +} + @Composable private fun AlphabetScroller(entries: List<AppEntry>, grid: LazyGridState, leadItems: Int, modifier: Modifier) { val colors = MaterialTheme.colorScheme From 7630173b2431c8b5e1051ff836af3913cb712f9d Mon Sep 17 00:00:00 2001 From: MaxsTechReview <maxjividen@gmail.com> Date: Tue, 24 Nov 2026 17:19:24 -0500 Subject: [PATCH 134/141] fix(ddsession): keep path and status buffers off the wrapper fast path (#3071) dd_descriptor_unlink, dd_descriptor_rmdir and dd_descriptor_rename put one or two PATH_MAX buffers on their own frame (12 KB, 24 KB), and dd_status_without_tracer put its 16 KB status buffer there, even on the common path that only calls through to libc. Threads with small stacks, such as .NET or Wine threads near their guard page, could overflow in an otherwise plain unlink, rename or open. The wrappers now do only the cheap checks and call the real function; the buffers live in noinline helpers that run only when the descriptor store or the status rewrite is actually needed. A test compiles both sources with -fstack-usage and keeps each wrapper frame under 1 KB. Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> --- tools/linuxfs/preload/descriptor.c | 42 +++++++++++++++-------- tools/linuxfs/preload/tracer.c | 12 ++++--- tools/tests/test_preload_wrapper_stack.py | 39 +++++++++++++++++++++ 3 files changed, 74 insertions(+), 19 deletions(-) create mode 100644 tools/tests/test_preload_wrapper_stack.py diff --git a/tools/linuxfs/preload/descriptor.c b/tools/linuxfs/preload/descriptor.c index 686030988c..5f2c19ed22 100644 --- a/tools/linuxfs/preload/descriptor.c +++ b/tools/linuxfs/preload/descriptor.c @@ -31,7 +31,7 @@ static int store_root(char *out, size_t size) { return n > 0 && (size_t)n < size ? n : -1; } -static int store_exists(void) { +static __attribute__((noinline)) int store_exists(void) { char root[PATH_MAX]; if (store_seen) return 1; @@ -223,10 +223,18 @@ int fremovexattr(int fd, const char *name) { return 0; } +static int watched(void) { + int saved = errno, found; + + found = dd_is_wineserver() && store_exists(); + errno = saved; + return found; +} + static int tracked(const char *path, char *out, size_t size) { int saved = errno, found; - found = dd_is_wineserver() && store_exists() && resolved(path, out, size) == 0; + found = resolved(path, out, size) == 0; errno = saved; return found; } @@ -258,22 +266,30 @@ static void follow(const char *from, const char *to) { errno = saved; } -__attribute__((visibility("hidden"))) -int dd_descriptor_unlink(const char *path, int (*real)(const char *)) { +static __attribute__((noinline)) int removed(const char *path, int (*real)(const char *), int folder) { char target[PATH_MAX]; int known = tracked(path, target, sizeof(target)), result = real(path); - if (result == 0 && known) forget(target, 0); + if (result == 0 && known) forget(target, folder); + return result; +} + +static __attribute__((noinline)) int moved(const char *from, const char *to, int (*real)(const char *, const char *)) { + char old[PATH_MAX], new[PATH_MAX]; + int known = tracked(from, old, sizeof(old)), result = real(from, to); + + if (result == 0 && known && tracked(to, new, sizeof(new))) follow(old, new); return result; } __attribute__((visibility("hidden"))) -int dd_descriptor_rmdir(const char *path, int (*real)(const char *)) { - char target[PATH_MAX]; - int known = tracked(path, target, sizeof(target)), result = real(path); +int dd_descriptor_unlink(const char *path, int (*real)(const char *)) { + return watched() ? removed(path, real, 0) : real(path); +} - if (result == 0 && known) forget(target, 1); - return result; +__attribute__((visibility("hidden"))) +int dd_descriptor_rmdir(const char *path, int (*real)(const char *)) { + return watched() ? removed(path, real, 1) : real(path); } __attribute__((visibility("hidden"))) @@ -283,9 +299,5 @@ int dd_descriptor_remove(const char *path, int (*real)(const char *)) { __attribute__((visibility("hidden"))) int dd_descriptor_rename(const char *from, const char *to, int (*real)(const char *, const char *)) { - char old[PATH_MAX], new[PATH_MAX]; - int known = tracked(from, old, sizeof(old)), result = real(from, to); - - if (result == 0 && known && tracked(to, new, sizeof(new))) follow(old, new); - return result; + return watched() ? moved(from, to, real) : real(from, to); } diff --git a/tools/linuxfs/preload/tracer.c b/tools/linuxfs/preload/tracer.c index ec8dd003f9..4b12a1d6a7 100644 --- a/tools/linuxfs/preload/tracer.c +++ b/tools/linuxfs/preload/tracer.c @@ -72,15 +72,12 @@ static int read_only_copy(const char *data, size_t len, int flags) { return ro; } -__attribute__((visibility("hidden"))) int dd_status_without_tracer(const char *path, int flags, const void *caller) { +static __attribute__((noinline)) int status_copy(const char *path, int flags, long pid) { char text[STATUS_MAX]; size_t len = 0; int saved = errno; int out = -1; - long pid; - if ((flags & O_ACCMODE) != O_RDONLY || (pid = status_pid(path)) < 0 || is_web_helper(caller) || dd_from_ntdll(caller)) - return -1; // through the next open(): the native userland's hook gives the app's ids as root's there static int (*next_open)(const char *, int, ...) = NULL; if (!next_open) next_open = (int (*)(const char *, int, ...))dlsym(RTLD_NEXT, "open"); @@ -116,3 +113,10 @@ done: errno = saved; return out; } + +__attribute__((visibility("hidden"))) int dd_status_without_tracer(const char *path, int flags, const void *caller) { + long pid; + if ((flags & O_ACCMODE) != O_RDONLY || (pid = status_pid(path)) < 0 || is_web_helper(caller) || dd_from_ntdll(caller)) + return -1; + return status_copy(path, flags, pid); +} diff --git a/tools/tests/test_preload_wrapper_stack.py b/tools/tests/test_preload_wrapper_stack.py new file mode 100644 index 0000000000..409799921e --- /dev/null +++ b/tools/tests/test_preload_wrapper_stack.py @@ -0,0 +1,39 @@ +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload" +LIMIT = 1024 +WRAPPERS = { + "descriptor.c": ("dd_descriptor_unlink", "dd_descriptor_rmdir", "dd_descriptor_remove", "dd_descriptor_rename"), + "tracer.c": ("dd_status_without_tracer",), +} + + +def frames(source, build): + obj = build / (source + ".o") + subprocess.run(["cc", "-c", "-fPIC", "-O2", "-Wall", "-fstack-usage", "-o", str(obj), str(PRELOAD / source)], + check=True) + sizes = {} + for line in obj.with_suffix(".su").read_text().splitlines(): + place, size, _ = line.split("\t") + sizes[place.rsplit(":", 1)[-1]] = int(size) + return sizes + + +@unittest.skipUnless(shutil.which("cc"), "needs a C compiler") +class PreloadWrapperStackTest(unittest.TestCase): + def test_wrappers_keep_path_buffers_off_their_frames(self): + with tempfile.TemporaryDirectory() as build: + for source, names in WRAPPERS.items(): + sizes = frames(source, Path(build)) + for name in names: + with self.subTest(function=name): + self.assertIn(name, sizes) + self.assertLess(sizes[name], LIMIT) + + +if __name__ == "__main__": + unittest.main() From a573f8b14f4e7f9f4e847cbdc67349bfa18474a9 Mon Sep 17 00:00:00 2001 From: The412Banner <205237651+The412Banner@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:19:50 -0500 Subject: [PATCH 135/141] fix(session): a fixed portrait resolution applies when landscape is set to Follow screen (#3124) --- .../com/droiddeck/launcher/SessionActivity.kt | 20 +++++-------- .../launcher/session/SessionPrefs.kt | 4 +++ .../launcher/session/SessionState.kt | 3 ++ .../session/PortraitResolutionTest.kt | 30 +++++++++++++++++++ 4 files changed, 45 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 98cabab689..7deb31a83e 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -875,9 +875,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde cornerTap = SessionPrefs.drawerCornerTap(this) applyOutputPacing() if (!SessionState.running) { - SessionState.followScreen = followChoice() - SessionState.followScale = followScale() + SessionState.followScales = SessionPrefs.followScales(this, displayMode(), + com.droiddeck.launcher.session.SessionDisplay.panelSize(this)) } + applyFollowChoice() applyFollowOrientation(resources.configuration) goFullscreen() volumeControlStream = android.media.AudioManager.STREAM_MUSIC @@ -2995,16 +2996,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun followPortrait(): Boolean = glassesScreen == null && SessionPrefs.portrait(this) - private fun followScale(): Float { - val mode = displayMode() - val choice = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this), followPortrait()) - return com.droiddeck.launcher.session.SessionDisplay.followScale(choice) ?: 1f - } - - private fun followChoice(): Boolean { - val mode = displayMode() - return com.droiddeck.launcher.session.SessionDisplay.isFollow( - SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this), followPortrait())) + private fun applyFollowChoice() { + val scale = SessionState.followScales.let { if (followPortrait()) it.second else it.first } + SessionState.followScreen = scale != null + SessionState.followScale = scale ?: 1f } private fun applyFollowOrientation(config: android.content.res.Configuration) { @@ -3018,6 +3013,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde SessionService.setActivityDisplay(this, sessionActivityDisplayId) } cancelTouchGestures() + applyFollowChoice() applyFollowOrientation(newConfig) applyNotchInset() applyUnfoldedControls() diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 9645c411cc..7624037de7 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -1343,6 +1343,10 @@ object SessionPrefs { SessionDisplay.effectiveChoice( resolutionStored(context, mode, panel, false), resolutionStored(context, mode, panel, true), portrait) + fun followScales(context: Context, mode: String, panel: Pair<Int, Int>): Pair<Float?, Float?> = + SessionDisplay.followScale(resolutionChoice(context, mode, panel, false)) to + SessionDisplay.followScale(resolutionChoice(context, mode, panel, true)) + fun resolutionStored(context: Context, mode: String, panel: Pair<Int, Int>, portrait: Boolean): String { if (!portrait) return landscapeResolutionStored(context, mode, panel) val value = prefs(context).getString("displayResolution.portrait.$mode", null) ?: return SessionDisplay.LINK_LANDSCAPE diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt index e695f8b932..92255febec 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt @@ -148,6 +148,9 @@ object SessionState { @Volatile var outputSize: Pair<Int, Int> = Pair(1920, 1080) + @Volatile + var followScales: Pair<Float?, Float?> = null to null + @Volatile var followScreen = false var followScale = 1f diff --git a/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt b/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt index fb9199157b..f010e97a65 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt @@ -1,6 +1,7 @@ package com.droiddeck.launcher.session import android.content.Context +import android.content.pm.ActivityInfo import org.junit.Assert.* import org.junit.Before import org.junit.Test @@ -74,6 +75,35 @@ class PortraitResolutionTest { assertEquals("1440x2560", SessionPrefs.resolutionStored(app, "steam", panel, true)) } + @Test fun followScreenInLandscapeLeavesAFixedPortraitSizeFixed() { + SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.FOLLOW_SCREEN) + SessionPrefs.setResolutionChoice(app, "steam", "1024x768", portrait = true) + assertEquals(1f to null, SessionPrefs.followScales(app, "steam", panel)) + } + + @Test fun followScreenInPortraitLeavesAFixedLandscapeSizeFixed() { + SessionPrefs.setResolutionChoice(app, "steam", "1080p") + SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.followScaled(2f), portrait = true) + assertEquals(null to 2f, SessionPrefs.followScales(app, "steam", panel)) + } + + @Test fun followScalesKeepLinkedAndFixedChoices() { + SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.followScaled(1.5f)) + assertEquals(1.5f to 1.5f, SessionPrefs.followScales(app, "steam", panel)) + SessionPrefs.setResolutionChoice(app, "steam", "1024x768", portrait = true) + SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.LINK_PORTRAIT) + assertEquals(null to null, SessionPrefs.followScales(app, "steam", panel)) + app.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() + assertEquals(null to null, SessionPrefs.followScales(app, "steam", panel)) + } + + @Test fun anAutoOrientationIsNotChangedByFollowScreen() { + assertFalse(SessionPrefs.portrait(app)) + SessionPrefs.setOrientation(app, ActivityInfo.SCREEN_ORIENTATION_USER) + assertEquals(ActivityInfo.SCREEN_ORIENTATION_USER, SessionPrefs.windowOrientation(app, true, 700)) + assertEquals(ActivityInfo.SCREEN_ORIENTATION_USER, SessionPrefs.windowOrientation(app, false, 700)) + } + @Test fun modesKeepSeparateChoices() { SessionPrefs.setResolutionChoice(app, "steam", "1080p", portrait = true) assertEquals(SessionDisplay.LINK_LANDSCAPE, SessionPrefs.resolutionStored(app, "lxqt", panel, true)) From 33bdc75a995eabe9850e6b099d1bc40d8c1462cf Mon Sep 17 00:00:00 2001 From: The412Banner <205237651+The412Banner@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:19:54 -0500 Subject: [PATCH 136/141] fix(logs): Share logs includes RPCS3's own log from the session (#3130) --- .../session/EnhancedSessionLogShare.kt | 3 +- .../launcher/session/SessionArtifacts.kt | 56 +++++++++++++--- .../launcher/session/SessionService.kt | 1 + .../session/EnhancedSessionLogShareTest.kt | 17 +++++ .../launcher/session/SessionSteamLogsTest.kt | 64 +++++++++++++++++++ 5 files changed, 130 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt b/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt index b437f3ae4e..e1b38fe9ec 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt @@ -935,7 +935,7 @@ internal object EnhancedSessionLogShare { private fun category(entry: String): Category { val value = entry.lowercase(Locale.US) - if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") || + if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") || value.startsWith("rpcs3/") || value.contains("droiddeck-esync/") || GAME_LOG.matches(value.substringAfterLast('/')) || listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug").any(value::contains)) return Category.GAMES if (listOf("wayland", "gamescope", "xwayland", "vulkan", "gpu", "mesa", "egl", "glx", "drm", "compositor", "frame-trace").any(value::contains)) return Category.GRAPHICS @@ -950,6 +950,7 @@ internal object EnhancedSessionLogShare { "frame-trace.log", "process-trace.log", "game-lifecycle.log", "launches.log", "tools.tsv", "wanted.tsv", "prefixes.json", "battlenet.log", "spawned.log", "flatpak-install.log", "cef_log.txt", "cef_log.previous.txt", "console_log.txt", "webhelper_js.txt", "controller_support.txt", "systemperfmanager.txt", + "rpcs3", "RPCS3.log", ) private val KNOWN_COMPONENT_PATTERNS = listOf( Regex("[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2,}-[a-z0-9-]{1,24}"), diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt index 2b4744574f..03c9fddcae 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt @@ -75,6 +75,7 @@ object SessionArtifacts { LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context)) val record = Record(dir) copySteamLogs(context, dir, record, steamArch) + copyRpcs3Log(context, dir, record) VacDiagnostics.collect(context, dir) SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log")) SessionLogCapture.dumpMemoryPressure(File(dir, "memory-pressure.log")) @@ -321,6 +322,9 @@ object SessionArtifacts { runCatching { File(dir, CLIENT_FILE).readText().trim() }.getOrNull()?.takeIf { it == "arm64" || it == "x86_64" } private const val LOG_MARKS = "steam-log-marks.txt" + private const val RPCS3_LOG_MARKS = "rpcs3-log-marks.txt" + private const val RPCS3_LOGS = "root/.cache/rpcs3" + private const val RPCS3_LOG = "RPCS3.log" private const val MAX_STEAM_LOG = 8L * 1024 * 1024 private const val HEAD = 4096L @@ -328,11 +332,19 @@ object SessionArtifacts { private class CopyResult(val files: List<File>, val failed: Boolean, val deferred: Boolean) fun markSteamLogs(dir: File, logs: File) { - val lines = logs.listFiles { f -> f.isFile }?.mapNotNull { f -> + logs.listFiles { f -> f.isFile }?.let { markLogs(dir, LOG_MARKS, it.toList()) } + } + + fun markRpcs3Log(dir: File, root: File) { + markLogs(dir, RPCS3_LOG_MARKS, listOf(File(root, "$RPCS3_LOGS/$RPCS3_LOG")).filter { it.isFile }) + } + + private fun markLogs(dir: File, marks: String, files: List<File>) { + val lines = files.mapNotNull { f -> val size = f.length() head(f, size)?.let { "$size\t$it\t${f.name}" } - } ?: return - runCatching { File(dir, LOG_MARKS).writeText(lines.joinToString("") { "$it\n" }) } + } + runCatching { File(dir, marks).writeText(lines.joinToString("") { "$it\n" }) } } private fun head(f: File, length: Long): String? = runCatching { @@ -348,8 +360,8 @@ object SessionArtifacts { java.security.MessageDigest.getInstance("SHA-1").digest(buf).joinToString("") { "%02x".format(it) } }.getOrNull() - private fun steamLogMarks(dir: File): List<Mark>? = runCatching { - File(dir, LOG_MARKS).readLines().mapNotNull { line -> + private fun logMarks(dir: File, marks: String): List<Mark>? = runCatching { + File(dir, marks).readLines().mapNotNull { line -> val parts = line.split('\t', limit = 3) parts.getOrNull(0)?.toLongOrNull()?.let { size -> parts.getOrNull(1)?.let { Mark(size, it) } } } @@ -371,11 +383,32 @@ object SessionArtifacts { val logs = File(steamArch?.let { SessionPrefs.steamRoot(context, it) } ?: SessionPrefs.activeSteamRoot(context), "logs") if (!logs.isDirectory) return val out = File(dir, "steam").apply { mkdirs() } - val result = copySessionLogsResult(logs, dir, out) { stopWhenSessionStarts && SessionState.running } + addCopied(record, copySessionLogsResult(logs, dir, out) { stopWhenSessionStarts && SessionState.running }) + Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out") + } + + private fun copyRpcs3Log(context: Context, dir: File, record: Record, stopWhenSessionStarts: Boolean = false) { + val out = File(dir, "rpcs3") + val logs = File(LinuxRuntime.rootDir(context), RPCS3_LOGS) + val copied = copyRpcs3LogResult(logs, dir, out) { stopWhenSessionStarts && SessionState.running } ?: return + addCopied(record, copied) + if (copied.files.isNotEmpty()) Log.i(TAG, "collected RPCS3's log, scrubbed, into $out") + } + + internal fun copyRpcs3Log(logs: File, dir: File, out: File): List<File> = copyRpcs3LogResult(logs, dir, out) { false }?.files.orEmpty() + + private fun copyRpcs3LogResult(logs: File, dir: File, out: File, shouldStop: () -> Boolean): CopyResult? { + if (!File(dir, RPCS3_LOG_MARKS).isFile || !File(logs, RPCS3_LOG).isFile) return null + out.mkdirs() + val result = copySessionLogsResult(logs, dir, out, marksName = RPCS3_LOG_MARKS, accept = { it.name == RPCS3_LOG }, shouldStop = shouldStop) + if (result.files.isEmpty()) out.delete() + return result + } + + private fun addCopied(record: Record, result: CopyResult) { result.files.forEach { dst -> record.files[dst] = Scrubbed(dst.length(), dst.lastModified()) } record.failed = record.failed || result.failed record.deferred = record.deferred || result.deferred - Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out") } internal fun copySessionLogs( @@ -383,20 +416,22 @@ object SessionArtifacts { dir: File, out: File, openWriter: (File) -> Writer = { it.bufferedWriter() }, - ): List<File> = copySessionLogsResult(logs, dir, out, openWriter) { false }.files + ): List<File> = copySessionLogsResult(logs, dir, out, openWriter = openWriter) { false }.files private fun copySessionLogsResult( logs: File, dir: File, out: File, + marksName: String = LOG_MARKS, + accept: (File) -> Boolean = { true }, openWriter: (File) -> Writer = { it.bufferedWriter() }, shouldStop: () -> Boolean, ): CopyResult { - val marks = steamLogMarks(dir) + val marks = logMarks(dir, marksName) val copied = ArrayList<File>() var failed = false var deferred = false - val sources = logs.listFiles { f -> f.isFile } ?: return CopyResult(copied, true, false) + val sources = logs.listFiles { f -> f.isFile && accept(f) } ?: return CopyResult(copied, true, false) for (src in sources) { if (shouldStop()) { failed = true @@ -567,6 +602,7 @@ object SessionArtifacts { steamArch = recordedClient(dir), stopWhenSessionStarts = stopWhenSessionStarts, ) + copyRpcs3Log(context, dir, record, stopWhenSessionStarts) if (!record.deferred && (!stopWhenSessionStarts || !SessionState.running)) { if (!record.failed && VacDiagnostics.collect(context, dir)) { try { diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index 144fad8894..cf63e5cba3 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -1070,6 +1070,7 @@ class SessionService : Service() { guest.addAll(GpuStatsComponent.guestEnv(LinuxRuntime.rootDir(this))) guest.add("GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.top_pad=16777216") if (SessionState.mode == MODE_STEAM) guest.add("DD_MANGOAPP=" + (if (SessionPrefs.mangoapp(this)) "1" else "0")) + SessionPaths.current()?.let { SessionArtifacts.markRpcs3Log(it, LinuxRuntime.rootDir(this)) } SessionState.steamClientArch = if (steamHere) SessionPrefs.steamClientArch(this) else null SessionState.steamClientArch?.let { arch -> guest.add("DD_STEAM_CLIENT_ARCH=$arch") diff --git a/app/src/test/java/com/droiddeck/launcher/session/EnhancedSessionLogShareTest.kt b/app/src/test/java/com/droiddeck/launcher/session/EnhancedSessionLogShareTest.kt index 05ef3bdd33..ea6bd6238d 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/EnhancedSessionLogShareTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/EnhancedSessionLogShareTest.kt @@ -403,6 +403,23 @@ class EnhancedSessionLogShareTest { SessionLogShare.clear(app) } + @Test fun rpcs3LogIsSharedByNameWithTheGameLogs() { + val session = tmp.newFolder("2026-11-24-05-rpcs3") + session.resolve("session.log").writeText("session\n") + session.resolve("rpcs3").mkdirs() + session.resolve("rpcs3/RPCS3.log").writeText("PPU: compiling\n") + + val zips = EnhancedSessionLogShare.create(app, session) + fun entries(suffix: String) = ZipFile(zips.single { it.name.endsWith("-$suffix.zip") }).use { archive -> + archive.entries().toList().map { it.name } + } + + assertTrue(entries("games").contains("${session.name}/rpcs3/RPCS3.log")) + assertTrue(entries("session").contains("${session.name}/session.log")) + assertFalse(entries("games").contains("${session.name}/session.log")) + SessionLogShare.clear(app) + } + @Test fun unreadableDiscoverySubtreeKeepsOtherLogsAndMarksTheManifestPartial() { assumeFilePermissionsEnforced() assumeFalse(System.getProperty("os.name").startsWith("Windows")) diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionSteamLogsTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionSteamLogsTest.kt index 3b996ae3d2..89baf52834 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionSteamLogsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionSteamLogsTest.kt @@ -63,6 +63,70 @@ class SessionSteamLogsTest { assertFalse(File(out, "web.txt").readText().contains("abcdef123456")) } + private fun rpcs3Root(): Pair<File, File> { + val root = tmp.newFolder("rootfs") + return root to File(root, "root/.cache/rpcs3").apply { mkdirs() } + } + + @Test fun rpcs3LogRewrittenThisSessionIsCollectedAloneAndRedacted() { + val (root, logs) = rpcs3Root() + val session = tmp.newFolder("session") + val out = File(session, "rpcs3") + File(logs, "RPCS3.log").writeText("earlier run\n") + File(logs, "RPCS3.log.gz").writeBytes(byteArrayOf(0x1f, 0x8b.toByte(), 8, 0)) + File(logs, "RPCS3.buf").writeText("lock\n") + SessionArtifacts.markRpcs3Log(session, root) + + File(logs, "RPCS3.log").writeText("PPU: compiling\nGET /x?sessionid=abcdef123456 200\n") + File(logs, "RPCS3.log.gz").appendBytes(byteArrayOf(1, 2, 3)) + File(logs, "RPCS3.buf").appendText("more\n") + + val copied = SessionArtifacts.copyRpcs3Log(logs, session, out) + assertEquals(listOf("RPCS3.log"), names(copied)) + val text = File(out, "RPCS3.log").readText() + assertTrue(text.startsWith("PPU: compiling\n")) + assertFalse(text.contains("abcdef123456")) + assertEquals(listOf("RPCS3.log"), out.list()!!.sorted()) + } + + @Test fun rpcs3LogFirstWrittenThisSessionIsCollected() { + val (root, logs) = rpcs3Root() + val session = tmp.newFolder("session") + val out = File(session, "rpcs3") + SessionArtifacts.markRpcs3Log(session, root) + + File(logs, "RPCS3.log").writeText("first boot\n") + + assertEquals(listOf("RPCS3.log"), names(SessionArtifacts.copyRpcs3Log(logs, session, out))) + assertEquals("first boot\n", File(out, "RPCS3.log").readText()) + } + + @Test fun anRpcs3LogFromAnEarlierSessionIsNotCollected() { + val (root, logs) = rpcs3Root() + val session = tmp.newFolder("session") + val out = File(session, "rpcs3") + File(logs, "RPCS3.log").writeText("earlier run\n") + SessionArtifacts.markRpcs3Log(session, root) + + assertTrue(SessionArtifacts.copyRpcs3Log(logs, session, out).isEmpty()) + assertFalse(out.exists()) + } + + @Test fun anUnmarkedSessionCollectsNoRpcs3LogEvenWithSteamMarks() { + val (_, logs) = rpcs3Root() + val steam = tmp.newFolder("steam-logs") + val session = tmp.newFolder("session") + val out = File(session, "rpcs3") + File(steam, "console_log.txt").writeText("steam\n") + SessionArtifacts.markSteamLogs(session, steam) + File(logs, "RPCS3.log").writeText("another session's run\n") + + assertTrue(SessionArtifacts.copyRpcs3Log(logs, session, out).isEmpty()) + assertFalse(out.exists()) + File(steam, "console_log.txt").appendText("new\n") + assertEquals(listOf("console_log.txt"), names(SessionArtifacts.copySessionLogs(steam, session, tmp.newFolder("out")))) + } + @Test fun aCopyFailurePreservesThePreviousSnapshotAndRemovesPartialStaging() { val logs = tmp.newFolder("logs") val session = tmp.newFolder("session") From 67b82ad9b4d9e4473da4eccccb74826de9101cc4 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:20:00 -0500 Subject: [PATCH 137/141] fix(epic): hand Epic's terms step to the browser instead of looping the sign-in (#2421) * fix(epic): hand Epic's terms step to the browser instead of looping the sign-in When Epic's redirect page answers corrective_action_required (privacy policy or EULA acceptance, e.g. for a newly created account), open Epic's account sign-in in the Android browser, where the step is shown, and tell the user to finish it there and retry, instead of failing verification and reloading the sign-in. * test(epic): remove live response identifiers from fixture * test(epic): cover browser step selection * fix(epic): ignore a stale sign-in page read after the login was reloaded * fix(epic): hold the browser handoff until the sign-in screen is started --- .../launcher/stores/StoreLoginActivity.kt | 28 +++++++++- .../launcher/stores/epic/EpicLogin.kt | 18 ++++++- .../droiddeck/launcher/ui/FrontEndSetup.kt | 4 +- app/src/main/res/values-ar/strings.xml | 1 + app/src/main/res/values-b+es+419/strings.xml | 1 + app/src/main/res/values-bg/strings.xml | 1 + app/src/main/res/values-cs/strings.xml | 1 + app/src/main/res/values-da/strings.xml | 1 + app/src/main/res/values-de/strings.xml | 1 + app/src/main/res/values-el/strings.xml | 1 + app/src/main/res/values-es/strings.xml | 1 + app/src/main/res/values-fi/strings.xml | 1 + app/src/main/res/values-fr/strings.xml | 1 + app/src/main/res/values-hi/strings.xml | 1 + app/src/main/res/values-hu/strings.xml | 1 + app/src/main/res/values-in/strings.xml | 1 + app/src/main/res/values-it/strings.xml | 1 + app/src/main/res/values-ja/strings.xml | 1 + app/src/main/res/values-ko/strings.xml | 1 + app/src/main/res/values-ms/strings.xml | 1 + app/src/main/res/values-nb/strings.xml | 1 + app/src/main/res/values-nl/strings.xml | 1 + app/src/main/res/values-pl/strings.xml | 1 + app/src/main/res/values-pt-rPT/strings.xml | 1 + app/src/main/res/values-pt/strings.xml | 1 + app/src/main/res/values-ro/strings.xml | 1 + app/src/main/res/values-ru/strings.xml | 1 + app/src/main/res/values-sv/strings.xml | 1 + app/src/main/res/values-th/strings.xml | 1 + app/src/main/res/values-tr/strings.xml | 1 + app/src/main/res/values-uk/strings.xml | 1 + app/src/main/res/values-vi/strings.xml | 1 + app/src/main/res/values-zh-rCN/strings.xml | 1 + app/src/main/res/values-zh-rHK/strings.xml | 1 + app/src/main/res/values-zh-rTW/strings.xml | 1 + app/src/main/res/values/strings.xml | 1 + .../launcher/stores/epic/EpicLoginTest.kt | 51 +++++++++++++++++++ 37 files changed, 129 insertions(+), 5 deletions(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/stores/epic/EpicLoginTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt index 54571ab172..0efcedbe88 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt @@ -65,6 +65,7 @@ class StoreLoginActivity : ComponentActivity() { val readsPage: Boolean get() = false val pageScript: String get() = "(function(){ try { return document.body.innerText; } catch(e){ return ''; } })()" fun pageReady(result: String): Boolean = true + fun browserStep(page: String): String? = null fun forgetSignIn(done: () -> Unit) = done() fun pageFinished(view: WebView, url: String) {} } @@ -72,6 +73,7 @@ class StoreLoginActivity : ComponentActivity() { private var store: Store? = null private var clientUrl: String? = null private var flow: Flow? = null + private var pendingBrowserStep: String? = null private var webViewRef: WebView? = null private var popupWebView: WebView? = null private lateinit var contentHost: FrameLayout @@ -211,6 +213,7 @@ class StoreLoginActivity : ComponentActivity() { private fun reloadLogin() { dismissPopup(); clearError() + pendingBrowserStep = null captured.set(false) val fresh = generateState() oauthState = fresh @@ -332,9 +335,13 @@ class StoreLoginActivity : ComponentActivity() { private fun readPage(view: WebView, f: Flow, left: Int) { view.evaluateJavascript(f.pageScript) { json -> + if (flow !== f) return@evaluateJavascript val result = json ?: "" if (!f.pageReady(result) && left > 0) view.postDelayed({ readPage(view, f, left - 1) }, PAGE_RETRY_MS) - else Thread({ settle(f.finish(this, view, result)) }, "store-login").start() + else { + val step = f.browserStep(result) + if (step == null || !continueInBrowser(step)) Thread({ settle(f.finish(this, view, result)) }, "store-login").start() + } } } @@ -350,6 +357,21 @@ class StoreLoginActivity : ComponentActivity() { if (f.readsPage) readPage(view, f, PAGE_TRIES) else Thread({ settle(f.finish(this, view, url)) }, "store-login").start() } + private fun continueInBrowser(url: String): Boolean { + if (isFinishing || isDestroyed) return false + if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.STARTED)) { + pendingBrowserStep = url + return true + } + val opened = runCatching { startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, Uri.parse(url))) } + .onFailure { Log.w(TAG, "no browser took the sign-in step: ${it.javaClass.simpleName}") } + .isSuccess + if (!opened) return false + titleText.text = getString(R.string.stores_login_title, store?.label ?: "") + showError(getString(R.string.stores_login_continue_in_browser, store?.label ?: "")) + return true + } + private fun settle(problem: String?) { runOnUiThread { if (problem == null) { StoresState.refresh(this); finish(); return@runOnUiThread } @@ -367,6 +389,10 @@ class StoreLoginActivity : ComponentActivity() { override fun onStart() { super.onStart() + pendingBrowserStep?.let { step -> + pendingBrowserStep = null + if (!continueInBrowser(step)) reloadLogin() + } if (clientUrl != null && !isFinishing) com.droiddeck.launcher.session.SessionService.holdForSignIn(this, true) } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicLogin.kt b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicLogin.kt index ff804a85e3..f2ee5a26a6 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicLogin.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicLogin.kt @@ -5,8 +5,9 @@ import android.webkit.WebView import com.droiddeck.launcher.R import com.droiddeck.launcher.stores.StoreLoginActivity import org.json.JSONObject +import org.json.JSONTokener -internal class EpicLogin private constructor( +internal class EpicLogin internal constructor( override val startUrl: String, override val userAgent: String, private val redirectPrefix: String, @@ -15,6 +16,12 @@ internal class EpicLogin private constructor( override fun isRedirect(url: String): Boolean = url.startsWith(redirectPrefix) + override fun browserStep(page: String): String? { + val action = correctiveAction(page) ?: return null + Log.i(TAG, "the redirect page asks for a corrective action: $action") + return ACCOUNT_SIGN_IN_URL + } + override fun finish(activity: StoreLoginActivity, view: WebView, url: String): String? { val code = EpicNative.call("auth.codeFromPage", JSONObject().put("text", url))?.optString("code", "").orEmpty() if (code.isEmpty()) { @@ -38,6 +45,15 @@ internal class EpicLogin private constructor( companion object { private const val TAG = "EpicLogin" + private const val CORRECTIVE_ACTION_REQUIRED = "errors.com.epicgames.oauth.corrective_action_required" + internal const val ACCOUNT_SIGN_IN_URL = "https://www.epicgames.com/id/login?redirectUrl=https%3A%2F%2Fwww.epicgames.com%2Faccount%2Fpersonal" + + internal fun correctiveAction(page: String): String? { + val text = runCatching { JSONTokener(page).nextValue() }.getOrNull() as? String ?: page + val body = runCatching { JSONObject(text.trim()) }.getOrNull() ?: return null + if (body.optString("errorCode") != CORRECTIVE_ACTION_REQUIRED) return null + return body.optJSONObject("metadata")?.optString("correctiveAction").orEmpty().ifEmpty { "unknown" } + } fun create(): StoreLoginActivity.Flow? { val config = EpicNative.call("auth.config") ?: return null diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt index 0062c67b24..543c5f6857 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -1098,8 +1098,6 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron internal const val GAME_SETTINGS_MENU = "game-settings" -private const val EPIC_RESOLVE_URL = "https://www.epicgames.com/id/login?redirectUrl=https%3A%2F%2Fwww.epicgames.com%2Faccount%2Fpersonal" - @Composable private fun StoreLaunchCard(host: MenuHost, folder: java.io.File, store: com.droiddeck.launcher.stores.Store) { val appContext = androidx.compose.ui.platform.LocalContext.current.applicationContext @@ -1149,7 +1147,7 @@ private fun StoreLaunchCard(host: MenuHost, folder: java.io.File, store: com.dro MenuItem(stringResource(R.string.epic_resolve), checked = false) { host.open = null runCatching { - appContext.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(EPIC_RESOLVE_URL)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)) + appContext.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(com.droiddeck.launcher.stores.epic.EpicLogin.ACCOUNT_SIGN_IN_URL)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)) } } } diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 973c8bb6c0..59188caba6 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -2818,6 +2818,7 @@ <string name="stores_login_error_ssl">الاتصال بصفحة تسجيل الدخول غير آمن.</string> <string name="stores_login_error_verification">تعذّر التحقّق من تسجيل الدخول. حاوِل مرة أخرى.</string> <string name="stores_login_error_generic">فشل تسجيل الدخول. حاوِل مرة أخرى.</string> + <string name="stores_login_continue_in_browser">يحتاج %1$s إلى خطوة أخرى. أكملها في المتصفح الذي فُتح، ثم حاول مرة أخرى.</string> <string name="common_close">إغلاق</string> <string name="common_back">رجوع</string> <string name="common_edit">تعديل</string> diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 540eec6450..c1314a8bd6 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -2784,6 +2784,7 @@ <string name="stores_login_error_ssl">La conexión con la página de inicio de sesión no es segura.</string> <string name="stores_login_error_verification">No se pudo verificar el inicio de sesión. Inténtalo de nuevo.</string> <string name="stores_login_error_generic">No se pudo iniciar sesión. Inténtalo de nuevo.</string> + <string name="stores_login_continue_in_browser">%1$s necesita un paso más. Complétalo en el navegador que se abrió y vuelve a intentarlo.</string> <string name="common_close">Cerrar</string> <string name="common_back">Atrás</string> <string name="common_edit">Editar</string> diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index 340f2d8467..2ab13542e9 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -2714,6 +2714,7 @@ <string name="stores_login_error_ssl">Връзката със страницата за вход не е защитена.</string> <string name="stores_login_error_verification">Входът не можа да бъде потвърден. Опитай отново.</string> <string name="stores_login_error_generic">Входът се провали. Опитай отново.</string> + <string name="stores_login_continue_in_browser">%1$s изисква още една стъпка. Завърши я в браузъра, който се отвори, и опитай отново.</string> <string name="common_close">Затвори</string> <string name="common_back">Назад</string> <string name="common_edit">Редактирай</string> diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 9cae733f68..04231de374 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -2766,6 +2766,7 @@ <string name="stores_login_error_ssl">Spojení s přihlašovací stránkou není zabezpečené.</string> <string name="stores_login_error_verification">Přihlášení se nepodařilo ověřit. Zkuste to znovu.</string> <string name="stores_login_error_generic">Přihlášení se nezdařilo. Zkuste to znovu.</string> + <string name="stores_login_continue_in_browser">%1$s vyžaduje ještě jeden krok. Dokončete ho v prohlížeči, který se otevřel, a zkuste to znovu.</string> <string name="common_close">Zavřít</string> <string name="common_back">Zpět</string> <string name="common_edit">Upravit</string> diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 59329a1f9e..609965ad7f 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -2714,6 +2714,7 @@ <string name="stores_login_error_ssl">Forbindelsen til loginsiden er ikke sikker.</string> <string name="stores_login_error_verification">Login kunne ikke bekræftes. Forsøg igen.</string> <string name="stores_login_error_generic">Login mislykkedes. Forsøg igen.</string> + <string name="stores_login_continue_in_browser">%1$s kræver et trin mere. Fuldfør det i browseren, der blev åbnet, og prøv igen.</string> <string name="common_close">Luk</string> <string name="common_back">Tilbage</string> <string name="common_edit">Rediger</string> diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 3559dcecec..f803d555bd 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -2703,6 +2703,7 @@ <string name="stores_login_error_ssl">Die Verbindung zur Anmeldeseite ist nicht sicher.</string> <string name="stores_login_error_verification">Die Anmeldung konnte nicht bestätigt werden. Versuche es erneut.</string> <string name="stores_login_error_generic">Anmeldung fehlgeschlagen. Versuche es erneut.</string> + <string name="stores_login_continue_in_browser">%1$s braucht noch einen Schritt. Schließe ihn im geöffneten Browser ab und versuche es dann erneut.</string> <string name="common_close">Schließen</string> <string name="common_back">Zurück</string> <string name="common_edit">Bearbeiten</string> diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 50903050c4..08d647886a 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -2714,6 +2714,7 @@ <string name="stores_login_error_ssl">Η σύνδεση με τη σελίδα σύνδεσης δεν είναι ασφαλής.</string> <string name="stores_login_error_verification">Δεν ήταν δυνατή η επαλήθευση της σύνδεσης. Δοκιμάστε ξανά.</string> <string name="stores_login_error_generic">Η σύνδεση απέτυχε. Δοκιμάστε ξανά.</string> + <string name="stores_login_continue_in_browser">Το %1$s χρειάζεται ένα ακόμη βήμα. Ολοκληρώστε το στο πρόγραμμα περιήγησης που άνοιξε και δοκιμάστε ξανά.</string> <string name="common_close">Κλείσιμο</string> <string name="common_back">Πίσω</string> <string name="common_edit">Επεξεργασία</string> diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 3138760ebe..d1859b029a 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -2737,6 +2737,7 @@ <string name="stores_login_error_ssl">La conexión con la página de inicio de sesión no es segura.</string> <string name="stores_login_error_verification">No se pudo verificar el inicio de sesión. Inténtalo de nuevo.</string> <string name="stores_login_error_generic">No se pudo iniciar sesión. Inténtalo de nuevo.</string> + <string name="stores_login_continue_in_browser">%1$s necesita un paso más. Complétalo en el navegador que se abrió y vuelve a intentarlo.</string> <string name="common_close">Cerrar</string> <string name="common_back">Atrás</string> <string name="common_edit">Editar</string> diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index f551a03c7e..4cf72f1674 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -2714,6 +2714,7 @@ <string name="stores_login_error_ssl">Yhteys kirjautumissivulle ei ole suojattu.</string> <string name="stores_login_error_verification">Kirjautumista ei voitu vahvistaa. Yritä uudelleen.</string> <string name="stores_login_error_generic">Kirjautuminen epäonnistui. Yritä uudelleen.</string> + <string name="stores_login_continue_in_browser">%1$s vaatii vielä yhden vaiheen. Viimeistele se avautuneessa selaimessa ja yritä sitten uudelleen.</string> <string name="common_close">Sulje</string> <string name="common_back">Takaisin</string> <string name="common_edit">Muokkaa</string> diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 8a93091282..c735507d40 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -2736,6 +2736,7 @@ <string name="stores_login_error_ssl">La liaison avec la page de connexion n\'est pas sécurisée.</string> <string name="stores_login_error_verification">Impossible de vérifier la connexion. Réessayez.</string> <string name="stores_login_error_generic">Échec de la connexion. Réessayez.</string> + <string name="stores_login_continue_in_browser">%1$s demande une étape de plus. Terminez-la dans le navigateur qui s\'est ouvert, puis réessayez.</string> <string name="common_close">Fermer</string> <string name="common_back">Retour</string> <string name="common_edit">Modifier</string> diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 3b76665f48..c3b71210f6 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -2714,6 +2714,7 @@ <string name="stores_login_error_ssl">साइन-इन पेज से कनेक्शन सुरक्षित नहीं है।</string> <string name="stores_login_error_verification">साइन-इन सत्यापित नहीं हो सका। फिर कोशिश करें।</string> <string name="stores_login_error_generic">साइन-इन विफल रहा। फिर कोशिश करें।</string> + <string name="stores_login_continue_in_browser">%1$s को एक और चरण चाहिए। खुले हुए ब्राउज़र में इसे पूरा करें, फिर दोबारा कोशिश करें।</string> <string name="common_close">बंद करें</string> <string name="common_back">बैक</string> <string name="common_edit">संपादित करें</string> diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index ea47bab819..8c51e3cf8a 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -2714,6 +2714,7 @@ <string name="stores_login_error_ssl">A kapcsolat a bejelentkezési oldalhoz nem biztonságos.</string> <string name="stores_login_error_verification">A bejelentkezést nem sikerült ellenőrizni. Próbálja újra.</string> <string name="stores_login_error_generic">A bejelentkezés sikertelen. Próbálja újra.</string> + <string name="stores_login_continue_in_browser">A(z) %1$s még egy lépést kér. Fejezze be a megnyílt böngészőben, majd próbálja újra.</string> <string name="common_close">Bezárás</string> <string name="common_back">Vissza</string> <string name="common_edit">Szerkesztés</string> diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 110833e35e..d067290684 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -2689,6 +2689,7 @@ <string name="stores_login_error_ssl">Koneksi ke halaman masuk tidak aman.</string> <string name="stores_login_error_verification">Proses masuk tidak dapat diverifikasi. Coba lagi.</string> <string name="stores_login_error_generic">Proses masuk gagal. Coba lagi.</string> + <string name="stores_login_continue_in_browser">%1$s memerlukan satu langkah lagi. Selesaikan di browser yang terbuka, lalu coba lagi.</string> <string name="common_close">Tutup</string> <string name="common_back">Kembali</string> <string name="common_edit">Edit</string> diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 8ec37be21e..2dfa1da981 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -2728,6 +2728,7 @@ <string name="stores_login_error_ssl">La connessione alla pagina di accesso non è sicura.</string> <string name="stores_login_error_verification">Impossibile verificare l\'accesso. Riprova.</string> <string name="stores_login_error_generic">Accesso non riuscito. Riprova.</string> + <string name="stores_login_continue_in_browser">%1$s richiede un altro passaggio. Completalo nel browser che si è aperto, poi riprova.</string> <string name="common_close">Chiudi</string> <string name="common_back">Indietro</string> <string name="common_edit">Modifica</string> diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index e012fed66b..b51efa75a8 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -2689,6 +2689,7 @@ <string name="stores_login_error_ssl">ログインページへの接続は安全ではありません。</string> <string name="stores_login_error_verification">ログインを確認できませんでした。もう一度お試しください。</string> <string name="stores_login_error_generic">ログインに失敗しました。もう一度お試しください。</string> + <string name="stores_login_continue_in_browser">%1$s で追加の手順が必要です。開いたブラウザーで完了してから、もう一度お試しください。</string> <string name="common_close">閉じる</string> <string name="common_back">戻る</string> <string name="common_edit">編集</string> diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 337c0d437e..8b3f92a2a9 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -2689,6 +2689,7 @@ <string name="stores_login_error_ssl">로그인 페이지 연결이 안전하지 않습니다.</string> <string name="stores_login_error_verification">로그인을 확인할 수 없습니다. 다시 시도하세요.</string> <string name="stores_login_error_generic">로그인에 실패했습니다. 다시 시도하세요.</string> + <string name="stores_login_continue_in_browser">%1$s에서 한 단계가 더 필요합니다. 열린 브라우저에서 완료한 다음 다시 시도하세요.</string> <string name="common_close">닫기</string> <string name="common_back">뒤로</string> <string name="common_edit">편집</string> diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index ef8393e099..95364b21d1 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -2689,6 +2689,7 @@ <string name="stores_login_error_ssl">Sambungan ke halaman log masuk tidak selamat.</string> <string name="stores_login_error_verification">Log masuk tidak dapat disahkan. Cuba lagi.</string> <string name="stores_login_error_generic">Log masuk gagal. Cuba lagi.</string> + <string name="stores_login_continue_in_browser">%1$s memerlukan satu langkah lagi. Selesaikannya dalam pelayar yang dibuka, kemudian cuba lagi.</string> <string name="common_close">Tutup</string> <string name="common_back">Kembali</string> <string name="common_edit">Sunting</string> diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index 81e2cfd0ba..2fd355eec3 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -2714,6 +2714,7 @@ <string name="stores_login_error_ssl">Tilkoblingen til innloggingssiden er ikke sikker.</string> <string name="stores_login_error_verification">Innloggingen kunne ikke verifiseres. Prøv igjen.</string> <string name="stores_login_error_generic">Innlogging mislyktes. Prøv igjen.</string> + <string name="stores_login_continue_in_browser">%1$s trenger ett trinn til. Fullfør det i nettleseren som ble åpnet, og prøv igjen.</string> <string name="common_close">Lukk</string> <string name="common_back">Tilbake</string> <string name="common_edit">Rediger</string> diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 2a8fb73b58..b788d41499 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -2714,6 +2714,7 @@ <string name="stores_login_error_ssl">De verbinding met de aanmeldpagina is niet beveiligd.</string> <string name="stores_login_error_verification">De aanmelding kon niet worden geverifieerd. Probeer het opnieuw.</string> <string name="stores_login_error_generic">Aanmelden mislukt. Probeer het opnieuw.</string> + <string name="stores_login_continue_in_browser">%1$s vraagt nog één stap. Rond die af in de browser die is geopend en probeer het opnieuw.</string> <string name="common_close">Sluiten</string> <string name="common_back">Terug</string> <string name="common_edit">Bewerken</string> diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 4fcc9f537b..59fadab554 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -2766,6 +2766,7 @@ <string name="stores_login_error_ssl">Połączenie ze stroną logowania nie jest bezpieczne.</string> <string name="stores_login_error_verification">Nie udało się zweryfikować logowania. Spróbuj ponownie.</string> <string name="stores_login_error_generic">Logowanie nie powiodło się. Spróbuj ponownie.</string> + <string name="stores_login_continue_in_browser">%1$s wymaga jeszcze jednego kroku. Dokończ go w otwartej przeglądarce, a potem spróbuj ponownie.</string> <string name="common_close">Zamknij</string> <string name="common_back">Wstecz</string> <string name="common_edit">Edytuj</string> diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 12267238f7..5e1f62f5d1 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -2742,6 +2742,7 @@ <string name="stores_login_error_ssl">A ligação à página de início de sessão não é segura.</string> <string name="stores_login_error_verification">Não foi possível verificar o início de sessão. Tente novamente.</string> <string name="stores_login_error_generic">Falha no início de sessão. Tente novamente.</string> + <string name="stores_login_continue_in_browser">%1$s precisa de mais um passo. Conclua-o no navegador que foi aberto e tente novamente.</string> <string name="common_close">Fechar</string> <string name="common_back">Voltar</string> <string name="common_edit">Editar</string> diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index e51abbbead..6372234699 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -2750,6 +2750,7 @@ <string name="stores_login_error_ssl">A conexão com a página de login não é segura.</string> <string name="stores_login_error_verification">Não foi possível verificar o login. Tente de novo.</string> <string name="stores_login_error_generic">Falha no login. Tente de novo.</string> + <string name="stores_login_continue_in_browser">%1$s precisa de mais uma etapa. Conclua no navegador que foi aberto e tente novamente.</string> <string name="common_close">Fechar</string> <string name="common_back">Voltar</string> <string name="common_edit">Editar</string> diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index 89e8d30b85..f25f8abbb2 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -2740,6 +2740,7 @@ <string name="stores_login_error_ssl">Conexiunea la pagina de autentificare nu este sigură.</string> <string name="stores_login_error_verification">Autentificarea nu a putut fi verificată. Încearcă din nou.</string> <string name="stores_login_error_generic">Autentificarea a eșuat. Încearcă din nou.</string> + <string name="stores_login_continue_in_browser">%1$s mai cere un pas. Finalizează-l în browserul care s-a deschis, apoi încearcă din nou.</string> <string name="common_close">Închide</string> <string name="common_back">Înapoi</string> <string name="common_edit">Editează</string> diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 09bb9155f6..956c3d5136 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -2764,6 +2764,7 @@ <string name="stores_login_error_ssl">Подключение к странице входа не защищено.</string> <string name="stores_login_error_verification">Не удалось подтвердить вход. Повторите попытку.</string> <string name="stores_login_error_generic">Ошибка входа. Повторите попытку.</string> + <string name="stores_login_continue_in_browser">%1$s требует ещё один шаг. Завершите его в открывшемся браузере и попробуйте снова.</string> <string name="common_close">Закрыть</string> <string name="common_back">Назад</string> <string name="common_edit">Изменить</string> diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 69960f0a1b..9361bca121 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -2714,6 +2714,7 @@ <string name="stores_login_error_ssl">Anslutningen till inloggningssidan är inte säker.</string> <string name="stores_login_error_verification">Inloggningen kunde inte verifieras. Försök igen.</string> <string name="stores_login_error_generic">Inloggningen misslyckades. Försök igen.</string> + <string name="stores_login_continue_in_browser">%1$s behöver ett steg till. Slutför det i webbläsaren som öppnades och försök sedan igen.</string> <string name="common_close">Stäng</string> <string name="common_back">Tillbaka</string> <string name="common_edit">Redigera</string> diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 924715aad9..a7f07bbe93 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -2689,6 +2689,7 @@ <string name="stores_login_error_ssl">การเชื่อมต่อไปยังหน้าลงชื่อเข้าใช้ไม่ปลอดภัย</string> <string name="stores_login_error_verification">ไม่สามารถยืนยันการลงชื่อเข้าใช้ได้ ลองใหม่</string> <string name="stores_login_error_generic">ลงชื่อเข้าใช้ล้มเหลว ลองใหม่</string> + <string name="stores_login_continue_in_browser">%1$s ต้องการอีกหนึ่งขั้นตอน ทำให้เสร็จในเบราว์เซอร์ที่เปิดขึ้น แล้วลองอีกครั้ง</string> <string name="common_close">ปิด</string> <string name="common_back">กลับ</string> <string name="common_edit">แก้ไข</string> diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 0056965a36..581d4aecbb 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -2703,6 +2703,7 @@ <string name="stores_login_error_ssl">Oturum açma sayfasına bağlantı güvenli değil.</string> <string name="stores_login_error_verification">Oturum açma doğrulanamadı. Yeniden deneyin.</string> <string name="stores_login_error_generic">Oturum açma başarısız oldu. Yeniden deneyin.</string> + <string name="stores_login_continue_in_browser">%1$s bir adım daha istiyor. Açılan tarayıcıda tamamlayın, ardından yeniden deneyin.</string> <string name="common_close">Kapat</string> <string name="common_back">Geri</string> <string name="common_edit">Düzenle</string> diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 3505527050..8db1b46441 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -2766,6 +2766,7 @@ <string name="stores_login_error_ssl">З’єднання зі сторінкою входу не захищене.</string> <string name="stores_login_error_verification">Не вдалося підтвердити вхід. Спробуйте ще раз.</string> <string name="stores_login_error_generic">Вхід не вдався. Спробуйте ще раз.</string> + <string name="stores_login_continue_in_browser">%1$s потребує ще одного кроку. Завершіть його у відкритому браузері та спробуйте ще раз.</string> <string name="common_close">Закрити</string> <string name="common_back">Назад</string> <string name="common_edit">Редагувати</string> diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 5598b9b8f2..707c107c89 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -2689,6 +2689,7 @@ <string name="stores_login_error_ssl">Kết nối đến trang đăng nhập không an toàn.</string> <string name="stores_login_error_verification">Không thể xác minh đăng nhập. Hãy thử lại.</string> <string name="stores_login_error_generic">Đăng nhập thất bại. Hãy thử lại.</string> + <string name="stores_login_continue_in_browser">%1$s cần thêm một bước. Hãy hoàn tất trong trình duyệt vừa mở, rồi thử lại.</string> <string name="common_close">Đóng</string> <string name="common_back">Quay lại</string> <string name="common_edit">Sửa</string> diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 7df9807375..e95780a79c 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -2763,6 +2763,7 @@ <string name="stores_login_error_ssl">与登录页面的连接不安全。</string> <string name="stores_login_error_verification">无法验证登录。请重试。</string> <string name="stores_login_error_generic">登录失败。请重试。</string> + <string name="stores_login_continue_in_browser">%1$s 还需要一个步骤。请在已打开的浏览器中完成,然后重试。</string> <string name="common_close">关闭</string> <string name="common_back">返回</string> <string name="common_edit">编辑</string> diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 6eb5d1a6dd..28dcdcb49f 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -2686,6 +2686,7 @@ <string name="stores_login_error_ssl">與登入頁面的連線不安全。</string> <string name="stores_login_error_verification">無法驗證登入,請再試一次。</string> <string name="stores_login_error_generic">登入失敗,請再試一次。</string> + <string name="stores_login_continue_in_browser">%1$s 還需要一個步驟。請在已開啟的瀏覽器中完成,然後再試一次。</string> <string name="common_close">關閉</string> <string name="common_back">返回</string> <string name="common_edit">編輯</string> diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index a678d12b2c..a1f1534f67 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -2686,6 +2686,7 @@ <string name="stores_login_error_ssl">與登入頁面的連線不安全。</string> <string name="stores_login_error_verification">無法驗證登入。請再試一次。</string> <string name="stores_login_error_generic">登入失敗。請再試一次。</string> + <string name="stores_login_continue_in_browser">%1$s 還需要一個步驟。請在已開啟的瀏覽器中完成,然後再試一次。</string> <string name="common_close">關閉</string> <string name="common_back">返回</string> <string name="common_edit">編輯</string> diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 844524c2f0..69b03e75f6 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -3034,6 +3034,7 @@ <string name="stores_login_error_ssl">The connection to the sign-in page is not secure.</string> <string name="stores_login_error_verification">The sign-in could not be verified. Try again.</string> <string name="stores_login_error_generic">Sign-in failed. Try again.</string> + <string name="stores_login_continue_in_browser">%1$s needs one more step. Finish it in the browser that opened, then try again.</string> <string name="common_close">Close</string> <string name="common_back">Back</string> <string name="common_edit">Edit</string> diff --git a/app/src/test/java/com/droiddeck/launcher/stores/epic/EpicLoginTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/epic/EpicLoginTest.kt new file mode 100644 index 0000000000..c5e9ab63fc --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/epic/EpicLoginTest.kt @@ -0,0 +1,51 @@ +package com.droiddeck.launcher.stores.epic + +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +@RunWith(RobolectricTestRunner::class) +class EpicLoginTest { + private fun innerText(body: String): String = JSONObject.quote(body) + + private fun corrective(action: String) = + """{"errorCode":"errors.com.epicgames.oauth.corrective_action_required","metadata":{"correctiveAction":"$action"}}""" + + private fun epicLogin() = EpicLogin("https://www.epicgames.com/id/authorize", "test-agent", "http://127.0.0.1/launcher/authorized") + + @Test fun aRedirectPageAskingForTermsIsACorrectiveAction() { + assertEquals("PRIVACY_POLICY_ACCEPTANCE", EpicLogin.correctiveAction(innerText(corrective("PRIVACY_POLICY_ACCEPTANCE")))) + assertEquals("EULA_ACCEPTANCE", EpicLogin.correctiveAction(innerText(corrective("EULA_ACCEPTANCE")))) + assertEquals("EULA_ACCEPTANCE", EpicLogin.correctiveAction(corrective("EULA_ACCEPTANCE"))) + assertEquals(EpicLogin.ACCOUNT_SIGN_IN_URL, epicLogin().browserStep(innerText(corrective("EULA_ACCEPTANCE")))) + } + + @Test fun aCorrectiveActionWithoutItsNameStillSelectsTheBrowserStep() { + val body = """{"errorCode":"errors.com.epicgames.oauth.corrective_action_required"}""" + assertEquals("unknown", EpicLogin.correctiveAction(innerText(body))) + assertEquals(EpicLogin.ACCOUNT_SIGN_IN_URL, epicLogin().browserStep(innerText(body))) + } + + @Test fun anAuthorizationCodeOrAnotherErrorStaysInTheSignInPage() { + val pages = listOf( + innerText("""{"warning":"Do not share this code with any 3rd party service.","redirectUrl":"https://localhost/launcher/authorized?code=c1","authorizationCode":"c1","sid":null}"""), + innerText("""{"errorCode":"errors.com.epicgames.common.authentication.authentication_failed","message":"Sorry"}"""), + innerText("Sign in"), + "null", + "", + ) + for (page in pages) { + assertNull(page, EpicLogin.correctiveAction(page)) + assertNull(page, epicLogin().browserStep(page)) + } + } + + @Test fun otherSignInFlowsHaveNoBrowserStep() { + val url = "https://www.epicgames.com/id/authorize?client_id=c85f4c6238b04d3399bc0080e83b83fd&response_type=code&redirect_uri=http%3A%2F%2F127.0.0.1%3A41234%2Flauncher%2Fauthorized&state=x" + val flow = EpicClient.loginFlow(url, "test-browser")!! + assertNull(flow.browserStep(innerText(corrective("EULA_ACCEPTANCE")))) + } +} From 4405e2a389b59d5c91a01cb73d6bb67e6eac5d66 Mon Sep 17 00:00:00 2001 From: The412Banner <205237651+The412Banner@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:30:32 -0500 Subject: [PATCH 138/141] fix(graphics): the Mali bridge switch works on GPUs without a Mali kernel node (#3164) --- .../main/java/com/droiddeck/launcher/core/DeviceSupport.kt | 4 +++- .../java/com/droiddeck/launcher/core/DeviceSupportTest.kt | 6 ++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt index c847dbcdfc..a063f251da 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt @@ -28,7 +28,9 @@ object DeviceSupport { com.droiddeck.launcher.gpu.GpuInfo.detect().family.name.startsWith("MALI")) } - fun bridgeUsable(): Boolean = !adreno() && !SystemVulkanDriver.isAvailable() && File("/dev/mali0").exists() + fun bridgeUsable(): Boolean = bridgeUsable(adreno(), SystemVulkanDriver.isAvailable()) + + internal fun bridgeUsable(adreno: Boolean, systemDriverReady: Boolean): Boolean = !adreno && !systemDriverReady fun openDriverActive(context: Context): Boolean { if (adreno()) return false diff --git a/app/src/test/java/com/droiddeck/launcher/core/DeviceSupportTest.kt b/app/src/test/java/com/droiddeck/launcher/core/DeviceSupportTest.kt index 6338889980..a554a647bb 100644 --- a/app/src/test/java/com/droiddeck/launcher/core/DeviceSupportTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/core/DeviceSupportTest.kt @@ -11,4 +11,10 @@ class DeviceSupportTest { // A PowerVR HAL without usable DRM access also reaches this unavailable case. assertFalse(DeviceSupport.graphicsAvailable(adreno = false, powerVrReady = false)) } + + @Test fun bridgeServesEveryNonAdrenoWithoutASystemDriverRoute() { + assertTrue(DeviceSupport.bridgeUsable(adreno = false, systemDriverReady = false)) + assertFalse(DeviceSupport.bridgeUsable(adreno = true, systemDriverReady = false)) + assertFalse(DeviceSupport.bridgeUsable(adreno = false, systemDriverReady = true)) + } } From f1f98c3baba46f9f5a8b1d5b4761b514652baeed Mon Sep 17 00:00:00 2001 From: The412Banner <205237651+The412Banner@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:30:36 -0500 Subject: [PATCH 139/141] fix(graphics): let Auto-installed display drivers fall back to the system driver (#2977) --- .../droiddeck/launcher/gpu/TurnipDriver.java | 3 +- .../launcher/session/SessionPrefs.kt | 5 ++ .../launcher/wayland/CompositorHost.kt | 2 +- .../session/DisplayDriverFromAutoTest.kt | 53 +++++++++++++++++++ 4 files changed, 60 insertions(+), 3 deletions(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/session/DisplayDriverFromAutoTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java b/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java index d8aad76348..a26b1987fd 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java +++ b/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java @@ -308,8 +308,7 @@ public final class TurnipDriver { } } if (chosen != null && !chosen.isEmpty()) { - if (SessionPrefs.GPU_DRIVERS_AUTO.equals(SessionPrefs.INSTANCE.gpuDriverMode(context)) - && SessionPrefs.INSTANCE.gpuAutoInstalled(context).contains(chosen) + if (SessionPrefs.INSTANCE.displayDriverFromAuto(context) && gpuDetector.get().getFamily() == GpuInfo.Family.A7XX_LOW) { Log.i(TAG, "Auto-selected display driver does not cover Adreno 710/720/722; leaving the display driver to the system"); return null; diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 7624037de7..c7bea1ec93 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -814,6 +814,11 @@ object SessionPrefs { prefs(context).edit().putStringSet("gpuAutoInstalled", ids.toSet()).apply() } + fun displayDriverFromAuto(context: Context): Boolean { + val id = androidDriver(context) + return id.isEmpty() || (gpuDriverMode(context) == GPU_DRIVERS_AUTO && id in gpuAutoInstalled(context)) + } + fun picturePosition(context: Context): String = prefs(context).getString("picturePosition", "center") diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt index 8d43d09c7b..d9d2eb111f 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt @@ -84,7 +84,7 @@ object CompositorHost { com.droiddeck.launcher.gpu.TpUbwcHint.applyToProcess(context) WaylandCompositor.nativeStartWithSurface( surface, xdgRuntimeDir, driverPath, libraryName, nativeLibDir, - SessionPrefs.androidDriver(context).isEmpty(), + SessionPrefs.displayDriverFromAuto(context), ) attached = surface started = true diff --git a/app/src/test/java/com/droiddeck/launcher/session/DisplayDriverFromAutoTest.kt b/app/src/test/java/com/droiddeck/launcher/session/DisplayDriverFromAutoTest.kt new file mode 100644 index 0000000000..1ab248db85 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/DisplayDriverFromAutoTest.kt @@ -0,0 +1,53 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import com.droiddeck.launcher.gpu.TurnipDriver +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class DisplayDriverFromAutoTest { + private val context: Context get() = RuntimeEnvironment.getApplication() + + @Before fun reset() { + context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() + } + + @Test fun noDisplayDriverChoiceIsAuto() { + SessionPrefs.setAndroidDriver(context, TurnipDriver.AUTO) + for (mode in listOf(SessionPrefs.GPU_DRIVERS_AUTO, SessionPrefs.GPU_DRIVERS_MANUAL, SessionPrefs.GPU_DRIVERS_MIX)) { + SessionPrefs.setGpuDriverMode(context, mode) + assertTrue(mode, SessionPrefs.displayDriverFromAuto(context)) + } + } + + @Test fun aPairDisplayHalfInstalledByAutoIsAuto() { + SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO) + SessionPrefs.setGpuAutoInstalled(context, setOf("DD-Turnip_v0.8.0", "DD-Turnip_v0.8.0-linux")) + SessionPrefs.setAndroidDriver(context, "DD-Turnip_v0.8.0") + assertTrue(SessionPrefs.displayDriverFromAuto(context)) + } + + @Test fun aDriverTheUserImportedStaysTheirChoiceUnderAuto() { + SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO) + SessionPrefs.setGpuAutoInstalled(context, setOf("DD-Turnip_v0.8.0")) + SessionPrefs.setAndroidDriver(context, "user-import") + assertFalse(SessionPrefs.displayDriverFromAuto(context)) + } + + @Test fun anAutoInstalledDriverPickedByHandStaysTheUsersChoice() { + SessionPrefs.setGpuAutoInstalled(context, setOf("DD-Turnip_v0.8.0")) + SessionPrefs.setAndroidDriver(context, "DD-Turnip_v0.8.0") + for (mode in listOf(SessionPrefs.GPU_DRIVERS_MANUAL, SessionPrefs.GPU_DRIVERS_MIX)) { + SessionPrefs.setGpuDriverMode(context, mode) + assertFalse(mode, SessionPrefs.displayDriverFromAuto(context)) + } + } +} From 7248d01b1b4c1e5f32aaa4d798d4d1d28211a0e0 Mon Sep 17 00:00:00 2001 From: The412Banner <205237651+The412Banner@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:30:41 -0500 Subject: [PATCH 140/141] fix(storage): the Add game picker lists every card the file manager can open (#3123) --- .../droiddeck/launcher/ui/ExePickerDialog.kt | 17 ++-- .../droiddeck/launcher/ui/PickVolumesTest.kt | 88 +++++++++++++++++++ 2 files changed, 100 insertions(+), 5 deletions(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/ui/PickVolumesTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ExePickerDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ExePickerDialog.kt index 9fd3631553..5a1363a65e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ExePickerDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ExePickerDialog.kt @@ -60,7 +60,8 @@ 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.session.GameStorage +import com.droiddeck.launcher.files.StorageRoot +import com.droiddeck.launcher.files.StorageRoots import com.droiddeck.launcher.stores.formatBytes import java.io.File @@ -74,10 +75,16 @@ internal class PickVolume(val root: File, val label: String, val removable: Bool } internal fun pickVolumes(context: Context): List<PickVolume> = - listOf(PickVolume(Environment.getExternalStorageDirectory(), context.getString(R.string.games_internal), removable = false)) + - GameStorage.options(context).mapNotNull { o -> - File(o.path.substringBefore("/Android/")).takeIf { it.isDirectory }?.let { PickVolume(it, o.name, removable = true) } - }.distinctBy { it.root.absolutePath } + pickVolumes(Environment.getExternalStorageDirectory(), context.getString(R.string.games_internal), StorageRoots.list(context)) + +internal fun pickVolumes(internal: File, internalLabel: String, roots: List<StorageRoot>): List<PickVolume> { + val internalPath = internal.absolutePath.trimEnd('/') + fun overlapsInternal(path: String) = path == internalPath || path.startsWith("$internalPath/") || internalPath.startsWith("$path/") + return listOf(PickVolume(internal, internalLabel, removable = false)) + + roots.filter { it.readable && !overlapsInternal(it.dir.absolutePath.trimEnd('/')) } + .map { PickVolume(it.dir, it.label, removable = true) } + .distinctBy { it.root.absolutePath } +} internal class PickFolder(val dir: File, val readable: Boolean) diff --git a/app/src/test/java/com/droiddeck/launcher/ui/PickVolumesTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/PickVolumesTest.kt new file mode 100644 index 0000000000..0ab95caf7f --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/PickVolumesTest.kt @@ -0,0 +1,88 @@ +package com.droiddeck.launcher.ui + +import android.os.Environment +import android.os.Process +import android.os.storage.StorageManager +import com.droiddeck.launcher.files.StorageRoot +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.shadows.StorageVolumeBuilder +import java.io.File + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class PickVolumesTest { + @get:Rule val temporary = TemporaryFolder() + + private val internal = File("/storage/emulated/0") + + private fun root(label: String, path: String, removable: Boolean = true, readable: Boolean = true) = + StorageRoot(label, File(path), removable, readable) + + @Test fun aCardOnlyReachableThroughMediaRwIsListed() { + val volumes = pickVolumes(internal, "Internal storage", listOf( + root("Internal", "/storage/emulated/0", removable = false), + root("4A1C-830B", "/mnt/media_rw/4A1C-830B"), + )) + + assertEquals(listOf("/storage/emulated/0", "/mnt/media_rw/4A1C-830B"), volumes.map { it.root.path }) + assertEquals("Internal storage", volumes.first().label) + assertFalse(volumes.first().removable) + assertEquals("4A1C-830B", volumes[1].label) + assertTrue(volumes[1].removable) + } + + @Test fun aVisibleCardKeepsItsStoragePathAndLabel() { + val volumes = pickVolumes(internal, "Internal storage", listOf( + root("Internal", "/storage/emulated/0", removable = false), + root("SanDisk SD card", "/storage/1234-ABCD"), + root("USB drive", "/storage/5678-EF01"), + )) + + assertEquals(listOf("Internal storage", "SanDisk SD card", "USB drive"), volumes.map { it.label }) + assertEquals(File("/storage/1234-ABCD"), volumes[1].root) + } + + @Test fun unreadableVolumesAndInternalStorageAreNotListedTwice() { + val volumes = pickVolumes(internal, "Internal storage", listOf( + root("Internal", "/storage/emulated", removable = false), + root("Internal", "/storage/emulated/0/Android/data/com.droiddeck.launcher/files", removable = false), + root("SD card", "/storage/1234-ABCD", readable = false), + root("USB drive", "/mnt/media_rw/5678-EF01"), + root("USB drive", "/mnt/media_rw/5678-EF01"), + )) + + assertEquals(listOf("/storage/emulated/0", "/mnt/media_rw/5678-EF01"), volumes.map { it.root.path }) + } + + @Test fun withNoExternalVolumesOnlyInternalStorageIsListed() { + val volumes = pickVolumes(internal, "Internal storage", listOf(root("Internal", "/storage/emulated/0", removable = false))) + + assertEquals(listOf(internal), volumes.map { it.root }) + } + + @Test fun aMountedVolumeWithoutAnAppFolderReachesThePicker() { + val mount = temporary.newFolder("4A1C-830B") + val context = RuntimeEnvironment.getApplication() + val volume = StorageVolumeBuilder("public:179,1", mount, "SD card", Process.myUserHandle(), Environment.MEDIA_MOUNTED) + .setIsPrimary(false) + .setIsEmulated(false) + .setIsRemovable(true) + .build() + shadowOf(context.getSystemService(StorageManager::class.java)).addStorageVolume(volume) + + val card = pickVolumes(context).single { it.root.absoluteFile == mount.absoluteFile } + + assertEquals("SD card", card.label) + assertTrue(card.removable) + } +} From 3c4ac0365685c94b6b6bf34b06b5a1eebc16343b Mon Sep 17 00:00:00 2001 From: The412Banner <205237651+The412Banner@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:33:21 -0500 Subject: [PATCH 141/141] fix(display): layer buffers are imported as AHardwareBuffers only on the phone's own Vulkan driver (#3076) * fix(display): layer buffers are imported as AHardwareBuffers only on the phone's own Vulkan driver * fix(display): a failed 10-bit layer pool still falls back to 8-bit linear buffers --- app/src/main/cpp/waylandcomp/src/sc_layer.c | 5 +- app/src/main/cpp/waylandcomp/src/vk_present.c | 2 +- tools/tests/test_vk_layer_ahb_import.py | 227 ++++++++++++++++++ 3 files changed, 232 insertions(+), 2 deletions(-) create mode 100644 tools/tests/test_vk_layer_ahb_import.py diff --git a/app/src/main/cpp/waylandcomp/src/sc_layer.c b/app/src/main/cpp/waylandcomp/src/sc_layer.c index a843500c95..74cd5d6b45 100644 --- a/app/src/main/cpp/waylandcomp/src/sc_layer.c +++ b/app/src/main/cpp/waylandcomp/src/sc_layer.c @@ -163,6 +163,7 @@ struct layer { ARect geo_src, geo_dst; int geo_valid; int alloc_tier; + unsigned import_failed_fmts; uint64_t pool_modifier; int first_logged; int64_t drop_logged_ns; @@ -487,7 +488,8 @@ static const char *tier_name(int tier) { static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fmt) { g_alloc_failed = 0; - while (l->alloc_tier <= TIER_LINEAR) { + const unsigned fmt_bit = fmt == AHB_RGB10A2 ? 2u : 1u; + while (l->alloc_tier <= TIER_LINEAR && !(l->import_failed_fmts & fmt_bit)) { const int tier = l->alloc_tier; AHardwareBuffer_Desc d = { .width = (uint32_t)w, .height = (uint32_t)h, .layers = 1, @@ -560,6 +562,7 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm nh ? nh->numFds : -1, nh ? nh->numInts : -1, hd); AHardwareBuffer_release(ahb); if (tier < TIER_LINEAR) { l->alloc_tier = tier + 1; continue; } + l->import_failed_fmts |= fmt_bit; g_alloc_failed = 1; return -1; } diff --git a/app/src/main/cpp/waylandcomp/src/vk_present.c b/app/src/main/cpp/waylandcomp/src/vk_present.c index 7184ff644f..61b2765c5b 100644 --- a/app/src/main/cpp/waylandcomp/src/vk_present.c +++ b/app/src/main/cpp/waylandcomp/src/vk_present.c @@ -1494,7 +1494,7 @@ struct vkp_image *vkp_image_from_ahb(AHardwareBuffer *ahb) { } int vkp_can_import_ahb(void) { - return dev_init() == 0 && g_vendor_id != VKP_VENDOR_QUALCOMM && g_ahb_import && + return dev_init() == 0 && g_vendor_id != VKP_VENDOR_QUALCOMM && !g_library_name && g_ahb_import && g_vk.GetAndroidHardwareBufferPropertiesANDROID; } diff --git a/tools/tests/test_vk_layer_ahb_import.py b/tools/tests/test_vk_layer_ahb_import.py new file mode 100644 index 0000000000..53d2ba40fa --- /dev/null +++ b/tools/tests/test_vk_layer_ahb_import.py @@ -0,0 +1,227 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +from tools.tests.test_vk_pending_completion import function + +SRC = Path(__file__).resolve().parents[2] / "app/src/main/cpp/waylandcomp/src" + +HARNESS = r''' +#include <assert.h> +#include <stddef.h> +#include <stdint.h> + +#define VKP_VENDOR_QUALCOMM 0x5143 +static int dev_state; +static uint32_t g_vendor_id; +static char *g_library_name; +static int g_ahb_import; +static struct { void *GetAndroidHardwareBufferPropertiesANDROID; } g_vk; +static int dev_init(void) { return dev_state; } +static int properties_stub; + +%(can_import)s + +static int can(uint32_t vendor, char *library, int ext) { + dev_state = 0; + g_vendor_id = vendor; + g_library_name = library; + g_ahb_import = ext; + g_vk.GetAndroidHardwareBufferPropertiesANDROID = ext ? &properties_stub : NULL; + return vkp_can_import_ahb(); +} + +int main(void) { + char radv[] = "libvulkan_radeon.so"; + char panvk[] = "libvulkan_panfrost.so"; + const uint32_t samsung = 0x144d, arm = 0x13b5, imagination = 0x1010; + + assert(can(samsung, NULL, 1)); + assert(can(arm, NULL, 1)); + assert(can(imagination, NULL, 1)); + + assert(!can(samsung, radv, 1)); + assert(!can(arm, panvk, 1)); + + assert(!can(VKP_VENDOR_QUALCOMM, NULL, 1)); + assert(!can(samsung, NULL, 0)); + + dev_state = -1; + g_vendor_id = samsung; g_library_name = NULL; g_ahb_import = 1; + g_vk.GetAndroidHardwareBufferPropertiesANDROID = &properties_stub; + assert(!vkp_can_import_ahb()); + return 0; +} +''' + + +POOL_HARNESS = r''' +#define _GNU_SOURCE +#include <assert.h> +#include <stddef.h> +#include <stdint.h> +#include <stdio.h> +#include <sys/types.h> + +#define FOURCC(a, b, c, d) ((uint32_t)(a) | ((uint32_t)(b) << 8) | ((uint32_t)(c) << 16) | ((uint32_t)(d) << 24)) +#define DRM_ABGR8888 FOURCC('A', 'B', '2', '4') +#define DRM_ABGR2101010 FOURCC('A', 'B', '3', '0') +#define AHB_RGBA8 1u +#define AHB_RGB10A2 0x2bu +#define MOD_LINEAR 0ULL +#define MOD_QCOM_COMPRESSED 0x0500000000000001ULL +#define SC_MOD_GRALLOC (~0ULL - 1) +#define SC_LAYER_AHB_USAGE_VENDOR_UBWC (1ULL << 28) +#define AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT (1ULL << 9) +#define AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE (1ULL << 8) +#define AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY (1ULL << 11) +#define AHARDWAREBUFFER_USAGE_CPU_READ_RARELY 2ULL + +typedef struct AHardwareBuffer AHardwareBuffer; +typedef struct { + uint32_t width, height, layers, format; + uint64_t usage; + uint32_t stride, rfu0; + uint64_t rfu1; +} AHardwareBuffer_Desc; +struct droiddeck_native_handle { int version; int numFds; int numInts; int data[4]; }; +struct vkp_image { int unused; }; +struct slot { AHardwareBuffer *ahb; struct vkp_image *img; int w, h; uint32_t fmt; int release_fd; int busy; }; +struct layer { + const char *name; + int pool_n; + int alloc_tier; + unsigned import_failed_fmts; + uint64_t pool_modifier; + int logged_w, logged_h, logged_tier; + uint32_t logged_fmt; + uint64_t logged_mod; +}; + +enum { TIER_UBWC, TIER_PLAIN, TIER_LINEAR }; +static int g_alloc_failed; +static uint32_t g_hdr_pool_fmt = AHB_RGB10A2; + +static struct droiddeck_native_handle handle = {.numFds = 1, .data = {3}}; +static AHardwareBuffer *buffer = (AHardwareBuffer *)&handle; +static struct vkp_image image; +static int allocations, imports_10_bit, imports_8_bit, accept_10_bit, accept_8_bit; + +static int AHardwareBuffer_allocate(const AHardwareBuffer_Desc *d, AHardwareBuffer **out) { + (void)d; allocations++; *out = buffer; return 0; +} +static void AHardwareBuffer_describe(const AHardwareBuffer *b, AHardwareBuffer_Desc *d) { + (void)b; d->stride = 1920; d->usage = 0; +} +static void AHardwareBuffer_release(AHardwareBuffer *b) { (void)b; } +static const void *native_handle(const AHardwareBuffer *b) { (void)b; return &handle; } +static struct { const void *(*getNativeHandle)(const AHardwareBuffer *); } api = {native_handle}; +static int sniff_modifier(const struct droiddeck_native_handle *h, uint64_t *mod) { (void)h; (void)mod; return 0; } +static int vkp_can_import_ahb(void) { return 0; } +static struct vkp_image *vkp_image_import_ahb(AHardwareBuffer *b, char *info, size_t n) { + (void)b; (void)info; (void)n; return NULL; +} +static struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm, uint64_t mod, int w, int h, uint32_t pitch, + uint32_t offset, int planes) { + (void)fd; (void)mod; (void)w; (void)h; (void)pitch; (void)offset; (void)planes; + if (drm == DRM_ABGR2101010) { imports_10_bit++; return accept_10_bit ? &image : NULL; } + imports_8_bit++; + return accept_8_bit ? &image : NULL; +} +static int handle_fd(const struct droiddeck_native_handle *h, off_t need, int *which) { + (void)need; *which = 0; return h->data[0]; +} +static void describe_handle(const struct droiddeck_native_handle *h, char *out, size_t n) { (void)h; snprintf(out, n, "-"); } +static const char *pool_kind(uint64_t mod) { return mod == SC_MOD_GRALLOC ? "gralloc-laid-out" : "linear"; } +static void droiddeck_log(const char *tag, const char *fmt, ...) { (void)tag; (void)fmt; } + +%(tier_name)s +%(alloc_slot)s + +static int take_free_slot(struct layer *l, int w, int h, uint32_t fmt, int *wait_fd) { + struct slot s = {0}; + *wait_fd = -1; + g_alloc_failed = 0; + return alloc_slot(l, &s, w, h, fmt) == 0 ? 0 : -1; +} + +%(take_hdr_slot)s + +static int frame(struct layer *l) { + int fd; + return take_hdr_slot(l, 1920, 1080, &fd); +} + +static void reset(int ten, int eight) { + g_hdr_pool_fmt = AHB_RGB10A2; + allocations = imports_10_bit = imports_8_bit = 0; + accept_10_bit = ten; + accept_8_bit = eight; +} + +int main(void) { + struct layer ten_bit_refused = {.name = "game", .pool_n = 3}; + reset(0, 1); + assert(frame(&ten_bit_refused) == 0); + assert(g_hdr_pool_fmt == AHB_RGBA8); + assert(imports_10_bit == 1 && imports_8_bit == 1); + assert(ten_bit_refused.alloc_tier == TIER_LINEAR); + assert(frame(&ten_bit_refused) == 0); + assert(imports_10_bit == 1 && imports_8_bit == 2); + + struct layer ten_bit_works = {.name = "game", .pool_n = 3}; + reset(1, 1); + assert(frame(&ten_bit_works) == 0); + assert(g_hdr_pool_fmt == AHB_RGB10A2); + assert(imports_10_bit == 1 && imports_8_bit == 0); + + struct layer nothing_imports = {.name = "game", .pool_n = 3}; + reset(0, 0); + assert(frame(¬hing_imports) == -1 && g_alloc_failed); + assert(imports_10_bit == 1 && imports_8_bit == 1); + const int tried = allocations; + assert(frame(¬hing_imports) == -1 && g_alloc_failed); + assert(frame(¬hing_imports) == -1 && g_alloc_failed); + assert(allocations == tried); + assert(imports_10_bit == 1 && imports_8_bit == 1); + return 0; +} +''' + +class LayerAhbImportTest(unittest.TestCase): + def test_only_the_system_driver_imports_gralloc_layouts(self): + compiler = shutil.which(os.environ.get("CC", "cc")) + if not compiler: + self.fail("A C compiler is required for the layer AHardwareBuffer import test") + body = function((SRC / "vk_present.c").read_text(), "vkp_can_import_ahb") + with tempfile.TemporaryDirectory(prefix="droiddeck-layer-ahb-") as tmp: + source = Path(tmp) / "layer_ahb_import_test.c" + source.write_text(HARNESS % {"can_import": body}) + program = Path(tmp) / "layer-ahb-import" + built = subprocess.run([compiler, "-std=c11", "-Wall", "-Wextra", "-Werror", "-UNDEBUG", str(source), + "-o", str(program)], capture_output=True, text=True) + self.assertEqual(built.returncode, 0, built.stdout + built.stderr) + ran = subprocess.run([str(program)], capture_output=True, text=True, timeout=30) + self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr) + + def test_a_failed_10_bit_pool_still_falls_back_to_8_bit_and_failures_are_latched_per_format(self): + compiler = shutil.which(os.environ.get("CC", "cc")) + if not compiler: + self.fail("A C compiler is required for the layer pool fallback test") + text = (SRC / "sc_layer.c").read_text() + functions = {name: function(text, name) for name in ("tier_name", "alloc_slot", "take_hdr_slot")} + with tempfile.TemporaryDirectory(prefix="droiddeck-layer-pool-") as tmp: + source = Path(tmp) / "layer_pool_fallback_test.c" + source.write_text(POOL_HARNESS % functions) + program = Path(tmp) / "layer-pool-fallback" + built = subprocess.run([compiler, "-std=c11", "-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter", + "-UNDEBUG", str(source), "-o", str(program)], capture_output=True, text=True) + self.assertEqual(built.returncode, 0, built.stdout + built.stderr) + ran = subprocess.run([str(program)], capture_output=True, text=True, timeout=30) + self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr) + +if __name__ == "__main__": + unittest.main()