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/.github/workflows/build.yml b/.github/workflows/build.yml index 08cb6341be..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 @@ -588,7 +594,7 @@ jobs: path: | ~/.cache/droiddeck-pack-inputs ~/.cache/droiddeck-build - key: pack-inputs-v2-${{ hashFiles('tools/packs/build.sh', 'tools/packs/fetch-verified.sh', 'tools/packs/tracking/release.env', 'tools/powervr/release.json') }} + key: pack-inputs-v2-${{ hashFiles('tools/packs/build.sh', 'tools/packs/fetch-verified.sh', 'tools/packs/tracking/release.env', 'tools/packs/zstd/release.env', 'tools/powervr/release.json') }} restore-keys: pack-inputs-v2- - name: Build the add-on packs run: | @@ -619,14 +625,18 @@ jobs: export NDK="$ANDROID_HOME/ndk/$NDK_VERSION" tools/syncthing/build.sh app/src/main/jniLibs/arm64-v8a - - name: Note when the proot pack pin is behind this build + - name: Check the proot pack pin against this build run: | set -euo pipefail # shellcheck disable=SC1091 source tools/packs/proot/release.env sha=$(sha256sum app/build/packs/proot.tar.zst | cut -d' ' -f1) - if [ "$sha" != "$PROOT_PACK_SHA256" ]; then - echo "::warning::built proot pack $sha does not match tools/packs/proot/release.env ($PROOT_PACK_SHA256). This build publishes the pack it just built. Source builds keep downloading the pinned pack until release.env is updated." + size=$(stat -c %s app/build/packs/proot.tar.zst) + if [ "$sha" != "$PROOT_PACK_SHA256" ] || [ "$size" != "$PROOT_PACK_SIZE" ]; then + level=warning + if [ "$GITHUB_EVENT_NAME" = pull_request ]; then level=error; fi + echo "::$level::built proot pack $sha ($size bytes) does not match tools/packs/proot/release.env ($PROOT_PACK_SHA256, $PROOT_PACK_SIZE bytes). Source builds download the pinned pack, so set PROOT_PACK_SHA256=$sha and PROOT_PACK_SIZE=$size in tools/packs/proot/release.env." + if [ "$level" = error ]; then exit 1; fi fi - name: Check out MaliBridge @@ -819,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/README.md b/README.md index 7154309b06..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. @@ -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/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/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt b/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt index 12c2451221..681b32a10b 100644 --- a/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt +++ b/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt @@ -1,6 +1,13 @@ package com.droiddeck.launcher.ui +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import com.droiddeck.launcher.R +import com.droiddeck.launcher.input.SecondScreenMode /** The launcher as a whole: rail and page, opened on each tab through FrontEndState.navigate. */ @Composable @@ -8,6 +15,7 @@ private fun Launcher(tab: String, games: List = listOf( PreviewCase("session-menu-hud") { SessionMenu(SessionDrawerPage.HUD) }, PreviewCase("session-menu-session") { SessionMenu(SessionDrawerPage.SESSION) }, PreviewCase("session-menu-desktop") { SessionMenu(SessionDrawerPage.CONTROLLER, steam = false, desktop = true) }, + PreviewCase("session-menu-docked") { DockedMenu(SessionDrawerPage.CONTROLLER) }, + PreviewCase("session-menu-docked-display") { DockedMenu(SessionDrawerPage.DISPLAY) }, + PreviewCase("bottom-panel-bar") { BottomPanelBar() }, ) 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 4e8ae8094b..fc83727e11 100644 --- a/app/src/debug/java/com/droiddeck/launcher/ui/PreviewSupport.kt +++ b/app/src/debug/java/com/droiddeck/launcher/ui/PreviewSupport.kt @@ -10,6 +10,7 @@ import androidx.compose.ui.tooling.preview.Preview import com.droiddeck.launcher.frontend.Library import com.droiddeck.launcher.gpu.FrameGen import com.droiddeck.launcher.gpu.Lossless +import com.droiddeck.launcher.input.SecondScreenDisplay import com.droiddeck.launcher.input.SecondScreenMode import com.droiddeck.launcher.session.SessionPrefs @@ -64,7 +65,9 @@ internal val sampleActions: FrontEndActions = FrontEndActions( ) /** The in-game menu's actions with settled sample values; its switches do nothing. */ -internal fun sampleDrawerActions(steam: Boolean = true, desktop: Boolean = false): DrawerActions = DrawerActions( +internal fun sampleDrawerActions( + steam: Boolean = true, desktop: Boolean = false, secondScreen: SecondScreenMode? = null, +): DrawerActions = DrawerActions( steam = steam, desktop = desktop, title = if (!steam && !desktop) "Hades" else null, isHomeApp = false, androidApps = emptyList(), hudOn = true, onHud = {}, @@ -75,8 +78,10 @@ internal fun sampleDrawerActions(steam: Boolean = true, desktop: Boolean = false backActionsInverted = false, onBackActionsInverted = {}, touchMode = SessionPrefs.TOUCH_AUTO, onTouch = {}, touchAuto = "Auto (direct)", fexPreset = "", onFexPreset = {}, - secondScreenMode = SecondScreenMode.NONE, onSecondScreenMode = {}, - secondScreenDisplays = emptyList(), selectedSecondScreenDisplay = -1, onSecondScreenDisplay = {}, + secondScreenMode = secondScreen ?: SecondScreenMode.NONE, onSecondScreenMode = {}, secondScreenNone = secondScreen == null, + secondScreenDisplays = listOfNotNull(secondScreen?.let { SecondScreenDisplay(2, "Built-in · 1240×1080") }), + selectedSecondScreenDisplay = if (secondScreen != null) 2 else -1, onSecondScreenDisplay = {}, + gameSwapAvailable = secondScreen != null, dashboardAvailable = secondScreen != null, onImportLossless = {}, onKeyboard = {}, onHardwareKeyboard = {}, onSteamMenu = if (steam) ({}) else null, onQam = if (steam) ({}) else null, onLaunchAndroidApp = { _, _ -> }, onBackground = {}, onShareLogs = {}, onStop = {}, onClose = {}, diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 560c92a7e5..3cee3538dc 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -313,15 +313,6 @@ android:resizeableActivity="true" android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" /> - 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..a843500c95 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) { @@ -443,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]; @@ -459,13 +538,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 +580,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 +620,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 +635,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 +674,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 +837,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 +850,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 +881,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 +904,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 +918,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,18 +933,19 @@ 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; } 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); @@ -879,10 +965,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 +981,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 +1079,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 +1134,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 " @@ -986,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) { @@ -1033,6 +1201,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_linear_dmabuf.h b/app/src/main/cpp/waylandcomp/src/vk_linear_dmabuf.h new file mode 100644 index 0000000000..a820026930 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/vk_linear_dmabuf.h @@ -0,0 +1,61 @@ +#ifndef VK_LINEAR_DMABUF_H +#define VK_LINEAR_DMABUF_H + +#include +#include + +static inline int vkp_linear_dmabuf_through_buffer(int drm_modifiers, uint64_t modifier, int blit_dst) { + return !drm_modifiers && modifier == 0 && !blit_dst; +} + +static inline int vkp_linear_dmabuf_foreign_image(int dmabuf, int staged) { + return dmabuf && !staged; +} + +static inline VkPipelineStageFlags vkp_linear_dmabuf_readback_stage(int in_general) { + return in_general ? VK_PIPELINE_STAGE_TRANSFER_BIT : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; +} + +static inline VkAccessFlags vkp_linear_dmabuf_readback_access(int in_general) { + return in_general ? VK_ACCESS_TRANSFER_WRITE_BIT : 0; +} + +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); + if (!copy || w <= 0 || h <= 0 || stride % texel || offset % texel || stride / texel < (uint32_t)w) return 0; + *copy = (VkBufferImageCopy){ + .bufferOffset = offset, + .bufferRowLength = stride / texel, + .bufferImageHeight = (uint32_t)h, + .imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, + .imageExtent = {(uint32_t)w, (uint32_t)h, 1}, + }; + return (VkDeviceSize)offset + (VkDeviceSize)stride * (VkDeviceSize)(h - 1) + (VkDeviceSize)w * texel; +} + +static inline VkBufferMemoryBarrier vkp_linear_dmabuf_ownership(VkBuffer buffer, uint32_t queue_family, + VkAccessFlags access, int acquire) { + return (VkBufferMemoryBarrier){ + .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, + .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, + .offset = 0, + .size = VK_WHOLE_SIZE, + }; +} + +#endif diff --git a/app/src/main/cpp/waylandcomp/src/vk_loader.h b/app/src/main/cpp/waylandcomp/src/vk_loader.h index 2742a1b82a..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,9 @@ 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) \ \ X(CreateShaderModule) X(DestroyShaderModule) X(CreatePipelineLayout) X(DestroyPipelineLayout) \ X(CreateGraphicsPipelines) X(DestroyPipeline) X(CreateRenderPass) X(DestroyRenderPass) \ diff --git a/app/src/main/cpp/waylandcomp/src/vk_present.c b/app/src/main/cpp/waylandcomp/src/vk_present.c index 53ddadaeb0..7184ff644f 100644 --- a/app/src/main/cpp/waylandcomp/src/vk_present.c +++ b/app/src/main/cpp/waylandcomp/src/vk_present.c @@ -2,6 +2,7 @@ #include "vk_present.h" #include "vk_loader.h" #include "vk_external_image_sync.h" +#include "vk_linear_dmabuf.h" #include "sc_layer.h" #include "effects_chain.h" #include "cardboard.h" @@ -42,10 +43,15 @@ struct vkp_image { VkFormat fmt; int sampled; AHardwareBuffer *android_buffer; + int staged; + VkBuffer linear_buf; + VkDeviceMemory linear_mem; + VkBufferImageCopy linear_copy; }; static ANativeWindow *g_window; static int g_ahb_import; +static int g_drm_modifiers; static char *g_driver_path, *g_library_name, *g_native_lib_dir; static int g_allow_driver_fallback; static int g_dev_state; @@ -628,6 +634,7 @@ static int dev_init(void) { if (has_ext(exts, ne, import_exts[i])) dev_exts[n_dev_exts++] = import_exts[i]; else LOGE("present: driver MISSING %s (dmabuf import will fail)", import_exts[i]); } + g_drm_modifiers = has_ext(exts, ne, "VK_EXT_image_drm_format_modifier"); int want_hdr_md = 0; if (droiddeck_color_requested()) { want_hdr_md = has_ext(exts, ne, VK_EXT_HDR_METADATA_EXTENSION_NAME); @@ -1088,6 +1095,10 @@ struct vkp_image *vkp_image_from_dmabuf(int fd, uint32_t drm_format, uint64_t mo return vkp_image_import_dmabuf(fd, drm_format, modifier, w, h, stride, offset, 0); } +static int foreign_image(const struct vkp_image *img) { + return vkp_linear_dmabuf_foreign_image(img->dmabuf, img->staged); +} + /* Return client sources to FOREIGN after their final read. The consuming paths * wait for our fence before Wayland can release an ordinary dma-buf or an * android_wlegl AHardwareBuffer. Producer-fence synchronization is separate from @@ -1095,7 +1106,7 @@ struct vkp_image *vkp_image_from_dmabuf(int fd, uint32_t drm_format, uint64_t mo static void release_external_client_image(VkCommandBuffer cmd, struct vkp_image *img) { struct vkp_external_client_barrier_pair pair; if (!img || !vkp_external_client_barrier_pair( - img->image, g_qfam, img->dmabuf, img->blit_dst, &pair)) + img->image, g_qfam, foreign_image(img), img->blit_dst, &pair)) return; g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &pair.release); @@ -1109,6 +1120,37 @@ 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, 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, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .image = img->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}; + 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, 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, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .image = img->image, .subresourceRange = range, .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, + .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_SHADER_READ_BIT}; + g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, + 0, NULL, 1, &release, 1, &read); +} + +static void stage_linear_dmabufs(VkCommandBuffer cmd, const struct vkp_draw *draws, int count) { + for (int i = 0; i < count; i++) { + int seen = 0; + for (int j = 0; j < i; j++) if (draws[j].img == draws[i].img) { seen = 1; break; } + if (!seen) stage_linear_dmabuf(cmd, draws[i].img); + } +} + int vkp_image_is_dmabuf(const struct vkp_image *img) { return img && vkp_is_external_client_image(img->dmabuf, img->blit_dst); } @@ -1181,18 +1223,122 @@ fail: return NULL; } +static int optimal_sampled(VkFormat fmt) { + if (!g_vk.GetPhysicalDeviceFormatProperties2) return 0; + VkFormatProperties2 fp = {.sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2}; + g_vk.GetPhysicalDeviceFormatProperties2(g_pd, fmt, &fp); + const VkFormatFeatureFlags need = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | + VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT; + return (fp.formatProperties.optimalTilingFeatures & need) == need; +} + +static void destroy_image_objects(struct vkp_image *img) { + if (img->image) g_vk.DestroyImage(g_dev, img->image, NULL); + if (img->mem) g_vk.FreeMemory(g_dev, img->mem, NULL); + if (img->linear_buf) g_vk.DestroyBuffer(g_dev, img->linear_buf, NULL); + if (img->linear_mem) g_vk.FreeMemory(g_dev, img->linear_mem, NULL); + img->image = VK_NULL_HANDLE; img->mem = VK_NULL_HANDLE; + img->linear_buf = VK_NULL_HANDLE; img->linear_mem = VK_NULL_HANDLE; + img->staged = 0; img->in_general = 0; +} + +static int import_linear_dmabuf(struct vkp_image *img, int fd, const VkBufferImageCopy *copy, VkDeviceSize need) { + int dupfd = dup(fd); + if (dupfd < 0) return -1; + VkDeviceSize size = need; + off_t end = lseek(dupfd, 0, SEEK_END); + if (end > 0 && (VkDeviceSize)end >= need) size = (VkDeviceSize)end; + lseek(dupfd, 0, SEEK_SET); + if (end > 0 && (VkDeviceSize)end < need) { + LOGE("dmabuf: the linear %dx%d buffer holds %lld bytes, its row pitch needs %llu", img->w, img->h, + (long long)end, (unsigned long long)need); + close(dupfd); + return -1; + } + VkExternalMemoryBufferCreateInfo ext = { + .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 = 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; + if (g_vk.GetMemoryFdPropertiesKHR) { + VkMemoryFdPropertiesKHR fp = {.sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR}; + if (g_vk.GetMemoryFdPropertiesKHR(g_dev, VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT, + dupfd, &fp) == VK_SUCCESS) + allowed = fp.memoryTypeBits; + } + VkMemoryRequirements breq; + g_vk.GetBufferMemoryRequirements(g_dev, img->linear_buf, &breq); + int bidx = memory_type(breq.memoryTypeBits & allowed, 0); + r = VK_ERROR_FORMAT_NOT_SUPPORTED; + if (bidx < 0) goto fail; + VkImportMemoryFdInfoKHR imp = {.sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR, + .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT, .fd = dupfd}; + VkMemoryDedicatedAllocateInfo ded = {.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO, + .pNext = &imp, .buffer = img->linear_buf}; + VkMemoryAllocateInfo mai = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .pNext = &ded, + .allocationSize = breq.size, .memoryTypeIndex = (uint32_t)bidx}; + r = g_vk.AllocateMemory(g_dev, &mai, NULL, &img->linear_mem); + if (r != VK_SUCCESS) goto fail; + dupfd = -1; + r = g_vk.BindBufferMemory(g_dev, img->linear_buf, img->linear_mem, 0); + if (r != VK_SUCCESS) goto fail; + + VkImageCreateInfo ici = { + .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .imageType = VK_IMAGE_TYPE_2D, .format = img->fmt, + .extent = {(uint32_t)img->w, (uint32_t)img->h, 1}, .mipLevels = 1, .arrayLayers = 1, + .samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL, + .usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | + (img->sampled ? VK_IMAGE_USAGE_SAMPLED_BIT : 0), + .sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED}; + r = g_vk.CreateImage(g_dev, &ici, NULL, &img->image); + if (r != VK_SUCCESS) goto fail; + VkMemoryRequirements ireq; + g_vk.GetImageMemoryRequirements(g_dev, img->image, &ireq); + int iidx = memory_type(ireq.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + if (iidx < 0) iidx = memory_type(ireq.memoryTypeBits, 0); + r = VK_ERROR_FORMAT_NOT_SUPPORTED; + if (iidx < 0) goto fail; + VkMemoryAllocateInfo iai = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + .allocationSize = ireq.size, .memoryTypeIndex = (uint32_t)iidx}; + r = g_vk.AllocateMemory(g_dev, &iai, NULL, &img->mem); + if (r != VK_SUCCESS) goto fail; + r = g_vk.BindImageMemory(g_dev, img->image, img->mem, 0); + if (r != VK_SUCCESS) goto fail; + img->linear_copy = *copy; + img->staged = 1; + img->in_general = 1; + return 0; +fail: + 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; +} + struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t modifier, int w, int h, uint32_t stride, uint32_t offset, int as_blit_dst) { 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); + 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; - img->sampled = !as_blit_dst && g_vk.GetPhysicalDeviceImageFormatProperties2 && - modifier_importable(img->fmt, modifier, sampled_usage); + const int modifier_sampled = !as_blit_dst && g_drm_modifiers && g_vk.GetPhysicalDeviceImageFormatProperties2 && + modifier_importable(img->fmt, modifier, sampled_usage); + 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. */ { @@ -1203,10 +1349,11 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t if (seen[i].fmt == drm_format && seen[i].mod == modifier && seen[i].w == w && seen[i].h == h) known = 1; if (!known && nseen < 32) { seen[nseen].fmt = drm_format; seen[nseen].mod = modifier; seen[nseen].w = w; seen[nseen].h = h; nseen++; - droiddeck_log("gpu", "dmabuf import: %c%c%c%c %s %dx%d stride %u offset %u -> vk format %d, %s%s", + droiddeck_log("gpu", "dmabuf import: %c%c%c%c %s %dx%d stride %u offset %u -> vk format %d, %s%s%s", drm_format & 0xff, (drm_format >> 8) & 0xff, (drm_format >> 16) & 0xff, (drm_format >> 24) & 0xff, vkp_modifier_name(modifier), w, h, stride, offset, (int)img->fmt, - img->sampled ? "sampled" : "copied", as_blit_dst ? ", blit target" : ""); + img->sampled ? "sampled" : "copied", as_blit_dst ? ", blit target" : "", + through_buffer ? ", trying a copy at its row pitch (no VK_EXT_image_drm_format_modifier)" : ""); } } @@ -1214,6 +1361,17 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t * vkCreateImage, which left the whole window unshown (David Cimo). One packed, 64-byte aligned * row is what a linear buffer that small holds. */ if (stride == 0 && modifier == 0) stride = ((uint32_t)w * 4 + 63) & ~63u; + 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) { + 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}; VkImageDrmFormatModifierExplicitCreateInfoEXT modInfo = { .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT, @@ -1501,8 +1659,7 @@ void vkp_image_destroy(struct vkp_image *img) { if (g_dev) { blendp_forget_image(img->image); if (img->map) g_vk.UnmapMemory(g_dev, img->mem); - if (img->image) g_vk.DestroyImage(g_dev, img->image, NULL); - if (img->mem) g_vk.FreeMemory(g_dev, img->mem, NULL); + destroy_image_objects(img); } if (img->android_buffer) AHardwareBuffer_release(img->android_buffer); free(img); @@ -1600,7 +1757,7 @@ static void effects_source_note(int scene_w, int scene_h, const struct vkp_draw static void record_draw(VkCommandBuffer cmd, const struct vkp_draw *d, const VkImageBlit *blit, VkImage target, VkFormat target_fmt, int target_w, int target_h, VkFilter filter) { const struct vkp_image *im = d->img; - const int external_client = vkp_image_is_dmabuf(im); + const int external_client = vkp_is_external_client_image(foreign_image(im), im->blit_dst); if (d->blend && im->sampled && blendp_draw(cmd, im->image, im->fmt, im->w, im->h, !external_client, target, target_fmt, target_w, target_h, @@ -1734,6 +1891,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; @@ -1750,6 +1912,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) { @@ -2084,6 +2247,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT}; g_vk.BeginCommandBuffer(cmd, &bi); blendp_begin_frame(); + stage_linear_dmabufs(cmd, draws, n); VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; VkImageMemoryBarrier *bars = calloc((size_t)n + 1, sizeof(*bars)); @@ -2101,7 +2265,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i if (seen || !im) continue; struct vkp_external_client_barrier_pair pair; if (vkp_external_client_barrier_pair( - im->image, g_qfam, im->dmabuf, im->blit_dst, &pair)) { + im->image, g_qfam, foreign_image(im), im->blit_dst, &pair)) { bars[nb++] = pair.acquire; } else if (!im->blit_dst && !im->in_general) { bars[nb++] = (VkImageMemoryBarrier){ @@ -2353,9 +2517,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); } @@ -2369,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); @@ -2383,44 +2589,32 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) { VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT}; g_vk.BeginCommandBuffer(g_cmd, &bi); + stage_linear_dmabuf(g_cmd, src); struct vkp_external_client_barrier_pair src_pair; const int src_external = vkp_external_client_barrier_pair( - src->image, g_qfam, src->dmabuf, src->blit_dst, &src_pair); - VkImageMemoryBarrier acq[2] = { - src_external ? src_pair.acquire : (VkImageMemoryBarrier){ + src->image, g_qfam, foreign_image(src), src->blit_dst, &src_pair); + 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; @@ -2489,22 +2683,26 @@ int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) { VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT}; g_vk.BeginCommandBuffer(cmd, &bi); + stage_linear_dmabuf(cmd, src); struct vkp_external_client_barrier_pair src_pair; const int src_external = vkp_external_client_barrier_pair( - src->image, g_qfam, src->dmabuf, src->blit_dst, &src_pair); + src->image, g_qfam, foreign_image(src), src->blit_dst, &src_pair); VkImageMemoryBarrier acq[2] = { src_external ? src_pair.acquire : (VkImageMemoryBarrier){ - .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, + .oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : 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}, + .image = src->image, .subresourceRange = range, + .srcAccessMask = vkp_linear_dmabuf_readback_access(src->in_general), + .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT}, {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, .newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .image = g_rb->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, 2, acq); + g_vk.CmdPipelineBarrier(cmd, vkp_linear_dmabuf_readback_stage(src->in_general), + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 2, acq); VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, .srcOffsets = {{0, 0, 0}, {src->w, src->h, 1}}, .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, @@ -2551,24 +2749,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; @@ -2588,13 +2795,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); @@ -2602,12 +2827,13 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT}; g_vk.BeginCommandBuffer(cmd, &bi); blendp_begin_frame(); + stage_linear_dmabufs(cmd, draws, n); VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; 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, @@ -2620,7 +2846,7 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw if (seen || !im) continue; struct vkp_external_client_barrier_pair pair; if (vkp_external_client_barrier_pair( - im->image, g_qfam, im->dmabuf, im->blit_dst, &pair)) { + im->image, g_qfam, foreign_image(im), im->blit_dst, &pair)) { bars[nb++] = pair.acquire; } else if (!im->blit_dst && !im->in_general) { bars[nb++] = (VkImageMemoryBarrier){ @@ -2638,12 +2864,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); @@ -2662,53 +2888,57 @@ 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; } 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}; - - 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, + for (int i = 0; i < n; i++) { + struct vkp_image *dst = dsts[i]; + 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}}}; + 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); - 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; @@ -2728,6 +2958,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/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt index 1a45ab8512..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" @@ -96,6 +97,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/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index c15996d8fe..1c0d4f8ef9 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 @@ -184,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) @@ -194,10 +197,12 @@ 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) 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("") @@ -528,7 +533,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) } @@ -537,7 +542,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) { @@ -584,6 +589,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") @@ -596,9 +602,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) @@ -875,7 +883,7 @@ 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: String? = null + private var pendingGameLink: com.droiddeck.launcher.frontend.GameRequest? = null private var gameLinkReading = false private var gameLinkTried = false private var gameSyncFolder by mutableStateOf(null) @@ -947,12 +955,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId) val copy = Intent(request) Thread({ - val id = GameLaunchIntent.read(this, copy) + val game = GameLaunchIntent.read(this, copy) ui.post { if (intent === request && !isDestroyed) { gameLinkReading = false - pendingGameLink = id - if (id == null) { + pendingGameLink = game + if (game == null) { syncDualPanel() android.widget.Toast.makeText(this, R.string.game_link_invalid, android.widget.Toast.LENGTH_LONG).show() } else { @@ -1202,16 +1210,16 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private fun handleGameLink(games: List, scanned: Boolean = true) { if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) return - val id = pendingGameLink ?: return - if (!scanned && games.none { it.gameIdString == id }) return + val request = pendingGameLink ?: 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 game = games.firstOrNull { it.gameIdString == id } val link = intent fun consume() { - if (intent !== link || pendingGameLink != id) return + if (intent !== link || pendingGameLink !== request) return pendingGameLink = null link.data = null link.action = Intent.ACTION_MAIN @@ -1220,7 +1228,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet if (game == null) { consume() syncDualPanel() - android.widget.Toast.makeText(this, R.string.game_link_missing, android.widget.Toast.LENGTH_LONG).show() + 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) } @@ -1259,6 +1269,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) @@ -1358,6 +1369,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet launcherOrientation = launcherOrientation, homePage = homePage, launcherFullscreen = launcherFullscreen, + controllerHaptics = controllerHaptics, downloadSource = downloadSource, downloadMirror = downloadMirror, downloadPrefix = downloadPrefix, @@ -1519,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) } }, @@ -1674,6 +1686,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 @@ -2003,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() @@ -2032,6 +2046,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) { @@ -2042,6 +2086,15 @@ 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)) { if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) { @@ -2058,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) } @@ -2077,6 +2133,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) @@ -2189,6 +2246,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } override fun onDestroy() { + triggerKeys.cancel() gameLaunchRequest.incrementAndGet() cancelCompatLaunch() updates.unregister() @@ -2582,9 +2640,9 @@ 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, + hdr = hdrOn, hdrReason = hdrReason, hdrDisplay = hdrDisplay, zeroCopy = zeroCopyOn, upscaler = upscaler, upscaleSharpness = upscaleSharpness, gpuDrivers = drivers.summary(), touchMode = touchMode, @@ -2602,6 +2660,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, @@ -2636,8 +2695,15 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet onIntegration = ::configureIntegration, onIntegrationAppInfo = ::openAppInfo, onIntegrationLocation = ::openWifiDiscoverySettings, - onResolution = { value -> SessionPrefs.setResolutionChoice(this, mode, value); resolution = value }, - onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on }, + 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 + 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 }, @@ -2664,6 +2730,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 @@ -2962,11 +3029,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) @@ -2981,9 +3054,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) } @@ -2996,6 +3071,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) @@ -3326,6 +3402,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/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 618452d028..96aeb08be3 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 @@ -109,6 +110,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 @@ -175,6 +177,38 @@ 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 && !activeCardboard.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) + 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() { if (!CompositorHost.isStarted) return @@ -210,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) } } @@ -245,7 +280,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 @@ -306,7 +350,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 @@ -496,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) @@ -510,6 +563,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( @@ -537,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) @@ -610,6 +667,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) @@ -647,6 +707,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()) @@ -782,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 @@ -839,6 +902,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) @@ -883,7 +950,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) } @@ -928,7 +995,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 { @@ -1028,7 +1095,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde kotlinx.coroutines.delay(2000) } } - pip = com.droiddeck.launcher.session.SessionPipController(this, ::pipBounds, ::showPipUi) + pip = com.droiddeck.launcher.session.SessionPipController(this, ::pipBounds, ::showPipUi) { + intent.getBooleanExtra(EXTRA_RETURN_HOME, false) + } surfaceView.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> pip.refresh() } pip.refresh() handleHomeGuideIntent(intent) @@ -1036,6 +1105,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) { @@ -1044,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 @@ -1072,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) @@ -1122,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) @@ -1239,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) @@ -1253,7 +1327,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde onBack = { inputSettingsOpen = false; secondScreenPresentation?.refreshControls() }, onChanged = { controllerSettings = ControllerPrefs.read(this@SessionActivity) - oscMode = SessionPrefs.oscMode(this@SessionActivity) + oscMode = SessionPrefs.oscMode(this@SessionActivity, SessionState.mode == SessionService.MODE_STEAM) padBridge?.setStickDeadZone(ControllerPrefs.deadZone(this@SessionActivity)) joyConVr?.refresh() onScreenControls?.reload() @@ -1293,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() } @@ -1358,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, @@ -1643,6 +1721,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() @@ -1683,12 +1764,22 @@ 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() + applyUnfoldedControls() + unfoldedPanel?.reload() + bottomInputControls?.reload() }, backHold = backHold, onBackHold = { on -> 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 -> @@ -1757,12 +1848,10 @@ 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 - typingReturnMode = null - automaticPanel = false - if (mode != SecondScreenMode.NONE) SessionPrefs.setSecondScreenPanel(this@SessionActivity, desktopSession, mode.id) - selectSecondScreenMode(mode) + pickSecondScreenMode(mode) }, onSecondScreenDisplay = ::selectSecondScreenDisplay, onLaunchAndroidApp = { app, displayId -> @@ -1783,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 @@ -1797,6 +1894,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(), @@ -1863,7 +1977,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun sendSteamGuide() { - drawerOpen = false + if (!dockedTouchOnly) drawerOpen = false padBridge?.triggerSteamMenu() } @@ -1910,7 +2024,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun triggerSteamQam() { - drawerOpen = false + if (!dockedTouchOnly) drawerOpen = false padBridge?.triggerQam() } @@ -1999,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?) { @@ -2490,9 +2604,13 @@ 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) + 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) @@ -2535,8 +2653,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde fexPreset = SessionPrefs.fexPreset(this) suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode) steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this) - oscMode = SessionPrefs.oscMode(this) + oscMode = SessionPrefs.oscMode(this, SessionState.mode == SessionService.MODE_STEAM) + 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) @@ -2748,6 +2870,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) @@ -2767,27 +2892,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( @@ -2859,16 +2988,18 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde WaylandCompositor.nativeResizeOutput(size.first, size.second) } + 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)) + 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))) + SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this), followPortrait())) } private fun applyFollowOrientation(config: android.content.res.Configuration) { @@ -2883,6 +3014,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } cancelTouchGestures() applyFollowOrientation(newConfig) + applyNotchInset() applyUnfoldedControls() resizeOutputForWindow(surfaceW, surfaceH) } @@ -2933,17 +3065,19 @@ 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 portraitOutput(): Boolean = SessionPrefs.portrait(this) && !controlsBelowWanted() + private fun outputSize(): Pair = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(com.droiddeck.launcher.session.SessionDisplay.panelSize(this), - resolutionChoice(), SessionPrefs.portrait(this) && !controlsBelowWanted()) + resolutionChoice(), portraitOutput()) - private fun resolutionChoice(): 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 && - 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) @@ -2963,6 +3097,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 -> @@ -2982,9 +3121,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()) @@ -3150,6 +3318,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() } @@ -3210,8 +3379,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun onSessionEnded(status: Int) { ended = true - uiHandler.removeCallbacks(guardWhenRunning) - com.droiddeck.launcher.session.KeepTopActivity.release() ++steamVrRequestGeneration if (isInPictureInPictureMode) { runOnUiThread { finish() } @@ -3386,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) @@ -3400,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, @@ -3414,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 } @@ -3445,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 @@ -3458,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) { @@ -3482,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) { @@ -3494,10 +3661,10 @@ 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(secondScreenDisplays.isNotEmpty(), glasses.present) + drawerPage = sessionDrawerPages(glasses.present) .step(drawerPage, if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1) releaseDrawerDirection() } @@ -3564,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 && @@ -3587,12 +3754,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) } @@ -3600,10 +3767,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) } @@ -3745,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) @@ -3752,8 +3920,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 @@ -3766,7 +3934,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun requestRelativeMouse() { - runCatching { relativeMouseRequests.execute { applyRelativeMouse() } } + runCatching { gamescopeConvarRequests.execute { applyRelativeMouse() } } } private fun applyRelativeMouse() { @@ -3780,23 +3948,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 @@ -4135,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 @@ -4154,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) { @@ -4182,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 @@ -4198,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) @@ -4232,6 +4473,20 @@ 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) + } + + 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 = ::pickMenuMode, + ) + private fun secondScreenPresentation(target: Display) = SecondScreenPresentation( this, target, onSteamMenu = ::tapSteamButton, @@ -4240,6 +4495,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde pad = padBridge, onKeyboardClosed = ::bottomKeyboardClosed, onMenu = { drawerOpen = true }, + picker = ::bottomScreenPicker, onMenuTouched = { if (drawerPinned) { drawerPinned = false @@ -4428,19 +4684,21 @@ 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() } ?: 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) { @@ -4449,7 +4707,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)) { @@ -4650,6 +4910,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 @@ -4668,6 +4929,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (reset) { panelMode(SecondScreenMode.NONE) automaticPanel = false + SessionState.bottomMenu = false } } @@ -4864,7 +5126,9 @@ 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 = inSurfaceSpace(event) { 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 onMouse(event) @@ -4991,7 +5255,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) @@ -5218,8 +5482,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 @@ -5302,7 +5571,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 @@ -5327,7 +5596,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val forced = File(Environment.getExternalStorageDirectory(), "Download/droiddeck-osc") .takeIf { it.isFile } ?.let { FileUtils.readString(it)?.trim()?.lowercase() } - ?: SessionPrefs.oscMode(this) + ?: 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) @@ -5493,31 +5766,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 @@ -5528,6 +5814,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } catch (_: IllegalArgumentException) { done() bitmap.recycle() + skipped("copy rejected") } } } @@ -5535,12 +5822,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 @@ -5623,8 +5933,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) { - if (::pip.isInitialized && intent.component?.className != com.droiddeck.launcher.session.KeepTopActivity::class.java.name && - (requestCode >= 0 || intent.component?.packageName == packageName || + if (::pip.isInitialized && (requestCode >= 0 || intent.component?.packageName == packageName || intent.action in setOf(Intent.ACTION_CHOOSER, Intent.ACTION_SEND, Intent.ACTION_OPEN_DOCUMENT, Intent.ACTION_GET_CONTENT, "android.settings.PICTURE_IN_PICTURE_SETTINGS"))) pip.background() super.startActivityForResult(intent, requestCode, options) @@ -5645,8 +5954,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() @@ -5656,7 +5968,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } override fun onStop() { - if (lightPause.stopped()) departureCleanup() if (runtimeRemovalBlocked) { super.onStop(); return } started = false if (::hud.isInitialized) hud.setBackgrounded(true) @@ -5686,6 +5997,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (this.intent.getBooleanExtra(EXTRA_RETURN_HOME, false)) intent.putExtra(EXTRA_RETURN_HOME, true) if (!intent.hasExtra(EXTRA_LINK_TASK)) intent.putExtra(EXTRA_LINK_TASK, this.intent.getIntExtra(EXTRA_LINK_TASK, -1)) setIntent(intent) + if (::pip.isInitialized) pip.refresh(true) if (intent.getBooleanExtra(EXTRA_STEAMVR, false) && SessionState.mode == SessionService.MODE_STEAM) { SessionState.steamVr = true steamVrAutoTried = false @@ -5700,12 +6012,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde override fun onResume() { super.onResume() - uiHandler.removeCallbacks(lightPauseCheck) - when (lightPause.resumed(com.droiddeck.launcher.session.KeepTopActivity.bounces)) { - com.droiddeck.launcher.session.LightPause.Resume.LIGHT -> return - com.droiddeck.launcher.session.LightPause.Resume.CLEANUP_FIRST -> departureCleanup() - com.droiddeck.launcher.session.LightPause.Resume.NORMAL -> Unit - } drawerGameInventoryRevision++ com.droiddeck.launcher.input.SystemKeyCapture.attach(this, { hasWindowFocus() && !appUiOwnsPointer() && CompositorHost.isStarted }) { event -> com.droiddeck.launcher.input.GuestKeys.send(event) { code, down -> sendGuestKey(code, down, 8) } @@ -5750,6 +6056,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) @@ -5771,56 +6078,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde SessionPrefs.sessionPrefs(this).registerOnSharedPreferenceChangeListener(cardboardPrefListener) } - private var memoryPressureAt = 0L - private var focusBounce = false - private val lightPause = com.droiddeck.launcher.session.LightPause() - private val lightPauseCheck = Runnable { if (lightPause.timedOut()) departureCleanup() } - private var topResumed = false - private val guardWhenRunning = object : Runnable { - override fun run() { - if (!topResumed || isFinishing) return - if (SessionState.running) guardOtherDisplays() else uiHandler.postDelayed(this, 2_000) - } - } - - // RUNNING_LOW and RUNNING_CRITICAL are not delivered from API 34, so the guard also goes up - // as soon as a running session is on top. - override fun onTrimMemory(level: Int) { - super.onTrimMemory(level) - if (!com.droiddeck.launcher.session.TopUnderPressure.isPressure(level)) return - memoryPressureAt = android.os.SystemClock.elapsedRealtime() - guardOtherDisplays() - } - - override fun onTopResumedActivityChanged(isTopResumedActivity: Boolean) { - super.onTopResumedActivityChanged(isTopResumedActivity) - topResumed = isTopResumedActivity - uiHandler.removeCallbacks(guardWhenRunning) - if (isTopResumedActivity) uiHandler.post(guardWhenRunning) - else if (com.droiddeck.launcher.session.TopUnderPressure.shouldReclaim( - android.os.SystemClock.elapsedRealtime(), memoryPressureAt, SessionState.running, isFinishing)) guardOtherDisplays() - } - - private fun guardOtherDisplays() { - if (!SessionState.running || isFinishing) return - val wasResumed = lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED) - val bounced = com.droiddeck.launcher.session.KeepTopActivity.guardOtherDisplays(this, display?.displayId ?: android.view.Display.DEFAULT_DISPLAY) - if (com.droiddeck.launcher.session.KeepTopActivity.hasPendingStarts()) { - uiHandler.removeCallbacks(guardWhenRunning) - uiHandler.postDelayed(guardWhenRunning, com.droiddeck.launcher.session.KeepTopActivity.RETRY_MS) - } - if (!bounced) return - if (!wasResumed) return - focusBounce = true - uiHandler.postDelayed({ focusBounce = false }, 500) - } - override fun onPause() { - if (focusBounce) { - focusBounce = false - lightPause.paused(com.droiddeck.launcher.session.KeepTopActivity.bounces) - uiHandler.postDelayed(lightPauseCheck, 200) - } else departureCleanup() + departureCleanup() super.onPause() } @@ -5850,7 +6109,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 } @@ -5868,6 +6129,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() @@ -6021,6 +6283,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() @@ -6104,6 +6367,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() @@ -6153,6 +6417,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde bottomGame = screen surfaceW = 0 surfaceH = 0 + applyNotchInset() screen.setOnDismissListener { if (bottomGame === screen) { restoreTopOutput(screen) @@ -6194,6 +6459,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 @@ -6224,7 +6490,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 @@ -6358,6 +6624,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 @@ -6482,8 +6749,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } override fun onDestroy() { - uiHandler.removeCallbacks(guardWhenRunning) - com.droiddeck.launcher.session.KeepTopActivity.release() + uiHandler.removeCallbacks(panelHeldCheck) + uiHandler.removeCallbacks(panelHeldRetry) synchronized(frameGenGlobalLock) { frameGenActivityActive = false frameGenRequests.incrementAndGet() @@ -6491,7 +6758,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) @@ -6534,6 +6801,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() } @@ -6608,9 +6878,13 @@ 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 + 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/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/agent/AgentSetup.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt index e917e36605..df90f6f86b 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt @@ -141,8 +141,11 @@ object AgentSetup { Step.CONNECTION -> return Step.INSTALL -> { listOf("sh", "-c", "set -e; export DEBIAN_FRONTEND=noninteractive; " + - "dpkg --configure -a; apt-get update || echo 'Some package sources could not be refreshed; continuing'; apt-get -f install -y; " + - "apt-get install -y --no-install-recommends git gh adb curl ca-certificates python3; ${harness.install}") + "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; " + + "apt -f install -y --fix-missing; " + + "apt install -y --fix-missing --no-install-recommends git gh adb curl ca-certificates python3; ${harness.install}") } Step.SIGN_IN -> harness.signIn Step.GITHUB -> listOf("dd-gh-login") 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/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/core/DeviceReport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt index fe835b10c8..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")) @@ -289,6 +291,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/frontend/GameFiles.kt b/app/src/main/java/com/droiddeck/launcher/frontend/GameFiles.kt index 63b5f6b4dc..3ab8928920 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/GameFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/GameFiles.kt @@ -2,6 +2,9 @@ package com.droiddeck.launcher.frontend import android.content.Context import android.content.Intent +import android.net.Uri +import android.provider.DocumentsContract +import android.provider.OpenableColumns import android.util.AtomicFile import com.droiddeck.launcher.R import androidx.core.util.readText @@ -13,27 +16,65 @@ import java.io.InputStream object GameFiles { const val EXTENSION = "steam" - private const val MAX_BYTES = 128 + private const val MAX_BYTES = 4096 private const val MAX_NAME_BYTES = 200 private const val INVENTORY = ".droiddeck-sync.json" private const val FORMAT = "droiddeck-game-files-v1" - fun readIntent(context: Context, request: Intent): String? = runCatching { + fun readIntent(context: Context, request: Intent): GameRequest? = runCatching { if (request.action != Intent.ACTION_VIEW) return null val uri = request.data ?: return null - GameLaunchLink.parse(uri.toString())?.let { return it } + GameRequest.link(uri.toString())?.let { return GameRequest(it) } + val name = displayName(context, uri) + val extension = name?.substringAfterLast('.', "").orEmpty() + if (extension.lowercase(java.util.Locale.ROOT) in GameRequest.PROGRAMS) { + val program = localFile(context, uri)?.takeIf { it.isFile } ?: return null + return GameRequest(title = name?.substringBeforeLast('.'), program = program.canonicalFile) + } val stream = when (uri.scheme) { - "content" -> context.contentResolver.openInputStream(uri) - "file" -> { - if (!uri.authority.isNullOrEmpty() || uri.query != null || uri.fragment != null) return null - File(uri.path ?: return null).inputStream() - } - null -> File(uri.toString()).takeIf { it.isAbsolute }?.inputStream() + "content" -> runCatching { context.contentResolver.openInputStream(uri) }.getOrNull() + ?: localFile(context, uri)?.takeIf { it.isFile }?.inputStream() + "file", null -> localFile(context, uri)?.inputStream() else -> null } ?: return null - stream.use(::read) + val id = stream.use(::read) ?: return null + GameRequest(id, GameRequest.sourceOf(extension), name?.substringBeforeLast('.')) }.getOrNull() + private fun displayName(context: Context, uri: Uri): String? = when (uri.scheme) { + "content" -> runCatching { + context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c -> + if (c.moveToFirst()) c.getString(0) else null + } + }.getOrNull() ?: uri.lastPathSegment?.substringAfterLast('/')?.substringAfterLast(':') + "file" -> uri.path?.let { File(it).name } + null -> File(uri.toString()).name + else -> null + }?.takeIf { it.isNotEmpty() } + + private fun localFile(context: Context, uri: Uri): File? = when (uri.scheme) { + "file" -> { + if (!uri.authority.isNullOrEmpty() || uri.query != null || uri.fragment != null) null + else uri.path?.let(::File) + } + null -> File(uri.toString()).takeIf { it.isAbsolute } + "content" -> storageDocument(context, uri) ?: uri.pathSegments.let { parts -> + (0..1).asSequence().map { File("/" + parts.drop(it).joinToString("/")) }.firstOrNull { it.isFile } + } + else -> null + } + + // Frontends pass SAF document URIs or FileProvider URIs whose path mirrors shared storage. + private fun storageDocument(context: Context, uri: Uri): File? { + if (uri.authority != "com.android.externalstorage.documents" || !DocumentsContract.isDocumentUri(context, uri)) return null + val id = DocumentsContract.getDocumentId(uri) + val volume = id.substringBefore(':') + val path = id.substringAfter(':', "") + val root = if (volume.equals("primary", ignoreCase = true)) android.os.Environment.getExternalStorageDirectory() + else File("/storage", volume) + return File(root, path) + } + fun read(stream: InputStream): String? { val bytes = ByteArray(MAX_BYTES + 1) var count = 0 @@ -44,8 +85,7 @@ object GameFiles { count += n } if (count > MAX_BYTES) return null - val text = String(bytes, 0, count, Charsets.UTF_8).trim() - return text.takeIf(GameLaunchLink::validId) + return GameRequest.parse(String(bytes, 0, count, Charsets.UTF_8)) } fun filename(game: Library.SteamGame, disambiguate: Boolean = false): String { @@ -61,7 +101,7 @@ object GameFiles { } val title = String(points, 0, end).trimEnd { it.isWhitespace() || it == '.' }.ifBlank { "Game" } val suffix = if (disambiguate) " (${game.gameIdString})" else "" - return "$title$suffix.$EXTENSION" + return "$title$suffix.${GameRequest.extension(game)}" } private fun contents(id: String): String { @@ -130,7 +170,7 @@ object GameFiles { } for (name in previous.keys()) { val id = previous.getString(name) - if (!next.has(name) && name.endsWith(".$EXTENSION") && GameLaunchLink.validId(id)) { + if (!next.has(name) && ours(name) && GameLaunchLink.validId(id)) { val file = child(context, folder, name) if (matches(file, contents(id))) { val retained = exports.any { java.nio.file.Files.isSameFile(it.toPath(), file.toPath()) } @@ -141,6 +181,9 @@ object GameFiles { if (previous.toString() != next.toString()) write(inventory, JSONObject().put("format", FORMAT).put("games", next).toString()) } + private fun ours(name: String) = name.substringAfterLast('.', "").lowercase(java.util.Locale.ROOT) + .let { it == EXTENSION || it in GameRequest.extensions } + private fun inventoryOwns(context: Context, folder: File, record: JSONObject, file: File, id: String): Boolean { if (record.optString(file.name) == id) return true if (!file.exists()) return false diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/GameLaunchIntent.kt b/app/src/main/java/com/droiddeck/launcher/frontend/GameLaunchIntent.kt index 6f71475cf9..3e5d4ae0dd 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/GameLaunchIntent.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/GameLaunchIntent.kt @@ -11,22 +11,26 @@ object GameLaunchIntent { fun accepts(action: String?): Boolean = action == Intent.ACTION_VIEW || action == ACTION || action == GAMENATIVE_ACTION - fun read(context: Context, intent: Intent): String? = when (intent.action) { + fun read(context: Context, intent: Intent): GameRequest? = when (intent.action) { Intent.ACTION_VIEW -> GameFiles.readIntent(context, intent) - ACTION, GAMENATIVE_ACTION -> readId(intent) + ACTION, GAMENATIVE_ACTION -> readExtras(intent) else -> null } @Suppress("DEPRECATION") - internal fun readId(intent: Intent): String? = runCatching { + internal fun readExtras(intent: Intent): GameRequest? = runCatching { if (intent.action != ACTION && intent.action != GAMENATIVE_ACTION) return null - val source = intent.extras?.get(EXTRA_GAME_SOURCE) - if (source != null && (source !is String || !source.equals("STEAM", ignoreCase = true))) return null + val source = when (val value = intent.extras?.get(EXTRA_GAME_SOURCE)) { + null -> Library.SOURCE_STEAM + is String -> GameRequest.sourceNamed(value) ?: return null + else -> return null + } val id = when (val value = intent.extras?.get(EXTRA_APP_ID)) { is Int -> value.takeIf { it > 0 }?.toString() + is Long -> value.takeIf { it != 0L }?.let(java.lang.Long::toUnsignedString) is String -> value.takeIf(GameLaunchLink::validId) else -> null - } - id + } ?: return null + GameRequest(id, source) }.getOrNull() } diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/GameRequest.kt b/app/src/main/java/com/droiddeck/launcher/frontend/GameRequest.kt new file mode 100644 index 0000000000..a6baf2d70f --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/frontend/GameRequest.kt @@ -0,0 +1,78 @@ +package com.droiddeck.launcher.frontend + +import com.droiddeck.launcher.stores.Store +import java.io.File +import java.util.Locale + +class GameRequest( + val id: String? = null, + val source: String = Library.SOURCE_STEAM, + val title: String? = null, + val program: File? = null, +) { + fun find(games: List, byTitle: Boolean = true): Library.SteamGame? { + program?.let { return owner(games, it) } + val exact = id?.let { id -> games.firstOrNull { it.gameIdString == id } } + if (source == Library.SOURCE_STEAM) return exact ?: games.firstOrNull { it.appId > 0 && it.appId.toString() == id } + exact?.takeIf { it.source == source }?.let { return it } + id?.let { id -> games.firstOrNull { it.source == source && it.storeId == id } }?.let { return it } + if (!byTitle) return null + val key = title?.let(::titleKey)?.takeIf { it.isNotEmpty() } ?: return null + return games.firstOrNull { it.source == source && titleKey(it.name) == key } + } + + private fun owner(games: List, program: File): Library.SteamGame? { + val path = program.path + return games.mapNotNull { game -> + val folder = game.gameFiles ?: return@mapNotNull null + val dir = folder.absolutePath.takeIf { inside(path, it) } + ?: runCatching { folder.canonicalPath }.getOrNull()?.takeIf { inside(path, it) } + dir?.let { game to it.length } + }.maxByOrNull { it.second }?.first + } + + companion object { + val PROGRAMS = setOf("exe", "bat") + private const val CUSTOM_GAME = "CUSTOM_GAME" + private const val CUSTOM_EXTENSION = "pcgame" + private val DAIJISHOU = setOf("# Daijishou Player Template", "# DST") + private val daijishouId = Regex("""(?i)\[steamappid]\s*([0-9]+)""") + private val steamLink = Regex("steam://rungameid/([1-9][0-9]{0,19})") + + val extensions: Set = Store.entries.map { it.id }.toSet() + CUSTOM_EXTENSION + + fun extension(game: Library.SteamGame): String = Store.byId(game.source)?.id ?: GameFiles.EXTENSION + + fun sourceNamed(value: String): String? = when { + value.equals(Library.SOURCE_STEAM, ignoreCase = true) -> Library.SOURCE_STEAM + value.equals(CUSTOM_GAME, ignoreCase = true) -> Library.ADDED + else -> Store.entries.firstOrNull { it.name.equals(value, ignoreCase = true) }?.id + } + + fun sourceOf(extension: String): String = when (val ext = extension.lowercase(Locale.ROOT)) { + CUSTOM_EXTENSION -> Library.ADDED + else -> Store.byId(ext)?.id ?: Library.SOURCE_STEAM + } + + fun link(text: String): String? = text.takeIf(GameLaunchLink::validId) + ?: GameLaunchLink.parse(text) + ?: steamLink.matchEntire(text)?.groupValues?.get(1)?.takeIf(GameLaunchLink::validId) + + fun parse(text: String): String? { + link(text.trim())?.let { return it } + val lines = text.lines().map { it.trim() }.filter { it.isNotEmpty() } + val header = lines.firstOrNull() ?: return null + return when { + DAIJISHOU.any { header.equals(it, ignoreCase = true) } -> lines.firstNotNullOfOrNull { daijishouId.matchEntire(it) } + ?.groupValues?.get(1)?.takeIf(GameLaunchLink::validId) + header.equals("[InternetShortcut]", ignoreCase = true) -> lines.firstOrNull { it.startsWith("URL=", ignoreCase = true) } + ?.substring(4)?.trim()?.takeIf { !GameLaunchLink.validId(it) }?.let(::link) + else -> null + } + } + + internal fun titleKey(name: String): String = name.lowercase(Locale.ROOT).filter { it.isLetterOrDigit() } + + private fun inside(path: String, dir: String) = path.startsWith(dir.trimEnd(File.separatorChar) + File.separator) + } +} 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/input/ControllerOverlayGeometry.kt b/app/src/main/java/com/droiddeck/launcher/input/ControllerOverlayGeometry.kt new file mode 100644 index 0000000000..d274269d4c --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/ControllerOverlayGeometry.kt @@ -0,0 +1,182 @@ +package com.droiddeck.launcher.input + +import android.graphics.Rect +import android.util.DisplayMetrics +import kotlin.math.max +import kotlin.math.min + +internal class ControllerOverlayGeometry( + 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 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 + 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)) + } + } + + 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 * size), y(848f), 46f).takeIf { elements.any { it.id == KEYBOARD } } + val row = fitRow(listOfNotNull(keyboard, + 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 * 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, + 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 + } + } + val chosen = placed.filter { it.id == "legacy:${it.control.id}" }.map { it.control } + return placed + optional.mapNotNull { (control, box) -> + 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 * 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), + 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 * 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 * size, y(400f) - 110f * size, 42f), + InputControl.R3 to Box(x(1130f) + 160f * size, y(690f) + 100f * size, 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 * 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) * size + 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) + 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 * size, w * .03f) + + fun at(cx: Float) = Box(cx, cy, hw, hh) + + fun place(element: InputSurfaceElement): InputSurfaceElement { + 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, + 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/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/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/FloatingSteamOverlay.kt b/app/src/main/java/com/droiddeck/launcher/input/FloatingSteamOverlay.kt new file mode 100644 index 0000000000..39a916fbcd --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/FloatingSteamOverlay.kt @@ -0,0 +1,93 @@ +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() + val chosen = lowered.filter(::isStock).map { it.control } + fun add(control: InputControl, x: Float, y: List, widthDp: Int, heightDp: Int, shape: InputButtonShape) { + 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) + } + 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/InputLibraries.kt b/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt index 5f0b082c8c..4683aece97 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt @@ -11,6 +11,10 @@ import java.util.UUID object InputLibraries { private const val VERSION = 14 + private val redesignVersions = 15..16 + private const val KIT_DPAD = "kit:dpad" + private const val KEYBOARD = "builtin:keyboard" + private const val REDESIGN_BACKUP = "library-before-controller-revert" private const val KEY = "library" private const val RECOVERY = "library-recovery." const val OVERLAY = "builtin.overlay" @@ -23,10 +27,18 @@ object InputLibraries { fun read(context: Context): InputLibrary { val p = prefs(context) val raw = p.getString(KEY, null) - val decoded = raw?.let(::decode) + val decoded = raw?.let { decode(it, context) } if (raw != null && decoded == null) return scopeLayouts(upgradeStockLayouts(upgradeOverlay(context, migrate(context)))) var library = decoded ?: scopeLayouts(upgradeStockLayouts(upgradeOverlay(context, migrate(context)))) val version = raw?.let { JSONObject(it).getInt("version") } ?: 0 + if (version in redesignVersions && raw != null) { + val encoded = encode(library) + if (encoded.length > 2_000_000) return library + if (!commitWithBackup(p, raw, REDESIGN_BACKUP, encoded)) { + android.util.Log.e("InputLibraries", "Could not save the restored input library") + return library + } + } if (version < 5) library = scopeLayouts(upgradeStockLayouts(upgradeOverlay(context, library))) if (version < 11) library = neutralStockLayouts(library) if (version < 10) library = restyleGamepads(context, library) @@ -75,20 +87,35 @@ object InputLibraries { fun update(context: Context, change: (InputLibrary) -> InputLibrary): InputLibrary { val p = prefs(context) val stored = p.getString(KEY, null) - val invalid = stored != null && decode(stored) == null + val invalid = stored != null && decode(stored, context) == null require(!invalid || runCatching { JSONObject(stored!!).getInt("version") }.getOrNull()?.let { it <= VERSION } != false) { "The saved input library cannot be edited by this version." } val updated = change(read(context)).validate() - if (invalid) { + val backupKey = when { + invalid -> RECOVERY + UUID.nameUUIDFromBytes(stored!!.toByteArray(Charsets.UTF_8)) + stored != null && p.getString(KEY, null) == stored && + JSONObject(stored).getInt("version") in redesignVersions -> REDESIGN_BACKUP + else -> null + } + if (backupKey != null) { val encoded = encode(updated) require(encoded.length <= 2_000_000) { "The input library is too large to save." } - check(p.edit().putString(RECOVERY + UUID.nameUUIDFromBytes(stored!!.toByteArray(Charsets.UTF_8)), stored) - .putString(KEY, encoded).commit()) { "Could not save the input library and its recovery copy." } + check(commitWithBackup(p, requireNotNull(stored), backupKey, encoded)) { + "Could not save the input library and its recovery copy." + } } else write(context, updated) return updated } + private fun commitWithBackup(prefs: android.content.SharedPreferences, raw: String, backupKey: String, encoded: String): Boolean { + val previousBackup = prefs.getString(backupKey, null) + if (prefs.edit().putString(backupKey, raw).putString(KEY, encoded).commit()) return true + // SharedPreferences updates its in-memory values even when the disk write fails. + prefs.edit().putString(KEY, raw).putString(backupKey, previousBackup).apply() + return false + } + private fun write(context: Context, library: InputLibrary) { val encoded = encode(library.validate()) require(encoded.length <= 2_000_000) { "The input library is too large to save." } @@ -297,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)) } @@ -336,22 +375,27 @@ object InputLibraries { .put("profiles", profiles).put("layouts", layouts).put("bindings", bindings).toString() } - internal fun decode(raw: String): InputLibrary? = runCatching { + internal fun decode(raw: String, context: Context? = null): InputLibrary? = runCatching { require(raw.length <= 2_000_000) - val doc = JSONObject(raw); require(doc.getInt("version") in 2..VERSION) + val doc = JSONObject(raw) + val version = doc.getInt("version") + val restore = context != null && version in redesignVersions + require(version in 2..VERSION || restore) + val generated = mutableSetOf() val layouts = doc.getJSONArray("layouts").objects(256).map { layout -> - val elements = 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)) - } - SavedInputLayout(layout.getString("id"), layout.getString("name"), elements, InputLayoutTemplate.valueOf(layout.getString("template")), + val stored = decodeElements(layout.getJSONArray("elements")) + val id = layout.getString("id") + val origin = layout.optionalString("origin") + val followsGamepad = restore && !layout.optBoolean("kitless") && + (id == OVERLAY || origin == OVERLAY) && + stored.none { it.id.startsWith("legacy:") || it.id == KIT_DPAD || it.id == KEYBOARD } + if (followsGamepad) generated += id + SavedInputLayout(id, layout.getString("name"), if (restore) stored.map { it.bounded() } else stored, InputLayoutTemplate.valueOf(layout.getString("template")), 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(), layout.optionalString("origin"), - layout.optDouble("scale", 1.0).toFloat()) + InputLayoutScreen.valueOf(layout.optString("screen", InputLayoutScreen.BOTH.name)), layout.optDouble("aspect", 0.0).toFloat(), origin, + 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)) } @@ -378,9 +422,41 @@ object InputLibraries { value.optBoolean("profileSelected", profile != InputProfiles.AUTO || parts.length() == 0)) } }.orEmpty() - InputLibrary(profiles, layouts, bindings, doc.getString("selected"), doc.getString("steam"), doc.getString("desktop"), selections).validate() + val library = InputLibrary(profiles, layouts, bindings, doc.getString("selected"), doc.getString("steam"), doc.getString("desktop"), selections) + (if (restore) restoreGamepads(requireNotNull(context), library, generated) else library).validate() }.getOrNull() + private fun restoreGamepads(context: Context, library: InputLibrary, generated: Set): InputLibrary { + val (display, metrics) = primaryDisplay(context) + val height = metrics.heightPixels.coerceAtLeast(1) + val layouts = library.layouts.map { layout -> + if (layout.id !in generated) return@map layout + val width = if (layout.aspect > 0f) (layout.aspect * height).toInt().coerceAtLeast(1) + else metrics.widthPixels.coerceAtLeast(1) + val gamepad = LegacyGamepadLayout(display, width, height, scale = layout.scale).elements() + layout.copy(elements = gamepad.take(64 - layout.elements.size) + layout.elements, + aspect = (width.toFloat() / height).coerceIn(.05f, 20f)) + } + val byId = layouts.associateBy { it.id } + val bindings = library.bindings.map { preset -> + val layout = byId[preset.layoutId] ?: return@map preset + val elements = layout.elements.associateBy { it.id } + val defaults = layout.elements.mapNotNull { element -> + val action = when (element.id) { + KEYBOARD -> InputAction.Command(InputCommand.KEYBOARD) + KIT_DPAD -> InputAction.Native() + else -> return@mapNotNull null + } + element.id to action + }.toMap() + preset.copy( + elements = defaults + preset.elements.filter { (id, action) -> elements[id]?.let { action.validFor(it) } == true }, + clicks = preset.clicks.filter { (id, action) -> elements[id]?.hasClick == true && action.validForClick() }, + ) + } + return library.copy(layouts = layouts, bindings = bindings) + } + private fun JSONArray.objects(limit: Int): List { require(length() <= limit) return (0 until length()).map { getJSONObject(it) } 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..9532f51778 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt @@ -22,8 +22,12 @@ 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 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)) @@ -249,6 +253,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/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 2a36489e85..a944ec28ef 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) @@ -345,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 @@ -360,3 +348,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 ee3a6560ae..142846a04f 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt @@ -72,12 +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) { - OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, isButtonsOnly, dock) + OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, isButtonsOnly, dock, + rearButtons = optional.first, trackpads = optional.second) } } @@ -88,11 +91,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 artwork = PadKit.forOverlay(context, layout) + surface.updateStyle(style, artwork) + quickToggle.tint = style.tint.takeUnless { artwork != null } + quickToggle.alpha = style.opacity / 100f quickToggle.invalidate() } @@ -125,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 9fbb01c7ad..ad5d8e2701 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,19 @@ 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 supportsFloatingSteamControls(controller: String, layout: SavedInputLayout?) = + 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) { companion object { fun deck(portrait: Boolean, gamepad: SavedInputLayout?): Dock { @@ -23,31 +30,96 @@ 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, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect, - buttonsOnly: Boolean = false, dock: Dock? = null): List { - val stored = layout?.elements ?: return emptyList() - if (width <= 0 || height <= 0) return stored + 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, dock?.portrait ?: (height > width)) + 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) + 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() 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 } - 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 } } + 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()) { + 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 = 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 } + + 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 { @@ -63,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 @@ -73,6 +162,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? = @@ -86,7 +177,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 new file mode 100644 index 0000000000..750bceb5c9 --- /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?.overlay != true) 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/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/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/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/runtime/CurseForgeApp.kt b/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt new file mode 100644 index 0000000000..a5fb9a4a40 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt @@ -0,0 +1,293 @@ +package com.droiddeck.launcher.runtime + +import android.content.Context +import com.droiddeck.launcher.stores.battlenet.BattleNetInstall +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.time.Instant +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean + +object CurseForgeApp { + const val NAME = "CurseForge" + const val FEED = "https://curseforge.overwolf.com/electron/linux/latest-linux.yml" + internal const val WOW = 1 + const val HELPER = "/usr/local/bin/droiddeck-curseforge" + internal const val AGENT = "/usr/local/bin/droiddeck-agent" + private const val READY_MS = 120_000L + private const val INSTALL_MS = 300_000L + private const val OUT_OF_DATE = 2 + + enum class Start { READY, BUSY, FAILED } + + class Started(val state: Start, val inspector: String? = null) + + class Project(val id: String, val installedModId: String, val folders: List, val update: Boolean) + + internal val INSPECTOR = Regex("ws://127\\.0\\.0\\.1:[0-9]{4,5}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") + + class Failure(message: String, val code: String? = null) : Exception(message) { + val gone get() = code == "DEVTOOLS_UNREACHABLE" + } + + fun find(apps: List): UserApps.App? = apps.firstOrNull { it.feed == FEED } + + fun request(): UserApps.Request = UserApps.Request(UserApps.Source.Feed(FEED), NAME, null) + + internal fun dir(app: UserApps.App): String? = app.args.firstOrNull()?.takeIf { it.startsWith("/") } + + internal fun helperArgv(command: String, dir: String): List = 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 + 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 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 -> + GuestCommand.run(context, argv, logName = "curseforge", extraBinds = BattleNetInstall.binds(context), fastPath = true, + cancelled = cancelled, redact = INSPECTOR, onLine = onLine) + } + + private val holds = ConcurrentHashMap() + + private fun lines(context: Context, argv: List): List { + val out = ArrayList() + guest(context, argv, null) { out += it } + return out + } + + private fun call(context: Context, inspector: String, service: String, method: String, args: JSONArray?, timeoutMs: Long, pick: String = "r => r"): Any? = + unwrap(lastJson(lines(context, evalArgv(inspector, expression(service, method, args, pick), timeoutMs))) ?: throw Failure("CurseForge gave no answer")) + + private sealed class Launch { + class Url(val inspector: String) : Launch() + class Exit(val code: Int) : Launch() + } + + private fun launch(context: Context, dir: String, hold: AtomicBoolean): Launch? { + val first = LinkedBlockingQueue() + Thread({ + val code = runCatching { + guest(context, helperArgv("start", dir), hold) { line -> inspectorUrl(line)?.let { first.offer(Launch.Url(it)) } } + }.getOrDefault(-1) + first.offer(Launch.Exit(code)) + }, "curseforge-headless").apply { isDaemon = true; start() } + return first.poll(READY_MS, TimeUnit.MILLISECONDS) + } + + fun start(context: Context, app: UserApps.App, hold: AtomicBoolean): Started { + val dir = dir(app) ?: return Started(Start.FAILED) + if (hold.get()) return Started(Start.FAILED) + holds.put(dir, hold)?.takeIf { it !== hold }?.let { + it.set(true) + runCatching { lines(context, helperArgv("stop", dir)) } + } + val inspector = when (val first = launch(context, dir, hold)) { + is Launch.Url -> first.inspector + is Launch.Exit -> if (startState(first.code) == Start.BUSY) { + holds.remove(dir, hold) + return Started(Start.BUSY) + } else null + null -> null + } + if (inspector == null) { + stop(context, app, null, hold) + return Started(Start.FAILED) + } + val deadline = System.currentTimeMillis() + READY_MS + while (System.currentTimeMillis() < deadline && !hold.get()) { + if (runCatching { call(context, inspector, "InstalledProjectsAppService", "installAddon", null, 10_000) }.isSuccess) return Started(Start.READY, inspector) + Thread.sleep(1_000) + } + stop(context, app, inspector, hold) + return Started(Start.FAILED) + } + + fun stop(context: Context, app: UserApps.App, inspector: String?, hold: AtomicBoolean) { + val dir = dir(app) ?: return + if (holds[dir] !== hold) { + hold.set(true) + return + } + if (inspector != null) runCatching { call(context, inspector, "CoreService", "shutdown", JSONArray(), 30_000, "r => true") } + hold.set(true) + if (holds.remove(dir, hold)) runCatching { lines(context, helperArgv("stop", dir)) } + } + + 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 projects(context: Context, inspector: String, guid: String, rescan: Boolean = false): List { + connect(context, inspector) + if (rescan) call(context, inspector, "GameDetectionAppService", "scanGameInstance", JSONArray().put(guid), 120_000) + return parseProjects(call(context, inspector, "InstalledProjectsAppService", "getProjects", JSONArray().put(guid), 30_000, PROJECTS)) + } + + private const val PROJECTS = "r => (r || []).map(p => ({ id: String(p.id), installedModId: p.installedModId, status: p.status, " + + "locked: !!(p.installedVersion && p.installedVersion.isLocked), " + + "folders: ((p.installedVersion && p.installedVersion.addonFolders) || []).map(f => f.name) }))" + + private fun settle(context: Context, inspector: String, guid: String, done: (List) -> 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 + 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/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/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/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..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) @@ -38,7 +39,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 @@ -94,8 +94,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 = @@ -116,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)) } @@ -209,10 +210,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 +223,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 +236,56 @@ 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") } + 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 { + 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 (!offersUpdate(version, latest.summary, sameSource = true) || !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..35536449ac 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) @@ -18,10 +28,28 @@ object WowAddons { class TooLarge : IOException() + fun changed() { + imports++ + } + + fun flavorDir(target: Target): File? = target.addOns.parentFile?.parentFile + + fun root(target: Target): File? = flavorDir(target)?.parentFile + class Target(val flavor: String, val addOns: File) class Addon(val name: String, val root: String) + class Installed(val name: String, val version: String?, val wowiId: String?, val curseId: String? = null) + + class Origin(val id: String, val version: String) + + private const val ORIGINS = ".droiddeck-sources" + private const val TOC_VERSION = "Version" + private const val TOC_WOWI_ID = "X-WoWI-ID" + private const val TOC_CURSE_ID = "X-Curse-Project-ID" + private val TOC_KEYS = setOf(TOC_VERSION, TOC_WOWI_ID, TOC_CURSE_ID) + internal const val MAX_EXPANDED_BYTES = 4L * 1024 * 1024 * 1024 private val SUFFIX = Regex("[-_](standard|mainline|classic|vanilla|tbc|bcc|wrath|wotlkc|cata|mists|forever)$", RegexOption.IGNORE_CASE) @@ -45,53 +73,168 @@ 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 -> + val toc = toc(File(target.addOns, name)) + val origin = origins[name] + Installed(name, origin?.version ?: toc[TOC_VERSION], origin?.id ?: toc[TOC_WOWI_ID], toc[TOC_CURSE_ID]) + } + } + + internal fun tocFields(lines: Sequence, keys: Set = TOC_KEYS): Map { + val out = LinkedHashMap() + 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 (value.isNotEmpty() && '@' !in value) out[key] = value + if (out.size == keys.size) break + } + return out + } + + private fun toc(folder: File): Map { + 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 -> + 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/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/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/KeepTopActivity.kt b/app/src/main/java/com/droiddeck/launcher/session/KeepTopActivity.kt deleted file mode 100644 index 849c0aafcc..0000000000 --- a/app/src/main/java/com/droiddeck/launcher/session/KeepTopActivity.kt +++ /dev/null @@ -1,91 +0,0 @@ -package com.droiddeck.launcher.session - -import android.app.Activity -import android.app.ActivityOptions -import android.content.Context -import android.content.Intent -import android.hardware.display.DisplayManager -import android.os.Bundle -import android.os.SystemClock -import android.util.Log -import android.view.Display -import android.view.WindowManager - -// While a session runs, sits invisibly on top of every other display until it ends, so -// that display's home launcher is not its top activity. lmkd kills the launcher first; restarted as a -// top activity it takes focus from the session, which then drops to adj 50 and is killed next. -class KeepTopActivity : Activity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - @Suppress("DEPRECATION") overridePendingTransition(0, 0) - if (intent.getBooleanExtra(EXTRA_BOUNCE, false)) { - bounces++ - finish() - return - } - if (intent.getIntExtra(EXTRA_GENERATION, -1) != generation) { - finishAndRemoveTask() - return - } - window.addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) - val id = display?.displayId ?: Display.INVALID_DISPLAY - starting.remove(id) - guards[id]?.takeIf { it !== this && !it.isFinishing }?.finishAndRemoveTask() - guards[id] = this - } - - override fun onDestroy() { - guards.values.remove(this) - super.onDestroy() - } - - companion object { - private const val TAG = "KeepTop" - private const val EXTRA_BOUNCE = "bounce" - private const val EXTRA_GENERATION = "generation" - private var generation = 0 - var bounces = 0 - private set - private val guards = HashMap() - private const val START_TIMEOUT_MS = 2_000L - private val starting = HashMap() - - fun guardOtherDisplays(context: Context, sessionDisplay: Int): Boolean { - val displays = context.getSystemService(DisplayManager::class.java)?.displays ?: return false - var started = false - for (display in displays) { - val id = display.displayId - if (id == sessionDisplay || display.state != Display.STATE_ON || guards[id]?.isFinishing == false || - starting[id]?.let { SystemClock.elapsedRealtime() - it < START_TIMEOUT_MS } == true) continue - runCatching { - launch(context, id, bounce = false) - starting[id] = SystemClock.elapsedRealtime() - started = true - Log.i(TAG, "guarding display $id from a home launcher restart") - }.onFailure { Log.w(TAG, "could not guard display $id", it) } - } - if (!started) return false - return runCatching { launch(context, sessionDisplay, bounce = true) } - .onFailure { Log.w(TAG, "could not return focus to display $sessionDisplay", it) }.isSuccess - } - - fun hasPendingStarts() = starting.isNotEmpty() - - const val RETRY_MS = START_TIMEOUT_MS + 250 - - fun release() { - generation++ - guards.values.toList().forEach { it.finishAndRemoveTask() } - guards.clear() - starting.clear() - } - - private fun launch(context: Context, displayId: Int, bounce: Boolean) { - val intent = Intent(context, KeepTopActivity::class.java) - .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION) - .putExtra(EXTRA_BOUNCE, bounce) - .putExtra(EXTRA_GENERATION, generation) - context.startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(displayId).toBundle()) - } - } -} diff --git a/app/src/main/java/com/droiddeck/launcher/session/LightPause.kt b/app/src/main/java/com/droiddeck/launcher/session/LightPause.kt deleted file mode 100644 index 6ac1eabf9f..0000000000 --- a/app/src/main/java/com/droiddeck/launcher/session/LightPause.kt +++ /dev/null @@ -1,32 +0,0 @@ -package com.droiddeck.launcher.session - -// Tracks a pause that skipped the session's departure cleanup for the keep-top focus bounce. -internal class LightPause { - private var pending = false - private var bouncesAtPause = 0 - - fun paused(bounces: Int) { - pending = true - bouncesAtPause = bounces - } - - // The bounce resumes the session within tens of milliseconds; still paused at the timeout means - // something else holds the pause. - fun timedOut(): Boolean = take() - - fun stopped(): Boolean = take() - - fun resumed(bounces: Int): Resume { - if (!pending) return Resume.NORMAL - pending = false - return if (bounces != bouncesAtPause) Resume.LIGHT else Resume.CLEANUP_FIRST - } - - private fun take(): Boolean { - val was = pending - pending = false - return was - } - - enum class Resume { NORMAL, LIGHT, CLEANUP_FIRST } -} 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/PipPolicy.kt b/app/src/main/java/com/droiddeck/launcher/session/PipPolicy.kt index d2d4d49bd9..cef3489a37 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/PipPolicy.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/PipPolicy.kt @@ -5,6 +5,11 @@ object PipPolicy { running && frameSeen && phase in setOf(SessionPhase.READY, SessionPhase.SUSPENDED) && (!automatic || !suspended) + // A front end or shortcut that launched the game brings it back by moving its task to the + // front, which Android ignores for a task in picture in picture, and draws its resume controls + // where the picture would sit. Going home suspends the game for it instead. + fun autoEnter(enabled: Boolean, launchedByAnotherApp: Boolean): Boolean = enabled && !launchedByAnotherApp + fun aspect(width: Int, height: Int): Pair = when { width <= 0 || height <= 0 -> 16 to 9 width.toDouble() / height > 2.39 -> 239 to 100 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..919891fa45 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()) @@ -69,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/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index 53b54e9ca2..34d96eab4b 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) @@ -177,6 +180,8 @@ object SessionFiles { "usr/local/bin/droiddeck-flatpak-run" to "usr/local/bin/droiddeck-flatpak-run", "usr/local/bin/droiddeck-appimage-run" to "usr/local/bin/droiddeck-appimage-run", "usr/local/bin/droiddeck-appimage-exec" to "usr/local/bin/droiddeck-appimage-exec", + "usr/local/bin/droiddeck-curseforge" to "usr/local/bin/droiddeck-curseforge", + "usr/local/bin/droiddeck-headless" to "usr/local/bin/droiddeck-headless", "usr/local/bin/droiddeck-script-run" to "usr/local/bin/droiddeck-script-run", "usr/local/bin/droiddeck-open" to "usr/local/bin/droiddeck-open", "usr/local/bin/droiddeck-proton-run" to "usr/local/bin/droiddeck-proton-run", @@ -284,6 +289,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/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/SessionPipController.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPipController.kt index f32fe2abbf..503b8c743e 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPipController.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPipController.kt @@ -16,6 +16,7 @@ class SessionPipController( private val activity: SessionActivity, private val bounds: () -> Rect, private val showPipUi: (Boolean) -> Unit, + private val launchedByAnotherApp: () -> Boolean = { false }, ) { var transitioning = false private set @@ -29,7 +30,8 @@ class SessionPipController( PipPolicy.eligible(SessionState.running, SessionState.firstFrameSeen, SessionState.phase, SessionState.suspended, automatic) - fun automatic() = !suppressAuto && SessionPrefs.pipAutoEnter(activity) && eligible(true) + fun automatic() = !suppressAuto && PipPolicy.autoEnter(SessionPrefs.pipAutoEnter(activity), launchedByAnotherApp()) && + eligible(true) fun refresh(force: Boolean = false) { if (!supported(activity)) return 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 e7c7f5f2bf..1928588c13 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) { @@ -280,6 +286,12 @@ object SessionPrefs { prefs(context).edit().putBoolean("developerTools", on).apply() } + fun previewShortcuts(context: Context): Boolean = prefs(context).getBoolean("previewShortcuts", false) + + fun setPreviewShortcuts(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("previewShortcuts", on).apply() + } + fun fpsLimitKey(mode: String?, game: String?): String? = when (mode) { SessionService.MODE_RUN -> game?.trim()?.takeIf(com.droiddeck.launcher.frontend.GameLaunchLink::validId)?.let { "fpsLimit.game.$it" } SessionService.MODE_DESKTOP -> "fpsLimit.desktop" @@ -413,6 +425,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() } @@ -590,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) { @@ -658,12 +688,21 @@ object SessionPrefs { prefs(context).getString("shape", null) ?: if (context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle")) SHAPE_WIDE else SHAPE_AUTO - fun oscMode(context: Context): String = prefs(context).getString("osc", OSC_AUTO) ?: OSC_AUTO + fun oscMode(context: Context, steamSession: Boolean = true): String { + val saved = prefs(context).getString("osc", OSC_AUTO) ?: OSC_AUTO + return if (!steamSession && saved == OSC_STEAM_QAM) OSC_AUTO else saved + } fun setOscMode(context: Context, mode: String) { 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) @@ -820,6 +859,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) @@ -966,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() @@ -1275,14 +1320,31 @@ 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 parseOrientedResolution(value)?.let { "${it.first}x${it.second}" } ?: SessionDisplay.LINK_LANDSCAPE + } + + 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 -> - 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}" } } @@ -1294,13 +1356,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" } + val size = requireNotNull(if (portrait) parseOrientedResolution(choice) else 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 @@ -1611,10 +1682,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 @@ -1931,7 +2010,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/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index e15fac1c64..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) @@ -1025,6 +1028,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()) { @@ -1613,6 +1619,11 @@ class SessionService : Service() { return } val accepted = gameId!! + if (pendingSteamGameId == null && SteamGameProcess.alreadyRunning(accepted, SessionState.gameId)) { + Log.i(TAG, "game $accepted is already running; resuming it instead of launching it again") + if (SessionState.suspended || SessionState.suspending) resumeSession() + return + } if (!pendingSteamPreviousGamePending) { pendingSteamPreviousGameId = SessionState.gameId pendingSteamPreviousGamePending = true @@ -1943,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 @@ -2394,8 +2400,7 @@ class SessionService : Service() { override fun onTaskRemoved(rootIntent: Intent?) { if (rootIntent?.component?.className in setOf( com.droiddeck.launcher.ui.DualScreenActivity::class.java.name, - com.droiddeck.launcher.ui.SessionTypingActivity::class.java.name, - KeepTopActivity::class.java.name)) return + com.droiddeck.launcher.ui.SessionTypingActivity::class.java.name)) return if (pipTask || xrActivityVisible) { Log.i(TAG, "panel task dismissed - retaining the session under its active surface policy") activityVisible = false 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..e695f8b932 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 @@ -129,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 f85318b595..5a61619d12 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt @@ -12,13 +12,13 @@ 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", - "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", "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/session/SteamGameProcess.kt b/app/src/main/java/com/droiddeck/launcher/session/SteamGameProcess.kt index 7a00553f3b..6b7ecda60c 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SteamGameProcess.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SteamGameProcess.kt @@ -61,4 +61,11 @@ object SteamGameProcess { runCatching { File(p, "cmdline").readBytes() } .getOrNull()?.let { matches(it, gameId) } == true } == true + + // A front end that resumes a player by launching the same game again would otherwise have Steam + // start it a second time, which Steam answers with "Game already running". + fun alreadyRunning(requested: String, current: String?, proc: File = File("/proc")): Boolean { + val appId = steamAppIdForGameId(requested) ?: return false + return appId == steamAppIdForGameId(current.orEmpty()) && running(requested, proc) + } } diff --git a/app/src/main/java/com/droiddeck/launcher/session/TopUnderPressure.kt b/app/src/main/java/com/droiddeck/launcher/session/TopUnderPressure.kt deleted file mode 100644 index 3c7a55adea..0000000000 --- a/app/src/main/java/com/droiddeck/launcher/session/TopUnderPressure.kt +++ /dev/null @@ -1,13 +0,0 @@ -package com.droiddeck.launcher.session - -import android.content.ComponentCallbacks2 - -internal object TopUnderPressure { - const val WINDOW_MS = 5_000L - - fun isPressure(level: Int) = - level == ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL || level == ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW - - fun shouldReclaim(nowMs: Long, pressureAtMs: Long, sessionRunning: Boolean, finishing: Boolean) = - sessionRunning && !finishing && pressureAtMs > 0 && nowMs - pressureAtMs in 0..WINDOW_MS -} 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/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/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/stores/itch/ItchBrowse.kt b/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchBrowse.kt index d430d11434..90138c5255 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchBrowse.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchBrowse.kt @@ -129,8 +129,6 @@ internal object ItchBrowseState { private var next = 1 private var generation = 0 - val active: Boolean get() = !query.isDefault - fun choose(context: Context, wanted: BrowseQuery) { if (wanted == query) return generation++ @@ -140,11 +138,11 @@ internal object ItchBrowseState { failed = false loading = false next = 1 - if (active) more(context) + more(context) } fun more(context: Context, retry: Boolean = false) { - if (loading || ended || !active || (failed && !retry)) return + if (loading || ended || (failed && !retry)) return loading = true failed = false val app = context.applicationContext 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..df8bc0ed89 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)) @@ -358,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/AddonBrowser.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt index 89e84fe697..5251fb12bf 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt @@ -1,29 +1,33 @@ 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.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.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf @@ -33,26 +37,53 @@ 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 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.platform.LocalLifecycleOwner 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 androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import coil.compose.AsyncImage import com.droiddeck.launcher.R +import com.droiddeck.launcher.frontend.AddedGames +import com.droiddeck.launcher.runtime.CurseForgeApp +import com.droiddeck.launcher.runtime.UserApps import com.droiddeck.launcher.runtime.WowAddonCatalog import com.droiddeck.launcher.runtime.WowAddons import com.droiddeck.launcher.session.SessionState +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File +import java.io.IOException +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicReference private class AddonResults { val items = mutableStateListOf() @@ -62,8 +93,157 @@ private class AddonResults { var more by mutableStateOf(false) } +internal enum class AddonStatus { INSTALL, UPDATE, INSTALLED } + +private enum class AddonSource { WOWI, CURSE } + +internal class CurseState(val notice: Int? = null) : Exception() + +internal class CurseLink(val app: UserApps.App) { + class Linked(val inspector: String, val guid: String) + + private val lock = Object() + private val work = SupervisorJob() + @Volatile private var closed = false + @Volatile private var hold: AtomicBoolean? = null + @Volatile private var inspector: String? = null + private val guids = HashMap() + private val scanLock = Object() + private val scans = HashMap>>() + var generation by mutableIntStateOf(0) + private set + + 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 + 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 { + return block(linked) + } catch (e: CurseForgeApp.Failure) { + if (e.gone) synchronized(lock) { + if (inspector == linked.inspector) { + inspector = null + guids.clear() + current.compareAndSet(this, null) + } + } + throw e + } + } + + private fun link(context: Context, target: WowAddons.Target, launch: Boolean): Linked { + if (closed) throw CurseState() + val url = inspector ?: run { + if (!launch) throw CurseState() + val hold = AtomicBoolean(false) + this.hold = hold + if (closed) throw CurseState() + val done = CurseForgeApp.start(context, app, hold) + when (done.state) { + CurseForgeApp.Start.READY -> { + inspector = done.inspector + if (!closed) current.set(this) + done.inspector ?: throw CurseState() + } + CurseForgeApp.Start.BUSY -> throw CurseState(R.string.addons_curse_busy) + else -> throw CurseState() + } + } + if (closed) throw CurseState() + guids[target.addOns.path]?.let { return Linked(url, it) } + val root = WowAddons.root(target)?.let { AddedGames.guestPath(context, it) } ?: throw CurseState() + val flavor = WowAddons.flavorDir(target)?.let { AddedGames.guestPath(context, it) } ?: throw CurseState() + val guid = CurseForgeApp.instance(context, url, root, flavor) + guids[target.addOns.path] = guid + return Linked(url, guid) + } + + fun uninstall(context: Context, target: WowAddons.Target, folder: String): Boolean = 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 + current.compareAndSet(this, null) + val launch = hold + return CoroutineScope(work + Dispatchers.IO).launch { + if (launch != null) CurseForgeApp.stop(context, app, inspector, launch) + synchronized(lock) { + hold = null + inspector = null + } + }.also { work.complete() } + } + + companion object { + private val current = AtomicReference() + 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() + } +} + +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, 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) @@ -72,12 +252,34 @@ 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 && 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() } 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 presentKey = curse to target.addOns + val scanKey = link?.generation to WowAddons.imports + val snapshot by produceState(presentKey to Present(), target.addOns, scanKey, curse, curseInstalls, curse == null && results.items.isEmpty()) { + val into = target + val key = curse to into.addOns + if (curse != null && link != null && value.first != key) value = key to withContext(Dispatchers.IO) { Present(curse = CurseLink.lastReported(into)) } + value = key to withContext(Dispatchers.IO) { + if (curse != null && link != null) Present(curse = link.marks(context, into, scanKey)) + else Present(disk = WowAddons.details(into).associateBy { it.name.lowercase() }) + } + } + val present = snapshot.second.takeIf { snapshot.first == presentKey } ?: Present() + fun status(addon: WowAddonCatalog.Addon): AddonStatus { + if (curse != null) return if (addon.id !in present.curse) AddonStatus.INSTALL else if (present.curse[addon.id] == CURSE_UPDATE) AddonStatus.UPDATE else AddonStatus.INSTALLED + val latest = installed[installKey(addon, target)]?.takeIf { it.first == addon.summary }?.second ?: addon.summary + return diskStatus(addon.folders, present.disk, latest, addon.id) + } fun load(page: Int) { if (results.loading) return results.loading = true @@ -86,10 +288,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 } }) @@ -106,6 +314,34 @@ 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 + val updating = status(addon) == AddonStatus.UPDATE + installing[key] = 0 + scope.launch { + 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 + WowAddons.changed() + curseInstalls++ + val message = when { + ok && updating -> context.getString(R.string.user_apps_updated, addon.name) + ok -> context.resources.getQuantityString(R.plurals.main_addons_imported, 1, 1, into.flavor) + else -> (done.exceptionOrNull() as? CurseState)?.notice?.let(context::getString) + ?: context.getString(R.string.stores_dl_failed_reason, done.exceptionOrNull()?.message ?: addon.name) + } + Toast.makeText(context, message, Toast.LENGTH_LONG).show() + } + return + } if (SessionState.running) { Toast.makeText(context, R.string.main_addons_close_session, Toast.LENGTH_LONG).show() return @@ -115,48 +351,131 @@ 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)) } - } + 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 } - ChipRow { + val into = target + val via = link?.takeIf { curse != null } + installing[key] = UNINSTALLING + scope.launch { + val done = withContext(Dispatchers.IO) { + runCatching { + val folders = if (via != null) curseFolders(into, addon.id, via.call(context, into) { linked -> + CurseForgeApp.projects(context, linked.inspector, linked.guid).firstOrNull { it.id == addon.id }?.folders.orEmpty() + }) else addon.folders + deleteAddons(context, into, folders, link) + } + } + installing.remove(key) + installed.remove(key) + WowAddons.changed() + curseInstalls++ + if (done.isFailure) Toast.makeText(context, R.string.fm_delete_failed, Toast.LENGTH_LONG).show() + } + } + val sourceName = stringResource(if (curse != null) R.string.addons_source_curse else R.string.addons_source_wowi) + val 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) + } + } + 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, modifier = Modifier.releaseTextFieldOnTap()) { + 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() } } } - if (categories.isNotEmpty()) BrowseDropdown(category?.name ?: stringResource(R.string.addons_category_all)) { first, done -> + } + val sourceChip: @Composable () -> Unit = { + if (curseForge != null) BrowseDropdown(sourceName) { first, done -> + MenuItem(stringResource(R.string.addons_source_wowi), source == AddonSource.WOWI, focusRequester = first) { source = AddonSource.WOWI; done() } + MenuItem(stringResource(R.string.addons_source_curse), source == AddonSource.CURSE) { source = AddonSource.CURSE; done() } + } + } + val categoryChip: @Composable () -> Unit = { + if (curse == null && categories.isNotEmpty()) BrowseDropdown(category?.name ?: stringResource(R.string.addons_category_all)) { first, done -> 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)) + sourceChip() + 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()), + ) { + sourceChip() + 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, { uninstall(addon) }) { 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 && 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) } + } results.items.isEmpty() -> Text(stringResource(R.string.addons_none_found), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) } } @@ -166,27 +485,69 @@ internal fun AddonBrowserDialog(targets: List, initial: WowAdd } @Composable -private fun AddonCard(addon: WowAddonCatalog.Addon, progress: Int?, done: Boolean, onInstall: () -> Unit) { - 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), - ) { - 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) - } - 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), - ) +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( + 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), + ) { + 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 uninstall = stringResource(R.string.common_uninstall) + when { + progress == UNINSTALLING -> SecondaryButton(stringResource(R.string.stores_uninstalling), compact = true, modifier = lead) {} + progress != null -> SecondaryButton(stringResource(R.string.store_installing), compact = true, modifier = lead, progress = progress / 100f, onClick = onInstall) + status == AddonStatus.INSTALL -> PrimaryButton(stringResource(R.string.store_install), compact = true, modifier = lead) { act(onInstall) } + else -> { + if (status == AddonStatus.UPDATE) PrimaryButton(stringResource(R.string.common_update), compact = true, modifier = lead) { act(onInstall) } + SecondaryButton(uninstall, compact = true, modifier = if (status == AddonStatus.UPDATE) Modifier else lead) { asking = true } + } + } + } + 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 { + 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 @@ -206,21 +567,42 @@ 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() } } +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 curseFolders(target: WowAddons.Target, id: String, listed: List): 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) + 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/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/BottomDesktopPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomDesktopPanel.kt index a0033d81a7..c9e8362c4d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BottomDesktopPanel.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomDesktopPanel.kt @@ -38,6 +38,7 @@ class BottomDesktopPanel( steamButtons: Pair<() -> Unit, () -> Unit>?, onSwap: (() -> Unit)? = null, private val fullResolution: Boolean = false, + picker: (() -> ScreenPicker?)? = null, ) : LinearLayout(context), SurfaceHolder.Callback { private lateinit var surfaceView: SurfaceView private val area = FrameLayout(context).apply { clipChildren = true } @@ -67,7 +68,7 @@ class BottomDesktopPanel( setBackgroundColor(Color.BLACK) isFocusable = true isFocusableInTouchMode = true - addView(bar(onClose, onMenu, steamButtons, onSwap), LayoutParams(-1, -2)) + addView(bar(onClose, onMenu, steamButtons, onSwap, picker), LayoutParams(-1, -2)) area.addView(keyboardHost) addSurface() area.addView(status, FrameLayout.LayoutParams(-1, -1)) @@ -84,7 +85,8 @@ class BottomDesktopPanel( area.addView(surfaceView, 1, FrameLayout.LayoutParams(fullWidth.takeIf { it > 0 } ?: -1, fullHeight.takeIf { it > 0 } ?: -1)) } - private fun bar(onClose: (() -> Unit)?, onMenu: (() -> Unit)?, steamButtons: Pair<() -> Unit, () -> Unit>?, onSwap: (() -> Unit)?): View = + private fun bar(onClose: (() -> Unit)?, onMenu: (() -> Unit)?, steamButtons: Pair<() -> Unit, () -> Unit>?, onSwap: (() -> Unit)?, + picker: (() -> ScreenPicker?)?): View = bottomScreenBarView(context) { val touch = touchMode.value BottomBarModel( @@ -97,6 +99,7 @@ class BottomDesktopPanel( BarExtra(context.getString(R.string.second_show_keyboard), icon = R.drawable.ic_bottom_keyboard) { keyboardHost.toggle() }, onSwap?.let { BarExtra(context.getString(R.string.swap_screens), icon = R.drawable.ic_bottom_swap, onClick = it) }, ), + picker = picker?.invoke(), ) } 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 e4715b6a15..b6509b332d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BottomScreenBar.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomScreenBar.kt @@ -24,12 +24,24 @@ import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Close +import androidx.compose.material.icons.outlined.Dashboard +import androidx.compose.material.icons.outlined.DesktopAccessDisabled +import androidx.compose.material.icons.outlined.DesktopWindows +import androidx.compose.material.icons.outlined.ExpandLess +import androidx.compose.material.icons.outlined.ExpandMore +import androidx.compose.material.icons.outlined.Keyboard import androidx.compose.material.icons.outlined.MoreHoriz +import androidx.compose.material.icons.outlined.SportsEsports +import androidx.compose.material.icons.outlined.Terminal +import androidx.compose.material.icons.outlined.Tune import androidx.compose.material3.Icon 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.remember +import androidx.compose.runtime.setValue import androidx.compose.foundation.rememberScrollState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -49,6 +61,7 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.droiddeck.launcher.R import com.droiddeck.launcher.input.DeckPanel +import com.droiddeck.launcher.input.SecondScreenMode import com.droiddeck.launcher.session.SessionService import com.droiddeck.launcher.session.SessionState @@ -61,6 +74,15 @@ internal class BarExtra( val onClick: () -> Unit, ) +/** What the bottom screen shows: the DroidDeck menu or one of the panels, picked from the bar's dropdown. */ +class ScreenPicker( + val modes: List, + val current: SecondScreenMode, + val onPick: (SecondScreenMode) -> Unit, + val onMenu: (() -> Unit)? = null, + val menuShown: Boolean = false, +) + internal class BarTabs(val labels: List, val selected: Int, val onSelect: (Int) -> Unit) internal class BottomBarModel( @@ -72,6 +94,7 @@ internal class BottomBarModel( val extras: List = emptyList(), val menuActive: Boolean = false, val tabs: BarTabs? = null, + val picker: ScreenPicker? = null, ) @Composable @@ -89,9 +112,15 @@ internal fun BottomScreenBar(model: BottomBarModel, modifier: Modifier = Modifie private fun BarRow(model: BottomBarModel, modifier: Modifier = Modifier) { val colors = MaterialTheme.colorScheme BoxWithConstraints(modifier.fillMaxWidth().height(BAR_HEIGHT).blockTouches()) { - val buttons = listOfNotNull(model.onClose, model.onMenu, model.onQam).size + model.extras.size + val picker = model.picker + val onMenu = model.onMenu.takeIf { picker == null } + val buttons = listOfNotNull(model.onClose, onMenu, model.onQam).size + model.extras.size val steamWidth = if (model.onSteam != null) STEAM_WIDTH + BAR_GAP else 0.dp - val titleWidth = if (model.title != null) MIN_TITLE + BAR_GAP else 0.dp + val titleWidth = when { + picker != null -> PICKER_WIDTH + BAR_GAP + model.title != null -> MIN_TITLE + BAR_GAP + else -> 0.dp + } val needed = BAR_PAD * 2 + BUTTON * buttons + BAR_GAP * (buttons - 1).coerceAtLeast(0) + steamWidth + titleWidth val fits = maxWidth >= needed Row( @@ -103,7 +132,9 @@ private fun BarRow(model: BottomBarModel, modifier: Modifier = Modifier) { model.onClose?.let { BarButton(stringResource(R.string.common_close), Modifier.testTag("bottom-bar-close"), vector = Icons.Outlined.Close, onClick = it) } - if (model.title != null) Text( + if (picker != null) Box(if (fits) Modifier.weight(1f) else Modifier) { + ScreenPickerChip(picker, Modifier.testTag("bottom-bar-screen")) + } else if (model.title != null) Text( model.title, fontSize = 14.sp, fontWeight = FontWeight.Bold, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = (if (fits) Modifier.weight(1f) else Modifier).padding(start = 4.dp), @@ -112,7 +143,7 @@ private fun BarRow(model: BottomBarModel, modifier: Modifier = Modifier) { BarButton(extra.description, extra.tag?.let { Modifier.testTag(it) } ?: Modifier, icon = extra.icon, vector = extra.vector, active = extra.active, onClick = extra.onClick) } - BarActions(model.onMenu, model.menuActive, model.onSteam, model.onQam) + BarActions(onMenu, model.menuActive, model.onSteam, model.onQam) } } } @@ -197,12 +228,89 @@ 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 + SecondScreenMode.CUSTOM_CONTROLS -> Icons.Outlined.Tune + SecondScreenMode.DASHBOARD -> Icons.Outlined.Dashboard + SecondScreenMode.DESKTOP -> Icons.Outlined.DesktopWindows +} + +@Composable +internal fun ScreenPickerChip(picker: ScreenPicker, modifier: Modifier = Modifier) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + var open by remember { mutableStateOf(false) } + val source = remember { MutableInteractionSource() } + val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value + val shape = RoundedCornerShape(22.dp) + val label = if (picker.menuShown) stringResource(R.string.touch_droiddeck_menu) else stringResource(picker.current.label) + val description = stringResource(R.string.screen_picker_description, label) + val toggle = { open = !open } + Box(modifier) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier.height(44.dp).widthIn(max = PICKER_MAX_WIDTH) + .semantics { contentDescription = description } + .clip(shape).background(if (hot || open) pal.signal.copy(alpha = 0.14f) else colors.surfaceVariant) + .glideBorder(hot || open, shape, pal.signal, pal.line2) + .hoverable(source) + .clickable(role = Role.Button, interactionSource = source, indication = LocalIndication.current, onClick = toggle) + .controllerConfirm(onClick = toggle) + .padding(start = 14.dp, end = 10.dp), + ) { + if (picker.menuShown) Icon(painterResource(R.drawable.ic_stat_session), contentDescription = null, tint = colors.onBackground, + modifier = Modifier.size(18.dp)) + else Icon(picker.current.icon, contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(18.dp)) + Text(label, fontSize = 14.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, + overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false)) + Icon(if (open) Icons.Outlined.ExpandLess else Icons.Outlined.ExpandMore, contentDescription = null, + tint = colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) + } + ScreenPickerMenu(picker, open) { open = false } + } +} + +/** On a panel, focus starts on the menu entry; from the menu (or with no menu entry), on the panel in use. */ +internal fun ScreenPicker.focusTarget(): SecondScreenMode? = + if (onMenu != null && !menuShown) null else current.takeIf { it in modes } ?: modes.firstOrNull() + +@Composable +private fun ScreenPickerMenu(picker: ScreenPicker, open: Boolean, dismiss: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val target = picker.focusTarget() + AnchoredMenu(open, dismiss, compact = true, minWidth = 240.dp) { first -> + picker.onMenu?.let { menu -> + MenuItem( + stringResource(R.string.touch_droiddeck_menu), checked = picker.menuShown, + 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() } + } + picker.modes.forEach { mode -> + val current = mode == picker.current + MenuItem( + stringResource(mode.label), checked = current && !picker.menuShown, + 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) } + } + } +} + internal val BAR_HEIGHT = 64.dp private val BAR_PAD = 12.dp private val BAR_GAP = 8.dp private val BUTTON = 44.dp private val STEAM_WIDTH = 80.dp private val MIN_TITLE = 72.dp +private val PICKER_WIDTH = 180.dp +private val PICKER_MAX_WIDTH = 240.dp internal fun sessionBarModel( title: String?, @@ -212,9 +320,10 @@ internal fun sessionBarModel( onQam: () -> Unit, extras: List = emptyList(), tabs: BarTabs? = null, + picker: ScreenPicker? = null, ): BottomBarModel { val steam = SessionState.mode == SessionService.MODE_STEAM - return BottomBarModel(title, onClose, onMenu, onSteam.takeIf { steam }, onQam.takeIf { steam }, extras, tabs = tabs) + return BottomBarModel(title, onClose, onMenu, onSteam.takeIf { steam }, onQam.takeIf { steam }, extras, tabs = tabs, picker = picker) } internal fun deckPanelTabs(context: Context, selected: DeckPanel, onSelect: (DeckPanel) -> Unit) = 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..73073cdf8f 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, @@ -1625,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/ControllerHaptics.kt b/app/src/main/java/com/droiddeck/launcher/ui/ControllerHaptics.kt new file mode 100644 index 0000000000..da1d8d4bb4 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/ControllerHaptics.kt @@ -0,0 +1,42 @@ +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, + KeyEvent.KEYCODE_BUTTON_L2, KeyEvent.KEYCODE_BUTTON_R2, + ) + + 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/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/DevPreview.kt b/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt new file mode 100644 index 0000000000..21057d1dea --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt @@ -0,0 +1,268 @@ +package com.droiddeck.launcher.ui + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.outlined.Science +import androidx.compose.material.icons.outlined.Visibility +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.layout.boundsInRoot +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.material3.Icon +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.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.onKeyEvent +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.key.type +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.droiddeck.launcher.R +import com.droiddeck.launcher.gpu.FrameGen +import com.droiddeck.launcher.gpu.Lossless +import com.droiddeck.launcher.input.SecondScreenDisplay +import com.droiddeck.launcher.input.SecondScreenMode +import com.droiddeck.launcher.session.SessionPrefs +import com.droiddeck.launcher.stores.CatalogItem +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoresState + +/** What the Library pretends while a developer previews it. Nothing here is saved: a restart always comes back to [OFF]. */ +internal enum class LibraryPreview { OFF, NOTHING_INSTALLED, SIGNED_OUT, SAMPLE } + +internal enum class DrawerPreview { STEAM, DESKTOP, GAME } + +/** Developer tools' preview states: screens that are otherwise hard to reach, shown without changing anything real. */ +internal object DevPreview { + var library by mutableStateOf(LibraryPreview.OFF) + var drawer by mutableStateOf(null) + /** The UI zoo sheet: where previews are picked, one at a time, only when asked for. */ + var zoo by mutableStateOf(false) + /** Opt-in: a preview button where its state lives (the Library's toolbar), for switching states without the zoo. */ + var shortcuts by mutableStateOf(false) + + fun setShortcuts(context: android.content.Context, on: Boolean) { + shortcuts = on + SessionPrefs.setPreviewShortcuts(context, on) + } + + /** Set when a Library preview is picked, so the launcher switches to the Library to show it. */ + var openLibrary by mutableStateOf(false) +} + +/** How many of each store's sample games look installed. */ +private const val SAMPLE_INSTALLED = 3 + +/** A store's storefront games, passed off as owned, for the sample library. Empty until the store's shelves have loaded. */ +internal fun sampleOwned(store: Store): List = + StoresState.shelves[store]?.all.orEmpty().filter { !it.mature }.distinctBy { it.id }.take(24).map { it.copy(owned = true) } + +internal fun sampleInstalled(owned: Map>): Set = + owned.values.flatMap { items -> items.take(SAMPLE_INSTALLED).map { it.key } }.toSet() + +/** The pill a previewed Library shows, so the fake state is never mistaken for the real one. */ +@Composable +internal fun LibraryPreviewPill(modifier: Modifier = Modifier) { + val preview = DevPreview.library + if (preview == LibraryPreview.OFF) return + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val label = stringResource( + when (preview) { + LibraryPreview.NOTHING_INSTALLED -> R.string.dev_preview_library_nothing_installed + LibraryPreview.SIGNED_OUT -> R.string.dev_preview_library_signed_out + else -> R.string.dev_preview_library_sample + }, + ) + val end = stringResource(R.string.dev_preview_end) + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), + modifier = modifier.background(colors.surface, CircleShape).border(1.dp, pal.signal, CircleShape) + .clickable(role = Role.Button, onClickLabel = end) { DevPreview.library = LibraryPreview.OFF } + .padding(start = 14.dp, end = 10.dp, top = 8.dp, bottom = 8.dp).testTag("dev-preview-end"), + ) { + Icon(Icons.Outlined.Visibility, null, tint = pal.signal, modifier = Modifier.size(18.dp)) + Text(stringResource(R.string.dev_preview_banner, label), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground) + Icon(Icons.Filled.Close, end, tint = colors.onSurfaceVariant, modifier = Modifier.size(18.dp)) + } +} + +/** + * The in-game menu over the launcher, for looking at without starting a session. Its switches change only this preview: nothing + * is saved and no session is told. Back or Close ends it. + */ +@Composable +internal fun SessionDrawerPreview(secondScreens: List) { + val mode = DevPreview.drawer ?: return + val ctx = LocalContext.current + val close = { DevPreview.drawer = null } + var page by remember { mutableStateOf(SessionDrawerPage.CONTROLLER) } + // A session's activity routes these keys to its menu; the launcher has no such routing, so the preview does it. + var layerOpen by remember { mutableStateOf(false) } + var backRequests by remember { mutableStateOf(0) } + val back = { if (layerOpen) backRequests++ else close() } + BackHandler { back() } + var hud by remember { mutableStateOf(SessionPrefs.hudEnabled(ctx)) } + var touch by remember { mutableStateOf(SessionPrefs.touchMode(ctx)) } + var osc by remember { mutableStateOf(SessionPrefs.oscMode(ctx)) } + var fex by remember { mutableStateOf(SessionPrefs.fexPreset(ctx)) } + var inverted by remember { mutableStateOf(SessionPrefs.backActionsInverted(ctx)) } + var suspend by remember { mutableStateOf(SessionPrefs.SUSPEND_MANUAL) } + var frameGen by remember { mutableStateOf(FrameGen.Mode.OFF) } + var second by remember { mutableStateOf(SecondScreenMode.NONE) } + var fps by remember { mutableStateOf(0) } + val steam = mode == DrawerPreview.STEAM + val actions = DrawerActions( + steam = steam, + desktop = mode == DrawerPreview.DESKTOP, + title = if (mode == DrawerPreview.GAME) stringResource(R.string.session_title_game) else null, + isHomeApp = false, + androidApps = emptyList(), + hudOn = hud, onHud = { hud = it }, + frameGen = frameGen, onFrameGenPick = { frameGen = it }, + lossless = Lossless.State.NONE, + oscMode = osc, onOsc = { osc = it }, + suspendPolicy = suspend, onSuspendPolicy = { suspend = it }, + backActionsInverted = inverted, onBackActionsInverted = { inverted = it }, + touchMode = touch, onTouch = { touch = it }, + touchAuto = stringResource(R.string.session_touch_auto_direct), + fexPreset = fex, onFexPreset = { fex = it }, + fpsLimit = fps, onFpsLimit = { fps = it }, + secondScreenMode = second, onSecondScreenMode = { second = it }, + secondScreenDisplays = secondScreens, + selectedSecondScreenDisplay = secondScreens.firstOrNull()?.id ?: -1, + onSecondScreenDisplay = {}, + onImportLossless = {}, + onKeyboard = {}, onHardwareKeyboard = {}, + onSteamMenu = if (steam) ({}) else null, + onQam = if (steam) ({}) else null, + onLaunchAndroidApp = { _, _ -> }, + onBackground = close, + onShareLogs = {}, + onStop = close, + onClose = close, + ) + Box( + Modifier.fillMaxSize().testTag("dev-preview-drawer") + .onPreviewKeyEvent { e -> + 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) + } + true + } + .onKeyEvent { e -> + if (e.nativeKeyEvent.keyCode != android.view.KeyEvent.KEYCODE_BUTTON_B) return@onKeyEvent false + if (e.type == KeyEventType.KeyDown && e.nativeKeyEvent.repeatCount == 0) back() + true + } + .background(Brush.linearGradient(listOf(Color(0xFF1B2A3A), Color(0xFF0B0F14), Color(0xFF2A1B2E)))), + ) { + Text( + stringResource(R.string.dev_preview_drawer_backdrop), fontSize = 13.sp, color = Color.White.copy(alpha = 0.5f), + modifier = Modifier.align(Alignment.BottomStart).padding(24.dp), + ) + SessionDrawer( + true, page, controllerActive = true, onPageChange = { page = it }, a = actions, + backRequest = backRequests, onLayerChange = { layerOpen = it }, + ) + } +} + +/** Developer tools' UI zoo: a sheet listing the previews. Nothing shows until one is picked, and picking one closes the sheet. */ +@Composable +internal fun UiZooSheet() { + val close = { DevPreview.zoo = false } + SideSheet(DevPreview.zoo, onClose = close, returnFocus = null, tag = "ui-zoo-sheet") { + PageHeader(stringResource(R.string.dev_ui_zoo)) { + androidx.compose.foundation.layout.Spacer(Modifier.weight(1f)) + SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = MaterialTheme.colorScheme.onSurfaceVariant) { close() } + } + androidx.compose.foundation.layout.Column(Modifier.weight(1f).verticalScroll(rememberScrollState())) { + val show = stringResource(R.string.dev_ui_zoo_show) + SettingsGroup(stringResource(R.string.dev_preview_drawer)) { + for ((mode, label) in listOf( + DrawerPreview.STEAM to R.string.source_steam, + DrawerPreview.DESKTOP to R.string.rail_desktop, + DrawerPreview.GAME to R.string.session_title_game, + )) ActionRow(stringResource(label), null, show, onClick = { close(); DevPreview.drawer = mode }, modifier = Modifier.testTag("zoo-drawer-${mode.name.lowercase()}")) + } + SettingsGroup(stringResource(R.string.dev_preview_library)) { + for ((mode, label) in listOf( + LibraryPreview.NOTHING_INSTALLED to R.string.dev_preview_library_nothing_installed, + LibraryPreview.SIGNED_OUT to R.string.dev_preview_library_signed_out, + LibraryPreview.SAMPLE to R.string.dev_preview_library_sample, + )) ActionRow( + stringResource(label), null, show, + onClick = { close(); DevPreview.library = mode; DevPreview.openLibrary = true }, + modifier = Modifier.testTag("zoo-library-${mode.name.lowercase()}"), + ) + } + Text( + stringResource(R.string.dev_ui_zoo_note), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp), + ) + } + } +} + +/** The Library toolbar's preview button, shown only with preview shortcuts on: picks the Library state in place. */ +@Composable +internal fun LibraryPreviewButton() { + val pal = LocalPalette.current + val title = stringResource(R.string.dev_preview_library) + var at by remember { mutableStateOf(null) } + val states = listOf( + LibraryPreview.OFF to R.string.dev_preview_real, + LibraryPreview.NOTHING_INSTALLED to R.string.dev_preview_library_nothing_installed, + LibraryPreview.SIGNED_OUT to R.string.dev_preview_library_signed_out, + LibraryPreview.SAMPLE to R.string.dev_preview_library_sample, + ) + Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }) { + HeaderIconButton(stringResource(R.string.dev_preview_shortcut), Icons.Outlined.Science, "library-preview") { + val from = at ?: return@HeaderIconButton + Steps.ask(StepAsk( + anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = states.size, + handle = { Icon(Icons.Outlined.Science, null, tint = pal.signal, modifier = Modifier.size(18.dp)) }, + ) { + StepTitle(title) + StepList { + states.forEachIndexed { i, (state, label) -> + StepChoice( + stringResource(label), selected = DevPreview.library == state, enabled = open, + modifier = Modifier.fillMaxWidth().stepItem(i).let { if (i == 0) it.focusRequester(first) else it }, + ) { DevPreview.library = state; Steps.fold() } + } + } + }) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/EmptyLibrary.kt b/app/src/main/java/com/droiddeck/launcher/ui/EmptyLibrary.kt index 4b8de6520f..192afbece1 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/EmptyLibrary.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/EmptyLibrary.kt @@ -33,7 +33,9 @@ import androidx.compose.ui.graphics.drawscope.translate import androidx.compose.ui.graphics.lerp import androidx.compose.ui.hapticfeedback.HapticFeedbackType import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.layout.positionInRoot import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalHapticFeedback import androidx.compose.ui.unit.dp @@ -47,21 +49,30 @@ import kotlin.math.sin @Composable internal fun EmptyLibrary(avoid: Rect?, wall: (@Composable () -> 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/FrontEndContent.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt index 47c667a634..1dcf36d9ba 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt @@ -289,6 +289,7 @@ private fun Content( if (selected == "games" || selected.startsWith("app:") || selected == "soundtracks" || selected.startsWith("sound:")) { Box(modifier) { LibraryPage(s, a, selected, onSelect, Modifier.fillMaxSize()) + if (selected == "games") LibraryPreviewPill(Modifier.align(androidx.compose.ui.Alignment.BottomCenter).padding(bottom = 20.dp)) ManageStoresSheet() } return @@ -480,7 +481,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)) { @@ -517,7 +518,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, ) @@ -529,7 +532,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/FrontEndRail.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt index 4f6f49248a..09bb9b88e8 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.filled.Toys import androidx.compose.material.icons.automirrored.outlined.ArrowBack import androidx.compose.ui.graphics.vector.ImageVector @@ -210,7 +209,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 ef414c4eb0..c2f49c2ef2 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 = {}, @@ -452,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) { @@ -650,6 +653,12 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com LaunchedEffect(SetupTabs.openSection) { if (SetupTabs.openSection != null && (railSelection != "setup" || s.pageKey != null)) showRailPage("setup", true) } + LaunchedEffect(DevPreview.openLibrary) { + if (!DevPreview.openLibrary) return@LaunchedEffect + DevPreview.openLibrary = false + LibraryView.source = LIBRARY_ALL + showRailPage("games", true) + } val onRailFocus: (String) -> Unit = { key -> if (key != railSelection) showRailPage(key, false) } @@ -753,24 +762,28 @@ 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 } } val agentKeyboardOpen = openTab == "agent" && WindowInsets.ime.getBottom(androidx.compose.ui.platform.LocalDensity.current) > 0 LauncherLayout( bottomNavigation && !s.dualScreen, pal.line, Modifier.fillMaxSize().onGloballyPositioned { screenAt = it.positionInRoot() } - .then(if (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) @@ -779,7 +792,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 -> @@ -806,6 +819,8 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com com.droiddeck.launcher.stores.StoresState.itchPicking?.let { item -> StoreTheme(item.store) { ItchBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.itchPicking = null } } } com.droiddeck.launcher.stores.StoresState.gameJoltPicking?.let { item -> StoreTheme(item.store) { GameJoltBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.gameJoltPicking = null } } } StepsLayer(screenAt) + UiZooSheet() + SessionDrawerPreview(s.secondScreenDisplays) appToChooseDisplay?.let { app -> val secondaryDisplay = s.secondScreenDisplays.firstOrNull() @@ -876,7 +891,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com (selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:") || selected == "store")) val exitArmed = !processSettingsPageVisible && !hasBackTarget LaunchedEffect(exitArmed, selected) { ExitGesture.reset() } - BackHandler(enabled = exitArmed) { + BackHandler(enabled = exitArmed && DevPreview.drawer == null) { when (ExitGesture.back()) { 2 -> android.widget.Toast.makeText(ctx, R.string.exit_hint_back, android.widget.Toast.LENGTH_SHORT).show() 3 -> { @@ -890,3 +905,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com } } } + +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 8815ea43ac..70c49a5518 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -59,6 +59,7 @@ 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.platform.testTag import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.res.stringResource @@ -515,6 +516,18 @@ 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), + 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), @@ -595,6 +608,14 @@ internal fun SetupPanel( ToggleRow(host, "developer-tools", stringResource(R.string.dev_tools_title), stringResource(R.string.dev_tools_hint), DeveloperTools.on) { DeveloperTools.set(devContext, it) } + if (DeveloperTools.on) ActionRow( + stringResource(R.string.dev_ui_zoo), stringResource(R.string.dev_ui_zoo_hint), stringResource(R.string.dev_ui_zoo_open), + onClick = { DevPreview.zoo = true }, modifier = Modifier.testTag("dev-ui-zoo"), + ) + if (DeveloperTools.on) ToggleRow( + host, "preview-shortcuts", stringResource(R.string.dev_preview_shortcuts), stringResource(R.string.dev_preview_shortcuts_hint), + DevPreview.shortcuts, + ) { DevPreview.setShortcuts(devContext, it) } } SettingsGroup(stringResource(R.string.dev_group_logs)) { ToggleRow(host, "logs", stringResource(R.string.setup_logs), stringResource(R.string.setup_logs_hint), s.logsEnabled) { a.onLogs() } @@ -1145,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/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 3b93f06527..5f9d6d0ebc 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 @@ -73,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 @@ -94,7 +97,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 @@ -125,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 { @@ -248,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) @@ -271,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, s.sessionRunning, 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) } } } @@ -342,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)) } } } @@ -361,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, @@ -427,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 } @@ -442,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) } } @@ -956,13 +1047,26 @@ 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) { 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 -> - 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) } + } + 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 } @@ -974,23 +1078,100 @@ 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, link?.let { l -> managed[item.name.lowercase()]?.let { it to l } }) } } } } } @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 +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 + 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)) - if (!SessionState.running) IconAction(Icons.Outlined.Delete, delete, "addon:delete:${target.flavor}:$name", danger = true) { asking = true } + Column(Modifier.weight(1f)) { + Text(name, fontSize = 14.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + val detail = listOfNotNull(item.version, if (outdated) stringResource(R.string.upd_available) else null).joinToString(" · ") + if (detail.isNotEmpty()) Text( + progress?.let { stringResource(R.string.ctrl_percent, it) } ?: detail, fontSize = 12.sp, + color = if (outdated) LocalPalette.current.signal else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, + ) + } + 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) { + 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 + if (message != null) android.widget.Toast.makeText(context, message, android.widget.Toast.LENGTH_LONG).show() + } + } + if (!SessionState.running) IconAction(Icons.Outlined.Delete, if (curse != null) stringResource(R.string.common_uninstall) else delete, "addon:delete:${target.flavor}:$name", danger = true) { asking = true } } if (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/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/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 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) 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 (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, 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, @@ -286,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/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt index 5b94225115..8f8e592cd2 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,21 +85,28 @@ 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) 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 -> (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 +116,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 +148,65 @@ 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 } } + 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) + + 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 +225,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 +249,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 +308,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 +328,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 +336,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,11 +354,13 @@ 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.onChange = { e -> if (!draft.properties) draft.elements = draft.elements.map { if (it.id == e.id) e else it } } + 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 = { changed -> if (!draft.properties) changed.associateBy { it.id }.let { byId -> draft.elements = draft.elements.map { byId[it.id] ?: it } } } }) } @@ -283,7 +373,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,15 +423,15 @@ 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)) } 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) } + 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) @@ -352,9 +443,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 1e21a245de..301747dc18 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt @@ -5,14 +5,20 @@ 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 +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 @@ -22,9 +28,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 @@ -33,11 +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 @@ -50,16 +63,39 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { addView(preview, LayoutParams(-1, -1)) } + private fun updatePreviewStyle() { + 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) { @@ -67,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 @@ -85,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 @@ -93,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) } @@ -107,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/InputSurfaceView.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt index 0058224c01..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,6 +57,10 @@ class InputSurfaceView( private val elementSources = ArrayList() private var customCanvas: ViewGroup? = null private val owners = HashMap() + 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) } @@ -134,12 +139,16 @@ class InputSurfaceView( } } - fun updateStyle(style: InputSurfaceStyle) { - if (surfaceStyle == style) 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.artwork = artwork 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 +182,7 @@ class InputSurfaceView( } private fun renderCustom(pad: PadBridge?) { + artworkDpad = emptyList() val canvas = object : ViewGroup(context) { override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val layout = customLayout @@ -190,6 +200,21 @@ class InputSurfaceView( val x = (width * e.x).toInt(); val y = (height * e.y).toInt() child.layout(x, y, x + child.measuredWidth, y + child.measuredHeight) } + updateArtworkDpad(this) + } + + override fun dispatchDraw(canvas: Canvas) { + 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(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) } } canvas.clipChildren = customLayout.none { it.kind == InputElementKind.STICK && (classic(it) || adaptive(it)) } @@ -197,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, 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() } }) @@ -206,6 +232,34 @@ class InputSurfaceView( customCanvas = canvas } + private fun updateArtworkDpad(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 + } + 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 + 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 false + artworkDpadBounds.set(left.left.toFloat(), up.top.toFloat(), right.right.toFloat(), down.bottom.toFloat()) + return true + } + override fun onAttachedToWindow() { super.onAttachedToWindow() if (pad != null && elementSources.isEmpty()) { @@ -344,9 +398,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) + 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) { + art.system(canvas, width.toFloat(), height.toFloat(), PadArt.Shape.ROUND, PadArt.Icon.KEYBOARD, 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 labelPaint.color = if (classic && tint != null) textColor(lit) else if (lit) ACCENT else TEXT @@ -364,7 +429,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,10 +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 (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 @@ -421,18 +488,22 @@ class InputSurfaceView( private val glow = Paint(Paint.ANTI_ALIAS_FLAG) override fun onDraw(canvas: Canvas) { + if (!captioned || stock && artwork?.steam == true) { + art.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 +605,18 @@ class InputSurfaceView( if (hideWhenIdle && !touching) return val cx = if (touching) originX else centreX() val cy = if (touching) originY else height / 2f + val kit = artwork + if (kit != null && classic(element)) { + val radius = min(width, height) / 2f - 2f * density + if (radius > 0f) { + 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) + } + 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/LibraryHidden.kt b/app/src/main/java/com/droiddeck/launcher/ui/LibraryHidden.kt index a0fb74ef6f..c50a6c8978 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LibraryHidden.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LibraryHidden.kt @@ -17,6 +17,7 @@ import com.droiddeck.launcher.frontend.SteamHidden import com.droiddeck.launcher.session.SessionPrefs internal const val LIBRARY_HIDDEN = "hidden" +internal val HIDDEN_DOT = androidx.compose.ui.graphics.Color(0xFF9AA0A6) internal object LibraryHidden { var keys by mutableStateOf>(emptySet()) 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 dab63bec1b..e940e7b47f 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 @@ -177,15 +178,15 @@ internal fun installedFirst(entries: List): List = e internal const val LIBRARY_ALL = "all" internal fun librarySources( entries: List, order: List, always: Set = emptySet(), favorites: Set = emptySet(), - hidden: (LibraryEntry) -> Boolean = { false }, showHidden: Boolean = false, offStores: Set = emptySet(), - places: List> = DEFAULT_LIBRARY_PLACES, offTabs: Set = emptySet(), + hidden: (LibraryEntry) -> Boolean = { false }, offStores: Set = emptySet(), + places: List> = DEFAULT_LIBRARY_PLACES, offTabs: Set = setOf(LIBRARY_HIDDEN), ): List { val tabs = arrangeStoreTabs(order, offStores) val shown = tabs.filter { it.shown }.map { it.store.id }.toSet() + LIBRARY_OWN_TABS - offTabs - return (placeLibraryTabs(tabs.map { it.store.id }, places).filter { it in shown } + Library.SOURCE_COLLECTION + LIBRARY_HIDDEN) + return (placeLibraryTabs(tabs.map { it.store.id }, places).filter { it in shown } + Library.SOURCE_COLLECTION) .filter { source -> when (source) { - LIBRARY_HIDDEN -> showHidden + LIBRARY_HIDDEN -> true LIBRARY_FAVORITES -> entries.any { it.favoriteKey in favorites && !hidden(it) } else -> source in always || entries.any { it.source == source && !hidden(it) } } @@ -201,14 +202,11 @@ internal object LibraryDisplay { private set var size by mutableStateOf(true) private set - var hidden by mutableStateOf(false) - private set fun load(context: android.content.Context) { level = SessionPrefs.libraryCardLevel(context).coerceIn(0, scales.lastIndex) title = SessionPrefs.libraryShowTitle(context) size = SessionPrefs.libraryShowSize(context) - hidden = SessionPrefs.libraryShowHidden(context) } fun step(context: android.content.Context, by: Int) { @@ -225,11 +223,6 @@ internal object LibraryDisplay { size = !size SessionPrefs.setLibraryShowSize(context, size) } - - fun toggleHidden(context: android.content.Context) { - hidden = !hidden - SessionPrefs.setLibraryShowHidden(context, hidden) - } } private enum class ToggleAt { NONE, TOP, SPLIT, BOTTOM } @@ -326,20 +319,33 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, val favorites = if (soundMode) emptySet() else LibraryFavorites.keys val concealed: (LibraryEntry) -> Boolean = { !soundMode && LibraryHidden.isHidden(it) } val stores = !s.shortcutPicker && !soundMode - val signedIn = Store.entries.filter { StoresState.isSignedIn(it) } - LaunchedEffect(stores, signedIn) { if (stores) signedIn.forEach { StoresState.loadLibrary(ctx, it) } } - val owned = if (stores) signedIn.associateWith { StoresState.library[it].orEmpty() } else emptyMap() - val installedStore = StoresState.installed.map { it.key }.toSet() - val syncing = if (stores) signedIn.mapNotNull { st -> StoresState.status[st]?.let { st to it } } else emptyList() + val preview = if (stores) DevPreview.library else LibraryPreview.OFF + val signedIn = when (preview) { + LibraryPreview.SAMPLE -> Store.entries.filter { StoresState.backend(it) != null } + LibraryPreview.SIGNED_OUT -> emptyList() + else -> Store.entries.filter { StoresState.isSignedIn(it) } + } + LaunchedEffect(stores, signedIn, preview) { + if (stores) signedIn.forEach { if (preview == LibraryPreview.SAMPLE) StoresState.preview(ctx, it) else StoresState.loadLibrary(ctx, it) } + } + val owned = when { + !stores -> emptyMap() + preview == LibraryPreview.SAMPLE -> signedIn.associateWith { sampleOwned(it) } + else -> signedIn.associateWith { StoresState.library[it].orEmpty() } + } + val reallyInstalled = StoresState.installed.map { it.key }.toSet() + val installedStore = reallyInstalled + if (preview == LibraryPreview.SAMPLE) sampleInstalled(owned) else emptySet() + val syncing = if (stores && preview == LibraryPreview.OFF) signedIn.mapNotNull { st -> StoresState.status[st]?.let { st to it } } else emptyList() val cloudRows = rememberXboxCloudRows(s) remember { SoundtrackCollections.load(ctx) } val savedSnapshot = SoundtrackCollections.snapshot val favoritesLabel = stringResource(R.string.soundtracks_favorites) - val all = remember(soundMode, s.steamGames, s.soundtracks, s.soundtracksEnabled, cloudRows, owned, installedStore, savedSnapshot, favoritesLabel) { + val all = remember(soundMode, s.steamGames, s.soundtracks, s.soundtracksEnabled, cloudRows, owned, installedStore, savedSnapshot, favoritesLabel, preview) { if (soundMode) s.soundtracks.map { LibraryEntry("sound:${it.appId}", it.source, it.name, it, null, true) } + (if (s.soundtracks.isEmpty() && savedSnapshot.favorites.isEmpty() && savedSnapshot.collections.isEmpty()) emptyList() else SoundtrackCollections.games(ctx, favoritesLabel, skipEmptyFavorites = true)) .map { LibraryEntry("sound:${it.appId}", it.source, it.name, it, null, true) } else libraryEntries(s.steamGames + cloudRows + if (s.soundtracksEnabled) emptyList() else s.soundtracks.filter { it.library != Library.ADDED }, owned, installedStore) + .let { rows -> if (preview == LibraryPreview.NOTHING_INSTALLED) rows.map { LibraryEntry(it.key, it.source, it.title, it.game, it.item, false) } else rows } } var addingSoundtrack by remember { mutableStateOf(false) } LaunchedEffect(Unit) { XboxLibraryFilter.load(ctx) } @@ -361,16 +367,16 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, val gameJoltSignedIn = owned.containsKey(Store.GAMEJOLT) remember { StoreTabsState.load(ctx) } val storeTabs = StoreTabsState.tabs - val signInChips = if (!stores || !StoresState.accountsLoaded) emptySet() else storeTabs - .filter { it.shown && StoresState.backend(it.store) != null && storeAccount(it.store) != StoreAccount.SIGNED_IN } + val signInChips = if (!stores || !StoresState.accountsLoaded || preview == LibraryPreview.SAMPLE) emptySet() else storeTabs + .filter { it.shown && StoresState.backend(it.store) != null && (preview == LibraryPreview.SIGNED_OUT || storeAccount(it.store) != StoreAccount.SIGNED_IN) } .map { it.store.id }.toSet() val sources = librarySources( all, storeTabs.map { it.store.id }, listOfNotNull(Store.ITCH.id.takeIf { itchSignedIn && !soundMode }, Store.GAMEJOLT.id.takeIf { gameJoltSignedIn && !soundMode }, Library.ADDED.takeIf { stores }).toSet() + signInChips, - favorites, concealed, LibraryDisplay.hidden && !soundMode, + favorites, concealed, offStores = if (soundMode) emptySet() else storeTabs.filterNot { it.shown }.map { it.store.id }.toSet(), places = if (soundMode) DEFAULT_LIBRARY_PLACES else StoreTabsState.libraryPlaces, - offTabs = if (soundMode) emptySet() else StoreTabsState.libraryHidden, + offTabs = if (soundMode) setOf(LIBRARY_HIDDEN) else StoreTabsState.libraryHidden, ) val source = LibraryView.source.takeIf { it == LIBRARY_ALL || it in sources } ?: LIBRARY_ALL val q = LibraryView.query.trim().lowercase() @@ -429,7 +435,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, fun sizeOf(e: LibraryEntry): Long? { val key = e.storeKey return when { - key != null && key in installedStore -> StoreSizes.onDisk[key] + key != null && e.installed && key in installedStore -> StoreSizes.onDisk[key] e.game?.gameFiles != null -> FolderSizes.known[e.game.gameFiles.path] e.item != null -> StoreSizes.size(e.item).takeIf { it > 0 } else -> 0L @@ -450,7 +456,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, var sizesWaited by remember(sizeSort) { mutableStateOf(false) } LaunchedEffect(sizeSort) { if (sizeSort) { kotlinx.coroutines.delay(8_000); sizesWaited = true } } fun sizeComing(e: LibraryEntry): Boolean = when { - e.storeKey != null && e.storeKey in installedStore -> true + e.storeKey != null && e.storeKey in installedStore -> e.storeKey in reallyInstalled // a sample install has no size to wait for e.game?.gameFiles != null -> true e.item != null -> StoreSizes.coming(e.item) else -> false @@ -545,7 +551,11 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, LibraryView.source = ids[(ids.indexOf(source).coerceAtLeast(0) + step + ids.size) % ids.size] cycled++ }, - onOpen = { focusManager.clearFocus(force = true); onSelect(it) }, + onOpen = { + // A preview is read-only: a game's page would act on the real install behind the pretend one. + if (preview != LibraryPreview.OFF) android.widget.Toast.makeText(ctx, R.string.dev_preview_read_only, android.widget.Toast.LENGTH_SHORT).show() + else { focusManager.clearFocus(force = true); onSelect(it) } + }, searchCleared = open != null, onFocus = { gridFocused = it }, soundMode = soundMode, @@ -560,7 +570,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, onCollections = { savedDialog = true }, trackHits = shownHits, onPlayHit = playHit, // An expired account keeps showing its cached games; with none cached it asks to sign in again, like a signed-out store. - signInStore = Store.byId(source)?.takeIf { st -> st.id in signInChips && (storeAccount(st) != StoreAccount.EXPIRED || all.none { it.source == st.id }) }, + signInStore = Store.byId(source)?.takeIf { st -> st.id in signInChips && (preview == LibraryPreview.SIGNED_OUT || storeAccount(st) != StoreAccount.EXPIRED || all.none { it.source == st.id }) }, ) } }, ) { key -> @@ -774,7 +784,7 @@ private fun LibraryGrid( Box(Modifier.padding(top = 4.dp, bottom = 16.dp)) { CustomGamesCard(splashHeight, art) } } else if (signInStore != null) item(key = "sign-in:${signInStore.id}", span = { GridItemSpan(maxLineSpan) }) { - StoreTheme(signInStore) { Box(Modifier.padding(top = 4.dp, bottom = 16.dp)) { SignInCard(signInStore, splashHeight) } } + StoreTheme(signInStore) { Box(Modifier.padding(top = 4.dp, bottom = 16.dp)) { SignInCard(signInStore, splashHeight, inert = DevPreview.library != LibraryPreview.OFF) } } } else if (split == 0) { if (toggleAt == ToggleAt.TOP) item(key = NOT_INSTALLED_ROW, span = { GridItemSpan(maxLineSpan) }) { toggleRow() } @@ -871,13 +881,15 @@ private fun LibraryHeader( lead = soundLead, ) { if (soundMode) HeaderIconButton(stringResource(R.string.soundtracks_saved), Icons.Filled.BookmarkBorder, "collections", onClick = onCollections) + if (!soundMode && DeveloperTools.on && DevPreview.shortcuts) LibraryPreviewButton() DisplayButton() if (!soundMode && xbox) LibraryFilterButton(null, onShowUninstalled, xbox) if (collections != null) CollectionsButton(collections) SortButton(s, a) ViewButton(s, a) if (!soundMode) GameFileFolderActions(s, a) - Store.byId(source)?.takeIf { !soundMode && StoresState.isSignedIn(it) }?.let { StoreAccountButton(it) } + // No sign-out in a preview: it would sign the real account out. + Store.byId(source)?.takeIf { !soundMode && DevPreview.library == LibraryPreview.OFF && StoresState.isSignedIn(it) }?.let { StoreAccountButton(it) } if (!s.shortcutPicker && (soundMode || (source == Library.ADDED && total > 0))) AddGameButton { if (soundMode) onAddSoundtrack() else GamesDialogState.adding = true } } if (s.steamGamesX64 && narrow) Box(Modifier.padding(top = 4.dp)) { ClientTag() } @@ -902,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) { @@ -934,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() } } } @@ -988,9 +1000,11 @@ private fun CustomGamesCard(height: androidx.compose.ui.unit.Dp, art: List) private fun sourceDot(src: String): Color? { val store = Store.byId(src) return when { - store != null -> sourceColours(src).dot.copy(alpha = if (StoresState.isSignedIn(store) && StoresState.expired[store] != true) 1f else 0.35f) + store != null -> sourceColours(src).dot.copy( + alpha = if (DevPreview.library == LibraryPreview.SAMPLE || (DevPreview.library != LibraryPreview.SIGNED_OUT && StoresState.isSignedIn(store) && StoresState.expired[store] != true)) 1f else 0.35f, + ) src == LIBRARY_FAVORITES -> FavoritesColours.dot - src == LIBRARY_HIDDEN -> Color(0xFF9AA0A6) + src == LIBRARY_HIDDEN -> HIDDEN_DOT src == Library.SOURCE_STEAM || src == Library.ADDED || src == Library.SOURCE_COLLECTION -> sourceColours(src).dot else -> null } @@ -1108,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) @@ -1348,7 +1370,7 @@ internal fun DisplayButton() { HeaderIconButton(title, Icons.Filled.Visibility, "display") { val from = at ?: return@HeaderIconButton Steps.ask(StepAsk( - anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = 5, + anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = 4, handle = { Icon(Icons.Filled.Visibility, null, tint = pal.signal, modifier = Modifier.size(18.dp)) }, ) { StepTitle(title) @@ -1371,10 +1393,6 @@ internal fun DisplayButton() { stringResource(R.string.library_display_size), selected = LibraryDisplay.size, enabled = open, modifier = Modifier.fillMaxWidth().stepItem(3), ) { LibraryDisplay.toggleSize(ctx) } - StepChoice( - stringResource(R.string.apps_filter_hidden), selected = LibraryDisplay.hidden, enabled = open, - modifier = Modifier.fillMaxWidth().stepItem(4), - ) { LibraryDisplay.toggleHidden(ctx) } } }) } 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/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 c56ac4a43a..39c4badb7e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt @@ -82,7 +82,7 @@ internal object StoreTabsState { SessionPrefs.settleStoresTabOrder(context, Store.entries.map { it.id }) tabs = arrangeStoreTabs(SessionPrefs.storesTabOrder(context), SessionPrefs.storesTabHidden(context)) libraryPlaces = SessionPrefs.libraryTabPlaces(context) ?: DEFAULT_LIBRARY_PLACES - libraryHidden = SessionPrefs.libraryTabsHidden(context) + libraryHidden = SessionPrefs.libraryTabsHidden(context) + listOfNotNull(LIBRARY_HIDDEN.takeUnless { SessionPrefs.libraryShowHidden(context) }) } /** [ids] may hold the Library's own tabs among the stores; each one's place is kept as the tab it follows. */ @@ -110,20 +110,21 @@ internal object StoreTabsState { fun setLibraryShown(context: android.content.Context, id: String, show: Boolean) { libraryHidden = if (show) libraryHidden - id else libraryHidden + id - SessionPrefs.setLibraryTabsHidden(context, libraryHidden) + if (id == LIBRARY_HIDDEN) SessionPrefs.setLibraryShowHidden(context, show) + else SessionPrefs.setLibraryTabsHidden(context, libraryHidden - LIBRARY_HIDDEN) } private fun save(context: android.content.Context, arranged: Boolean) = SessionPrefs.saveStoresTabs(context, tabs.map { it.store.id }, tabs.filterNot { it.shown }.map { it.store.id }.toSet(), arranged) } -/** The Library tabs that are not stores but sort among them in Manage stores. Only Favorites and Custom games can be hidden. */ -internal val LIBRARY_OWN_TABS = listOf(LIBRARY_FAVORITES, Library.SOURCE_STEAM, Library.ADDED) -internal val LIBRARY_HIDEABLE_TABS = setOf(LIBRARY_FAVORITES, Library.ADDED) +/** The Library tabs that are not stores but sort among them in Manage stores. Only Favorites, Custom games and Hidden can be turned off; Hidden starts off. */ +internal val LIBRARY_OWN_TABS = listOf(LIBRARY_FAVORITES, Library.SOURCE_STEAM, Library.ADDED, LIBRARY_HIDDEN) +internal val LIBRARY_HIDEABLE_TABS = setOf(LIBRARY_FAVORITES, Library.ADDED, LIBRARY_HIDDEN) -/** Favorites, then Steam, ahead of the stores; Custom games after them (null: the end). */ +/** Favorites, then Steam, ahead of the stores; Custom games and Hidden after them (null: the end). */ internal val DEFAULT_LIBRARY_PLACES: List> = - listOf(LIBRARY_FAVORITES to "", Library.SOURCE_STEAM to LIBRARY_FAVORITES, Library.ADDED to null) + listOf(LIBRARY_FAVORITES to "", Library.SOURCE_STEAM to LIBRARY_FAVORITES, Library.ADDED to null, LIBRARY_HIDDEN to null) /** * Puts the Library's own tabs into a store tab order. Each goes after the tab it follows ("" for first; null or a tab that is gone @@ -220,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() { @@ -301,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, ) { @@ -338,9 +339,14 @@ private fun LibraryTabSortRow(id: String, held: Boolean, offset: Float, hint: St val label = when (id) { LIBRARY_FAVORITES -> stringResource(R.string.soundtracks_favorites) Library.ADDED -> stringResource(R.string.library_custom_games) + LIBRARY_HIDDEN -> stringResource(R.string.apps_filter_hidden) else -> stringResource(R.string.source_steam) } - val dot = if (id == LIBRARY_FAVORITES) FavoritesColours.dot else sourceColours(id).dot + val dot = when (id) { + LIBRARY_FAVORITES -> FavoritesColours.dot + LIBRARY_HIDDEN -> HIDDEN_DOT + else -> sourceColours(id).dot + } SortRowFrame(held, offset, modifier.testTag("store-row-$id"), hot, src, onFocus) { Box(contentAlignment = Alignment.Center, modifier = Modifier.size(width = STORE_HANDLE, height = STORE_ROW).testTag("store-handle-$id")) { Icon(Icons.Filled.DragHandle, null, tint = if (held) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) 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..fc611d6ca6 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -56,9 +56,12 @@ 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?, + val hdrDisplay: Boolean = true, + val zeroCopy: Boolean = true, val gpuDrivers: String? = null, val upscaler: Int = 0, val upscaleSharpness: Int = 75, @@ -85,6 +88,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, @@ -113,7 +117,9 @@ class ModeSettings( class ModeSettingsActions( val onResolution: (String) -> Unit, + val onResolutionPortrait: (String) -> Unit = {}, val onHdr: (Boolean) -> Unit, + val onZeroCopy: (Boolean) -> Unit = {}, val onGpuDrivers: () -> Unit = {}, val onUpscaler: (Int) -> Unit = {}, val onUpscaleSharpness: (Int) -> Unit = {}, @@ -142,6 +148,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 = {}, @@ -229,9 +236,20 @@ 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 (portraitWindow) 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, + 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, + 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), @@ -243,13 +261,18 @@ 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), 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)) { s.integerScaling?.let { enabled -> @@ -276,9 +299,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, ) } @@ -698,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/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/NavTabs.kt b/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt index 82bf5cce39..aa08670e69 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt @@ -15,6 +15,7 @@ internal object DeveloperTools { fun load(context: Context) { on = SessionPrefs.developerTools(context) + DevPreview.shortcuts = SessionPrefs.previewShortcuts(context) } fun set(context: Context, enabled: Boolean) { 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..e0ae4c9480 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/PadArt.kt @@ -0,0 +1,392 @@ +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.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) + } + 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) + } + + 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 + 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/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/ResolutionRow.kt b/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt index 7112d4f399..ca9ca5976c 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,25 @@ 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, followTarget: 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 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, + 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) else if (value == SessionDisplay.FOLLOW_SCREEN) stringResource(R.string.display_follow_screen) @@ -35,18 +40,18 @@ 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 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/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/SecondScreenPresentation.kt b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt index 62f3c61f6c..ff0400860c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt @@ -42,6 +42,7 @@ class SecondScreenPresentation( private val onSwap: (() -> Unit)? = null, private val onMenuTouched: () -> Unit = {}, private val onDeckPanel: (DeckPanel) -> Unit = { SessionPrefs.setDeckPanel(sessionActivity, it) }, + private val picker: ((SecondScreenMode) -> ScreenPicker?)? = null, ) : Presentation(sessionActivity, display) { private val frame = FrameLayout(context) private var menuView: androidx.compose.ui.platform.ComposeView? = null @@ -301,9 +302,10 @@ class SecondScreenPresentation( SecondScreenMode.DASHBOARD -> renderDashboard() SecondScreenMode.DESKTOP -> { root.addView(BottomDesktopPanel(context, onClose, onMenu, - (onSteamMenu to onQam).takeIf { SessionState.mode == SessionService.MODE_STEAM }, onSwap), weightParams()) + (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 } } @@ -318,15 +320,15 @@ class SecondScreenPresentation( internal fun barModel(mode: SecondScreenMode): BottomBarModel? { val swap = listOfNotNull(onSwap?.let { BarExtra(context.getString(R.string.swap_screens), icon = R.drawable.ic_bottom_swap, tag = "bottom-swap", onClick = it) }) fun model(extras: List, tabs: BarTabs? = null) = - sessionBarModel(context.getString(mode.label), onClose, onMenu, onSteamMenu, onQam, extras, tabs) + sessionBarModel(context.getString(mode.label), onClose, onMenu, onSteamMenu, onQam, extras, tabs, picker?.invoke(mode)) return when (mode) { SecondScreenMode.KEYBOARD_TRACKPAD -> model(listOf(BarExtra( context.getString(if (keyboardShown.value) R.string.second_hide_keyboard else R.string.second_show_keyboard), - icon = R.drawable.ic_bottom_keyboard, active = keyboardShown.value, tag = "bottom-keyboard") { showKeyboard() })) + icon = R.drawable.ic_bottom_keyboard, active = keyboardShown.value, tag = "bottom-keyboard") { showKeyboard() }) + swap) SecondScreenMode.DECK_CONTROLS -> model(swap, deckPanelTabs(context, deckPanel.value, ::selectDeckPanel)) SecondScreenMode.DASHBOARD, SecondScreenMode.CUSTOM_CONTROLS -> model(swap) SecondScreenMode.TERMINAL -> model(listOf(BarExtra(context.getString(R.string.drawer_keyboard), icon = R.drawable.ic_bottom_keyboard, - tag = "bottom-keyboard") { terminalPanel?.showKeyboard() })) + tag = "bottom-keyboard") { terminalPanel?.showKeyboard() }) + swap) else -> null } } 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 d65852ece2..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,9 +1,14 @@ 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"), - SECOND_SCREEN("second-screen:custom-controls"), DISPLAY("fg"), HUD("hud"), EFFECTS("look"), @@ -13,14 +18,69 @@ internal enum class SessionDrawerPage(val firstControl: String) { SESSION("suspend"), } -internal fun sessionDrawerPages( - hasSecondScreen: Boolean, hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown, +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 { - (hasSecondScreen || it != SessionDrawerPage.SECOND_SCREEN) && (hasGlasses || it != SessionDrawerPage.GLASSES) && + 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 49bf448925..ffca74a17f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -43,11 +43,12 @@ import androidx.compose.material.icons.outlined.PowerSettingsNew 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.ScreenShare 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 +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 @@ -163,10 +164,9 @@ 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.SECOND_SCREEN -> R.string.drawer_second_screen SessionDrawerPage.DISPLAY -> R.string.drawer_page_display SessionDrawerPage.HUD -> R.string.drawer_hud SessionDrawerPage.VR -> R.string.vr_title @@ -176,10 +176,9 @@ 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.SECOND_SCREEN -> Icons.Outlined.ScreenShare SessionDrawerPage.DISPLAY -> Icons.Outlined.DesktopWindows SessionDrawerPage.HUD -> Icons.Outlined.Speed SessionDrawerPage.VR -> VrHeadsetIcon @@ -232,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 = {}, @@ -284,6 +285,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, @@ -331,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, @@ -339,10 +344,19 @@ 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, 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 = {}, @@ -386,8 +400,11 @@ class DrawerActions( @Composable 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.secondScreenDisplays.isNotEmpty(), a.glassesPresent) - val page = requestedPage.takeIf { it in pages } ?: SessionDrawerPage.CONTROLLER + val pages = sessionDrawerPages(a.glassesPresent) + 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 @@ -460,8 +477,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont val first = when { page == SessionDrawerPage.GLASSES -> "glasses-tab-$glassesTab" page == SessionDrawerPage.SESSION && a.isHomeApp -> "apps" - page == SessionDrawerPage.SECOND_SCREEN -> "second-screen:" + - (if (a.secondScreenMode == SecondScreenMode.NONE && !a.secondScreenNone) SecondScreenMode.KEYBOARD_TRACKPAD else a.secondScreenMode).id else -> page.firstControl } if (turned) focus.forget(page) @@ -506,28 +521,46 @@ 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 roomyHeader = sheetWidth >= 408.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( stringResource(R.string.common_close), Icons.Outlined.Close, focus.track(page, "close"), ) { host.open = null; (a.onDismissScreen ?: a.onClose)() } - if (roomyHeader) Spacer(Modifier.weight(1f)) + if (showPicker) Box(if (roomyHeader) Modifier.weight(1f) else Modifier) { + ScreenPickerChip( + 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; 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() } - 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) } @@ -543,7 +576,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont } } BarActions( - onMenu = if (docked) ({ host.open = null; a.onClose() }) else null, menuActive = true, + onMenu = null, menuActive = false, onSteam = if (steamActions) ({ host.open = null; a.onSteamMenu?.invoke() }) else null, onQam = if (steamActions) ({ host.open = null @@ -557,7 +590,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"))) { @@ -576,7 +610,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") }, @@ -631,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( @@ -650,6 +697,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont stringResource(R.string.display_sharpness), null, a.upscaleSharpness, 0..100, step = 5, format = { "$it%" }, modifier = focus.track(page, "upscale-sharpness"), onChange = a.onUpscaleSharpness) } + SecondScreenGroup(host, a) { key -> focus.track(page, key) } } SessionDrawerPage.EFFECTS -> { ScreenEffectsGroup(host, a, advancedEffectsExpanded, @@ -712,6 +760,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, @@ -740,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) @@ -796,9 +853,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont onToggle = { id, on -> PcKeyboardPrefs.toggleHiddenKey(keyboardContext, PC_KEY_GROUP_IDS.getValue(id), on) }) } } - SessionDrawerPage.SECOND_SCREEN -> { - SecondScreenGroup(host, a) { key -> focus.track(page, key) } - } SessionDrawerPage.GLASSES -> if (glassesTab == GlassesTab.CONTROLLERS) { VrControllerGroups(host) { key -> focus.track(page, key) } } else { @@ -909,6 +963,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont } } } } + } } StopConfirm( open = confirmStop, @@ -966,7 +1021,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() } @@ -988,15 +1043,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)) } @@ -1158,7 +1212,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) @@ -1284,43 +1340,17 @@ internal fun secondScreenModes(none: Boolean, deckPad: Boolean, dashboard: Boole @Composable private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) { - val colors = MaterialTheme.colorScheme - val pal = LocalPalette.current - val modes = secondScreenModes(a.secondScreenNone, com.droiddeck.launcher.session.SessionState.deckPad, a.dashboardAvailable, a.desktopAvailable) - SettingsGroup(stringResource(R.string.drawer_second_screen_mode)) { - Text(stringResource(R.string.input_second_mode_hint), Modifier.padding(14.dp), - style = MaterialTheme.typography.bodySmall, color = colors.onSurfaceVariant) - Column(Modifier.fillMaxWidth().selectableGroup()) { - modes.forEach { mode -> - val selected = a.secondScreenMode == mode - val source = remember { MutableInteractionSource() } - val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value - val pick = { host.open = null; a.onSecondScreenMode(mode) } - Row( - verticalAlignment = Alignment.CenterVertically, - modifier = track("second-screen:${mode.id}").fillMaxWidth().heightIn(min = 56.dp) - .background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent) - .glideBorder(hot, RoundedCornerShape(8.dp), pal.signal) - .hoverable(source) - .selectable(selected, interactionSource = source, indication = null, role = Role.RadioButton, onClick = pick) - .controllerConfirm(onClick = pick) - .padding(horizontal = 14.dp, vertical = 8.dp), - ) { - Text(stringResource(mode.label), fontSize = 15.sp, color = colors.onBackground, modifier = Modifier.weight(1f)) - RadioButton(selected, onClick = null, - colors = RadioButtonDefaults.colors(selectedColor = pal.signal, unselectedColor = colors.onSurfaceVariant)) - } - } - } - if (a.secondScreenDisplays.size > 1) ChoiceRow(host, "second-screen-display", stringResource(R.string.drawer_page_display), null, - a.secondScreenDisplays.map { it.id to it.label }, a.selectedSecondScreenDisplay, - chipModifier = track("second-screen-display"), onPick = a.onSecondScreenDisplay) - } - if (a.gameSwapAvailable || a.gameOnBottom) SettingsGroup(stringResource(R.string.swap_game_screen_group)) { - ChoiceRow(host, "game-screen", stringResource(R.string.swap_game_screen), null, + val choosesDisplay = a.secondScreenDisplays.size > 1 + val swapsGame = a.gameSwapAvailable || a.gameOnBottom + if (!choosesDisplay && !swapsGame) return + SettingsGroup(stringResource(R.string.drawer_second_screen)) { + 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)), a.gameOnBottom, chipModifier = track("game-screen"), onPick = a.onGameOnBottom) + if (choosesDisplay) ChoiceRow(host, "second-screen-display", stringResource(R.string.drawer_page_display), null, + a.secondScreenDisplays.map { it.id to it.label }, a.selectedSecondScreenDisplay, + chipModifier = track("second-screen-display"), onPick = a.onSecondScreenDisplay) } } 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..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,8 @@ 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), s(SettingsSection.LAUNCHER, R.string.mode_sgdb_key, "artwork", "steamgriddb"), @@ -137,7 +139,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/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/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() 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() 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, c: SourceColours, heigh } @Composable -private fun SignInButton(store: Store, large: Boolean = false) { +private fun SignInButton(store: Store, large: Boolean = false, inert: Boolean = false) { val ctx = LocalContext.current val colors = MaterialTheme.colorScheme val placed = remember { arrayOfNulls(1) } @@ -637,7 +638,8 @@ private fun SignInButton(store: Store, large: Boolean = false) { if (askKey) ItchKeyDialog { askKey = false } Box(Modifier.onGloballyPositioned { placed[0] = it }) { PrimaryButton(stringResource(R.string.stores_signin), main = true, large = large, icon = if (large) Icons.AutoMirrored.Filled.Login else null) { - startStoreSignIn(ctx, store, placed[0]?.takeIf { it.isAttached }?.boundsInRoot(), colors.primary) { askKey = true } + if (inert) android.widget.Toast.makeText(ctx, R.string.dev_preview_read_only, android.widget.Toast.LENGTH_SHORT).show() + else startStoreSignIn(ctx, store, placed[0]?.takeIf { it.isAttached }?.boundsInRoot(), colors.primary) { askKey = true } } } } @@ -663,7 +665,7 @@ private fun Storefront( LaunchedEffect(store, q) { StoresState.search(ctx, store, q) } val gameJolt = store == Store.GAMEJOLT LaunchedEffect(gameJolt, s.storesShowMature) { if (gameJolt) GameJoltBrowseState.sync(ctx, s.storesShowMature) } - val browsing = q.isEmpty() && ((store == Store.ITCH && ItchBrowseState.active) || gameJolt) + val browsing = q.isEmpty() && (store == Store.ITCH || gameJolt) val browseItems = if (!browsing) emptyList() else if (gameJolt) GameJoltBrowseState.items else ItchBrowseState.items val catalog = store == Store.BATTLENET && q.isEmpty() val visible = remember(found, library, shelves, q, s.storesShowMature, browsing, browseItems, catalog) { @@ -923,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() } @@ -953,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) @@ -963,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/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/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/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) 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/input_library.xml b/app/src/main/res/values-ar/input_library.xml index 68f65da57e..4a94939081 100644 --- a/app/src/main/res/values-ar/input_library.xml +++ b/app/src/main/res/values-ar/input_library.xml @@ -103,7 +103,6 @@ رجوع · مرتان في Steam ومرة في سطح المكتب في وضع Steam. الاستمرار بالضغط على رجوع يفتح الوصول السريع أيضًا. الاستعادة إلى الافتراضي - يتم تذكر اختيار اللوحة. يفتح سطح المكتب مساحة عمل ثانية؛ ولا يغيّر الجلسة أو ملف تعريف الإدخال. وحدة تحكم افتراضية نوع وحدة التحكم التي يراها Steam أو اللعبة. شاشة لمس diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 52c5f64a1e..f8217b0fd5 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 وسطح المكتب. يتم ضبطها في صفحة «المكوّنات». @@ -812,7 +811,6 @@ لوحة مفاتيح الكمبيوتر Android الشاشة الثانية - الوضع يعرض تطبيقات Android تشغيل تطبيق @@ -966,13 +964,15 @@ اتّباع تدوير الجهاز عمودي اتجاه الجلسة - يُطبَّق على Steam والألعاب وسطح المكتب ومحرّر وحدة التحكم. تدور الدقّات المُعدّة مسبقًا مع الجلسة، ويبقى العرض والارتفاع المخصّصان كما أُدخلا. + يُطبَّق على Steam والألعاب وسطح المكتب ومحرّر وحدة التحكم. تدور الدقّات المُعدّة مسبقًا مع الجلسة، وعندما يتبع أحد الاتجاهين الآخر ينعكس العرض والارتفاع المخصّصان ليتطابقا. أفقي تلقائي أفقي أفقي معكوس ملء الشاشة يخفي شريطي الحالة والتنقّل في Android يعرض شريطي الحالة والتنقّل في Android + التمرير بين الصفحات + اسحب عبر الصفحة لتغيير علامة التبويب. المشغّل على شاشتين يضع الوضع «تلقائي» أقسام المشغّل (Steam والمكتبة والمتاجر وغيرها) على الشاشة الثانية في الأجهزة المحمولة المزوّدة بشاشة ثانية مدمجة. ويستخدم الوضع «تشغيل» أي شاشة ثانية. أما الوضع «إيقاف» فيُبقي المشغّل على شاشة واحدة. الجلسات على شاشتين @@ -2566,10 +2566,16 @@ Android + Linux %1$s. %2$s\n\n%3$s شاشة الجلسة - الدقة + العرض بدون نسخ + دقة الوضع الأفقي + دقة الوضع العمودي + اتباع الأفقي (%1$d×%2$d) + اتباع العمودي (%1$d×%2$d) ملاءمة اللعبة لنسبة 16:9 كيفية ملاءمة ألعاب 16:9 لهذه الشاشة. يُطبَّق في الجلسة التالية. اختر «مطابقة الشاشة» أو حجمًا مخصَّصًا أضيق من 16:9. + تجنّب فتحة الكاميرا + يُبقي الصورة بعيدًا عن فتحة الكاميرا. يُطبَّق عند العودة إلى الجلسة. الحفاظ على النسب تمديد لملء الشاشة تكبير الصورة @@ -4171,6 +4177,7 @@ الأكثر تنزيلًا كل الفئات لم يتم العثور على إضافات + أغلق CurseForge أولاً تعذّر الوصول إلى %1$s لا يوجد ملف لإصدار اللعبة هذا إعادة تعيين المواضع diff --git a/app/src/main/res/values-b+es+419/input_library.xml b/app/src/main/res/values-b+es+419/input_library.xml index 7769845d32..82305bea9d 100644 --- a/app/src/main/res/values-b+es+419/input_library.xml +++ b/app/src/main/res/values-b+es+419/input_library.xml @@ -103,7 +103,6 @@ Atrás · dos veces en Steam, una en escritorio En modo Steam. Mantener Atrás también abre el acceso rápido. Restaurar valores predeterminados - Tu elección de panel se recuerda. Escritorio abre un segundo espacio de trabajo; no cambia la sesión ni su perfil de entrada. Control virtual El tipo de control que ven Steam o el juego. Pantalla táctil 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 6bb03b842b..8b0e2378e3 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. @@ -830,7 +829,6 @@ Teclado de PC Android Segunda pantalla - Modo Muestra Apps de Android Abrir una app @@ -984,13 +982,15 @@ 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 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 @@ -2558,10 +2558,16 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Pantalla de la sesión - Resolución + Presentación sin copia + 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. + 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 @@ -4051,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/input_library.xml b/app/src/main/res/values-bg/input_library.xml index 53f2103152..31967ac490 100644 --- a/app/src/main/res/values-bg/input_library.xml +++ b/app/src/main/res/values-bg/input_library.xml @@ -103,7 +103,6 @@ Назад · два пъти в Steam, веднъж в работен плот В режим Steam. Задържането на Назад отваря и бързия достъп. Връщане към подразбирането - Изборът на панел се запомня. Работният плот отваря второ работно пространство; не сменя сесията или профила ѝ за вход. Виртуален контролер Типът контролер, който Steam или играта виждат. Сензорен екран diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index cc99224c93..8531a5dab1 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 и работния плот. Задават се в страницата Компоненти. @@ -804,7 +803,6 @@ Клавиатура за компютър Android Втори екран - Режим Показва Приложения за Android Стартиране на приложение @@ -954,13 +952,15 @@ Следва завъртането на устройството Вертикална Ориентация на сесията - Прилага се за Steam, игрите, работния плот и редактора на контролера. Предварително зададените резолюции се завъртат със сесията; персонализираните ширина и височина остават както са въведени. + Прилага се за Steam, игрите, работния плот и редактора на контролера. Предварително зададените резолюции се завъртат със сесията; когато едната ориентация следва другата, персонализираните ширина и височина се разменят, за да съвпадат. Автоматичен хоризонтален Хоризонтална Обърната хоризонтална Цял екран Скрива лентите за състояние и навигация на Android Показва лентите за състояние и навигация на Android + Плъзгане между страниците + Плъзнете по страница, за да смените раздела. Лаунчер с два екрана Автоматично: секциите на лаунчера (Steam, Библиотека, Магазини и останалите) се показват на втория екран при преносими устройства с вграден такъв. Включено: използва се всеки втори дисплей. Изключено: лаунчерът остава на един екран. Сесии с два екрана @@ -2462,10 +2462,16 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Екран на сесията - Разделителна способност + Представяне без копиране + Резолюция в пейзажен режим + Резолюция в портретен режим + Като пейзажния (%1$d×%2$d) + Като портретния (%1$d×%2$d) Напасване на игра 16:9 Как игрите с 16:9 се напасват на този екран. При следващата сесия. Избери „Напасване на екрана“ или собствен размер, по-тесен от 16:9. + Избягване на прореза + Държи картината извън прореза за камерата. Важи при връщане към сесията. Запазване на пропорциите Разтягане до екрана Мащабиране на изображението @@ -4011,6 +4017,7 @@ Най-изтегляни Всички категории Няма намерени добавки + Първо затворете CurseForge Няма връзка с %1$s Няма файл за тази версия на играта Нулиране на позициите diff --git a/app/src/main/res/values-cs/input_library.xml b/app/src/main/res/values-cs/input_library.xml index 10783695ce..6ba6584e5e 100644 --- a/app/src/main/res/values-cs/input_library.xml +++ b/app/src/main/res/values-cs/input_library.xml @@ -103,7 +103,6 @@ Zpět · dvakrát v Steam, jednou na ploše V režimu Steam. Podržením Zpět se také otevře rychlý přístup. Obnovit výchozí - Volba panelu se pamatuje. Plocha otevře druhý pracovní prostor; nepřepíná relaci ani její vstupní profil. Virtuální ovladač Typ ovladače, který vidí Steam nebo hra. Dotyková obrazovka diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 15df9624b9..e8d2dc5c94 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. @@ -808,7 +807,6 @@ Klávesnice PC Android Druhá obrazovka - Režim Zobrazuje Aplikace Android Spustit aplikaci @@ -960,13 +958,15 @@ 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ě 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 @@ -2514,10 +2514,16 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Obrazovka relace - Rozlišení + Zobrazení bez kopírování + 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. + 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 @@ -4091,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/input_library.xml b/app/src/main/res/values-da/input_library.xml index f3fd6e80ac..3ba74431ee 100644 --- a/app/src/main/res/values-da/input_library.xml +++ b/app/src/main/res/values-da/input_library.xml @@ -103,7 +103,6 @@ Tilbage · to gange i Steam, én gang på skrivebordet I Steam-tilstand. Hvis du holder Tilbage, åbnes hurtigadgang også. Gendan standard - Dit panelvalg huskes. Skrivebord åbner et andet arbejdsområde; det skifter ikke sessionen eller dens inputprofil. Virtuel controller Den controllertype, som Steam eller spillet ser. Berøringsskærm diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 4a5dac730f..043a52c4b8 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. @@ -804,7 +803,6 @@ PC-tastatur Android Anden skærm - Tilstand Viser Android-apps Start en app @@ -954,13 +952,15 @@ 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 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 @@ -2462,10 +2462,16 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Sessionsskærm - Opløsning + Præsentation uden kopiering + 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. + 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 @@ -4011,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/input_library.xml b/app/src/main/res/values-de/input_library.xml index 8ba2b07f50..754679261f 100644 --- a/app/src/main/res/values-de/input_library.xml +++ b/app/src/main/res/values-de/input_library.xml @@ -103,7 +103,6 @@ Zurück · zweimal in Steam, einmal im Desktop Im Steam-Modus. Halten von Zurück öffnet auch den Schnellzugriff. Auf Standard zurücksetzen - Ihre Panel-Auswahl wird gespeichert. Desktop öffnet einen zweiten Arbeitsbereich; es wechselt weder die Sitzung noch ihr Eingabeprofil. Virtueller Controller Der von Steam oder dem Spiel erkannte Controller-Typ. Touchscreen diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 068f519c59..4d52b46b32 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. @@ -804,7 +803,6 @@ PC-Tastatur Android Zweiter Bildschirm - Modus Zeigt Android-Apps App starten @@ -946,13 +944,15 @@ 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 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 @@ -2454,10 +2454,16 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Sitzungsanzeige - Auflösung + Kopierfreie Darstellung + 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. + Notch aussparen + Hält das Bild aus der Kameraaussparung heraus. Gilt, sobald du zur Sitzung zurückkehrst. Seitenverhältnis beibehalten Auf Display strecken Bildskalierung @@ -4011,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/input_library.xml b/app/src/main/res/values-el/input_library.xml index c9f40579e3..d100812712 100644 --- a/app/src/main/res/values-el/input_library.xml +++ b/app/src/main/res/values-el/input_library.xml @@ -103,7 +103,6 @@ Πίσω · δύο φορές στο Steam, μία στην επιφάνεια εργασίας Σε λειτουργία Steam. Το κράτημα του Πίσω ανοίγει και τη γρήγορη πρόσβαση. Επαναφορά στις προεπιλογές - Η επιλογή πίνακα απομνημονεύεται. Η επιφάνεια εργασίας ανοίγει δεύτερο χώρο εργασίας· δεν αλλάζει τη συνεδρία ούτε το προφίλ εισόδου της. Εικονικό χειριστήριο Ο τύπος χειριστηρίου που βλέπουν το Steam ή το παιχνίδι. Οθόνη αφής diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index f4873ceb7c..826d8680e6 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 και την Επιφάνεια εργασίας. Ορίζονται στη σελίδα Στοιχεία. @@ -804,7 +803,6 @@ Πληκτρολόγιο PC Android Δεύτερη οθόνη - Λειτουργία Εμφανίζει Εφαρμογές Android Εκκίνηση εφαρμογής @@ -954,13 +952,15 @@ Ακολουθεί την περιστροφή της συσκευής Κατακόρυφος Προσανατολισμός συνεδρίας - Ισχύει για το Steam, τα παιχνίδια, την επιφάνεια εργασίας και τον επεξεργαστή χειριστηρίου. Οι προκαθορισμένες αναλύσεις περιστρέφονται με τη συνεδρία· το προσαρμοσμένο πλάτος και ύψος μένουν όπως καταχωρίστηκαν. + Ισχύει για το Steam, τα παιχνίδια, την επιφάνεια εργασίας και τον επεξεργαστή χειριστηρίου. Οι προκαθορισμένες αναλύσεις περιστρέφονται με τη συνεδρία· όταν ένας προσανατολισμός ακολουθεί τον άλλον, το προσαρμοσμένο πλάτος και ύψος αντιστρέφονται ώστε να ταιριάζουν. Αυτόματος οριζόντιος προσανατολισμός Οριζόντιος προσανατολισμός Αντίστροφος οριζόντιος προσανατολισμός Πλήρης οθόνη Αποκρύπτει τις γραμμές κατάστασης και πλοήγησης του Android Εμφανίζει τις γραμμές κατάστασης και πλοήγησης του Android + Σάρωση μεταξύ σελίδων + Σαρώστε κατά μήκος μιας σελίδας για να αλλάξετε καρτέλα. Εκκινητής διπλής οθόνης Η επιλογή Αυτόματα τοποθετεί τις ενότητες του εκκινητή (Steam, Βιβλιοθήκη, Καταστήματα και τις υπόλοιπες) στη δεύτερη οθόνη των φορητών κονσολών με ενσωματωμένη δεύτερη οθόνη. Η επιλογή Ενεργό χρησιμοποιεί οποιαδήποτε δεύτερη οθόνη. Η επιλογή Ανενεργό κρατά τον εκκινητή σε μία οθόνη. Συνεδρίες διπλής οθόνης @@ -2462,10 +2462,16 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Οθόνη συνεδρίας - Ανάλυση + Παρουσίαση χωρίς αντιγραφή + Ανάλυση σε οριζόντιο προσανατολισμό + Ανάλυση σε κατακόρυφο προσανατολισμό + Ίδια με οριζόντιο (%1$d×%2$d) + Ίδια με κατακόρυφο (%1$d×%2$d) Προσαρμογή παιχνιδιού 16:9 Πώς προσαρμόζονται τα παιχνίδια 16:9 σε αυτή την οθόνη. Από την επόμενη συνεδρία. Επιλέξτε Αντιστοίχιση οθόνης ή ένα προσαρμοσμένο μέγεθος πιο στενό από 16:9. + Αποφυγή εγκοπής + Κρατά την εικόνα μακριά από την εγκοπή της κάμερας. Εφαρμόζεται όταν επιστρέψεις στη συνεδρία. Διατήρηση αναλογιών Διάταση στην οθόνη Κλιμάκωση εικόνας @@ -4011,6 +4017,7 @@ Περισσότερες λήψεις Όλες οι κατηγορίες Δεν βρέθηκαν πρόσθετα + Κλείστε πρώτα το CurseForge Δεν ήταν δυνατή η σύνδεση με %1$s Δεν υπάρχει αρχείο για αυτή την έκδοση του παιχνιδιού Επαναφορά θέσεων diff --git a/app/src/main/res/values-es/input_library.xml b/app/src/main/res/values-es/input_library.xml index fe2ee17896..a2271204a7 100644 --- a/app/src/main/res/values-es/input_library.xml +++ b/app/src/main/res/values-es/input_library.xml @@ -103,7 +103,6 @@ Atrás · dos veces en Steam, una en escritorio En modo Steam. Mantener Atrás también abre el acceso rápido. Restaurar valores predeterminados - Tu elección de panel se recuerda. Escritorio abre un segundo espacio de trabajo; no cambia la sesión ni su perfil de entrada. Mando virtual El tipo de mando que ven Steam o el juego. Pantalla táctil diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index e39fae7b8a..3dcc0a4d1e 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. @@ -806,7 +805,6 @@ Teclado de PC Android Segunda pantalla - Modo Muestra Apps de Android Abrir una app @@ -957,13 +955,15 @@ 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 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 @@ -2488,10 +2488,16 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Pantalla de la sesión - Resolución + Presentación sin copia + 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. + 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 @@ -4051,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/input_library.xml b/app/src/main/res/values-fi/input_library.xml index 846dae260f..8fd745f70a 100644 --- a/app/src/main/res/values-fi/input_library.xml +++ b/app/src/main/res/values-fi/input_library.xml @@ -103,7 +103,6 @@ Takaisin · kahdesti Steamissa, kerran työpöydällä Steam-tilassa. Takaisin-painikkeen pitäminen avaa myös pikakäytön. Palauta oletukset - Paneelivalintasi muistetaan. Työpöytä avaa toisen työtilan; se ei vaihda istuntoa tai sen syöttöprofiilia. Virtuaaliohjain Ohjaintyyppi, jonka Steam tai peli näkee. Kosketusnäyttö diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index e9dacd8e0f..ebe843786e 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. @@ -804,7 +803,6 @@ PC-näppäimistö Android Toinen näyttö - Tila Näyttää Android-sovellukset Käynnistä sovellus @@ -954,13 +952,15 @@ 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 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 @@ -2462,10 +2462,16 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Istunnon näyttö - Tarkkuus + Kopioimaton esitys + 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. + Vältä lovea + Pitää kuvan poissa kameran lovesta. Tulee voimaan, kun palaat istuntoon. Säilytä kuvasuhde Venytä näyttöön Kuvan skaalaus @@ -4011,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/input_library.xml b/app/src/main/res/values-fr/input_library.xml index 4e899b637f..0dbdf5dbca 100644 --- a/app/src/main/res/values-fr/input_library.xml +++ b/app/src/main/res/values-fr/input_library.xml @@ -103,7 +103,6 @@ Retour · deux fois dans Steam, une fois sur le bureau En mode Steam. Maintenir Retour ouvre aussi l\'accès rapide. Rétablir par défaut - Votre choix de panneau est mémorisé. Le bureau ouvre un second espace de travail ; il ne change ni la session ni son profil d\'entrée. Manette virtuelle Le type de manette vu par Steam ou le jeu. Écran tactile diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index e76d3e6dab..bd5525aa28 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 ». @@ -806,7 +805,6 @@ Clavier PC Android Deuxième écran - Mode Afficher Applications Android Lancer l\'application @@ -957,13 +955,15 @@ 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é 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 @@ -2487,10 +2487,16 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Affichage de la session - Résolution + Affichage sans copie + 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. + É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 @@ -4050,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/input_library.xml b/app/src/main/res/values-hi/input_library.xml index 81147024d8..7ba5438500 100644 --- a/app/src/main/res/values-hi/input_library.xml +++ b/app/src/main/res/values-hi/input_library.xml @@ -103,7 +103,6 @@ वापस · Steam में दो बार, डेस्कटॉप में एक बार Steam मोड में। वापस दबाए रखने से क्विक एक्सेस भी खुलता है। डिफ़ॉल्ट पर पुनर्स्थापित करें - आपका पैनल चयन याद रखा जाता है। डेस्कटॉप दूसरा कार्यक्षेत्र खोलता है; यह सत्र या उसका इनपुट प्रोफ़ाइल नहीं बदलता। वर्चुअल कंट्रोलर Steam या गेम द्वारा देखा जाने वाला कंट्रोलर प्रकार। टचस्क्रीन diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 2f5d3957fc..7cd6bf3050 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 पेज पर सेट करें। @@ -804,7 +803,6 @@ पीसी कीबोर्ड Android दूसरी स्क्रीन - मोड दिखाता है Android ऐप ऐप लॉन्च करें @@ -954,13 +952,15 @@ डिवाइस रोटेशन के अनुसार पोर्ट्रेट सेशन ओरिएंटेशन - Steam, गेम, डेस्कटॉप और कंट्रोलर एडिटर पर लागू होता है। रिज़ॉल्यूशन प्रीसेट सेशन के साथ घूमते हैं; कस्टम चौड़ाई और ऊंचाई जैसी डाली गई वैसी ही रहती हैं। + Steam, गेम, डेस्कटॉप और कंट्रोलर एडिटर पर लागू होता है। रिज़ॉल्यूशन प्रीसेट सेशन के साथ घूमते हैं; जब एक ओरिएंटेशन दूसरे को फ़ॉलो करता है, तो कस्टम चौड़ाई और ऊंचाई बदलकर मेल खाती हैं। ऑटोमैटिक लैंडस्केप लैंडस्केप उलटा लैंडस्केप फ़ुलस्क्रीन Android स्टेटस और नेविगेशन बार छिपाता है Android स्टेटस और नेविगेशन बार दिखाता है + पेजों के बीच स्वाइप करें + टैब बदलने के लिए किसी पेज पर स्वाइप करें। डुअल स्क्रीन लॉन्चर स्वचालित पर, बिल्ट-इन दूसरी स्क्रीन वाले हैंडहेल्ड में लॉन्चर के सेक्शन (Steam, लाइब्रेरी, स्टोर्स और बाकी) दूसरी स्क्रीन पर चले जाते हैं। चालू पर कोई भी दूसरी डिस्प्ले इस्तेमाल होती है। बंद पर लॉन्चर एक ही स्क्रीन पर रहता है। डुअल स्क्रीन सत्र @@ -2462,10 +2462,16 @@ ANDROID + LINUX %1$s। %2$s\n\n%3$s सेशन डिस्प्ले - रिज़ॉल्यूशन + बिना कॉपी प्रस्तुति + लैंडस्केप रेज़ोल्यूशन + पोर्ट्रेट रेज़ोल्यूशन + लैंडस्केप जैसा (%1$d×%2$d) + पोर्ट्रेट जैसा (%1$d×%2$d) 16:9 गेम फ़िट 16:9 गेम इस डिस्प्ले में कैसे फ़िट होते हैं। अगले सेशन से। Match screen चुनें या 16:9 से पतला कस्टम आकार चुनें। + नॉच से बचें + तस्वीर को कैमरा कटआउट से दूर रखता है। सेशन में लौटने पर लागू होता है। अनुपात बनाए रखें डिस्प्ले में स्ट्रेच करें इमेज स्केलिंग @@ -4011,6 +4017,7 @@ सबसे ज़्यादा डाउनलोड सभी श्रेणियाँ कोई ऐडऑन नहीं मिला + पहले CurseForge बंद करें %1$s तक नहीं पहुँच सके गेम के इस संस्करण के लिए कोई फ़ाइल नहीं है स्थितियाँ रीसेट करें diff --git a/app/src/main/res/values-hu/input_library.xml b/app/src/main/res/values-hu/input_library.xml index ceeaeaf94e..a02e758852 100644 --- a/app/src/main/res/values-hu/input_library.xml +++ b/app/src/main/res/values-hu/input_library.xml @@ -103,7 +103,6 @@ Vissza · kétszer Steam módban, egyszer asztali módban Steam módban. A Vissza nyomva tartása a gyorselérést is megnyitja. Visszaállítás alapértelmezettre - A panelválasztás megjegyződik. Az asztali mód második munkateret nyit; nem váltja a munkamenetet vagy annak beviteli profilját. Virtuális vezérlő A Steam vagy a játék által látott vezérlőtípus. Érintőképernyő diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 50d616a3ca..d4c46656d6 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. @@ -804,7 +803,6 @@ PC-billentyűzet Android Második képernyő - Mód Megjelenít Android-alkalmazások Alkalmazás indítása @@ -954,13 +952,15 @@ 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ő 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 @@ -2462,10 +2462,16 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Munkamenet kijelzője - Felbontás + Másolásmentes megjeleníté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. + 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 @@ -4011,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/input_library.xml b/app/src/main/res/values-in/input_library.xml index f24780d5cc..28025b1073 100644 --- a/app/src/main/res/values-in/input_library.xml +++ b/app/src/main/res/values-in/input_library.xml @@ -103,7 +103,6 @@ Kembali · dua kali di Steam, sekali di desktop Di mode Steam. Menahan Kembali juga membuka akses cepat. Pulihkan ke bawaan - Pilihan panel Anda diingat. Desktop membuka ruang kerja kedua; tidak mengganti sesi atau profil inputnya. Pengontrol virtual Jenis pengontrol yang dilihat Steam atau game. Layar sentuh diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 1191dc3ac7..53c9708ecc 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. @@ -802,7 +801,6 @@ Keyboard PC Android Layar kedua - Mode Menampilkan Aplikasi Android Luncurkan aplikasi @@ -951,13 +949,15 @@ 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 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 @@ -2437,10 +2437,16 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Tampilan sesi - Resolusi + Presentasi tanpa salin + 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. + Hindari poni + Menjauhkan gambar dari lubang kamera. Berlaku saat Anda kembali ke sesi. Pertahankan proporsi Bentangkan ke tampilan Penskalaan gambar @@ -3981,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/input_library.xml b/app/src/main/res/values-it/input_library.xml index 87061db293..b825c1fb96 100644 --- a/app/src/main/res/values-it/input_library.xml +++ b/app/src/main/res/values-it/input_library.xml @@ -103,7 +103,6 @@ Indietro · due volte in Steam, una su desktop In modalità Steam. Tenere premuto Indietro apre anche l\'accesso rapido. Ripristina i valori predefiniti - La scelta del pannello viene ricordata. Desktop apre un secondo spazio di lavoro; non cambia la sessione né il suo profilo di input. Controller virtuale Il tipo di controller visto da Steam o dal gioco. Touchscreen diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 66fcd52a17..78a9ae250a 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. @@ -806,7 +805,6 @@ Tastiera PC Android Secondo schermo - Modalità Mostra App Android Avvia un\'app @@ -949,13 +947,15 @@ 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 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 @@ -2479,10 +2479,16 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Schermo della sessione - Risoluzione + Presentazione senza copia + 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. + Evita il notch + Tiene l\'immagine fuori dal ritaglio della fotocamera. Si applica al ritorno alla sessione. Mantieni proporzioni Estendi allo schermo Ridimensionamento immagine @@ -4050,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/input_library.xml b/app/src/main/res/values-ja/input_library.xml index ecf218c491..f4294982be 100644 --- a/app/src/main/res/values-ja/input_library.xml +++ b/app/src/main/res/values-ja/input_library.xml @@ -103,7 +103,6 @@ 戻る · Steam では 2 回、デスクトップでは 1 回 Steam モード時。戻るを長押しするとクイックアクセスも開きます。 既定に戻す - パネルの選択は記憶されます。デスクトップは 2 つ目のワークスペースを開くだけで、セッションやその入力プロファイルを切り替えません。 仮想コントローラー Steam またはゲームが認識するコントローラーの種類。 タッチスクリーン diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index a274e0c638..a7f1d18d19 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とデスクトップで共有されます。「コンポーネント」ページで設定してください。 @@ -802,7 +801,6 @@ PCキーボード Android セカンドスクリーン - モード 表示 Androidアプリ アプリを起動 @@ -951,13 +949,15 @@ デバイスの回転に合わせる 縦向き セッションの向き - Steam、ゲーム、デスクトップ、コントローラーエディターに適用されます。解像度プリセットはセッションに合わせて回転し、カスタムの幅と高さは入力したとおりになります。 + Steam、ゲーム、デスクトップ、コントローラーエディターに適用されます。解像度プリセットはセッションに合わせて回転し、一方の向きがもう一方に従う場合、カスタムの幅と高さは向きに合わせて入れ替わります。 横向き(自動回転) 横向き 横向き(反転) 全画面 Androidのステータスバーとナビゲーションバーを非表示 Androidのステータスバーとナビゲーションバーを表示 + スワイプでページを切り替え + ページを横切るようにスワイプすると、タブを切り替えます。 デュアルスクリーンランチャー 自動では、内蔵セカンドスクリーンを搭載した携帯ゲーム機で、ランチャーの各セクション(Steam、ライブラリ、ストアなど)を2画面目に表示します。オンでは任意のセカンドディスプレイを使用します。オフではランチャーを1画面に留めます。 デュアルスクリーンセッション @@ -2437,10 +2437,16 @@ ANDROID + LINUX %1$s。%2$s\n\n%3$s セッションの表示 - 解像度 + ゼロコピー表示 + 横向きの解像度 + 縦向きの解像度 + 横向きに合わせる (%1$d×%2$d) + 縦向きに合わせる (%1$d×%2$d) 16:9ゲームの表示 16:9のゲームをこのディスプレイにどう合わせるか。次回のセッションから。 「画面に合わせる」か、16:9より縦長のカスタムサイズを選んでください。 + ノッチを避ける + 映像をカメラの切り欠きから離します。セッションに戻ると反映されます。 縦横比を保持 画面いっぱいに引き伸ばす 画像のスケーリング @@ -3981,6 +3987,7 @@ ダウンロード数順 すべてのカテゴリ アドオンが見つかりません + 先に CurseForge を閉じてください %1$s に接続できませんでした このゲームバージョン用のファイルがありません 位置をリセット diff --git a/app/src/main/res/values-ko/input_library.xml b/app/src/main/res/values-ko/input_library.xml index d19c198c7e..c5030b8290 100644 --- a/app/src/main/res/values-ko/input_library.xml +++ b/app/src/main/res/values-ko/input_library.xml @@ -103,7 +103,6 @@ 뒤로 · Steam에서는 두 번, 데스크톱에서는 한 번 Steam 모드에서. 뒤로를 길게 누르면 빠른 액세스도 열립니다. 기본값으로 복원 - 패널 선택이 기억됩니다. 데스크톱은 두 번째 작업 공간을 열 뿐 세션이나 입력 프로필을 전환하지 않습니다. 가상 컨트롤러 Steam 또는 게임이 인식하는 컨트롤러 유형입니다. 터치스크린 diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index c3bd68537b..f97db37e65 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과 데스크톱에서 공유됩니다. \"구성 요소\" 페이지에서 설정하세요. @@ -802,7 +801,6 @@ PC 키보드 Android 보조 화면 - 모드 표시 Android 앱 앱 실행 @@ -951,13 +949,15 @@ 기기 회전 따르기 세로 세션 방향 - Steam, 게임, 데스크톱 및 컨트롤러 편집기에 적용됩니다. 해상도 프리셋은 세션에 맞춰 회전하며, 사용자 정의 너비와 높이는 입력한 그대로 유지됩니다. + Steam, 게임, 데스크톱 및 컨트롤러 편집기에 적용됩니다. 해상도 프리셋은 세션에 맞춰 회전하며, 한 방향이 다른 방향을 따를 때 사용자 정의 너비와 높이는 방향에 맞게 서로 바뀝니다. 자동 가로 모드 가로 모드 역방향 가로 모드 전체 화면 Android 상태 표시줄 및 탐색 표시줄 숨기기 Android 상태 표시줄 및 탐색 표시줄 표시 + 스와이프로 페이지 전환 + 페이지를 가로질러 스와이프하면 탭이 바뀝니다. 듀얼 화면 런처 자동은 내장 두 번째 화면이 있는 휴대용 기기에서 런처 섹션(Steam, 라이브러리, 스토어 등)을 두 번째 화면에 표시합니다. 켜기는 어떤 두 번째 디스플레이든 사용합니다. 끄기는 런처를 한 화면에 유지합니다. 듀얼 화면 세션 @@ -2437,10 +2437,16 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s 세션 디스플레이 - 해상도 + 제로카피 표시 + 가로 해상도 + 세로 해상도 + 가로와 동일 (%1$d×%2$d) + 세로와 동일 (%1$d×%2$d) 16:9 게임 맞춤 16:9 게임을 이 디스플레이에 맞추는 방식입니다. 다음 세션부터 적용됩니다. 화면에 맞춤 또는 16:9보다 좁은 사용자 정의 크기를 선택하세요. + 노치 피하기 + 화면을 카메라 컷아웃 밖에 표시합니다. 세션으로 돌아오면 적용됩니다. 비율 유지 화면에 맞게 늘이기 이미지 스케일링 @@ -3981,6 +3987,7 @@ 다운로드 많은 순 모든 카테고리 애드온을 찾을 수 없음 + 먼저 CurseForge를 닫으세요 %1$s에 연결할 수 없습니다 이 게임 버전용 파일이 없습니다 위치 초기화 diff --git a/app/src/main/res/values-ms/input_library.xml b/app/src/main/res/values-ms/input_library.xml index bd4b455121..e14f8a4252 100644 --- a/app/src/main/res/values-ms/input_library.xml +++ b/app/src/main/res/values-ms/input_library.xml @@ -103,7 +103,6 @@ Kembali · dua kali dalam Steam, sekali di desktop Dalam mod Steam. Menahan Kembali juga membuka akses pantas. Pulihkan kepada lalai - Pilihan panel anda diingati. Desktop membuka ruang kerja kedua; ia tidak menukar sesi atau profil inputnya. Pengawal maya Jenis pengawal yang dilihat oleh Steam atau permainan. Skrin sentuh diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index 134f1702c0..9d2d102625 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. @@ -802,7 +801,6 @@ Papan kekunci PC Android Skrin kedua - Mod Memaparkan Apl Android Lancarkan apl @@ -951,13 +949,15 @@ 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 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 @@ -2437,10 +2437,16 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Paparan sesi - Resolusi + Paparan tanpa salinan + 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. + Elak takuk + Memastikan gambar tidak berada di potongan kamera. Digunakan apabila anda kembali ke sesi. Kekalkan nisbah Regang ke paparan Penskalaan imej @@ -3981,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/input_library.xml b/app/src/main/res/values-nb/input_library.xml index e810fed5a4..340337947a 100644 --- a/app/src/main/res/values-nb/input_library.xml +++ b/app/src/main/res/values-nb/input_library.xml @@ -103,7 +103,6 @@ Tilbake · to ganger i Steam, én gang på skrivebordet I Steam-modus. Å holde Tilbake åpner også hurtigtilgang. Tilbakestill til standard - Panelvalget ditt huskes. Skrivebord åpner et andre arbeidsområde; det bytter ikke økten eller inndataprofilen. Virtuell kontroller Kontrollertypen som Steam eller spillet ser. Berøringsskjerm diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index de0bac7fc6..a09d35a922 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. @@ -804,7 +803,6 @@ PC-tastatur Android Andre skjerm - Modus Viser Android-apper Start en app @@ -954,13 +952,15 @@ 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 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 @@ -2462,10 +2462,16 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Sesjonsskjerm - Oppløsning + Presentasjon uten kopiering + 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. + Unngå notch + Holder bildet unna kamerautskjæringen. Gjelder når du går tilbake til økten. Behold proporsjoner Strekk til skjermen Bildeskalering @@ -4011,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/input_library.xml b/app/src/main/res/values-nl/input_library.xml index 80f96a853b..48db0c68ed 100644 --- a/app/src/main/res/values-nl/input_library.xml +++ b/app/src/main/res/values-nl/input_library.xml @@ -103,7 +103,6 @@ Terug · twee keer in Steam, één keer op bureaublad In spelmodus Steam. Terug ingedrukt houden opent ook snelle toegang. Terugzetten naar standaard - Je paneelkeuze wordt onthouden. Bureaublad opent een tweede werkruimte; het wisselt de sessie of het invoerprofiel niet. Virtuele controller Het controllertype dat Steam of het spel ziet. Touchscreen diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 16b5a74ec8..023fe7bb97 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. @@ -804,7 +803,6 @@ Pc-toetsenbord Android Tweede scherm - Modus Toont Android-apps Een app starten @@ -954,13 +952,15 @@ 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 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 @@ -2462,10 +2462,16 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Sessiescherm - Resolutie + Weergave zonder kopie + 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. + Notch vermijden + Houdt het beeld buiten de camerauitsparing. Geldt zodra je terugkeert naar de sessie. Beeldverhouding behouden Uitrekken naar scherm Beeldschaling @@ -4011,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/input_library.xml b/app/src/main/res/values-pl/input_library.xml index 1193c2a125..02c4db578b 100644 --- a/app/src/main/res/values-pl/input_library.xml +++ b/app/src/main/res/values-pl/input_library.xml @@ -103,7 +103,6 @@ Wstecz · dwa razy w Steam, raz na pulpicie W trybie Steam. Przytrzymanie Wstecz otwiera też szybki dostęp. Przywróć domyślne - Wybór panelu jest zapamiętywany. Pulpit otwiera drugą przestrzeń roboczą; nie przełącza sesji ani jej profilu wejścia. Wirtualny kontroler Typ kontrolera widziany przez Steam lub grę. Ekran dotykowy diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 8b624db10e..3ff4e06620 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. @@ -808,7 +807,6 @@ Klawiatura PC Android Drugi ekran - Tryb Pokazuje Aplikacje Android Uruchom aplikację @@ -960,13 +958,15 @@ 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 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 @@ -2514,10 +2514,16 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Ekran sesji - Rozdzielczość + Prezentacja bez kopiowania + 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. + Omijaj notch + Utrzymuje obraz poza wycięciem na aparat. Działa po powrocie do sesji. Zachowaj proporcje Rozciągnij do ekranu Skalowanie obrazu @@ -4091,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/input_library.xml b/app/src/main/res/values-pt-rPT/input_library.xml index 498a7442e0..ec88357260 100644 --- a/app/src/main/res/values-pt-rPT/input_library.xml +++ b/app/src/main/res/values-pt-rPT/input_library.xml @@ -103,7 +103,6 @@ Voltar · duas vezes no Steam, uma no ambiente de trabalho No modo Steam. Manter Voltar também abre o acesso rápido. Repor predefinições - A sua escolha de painel é memorizada. O ambiente de trabalho abre um segundo espaço de trabalho; não muda a sessão nem o seu perfil de entrada. Comando virtual O tipo de comando visto pelo Steam ou pelo jogo. Ecrã tátil diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 732df24c4c..15c7cb206c 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. @@ -806,7 +805,6 @@ Teclado de PC Android Segundo ecrã - Modo Mostra Apps Android Iniciar uma app @@ -949,13 +947,15 @@ 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 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 @@ -2493,10 +2493,16 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Ecrã da sessão - Resolução + Apresentação sem cópia + 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. + 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 @@ -4064,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/input_library.xml b/app/src/main/res/values-pt/input_library.xml index ae84ba99ce..93dd70368e 100644 --- a/app/src/main/res/values-pt/input_library.xml +++ b/app/src/main/res/values-pt/input_library.xml @@ -103,7 +103,6 @@ Voltar · duas vezes no Steam, uma no desktop No modo Steam. Manter Voltar também abre o acesso rápido. Restaurar o padrão - Sua escolha de painel é lembrada. O desktop abre um segundo espaço de trabalho; não troca a sessão nem o perfil de entrada. Controle virtual O tipo de controle visto pelo Steam ou pelo jogo. Tela sensível ao toque diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index f0814f45b2..1e291f316b 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. @@ -813,7 +812,6 @@ Teclado de PC Android Segunda tela - Modo Mostra Apps Android Abrir um app @@ -956,13 +954,15 @@ 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 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 @@ -2501,10 +2501,16 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Tela da sessão - Resolução + Apresentação sem cópia + 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. + 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 @@ -4072,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/input_library.xml b/app/src/main/res/values-ro/input_library.xml index 5a3648d509..7f2b804916 100644 --- a/app/src/main/res/values-ro/input_library.xml +++ b/app/src/main/res/values-ro/input_library.xml @@ -103,7 +103,6 @@ Înapoi · de două ori în Steam, o dată pe desktop În modul Steam. Ținerea butonului Înapoi deschide și accesul rapid. Restabilește implicit - Alegerea panoului este reținută. Desktopul deschide un al doilea spațiu de lucru; nu schimbă sesiunea sau profilul ei de intrare. Controller virtual Tipul de controller văzut de Steam sau de joc. Ecran tactil diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index c228979545..f5868d56e5 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. @@ -806,7 +805,6 @@ Tastatură de PC Android Al doilea ecran - Mod Arată Aplicații Android Lansează o aplicație @@ -957,13 +955,15 @@ 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 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 @@ -2488,10 +2488,16 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Afișajul sesiunii - Rezoluție + Prezentare fără copiere + 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. + Evită decupajul + Ține imaginea departe de decupajul camerei. Se aplică la revenirea în sesiune. Păstrează proporțiile Întinde pe afișaj Scalarea imaginii @@ -4051,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/input_library.xml b/app/src/main/res/values-ru/input_library.xml index d02df2ffe6..b4b9cfd9f6 100644 --- a/app/src/main/res/values-ru/input_library.xml +++ b/app/src/main/res/values-ru/input_library.xml @@ -103,7 +103,6 @@ Назад · дважды в Steam, один раз в рабочем столе В режиме Steam. Удержание «Назад» также открывает быстрый доступ. Вернуть по умолчанию - Выбор панели запоминается. Рабочий стол открывает второе рабочее пространство; он не переключает сеанс или его профиль ввода. Виртуальный контроллер Тип контроллера, который видят Steam или игра. Сенсорный экран diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 58a3c4e745..da7e65b3f6 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 и рабочего стола. Настройте на странице «Компоненты». @@ -808,7 +807,6 @@ Клавиатура ПК Android Второй экран - Режим Показывать Приложения Android Запустить приложение @@ -960,13 +958,15 @@ Следовать повороту устройства Портретная Ориентация сессии - Применяется к Steam, играм, рабочему столу и редактору контроллера. Предустановки разрешения поворачиваются вместе с сессией; свои ширина и высота остаются как введены. + Применяется к Steam, играм, рабочему столу и редактору контроллера. Предустановки разрешения поворачиваются вместе с сессией; когда одна ориентация следует за другой, свои ширина и высота меняются местами. Альбомная (авто) Альбомная Перевернутая альбомная Полноэкранный режим Скрывает строку состояния и панель навигации Android Показывает строку состояния и панель навигации Android + Перелистывание страниц свайпом + Проведите по странице, чтобы сменить вкладку. Лаунчер на двух экранах «Автоматически» переносит разделы лаунчера (Steam, Библиотека, Магазины и остальные) на второй экран портативных устройств со встроенным вторым экраном. «Вкл.» использует любой второй дисплей. «Выкл.» оставляет лаунчер на одном экране. Сессии на двух экранах @@ -2514,10 +2514,16 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Экран сессии - Разрешение + Вывод без копирования + Разрешение в альбомной ориентации + Разрешение в портретной ориентации + Как в альбомной (%1$d×%2$d) + Как в портретной (%1$d×%2$d) Игры 16:9 Как игры 16:9 вписываются в этот экран. Вступит в силу в следующей сессии. Выберите «По размеру экрана» или свой размер уже 16:9. + Обходить вырез + Не выводит картинку под вырез камеры. Применяется при возврате в сессию. Сохранять пропорции Растянуть на экран Масштабирование изображения @@ -4091,6 +4097,7 @@ Самые скачиваемые Все категории Аддоны не найдены + Сначала закройте CurseForge Не удалось подключиться к %1$s Нет файла для этой версии игры Сбросить положение diff --git a/app/src/main/res/values-sv/input_library.xml b/app/src/main/res/values-sv/input_library.xml index dfe4102366..15e3e12e03 100644 --- a/app/src/main/res/values-sv/input_library.xml +++ b/app/src/main/res/values-sv/input_library.xml @@ -103,7 +103,6 @@ Tillbaka · två gånger i Steam, en gång på skrivbordet I Steam-läge. Att hålla Tillbaka öppnar även snabbåtkomst. Återställ till standard - Ditt panelval kommer ihåg. Skrivbord öppnar en andra arbetsyta; det byter inte sessionen eller dess inmatningsprofil. Virtuell handkontroll Den handkontrolltyp som Steam eller spelet ser. Pekskärm diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 73c1f9dbe0..58be1afa71 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. @@ -804,7 +803,6 @@ PC-tangentbord Android Andra skärmen - Läge Visar Android-appar Starta en app @@ -954,13 +952,15 @@ 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 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 @@ -2462,10 +2462,16 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Sessionsskärm - Upplösning + Presentation utan kopiering + 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. + 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 @@ -4011,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/input_library.xml b/app/src/main/res/values-th/input_library.xml index 944a4aaa79..ef2ae2702a 100644 --- a/app/src/main/res/values-th/input_library.xml +++ b/app/src/main/res/values-th/input_library.xml @@ -103,7 +103,6 @@ ย้อนกลับ · สองครั้งใน Steam หนึ่งครั้งบนเดสก์ท็อป ในโหมด Steam การกดย้อนกลับค้างจะเปิดการเข้าถึงด่วนด้วย คืนค่าเริ่มต้น - ตัวเลือกแผงของคุณจะถูกจำไว้ เดสก์ท็อปจะเปิดพื้นที่ทำงานที่สอง ไม่ได้สลับเซสชันหรือโปรไฟล์อินพุต คอนโทรลเลอร์เสมือน ชนิดคอนโทรลเลอร์ที่ Steam หรือเกมมองเห็น หน้าจอสัมผัส diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 43c49d86fa..d8ec6f41e1 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 @@ -802,7 +801,6 @@ แป้นพิมพ์พีซี Android หน้าจอที่สอง - โหมด แสดง แอป Android เปิดแอป @@ -951,13 +949,15 @@ หมุนตามอุปกรณ์ แนวตั้ง การวางแนวของเซสชัน - มีผลกับ Steam เกม เดสก์ท็อป และตัวแก้ไขคอนโทรลเลอร์ ค่าความละเอียดที่ตั้งไว้ล่วงหน้าจะหมุนตามเซสชัน ส่วนความกว้างและความสูงที่กำหนดเองจะคงตามที่ป้อนไว้ + มีผลกับ Steam เกม เดสก์ท็อป และตัวแก้ไขคอนโทรลเลอร์ ค่าความละเอียดที่ตั้งไว้ล่วงหน้าจะหมุนตามเซสชัน เมื่อแนวหนึ่งตามอีกแนวหนึ่ง ความกว้างและความสูงที่กำหนดเองจะสลับกันให้ตรงกัน แนวนอนอัตโนมัติ แนวนอน แนวนอนกลับด้าน เต็มจอ ซ่อนแถบสถานะและแถบนำทางของ Android แสดงแถบสถานะและแถบนำทางของ Android + ปัดเพื่อเปลี่ยนหน้า + ปัดผ่านหน้าเพื่อเปลี่ยนแท็บ ลอนเชอร์แบบสองจอ โหมดอัตโนมัติจะแสดงส่วนต่างๆ ของลอนเชอร์ (Steam, คลังเกม, ร้านค้า และส่วนอื่นๆ) บนจอที่สองของเครื่องเล่นพกพาที่มีจอที่สองในตัว โหมดเปิดใช้จอที่สองใดก็ได้ โหมดปิดจะแสดงลอนเชอร์บนจอเดียว เซสชันแบบสองจอ @@ -2437,10 +2437,16 @@ ANDROID + LINUX %1$s %2$s\n\n%3$s การแสดงผลของเซสชัน - ความละเอียด + การแสดงผลแบบไม่คัดลอก + ความละเอียดแนวนอน + ความละเอียดแนวตั้ง + ตามแนวนอน (%1$d×%2$d) + ตามแนวตั้ง (%1$d×%2$d) การแสดงเกม 16:9 ให้พอดี วิธีที่เกม 16:9 แสดงพอดีกับหน้าจอนี้ มีผลในเซสชันถัดไป เลือกพอดีหน้าจอ หรือขนาดกำหนดเองที่แคบกว่า 16:9 + เลี่ยงรอยบาก + ไม่แสดงภาพทับช่องกล้อง มีผลเมื่อคุณกลับเข้าสู่เซสชัน คงสัดส่วนไว้ ยืดให้พอดีหน้าจอ การปรับขนาดภาพ @@ -3981,6 +3987,7 @@ ดาวน์โหลดมากที่สุด ทุกหมวดหมู่ ไม่พบแอดออน + ปิด CurseForge ก่อน ไม่สามารถเชื่อมต่อ %1$s ได้ ไม่มีไฟล์สำหรับเกมเวอร์ชันนี้ รีเซ็ตตำแหน่ง diff --git a/app/src/main/res/values-tr/input_library.xml b/app/src/main/res/values-tr/input_library.xml index 12d264ee81..563657c5d4 100644 --- a/app/src/main/res/values-tr/input_library.xml +++ b/app/src/main/res/values-tr/input_library.xml @@ -103,7 +103,6 @@ Geri · Steam\'de iki kez, masaüstünde bir kez Steam modunda. Geri tuşunu basılı tutmak hızlı erişimi de açar. Varsayılana sıfırla - Panel seçiminiz hatırlanır. Masaüstü ikinci bir çalışma alanı açar; oturumu veya giriş profilini değiştirmez. Sanal denetleyici Steam veya oyunun gördüğü denetleyici türü. Dokunmatik ekran diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 7fd0d204d3..6bec3f37b5 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. @@ -804,7 +803,6 @@ PC klavyesi Android İkinci ekran - Mod Gösterilen Android uygulamaları Uygulama başlat @@ -946,13 +944,15 @@ 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 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 @@ -2454,10 +2454,16 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Oturum ekranı - Çözünürlük + Kopyasız sunum + 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. + Ç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 @@ -4011,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/input_library.xml b/app/src/main/res/values-uk/input_library.xml index f2504dde51..9993d25a57 100644 --- a/app/src/main/res/values-uk/input_library.xml +++ b/app/src/main/res/values-uk/input_library.xml @@ -103,7 +103,6 @@ Назад · двічі в Steam, один раз у робочому столі У режимі Steam. Утримання «Назад» також відкриває швидкий доступ. Відновити типове - Ваш вибір панелі запам\'ятовується. Робочий стіл відкриває другий робочий простір; він не перемикає сеанс або його профіль введення. Віртуальний контролер Тип контролера, який бачать Steam або гра. Сенсорний екран diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index be20c1fb05..472a1d8050 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 і робочого столу. Налаштовуються на сторінці «Компоненти». @@ -808,7 +807,6 @@ Клавіатура ПК Android Другий екран - Режим Показує Додатки Android Запустити додаток @@ -960,13 +958,15 @@ Слідувати повороту пристрою Книжкова Орієнтація сеансу - Застосовується до Steam, ігор, робочого столу й редактора контролера. Готові роздільні здатності повертаються разом із сеансом; власні ширина й висота залишаються як введено. + Застосовується до Steam, ігор, робочого столу й редактора контролера. Готові роздільні здатності повертаються разом із сеансом; коли одна орієнтація слідує за іншою, власні ширина й висота міняються місцями. Автоматично альбомна Альбомна Перевернута альбомна Повний екран Приховує рядок стану та панель навігації Android Показує рядок стану та панель навігації Android + Гортання сторінок свайпом + Проведіть по сторінці, щоб змінити вкладку. Лаунчер для двох екранів Автоматичний режим розміщує розділи лаунчера (Steam, Бібліотека, Магазини тощо) на вбудованому другому екрані портативних пристроїв. У режимі «Увімкнено» використовується будь-який другий дисплей. У режимі «Вимкнено» лаунчер залишається на одному екрані. Сеанси для двох екранів @@ -2514,10 +2514,16 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Дисплей сеансу - Роздільна здатність + Показ без копіювання + Роздільна здатність в альбомній орієнтації + Роздільна здатність у портретній орієнтації + Як в альбомній (%1$d×%2$d) + Як у портретній (%1$d×%2$d) Вписування гри 16:9 Як ігри 16:9 вписуються в цей дисплей. З наступного сеансу. Виберіть «Під екран» або власний розмір, вужчий за 16:9. + Обходити виріз + Не виводить зображення під виріз камери. Застосовується після повернення до сесії. Зберігати пропорції Розтягнути на весь дисплей Масштабування зображення @@ -4091,6 +4097,7 @@ Найбільше завантажень Усі категорії Аддонів не знайдено + Спочатку закрийте CurseForge Не вдалося під’єднатися до %1$s Немає файлу для цієї версії гри Скинути розташування diff --git a/app/src/main/res/values-vi/input_library.xml b/app/src/main/res/values-vi/input_library.xml index 6b75fe7fd8..71e6b034cc 100644 --- a/app/src/main/res/values-vi/input_library.xml +++ b/app/src/main/res/values-vi/input_library.xml @@ -103,7 +103,6 @@ Quay lại · hai lần trong Steam, một lần trên máy tính Ở chế độ Steam. Giữ Quay lại cũng mở truy cập nhanh. Khôi phục mặc định - Lựa chọn bảng của bạn được ghi nhớ. Máy tính mở không gian làm việc thứ hai; không chuyển phiên hay hồ sơ đầu vào của nó. Tay cầm ảo Loại tay cầm mà Steam hoặc trò chơi thấy. Màn hình cảm ứng diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 33796ad9c4..fbf6432863 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. @@ -802,7 +801,6 @@ Bàn phím PC Android Màn hình thứ hai - Chế độ Hiển thị Ứng dụng Android Khởi chạy một ứng dụng @@ -951,13 +949,15 @@ 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 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 @@ -2437,10 +2437,16 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Hiển thị phiên - Độ phân giải + Hiển thị không sao chép + Độ 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. + 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 @@ -3981,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/input_library.xml b/app/src/main/res/values-zh-rCN/input_library.xml index 00c716c4cc..921f57c80d 100644 --- a/app/src/main/res/values-zh-rCN/input_library.xml +++ b/app/src/main/res/values-zh-rCN/input_library.xml @@ -103,7 +103,6 @@ 返回 · Steam 里两下,桌面上一下 Steam 模式下。按住返回也会打开快捷菜单。 恢复默认 - 面板选择会被记住。桌面会打开第二个工作区,不切换会话或它的输入配置。 虚拟手柄 Steam 或游戏看到的手柄类型。 触摸屏 diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 667f1cb9c1..4446a1fb81 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 和桌面共享。在“组件”页面设置。 @@ -802,7 +801,6 @@ PC 键盘 Android 副屏 - 模式 显示 Android 应用 启动应用 @@ -951,13 +949,15 @@ 跟随设备旋转 竖屏 会话方向 - 适用于 Steam、游戏、桌面和手柄编辑器。分辨率预设会随会话旋转;自定义宽度和高度保持输入值不变。 + 适用于 Steam、游戏、桌面和手柄编辑器。分辨率预设会随会话旋转;当一个方向跟随另一个方向时,自定义宽度和高度会互换以保持一致。 自动横屏 横屏 反向横屏 全屏 隐藏 Android 状态栏和导航栏 显示 Android 状态栏和导航栏 + 滑动切换页面 + 在页面上滑动即可切换标签。 双屏启动器 自动会把启动器的各个板块(Steam、库、商店等)放到带内置副屏的掌机的第二块屏幕上。开启使用任意第二块显示屏。关闭则让启动器只显示在一块屏幕上。 双屏会话 @@ -2514,10 +2514,16 @@ Android + Linux %1$s。%2$s\n\n%3$s 会话显示 - 分辨率 + 零拷贝呈现 + 横屏分辨率 + 竖屏分辨率 + 跟随横屏 (%1$d×%2$d) + 跟随竖屏 (%1$d×%2$d) 16:9 游戏适配 16:9 游戏如何适配此屏幕。下次会话生效。 请选择“匹配屏幕”或比 16:9 更窄的自定义尺寸。 + 避开刘海 + 让画面避开摄像头挖孔区域。返回会话时生效。 保持比例 拉伸至屏幕 画面缩放 @@ -3981,6 +3987,7 @@ 下载最多 所有类别 未找到插件 + 请先关闭 CurseForge 无法连接到 %1$s 没有适用于此游戏版本的文件 重置位置 diff --git a/app/src/main/res/values-zh-rHK/input_library.xml b/app/src/main/res/values-zh-rHK/input_library.xml index 20930002a7..d997b2e0ca 100644 --- a/app/src/main/res/values-zh-rHK/input_library.xml +++ b/app/src/main/res/values-zh-rHK/input_library.xml @@ -103,7 +103,6 @@ 返回 · Steam 裡兩下,桌面上一下 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 2ec673e61b..daa483e57d 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 和桌面共用,請在「組件」頁面設定。 @@ -802,7 +801,6 @@ 電腦鍵盤 Android 第二螢幕 - 模式 顯示 Android 應用程式 啟動應用程式 @@ -950,13 +948,15 @@ 跟隨裝置旋轉 直向 會話方向 - 套用至 Steam、遊戲、桌面和控制器編輯器。解像度預設會隨會話旋轉;自訂的寬度和高度則維持輸入值。 + 套用至 Steam、遊戲、桌面和控制器編輯器。解像度預設會隨會話旋轉;當一個方向跟隨另一個方向時,自訂的寬度和高度會互換以保持一致。 自動橫向 橫向 反向橫向 全螢幕 隱藏 Android 狀態列和導覽列 顯示 Android 狀態列和導覽列 + 滑動切換頁面 + 在頁面上滑動即可切換標籤。 雙螢幕啟動器 自動會把啟動器各部分(Steam、收藏庫、商店及其他部分)放到內建雙螢幕手持裝置的第二螢幕。開啟會使用任何第二顯示器。關閉會將啟動器保持在單一螢幕。 雙螢幕工作階段 @@ -2434,10 +2434,16 @@ ANDROID + LINUX %1$s。%2$s\n\n%3$s 會話顯示 - 解像度 + 零複製呈現 + 橫向解析度 + 直向解析度 + 跟隨橫向 (%1$d×%2$d) + 跟隨直向 (%1$d×%2$d) 16:9 遊戲顯示方式 16:9 遊戲如何配合此螢幕。下次會話生效。 請選擇「配合螢幕」或比 16:9 更窄的自訂尺寸。 + 避開瀏海 + 讓畫面避開鏡頭挖孔區域。返回工作階段時生效。 保持比例 拉伸至螢幕 畫面縮放 @@ -3981,6 +3987,7 @@ 下載最多 所有類別 找不到插件 + 請先關閉 CurseForge 無法連接 %1$s 沒有適用於此遊戲版本的檔案 重設位置 diff --git a/app/src/main/res/values-zh-rTW/input_library.xml b/app/src/main/res/values-zh-rTW/input_library.xml index 20930002a7..d997b2e0ca 100644 --- a/app/src/main/res/values-zh-rTW/input_library.xml +++ b/app/src/main/res/values-zh-rTW/input_library.xml @@ -103,7 +103,6 @@ 返回 · Steam 裡兩下,桌面上一下 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 d6d0037309..18805781c2 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 和桌面共用。請在「元件」頁面設定。 @@ -802,7 +801,6 @@ 電腦鍵盤 Android 第二螢幕 - 模式 顯示 Android 應用程式 啟動應用程式 @@ -950,13 +948,15 @@ 跟隨裝置旋轉 直向 工作階段方向 - 套用至 Steam、遊戲、桌面和控制器編輯器。解析度預設會隨工作階段旋轉;自訂的寬度和高度則維持輸入值。 + 套用至 Steam、遊戲、桌面和控制器編輯器。解析度預設會隨工作階段旋轉;當一個方向跟隨另一個方向時,自訂的寬度和高度會互換以保持一致。 自動橫向 橫向 反向橫向 全螢幕 隱藏 Android 狀態列和導覽列 顯示 Android 狀態列和導覽列 + 滑動切換頁面 + 在頁面上滑動即可切換分頁。 雙螢幕啟動器 自動:在內建第二螢幕的掌機上,將啟動器區塊(Steam、收藏庫、商店等)放到第二螢幕。開啟:使用任一第二螢幕。關閉:啟動器維持在單一螢幕。 雙螢幕工作階段 @@ -2434,10 +2434,16 @@ ANDROID + LINUX %1$s。%2$s\n\n%3$s 工作階段顯示 - 解析度 + 零複製呈現 + 橫向解析度 + 直向解析度 + 跟隨橫向 (%1$d×%2$d) + 跟隨直向 (%1$d×%2$d) 16:9 遊戲顯示方式 16:9 遊戲如何配合此螢幕。下次工作階段生效。 請選擇「符合螢幕」或比 16:9 更窄的自訂尺寸。 + 避開瀏海 + 讓畫面避開鏡頭挖孔區域。返回工作階段時生效。 維持比例 延展至螢幕 畫面縮放 @@ -3981,6 +3987,7 @@ 下載最多 所有類別 找不到插件 + 請先關閉 CurseForge 無法連線至 %1$s 沒有適用於此遊戲版本的檔案 重設位置 diff --git a/app/src/main/res/values/input_library.xml b/app/src/main/res/values/input_library.xml index 27d018b6e8..b2969a042b 100644 --- a/app/src/main/res/values/input_library.xml +++ b/app/src/main/res/values/input_library.xml @@ -103,7 +103,6 @@ Back · twice in Steam, once in Desktop In Steam mode. Holding Back also opens quick access. Restore to default - Your panel choice is remembered. Desktop opens a second workspace; it does not switch the session or its input profile. Virtual controller The controller type seen by Steam or the game. Touchscreen diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 3f26123f47..f96dbb5a8a 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. @@ -324,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 @@ -707,6 +708,9 @@ Open Quick Access Menu Previous page Next page + Arrange pages + Reset + Done Performance HUD Frame rate Battery temperature @@ -865,7 +869,6 @@ PC keyboard Android Second screen - Mode Shows Android apps Launch an app @@ -1025,13 +1028,17 @@ 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 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 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 @@ -1775,6 +1782,7 @@ This launcher cannot add shortcuts. Use Copy launch link instead. Invalid game launch link. This game is no longer in your DroidDeck library. + Add this game to DroidDeck first, then start it from your frontend. Stop the current session before launching a Steam game. Could not send the game to Steam. Try launching it again. %1$s is a UWP app. This runtime has no Windows app-model host to start it. @@ -2260,6 +2268,8 @@ Deck grips + trackpads Dashboard Desktop + Second screen: %1$s + Last used Start the desktop Desktop · %1$s Trackpad @@ -2715,10 +2725,16 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Session display - Resolution + Zero-copy presentation + 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. + Avoid notch + Keeps the picture out of the camera cutout. Applies when you return to the session. Keep proportions Stretch to display Image scaling @@ -4213,6 +4229,7 @@ Most downloaded All categories No addons found + Close CurseForge first Could not reach %1$s No file for this game version WoWInterface @@ -4315,6 +4332,24 @@ Steam or Desktop options (swipe up) Steam quick menu (•••) Logs + UI zoo + Screens that are hard to reach, shown only when you pick one + Open + Show + Previews change nothing real: nothing is installed, removed or signed out, and the menu\'s switches save nothing. A Library preview stays until you end it from its pill or restart. + Library + Nothing installed + Signed out of every store + Sample games in every store + Preview: %1$s + End preview + Real library + Preview a state + Preview shortcuts + Adds a preview button where a state lives, such as the Library\'s toolbar, to switch states in place + Previews are read-only. End the preview to open games. + In-game menu + In-game menu preview · Back to close Tabs Storage Syncthing @@ -4337,6 +4372,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/frontend/GameFilesTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/GameFilesTest.kt index bcae5c8fec..b5f58de79a 100644 --- a/app/src/test/java/com/droiddeck/launcher/frontend/GameFilesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/frontend/GameFilesTest.kt @@ -33,27 +33,64 @@ class GameFilesTest { assertEquals("18446744073709551615", file.readText()) val context = RuntimeEnvironment.getApplication() listOf(Uri.fromFile(file), Uri.parse(file.path)).forEach { uri -> - assertEquals("18446744073709551615", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, uri))) + assertEquals("18446744073709551615", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, uri))?.id) } val provider = LaunchFileProvider(file) provider.attachInfo(context, android.content.pm.ProviderInfo().apply { authority = "frontend" }) ShadowContentResolver.registerProviderInternal("frontend", provider) val uri = Uri.parse("content://frontend/document/opaque%3A42") - assertEquals("18446744073709551615", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, uri))) + assertEquals("18446744073709551615", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, uri))?.id) + } + + @Test fun readsIdsFromEveryFrontendFileFormat() { + listOf("8400\n", "steam://rungameid/8400", "droiddeck://game/8400", + "# Daijishou Player Template\n[steamappid] 8400\n", "# DST\n[steamappid] 8400\n", + "[InternetShortcut]\r\nIconIndex=0\r\nURL=steam://rungameid/8400\r\nIconFile=C:\\steam.ico\r\n").forEach { value -> + assertEquals(value, "8400", GameFiles.read(ByteArrayInputStream(value.toByteArray()))) + } } @Test fun rejectsCommandsMalformedIdsLargeFilesAndUnsupportedIntents() { - listOf("", "0", "01", "-1", "18446744073709551616", "steam://rungameid/8400", - "8400\n8401", "droiddeck://game/8400", "droiddeck://game/8400?command=quit", "x".repeat(129)).forEach { value -> + listOf("", "0", "01", "-1", "18446744073709551616", "steam://rungameid/8400?x=1", "steam://run/8400", + "8400\n8401", "droiddeck://game/8400?command=quit", "x".repeat(4097), + "[InternetShortcut]\nURL=https://example.com/8400", "[InternetShortcut]\nURL=8400", + "# Daijishou Player Template\n[epicappid] 8400").forEach { value -> assertNull(value, GameFiles.read(ByteArrayInputStream(value.toByteArray()))) } - assertEquals("8400", GameFiles.read(ByteArrayInputStream("8400\n".toByteArray()))) val context = RuntimeEnvironment.getApplication() assertNull(GameFiles.readIntent(context, Intent(Intent.ACTION_SEND, Uri.parse("droiddeck://game/8400")))) assertNull(GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.parse("https://example.com/8400.steam")))) assertNull(GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.parse("file://remote/game.steam")))) assertNull(GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.fromFile(File(tmp.root, "missing.steam"))))) - assertEquals("8400", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.parse("droiddeck://game/8400")))) + assertEquals("8400", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.parse("droiddeck://game/8400")))?.id) + assertEquals("8400", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.parse("8400")))?.id) + assertEquals("8400", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.parse("steam://rungameid/8400")))?.id) + } + + @Test fun storeFilesCarryTheirSourceAndTitle() { + val context = RuntimeEnvironment.getApplication() + val epic = File(tmp.root, "Hades II.epic").apply { writeText("17") } + val request = GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.fromFile(epic)))!! + assertEquals("epic", request.source) + assertEquals("Hades II", request.title) + val daijishou = File(tmp.root, "Portal.steamappid").apply { writeText("# Daijishou Player Template\n[steamappid] 400\n") } + val steam = GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.fromFile(daijishou)))!! + assertEquals(Library.SOURCE_STEAM, steam.source) + assertEquals("400", steam.id) + } + + @Test fun programFilesArriveAsPathsNotContents() { + val context = RuntimeEnvironment.getApplication() + val exe = File(tmp.newFolder("Game"), "Game.exe").apply { writeBytes(byteArrayOf(0x4d, 0x5a)) } + val request = GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.fromFile(exe)))!! + assertEquals(exe.canonicalFile, request.program) + assertNull(request.id) + val provider = LaunchFileProvider(exe) + provider.attachInfo(context, android.content.pm.ProviderInfo().apply { authority = "frontend.files" }) + ShadowContentResolver.registerProviderInternal("frontend.files", provider) + val shared = Uri.parse("content://frontend.files/root" + exe.canonicalPath) + assertEquals(exe.canonicalFile, GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, shared))?.program) + assertNull(GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.fromFile(File(exe.parentFile, "Missing.exe"))))) } @Test fun exportsGameIconBeforeCapsuleAndPreservesCustomArtwork() { @@ -185,13 +222,32 @@ class GameFilesTest { val file = GameFiles.export(app, folder, game("620", "Portal 2")) assertEquals("Portal 2.steam", file.name) assertEquals("620", file.readText()) - assertEquals("620", GameFiles.readIntent(RuntimeEnvironment.getApplication(), Intent(Intent.ACTION_VIEW, Uri.fromFile(file)))) + assertEquals("620", GameFiles.readIntent(RuntimeEnvironment.getApplication(), Intent(Intent.ACTION_VIEW, Uri.fromFile(file)))?.id) val added = Library.SteamGame(1, "Added Game", null, Library.ADDED, -1L) val addedFile = GameFiles.export(app, folder, added) assertEquals("Added Game.steam", addedFile.name) assertEquals("18446744073709551615", addedFile.readText()) } + @Test fun storeGamesExportUnderTheirStoreExtensionAndLaunchBack() { + val folder = tmp.newFolder() + val forza = Library.SteamGame(1, "Forza Horizon 5", null, Library.ADDED, -7L, source = "xbox", storeId = "9NKX70BBCDRN") + val steam = File(folder, "Forza Horizon 5.steam").apply { writeText(forza.gameIdString) } + File(folder, ".droiddeck-sync.json").writeText( + """{"format":"droiddeck-game-files-v1","games":{"Forza Horizon 5.steam":"${forza.gameIdString}"}}""") + GameFiles.sync(app, folder, listOf(forza)) + val file = File(folder, "Forza Horizon 5.xbox") + assertEquals(forza.gameIdString, file.readText()) + assertFalse(steam.exists()) + val request = GameFiles.readIntent(RuntimeEnvironment.getApplication(), Intent(Intent.ACTION_VIEW, Uri.fromFile(file)))!! + assertEquals("xbox", request.source) + assertSame(forza, request.find(listOf(game("620", "Portal 2"), forza))) + listOf("ubisoft", "ea", "rockstar", "battlenet", "itch", "gamejolt", "epic", "gog", "amazon").forEach { store -> + val game = Library.SteamGame(1, "Game", null, Library.ADDED, -8L, source = store) + assertEquals("Game.$store", GameFiles.filename(game)) + } + } + @Test fun steamSyncDisambiguatesTitlesAndPreservesEditedAndForeignFiles() { val folder = tmp.newFolder() val first = game("620", "A/B") diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/GameLaunchIntentTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/GameLaunchIntentTest.kt index 002085daf8..63b6807c0f 100644 --- a/app/src/test/java/com/droiddeck/launcher/frontend/GameLaunchIntentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/frontend/GameLaunchIntentTest.kt @@ -14,29 +14,41 @@ class GameLaunchIntentTest { @Test fun acceptsNativeAndExplicitlyRetargetedGameNativeProfiles() { listOf(GameLaunchIntent.ACTION, "app.gamenative.LAUNCH_GAME").forEach { action -> val request = Intent(action).putExtra("app_id", 620).putExtra("game_source", "STEAM") - assertEquals("620", GameLaunchIntent.read(RuntimeEnvironment.getApplication(), request)) - assertEquals("8400", GameLaunchIntent.readId(Intent(action).putExtra("app_id", "8400"))) - assertEquals("620", GameLaunchIntent.readId(request.putExtra("game_source", "steam"))) + assertEquals("620", GameLaunchIntent.read(RuntimeEnvironment.getApplication(), request)?.id) + assertEquals("8400", GameLaunchIntent.readExtras(Intent(action).putExtra("app_id", "8400"))?.id) + assertEquals("620", GameLaunchIntent.readExtras(request.putExtra("game_source", "steam"))?.id) } } - @Test fun stringIdsPreserveUnsignedShortcutIds() { + @Test fun longAndStringIdsPreserveUnsignedShortcutIds() { listOf("2147483648", "18446744073709551615").forEach { id -> - assertEquals(id, GameLaunchIntent.readId(Intent(GameLaunchIntent.ACTION).putExtra("app_id", id))) + assertEquals(id, GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", id))?.id) + } + assertEquals("620", GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 620L))?.id) + assertEquals("18446744073709551615", GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", -1L))?.id) + } + + @Test fun storeSourcesComeThroughForLibraryMatching() { + mapOf("EPIC" to "epic", "gog" to "gog", "AMAZON" to "amazon", "XBOX" to "xbox", "UBISOFT" to "ubisoft", + "EA" to "ea", "ROCKSTAR" to "rockstar", "BATTLENET" to "battlenet", "ITCH" to "itch", "GAMEJOLT" to "gamejolt", + "CUSTOM_GAME" to Library.ADDED).forEach { (name, source) -> + val request = GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 1207658924).putExtra("game_source", name)) + assertEquals(name, source, request?.source) + assertEquals("1207658924", request?.id) } } @Test fun rejectsUnsupportedSourcesTypesAndIdsWithoutFallingBackToData() { listOf("", "0", "01", "+1", "-1", "18446744073709551616", "620\n", "steam://rungameid/620").forEach { id -> - assertNull(id, GameLaunchIntent.readId(Intent(GameLaunchIntent.ACTION).putExtra("app_id", id))) + assertNull(id, GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", id))) } - listOf("EPIC", "GOG", "CUSTOM_GAME", "", "STEAM ").forEach { source -> - assertNull(GameLaunchIntent.readId(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 620).putExtra("game_source", source))) + listOf("STADIA", "", "STEAM ", "added").forEach { source -> + assertNull(GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 620).putExtra("game_source", source))) } - assertNull(GameLaunchIntent.readId(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 620L))) - assertNull(GameLaunchIntent.readId(Intent(GameLaunchIntent.ACTION).putExtra("app_id", -1))) - assertNull(GameLaunchIntent.readId(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 620).putExtra("game_source", 1))) - assertNull(GameLaunchIntent.readId(Intent(Intent.ACTION_MAIN).putExtra("app_id", 620))) + assertNull(GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 0L))) + assertNull(GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", -1))) + assertNull(GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 620).putExtra("game_source", 1))) + assertNull(GameLaunchIntent.readExtras(Intent(Intent.ACTION_MAIN).putExtra("app_id", 620))) assertNull(GameLaunchIntent.read(RuntimeEnvironment.getApplication(), Intent(GameLaunchIntent.ACTION, android.net.Uri.parse("droiddeck://game/620")))) } @@ -44,7 +56,7 @@ class GameLaunchIntentTest { @Test fun deepLinksStillAcceptUnsignedShortcutIds() { val context = RuntimeEnvironment.getApplication() assertEquals("18446744073709551615", GameLaunchIntent.read(context, - Intent(Intent.ACTION_VIEW, android.net.Uri.parse("droiddeck://game/18446744073709551615")))) + Intent(Intent.ACTION_VIEW, android.net.Uri.parse("droiddeck://game/18446744073709551615")))?.id) assertFalse(GameLaunchIntent.accepts(Intent.ACTION_SEND)) assertTrue(GameLaunchIntent.accepts(GameLaunchIntent.ACTION)) } diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/GameRequestTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/GameRequestTest.kt new file mode 100644 index 0000000000..d7a50728c7 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/frontend/GameRequestTest.kt @@ -0,0 +1,62 @@ +package com.droiddeck.launcher.frontend + +import org.junit.Assert.* +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File + +class GameRequestTest { + @get:Rule val tmp = TemporaryFolder() + + private fun game(id: Long, name: String, source: String = Library.SOURCE_STEAM, storeId: String? = null, files: File? = null, + library: String = "internal", appId: Int = id.toInt()) = + Library.SteamGame(appId, name, null, library, id, gameFiles = files, source = source, storeId = storeId) + + @Test fun steamIdsMatchTheGameIdOrAnAddedGamesSteamAppId() { + val portal = game(400, "Portal") + val added = game(-1L, "Celeste", library = Library.ADDED, source = Library.ADDED, appId = 504230) + val games = listOf(portal, added) + assertSame(portal, GameRequest("400").find(games)) + assertSame(added, GameRequest("18446744073709551615").find(games)) + assertSame(added, GameRequest("504230").find(games)) + assertNull(GameRequest("401").find(games)) + } + + @Test fun titleMatchingWaitsForTheFullScan() { + val cached = game(-2L, "Example", source = "gog", storeId = "111") + assertNull(GameRequest("222", "gog", "Example").find(listOf(cached), byTitle = false)) + assertSame(cached, GameRequest("222", "gog", "Example").find(listOf(cached))) + assertSame(cached, GameRequest("111", "gog", "Other").find(listOf(cached), byTitle = false)) + } + + @Test fun gogMatchesItsProductIdThenTitle() { + val witcher = game(-2L, "The Witcher 3: Wild Hunt", source = "gog", storeId = "1207664663") + val games = listOf(game(292030, "The Witcher 3: Wild Hunt"), witcher) + assertSame(witcher, GameRequest("1207664663", "gog").find(games)) + assertSame(witcher, GameRequest("5", "gog", "The Witcher 3 Wild Hunt").find(games)) + } + + @Test fun storesWithAppLocalIdsMatchByTitleWithinTheirStore() { + val hades = game(-3L, "Hades II", source = "epic", storeId = "Ixion") + val custom = game(-4L, "Cave Story+", library = Library.ADDED, source = Library.ADDED) + val games = listOf(game(1145350, "Hades II"), hades, custom) + assertSame(hades, GameRequest("17", "epic", "hades ii").find(games)) + assertSame(custom, GameRequest("9", Library.ADDED, "Cave Story").find(games)) + assertNull(GameRequest("17", "epic").find(games)) + assertNull(GameRequest("17", "amazon", "Hades II").find(games)) + } + + @Test fun programsStartTheDeepestGameThatOwnsThem() { + val root = tmp.newFolder("Games") + val suite = File(root, "Suite").apply { mkdirs() } + val inner = File(suite, "Episode 2").apply { mkdirs() } + val outer = game(-5L, "Suite", files = suite) + val episode = game(-6L, "Episode 2", files = inner) + val games = listOf(outer, episode) + assertSame(episode, GameRequest(program = File(inner, "bin/game.exe")).find(games)) + assertSame(outer, GameRequest(program = File(suite, "launcher.exe")).find(games)) + assertNull(GameRequest(program = File(root, "Other/other.exe")).find(games)) + assertNull(GameRequest(program = File(root, "Suite2/game.exe")).find(games)) + } +} 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/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/InputLibraryTest.kt b/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt index 9c81655b0a..a5472bae6f 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt @@ -1,6 +1,8 @@ package com.droiddeck.launcher.input import android.content.Context +import android.content.ContextWrapper +import android.content.SharedPreferences import org.json.JSONObject import org.junit.Assert.* import org.junit.Before @@ -48,6 +50,100 @@ class InputLibraryTest { assertEquals(library, InputLibraries.decode(InputLibraries.encode(library))) } + @Test fun reopeningARedesignLibraryRestoresTheGamepadAndKeepsCustomBindings() { + val original = InputLibraries.read(context) + val overlay = original.activeLayout(false, InputRole.PRIMARY)!! + val custom = InputSurfaceElement(InputControl.A, .98f, .2f, .02f, .02f, id = "extra") + val preset = original.preset(original.profile("game").binding(InputRole.PRIMARY)) + val saved = original.copy( + layouts = original.layouts.map { if (it.id == overlay.id) it.copy(elements = listOf(custom), aspect = 0f) else it }, + bindings = original.bindings.map { + if (it.id == preset.id) it.copy(elements = it.elements + mapOf("extra" to InputAction.Keys(listOf(29)), + "legacy:a" to InputAction.Keys(listOf(30)))) else it + }, + ) + for (version in 15..16) { + val raw = JSONObject(InputLibraries.encode(saved)).put("version", version).toString() + prefs.edit().putString("library", raw).commit() + + val restored = InputLibraries.read(context) + val layout = restored.activeLayout(false, InputRole.PRIMARY)!! + assertTrue(layout.elements.any { it.id == "legacy:a" }) + assertEquals(custom.bounded(), layout.elements.single { it.id == "extra" }) + assertEquals(InputAction.Keys(listOf(30)), restored.preset(preset.id).elements["legacy:a"]) + assertEquals(InputAction.Keys(listOf(29)), restored.preset(preset.id).elements["extra"]) + assertEquals(raw, prefs.getString("library-before-controller-revert", null)) + assertEquals(restored, InputLibraries.read(context)) + assertEquals(restored, InputLibraries.update(context) { it }) + } + } + + @Test fun failedRollbackBackupLeavesTheLayoutUsableAndRetriesLater() { + val original = InputLibraries.read(context) + val raw = JSONObject(InputLibraries.encode(original)).put("version", 16).toString() + val backup = "library-before-controller-revert" + prefs.edit().putString("library", raw).putString(backup, "previous backup").commit() + + assertEquals(original, InputLibraries.read(contextWithFailedCommits())) + assertEquals(raw, prefs.getString("library", null)) + assertEquals("previous backup", prefs.getString(backup, null)) + + assertEquals(original, InputLibraries.read(context)) + assertEquals(14, JSONObject(prefs.getString("library", null)!!).getInt("version")) + assertEquals(raw, prefs.getString(backup, null)) + } + + @Test fun failedRecoveryRestoresBothValuesAndTheNextEditRetriesRecovery() { + val raw = "unreadable library" + val backup = "library-recovery." + java.util.UUID.nameUUIDFromBytes(raw.toByteArray(Charsets.UTF_8)) + prefs.edit().putString("library", raw).putString(backup, "previous backup").commit() + val failing = contextWithFailedCommits() + + repeat(2) { + assertThrows(IllegalStateException::class.java) { InputLibraries.update(failing) { it } } + assertEquals(raw, prefs.getString("library", null)) + assertEquals("previous backup", prefs.getString(backup, null)) + } + InputLibraries.update(context) { it } + assertEquals(raw, prefs.getString(backup, null)) + assertNotNull(InputLibraries.decode(prefs.getString("library", null)!!)) + } + + private fun contextWithFailedCommits(): Context = object : ContextWrapper(context) { + override fun getSharedPreferences(name: String, mode: Int): SharedPreferences { + val original = super.getSharedPreferences(name, mode) + if (name != "input-profiles") return original + return object : SharedPreferences by original { + override fun edit(): SharedPreferences.Editor { + val editor = original.edit() + return object : SharedPreferences.Editor by editor { + override fun putString(key: String, value: String?): SharedPreferences.Editor { + editor.putString(key, value) + return this + } + + override fun commit(): Boolean { + editor.apply() + return false + } + } + } + } + } + } + + @Test fun revertingKeepsIntentionallyEmptyGamepadsEmpty() { + val original = InputLibraries.read(context) + val doc = JSONObject(InputLibraries.encode(original)).put("version", 16) + val layouts = doc.getJSONArray("layouts") + val overlay = (0 until layouts.length()).map(layouts::getJSONObject) + .single { it.getString("id") == InputLibraries.OVERLAY } + overlay.put("kitless", true).put("elements", org.json.JSONArray()) + prefs.edit().putString("library", doc.toString()).commit() + + assertTrue(InputLibraries.read(context).activeLayout(false, InputRole.PRIMARY)!!.elements.isEmpty()) + } + @Test fun legacyLowerScreenBindingsKeepTheirOriginalControlsWithoutSavedGeometry() { prefs.edit().putBoolean("migrated", true).putString("profile.game", """{"version":1,"bindings":[{"role":"SECONDARY","control":"a","action":{"type":"keys","codes":[57]}}]}""").commit() 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..1fa557b6d9 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,7 +49,43 @@ 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.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 }, 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_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()) @@ -51,6 +98,7 @@ class OnScreenLayoutTest { @Test @Config(qualifiers = "w745dp-h343dp-land-420dpi") fun aBuiltInGamepadSavedAtTheDisplaySizeRegeneratesForTheMeasuredSurface() { + 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()) assertEquals(LegacyGamepadLayout(context, 2048, 1200).regenerate(saved.elements), placed) @@ -58,6 +106,7 @@ class OnScreenLayoutTest { @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 +115,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 +171,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_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" }) @@ -136,6 +186,47 @@ 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, 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) + 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) @@ -188,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)) @@ -215,6 +307,86 @@ 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) + 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:") } @@ -310,6 +482,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) @@ -366,4 +539,164 @@ 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 = "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) { + 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/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..d32edcdd8d 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,14 +101,22 @@ 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) } } + @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 -> 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/runtime/CurseForgeAppTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt new file mode 100644 index 0000000000..47d892993b --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt @@ -0,0 +1,570 @@ +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.After +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 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":[ + {"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 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)) + 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)) + } + } + + @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)) + } + + 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")) + assertNull(CurseForgeApp.lastJson(listOf("noise"))) + } +} 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..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")) @@ -150,8 +156,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 +168,66 @@ 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 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() { 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..6ea502407e 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,100 @@ 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".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") + 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", "X-Curse-Project-ID" to "9"), 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() } + 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")) + 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")) + } } 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)) + } +} 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/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/LightPauseTest.kt b/app/src/test/java/com/droiddeck/launcher/session/LightPauseTest.kt deleted file mode 100644 index 8e14b74147..0000000000 --- a/app/src/test/java/com/droiddeck/launcher/session/LightPauseTest.kt +++ /dev/null @@ -1,56 +0,0 @@ -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 LightPauseTest { - @Test - fun theBounceAloneResumesLight() { - val pause = LightPause() - pause.paused(bounces = 3) - assertEquals(LightPause.Resume.LIGHT, pause.resumed(bounces = 4)) - assertFalse(pause.timedOut()) - } - - @Test - fun anUnrelatedPauseWithoutABounceCleansUpAtTheTimeout() { - val pause = LightPause() - pause.paused(bounces = 3) - assertTrue(pause.timedOut()) - assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 3)) - } - - @Test - fun aBounceWhileAnotherActivityHoldsThePauseStillCleansUpAtTheTimeout() { - val pause = LightPause() - pause.paused(bounces = 3) - assertTrue(pause.timedOut()) - assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 4)) - } - - @Test - fun aResumeBeforeTheTimeoutWithoutABounceCleansUpFirst() { - val pause = LightPause() - pause.paused(bounces = 3) - assertEquals(LightPause.Resume.CLEANUP_FIRST, pause.resumed(bounces = 3)) - assertFalse(pause.timedOut()) - } - - @Test - fun aStopAfterALightPauseCleansUpOnce() { - val pause = LightPause() - pause.paused(bounces = 3) - assertTrue(pause.stopped()) - assertFalse(pause.timedOut()) - assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 4)) - } - - @Test - fun aNormalPauseIsUntouched() { - val pause = LightPause() - assertFalse(pause.stopped()) - assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 0)) - } -} 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/app/src/test/java/com/droiddeck/launcher/session/PipPolicyTest.kt b/app/src/test/java/com/droiddeck/launcher/session/PipPolicyTest.kt index 1261abd542..ad4f169c44 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/PipPolicyTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/PipPolicyTest.kt @@ -18,6 +18,12 @@ class PipPolicyTest { assertFalse(PipPolicy.eligible(true, false, SessionPhase.SUSPENDED, true, false)) } + @Test fun goingHomeFloatsOnlyGamesDroidDeckLaunchedItself() { + assertTrue(PipPolicy.autoEnter(enabled = true, launchedByAnotherApp = false)) + assertFalse(PipPolicy.autoEnter(enabled = true, launchedByAnotherApp = true)) + assertFalse(PipPolicy.autoEnter(enabled = false, launchedByAnotherApp = false)) + } + @Test fun aspectRatiosStayWithinAndroidLimitsWithoutChangingNormalContent() { assertEquals(1920 to 1080, PipPolicy.aspect(1920, 1080)) assertEquals(239 to 100, PipPolicy.aspect(5760, 1080)) 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..fb9199157b --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt @@ -0,0 +1,97 @@ +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 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 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)) + } + + @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)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionBackgroundPrefsTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionBackgroundPrefsTest.kt index f7ba39b65f..b1dcbc4e4a 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionBackgroundPrefsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionBackgroundPrefsTest.kt @@ -29,6 +29,16 @@ class SessionBackgroundPrefsTest { } } + @Test fun steamAndQuickAccessFallsBackToAutoOutsideSteam() { + SessionPrefs.setOscMode(context, SessionPrefs.OSC_STEAM_QAM) + assertEquals(SessionPrefs.OSC_AUTO, SessionPrefs.oscMode(context, steamSession = false)) + assertEquals(SessionPrefs.OSC_STEAM_QAM, SessionPrefs.oscMode(context)) + assertEquals(SessionPrefs.OSC_STEAM_QAM, SessionPrefs.oscMode(context, steamSession = true)) + + SessionPrefs.setOscMode(context, SessionPrefs.OSC_ALWAYS) + assertEquals(SessionPrefs.OSC_ALWAYS, SessionPrefs.oscMode(context, steamSession = false)) + } + @Test fun automaticPipDefaultsOnAndHonorsSavedChoices() { assertEquals(true, SessionPrefs.pipAutoEnter(context)) SessionPrefs.setPipAutoEnter(context, false) 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..f8dd6e34e2 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(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)) diff --git a/app/src/test/java/com/droiddeck/launcher/session/SteamGameProcessTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SteamGameProcessTest.kt index ae9b31d80c..5e68b5fee9 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SteamGameProcessTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SteamGameProcessTest.kt @@ -88,4 +88,17 @@ class SteamGameProcessTest { process("301", "reaper", "SteamLaunch", "AppId=351710", "--", "proton", "waitforexitandrun", "game.exe") assertTrue(SteamGameProcess.running("351710", proc)) } + + @Test fun onlyTheRunningCurrentGameCountsAsAlreadyRunning() { + val proc = tmp.newFolder("proc-relaunch") + File(proc, "200").apply { mkdirs() }.resolve("cmdline") + .writeBytes(cmdline("reaper", "SteamLaunch", "AppId=584400", "--", "proton", "waitforexitandrun", "SonicMania.exe")) + assertTrue(SteamGameProcess.alreadyRunning("584400", "584400", proc)) + assertFalse(SteamGameProcess.alreadyRunning("584400", "311340", proc)) + assertFalse(SteamGameProcess.alreadyRunning("311340", "311340", proc)) + assertFalse(SteamGameProcess.alreadyRunning("584400", null, proc)) + val shortcutId = ((584400uL shl 32) or 0x02000000uL).toString() + assertTrue(SteamGameProcess.alreadyRunning(shortcutId, "584400", proc)) + assertTrue(SteamGameProcess.alreadyRunning("584400", shortcutId, proc)) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/session/TopUnderPressureTest.kt b/app/src/test/java/com/droiddeck/launcher/session/TopUnderPressureTest.kt deleted file mode 100644 index ac0ec06843..0000000000 --- a/app/src/test/java/com/droiddeck/launcher/session/TopUnderPressureTest.kt +++ /dev/null @@ -1,25 +0,0 @@ -package com.droiddeck.launcher.session - -import android.content.ComponentCallbacks2 -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Test - -class TopUnderPressureTest { - @Test - fun onlyRunningLevelsCountAsPressure() { - assertTrue(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL)) - assertTrue(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW)) - assertFalse(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE)) - assertFalse(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN)) - } - - @Test - fun reclaimsOnlyDuringASessionShortlyAfterPressure() { - assertTrue(TopUnderPressure.shouldReclaim(10_000, 9_500, sessionRunning = true, finishing = false)) - assertFalse(TopUnderPressure.shouldReclaim(20_000, 9_500, sessionRunning = true, finishing = false)) - assertFalse(TopUnderPressure.shouldReclaim(10_000, 0, sessionRunning = true, finishing = false)) - assertFalse(TopUnderPressure.shouldReclaim(10_000, 9_500, sessionRunning = false, finishing = false)) - assertFalse(TopUnderPressure.shouldReclaim(10_000, 9_500, sessionRunning = true, finishing = true)) - } -} 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/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/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/BottomScreenBarTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/BottomScreenBarTest.kt index 97389fa285..2af8942ca2 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/BottomScreenBarTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/BottomScreenBarTest.kt @@ -1,8 +1,11 @@ package com.droiddeck.launcher.ui import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import com.droiddeck.launcher.R +import com.droiddeck.launcher.input.SecondScreenMode import com.droiddeck.launcher.session.SessionService import com.droiddeck.launcher.session.SessionState import org.junit.After @@ -75,4 +78,35 @@ class BottomScreenBarTest { compose.onNodeWithContentDescription(context.getString(R.string.drawer_steam_menu)).assertDoesNotExist() compose.onNodeWithContentDescription(context.getString(R.string.drawer_open_qam)).assertDoesNotExist() } + + @Test fun thePanelNameOpensTheScreenPickerInsteadOfAMenuButton() { + var menus = 0 + val picked = mutableListOf() + val modes = listOf(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL, SecondScreenMode.CUSTOM_CONTROLS) + compose.setContent { + DroidDeckTheme { + BottomScreenBar(BottomBarModel("Trackpad", {}, { menus++ }, null, null, + picker = ScreenPicker(modes, SecondScreenMode.KEYBOARD_TRACKPAD, { picked += it }, onMenu = { menus++ }))) + } + } + compose.onNodeWithTag("bottom-bar-menu").assertDoesNotExist() + compose.onNodeWithText(context.getString(R.string.second_mode_keyboard_trackpad)).assertExists() + compose.onNodeWithTag("bottom-bar-screen").performClick() + compose.onNodeWithTag("screen-picker:${SecondScreenMode.TERMINAL.id}").performClick() + compose.waitForIdle() + assertEquals(listOf(SecondScreenMode.TERMINAL), picked) + compose.onNodeWithTag("screen-picker:${SecondScreenMode.TERMINAL.id}").assertDoesNotExist() + compose.onNodeWithTag("bottom-bar-screen").performClick() + compose.onNodeWithTag("screen-picker-menu").performClick() + compose.waitForIdle() + assertEquals(1, menus) + } + + @Test fun focusStartsOnTheMenuFromAPanelAndOnThePanelFromTheMenu() { + val modes = listOf(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL) + assertNull(ScreenPicker(modes, SecondScreenMode.TERMINAL, {}, onMenu = {}).focusTarget()) + assertEquals(SecondScreenMode.TERMINAL, ScreenPicker(modes, SecondScreenMode.TERMINAL, {}, onMenu = {}, menuShown = true).focusTarget()) + assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, ScreenPicker(modes, SecondScreenMode.NONE, {}, onMenu = {}, menuShown = true).focusTarget()) + assertEquals(SecondScreenMode.TERMINAL, ScreenPicker(modes, SecondScreenMode.TERMINAL, {}).focusTarget()) + } } 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 new file mode 100644 index 0000000000..0ea4048e3a --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt @@ -0,0 +1,253 @@ +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.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.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) +@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 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() } + } + } + + 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() + 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/InputSettingsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt index 8def5601a4..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() @@ -522,6 +534,127 @@ 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)!! + 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..d322a387df 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,46 @@ 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.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 +126,185 @@ 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) + } + + @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 + 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 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" } + 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 + +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<*> } 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..cd92665cc2 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,25 @@ 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)) + 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)) + } + @Test fun aStickKeepsItsFingerWhenItCrossesAButton() { touch(MotionEvent.ACTION_DOWN, 1 to (200f to 300f)) touch(MotionEvent.ACTION_MOVE, 1 to (800f to 240f)) diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt index 772578ea37..b168587e09 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt @@ -96,9 +96,9 @@ class LibraryEntriesTest { } @Test fun placesRoundTripThroughTheirOrder() { - val order = listOf("epic", "steam", "favorites", "gog", "xbox", "added") + val order = listOf("epic", "steam", "favorites", LIBRARY_HIDDEN, "gog", "xbox", "added") assertEquals(order, placeLibraryTabs(listOf("epic", "gog", "xbox"), libraryPlacesOf(order))) - assertEquals(listOf("favorites", "steam", "epic", "gog", "added"), placeLibraryTabs(listOf("epic", "gog"), emptyList())) + assertEquals(listOf("favorites", "steam", "epic", "gog", "added", LIBRARY_HIDDEN), placeLibraryTabs(listOf("epic", "gog"), emptyList())) } @Test fun librarySourcesIgnoreUnknownAndDuplicateOrderEntriesAndAppendNewStores() { diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LibraryFavoritesTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LibraryFavoritesTest.kt index c2ce77dbf7..8a8cf59736 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/LibraryFavoritesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/LibraryFavoritesTest.kt @@ -53,6 +53,6 @@ class LibraryFavoritesTest { @Test fun aHiddenFavoritesTabStaysHiddenWithHeartedGames() { val entries = listOf(steam(440, "Team Fortress 2"), owned("123", "Witcher")) - assertEquals(listOf("steam", "gog"), librarySources(entries, listOf("gog"), favorites = setOf("gog:123"), offTabs = setOf(LIBRARY_FAVORITES))) + assertEquals(listOf("steam", "gog"), librarySources(entries, listOf("gog"), favorites = setOf("gog:123"), offTabs = setOf(LIBRARY_FAVORITES, LIBRARY_HIDDEN))) } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LibraryHiddenTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LibraryHiddenTest.kt index ac5835c2a5..0cea327e82 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/LibraryHiddenTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/LibraryHiddenTest.kt @@ -30,10 +30,16 @@ class LibraryHiddenTest { assertFalse(inLibrarySource(LIBRARY_HIDDEN, cs, emptySet(), hidden)) } - @Test fun theHiddenTabIsLastAndOnlyWhenEnabled() { + @Test fun theHiddenTabIsLastAndOnlyWhenTurnedOn() { val entries = listOf(tf2, cs) assertEquals(listOf(Library.SOURCE_STEAM), librarySources(entries, emptyList(), hidden = hidden)) - assertEquals(listOf(Library.SOURCE_STEAM, LIBRARY_HIDDEN), librarySources(entries, emptyList(), hidden = hidden, showHidden = true)) + assertEquals(listOf(Library.SOURCE_STEAM, LIBRARY_HIDDEN), librarySources(entries, emptyList(), hidden = hidden, offTabs = emptySet())) + } + + @Test fun theHiddenTabSortsLastUnlessMoved() { + assertEquals(listOf(LIBRARY_FAVORITES, Library.SOURCE_STEAM, "epic", Library.ADDED, LIBRARY_HIDDEN), placeLibraryTabs(listOf("epic"), DEFAULT_LIBRARY_PLACES)) + val moved = placeLibraryTabs(listOf("epic"), listOf(LIBRARY_HIDDEN to "epic")) + assertEquals(listOf("epic", LIBRARY_HIDDEN), moved.filter { it == "epic" || it == LIBRARY_HIDDEN }) } @Test fun aStoreTabWithOnlyHiddenGamesDisappears() { 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()) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SecondScreenBarTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SecondScreenBarTest.kt index 4779843153..a2e7f61c31 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SecondScreenBarTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SecondScreenBarTest.kt @@ -76,9 +76,10 @@ class SecondScreenBarTest { return (0 until root.childCount).map { root.getChildAt(it) } } - @Test fun trackpadPanelHasTheBarWithTheKeyboardToggleState() { + @Test fun trackpadPanelHasTheBarWithTheKeyboardToggleStateAndSwap() { SessionState.mode = SessionService.MODE_STEAM - val panel = presentation() + var swaps = 0 + val panel = presentation { swaps++ } try { panel.show() panel.showMode(SecondScreenMode.KEYBOARD_TRACKPAD) @@ -89,11 +90,15 @@ class SecondScreenBarTest { assertEquals(context.getString(R.string.second_mode_keyboard_trackpad), bar.title) assertNotNull(bar.onClose); assertNotNull(bar.onMenu); assertNotNull(bar.onSteam); assertNotNull(bar.onQam) assertNull(bar.tabs) - val keyboard = bar.extras.single() + assertEquals(listOf("bottom-keyboard", "bottom-swap"), bar.extras.map { it.tag }) + val keyboard = bar.extras.first() assertEquals(context.getString(R.string.second_show_keyboard), keyboard.description) assertFalse(keyboard.active) + bar.extras.last().onClick() + assertEquals(1, swaps) + assertEquals(listOf("bottom-keyboard", "bottom-swap"), panel.barModel(SecondScreenMode.TERMINAL)!!.extras.map { it.tag }) ReflectionHelpers.getField>(panel, "keyboardShown").value = true - val shown = panel.barModel(SecondScreenMode.KEYBOARD_TRACKPAD)!!.extras.single() + val shown = panel.barModel(SecondScreenMode.KEYBOARD_TRACKPAD)!!.extras.first() assertEquals(context.getString(R.string.second_hide_keyboard), shown.description) assertTrue(shown.active) } finally { panel.closeControls() } @@ -130,6 +135,8 @@ class SecondScreenBarTest { noSwap.show() noSwap.showMode(SecondScreenMode.DECK_CONTROLS) assertTrue(noSwap.barModel(SecondScreenMode.DECK_CONTROLS)!!.extras.isEmpty()) + assertEquals(listOf("bottom-keyboard"), noSwap.barModel(SecondScreenMode.TERMINAL)!!.extras.map { it.tag }) + assertEquals(listOf("bottom-keyboard"), noSwap.barModel(SecondScreenMode.KEYBOARD_TRACKPAD)!!.extras.map { it.tag }) } finally { noSwap.closeControls() } } 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 58b8ba055b..019f47784c 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt @@ -4,33 +4,42 @@ import org.junit.Assert.* import org.junit.Test class SessionDrawerPageTest { - @Test fun singleScreenNavigationStartsWithControllerAndSkipsSecondScreen() { - val pages = sessionDrawerPages(false, hasAgent = false) + @Test fun navigationStartsWithControllerAndGoesStraightToDisplay() { + val pages = sessionDrawerPages(hasAgent = false) assertEquals(SessionDrawerPage.CONTROLLER, pages.first()) - assertFalse(SessionDrawerPage.SECOND_SCREEN in pages) 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.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.SESSION, pages.step(SessionDrawerPage.GAMES, 1)) } - @Test fun connectedSecondaryDisplayAddsItsPageAfterControllerAndPreservesOtherPages() { - val connected = sessionDrawerPages(true, hasAgent = false) - assertEquals(SessionDrawerPage.SECOND_SCREEN, connected.step(SessionDrawerPage.CONTROLLER, 1)) - assertEquals(SessionDrawerPage.DISPLAY, connected.step(SessionDrawerPage.SECOND_SCREEN, 1)) - assertEquals(sessionDrawerPages(false, hasAgent = false), connected.filter { it != SessionDrawerPage.SECOND_SCREEN }) - for (pages in listOf(connected, sessionDrawerPages(false, hasAgent = false))) { - 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.SESSION, pages.step(SessionDrawerPage.GAMES, 1)) - } + @Test fun glassesAddTheirPageAfterController() { + val pages = sessionDrawerPages(hasGlasses = true, hasAgent = false) + assertEquals(SessionDrawerPage.GLASSES, pages.step(SessionDrawerPage.CONTROLLER, 1)) + assertEquals(sessionDrawerPages(hasAgent = false), pages.filter { it != SessionDrawerPage.GLASSES }) } @Test fun theAgentPageComesBeforeSessionOnlyWhenTheTabIsShown() { - val with = sessionDrawerPages(false, hasAgent = true) + val with = sessionDrawerPages(hasAgent = true) assertEquals(SessionDrawerPage.AGENT, with.step(SessionDrawerPage.GAMES, 1)) assertEquals(SessionDrawerPage.SESSION, with.step(SessionDrawerPage.AGENT, 1)) - assertFalse(SessionDrawerPage.AGENT in sessionDrawerPages(false, hasAgent = false)) + 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)) } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt index dc2ff1cc6c..c45b32d234 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt @@ -83,7 +83,7 @@ class SessionSecondScreenTest { var selected = SecondScreenMode.CUSTOM_CONTROLS compose.setContent { DroidDeckTheme { - SessionDrawer(true, SessionDrawerPage.SECOND_SCREEN, false, {}, + SessionDrawer(true, SessionDrawerPage.CONTROLLER, false, {}, actions(true, listOf(SecondScreenDisplay(1, "Bottom screen")), onClose = { closes++ }, select = { selected = it }), docked = true) } @@ -93,18 +93,47 @@ class SessionSecondScreenTest { assertEquals(SecondScreenMode.CUSTOM_CONTROLS, selected) } - @Test fun desktopWithoutASecondDisplayFallsBackToController() { + @Test fun desktopWithoutASecondDisplayHasNoScreenPicker() { SessionState.mode = SessionService.MODE_DESKTOP - var page = SessionDrawerPage.SECOND_SCREEN compose.setContent { DroidDeckTheme { - SessionDrawer(true, page, false, { page = it }, actions(false, emptyList())) + SessionDrawer(true, SessionDrawerPage.CONTROLLER, false, {}, actions(false, emptyList())) } } - compose.runOnIdle { assertEquals(SessionDrawerPage.CONTROLLER, page) } + compose.onNodeWithTag("drawer-screen-picker").assertDoesNotExist() compose.onNodeWithText(context.getString(R.string.second_mode_keyboard_trackpad)).assertDoesNotExist() } + @Test fun dockedMenuPickerReturnsToThePanelAndHasNoMenuButton() { + SessionState.mode = SessionService.MODE_STEAM + val selected = mutableListOf() + compose.setContent { + DroidDeckTheme { + SessionDrawer(true, SessionDrawerPage.CONTROLLER, false, {}, + actions(true, listOf(SecondScreenDisplay(1, "Bottom screen")), mode = SecondScreenMode.TERMINAL) { selected += it }, + docked = true) + } + } + compose.onNodeWithTag("bottom-bar-menu").assertDoesNotExist() + compose.onNodeWithContentDescription(context.getString(R.string.screen_picker_description, + context.getString(R.string.touch_droiddeck_menu))).performClick() + compose.onNodeWithTag("screen-picker-menu").assertExists() + compose.onNodeWithTag("screen-picker:${SecondScreenMode.TERMINAL.id}").performClick() + assertEquals(listOf(SecondScreenMode.TERMINAL), selected) + } + + @Test fun displayPageCarriesTheGameScreenAndDisplayChoices() { + SessionState.mode = SessionService.MODE_STEAM + compose.setContent { + DroidDeckTheme { + SessionDrawer(true, SessionDrawerPage.DISPLAY, false, {}, + actions(true, listOf(SecondScreenDisplay(1, "Bottom screen"), SecondScreenDisplay(2, "Monitor")), gameSwap = true)) + } + } + compose.onNodeWithText(context.getString(R.string.swap_game_screen)).performScrollTo().assertIsDisplayed() + compose.onNodeWithText("Bottom screen").performScrollTo().assertIsDisplayed() + } + @Test fun provisionalBottomScreenPanelSettlesOnlyOnceTheSessionIsInFront() { SessionState.mode = SessionService.MODE_STEAM val previousMode = SessionState.secondScreenMode @@ -236,7 +265,7 @@ class SessionSecondScreenTest { state("drawerOpenState").value = true state("drawerControllerActive").value = true state>("secondScreenDisplays").value = listOf(SecondScreenDisplay(1, "Bottom screen")) - for ((button, page) in listOf(KeyEvent.KEYCODE_BUTTON_R1 to SessionDrawerPage.SECOND_SCREEN, + for ((button, page) in listOf(KeyEvent.KEYCODE_BUTTON_R1 to SessionDrawerPage.DISPLAY, KeyEvent.KEYCODE_BUTTON_L1 to SessionDrawerPage.CONTROLLER)) { assertTrue(activity.dispatchKeyEvent(KeyEvent(0L, 0L, KeyEvent.ACTION_DOWN, button, 0, 0, device.id, 0, 0, InputDevice.SOURCE_GAMEPAD))) @@ -351,14 +380,16 @@ class SessionSecondScreenTest { val displays = listOf(SecondScreenDisplay(1, "Bottom screen")) compose.setContent { DroidDeckTheme { - SessionDrawer(true, SessionDrawerPage.SECOND_SCREEN, false, {}, actions(steam, displays) { selected += it }) + SessionDrawer(true, SessionDrawerPage.CONTROLLER, false, {}, actions(steam, displays) { selected += it }) } } val modes = listOf(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL, SecondScreenMode.CUSTOM_CONTROLS) for (mode in modes) { - compose.onNodeWithText(context.getString(mode.label)).performScrollTo().assertIsDisplayed().performClick() + compose.onNodeWithTag("drawer-screen-picker").performClick() + compose.onNodeWithTag("screen-picker-menu").assertDoesNotExist() + compose.onNodeWithTag("screen-picker:${SecondScreenMode.DECK_CONTROLS.id}").assertDoesNotExist() + compose.onNodeWithTag("screen-picker:${mode.id}").assertIsDisplayed().performClick() } - compose.onNodeWithText(context.getString(SecondScreenMode.DECK_CONTROLS.label)).assertDoesNotExist() assertEquals(modes, selected) } @@ -370,7 +401,7 @@ class SessionSecondScreenTest { private fun actions(steam: Boolean, displays: List, micAvailable: Boolean = false, micEnabled: Boolean = false, onMic: (Boolean) -> Unit = {}, desktop: Boolean = !steam, direct: Boolean = false, onInputSelection: (InputRole?) -> Unit = {}, - onClose: () -> Unit = {}, + onClose: () -> Unit = {}, mode: SecondScreenMode = SecondScreenMode.NONE, gameSwap: Boolean = false, select: (SecondScreenMode) -> Unit = {}) = DrawerActions(steam = steam, desktop = desktop, direct = direct, onInputSelection = onInputSelection, isHomeApp = false, androidApps = emptyList(), hudOn = false, @@ -378,7 +409,7 @@ class SessionSecondScreenTest { frameGen = FrameGen.Mode.OFF, lossless = Lossless.State.NONE, oscMode = "never", suspendPolicy = "auto", backActionsInverted = false, touchMode = "auto", touchAuto = "trackpad", fexPreset = "default", - secondScreenMode = SecondScreenMode.NONE, secondScreenDisplays = displays, selectedSecondScreenDisplay = 1, + secondScreenMode = mode, secondScreenDisplays = displays, selectedSecondScreenDisplay = 1, gameSwapAvailable = gameSwap, onHud = {}, onFrameGenPick = {}, onImportLossless = {}, onKeyboard = {}, onHardwareKeyboard = {}, onSteamMenu = null, onQam = null, onOsc = {}, onSuspendPolicy = {}, onBackActionsInverted = {}, onTouch = {}, onFexPreset = {}, onSecondScreenMode = select, onSecondScreenDisplay = {}, diff --git a/app/src/test/java/com/droiddeck/launcher/ui/StoreTabsStateTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/StoreTabsStateTest.kt index e159f51853..c295f5305d 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/StoreTabsStateTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/StoreTabsStateTest.kt @@ -39,4 +39,17 @@ class StoreTabsStateTest { assertFalse(StoreTabsState.setShown(ctx, last, false)) assertTrue(StoreTabsState.tabs.single { it.store == last }.shown) } + + @Test fun theHiddenTabStartsOffAndItsSwitchSurvivesAReload() { + assertTrue(LIBRARY_HIDDEN in StoreTabsState.libraryHidden) + StoreTabsState.setLibraryShown(ctx, LIBRARY_HIDDEN, true) + assertTrue(SessionPrefs.libraryShowHidden(ctx)) + StoreTabsState.load(ctx) + assertFalse(LIBRARY_HIDDEN in StoreTabsState.libraryHidden) + StoreTabsState.setLibraryShown(ctx, LIBRARY_FAVORITES, false) + assertEquals(setOf(LIBRARY_FAVORITES), SessionPrefs.libraryTabsHidden(ctx)) + StoreTabsState.setLibraryShown(ctx, LIBRARY_HIDDEN, false) + StoreTabsState.load(ctx) + assertEquals(setOf(LIBRARY_FAVORITES, LIBRARY_HIDDEN), StoreTabsState.libraryHidden) + } } 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)) + } +} 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/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/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/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/docs/development/memory-guard-ab.md b/docs/development/memory-guard-ab.md new file mode 100644 index 0000000000..ded09a59f4 --- /dev/null +++ b/docs/development/memory-guard-ab.md @@ -0,0 +1,123 @@ +# Keep-top guard A/B on dual screens + +`KeepTopActivity` (#2763, removed in the change that added this section) covered every other +display while a session was on top, so that display's home was not its top activity. The +reasoning: on the Thor, lmkd kills the bottom home under memory pressure, Android relaunches it +to the front, the session loses the top spot, drops to adj 50 and is killed next. + +It had three side effects: + +- Android gives a translucent activity alone in its task an `ActivityRecordInputSink` that + consumes every touch in the task bounds whatever the window's flags say + (`ENABLE_TOUCH_OPAQUE_ACTIVITIES`), so the bottom screen took no touch (#2910 worked around it). +- Cocoon tracks the top activity of each display; with a DroidDeck activity on the bottom it + could not suspend or resume DroidDeck properly. +- The Thor's `com.odin.gameassistant` gives every app with an activity on top of the bottom + display that display's volume (`secondary_screen_volume_level`). With the guard up, all of + DroidDeck's audio played at the bottom screen's volume (AudioFlinger track gain -37, -13 and + -2.6 dB at levels 3, 8 and 13; -7.4 dB, the top level, once the guard was removed). + +The A/B below found no case on either device where the guard kept the session alive, so it was +removed. + +## Tool + +`tools/memory_guard_ab.py` drives a rooted dual-screen device over adb (`su` required) with a +build that has the debugging tools: + +```sh +python3 tools/memory_guard_ab.py --label main --apk main.apk states +python3 tools/memory_guard_ab.py --label fix --apk fix.apk states +python3 tools/memory_guard_ab.py --label fix pressure --stop-mb 650 --hold 30 --runs 3 +python3 tools/memory_guard_ab.py --label fix pressure --burst --stop-mb 1500 --hold 20 --runs 3 +python3 tools/memory_guard_ab.py --label fix summarize ~/.cache/droiddeck-memory-guard-ab/fix-stop650-1-events.txt +``` + +Results are JSON lines in `~/.cache/droiddeck-memory-guard-ab/