diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 3816c1a52c..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: | @@ -823,6 +829,7 @@ jobs: run: | cargo test --locked --manifest-path tools/ubisoft-launcher/Cargo.toml cargo test --locked --manifest-path tools/rockstar-launcher/Cargo.toml + cargo test --locked --manifest-path tools/epic-launcher/Cargo.toml python-tests: name: Python and native regression tests diff --git a/.github/workflows/publish-packs.yml b/.github/workflows/publish-packs.yml index c9e036f2db..a3c46b8f8b 100644 --- a/.github/workflows/publish-packs.yml +++ b/.github/workflows/publish-packs.yml @@ -55,7 +55,7 @@ jobs: jq -r --arg n "$2" '.assets // [] | .[] | select(.name == $n) | .digest // empty' } commit=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$BUILD_RUN" --jq .head_sha 2>/dev/null || echo "$GITHUB_SHA") - for name in proot directaudio tracking xbox comet butler powervr ubisoft rockstar dirt; do + for name in proot directaudio tracking xbox comet butler powervr ubisoft rockstar dirt epic; do file="packs/$name.tar.zst" [ -f "$file" ] || { echo "::error::$name.tar.zst is missing from Build APK run $BUILD_RUN"; exit 1; } sha=$(sha256sum "$file" | cut -d' ' -f1) diff --git a/.gitignore b/.gitignore index eeb1404467..395d551a1f 100644 --- a/.gitignore +++ b/.gitignore @@ -37,3 +37,4 @@ app/src/main/assets/directaudio/ app/src/main/assets/hybris/ /tools/vr/out/ app/src/main/assets/linuxfs/usr/local/lib/droiddeck-rockstar/ +app/src/main/assets/linuxfs/usr/local/lib/droiddeck-epic/ diff --git a/app/build.gradle b/app/build.gradle index c271f963b9..634a41eec0 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -93,7 +93,7 @@ def trackingPack = rootProject.file('tools/packs/tracking/release.env').readLine def prootPackPin = rootProject.file('tools/packs/proot/release.env').readLines() .findAll { it.contains('=') && !it.startsWith('#') } .collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] } -def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt'].collectEntries { name -> +def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt', 'epic'].collectEntries { name -> def pack = file("build/packs/${name}.tar.zst") if (!pack.isFile()) { if (ciBuild) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs") @@ -202,7 +202,7 @@ android { } androidResources { - ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:_*:!CVS:!thumbs.db:!picasa.ini:!*~:droiddeck-xbox:droiddeck-comet:droiddeck-ubisoft:droiddeck-rockstar:droiddeck-dirt:directaudio:hybris' + ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:_*:!CVS:!thumbs.db:!picasa.ini:!*~:droiddeck-xbox:droiddeck-comet:droiddeck-ubisoft:droiddeck-rockstar:droiddeck-dirt:droiddeck-epic:directaudio:hybris' } packagingOptions { diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index aff5658bbe..30650081fc 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -302,15 +302,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..05b201b2e5 100644 --- a/app/src/main/cpp/waylandcomp/src/sc_layer.c +++ b/app/src/main/cpp/waylandcomp/src/sc_layer.c @@ -3,6 +3,7 @@ #include "ahb_swapchain.h" #include "droiddeck_color.h" #include "vk_present.h" +#include "framegen_bridge.h" #include #include #include @@ -64,6 +65,8 @@ static struct { void (*setHdrMetadata_cta861_3)(ASurfaceTransaction *, ASurfaceControl *, const struct droiddeck_hdr_cta861_3 *); const void *(*getNativeHandle)(const AHardwareBuffer *); void (*setDesiredHdrHeadroom)(ASurfaceTransaction *, ASurfaceControl *, float); + void (*setEnableBackPressure)(ASurfaceTransaction *, ASurfaceControl *, bool); + void (*setDesiredPresentTime)(ASurfaceTransaction *, int64_t); int state; } api; @@ -105,6 +108,8 @@ static int load_api(void) { SYM(setHdrMetadata_smpte2086, "ASurfaceTransaction_setHdrMetadata_smpte2086"); SYM(setHdrMetadata_cta861_3, "ASurfaceTransaction_setHdrMetadata_cta861_3"); SYM(setDesiredHdrHeadroom, "ASurfaceTransaction_setDesiredHdrHeadroom"); + SYM(setEnableBackPressure, "ASurfaceTransaction_setEnableBackPressure"); + SYM(setDesiredPresentTime, "ASurfaceTransaction_setDesiredPresentTime"); #undef SYM if (!api.createFromWindow || !api.release || !api.txCreate || !api.txDelete || !api.txApply || !api.setBuffer || !api.setZOrder || !api.setVisibility || !api.setGeometry || @@ -134,7 +139,7 @@ void sc_layer_set_frame_rate(float fps) { } -#define POOL_MAX 5 +#define POOL_MAX 8 struct slot { AHardwareBuffer *ahb; @@ -183,6 +188,12 @@ static int g_layers_ready; static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER; static int g_pending_cb; static unsigned g_stat_layer_frames; +static pthread_mutex_t g_timeline_lock = PTHREAD_MUTEX_INITIALIZER; +static int64_t g_timeline_present_ns, g_timeline_deadline_ns, g_timeline_period_ns; +static int g_timeline_late; +static int64_t g_cadence_seen_ns, g_cadence_gap_ns, g_cadence_target_ns; +static int g_group_frames = 1, g_group_index; +static unsigned g_stat_aimed_next, g_stat_aimed_later, g_stat_aimed_even; static int g_two_logged; static AHardwareBuffer *g_blank; static ASurfaceControl *g_base_sc; @@ -219,6 +230,58 @@ static int64_t now_ns(void) { return (int64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec; } +void sc_layer_frame_timeline(int64_t present_ns, int64_t deadline_ns, int64_t period_ns) { + pthread_mutex_lock(&g_timeline_lock); + g_timeline_present_ns = present_ns; + g_timeline_deadline_ns = deadline_ns; + g_timeline_period_ns = period_ns; + pthread_mutex_unlock(&g_timeline_lock); +} + +static int64_t cadence_target(int64_t now, int64_t earliest, int64_t period) { + const int64_t gap = now - g_cadence_seen_ns; + g_cadence_seen_ns = now; + if (gap <= 0 || gap > 8 * period) { + g_cadence_gap_ns = 0; + g_cadence_target_ns = earliest; + return earliest; + } + g_cadence_gap_ns = g_cadence_gap_ns ? (g_cadence_gap_ns * 15 + gap) / 16 : gap; + const int64_t steps = (g_cadence_gap_ns + period / 2) / period; + const int64_t even = g_cadence_target_ns + steps * period; + int64_t target = earliest; + if (steps >= 1 && llabs(g_cadence_gap_ns - steps * period) < period / 8 && + even > earliest + period / 2 && even < earliest + steps * period + period / 2) { + target = even; + g_stat_aimed_even++; + } + g_cadence_target_ns = target; + return target; +} + +static void apply_present_time(ASurfaceTransaction *tx, int game) { + if (!api.setDesiredPresentTime) return; + pthread_mutex_lock(&g_timeline_lock); + const int64_t present = g_timeline_present_ns, deadline = g_timeline_deadline_ns, period = g_timeline_period_ns; + pthread_mutex_unlock(&g_timeline_lock); + const int64_t now = now_ns(); + if (period <= 0 || now - deadline > 4 * period) return; + int64_t ahead = now > deadline ? (now - deadline + period - 1) / period : -((deadline - now) / period); + const int64_t slack = deadline + ahead * period - now; + g_timeline_late = slack < (g_timeline_late ? period * 5 / 8 : period / 8); + if (g_timeline_late) { ahead++; g_stat_aimed_later++; } else g_stat_aimed_next++; + int64_t target = present + ahead * period; + if (game && g_group_index > 0) { + int64_t steps = (g_group_index * g_cadence_gap_ns / g_group_frames + period / 2) / period; + if (steps < g_group_index) steps = g_group_index; + if (target < g_cadence_target_ns + steps * period) target = g_cadence_target_ns + steps * period; + } else if (game) { + target = cadence_target(now, target, period); + } + if (game && g_group_frames > 1 && ++g_group_index >= g_group_frames) { g_group_index = 0; g_group_frames = 1; } + api.setDesiredPresentTime(tx, target - period / 2); +} + static void on_complete(void *context, ASurfaceTransactionStats *stats) { struct complete_ctx *ctx = context; pthread_mutex_lock(&g_lock); @@ -401,10 +464,22 @@ static void describe_handle(const struct droiddeck_native_handle *h, char *out, o += (size_t)snprintf(out + o, n - o, " %#x", (unsigned)h->data[h->numFds + i]); } +static int handle_fd(const struct droiddeck_native_handle *h, off_t need, int *which) { + for (int i = 0; h && i < h->numFds; i++) { + off_t sz = lseek(h->data[i], 0, SEEK_END); + if (sz >= 0) lseek(h->data[i], 0, SEEK_SET); + if (sz >= need) { if (which) *which = i; return h->data[i]; } + } + return -1; +} + +int sc_layer_ahb_fd(AHardwareBuffer *ahb, uint64_t need) { + return load_api() == 0 ? handle_fd(api.getNativeHandle(ahb), (off_t)need, NULL) : -1; +} + static int g_alloc_failed; enum { TIER_UBWC, TIER_PLAIN, TIER_LINEAR }; -#define DROIDDECK_AHB_USAGE_VENDOR_UBWC (1ULL << 28) static const char *tier_name(int tier) { return tier == TIER_UBWC ? "asked for UBWC" : tier == TIER_PLAIN ? "no UBWC request" : "linear by request (CPU bit)"; @@ -419,7 +494,7 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm .format = fmt, .usage = AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY | - (tier == TIER_UBWC ? DROIDDECK_AHB_USAGE_VENDOR_UBWC : 0) | + (tier == TIER_UBWC ? SC_LAYER_AHB_USAGE_VENDOR_UBWC : 0) | (tier == TIER_LINEAR ? AHARDWAREBUFFER_USAGE_CPU_READ_RARELY : 0)}; AHardwareBuffer *ahb = NULL; if (AHardwareBuffer_allocate(&d, &ahb) != 0 || !ahb) { @@ -459,13 +534,8 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm path = "AHardwareBuffer"; img = vkp_image_import_ahb(ahb, info, sizeof(info)); if (!img && tier == TIER_LINEAR) { - const off_t need = (off_t)got.stride * 4 * h; - int fd = -1, which = -1; - for (int i = 0; nh && i < nh->numFds; i++) { - off_t sz = lseek(nh->data[i], 0, SEEK_END); - if (sz >= 0) lseek(nh->data[i], 0, SEEK_SET); - if (sz >= need) { fd = nh->data[i]; which = i; break; } - } + int which = -1; + int fd = handle_fd(nh, (off_t)got.stride * 4 * h, &which); if (fd < 0 && nh && nh->numFds > 0) { fd = nh->data[0]; which = 0; } mod = MOD_LINEAR; path = "linear dma-buf"; @@ -506,16 +576,27 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm return -1; } -static int fence_signalled(int fd) { +static int fence_wait(int fd, int timeout_ms) { struct pollfd p = {.fd = fd, .events = POLLIN}; int r; - do { r = poll(&p, 1, 0); } while (r < 0 && errno == EINTR); - return r > 0; + do { r = poll(&p, 1, timeout_ms); } while (r < 0 && errno == EINTR); + return r; +} + +static int fence_signalled(int fd) { + return fence_wait(fd, 0) > 0; +} + +static void slot_keep_fence(struct slot *s, int fd) { + pthread_mutex_lock(&g_lock); + if (s->release_fd < 0) s->release_fd = fd; else close(fd); + pthread_mutex_unlock(&g_lock); } static int take_free_slot(struct layer *l, int w, int h, uint32_t fmt, int *wait_fd) { int idx = -1, pending = -1, fd = -1; *wait_fd = -1; + g_alloc_failed = 0; pthread_mutex_lock(&g_lock); for (int i = 0; i < l->pool_n; i++) { if (i == l->cur_slot || l->slots[i].busy) continue; @@ -535,15 +616,7 @@ static int take_free_slot(struct layer *l, int w, int h, uint32_t fmt, int *wait memset(s, 0, sizeof(*s)); s->release_fd = -1; } if (fd >= 0 && !vkp_can_wait_sync_fd()) { - struct pollfd p = {.fd = fd, .events = POLLIN}; - int r; - do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR); - if (r == 0) { - pthread_mutex_lock(&g_lock); - if (s->release_fd < 0) s->release_fd = fd; else close(fd); - pthread_mutex_unlock(&g_lock); - return -1; - } + if (fence_wait(fd, 100) == 0) { slot_keep_fence(s, fd); return -1; } close(fd); fd = -1; } @@ -558,6 +631,8 @@ static int take_free_slot(struct layer *l, int w, int h, uint32_t fmt, int *wait int sc_layer_available(void) { return load_api() == 0; } +int sc_layer_queues(void) { return load_api() == 0 && api.setEnableBackPressure != NULL; } + void sc_layer_probe_dmabuf_fd(int fd) { static int done; if (done || fd < 0) return; @@ -595,9 +670,10 @@ static int ensure_sc(struct layer *l) { return 0; } -static int layer_geometry(int w, int h, int scene_w, int scene_h, int r[8]) { +static int layer_geometry(int w, int h, int scene_w, int scene_h, const struct vkp_draw *draw, int r[8]) { if (vkp_update_map(scene_w, scene_h) != 0) return -1; - return vkp_map_rect(w, h, scene_w, scene_h, r) ? 1 : 0; + if (draw) return vkp_map_draw(draw, r) ? 1 : 0; + return vkp_map_rect(w, h, (const int[4]){0, 0, scene_w, scene_h}, r) ? 1 : 0; } static ARect g_game_src, g_game_dst; @@ -757,6 +833,7 @@ static int present_slot(struct layer *l, int idx, const int r[8], const struct d ASurfaceControl *old = swap_sc_begin(l); if (old) api.setZOrder(tx, l->sc, l->z); api.setBuffer(tx, l->sc, s->ahb, -1); + if (api.setEnableBackPressure) api.setEnableBackPressure(tx, l->sc, true); api.setBufferTransparency(tx, l->sc, translucent ? ASC_TRANSPARENCY_TRANSLUCENT : ASC_TRANSPARENCY_OPAQUE); apply_geometry(tx, l, r); @@ -769,6 +846,7 @@ static int present_slot(struct layer *l, int idx, const int r[8], const struct d pthread_mutex_lock(&g_lock); s->busy = 1; pthread_mutex_unlock(&g_lock); + apply_present_time(tx, l == &g_layers[SC_LAYER_GAME]); api.txApply(tx); api.txDelete(tx); l->cur_slot = idx; @@ -799,11 +877,12 @@ unsigned sc_layer_drops_take(void) { } int sc_layer_present_ahb(AHardwareBuffer *ahb, int w, int h, int acquire_fd, void *token, int scene_w, int scene_h, + const struct vkp_draw *draw, const struct droiddeck_color *color, uint32_t ahb_format) { struct layer *l = layer_of(SC_LAYER_GAME); int r[8]; if (!ahb || !token || ensure_sc(l) != 0) goto unavailable; - int g = layer_geometry(w, h, scene_w, scene_h, r); + int g = layer_geometry(w, h, scene_w, scene_h, draw, r); if (g < 0) goto unavailable; if (g == 0) { if (acquire_fd >= 0) close(acquire_fd); sc_layer_hide(); return 1; } if (token == l->cur_token && l->shown && !l->recreate_pending) { @@ -821,6 +900,7 @@ int sc_layer_present_ahb(AHardwareBuffer *ahb, int w, int h, int acquire_fd, voi ASurfaceControl *old = swap_sc_begin(l); if (old) api.setZOrder(tx, l->sc, l->z); api.setBuffer(tx, l->sc, ahb, acquire_fd); + if (api.setEnableBackPressure) api.setEnableBackPressure(tx, l->sc, true); api.setBufferTransparency(tx, l->sc, ASC_TRANSPARENCY_OPAQUE); apply_geometry(tx, l, r); apply_frame_rate(tx, l); @@ -834,6 +914,7 @@ int sc_layer_present_ahb(AHardwareBuffer *ahb, int w, int h, int acquire_fd, voi l->ds_applied = -1; l->md_applied = 0; l->hr_applied = -1.0f; return -1; } + apply_present_time(tx, 1); api.txApply(tx); api.txDelete(tx); l->cur_slot = -1; @@ -848,12 +929,13 @@ unavailable: return -1; } -int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct droiddeck_color *color) { +int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct vkp_draw *draw, + const struct droiddeck_color *color) { struct layer *l = layer_of(SC_LAYER_GAME); if (!src || ensure_sc(l) != 0) return -1; int sw = vkp_image_width(src), sh = vkp_image_height(src); int r[8]; - int g = layer_geometry(sw, sh, scene_w, scene_h, r); + int g = layer_geometry(sw, sh, scene_w, scene_h, draw, r); if (g < 0) return -1; if (g == 0) { sc_layer_hide(); return 0; } @@ -879,10 +961,10 @@ int sc_layer_present_pass(const struct vkp_draw *draws, int n, int scene_w, int if (!draws || n <= 0 || ensure_sc(l) != 0) return -1; if (vkp_update_map(scene_w, scene_h) != 0) return -1; if (vkp_pass_begin(scene_w, scene_h, draws, n, &rw, &rh) != 0) return -1; - if (!vkp_map_rect(rw, rh, scene_w, scene_h, r)) { vkp_pass_abort(); sc_layer_hide(); return 0; } + if (!vkp_map_rect(rw, rh, (const int[4]){0, 0, scene_w, scene_h}, r)) { vkp_pass_abort(); sc_layer_hide(); return 0; } int wait_fd; int idx = take_free_slot(l, rw, rh, AHB_RGBA8, &wait_fd); - if (idx < 0) { vkp_pass_abort(); log_drop(l); return 0; } + if (idx < 0) { vkp_pass_abort(); log_drop(l); return g_alloc_failed ? -1 : 0; } if (vkp_pass_copy_to(l->slots[idx].img, wait_fd) != 0) return -1; if (present_slot(l, idx, r, NULL, 0) != 0) return -1; if (!l->first_logged) { @@ -895,8 +977,97 @@ int sc_layer_present_pass(const struct vkp_draw *draws, int n, int scene_w, int return 0; } +static void slots_idle(struct layer *l, const int *idx, int from, int to) { + pthread_mutex_lock(&g_lock); + for (int i = from; i < to; i++) l->slots[idx[i]].busy = 0; + pthread_mutex_unlock(&g_lock); +} + static uint32_t g_hdr_pool_fmt = AHB_RGB10A2; +static int take_hdr_slot(struct layer *l, int w, int h, int *wait_fd) { + int idx = take_free_slot(l, w, h, g_hdr_pool_fmt, wait_fd); + if (idx < 0 && g_alloc_failed && g_hdr_pool_fmt == AHB_RGB10A2) { + g_hdr_pool_fmt = AHB_RGBA8; + droiddeck_log("color", "%s: this device will not make a 10-bit layer buffer (RGBA1010102): the HDR picture goes " + "on 8-bit buffers instead (still tagged BT2020_PQ; less precision)", l->name); + idx = take_free_slot(l, w, h, g_hdr_pool_fmt, wait_fd); + } + return idx; +} + +int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws, const struct vkp_hdr_frame *hf, + int scene_w, int scene_h, int composed, const struct droiddeck_color *color) { + struct layer *l = layer_of(SC_LAYER_GAME); + int rw = 0, rh = 0, r[8], idx[VKP_FG_MAX_GENERATIONS + 1], m = 0, first_fd = -1, have_fd = 0; + struct vkp_image *dst[VKP_FG_MAX_GENERATIONS], *real = NULL; + g_group_index = 0; + g_group_frames = 1; + if (!draws || n_draws <= 0 || ensure_sc(l) != 0) return -1; + if (vkp_update_map(scene_w, scene_h) != 0) return -1; + const int deep = hf && !hf->tonemap; + if (hf) composed = 1; + if (hf && hf->tonemap) color = NULL; + int n = vkp_pass_begin_generate(scene_w, scene_h, draws, n_draws, hf, &rw, &rh); + if (n < 0) return -1; + const int mapped = vkp_map_rect(rw, rh, (const int[4]){0, 0, scene_w, scene_h}, r); + if (!mapped) n = 0; + if (composed) { + if (!mapped) { vkp_pass_abort(); sc_layer_hide(); return 0; } + idx[VKP_FG_MAX_GENERATIONS] = deep ? take_hdr_slot(l, rw, rh, &first_fd) + : take_free_slot(l, rw, rh, AHB_RGBA8, &first_fd); + if (idx[VKP_FG_MAX_GENERATIONS] < 0) { vkp_pass_abort(); log_drop(l); return g_alloc_failed ? -1 : 0; } + pthread_mutex_lock(&g_lock); + l->slots[idx[VKP_FG_MAX_GENERATIONS]].busy = 1; + pthread_mutex_unlock(&g_lock); + real = l->slots[idx[VKP_FG_MAX_GENERATIONS]].img; + have_fd = 1; + } + for (; m < n; m++) { + int fd; + idx[m] = take_free_slot(l, rw, rh, deep ? g_hdr_pool_fmt : AHB_RGBA8, &fd); + if (idx[m] < 0) { log_drop(l); break; } + if (have_fd && fd >= 0) { + if (fence_wait(fd, 100) == 0) { slot_keep_fence(&l->slots[idx[m]], fd); log_drop(l); break; } + close(fd); + } + pthread_mutex_lock(&g_lock); + l->slots[idx[m]].busy = 1; + pthread_mutex_unlock(&g_lock); + dst[m] = l->slots[idx[m]].img; + if (!have_fd) { first_fd = fd; have_fd = 1; } + } + if (vkp_pass_copy_generated(dst, m, real, first_fd) != 0) { + slots_idle(l, idx, 0, m); + if (real) slots_idle(l, idx, VKP_FG_MAX_GENERATIONS, VKP_FG_MAX_GENERATIONS + 1); + return -1; + } + g_group_frames = m + 1; + for (int k = 0; k < m; k++) { + if (present_slot(l, idx[k], r, color, 0) == 0) continue; + slots_idle(l, idx, k, m); + if (real) slots_idle(l, idx, VKP_FG_MAX_GENERATIONS, VKP_FG_MAX_GENERATIONS + 1); + g_group_index = 0; + g_group_frames = 1; + return -1; + } + vkp_framegen_presented(m); + if (real) { + if (present_slot(l, idx[VKP_FG_MAX_GENERATIONS], r, color, 0) != 0) { + slots_idle(l, idx, VKP_FG_MAX_GENERATIONS, VKP_FG_MAX_GENERATIONS + 1); + g_group_index = 0; + g_group_frames = 1; + return -1; + } + l->first_logged = 1; + vkp_signal_first_frame(); + } + if (hf && hf->color && hf->color->dataspace) + droiddeck_color_frame_shown(hf->color, deep ? DROIDDECK_HDR_COMPOSED : DROIDDECK_HDR_TONEMAPPED, + deep ? g_hdr_pool_fmt : AHB_RGBA8); + return m; +} + int sc_layer_present_hdr_scene(const struct vkp_draw *draws, int n, const struct vkp_hdr_frame *hf, int scene_w, int scene_h, const struct droiddeck_color *color) { struct layer *l = layer_of(SC_LAYER_GAME); @@ -904,19 +1075,11 @@ int sc_layer_present_hdr_scene(const struct vkp_draw *draws, int n, const struct if (!draws || n <= 0 || !hf || ensure_sc(l) != 0) return -1; if (vkp_update_map(scene_w, scene_h) != 0) return -1; if (vkp_pass_begin_hdr(scene_w, scene_h, draws, n, hf, &rw, &rh) != 0) return -1; - if (!vkp_map_rect(rw, rh, scene_w, scene_h, r)) { vkp_pass_abort(); sc_layer_hide(); return 0; } + if (!vkp_map_rect(rw, rh, (const int[4]){0, 0, scene_w, scene_h}, r)) { vkp_pass_abort(); sc_layer_hide(); return 0; } const int tm = hf->tonemap; - const uint32_t fmt = tm ? AHB_RGBA8 : g_hdr_pool_fmt; - g_alloc_failed = 0; int wait_fd; - int idx = take_free_slot(l, rw, rh, fmt, &wait_fd); - if (idx < 0 && g_alloc_failed && fmt == AHB_RGB10A2) { - g_hdr_pool_fmt = AHB_RGBA8; - droiddeck_log("color", "%s: this device will not make a 10-bit layer buffer (RGBA1010102): the HDR picture goes " - "on 8-bit buffers instead (still tagged BT2020_PQ; less precision)", l->name); - idx = take_free_slot(l, rw, rh, g_hdr_pool_fmt, &wait_fd); - } - if (idx < 0) { vkp_pass_abort(); log_drop(l); return 0; } + int idx = tm ? take_free_slot(l, rw, rh, AHB_RGBA8, &wait_fd) : take_hdr_slot(l, rw, rh, &wait_fd); + if (idx < 0) { vkp_pass_abort(); log_drop(l); return g_alloc_failed ? -1 : 0; } if (vkp_pass_copy_to(l->slots[idx].img, wait_fd) != 0) return -1; if (present_slot(l, idx, r, tm ? NULL : color, 0) != 0) return -1; if (color && color->dataspace) @@ -967,8 +1130,9 @@ int sc_layer_overlay_affordable(void) { if (want) droiddeck_log("layer", "overlay layer declined: this display rotates every layer %d° and the game " "layer is scaled %dx%d -> %dx%d, and on that combination a second layer drops the " - "whole frame to GPU composition for the rest of the session (measured). The window " - "above the game goes on the copy path instead - same picture, one blit.", + "whole frame to GPU composition for the rest of the session (measured). A nested " + "compositor is asked to compose its own overlays into the game picture; any other " + "window above the game goes on the copy path instead.", deg, sr[0], sr[1], ds[0], ds[1]); else if (!first) droiddeck_log("layer", "overlay layer allowed again: the game layer is no longer both rotated and " @@ -1033,6 +1197,13 @@ void sc_layer_window_gone(void) { drain_and_free_pools(); } +void sc_layer_aim_take(unsigned *next, unsigned *later, unsigned *even) { + *next = g_stat_aimed_next; + *later = g_stat_aimed_later; + *even = g_stat_aimed_even; + g_stat_aimed_next = g_stat_aimed_later = g_stat_aimed_even = 0; +} + unsigned sc_layer_frames_take(void) { unsigned n = g_stat_layer_frames; g_stat_layer_frames = 0; diff --git a/app/src/main/cpp/waylandcomp/src/sc_layer.h b/app/src/main/cpp/waylandcomp/src/sc_layer.h index 58fe5f6d61..24a24fc25e 100644 --- a/app/src/main/cpp/waylandcomp/src/sc_layer.h +++ b/app/src/main/cpp/waylandcomp/src/sc_layer.h @@ -7,10 +7,13 @@ struct vkp_image; struct vkp_draw; struct droiddeck_color; +struct vkp_hdr_frame; enum sc_layer_id { SC_LAYER_GAME = 0, SC_LAYER_OVERLAY = 1, SC_LAYER_COUNT = 2 }; int sc_layer_available(void); +#define SC_LAYER_AHB_USAGE_VENDOR_UBWC (1ULL << 28) +int sc_layer_ahb_fd(AHardwareBuffer *ahb, uint64_t need); void sc_layer_probe_dmabuf_fd(int fd); @@ -18,21 +21,25 @@ int sc_layer_can_tag_hdr(void); void sc_layer_hdr_symbols(char *out, size_t size); -int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct droiddeck_color *color); +int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct vkp_draw *draw, + const struct droiddeck_color *color); int sc_layer_present_pass(const struct vkp_draw *draws, int n, int scene_w, int scene_h); +int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws, const struct vkp_hdr_frame *hf, + int scene_w, int scene_h, int composed, const struct droiddeck_color *color); -struct vkp_hdr_frame; int sc_layer_present_hdr_scene(const struct vkp_draw *draws, int n, const struct vkp_hdr_frame *hf, int scene_w, int scene_h, const struct droiddeck_color *color); int sc_layer_present_ahb(AHardwareBuffer *ahb, int w, int h, int acquire_fd, void *token, - int scene_w, int scene_h, const struct droiddeck_color *color, uint32_t ahb_format); + int scene_w, int scene_h, const struct vkp_draw *draw, const struct droiddeck_color *color, uint32_t ahb_format); void sc_layer_set_frame_rate(float fps); int sc_layer_overlay_affordable(void); +int sc_layer_queues(void); + int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int translucent); void sc_layer_hide(void); @@ -42,6 +49,8 @@ void sc_layer_hide_overlay(void); void sc_layer_window_gone(void); +void sc_layer_frame_timeline(int64_t present_ns, int64_t deadline_ns, int64_t period_ns); +void sc_layer_aim_take(unsigned *next, unsigned *later, unsigned *even); unsigned sc_layer_frames_take(void); unsigned sc_layer_drops_take(void); diff --git a/app/src/main/cpp/waylandcomp/src/vk_linear_dmabuf.h b/app/src/main/cpp/waylandcomp/src/vk_linear_dmabuf.h new file mode 100644 index 0000000000..f0c92229a7 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/vk_linear_dmabuf.h @@ -0,0 +1,55 @@ +#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 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, + int acquire) { + return (VkBufferMemoryBarrier){ + .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, + .srcAccessMask = acquire ? 0 : VK_ACCESS_TRANSFER_READ_BIT, + .dstAccessMask = acquire ? VK_ACCESS_TRANSFER_READ_BIT : 0, + .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..ee6328a287 100644 --- a/app/src/main/cpp/waylandcomp/src/vk_loader.h +++ b/app/src/main/cpp/waylandcomp/src/vk_loader.h @@ -23,6 +23,8 @@ 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(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..ebd9404281 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, 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, 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,6 +1223,102 @@ 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 = 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: reading the linear %dx%d buffer at its row pitch failed (%s); importing it as an image", + img->w, img->h, vk_result_name(r)); + 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; @@ -1190,9 +1328,11 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t if (!img) return NULL; img->w = w; img->h = h; img->dmabuf = 1; img->blit_dst = as_blit_dst ? 1 : 0; img->fmt = drm_to_vk(drm_format); + const int through_buffer = vkp_linear_dmabuf_through_buffer(g_drm_modifiers, modifier, as_blit_dst); 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 = 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 +1343,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 +1355,12 @@ 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) return img; + 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 +1648,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 +1746,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 +1880,11 @@ static int compose_hdr(VkCommandBuffer cmd, const struct vkp_draw *draws, int n, struct hdrc_params p = {.mode = mode, .sdr_white_nits = droiddeck_color_sdr_white(), .peak_nits = hf->peak_nits > 0.0f ? hf->peak_nits : 1000.0f}; + if (hf->convert) { + p.conv_linear = hf->convert->convert == 2; + p.conv_gain = hf->convert->gain; + memcpy(p.conv, hf->convert->to2020, sizeof(p.conv)); + } int lowest_hdr = -1; for (int i = 0; i < n; i++) { VkImageBlit blit; @@ -1750,6 +1901,7 @@ static int compose_hdr(VkCommandBuffer cmd, const struct vkp_draw *draws, int n, p.rects[p.count][0] = (float)blit.dstOffsets[0].x; p.rects[p.count][1] = (float)blit.dstOffsets[0].y; p.rects[p.count][2] = (float)blit.dstOffsets[1].x; p.rects[p.count][3] = (float)blit.dstOffsets[1].y; if (hf->is_hdr[i]) p.hdr_mask |= 1u << p.count; + if (hf->is_hdr[i] == 2 && hf->convert) p.conv_mask |= 1u << p.count; p.count++; } if (i >= lowest_hdr && !truncated_said) { @@ -2084,6 +2236,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 +2254,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 +2506,9 @@ int vkp_update_map(int scene_w, int scene_h) { return g_map.valid ? 0 : -1; } -int vkp_map_rect(int img_w, int img_h, int scene_w, int scene_h, int out[8]) { +int vkp_map_rect(int img_w, int img_h, const int dst[4], int out[8]) { struct vkp_image tmp = {.w = img_w, .h = img_h}; - struct vkp_draw d = {&tmp, 0, 0, (float)img_w, (float)img_h, 0, 0, scene_w, scene_h}; + struct vkp_draw d = {&tmp, 0, 0, (float)img_w, (float)img_h, dst[0], dst[1], dst[2], dst[3]}; return vkp_map_draw(&d, out); } @@ -2383,9 +2536,10 @@ 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); + 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, @@ -2489,22 +2643,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 +2709,33 @@ static struct { int active; VkImage result; int rw, rh; + int ngen; + VkImage gens[VKP_FG_MAX_GENERATIONS]; } g_pass; static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draws, int n, - const struct vkp_hdr_frame *hf, int *rw, int *rh); + const struct vkp_hdr_frame *hf, int generate, int *rw, int *rh); int vkp_pass_begin(int scene_w, int scene_h, const struct vkp_draw *draws, int n, int *rw, int *rh) { - return pass_begin_impl(scene_w, scene_h, draws, n, NULL, rw, rh); + return pass_begin_impl(scene_w, scene_h, draws, n, NULL, 0, rw, rh); +} + +int vkp_pass_begin_generate(int scene_w, int scene_h, const struct vkp_draw *draws, int n, + const struct vkp_hdr_frame *hf, int *rw, int *rh) { + if (pass_begin_impl(scene_w, scene_h, draws, n, hf, 1, rw, rh) != 0) return -1; + return g_pass.ngen; } int vkp_pass_begin_hdr(int scene_w, int scene_h, const struct vkp_draw *draws, int n, const struct vkp_hdr_frame *hf, int *rw, int *rh) { if (!hf) return -1; - return pass_begin_impl(scene_w, scene_h, draws, n, hf, rw, rh); + return pass_begin_impl(scene_w, scene_h, draws, n, hf, 0, rw, rh); } static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draws, int n, - const struct vkp_hdr_frame *hf, int *rw, int *rh) { + const struct vkp_hdr_frame *hf, int generate, int *rw, int *rh) { if (g_pass.active) vkp_pass_abort(); + g_pass.ngen = 0; if (vkp_update_map(scene_w, scene_h) != 0) return -1; int input_w = scene_w, input_h = scene_h; int pass_n = n, overlay_start = n; @@ -2588,13 +2755,31 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw effects_source_note(scene_w, scene_h, draws, n, input_w, input_h, (int)(scene_w * g_map.kx + 0.5f), (int)(scene_h * g_map.ky + 0.5f)); } - if (hf) { + const int deep = hf && generate && !hf->tonemap && vkp_framegen_format_ok(FG_HDR_FMT) && + ensure_img(&g_fgscene, scene_w, scene_h, FG_HDR_FMT, + VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | + VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, + "HDR frame generation (scene)") == 0; + const int narrow = hf && generate && !deep; + if (hf && !deep && !narrow) { if (ensure_img(&g_hdrscene, scene_w, scene_h, HDR_FMT, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, "HDR composition (picture)") != 0) return -1; - } else if (ensure_scene_image(input_w, input_h) != 0) return -1; + } else if (!deep && ensure_scene_image(input_w, input_h) != 0) return -1; + const VkFormat scene_fmt = deep ? FG_HDR_FMT : narrow || !hf ? SCENE_FMT : HDR_FMT; + if (hf && generate) { + static int said = -1; + if (said != deep + 2 * hf->tonemap) { + said = deep + 2 * hf->tonemap; + droiddeck_log("color", hf->tonemap + ? "frame generation runs on the tone-mapped picture in 8 bits, onto the game's display layer" + : deep ? "frame generation runs on the HDR picture in FP16 (RGBA16F), onto the game's display layer" + : "frame generation runs on the HDR picture in 8 bits (the engine cannot take FP16 here), onto " + "the game's display layer: banding possible in smooth gradients"); + } + } VkCommandBuffer cmd = g_cmds[0]; g_vk.ResetCommandBuffer(cmd, 0); @@ -2602,12 +2787,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 +2806,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 +2824,12 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw free(bars); if (hf) { - if (compose_hdr(cmd, draws, n, hf, scene_w, scene_h, g_hdrscene.img, HDR_FMT, + if (compose_hdr(cmd, draws, n, hf, scene_w, scene_h, scene_img, scene_fmt, hf->tonemap ? HDRC_OUT_SDR : HDRC_OUT_PQ) != 0) { g_vk.EndCommandBuffer(cmd); return -1; } - if (vkp_effects_active()) vkp_effects_set_formats(HDR_FMT, HDR_FMT); + if (vkp_effects_active()) vkp_effects_set_formats(scene_fmt, scene_fmt); } else { VkClearColorValue black = {.float32 = {0.0f, 0.0f, 0.0f, 1.0f}}; g_vk.CmdClearColorImage(cmd, g_scene.img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &black, 1, &range); @@ -2662,24 +2848,42 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw } int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f); + if (generate && !vkp_effects_sharpening()) { mapped_w = scene_w; mapped_h = scene_h; } g_pass.rw = input_w; g_pass.rh = input_h; g_pass.result = vkp_effects_run(cmd, scene_img, input_w, input_h, mapped_w, mapped_h, &g_pass.rw, &g_pass.rh); effects_overlay_draws(cmd, g_pass.result, g_pass.rw, g_pass.rh, scene_w, scene_h, draws ? draws + overlay_start : NULL, n - overlay_start); release_external_client_draws(cmd, draws, n); + if (generate) { + VkImageMemoryBarrier b = { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + .newLayout = VK_IMAGE_LAYOUT_GENERAL, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .image = g_pass.result, .subresourceRange = range, + .srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT, + .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_SHADER_READ_BIT}; + g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + 0, 0, NULL, 0, NULL, 1, &b); + int ngen = vkp_framegen_run(cmd, g_pass.result, VK_NULL_HANDLE, g_pass.rw, g_pass.rh, scene_fmt, g_pass.gens); + if (ngen < 0) ngen = 0; + g_pass.ngen = ngen > VKP_FG_MAX_GENERATIONS ? VKP_FG_MAX_GENERATIONS : ngen; + } g_pass.active = 1; if (rw) *rw = g_pass.rw; if (rh) *rh = g_pass.rh; return 0; } -int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd) { +static int pass_finish(const VkImage *srcs, VkImageLayout src_layout, struct vkp_image *const *dsts, int n, + int wait_fd) { if (!g_pass.active) { if (wait_fd >= 0) close(wait_fd); return -1; } g_pass.active = 0; if (g_dev_state != 1) { if (wait_fd >= 0) close(wait_fd); return -1; } VkCommandBuffer cmd = g_cmds[0]; - if (!dst || !dst->blit_dst) { + for (int i = 0; i < n; i++) { + if (dsts[i] && dsts[i]->blit_dst) continue; if (wait_fd >= 0) close(wait_fd); g_vk.EndCommandBuffer(cmd); return -1; @@ -2688,27 +2892,30 @@ int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd) { if (gpu_wait < 0) { g_vk.EndCommandBuffer(cmd); return -1; } VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - VkImageMemoryBarrier acq = { - .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, - .newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, - .dstQueueFamilyIndex = g_qfam, .image = dst->image, .subresourceRange = range, - .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}; - g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, - 0, 0, NULL, 0, NULL, 1, &acq); - VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, - .srcOffsets = {{0, 0, 0}, {g_pass.rw, g_pass.rh, 1}}, - .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, - .dstOffsets = {{0, 0, 0}, {dst->w, dst->h, 1}}}; - g_vk.CmdBlitImage(cmd, g_pass.result, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dst->image, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, - (g_pass.rw == dst->w && g_pass.rh == dst->h) ? VK_FILTER_NEAREST : VK_FILTER_LINEAR); - VkImageMemoryBarrier rel = { - .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - .newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam, - .dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .image = dst->image, .subresourceRange = range, - .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}; - g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - 0, 0, NULL, 0, NULL, 1, &rel); + for (int i = 0; i < n; i++) { + struct vkp_image *dst = dsts[i]; + VkImageMemoryBarrier acq = { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, + .dstQueueFamilyIndex = g_qfam, .image = dst->image, .subresourceRange = range, + .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}; + g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, 0, NULL, 0, NULL, 1, &acq); + VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, + .srcOffsets = {{0, 0, 0}, {g_pass.rw, g_pass.rh, 1}}, + .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, + .dstOffsets = {{0, 0, 0}, {dst->w, dst->h, 1}}}; + g_vk.CmdBlitImage(cmd, srcs[i], src_layout, dst->image, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, + (g_pass.rw == dst->w && g_pass.rh == dst->h) ? VK_FILTER_NEAREST : VK_FILTER_LINEAR); + VkImageMemoryBarrier rel = { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + .newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .image = dst->image, .subresourceRange = range, + .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}; + g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, + 0, 0, NULL, 0, NULL, 1, &rel); + } g_vk.EndCommandBuffer(cmd); VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT; @@ -2728,6 +2935,19 @@ int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd) { return 0; } +int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd) { + return pass_finish(&g_pass.result, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, &dst, 1, wait_fd); +} + +int vkp_pass_copy_generated(struct vkp_image *const *dsts, int n, struct vkp_image *real, int wait_fd) { + VkImage srcs[VKP_FG_MAX_GENERATIONS + 1]; + struct vkp_image *all[VKP_FG_MAX_GENERATIONS + 1]; + if (n > g_pass.ngen) n = g_pass.ngen; + for (int i = 0; i < n; i++) { srcs[i] = g_pass.gens[i]; all[i] = dsts[i]; } + if (real) { srcs[n] = g_pass.result; all[n] = real; } + return pass_finish(srcs, VK_IMAGE_LAYOUT_GENERAL, all, n + (real ? 1 : 0), wait_fd); +} + void vkp_pass_abort(void) { if (!g_pass.active) return; g_pass.active = 0; diff --git a/app/src/main/cpp/waylandcomp/src/vk_present.h b/app/src/main/cpp/waylandcomp/src/vk_present.h index b8cd889219..69af7dca23 100644 --- a/app/src/main/cpp/waylandcomp/src/vk_present.h +++ b/app/src/main/cpp/waylandcomp/src/vk_present.h @@ -96,6 +96,7 @@ struct vkp_hdr_frame { float peak_nits; int tonemap; const struct droiddeck_color *color; + const struct droiddeck_color *convert; }; int vkp_render_hdr(int scene_w, int scene_h, const struct vkp_draw *draws, int n, const struct vkp_hdr_frame *hf, int *how); @@ -106,7 +107,7 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd); int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px); int vkp_update_map(int scene_w, int scene_h); int vkp_map_draw(const struct vkp_draw *d, int out[8]); -int vkp_map_rect(int img_w, int img_h, int scene_w, int scene_h, int out[8]); +int vkp_map_rect(int img_w, int img_h, const int dst[4], int out[8]); int vkp_surface_rotation_degrees(void); ANativeWindow *vkp_window(void); @@ -114,6 +115,9 @@ void vkp_signal_first_frame(void); int vkp_pass_begin(int scene_w, int scene_h, const struct vkp_draw *draws, int n, int *rw, int *rh); int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd); +int vkp_pass_begin_generate(int scene_w, int scene_h, const struct vkp_draw *draws, int n, + const struct vkp_hdr_frame *hf, int *rw, int *rh); +int vkp_pass_copy_generated(struct vkp_image *const *dsts, int n, struct vkp_image *real, int wait_fd); void vkp_pass_abort(void); void droiddeck_log(const char *tag, const char *fmt, ...) __attribute__((format(printf, 2, 3))); diff --git a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c index 7879d51521..4dc2f2c08c 100644 --- a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c +++ b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c @@ -34,11 +34,13 @@ extern int droiddeck_cursor_input_pos(int *x, int *y); extern void droiddeck_wayland_send_scene_input(int type, int a, int b); extern void droiddeck_wayland_set_cursor_composite(int on); extern void droiddeck_wayland_vsync(int64_t frame_time_ns); +extern void sc_layer_frame_timeline(int64_t present_ns, int64_t deadline_ns, int64_t period_ns); extern void droiddeck_stream_set(int on); extern void droiddeck_stream_frame(AHardwareBuffer *ahb); extern unsigned droiddeck_stream_frames(void); extern void droiddeck_wayland_output_resized(void); extern void droiddeck_wayland_set_output_refresh_rate(int mhz); +extern void droiddeck_wayland_set_panel_rates(const int *rates, int count); extern volatile int g_fps_limit; extern volatile int g_release_unpaced; extern volatile int g_render_on_commit; @@ -48,6 +50,8 @@ extern volatile int g_hide_shell; extern volatile int g_zero_copy; extern volatile unsigned g_zero_copy_last; extern volatile int g_ubwc; +extern volatile int g_display_buffer_driver; +void droiddeck_dmabuf_formats_stale(void); extern volatile int g_no_render_node; extern volatile int g_output_w, g_output_h; @@ -63,6 +67,9 @@ static jmethodID g_on_game_program; static jmethodID g_on_pointer_lock; static jmethodID g_on_clipboard; static jmethodID g_on_text_input; +static jmethodID g_on_overlay_planes; +static jmethodID g_on_refresh_target; +static jmethodID g_on_content_rate; JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { (void)reserved; @@ -84,6 +91,9 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { g_on_clipboard = (*env)->GetStaticMethodID(env, g_compositor_cls, "onClipboardText", "([B)V"); g_on_text_input = (*env)->GetStaticMethodID(env, g_compositor_cls, "onTextInput", "(ZLjava/lang/String;IIII)V"); + g_on_overlay_planes = (*env)->GetStaticMethodID(env, g_compositor_cls, "onOverlayPlanes", "(I)V"); + g_on_refresh_target = (*env)->GetStaticMethodID(env, g_compositor_cls, "onRefreshTarget", "(II)V"); + g_on_content_rate = (*env)->GetStaticMethodID(env, g_compositor_cls, "onContentRate", "(I)V"); } } return JNI_VERSION_1_6; @@ -144,6 +154,27 @@ void droiddeck_on_game_frame(void) { if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env); } +void droiddeck_on_refresh_target(int refresh, int frame_rate) { + JNIEnv *env; + if (!g_compositor_cls || !g_on_refresh_target || !(env = thread_env())) return; + (*env)->CallStaticVoidMethod(env, g_compositor_cls, g_on_refresh_target, (jint)refresh, (jint)frame_rate); + if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env); +} + +void droiddeck_on_content_rate(int fps) { + JNIEnv *env; + if (!g_compositor_cls || !g_on_content_rate || !(env = thread_env())) return; + (*env)->CallStaticVoidMethod(env, g_compositor_cls, g_on_content_rate, (jint)fps); + if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env); +} + +void droiddeck_on_overlay_planes(int planes) { + JNIEnv *env; + if (!g_compositor_cls || !g_on_overlay_planes || !(env = thread_env())) return; + (*env)->CallStaticVoidMethod(env, g_compositor_cls, g_on_overlay_planes, (jint)planes); + if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env); +} + void droiddeck_on_pointer_lock(int locked, int x, int y) { JNIEnv *env; if (!g_compositor_cls || !g_on_pointer_lock || !(env = thread_env())) return; @@ -365,6 +396,12 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeVsync(JNIEnv *env, j droiddeck_wayland_vsync((int64_t)frameTimeNanos); } +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeFrameTimeline(JNIEnv *env, jclass clazz, jlong presentNanos, + jlong deadlineNanos, jlong periodNanos) { + sc_layer_frame_timeline((int64_t)presentNanos, (int64_t)deadlineNanos, (int64_t)periodNanos); +} + JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetClockControl(JNIEnv *env, jclass clazz, jstring path) { const char *value = path ? (*env)->GetStringUTFChars(env, path, NULL) : NULL; @@ -380,11 +417,18 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetHideShell(JNIEnv JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetZeroCopy(JNIEnv *env, jclass clazz, jboolean on) { int live = droiddeck_get_display() != NULL; - if (!live) g_zero_copy = on ? 1 : 0; + if (!live) { g_zero_copy = on ? 1 : 0; droiddeck_dmabuf_formats_stale(); } droiddeck_host_zero_copy(on ? 1 : 0, live); __android_log_print(ANDROID_LOG_INFO, TAG, "zero-copy layer mode %s%s", on ? "on" : "off", live ? " (live)" : ""); } +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetDisplayBufferDriver(JNIEnv *env, jclass clazz, jboolean on) { + g_display_buffer_driver = on ? 1 : 0; + droiddeck_dmabuf_formats_stale(); + __android_log_print(ANDROID_LOG_INFO, TAG, "session driver %s for display buffers", on ? "asks" : "does not ask"); +} + JNIEXPORT jint JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeZeroCopyLastFrameAgeMs(JNIEnv *env, jclass clazz) { return (jint)ahb_swapchain_last_frame_age_ms(); @@ -418,6 +462,16 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetOutputRefreshRate droiddeck_wayland_set_output_refresh_rate(hz > 1.0f ? (int)(hz * 1000.0f + 0.5f) : 0); } +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetPanelRates(JNIEnv *env, jclass clazz, jintArray rates) { + (void)clazz; + jint values[16]; + jsize count = rates ? (*env)->GetArrayLength(env, rates) : 0; + if (count > 16) count = 16; + if (count > 0) (*env)->GetIntArrayRegion(env, rates, 0, count, values); + droiddeck_wayland_set_panel_rates((const int *)values, (int)count); +} + extern void vkp_reset_first_frame(void); JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeResetFirstFrame(JNIEnv *env, jclass clazz) { diff --git a/app/src/main/cpp/waylandcomp/src/wl_color_mgmt.c b/app/src/main/cpp/waylandcomp/src/wl_color_mgmt.c index 1ba254c4cd..a45d2691cf 100644 --- a/app/src/main/cpp/waylandcomp/src/wl_color_mgmt.c +++ b/app/src/main/cpp/waylandcomp/src/wl_color_mgmt.c @@ -84,15 +84,18 @@ static struct { static _Atomic int g_gate = -1; static char g_gate_why[320]; static _Atomic int g_output_on = 1; +static _Atomic int g_output_wanted = 1; +static pthread_mutex_t g_output_mu = PTHREAD_MUTEX_INITIALIZER; void droiddeck_color_set_request(int mode, const char *source, int dxvk_hdr, int zero_copy_forced) { pthread_mutex_lock(&g_mu); - g_req.mode = mode < 0 ? 0 : mode > 2 ? 2 : mode; + g_req.mode = mode < 0 ? 0 : mode > 3 ? 3 : mode; snprintf(g_req.source, sizeof(g_req.source), "%s", source ? source : "environment"); g_req.dxvk_hdr = dxvk_hdr ? 1 : 0; g_req.zero_copy_forced = zero_copy_forced ? 1 : 0; pthread_mutex_unlock(&g_mu); atomic_store(&g_output_on, 1); + atomic_store(&g_output_wanted, 1); } void droiddeck_color_set_display(int id, const char *name, const char *formats, int hdr10, float max_lum, @@ -610,11 +613,23 @@ int droiddeck_color_tonemapped_on_screen(void) { void droiddeck_color_set_output(int on) { on = on ? 1 : 0; - if (atomic_load(&g_gate) != 1) { - droiddeck_log(TAG, "HDR output switch (%s) ignored: HDR is not open in this session", on ? "on" : "off"); + pthread_mutex_lock(&g_mu); + const int tonemap_only = g_req.mode == 3; + pthread_mutex_unlock(&g_mu); + pthread_mutex_lock(&g_output_mu); + atomic_store(&g_output_wanted, on); + const int gate = atomic_load(&g_gate); + const int changed = gate == 1 && !(on && tonemap_only) && atomic_exchange(&g_output_on, on) != on; + pthread_mutex_unlock(&g_output_mu); + if (gate != 1) { + if (gate == 0) droiddeck_log(TAG, "HDR output switch (%s) ignored: HDR is not open in this session", on ? "on" : "off"); return; } - if (atomic_exchange(&g_output_on, on) == on) return; + if (on && tonemap_only) { + droiddeck_log(TAG, "HDR output switch (on) ignored: this display cannot show HDR10, HDR frames stay tone-mapped"); + return; + } + if (!changed) return; char who[160]; int age = droiddeck_color_last_frame_age_ms(), tm = droiddeck_color_tonemapped_on_screen(); pthread_mutex_lock(&g_mu); @@ -658,6 +673,8 @@ static void desc_unref(struct cm_desc *d) { if (d && --d->refs <= 0) free(d); } struct cm_params { uint32_t tf, primaries; + int has_prim; int32_t prim[8]; + int has_lum; uint32_t lum_ref; int has_mprim; int32_t mprim[8]; int has_mlum; uint32_t mlum_min, mlum_max; int has_cll; uint32_t cll; @@ -730,9 +747,83 @@ static void make_output_description(struct wl_client *c, struct wl_resource *par droiddeck_client_name(c), what, col->text); } +static const float BT709_XY[8] = {0.64f, 0.33f, 0.30f, 0.60f, 0.15f, 0.06f, 0.3127f, 0.3290f}; +static const float BT2020_XY[8] = {0.708f, 0.292f, 0.170f, 0.797f, 0.131f, 0.046f, 0.3127f, 0.3290f}; + +static void mat_mul(const double a[9], const double b[9], double out[9]) { + double m[9]; + for (int i = 0; i < 3; i++) + for (int j = 0; j < 3; j++) + m[3 * i + j] = a[3 * i] * b[j] + a[3 * i + 1] * b[3 + j] + a[3 * i + 2] * b[6 + j]; + memcpy(out, m, sizeof(m)); +} + +static int mat_invert(const double m[9], double out[9]) { + const double det = m[0] * (m[4] * m[8] - m[5] * m[7]) - m[1] * (m[3] * m[8] - m[5] * m[6]) + + m[2] * (m[3] * m[7] - m[4] * m[6]); + if (det > -1e-12 && det < 1e-12) return -1; + const double k = 1.0 / det; + double r[9] = {(m[4] * m[8] - m[5] * m[7]) * k, (m[2] * m[7] - m[1] * m[8]) * k, (m[1] * m[5] - m[2] * m[4]) * k, + (m[5] * m[6] - m[3] * m[8]) * k, (m[0] * m[8] - m[2] * m[6]) * k, (m[2] * m[3] - m[0] * m[5]) * k, + (m[3] * m[7] - m[4] * m[6]) * k, (m[1] * m[6] - m[0] * m[7]) * k, (m[0] * m[4] - m[1] * m[3]) * k}; + memcpy(out, r, sizeof(r)); + return 0; +} + +static int rgb_to_xyz(const float xy[8], double out[9], double white[3]) { + for (int i = 0; i < 4; i++) + if (xy[2 * i + 1] < 1e-4f) return -1; + double p[9], inv[9]; + for (int i = 0; i < 3; i++) { + const double x = xy[2 * i], y = xy[2 * i + 1]; + p[i] = x / y; p[3 + i] = 1.0; p[6 + i] = (1.0 - x - y) / y; + } + white[0] = xy[6] / xy[7]; white[1] = 1.0; white[2] = (1.0 - xy[6] - xy[7]) / xy[7]; + if (mat_invert(p, inv) != 0) return -1; + for (int i = 0; i < 3; i++) { + const double scale = inv[3 * i] * white[0] + inv[3 * i + 1] * white[1] + inv[3 * i + 2] * white[2]; + out[i] = p[i] * scale; out[3 + i] = p[3 + i] * scale; out[6 + i] = p[6 + i] * scale; + } + return 0; +} + +static int matrix_to_bt2020(const float xy[8], float out[9]) { + static const double bradford[9] = {0.8951, 0.2664, -0.1614, -0.7502, 1.7135, 0.0367, 0.0389, -0.0685, 1.0296}; + double src[9], dst[9], dst_inv[9], sw[3], dw[3], cone_inv[9], adapt[9], m[9]; + if (rgb_to_xyz(xy, src, sw) != 0 || rgb_to_xyz(BT2020_XY, dst, dw) != 0) return -1; + if (mat_invert(dst, dst_inv) != 0 || mat_invert(bradford, cone_inv) != 0) return -1; + double scale[9] = {0}; + for (int i = 0; i < 3; i++) { + const double from = bradford[3 * i] * sw[0] + bradford[3 * i + 1] * sw[1] + bradford[3 * i + 2] * sw[2]; + const double to = bradford[3 * i] * dw[0] + bradford[3 * i + 1] * dw[1] + bradford[3 * i + 2] * dw[2]; + if (from > -1e-9 && from < 1e-9) return -1; + scale[4 * i] = to / from; + } + mat_mul(scale, bradford, adapt); + mat_mul(cone_inv, adapt, adapt); + mat_mul(adapt, src, m); + mat_mul(dst_inv, m, m); + for (int i = 0; i < 9; i++) out[i] = (float)m[i]; + return 0; +} + +static struct wl_resource *publish_description(struct wl_client *client, struct wl_resource *parent, uint32_t id, + struct cm_desc *d) { + struct wl_resource *out = wl_resource_create(client, &wp_image_description_v1_interface, + wl_resource_get_version(parent), id); + if (!out) { free(d); wl_client_post_no_memory(client); return NULL; } + d->refs = 1; + wl_resource_set_implementation(out, &image_description_impl, d, image_description_resource_destroy); + wp_image_description_v1_send_ready(out, d->c.identity); + pthread_mutex_lock(&g_mu); + g_hdr.descs++; + pthread_mutex_unlock(&g_mu); + return out; +} + static void params_create(struct wl_client *client, struct wl_resource *r, uint32_t id) { struct cm_params *p = wl_resource_get_user_data(r); - if (!p->tf || !p->primaries) { + if (!p->tf || (!p->primaries && !p->has_prim)) { wl_resource_post_error(r, WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_INCOMPLETE_SET, "transfer function and primaries must both be set"); return; @@ -744,10 +835,29 @@ static void params_create(struct wl_client *client, struct wl_resource *r, uint3 if (!g_next_identity) g_next_identity = 1; c->primaries = p->primaries; c->tf = p->tf; - if (p->primaries == WP_COLOR_MANAGER_V1_PRIMARIES_BT2020 && p->tf == WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_ST2084_PQ) + const float ref = p->has_lum ? (float)p->lum_ref : 203.0f; + float xy[8]; + for (int i = 0; i < 8; i++) + xy[i] = p->has_prim ? p->prim[i] / 1e6f + : p->primaries == WP_COLOR_MANAGER_V1_PRIMARIES_SRGB ? BT709_XY[i] : BT2020_XY[i]; + if (p->primaries == WP_COLOR_MANAGER_V1_PRIMARIES_BT2020 && ref == 203.0f) { c->dataspace = DROIDDECK_ADATASPACE_BT2020_PQ; - else if (p->primaries == WP_COLOR_MANAGER_V1_PRIMARIES_BT2020 && p->tf == WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_HLG) - c->dataspace = DROIDDECK_ADATASPACE_BT2020_HLG; + } else if (matrix_to_bt2020(xy, c->to2020) == 0) { + c->convert = 1; + c->gain = 10000.0f * 203.0f / ref; + } else { + struct wl_resource *bad = wl_resource_create(client, &wp_image_description_v1_interface, + wl_resource_get_version(r), id); + free(d); + if (!bad) { wl_client_post_no_memory(client); return; } + wl_resource_set_implementation(bad, &image_description_impl, NULL, NULL); + wp_image_description_v1_send_failed(bad, WP_IMAGE_DESCRIPTION_V1_CAUSE_UNSUPPORTED, + "the primaries do not form a colour space"); + droiddeck_log(TAG, "image description from %s refused: its primaries do not form a colour space", + droiddeck_client_name(client)); + wl_resource_destroy(r); + return; + } char dropped[160] = ""; float mlum_min = 0.005f, mlum_max = 10000.0f; @@ -781,7 +891,12 @@ static void params_create(struct wl_client *client, struct wl_resource *r, uint3 } if (cll > 0.0f || fall > 0.0f) { c->has_cta861 = 1; c->max_cll = cll; c->max_fall = fall; } - int n = snprintf(c->text, sizeof(c->text), "%s, %s", primaries_name(c->primaries), tf_name(c->tf)); + int n = snprintf(c->text, sizeof(c->text), "%s, %s", p->has_prim ? "custom primaries" : primaries_name(c->primaries), + tf_name(c->tf)); + if (c->convert && n < (int)sizeof(c->text)) + n += snprintf(c->text + n, sizeof(c->text) - (size_t)n, + "; R %.4f,%.4f G %.4f,%.4f B %.4f,%.4f W %.4f,%.4f, reference white %.0f nits", + xy[0], xy[1], xy[2], xy[3], xy[4], xy[5], xy[6], xy[7], ref); if (c->has_st2086 && n < (int)sizeof(c->text)) n += snprintf(c->text + n, sizeof(c->text) - (size_t)n, "; mastering R %.4f,%.4f G %.4f,%.4f B %.4f,%.4f W %.4f,%.4f, %.4f-%.0f nits%s", @@ -793,19 +908,13 @@ static void params_create(struct wl_client *client, struct wl_resource *r, uint3 if (!c->has_st2086 && !c->has_cta861 && n < (int)sizeof(c->text)) snprintf(c->text + n, sizeof(c->text) - (size_t)n, " (no HDR metadata: the game has not called vkSetHdrMetadataEXT)"); - struct wl_resource *out = wl_resource_create(client, &wp_image_description_v1_interface, - wl_resource_get_version(r), id); - if (!out) { free(d); wl_client_post_no_memory(client); return; } - d->refs = 1; - wl_resource_set_implementation(out, &image_description_impl, d, image_description_resource_destroy); - wp_image_description_v1_send_ready(out, c->identity); - if (c->dataspace) { - pthread_mutex_lock(&g_mu); - g_hdr.descs++; - pthread_mutex_unlock(&g_mu); - } - droiddeck_log(TAG, "image description #%u from %s: %s -> ready (on a display layer: dataspace %s)", c->identity, - droiddeck_client_name(client), c->text, dataspace_name(c->dataspace)); + if (!publish_description(client, r, id, d)) return; + if (c->convert) + droiddeck_log(TAG, "image description #%u from %s: %s -> ready (converted to BT.2020 PQ when the scene is " + "composed)", c->identity, droiddeck_client_name(client), c->text); + else + droiddeck_log(TAG, "image description #%u from %s: %s -> ready (on a display layer: dataspace %s)", c->identity, + droiddeck_client_name(client), c->text, dataspace_name(c->dataspace)); if (dropped[0]) { size_t l = strlen(dropped); if (l && dropped[l - 1] == ',') dropped[l - 1] = 0; @@ -840,8 +949,8 @@ static void params_set_tf_power(struct wl_client *c, struct wl_resource *r, uint } static void params_set_primaries_named(struct wl_client *c, struct wl_resource *r, uint32_t primaries) { struct cm_params *p = wl_resource_get_user_data(r); - PARAMS_ONCE(p->primaries, "primaries"); - if (primaries != WP_COLOR_MANAGER_V1_PRIMARIES_BT2020) { + PARAMS_ONCE(p->primaries || p->has_prim, "primaries"); + if (primaries != WP_COLOR_MANAGER_V1_PRIMARIES_BT2020 && primaries != WP_COLOR_MANAGER_V1_PRIMARIES_SRGB) { wl_resource_post_error(r, WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_INVALID_PRIMARIES_NAMED, "primaries %u were not advertised", primaries); return; @@ -850,12 +959,21 @@ static void params_set_primaries_named(struct wl_client *c, struct wl_resource * } static void params_set_primaries(struct wl_client *c, struct wl_resource *r, int32_t rx, int32_t ry, int32_t gx, int32_t gy, int32_t bx, int32_t by, int32_t wx, int32_t wy) { - wl_resource_post_error(r, WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_UNSUPPORTED_FEATURE, - "set_primaries is not supported"); + struct cm_params *p = wl_resource_get_user_data(r); + PARAMS_ONCE(p->primaries || p->has_prim, "primaries"); + p->has_prim = 1; + p->prim[0] = rx; p->prim[1] = ry; p->prim[2] = gx; p->prim[3] = gy; + p->prim[4] = bx; p->prim[5] = by; p->prim[6] = wx; p->prim[7] = wy; } static void params_set_luminances(struct wl_client *c, struct wl_resource *r, uint32_t mn, uint32_t mx, uint32_t ref) { - wl_resource_post_error(r, WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_UNSUPPORTED_FEATURE, - "set_luminances is not supported"); + struct cm_params *p = wl_resource_get_user_data(r); + PARAMS_ONCE(p->has_lum, "luminances"); + if ((uint64_t)mx * 10000u <= mn || (uint64_t)ref * 10000u <= mn) { + wl_resource_post_error(r, WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_INVALID_LUMINANCE, + "maximum and reference luminance must be above the minimum"); + return; + } + p->has_lum = 1; p->lum_ref = ref; } static void params_set_mastering_display_primaries(struct wl_client *c, struct wl_resource *r, int32_t rx, int32_t ry, int32_t gx, int32_t gy, int32_t bx, int32_t by, int32_t wx, int32_t wy) { @@ -1083,7 +1201,20 @@ static void cm_create_parametric_creator(struct wl_client *c, struct wl_resource } static void cm_create_windows_scrgb(struct wl_client *c, struct wl_resource *r, uint32_t id) { - wl_resource_post_error(r, WP_COLOR_MANAGER_V1_ERROR_UNSUPPORTED_FEATURE, "windows_scrgb is not supported"); + struct cm_desc *d = calloc(1, sizeof(*d)); + if (!d) { wl_client_post_no_memory(c); return; } + struct droiddeck_color *col = &d->c; + col->identity = g_next_identity++; + if (!g_next_identity) g_next_identity = 1; + col->primaries = WP_COLOR_MANAGER_V1_PRIMARIES_SRGB; + col->tf = WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_EXT_LINEAR; + col->convert = 2; + col->gain = 80.0f; + matrix_to_bt2020(BT709_XY, col->to2020); + snprintf(col->text, sizeof(col->text), "%s, %s (1.0 = 80 nits)", primaries_name(col->primaries), tf_name(col->tf)); + if (!publish_description(c, r, id, d)) return; + droiddeck_log(TAG, "image description #%u from %s: %s -> ready (converted to BT.2020 PQ when the scene is composed)", + col->identity, droiddeck_client_name(c), col->text); } static const struct wp_color_manager_v1_interface cm_impl = { @@ -1103,14 +1234,20 @@ static void bind_cm(struct wl_client *c, void *data, uint32_t ver, uint32_t id) wl_resource_set_implementation(r, &cm_impl, NULL, NULL); wp_color_manager_v1_send_supported_intent(r, WP_COLOR_MANAGER_V1_RENDER_INTENT_PERCEPTUAL); wp_color_manager_v1_send_supported_feature(r, WP_COLOR_MANAGER_V1_FEATURE_PARAMETRIC); + wp_color_manager_v1_send_supported_feature(r, WP_COLOR_MANAGER_V1_FEATURE_SET_PRIMARIES); + wp_color_manager_v1_send_supported_feature(r, WP_COLOR_MANAGER_V1_FEATURE_SET_LUMINANCES); wp_color_manager_v1_send_supported_feature(r, WP_COLOR_MANAGER_V1_FEATURE_SET_MASTERING_DISPLAY_PRIMARIES); + wp_color_manager_v1_send_supported_feature(r, WP_COLOR_MANAGER_V1_FEATURE_EXTENDED_TARGET_VOLUME); + wp_color_manager_v1_send_supported_feature(r, WP_COLOR_MANAGER_V1_FEATURE_WINDOWS_SCRGB); + wp_color_manager_v1_send_supported_primaries_named(r, WP_COLOR_MANAGER_V1_PRIMARIES_SRGB); wp_color_manager_v1_send_supported_primaries_named(r, WP_COLOR_MANAGER_V1_PRIMARIES_BT2020); wp_color_manager_v1_send_supported_tf_named(r, WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_ST2084_PQ); wp_color_manager_v1_send_done(r); if (last_named != c) { last_named = c; droiddeck_log(TAG, "%s bound wp_color_manager_v1 version %u (offered: perceptual intent; parametric descriptions " - "with mastering metadata; BT.2020 primaries; ST 2084 PQ) - its Vulkan driver can now list " + "with custom primaries, luminances and mastering metadata; Windows scRGB; sRGB and BT.2020 primaries; " + "ST 2084 PQ) - its Vulkan driver can now list " "VK_COLOR_SPACE_HDR10_ST2084_EXT", droiddeck_client_name(c), ver > 1 ? 1u : ver); } } @@ -1150,6 +1287,7 @@ void droiddeck_color_init(struct wl_display *display) { char asked[128]; if (mode == 2) snprintf(asked, sizeof(asked), "DROIDDECK_WAYLAND_HDR=force (%s)", source); + else if (mode == 3) snprintf(asked, sizeof(asked), "HDR is on, tone-mapped for this display (%s)", source); else if (strstr(source, "env")) snprintf(asked, sizeof(asked), "DROIDDECK_WAYLAND_HDR=1 (%s)", source); else snprintf(asked, sizeof(asked), "HDR output is on (%s)", source); @@ -1168,7 +1306,7 @@ void droiddeck_color_init(struct wl_display *display) { snprintf(why, sizeof(why), "this Android has no display layers with dataspace control " "(ASurfaceControl + ASurfaceTransaction_setBufferDataSpace, Android 10+)"); else if (!ahb_ok) - snprintf(why, sizeof(why), "zero-copy presentation is unavailable here (banner_ahb_v1 not advertised), and an " + snprintf(why, sizeof(why), "zero-copy presentation is unavailable here (droiddeck_ahb_v1 not advertised), and an " "HDR frame is only honest on the game's own display layer"); if (why[0]) { @@ -1198,13 +1336,20 @@ void droiddeck_color_init(struct wl_display *display) { log_verdict(1); return; } + pthread_mutex_lock(&g_output_mu); atomic_store(&g_gate, 1); + if (mode == 3 || !atomic_load(&g_output_wanted)) atomic_store(&g_output_on, 0); + pthread_mutex_unlock(&g_output_mu); char syms[160]; sc_layer_hdr_symbols(syms, sizeof(syms)); droiddeck_log(TAG, "HDR gate %s: %s and %s. Offering games HDR10: wp_color_manager_v1 version 1 (BT.2020 primaries " "+ ST 2084 PQ, parametric descriptions with mastering metadata) and 10-bit AB30/XB30 dma-buf formats; HDR " "frames go on the game's own display layer as BT2020_PQ (%s)", mode == 2 ? "FORCED OPEN (testing)" : "OPEN", asked, disp, syms); + if (mode == 3) { + droiddeck_log(TAG, "this display cannot show HDR10: games still render HDR and every HDR frame is tone-mapped to " + "SDR on the game's display layer"); + } if (mode == 2 && !hdr10) droiddeck_log(TAG, "DROIDDECK_WAYLAND_HDR=force on a display without HDR10 - testing only: SurfaceFlinger will tone-map " "the game layer for this panel (expect GPU/CLIENT composition for it), nothing looks HDR"); diff --git a/app/src/main/cpp/waylandcomp/src/wl_dmabuf.c b/app/src/main/cpp/waylandcomp/src/wl_dmabuf.c index cc85bd32e6..a6e0eac3a6 100644 --- a/app/src/main/cpp/waylandcomp/src/wl_dmabuf.c +++ b/app/src/main/cpp/waylandcomp/src/wl_dmabuf.c @@ -14,6 +14,7 @@ #include "droiddeck_ext.h" #include "droiddeck_color.h" #include "compositor_internal.h" +#include "display_buffers.h" static void dbuf_buffer_resource_destroy(struct wl_resource *r) { @@ -58,6 +59,7 @@ static struct wl_resource *params_do_create(struct wl_client *c, struct wl_resou wl_resource_set_implementation(buf, &dbuf_buffer_impl, b, dbuf_buffer_resource_destroy); struct client_info *ci = client_info_of(c); if (ci) ci->dmabuf_buffers++; + display_buffers_match(c, buf, b); return buf; } static void params_create(struct wl_client *c, struct wl_resource *r, int32_t w, int32_t h, @@ -111,13 +113,16 @@ static const struct zwp_linux_dmabuf_v1_interface dmabuf_impl = { static struct { uint32_t fmt; uint64_t mods[DMABUF_NMOD]; int n; } g_dmabuf_fmts[DMABUF_NFMT_MAX] = { {DRM_ARGB8888}, {DRM_XRGB8888}, {DRM_ABGR8888}, {DRM_XBGR8888}, {DRM_ABGR2101010}, {DRM_XBGR2101010}}; static int g_dmabuf_nfmt = DMABUF_NFMT_SDR; -static int g_dmabuf_fmts_ready; +static volatile int g_dmabuf_fmts_ready; static void dmabuf_build_feedback(void); +void droiddeck_dmabuf_formats_stale(void) { g_dmabuf_fmts_ready = 0; } + static void dmabuf_build_formats(void) { char line[320]; - int pos = 0, compressed = 0; + int pos = 0, compressed = 0, backed = 0; g_dmabuf_fmts_ready = 1; + display_buffers_withdraw_ubwc(); g_dmabuf_nfmt = droiddeck_color_hdr_open() ? DMABUF_NFMT_MAX : DMABUF_NFMT_SDR; for (int f = 0; f < g_dmabuf_nfmt; f++) { uint64_t got[DMABUF_NMOD]; @@ -129,6 +134,12 @@ static void dmabuf_build_formats(void) { g_dmabuf_fmts[f].mods[k++] = got[i]; if (got[i] == VKP_MOD_QCOM_COMPRESSED) compressed++; } + int listed = 0; + for (int i = 0; i < k; i++) if (g_dmabuf_fmts[f].mods[i] == VKP_MOD_QCOM_COMPRESSED) listed = 1; + if (display_buffers_offer_ubwc(g_dmabuf_fmts[f].fmt) && !listed) { + g_dmabuf_fmts[f].mods[k++] = VKP_MOD_QCOM_COMPRESSED; + backed++; + } g_dmabuf_fmts[f].mods[k++] = MOD_INVALID; g_dmabuf_fmts[f].n = k; uint32_t fmt = g_dmabuf_fmts[f].fmt; @@ -141,7 +152,10 @@ static void dmabuf_build_formats(void) { } droiddeck_log("dmabuf", "formats: %s%s", line, !g_ubwc ? " (DROIDDECK_WAYLAND_UBWC=0: qcom_compressed not advertised)" : ""); - if (g_ubwc && !compressed) + if (backed) + droiddeck_log("dmabuf", "qcom_compressed is advertised for %d formats the compositor's driver (%s) does not " + "import as dma-bufs: this session's driver renders them into gralloc buffers", backed, vkp_gpu_name()); + else if (g_ubwc && !compressed) droiddeck_log("dmabuf", "the compositor's driver (%s) reports no importable qcom_compressed layout: " "game swapchains stay linear", vkp_gpu_name()); if (g_dmabuf_nfmt > DMABUF_NFMT_SDR) { @@ -212,6 +226,7 @@ static void dmabuf_build_feedback(void) { return; } fcntl(fd, F_ADD_SEALS, F_SEAL_SEAL | F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE); + if (g_fmt_table_fd >= 0) close(g_fmt_table_fd); g_fmt_table_fd = fd; g_fmt_table_size = size; g_fmt_table_n = (uint16_t)n; diff --git a/app/src/main/java/com/droiddeck/launcher/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 d286cce1f5..99e164d108 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -194,10 +194,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("") @@ -596,9 +598,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) @@ -1261,6 +1265,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet requestedOrientation = launcherOrientation homePage = com.droiddeck.launcher.core.AppUiPrefs.homePage(this) launcherFullscreen = SessionPrefs.launcherFullscreen(this) + controllerHaptics = SessionPrefs.controllerHaptics(this) downloadSource = DownloadSource.mode(this) downloadMirror = DownloadSource.mirror(this) downloadPrefix = DownloadSource.custom(this) @@ -1360,6 +1365,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet launcherOrientation = launcherOrientation, homePage = homePage, launcherFullscreen = launcherFullscreen, + controllerHaptics = controllerHaptics, downloadSource = downloadSource, downloadMirror = downloadMirror, downloadPrefix = downloadPrefix, @@ -1676,6 +1682,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet com.droiddeck.launcher.core.AppUiPrefs.setHomePage(this, value) homePage = value }, + onControllerHaptics = { on -> SessionPrefs.setControllerHaptics(this, on); controllerHaptics = on }, onLauncherFullscreen = { on -> SessionPrefs.setLauncherFullscreen(this, on) launcherFullscreen = on @@ -2044,6 +2051,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet if (!compatLaunch!!.loading.ended && event.keyCode !in listOf( KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE)) return true } + if (controllerHaptics) com.droiddeck.launcher.ui.ControllerHaptics.onKey(this, event) if (event.keyCode == KeyEvent.KEYCODE_BUTTON_A) com.droiddeck.launcher.ui.HeldKeys.confirm = event.action == KeyEvent.ACTION_DOWN if (showComponents && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) { if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) { @@ -2079,6 +2087,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet refreshHomeAppState() } if (settingsMode == SessionService.MODE_STEAM) refreshFoundSteamLibraries() + settingsMode?.let { hdrOn = SessionPrefs.hdr(this, it) } compatLaunchVisible = true com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false) com.droiddeck.launcher.ui.DualScreenPanel.ownerPaused(taskId, false) @@ -2586,7 +2595,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet ModeSettings( mode = mode, resolution = resolution, panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this), - hdr = hdrOn, hdrReason = hdrReason, + hdr = hdrOn, hdrReason = hdrReason, hdrDisplay = hdrDisplay, zeroCopy = zeroCopyOn, upscaler = upscaler, upscaleSharpness = upscaleSharpness, gpuDrivers = drivers.summary(), touchMode = touchMode, @@ -2604,6 +2613,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, @@ -2639,7 +2649,13 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet onIntegrationAppInfo = ::openAppInfo, onIntegrationLocation = ::openWifiDiscoverySettings, onResolution = { value -> SessionPrefs.setResolutionChoice(this, mode, value); resolution = value }, - onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on }, + onHdr = { on -> com.droiddeck.launcher.session.SessionHdr.set(this, mode, on); hdrOn = on }, + onZeroCopy = { on -> + SessionPrefs.setZeroCopy(this, mode, on); zeroCopyOn = on + if (com.droiddeck.launcher.wayland.CompositorHost.isStarted && !SessionState.hdr && + SessionPrefs.prefMode(SessionState.mode) == SessionPrefs.prefMode(mode)) + com.droiddeck.launcher.wayland.WaylandCompositor.nativeSetZeroCopy(on) + }, onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) }, onUpscaler = { m -> SessionPrefs.setUpscaler(this, m); upscaler = m }, onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct }, @@ -2666,6 +2682,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 @@ -2983,9 +3000,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) } @@ -2998,6 +3017,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) @@ -3328,6 +3348,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 42cea423e6..db0ac0f2b1 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 @@ -171,8 +173,42 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var pipAutoEnter by mutableStateOf(false) private var unfoldedControls by mutableStateOf(false) private var unfoldedControlsWithController by mutableStateOf(false) + private var adaptiveSticks by mutableStateOf(null) + 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 @@ -189,7 +225,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private var unfoldedPanel by mutableStateOf(null) private var unfoldedColumn: android.widget.LinearLayout? = null + private var unfoldedDeckSurface: com.droiddeck.launcher.ui.InputSurfaceView? = null private var swappedInputSurface: com.droiddeck.launcher.ui.InputSurfaceView? = null + private var unfoldedDeckPanel by mutableStateOf(null) private var deckPanelLayouts: Map = emptyMap() private lateinit var sessionRoot: FrameLayout private var inputRouter: InputRouter? = null @@ -241,7 +279,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 @@ -302,7 +349,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 @@ -506,6 +559,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( @@ -606,6 +661,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) @@ -643,15 +701,9 @@ 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 layoutOptions by mutableStateOf>>(emptyList()) - private var layoutChoice by mutableStateOf("") - private var layoutEditor by mutableStateOf?>(null) - private var layoutEditorScope: String? = null - private var layoutEditorSplit: com.droiddeck.launcher.ui.InputEditorSplit? = null - private var controlsGame: Long? = null - private var controllerInUse = false - private var controlsHiddenByTap = false private var secondScreenMode by mutableStateOf(SessionState.secondScreenMode) private var secondScreenDisplays by mutableStateOf>(emptyList()) private var selectedSecondScreenDisplay by mutableStateOf(SessionState.secondScreenDisplay) @@ -843,6 +895,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) @@ -854,7 +910,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde bridge.setStickDeadZone(ControllerPrefs.deadZone(this)) bridge.setBuiltinPad(SessionState.mode != SessionService.MODE_STEAM || SessionPrefs.builtinPad(this)) padBridge = bridge - inputRouter = InputRouter(inputOutput).also { bridge.setInputRouter(it); DeckControls.setRouter(it); physicalInputBindings = com.droiddeck.launcher.input.PhysicalInputBindings(it, ::noteRemappedControllerUse) } + inputRouter = InputRouter(inputOutput).also { bridge.setInputRouter(it); DeckControls.setRouter(it); physicalInputBindings = com.droiddeck.launcher.input.PhysicalInputBindings(it) } refreshInputProfile() bridge.setOnChordInput(backQamInput::onChordInput) SessionState.padBridge = bridge @@ -868,15 +924,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde bridge.setExcluded(vr::owns) joyConVr = vr } - SteamControllerBle.listener = { - uiHandler.post { - if (isDestroyed) return@post - if (SteamControllerBle.connected) controllerInUse = true - updatePadMotion() - refreshControls() - } - } - steamController = SteamControllerBle(this, inputRouter, ::noteSteamControllerUse).also { it.start() } + SteamControllerBle.listener = { uiHandler.post { updatePadMotion(); refreshControls() } } + steamController = SteamControllerBle(this, inputRouter).also { it.start() } if (Build.VERSION.SDK_INT >= 31 && checkSelfPermission(BLUETOOTH_CONNECT) != android.content.pm.PackageManager.PERMISSION_GRANTED && !SessionPrefs.bluetoothAsked(this)) { SessionPrefs.setBluetoothAsked(this) @@ -889,16 +938,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde SessionState.deckPadListener = deckPadListener openDeckRing("activity created") bridge.setOnPlayerInput(::onPadInput) - bridge.setOnPhysicalInput(::noteControllerUse) - controllerInUse = PadBridge.anyControllerConnected() || SteamControllerBle.connected onScreenControls = OnScreenControls(this, bridge).also { controls -> controls.updateLayout(primaryInputLayout) - controls.onCornerTap = ::onControlsCornerTap - controls.onCornerHold = ::openControllerMenu 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) } @@ -943,7 +988,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde false } else if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SURFACE, event)) { false - } else onTouchEvent(event) + } else handleTouch(event) } padMouse = PadMouse(padMouseListener) bridge.setTouchRoute(object : PadBridge.TouchRoute { @@ -974,7 +1019,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde hud = DroidDeckHudHost(this) hud.onConfigChanged = { hudConfig = DroidDeckHudConfig.load(this) } hud.passesTouchAt = ::controlTakesTouchAt - hud.attach(root, onScreenControls?.let(root::indexOfChild)?.takeIf { it >= 0 } ?: root.childCount) + hud.attach(root, root.childCount) memoryHud = com.droiddeck.launcher.session.MemoryHud(this) hud.onPresentingWindowChanged = { CompositorHost.rearmFrameGen { applyFrameGen(force = true) } @@ -1053,6 +1098,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) { @@ -1266,19 +1314,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } } com.droiddeck.launcher.ui.GestureFeedback(recognizedGesture) - layoutEditor?.let { (profile, layout, bindings) -> - com.droiddeck.launcher.ui.InputSurfaceDialog(profile, onDismiss = { - layoutEditor = null; inputSettingsOpen = false - refreshInputProfile(); updateOnScreenControls() - }, onChanged = { refreshInputProfile() }, role = InputRole.PRIMARY, layoutId = layout, bindingsId = bindings, - scope = layoutEditorScope, split = layoutEditorSplit) - } - if (inputSettingsOpen && layoutEditor == null) com.droiddeck.launcher.ui.InputSettingsDialog( - desktop = loadingMode() == SessionService.MODE_DESKTOP, + if (inputSettingsOpen) com.droiddeck.launcher.ui.InputSettingsDialog( onBack = { inputSettingsOpen = false; secondScreenPresentation?.refreshControls() }, onChanged = { controllerSettings = ControllerPrefs.read(this@SessionActivity) - oscMode = sessionOscMode() + oscMode = SessionPrefs.oscMode(this@SessionActivity, SessionState.mode == SessionService.MODE_STEAM) padBridge?.setStickDeadZone(ControllerPrefs.deadZone(this@SessionActivity)) joyConVr?.refresh() onScreenControls?.reload() @@ -1459,7 +1499,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde textureLodBias = if (drawerGameProfileId == null) textureLodBias else drawerTextureLodBias, frameGen = frameGen, frameGenTargetGameId = frameGenTargetGameId()?.toString(), - frameGenTargetGameName = frameGenTargetGameName(), + frameGenTargetGameName = when { + !drawerGameProfileFollowState.followsSteam -> + drawerGameProfileRefresh.data?.profiles + ?.firstOrNull { it.first == frameGenTargetGameId() }?.second + SessionState.mode == SessionService.MODE_STEAM -> frameGenActiveGameName + SessionState.mode == SessionService.MODE_RUN -> + com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) + else -> drawerGameProfileRefresh.data?.profiles + ?.firstOrNull { it.first == frameGenTargetGameId() }?.second + }, hasGameOverride = frameGenHasGameOverride, lossless = lossless, oscMode = oscMode, suspendPolicy = suspendPolicy, @@ -1467,7 +1516,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde micAvailable = SessionState.micAvailable && !SessionState.suspended, micEnabled = SessionState.micEnabled, onMicEnabled = { SessionService.setMicEnabled(this@SessionActivity, it) }, - touchAuto = getString(if (usingTouchpad(SessionPrefs.TOUCH_AUTO)) R.string.mode_touch_touchpad else R.string.mode_touch_mouse), + touchAuto = getString(if (usingTouchpad()) R.string.session_touch_auto_touchpad else R.string.session_touch_auto_direct), pen = penSettings.takeIf { penSeen }, onPen = { key, value -> SessionPrefs.setPenSetting(this@SessionActivity, key, value); readPrefs() }, fexPreset = fexPreset, @@ -1659,6 +1708,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() @@ -1699,7 +1751,10 @@ 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 - refreshInputProfile() + onScreenControls?.reload() + applyUnfoldedControls() + unfoldedPanel?.reload() + bottomInputControls?.reload() }, backHold = backHold, onBackHold = { on -> @@ -1736,23 +1791,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde }, onOsc = { v -> SessionPrefs.setOscMode(this@SessionActivity, v) - controlsHiddenByTap = false readPrefs() - applyUnfoldedControls() updateOnScreenControls() + if (v == SessionPrefs.OSC_STEAM_TOUCH && com.droiddeck.launcher.input.SteamTouchDevice.current == null) + Toast.makeText(this@SessionActivity, R.string.osc_style_next_session, Toast.LENGTH_LONG).show() }, - layoutGame = controlsGameName(), - layoutOptions = layoutOptions, - layoutChoice = layoutChoice, - onLayout = ::chooseLayout, - onEditLayout = when { - layoutChoice == com.droiddeck.launcher.input.GameControls.STEAM -> steamTouchControls?.takeIf { steamTouchAvailable && onScreenButtonsVisible && it.visibility == View.VISIBLE }?.let { view -> { - drawerOpen = false - view.startEditing() - } } - primaryInputLayout?.editable == true -> ({ openLayoutEditor() }) - else -> null - }, + onEditSteamTouch = if (steamTouchAvailable && oscMode == SessionPrefs.OSC_STEAM_TOUCH && onScreenButtonsVisible) ({ + drawerOpen = false + steamTouchControls?.startEditing() + }) else null, onSuspendPolicy = { policy -> SessionPrefs.setSuspendPolicy(this@SessionActivity, SessionState.mode, policy) suspendPolicy = policy @@ -1812,6 +1859,38 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde }, unfoldedControls = unfoldedControls, onUnfoldedControls = ::chooseUnfoldedControls, + adaptiveSticks = adaptiveSticks.takeIf { + unfoldedPanel != null || oscMode != SessionPrefs.OSC_NEVER && oscMode != SessionPrefs.OSC_STEAM_QAM && !steamTouchInUse + }, + onAdaptiveSticks = { on -> + 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(), + onQuickButton = { button, on -> + primaryInputLayout?.let { com.droiddeck.launcher.input.InputLibraries.setQuickButton(this@SessionActivity, it.id, button, on) } + refreshInputProfile() + updateOnScreenControls() + }, unfoldedControlsWithController = unfoldedControlsWithController, onUnfoldedControlsWithController = ::chooseUnfoldedControlsWithController, onBackground = { drawerOpen = false; pip.background(); moveTaskToBack(true) }, @@ -2031,17 +2110,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde }, "drawer-components").start() } - private fun frameGenTargetGameName(): String? = when { - !drawerGameProfileFollowState.followsSteam -> - drawerGameProfileRefresh.data?.profiles - ?.firstOrNull { it.first == frameGenTargetGameId() }?.second - SessionState.mode == SessionService.MODE_STEAM -> frameGenActiveGameName - SessionState.mode == SessionService.MODE_RUN -> - com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) - else -> drawerGameProfileRefresh.data?.profiles - ?.firstOrNull { it.first == frameGenTargetGameId() }?.second - } - private fun frameGenTargetGameId(): Long? { if (!drawerGameProfileFollowState.followsSteam) { return drawerGameProfileId @@ -2059,8 +2127,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun loadFrameGenFor(appId: Long?) { - val layoutGame = controlsGameId() - if (layoutGame != controlsGame) { controlsGame = layoutGame; uiHandler.post { refreshInputProfile(); updateOnScreenControls() } } val profileId = appId?.toString() frameGen = FrameGen.mode(this, profileId) frameGenHasGameOverride = appId?.let { @@ -2510,9 +2576,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) @@ -2555,7 +2625,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde fexPreset = SessionPrefs.fexPreset(this) suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode) steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this) - oscMode = sessionOscMode() + oscMode = SessionPrefs.oscMode(this, SessionState.mode == SessionService.MODE_STEAM) + oscRearButtons = SessionPrefs.oscRearButtons(this) + oscTrackpads = SessionPrefs.oscTrackpads(this) backHold = SessionPrefs.backHold(this) backActionsInverted = SessionPrefs.backActionsInverted(this) physicalShortcuts.bindings = PhysicalShortcuts.read(this) @@ -2768,6 +2840,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) @@ -2787,27 +2862,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( @@ -2903,6 +2982,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } cancelTouchGestures() applyFollowOrientation(newConfig) + applyNotchInset() applyUnfoldedControls() resizeOutputForWindow(surfaceW, surfaceH) } @@ -2983,6 +3063,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 -> @@ -3002,9 +3087,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()) @@ -3170,6 +3284,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() } @@ -3230,8 +3345,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() } @@ -3607,12 +3720,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) } @@ -3620,10 +3733,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) } @@ -3643,6 +3756,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde return onScreenControls?.let { takes(it, it::takesTouchAt) } == true || steamTouchControls?.let { takes(it, it::takesTouchAt) } == true || unfoldedPanel?.let { takes(it, it::takesTouchAt) } == true || + unfoldedDeckSurface?.let { takes(it, it::takesTouchAt) } == true || unfoldedColumn?.getChildAt(0)?.let { takes(it) { _, _ -> true } } == true } @@ -3653,7 +3767,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde (event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN) || PenStream.penIndex(event) >= 0)) { drawerControllerActive = false gestureTouchStreamGate.reset() - if (event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) noteScreenTouch(event) } return super.dispatchTouchEvent(event) } @@ -3772,8 +3885,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 @@ -3786,7 +3899,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun requestRelativeMouse() { - runCatching { relativeMouseRequests.execute { applyRelativeMouse() } } + runCatching { gamescopeConvarRequests.execute { applyRelativeMouse() } } } private fun applyRelativeMouse() { @@ -3800,23 +3913,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 @@ -4403,66 +4551,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (started && displayId !in inputWindowDisplays && secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode) } - private fun controlsGameId(): Long? = frameGenTargetGameId() - - private fun controlsGameName(): String? = controlsGameId()?.let { frameGenTargetGameName() } - - private fun gameLibrary(): com.droiddeck.launcher.input.InputLibrary = - com.droiddeck.launcher.input.ControlsChoice.library(this, controlsGameId(), loadingMode() == SessionService.MODE_DESKTOP) - - private fun refreshLayoutOptions() { - val steam = SessionState.mode == SessionService.MODE_STEAM - val game = controlsGameId() - layoutOptions = com.droiddeck.launcher.input.ControlsChoice.options(this, game, steam, controlsGameName()) - layoutChoice = com.droiddeck.launcher.input.ControlsChoice.current(this, game, steam, loadingMode() == SessionService.MODE_DESKTOP) - } - - private fun chooseLayout(id: String) { - val game = controlsGameId() - val name = controlsGameName() - val desktop = loadingMode() == SessionService.MODE_DESKTOP - val created = runCatching { - if (id == com.droiddeck.launcher.input.ControlsChoice.NEW) { - if (game != null && name != null) com.droiddeck.launcher.input.ControlsChoice.newForGame(this, game, name, desktop) else null - } else { com.droiddeck.launcher.input.ControlsChoice.choose(this, game, id, desktop, name); null } - }.onFailure { Log.w(TAG, "could not choose layout $id", it) }.getOrNull() - releasePads() - refreshInputProfile() - updateOnScreenControls() - if (created != null) openLayoutEditor() - } - - private fun openLayoutEditor() { - val game = controlsGameId() - val name = controlsGameName() - val desktop = loadingMode() == SessionService.MODE_DESKTOP - val target = com.droiddeck.launcher.input.ControlsChoice.editTarget(this, game, desktop) ?: return - val layoutName = com.droiddeck.launcher.input.InputLibraries.read(this).layouts.firstOrNull { it.id == target.second }?.name ?: return - val own = com.droiddeck.launcher.input.ControlsChoice.hasOwn(this, game) - val shared = com.droiddeck.launcher.input.ControlsChoice.shared(this, game) - layoutEditorScope = when { - game == null || name == null || !own -> getString(R.string.osc_scope_default, layoutName) - shared -> getString(R.string.osc_scope_shared, layoutName) - layoutName == name -> getString(R.string.osc_scope_own, name) - else -> getString(R.string.osc_scope_game, layoutName, name) - } - layoutEditorSplit = if (game != null && name != null && shared) com.droiddeck.launcher.ui.InputEditorSplit(getString(R.string.osc_just_this_game), - getString(R.string.osc_scope_game, layoutName, name), - { library, layoutId, bindingsId -> com.droiddeck.launcher.input.ControlsChoice.copyForGame(this, library, game, name, desktop, layoutId, bindingsId) }, - { bindingsId -> com.droiddeck.launcher.input.ControlsChoice.useForGame(this, game, name, bindingsId) }) else null - releasePads() - drawerOpen = false - layoutEditor = target - inputSettingsOpen = true - } - private fun refreshInputProfile() { - val library = gameLibrary() + val library = com.droiddeck.launcher.input.InputLibraries.read(this) val desktop = loadingMode() == SessionService.MODE_DESKTOP inputProfile = library.compileActive(desktop, secondScreenMode.panel(this)) stockInputProfile = library.compileStock(desktop, secondScreenMode.panel(this)) primaryInputLayout = library.activeLayout(desktop, InputRole.PRIMARY) - refreshLayoutOptions() + adaptiveSticks = primaryInputLayout?.adaptiveSticks + quickButtons = primaryInputLayout?.takeIf { it.editable }?.let { l -> l.quickButtons.associateWith { it !in l.style.hidden } }.orEmpty() secondaryInputLayout = library.panelLayout(desktop, secondScreenMode.panel(this)) deckPanelLayouts = com.droiddeck.launcher.input.DeckPanel.entries.associateWith { library.panelLayout(desktop, it.bindings) } inputUsesLocalActions = InputControl.padControls.any { inputProfile.action(InputRole.PHYSICAL, it) !is InputAction.Native } @@ -4478,7 +4574,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde onScreenControls?.updateLayout(primaryInputLayout) bottomInputControls?.updateLayout(primaryInputLayout) unfoldedPanel?.updateLayout(primaryInputLayout) - if (onScreenControls != null) applyUnfoldedControls() + if (unfoldedPanel != null) applyUnfoldedControls() + showUnfoldedDeckPanel() updateOnScreenPad() secondScreenPresentation?.refreshControls() } @@ -4513,21 +4610,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun controlsBelowWanted(): Boolean { if (!::sessionRoot.isInitialized || glassesScreen != null || bottomGame != null || cardboard.enabled) return false - if (sessionOscMode() == SessionPrefs.OSC_NEVER || usesSteamTouchLayout()) 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 aspect = if (SessionState.followScreen) 16f / 9f else outputSize().let { (w, h) -> w.toFloat() / h.coerceAtLeast(1) } - val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height, tabRow, aspect) + val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height, tabRow) else FrameLayout.LayoutParams.MATCH_PARENT val params = surfaceView.layoutParams as FrameLayout.LayoutParams if (params.height != gameHeight) { @@ -4536,12 +4631,16 @@ 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)) { sessionRoot.removeView(unfoldedColumn) unfoldedColumn = null + unfoldedDeckSurface = null + unfoldedDeckPanel = null unfoldedPanel = null panel = null if (!wanted) updateOnScreenControls() @@ -4562,14 +4661,36 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde sessionRoot.addView(column, sessionRoot.indexOfChild(surfaceView) + 1) unfoldedColumn = column unfoldedPanel = panel + showUnfoldedDeckPanel() updateOnScreenControls() } unfoldedColumn?.layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, height - gameHeight, Gravity.BOTTOM) } private fun unfoldedBar(): View = com.droiddeck.launcher.ui.bottomScreenBarView(this) { - com.droiddeck.launcher.ui.sessionBarModel(getString(R.string.deck_tab_gamepad), - { chooseUnfoldedControls(false) }, { drawerOpen = true }, ::tapSteamButton, ::tapQam) + val deck = unfoldedDeckPanel + com.droiddeck.launcher.ui.sessionBarModel(getString(if (deck != null) R.string.second_mode_deck_controls else R.string.deck_tab_gamepad), + { chooseUnfoldedControls(false) }, { drawerOpen = true }, ::tapSteamButton, ::tapQam, + tabs = deck?.let { com.droiddeck.launcher.ui.deckPanelTabs(this, it, ::selectDeckPanel) }) + } + + private fun showUnfoldedDeckPanel() { + val column = unfoldedColumn + val panel = unfoldedPanel + val selected = SessionPrefs.deckPanel(this).takeIf { column != null && panel?.dock?.grips == true } + unfoldedDeckPanel = selected + val layout = selected?.takeIf { it != com.droiddeck.launcher.input.DeckPanel.GAMEPAD }?.let { deckPanelLayouts[it] } + if (layout != null && unfoldedDeckSurface?.tag == layout) return + unfoldedDeckSurface?.let { it.releaseInputs(); column?.removeView(it) } + unfoldedDeckSurface = null + if (column == null || panel == null) return + if (layout == null) { panel.visibility = View.VISIBLE; return } + panel.releaseAll() + panel.visibility = View.GONE + unfoldedDeckSurface = com.droiddeck.launcher.ui.InputSurfaceView(this, padBridge, layout.elements, InputRole.PRIMARY, layout.style, haptics = true).also { + it.tag = layout + column.addView(it, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)) + } } private fun bottomKeyboardPresentation(): SecondScreenPresentation? { @@ -4779,7 +4900,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun deliversTouches(mode: String) = mode == SessionPrefs.TOUCH_DIRECT || mode == SessionPrefs.TOUCH_AUTO - private fun usingTouchpad(mode: String = routedTouchMode): Boolean = when (mode) { + private fun usingTouchpad(): Boolean = when (routedTouchMode) { SessionPrefs.TOUCH_PAD -> true SessionPrefs.TOUCH_DIRECT -> false else -> SessionState.mode != SessionService.MODE_STEAM || SessionState.steamUi == "desktop" @@ -4923,11 +5044,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var screenTapsClick = true private fun onScreenMouseButtonShown(): Boolean = listOfNotNull( - onScreenControls?.inputSurface, bottomInputControls?.inputSurface, unfoldedPanel?.inputSurface, + onScreenControls?.inputSurface, bottomInputControls?.inputSurface, unfoldedPanel?.inputSurface, unfoldedDeckSurface, 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) @@ -5054,7 +5177,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) @@ -5347,7 +5470,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } val root = onScreenControls?.parent as? android.view.ViewGroup ?: return null val view = com.droiddeck.launcher.input.SteamTouchControls(this, device, - onMenu = ::openControllerMenu, onKeyboard = ::togglePcKeyboard) + onMenu = { drawerOpen = true }, onKeyboard = ::togglePcKeyboard) view.visibility = View.GONE view.onEditingChanged = { touchEditorChanged() } view.onOptions = { options -> @@ -5365,7 +5488,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 @@ -5377,140 +5500,103 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde updateOnScreenPad() val c = onScreenControls glassesSlot = when { - c == null || c.visibility != View.VISIBLE || c.hidden != null -> 0 - c.inputSurface.shownElements.any { it.id == com.droiddeck.launcher.input.KitLayout.KEYBOARD_ID } -> 2 + c == null || c.visibility != View.VISIBLE || c.isPinnedOnly -> 0 + c.isButtonsOnly -> -1 + primaryInputLayout?.let { l -> l.elements.any { it.quickButton == InputCommand.KEYBOARD && !l.style.hides(it) } } + ?: (controllerSettings?.keyboardButton != false) -> 2 else -> 1 } } - private fun sessionOscMode() = SessionPrefs.oscMode(this, steamSession = SessionState.mode == SessionService.MODE_STEAM) - - private fun usesSteamTouchLayout() = SessionState.mode == SessionService.MODE_STEAM && - com.droiddeck.launcher.input.GameControls.steamLayout(this, controlsGameId()) - - private fun controlsPlan(): com.droiddeck.launcher.input.ControlsPresenter.Plan { - val steam = SessionState.mode == SessionService.MODE_STEAM - if (!PadBridge.anyControllerConnected() && !SteamControllerBle.connected) controllerInUse = false - return com.droiddeck.launcher.input.ControlsPresenter.plan(com.droiddeck.launcher.input.ControlsPresenter.State( - mode = sessionOscMode(), - desktop = SessionState.mode == SessionService.MODE_DESKTOP, - virtualPad = !steam || SessionPrefs.builtinPad(this), - covered = controlsCovered(), - controllerInUse = controllerInUse, - hiddenByTap = controlsHiddenByTap, - steamLayout = usesSteamTouchLayout(), - bottomScreen = bottomGame?.surfaceView?.parent is android.view.ViewGroup, - )) - } - - private fun controlsCovered() = pipUi || unfoldedPanel != null || pcKeyboardOpen || inputSettingsOpen || keyboardCoversPad() - private fun updateOnScreenPad() { - val controls = onScreenControls ?: return fun hideBottomControls() { bottomInputControls?.takeIf { it.visibility == View.VISIBLE }?.let { it.releaseAll(); it.visibility = View.GONE } } - fun hideSteam() { - steamTouchControls?.let { it.cancelEditing(); it.releaseAll(); it.visibility = View.GONE } - val keyboardOver = controlsCovered() && usesSteamTouchLayout() - if (!keyboardOver) com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = false + val forced = File(Environment.getExternalStorageDirectory(), "Download/droiddeck-osc") + .takeIf { it.isFile } + ?.let { FileUtils.readString(it)?.trim()?.lowercase() } + ?: SessionPrefs.oscMode(this, SessionState.mode == SessionService.MODE_STEAM) + unfoldedColumn?.let { column -> + val shown = if (inputSettingsOpen) View.INVISIBLE else View.VISIBLE + if (column.visibility != shown) { unfoldedPanel?.releaseAll(); unfoldedDeckSurface?.releaseInputs(); column.visibility = shown } } - val plan = controlsPlan() - onScreenButtonsVisible = plan.shown - val wantsSteam = plan.place == com.droiddeck.launcher.input.ControlsPresenter.Place.STEAM - val steam = if (wantsSteam) steamTouch() else null - steamTouchInUse = steam != null - uiHandler.removeCallbacks(steamTouchRetry) - if (wantsSteam && steam == null && !isFinishing && !isDestroyed) { - uiHandler.postDelayed(steamTouchRetry, 1000) + val controls = onScreenControls ?: return + fun showPinned() { + controls.setPinnedOnly(true) + val pinned = controls.hasPinned && !pipUi && !inputSettingsOpen + if (!pinned) controls.releaseAll() + controls.visibility = if (pinned) View.VISIBLE else View.GONE } - if (steam != null) { + if (pipUi || unfoldedPanel != null || pcKeyboardOpen || inputSettingsOpen || + (SessionState.mode == SessionService.MODE_STEAM && !SessionPrefs.builtinPad(this))) { + onScreenButtonsVisible = false hideBottomControls() - controls.releaseAll(); controls.visibility = View.GONE - if (!plan.shown) { steam.cancelEditing(); steam.releaseAll() } - steam.visibility = if (plan.shown) View.VISIBLE else View.GONE - // Steam takes seconds to configure a newly plugged touch controller, so hiding the layout keeps it plugged. - com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = true + showPinned() + steamTouchControls?.let { it.cancelEditing(); it.releaseAll(); it.visibility = View.GONE } + com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = false applyTouchRouting() return } - hideSteam() - applyTouchRouting() - when (plan.place) { - com.droiddeck.launcher.input.ControlsPresenter.Place.BOTTOM -> { - val bottomRoot = bottomGame?.surfaceView?.parent as android.view.ViewGroup - controls.releaseAll(); controls.visibility = View.GONE - var bottom = bottomInputControls - if (bottom?.parent !== bottomRoot) { - (bottom?.parent as? android.view.ViewGroup)?.removeView(bottom) - bottom = OnScreenControls(bottomRoot.context, padBridge).also { view -> - view.onTouchMiss = { event -> onBottomGameTouch(event) } - view.onCornerTap = ::onControlsCornerTap - view.onCornerHold = ::openControllerMenu - bottomRoot.addView(view, android.view.ViewGroup.LayoutParams(-1, -1)) - } - bottomInputControls = bottom + val buttonsOnly = forced == SessionPrefs.OSC_STEAM_QAM + val wantsSteam = forced == SessionPrefs.OSC_STEAM_TOUCH && SessionState.mode == SessionService.MODE_STEAM + val steam = if (wantsSteam) steamTouch() else null + steamTouchInUse = steam != null + if (wantsSteam && steam == null && !isFinishing && !isDestroyed) { + uiHandler.removeCallbacks(steamTouchRetry) + uiHandler.postDelayed(steamTouchRetry, 1000) + } + if (steam == null) { + steamTouchControls?.let { it.cancelEditing(); it.releaseAll(); it.visibility = View.GONE } + com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = false + applyTouchRouting() + } + controls.setButtonsOnly(buttonsOnly) + val show = when (forced) { + SessionPrefs.OSC_ALWAYS -> true + SessionPrefs.OSC_STEAM_QAM -> true + SessionPrefs.OSC_NEVER -> false + SessionPrefs.OSC_STEAM_TOUCH -> SessionState.mode == SessionService.MODE_STEAM || + (!PadBridge.anyControllerConnected() && SessionState.mode != SessionService.MODE_DESKTOP) + else -> !PadBridge.anyControllerConnected() && !SteamControllerBle.connected && + SessionState.mode != SessionService.MODE_DESKTOP + } + onScreenButtonsVisible = show + val drawn = show && !keyboardCoversPad() + if (steam != null) { + hideBottomControls() + showPinned() + if (!drawn) { steam.cancelEditing(); steam.releaseAll() } + steam.visibility = if (drawn) View.VISIBLE else View.GONE + com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = show + applyTouchRouting() + Log.i(TAG, "on-screen controls: Steam's touch controller " + if (drawn) "shown" else "hidden") + return + } + val bottomRoot = bottomGame?.surfaceView?.parent as? android.view.ViewGroup + if (bottomRoot != null && (drawn || controls.hasPinned)) { + controls.releaseAll(); controls.visibility = View.GONE + var bottom = bottomInputControls + if (bottom?.parent !== bottomRoot) { + (bottom?.parent as? android.view.ViewGroup)?.removeView(bottom) + bottom = OnScreenControls(bottomRoot.context, padBridge).also { view -> + view.onTouchMiss = { event -> onBottomGameTouch(event) } + bottomRoot.addView(view, android.view.ViewGroup.LayoutParams(-1, -1)) } - bottom.updateLayout(primaryInputLayout) - bottom.setHidden(plan.hidden) - bottom.visibility = View.VISIBLE - } - com.droiddeck.launcher.input.ControlsPresenter.Place.MAIN, - com.droiddeck.launcher.input.ControlsPresenter.Place.STEAM -> { - hideBottomControls() - controls.setHidden(plan.hidden) - controls.visibility = View.VISIBLE - } - else -> { - hideBottomControls() - controls.releaseAll() - controls.visibility = View.GONE + bottomInputControls = bottom } + bottom.updateLayout(primaryInputLayout) + bottom.setButtonsOnly(buttonsOnly) + bottom.setPinnedOnly(!drawn) + bottom.visibility = View.VISIBLE + return } - } - - private fun onControlsCornerTap(next: OnScreenControls.Hidden?) { - controlsHiddenByTap = next == OnScreenControls.Hidden.BY_TAP - if (next == null) controllerInUse = false - updateOnScreenControls() - } - - private fun openControllerMenu() { - drawerPage = SessionDrawerPage.CONTROLLER - drawerOpen = true - } - - private fun noteRemappedControllerUse(event: KeyEvent) { - if (PadBridge.isControllerKeyEvent(event) || - (event.isFromSource(InputDevice.SOURCE_GAMEPAD) && PadBridge.isFromController(event.device))) { - noteControllerUse() - } - } - - private fun noteSteamControllerUse() { - uiHandler.post { - if (!isDestroyed && SteamControllerBle.connected) noteControllerUse() - } - } - - private fun noteControllerUse() { - if (controllerInUse) return - controllerInUse = true - uiHandler.post { - val wasShown = onScreenButtonsVisible - updateOnScreenControls() - if (wasShown && controlsPlan().hidden == OnScreenControls.Hidden.BY_CONTROLLER) - Toast.makeText(this, R.string.osc_hidden_controller, Toast.LENGTH_SHORT).show() - } - } - - private fun noteScreenTouch(event: MotionEvent) { - if (!controllerInUse) return - val corner = onScreenControls?.takeIf { it.isShown }?.let { c -> - val at = IntArray(2).also(c::getLocationOnScreen) - c.cornerTakes(event.rawX - at[0], event.rawY - at[1]) - } == true - if (corner) return - controllerInUse = false - updateOnScreenControls() + hideBottomControls() + val wasDrawn = controls.visibility == View.VISIBLE && !controls.isPinnedOnly + if (!drawn) showPinned() else { controls.setPinnedOnly(false); controls.visibility = View.VISIBLE } + if (drawn == wasDrawn) return + Log.i(TAG, "on-screen controls " + when { + !drawn -> "hidden" + buttonsOnly -> "Steam + QAM" + else -> "full pad" + }) } private fun desktopTextInput() = @@ -5719,11 +5805,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde override fun onPictureInPictureModeChanged(inPip: Boolean, newConfig: android.content.res.Configuration) { super.onPictureInPictureModeChanged(inPip, newConfig) - if (inPip) { - uiHandler.removeCallbacks(guardWhenRunning) - uiHandler.removeCallbacks(rearmAfterYield) - com.droiddeck.launcher.session.KeepTopActivity.stepAside() - } if (::pip.isInitialized) pip.changed(inPip) if (!inPip && surfaceW > 0) resizeOutputForWindow(surfaceW, surfaceH) applyUnfoldedControls() @@ -5732,8 +5813,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) @@ -5765,10 +5845,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } override fun onStop() { - if (lightPause.stopped()) departureCleanup() - uiHandler.removeCallbacks(guardWhenRunning) - uiHandler.removeCallbacks(rearmAfterYield) - com.droiddeck.launcher.session.KeepTopActivity.stepAside() if (runtimeRemovalBlocked) { super.onStop(); return } started = false if (::hud.isInitialized) hud.setBackgrounded(true) @@ -5813,13 +5889,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde override fun onResume() { super.onResume() - com.droiddeck.launcher.session.KeepTopActivity.onYield = onGuardYield - 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) } @@ -5864,6 +5933,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) @@ -5885,73 +5955,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) - } - } - - // A touch that removed a guard while the session kept the top spot did not move focus to that - // display, so the guard comes back unless the user carries on there. - private val rearmAfterYield = Runnable { - if (topResumed && !isFinishing) { - com.droiddeck.launcher.session.KeepTopActivity.rearm() - guardOtherDisplays() - } - } - private val onGuardYield: () -> Unit = { - uiHandler.removeCallbacks(rearmAfterYield) - uiHandler.postDelayed(rearmAfterYield, com.droiddeck.launcher.session.KeepTopActivity.YIELD_GRACE_MS) - } - - // 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) - uiHandler.removeCallbacks(rearmAfterYield) - if (isTopResumedActivity) { - com.droiddeck.launcher.session.KeepTopActivity.rearm() - 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 || isInPictureInPictureMode) 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() } @@ -5976,7 +5981,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (!screenOff) { gestureSettingsOpen = false inputSettingsOpen = false - layoutEditor = null } releasePads() heldKeys.clear() @@ -6000,6 +6004,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() @@ -6153,6 +6158,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() @@ -6236,6 +6242,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() @@ -6285,6 +6292,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde bottomGame = screen surfaceW = 0 surfaceH = 0 + applyNotchInset() screen.setOnDismissListener { if (bottomGame === screen) { restoreTopOutput(screen) @@ -6326,6 +6334,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 @@ -6354,10 +6363,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (event.actionMasked == MotionEvent.ACTION_DOWN) { drawerControllerActive = false gestureTouchStreamGate.reset() - if (controllerInUse && event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) { controllerInUse = false; updateOnScreenControls() } } if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SURFACE, event)) return false - return onTouchEvent(event) + return handleTouch(event) } @androidx.compose.runtime.Composable @@ -6400,7 +6408,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } androidx.compose.runtime.key(profileLayout) { androidx.compose.ui.viewinterop.AndroidView( - factory = { context -> com.droiddeck.launcher.ui.InputSurfaceView(context, padBridge).also { it.showLayout(profileLayout); swappedInputSurface = it } }, + factory = { context -> com.droiddeck.launcher.ui.InputSurfaceView(context, padBridge, profileLayout?.elements.orEmpty(), + surfaceStyle = profileLayout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle()).also { swappedInputSurface = it } }, modifier = Modifier.fillMaxWidth().weight(1f), onRelease = { if (swappedInputSurface === it) swappedInputSurface = null }, ) @@ -6490,6 +6499,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 @@ -6614,10 +6624,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } override fun onDestroy() { - uiHandler.removeCallbacks(guardWhenRunning) - uiHandler.removeCallbacks(rearmAfterYield) - if (com.droiddeck.launcher.session.KeepTopActivity.onYield === onGuardYield) com.droiddeck.launcher.session.KeepTopActivity.onYield = null - com.droiddeck.launcher.session.KeepTopActivity.release() + uiHandler.removeCallbacks(panelHeldCheck) + uiHandler.removeCallbacks(panelHeldRetry) synchronized(frameGenGlobalLock) { frameGenActivityActive = false frameGenRequests.incrementAndGet() @@ -6625,7 +6633,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) @@ -6668,6 +6676,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() } @@ -6731,7 +6742,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode != REQUEST_BLUETOOTH || grantResults.firstOrNull() != android.content.pm.PackageManager.PERMISSION_GRANTED) return steamController?.stop() - steamController = SteamControllerBle(this, inputRouter, ::noteSteamControllerUse).also { it.start() } + steamController = SteamControllerBle(this, inputRouter).also { it.start() } } companion object { @@ -6742,6 +6753,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde const val EXTRA_STEAMVR = "steamVr" const val EXTRA_PLAYED_GAME = "com.droiddeck.launcher.PLAYED_GAME" const val EXTRA_REPAIR_RUNTIME = "repairRuntime" + private const val PANEL_HELD_CHECK_MS = 2_500L + private const val PANEL_HELD_RETRY_MS = 60_000L private const val LEAVE_TIMEOUT_MS = 1_500L private const val TEXT_FIELD_TAP_MS = 1_000L private const val PAUSED_FRAME_MAX_EDGE = 1920f diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentGuest.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentGuest.kt index e04dda2580..abe8abb3a3 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentGuest.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentGuest.kt @@ -230,6 +230,20 @@ object AgentGuest { call(context, JSONObject().put("kind", "cdp").put("expression", expression).put("timeout", timeoutMs / 1000.0), timeoutMs + 2_000, trusted = true) + fun setGamescopeConvar(context: Context, name: String, value: Int): Boolean { + val request = JSONObject() + .put("kind", "exec") + .put("argv", org.json.JSONArray(listOf("gamescopectl", name, value.toString()))) + .put("timeout", 5.0) + val result = runCatching { call(context, request, 8_000, trusted = true) } + val answer = result.getOrNull() + val applied = answer?.optBoolean("ok") == true + && answer.optInt("exitCode", -1) == 0 + && !answer.optBoolean("timedOut") + if (!applied) Log.w(TAG, "gamescope did not take $name $value: ${result.exceptionOrNull() ?: answer}") + return applied + } + fun call(context: Context, request: JSONObject, timeoutMs: Long, trusted: Boolean = false): JSONObject { if (!trusted && request.optString("kind") in setOf("exec", "cdp")) AgentAccess.requireCommands(context) if (!SessionState.running) throw AgentException("NO_ACTIVE_SESSION", "There is no running session") diff --git a/app/src/main/java/com/droiddeck/launcher/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/DeviceReport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt index fe835b10c8..dbc78c6a2d 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt @@ -289,6 +289,7 @@ object DeviceReport { k("Guest host name", SessionPrefs.guestHostname(context)) k("DirectAudio for games", SessionPrefs.directAudio(context)) k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context)) + k("Avoid notch", SessionPrefs.avoidNotch(context)) k("Return to launcher after a game", SessionPrefs.returnAfterGame(context)) k("Microphone", SessionPrefs.micEnabled(context)) k("On-screen controls", SessionPrefs.oscMode(context)) diff --git a/app/src/main/java/com/droiddeck/launcher/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..c5d33d9508 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/ControllerOverlayGeometry.kt @@ -0,0 +1,180 @@ +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 unit = minOf( + min(w / 1600f, h / 900f) * min(1f, 80f / max(h / dpi * 25.4f, 1f)) * scale, + (w - safe.left - safe.right).coerceAtLeast(1f) / 1200f, + (h - safe.top - safe.bottom).coerceAtLeast(1f) / 900f, + ) + + private fun anchor(value: Float, reference: Float, extent: Float, start: Int, end: Int): Float { + val low = start + value * unit + val high = extent - end - (reference - value) * unit + return when { + value < reference / 3f -> low + value > reference * 2f / 3f -> high + else -> (extent / 2f + (value - reference / 2f) * unit).coerceIn(low, max(low, high)) + } + } + + private fun x(ref: Float) = anchor(ref, 1600f, w, safe.left, safe.right) + + private fun y(ref: Float) = max(safe.top + ref * unit, h - safe.bottom - (900f - ref) * unit) + + fun place(elements: List, kit: PadKit, rearButtons: Boolean, trackpads: Boolean): List { + if (!kit.steam) return placeStandardPad(elements, kit) + val leftEdge = safe.left + 52f * density + val middle = (w + safe.left - safe.right) / 2f + val keyboard = Box(max(x(136f), leftEdge + 46f * unit), y(848f), 46f).takeIf { elements.any { it.id == KEYBOARD } } + val row = fitRow(listOfNotNull(keyboard, + Box(max(x(370f), leftEdge + 66f * unit), y(852f), 66f, 30f), + Box(middle - 140f * unit, y(850f), 46f, 26f), + Box(middle + 140f * unit, y(850f), 46f, 26f), + Box(x(1230f), y(852f), 66f, 30f)), leftEdge) + val (guide, select, start, qam) = row.takeLast(4) + val positions = shoulders() + face(1375f, 345f, 96f) + mapOf( + InputControl.UP to Box(x(220f), y(345f) - 102.5f * unit, 55.5f, 47.5f), + InputControl.RIGHT to Box(x(220f) + 102.5f * unit, y(345f), 47.5f, 55.5f), + InputControl.DOWN to Box(x(220f), y(345f) + 102.5f * unit, 55.5f, 47.5f), + InputControl.LEFT to Box(x(220f) - 102.5f * unit, y(345f), 47.5f, 55.5f), + InputControl.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 * unit), y(848f), 46f).takeIf { elements.any { it.id == KEYBOARD } } + val controls = if (kit.playStation) listOf( + InputControl.QAM to Box(x(220f), y(848f), 46f), + InputControl.SELECT to Box(middle - 160f * unit, y(850f), 50f, 30f), + InputControl.GUIDE to Box(middle, y(850f), 46f), + InputControl.START to Box(middle + 160f * unit, y(850f), 50f, 30f), + ) else listOf( + InputControl.QAM to Box(x(220f), y(848f), 46f), + InputControl.SELECT to Box(middle - 110f * unit, y(850f), 38f), + InputControl.GUIDE to Box(middle, y(850f), 46f), + InputControl.START to Box(middle + 110f * unit, y(850f), 38f), + ) + val row = fitRow(listOfNotNull(keyboard) + controls.map { it.second }, leftEdge) + val positions = controls.map { it.first }.zip(row.takeLast(controls.size)).toMap() + shoulders() + + if (kit.playStation) { + face(1350f, 395f, 96f) + dpad(250f, 395f, 125f, kit.dpad) + mapOf( + InputControl.LS to Box(x(565f), y(690f), 100f), + InputControl.RS to Box(x(1035f), y(690f), 100f), + InputControl.L3 to Box(x(565f) - 135f * unit, y(690f) - 100f * unit, 42f), + InputControl.R3 to Box(x(1035f) + 135f * unit, y(690f) - 100f * unit, 42f), + ) + } else { + face(1375f, 400f, 94f) + dpad(470f, 675f, 118f, kit.dpad) + mapOf( + InputControl.LS to Box(x(235f), y(400f), 104f), + InputControl.RS to Box(x(1130f), y(690f), 104f), + InputControl.L3 to Box(x(235f) + 150f * unit, y(400f) - 110f * unit, 42f), + InputControl.R3 to Box(x(1130f) + 160f * unit, y(690f) + 100f * unit, 42f), + ) + } + return elements.map { element -> + when (element.id) { + KEYBOARD -> row.first().place(element) + "legacy:${element.control.id}" -> positions[element.control]?.place(element) ?: element + else -> element + } + } + } + + private fun shoulders() = mapOf( + InputControl.LT to Box(x(120f), y(96f), 80f, 34f), + InputControl.LB to Box(x(310f), y(96f), 80f, 34f), + InputControl.RB to Box(x(1290f), y(96f), 80f, 34f), + InputControl.RT to Box(x(1480f), y(96f), 80f, 34f), + ) + + private fun face(cx: Float, cy: Float, offset: Float) = mapOf( + InputControl.Y to Box(x(cx), y(cy) - offset * unit, 58f), + InputControl.X to Box(x(cx) - offset * unit, y(cy), 58f), + InputControl.B to Box(x(cx) + offset * unit, y(cy), 58f), + InputControl.A to Box(x(cx), y(cy) + offset * unit, 58f), + ) + + private fun dpad(cx: Float, cy: Float, radius: Float, style: DpadStyle): Map { + val inner = radius * if (style == DpadStyle.DISC) .25f else .14f + val depth = (radius - inner) / 2f + val offset = (radius - depth) * unit + val side = radius * .25f + return mapOf( + InputControl.UP to Box(x(cx), y(cy) - offset, side, depth), + InputControl.RIGHT to Box(x(cx) + offset, y(cy), depth, side), + InputControl.DOWN to Box(x(cx), y(cy) + offset, side, depth), + InputControl.LEFT to Box(x(cx) - offset, y(cy), depth, side), + ) + } + + private fun fitRow(row: List, start: Float): List { + val end = w - safe.right + val gap = ((end - start - row.fold(0f) { sum, box -> sum + box.width }) / (row.size - 1)).coerceIn(0f, 8f * density) + var edge = start - gap + val pushed = row.map { box -> box.at(max(box.cx, edge + gap + box.width / 2f)).also { edge = it.cx + it.width / 2f } } + edge = end + gap + return pushed.asReversed().map { box -> box.at(min(box.cx, edge - gap - box.width / 2f)).also { edge = it.cx - it.width / 2f } }.asReversed() + } + + private inner class Box(val cx: Float, val cy: Float, val hw: Float, val hh: Float = hw) { + val width get() = max(hw * 2f * unit, w * .03f) + + fun at(cx: Float) = Box(cx, cy, hw, hh) + + fun place(element: InputSurfaceElement): InputSurfaceElement { + val height = max(hh * 2f * unit, h * .03f) + return element.copy( + x = (cx - width / 2f).coerceIn(safe.left.toFloat(), max(safe.left.toFloat(), w - safe.right - width)) / w, + y = (cy - height / 2f).coerceIn(safe.top.toFloat(), max(safe.top.toFloat(), h - safe.bottom - height)) / h, + width = width / w, height = height / h, + ).bounded() + } + } + + private companion object { + const val KEYBOARD = "builtin:keyboard" + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/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/ControllerPrefs.kt b/app/src/main/java/com/droiddeck/launcher/input/ControllerPrefs.kt index a94147e714..5231a753ac 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/ControllerPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/ControllerPrefs.kt @@ -7,6 +7,21 @@ object ControllerPrefs { const val STEAM_BLUE = 0xFF1A9FFF.toInt() const val OFF = "off" + val tints = listOf( + STEAM_BLUE to R.string.ctrl_tint_steam_blue, + 0xFF66C0F4.toInt() to R.string.ctrl_tint_sky, + 0xFFE8EEF4.toInt() to R.string.ctrl_tint_white, + 0xFFC77DFF.toInt() to R.string.ctrl_tint_violet, + 0xFF3DDC84.toInt() to R.string.ctrl_tint_green, + 0xFFFFA726.toInt() to R.string.ctrl_tint_amber, + 0xFFFF5252.toInt() to R.string.ctrl_tint_red, + 0xFFFF6FB5.toInt() to R.string.ctrl_tint_pink, + ) + + val opacities = listOf(40, 60, 80, 100) + + val sizes = listOf(80, 90, 100, 110, 125) + val deadZones = listOf(0, 5, 8, 12, 15, 20, 25) const val DEFAULT_DEAD_ZONE_PERCENT = 12 @@ -24,15 +39,20 @@ object ControllerPrefs { OFF to R.string.ctrl_target_hidden, ) - /** Settings still read: the rest only seed the one-time library and layout migrations. */ class Settings( val tint: Int, val opacity: Int, + val size: Int, val stickClick: Boolean, + val adaptiveSticks: Boolean, val rumble: Boolean, + val steamButton: Boolean, + val qamButton: Boolean, + val keyboardButton: Boolean, val selectSteam: Boolean, val joyConVr: Boolean, val snap: Boolean, + val customLayout: Boolean, val mapping: Map, val deadZone: Int, ) @@ -43,17 +63,50 @@ object ControllerPrefs { val p = prefs(context) return Settings( tint = p.getInt("tint", STEAM_BLUE), - opacity = p.getInt("opacity", 100).coerceIn(1, 100), + opacity = p.getInt("opacity", 100).takeIf { it in opacities } ?: 100, + size = p.getInt("size", 100).takeIf { it in sizes } ?: 100, stickClick = p.getBoolean("stickClick", true), + adaptiveSticks = p.getBoolean("adaptiveSticks", true), rumble = rumbleEnabled(context), + steamButton = p.getBoolean("steamButton", true), + qamButton = p.getBoolean("qamButton", true), + keyboardButton = p.getBoolean("keyboardButton", true), selectSteam = p.getBoolean("selectSteam", false), joyConVr = joyConVr(context), snap = snap(context), - mapping = mappable.associate { (id, _) -> id to (p.getString("map.$id", id)?.takeIf { t -> targets.any { it.first == t } } ?: id) }, + customLayout = p.all.keys.any { it.startsWith("layout.") }, + mapping = mappable.associate { (id, _) -> id to target(context, id) }, deadZone = deadZone(context), ) } + fun target(context: Context, id: String): String = + prefs(context).getString("map.$id", id)?.takeIf { t -> targets.any { it.first == t } } ?: id + + fun setTarget(context: Context, id: String, target: String) { + prefs(context).edit().putString("map.$id", target).apply() + } + + fun setTint(context: Context, tint: Int) { + prefs(context).edit().putInt("tint", tint).apply() + } + + fun setOpacity(context: Context, percent: Int) { + prefs(context).edit().putInt("opacity", percent).apply() + } + + fun setSize(context: Context, percent: Int) { + prefs(context).edit().putInt("size", percent).apply() + } + + fun setStickClick(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("stickClick", on).apply() + } + + fun setAdaptiveSticks(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("adaptiveSticks", on).apply() + } + fun rumbleEnabled(context: Context): Boolean = prefs(context).getBoolean("rumble", true) fun deadZone(context: Context): Int = @@ -67,6 +120,18 @@ object ControllerPrefs { prefs(context).edit().putBoolean("rumble", on).apply() } + fun setSteamButton(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("steamButton", on).apply() + } + + fun setKeyboardButton(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("keyboardButton", on).apply() + } + + fun setSelectSteam(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("selectSteam", on).apply() + } + fun joyConVr(context: Context): Boolean = prefs(context).getBoolean("joyConVr", true) fun setJoyConVr(context: Context, on: Boolean) { @@ -79,6 +144,24 @@ object ControllerPrefs { prefs(context).edit().putBoolean("snap", on).apply() } + fun layout(context: Context, width: Int, height: Int): Map> { + val raw = prefs(context).getString("layout.${width}x$height", null) ?: return emptyMap() + return raw.split(';').mapNotNull { entry -> + val (group, pos) = entry.split(':').takeIf { it.size == 2 } ?: return@mapNotNull null + val (x, y) = pos.split(',').mapNotNull { it.toFloatOrNull() }.takeIf { it.size == 2 } ?: return@mapNotNull null + group to (x to y) + }.toMap() + } + + fun setLayout(context: Context, width: Int, height: Int, positions: Map>) { + val raw = positions.entries.joinToString(";") { (group, pos) -> "$group:${pos.first},${pos.second}" } + prefs(context).edit().putString("layout.${width}x$height", raw).apply() + } + + fun resetLayout(context: Context, width: Int, height: Int) { + prefs(context).edit().remove("layout.${width}x$height").apply() + } + fun resetAll(context: Context) { prefs(context).edit().clear().putBoolean("rumble", true).apply() } diff --git a/app/src/main/java/com/droiddeck/launcher/input/ControlsChoice.kt b/app/src/main/java/com/droiddeck/launcher/input/ControlsChoice.kt deleted file mode 100644 index 2e4952b971..0000000000 --- a/app/src/main/java/com/droiddeck/launcher/input/ControlsChoice.kt +++ /dev/null @@ -1,123 +0,0 @@ -package com.droiddeck.launcher.input - -import android.content.Context -import com.droiddeck.launcher.R -import com.droiddeck.launcher.session.SessionPrefs - -/** The on-screen layout each game draws, shared by the in-game Controller page and Settings › Controller. A null game is the default. */ -object ControlsChoice { - const val NEW = "new" - const val DEFAULT = "default" - - data class Game(val id: Long, val name: String, val layout: String) - - private fun own(library: InputLibrary, id: String?): String? = id?.takeIf { bindings -> - library.bindings.any { it.id == bindings && !it.physical && it.layoutId?.let { l -> library.layouts.any { x -> x.id == l && x.supports(InputRole.PRIMARY) } } == true } - } - - private fun own(context: Context, library: InputLibrary, game: Long?) = own(library, GameControls.bindings(context, game)) - - /** The input library with [game]'s main-screen layout selected, without saving it. */ - fun library(context: Context, game: Long?, desktop: Boolean): InputLibrary { - val library = InputLibraries.read(context) - val chosen = own(context, library, game) - return if (chosen == null) library else library.selectPart(desktop, InputRole.PRIMARY, chosen) - } - - fun options(context: Context, game: Long?, steamMode: Boolean, gameName: String? = null): List> { - val library = InputLibraries.read(context) - val own = game != null && game in GameControls.games(context) - return (if (own) listOf(DEFAULT to context.getString(R.string.osc_default)) else emptyList()) + - listOf(InputLibraries.OVERLAY to context.getString(R.string.osc_layout_gamepad)) + - (if (steamMode) listOf(GameControls.STEAM to context.getString(R.string.osc_layout_steam)) else emptyList()) + - library.layouts.filter { it.editable && it.supports(InputRole.PRIMARY) && it.id != InputLibraries.OVERLAY }.map { it.id to it.name } + - (if (game != null && !gameName.isNullOrBlank()) listOf(NEW to context.getString(R.string.osc_layout_new_for, gameName)) else emptyList()) - } - - fun current(context: Context, game: Long?, steamMode: Boolean, desktop: Boolean = false): String = - if (steamMode && GameControls.steamLayout(context, game)) GameControls.STEAM - else library(context, game, desktop).activeLayout(desktop, InputRole.PRIMARY)?.id ?: InputLibraries.OVERLAY - - fun choose(context: Context, game: Long?, id: String, desktop: Boolean, gameName: String? = null) { - require(id != NEW) - if (id == DEFAULT) { if (game != null) useDefault(context, game); return } - val steam = id == GameControls.STEAM - val bindings = if (steam) null else { - val library = InputLibraries.read(context) - val layout = library.layouts.first { it.id == id } - library.bindings.firstOrNull { !it.physical && it.layoutId == layout.id && it.compatible(layout) }?.id ?: newInputId().also { newId -> - InputLibraries.update(context) { it.withPreset(SavedInputBindings(newId, layout.name, false, layout.id)) } - } - } - if (game != null) GameControls.choose(context, game, bindings, steam, gameName) - else { - if (bindings != null) InputLibraries.update(context) { it.selectPart(desktop, InputRole.PRIMARY, bindings) } - SessionPrefs.setSteamTouchLayout(context, steam) - } - } - - /** Copies the layout [game] draws now, actions included, into a layout of its own and chooses it for that game only. */ - fun newForGame(context: Context, game: Long, name: String, desktop: Boolean): Pair { - val layoutId = newInputId() - val bindingsId = newInputId() - InputLibraries.update(context) { latest -> copyForGame(context, latest, game, name, desktop, layoutId, bindingsId) } - GameControls.choose(context, game, bindingsId, steam = false, name = name) - return layoutId to bindingsId - } - - /** [latest] with a copy of the layout [game] draws now, actions included, under the given ids. Nothing is chosen for the game. */ - fun copyForGame(context: Context, latest: InputLibrary, game: Long, name: String, desktop: Boolean, layoutId: String, bindingsId: String): InputLibrary { - run { - val chosen = own(context, latest, game) - val part = (if (chosen == null) latest else latest.selectPart(desktop, InputRole.PRIMARY, chosen)).activePart(desktop, InputRole.PRIMARY) - val source = latest.layouts.firstOrNull { it.id == part.layout && it.editable } ?: latest.layouts.first { it.id == InputLibraries.OVERLAY } - val actions = latest.bindings.firstOrNull { it.id == part.bindings && it.compatible(source) } - ?: latest.bindings.firstOrNull { !it.physical && it.compatible(source) } - ?: SavedInputBindings(bindingsId, source.name, false, source.id) - val title = name.trim().take(80).ifEmpty { source.name } - return latest.withLayout(source.derived(layoutId, title)).withPreset(actions.copy(id = bindingsId, name = title, layoutId = layoutId)) - } - } - - /** Uses [bindingsId], made by [copyForGame], for [game] only. */ - fun useForGame(context: Context, game: Long, name: String, bindingsId: String) = GameControls.choose(context, game, bindingsId, steam = false, name = name) - - /** The profile, layout and actions the editor opens for [game], or null when its layout can't be edited here. */ - fun editTarget(context: Context, game: Long?, desktop: Boolean): Triple? { - val library = library(context, game, desktop) - val layout = library.activeLayout(desktop, InputRole.PRIMARY)?.takeIf { it.editable } ?: return null - return Triple(library.activeId(desktop), layout.id, library.activePart(desktop, InputRole.PRIMARY).bindings) - } - - /** Whether [game] has a layout of its own, rather than the default. */ - fun hasOwn(context: Context, game: Long?): Boolean = own(context, InputLibraries.read(context), game) != null - - /** Whether saving an edit of [game]'s layout would also change the default or another game. */ - fun shared(context: Context, game: Long?): Boolean { - game ?: return false - val library = InputLibraries.read(context) - val bindings = own(context, library, game) ?: return true - val layout = library.preset(bindings).layoutId - fun drawsLayout(id: String) = library.bindings.firstOrNull { it.id == id }?.layoutId == layout - return library.usersOfLayout(layout ?: return true).isNotEmpty() || - library.selections.values.any { s -> s.parts[InputRole.PRIMARY]?.let(::drawsLayout) == true } || - GameControls.games(context).any { it != game && own(context, library, it)?.let(::drawsLayout) == true } - } - - fun useDefault(context: Context, game: Long) = GameControls.clear(context, game) - - /** Games with a layout of their own, by name. */ - fun games(context: Context): List { - val library = InputLibraries.read(context) - return GameControls.games(context).mapNotNull { id -> - val layout = when { - GameControls.steamLayout(context, id) -> context.getString(R.string.osc_layout_steam) - else -> own(context, library, id)?.let { b -> library.layouts.firstOrNull { it.id == library.preset(b).layoutId }?.name } ?: return@mapNotNull null - } - val name = GameControls.name(context, id) - ?: id.takeIf { it in Int.MIN_VALUE..Int.MAX_VALUE }?.let { runCatching { SteamTouchConfig.gameName(context, it.toInt()) }.getOrNull() } - ?: id.toString() - Game(id, name, layout) - }.sortedBy { it.name.lowercase() } - } -} diff --git a/app/src/main/java/com/droiddeck/launcher/input/ControlsPresenter.kt b/app/src/main/java/com/droiddeck/launcher/input/ControlsPresenter.kt deleted file mode 100644 index 0ab1d33719..0000000000 --- a/app/src/main/java/com/droiddeck/launcher/input/ControlsPresenter.kt +++ /dev/null @@ -1,40 +0,0 @@ -package com.droiddeck.launcher.input - -import com.droiddeck.launcher.session.SessionPrefs - -/** Decides where the on-screen controls go and why they're hidden, from the session's state alone. */ -object ControlsPresenter { - enum class Place { NONE, MAIN, BOTTOM, STEAM } - - data class State( - val mode: String, - val desktop: Boolean, - val virtualPad: Boolean, - val covered: Boolean, - val controllerInUse: Boolean, - val hiddenByTap: Boolean, - val steamLayout: Boolean, - val bottomScreen: Boolean, - ) - - data class Plan(val place: Place, val hidden: OnScreenControls.Hidden? = null) { - val shown get() = place != Place.NONE && hidden == null - } - - fun plan(state: State): Plan = when { - state.covered || !state.virtualPad || state.mode == SessionPrefs.OSC_NEVER -> Plan(Place.NONE) - state.mode == SessionPrefs.OSC_AUTO && state.desktop -> Plan(Place.NONE) - else -> Plan( - when { - state.bottomScreen -> Place.BOTTOM - state.steamLayout -> Place.STEAM - else -> Place.MAIN - }, - when { - state.hiddenByTap -> OnScreenControls.Hidden.BY_TAP - state.mode == SessionPrefs.OSC_AUTO && state.controllerInUse -> OnScreenControls.Hidden.BY_CONTROLLER - else -> null - }, - ) - } -} 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/GameControls.kt b/app/src/main/java/com/droiddeck/launcher/input/GameControls.kt deleted file mode 100644 index 8faead1599..0000000000 --- a/app/src/main/java/com/droiddeck/launcher/input/GameControls.kt +++ /dev/null @@ -1,36 +0,0 @@ -package com.droiddeck.launcher.input - -import android.content.Context -import com.droiddeck.launcher.session.SessionPrefs - -/** Which on-screen layout each game uses. Games without a choice use the default profile's main-screen layout. */ -object GameControls { - const val STEAM = "steam" - - private fun prefs(context: Context) = context.getSharedPreferences("game-controls", Context.MODE_PRIVATE) - - /** The main-screen bindings preset saved for [game], whose layout is the one drawn. */ - fun bindings(context: Context, game: Long?): String? = game?.let { prefs(context).getString("$it.bindings", null) } - - fun steamLayout(context: Context, game: Long?): Boolean { - val p = prefs(context) - return if (game != null && p.contains("$game.steam")) p.getBoolean("$game.steam", false) else SessionPrefs.steamTouchLayout(context) - } - - fun choose(context: Context, game: Long, bindings: String?, steam: Boolean, name: String? = null) { - prefs(context).edit().apply { if (bindings == null) remove("$game.bindings") else putString("$game.bindings", bindings) } - .apply { if (!name.isNullOrBlank()) putString("$game.name", name) } - .putBoolean("$game.steam", steam).apply() - } - - /** Games with their own choice, in the order of their ids. */ - fun games(context: Context): List = prefs(context).all.keys - .filter { it.endsWith(".steam") || it.endsWith(".bindings") } - .mapNotNull { it.substringBeforeLast('.').toLongOrNull() }.distinct().sorted() - - fun name(context: Context, game: Long): String? = prefs(context).getString("$game.name", null) - - fun clear(context: Context, game: Long) { - prefs(context).edit().remove("$game.bindings").remove("$game.steam").apply() - } -} diff --git a/app/src/main/java/com/droiddeck/launcher/input/GamepadGeometry.kt b/app/src/main/java/com/droiddeck/launcher/input/GamepadGeometry.kt index c448fb3573..988ab5f764 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/GamepadGeometry.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/GamepadGeometry.kt @@ -9,7 +9,6 @@ object GamepadGeometry { VIEW, STEAM, QAM, MENU, PANELS, L4, L5, R5, R4, - LEFT_TOUCH, RIGHT_TOUCH, } data class Box(val cx: Float, val cy: Float, val width: Float, val height: Float) { @@ -27,11 +26,10 @@ object GamepadGeometry { fun tall(w: Float, h: Float): Boolean = h >= w * 0.45f - fun layout(w: Float, h: Float, density: Float, portraitDock: Boolean = false, grips: Boolean = false, upright: Boolean = false, - trackpads: Boolean = false): Map { + fun layout(w: Float, h: Float, density: Float, portraitDock: Boolean = false): Map { if (w <= 0f || h <= 0f) return emptyMap() - if (upright || portraitDock && h >= w * 0.6f && w >= 300 * density && h >= 300 * density) { - return portraitLayout(w, h, density, grips, trackpads) + if (portraitDock && h >= w * 0.9f && w >= 300 * density && h >= 360 * density) { + return portraitLayout(w, h, density) } val pad = 8 * density val buttonH = 40 * density @@ -72,7 +70,6 @@ object GamepadGeometry { else -> 1 } middleGrid(columns, gap - 2 * gutter, shoulderY - buttonH / 2f) - if (grips) gripsBetween(boxes, w, gap - 2 * gutter, boxes.values.maxOf { if (it.cx in (w - gap) / 2f..(w + gap) / 2f) it.bottom else 0f } + gutter, h - pad, density) } else { val side = min(min(w * 0.5f, h * 0.70f), (w - 2 * gridButton - 2 * gutter) / 1.42f) val main = side * 0.62f @@ -88,75 +85,45 @@ object GamepadGeometry { val gap = w - 2 * (side * 0.40f + main / 2f) val columns = if (gap >= 2 * gridButton) 2 else 1 val rows = (middle.size + columns - 1) / columns - val gridTop = h - pad - rows * buttonH - (rows - 1) * 10 * density - middleGrid(columns, gap - 2 * gutter, gridTop) - if (grips) gripsBetween(boxes, w, w - 2 * (side * 0.74f + second / 2f) - 2 * gutter, shoulderY + buttonH / 2f + gutter, gridTop - gutter, density) + middleGrid(columns, gap - 2 * gutter, h - pad - rows * buttonH - (rows - 1) * 10 * density) val panelsW = min(112 * density, w - 2 * (side * 0.57f + shoulderW / 2f) - 2 * gutter) if (panelsW >= buttonH) boxes[Slot.PANELS] = Box(w / 2f, shoulderY, panelsW, buttonH) } return boxes } - /** The back grips in the gap between a landscape panel's two clusters: one row of four, or two rows of two. */ - private fun gripsBetween(boxes: MutableMap, w: Float, span: Float, top: Float, bottom: Float, density: Float) { - val gap = 8 * density - val minimum = 44 * density - val rows = if ((span - 3 * gap) / 4f >= minimum) 1 else if ((span - gap) / 2f >= minimum) 2 else return - val perRow = 4 / rows - val cellW = ((span - (perRow - 1) * gap) / perRow).coerceAtMost(96 * density) - val cellH = ((bottom - top - (rows - 1) * gap) / rows).coerceAtMost(64 * density) - if (cellH < minimum) return - for ((i, slot) in listOf(Slot.L4, Slot.L5, Slot.R5, Slot.R4).withIndex()) { - val col = i % perRow; val row = i / perRow - boxes[slot] = Box(w / 2f + (col - (perRow - 1) / 2f) * (cellW + gap), bottom - (rows - 1 - row) * (cellH + gap) - cellH / 2f, cellW, cellH) - } - } - - /** - * The panel under a portrait game: shoulders with View and Menu across the top, the back grips under them when the kit has - * them, then the d-pad and face buttons and, along the bottom edge, the sticks or trackpads, each as large as the panel allows. - */ - private fun portraitLayout(w: Float, h: Float, density: Float, grips: Boolean, trackpads: Boolean): Map { + private fun portraitLayout(w: Float, h: Float, density: Float): Map { val pad = 8 * density val gap = 8 * density val buttonH = 44 * density - val boxes = LinkedHashMap() - val topGap = 4 * density - val topW = (w - 2 * pad - 5 * topGap) / 6f - val top = listOf(Slot.LEFT_OUTER_SHOULDER, Slot.LEFT_INNER_SHOULDER, Slot.VIEW, Slot.MENU, Slot.RIGHT_INNER_SHOULDER, Slot.RIGHT_OUTER_SHOULDER) - for ((i, slot) in top.withIndex()) boxes[slot] = Box(pad + topW / 2f + i * (topW + topGap), pad + buttonH / 2f, topW, buttonH) - var areaTop = pad + buttonH + gap - if (grips) { - val gripW = (w - 2 * pad - 3 * gap) / 4f - val gripH = min(56 * density, (h - areaTop) * 0.12f).coerceAtLeast(buttonH) - for ((i, slot) in listOf(Slot.L4, Slot.L5, Slot.R5, Slot.R4).withIndex()) - boxes[slot] = Box(pad + gripW / 2f + i * (gripW + gap), areaTop + gripH / 2f, gripW, gripH) - areaTop += gripH + gap - } - val area = h - pad - areaTop - gap - if (trackpads) { - val second = min(w * 0.42f, area * 0.5f) - val rowH = area - second - val col = (w - 2 * pad - 3 * gap) / 4f - val stick = min(col, rowH) - val rowY = h - pad - rowH / 2f - val secondY = areaTop + second / 2f - boxes[Slot.LEFT_SECOND] = Box(w * 0.25f, secondY, second, second) - boxes[Slot.RIGHT_SECOND] = Box(w * 0.75f, secondY, second, second) - boxes[Slot.LEFT_TOUCH] = Box(pad + col / 2f, rowY, col, rowH) - boxes[Slot.LEFT_MAIN] = Box(pad + col * 1.5f + gap, rowY, stick, stick) - boxes[Slot.RIGHT_MAIN] = Box(w - pad - col * 1.5f - gap, rowY, stick, stick) - boxes[Slot.RIGHT_TOUCH] = Box(w - pad - col / 2f, rowY, col, rowH) - return boxes - } - val main = min(w * 0.46f, area * 0.53f) - val second = min(w * 0.42f, area - main) - val secondY = areaTop + second / 2f + val scale = min(1f, (h - 2 * pad - 4 * gap - 3 * buttonH) / (w * 0.7f)) + val main = w * 0.4f * scale + val second = w * 0.3f * scale val mainY = h - pad - main / 2f - boxes[Slot.LEFT_SECOND] = Box(w * 0.25f, secondY, second, second) - boxes[Slot.RIGHT_SECOND] = Box(w * 0.75f, secondY, second, second) - boxes[Slot.LEFT_MAIN] = Box(w * 0.25f, mainY, main, main) - boxes[Slot.RIGHT_MAIN] = Box(w * 0.75f, mainY, main, main) + val secondY = mainY - main / 2f - gap - second / 2f + val shoulderY = secondY - second / 2f - gap - buttonH / 2f + val boxes = linkedMapOf( + Slot.LEFT_MAIN to Box(w * 0.25f, mainY, main, main), + Slot.RIGHT_MAIN to Box(w * 0.75f, mainY, main, main), + Slot.LEFT_SECOND to Box(w * 0.25f, secondY, second, second), + Slot.RIGHT_SECOND to Box(w * 0.75f, secondY, second, second), + ) + val utilityW = (w - 2 * pad - 3 * gap) / 4f + for ((i, slot) in middle.withIndex()) { + boxes[slot] = Box(pad + utilityW / 2f + i * (utilityW + gap), pad + buttonH / 2f, utilityW, buttonH) + } + val gripTop = pad + buttonH + gap + val gripH = min(64 * density, shoulderY - buttonH / 2f - gap - gripTop) + for ((i, slot) in listOf(Slot.L4, Slot.L5, Slot.R5, Slot.R4).withIndex()) { + boxes[slot] = Box(pad + utilityW / 2f + i * (utilityW + gap), gripTop + gripH / 2f, utilityW, gripH) + } + val panelsW = min(112 * density, w * 0.22f) + val shoulderW = (w - 2 * pad - 4 * gap - panelsW) / 4f + boxes[Slot.PANELS] = Box(w / 2f, shoulderY, panelsW, buttonH) + boxes[Slot.LEFT_OUTER_SHOULDER] = Box(pad + shoulderW / 2f, shoulderY, shoulderW, buttonH) + boxes[Slot.LEFT_INNER_SHOULDER] = Box(pad + shoulderW * 1.5f + gap, shoulderY, shoulderW, buttonH) + boxes[Slot.RIGHT_INNER_SHOULDER] = Box(w - pad - shoulderW * 1.5f - gap, shoulderY, shoulderW, buttonH) + boxes[Slot.RIGHT_OUTER_SHOULDER] = Box(w - pad - shoulderW / 2f, shoulderY, shoulderW, buttonH) return boxes } } 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 127c525d15..4683aece97 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt @@ -10,7 +10,11 @@ import org.json.JSONObject import java.util.UUID object InputLibraries { - private const val VERSION = 15 + 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,16 +27,24 @@ 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) if (version < 12) library = barStockLayouts(library) if (version < 13) library = LegacyScreenKeyMigration.pin(library) if (version < 14) library = deckGamepadSurfaces(context, library) - if (version < 15) library = kitGamepads(library) if (version < 6 || !p.contains(LegacyScreenKeyMigration.BACKUP)) { val legacy = LegacyScreenKeyMigration.snapshot(context) if (legacy != null) { @@ -75,24 +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." } - val recovery = RECOVERY + UUID.nameUUIDFromBytes(stored!!.toByteArray(Charsets.UTF_8)) - if (!p.edit().putString(recovery, stored).putString(KEY, encoded).commit()) { - // A failed commit has already changed the in-memory preferences; put the previous library back. - p.edit().putString(KEY, stored).remove(recovery).apply() - error("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." } @@ -129,14 +152,27 @@ object InputLibraries { return InputLibrary(profiles, layouts, bindings, selected).validate() } + fun setAdaptiveSticks(context: Context, layoutId: String, on: Boolean): Boolean = runCatching { + update(context) { library -> + library.copy(layouts = library.layouts.map { layout -> + if (layout.id != layoutId || !layout.editable) layout + else layout.copy(elements = layout.elements.map { if (it.kind == InputElementKind.STICK) it.copy(floating = on, hideWhenIdle = on) else it }) + }) + } + }.onSuccess { ControllerPrefs.setAdaptiveSticks(context, on) }.isSuccess + + fun setQuickButton(context: Context, layoutId: String, button: InputCommand, shown: Boolean): Boolean = runCatching { + update(context) { library -> library.layouts.firstOrNull { it.id == layoutId && it.editable }?.let { library.withLayout(it.withQuickButton(button, shown)) } ?: library } + }.isSuccess + fun defaultPositions(context: Context, library: InputLibrary, layout: SavedInputLayout): Pair, Float>? { val origin = layout.origin ?: layout.id InputStockLayouts.layouts().firstOrNull { it.id == origin }?.let { return it.elements to it.aspect } - if (origin == OVERLAY) { + if (origin == OVERLAY || origin.startsWith("migrated.layout.")) { val (surfaceContext, metrics) = primaryDisplay(context) - val w = metrics.widthPixels.coerceAtLeast(1) - val h = metrics.heightPixels.coerceAtLeast(1) - return KitLayout.elements(surfaceContext, PadKit.current(context), w, h, scale = layout.scale) to w.toFloat() / h + val size = if (origin == OVERLAY) listOf(metrics.widthPixels, metrics.heightPixels) + else origin.removePrefix("migrated.layout.").split('x').mapNotNull { it.toIntOrNull() } + return size.takeIf { it.size == 2 && it.all { side -> side > 0 } }?.let { LegacyGamepadLayout(surfaceContext, it[0], it[1]).elements() to it[0].toFloat() / it[1] } } return library.layouts.firstOrNull { it.id == origin && it.id != layout.id }?.let { it.elements to it.aspect } } @@ -148,12 +184,29 @@ object InputLibraries { return surfaceContext to DisplayMetrics().also { if (display != null) display.getRealMetrics(it) else it.setTo(context.resources.displayMetrics) } } + private fun restyleGamepads(context: Context, library: InputLibrary): InputLibrary { + if (library.layouts.none { it.id == OVERLAY || it.id.startsWith("migrated.layout.") }) return library + val (surfaceContext, metrics) = primaryDisplay(context) + return library.copy(layouts = library.layouts.map { layout -> + val size = when { + layout.id == OVERLAY -> listOf(metrics.widthPixels, metrics.heightPixels) + layout.id.startsWith("migrated.layout.") -> layout.id.removePrefix("migrated.layout.").split('x').mapNotNull { it.toIntOrNull() } + else -> emptyList() + } + if (size.size != 2 || size.any { it <= 0 }) layout + else layout.copy(elements = LegacyGamepadLayout(surfaceContext, size[0], size[1]).restyle(layout.elements)) + }) + } + private fun upgradeOverlay(context: Context, library: InputLibrary): InputLibrary { if (library.layouts.none { it.template == InputLayoutTemplate.OVERLAY }) return library + val (surfaceContext, metrics) = primaryDisplay(context) val settings = ControllerPrefs.read(context) - val style = InputSurfaceStyle(opacity = settings.opacity) + val elements = LegacyGamepadLayout(surfaceContext, metrics.widthPixels.coerceAtLeast(1), metrics.heightPixels.coerceAtLeast(1)).elements() + val style = InputSurfaceStyle(settings.tint, settings.opacity) val replacements = library.layouts.filter { it.template == InputLayoutTemplate.OVERLAY }.associate { old -> - old.id to old.copy(name = "Gamepad", elements = emptyList(), template = InputLayoutTemplate.CUSTOM, style = style) + old.id to old.copy(name = "Gamepad", elements = elements, template = InputLayoutTemplate.CUSTOM, style = style, + aspect = (metrics.widthPixels.coerceAtLeast(1).toFloat() / metrics.heightPixels.coerceAtLeast(1)).coerceIn(.05f, 20f)) } var result = library.copy(layouts = library.layouts.map { replacements[it.id] ?: it }) val migrated = mutableMapOf, String>() @@ -164,8 +217,9 @@ object InputLibraries { val id = migrated.getOrPut(key) { val old = library.preset(part.bindings) val newId = migrationBindingId(result, old.id, layout.id) - val clicks = if (settings.stickClick) old.clicks else old.clicks + KitLayout.clickIds.associateWith { InputAction.Disabled } - result = result.withPreset(old.copy(id = newId, layoutId = layout.id, clicks = clicks)) + val keyboard = elements.filter { it.id == "builtin:keyboard" }.associate { it.id to InputAction.Command(InputCommand.KEYBOARD) } + val clicks = if (settings.stickClick) old.clicks else old.clicks + elements.filter { it.hasClick }.associate { it.id to InputAction.Disabled } + result = result.withPreset(old.copy(id = newId, layoutId = layout.id, elements = old.elements + keyboard, clicks = clicks)) newId } part.copy(bindings = id) @@ -174,6 +228,15 @@ object InputLibraries { } val oldBindings = migrated.keys.map { it.first }.toSet() result = result.copy(bindings = result.bindings.filter { it.id !in oldBindings || result.usersOfBindings(it.id).isNotEmpty() }) + // Older editor layouts were resolution-specific. Keep each as a selectable saved layout. + for (key in ControllerPrefs.prefs(context).all.keys.filter { it.startsWith("layout.") }.sorted()) { + val size = key.removePrefix("layout.").split('x').mapNotNull { it.toIntOrNull() } + if (size.size != 2 || size.any { it <= 0 } || result.layouts.size >= 128) continue + if (size[0] == metrics.widthPixels && size[1] == metrics.heightPixels) continue + val id = "migrated.$key" + if (result.layouts.none { it.id == id }) result = result.withLayout(SavedInputLayout(id, "Gamepad ${size[0]} × ${size[1]}", + LegacyGamepadLayout(surfaceContext, size[0], size[1]).elements(), style = style, aspect = (size[0].toFloat() / size[1]).coerceIn(.05f, 20f))) + } return result.validate() } @@ -239,16 +302,6 @@ object InputLibraries { return library.withLayout(saved.copy(elements = InputStockLayouts.gamepad(leftPad, rightStick))).validate() } - /** Gamepads saved by the old editor follow the virtual controller's kit again; their positions don't map onto the new controls. */ - private fun kitGamepads(library: InputLibrary): InputLibrary { - return library.copy(layouts = library.layouts.map { layout -> - val origin = layout.origin ?: layout.id - if (origin != OVERLAY && !origin.startsWith("migrated.layout.")) return@map layout - val extras = layout.elements.filterNot { KitLayout.isKit(it.id) } - layout.copy(elements = extras, origin = if (layout.id == OVERLAY) null else OVERLAY, aspect = if (extras.isEmpty()) 0f else layout.aspect, scale = 1f) - }).validate() - } - private fun migrationBindingId(library: InputLibrary, binding: String, layout: String): String { val seed = JSONArray(listOf(binding, layout)).toString().toByteArray(Charsets.UTF_8) val base = "migrated.bindings." + UUID.nameUUIDFromBytes(seed) @@ -271,17 +324,29 @@ 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).put("kitless", layout.kitless)) + .put("hidden", JSONArray(layout.style.hidden.map { it.name }.sorted())).put("origin", layout.origin ?: JSONObject.NULL)) } val bindings = JSONArray() for (b in library.bindings) { @@ -310,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(), layout.optBoolean("kitless", false)) + 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)) } @@ -352,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 976b55970b..ca8838a199 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt @@ -22,8 +22,9 @@ data class SavedInputLayout( val aspect: Float = 0f, val origin: String? = null, val scale: Float = 1f, - /** The player removed every kit control from this gamepad, so it must not follow the virtual controller again. */ - val kitless: Boolean = false, + val rotated: List = emptyList(), + val rotatedAspect: Float = 0f, + val rotatedScale: Float = 1f, ) { val editable get() = template == InputLayoutTemplate.CUSTOM val quickButtons get() = QUICK_BUTTONS.filter { button -> elements.any { it.quickButton == button } } @@ -51,7 +52,7 @@ data class SavedInputBindings( fun action(element: InputSurfaceElement) = elements[element.id] ?: if (element.id == "legacy:${element.control.id}") controls[element.control] ?: InputAction.Native() - else defaultElementAction(element.id) + else InputAction.Disabled fun clickAction(element: InputSurfaceElement) = clicks[element.id] ?: defaultElementClick(element, action(element)) { controls[it] ?: InputAction.Native() } @@ -138,8 +139,8 @@ data class InputLibrary( fun withPreset(value: SavedInputBindings) = copy(bindings = bindings.filterNot { it.id == value.id } + value) fun withLayout(value: SavedInputLayout) = copy(layouts = layouts.filterNot { it.id == value.id } + value, bindings = bindings.map { preset -> if (preset.layoutId != value.id) preset else preset.copy( - elements = preset.elements.filter { (id, action) -> value.element(id)?.let { action.validFor(it) } == true }, - clicks = preset.clicks.filter { (id, action) -> value.element(id)?.hasClick == true && action.validForClick() }) }) + elements = preset.elements.filter { (id, action) -> value.elements.any { it.id == id && action.validFor(it) } }, + clicks = preset.clicks.filter { (id, action) -> value.elements.any { it.id == id && it.hasClick && action.validForClick() } }) }) fun duplicateProfile(id: String, name: String, newId: String = newInputId(), sharePhysical: Boolean = false): InputLibrary { require(profiles.size < 64) @@ -251,6 +252,8 @@ data class InputLibrary( for (layout in layouts) { require(layout.style.opacity in 1..100 && layout.style.hidden.all { it in QUICK_BUTTONS }) require(layout.aspect == 0f || layout.aspect.isFinite() && layout.aspect in .05f..20f) + require(layout.rotated.isEmpty() || layout.rotatedAspect.isFinite() && layout.rotatedAspect in .05f..20f && layout.rotatedScale.isFinite() && layout.rotatedScale in .5f..2f) + require(layout.rotated.size <= 64 && layout.rotated.all { r -> listOf(r.x, r.y, r.width, r.height).all { it.isFinite() } }) require(layout.scale.isFinite() && layout.scale in .5f..2f) inputName(layout.name); require(layout.elements.size <= 64); unique(layout.elements.map { it.id }) for (e in layout.elements) { @@ -273,8 +276,8 @@ data class InputLibrary( require(preset.physical || preset.keys.isEmpty()) val layout = preset.layoutId?.let { id -> layouts.first { it.id == id } } require(!preset.physical || layout == null && preset.elements.isEmpty() && preset.clicks.isEmpty()) - require(preset.elements.all { (id, action) -> layout?.element(id)?.let { action.validFor(it) } == true }) - require(preset.clicks.all { (id, action) -> layout?.element(id)?.hasClick == true && action.validForClick() }) + require(preset.elements.all { (id, action) -> layout?.elements?.firstOrNull { it.id == id }?.let { action.validFor(it) } == true }) + require(preset.clicks.all { (id, action) -> layout?.elements?.any { it.id == id && it.hasClick } == true && action.validForClick() }) require(preset.keys.all { it.key.device.isNotBlank() && it.key.keyCode >= 0 && it.key.scanCode >= 0 && it.action.validFor(InputControl.A) && (it.action !is InputAction.Native || it.action.target == null) }) } @@ -314,12 +317,3 @@ internal fun InputAction.validFor(element: InputSurfaceElement): Boolean = when element.kind == InputElementKind.TRIGGER -> target == InputControl.LT || target == InputControl.RT else -> target.dimensions == 1 && target != InputControl.LT && target != InputControl.RT } - -/** - * A saved element, or the kit control that [id] names: in a layout made from the built-in gamepad every kit control keeps its - * binding while it's removed, so Reset or Restore brings it back with its action. - */ -internal fun SavedInputLayout.element(id: String): InputSurfaceElement? = - elements.firstOrNull { it.id == id } ?: KitLayout.element(id)?.takeIf { - this.id == InputLibraries.OVERLAY || origin == InputLibraries.OVERLAY || KitLayout.bindsTo(id, elements) - } diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputProfile.kt b/app/src/main/java/com/droiddeck/launcher/input/InputProfile.kt index c02cb7811f..a122766271 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/InputProfile.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/InputProfile.kt @@ -48,7 +48,7 @@ data class InputProfile( copy(bindings = bindings + (role to (bindings[role].orEmpty() + (control to action)))) fun elementAction(role: InputRole, id: String, control: InputControl): InputAction = - elements[role]?.get(id) ?: if (id == "legacy:${control.id}") action(role, control) else defaultElementAction(id) + elements[role]?.get(id) ?: if (id == "legacy:${control.id}") action(role, control) else InputAction.Disabled fun elementClickAction(role: InputRole, element: InputSurfaceElement): InputAction = clicks[role]?.get(element.id) ?: defaultElementClick(element, elementAction(role, element.id, element.control)) { action(role, it) } @@ -115,10 +115,3 @@ internal fun InputAction.validFor(control: InputControl): Boolean = when (this) is InputAction.Scroll -> control.dimensions == 2 && speed.isFinite() && speed in 1f..60f else -> true } - -/** What an on-screen element with no saved action does: kit controls press their own button, everything else is unassigned. */ -internal fun defaultElementAction(id: String): InputAction = when (id) { - KitLayout.DPAD_ID -> InputAction.Native() - KitLayout.KEYBOARD_ID -> InputAction.Command(InputCommand.KEYBOARD) - else -> InputAction.Disabled -} 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 c96589573f..e7e1c58a36 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/InputSurfaceLayout.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/InputSurfaceLayout.kt @@ -38,13 +38,8 @@ data class InputSurfaceElement( ) { val hasClick get() = kind == InputElementKind.STICK || kind == InputElementKind.TRACKPAD - fun bounded() = copy(x = x.coerceIn(0f, 1f - MIN_SIZE), y = y.coerceIn(0f, 1f - MIN_SIZE), - width = width.coerceIn(MIN_SIZE, (1f - x.coerceIn(0f, 1f - MIN_SIZE)).coerceAtLeast(MIN_SIZE)), - height = height.coerceIn(MIN_SIZE, (1f - y.coerceIn(0f, 1f - MIN_SIZE)).coerceAtLeast(MIN_SIZE))) - - companion object { - const val MIN_SIZE = .01f - } + fun bounded() = copy(x = x.coerceIn(0f, 0.97f), y = y.coerceIn(0f, 0.97f), + width = width.coerceIn(0.03f, (1f - x.coerceIn(0f, 0.97f)).coerceAtLeast(0.03f)), height = height.coerceIn(0.03f, (1f - y.coerceIn(0f, 0.97f)).coerceAtLeast(0.03f))) } internal val QUICK_BUTTONS = listOf(InputCommand.STEAM, InputCommand.QUICK_ACCESS, InputCommand.KEYBOARD) @@ -56,31 +51,15 @@ val InputSurfaceElement.quickButton: InputCommand? get() = when { else -> null } -/** Controls whose boxes touch, grown by 15%, scale around one shared anchor so a cluster such as the face buttons keeps its shape. */ -internal fun List.scaled(factor: Float): List { +internal fun List.scaled(factor: Float): List = map { e -> fun anchor(centre: Float) = when { centre < 1f / 3f -> 0f; centre > 2f / 3f -> 1f; else -> .5f } - val group = IntArray(size) { it } - fun root(i: Int): Int = if (group[i] == i) i else root(group[i]).also { group[i] = it } - for (i in indices) for (j in i + 1 until size) { - val a = this[i]; val b = this[j] - val near = kotlin.math.abs(a.x + a.width / 2 - b.x - b.width / 2) < (a.width + b.width) / 2 * 1.15f && - kotlin.math.abs(a.y + a.height / 2 - b.y - b.height / 2) < (a.height + b.height) / 2 * 1.15f - if (near) group[root(i)] = root(j) - } - val anchors = indices.groupBy(::root).mapValues { (_, members) -> - anchor(members.map { this[it].x + this[it].width / 2 }.average().toFloat()) to anchor(members.map { this[it].y + this[it].height / 2 }.average().toFloat()) - } - return mapIndexed { i, e -> e.scaledAround(factor, anchors.getValue(root(i))) } -} - -private fun InputSurfaceElement.scaledAround(factor: Float, anchor: Pair): InputSurfaceElement { - val e = this - val w = (e.width * factor).coerceIn(InputSurfaceElement.MIN_SIZE, 1f) - val h = (e.height * factor).coerceIn(InputSurfaceElement.MIN_SIZE, 1f) + val w = (e.width * factor).coerceIn(.03f, 1f) + val h = (e.height * factor).coerceIn(.03f, 1f) val cx = e.x + e.width / 2 val cy = e.y + e.height / 2 - val (ax, ay) = anchor - return e.copy(x = (ax + (cx - ax) * factor - w / 2).coerceIn(0f, 1f - w), y = (ay + (cy - ay) * factor - h / 2).coerceIn(0f, 1f - h), + val ax = anchor(cx) + val ay = anchor(cy) + e.copy(x = (ax + (cx - ax) * factor - w / 2).coerceIn(0f, 1f - w), y = (ay + (cy - ay) * factor - h / 2).coerceIn(0f, 1f - h), width = w, height = h).bounded() } diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputSurfaceSource.kt b/app/src/main/java/com/droiddeck/launcher/input/InputSurfaceSource.kt index 60ffc54976..7012731ae0 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/InputSurfaceSource.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/InputSurfaceSource.kt @@ -3,10 +3,6 @@ package com.droiddeck.launcher.input class InputSurfaceSource(private val pad: PadBridge, private val role: InputRole, val element: InputSurfaceElement) { private val router = pad.inputRouter private val route = router?.channel(role, element.control, element = element) - /** The kit's D-pad keeps each direction's own binding, as the separate direction buttons it replaced did. */ - private val arms = if (element.id == KitLayout.DPAD_ID && router != null) - listOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT).map { router.channel(role, it, element = KitLayout.element("legacy:${it.id}")) } - else emptyList() private val deck = DeckControls.source(role, routed = true) private val clickDeck = DeckControls.source(role, routed = true) private val clickOwner = Any() @@ -59,15 +55,6 @@ class InputSurfaceSource(private val pad: PadBridge, private val role: InputRole fingerDown = down if (latched) 1f else 0f } else value - if (arms.isNotEmpty() && route?.action is InputAction.Native) { - val ready = route.update(x, y, touching) != null - val values = listOf(y < -.5f, x > .5f, y > .5f, x < -.5f).map { if (it && ready) 1f else 0f } - val toPad = arms.mapIndexed { i, arm -> arm.update(values[i])?.takeIf { it.isPad }?.let { it to values[i] } }.filterNotNull() - if (toPad.isNotEmpty() || nativePad) writePad(this, null) { state -> state.clear(); for ((t, v) in toPad) state.add(t, v) } - nativePad = toPad.isNotEmpty() - InputTiming.end(timing) - return - } val target = if (router == null) element.control else route?.update(x, y, touching) val toPad = target?.isPad == true val toDeck = target != null && !target.isPad @@ -88,7 +75,6 @@ class InputSurfaceSource(private val pad: PadBridge, private val role: InputRole fun cancel() { if (closed) return route?.takeIf { it.action is InputAction.Command }?.release() - arms.filter { it.action is InputAction.Command }.forEach { it.release() } update(0f) } @@ -126,13 +112,13 @@ class InputSurfaceSource(private val pad: PadBridge, private val role: InputRole closed = true router?.removeSnapshot(snapshot) releaseNative(); resetLatch() - route?.close(); arms.forEach { it.close() }; clickRoute?.close(); gestureWheel?.close(); gestureRight?.close(); gestureMiddle?.close(); deck.close(); clickDeck.close() + route?.close(); clickRoute?.close(); gestureWheel?.close(); gestureRight?.close(); gestureMiddle?.close(); deck.close(); clickDeck.close() } fun release() { if (closed) return releaseNative(); resetLatch() - route?.release(); arms.forEach { it.release() }; clickRoute?.release(); gestureWheel?.release(); gestureRight?.release(); gestureMiddle?.release() + route?.release(); clickRoute?.release(); gestureWheel?.release(); gestureRight?.release(); gestureMiddle?.release() } } diff --git a/app/src/main/java/com/droiddeck/launcher/input/KitLayout.kt b/app/src/main/java/com/droiddeck/launcher/input/KitLayout.kt deleted file mode 100644 index ef8322e9ce..0000000000 --- a/app/src/main/java/com/droiddeck/launcher/input/KitLayout.kt +++ /dev/null @@ -1,222 +0,0 @@ -package com.droiddeck.launcher.input - -import android.content.Context -import android.graphics.Rect -import kotlin.math.max -import kotlin.math.min - -/** - * Places a virtual controller's default on-screen controls. Each kit is drawn on a 1600 × 900 reference screen; controls keep - * their distance from the nearest edge, so wider screens spread them apart instead of stretching them. Clusters such as the face - * buttons are placed by their centre so they move as one, and the row along the bottom-left edge always starts after DroidDeck's - * corner button. - */ -object KitLayout { - const val DPAD_ID = "kit:dpad" - const val KEYBOARD_ID = "builtin:keyboard" - - /** Whether [id] names one of a kit's own controls rather than a key or control the player added. */ - fun isKit(id: String) = id.startsWith("legacy:") || id == DPAD_ID || id == KEYBOARD_ID - - /** The control a kit id stands for in a layout that keeps no kit positions, so bindings saved for it stay valid. */ - fun element(id: String): InputSurfaceElement? = when { - id == DPAD_ID -> InputSurfaceElement(InputControl.LS, 0f, 0f, .1f, .1f, id, InputElementKind.DPAD) - id == KEYBOARD_ID -> InputSurfaceElement(InputControl.A, 0f, 0f, .1f, .1f, id) - id.startsWith("legacy:") -> InputControl.entries.firstOrNull { "legacy:${it.id}" == id } - ?.let { InputSurfaceElement(it, 0f, 0f, .1f, .1f, id, InputElementKind.from(it)) } - else -> null - } - - /** The direction buttons the kit's D-pad stands in for; their saved overrides stay with the D-pad. */ - val dpadDirectionIds = listOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT).map { "legacy:${it.id}" } - - /** Whether a binding for [id] belongs to a layout made of [elements]. */ - fun bindsTo(id: String, elements: List) = - elements.any { it.id == id } || id in dpadDirectionIds && elements.any { it.id == DPAD_ID } - - /** Every kit control that has a click, across all virtual controllers. */ - val clickIds = listOf(InputControl.LS, InputControl.RS, InputControl.LEFT_PAD, InputControl.RIGHT_PAD).map { "legacy:${it.id}" } - private const val REF_W = 1600f - private const val REF_H = 900f - /** The widest pair of side controls on any kit: a larger size never pushes the two halves, or the rows, into each other. */ - private const val MIN_SPAN = 1200f - private const val MAX_HEIGHT_MM = 80f - /** The smallest half-size of any kit control in reference units. */ - private const val SMALLEST_HALF = 26f - private const val CORNER_DP = 52f - private const val ROW_DP = 60f - private const val BUTTON_DP = 44f - private const val GAP_DP = 8f - - private class Spec(val control: InputControl, val cx: Float, val cy: Float, val hw: Float, val hh: Float = hw, val id: String = "legacy:${control.id}", - val kind: InputElementKind = InputElementKind.from(control), val shape: InputButtonShape = InputButtonShape.CIRCLE, val icon: Int = 0, val name: String = control.label, - val ax: Float = cx, val ay: Float = cy) - - private fun shoulders() = listOf( - Spec(InputControl.LT, 140f, 66f, 88f, 34f, shape = InputButtonShape.PILL), Spec(InputControl.LB, 140f, 148f, 88f, 30f, shape = InputButtonShape.PILL), - Spec(InputControl.RT, 1460f, 66f, 88f, 34f, shape = InputButtonShape.PILL), Spec(InputControl.RB, 1460f, 148f, 88f, 30f, shape = InputButtonShape.PILL)) - - private fun face(cx: Float, cy: Float, r: Float, off: Float) = listOf( - Spec(InputControl.Y, cx, cy - off, r, ax = cx, ay = cy), Spec(InputControl.X, cx - off, cy, r, ax = cx, ay = cy), - Spec(InputControl.B, cx + off, cy, r, ax = cx, ay = cy), Spec(InputControl.A, cx, cy + off, r, ax = cx, ay = cy)) - - private fun dpad(cx: Float, cy: Float, half: Float) = - Spec(InputControl.LS, cx, cy, half, id = DPAD_ID, kind = InputElementKind.DPAD, shape = InputButtonShape.ROUNDED, name = "D-pad") - - private fun keyboard(cx: Float) = Spec(InputControl.A, cx, 848f, 46f, id = KEYBOARD_ID, icon = InputButtonIcons.KEYBOARD, name = "Keyboard") - - private fun specs(kit: PadKit): List = when { - kit.steam -> shoulders() + listOf( - Spec(InputControl.L4, 30f, 470f, 30f, 58f, shape = InputButtonShape.ROUNDED), Spec(InputControl.L5, 30f, 590f, 30f, 58f, shape = InputButtonShape.ROUNDED), - Spec(InputControl.R4, 1570f, 470f, 30f, 58f, shape = InputButtonShape.ROUNDED), Spec(InputControl.R5, 1570f, 590f, 30f, 58f, shape = InputButtonShape.ROUNDED), - dpad(220f, 345f, 150f)) + face(1375f, 345f, 58f, 96f) + listOf( - Spec(InputControl.LS, 290f, 640f, 96f), Spec(InputControl.RS, 1310f, 640f, 96f), - Spec(InputControl.LEFT_PAD, 470f, 360f, 88f, shape = InputButtonShape.ROUNDED), Spec(InputControl.RIGHT_PAD, 1130f, 360f, 88f, shape = InputButtonShape.ROUNDED), - Spec(InputControl.SELECT, 660f, 150f, 46f, 26f, shape = InputButtonShape.PILL), Spec(InputControl.START, 940f, 150f, 46f, 26f, shape = InputButtonShape.PILL), - Spec(InputControl.GUIDE, 370f, 852f, 66f, 30f, shape = InputButtonShape.PILL), Spec(InputControl.QAM, 1230f, 852f, 66f, 30f, shape = InputButtonShape.PILL), - keyboard(136f)) - kit.playStation -> shoulders() + listOf(dpad(250f, 395f, 125f)) + face(1350f, 395f, 58f, 96f) + listOf( - Spec(InputControl.LS, 565f, 690f, 100f), Spec(InputControl.RS, 1035f, 690f, 100f), - Spec(InputControl.L3, 430f, 590f, 42f, ax = 565f, ay = 690f), Spec(InputControl.R3, 1170f, 590f, 42f, ax = 1035f, ay = 690f), - Spec(InputControl.SELECT, 640f, 150f, 50f, 30f, shape = InputButtonShape.PILL), Spec(InputControl.START, 960f, 150f, 50f, 30f, shape = InputButtonShape.PILL), - Spec(InputControl.GUIDE, 800f, 250f, 46f), Spec(InputControl.QAM, 220f, 848f, 46f), keyboard(136f)) - else -> shoulders() + listOf(Spec(InputControl.LS, 235f, 400f, 104f), dpad(470f, 675f, 118f)) + face(1375f, 400f, 58f, 94f) + listOf( - Spec(InputControl.RS, 1130f, 690f, 104f), Spec(InputControl.L3, 385f, 290f, 42f, ax = 235f, ay = 400f), Spec(InputControl.R3, 1290f, 790f, 42f, ax = 1130f, ay = 690f), - Spec(InputControl.SELECT, 690f, 162f, 38f), Spec(InputControl.GUIDE, 800f, 162f, 54f), Spec(InputControl.START, 910f, 162f, 38f), - Spec(InputControl.QAM, 220f, 848f, 46f), keyboard(136f)) - } - - /** The default controls for [kit] on a [width] × [height] screen. */ - fun elements(context: Context, kit: PadKit, width: Int, height: Int, inset: Rect = Rect(), scale: Float = 1f): List { - if (width <= 0 || height <= 0) return emptyList() - // Insets stay as reported unless what's left is too small to keep every control above the minimum element size. - val smallestUnit = InputSurfaceElement.MIN_SIZE * max(width, height) / (2 * SMALLEST_HALF) - fun fit(a: Int, b: Int, side: Int, reference: Float): Pair { - val first = a.coerceAtLeast(0); val second = b.coerceAtLeast(0) - val room = (side - (smallestUnit * reference).toInt() - 1).coerceAtLeast(0) - return if (first + second <= room) first to second else (first.toLong() * room / (first + second)).toInt() to (second.toLong() * room / (first + second)).toInt() - } - val (left, right) = fit(inset.left, inset.right, width, MIN_SPAN) - val (top, bottom) = fit(inset.top, inset.bottom, height, REF_H) - val safe = Rect(left, top, right, bottom) - if (height > width) return portrait(context, kit, width, height, safe, scale) - val w = width.toFloat(); val h = height.toFloat() - val unit = (min(w / REF_W, h / REF_H) * cap(context, min(width, height)) * scale).coerceAtMost(min((w - safe.left - safe.right).coerceAtLeast(1f) / MIN_SPAN, (h - safe.top - safe.bottom).coerceAtLeast(1f) / REF_H)) - fun x(ref: Float) = when { - ref < REF_W / 3f -> safe.left + ref * unit - ref > REF_W * 2f / 3f -> w - safe.right - (REF_W - ref) * unit - else -> (w / 2f + (ref - REF_W / 2f) * unit).between(safe.left + ref * unit, w - safe.right - (REF_W - ref) * unit) - } - fun y(ref: Float) = when { - ref < REF_H / 3f -> safe.top + ref * unit - ref > REF_H * 2f / 3f -> h - safe.bottom - (REF_H - ref) * unit - else -> (h / 2f + (ref - REF_H / 2f) * unit).between(safe.top + ref * unit, h - safe.bottom - (REF_H - ref) * unit) - } - val density = context.resources.displayMetrics.density - var edge = safe.left + CORNER_DP * density - val specs = specs(kit) - val row = specs.filter { it.cy > REF_H * .88f && it.cx < REF_W / 3f }.sortedBy { it.cx }.associateWith { s -> - val hw = s.hw * unit - max(x(s.cx), edge + hw).also { edge = it + hw + GAP_DP * density } - } - return specs.map { s -> - val cx = row[s] ?: (x(s.ax) + (s.cx - s.ax) * unit); val cy = y(s.ay) + (s.cy - s.ay) * unit; val hw = s.hw * unit; val hh = s.hh * unit - InputSurfaceElement(s.control, (cx - hw) / w, (cy - hh) / h, 2 * hw / w, 2 * hh / h, s.id, s.kind, if (s.name == s.control.label) kit.name(s.control) else s.name, - floating = s.kind == InputElementKind.STICK, buttonShape = s.shape, icon = s.icon).bounded() - } - } - - /** - * A portrait surface gets the same pad as the panel under the game, in the lower part of the screen, with the keyboard, - * Steam, Quick Access and stick-click buttons in a row along the bottom edge that starts after DroidDeck's corner button. - */ - private fun portrait(context: Context, kit: PadKit, width: Int, height: Int, safe: Rect, scale: Float): List { - val w = width.toFloat(); val h = height.toFloat() - val density = context.resources.displayMetrics.density - val row = ROW_DP * density - val inner = (w - safe.left - safe.right).coerceAtLeast(1f) - val area = (min(h * .6f, inner * 1.15f) * scale).coerceAtMost(h - safe.top - safe.bottom - row).coerceAtLeast(1f) - val top = h - safe.bottom - row - area - val pad = dock(context, kit, inner.toInt(), area.toInt(), true, InputControl.LS, InputControl.RS, upright = true).map { e -> - e.copy(x = (safe.left + e.x * inner) / w, y = (top + e.y * area) / h, width = e.width * inner / w, height = e.height * area / h, - floating = e.kind == InputElementKind.STICK) - } - val specs = specs(kit) - fun spec(control: InputControl, id: String = "legacy:${control.id}") = specs.firstOrNull { it.control == control && it.id == id } - val gap = GAP_DP * density - val leftRow = listOfNotNull(spec(InputControl.A, KEYBOARD_ID), spec(InputControl.GUIDE).takeIf { kit.steam }, spec(InputControl.L3)) - val rightRow = listOfNotNull(spec(InputControl.QAM), spec(InputControl.GUIDE).takeIf { !kit.steam }, spec(InputControl.R3)) - val start = safe.left + CORNER_DP * density - val span = (w - safe.right - gap - start - gap * (leftRow.size + rightRow.size - 1)).coerceAtLeast(1f) - val size = min(BUTTON_DP * density, span / (leftRow + rightRow).sumOf { (it.hw / it.hh).toDouble() }.toFloat()) - val cy = h - safe.bottom - row / 2f - val placed = mutableListOf() - fun put(s: Spec, cx: Float) { - val bw = size * s.hw / s.hh - placed += InputSurfaceElement(s.control, (cx - bw / 2) / w, (cy - size / 2) / h, bw / w, size / h, s.id, s.kind, - if (s.name == s.control.label) kit.name(s.control) else s.name, buttonShape = s.shape, icon = s.icon) - } - var left = start - for (s in leftRow) { - val bw = size * s.hw / s.hh - put(s, left + bw / 2); left += bw + gap - } - var right = w - safe.right - gap - for (s in rightRow) { - val bw = size * s.hw / s.hh - put(s, right - bw / 2); right -= bw + gap - } - return pad + placed - } - - /** Controls for the panel below the game, in [GamepadGeometry]'s slots. */ - fun dock(context: Context, kit: PadKit, width: Int, height: Int, portrait: Boolean, left: InputControl, right: InputControl, - upright: Boolean = false): List { - val w = width.toFloat(); val h = height.toFloat() - val boxes = GamepadGeometry.layout(w, h, context.resources.displayMetrics.density, portrait, grips = kit.steam, upright = upright, - trackpads = kit.steam) - val placed = mutableListOf() - fun put(control: InputControl, box: GamepadGeometry.Box?, shape: InputButtonShape, id: String = "legacy:${control.id}", - kind: InputElementKind = InputElementKind.from(control), name: String = kit.name(control)) { - val b = box ?: return - placed += InputSurfaceElement(control, b.left / w, b.top / h, b.width / w, b.height / h, id, kind, name, floating = false, buttonShape = shape).bounded() - } - fun square(box: GamepadGeometry.Box?) = box?.let { val side = min(it.width, it.height); GamepadGeometry.Box(it.cx, it.cy, side, side) } - val four = GamepadGeometry.Slot.LEFT_TOUCH in boxes - val leftMain = if (four || !kit.steam && left == InputControl.LEFT_PAD) InputControl.LS else left - val rightMain = if (four || !kit.steam && right == InputControl.RIGHT_PAD) InputControl.RS else right - if (four) { - put(InputControl.LEFT_PAD, boxes[GamepadGeometry.Slot.LEFT_TOUCH], InputButtonShape.ROUNDED) - put(InputControl.RIGHT_PAD, boxes[GamepadGeometry.Slot.RIGHT_TOUCH], InputButtonShape.ROUNDED) - } - put(leftMain, square(boxes[GamepadGeometry.Slot.LEFT_MAIN]), InputButtonShape.CIRCLE) - put(InputControl.LS, square(boxes[GamepadGeometry.Slot.LEFT_SECOND]), InputButtonShape.ROUNDED, DPAD_ID, InputElementKind.DPAD, "D-pad") - put(rightMain, square(boxes[GamepadGeometry.Slot.RIGHT_MAIN]), InputButtonShape.CIRCLE) - square(boxes[GamepadGeometry.Slot.RIGHT_SECOND])?.let { b -> - val r = b.width * .17f; val off = b.width * .3f - listOf(InputControl.Y to (0f to -1f), InputControl.B to (1f to 0f), InputControl.A to (0f to 1f), InputControl.X to (-1f to 0f)).forEach { (c, d) -> - put(c, GamepadGeometry.Box(b.cx + d.first * off, b.cy + d.second * off, 2 * r, 2 * r), InputButtonShape.CIRCLE) - } - } - put(InputControl.LT, boxes[GamepadGeometry.Slot.LEFT_OUTER_SHOULDER], InputButtonShape.PILL) - put(InputControl.LB, boxes[GamepadGeometry.Slot.LEFT_INNER_SHOULDER], InputButtonShape.PILL) - put(InputControl.RB, boxes[GamepadGeometry.Slot.RIGHT_INNER_SHOULDER], InputButtonShape.PILL) - put(InputControl.RT, boxes[GamepadGeometry.Slot.RIGHT_OUTER_SHOULDER], InputButtonShape.PILL) - put(InputControl.SELECT, boxes[GamepadGeometry.Slot.VIEW], InputButtonShape.PILL) - put(InputControl.START, boxes[GamepadGeometry.Slot.MENU], InputButtonShape.PILL) - if (kit.steam) listOf(InputControl.L4 to GamepadGeometry.Slot.L4, InputControl.L5 to GamepadGeometry.Slot.L5, - InputControl.R5 to GamepadGeometry.Slot.R5, InputControl.R4 to GamepadGeometry.Slot.R4).forEach { (c, slot) -> put(c, boxes[slot], InputButtonShape.ROUNDED) } - return placed - } - - private fun cap(context: Context, shortSide: Int): Float { - val metrics = context.resources.displayMetrics - val nominal = metrics.densityDpi.toFloat() - val dpi = metrics.ydpi.takeIf { it > nominal * .6f && it < nominal * 1.6f } ?: nominal - val mm = shortSide / dpi * 25.4f - return min(1f, MAX_HEIGHT_MM / max(mm, 1f)) - } - - /** The middle band never comes closer to an edge than the edge rows' own reference spacing allows. */ - private fun Float.between(low: Float, high: Float) = coerceIn(low, max(low, high)) -} diff --git a/app/src/main/java/com/droiddeck/launcher/input/LegacyGamepadLayout.kt b/app/src/main/java/com/droiddeck/launcher/input/LegacyGamepadLayout.kt new file mode 100644 index 0000000000..5d81a356d9 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/LegacyGamepadLayout.kt @@ -0,0 +1,370 @@ +package com.droiddeck.launcher.input + +import android.content.Context +import android.graphics.Rect +import kotlin.math.* + +internal class LegacyGamepadLayout(private val context: Context, private val width: Int, private val height: Int, private val safe: Rect = Rect(), + private val scale: Float = 1f) { + private val resources get() = context.resources + private val settings = ControllerPrefs.read(context) + private var fit = 1f + private class Control(val id: String, val group: String, val stick: Int, val radiusDp: Float, val offsetXDp: Float, val offsetYDp: Float) { + var radius = 0f + var cx = 0f + var cy = 0f + val halfW get() = if (id in shoulderIds) radius * SHOULDER_WIDTH else radius + val halfH get() = if (id in shoulderIds) radius * SHOULDER_HEIGHT else radius + } + private val controls = listOf( + Control("up", "dpad", -1, 30f, 0f, -50f), + Control("right", "dpad", -1, 30f, 50f, 0f), + Control("down", "dpad", -1, 30f, 0f, 50f), + Control("left", "dpad", -1, 30f, -50f, 0f), + Control("ls", "ls", 0, 48f, 0f, 0f), + Control("rs", "rs", 1, 48f, 0f, 0f), + Control("a", "face", -1, 30f, 0f, 50f), + Control("b", "face", -1, 30f, 50f, 0f), + Control("x", "face", -1, 30f, -50f, 0f), + Control("y", "face", -1, 30f, 0f, -50f), + Control("lb", "lb", -1, 24f, 0f, 0f), + Control("rb", "rb", -1, 24f, 0f, 0f), + Control("lt", "lt", -1, 24f, 0f, 0f), + Control("rt", "rt", -1, 24f, 0f, 0f), + Control("select", "select", -1, 20f, 0f, 0f), + Control("start", "start", -1, 20f, 0f, 0f), + Control("guide", "guide", -1, 22f, 0f, 0f), + Control("qam", "qam", -1, 22f, 0f, 0f), + ) + + private val groups = controls.map { it.group }.distinct() + + private fun dp(value: Float) = value * resources.displayMetrics.density + + private fun scaled(value: Float) = dp(value) * settings.size / 100f * scale * fit + + private fun fitScale(): Float { + val metrics = resources.displayMetrics + val heightMm = (height - safe.top - safe.bottom) / pxPerMm(metrics.ydpi) + val faceMm = dp(60f) / pxPerMm(metrics.xdpi) + val floor = (MIN_FACE_MM / faceMm).coerceAtMost(1f) + return (heightMm / FULL_SIZE_HEIGHT_MM).coerceIn(floor, 1f) + } + + private fun pxPerMm(dpi: Float): Float { + val nominal = resources.displayMetrics.densityDpi.toFloat() + return (if (dpi > nominal * 0.6f && dpi < nominal * 1.6f) dpi else nominal) / 25.4f + } + + private fun placeAuto(w: Float, h: Float) { + val metrics = resources.displayMetrics + val mmX = pxPerMm(metrics.xdpi) + val mmY = pxPerMm(metrics.ydpi) + val usableW = w - safe.left - safe.right + val usableH = h - safe.top - safe.bottom + val inboard = (0.17f * usableW / mmX).coerceIn(24f, 40f) * mmX + val lift = (0.285f * usableH / mmY).coerceIn(22f, 45f) * mmY + val gap = dp(12f) + val floor = BOTTOM_MARGIN_MM * mmY + val drop = max(drop("dpad", "ls", gap), drop("rs", "face", gap)) + val restY = min(h - safe.bottom - lift, h - safe.bottom - floor - drop) + put("ls", safe.left + inboard, restY) + put("face", w - safe.right - inboard, restY) + besideBelow("dpad", "ls", 1f, gap, floor) + besideBelow("rs", "face", -1f, gap, floor) + val phone = usableH / mmY < PHONE_MAX_HEIGHT_MM + val shoulderY = if (phone) safe.top + floor + halfH("lb") + else min(centre("ls").second - extent("ls"), centre("face").second - extent("face")) - gap - halfH("lb") + shoulders("ls", "lb", "lt", 1f, gap, shoulderY) + shoulders("face", "rb", "rt", -1f, gap, shoulderY) + val bottom = h - safe.bottom - floor - extent("guide") + val spread = extent("guide") + gap / 2f + put("guide", w / 2f - spread, bottom) + put("qam", w / 2f + spread, bottom) + val inner = max(centre("dpad").first + extent("dpad"), w - centre("rs").first + extent("rs")) + gap + extent("select") + put("select", inner, restY) + put("start", w - inner, restY) + if (phone) { + val top = max(centre("lb").first + extent("lb"), w - centre("rb").first + extent("rb")) + gap * 2.5f + extent("select") + put("select", top, shoulderY) + put("start", w - top, shoulderY) + } + if (crowded("select", gap) || crowded("start", gap)) { + above("select", "dpad", gap) + val (sx, sy) = centre("select") + put("start", w - sx, sy) + if (crowded("start", gap)) above("start", "rs", gap) + } + if (crowded("guide", gap, gap, "qam") || crowded("qam", gap, gap, "guide")) { + val row = centre("select").second + put("guide", w / 2f - spread, row) + put("qam", w / 2f + spread, row) + if (crowded("guide", gap, gap, "qam") || crowded("qam", gap, gap, "guide")) { + val top = safe.top + dp(8f) + extent("guide") + put("guide", w / 2f - spread, top) + put("qam", w / 2f + spread, top) + } + } + } + + private fun drop(group: String, anchor: String, gap: Float): Float = + (extent(anchor) + extent(group) + gap) * sin(Math.toRadians(DROP_DEGREES)).toFloat() + extent(group) + + private fun besideBelow(group: String, anchor: String, inward: Float, gap: Float, margin: Float) { + val (ax, ay) = centre(anchor) + val reach = extent(anchor) + extent(group) + gap + val floor = height - safe.bottom - margin - extent(group) + val dy = min(reach * sin(Math.toRadians(DROP_DEGREES)).toFloat(), floor - ay) + val dx = sqrt(max(0f, reach * reach - dy * dy)) + put(group, ax + inward * dx, ay + dy) + } + + private fun shoulders(anchor: String, bumper: String, trigger: String, inward: Float, gap: Float, y: Float) { + val (ax, _) = centre(anchor) + val spread = extent(bumper) + gap / 2f + put(bumper, ax + inward * spread, y) + put(trigger, ax - inward * spread, y) + } + + private fun above(group: String, anchor: String, gap: Float) { + val (ax, ay) = centre(anchor) + put(group, ax, ay - extent(anchor) - gap - extent(group)) + } + + private fun crowded(group: String, gap: Float, space: Float = gap / 2f, except: String? = null): Boolean { + val (x, y) = centre(group) + return groups.any { other -> + if (other == group || other == except) return@any false + val (ox, oy) = centre(other) + val dx = x - ox + val dy = y - oy + sqrt(dx * dx + dy * dy) < extent(group) + extent(other) + space + } + } + + private fun members(group: String) = controls.filter { it.group == group } + + private fun centre(group: String): Pair { + val first = members(group).first() + return (first.cx - scaled(first.offsetXDp)) to (first.cy - scaled(first.offsetYDp)) + } + + private fun extent(group: String): Float = members(group).maxOf { control -> + sqrt(scaled(control.offsetXDp).let { it * it } + scaled(control.offsetYDp).let { it * it }) + control.halfW + } + + private fun halfH(group: String): Float = members(group).maxOf { abs(scaled(it.offsetYDp)) + it.halfH } + + private fun put(group: String, x: Float, y: Float) { + for (control in members(group)) { + control.cx = x + scaled(control.offsetXDp) + control.cy = y + scaled(control.offsetYDp) + } + } + + private fun clamp(group: String) { + val list = members(group) + val margin = dp(4f) + val minX = list.minOf { it.cx - it.halfW } - safe.left - margin + val maxX = list.maxOf { it.cx + it.halfW } - (width - safe.right - margin) + val minY = list.minOf { it.cy - it.halfH } - safe.top - margin + val maxY = list.maxOf { it.cy + it.halfH } - (height - safe.bottom - margin) + val dx = if (minX < 0) -minX else if (maxX > 0) -maxX else 0f + val dy = if (minY < 0) -minY else if (maxY > 0) -maxY else 0f + if (dx == 0f && dy == 0f) return + for (control in list) { control.cx += dx; control.cy += dy } + } + + + fun elements(previousStickGeometry: Boolean = false): List { + fit = fitScale() + controls.forEach { it.radius = scaled(it.radiusDp) } + placeAuto(width.toFloat(), height.toFloat()) + for ((group, position) in ControllerPrefs.layout(context, width, height)) { + if (group in groups && position.first.isFinite() && position.second.isFinite()) put(group, position.first * width, position.second * height) + } + groups.forEach(::clamp) + val result = controls.filter { + settings.mapping[it.id] != ControllerPrefs.OFF && (it.id != "guide" || settings.steamButton) && (it.id != "qam" || settings.qamButton) + }.map { c -> + InputSurfaceElement(requireNotNull(InputControl.fromId(c.id)), (c.cx - c.halfW) / width, (c.cy - c.halfH) / height, + 2 * c.halfW / width, 2 * c.halfH / height, floating = settings.adaptiveSticks, hideWhenIdle = c.stick >= 0 && settings.adaptiveSticks, + buttonShape = if (c.id in shoulderIds) InputButtonShape.PILL else InputButtonShape.CIRCLE).let { if (previousStickGeometry) widenStickPreviously(it) else widenStick(it) }.bounded() + }.toMutableList() + if (settings.keyboardButton) result += keyboard() + return result + } + + fun regenerate(stored: List): List = withGeometry(stored, elements()) + + fun rescale(stored: List, from: LegacyGamepadLayout): List = + rescaleBetween(stored, from.elements(), elements()) + + fun buttonsOnly(stored: List): List { + val inset = dp(BUTTONS_ONLY_INSET_DP) + val bottom = height - safe.bottom - inset + val radius = dp(BUTTONS_ONLY_RADIUS_DP) + fun pick(control: InputControl, shown: Boolean) = stored.firstOrNull { it.id == "legacy:${control.id}" } + ?: stored.firstOrNull { it.control == control && it.kind == InputElementKind.BUTTON } + ?: InputSurfaceElement(control, 0f, 0f, 0f, 0f, buttonShape = InputButtonShape.CIRCLE).takeIf { shown } + return listOfNotNull( + pick(InputControl.GUIDE, settings.steamButton)?.let { circle(it, safe.left + inset, bottom, radius) }, + pick(InputControl.QAM, settings.qamButton)?.let { circle(it, width - safe.right - inset, bottom, radius) }, + stored.firstOrNull { it.id == KEYBOARD_ID }?.let { circle(it, width / 2f, bottom, dp(KEYBOARD_RADIUS_DP)) }, + ) + } + + fun dock(stored: List, portrait: Boolean, grips: Boolean, left: InputControl = InputControl.LS, + right: InputControl = InputControl.RS): List { + val boxes = GamepadGeometry.layout(width.toFloat(), height.toFloat(), resources.displayMetrics.density, portrait) + val placed = mutableListOf() + fun box(control: InputControl, slot: GamepadGeometry.Slot, shape: InputButtonShape) { + val b = boxes[slot] ?: return + placed += InputSurfaceElement(control, b.left / width, b.top / height, b.width / width, b.height / height, + floating = false, buttonShape = shape).bounded() + } + fun cross(controls: List, slot: GamepadGeometry.Slot) { + val b = boxes[slot] ?: return + val side = min(b.width, b.height) + val spread = side * CROSS_SPREAD + val radius = side * CROSS_RADIUS + controls.zip(listOf(0f to -1f, 1f to 0f, 0f to 1f, -1f to 0f)).forEach { (control, direction) -> + placed += circle(InputSurfaceElement(control, 0f, 0f, 0f, 0f, buttonShape = InputButtonShape.CIRCLE), + b.cx + direction.first * spread, b.cy + direction.second * spread, radius) + } + } + box(left, GamepadGeometry.Slot.LEFT_MAIN, InputButtonShape.CIRCLE) + cross(DPAD_ORDER, GamepadGeometry.Slot.LEFT_SECOND) + box(right, GamepadGeometry.Slot.RIGHT_MAIN, InputButtonShape.CIRCLE) + cross(FACE_ORDER, GamepadGeometry.Slot.RIGHT_SECOND) + box(InputControl.LT, GamepadGeometry.Slot.LEFT_OUTER_SHOULDER, InputButtonShape.PILL) + box(InputControl.LB, GamepadGeometry.Slot.LEFT_INNER_SHOULDER, InputButtonShape.PILL) + box(InputControl.RB, GamepadGeometry.Slot.RIGHT_INNER_SHOULDER, InputButtonShape.PILL) + box(InputControl.RT, GamepadGeometry.Slot.RIGHT_OUTER_SHOULDER, InputButtonShape.PILL) + box(InputControl.SELECT, GamepadGeometry.Slot.VIEW, InputButtonShape.PILL) + box(InputControl.START, GamepadGeometry.Slot.MENU, InputButtonShape.PILL) + if (grips) GRIPS.forEach { (control, slot) -> box(control, slot, InputButtonShape.ROUNDED) } + val surfaces = listOf(left, right).filter { it.isTrackpad } + return withGeometry(stored, placed) + placed.filter { p -> (GRIPS.any { it.first == p.control } || p.control in surfaces) && stored.none { it.id == p.id } } + } + + private fun circle(e: InputSurfaceElement, cx: Float, cy: Float, radius: Float) = + e.copy(x = (cx - radius) / width, y = (cy - radius) / height, width = 2 * radius / width, height = 2 * radius / height).bounded() + + private fun withGeometry(stored: List, placed: List): List { + val byId = placed.associateBy { it.id } + return stored.mapNotNull { e -> byId[e.id]?.let { e.copy(x = it.x, y = it.y, width = it.width, height = it.height) } } + } + + private fun keyboard(): InputSurfaceElement { + val radius = dp(KEYBOARD_RADIUS_DP) + val cx = safe.left + dp(KEYBOARD_X_DP) + val cy = height - safe.bottom - dp(KEYBOARD_Y_DP) + return InputSurfaceElement(InputControl.A, (cx - radius) / width, (cy - radius) / height, 2 * radius / width, 2 * radius / height, + KEYBOARD_ID, name = "Keyboard", icon = InputButtonIcons.KEYBOARD, buttonShape = InputButtonShape.CIRCLE).bounded() + } + + fun restyle(elements: List): List { + val dpad = elements.filter { it.id == "legacy:${it.control.id}" && it.control in DPAD && it.buttonShape == InputButtonShape.ROUNDED } + val centreX = dpad.map { (it.x + it.width / 2f) * width }.average().toFloat() + val centreY = dpad.map { (it.y + it.height / 2f) * height }.average().toFloat() + val resize = untouchedDpad(dpad, centreX, centreY) + return elements.map { e -> + when { + e.id == KEYBOARD_ID && e.icon == 0 && e.name == "Keyboard" && e.buttonShape == InputButtonShape.ROUNDED && + e.x == .02f && e.y == .9f && e.width == .12f && e.height == .08f -> keyboard() + e.id == "legacy:${e.control.id}" && e.buttonShape == InputButtonShape.ROUNDED -> { + val round = e.copy(buttonShape = if (e.control.id in shoulderIds) InputButtonShape.PILL else InputButtonShape.CIRCLE) + (if (resize && e.control in DPAD) resizeDpad(round, centreX, centreY) else widenStick(round)).bounded() + } + else -> e + } + } + } + + private fun untouchedDpad(dpad: List, centreX: Float, centreY: Float): Boolean { + if (dpad.size != DPAD.size) return false + val radius = dpad[0].width * width / 2f + val tolerance = 1.5f + val offset = radius * LEGACY_DPAD_OFFSET_DP / LEGACY_DPAD_RADIUS_DP + return dpad.all { e -> + val old = controls.first { it.id == e.control.id } + val dx = (e.x + e.width / 2f) * width - centreX + val dy = (e.y + e.height / 2f) * height - centreY + abs(e.width * width / 2f - radius) <= tolerance && abs(e.height * height / 2f - radius) <= tolerance && + abs(dx - offset * sign(old.offsetXDp)) <= tolerance && abs(dy - offset * sign(old.offsetYDp)) <= tolerance + } + } + + private fun resizeDpad(e: InputSurfaceElement, centreX: Float, centreY: Float): InputSurfaceElement { + val old = controls.first { it.id == e.control.id } + val radius = e.width * width / 2f * old.radiusDp / LEGACY_DPAD_RADIUS_DP + val cx = centreX + ((e.x + e.width / 2f) * width - centreX) * abs(old.offsetXDp + old.offsetYDp) / LEGACY_DPAD_OFFSET_DP + val cy = centreY + ((e.y + e.height / 2f) * height - centreY) * abs(old.offsetXDp + old.offsetYDp) / LEGACY_DPAD_OFFSET_DP + return e.copy(x = (cx - radius) / width, y = (cy - radius) / height, width = 2 * radius / width, height = 2 * radius / height) + } + + private fun widenStickPreviously(e: InputSurfaceElement): InputSurfaceElement { + val extra = e.width * (STICK_REACH - 1f) + return when (e.control) { + InputControl.LS -> (e.x - extra).coerceAtLeast(0f).let { x -> e.copy(x = x, width = e.x + e.width - x) } + InputControl.RS -> e.copy(width = (e.width + extra).coerceAtMost(1f - e.x)) + else -> e + } + } + + private fun widenStick(e: InputSurfaceElement): InputSurfaceElement { + val extra = e.width * (STICK_REACH - 1f) + val width = e.width + extra + return when (e.control) { + InputControl.LS -> e.copy(x = (e.x - extra).coerceIn(0f, (1f - width).coerceAtLeast(0f)), width = width) + InputControl.RS -> e.copy(x = e.x.coerceIn(0f, (1f - width).coerceAtLeast(0f)), width = width) + else -> e + } + } + private companion object { + const val MIN_FACE_MM = 9.5f + const val FULL_SIZE_HEIGHT_MM = 85f + const val BOTTOM_MARGIN_MM = 5f + const val DROP_DEGREES = 35.0 + const val PHONE_MAX_HEIGHT_MM = 90f + const val SHOULDER_WIDTH = 1.45f + const val SHOULDER_HEIGHT = 0.8f + val shoulderIds = setOf("lb", "rb", "lt", "rt") + 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 + const val KEYBOARD_Y_DP = 34f + const val BUTTONS_ONLY_RADIUS_DP = 30f + const val BUTTONS_ONLY_INSET_DP = 44f + const val CROSS_SPREAD = .30f + const val CROSS_RADIUS = .16f + val DPAD_ORDER = listOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT) + val FACE_ORDER = listOf(InputControl.Y, InputControl.B, InputControl.A, InputControl.X) + val GRIPS = listOf(InputControl.L4 to GamepadGeometry.Slot.L4, InputControl.L5 to GamepadGeometry.Slot.L5, + 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 ef65bb1cf7..142846a04f 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt @@ -3,78 +3,111 @@ package com.droiddeck.launcher.input import android.annotation.SuppressLint import android.content.Context import android.graphics.Canvas -import android.graphics.Color import android.graphics.Paint import android.graphics.Rect -import android.graphics.RectF +import android.graphics.Typeface import android.os.Build import android.view.Gravity import android.view.HapticFeedbackConstants import android.view.MotionEvent import android.view.View -import android.view.ViewConfiguration import android.view.WindowInsets import android.widget.FrameLayout import com.droiddeck.launcher.ui.InputSurfaceView -import com.droiddeck.launcher.ui.PadArt class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayout.Dock? = null) : FrameLayout(context) { - /** Why the controls are hidden while the corner button stays. */ - enum class Hidden { BY_TAP, BY_CONTROLLER } - private val surface = InputSurfaceView(context, pad, inputRole = InputRole.PRIMARY, haptics = dock != null) private var layout: SavedInputLayout? = null private val safe = Rect() private var viewWidth = 0 private var viewHeight = 0 - private val corner = CornerButton(context) - var hidden: Hidden? = null + private val placements = object : LinkedHashMap>(4, .75f, true) { + override fun removeEldestEntry(eldest: MutableMap.MutableEntry>) = size > PLACEMENT_CACHE + } + private val quickToggle = QuickToggle(context) + var isButtonsOnly = false private set - /** Holding the corner button opens DroidDeck's controller menu. */ - var onCornerHold: (() -> Unit)? = null - /** The player tapped the corner button. */ - var onCornerTap: ((Hidden?) -> Unit)? = null - val inputSurface: InputSurfaceView get() = surface + var isQuickHidden = false + private set + var isPinnedOnly = false + private set + val hasPinned get() = layout?.elements?.any { it.alwaysShown } == true + val inputSurface: com.droiddeck.launcher.ui.InputSurfaceView get() = surface var onTouchMiss: ((MotionEvent) -> Unit)? get() = surface.onTouchMiss set(value) { surface.onTouchMiss = value } init { addView(surface, LayoutParams(-1, -1)) - val size = (CORNER_HIT_DP * resources.displayMetrics.density).toInt() - addView(corner, LayoutParams(size, size, Gravity.START or Gravity.BOTTOM)) + val size = (QUICK_HIT_DP * 2 * resources.displayMetrics.density).toInt() + addView(quickToggle, LayoutParams(size, size, Gravity.START or Gravity.BOTTOM)) } fun updateLayout(value: SavedInputLayout?) { - val kit = PadKit.current(context) - if (layout == value && surface.kit == kit) return + if (layout == value) return releaseAll() layout = value - surface.kit = kit render() } - fun setHidden(value: Hidden?) { - if (hidden == value) return + fun setButtonsOnly(enabled: Boolean) { + if (isButtonsOnly == enabled) return releaseAll() - hidden = value + isButtonsOnly = enabled + isQuickHidden = false render() } + fun setQuickHidden(hidden: Boolean) { + if (isButtonsOnly || isQuickHidden == hidden) return + releaseAll() + isQuickHidden = hidden + render() + } + + fun setPinnedOnly(enabled: Boolean) { + if (isPinnedOnly == enabled) return + releaseAll() + isPinnedOnly = enabled + render() + } + + 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 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, + rearButtons = optional.first, trackpads = optional.second) + } + } + private fun render() { - val placed = OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, dock) - surface.updateCustomLayout(if (hidden != null) placed.filter { it.alwaysShown } else placed) - surface.updateStyle(layout?.style ?: InputSurfaceStyle()) - corner.visibility = if (layout == null || dock != null) GONE else VISIBLE - corner.alpha = (layout?.style?.opacity ?: 100) / 100f - corner.invalidate() + val elements = placed() + surface.updateCustomLayout(when { + isPinnedOnly -> elements.filter { it.alwaysShown } + isQuickHidden -> elements.filter { it.id == "builtin:keyboard" || it.alwaysShown } + else -> elements + }) + 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() } fun takesTouchAt(x: Float, y: Float) = surface.takesTouchAt(x, y) || - corner.visibility == VISIBLE && x >= corner.left && x < corner.right && y >= corner.top && y < corner.bottom - fun cornerTakes(x: Float, y: Float) = corner.visibility == VISIBLE && x >= corner.left && x < corner.right && y >= corner.top && y < corner.bottom + quickToggle.visibility == VISIBLE && x >= quickToggle.left && x < quickToggle.right && y >= quickToggle.top && y < quickToggle.bottom fun releaseAll() = surface.releaseInputs() - fun reload() { releaseAll(); surface.kit = PadKit.current(context); render() } + fun reload() { releaseAll(); placements.clear(); render() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val w = MeasureSpec.getSize(widthMeasureSpec) @@ -91,16 +124,16 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets { val cutout = if (Build.VERSION.SDK_INT >= 28) insets.displayCutout else null - val margin = (CORNER_MARGIN_DP * resources.displayMetrics.density).toInt() - val params = corner.layoutParams as LayoutParams - val left = (cutout?.safeInsetLeft ?: 0) + margin - val bottom = (cutout?.safeInsetBottom ?: 0) + margin + val offset = ((QUICK_CENTER_DP - QUICK_HIT_DP) * resources.displayMetrics.density).toInt() + val params = quickToggle.layoutParams as LayoutParams + val left = (cutout?.safeInsetLeft ?: 0) + offset + val bottom = (cutout?.safeInsetBottom ?: 0) + offset if (params.leftMargin != left || params.bottomMargin != bottom) { params.leftMargin = left params.bottomMargin = bottom - corner.layoutParams = params + 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() @@ -108,45 +141,42 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo return super.onApplyWindowInsets(insets) } - private inner class CornerButton(context: Context) : View(context) { - private val art = PadArt(context) - private val badge = Paint(Paint.ANTI_ALIAS_FLAG) + private inner class QuickToggle(context: Context) : View(context) { + var tint: Int? = ControllerPrefs.STEAM_BLUE + private val density = resources.displayMetrics.density private var armed = false - private var held = false - private val hold = Runnable { if (armed) { held = true; performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) } } + private val fill = Paint(Paint.ANTI_ALIAS_FLAG) + private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeWidth = 1.5f * density } + private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply { + textAlign = Paint.Align.CENTER + typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD) + textSize = 22 * density + } override fun onDraw(canvas: Canvas) { - val w = width.toFloat(); val h = height.toFloat() - val dimmed = hidden != null && !armed - if (dimmed) canvas.saveLayerAlpha(0f, 0f, w, h, 170) - art.system(canvas, w, h, PadArt.Shape.ROUND, PadArt.Icon.MARK, armed) - if (dimmed) canvas.restore() - if (hidden == Hidden.BY_CONTROLLER) { - val d = art.density - val r = RectF(w - 15 * d, 3 * d, w - 2 * d, 12 * d) - badge.style = Paint.Style.FILL; badge.color = Color.rgb(0x16, 0x19, 0x1E) - canvas.drawRoundRect(r, 2.5f * d, 2.5f * d, badge) - badge.style = Paint.Style.STROKE; badge.strokeWidth = 1.3f * d; badge.color = Color.rgb(0xFF, 0xB3, 0x47) - canvas.drawRoundRect(r, 2.5f * d, 2.5f * d, badge) - } + val x = width / 2f + val y = height / 2f + val radius = QUICK_RADIUS_DP * density + val color = tint + fill.color = if (color != null) InputSurfaceView.shade(color, 190, 0.12f) else (InputSurfaceView.SURFACE and 0x00ffffff) or (190 shl 24) + canvas.drawCircle(x, y, radius, fill) + stroke.color = if (color != null) InputSurfaceView.light(color, 150, 0.25f) else InputSurfaceView.LINE + canvas.drawCircle(x, y, radius, stroke) + text.color = if (color != null) InputSurfaceView.light(color, 210, 0.75f) else InputSurfaceView.TEXT + canvas.drawText(if (isQuickHidden) "+" else "−", x, y + text.textSize * 0.35f, text) } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { when (event.actionMasked) { - MotionEvent.ACTION_DOWN -> { armed = true; held = false; postDelayed(hold, ViewConfiguration.getLongPressTimeout().toLong()); invalidate() } - MotionEvent.ACTION_CANCEL -> { armed = false; removeCallbacks(hold); invalidate() } + MotionEvent.ACTION_DOWN -> armed = true + MotionEvent.ACTION_CANCEL -> armed = false MotionEvent.ACTION_UP -> { - removeCallbacks(hold) - if (armed && held) post { onCornerHold?.invoke() } - else if (armed && event.x in 0f..width.toFloat() && event.y in 0f..height.toFloat()) { + if (armed && event.x in 0f..width.toFloat() && event.y in 0f..height.toFloat()) { performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY) - val next = if (hidden == null) Hidden.BY_TAP else null - setHidden(next) - onCornerTap?.invoke(next) + setQuickHidden(!isQuickHidden) } armed = false - invalidate() } } return true @@ -154,7 +184,9 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo } private companion object { - const val CORNER_HIT_DP = 48f - const val CORNER_MARGIN_DP = 4f + const val QUICK_CENTER_DP = 34f + const val QUICK_HIT_DP = 26f + const val QUICK_RADIUS_DP = 18f + const val PLACEMENT_CACHE = 4 } } 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 39235de581..3f74de743f 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt @@ -2,10 +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?.id == InputLibraries.OVERLAY && + (controller == SessionPrefs.CONTROLLER_DECK || controller == SessionPrefs.CONTROLLER_STEAM) + data class Dock(val portrait: Boolean, val grips: Boolean, val left: InputControl = InputControl.LS, val right: InputControl = InputControl.RS) { companion object { fun deck(portrait: Boolean, gamepad: SavedInputLayout?): Dock { @@ -19,31 +28,94 @@ object OnScreenLayout { } } - /** - * The built-in gamepad keeps no kit positions until its kit is edited; until then the kit follows the virtual controller and - * the layout stores only the keys and controls the player added on top. - */ - fun generated(layout: SavedInputLayout) = (layout.id == InputLibraries.OVERLAY || layout.origin == InputLibraries.OVERLAY) && - !layout.kitless && layout.elements.none { KitLayout.isKit(it.id) } + private const val TOLERANCE = .01f + private const val KEYBOARD_ID = "builtin:keyboard" + private val REAR = setOf(InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5) - fun elements(context: Context, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect, dock: Dock? = null): List { - layout ?: return emptyList() - if (width <= 0 || height <= 0) return layout.elements - if (generated(layout)) { - val kit = PadKit.current(context) - val extras = if (layout.elements.isEmpty()) emptyList() else fit(layout.elements, aspect(context, layout), 1f, width, height, safe) - return (if (dock != null) KitLayout.dock(context, kit, width, height, dock.portrait, dock.left, dock.right) - else KitLayout.elements(context, kit, width, height, safe, layout.scale)) + extras + fun elements(context: Context, saved: SavedInputLayout?, width: Int, height: Int, safe: Rect, + buttonsOnly: Boolean = false, dock: Dock? = null, rearButtons: Boolean? = null, + trackpads: Boolean? = null): List { + if (saved == null) return emptyList() + if (width <= 0 || height <= 0) return saved.elements + val layout = oriented(saved, width, height) + val stored = layout.elements + val generator = LegacyGamepadLayout(context, width, height, safe, layout.scale) + val (reference, matched) = reference(context, layout, width, height) + if (buttonsOnly && dock == null) return generator.buttonsOnly(stored) + fit(stored.filter { it.alwaysShown }, reference.first, reference.second, width, height, safe) + 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 regenerated = when { + gamepad.isEmpty() -> emptyList() + dock != null -> generator.dock(gamepad, dock.portrait, dock.grips, dock.left, dock.right) + else -> generator.regenerate(gamepad) } - return fit(layout.elements, aspect(context, layout), 1f, width, height, safe) + val placed = regenerated + gamepad.filter { g -> dock == null && optional(g) && regenerated.none { it.id == g.id } } + val byId = (placed + others).associateBy { it.id } + val ordered = stored.mapNotNull { byId[it.id] } + placed.filter { p -> stored.none { it.id == p.id } } + 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 { + val portrait = height > width + if (layout.rotated.isEmpty() || layout.aspect <= 0f || (layout.aspect < 1f) == portrait || (layout.rotatedAspect < 1f) != portrait) return layout + val rotated = layout.rotated.associateBy { it.id } + return layout.copy(elements = layout.elements.map { e -> rotated[e.id]?.let { e.copy(x = it.x, y = it.y, width = it.width, height = it.height) } ?: e } + + layout.rotated.filter { r -> optional(r) && layout.elements.none { it.id == r.id } }, + aspect = layout.rotatedAspect, scale = layout.rotatedScale, rotated = emptyList(), rotatedAspect = 0f, rotatedScale = 1f) + } + + fun withFrame(context: Context, saved: SavedInputLayout, elements: List, aspect: Float, scale: Float = saved.scale): SavedInputLayout { + val (_, metrics) = InputLibraries.primaryDisplay(context) + val generated = generatedSize(context, saved, metrics.widthPixels, metrics.heightPixels) != null + val portraitMain = saved.aspect > 0f && saved.aspect < 1f + if (aspect <= 0f || aspect >= 1f || portraitMain && !generated) { + val rotated = if (aspect >= 1f && portraitMain && !generated) Triple(saved.elements, saved.aspect, saved.scale) else Triple(saved.rotated, saved.rotatedAspect, saved.rotatedScale) + return saved.copy(elements = elements, aspect = aspect, scale = scale, rotated = rotated.first, + rotatedAspect = if (rotated.first.isEmpty()) 0f else rotated.second, rotatedScale = if (rotated.first.isEmpty()) 1f else rotated.third) + } + val main = if (portraitMain) 1f / saved.aspect else saved.aspect.takeIf { it > 0f } ?: (1f / aspect) + val ids = elements.associateBy { it.id } + val kept = saved.elements.mapNotNull { e -> ids[e.id]?.copy(x = e.x, y = e.y, width = e.width, height = e.height) } + val added = fit(elements.filter { d -> !optional(d) && saved.elements.none { it.id == d.id } }, aspect, 1f, (main * 1000).roundToInt().coerceAtLeast(1), 1000, Rect()) + return saved.copy(elements = kept + added, aspect = main, rotated = elements, rotatedAspect = aspect, rotatedScale = scale) + } + + fun optionalControls(context: Context): Pair { + val steam = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad + return SessionPrefs.oscRearButtons(context).takeIf { steam } to SessionPrefs.oscTrackpads(context).takeIf { steam } + } + + fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false, safe: Rect = Rect()): List { + val (rear, pads) = optionalControls(context) + return elements(context, if (edited && width > 0 && height > 0) layout.copy(aspect = width.toFloat() / height) else layout, width, height, safe, + rearButtons = rear, trackpads = pads) + } fun editorFrame(layout: SavedInputLayout, displayed: List): List { val byId = displayed.associateBy { it.id } - return layout.elements.map { byId[it.id] ?: it } + return layout.elements.map { byId[it.id] ?: it } + displayed.filter { d -> + optional(d) && layout.elements.none { it.id == d.id } + } + } + + fun safeInsets(insets: android.view.WindowInsets?, docked: Boolean): Rect { + val cutout = if (android.os.Build.VERSION.SDK_INT >= 28) insets?.displayCutout else null + return Rect(cutout?.safeInsetLeft ?: 0, if (docked) 0 else cutout?.safeInsetTop ?: 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0) } fun fit(elements: List, referenceWidth: Float, referenceHeight: Float, width: Int, height: Int, safe: Rect): List { @@ -69,8 +141,37 @@ object OnScreenLayout { } } - private fun aspect(context: Context, layout: SavedInputLayout): Float = layout.aspect.takeIf { it > 0f } ?: run { - val metrics = InputLibraries.primaryDisplay(context).second - max(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1).toFloat() / min(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1) + 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? = + reference(context, layout, width, height).takeIf { it.second }?.first?.let { it.first.toInt() to it.second.toInt() } + + private fun reference(context: Context, layout: SavedInputLayout, width: Int, height: Int): Pair, Boolean> { + val (display, metrics) = InputLibraries.primaryDisplay(context) + val long = max(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1) + val short = min(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1) + val gamepad = layout.elements.filter(::isGamepad) + 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 } + ?.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) + if (matches(gamepad, generator.elements()) || matches(gamepad, generator.elements(previousStickGeometry = true))) return (w.toFloat() to h.toFloat()) to true + } + } + val aspect = layout.aspect.takeIf { it > 0f } ?: (long.toFloat() / short) + return (aspect to 1f) to false + } + + private fun matches(stored: List, generated: List): Boolean { + val byId = generated.associateBy { it.id } + return stored.all { e -> + val g = byId[e.id] ?: return@all false + abs(e.x - g.x) <= TOLERANCE && abs(e.y - g.y) <= TOLERANCE && abs(e.width - g.width) <= TOLERANCE && abs(e.height - g.height) <= TOLERANCE + } } } diff --git a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java index 55d81ca2c1..666a9d1ceb 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java +++ b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java @@ -107,8 +107,6 @@ public final class PadBridge { private volatile Runnable onPlayerInput; private Runnable onChordInput; private final java.util.concurrent.atomic.AtomicBoolean playerInputPosted = new java.util.concurrent.atomic.AtomicBoolean(); - private volatile Runnable onPhysicalInput; - private final java.util.concurrent.atomic.AtomicBoolean physicalInputPosted = new java.util.concurrent.atomic.AtomicBoolean(); private static final long STATS_WINDOW_MS = 10_000; private int statButtons, statAxes, statOnScreen, statDropped; @@ -370,20 +368,6 @@ public final class PadBridge { onPlayerInput = listener; } - /** Input from a controller the player holds, never from the on-screen controls. */ - public void setOnPhysicalInput(Runnable listener) { - onPhysicalInput = listener; - } - - private void notePhysicalInput() { - Runnable listener = onPhysicalInput; - if (listener == null || !physicalInputPosted.compareAndSet(false, true)) return; - mainHandler.post(() -> { - physicalInputPosted.set(false); - listener.run(); - }); - } - public synchronized void setOnChordInput(Runnable listener) { onChordInput = listener; } @@ -449,7 +433,7 @@ public final class PadBridge { } noteDevice(device, slot); if (pressed && event.getRepeatCount() == 0 && !event.isCanceled()) noteChordInput(slot); - if (pressed) { notePlayerInput(); notePhysicalInput(); } + if (pressed) notePlayerInput(); statButtons++; scheduleStats(); publish(slot); @@ -537,7 +521,7 @@ public final class PadBridge { retainStick(slot, side, x, y); projectSticks(slot); if (chordStickInput) noteChordInput(slot); - if (Math.max(Math.abs(x), Math.abs(y)) > 0.5f) { notePlayerInput(); notePhysicalInput(); } + if (Math.max(Math.abs(x), Math.abs(y)) > 0.5f) notePlayerInput(); publish(slot); InputTiming.end(timing); return true; @@ -579,7 +563,6 @@ public final class PadBridge { if (Math.max(Math.max(Math.abs(pad.leftX), Math.abs(pad.leftY)), Math.max(Math.abs(pad.rightX), Math.abs(pad.rightY))) > 0.5f || lt > 0.5f || rt > 0.5f || pad.up || pad.right || pad.down || pad.left) { notePlayerInput(); - notePhysicalInput(); } publish(slot); InputTiming.end(timing); diff --git a/app/src/main/java/com/droiddeck/launcher/input/PadKit.kt b/app/src/main/java/com/droiddeck/launcher/input/PadKit.kt index 59efeccfa0..c976d310e9 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/PadKit.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/PadKit.kt @@ -3,11 +3,11 @@ package com.droiddeck.launcher.input import android.content.Context import com.droiddeck.launcher.session.SessionPrefs -enum class FaceGlyphs { MONO_LETTERS, COLOR_LETTERS, COLOR_SYMBOLS, MONO_SYMBOLS } -enum class DpadStyle { CROSS, DISC, ARROWS } -enum class StickCap { RINGED, DISHED, KNURLED } +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 } -enum class PadKit(val face: FaceGlyphs, val dpad: DpadStyle, val stick: StickCap, private val xbox: Boolean = false) { +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), @@ -34,15 +34,21 @@ enum class PadKit(val face: FaceGlyphs, val dpad: DpadStyle, val stick: StickCap else -> label(control) } - companion object { - fun of(type: String) = when (type) { - SessionPrefs.CONTROLLER_STEAM -> STEAM_CONTROLLER - SessionPrefs.CONTROLLER_XBOX360 -> XBOX - SessionPrefs.CONTROLLER_DS4 -> DUALSHOCK - SessionPrefs.CONTROLLER_DUALSENSE -> DUALSENSE - else -> STEAM_DECK - } + fun native(element: InputSurfaceElement) = element.id == "legacy:${element.control.id}" && element.icon == 0 && + (element.name == element.control.label || element.name == name(element.control)) - fun current(context: Context) = of(SessionPrefs.steamController(context)) + fun artwork(element: InputSurfaceElement) = element.image.isEmpty() && element.showLabel && + (native(element) || element.id == "builtin:keyboard" && element.icon == InputButtonIcons.KEYBOARD) + + companion object { + fun forOverlay(context: Context, layout: SavedInputLayout?): PadKit? = + if (layout?.id != InputLibraries.OVERLAY) null else when (SessionPrefs.steamController(context)) { + SessionPrefs.CONTROLLER_DECK -> STEAM_DECK + SessionPrefs.CONTROLLER_STEAM -> STEAM_CONTROLLER + SessionPrefs.CONTROLLER_XBOX360 -> XBOX + SessionPrefs.CONTROLLER_DS4 -> DUALSHOCK + SessionPrefs.CONTROLLER_DUALSENSE -> DUALSENSE + else -> null + } } } diff --git a/app/src/main/java/com/droiddeck/launcher/input/PhysicalInputBindings.kt b/app/src/main/java/com/droiddeck/launcher/input/PhysicalInputBindings.kt index 664e060926..fcb883a997 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/PhysicalInputBindings.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/PhysicalInputBindings.kt @@ -25,10 +25,7 @@ data class PhysicalInputKey(val device: String, val name: String, val keyCode: I data class PhysicalInputBinding(val key: PhysicalInputKey, val action: InputAction) -class PhysicalInputBindings( - private val router: InputRouter, - private val onPress: (KeyEvent) -> Unit = {}, -) { +class PhysicalInputBindings(private val router: InputRouter) { private class Entry(val binding: PhysicalInputBinding, val channel: InputRouter.Channel) { var heldDevice = -1 var suppressed = false @@ -69,10 +66,7 @@ class PhysicalInputBindings( if (identity != key.device) continue entry.heldDevice = event.deviceId entry.suppressed = event.repeatCount != 0 - if (!entry.suppressed) { - entry.channel.update(1f) - onPress(event) - } + if (!entry.suppressed) entry.channel.update(1f) return true } return false diff --git a/app/src/main/java/com/droiddeck/launcher/input/SteamControllerBle.kt b/app/src/main/java/com/droiddeck/launcher/input/SteamControllerBle.kt index 5a567c0bc1..8194cea3b3 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/SteamControllerBle.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/SteamControllerBle.kt @@ -20,11 +20,7 @@ import java.util.ArrayDeque import java.util.UUID @SuppressLint("MissingPermission") -class SteamControllerBle( - private val context: Context, - router: InputRouter? = null, - private val onPhysicalInput: (() -> Unit)? = null, -) { +class SteamControllerBle(private val context: Context, router: InputRouter? = null) { private val inputLock = router ?: Any() private var routedInput = router?.let(::TritonInputRouter) @Volatile private var stopped = false @@ -43,7 +39,6 @@ class SteamControllerBle( private var outputSequence = 0L private var outputWritePending = false private var featureRead = 0L - private var lastPressedControls = 0 fun start(): Unit = synchronized(inputLock) { if (stopped || started) return@synchronized @@ -271,18 +266,12 @@ class SteamControllerBle( val timing = InputTiming.begin() FakeInputWriter.writeTritonState(SLOT, reportId, routedInput?.route(data) ?: data) InputTiming.end(timing) - if (connected && onPhysicalInput != null) { - val pressed = TritonInputRouter.pressedControls(data) - if (pressed and lastPressedControls.inv() != 0) onPhysicalInput() - lastPressedControls = pressed - } } private fun release() = synchronized(inputLock) { if (stopped) return@synchronized routedInput?.release() withSlot { - lastPressedControls = 0 FakeInputWriter.writeTritonState(SLOT, if (reportId == 0x47) 0x47 else 0x45, ByteArray(STATE_BYTES)) } } diff --git a/app/src/main/java/com/droiddeck/launcher/input/SteamTouchControls.kt b/app/src/main/java/com/droiddeck/launcher/input/SteamTouchControls.kt index 1a4765fc13..3e6e7944af 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/SteamTouchControls.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/SteamTouchControls.kt @@ -119,7 +119,6 @@ class SteamTouchControls( private var selectedArm = 0 private val fill = Paint(Paint.ANTI_ALIAS_FLAG) - private val art = com.droiddeck.launcher.ui.PadArt(context) private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE } private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER; isFakeBoldText = true } @@ -241,10 +240,7 @@ class SteamTouchControls( private fun cx(e: Element) = e.x * width private fun cy(e: Element) = e.y * height - private fun reach(e: Element, x: Float, y: Float): Float { - val dx = (x - cx(e)) / radius(e); val dy = (y - cy(e)) / radiusY(e) - return if (e.type in TRACKPADS) max(abs(dx), abs(dy)) else hypot(dx, dy) - } + private fun reach(e: Element, x: Float, y: Float) = hypot((x - cx(e)) / radius(e), (y - cy(e)) / radiusY(e)) private fun hit(list: List, x: Float, y: Float): Element? = list.filter { reach(it, x, y) <= 1.15f }.minByOrNull { reach(it, x, y) } @@ -285,61 +281,58 @@ class SteamTouchControls( val r = radius(e) val pressed = !editing && e.type in pressedTypes() val alpha = (255 * alphaScale * if (faded) FADED else 1f).toInt().coerceIn(30, 255) - stroke.color = Color.rgb(Color.red(tint), Color.green(tint), Color.blue(tint)); stroke.strokeWidth = lineWidth() - fill.color = Color.argb(217, 230, 233, 236) - if (alpha < 255) canvas.saveLayerAlpha(x - r * 1.5f, y - r * 1.5f, x + r * 1.5f, y + r * 1.5f, alpha) + val ink = Color.argb(alpha, Color.red(tint), Color.green(tint), Color.blue(tint)) + stroke.color = if (isSelected) Color.rgb(26, 159, 255) else ink + stroke.strokeWidth = if (isSelected) lineWidth() * 2f else lineWidth() + fill.color = Color.argb((alpha * 0.85f).toInt(), 230, 233, 236) + text.color = ink + text.typeface = android.graphics.Typeface.DEFAULT_BOLD when (e.type) { - SteamTouchConfig.DPAD -> if (visuals[SteamTouchConfig.DPAD].orEmpty().any { it.binding?.hasIcon == true }) drawDpad(canvas, e, x, y, r) else { - val bits = if (editing) 0L else dpadBits(e) - val held = (if (bits and DPAD_UP != 0L) 1 else 0) or (if (bits and DPAD_RIGHT != 0L) 2 else 0) or - (if (bits and DPAD_DOWN != 0L) 4 else 0) or (if (bits and DPAD_LEFT != 0L) 8 else 0) - canvas.save(); canvas.translate(x - r, y - r) - art.dpad(canvas, 2 * r, 2 * r, PadKit.STEAM_DECK, held, ink = glyphInk()) - canvas.restore() - } + SteamTouchConfig.DPAD -> drawDpad(canvas, e, x, y, r) SteamTouchConfig.JOYSTICK_LEFT, SteamTouchConfig.JOYSTICK_RIGHT -> { - val f = fingers.values.firstOrNull { it.element?.type == e.type }.takeIf { !editing } - var kx = 0f; var ky = 0f - if (f != null) { + canvas.drawCircle(x, y, r, stroke) + val f = fingers.values.firstOrNull { it.element?.type == e.type } + if (f != null && !editing) { val d = hypot(f.x - x, f.y - y) val k = if (d > r) r / d else 1f - kx = (f.x - x) * k * .54f; ky = (f.y - y) * k * .54f + val kx = x + (f.x - x) * k + val ky = y + (f.y - y) * k + canvas.drawCircle(kx, ky, r * 0.42f, fill) } - art.stick(canvas, x, y, r, PadKit.STEAM_DECK, kx, ky, f != null) } SteamTouchConfig.TRACKPAD_LEFT, SteamTouchConfig.TRACKPAD_RIGHT, SteamTouchConfig.TRACKPAD_CENTER -> { - val f = fingers.values.firstOrNull { it.element?.type == e.type }.takeIf { !editing } - canvas.save(); canvas.translate(x - r, y - r) - art.trackpad(canvas, r * 2f, r * 2f, f != null, (f?.x ?: x) - x + r, (f?.y ?: y) - y + r) - canvas.restore() - if (editing) art.text(canvas, context.getString(R.string.deck_surface_trackpad), x, y, r * .3f, Color.argb(128, 255, 255, 255)) + val rect = RectF(x - r * 1.3f, y - r * 0.85f, x + r * 1.3f, y + r * 0.85f) + if (pressed) canvas.drawRoundRect(rect, r * 0.18f, r * 0.18f, fill) + canvas.drawRoundRect(rect, r * 0.18f, r * 0.18f, stroke) + if (editing) { + text.textSize = r * 0.3f + text.color = Color.argb(alpha / 2, 255, 255, 255) + canvas.drawText(context.getString(R.string.deck_surface_trackpad), x, y - (text.descent() + text.ascent()) / 2, text) + } + } + SteamTouchConfig.STEAM -> { + if (isSelected) canvas.drawCircle(x, y, r, stroke) + drawMark(canvas, x, y, r * 0.5f, if (pressed) accent else ink, alpha) } - SteamTouchConfig.STEAM -> systemButton(canvas, x, y, r, com.droiddeck.launcher.ui.PadArt.Shape.PILL, com.droiddeck.launcher.ui.PadArt.Icon.STEAM, pressed) SteamTouchConfig.SELECT, SteamTouchConfig.START -> { val binding = visuals[e.type]?.firstOrNull()?.binding - if (binding?.hasIcon == true) drawFace(canvas, e.type, binding, x, y, r, pressed) - else systemButton(canvas, x, y, r, com.droiddeck.launcher.ui.PadArt.Shape.CHIP, - if (e.type == SteamTouchConfig.START) com.droiddeck.launcher.ui.PadArt.Icon.MENU else com.droiddeck.launcher.ui.PadArt.Icon.VIEW, pressed) + if (binding?.hasIcon == true) { + drawFace(canvas, e.type, binding, x, y, r, alpha, pressed); return + } + val rect = RectF(x - r * 1.08f, y - r * 0.55f, x + r * 1.08f, y + r * 0.55f) + if (pressed) canvas.drawRoundRect(rect, r * 0.5f, r * 0.5f, fill) + canvas.drawRoundRect(rect, r * 0.5f, r * 0.5f, stroke) + val t = r * 0.26f + val dir = if (e.type == SteamTouchConfig.START) 1f else -1f + val tri = Path().apply { + moveTo(x + dir * t, y); lineTo(x - dir * t * 0.75f, y - t); lineTo(x - dir * t * 0.75f, y + t); close() + } + canvas.drawPath(tri, Paint(Paint.ANTI_ALIAS_FLAG).apply { color = if (pressed) Color.argb(alpha, 23, 26, 33) else ink }) } - else -> drawFace(canvas, e.type, visuals[e.type]?.firstOrNull()?.binding, x, y, r, pressed) - } - if (alpha < 255) canvas.restore() - if (isSelected) { - stroke.color = accent; stroke.strokeWidth = lineWidth() * 2f - if (isSquare(e.type)) canvas.drawRoundRect(RectF(x - r, y - r, x + r, y + r), r * .3f, r * .3f, stroke) else canvas.drawCircle(x, y, r, stroke) + else -> drawFace(canvas, e.type, visuals[e.type]?.firstOrNull()?.binding, x, y, r, alpha, pressed) } } - private fun systemButton(canvas: Canvas, x: Float, y: Float, r: Float, shape: com.droiddeck.launcher.ui.PadArt.Shape, - icon: com.droiddeck.launcher.ui.PadArt.Icon, pressed: Boolean) { - canvas.save(); canvas.translate(x - r * 1.4f, y - r * 1.4f) - art.system(canvas, r * 2.8f, r * 2.8f, shape, icon, pressed, glyphInk()) - canvas.restore() - } - - /** Glyphs follow the colour picked for Steam touch controls; white keeps the shared artwork's own ink. */ - private fun glyphInk() = if (tint != Color.WHITE) tint else com.droiddeck.launcher.ui.PadArt.INK - private fun isSquare(type: Int) = type in setOf(SteamTouchConfig.BUMPER_LEFT, SteamTouchConfig.BUMPER_RIGHT, SteamTouchConfig.TRIGGER_LEFT, SteamTouchConfig.TRIGGER_RIGHT, SteamTouchConfig.THUMB, SteamTouchConfig.KEYBOARD, SteamTouchConfig.PASTE, SteamTouchConfig.MACRO_1_FINGER, SteamTouchConfig.MACRO_2_FINGER) || @@ -357,29 +350,53 @@ class SteamTouchControls( canvas.restore() } - private fun drawFace(canvas: Canvas, type: Int, binding: SteamTouchBindings.Binding?, x: Float, y: Float, r: Float, pressed: Boolean) { - val shape = if (isSquare(type)) art.roundRect(x - r, y - r, x + r, y + r, r * .3f) else art.circle(x, y, r) + private fun drawFace(canvas: Canvas, type: Int, binding: SteamTouchBindings.Binding?, x: Float, y: Float, r: Float, + alpha: Int, pressed: Boolean) { + val square = isSquare(type) + val rect = RectF(x - r, y - r, x + r, y + r) + val corner = r * 0.3f + fun shape(paint: Paint) = if (square) canvas.drawRoundRect(rect, corner, corner, paint) else canvas.drawCircle(x, y, r, paint) val icon = binding?.icon?.takeIf { it.isNotEmpty() }?.let(::iconOrLoad) - val custom = binding != null && binding.background.isNotEmpty() && !binding.background.equals(SteamTouchBindings.DEFAULT_BACKGROUND, true) - art.glass(canvas, shape, pressed && !custom, if (custom) parseColor(binding!!.background, SteamTouchBindings.DEFAULT_BACKGROUND) else 0x850E1014.toInt()) - val ink = if (pressed && !custom) com.droiddeck.launcher.ui.PadArt.ON_ACCENT else glyphInk() if (icon != null) { val s = r * 0.62f - if (custom) canvas.drawBitmap(tinted(binding!!.icon, icon, binding.foreground), null, RectF(x - s, y - s, x + s, y + s), Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)) - else canvas.drawBitmap(inked(binding!!.icon, icon), null, RectF(x - s, y - s, x + s, y + s), - Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG).apply { colorFilter = android.graphics.PorterDuffColorFilter(ink, android.graphics.PorterDuff.Mode.SRC_IN) }) + val custom = binding.background.isNotEmpty() && !binding.background.equals(SteamTouchBindings.DEFAULT_BACKGROUND, true) + if (custom) { + shape(Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = parseColor(binding.background, SteamTouchBindings.DEFAULT_BACKGROUND) + this.alpha = if (pressed) alpha else (alpha * 0.85f).toInt() + }) + canvas.drawBitmap(tinted(binding.icon, icon, binding.foreground), null, RectF(x - s, y - s, x + s, y + s), + Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG).apply { this.alpha = alpha }) + } else { + if (pressed) shape(fill) + val ink = if (pressed) Color.argb(alpha, 23, 26, 33) else stroke.color + canvas.drawBitmap(inked(binding.icon, icon), null, RectF(x - s, y - s, x + s, y + s), + Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG).apply { + colorFilter = android.graphics.PorterDuffColorFilter(ink, android.graphics.PorterDuff.Mode.SRC_IN) + }) + } + shape(stroke) return } - if (type == SteamTouchConfig.THUMB) { art.icon(canvas, x, y, r * 1.1f, com.droiddeck.launcher.ui.PadArt.Icon.QAM, ink); return } - if (type == SteamTouchConfig.KEYBOARD) { art.icon(canvas, x, y, r * 1.1f, com.droiddeck.launcher.ui.PadArt.Icon.KEYBOARD, ink); return } - val shown = label(type) - val size = when { + if (pressed) shape(fill) + shape(stroke) + if (type == SteamTouchConfig.THUMB) { drawDots(canvas, x, y, r, if (pressed) Color.argb(alpha, 23, 26, 33) else text.color); return } + if (type == SteamTouchConfig.KEYBOARD) { drawKeyboardGlyph(canvas, x, y, r, if (pressed) Color.argb(alpha, 23, 26, 33) else text.color); return } + val own = label(type) + val shown = own + text.textSize = when { shown.length <= 1 -> r * 0.9f shown.length <= 2 -> r * 0.66f shown.length <= 5 -> r * 0.4f else -> r * 0.3f } - art.text(canvas, if (shown.length > 10) shown.take(9) + "…" else shown, x, y, size, ink, r * 1.8f) + text.color = when { + pressed -> Color.argb(alpha, 23, 26, 33) + shown == own -> LABEL_COLORS[type]?.let { Color.argb(alpha, Color.red(it), Color.green(it), Color.blue(it)) } ?: text.color + else -> text.color + } + val line = if (shown.length > 10) shown.take(9) + "…" else shown + canvas.drawText(line, x, y - (text.descent() + text.ascent()) / 2, text) } private fun drawDots(canvas: Canvas, x: Float, y: Float, r: Float, color: Int) { @@ -387,6 +404,15 @@ class SteamTouchControls( for (i in -1..1) canvas.drawCircle(x + i * r * 0.3f, y + r * 0.22f, r * 0.08f, p) } + private fun drawKeyboardGlyph(canvas: Canvas, x: Float, y: Float, r: Float, color: Int) { + val p = Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = color; style = Paint.Style.STROKE; strokeWidth = lineWidth() * 0.8f } + val body = RectF(x - r * 0.6f, y - r * 0.34f, x + r * 0.6f, y + r * 0.34f) + canvas.drawRoundRect(body, r * 0.08f, r * 0.08f, p) + val dot = Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = color } + for (row in 0..1) for (i in 0..5) canvas.drawCircle(body.left + r * 0.15f + i * r * 0.18f, body.top + r * 0.18f + row * r * 0.17f, r * 0.035f, dot) + canvas.drawLine(x - r * 0.3f, body.bottom - r * 0.14f, x + r * 0.3f, body.bottom - r * 0.14f, p) + } + private val iconsLoading = HashSet() private val inkedIcons = android.util.LruCache(48) @@ -1452,7 +1478,6 @@ class SteamTouchControls( var onSaved: () -> Unit = {} companion object { - private val TRACKPADS = setOf(SteamTouchConfig.TRACKPAD_LEFT, SteamTouchConfig.TRACKPAD_RIGHT, SteamTouchConfig.TRACKPAD_CENTER) private const val TAG = "SteamTouch" private const val POLL_MS = 150L private const val MOVE_REDRAW_MS = 33L @@ -1494,5 +1519,11 @@ class SteamTouchControls( put(SteamTouchConfig.PASTE, 0L) } + private val LABEL_COLORS = mapOf( + SteamTouchConfig.A to Color.rgb(72, 133, 48), + SteamTouchConfig.B to Color.rgb(211, 68, 37), + SteamTouchConfig.X to Color.rgb(23, 60, 184), + SteamTouchConfig.Y to Color.rgb(235, 200, 70), + ) } } diff --git a/app/src/main/java/com/droiddeck/launcher/input/TritonInputRouter.kt b/app/src/main/java/com/droiddeck/launcher/input/TritonInputRouter.kt index cbc3659fc1..c85b4ffa94 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/TritonInputRouter.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/TritonInputRouter.kt @@ -63,25 +63,16 @@ class TritonInputRouter(private val router: InputRouter) { fun release() = synchronized(router) { channels.forEach { it.release() }; last = null } fun close() = synchronized(router) { release(); channels.forEach { it.close() }; router.removeSnapshot(snapshot) } + private fun bits(data: ByteArray): Int = (data[1].toInt() and 255) or ((data[2].toInt() and 255) shl 8) or + ((data[3].toInt() and 255) shl 16) or ((data[4].toInt() and 255) shl 24) private fun putBits(data: ByteArray, value: Int) { for (i in 0..3) data[i + 1] = (value ushr (i * 8)).toByte() } + private fun short(data: ByteArray, offset: Int) = ((data[offset].toInt() and 255) or (data[offset + 1].toInt() shl 8)).toShort().toInt() private fun axis(data: ByteArray, offset: Int): Float = short(data, offset).let { it / if (it < 0) 32768f else 32767f } private fun shortValue(value: Float) = (value * if (value < 0f) 32768f else 32767f).roundToInt().coerceIn(-32768, 32767) private fun putShort(data: ByteArray, offset: Int, value: Int) { data[offset] = value.toByte(); data[offset + 1] = (value shr 8).toByte() } companion object { private const val CONTROL_BITS = 0x0fffffff - - internal fun pressedControls(data: ByteArray): Int { - var active = bits(data) and CONTROL_BITS - if ((5..15 step 2).any { kotlin.math.abs(short(data, it)) > 16384 }) active = active or (1 shl 28) - return active - } - - private fun bits(data: ByteArray): Int = (data[1].toInt() and 255) or ((data[2].toInt() and 255) shl 8) or - ((data[3].toInt() and 255) shl 16) or ((data[4].toInt() and 255) shl 24) - - private fun short(data: ByteArray, offset: Int) = - ((data[offset].toInt() and 255) or (data[offset + 1].toInt() shl 8)).toShort().toInt() private fun bit(c: InputControl): Int = when (c) { InputControl.A -> 0x1; InputControl.B -> 0x2; InputControl.X -> 0x4; InputControl.Y -> 0x8 InputControl.QAM -> 0x10; InputControl.R3 -> 0x20; InputControl.START -> 0x40 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/DeviceControlsComponent.kt b/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt index 0f5c48ce21..e589c5c8b5 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt @@ -17,6 +17,9 @@ import android.provider.Settings import android.util.Log import com.droiddeck.launcher.core.SessionPart import com.droiddeck.launcher.R +import com.droiddeck.launcher.session.SessionHdr +import com.droiddeck.launcher.session.SessionPrefs +import com.droiddeck.launcher.session.SessionState import java.io.File import java.nio.file.Files import java.nio.file.StandardCopyOption @@ -74,8 +77,10 @@ class DeviceControlsComponent(context: Context, root: File, private val activity val value = Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 128) write("backlight/droiddeck/brightness", "$value\n") write("backlight/droiddeck/actual_brightness", "$value\n") - val state = JSONObject().put("brightness", (value.coerceIn(1, 255) - 1) / 254.0) - .put("brightnessWritable", Settings.System.canWrite(context)).toString() + val controls = JSONObject().put("brightness", (value.coerceIn(1, 255) - 1) / 254.0) + .put("brightnessWritable", Settings.System.canWrite(context)) + if (SessionState.hdrCapable) controls.put("hdr", SessionState.hdr) + val state = controls.toString() if (force || state != previous) { write("state.json", JSONObject(state).put("revision", ++revision).toString()) previous = state @@ -132,6 +137,9 @@ class DeviceControlsComponent(context: Context, root: File, private val activity audio.setStreamVolume(AudioManager.STREAM_MUSIC, it.coerceIn(0, audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC)), 0) } + "hdr.request" -> if (text == "0" || text == "1") { + SessionHdr.set(context, SessionPrefs.prefMode(SessionState.mode), text == "1") + } "mute.request" -> if (text == "0" || text == "1") { audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, if (text == "1") AudioManager.ADJUST_MUTE else AudioManager.ADJUST_UNMUTE, 0) @@ -196,7 +204,7 @@ class DeviceControlsComponent(context: Context, root: File, private val activity private const val STREAM_MUTE_CHANGED_ACTION = "android.media.STREAM_MUTE_CHANGED_ACTION" private const val PERMISSION_CHANNEL = "brightness_permission" private const val PERMISSION_NOTIFICATION = 0x4442 - private val REQUESTS = setOf("brightness.request", "volume.request", "mute.request") + private val REQUESTS = setOf("brightness.request", "volume.request", "mute.request", "hdr.request") @JvmStatic fun directory(root: File) = File(root, "etc/droiddeck-device-controls") @JvmStatic fun prepareBacklight(context: Context, root: File): File { val base = File(directory(root), "backlight") diff --git a/app/src/main/java/com/droiddeck/launcher/session/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 109f6d282a..0000000000 --- a/app/src/main/java/com/droiddeck/launcher/session/KeepTopActivity.kt +++ /dev/null @@ -1,120 +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.MotionEvent -import android.view.WindowManager - -// While a session is on screen, sits invisibly on top of every other display, 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. -// Android gives a translucent activity alone in its task an input sink that eats every touch on the -// display whatever its window flags say, so a touch makes the guard leave that display until the -// session is back on top. -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_FOCUSABLE) - val id = display?.displayId ?: Display.INVALID_DISPLAY - starting.remove(id) - if (id in yielded) { - finishAndRemoveTask() - return - } - guards[id]?.takeIf { it !== this && !it.isFinishing }?.finishAndRemoveTask() - guards[id] = this - } - - override fun dispatchTouchEvent(event: MotionEvent): Boolean { - if (event.actionMasked == MotionEvent.ACTION_DOWN && !isFinishing) { - val id = display?.displayId ?: Display.INVALID_DISPLAY - yielded.add(id) - Log.i(TAG, "display $id touched, leaving it to the app below") - finishAndRemoveTask() - onYield?.invoke() - } - return true - } - - 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() - private val yielded = HashSet() - const val YIELD_GRACE_MS = 5_000L - var onYield: (() -> Unit)? = null - - fun rearm() = yielded.clear() - - 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 || id in yielded || 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 stepAside() { - generation++ - guards.values.toList().forEach { it.finishAndRemoveTask() } - guards.clear() - starting.clear() - } - - fun release() { - stepAside() - yielded.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/SessionDisplay.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt index 2c11ffcabf..9b253d88a7 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt @@ -69,18 +69,8 @@ object SessionDisplay { const val UNFOLDED_MIN_DP = 600 - /** - * The game's share of a screen with the controls below it, at the game's [aspect] across the full width. A tab row under the bar - * comes out of the controls while they keep [UNFOLDED_MIN_CONTROLS_SHARE] of the screen, and out of the game otherwise. - */ - fun unfoldedGameHeight(width: Int, height: Int, tabRow: Int = 0, aspect: Float = 16f / 9f): Int { - val game = minOf((width / aspect.coerceAtLeast(.5f)).toInt(), (height * UNFOLDED_MAX_GAME_SHARE).toInt()) - val tabs = tabRow.coerceAtLeast(0) - val roomy = height - game - tabs >= height * UNFOLDED_MIN_CONTROLS_SHARE - return (if (roomy) game else game - tabs).coerceAtLeast(0) and 1.inv() - } - - const val UNFOLDED_MIN_CONTROLS_SHARE = .45f + 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 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..1082de60d5 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) @@ -284,6 +287,7 @@ object SessionFiles { File(root, "usr/share/vulkan/implicit_layer.d/droiddeck_vram_cap.json").delete() LegacyNames.migrateRootfs(root) ComponentsManager.migrateLaunchDir(context) + runCatching { ComponentsManager.migrateBattleNetFex(context) }.onFailure { Log.w(TAG, "Battle.net FEX selection", it) } EsyncPacks.stageBundled(context, root) val directAudio = arrayOf( "aarch64-unix/winedirectaudio.so", diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionHdr.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionHdr.kt new file mode 100644 index 0000000000..e559ac4ff0 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionHdr.kt @@ -0,0 +1,36 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import com.droiddeck.launcher.agent.AgentGuest +import com.droiddeck.launcher.wayland.CompositorHost +import com.droiddeck.launcher.wayland.WaylandCompositor +import java.util.concurrent.Executors + +object SessionHdr { + private const val RETRIES = 5 + private const val RETRY_MS = 2_000L + + private val requests = Executors.newSingleThreadExecutor { runnable -> + Thread(runnable, "session-hdr").apply { isDaemon = true } + } + @Volatile private var wanted = false + + fun set(context: Context, mode: String, on: Boolean) { + SessionPrefs.setHdr(context, mode, on) + if (!SessionState.running || !SessionState.hdrCapable || !CompositorHost.isStarted) return + if (SessionPrefs.prefMode(SessionState.mode) != mode) return + SessionState.hdr = on + wanted = on + WaylandCompositor.nativeSetHdrOutput(on) + WaylandCompositor.nativeSetZeroCopy(on || SessionPrefs.zeroCopy(context, mode)) + val app = context.applicationContext + val session = SessionState.sessionId + requests.execute { + var tries = 0 + while (wanted == on && SessionState.running && SessionState.sessionId == session && + !AgentGuest.setGamescopeConvar(app, "hdr_enabled", if (on) 1 else 0) && tries++ < RETRIES) { + try { Thread.sleep(RETRY_MS) } catch (e: InterruptedException) { return@execute } + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 5f62fec93a..826cfac74a 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -85,6 +85,12 @@ object SessionPrefs { prefs(context).edit().putBoolean("launcherFullscreen", on).apply() } + fun controllerHaptics(context: Context): Boolean = prefs(context).getBoolean("controllerHaptics", true) + + fun setControllerHaptics(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("controllerHaptics", on).apply() + } + fun blackFrameInsertion(context: Context): Boolean = prefs(context).getBoolean("blackFrameInsertion", false) fun setBlackFrameInsertion(context: Context, on: Boolean) { @@ -419,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() } @@ -664,27 +682,20 @@ object SessionPrefs { prefs(context).getString("shape", null) ?: if (context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle")) SHAPE_WIDE else SHAPE_AUTO - /** Auto, Always or Never. Older builds also stored the Steam layout and a buttons-only mode here. */ - fun oscMode(context: Context, steamSession: Boolean = false): String = when (val mode = prefs(context).getString("osc", OSC_AUTO)) { - OSC_ALWAYS, OSC_NEVER -> mode - OSC_STEAM_QAM -> OSC_ALWAYS - OSC_STEAM_TOUCH -> if (steamSession) OSC_ALWAYS else OSC_AUTO - else -> 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) { - val editor = prefs(context).edit() - if (!prefs(context).contains("steamTouchLayout")) editor.putBoolean("steamTouchLayout", steamTouchLayout(context)) - editor.putString("osc", mode).apply() + prefs(context).edit().putString("osc", mode).apply() } - /** Draw Steam's touch layout for the game instead of DroidDeck's own. */ - fun steamTouchLayout(context: Context): Boolean = - prefs(context).getBoolean("steamTouchLayout", prefs(context).getString("osc", null) == OSC_STEAM_TOUCH) + fun oscRearButtons(context: Context): Boolean = prefs(context).getBoolean("oscRearButtons", false) + fun setOscRearButtons(context: Context, shown: Boolean) { prefs(context).edit().putBoolean("oscRearButtons", shown).apply() } - fun setSteamTouchLayout(context: Context, on: Boolean) { - prefs(context).edit().putBoolean("steamTouchLayout", on).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) @@ -842,6 +853,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) @@ -1633,10 +1650,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 @@ -1962,7 +1987,7 @@ object SessionPrefs { prefs(context).edit().putBoolean("pipAutoEnter", enabled).apply() } - fun unfoldedControls(context: Context): Boolean = prefs(context).getBoolean("unfoldedControls", true) + fun unfoldedControls(context: Context): Boolean = prefs(context).getBoolean("unfoldedControls", false) fun controlsBelowWanted(context: Context, mode: String, width: Int, height: Int, pip: Boolean = false): Boolean = SessionDisplay.unfoldedControlsWanted( 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 32f6e1e5d2..351cc7332e 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) @@ -1026,6 +1029,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()) { @@ -1614,6 +1620,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 @@ -1944,11 +1955,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 @@ -2395,8 +2401,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..847ed340b6 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt @@ -115,6 +115,10 @@ object SessionState { @JvmStatic var hdr = false + @JvmStatic var hdrCapable = false + + @JvmStatic var hdrDisplay = false + @Volatile private var deckPadValue = false @JvmStatic var deckPad: Boolean get() = deckPadValue diff --git a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt index f85318b595..2bb6190ce5 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt @@ -12,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", "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/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/ui/ControllerHaptics.kt b/app/src/main/java/com/droiddeck/launcher/ui/ControllerHaptics.kt new file mode 100644 index 0000000000..8f06cd50af --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/ControllerHaptics.kt @@ -0,0 +1,41 @@ +package com.droiddeck.launcher.ui + +import android.content.Context +import android.os.Build +import android.os.VibrationEffect +import android.os.Vibrator +import android.os.VibratorManager +import android.view.InputDevice +import android.view.KeyEvent + +object ControllerHaptics { + private val navKeys = setOf( + KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT, + KeyEvent.KEYCODE_BUTTON_A, KeyEvent.KEYCODE_BUTTON_L1, KeyEvent.KEYCODE_BUTTON_R1, + ) + + fun onKey(context: Context, event: KeyEvent) { + if (event.action != KeyEvent.ACTION_DOWN || event.keyCode !in navKeys) return + if (event.keyCode == KeyEvent.KEYCODE_BUTTON_A && event.repeatCount > 0) return + val fromController = event.isFromSource(InputDevice.SOURCE_GAMEPAD) || + event.isFromSource(InputDevice.SOURCE_DPAD) || event.isFromSource(InputDevice.SOURCE_JOYSTICK) + if (!fromController) return + tick(context) + } + + fun tick(context: Context) { + val vibrator = if (Build.VERSION.SDK_INT >= 31) { + context.getSystemService(VibratorManager::class.java)?.defaultVibrator + } else { + @Suppress("DEPRECATION") context.getSystemService(Context.VIBRATOR_SERVICE) as? Vibrator + } ?: return + if (!vibrator.hasVibrator()) return + if (Build.VERSION.SDK_INT >= 29) { + vibrator.vibrate(VibrationEffect.createPredefined(VibrationEffect.EFFECT_TICK)) + } else if (Build.VERSION.SDK_INT >= 26) { + vibrator.vibrate(VibrationEffect.createOneShot(10, VibrationEffect.DEFAULT_AMPLITUDE)) + } else { + @Suppress("DEPRECATION") vibrator.vibrate(10) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt b/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt index 04cd21cf7d..21057d1dea 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt @@ -152,7 +152,7 @@ internal fun SessionDrawerPreview(secondScreens: List) { suspendPolicy = suspend, onSuspendPolicy = { suspend = it }, backActionsInverted = inverted, onBackActionsInverted = { inverted = it }, touchMode = touch, onTouch = { touch = it }, - touchAuto = stringResource(R.string.mode_touch_mouse), + touchAuto = stringResource(R.string.session_touch_auto_direct), fexPreset = fex, onFexPreset = { fex = it }, fpsLimit = fps, onFpsLimit = { fps = it }, secondScreenMode = second, onSecondScreenMode = { second = it }, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt index 2267bef930..b74e179384 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -174,6 +174,7 @@ class FrontEndState( val launcherOrientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER, val homePage: String = com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM, val launcherFullscreen: Boolean = true, + val controllerHaptics: Boolean = true, val downloadSource: String = DownloadSource.MODE_AUTO, val downloadMirror: String = "", val downloadPrefix: String = "", @@ -279,6 +280,7 @@ class FrontEndActions( val onLauncherOrientation: (Int) -> Unit = {}, val onHomePage: (String) -> Unit = {}, val onLauncherFullscreen: (Boolean) -> Unit = {}, + val onControllerHaptics: (Boolean) -> Unit = {}, val onAnimationsEnabled: (Boolean) -> Unit = {}, val onLowStorageWarning: (Boolean) -> Unit = {}, val onDualScreenMode: (String) -> Unit = {}, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt index b7976c89dd..ec3b1c1b55 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -516,6 +516,11 @@ internal fun SetupPanel( if (s.launcherFullscreen) stringResource(R.string.setup_fullscreen_on) else stringResource(R.string.setup_fullscreen_off), s.launcherFullscreen, ) { a.onLauncherFullscreen(it) } + ToggleRow( + host, "controller-haptics", stringResource(R.string.setup_controller_haptics), + stringResource(R.string.setup_controller_haptics_hint), + s.controllerHaptics, + ) { a.onControllerHaptics(it) } if (s.dualScreenDevice) { val dualModes = listOf( com.droiddeck.launcher.input.DualScreen.MODE_AUTO to stringResource(R.string.setup_dual_screen_auto), diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputElementProperties.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputElementProperties.kt index 63257a313f..406e6f7f5f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputElementProperties.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputElementProperties.kt @@ -38,7 +38,7 @@ internal fun InputElementProperties(element: InputSurfaceElement, action: InputA withContext(Dispatchers.IO) { InputButtonImages.import(context.applicationContext, uri) }?.let { change(current.copy(icon = 0, image = it)) } } } - ToggleRow(host, "element-toggle", stringResource(R.string.input_toggle_button), null, element.toggle) { onChange(element.copy(toggle = it)) } + ToggleRow(host, "element-toggle", stringResource(R.string.input_toggle_button), stringResource(R.string.input_toggle_button_hint), element.toggle) { onChange(element.copy(toggle = it)) } ChoiceRow(host, "element-shape", stringResource(R.string.input_button_shape), null, InputButtonShape.entries.map { it to stringResource(when (it) { InputButtonShape.ROUNDED -> R.string.input_shape_rounded; InputButtonShape.PILL -> R.string.input_shape_pill; InputButtonShape.CIRCLE -> R.string.input_shape_circle; InputButtonShape.RECTANGLE -> R.string.input_shape_rectangle }) }, element.buttonShape) { onChange(element.copy(buttonShape = it)) } @@ -63,7 +63,7 @@ internal fun InputElementProperties(element: InputSurfaceElement, action: InputA } } if (element.kind == InputElementKind.TRACKPAD) { - ToggleRow(rememberMenuHost(), "element-mouse-gestures", stringResource(R.string.input_mouse_gestures), null, element.mouseGestures) { onChange(element.copy(mouseGestures = it)) } + ToggleRow(rememberMenuHost(), "element-mouse-gestures", stringResource(R.string.input_mouse_gestures), stringResource(R.string.input_mouse_gestures_hint), element.mouseGestures) { onChange(element.copy(mouseGestures = it)) } } if (element.kind == InputElementKind.STICK) { val host = rememberMenuHost() diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputLayoutWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputLayoutWidgets.kt index 414105ee69..47952e8502 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputLayoutWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputLayoutWidgets.kt @@ -3,16 +3,54 @@ package com.droiddeck.launcher.ui import android.content.Context import android.graphics.Canvas import android.view.View +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.compose.ui.viewinterop.AndroidView +import com.droiddeck.launcher.R import com.droiddeck.launcher.input.* +@Composable +internal fun InputLayoutRow(layout: SavedInputLayout, role: InputRole, detail: String?, onManage: () -> Unit, onPick: () -> Unit) { + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Row(Modifier.weight(1f).focusRow(onClick = onPick).padding(12.dp), + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { + InputLayoutThumbnail(layout, role) + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text(layout.name, style = MaterialTheme.typography.titleMedium) + Text(detail ?: stringResource(R.string.input_layout_count, layout.elements.size), + style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + PadTextButton(onClick = onManage, modifier = Modifier.testTag("layout-manage-${layout.id}")) { Text("⋮", style = MaterialTheme.typography.titleLarge) } + } +} + +@Composable +internal fun InputLayoutThumbnail(layout: SavedInputLayout, role: InputRole) { + AndroidView(factory = { InputLayoutPreviewView(it) }, modifier = Modifier.width(112.dp).height(76.dp).testTag("layout-preview-${layout.id}"), + update = { it.update(layout, role) }) +} + internal class InputLayoutPreviewView(context: Context) : View(context) { private val renderer = InputSurfaceView(context) private var sourceHeight = 563 fun update(layout: SavedInputLayout, role: InputRole) { sourceHeight = if (role == InputRole.PRIMARY) 563 else 870 - renderer.measure(MeasureSpec.makeMeasureSpec(1000, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(sourceHeight, MeasureSpec.EXACTLY)) - renderer.layout(0, 0, 1000, sourceHeight) - renderer.showLayout(layout.copy(style = layout.style.copy(opacity = 100))) + val primary = role == InputRole.PRIMARY + val artwork = if (primary) PadKit.forOverlay(context, layout) else null + val elements = if (artwork != null) OnScreenLayout.editorElements(context, layout, 1000, sourceHeight) else layout.elements + renderer.updateCustomLayout(elements) + renderer.updateStyle(layout.style.copy(opacity = 100), artwork) renderer.measure(MeasureSpec.makeMeasureSpec(1000, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(sourceHeight, MeasureSpec.EXACTLY)) renderer.layout(0, 0, 1000, sourceHeight) contentDescription = layout.name @@ -30,4 +68,28 @@ internal class InputLayoutPreviewView(context: Context) : View(context) { } } +@Composable +internal fun InputColorRow(host: MenuHost, value: Int?, onPick: (Int?) -> Unit) { + val open = host.open == "layout-color" + val tints = listOf>(null to R.string.ctrl_tint_gray) + ControllerPrefs.tints + SettingsRow(stringResource(R.string.ctrl_color), null, highlighted = open) { + Box { + ValueChip(tints.firstOrNull { it.first == value }?.second?.let { stringResource(it) } + ?: stringResource(R.string.ctrl_custom), open, modifier = Modifier.testTag("setting-layout-color")) { + host.open = if (open) null else "layout-color" + } + AnchoredMenu(open, onDismiss = { if (host.open == "layout-color") host.open = null }, title = stringResource(R.string.ctrl_color)) { firstItemFocus -> + tints.forEachIndexed { index, (color, name) -> + MenuItem(stringResource(name), checked = value == color, leading = { + Box(Modifier.size(14.dp).background(Color(color ?: GRAY_SWATCH), CircleShape).border(1.dp, Color.White.copy(alpha = .35f), CircleShape)) + }, focusRequester = if (index == 0) firstItemFocus else null) { + onPick(color) + host.open = null + } + } + } + } + } +} + private const val GRAY_SWATCH = 0xFF26292E.toInt() diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputQuickSettings.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputQuickSettings.kt new file mode 100644 index 0000000000..3e53e3cce1 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputQuickSettings.kt @@ -0,0 +1,81 @@ +package com.droiddeck.launcher.ui + +import android.content.Context +import android.content.SharedPreferences +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.ui.Alignment +import androidx.compose.ui.unit.dp +import androidx.compose.ui.platform.testTag +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import com.droiddeck.launcher.R +import com.droiddeck.launcher.input.* + +@Composable +internal fun InputQuickSettings(host: MenuHost, desktop: Boolean, onChanged: (InputRole?) -> Unit = {}, onEdit: () -> Unit = {}, track: (String) -> Modifier = { Modifier }) { + val context = LocalContext.current + var library by remember { mutableStateOf(InputLibraries.read(context)) } + var expanded by remember { mutableStateOf(false) } + var naming by remember { mutableStateOf(false) } + var failure by remember { mutableStateOf(null) } + DisposableEffect(context) { + val preferences = context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE) + val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, key -> if (key == "library") library = InputLibraries.read(context) } + preferences.registerOnSharedPreferenceChangeListener(listener) + onDispose { preferences.unregisterOnSharedPreferenceChangeListener(listener) } + } + fun update(role: InputRole?, change: (InputLibrary) -> InputLibrary) { + runCatching { InputLibraries.update(context, change) }.onSuccess { library = it; onChanged(role) } + .onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) } + } + val selection = library.selection(desktop) + val mixed = selection.parts.isNotEmpty() + val active = library.profile(library.activeId(desktop)) + val profiles = listOf(InputProfiles.AUTO to stringResource(R.string.input_quick_auto, if (desktop) library.profile(library.desktop).name else library.profile(library.steam).name)) + + library.profiles.map { it.id to it.name } + if (mixed) listOf("mixed" to stringResource(R.string.input_quick_mixed, active.name)) else emptyList() + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Row(Modifier.weight(1f).focusRow { expanded = !expanded }.padding(14.dp).testTag("input-profile-expand"), + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { + Text(if (expanded) "▾" else "▸", color = MaterialTheme.colorScheme.onSurface) + Text(stringResource(R.string.input_profile), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onSurface) + } + Box(Modifier.padding(end = 14.dp).widthIn(max = 280.dp)) { + ChoiceChip(host, "input-profile", stringResource(R.string.input_profile), profiles, if (mixed) "mixed" else selection.profile, + modifier = track("input-profile")) { id -> if (id != "mixed") update(null) { it.selectProfile(desktop, id) } } + } + } + if (expanded) Surface( + modifier = Modifier.fillMaxWidth().padding(start = 18.dp, end = 12.dp, bottom = 14.dp).testTag("input-profile-parts"), + shape = RoundedCornerShape(12.dp), + color = MaterialTheme.colorScheme.primary.copy(alpha = .08f), + border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = .35f)), + ) { + Column(Modifier.padding(vertical = 6.dp)) { + for (role in InputRole.entries) { + val options = library.bindings.filter { binding -> + if (role == InputRole.PHYSICAL) binding.physical + else !binding.physical && library.layouts.any { it.id == binding.layoutId && it.supports(role) } + }.map { it.id to it.name } + ChoiceRow(host, "input-part-${role.name}", roleLabel(role), null, options, library.activePart(desktop, role).bindings, + chipModifier = track("input-part-${role.name}")) { id -> update(role) { it.selectPart(desktop, role, id) } } + } + if (mixed) SecondaryButton(stringResource(R.string.input_save_combination)) { naming = true } + ActionRow(stringResource(R.string.input_settings), null, stringResource(R.string.ctrl_edit), onEdit, + modifier = track("input-settings").testTag("input-profile-edit")) + } + } + if (naming) { + var name by remember { mutableStateOf("") } + AlertDialog(onDismissRequest = { naming = false }, title = { Text(stringResource(R.string.input_save_combination)) }, + text = { OutlinedTextField(name, { name = it.take(80) }, singleLine = true, label = { Text(stringResource(R.string.input_name)) }) }, + confirmButton = { PadTextButton(enabled = name.isNotBlank(), onClick = { update(null) { it.saveSelection(desktop, name) }; naming = false }) { Text(stringResource(R.string.gesture_save_changes)) } }, + dismissButton = { PadTextButton(onClick = { naming = false }) { Text(stringResource(R.string.common_cancel)) } }) + } + failure?.let { message -> AlertDialog(onDismissRequest = { failure = null }, title = { Text(stringResource(R.string.input_save_failed)) }, + text = { Text(message) }, confirmButton = { PadTextButton(onClick = { failure = null }) { Text(stringResource(R.string.common_ok)) } }) } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt index 3176734495..bd319dc2d9 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt @@ -1,10 +1,18 @@ package com.droiddeck.launcher.ui +import android.content.Context +import android.net.Uri +import android.provider.OpenableColumns +import android.util.DisplayMetrics import androidx.activity.compose.BackHandler +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.focusGroup import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.ui.focus.focusRequester import androidx.compose.foundation.layout.* +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment @@ -12,85 +20,142 @@ import androidx.compose.ui.Modifier 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.unit.dp import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties import com.droiddeck.launcher.R import com.droiddeck.launcher.input.* import com.droiddeck.launcher.session.SessionPrefs +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext -/** The in-game Remap buttons page. */ @Composable -fun InputSettingsDialog(onBack: () -> Unit, onChanged: () -> Unit, desktop: Boolean = false) { +fun InputSettingsDialog(onBack: () -> Unit, onChanged: () -> Unit) { val context = LocalContext.current val activity = context.findActivity() as? com.droiddeck.launcher.SessionActivity val target = activity?.inputEditorDisplay(InputRole.SECONDARY) if (activity != null && target != null && target.displayId != activity.window.decorView.display?.displayId) { - InputDisplayContent(activity, target, onBack) { InputSettingsPane(onBack, onChanged, desktop) } - } else Dialog(onDismissRequest = onBack, properties = DialogProperties(usePlatformDefaultWidth = false)) { - InputSettingsPane(onBack, onChanged, desktop) + InputDisplayContent(activity, target, onBack) { InputSettingsPane(onBack, onChanged) } + } else InputSettingsWindow(onBack, onChanged) +} + +@Composable +private fun InputSettingsWindow(onBack: () -> Unit, onChanged: () -> Unit) { + Dialog(onDismissRequest = onBack, properties = DialogProperties(usePlatformDefaultWidth = false)) { + InputSettingsPane(onBack, onChanged) } } @Composable -private fun InputSettingsPane(onBack: () -> Unit, onChanged: () -> Unit, desktop: Boolean) { +private fun InputSettingsPane(onBack: () -> Unit, onChanged: () -> Unit) { + var editingSurface by remember { mutableStateOf(false) } + val window = (androidx.compose.ui.platform.LocalView.current.parent as? androidx.compose.ui.window.DialogWindowProvider)?.window + DisposableEffect(window, editingSurface) { + window?.setDimAmount(if (editingSurface) 0f else .32f) + onDispose { } + } BoxWithConstraints(Modifier.fillMaxSize().systemBarsPadding().padding(8.dp)) { CompositionLocalProvider(LocalNarrowPane provides (maxWidth < NarrowPaneWidth)) { - Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.surface) { - InputSettingsPage(onBack, onChanged, remapOnly = true, desktop = desktop) + Surface(Modifier.fillMaxSize(), color = if (editingSurface) androidx.compose.ui.graphics.Color.Transparent else MaterialTheme.colorScheme.surface) { + InputSettingsPage(onBack, onChanged, onSurfaceEditing = { editingSurface = it }) } } } } -private enum class InputPage { HOME, REMAP } -private data class InputBindingEdit(val preset: String, val control: InputControl, val key: PhysicalInputKey? = null) +private enum class InputPage { HOME, PROFILE, SOURCE, LAYOUTS, REUSE } +private data class InputBindingEdit(val preset: String, val control: InputControl, val element: InputSurfaceElement? = null, val key: PhysicalInputKey? = null, val click: Boolean = false) +private data class InputNameRequest(val title: Int, val initial: String, val sources: List> = emptyList(), + val source: String = "", val offerSharing: Boolean = false, val save: (String, String, Boolean) -> Unit) +private data class InputConfirmation(val title: String, val detail: String, val action: () -> Unit) +private data class InputReuseRequest(val name: String, val layoutOnly: Boolean, val apply: (Boolean) -> Unit) -/** Settings › Controller: the in-game Controller page for the default, or with [remapOnly] just the physical controller's buttons. */ @Composable -fun InputSettingsPage(onBack: () -> Unit, onChanged: () -> Unit = {}, embedded: Boolean = false, onSurfaceEditing: (Boolean) -> Unit = {}, - remapOnly: Boolean = false, desktop: Boolean = false) { +fun InputSettingsPage(onBack: () -> Unit, onChanged: () -> Unit = {}, embedded: Boolean = false, onSurfaceEditing: (Boolean) -> Unit = {}) { CompositionLocalProvider(LocalContentColor provides MaterialTheme.colorScheme.onBackground) { - InputSettingsContent(onBack, onChanged, embedded, onSurfaceEditing, remapOnly, desktop) + InputSettingsContent(onBack, onChanged, embedded, onSurfaceEditing) } } @Composable -private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embedded: Boolean, onSurfaceEditing: (Boolean) -> Unit, - remapOnly: Boolean, desktop: Boolean) { +private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embedded: Boolean, onSurfaceEditing: (Boolean) -> Unit) { val context = LocalContext.current val host = rememberMenuHost() var library by remember { mutableStateOf(InputLibraries.read(context)) } - var page by remember { mutableStateOf(if (remapOnly) InputPage.REMAP else InputPage.HOME) } + var page by remember { mutableStateOf(InputPage.HOME) } var bindingsTab by remember { mutableIntStateOf(0) } + var profileId by remember { mutableStateOf(InputProfile.GAME) } + var role by remember { mutableStateOf(InputRole.PHYSICAL) } var edit by remember { mutableStateOf(null) } + var naming by remember { mutableStateOf(null) } + var confirmation by remember { mutableStateOf(null) } + var reuse by remember { mutableStateOf(null) } var capture by remember { mutableStateOf(false) } - var surface by remember { mutableStateOf?>(null) } - var revision by remember { mutableIntStateOf(0) } - LaunchedEffect(surface) { onSurfaceEditing(surface != null) } + var surface by remember { mutableStateOf(false) } + LaunchedEffect(surface) { onSurfaceEditing(surface) } DisposableEffect(Unit) { onDispose { onSurfaceEditing(false) } } + var managingLayout by remember { mutableStateOf(null) } + var exporting by remember { mutableStateOf(null) } var error by remember { mutableStateOf(null) } + val scope = rememberCoroutineScope() val controller = rememberControllerSettings() - fun changed() { library = InputLibraries.read(context); revision++; onChanged() } + var oscMode by remember { mutableStateOf(SessionPrefs.oscMode(context)) } fun update(change: (InputLibrary) -> InputLibrary): Boolean = runCatching { InputLibraries.update(context, change) } .onSuccess { library = it; onChanged() }.onFailure { error = it.message ?: context.getString(R.string.input_save_failed) }.isSuccess fun go(next: InputPage) { page = next; host.open = null } fun back() { when { edit != null -> edit = null - page == InputPage.REMAP && !remapOnly -> go(InputPage.HOME) - else -> onBack() + page == InputPage.HOME -> onBack() + page == InputPage.PROFILE -> go(InputPage.HOME) + page == InputPage.SOURCE -> go(InputPage.PROFILE) + else -> go(InputPage.SOURCE) } } BackHandler(enabled = !embedded || page != InputPage.HOME || edit != null, onBack = ::back) - val profile = library.profile(library.activeId(desktop)) - val preset = library.preset(library.activePart(desktop, InputRole.PHYSICAL).bindings) + val profile = library.profile(profileId) + val preset = library.preset(profile.binding(role)) + val layout = library.layout(profileId, role) + val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> + if (uri == null) return@rememberLauncherForActivityResult + val target = role + scope.launch { + val raw = withContext(Dispatchers.IO) { readLayoutFile(context, uri) } + val metrics = inputDisplayMetrics(context, target) + val imported = raw?.let { InputLayoutFile.import(context, it, layoutFileName(context, uri) ?: context.getString(R.string.ctrl_layout), + if (target == InputRole.PRIMARY) InputLayoutScreen.MAIN else InputLayoutScreen.SECONDARY, layout?.style ?: InputSurfaceStyle(), + metrics.widthPixels, metrics.heightPixels, metrics.density) } + if (imported == null) error = context.getString(R.string.input_layout_import_failed) + else if (update { it.withLayout(imported.first).withPreset(imported.second).chooseLayout(profileId, target, imported.first.id) }) go(InputPage.SOURCE) + } + } + val exporter = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/json")) { uri -> + val text = exporting + exporting = null + if (uri != null && text != null) scope.launch { + val saved = withContext(Dispatchers.IO) { runCatching { context.contentResolver.openOutputStream(uri, "wt")?.use { it.write(text.toByteArray()) } != null }.getOrDefault(false) } + if (!saved) error = context.getString(R.string.input_save_failed) + } + } + fun rename(title: Int, name: String, save: (String) -> Unit) { + naming = InputNameRequest(title, name) { value, _, _ -> save(value) } + } + fun newProfile(copy: Boolean) { + naming = InputNameRequest(if (copy) R.string.input_copy_profile else R.string.input_new_profile, + if (copy) profile.name else "", library.profiles.map { it.id to it.name }, profileId, offerSharing = true) { name, source, shared -> + val id = newInputId() + if (update { it.duplicateProfile(source, name, id, sharePhysical = shared) }) { profileId = id; go(InputPage.PROFILE) } + } + } + fun editPart(nextRole: InputRole) { role = nextRole; bindingsTab = 0; go(InputPage.SOURCE) } val pageFocus = remember { androidx.compose.ui.focus.FocusRequester() } val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current var settled by remember { mutableStateOf(false) } - LaunchedEffect(page, edit != null, surface) { + LaunchedEffect(page, role, profileId, edit != null, surface) { if (!settled) { settled = true; return@LaunchedEffect } - if (surface != null || inputMode.inputMode != androidx.compose.ui.input.InputMode.Keyboard) return@LaunchedEffect + if (surface || inputMode.inputMode != androidx.compose.ui.input.InputMode.Keyboard) return@LaunchedEffect repeat(2) { withFrameNanos { } } runCatching { pageFocus.requestFocus() } } @@ -98,46 +163,70 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe Box(Modifier.focusRequester(pageFocus).focusGroup()) { if (editing != null) { val b = library.preset(editing.preset) - val current = editing.key?.let { k -> b.keys.firstOrNull { it.key == k }?.action ?: InputAction.Disabled } + var elementProperties by remember(editing) { mutableStateOf(editing.element) } + val current = editing.element?.let { if (editing.click) b.clickAction(it) else b.action(it) } + ?: editing.key?.let { k -> b.keys.firstOrNull { it.key == k }?.action ?: InputAction.Disabled } ?: b.controls[editing.control] ?: InputAction.Native() - InputActionEditor(editing.control, current, editing.key?.label ?: editing.control.label, - onBack = { edit = null }, nativeTargets = editing.key == null, detail = stringResource(R.string.input_remap_buttons), onSave = { action -> - if (update { l -> l.withPreset(when { + InputActionEditor(editing.control, current, if (editing.click) stringResource(R.string.input_click_name, editing.element!!.name) + else editing.element?.name ?: editing.key?.label ?: editing.control.label, + properties = { action -> if (!editing.click) elementProperties?.let { e -> InputElementProperties(e, action) { elementProperties = it } } }, + onBack = { edit = null }, element = editing.element, nativeTargets = editing.key == null, click = editing.click, + detail = if (library.usersOfBindings(b.id).size > 1) stringResource(R.string.input_shared_detail, b.name, library.usersOfBindings(b.id).size) + else "${profile.name} · ${roleLabel(role)}", onSave = { action -> + if (update { l -> + val geometry = if (!editing.click && elementProperties != null && layout != null) l.withLayout(layout.copy(elements = layout.elements.map { + if (it.id == elementProperties!!.id) elementProperties!!.copy(name = elementProperties!!.name.trim().ifBlank { it.name }) else it + })) else l + geometry.withPreset(when { + editing.element != null && editing.click -> b.copy(clicks = b.clicks + (editing.element.id to action)) + editing.element != null -> b.copy(elements = b.elements + (editing.element.id to action)) editing.key != null -> b.copy(keys = b.keys.filterNot { it.key == editing.key } + PhysicalInputBinding(editing.key, action)) else -> b.copy(controls = b.controls + (editing.control to action)) }) }) edit = null }) - } else if (surface == null) key(page) { + } else if (!surface) key(page, profileId, role) { SettingsPage(host, title = when (page) { InputPage.HOME -> if (embedded) null else stringResource(R.string.setup_controller) - InputPage.REMAP -> stringResource(R.string.input_remap_buttons) - }, onBack = ::back, showBack = !(embedded && page == InputPage.HOME), compactLayout = true) { + InputPage.PROFILE -> profile.name + InputPage.SOURCE -> roleLabel(role) + InputPage.LAYOUTS -> stringResource(R.string.input_saved_layouts) + InputPage.REUSE -> stringResource(R.string.input_use_settings_from) + }, eyebrow = when (page) { + InputPage.SOURCE -> profile.name + InputPage.LAYOUTS, InputPage.REUSE -> "${profile.name} · ${roleLabel(role)}" + else -> null + }, + onBack = ::back, showBack = !(embedded && page == InputPage.HOME), compactLayout = true) { when (page) { InputPage.HOME -> { + SettingsGroup(stringResource(R.string.input_default_profiles)) { + ChoiceRow(host, "auto-desktop", stringResource(R.string.input_desktop_mode), null, + library.profiles.map { it.id to it.name }, library.desktop) { id -> update { it.copy(desktop = id) } } + ChoiceRow(host, "auto-game", stringResource(R.string.input_game_mode), null, + library.profiles.map { it.id to it.name }, library.steam) { id -> update { it.copy(steam = id) } } + for (desktop in listOf(true, false)) { + val selection = library.selection(desktop) + if (selection.profile != InputProfiles.AUTO || selection.parts.isNotEmpty()) InputHint(stringResource(R.string.input_quick_override_hint, + stringResource(if (desktop) R.string.input_desktop_mode else R.string.input_game_mode))) + } + } if (InputLibraries.hasPendingScreenKeyMigration(context)) InputHint(stringResource(R.string.input_import_failed)) if (InputLibraries.hasLibraryRecovery(context)) InputHint(stringResource(R.string.input_library_recovered)) - DefaultControlsGroup(host, revision, onEdit = { surface = it }, onChanged = ::changed, - onFailure = { error = it.message ?: context.getString(R.string.input_save_failed) }) - SettingsGroup(stringResource(R.string.drawer_page_controller)) { - var padType by remember { mutableStateOf(SessionPrefs.steamController(context)) } - ChoiceRow(host, "pad-type", stringResource(R.string.input_virtual_controller), null, - listOf(SessionPrefs.CONTROLLER_DECK to stringResource(R.string.mode_controller_deck), - SessionPrefs.CONTROLLER_STEAM to stringResource(R.string.mode_controller_steam), - SessionPrefs.CONTROLLER_DS4 to stringResource(R.string.mode_controller_ds4), - SessionPrefs.CONTROLLER_DUALSENSE to stringResource(R.string.mode_controller_dualsense), - SessionPrefs.CONTROLLER_XBOX360 to stringResource(R.string.mode_controller_x360)), - padType) { SessionPrefs.setSteamController(context, it); padType = it; onChanged() } + if (library.profiles.any { it.id.startsWith("migrated.screenkeys.") }) Text(stringResource(R.string.input_imported_keys_hint), + Modifier.padding(16.dp), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + SettingsGroup(stringResource(R.string.input_profiles)) { + for (p in library.profiles) InputNavigationRow(p.name, when { + p.id == library.steam && p.id == library.desktop -> stringResource(R.string.input_default_both) + p.id == library.steam -> stringResource(R.string.input_default_game) + p.id == library.desktop -> stringResource(R.string.input_default_desktop) + else -> null + }, Modifier.testTag("input-profile-${p.id}")) { profileId = p.id; go(InputPage.PROFILE) } + PadTextButton(onClick = { newProfile(false) }, modifier = Modifier.padding(8.dp)) { Text(stringResource(R.string.input_new_profile)) } + } + SettingsGroup(stringResource(R.string.input_device_settings)) { ToggleRow(host, "controller-rumble", stringResource(R.string.ctrl_rumble), null, controller.rumble) { ControllerPrefs.setRumble(context, it); onChanged() } ChoiceRow(host, "controller-dead-zone", stringResource(R.string.ctrl_dead_zone), null, ControllerPrefs.deadZones.map { it to stringResource(R.string.ctrl_percent, it) }, controller.deadZone) { ControllerPrefs.setDeadZone(context, it); onChanged() } - ToggleRow(host, "controller-joycon-vr", stringResource(R.string.ctrl_joycon_vr), null, controller.joyConVr) { ControllerPrefs.setJoyConVr(context, it); onChanged() } - ActionRow(stringResource(R.string.input_remap_buttons), null, stringResource(R.string.ctrl_edit), { go(InputPage.REMAP) }, - modifier = Modifier.testTag("input-remap")) - } - val games = remember(revision) { ControlsChoice.games(context) } - if (games.isNotEmpty()) SettingsGroup(stringResource(R.string.osc_games_own)) { - for (game in games) ActionRow(game.name, game.layout, stringResource(R.string.osc_use_default), { - ControlsChoice.useDefault(context, game.id); changed() - }, modifier = Modifier.testTag("osc-use-default-${game.id}")) + ToggleRow(host, "controller-joycon-vr", stringResource(R.string.ctrl_joycon_vr), stringResource(R.string.ctrl_joycon_vr_hint), controller.joyConVr) { ControllerPrefs.setJoyConVr(context, it); onChanged() } } SettingsGroup(stringResource(R.string.shortcuts_title)) { PhysicalShortcutRows() } SettingsGroup(stringResource(R.string.input_latency)) { @@ -155,70 +244,191 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe } }, confirmButton = { PadTextButton(onClick = { reading = false }) { Text(stringResource(R.string.common_close)) } }) } } - InputPage.REMAP -> { - SettingsGroup(stringResource(R.string.input_physical)) { - Box(Modifier.padding(horizontal = 12.dp, vertical = 12.dp)) { - SheetChips(listOf(stringResource(R.string.input_buttons), stringResource(R.string.input_axes), stringResource(R.string.input_extra_keys)), bindingsTab) { bindingsTab = it } + InputPage.PROFILE -> { + SettingsGroup(stringResource(R.string.input_profile_controls)) { + for (r in InputRole.entries) InputNavigationRow(roleLabel(r), + if (r == InputRole.PHYSICAL) stringResource(R.string.input_physical_hint) else library.layout(profileId, r)?.name, + Modifier.testTag("input-part-${r.name.lowercase()}"), leading = { + library.layout(profileId, r)?.let { InputLayoutThumbnail(it, r) } + }) { editPart(r) } + } + Spacer(Modifier.height(16.dp)) + Actions { + SecondaryButton(stringResource(R.string.input_rename)) { rename(R.string.input_rename, profile.name) { name -> update { it.withProfile(profile.copy(name = name)) } } } + SecondaryButton(stringResource(R.string.input_copy_profile)) { newProfile(true) } + SecondaryButton(stringResource(R.string.input_reset_actions)) { + confirmation = InputConfirmation(context.getString(R.string.input_reset_actions), context.getString(R.string.input_reset_profile_detail, profile.name)) { update { it.resetProfile(profileId) } } } - if (bindingsTab != 2) InputControlGrid(preset, InputControl.padControls.asList(), bindingsTab == 1) { edit = InputBindingEdit(preset.id, it) } - else { - for (b in preset.keys) { - InputNavigationRow(b.key.label, actionLabel(b.action)) { edit = InputBindingEdit(preset.id, InputControl.A, key = b.key) } - PadTextButton(onClick = { update { it.withPreset(preset.copy(keys = preset.keys - b)) } }) { Text(stringResource(R.string.input_remove_binding)) } + if (profileId !in listOf(InputProfile.GAME, InputProfile.DESKTOP)) SecondaryButton(stringResource(R.string.input_delete)) { + confirmation = InputConfirmation(context.getString(R.string.input_delete), context.getString(R.string.input_delete_profile_detail, profile.name)) { + if (update { it.removeProfile(profileId) }) { profileId = InputProfile.GAME; go(InputPage.HOME) } } - InputNavigationRow(stringResource(R.string.input_capture), null) { capture = true } } - val defaults = InputProfile.defaults(profile.base).bindings[InputRole.PHYSICAL].orEmpty() - if (preset.controls != defaults || preset.keys.isNotEmpty()) ActionRow(stringResource(R.string.input_reset_actions), null, - stringResource(R.string.hud_reset_button), { update { it.withPreset(preset.copy(controls = defaults, keys = emptyList())) } }, - modifier = Modifier.testTag("input-remap-reset")) } } + 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) { + 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, + button !in layout.style.hidden) { on -> update { it.withLayout(layout.withQuickButton(button, on)) } } + } + if (role == InputRole.SECONDARY) InputHint(stringResource(R.string.input_second_screen_enable)) + } + 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 })) + val elements = layout?.takeIf { it.editable }?.elements + if (elements != null) { + if (elements.isEmpty()) InputHint(stringResource(R.string.input_empty_elements)) + for (e in elements) { + InputNavigationRow(e.name, actionLabel(preset.action(e)), Modifier.testTag("input-element-${e.id}")) { edit = InputBindingEdit(preset.id, e.control, e) } + if (e.hasClick) InputNavigationRow(stringResource(R.string.input_click_name, e.name), actionLabel(preset.clickAction(e)), Modifier.testTag("input-click-${e.id}")) { edit = InputBindingEdit(preset.id, InputControl.A, e, click = true) } + } + } else { + Box(Modifier.padding(horizontal = 12.dp, vertical = 12.dp)) { + SheetChips(listOf(stringResource(R.string.input_buttons), stringResource(R.string.input_axes)) + + if (preset.physical) listOf(stringResource(R.string.input_extra_keys)) else emptyList(), bindingsTab) { bindingsTab = it } + } + val controls = InputControl.padControls.asList() + if (bindingsTab != 2) InputControlGrid(preset, controls, bindingsTab == 1) { edit = InputBindingEdit(preset.id, it) } + else { + for (b in preset.keys) { + InputNavigationRow(b.key.label, actionLabel(b.action)) { edit = InputBindingEdit(preset.id, InputControl.A, key = b.key) } + PadTextButton(onClick = { update { it.withPreset(preset.copy(keys = preset.keys - b)) } }) { Text(stringResource(R.string.input_remove_binding)) } + } + InputNavigationRow(stringResource(R.string.input_capture), stringResource(R.string.input_capture_hint)) { capture = true } + } + } + } + SettingsGroup(stringResource(R.string.input_reuse)) { + InputNavigationRow(stringResource(R.string.input_use_settings_from), stringResource(R.string.input_reuse_hint)) { go(InputPage.REUSE) } + if (library.usersOfBindings(preset.id).size > 1 || layout?.let { it.editable && library.usersOfLayout(it.id).size > 1 } == true) + InputNavigationRow(stringResource(R.string.input_make_independent), stringResource(R.string.input_independent_hint), Modifier.testTag("input-make-independent")) { + update { it.usePart(profileId, role, profileId, shared = false) } + } + } + } + InputPage.LAYOUTS -> { + InputHint(stringResource(R.string.input_layout_geometry_hint)) + SettingsGroup(stringResource(R.string.input_saved_layouts)) { + var showOther by remember { mutableStateOf(false) } + val available = library.layouts.filter { it.supports(role) } + val other = available.filter { saved -> !saved.id.startsWith("builtin.") && saved.id != layout?.id && + library.usersOfLayout(saved.id).isEmpty() && library.bindings.none { it.layoutId == saved.id && library.selectedBindings(it.id) } } + for (saved in available.filter { showOther || it !in other }) { + InputLayoutRow(saved, role, if (saved.id == layout?.id) stringResource(R.string.input_current_layout) else null, + onManage = { managingLayout = saved }) { + reuse = InputReuseRequest(saved.name, layoutOnly = true) { shared -> if (update { it.useLayout(profileId, role, saved.id, shared) }) go(InputPage.SOURCE) } + } + } + if (other.isNotEmpty()) PadTextButton(onClick = { showOther = !showOther }, modifier = Modifier.padding(8.dp)) { + Text(stringResource(if (showOther) R.string.input_hide_other_layouts else R.string.input_other_layouts, other.size)) + } + Row { + PadTextButton(onClick = { naming = InputNameRequest(R.string.input_new_layout, "") { name, _, _ -> + val created = SavedInputLayout(newInputId(), name, screen = if (role == InputRole.PRIMARY) InputLayoutScreen.MAIN else InputLayoutScreen.SECONDARY) + if (update { it.withLayout(created).useLayout(profileId, role, created.id, shared = true) }) { go(InputPage.SOURCE); surface = true } + } }, modifier = Modifier.padding(8.dp)) { Text(stringResource(R.string.input_new_layout)) } + PadTextButton(onClick = { importer.launch(arrayOf("application/json", "text/plain", "application/octet-stream", "*/*")) }, + modifier = Modifier.padding(8.dp).testTag("input-layout-import")) { Text(stringResource(R.string.boot_movie_import)) } + } + } + + } + InputPage.REUSE -> { + InputHint(stringResource(R.string.input_reuse_explanation, roleLabel(role))) + SettingsGroup(stringResource(R.string.input_profiles)) { + for (p in library.profiles.filterNot { it.id == profileId }) InputNavigationRow(p.name, library.layout(p.id, role)?.name) { + reuse = InputReuseRequest(p.name, layoutOnly = false) { shared -> if (update { it.usePart(profileId, role, p.id, shared) }) go(InputPage.SOURCE) } + } + } + } + } } } } + managingLayout?.let { saved -> AlertDialog(onDismissRequest = { managingLayout = null }, title = { Text(saved.name) }, + text = { Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(stringResource(R.string.input_layout_count, saved.elements.size)) + SecondaryButton(stringResource(R.string.input_rename)) { + managingLayout = null + rename(R.string.input_rename_layout, saved.name) { name -> update { it.withLayout(saved.copy(name = name)) } } + } + val exported = remember(saved, library) { + val metrics = inputDisplayMetrics(context, if (saved.screen == InputLayoutScreen.SECONDARY) InputRole.SECONDARY else InputRole.PRIMARY) + InputLayoutFile.export(saved, library.bindings.firstOrNull { it.id == preset.id && it.layoutId == saved.id } + ?: library.bindings.firstOrNull { it.layoutId == saved.id }, metrics.widthPixels, metrics.heightPixels) + } + if (exported != null) SecondaryButton(stringResource(R.string.screen_key_layout_export)) { + managingLayout = null + exporting = exported + exporter.launch(InputLayoutFile.fileName(saved)) + } + val used = library.usersOfLayout(saved.id).isNotEmpty() || library.bindings.any { it.layoutId == saved.id && library.selectedBindings(it.id) } + if (!used && saved.editable) SecondaryButton(stringResource(R.string.input_delete)) { + managingLayout = null + confirmation = InputConfirmation(context.getString(R.string.input_delete), context.getString(R.string.input_delete_layout_detail, saved.name)) { update { it.removeLayout(saved.id) } } + } + } }, confirmButton = { PadTextButton(onClick = { managingLayout = null }) { Text(stringResource(R.string.common_close)) } }) } if (capture) InputCaptureDialog(onDismiss = { capture = false }) { capture = false; edit = InputBindingEdit(preset.id, InputControl.A, key = it) } - surface?.let { (profileId, layoutId, bindingsId) -> - val name = library.layouts.firstOrNull { it.id == layoutId }?.name.orEmpty() - InputSurfaceDialog(profileId, onDismiss = { surface = null; changed() }, onChanged = ::changed, role = InputRole.PRIMARY, - layoutId = layoutId, bindingsId = bindingsId, scope = stringResource(R.string.osc_scope_default, name)) - } + if (surface) InputSurfaceDialog(profileId, onDismiss = { surface = false; library = InputLibraries.read(context) }, onChanged = { + library = InputLibraries.read(context); onChanged() + }, role = role, layoutId = layout?.id, bindingsId = preset.id) + naming?.let { request -> key(request) { InputNameDialog(request) { naming = null } } } + reuse?.let { request -> key(request) { InputReuseDialog(request) { reuse = null } } } + confirmation?.let { request -> AlertDialog(onDismissRequest = { confirmation = null }, title = { Text(request.title) }, + text = { Text(request.detail) }, confirmButton = { PadTextButton(onClick = { confirmation = null; request.action() }) { Text(stringResource(R.string.common_ok)) } }, + dismissButton = { PadTextButton(onClick = { confirmation = null }) { Text(stringResource(R.string.common_cancel)) } }) } error?.let { message -> AlertDialog(onDismissRequest = { error = null }, title = { Text(stringResource(R.string.input_save_failed)) }, text = { Text(message) }, confirmButton = { PadTextButton(onClick = { error = null }) { Text(stringResource(R.string.common_ok)) } }) } } -/** The in-game "On-screen controls" group, for games without a layout of their own. */ @Composable -private fun DefaultControlsGroup(host: MenuHost, revision: Int, onEdit: (Triple) -> Unit, onChanged: () -> Unit, - onFailure: (Throwable) -> Unit) { - val context = LocalContext.current - val options = remember(revision) { ControlsChoice.options(context, null, steamMode = true) } - val choice = remember(revision) { ControlsChoice.current(context, null, steamMode = true) } - var oscMode by remember { mutableStateOf(SessionPrefs.oscMode(context)) } - var touch by remember { mutableStateOf(SessionPrefs.touchMode(context)) } - var below by remember { mutableStateOf(SessionPrefs.unfoldedControls(context)) } - SettingsGroup(stringResource(R.string.osc_group_for, stringResource(R.string.osc_default))) { - ChoiceRow(host, "osc-layout", stringResource(R.string.osc_layout), null, options, choice) { id -> - runCatching { ControlsChoice.choose(context, null, id, desktop = false) }.onSuccess { onChanged() }.onFailure(onFailure) +private fun InputNameDialog(request: InputNameRequest, onDismiss: () -> Unit) { + var name by remember { mutableStateOf(request.initial) } + var source by remember { mutableStateOf(request.source) } + var shared by remember { mutableStateOf(false) } + val host = rememberMenuHost() + AlertDialog(onDismissRequest = onDismiss, title = { Text(stringResource(request.title)) }, text = { Column(Modifier.verticalScroll(rememberScrollState())) { + OutlinedTextField(name, { name = it.take(80) }, label = { Text(stringResource(R.string.input_name)) }, singleLine = true, modifier = Modifier.testTag("input-name")) + if (request.sources.isNotEmpty()) ChoiceRow(host, "input-copy-source", stringResource(R.string.input_start_from), null, request.sources, source) { source = it } + if (request.offerSharing) { + Row(Modifier.fillMaxWidth().focusRow(role = Role.Checkbox, checked = shared) { shared = !shared }.testTag("input-share-physical"), verticalAlignment = Alignment.CenterVertically) { + Checkbox(shared, null) + Text(stringResource(R.string.input_share_physical)) + } + Text(stringResource(R.string.input_new_independent_hint), style = MaterialTheme.typography.bodySmall) } - if (choice != GameControls.STEAM) ActionRow(stringResource(R.string.osc_edit_layout), null, stringResource(R.string.ctrl_edit), { - host.open = null - ControlsChoice.editTarget(context, null, desktop = false)?.let(onEdit) - }, modifier = Modifier.testTag("osc-edit")) - SettingsRow(stringResource(R.string.osc_show), null) { - SegmentedTabs(listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), - SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)), oscMode, - tabModifier = { Modifier.testTag("osc-$it") }) { SessionPrefs.setOscMode(context, it); oscMode = it; onChanged() } + } }, confirmButton = { PadTextButton(enabled = name.isNotBlank(), onClick = { request.save(name.trim(), source, shared); onDismiss() }) { Text(stringResource(R.string.gesture_save_changes)) } }, + dismissButton = { PadTextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } }) +} + +@Composable +private fun InputReuseDialog(request: InputReuseRequest, onDismiss: () -> Unit) { + var shared by remember { mutableStateOf(false) } + AlertDialog(onDismissRequest = onDismiss, title = { Text(request.name) }, text = { Column(Modifier.verticalScroll(rememberScrollState())) { + Text(stringResource(if (request.layoutOnly) R.string.input_reuse_layout_detail else R.string.input_reuse_part_detail)) + for (link in listOf(false, true)) Row(Modifier.fillMaxWidth().focusRow(role = Role.RadioButton, checked = shared == link) { shared = link }, verticalAlignment = Alignment.CenterVertically) { + RadioButton(shared == link, null) + Text(stringResource(if (link) R.string.input_keep_shared else R.string.input_independent_copy)) } - ChoiceRow(host, "touch", stringResource(R.string.input_touches), null, - listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.common_auto), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_mouse), - SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_GESTURES to stringResource(R.string.mode_touch_gestures), - SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)), touch) { SessionPrefs.setTouchMode(context, it); touch = it; onChanged() } - ToggleRow(host, "unfolded-controls", stringResource(R.string.unfolded_controls), null, below) { - SessionPrefs.setUnfoldedControls(context, it); below = it; onChanged() - } - } + } }, confirmButton = { PadTextButton(onClick = { request.apply(shared); onDismiss() }) { Text(stringResource(R.string.common_ok)) } }, + dismissButton = { PadTextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } }) } @Composable @@ -241,9 +451,10 @@ private fun InputControlGrid(preset: SavedInputBindings, available: List Unit) { +private fun InputNavigationRow(title: String, detail: String?, modifier: Modifier = Modifier, leading: (@Composable () -> Unit)? = null, onClick: () -> Unit) { Row(modifier.fillMaxWidth().focusRow(RoundedCornerShape(0.dp), onClick = onClick).heightIn(min = 64.dp).padding(14.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { + leading?.invoke() Column(Modifier.weight(1f)) { Text(title, style = MaterialTheme.typography.titleMedium) if (detail != null) Text(detail, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) @@ -252,6 +463,43 @@ private fun InputNavigationRow(title: String, detail: String?, modifier: Modifie } } +internal fun quickButtonLabel(button: InputCommand) = when (button) { + InputCommand.STEAM -> R.string.ctrl_steam_button + InputCommand.QUICK_ACCESS -> R.string.ctrl_qam_button + else -> R.string.ctrl_keyboard_button +} + +@Suppress("DEPRECATION") +internal fun inputDisplayMetrics(context: Context, role: InputRole): DisplayMetrics = DisplayMetrics().also { metrics -> + (context.findActivity() as? com.droiddeck.launcher.SessionActivity)?.inputEditorDisplay(role)?.getRealMetrics(metrics) + ?: metrics.setTo(context.resources.displayMetrics) +} + +private fun readLayoutFile(context: Context, uri: Uri): String? = runCatching { + context.contentResolver.openInputStream(uri)?.use { input -> + val out = java.io.ByteArrayOutputStream() + val buffer = ByteArray(8192) + while (true) { + val read = input.read(buffer) + if (read < 0) break + out.write(buffer, 0, read) + if (out.size() > 1_000_000) return@use null + } + out.toString(Charsets.UTF_8.name()) + } +}.getOrNull() + +private fun layoutFileName(context: Context, uri: Uri): String? = runCatching { + context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor -> + if (cursor.moveToFirst()) cursor.getString(0)?.substringBeforeLast('.')?.trim()?.takeIf { it.isNotEmpty() } else null + } +}.getOrNull() + +@Composable +internal fun roleLabel(role: InputRole) = stringResource(when (role) { + InputRole.PHYSICAL -> R.string.input_physical; InputRole.PRIMARY -> R.string.input_primary; InputRole.SECONDARY -> R.string.input_secondary +}) + @Composable private fun InputHint(text: String) { Text(text, Modifier.padding(14.dp), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) 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 49657039bc..ca701cebf8 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt @@ -63,98 +63,153 @@ 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 val layout: SavedInputLayout) { + private fun generator(scale: Float) = LegacyGamepadLayout(context, width, height, scale = scale) + val ids = generator(1f).elements().map { it.id }.toSet() + 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 } } +} + private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputBindings, val defaults: List? = null, - private val defaultsFrame: Float = 0f, snap: Boolean = true) { + private val defaultsFrame: Float = 0f, private var gamepad: GamepadScaler? = null, snap: Boolean = true) { + val hasGamepad get() = gamepad != null var elements by mutableStateOf(layout.elements) var actions by mutableStateOf(preset.elements) var clicks by mutableStateOf(preset.clicks) var selected by mutableStateOf(null) + var toolsExpanded by mutableStateOf(false) + var toolsX by mutableFloatStateOf(-1f) + var toolsY by mutableFloatStateOf(.02f) var snap by mutableStateOf(snap) - var popover by mutableStateOf(null) - var confirmDiscard by mutableStateOf(false) + 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>?>(null) + private var scaleBase by mutableStateOf, List, Float>?>(null) private var scaleValue by mutableIntStateOf(100) - val scale get() = if (scaleBase?.second == elements) scaleValue else 100 - val positioned get() = defaults?.let { elements.withPositionsOf(refit(it, defaultsFrame)) }?.takeIf { it != elements } + private val rescales get() = gamepad?.let { pad -> elements.any { it.id in pad.ids } } == true + val scale get() = when { + scaleBase?.second == elements -> scaleValue + rescales -> ((if (canvas.width > 0 && canvas.height > 0 && aspect > 0f && (aspect < 1f) != (canvasAspect < 1f)) + OnScreenLayout.oriented(layout, canvas.width, canvas.height).scale else layoutScale) * 100).roundToInt() + else -> 100 + } + val positioned get() = (if (rescales) gamepad!!.reset(elements) else defaults?.let { elements.withPositionsOf(refit(it, defaultsFrame)) }) + ?.takeIf { it != elements || rescales && layoutScale != 1f } private fun refit(placed: List, from: Float): List { 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) } } - fun beginEdit(displayed: List, aspect: Float) { + 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 } ?: (elements to elements).also { checkpoint() } - elements = base.first.scaled(percent / 100f) - scaleValue = percent; scaleBase = base.first to elements + 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) { + layoutScale = factor + val others = base.first.filterNot { it.id in pad.ids }.scaled(factor / base.third).associateBy { it.id } + pad.rescale(base.first, base.third, factor).map { others[it.id] ?: it } + } else base.first.scaled(factor) + scaleValue = percent; scaleBase = Triple(base.first, elements, base.third) } - fun resetPositions() { positioned?.let { checkpoint(); elements = it } } - private val restored get() = defaults?.let { refit(it, defaultsFrame) } - private fun matches(defaults: List, placed: List) = defaults.size == placed.size && defaults.all { a -> - placed.any { e -> e.copy(x = a.x, y = a.y, width = a.width, height = a.height) == a && - abs(e.x - a.x) < .002f && abs(e.y - a.y) < .002f && abs(e.width - a.width) < .002f && abs(e.height - a.height) < .002f } + 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 } - val atDefaults get() = restored?.let { matches(it, elements) } == true - /** The kit's own controls are where the kit puts them, so only the added ones need saving. */ - val kitAtDefaults get() = restored?.let { matches(it, elements.filter { e -> KitLayout.isKit(e.id) }) } == true - fun reset() { - val d = restored?.takeIf { !atDefaults } ?: return - checkpoint(); elements = d; selected = null - actions = actions.filterKeys { id -> KitLayout.bindsTo(id, d) }; clicks = clicks.filterKeys { id -> d.any { it.id == id } } + + 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 hiddenDefaults(): List = defaults?.let { refit(it, defaultsFrame) }?.filter { d -> elements.none { it.id == d.id } }.orEmpty() - fun add(element: InputSurfaceElement) { checkpoint(); elements = elements + element; selected = element.id; popover = null } + + 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) { - checkpoint(); elements = elements.filterNot { it.id == id }; selected = null - if (!KitLayout.isKit(id)) { actions = actions - id; clicks = clicks - id } + 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 resizeSelected(factor: Float) { - val e = element ?: return - checkpoint() - val w = (e.width * factor).coerceIn(InputSurfaceElement.MIN_SIZE, 1f); val h = (e.height * factor).coerceIn(InputSurfaceElement.MIN_SIZE, 1f) - val cx = e.x + e.width / 2; val cy = e.y + e.height / 2 - elements = elements.map { if (it.id == e.id) e.copy(x = (cx - w / 2).coerceIn(0f, 1f - w), y = (cy - h / 2).coerceIn(0f, 1f - h), width = w, height = h).bounded() else it } + + 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) } -/** Offered when the layout being edited is shared: [create] makes the copy that Done then saves into, and [scope] describes it. */ -/** Turns an edit of a shared layout into a copy for one game: [copy] adds it to the library being saved, [use] picks it once that save succeeded. */ -class InputEditorSplit(val label: String, val scope: String, val copy: (InputLibrary, String, String) -> InputLibrary, val use: (String) -> Unit) - @Composable fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> Unit, - role: InputRole = InputRole.SECONDARY, layoutId: String? = null, bindingsId: String? = null, scope: String? = null, - split: InputEditorSplit? = null) { + role: InputRole = InputRole.SECONDARY, layoutId: String? = null, bindingsId: String? = null) { val context = LocalContext.current val host = LocalInputActivity.current ?: context.findActivity() as? ComponentActivity val library = remember { InputLibraries.read(context) } val savedLayout = remember { library.layouts.first { it.id == (layoutId ?: library.profile(profile).parts.getValue(role).layout) } } val savedBindings = remember { library.preset(bindingsId ?: library.profile(profile).binding(role)) } val layoutUsers = library.usersOfLayout(savedLayout.id).size - var splitting by remember { mutableStateOf(false) } + val bindingUsers = library.usersOfBindings(savedBindings.id).size val draft = remember { + 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, savedLayout) + } val defaults = InputLibraries.defaultPositions(context, library, savedLayout) - val start = if (OnScreenLayout.generated(savedLayout) && defaults != null) savedLayout.copy(elements = defaults.first + - OnScreenLayout.fit(savedLayout.elements, savedLayout.aspect.takeIf { it > 0f } ?: defaults.second, 1f, (defaults.second * 1000).roundToInt(), 1000, Rect()), - aspect = defaults.second) else savedLayout - SurfaceDraft(start, savedBindings, defaults?.first, defaults?.second ?: 0f, ControllerPrefs.snap(context)) + SurfaceDraft(savedLayout, savedBindings, defaults?.first, defaults?.second ?: 0f, gamepad, ControllerPrefs.snap(context)) } val manager = remember { context.getSystemService(DisplayManager::class.java) } var revision by remember { mutableIntStateOf(0) } + var discard by remember { mutableStateOf(false) } var failure by remember { mutableStateOf(null) } val target = remember(revision, role) { if (host is SessionActivity) host.inputEditorDisplay(role) @@ -165,23 +220,15 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> } } val remote = target != null && target.displayId != host?.window?.decorView?.display?.displayId - fun leave() { if (draft.dirty) draft.confirmDiscard = true else onDismiss() } + fun leave() { if (draft.dirty) discard = true else onDismiss() } fun save() { runCatching { - val copy = split?.takeIf { splitting } - val (layoutTarget, bindingsTarget) = if (copy != null) newInputId() to newInputId() else savedLayout.id to savedBindings.id - InputLibraries.update(context) { saved -> - val latest = copy?.copy?.invoke(saved, layoutTarget, bindingsTarget) ?: saved - val l = latest.layouts.first { it.id == layoutTarget } - val p = latest.preset(bindingsTarget) - val generated = draft.kitAtDefaults && OnScreenLayout.generated(l.copy(elements = emptyList(), kitless = false)) - val extras = draft.elements.filterNot { KitLayout.isKit(it.id) } - val edited = if (generated) l.copy(elements = extras, aspect = if (extras.isEmpty()) 0f else draft.aspect, scale = draft.layoutScale, kitless = false) - else l.copy(elements = draft.elements, aspect = draft.aspect, scale = draft.layoutScale, kitless = draft.elements.none { KitLayout.isKit(it.id) }) - latest.withLayout(edited).withPreset(p.copy(elements = draft.actions.filterKeys { id -> edited.element(id) != null }, - clicks = draft.clicks.filterKeys { id -> edited.element(id)?.hasClick == true })) + InputLibraries.update(context) { latest -> + val l = latest.layouts.first { it.id == savedLayout.id } + val p = latest.preset(savedBindings.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 } })) } - copy?.use?.invoke(bindingsTarget) }.onSuccess { onChanged(); onDismiss() }.onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) } } DisposableEffect(manager) { @@ -222,53 +269,61 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> androidx.compose.ui.graphics.Color.Transparent else MaterialTheme.colorScheme.surface) { val element = draft.element BackHandler { if (draft.properties) draft.properties = false else leave() } - val editorScope = split?.scope?.takeIf { splitting } ?: scope ?: if (layoutUsers > 1) stringResource(R.string.input_editor_shared, layoutUsers) else savedLayout.name - val splitLabel = split?.label?.takeIf { !splitting } - val propertiesEditor: @Composable (InputSurfaceElement) -> Unit = { element -> - var properties by remember(element.id) { mutableStateOf(element) } - InputActionEditor(if (draft.clickProperties) InputControl.A else element.control, - if (draft.clickProperties) draft.clickAction(element) else draft.action(element), - if (draft.clickProperties) stringResource(R.string.input_click_name, element.name) else element.name, - onBack = { draft.properties = false }, element = element, click = draft.clickProperties, - properties = { action -> - if (!draft.clickProperties) InputElementProperties(properties, action) { properties = it } - }, detail = editorScope, 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.properties = false - }) - } when { - (remote || target == null) && draft.properties && element != null -> propertiesEditor(element) + draft.properties && element != null -> { + var properties by remember(element.id) { mutableStateOf(element) } + InputActionEditor(if (draft.clickProperties) InputControl.A else element.control, + if (draft.clickProperties) draft.clickAction(element) else draft.action(element), + if (draft.clickProperties) stringResource(R.string.input_click_name, element.name) else element.name, + onBack = { draft.properties = false }, element = element, click = draft.clickProperties, + properties = { action -> + if (!draft.clickProperties) InputElementProperties(properties, action) { properties = it } + if (layoutUsers > 1) Text(stringResource(R.string.input_editor_shared, layoutUsers), + style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(bottom = 12.dp)) + }, detail = if (bindingUsers > 1) stringResource(R.string.input_shared_detail, savedBindings.name, bindingUsers) + 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.update(properties.copy(name = properties.name.trim().ifBlank { element.name })) + draft.properties = false + }) + } target == null -> SettingsPage(rememberMenuHost(), savedLayout.name, ::leave) { Text(stringResource(R.string.input_display_unavailable)) - failure?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) } - if (draft.confirmDiscard) { - Text(stringResource(R.string.input_editor_discard), style = MaterialTheme.typography.titleSmall) - SecondaryButton(stringResource(R.string.input_keep_editing)) { draft.confirmDiscard = false } - SecondaryButton(stringResource(R.string.input_discard), onClick = onDismiss) - } PrimaryButton(stringResource(R.string.input_editor_done)) { save() } } - remote -> SettingsPage(rememberMenuHost(), stringResource(R.string.input_editor_remote), ::leave, lede = editorScope) { - splitLabel?.let { SecondaryButton(it, compact = true, modifier = Modifier.padding(horizontal = 8.dp).testTag("input-editor-split")) { splitting = true } } - SurfaceToolbar(draft, ::save, ::leave, onDismiss) - failure?.let { Text(it, Modifier.padding(horizontal = 8.dp), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) } + remote -> SettingsPage(rememberMenuHost(), stringResource(R.string.input_editor_remote), ::leave, + lede = if (layoutUsers > 1) stringResource(R.string.input_editor_shared, layoutUsers) else savedLayout.name) { + SurfaceToolbar(draft, ::save, ::leave) SurfaceSelection(draft) - when (draft.popover) { EditorPopover.ADD -> AddRows(draft); EditorPopover.HIDDEN -> HiddenRows(draft); null -> Unit } } else -> Box(Modifier.fillMaxSize()) { SurfaceCanvas(draft, transparent = host is SessionActivity && role == InputRole.PRIMARY) - EditorChrome(draft, editorScope, splitLabel, { splitting = true }, failure, ::save, ::leave, onDismiss) - if (draft.properties && element != null) Surface(Modifier.align(Alignment.CenterEnd).fillMaxHeight().fillMaxWidth(.44f), - color = MaterialTheme.colorScheme.surface, shadowElevation = 12.dp) { - propertiesEditor(element) - } + FloatingSurfaceTools(draft, ::save, ::leave) } } } } + 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 + val name = context.getString(kind.label()) + " " + (draft.elements.count { it.kind == kind } + 1) + 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)) } }, + dismissButton = { PadTextButton(onClick = { discard = false }) { Text(stringResource(R.string.common_cancel)) } }) + failure?.let { AlertDialog(onDismissRequest = { failure = null }, title = { Text(stringResource(R.string.input_save_failed)) }, text = { Text(it) }, + confirmButton = { PadTextButton(onClick = { failure = null }) { Text(stringResource(R.string.common_ok)) } }) } } @Composable @@ -276,161 +331,76 @@ 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.isEnabled = !draft.properties && draft.popover == null && !draft.confirmDiscard + 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) } + view.onBeginEdit = { e, w, h -> draft.beginEdit(e, w.toFloat() / h, if (draft.hasGamepad) GamepadScaler(view.context, w, h, draft.layout) else null) } + view.onResize = { w, h -> draft.canvas = IntSize(w, h) } + view.onDisplayed = { draft.shown = it } view.onChange = { e -> if (!draft.properties) draft.elements = draft.elements.map { if (it.id == e.id) e else it } } }) } -private enum class EditorPopover { ADD, HIDDEN } - @Composable -private fun EditorBar(modifier: Modifier = Modifier, content: @Composable RowScope.() -> Unit) { - Surface(modifier, shape = RoundedCornerShape(16.dp), color = MaterialTheme.colorScheme.surface.copy(alpha = .96f), - contentColor = MaterialTheme.colorScheme.onSurface, shadowElevation = 8.dp) { - Row(Modifier.horizontalScroll(rememberScrollState()).padding(6.dp), horizontalArrangement = Arrangement.spacedBy(6.dp), - verticalAlignment = Alignment.CenterVertically, content = content) - } -} - -/** The editor's tools over the canvas: one toolbar, a bar on the selected control, and the Add and Hidden lists. */ -@Composable -private fun EditorChrome(draft: SurfaceDraft, scope: String, splitLabel: String?, onSplit: () -> Unit, failure: String?, - onSave: () -> Unit, onLeave: () -> Unit, onDiscard: () -> Unit) { - val context = LocalContext.current +private fun FloatingSurfaceTools(draft: SurfaceDraft, onSave: () -> Unit, onLeave: () -> Unit) { BoxWithConstraints(Modifier.fillMaxSize()) { - Column(Modifier.align(Alignment.TopCenter).padding(top = 10.dp).widthIn(max = maxWidth - 16.dp), - horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(6.dp)) { - EditorBar(Modifier.testTag("input-editor-tools")) { - if (draft.confirmDiscard) { - Text(stringResource(R.string.input_editor_discard), Modifier.padding(horizontal = 8.dp), style = MaterialTheme.typography.titleSmall) - SecondaryButton(stringResource(R.string.input_keep_editing), compact = true) { draft.confirmDiscard = false } - PrimaryButton(stringResource(R.string.input_discard), compact = true, onClick = onDiscard) - } else { - SecondaryButton(stringResource(R.string.common_cancel), compact = true, onClick = onLeave) - SecondaryButton(stringResource(R.string.input_editor_undo), enabled = draft.history.isNotEmpty(), compact = true) { draft.undo() } - SecondaryButton(stringResource(R.string.input_editor_add), enabled = draft.elements.size < 64, compact = true) { - draft.popover = if (draft.popover == EditorPopover.ADD) null else EditorPopover.ADD + val density = LocalDensity.current + val screenWidth = with(density) { maxWidth.toPx() } + val screenHeight = with(density) { maxHeight.toPx() } + val margin = with(density) { 8.dp.toPx() } + var panelSize by remember { mutableStateOf(IntSize.Zero) } + 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) + val panelWidth by animateDpAsState(if (draft.toolsExpanded) expandedWidth else 152.dp, label = "input-tools-width") + Surface(Modifier.offset { IntOffset(x.roundToInt(), y.roundToInt()) } + .width(panelWidth).clipToBounds() + .heightIn(max = maxHeight - 16.dp).onSizeChanged { panelSize = it }, + shape = RoundedCornerShape(18.dp), color = MaterialTheme.colorScheme.surface, + tonalElevation = 6.dp, shadowElevation = 10.dp) { + Column { + Row(Modifier.fillMaxWidth().heightIn(min = 52.dp).testTag("input-editor-tools") + .pointerInput(screenWidth, screenHeight, panelSize) { + var dragPosition = Offset.Zero + detectDragGestures(onDragStart = { dragPosition = position }) { change, delta -> + change.consume() + dragPosition = Offset((dragPosition.x + delta.x).coerceIn(margin, (screenWidth - panelSize.width - margin).coerceAtLeast(margin)), + (dragPosition.y + delta.y).coerceIn(margin, (screenHeight - panelSize.height - margin).coerceAtLeast(margin))) + draft.toolsX = dragPosition.x / screenWidth + draft.toolsY = dragPosition.y / screenHeight + } } - if (draft.defaults != null) SecondaryButton(stringResource(R.string.input_hidden_count, draft.hiddenDefaults().size), compact = true) { - draft.popover = if (draft.popover == EditorPopover.HIDDEN) null else EditorPopover.HIDDEN + .clickable { draft.toolsExpanded = !draft.toolsExpanded }.padding(horizontal = 16.dp), + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { + Text("⠿", color = MaterialTheme.colorScheme.primary) + Text(stringResource(if (draft.toolsExpanded) R.string.input_hide_tools else R.string.input_tools), style = MaterialTheme.typography.titleSmall, maxLines = 1) + } + AnimatedVisibility(draft.toolsExpanded, enter = expandVertically(expandFrom = Alignment.Top) + fadeIn(), + exit = shrinkVertically(shrinkTowards = Alignment.Top) + fadeOut()) { + Column(Modifier.requiredWidth(expandedWidth).verticalScroll(rememberScrollState())) { + HorizontalDivider() + SurfaceToolbar(draft, onSave, onLeave) + HorizontalDivider() + SurfaceSelection(draft) } - if (draft.defaults != null) SecondaryButton(stringResource(R.string.hud_reset_button), enabled = !draft.atDefaults, compact = true) { draft.reset() } - Row(verticalAlignment = Alignment.CenterVertically) { - Checkbox(draft.snap, { draft.snap = it; ControllerPrefs.setSnap(context, it) }) - Text(stringResource(R.string.ctrl_editor_snap)) - } - if (draft.elements.isNotEmpty()) { - SecondaryButton("−", enabled = draft.scale > 80, compact = true) { draft.scaleAll((draft.scale - 5).coerceAtLeast(80)) } - Text("${draft.scale}%", Modifier.widthIn(min = 44.dp).testTag("input-editor-scale"), style = MaterialTheme.typography.titleSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant) - SecondaryButton("+", enabled = draft.scale < 150, compact = true) { draft.scaleAll((draft.scale + 5).coerceAtMost(150)) } - } - PrimaryButton(stringResource(R.string.input_editor_done), compact = true, onClick = onSave) } } - Row(Modifier.background(MaterialTheme.colorScheme.background.copy(alpha = .7f), RoundedCornerShape(50)).padding(horizontal = 12.dp, vertical = 4.dp), - verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Text(scope, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - splitLabel?.let { SecondaryButton(it, compact = true, modifier = Modifier.testTag("input-editor-split"), onClick = onSplit) } - } - failure?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) } - when (draft.popover) { - EditorPopover.ADD -> EditorList { AddRows(draft) } - EditorPopover.HIDDEN -> EditorList { HiddenRows(draft) } - null -> Unit - } - } - val e = draft.element - if (e != null && !draft.properties && draft.popover == null && !draft.confirmDiscard) { - val density = LocalDensity.current - var size by remember { mutableStateOf(IntSize.Zero) } - val w = with(density) { maxWidth.toPx() } - val h = with(density) { maxHeight.toPx() } - val gap = with(density) { 12.dp.toPx() } - val margin = with(density) { 8.dp.toPx() } - val top = h * e.y - gap - size.height - val above = top > with(density) { 110.dp.toPx() } - val x = (w * (e.x + e.width / 2) - size.width / 2).coerceIn(margin, (w - size.width - margin).coerceAtLeast(margin)) - val y = if (above) top else (h * (e.y + e.height) + gap).coerceAtMost(h - size.height - margin) - EditorBar(Modifier.offset { IntOffset(x.roundToInt(), y.roundToInt()) }.onSizeChanged { size = it }.testTag("input-editor-selection")) { - SecondaryButton("−", compact = true) { draft.resizeSelected(1f / 1.1f) } - SecondaryButton("+", compact = true) { draft.resizeSelected(1.1f) } - PrimaryButton(stringResource(R.string.input_options), compact = true) { draft.clickProperties = false; draft.properties = true } - if (e.hasClick) SecondaryButton(stringResource(R.string.input_click_short), compact = true) { draft.clickProperties = true; draft.properties = true } - SecondaryButton(stringResource(R.string.input_remove_element), compact = true) { draft.remove(e.id) } - } } } } -@Composable -private fun EditorList(content: @Composable ColumnScope.() -> Unit) { - Surface(Modifier.widthIn(min = 260.dp, max = 360.dp), shape = RoundedCornerShape(16.dp), color = MaterialTheme.colorScheme.surface.copy(alpha = .97f), - contentColor = MaterialTheme.colorScheme.onSurface, shadowElevation = 8.dp) { - Column(Modifier.padding(6.dp).heightIn(max = 320.dp).verticalScroll(rememberScrollState()), content = content) - } -} - -@Composable -private fun EditorRow(title: String, action: String, onClick: () -> Unit) { - Row(Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) { - Text(title, Modifier.weight(1f), style = MaterialTheme.typography.bodyMedium) - SecondaryButton(action, compact = true, onClick = onClick) - } -} - -@Composable -private fun CloseRow(draft: SurfaceDraft) { - Row(Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 4.dp), horizontalArrangement = Arrangement.End) { - SecondaryButton(stringResource(R.string.common_close), compact = true) { draft.popover = null } - } -} - -@Composable -private fun AddRows(draft: SurfaceDraft) { - val context = LocalContext.current - CloseRow(draft) - for (control in listOf(InputControl.L3, InputControl.R3).filter { c -> draft.elements.none { it.id == "legacy:${c.id}" } }) - EditorRow(control.label, stringResource(R.string.input_editor_add)) { draft.add(InputSurfaceElement(control, .47f, .45f, .06f, .1f, buttonShape = InputButtonShape.CIRCLE)) } - for (kind in InputElementKind.entries) EditorRow(stringResource(kind.label()), stringResource(R.string.input_editor_add)) { - val w = if (kind.control.dimensions == 2) .2f else .1f - val h = if (kind.control.dimensions == 2) .35f else .16f - val name = context.getString(kind.label()) + " " + (draft.elements.count { it.kind == kind } + 1) - draft.add(InputSurfaceElement(kind.control, (1f - w) / 2, (1f - h) / 2, w, h, newInputId(), kind, name)) - } -} - -@Composable -private fun HiddenRows(draft: SurfaceDraft) { - val hidden = draft.hiddenDefaults() - CloseRow(draft) - if (hidden.isEmpty()) Text(stringResource(R.string.input_nothing_hidden), Modifier.padding(12.dp), style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant) - for (e in hidden) EditorRow(e.name, stringResource(R.string.input_restore)) { draft.add(e) } -} - @OptIn(ExperimentalLayoutApi::class) @Composable -private fun SurfaceToolbar(draft: SurfaceDraft, onSave: () -> Unit, onLeave: () -> Unit, onDiscard: () -> Unit) { +private fun SurfaceToolbar(draft: SurfaceDraft, onSave: () -> Unit, onLeave: () -> Unit) { val context = LocalContext.current - if (draft.confirmDiscard) { - FlowRow(Modifier.fillMaxWidth().padding(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Text(stringResource(R.string.input_editor_discard), style = MaterialTheme.typography.titleSmall) - SecondaryButton(stringResource(R.string.input_keep_editing), compact = true) { draft.confirmDiscard = false } - PrimaryButton(stringResource(R.string.input_discard), compact = true, onClick = onDiscard) - } - return - } FlowRow(Modifier.fillMaxWidth().padding(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { 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.popover = EditorPopover.ADD } - if (draft.defaults != null) SecondaryButton(stringResource(R.string.input_hidden_count, draft.hiddenDefaults().size), compact = true) { draft.popover = EditorPopover.HIDDEN } + 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)) @@ -438,7 +408,7 @@ private fun SurfaceToolbar(draft: SurfaceDraft, onSave: () -> Unit, onLeave: () PrimaryButton(stringResource(R.string.input_editor_done), compact = true, onClick = onSave) } if (draft.elements.isNotEmpty()) SliderRow(stringResource(R.string.ctrl_size), null, draft.scale, 80..125, step = 5, - format = { "$it%" }, modifier = Modifier.testTag("input-editor-scale")) { draft.scaleAll(it) } + format = { "$it%" }, modifier = Modifier.testTag("input-editor-scale")) { draft.scaleAll(context, it) } } @OptIn(ExperimentalLayoutApi::class) 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..d3922ef0c5 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt @@ -5,11 +5,14 @@ import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint +import android.graphics.Rect import android.view.HapticFeedbackConstants import android.view.MotionEvent import android.view.ViewConfiguration +import android.view.WindowInsets import android.widget.FrameLayout import com.droiddeck.launcher.input.OnScreenLayout +import com.droiddeck.launcher.input.PadKit import com.droiddeck.launcher.input.SavedInputLayout import com.droiddeck.launcher.input.InputSurfaceElement import com.droiddeck.launcher.input.InputSurfaceStyle @@ -22,9 +25,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 @@ -34,6 +42,8 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { var onSelect: (String?) -> Unit = {} var onBeginEdit: (List, Int, Int) -> Unit = { _, _, _ -> } var onChange: (InputSurfaceElement) -> Unit = {} + var onResize: (Int, Int) -> Unit = { _, _ -> } + var onDisplayed: (List) -> Unit = {} private val preview = InputSurfaceView(context) private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.rgb(26, 159, 255); strokeWidth = 2 * resources.displayMetrics.density } private val radius = 14 * resources.displayMetrics.density @@ -50,16 +60,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) { 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 0c297e0d58..79ee2d8491 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt @@ -1,12 +1,17 @@ package com.droiddeck.launcher.ui +import com.droiddeck.launcher.R + import android.annotation.SuppressLint import android.content.Context import android.graphics.BitmapFactory import android.graphics.Canvas import android.graphics.Color 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 android.graphics.drawable.GradientDrawable import android.view.Gravity @@ -31,9 +36,6 @@ import com.droiddeck.launcher.input.InputAction import com.droiddeck.launcher.input.InputButtonIcons import com.droiddeck.launcher.input.InputButtonShape import com.droiddeck.launcher.input.InputButtonImages -import com.droiddeck.launcher.input.KitLayout -import com.droiddeck.launcher.input.OnScreenLayout -import com.droiddeck.launcher.input.SavedInputLayout import com.droiddeck.launcher.input.PadBridge import com.droiddeck.launcher.input.PadKit import com.droiddeck.launcher.input.pcKeyLabel @@ -50,15 +52,15 @@ class InputSurfaceView( val inputRole: InputRole = InputRole.SECONDARY, private var surfaceStyle: InputSurfaceStyle = InputSurfaceStyle(), private val haptics: Boolean = inputRole != InputRole.PRIMARY, - kit: PadKit = PadKit.current(context), ) : FrameLayout(context) { - var kit: PadKit = kit - set(value) { if (field != value) { field = value; customCanvas?.let { c -> for (i in 0 until c.childCount) c.getChildAt(i).invalidate() } } } - private val art = PadArt(context) private val content = FrameLayout(context) 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) } @@ -137,35 +139,24 @@ 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) { view.alpha = surfaceStyle.opacity / 100f * ((view.tag as? InputSurfaceElement)?.opacity ?: 1f) + (view as? Surface)?.tint = surfaceStyle.tint view.invalidate() } - private var generated: SavedInputLayout? = null - - /** Shows [layout]; a layout that has no elements of its own gets the virtual controller's defaults at this view's size. */ - fun showLayout(layout: SavedInputLayout?) { - generated = layout?.takeIf(OnScreenLayout::generated) - kit = PadKit.current(context) - updateStyle(layout?.style ?: InputSurfaceStyle()) - updateCustomLayout(generated?.let { OnScreenLayout.elements(context, it, width, height, android.graphics.Rect(), null) } ?: layout?.elements.orEmpty()) - } - - override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { - super.onSizeChanged(w, h, oldw, oldh) - val layout = generated ?: return - post { if (generated === layout) updateCustomLayout(OnScreenLayout.elements(context, layout, width, height, android.graphics.Rect(), null)) } - } - fun updateCustomLayout(requested: List) { requestedLayout = requested val layout = surfaceStyle.shown(requested) @@ -191,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 @@ -208,14 +200,30 @@ 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(::adaptive) + canvas.clipChildren = customLayout.none { it.kind == InputElementKind.STICK && (classic(it) || adaptive(it)) } for (element in customLayout) { 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, 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() } }) @@ -224,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()) { @@ -285,12 +321,64 @@ class InputSurfaceView( private fun feedback(view: View, type: Int) { if (haptics) view.performHapticFeedback(type) } private abstract class Surface(context: Context) : View(context) { + var tint: Int? = null protected val density = resources.displayMetrics.density + protected val rect = RectF() + private val fill = Paint(Paint.ANTI_ALIAS_FLAG) + private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE } protected val labelPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD) - color = TEXT } + protected val captionPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + textAlign = Paint.Align.CENTER + color = TEXT_DIM + } + + protected fun drawSurface(canvas: Canvas, lit: Boolean, shape: InputButtonShape = InputButtonShape.ROUNDED, classic: Boolean = false) { + val inset = if (classic && tint != null) 0.75f * density else density + rect.set(inset, inset, width - inset, height - inset) + val radius = when (shape) { InputButtonShape.CIRCLE, InputButtonShape.PILL -> min(width, height) / 2f; InputButtonShape.RECTANGLE -> 2 * density; else -> CORNER * density } + val color = tint + if (classic && color != null) { + val corner = if (shape == InputButtonShape.PILL) radius * 0.55f else radius + fill.color = if (lit) shade(color, 160, 1f) else shade(color, 80, 0.12f) + canvas.drawRoundRect(rect, corner, corner, fill) + stroke.color = if (lit) light(color, 230, 0.7f) else light(color, 150, 0.25f) + stroke.strokeWidth = 1.5f * density + canvas.drawRoundRect(rect, corner, corner, stroke) + return + } + fill.color = tint?.let { color -> (color and 0x00ffffff) or ((if (lit) 140 else 48) shl 24) } ?: if (lit) ACCENT_WASH else SURFACE + canvas.drawRoundRect(rect, radius, radius, fill) + stroke.color = tint?.let { color -> (color and 0x00ffffff) or ((if (lit) 255 else 160) shl 24) } ?: if (lit) ACCENT else LINE + stroke.strokeWidth = (if (lit) 2f else 1f) * density + canvas.drawRoundRect(rect, radius, radius, stroke) + } + + protected fun drawCircle(canvas: Canvas, x: Float, y: Float, radius: Float, fillColor: Int, strokeColor: Int) { + fill.color = fillColor + canvas.drawCircle(x, y, radius, fill) + stroke.color = strokeColor + stroke.strokeWidth = 1.5f * density + canvas.drawCircle(x, y, radius, stroke) + } + + protected fun drawKeyboard(canvas: Canvas, x: Float, y: Float, lit: Boolean) { + val color = tint ?: return + stroke.color = if (lit) light(color, 230, 0.7f) else light(color, 150, 0.25f) + stroke.strokeWidth = 1.5f * density + rect.set(x - 10 * density, y - 7 * density, x + 10 * density, y + 7 * density) + canvas.drawRoundRect(rect, 2 * density, 2 * density, stroke) + for (row in 0..1) for (col in 0..2) { + val kx = x + (-6f + col * 5f) * density + val ky = y + (-3f + row * 4f) * density + canvas.drawLine(kx, ky, kx + 2 * density, ky, stroke) + } + canvas.drawLine(x - 5 * density, y + 4 * density, x + 5 * density, y + 4 * density, stroke) + } + + protected fun textColor(lit: Boolean) = if (lit) Color.WHITE else tint?.let { light(it, 210, 0.75f) } ?: TEXT } private inner class HoldButton(context: Context, private val element: InputSurfaceElement, private val source: InputSurfaceSource?) : Surface(context) { @@ -310,61 +398,51 @@ 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 w = width.toFloat(); val h = height.toFloat() - val c = element.control - val native = element.id == "legacy:${c.id}" && element.showLabel && element.icon == 0 && bitmap == null && - (element.name == c.label || element.name == kit.name(c)) && (c !in FACE || element.buttonShape == InputButtonShape.CIRCLE) - when { - element.id == KitLayout.KEYBOARD_ID && element.icon == InputButtonIcons.KEYBOARD -> art.system(canvas, w, h, PadArt.Shape.ROUND, PadArt.Icon.KEYBOARD, lit) - native && c in FACE -> art.face(canvas, w / 2f, h / 2f, min(w, h) / 2f - art.dp(2f), c, kit, lit) - native && c in SHOULDERS -> art.shoulder(canvas, w, h, c, kit, lit) - native && c in GRIPS -> art.grip(canvas, w, h, c.label, lit) - native && (c == InputControl.L3 || c == InputControl.R3) -> art.small(canvas, w, h, c.label, lit) - native && c in SYSTEM -> systemLook(c).let { (shape, icon) -> art.system(canvas, w, h, shape, icon, lit) } - else -> custom(canvas, w, h, lit) + 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 } - } - - private fun systemLook(c: InputControl): Pair = when { - kit.steam -> when (c) { - InputControl.SELECT -> PadArt.Shape.CHIP to PadArt.Icon.VIEW - InputControl.START -> PadArt.Shape.CHIP to PadArt.Icon.MENU - InputControl.GUIDE -> PadArt.Shape.PILL to PadArt.Icon.STEAM - else -> PadArt.Shape.PILL to PadArt.Icon.QAM - } - kit.playStation -> when (c) { - InputControl.SELECT -> PadArt.Shape.PILL to if (kit == PadKit.DUALSHOCK) PadArt.Icon.SHARE else PadArt.Icon.CREATE - InputControl.START -> PadArt.Shape.PILL to if (kit == PadKit.DUALSHOCK) PadArt.Icon.OPTIONS else PadArt.Icon.MENU - InputControl.GUIDE -> PadArt.Shape.ROUND to PadArt.Icon.HOME - else -> PadArt.Shape.ROUND to PadArt.Icon.QAM - } - else -> PadArt.Shape.ROUND to when (c) { - InputControl.SELECT -> PadArt.Icon.BACK - InputControl.START -> PadArt.Icon.START - InputControl.GUIDE -> PadArt.Icon.HOME - else -> PadArt.Icon.QAM - } - } - - private fun custom(canvas: Canvas, w: Float, h: Float, lit: Boolean) { - val inset = art.dp(2f) - art.glass(canvas, when (element.buttonShape) { - InputButtonShape.CIRCLE -> art.circle(w / 2f, h / 2f, min(w, h) / 2f - inset) - InputButtonShape.PILL -> art.roundRect(inset, inset, w - inset, h - inset, min(w, h) / 2f) - InputButtonShape.RECTANGLE -> art.roundRect(inset, inset, w - inset, h - inset, art.dp(4f)) - InputButtonShape.ROUNDED -> art.roundRect(inset, inset, w - inset, h - inset, min(w, h) * .22f) - }, lit) - labelPaint.color = if (lit) PadArt.ON_ACCENT else PadArt.INK + drawSurface(canvas, lit, element.buttonShape, classic) + val cx = width / 2f + labelPaint.color = if (classic && tint != null) textColor(lit) else if (lit) ACCENT else TEXT bitmap?.let { - val scale = min(w * .84f / it.width, h * .84f / it.height) - imageRect.set(w / 2f - it.width * scale / 2, (h - it.height * scale) / 2, w / 2f + it.width * scale / 2, (h + it.height * scale) / 2) + val scale = min(width * .84f / it.width, height * .84f / it.height) + imageRect.set(cx - it.width * scale / 2, (height - it.height * scale) / 2, + cx + it.width * scale / 2, (height + it.height * scale) / 2) canvas.drawBitmap(it, null, imageRect, labelPaint) return } - if (element.icon != 0 && InputButtonIcons.draw(canvas, element.icon, w / 2f, h / 2f, min(w, h) * .6f, labelPaint, symbol)) return - if (element.showLabel) art.text(canvas, element.name, w / 2f, h / 2f, min(h * .34f, 26 * density), labelPaint.color, w * .82f) + if (classic && element.id == "builtin:keyboard" && element.icon == InputButtonIcons.KEYBOARD) { drawKeyboard(canvas, cx, height / 2f, lit); return } + if (element.icon != 0 && InputButtonIcons.draw(canvas, element.icon, cx, height / 2f, min(width, height) * .68f, labelPaint, symbol)) return + if (!element.showLabel) return + labelPaint.style = Paint.Style.FILL + 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 * .34f, direction, labelPaint); return } + val glyph = glyph(element.control) + labelPaint.textSize = when { + element.buttonShape == InputButtonShape.PILL -> height / 2f * 0.8f + glyph.length > 2 -> 11 * density + else -> radius * if (glyph.length == 2) 0.62f else 0.85f + } + canvas.drawText(glyph, cx, height / 2f + labelPaint.textSize * .35f, labelPaint) + return + } + labelPaint.textSize = min(height * .3f, 30 * density) + val labelWidth = labelPaint.measureText(element.name) + if (labelWidth > width * .84f) labelPaint.textSize *= width * .84f / labelWidth + canvas.drawText(element.name, cx, height / 2f + labelPaint.textSize * .35f, labelPaint) } fun press(pointer: Int, pressed: Boolean, cancelled: Boolean = false) { @@ -382,10 +460,13 @@ 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 source: InputSurfaceSource? = null) : Surface(context) { + 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 private val mouse = TouchpadGestures(ViewConfiguration.get(context).scaledTouchSlop.toFloat(), object : PointerGestures.Listener { @@ -402,9 +483,33 @@ class InputSurfaceView( private var clicked = false private var fingerX = 0f private var fingerY = 0f + private val guide = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; color = GUIDE } + private val dot = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = ACCENT } + private val glow = Paint(Paint.ANTI_ALIAS_FLAG) override fun onDraw(canvas: Canvas) { - art.trackpad(canvas, width.toFloat(), height.toFloat(), touching || clicked, fingerX, fingerY) + if (!captioned || stock && artwork?.steam == true) { + art.trackpad(canvas, width.toFloat(), height.toFloat(), touching || clicked, fingerX, fingerY) + return + } + drawSurface(canvas, clicked) + val cx = width / 2f + val cy = height / 2f + guide.strokeWidth = 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 + 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) + canvas.drawCircle(fingerX, fingerY, radius, glow) + canvas.drawCircle(fingerX, fingerY, (if (clicked) 16 else 12) * density, dot) + } } @SuppressLint("ClickableViewAccessibility") @@ -476,31 +581,67 @@ class InputSurfaceView( private var originY = 0f private var knobX = 0f private var knobY = 0f + private val ring = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE } + private val knob = Paint(Paint.ANTI_ALIAS_FLAG) + val adaptive get() = adaptive(element) - private fun radius() = (min(width, height) / 2f - 3 * density).coerceAtLeast(1f) - - fun reach() = radius() * STICK_REACH + fun reach() = min(width, height) * if (classic(element)) CLASSIC_REACH else PANEL_REACH fun captures(x: Float, y: Float): Boolean { val cx = centreX() - val dx = when (element.control) { InputControl.LS -> maxOf(0f, x - cx); InputControl.RS -> minOf(0f, x - cx); else -> x - cx } - val limit = radius() * ADAPTIVE_REACH + val dx = if (element.control == InputControl.LS) maxOf(0f, x - cx) else x - cx + val limit = reach() * ADAPTIVE_REACH return dx * dx + (y - height / 2f) * (y - height / 2f) <= limit * limit } - fun centreX() = width / 2f + fun centreX() = when { + !classic(element) || width <= height -> width / 2f + element.control == InputControl.LS -> width - height / 2f + else -> height / 2f + } override fun onDraw(canvas: Canvas) { if (hideWhenIdle && !touching) return val cx = if (touching) originX else centreX() val cy = if (touching) originY else height / 2f - val r = radius() - val travel = r * KNOB_TRAVEL / reach().coerceAtLeast(1f) - art.stick(canvas, cx, cy, r, kit, knobX * travel, knobY * travel, touching || clicking) + 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 + drawCircle(canvas, cx, cy, radius, + if (touching) shade(color, 160, 1f) else shade(color, 60, 0.12f), if (touching) light(color, 230, 0.7f) else light(color, 150, 0.25f)) + val knobRadius = radius * 0.46f + drawCircle(canvas, cx + knobX, cy + knobY, knobRadius, + if (touching || clicking) shade(color, 160, 1f) else shade(color, 120, 0.35f), if (touching) light(color, 230, 0.7f) else light(color, 150, 0.25f)) + if (!element.showLabel) return + labelPaint.color = textColor(touching) + if (drawDirectionLabels(canvas, source, false, cx, cy, radius * 0.66f, radius * 0.34f, labelPaint)) return + labelPaint.textSize = knobRadius * 0.8f + val label = if (element.name == element.control.label) glyph(element.control) else element.name + canvas.drawText(label, cx + knobX, cy + knobY + labelPaint.textSize * 0.35f, labelPaint) + return + } + drawSurface(canvas, clicking) + ring.strokeWidth = 2 * density + ring.color = if (touching) ACCENT else LINE + canvas.drawCircle(cx, cy, reach(), ring) + knob.color = if (touching) ACCENT else KNOB + canvas.drawCircle(cx + knobX, cy + knobY, reach() * 0.45f, knob) if (!element.showLabel) return - labelPaint.color = PadArt.INK - drawDirectionLabels(canvas, source, false, cx, cy, r * .66f, r * .34f, labelPaint) + labelPaint.color = if (touching) ACCENT else TEXT + drawDirectionLabels(canvas, source, false, cx, cy, reach() * 1.32f, reach() * 0.68f, labelPaint) } @SuppressLint("ClickableViewAccessibility") @@ -563,20 +704,34 @@ class InputSurfaceView( } private inner class DirectionPad(context: Context, private val element: InputSurfaceElement, private val source: InputSurfaceSource? = null) : View(context) { + private val density = resources.displayMetrics.density private var held = 0 + private val arm = Paint(Paint.ANTI_ALIAS_FLAG) private val label = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER; typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD); color = TEXT } + private val rect = RectF() override fun onDraw(canvas: Canvas) { - val labels = element.showLabel && directionLabels(context, source?.directions, true).isNotEmpty() - art.dpad(canvas, width.toFloat(), height.toFloat(), kit, held, chevrons = !labels) - if (!labels) return - val half = min(width, height) / 2f - drawDirectionLabels(canvas, source, true, width / 2f, height / 2f, half * .68f, half * .32f, label) + val size = min(width, height) * 0.86f + val cx = width / 2f + val cy = height / 2f + val half = size / 2f + val thick = size / 3f / 2f + fun armRect(bit: Int, l: Float, t: Float, r: Float, b: Float) { + arm.color = if (held and bit != 0) ACCENT else KNOB + rect.set(l, t, r, b) + canvas.drawRoundRect(rect, 8 * density, 8 * density, arm) + } + armRect(1, cx - thick, cy - half, cx + thick, cy - thick) + armRect(4, cx - thick, cy + thick, cx + thick, cy + half) + armRect(8, cx - half, cy - thick, cx - thick, cy + thick) + armRect(2, cx + thick, cy - thick, cx + half, cy + thick) + arm.color = KNOB + canvas.drawRect(cx - thick, cy - thick, cx + thick, cy + thick, arm) + if (element.showLabel) drawDirectionLabels(canvas, source, true, cx, cy, (half + thick) / 2f, thick * 1.7f, label) } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { - if (event.actionMasked == MotionEvent.ACTION_CANCEL) { source?.cancel(); held = 0; invalidate(); return true } val bits = when (event.actionMasked) { MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> { val dx = event.getX(0) - width / 2f @@ -611,21 +766,48 @@ class InputSurfaceView( companion object { private const val CLICK_MS = 300L private const val STICK_TAP_MS = 200L - private const val STICK_REACH = .62f - private const val KNOB_TRAVEL = .54f + private const val CLASSIC_REACH = 0.5f + private const val PANEL_REACH = 0.30f private const val HIT_SLACK = 0.25f private const val ADAPTIVE_CLEARANCE_PX = 5f - private const val ADAPTIVE_REACH = 1.71f + private val ADAPTIVE_REACH = 1.4f * kotlin.math.sqrt(1.5f) + + + private const val CORNER = 20f private const val CORNER_PILL = 22f + private val ACCENT = Color.rgb(0x1A, 0x9F, 0xFF) + private val ACCENT_WASH = Color.argb(0x2E, 0x1A, 0x9F, 0xFF) + private val ACCENT_GLOW = Color.argb(0x66, 0x1A, 0x9F, 0xFF) + private val ON_ACCENT = Color.rgb(0x03, 0x11, 0x1F) internal val SURFACE = Color.rgb(0x0A, 0x0B, 0x0D) internal val LINE = Color.rgb(0x26, 0x29, 0x2E) + private val GUIDE = Color.rgb(0x16, 0x18, 0x1B) internal val TEXT = Color.rgb(0xF2, 0xF4, 0xF7) - private val FACE = setOf(InputControl.A, InputControl.B, InputControl.X, InputControl.Y) - private val SHOULDERS = setOf(InputControl.LB, InputControl.RB, InputControl.LT, InputControl.RT) - private val GRIPS = setOf(InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5) - private val SYSTEM = setOf(InputControl.SELECT, InputControl.START, InputControl.GUIDE, InputControl.QAM) + private val TEXT_DIM = Color.rgb(0x7A, 0x80, 0x8A) + private val KNOB = Color.rgb(0x2A, 0x2D, 0x33) - private fun adaptive(element: InputSurfaceElement) = element.kind == InputElementKind.STICK && element.floating + private fun adaptive(element: InputSurfaceElement) = element.kind == InputElementKind.STICK && element.floating && element.hideWhenIdle + + private fun classic(element: InputSurfaceElement) = (element.id == "legacy:${element.control.id}" || element.id == "builtin:keyboard") && + (element.buttonShape == InputButtonShape.CIRCLE || element.buttonShape == InputButtonShape.PILL) + + private val DIRECTIONS = listOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT) + + internal fun shade(tint: Int, alpha: Int, f: Float) = + Color.argb(alpha, (Color.red(tint) * f).toInt(), (Color.green(tint) * f).toInt(), (Color.blue(tint) * f).toInt()) + + internal fun light(tint: Int, alpha: Int, f: Float) = Color.argb(alpha, (Color.red(tint) + (255 - Color.red(tint)) * f).toInt(), + (Color.green(tint) + (255 - Color.green(tint)) * f).toInt(), (Color.blue(tint) + (255 - Color.blue(tint)) * f).toInt()) + + private fun glyph(control: InputControl) = when (control) { + InputControl.LS -> "L" + InputControl.RS -> "R" + InputControl.SELECT -> "⧉" + InputControl.START -> "☰" + InputControl.GUIDE -> "◉" + InputControl.QAM -> "⋯" + else -> control.id.uppercase() + } private val CARDINAL = listOf(0f to -1f, 1f to 0f, 0f to 1f, -1f to 0f) private val DIAGONAL = listOf(.7071f to -.7071f, .7071f to .7071f, -.7071f to .7071f, -.7071f to -.7071f) @@ -650,6 +832,16 @@ class InputSurfaceView( return labels.isNotEmpty() } + private fun drawArrow(canvas: Canvas, x: Float, y: Float, size: Float, direction: Int, paint: Paint) { + val (fx, fy) = when (direction) { 0 -> 0f to -1f; 1 -> 1f to 0f; 2 -> 0f to 1f; else -> -1f to 0f } + val path = Path() + path.moveTo(x + fx * size, y + fy * size) + path.lineTo(x - fx * size * 0.7f - fy * size, y - fy * size * 0.7f + fx * size) + path.lineTo(x - fx * size * 0.7f + fy * size, y - fy * size * 0.7f - fx * size) + path.close() + canvas.drawPath(path, paint) + } + internal fun dp(context: Context, value: Int): Int = (value * context.resources.displayMetrics.density + 0.5f).toInt() internal fun outline(context: Context, radius: Float, fill: Int) = GradientDrawable().apply { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ManageDrawerPages.kt b/app/src/main/java/com/droiddeck/launcher/ui/ManageDrawerPages.kt new file mode 100644 index 0000000000..30a9c554f9 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/ManageDrawerPages.kt @@ -0,0 +1,93 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.DragHandle +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.focus.focusProperties +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.activity.compose.BackHandler +import com.droiddeck.launcher.R + +@Composable +internal fun ManageDrawerPages(offeredNow: List, modifier: Modifier = Modifier, releaseSignal: Int = 0, onDone: () -> Unit) { + val ctx = LocalContext.current + val current by rememberUpdatedState(offeredNow) + val previewing = DevPreview.drawer != null + DisposableEffect(Unit) { onDispose { DrawerPages.heldFrom = null } } + DisposableEffect(previewing) { onDispose { if (previewing) DrawerPages.load(ctx) } } + val colors = MaterialTheme.colorScheme + BackHandler { onDone() } + Column(modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + stringResource(R.string.drawer_manage_pages), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, + color = colors.onBackground, modifier = Modifier.weight(1f), + ) + if (!DrawerPages.isDefault()) DrawerOutlineButton(stringResource(R.string.drawer_pages_reset)) { DrawerPages.reset(ctx) } + Spacer(Modifier.width(8.dp)) + DrawerOutlineButton(stringResource(R.string.drawer_pages_done), onClick = onDone) + } + SortableRows( + rows = { current.map { it.name } }, + commit = { names -> DrawerPages.rearrange(ctx, names.mapNotNull { n -> current.firstOrNull { it.name == n } }) }, + movable = { true }, + rowHeight = STORE_ROW, handleWidth = STORE_HANDLE, + releaseSignal = releaseSignal, + onGrab = { before -> DrawerPages.heldFrom = before?.mapNotNull { n -> current.firstOrNull { it.name == n } } }, + onActivate = { name -> + current.firstOrNull { it.name == name }?.let { DrawerPages.setHidden(ctx, it, it !in DrawerPages.hidden) } + }, + ) { name, held, offset, hint, rowModifier, onFocus -> + val page = current.first { it.name == name } + val shown = page !in DrawerPages.hidden + val pal = LocalPalette.current + val label = stringResource(page.title) + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + SortRowFrame(held, offset, rowModifier.testTag("drawer-page-row-$name"), hot, src, onFocus) { + Box(contentAlignment = Alignment.Center, modifier = Modifier.size(width = STORE_HANDLE, height = STORE_ROW)) { + Icon(Icons.Filled.DragHandle, null, tint = if (held) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) + } + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier.weight(1f).alpha(if (shown) 1f else 0.5f), + ) { + Icon(page.icon, null, tint = colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) + Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + if (hint != null) KeyHint("Y", hint) + ToggleSwitch( + shown, DrawerPages.hideable(page), label, + Modifier.testTag("drawer-page-shown-$name").focusProperties { canFocus = false }, + ) { DrawerPages.setHidden(ctx, page, !it) } + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt b/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt index 7e732d4fe4..39c4badb7e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt @@ -221,8 +221,8 @@ internal fun SideSheet(open: Boolean, onClose: () -> Unit, returnFocus: FocusReq } } -private val STORE_ROW = 60.dp -private val STORE_HANDLE = 44.dp +internal val STORE_ROW = 60.dp +internal val STORE_HANDLE = 44.dp @Composable internal fun ManageStoresSheet() { @@ -302,7 +302,7 @@ private fun StoreSortRow( } @Composable -private fun SortRowFrame( +internal fun SortRowFrame( held: Boolean, offset: Float, modifier: Modifier, hot: Boolean, src: MutableInteractionSource, onFocus: (Boolean) -> Unit, content: @Composable androidx.compose.foundation.layout.RowScope.() -> Unit, ) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt index 8ff82e86b2..73580d8676 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -59,6 +59,8 @@ class ModeSettings( val panelSize: Pair = 1280 to 720, val hdr: Boolean, val hdrReason: String?, + val hdrDisplay: Boolean = true, + val zeroCopy: Boolean = true, val gpuDrivers: String? = null, val upscaler: Int = 0, val upscaleSharpness: Int = 75, @@ -85,6 +87,7 @@ class ModeSettings( val picturePosition: String? = null, val integerScaling: Boolean? = null, val stretch16x9: Boolean? = null, + val avoidNotch: Boolean? = null, val steamClientArch: String? = null, val returnAfterGame: Boolean? = null, val shaderPrecache: Boolean? = null, @@ -114,6 +117,7 @@ class ModeSettings( class ModeSettingsActions( val onResolution: (String) -> Unit, val onHdr: (Boolean) -> Unit, + val onZeroCopy: (Boolean) -> Unit = {}, val onGpuDrivers: () -> Unit = {}, val onUpscaler: (Int) -> Unit = {}, val onUpscaleSharpness: (Int) -> Unit = {}, @@ -142,6 +146,7 @@ class ModeSettingsActions( val onPicturePosition: (String) -> Unit = {}, val onIntegerScaling: (Boolean) -> Unit = {}, val onStretch16x9: (Boolean) -> Unit = {}, + val onAvoidNotch: (Boolean) -> Unit = {}, val onSteamRepair: () -> Unit = {}, val onSteamClientArch: (String) -> Unit = {}, val onMangoapp: (Boolean) -> Unit = {}, @@ -250,6 +255,11 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: listOf(false to stringResource(R.string.display_preserve), true to stringResource(R.string.display_stretch)), s.stretch16x9 && canStretch, enabled = canStretch, onPick = a.onStretch16x9) } + s.avoidNotch?.let { enabled -> + ToggleRow(host, "avoid-notch", stringResource(R.string.display_avoid_notch), + stringResource(R.string.display_avoid_notch_hint), checked = enabled, onChange = a.onAvoidNotch) + } + ToggleRow(host, "zero-copy", stringResource(R.string.display_zero_copy), null, checked = s.zeroCopy, onChange = a.onZeroCopy) } SettingsGroup(stringResource(R.string.display_image_scaling)) { s.integerScaling?.let { enabled -> @@ -276,9 +286,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, ) } @@ -286,9 +295,7 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: extras.drivers(s.gpuDrivers) } if (tab == SheetTab.CONTROLS) { - SettingsGroup(stringResource(R.string.drawer_page_controller)) { - ActionRow(stringResource(R.string.input_remap_buttons), null, stringResource(R.string.ctrl_edit), a.onInputSettings) - } + InputQuickSettings(host, desktop = s.mode == SessionService.MODE_DESKTOP, onEdit = a.onInputSettings) SettingsGroup(if (steam) stringResource(R.string.mode_touch_controls) else stringResource(R.string.mode_touch)) { ChoiceRow( host, "touch", stringResource(R.string.mode_touch), null, @@ -301,6 +308,8 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: 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), ), s.oscMode, note = stringResource(R.string.mode_osc_note), onPick = a.onOsc, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PadArt.kt b/app/src/main/java/com/droiddeck/launcher/ui/PadArt.kt index bf74368488..f92e694241 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PadArt.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PadArt.kt @@ -11,7 +11,6 @@ import android.graphics.RadialGradient import android.graphics.RectF import android.graphics.Shader import android.graphics.Typeface -import androidx.core.graphics.PathParser import com.droiddeck.launcher.input.DpadStyle import com.droiddeck.launcher.input.FaceGlyphs import com.droiddeck.launcher.input.InputControl @@ -25,7 +24,7 @@ import kotlin.math.sin /** The on-screen controls' shared drawing: one glass material, shaped per virtual controller. */ internal class PadArt(context: Context) { - val density = context.resources.displayMetrics.density + 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 } @@ -39,7 +38,47 @@ internal class PadArt(context: Context) { private var shineTop = Float.NaN private var shineHeight = Float.NaN - fun dp(value: Float) = value * density + private fun dp(value: Float) = value * density + + fun button(canvas: Canvas, width: Int, height: Int, control: InputControl, kit: PadKit, pressed: Boolean): Boolean { + val w = width.toFloat() + val h = height.toFloat() + if (min(w, h) <= dp(4f)) return false + when (control) { + InputControl.A, InputControl.B, InputControl.X, InputControl.Y -> + face(canvas, w / 2f, h / 2f, min(w, h) / 2f - dp(2f), control, kit, pressed) + InputControl.LB, InputControl.RB, InputControl.LT, InputControl.RT -> shoulder(canvas, w, h, control, kit, pressed) + InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5 -> grip(canvas, w, h, control.label, pressed) + InputControl.L3, InputControl.R3 -> small(canvas, w, h, control.label, pressed) + InputControl.SELECT, InputControl.START, InputControl.GUIDE, InputControl.QAM -> { + val (shape, icon) = systemLook(kit, control) + system(canvas, w, h, shape, icon, pressed) + } + else -> return false + } + return true + } + + private fun systemLook(kit: PadKit, control: InputControl): Pair = when { + kit.steam -> when (control) { + InputControl.SELECT -> Shape.CHIP to Icon.VIEW + InputControl.START -> Shape.CHIP to Icon.MENU + InputControl.GUIDE -> Shape.PILL to Icon.STEAM + else -> Shape.PILL to Icon.QAM + } + kit.playStation -> when (control) { + InputControl.SELECT -> Shape.PILL to if (kit == PadKit.DUALSHOCK) Icon.SHARE else Icon.CREATE + InputControl.START -> Shape.PILL to if (kit == PadKit.DUALSHOCK) Icon.OPTIONS else Icon.MENU + InputControl.GUIDE -> Shape.ROUND to Icon.HOME + else -> Shape.ROUND to Icon.QAM + } + else -> Shape.ROUND to when (control) { + InputControl.SELECT -> Icon.BACK + InputControl.START -> Icon.START + InputControl.GUIDE -> Icon.HOME + else -> Icon.QAM + } + } fun glass(canvas: Canvas, shape: Path, pressed: Boolean, tint: Int = BODY) { shape.computeBounds(rect, false) @@ -127,7 +166,7 @@ internal class PadArt(context: Context) { } enum class Shape { ROUND, PILL, CHIP } - enum class Icon { VIEW, MENU, QAM, KEYBOARD, BACK, START, CREATE, HOME, STEAM, SHARE, OPTIONS, MARK } + 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 @@ -179,22 +218,9 @@ internal class PadArt(context: Context) { text(canvas, when (icon) { Icon.STEAM -> "STEAM"; Icon.SHARE -> "SHARE"; else -> "OPTIONS" }, cx, cy, 14 * u, color, size * 1.9f) ink.letterSpacing = 0f } - Icon.MARK -> mark(canvas, cx, cy, size * .5f, color, if (color == ON_ACCENT) ON_ACCENT else ACCENT) } } - fun mark(canvas: Canvas, cx: Float, cy: Float, radius: Float, ink: Int, orb: Int) { - val k = radius / 111.86f - canvas.save() - canvas.translate(cx - 71.98f * k, cy - 111.86f * k) - canvas.scale(k, k) - fill.shader = null; fill.color = ink - canvas.drawPath(MARK, fill) - fill.color = orb - canvas.drawCircle(63.98f, 111.86f, 55.98f, fill) - canvas.restore() - } - 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 @@ -216,6 +242,7 @@ internal class PadArt(context: Context) { 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 -> { @@ -232,7 +259,7 @@ internal class PadArt(context: Context) { 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) { + 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, @@ -269,6 +296,7 @@ internal class PadArt(context: Context) { } 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) @@ -327,12 +355,6 @@ internal class PadArt(context: Context) { fill.color = ACCENT; canvas.drawCircle(fx, fy, dp(5f), fill) } - fun label(canvas: Canvas, w: Float, h: Float, round: Boolean, value: String, pressed: Boolean) { - val inset = dp(2f) - glass(canvas, if (round) circle(w / 2f, h / 2f, min(w, h) / 2f - inset) else roundRect(inset, inset, w - inset, h - inset, min(w, h) * .25f), pressed) - text(canvas, value, w / 2f, h / 2f, min(h * .38f, dp(18f)), if (pressed) ON_ACCENT else INK, w * .82f) - } - companion object { const val VISUAL = .72f val ACCENT = Color.rgb(0x1A, 0x9F, 0xFF) @@ -352,8 +374,5 @@ internal class PadArt(context: Context) { 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)) - private const val MARK_DATA = "M-31.98 0H56.055V40.489A71.81 71.81 0 0 0 56.055 183.231V223.72H-31.98Z" + - "M71.885 0.28A111.86 111.86 0 0 1 71.885 223.44V183.234A71.81 71.81 0 0 0 71.885 40.486Z" - val MARK: Path by lazy { PathParser.createPathFromPathData(MARK_DATA) } } } 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 486061bf74..6944d5a302 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt @@ -245,7 +245,8 @@ class SecondScreenPresentation( if (!created || !currentMode.controls) return val controls = controlsView ?: return val layout = panelLayout(currentMode) - controls.showLayout(layout) + controls.updateCustomLayout(layout?.elements.orEmpty()) + controls.updateStyle(layout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle()) } fun showKeyboard(): Boolean { @@ -292,7 +293,8 @@ class SecondScreenPresentation( if (mode == SecondScreenMode.DECK_CONTROLS) deckPanel.value = SessionPrefs.deckPanel(context) bar(mode) val layout = panelLayout(mode) - val controls = InputSurfaceView(context, pad).also { it.showLayout(layout) } + val controls = InputSurfaceView(context, pad, layout?.elements.orEmpty(), + surfaceStyle = layout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle()) controlsView = controls root.addView(controls, weightParams()) attachKeyboard() 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 32b70d5698..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,7 +1,13 @@ 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("touch"), + CONTROLLER("input-profile"), GLASSES("glasses-game"), DISPLAY("fg"), HUD("hud"), @@ -12,14 +18,69 @@ internal enum class SessionDrawerPage(val firstControl: String) { SESSION("suspend"), } -internal fun sessionDrawerPages( +internal object DrawerPages { + var order by mutableStateOf(SessionDrawerPage.entries.toList()) + private set + var hidden by mutableStateOf(emptySet()) + private set + + /** The order captured when a page row was grabbed in Arrange pages; Back restores it. */ + var heldFrom: List? = null + + fun hideable(page: SessionDrawerPage) = page != SessionDrawerPage.SESSION + + fun load(context: Context) { + order = arrange(SessionPrefs.drawerPageOrder(context)) + hidden = SessionPrefs.drawerPageHidden(context).mapNotNull { name -> SessionDrawerPage.entries.firstOrNull { it.name == name } } + .filter(::hideable).toSet() + } + + fun arrange(saved: List): List { + val all = SessionDrawerPage.entries + val out = saved.mapNotNull { name -> all.firstOrNull { it.name == name } }.distinct().toMutableList() + for (page in all.filterNot { it in out }) { + val before = all.subList(0, all.indexOf(page)).lastOrNull { it in out } + out.add(if (before == null) 0 else out.indexOf(before) + 1, page) + } + return out + } + + fun setHidden(context: Context, page: SessionDrawerPage, hide: Boolean) { + hidden = if (hide && hideable(page)) hidden + page else hidden - page + if (DevPreview.drawer == null) SessionPrefs.setDrawerPageHidden(context, hidden.map { it.name }.toSet()) + } + + /** [placed] holds the pages on offer in their new order; pages not on offer keep their slots. */ + fun rearrange(context: Context, placed: List) { + if (placed.isEmpty() || !order.containsAll(placed)) return + val next = placed.iterator() + order = order.map { if (it in placed) next.next() else it } + if (DevPreview.drawer == null) SessionPrefs.setDrawerPageOrder(context, order.map { it.name }) + } + + fun reset(context: Context) { + order = SessionDrawerPage.entries.toList() + hidden = emptySet() + if (DevPreview.drawer != null) return + SessionPrefs.setDrawerPageOrder(context, order.map { it.name }) + SessionPrefs.setDrawerPageHidden(context, emptySet()) + } + + fun isDefault() = order == SessionDrawerPage.entries.toList() && hidden.isEmpty() +} + +internal fun offeredDrawerPages( hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown, ): List = - SessionDrawerPage.entries.filter { + DrawerPages.order.filter { (hasGlasses || it != SessionDrawerPage.GLASSES) && (hasAgent || it != SessionDrawerPage.AGENT) } +internal fun sessionDrawerPages( + hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown, +): List = offeredDrawerPages(hasGlasses, hasAgent).filter { it !in DrawerPages.hidden } + internal fun List.step(current: SessionDrawerPage, direction: Int): SessionDrawerPage { val index = indexOf(current).coerceAtLeast(0) return this[Math.floorMod(index + direction, size)] diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index 5a95a0eacf..474e613c6a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -47,9 +47,12 @@ import androidx.compose.material.icons.outlined.Pause import androidx.compose.material.icons.outlined.PictureInPictureAlt import androidx.compose.material.icons.automirrored.outlined.ExitToApp import androidx.compose.material.icons.outlined.Settings +import androidx.compose.material.icons.outlined.Tune import androidx.compose.material.icons.outlined.Speed import androidx.compose.material.icons.outlined.SportsEsports import androidx.compose.material3.Icon +import androidx.compose.material3.RadioButton +import androidx.compose.material3.RadioButtonDefaults import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.selection.selectableGroup import androidx.compose.ui.semantics.Role @@ -160,7 +163,7 @@ import com.droiddeck.launcher.input.TouchGestureConfig.Companion.MOUSE_BEHAVIOR_ import kotlinx.coroutines.flow.collect import java.util.Locale -private val SessionDrawerPage.title: Int get() = when (this) { +internal val SessionDrawerPage.title: Int get() = when (this) { SessionDrawerPage.CONTROLLER -> R.string.drawer_page_controller SessionDrawerPage.GLASSES -> R.string.drawer_page_glasses SessionDrawerPage.DISPLAY -> R.string.drawer_page_display @@ -172,7 +175,7 @@ private val SessionDrawerPage.title: Int get() = when (this) { SessionDrawerPage.SESSION -> R.string.mode_session } -private val SessionDrawerPage.icon get() = when (this) { +internal val SessionDrawerPage.icon get() = when (this) { SessionDrawerPage.CONTROLLER -> Icons.Outlined.SportsEsports SessionDrawerPage.GLASSES -> GlassesIcon SessionDrawerPage.DISPLAY -> Icons.Outlined.DesktopWindows @@ -279,6 +282,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, @@ -290,11 +296,7 @@ class DrawerActions( val onAchievements: (() -> Unit)? = null, val achievementsProgress: Pair? = null, val onOsc: (String) -> Unit, - val layoutGame: String? = null, - val layoutOptions: List> = emptyList(), - val layoutChoice: String = "", - val onLayout: (String) -> Unit = {}, - val onEditLayout: (() -> Unit)? = null, + val onEditSteamTouch: (() -> Unit)? = null, val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null, val onRumble: (Boolean) -> Unit = {}, val onSuspendPolicy: (String) -> Unit, @@ -340,6 +342,15 @@ class DrawerActions( val onPause: () -> 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 = {}, val unfoldedControlsWithController: Boolean = false, val onUnfoldedControlsWithController: (Boolean) -> Unit = {}, @@ -382,7 +393,10 @@ class DrawerActions( internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, controllerActive: Boolean, onPageChange: (SessionDrawerPage) -> Unit, a: DrawerActions, docked: Boolean = false, backRequest: Int = 0, onLayerChange: (Boolean) -> Unit = {}) { val pages = sessionDrawerPages(a.glassesPresent) - val page = requestedPage.takeIf { it in pages } ?: SessionDrawerPage.CONTROLLER + val page = requestedPage.takeIf { it in pages } ?: pages.first() + var managing by rememberSaveable { mutableStateOf(false) } + var releaseSignal by remember { mutableStateOf(0) } + val drawerContext = androidx.compose.ui.platform.LocalContext.current LaunchedEffect(requestedPage, pages) { if (page != requestedPage) onPageChange(page) } val colors = MaterialTheme.colorScheme val pal = LocalPalette.current @@ -499,16 +513,24 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont .blockTouches() .focusGroup() .controllerBack { - if (host.open != null) host.open = null else a.onClose() + when { + host.open != null -> host.open = null + managing -> DrawerPages.heldFrom?.let { held -> + DrawerPages.rearrange(drawerContext, held) + releaseSignal++ + } ?: run { managing = false } + else -> a.onClose() + } } .padding(12.dp), ) { val showPicker = a.secondScreenDisplays.isNotEmpty() val roomyHeader = sheetWidth >= if (showPicker) 560.dp else 408.dp + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), - modifier = Modifier.fillMaxWidth().heightIn(min = 44.dp) + modifier = Modifier.weight(1f).heightIn(min = 44.dp) .then(if (roomyHeader) Modifier else Modifier.horizontalScroll(rememberScrollState())), ) { SteamActionPill( @@ -530,7 +552,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont if (a.pipSupported) SteamActionPill( stringResource(R.string.pip_title), Icons.Outlined.PictureInPictureAlt, focus.track(page, "pip"), ) { host.open = null; a.onPip() } - if (docked) StopSessionButton(modifier = focus.track(page, "stop").onGloballyPositioned { stopCoords = it }) { host.open = null; confirmStop = true } val steamActions = a.steam && a.onSteamMenu != null && a.onQam != null val qamInteraction = remember { MutableInteractionSource() } var qamStartedOnPress by remember { mutableStateOf(false) } @@ -560,7 +581,8 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont onQamConfirm = { host.open = null; a.onQam?.invoke() }, showShortcuts = !docked, ) - if (!docked) StopSessionButton(modifier = focus.track(page, "stop").onGloballyPositioned { stopCoords = it }) { host.open = null; confirmStop = true } + } + StopSessionButton(modifier = focus.track(page, "stop").onGloballyPositioned { stopCoords = it }) { host.open = null; confirmStop = true } } a.onAchievements?.let { show -> DrawerAchievementsRow(a.achievementsProgress, Modifier.padding(top = if (short) 6.dp else 10.dp).then(focus.track(page, "achievements"))) { @@ -579,7 +601,15 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont DrawerBumper("RB", stringResource(R.string.drawer_next_page), modifier = focus.track(page, "next")) { host.open = null; onPageChange(pages.step(page, 1)) } + SmallIconButton( + Icons.Outlined.Tune, stringResource(R.string.drawer_manage_pages), colors.onSurfaceVariant, + ) { host.open = null; managing = !managing } } + if (managing) ManageDrawerPages( + offeredDrawerPages(a.glassesPresent), + Modifier.weight(1f).fillMaxWidth().padding(top = 8.dp, start = 14.dp, end = 14.dp), + releaseSignal, + ) { managing = false } else { if (page == SessionDrawerPage.GLASSES) SegmentedTabs( glassesPages, glassesTab, modifier = Modifier.fillMaxWidth().padding(top = 8.dp), tabModifier = { key -> focus.track(page, "glasses-tab-$key").testTag("glasses-tab-$key") }, @@ -664,52 +694,12 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont if (!a.glassesOutput) CardboardGroup(host, a) { key -> focus.track(page, key) } } SessionDrawerPage.CONTROLLER -> { - SettingsGroup(a.layoutGame?.let { stringResource(R.string.osc_group_for, it) } ?: stringResource(R.string.mode_osc)) { - if (a.layoutOptions.isNotEmpty()) ChoiceRow(host, "osc-layout", stringResource(R.string.osc_layout), null, - a.layoutOptions, a.layoutChoice, chipModifier = focus.track(page, "osc-layout"), onPick = a.onLayout) - a.onEditLayout?.let { edit -> - ActionRow(stringResource(R.string.osc_edit_layout), null, stringResource(R.string.ctrl_edit), { host.open = null; edit() }, - modifier = focus.track(page, "osc-edit")) - } - SettingsRow(stringResource(R.string.osc_show), null) { - SegmentedTabs(listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), - SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)), a.oscMode, - tabModifier = { focus.track(page, "osc-$it") }, onPick = a.onOsc) - } - ChoiceRow(host, "touch", stringResource(R.string.input_touches), null, - listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.drawer_touch_auto, a.touchAuto), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_mouse), - SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_GESTURES to stringResource(R.string.mode_touch_gestures), - SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)), - a.touchMode, chipModifier = focus.track(page, "touch"), onPick = a.onTouch) - if (a.touchActive == SessionPrefs.TOUCH_PAD) - RelativeMouseRow(host, a, focus.track(page, "relative-mouse")) - if (a.touchActive == SessionPrefs.TOUCH_DIRECT) - ToggleRow(host, "direct-cursor", stringResource(R.string.input_touch_cursor), - null, a.directCursor, - chipModifier = focus.track(page, "direct-cursor"), onChange = a.onDirectCursor) - when (a.touchActive) { - SessionPrefs.TOUCH_GESTURES -> ActionRow(stringResource(R.string.gesture_settings), null, - stringResource(R.string.ctrl_edit), a.onGestureSettings, - modifier = focus.track(page, "gesture-settings")) - SessionPrefs.TOUCH_DIRECT -> ChoiceRow(host, "long-press", stringResource(R.string.input_touch_hold), null, - listOf(MOUSE_BEHAVIOR_NONE to stringResource(R.string.gesture_hold_left), - MOUSE_BEHAVIOR_CLICK to stringResource(R.string.gesture_right_click), - MOUSE_BEHAVIOR_HOLD to stringResource(R.string.gesture_hold_right)), - a.directHoldBehavior, chipModifier = focus.track(page, "long-press"), - onPick = a.onDirectHoldBehavior) - } - if (a.steam && a.unfoldedControls != null) ToggleRow(host, "unfolded-controls", stringResource(R.string.unfolded_controls), - null, a.unfoldedControls, - chipModifier = focus.track(page, "unfolded-controls"), onChange = a.onUnfoldedControls) - if (a.steam && a.unfoldedControls == true) ToggleRow(host, "unfolded-controls-with-controller", - stringResource(R.string.unfolded_controls_with_controller), - null, a.unfoldedControlsWithController, - chipModifier = focus.track(page, "unfolded-controls-with-controller"), - onChange = a.onUnfoldedControlsWithController) - } SettingsGroup(stringResource(R.string.drawer_page_controller)) { + InputQuickSettings(host, desktop = a.desktop, onChanged = a.onInputSelection, onEdit = a.onInputSettings) { key -> focus.track(page, key) } + } + SettingsGroup(stringResource(R.string.input_device_settings)) { a.padType?.let { type -> - ChoiceRow(host, "pad-type", stringResource(R.string.input_virtual_controller), null, + ChoiceRow(host, "pad-type", stringResource(R.string.input_virtual_controller), stringResource(R.string.input_virtual_controller_hint), listOf(SessionPrefs.CONTROLLER_DECK to stringResource(R.string.mode_controller_deck), SessionPrefs.CONTROLLER_STEAM to stringResource(R.string.mode_controller_steam), SessionPrefs.CONTROLLER_DS4 to stringResource(R.string.mode_controller_ds4), @@ -720,9 +710,89 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont a.controller?.let { c -> ToggleRow(host, "rumble", stringResource(R.string.ctrl_rumble), null, c.rumble, chipModifier = focus.track(page, "rumble"), onChange = a.onRumble) + } - ActionRow(stringResource(R.string.input_remap_buttons), null, stringResource(R.string.ctrl_edit), - a.onInputSettings, modifier = focus.track(page, "remap")) + } + SettingsGroup(stringResource(R.string.input_touchscreen)) { + ChoiceRow(host, "touch", stringResource(R.string.input_touchscreen), stringResource(R.string.input_touchscreen_hint), + listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.drawer_touch_auto, a.touchAuto), SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_direct), SessionPrefs.TOUCH_GESTURES to stringResource(R.string.mode_touch_gestures), SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)), + a.touchMode, chipModifier = focus.track(page, "touch"), onPick = a.onTouch) + if (a.touchActive == SessionPrefs.TOUCH_PAD) + RelativeMouseRow(host, a, focus.track(page, "relative-mouse")) + if (a.touchActive == SessionPrefs.TOUCH_DIRECT) + ToggleRow(host, "direct-cursor", stringResource(R.string.input_touch_cursor), + stringResource(R.string.input_touch_cursor_hint), a.directCursor, + chipModifier = focus.track(page, "direct-cursor"), onChange = a.onDirectCursor) + when (a.touchActive) { + SessionPrefs.TOUCH_GESTURES -> ActionRow(stringResource(R.string.gesture_settings), null, + stringResource(R.string.ctrl_edit), a.onGestureSettings, + modifier = focus.track(page, "gesture-settings")) + SessionPrefs.TOUCH_DIRECT -> ChoiceRow(host, "long-press", stringResource(R.string.input_touch_hold), stringResource(R.string.input_touch_hold_hint), + listOf(MOUSE_BEHAVIOR_NONE to stringResource(R.string.gesture_hold_left), + MOUSE_BEHAVIOR_CLICK to stringResource(R.string.gesture_right_click), + MOUSE_BEHAVIOR_HOLD to stringResource(R.string.gesture_hold_right)), + a.directHoldBehavior, chipModifier = focus.track(page, "long-press"), + onPick = a.onDirectHoldBehavior) + } + } + a.pen?.let { PenSettingsGroup(host, it, track = { key -> focus.track(page, key) }, onPick = a.onPen) } + SettingsGroup(stringResource(R.string.input_screen_visibility)) { + ChoiceRow(host, "osc", stringResource(R.string.mode_osc), null, + if (a.steam) 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)) + else listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)), + if (!a.steam && a.oscMode == SessionPrefs.OSC_STEAM_TOUCH) SessionPrefs.OSC_AUTO else a.oscMode, + chipModifier = focus.track(page, "osc"), onPick = a.onOsc) + a.adaptiveSticks?.let { on -> + 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, + chipModifier = focus.track(page, key)) { a.onQuickButton(button, it) } + } + a.onEditSteamTouch?.let { edit -> + ActionRow(stringResource(R.string.osc_steam_layout), stringResource(R.string.osc_steam_layout_hint), stringResource(R.string.ctrl_edit), edit) + } + if (a.steam && a.unfoldedControls != null) ToggleRow(host, "unfolded-controls", stringResource(R.string.unfolded_controls), + stringResource(R.string.unfolded_controls_hint), a.unfoldedControls, + chipModifier = focus.track(page, "unfolded-controls"), onChange = a.onUnfoldedControls) + if (a.steam && a.unfoldedControls == true) ToggleRow(host, "unfolded-controls-with-controller", + stringResource(R.string.unfolded_controls_with_controller), + stringResource(R.string.unfolded_controls_with_controller_hint), a.unfoldedControlsWithController, + chipModifier = focus.track(page, "unfolded-controls-with-controller"), + onChange = a.onUnfoldedControlsWithController) + } + SettingsGroup(stringResource(R.string.shortcuts_title)) { + if (a.steam) ToggleRow(host, "back-hold", stringResource(R.string.back_hold), + stringResource(R.string.back_hold_hint), a.backHold, + chipModifier = focus.track(page, "back-hold"), onChange = a.onBackHold) + if (a.steam) ChoiceRow(host, "back-actions", stringResource(R.string.input_back_taps), stringResource(R.string.input_back_taps_hint), + listOf(false to stringResource(SessionPrefs.BACK_MENU_THEN_QAM), true to stringResource(SessionPrefs.BACK_QAM_THEN_MENU)), + a.backActionsInverted, chipModifier = focus.track(page, "back-actions"), onPick = a.onBackActionsInverted) + if (a.steam) ChoiceRow(host, "back-double-tap", stringResource(R.string.back_double_tap_window), null, + 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}") }) + 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) + } + SettingsGroup(stringResource(R.string.drawer_latency)) { + ToggleRow(host, "low-latency", stringResource(R.string.drawer_low_latency), + stringResource(R.string.drawer_low_latency_hint), a.lowLatency, + chipModifier = focus.track(page, "low-latency"), onChange = a.onLowLatency) + ToggleRow(host, "evdev-mouse", stringResource(R.string.drawer_evdev_mouse), + null, a.evdevMouse, + chipModifier = focus.track(page, "evdev-mouse"), onChange = a.onEvdevMouse) + if (a.touchActive != SessionPrefs.TOUCH_PAD) + RelativeMouseRow(host, a, focus.track(page, "relative-mouse")) } SettingsGroup(stringResource(R.string.drawer_keyboard)) { Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(8.dp)) { @@ -742,57 +812,28 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont ), a.wowChat, chipModifier = focus.track(page, "wow-chat"), onPick = a.onWowChat, ) - } - a.pen?.let { PenSettingsGroup(host, it, track = { key -> focus.track(page, key) }, onPick = a.onPen) } - var moreControls by rememberSaveable { mutableStateOf(false) } - SettingsGroup(stringResource(R.string.osc_more)) { - ActionRow(stringResource(R.string.osc_more_detail), null, stringResource(if (moreControls) R.string.common_hide else R.string.common_show), - { moreControls = !moreControls }, modifier = focus.track(page, "more-controls")) - if (moreControls) { - if (a.steam) ToggleRow(host, "back-hold", stringResource(R.string.back_hold), - null, a.backHold, - chipModifier = focus.track(page, "back-hold"), onChange = a.onBackHold) - if (a.steam) ChoiceRow(host, "back-actions", stringResource(R.string.input_back_taps), null, - listOf(false to stringResource(SessionPrefs.BACK_MENU_THEN_QAM), true to stringResource(SessionPrefs.BACK_QAM_THEN_MENU)), - a.backActionsInverted, chipModifier = focus.track(page, "back-actions"), onPick = a.onBackActionsInverted) - if (a.steam) ChoiceRow(host, "back-double-tap", stringResource(R.string.back_double_tap_window), null, - 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}") }) - 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) - ToggleRow(host, "low-latency", stringResource(R.string.drawer_low_latency), - null, a.lowLatency, - chipModifier = focus.track(page, "low-latency"), onChange = a.onLowLatency) - ToggleRow(host, "evdev-mouse", stringResource(R.string.drawer_evdev_mouse), - null, a.evdevMouse, - chipModifier = focus.track(page, "evdev-mouse"), onChange = a.onEvdevMouse) - if (a.touchActive != SessionPrefs.TOUCH_PAD) - RelativeMouseRow(host, a, focus.track(page, "relative-mouse")) - val keyboardContext = LocalContext.current - remember { PcKeyboardPrefs.load(keyboardContext) } - SliderRow( - stringResource(R.string.pckb_size), null, - PcKeyboardPrefs.size, SessionPrefs.PC_KEYBOARD_SIZE_RANGE, step = 1, - format = { "$it%" }, modifier = focus.track(page, "pckb-size"), - onChange = { PcKeyboardPrefs.setSize(keyboardContext, it) }) - SliderRow( - stringResource(R.string.pckb_opacity), null, - PcKeyboardPrefs.opacity, SessionPrefs.PC_KEYBOARD_OPACITY_RANGE, step = 5, - format = { "$it%" }, modifier = focus.track(page, "pckb-opacity"), - onChange = { PcKeyboardPrefs.setOpacity(keyboardContext, it) }) - MultiRow( - host, "pckb-hidden", stringResource(R.string.pckb_hidden_keys), - null, - listOf( - 0 to stringResource(R.string.pckb_group_function), - 1 to stringResource(R.string.pckb_group_nav), - 2 to stringResource(R.string.pckb_group_arrows), - ), - PC_KEY_GROUP_IDS.filterValues { it in PcKeyboardPrefs.hiddenKeys }.keys, - onToggle = { id, on -> PcKeyboardPrefs.toggleHiddenKey(keyboardContext, PC_KEY_GROUP_IDS.getValue(id), on) }) - } + val keyboardContext = LocalContext.current + remember { PcKeyboardPrefs.load(keyboardContext) } + SliderRow( + stringResource(R.string.pckb_size), stringResource(R.string.pckb_size_hint), + PcKeyboardPrefs.size, SessionPrefs.PC_KEYBOARD_SIZE_RANGE, step = 1, + format = { "$it%" }, modifier = focus.track(page, "pckb-size"), + onChange = { PcKeyboardPrefs.setSize(keyboardContext, it) }) + SliderRow( + stringResource(R.string.pckb_opacity), stringResource(R.string.pckb_opacity_hint), + PcKeyboardPrefs.opacity, SessionPrefs.PC_KEYBOARD_OPACITY_RANGE, step = 5, + format = { "$it%" }, modifier = focus.track(page, "pckb-opacity"), + onChange = { PcKeyboardPrefs.setOpacity(keyboardContext, it) }) + MultiRow( + host, "pckb-hidden", stringResource(R.string.pckb_hidden_keys), + stringResource(R.string.pckb_hidden_keys_hint), + listOf( + 0 to stringResource(R.string.pckb_group_function), + 1 to stringResource(R.string.pckb_group_nav), + 2 to stringResource(R.string.pckb_group_arrows), + ), + PC_KEY_GROUP_IDS.filterValues { it in PcKeyboardPrefs.hiddenKeys }.keys, + onToggle = { id, on -> PcKeyboardPrefs.toggleHiddenKey(keyboardContext, PC_KEY_GROUP_IDS.getValue(id), on) }) } } SessionDrawerPage.GLASSES -> if (glassesTab == GlassesTab.CONTROLLERS) { @@ -832,7 +873,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont SessionDrawerPage.AGENT -> Unit SessionDrawerPage.SESSION -> { SettingsGroup(stringResource(R.string.drawer_support)) { - SettingsRow(stringResource(R.string.report_problem), null) { + SettingsRow(stringResource(R.string.report_problem), stringResource(R.string.report_problem_hint)) { DrawerOutlineButton(stringResource(R.string.drawer_share_logs), modifier = focus.track(page, "share-logs"), progress = com.droiddeck.launcher.session.SessionLogShare.progress) { host.open = null @@ -870,7 +911,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont } SettingsGroup(stringResource(R.string.drawer_session_behavior)) { if (a.micAvailable) ToggleRow(host, "microphone", stringResource(R.string.mode_mic), - null, a.micEnabled, + stringResource(R.string.drawer_mic_hint), a.micEnabled, chipModifier = focus.track(page, "microphone"), onChange = a.onMicEnabled) ChoiceRow( host, "suspend", stringResource(R.string.mode_suspend), @@ -889,7 +930,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont ) if (a.steam && a.suspendPolicy != SessionPrefs.SUSPEND_NEVER) ToggleRow( host, "background-downloads", stringResource(R.string.mode_background_downloads), - null, + stringResource(R.string.mode_background_downloads_hint), a.steamDownloadsInBackground, onChange = a.onSteamDownloadsInBackground, ) @@ -905,6 +946,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont } } } } + } } StopConfirm( open = confirmStop, @@ -962,7 +1004,7 @@ private fun DrawerActionButton(text: String, icon: androidx.compose.ui.graphics. } @Composable -private fun DrawerOutlineButton(text: String, modifier: Modifier = Modifier, progress: Float? = null, onClick: () -> Unit) { +internal fun DrawerOutlineButton(text: String, modifier: Modifier = Modifier, progress: Float? = null, onClick: () -> Unit) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val source = remember { MutableInteractionSource() } @@ -984,15 +1026,14 @@ private fun StopSessionButton(modifier: Modifier = Modifier, onClick: () -> Unit val src = remember { MutableInteractionSource() } val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value val fill by animateColorAsState(if (hot) colors.error.copy(alpha = 0.18f) else Color.Transparent, Motion.tw(220), label = "dangerFill") - val shape = RoundedCornerShape(20.dp) + val shape = androidx.compose.foundation.shape.CircleShape val stopDescription = stringResource(R.string.stop_session) Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center, - modifier = modifier.heightIn(min = 44.dp).widthIn(min = 44.dp).semantics { contentDescription = stopDescription }.testTag("drawer-stop") + modifier = modifier.size(44.dp).semantics { contentDescription = stopDescription }.testTag("drawer-stop") .clip(shape).background(fill).glideBorder(hot, shape, colors.error.copy(alpha = 0.9f), colors.error.copy(alpha = 0.55f)) .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = onClick) - .controllerConfirm(onClick = onClick) - .padding(horizontal = 12.dp), + .controllerConfirm(onClick = onClick), ) { Icon(Icons.Outlined.PowerSettingsNew, contentDescription = null, tint = colors.error, modifier = Modifier.size(18.dp)) } @@ -1106,20 +1147,20 @@ private fun ScreenEffectsGroup( SettingsGroup(stringResource(R.string.drawer_effects)) { ChoiceRow( host, "effects-profile", stringResource(R.string.screen_effects_target), - null, a.screenEffectsTargets, + stringResource(R.string.screen_effects_target_hint), a.screenEffectsTargets, a.screenEffectsTarget, chipModifier = track("effects-profile"), onPick = a.onScreenEffectsTarget, ) ActionRow( stringResource(R.string.screen_effects_reset), - null, + stringResource(R.string.screen_effects_reset_hint), stringResource(R.string.hud_reset_button), a.onScreenEffectsReset, modifier = track("effects-reset"), ) if (a.screenEffectsCanDelete) ActionRow( stringResource(R.string.screen_effects_delete), - null, + stringResource(R.string.screen_effects_delete_hint), stringResource(R.string.common_delete), a.onScreenEffectsDelete, modifier = track("effects-delete"), @@ -1154,7 +1195,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) @@ -1202,7 +1245,7 @@ private fun ScreenEffectsGroup( private fun CardboardGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) { val c = a.cardboard SettingsGroup(stringResource(R.string.cardboard_title)) { - ToggleRow(host, "cardboard", stringResource(R.string.cardboard_mode), null, + ToggleRow(host, "cardboard", stringResource(R.string.cardboard_mode), stringResource(R.string.cardboard_mode_hint), c.enabled, chipModifier = track("cardboard")) { a.onCardboard(c.copy(enabled = it)) } if (!c.enabled) return@SettingsGroup ChoiceRow(host, "cardboard-source", stringResource(R.string.cardboard_source), null, @@ -1676,6 +1719,8 @@ internal fun ComponentDownloadsDrawerGroup( val installed = packages.map { it.file }.toSet() val nightlyPicked = remember { mutableStateMapOf() } SettingsGroup(stringResource(R.string.drawer_component_downloads)) { + Text(stringResource(R.string.drawer_component_downloads_hint), fontSize = 12.sp, + color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp)) SettingsRow(stringResource(R.string.comp_nightlies_checked, if (catalogAt > 0) java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT) .format(java.util.Date(catalogAt * 1000)) else stringResource(R.string.comp_never)), null, stacked = true) { 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..baa2b0e69a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt @@ -108,6 +108,7 @@ internal object SettingsIndex { s(SettingsSection.LAUNCHER, R.string.setup_launcher_orientation, "rotate", "portrait"), s(SettingsSection.LAUNCHER, R.string.setup_session_orientation, "rotate", "portrait"), s(SettingsSection.LAUNCHER, R.string.setup_fullscreen), + s(SettingsSection.LAUNCHER, R.string.setup_controller_haptics, "vibration", "rumble"), s(SettingsSection.LAUNCHER, R.string.setup_dual_screen_launcher, "thor", "second screen", "bottom screen"), s(SettingsSection.LAUNCHER, R.string.setup_low_storage_warning), s(SettingsSection.LAUNCHER, R.string.mode_sgdb_key, "artwork", "steamgriddb"), @@ -137,7 +138,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/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/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 fa5a0dfdcc..4a94939081 100644 --- a/app/src/main/res/values-ar/input_library.xml +++ b/app/src/main/res/values-ar/input_library.xml @@ -75,9 +75,14 @@ نسخة مستقلة بدء العصا عند موضع اللمس إخفاء العصا عند عدم الاستخدام + الأدوات + تلقائي (%1$s) + مخصص (%1$s) حفظ كملف تعريف جديد عناصر تحكم ملف التعريف + ملف التعريف إيماءات لوحة لمس الفأرة + عند تعيينها لمؤشر الفأرة: اضغط للنقر، واستمر للتمرير بالسحب، ومرّر بإصبعين. لدى %1$s تجاوز للقائمة السريعة. اختر تلقائي هناك لاستخدام ملف التعريف الافتراضي والأجزاء الثلاثة المحفوظة. إدخال DroidDeck يُحتجز أثناء تحريك العصا في أي اتجاه: يُضغط فوق 55% ويُحرّر تحت 35%. استخدم مفاتيح الاتجاه لتعيين كل اتجاه على حدة. تُنفَّذ أوامر DroidDeck مرة واحدة لكل انحراف. يُضبط النقر على العصا على حدة. @@ -99,11 +104,17 @@ في وضع Steam. الاستمرار بالضغط على رجوع يفتح الوصول السريع أيضًا. الاستعادة إلى الافتراضي وحدة تحكم افتراضية + نوع وحدة التحكم التي يراها Steam أو اللعبة. شاشة لمس + كيفية التعامل مع اللمسات على شاشة اللعبة. تحتفظ أزرار ملف التعريف بإجراءاتها المعيّنة. مؤشر اللمس + إظهار مؤشر للمسات المباشرة على شاشة اللعبة. اللمس والاستمرار + إجراء الفأرة عند الاستمرار بإصبع على شاشة اللعبة. نقرات زر رجوع + الإجراء الأول: نقرة واحدة. الإجراء الثاني: نقرتان. زر تبديل + اضغط للاستمرار، واضغط مرة أخرى للتحرير. فتح قائمة أو تبديل ملف التعريف يحرّر الزر. الشكل مستدير كبسولة diff --git a/app/src/main/res/values-ar/input_strings.xml b/app/src/main/res/values-ar/input_strings.xml index f9edaba92f..d375d35ff4 100644 --- a/app/src/main/res/values-ar/input_strings.xml +++ b/app/src/main/res/values-ar/input_strings.xml @@ -1,5 +1,6 @@ + ملفات تعريف الإدخال ملفات التعريف وحدة تحكم فعلية الشاشة الرئيسية @@ -22,6 +23,7 @@ فتح قائمة Steam فتح الوصول السريع في Steam إزالة عنصر التحكم + إضافة عنصر تحكم أزرار خاصة بالجهاز تعيين زر فعلي حرّر الزر ثم اختر تحرير أو إعادة المحاولة أو إلغاء. يلغي B أو رجوع بعد التحرير. diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 53fc57eabc..d47088cf05 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 وسطح المكتب. يتم ضبطها في صفحة «المكوّنات». @@ -295,10 +294,14 @@ اللمس الزر الجانبي عناصر التحكم على الشاشة + Steam + QAM يعرض الخيار «تلقائي» عناصر التحكم عند عدم توصيل وحدة تحكم. + لمس Steam (تجريبي) + تبدأ عناصر التحكم باللمس من Steam مع جلسة Steam التالية تخطيط لمس Steam تصدير صورة + انقل عناصر التحكم باللمس لهذه اللعبة أو غيّر حجمها أو أخفها؛ ويتم الحفظ في Steam وحدة التحكم كيف يرى Steam وحدة التحكم لديك. يُطبَّق في الجلسة التالية. وحدة تحكم Steam Deck @@ -429,6 +432,7 @@ يتجاوز PulseAudio لتقليل زمن الاستجابة. الميكروفون للدردشة الصوتية. + شغّل التقاط الميكروفون أو أوقفه لهذه الجلسة. تعذّر تغيير الميكروفون. يُرجى المحاولة مرة أخرى. الشبكة اكتشاف Wi-Fi @@ -794,6 +798,7 @@ لوحة المفاتيح زمن الاستجابة وضع زمن الاستجابة المنخفض + يزيد استهلاك CPU والبطارية وحدة تحكم بزمن استجابة منخفض تبلغ وحدة التحكم بمعدل 1000 هرتز بدلًا من 250 هرتز. استهلاك معالج أعلى قليلًا. لمس بزمن استجابة منخفض @@ -1367,8 +1372,12 @@ العتامة %1$d%% حجم الأزرار + عصي تكيّفية اهتزاز اللعبة المنطقة الميتة لعصا التحكم + زر Steam + زر QAM + زر لوحة المفاتيح أجهزة Joy-Con كوحدات تحكم VR أثناء تشغيل SteamVR، يصبح كل Joy-Con يدًا. وجّهه إلى الأمام واضغط مطولًا على Home أو Capture لإعادة توسيطه. الرسوم المتحركة @@ -1501,6 +1510,8 @@ لوحة اللمس إغلاق عناصر التحكّم على الشاشة الثانية فتح قائمة Steam + لوحة اللمس اليمنى + لوحة اللمس اليسرى لوحة اللمس إظهار لوحة المفاتيح إخفاء لوحة المفاتيح @@ -1539,8 +1550,11 @@ لوحة مفاتيح Android إخفاء ✕ الحجم على الشاشة + نسبة الشاشة التي تشغلها لوحة المفاتيح، بما في ذلك الشريط العلوي. العتامة + قلّلها لرؤية اللعبة خلف لوحة المفاتيح. المفاتيح المخفية + المفاتيح التي نادرًا ما تستخدمها لا تظهر على لوحة المفاتيح. صف Esc ومفاتيح الوظائف Ins / Del / Home / End / PgUp / PgDn مفاتيح الأسهم @@ -1785,6 +1799,8 @@ تم تثبيت %1$s - اختره من القائمة انتظر حتى تنتهي إزالة بيئة التشغيل لعبة + لوحة اللمس + مباشر فشل التبديل: %1$s فشل حفظ ملف التعريف: %1$s تم إيقاف سطح المكتب مؤقتًا @@ -2076,6 +2092,15 @@ الانتقال لمستوى أعلى اختر مجلدًا اختر ملفًا + أزرق Steam + سماوي + أبيض + بنفسجي + أخضر + كهرماني + أحمر + وردي + رمادي الزر A الزر B الزر X @@ -2539,10 +2564,13 @@ Android + Linux %1$s. %2$s\n\n%3$s شاشة الجلسة + العرض بدون نسخ الدقة ملاءمة اللعبة لنسبة 16:9 كيفية ملاءمة ألعاب 16:9 لهذه الشاشة. يُطبَّق في الجلسة التالية. اختر «مطابقة الشاشة» أو حجمًا مخصَّصًا أضيق من 16:9. + تجنّب فتحة الكاميرا + يُبقي الصورة بعيدًا عن فتحة الكاميرا. يُطبَّق عند العودة إلى الجلسة. الحفاظ على النسب تمديد لملء الشاشة تكبير الصورة @@ -3233,6 +3261,7 @@ تتبّع تجريبي لحركة الرأس لنظارة Pro 2. لا يُدعم بعد ضبط السطوع ومستوى الصوت أو تبديل وضع العرض. Cardboard VR وضع Cardboard + عرض للعين اليسرى وآخر لليمنى لنظارة واقع افتراضي للهاتف. الصورة شاشة افتراضية ثلاثي الأبعاد جنبًا إلى جنب @@ -3255,6 +3284,7 @@ غير متوفر في هذه الجلسة. لم يستجب SteamVR؛ تحقّق من سجل الجلسة. تنزيل المكوّنات + التنزيلات مشتركة مع صفحة «المكوّنات». اختر نسخة منزّلة أعلاه لاستخدامها عند التشغيل التالي للعبة. اختر نسخة لتنزيلها المطوّر الناشر 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 d850c1a7ff..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 @@ -75,9 +75,14 @@ Copia independiente Iniciar la palanca en el punto de toque Ocultar la palanca cuando no se use + Herramientas + Auto (%1$s) + Personalizado (%1$s) Guardar como perfil nuevo Controles del perfil + Perfil Gestos del panel táctil del mouse + Si se asigna al puntero del mouse: toca para hacer clic, mantén para arrastrar y desplaza con dos dedos. %1$s tiene una anulación del menú rápido. Selecciona Auto allí para usar su perfil predeterminado y sus tres partes guardadas. Entrada de DroidDeck Se mantiene mientras la palanca se mueve en cualquier dirección: se presiona por encima del 55 %, se suelta por debajo del 35 %. Usa Teclas de dirección para asignar cada dirección por separado. Los comandos de DroidDeck se ejecutan una vez por desvío. El clic de la palanca se configura aparte. @@ -99,11 +104,17 @@ En modo Steam. Mantener Atrás también abre el acceso rápido. Restaurar valores predeterminados Control virtual + El tipo de control que ven Steam o el juego. Pantalla táctil + Cómo se manejan los toques en la pantalla del juego. Los botones del perfil mantienen sus acciones asignadas. Cursor táctil + Muestra un puntero para toques directos en la pantalla del juego. Tocar y mantener + Acción del mouse al mantener un dedo en la pantalla del juego. Toques del botón Atrás + Primera acción: un toque. Segunda acción: doble toque. Botón de alternar + Toca para mantener, toca de nuevo para soltar. Abrir un menú o cambiar de perfil suelta el botón. Forma Redondeada Píldora diff --git a/app/src/main/res/values-b+es+419/input_strings.xml b/app/src/main/res/values-b+es+419/input_strings.xml index 588991fb7d..744979897b 100644 --- a/app/src/main/res/values-b+es+419/input_strings.xml +++ b/app/src/main/res/values-b+es+419/input_strings.xml @@ -1,5 +1,6 @@ + Perfiles de entrada Perfiles Control físico Pantalla principal @@ -22,6 +23,7 @@ Abrir el menú de Steam Abrir el acceso rápido de Steam Quitar control + Agregar control Botones específicos del dispositivo Asignar un botón físico Suelta el botón y elige Editar, Reintentar o Cancelar. B o Atrás cancela después de soltarlo. 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 85ae431537..5549df7437 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. @@ -295,10 +294,14 @@ Táctil Botón lateral Controles en pantalla + Steam + QAM Auto muestra los controles en pantalla cuando no hay ningún control conectado. + Táctil de Steam (beta) + Los controles táctiles de Steam se activan en la próxima sesión de Steam Disposición táctil de Steam Exportar Imagen + Mueve, cambia de tamaño u oculta los controles táctiles de este juego; se guarda en Steam Control Cómo ve Steam tu control. Se aplica en la próxima sesión. Control de Steam Deck @@ -426,6 +429,7 @@ Evita PulseAudio para menor latencia. Micrófono Para el chat de voz. + Activa o desactiva la captura del micrófono en esta sesión. No se pudo cambiar el micrófono. Inténtalo de nuevo. Red Detección de redes Wi-Fi @@ -767,6 +771,7 @@ HDR simulado Cardboard VR Modo Cardboard + Vistas para el ojo izquierdo y el derecho para un visor de RV para celular. Imagen Pantalla virtual 3D lado a lado @@ -811,6 +816,7 @@ Teclado Latencia Modo de baja latencia + Aumenta el uso de CPU y batería Control de baja latencia El control informa a 1000 Hz en lugar de 250 Hz. Usa algo más de CPU. Táctil de baja latencia @@ -861,6 +867,7 @@ Original Importa y elimina en la página Componentes. Descargar componentes + Las descargas se comparten con la página Componentes. Elige arriba una versión descargada para usarla al iniciar el próximo juego. Elige una versión para descargar Hecho Requiere atención @@ -1371,8 +1378,12 @@ Opacidad %1$d%% Tamaño de botones + Sticks adaptables Vibración en juegos Zona muerta de la palanca + Botón Steam + Botón QAM + Botón de teclado Joy-Con como controles de RV Mientras SteamVR está activo, cada Joy-Con es una mano. Apúntalo al frente y mantén Home o Captura para recentrarlo. Sin ningún mando conectado, la cámara del teléfono rastrea tus manos en realidad virtual: pellizca con el pulgar y el índice para hacer clic, cierra la mano para agarrar y gira la palma hacia ti y pellizca para abrir el menú. Con los mandos Joy-Con emparejados, la cámara rastrea su posición mientras los mandos Joy-Con proporcionan la rotación y las entradas de los botones. Las imágenes se procesan en este dispositivo y nunca se guardan ni se envían. @@ -1545,6 +1556,8 @@ Trackpad Cerrar controles de la segunda pantalla Abrir menú de Steam + Trackpad derecho + Trackpad izquierdo Trackpad Mostrar teclado Ocultar teclado @@ -1583,8 +1596,11 @@ Teclado de Android Ocultar ✕ Tamaño en pantalla + Parte de la pantalla que ocupa el teclado, encabezado incluido. Opacidad + Bájala para ver el juego detrás del teclado. Teclas ocultas + Las teclas que casi no usas no aparecen en el teclado. Esc y fila de funciones Ins / Del / Home / End / PgUp / PgDn Teclas de dirección @@ -1805,6 +1821,8 @@ %1$s instalado - elígelo en el menú Espera a que termine la eliminación del runtime Juego + touchpad + directo El reemplazo falló: %1$s No se pudo guardar el perfil: %1$s El escritorio está en pausa @@ -2069,6 +2087,15 @@ Subir un nivel Elige una carpeta Elige un archivo + Azul Steam + Celeste + Blanco + Violeta + Verde + Ámbar + Rojo + Rosa + Gris Botón A Botón B Botón X @@ -2529,10 +2556,13 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Pantalla de la sesión + Presentación sin copia Resolución Ajuste de juegos 16:9 Cómo se ajustan los juegos 16:9 a esta pantalla. Próxima sesión. Elige Igual a la pantalla o un tamaño personalizado más estrecho que 16:9. + Evitar la muesca + Mantiene la imagen fuera del recorte de la cámara. Se aplica al volver a la sesión. Mantener proporciones Estirar a la pantalla Escalado de imagen diff --git a/app/src/main/res/values-bg/input_library.xml b/app/src/main/res/values-bg/input_library.xml index 189c4332f8..31967ac490 100644 --- a/app/src/main/res/values-bg/input_library.xml +++ b/app/src/main/res/values-bg/input_library.xml @@ -75,9 +75,14 @@ Независимо копие Стартиране на стика от точката на докосване Скриване на стика, когато не се използва + Инструменти + Автоматично (%1$s) + Персонализирано (%1$s) Запазване като нов профил Управление на профила + Профил Жестове на тъчпада на мишката + Когато е зададено на показалеца на мишката: докоснете за щракване, задръжте за плъзгане и превъртайте с два пръста. %1$s има замяна на бързото меню. Изберете Автоматично, за да използвате профила по подразбиране и трите запазени части. Вход на DroidDeck Задържа се, докато стикът е отместен в която и да е посока: натиска при над 55%, отпуска под 35%. Използвайте Клавиши за посока, за да зададете всяка посока отделно. Командите на DroidDeck се изпълняват веднъж на отклонение. Щракването на стика се настройва отделно. @@ -99,11 +104,17 @@ В режим Steam. Задържането на Назад отваря и бързия достъп. Връщане към подразбирането Виртуален контролер + Типът контролер, който Steam или играта виждат. Сензорен екран + Как се обработват докосванията на екрана на играта. Бутоните на профила запазват зададените си действия. Курсор за докосване + Показва показалец за директни докосвания на екрана на играта. Докосване и задържане + Действие на мишката при задържане на пръст на екрана на играта. Докосвания на бутона Назад + Първо действие: едно докосване. Второ действие: двойно докосване. Превключващ бутон + Докоснете за задържане, докоснете отново за освобождаване. Отваряне на меню или смяна на профил освобождава бутона. Форма Заоблена Капсула diff --git a/app/src/main/res/values-bg/input_strings.xml b/app/src/main/res/values-bg/input_strings.xml index 4988b4bf7d..3e16a7059a 100644 --- a/app/src/main/res/values-bg/input_strings.xml +++ b/app/src/main/res/values-bg/input_strings.xml @@ -1,5 +1,6 @@ + Профили за вход Профили Физически контролер Основен екран @@ -22,6 +23,7 @@ Отваряне на менюто на Steam Отваряне на бързия достъп на Steam Премахване на контрола + Добавяне на контрол Бутони, специфични за устройството Задаване на физически бутон Отпуснете бутона, след което изберете Редакция, Повторение или Отказ. B или Назад отменя след отпускането. diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index 14ffae0eb4..38005ba0b8 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 и работния плот. Задават се в страницата Компоненти. @@ -295,10 +294,14 @@ Докосване Страничен бутон Екранни контроли + Steam + QAM Автоматично показва контролите, когато няма свързан контролер. + Докосване в Steam (бета) + Сензорните контроли на Steam ще стартират от следващата сесия на Steam Разположение на докосването в Steam Експорт Изображение + Премествайте, преоразмерявайте или скривайте сензорните контроли на тази игра; записва се в Steam Контролер Как Steam разпознава контролера ви. Прилага се от следващата сесия. Контролер на Steam Deck @@ -425,6 +428,7 @@ Пропуска PulseAudio за по-ниска латентност. Микрофон За гласов чат. + Включване или изключване на записа от микрофона за тази сесия. Микрофонът не можа да бъде променен. Опитайте пак. Мрежа Откриване на Wi-Fi @@ -786,6 +790,7 @@ Клавиатура Закъснение Режим на ниска латентност + Увеличава използването на CPU и батерията Контролер с ниско закъснение Контролерът докладва при 1000 Hz вместо 250 Hz. Малко повече CPU. Докосване с ниско закъснение @@ -1339,8 +1344,12 @@ Прозрачност %1$d%% Размер на бутоните + Адаптивни стикове Вибрация от играта Мъртва зона на стика + Бутон Steam + Бутон QAM + Бутон за клавиатура Joy-Con като VR контролери Докато SteamVR работи, всеки Joy-Con става ръка. Насочете го напред и задръжте Home или Capture, за да го центрирате отново. Анимации @@ -1469,6 +1478,8 @@ Тракпад Затваряне на контролите за втория екран Отваряне на менюто на Steam + Десен тракпад + Ляв тракпад Тракпад Показване на клавиатурата Скриване на клавиатурата @@ -1507,8 +1518,11 @@ Клавиатура на Android Скриване ✕ Размер на екрана + Каква част от екрана заема клавиатурата, включително заглавката. Непрозрачност + Намалете я, за да виждате играта зад клавиатурата. Скрити клавиши + Рядко използваните клавиши не се показват на клавиатурата. Esc и ред с функционални клавиши Ins / Del / Home / End / PgUp / PgDn Клавиши със стрелки @@ -1721,6 +1735,8 @@ Инсталирано: %1$s - избери го от менюто Изчакай премахването на средата да приключи Игра + тракпад + директно Размяната се провали: %1$s Запазването на профила се провали: %1$s Работният плот е на пауза @@ -1976,6 +1992,15 @@ Едно ниво нагоре Избор на папка Избор на файл + Синьо на Steam + Небесно + Бяло + Виолетово + Зелено + Кехлибарено + Червено + Розово + Сиво Бутон A Бутон B Бутон X @@ -2435,10 +2460,13 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Екран на сесията + Представяне без копиране Разделителна способност Напасване на игра 16:9 Как игрите с 16:9 се напасват на този екран. При следващата сесия. Избери „Напасване на екрана“ или собствен размер, по-тесен от 16:9. + Избягване на прореза + Държи картината извън прореза за камерата. Важи при връщане към сесията. Запазване на пропорциите Разтягане до екрана Мащабиране на изображението @@ -3113,6 +3141,7 @@ Експериментално проследяване на движенията на главата за Pro 2. Регулирането на яркостта и силата на звука и превключването на режима на показване все още не се поддържат. Cardboard VR Режим Cardboard + Изображения за лявото и дясното око за VR очила за телефон. Картина Виртуален екран 3D един до друг @@ -3135,6 +3164,7 @@ Не е налично в тази сесия. SteamVR не отговори; проверете лога на сесията. Изтегляне на компоненти + Изтеглянията са общи със страницата Компоненти. Изберете по-горе изтеглена версия, за да се използва при следващото стартиране на играта. Изберете версия за изтегляне Разработчик Издател diff --git a/app/src/main/res/values-cs/input_library.xml b/app/src/main/res/values-cs/input_library.xml index 2b67a7976d..6ba6584e5e 100644 --- a/app/src/main/res/values-cs/input_library.xml +++ b/app/src/main/res/values-cs/input_library.xml @@ -75,9 +75,14 @@ Nezávislá kopie Spustit páčku v místě dotyku Skrýt páčku, když se nepoužívá + Nástroje + Automaticky (%1$s) + Vlastní (%1$s) Uložit jako nový profil Ovládání profilu + Profil Gesta touchpadu myši + Při přiřazení k ukazateli myši: klepnutím kliknete, podržením táhnete a dvěma prsty posouváte. %1$s má přepsání rychlé nabídky. Vyberte Automaticky, chcete-li použít výchozí profil a všechny tři uložené části. Vstup DroidDeck Drženo, když je páčka vychýlena jakýmkoli směrem: stisk nad 55 %, uvolnění pod 35 %. Pomocí Směrových kláves přiřaďte každý směr zvlášť. Příkazy DroidDeck se spustí jednou za vychýlení. Kliknutí páčky se nastavuje zvlášť. @@ -99,11 +104,17 @@ V režimu Steam. Podržením Zpět se také otevře rychlý přístup. Obnovit výchozí Virtuální ovladač + Typ ovladače, který vidí Steam nebo hra. Dotyková obrazovka + Jak se zpracovávají dotyky na obrazovce hry. Tlačítka profilu si zachovávají přiřazené akce. Kurzor dotyku + Zobrazí ukazatel pro přímé dotyky na obrazovce hry. Dotknout se a podržet + Akce myši při podržení prstu na obrazovce hry. Klepnutí tlačítka Zpět + První akce: jedno klepnutí. Druhá akce: dvojité klepnutí. Přepínací tlačítko + Klepnutím podržíte, dalším klepnutím uvolníte. Otevření nabídky nebo přepnutí profilu tlačítko uvolní. Tvar Zaoblený Kapsle diff --git a/app/src/main/res/values-cs/input_strings.xml b/app/src/main/res/values-cs/input_strings.xml index 86c55d2f05..6cd32d90b3 100644 --- a/app/src/main/res/values-cs/input_strings.xml +++ b/app/src/main/res/values-cs/input_strings.xml @@ -1,5 +1,6 @@ + Profily vstupu Profily Fyzický ovladač Hlavní obrazovka @@ -22,6 +23,7 @@ Otevřít nabídku Steam Otevřít rychlý přístup Steam Odebrat prvek + Přidat prvek Tlačítka specifická pro zařízení Přiřadit fyzické tlačítko Uvolněte tlačítko a zvolte Upravit, Znovu nebo Zrušit. B nebo Zpět zruší po uvolnění. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 72895e79a9..e659eaf255 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. @@ -295,10 +294,14 @@ Dotyk Boční tlačítko Ovládání na obrazovce + Steam + QAM Automaticky zobrazí ovládání, pokud není připojen žádný ovladač. + Dotykové ovládání Steamu (beta) + Dotykové ovládání Steamu se spustí od příští relace Steamu Rozvržení dotykového ovládání Steamu Exportovat Obrázek + Přesuňte, změňte velikost nebo skryjte dotykové ovládání této hry; uloží se do Steamu Ovladač Jak Steam vidí váš ovladač. Použije se od příští relace. Ovladač Steam Deck @@ -427,6 +430,7 @@ Obchází PulseAudio pro nižší latenci. Mikrofon Pro hlasový chat. + Zapnout nebo vypnout snímání mikrofonu pro tuto relaci. Mikrofon se nepodařilo změnit. Zkuste to znovu. Síť Vyhledávání Wi-Fi @@ -790,6 +794,7 @@ Klávesnice Zpoždění Režim nízkého zpoždění + Zvyšuje využití CPU a baterie Ovladač s nízkým zpožděním Ovladač hlásí na 1000 Hz místo 250 Hz. O něco víc CPU. Dotek s nízkým zpožděním @@ -1353,8 +1358,12 @@ Průhlednost %1$d%% Velikost tlačítek + Adaptivní páčky Vibrace ve hře Mrtvá zóna páčky + Tlačítko Steam + Tlačítko QAM + Tlačítko klávesnice Joy-Cony jako ovladače VR Když běží SteamVR, každý Joy-Con slouží jako ruka. Namiřte ho dopředu a podržením Home nebo Capture ho znovu vycentrujete. Animace @@ -1485,6 +1494,8 @@ Trackpad Zavřít ovládání druhé obrazovky Otevřít nabídku Steamu + Pravý trackpad + Levý trackpad Trackpad Zobrazit klávesnici Skrýt klávesnici @@ -1523,8 +1534,11 @@ Klávesnice Androidu Skrýt ✕ Velikost na obrazovce + Podíl obrazovky, který klávesnice zabírá, včetně záhlaví. Neprůhlednost + Snižte ji, abyste viděli hru za klávesnicí. Skryté klávesy + Klávesy, které používáte zřídka, se na klávesnici nezobrazují. Esc a řada funkčních kláves Ins / Del / Home / End / PgUp / PgDn Klávesy se šipkami @@ -1753,6 +1767,8 @@ Nainstalováno %1$s - vyberte ho v nabídce Počkejte, až skončí odstranění runtime Hra + touchpad + přímý Přepnutí se nezdařilo: %1$s Uložení profilu se nezdařilo: %1$s Plocha je na pauze @@ -2026,6 +2042,15 @@ O úroveň výš Vybrat složku Vybrat soubor + Steam modrá + Nebeská + Bílá + Fialová + Zelená + Ambrová + Červená + Růžová + Šedá Tlačítko A Tlačítko B Tlačítko X @@ -2487,10 +2512,13 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Obrazovka relace + Zobrazení bez kopírování Rozlišení Přizpůsobení hry 16:9 Jak se hry s poměrem 16:9 přizpůsobí této obrazovce. Příští relace. 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 @@ -3173,6 +3201,7 @@ Experimentální sledování pohybu hlavy pro Pro 2. Nastavení jasu, hlasitosti a přepínání režimů zobrazení zatím nejsou podporovány. Cardboard VR Režim Cardboard + Obraz pro levé a pravé oko pro VR brýle pro telefon. Obraz Virtuální obrazovka 3D vedle sebe @@ -3195,6 +3224,7 @@ V této relaci není k dispozici. SteamVR neodpovídá; zkontrolujte protokol relace. Stáhnout komponenty + Stažené soubory se sdílejí se stránkou Komponenty. Výběrem stažené verze výše ji použijete při dalším spuštění hry. Vyberte verzi ke stažení Vývojář Vydavatel diff --git a/app/src/main/res/values-da/input_library.xml b/app/src/main/res/values-da/input_library.xml index ca20501cf7..3ba74431ee 100644 --- a/app/src/main/res/values-da/input_library.xml +++ b/app/src/main/res/values-da/input_library.xml @@ -75,9 +75,14 @@ Uafhængig kopi Start stikket ved berøringspunktet Skjul stikket, når det ikke bruges + Værktøjer + Auto (%1$s) + Brugerdefineret (%1$s) Gem som ny profil Profilbetjening + Profil Musetouchpadbevægelser + Når tildelt musemarkøren: tryk for at klikke, hold for at trække, og rul med to fingre. %1$s har en tilsidesættelse af hurtigmenuen. Vælg Auto for at bruge dens standardprofil og alle tre gemte dele. DroidDeck-input Holdes, mens styrepinden flyttes i en vilkårlig retning: tryk over 55 %, slip under 35 %. Brug Retningstaster til at tildele hver retning separat. DroidDeck-kommandoer kører én gang pr. udsving. Stikklikket konfigureres separat. @@ -99,11 +104,17 @@ I Steam-tilstand. Hvis du holder Tilbage, åbnes hurtigadgang også. Gendan standard Virtuel controller + Den controllertype, som Steam eller spillet ser. Berøringsskærm + Hvordan berøringer på spilskærmen håndteres. Profilknapper beholder deres tildelte handlinger. Berøringsmarkør + Viser en markør ved direkte berøringer på spilskærmen. Rør og hold + Musehandling, når du holder en finger på spilskærmen. Tryk på Tilbage-knappen + Første handling: enkelt tryk. Anden handling: dobbelttryk. Skifteknap + Tryk for at holde, tryk igen for at slippe. Åbning af en menu eller skift af profil slipper knappen. Form Afrundet Pille diff --git a/app/src/main/res/values-da/input_strings.xml b/app/src/main/res/values-da/input_strings.xml index 97d67bc242..2e4e23b45a 100644 --- a/app/src/main/res/values-da/input_strings.xml +++ b/app/src/main/res/values-da/input_strings.xml @@ -1,5 +1,6 @@ + Inputprofiler Profiler Fysisk controller Hovedskærm @@ -22,6 +23,7 @@ Åbn Steam-menuen Åbn Steams hurtigadgang Fjern kontrol + Tilføj kontrol Enhedsspecifikke knapper Tildel en fysisk knap Slip knappen, og vælg Rediger, Prøv igen eller Annuller. B eller Tilbage annullerer efter slip. diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index f38a57c7af..b1de62f68f 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. @@ -295,10 +294,14 @@ Berøring Sideknap Kontroller på skærmen + Steam + QAM Auto viser kontrollerne, når ingen controller er tilsluttet. + Steam-berøring (beta) + Steams berøringskontroller starter med næste Steam-session Steam-berøringslayout Eksportér Billede + Flyt, tilpas størrelsen på eller skjul dette spils berøringskontroller; gemmes til Steam Controller Hvordan Steam ser din controller. Gælder fra næste session. Steam Deck-controller @@ -425,6 +428,7 @@ Går uden om PulseAudio for lavere forsinkelse. Mikrofon Til voicechat. + Slå mikrofonoptagelse til eller fra for denne session. Kunne ikke ændre mikrofonen. Prøv igen. Netværk Wi-Fi-søgning @@ -786,6 +790,7 @@ Tastatur Forsinkelse Lav forsinkelse + Øger CPU- og batteriforbrug Controller med lav forsinkelse Controlleren rapporterer ved 1000 Hz i stedet for 250 Hz. Lidt mere CPU. Berøring med lav forsinkelse @@ -1339,8 +1344,12 @@ Gennemsigtighed %1$d%% Knapstørrelse + Adaptive styrepinde Spilvibration Dødzone for styrepind + Steam-knap + QAM-knap + Tastaturknap Joy-Cons som VR-controllere Mens SteamVR kører, bliver hver Joy-Con en hånd. Peg den fremad, og hold Home eller Capture nede for at centrere den igen. Animationer @@ -1469,6 +1478,8 @@ Trackpad Luk kontrollerne til den anden skærm Åbn Steam-menuen + Højre trackpad + Venstre trackpad Trackpad Vis tastatur Skjul tastatur @@ -1507,8 +1518,11 @@ Android-tastatur Skjul ✕ Størrelse på skærmen + Den del af skærmen, tastaturet fylder, inklusive header. Uigennemsigtighed + Sænk den for at se spillet bag tastaturet. Skjulte taster + Taster, du sjældent bruger, vises ikke på tastaturet. Esc og funktionsrækken Ins / Del / Home / End / PgUp / PgDn Piletaster @@ -1721,6 +1735,8 @@ Installeret %1$s - vælg den i menuen Vent til fjernelse af runtime er færdig Spil + touchpad + direkte Udskiftning mislykkedes: %1$s Lagring af profil mislykkedes: %1$s Skrivebordet er sat på pause @@ -1976,6 +1992,15 @@ Et niveau op Vælg en mappe Vælg en fil + Steam-blå + Himmelblå + Hvid + Violet + Grøn + Ravgul + Rød + Pink + Grå A-knap B-knap X-knap @@ -2435,10 +2460,13 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Sessionsskærm + Præsentation uden kopiering Opløsning 16:9-spiltilpasning Hvordan 16:9-spil tilpasses denne skærm. Fra næste session. 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 @@ -3113,6 +3141,7 @@ Eksperimentel hovedsporing til Pro 2. Justering af lysstyrke og lydstyrke samt skift af visningstilstand understøttes endnu ikke. Cardboard VR Cardboard-tilstand + Billeder til venstre og højre øje til en VR-brille til telefonen. Billede Virtuel skærm Side-by-side-3D @@ -3135,6 +3164,7 @@ Ikke tilgængelig i denne session. SteamVR svarede ikke; se sessionsloggen. Download komponenter + Downloads deles med siden Komponenter. Vælg en downloadet version ovenfor for at bruge den fra næste spilstart. Vælg en version at downloade Udvikler Udgiver diff --git a/app/src/main/res/values-de/input_library.xml b/app/src/main/res/values-de/input_library.xml index 3db1a6838d..754679261f 100644 --- a/app/src/main/res/values-de/input_library.xml +++ b/app/src/main/res/values-de/input_library.xml @@ -75,9 +75,14 @@ Unabhängige Kopie Stick an der Berührungsstelle starten Stick ausblenden, wenn nicht benutzt + Werkzeuge + Auto (%1$s) + Benutzerdefiniert (%1$s) Als neues Profil speichern Profilsteuerung + Profil Maus-Touchpad-Gesten + Wenn dem Mauszeiger zugewiesen: Tippen zum Klicken, Halten zum Ziehen, mit zwei Fingern scrollen. %1$s hat eine Schnellmenü-Überschreibung. Wähle dort Auto, um sein Standardprofil und alle drei gespeicherten Teile zu verwenden. DroidDeck Input Gehalten, während der Stick in eine beliebige Richtung bewegt wird: drücken über 55 %, loslassen unter 35 %. Mit Richtungstasten jede Richtung einzeln zuweisen. DroidDeck-Aktionen laufen einmal pro Ausschlag. Der Stick-Klick wird separat konfiguriert. @@ -99,11 +104,17 @@ Im Steam-Modus. Halten von Zurück öffnet auch den Schnellzugriff. Auf Standard zurücksetzen Virtueller Controller + Der von Steam oder dem Spiel erkannte Controller-Typ. Touchscreen + Wie Berührungen auf dem Spielbildschirm behandelt werden. Profiltasten behalten ihre zugewiesenen Aktionen. Touch-Cursor + Zeigt einen Zeiger für direkte Berührungen auf dem Spielbildschirm. Berühren und halten + Mausaktion beim Halten eines Fingers auf dem Spielbildschirm. Zurück-Taste tippen + Erste Aktion: einmal tippen. Zweite Aktion: zweimal tippen. Umschalttaste + Tippen zum Halten, erneut tippen zum Loslassen. Das Öffnen eines Menüs oder ein Profilwechsel lässt die Taste los. Form Abgerundet Pille diff --git a/app/src/main/res/values-de/input_strings.xml b/app/src/main/res/values-de/input_strings.xml index cdff5d7a23..b37b9c2b71 100644 --- a/app/src/main/res/values-de/input_strings.xml +++ b/app/src/main/res/values-de/input_strings.xml @@ -1,5 +1,6 @@ + Eingabeprofile Profile Physischer Controller Hauptbildschirm @@ -22,6 +23,7 @@ Steam-Menü öffnen Steam-Schnellzugriff öffnen Steuerung entfernen + Steuerung hinzufügen Gerätespezifische Tasten Physische Taste zuweisen Taste loslassen, dann Bearbeiten, Wiederholen oder Abbrechen wählen. B oder Zurück bricht nach dem Loslassen ab. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index c897478fbb..e24db01500 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. @@ -295,10 +294,14 @@ Touch Seitentaste Bildschirmsteuerung + Steam + QAM Auto zeigt die Steuerung an, wenn kein Controller verbunden ist. + Steam-Touch (Beta) + Steams Touch-Steuerung startet mit der nächsten Steam-Sitzung Steam-Touch-Layout Exportieren Bild + Touch-Steuerung dieses Spiels verschieben, skalieren oder ausblenden; wird in Steam gespeichert Controller Wie Steam deinen Controller erkennt. Gilt ab der nächsten Sitzung. Steam-Deck-Controller @@ -425,6 +428,7 @@ Umgeht PulseAudio für geringere Latenz. Mikrofon Für Sprachchat. + Mikrofonaufnahme für diese Sitzung ein- oder ausschalten. Das Mikrofon konnte nicht umgeschaltet werden. Bitte versuch es erneut. Netzwerk Wi-Fi-Erkennung @@ -786,6 +790,7 @@ Tastatur Latenz Modus mit geringer Latenz + Erhöht CPU- und Akkuverbrauch Controller mit geringer Latenz Der Controller meldet mit 1000 Hz statt 250 Hz. Die CPU-Last ist etwas höher. Touch mit geringer Latenz @@ -1331,8 +1336,12 @@ Deckkraft %1$d %% Tastengröße + Adaptive Sticks Spielvibration Stick-Totzone + Steam-Taste + QAM-Taste + Tastatur-Taste Joy-Cons als VR-Controller Während SteamVR läuft, wird jeder Joy-Con zu einer Hand. Richte ihn nach vorn und halte HOME oder Capture gedrückt, um ihn neu auszurichten. Animationen @@ -1461,6 +1470,8 @@ Trackpad Steuerung auf dem Zweitbildschirm schließen Steam-Menü öffnen + Rechtes Trackpad + Linkes Trackpad Trackpad Tastatur einblenden Tastatur ausblenden @@ -1499,8 +1510,11 @@ Android-Tastatur Ausblenden ✕ Größe auf dem Bildschirm + Anteil des Bildschirms, den die Tastatur einnimmt, inklusive Kopfzeile. Deckkraft + Verringern, um das Spiel hinter der Tastatur zu sehen. Ausgeblendete Tasten + Tasten, die du selten nutzt, bleiben auf der Tastatur ausgeblendet. Esc- und Funktionstastenreihe Ins / Del / Home / End / PgUp / PgDn Pfeiltasten @@ -1713,6 +1727,8 @@ %1$s installiert - wähle ihn im Menü aus Warte, bis die Laufzeit entfernt ist Spiel + Touchpad + direkt Austausch fehlgeschlagen: %1$s Profil konnte nicht gespeichert werden: %1$s Der Desktop ist pausiert @@ -1968,6 +1984,15 @@ Eine Ebene nach oben Ordner auswählen Datei auswählen + Steam-Blau + Himmelblau + Weiß + Violett + Grün + Bernstein + Rot + Pink + Grau A-Taste B-Taste X-Taste @@ -2427,10 +2452,13 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Sitzungsanzeige + Kopierfreie Darstellung Auflösung 16:9-Spielanpassung Wie 16:9-Spiele auf dieses Display passen. Ab der nächsten Sitzung. 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 @@ -3102,6 +3130,7 @@ Experimentelles Kopftracking für Pro 2. Das Einstellen von Helligkeit und Lautstärke sowie das Umschalten des Anzeigemodus werden noch nicht unterstützt. Cardboard VR Cardboard-Modus + Bilder für linkes und rechtes Auge für eine Smartphone-VR-Brille. Bild Virtueller Bildschirm Side-by-Side-3D @@ -3124,6 +3153,7 @@ In dieser Sitzung nicht verfügbar. SteamVR hat nicht reagiert; Sitzungsprotokoll prüfen. Komponenten herunterladen + Downloads werden mit der Seite „Komponenten“ geteilt. Wähle oben eine heruntergeladene Version, um sie beim nächsten Spielstart zu verwenden. Version zum Herunterladen wählen Entwickler Publisher diff --git a/app/src/main/res/values-el/input_library.xml b/app/src/main/res/values-el/input_library.xml index 7237c6763d..d100812712 100644 --- a/app/src/main/res/values-el/input_library.xml +++ b/app/src/main/res/values-el/input_library.xml @@ -75,9 +75,14 @@ Ανεξάρτητο αντίγραφο Έναρξη μοχλού στο σημείο αφής Απόκρυψη μοχλού όταν δεν χρησιμοποιείται + Εργαλεία + Αυτόματο (%1$s) + Προσαρμοσμένο (%1$s) Αποθήκευση ως νέο προφίλ Χειριστήρια προφίλ + Προφίλ Χειρονομίες touchpad ποντικιού + Όταν αντιστοιχιστεί στον δείκτη του ποντικιού: πατήστε για κλικ, κρατήστε για μεταφορά και κυλήστε με δύο δάχτυλα. Το %1$s έχει παράκαμψη γρήγορου μενού. Επιλέξτε Αυτόματο εκεί για να χρησιμοποιήσετε το προεπιλεγμένο προφίλ και τα τρία αποθηκευμένα μέρη. Είσοδος DroidDeck Κρατείται όσο ο μοχλός κινείται προς οποιαδήποτε κατεύθυνση: πάτημα πάνω από 55%, απελευθέρωση κάτω από 35%. Χρησιμοποιήστε Πλήκτρα κατεύθυνσης για κάθε κατεύθυνση ξεχωριστά. Οι εντολές DroidDeck εκτελούνται μία φορά ανά εκτροπή. Το κλικ του μοχλού ρυθμίζεται ξεχωριστά. @@ -99,11 +104,17 @@ Σε λειτουργία Steam. Το κράτημα του Πίσω ανοίγει και τη γρήγορη πρόσβαση. Επαναφορά στις προεπιλογές Εικονικό χειριστήριο + Ο τύπος χειριστηρίου που βλέπουν το Steam ή το παιχνίδι. Οθόνη αφής + Πώς χειρίζονται τα αγγίγματα στην οθόνη του παιχνιδιού. Τα κουμπιά του προφίλ διατηρούν τις αντιστοιχισμένες ενέργειες. Δείκτης αφής + Εμφανίζει δείκτη για άμεσα αγγίγματα στην οθόνη του παιχνιδιού. Άγγιγμα και κράτημα + Ενέργεια ποντικιού όταν κρατάτε το δάχτυλό σας στην οθόνη του παιχνιδιού. Πατήματα του κουμπιού Πίσω + Πρώτη ενέργεια: ένα πάτημα. Δεύτερη ενέργεια: διπλό πάτημα. Κουμπί εναλλαγής + Πατήστε για κράτημα, πατήστε ξανά για απελευθέρωση. Το άνοιγμα μενού ή η αλλαγή προφίλ απελευθερώνει το κουμπί. Σχήμα Στρογγυλεμένο Κάψουλα diff --git a/app/src/main/res/values-el/input_strings.xml b/app/src/main/res/values-el/input_strings.xml index 935464ffb4..58b5bce713 100644 --- a/app/src/main/res/values-el/input_strings.xml +++ b/app/src/main/res/values-el/input_strings.xml @@ -1,5 +1,6 @@ + Προφίλ εισόδου Προφίλ Φυσικό χειριστήριο Κύρια οθόνη @@ -22,6 +23,7 @@ Άνοιγμα μενού Steam Άνοιγμα γρήγορης πρόσβασης Steam Αφαίρεση στοιχείου + Προσθήκη στοιχείου Κουμπιά ειδικά για τη συσκευή Αντιστοίχιση φυσικού κουμπιού Αφήστε το κουμπί και επιλέξτε Επεξεργασία, Επανάληψη ή Ακύρωση. Το B ή το Πίσω ακυρώνει αφού αφήσετε το κουμπί. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 5f23fee839..4bb5fc7344 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 και την Επιφάνεια εργασίας. Ορίζονται στη σελίδα Στοιχεία. @@ -295,10 +294,14 @@ Αφή Πλαϊνό κουμπί Χειριστήρια στην οθόνη + Steam + QAM Το Αυτόματο εμφανίζει τα χειριστήρια όταν δεν είναι συνδεδεμένο χειριστήριο. + Αφή Steam (beta) + Τα χειριστήρια αφής του Steam ξεκινούν από την επόμενη συνεδρία Steam Διάταξη αφής Steam Εξαγωγή Εικόνα + Μετακινήστε, αλλάξτε μέγεθος ή αποκρύψτε τα χειριστήρια αφής αυτού του παιχνιδιού· αποθηκεύεται στο Steam Χειριστήριο Πώς βλέπει το Steam το χειριστήριό σας. Εφαρμόζεται στην επόμενη συνεδρία. Χειριστήριο Steam Deck @@ -425,6 +428,7 @@ Παρακάμπτει το PulseAudio για μικρότερη καθυστέρηση. Μικρόφωνο Για φωνητική συνομιλία. + Ενεργοποίηση ή απενεργοποίηση της λήψης μικροφώνου για αυτή τη συνεδρία. Δεν ήταν δυνατή η αλλαγή του μικροφώνου. Δοκιμάστε ξανά. Δίκτυο Εντοπισμός Wi-Fi @@ -786,6 +790,7 @@ Πληκτρολόγιο Καθυστέρηση Λειτουργία χαμηλής καθυστέρησης + Αυξάνει τη χρήση CPU και μπαταρίας Χειριστήριο χαμηλής καθυστέρησης Το χειριστήριο αναφέρει στα 1000 Hz αντί για 250 Hz. Λίγο περισσότερο CPU. Αφή χαμηλής καθυστέρησης @@ -1339,8 +1344,12 @@ Διαφάνεια %1$d%% Μέγεθος κουμπιών + Προσαρμοστικοί μοχλοί Κραδασμός παιχνιδιού Νεκρή ζώνη μοχλού + Κουμπί Steam + Κουμπί QAM + Κουμπί πληκτρολογίου Joy-Con ως χειριστήρια VR Όσο εκτελείται το SteamVR, κάθε Joy-Con γίνεται χέρι. Στρέψτε το μπροστά και κρατήστε πατημένο το Home ή το Capture για να το επανακεντράρετε. Κινήσεις @@ -1469,6 +1478,8 @@ Πινακίδα αφής Κλείσιμο χειριστηρίων δεύτερης οθόνης Άνοιγμα μενού Steam + Δεξιά πινακίδα αφής + Αριστερή πινακίδα αφής Πινακίδα αφής Εμφάνιση πληκτρολογίου Απόκρυψη πληκτρολογίου @@ -1507,8 +1518,11 @@ Πληκτρολόγιο Android Απόκρυψη ✕ Μέγεθος στην οθόνη + Ποσοστό της οθόνης που καταλαμβάνει το πληκτρολόγιο, συμπεριλαμβανομένης της κεφαλίδας. Αδιαφάνεια + Μειώστε την για να βλέπετε το παιχνίδι πίσω από το πληκτρολόγιο. Κρυφά πλήκτρα + Τα πλήκτρα που χρησιμοποιείτε σπάνια δεν εμφανίζονται στο πληκτρολόγιο. Esc και σειρά λειτουργιών Ins / Del / Home / End / PgUp / PgDn Πλήκτρα βελών @@ -1721,6 +1735,8 @@ Εγκατεστημένο %1$s - επιλέξτε το στο μενού Περιμένετε να ολοκληρωθεί η κατάργηση του runtime Παιχνίδι + πινακίδα αφής + απευθείας Η εναλλαγή απέτυχε: %1$s Η αποθήκευση προφίλ απέτυχε: %1$s Η επιφάνεια εργασίας είναι σε παύση @@ -1976,6 +1992,15 @@ Ένα επίπεδο πάνω Επιλέξτε φάκελο Επιλέξτε αρχείο + Μπλε Steam + Γαλάζιο + Λευκό + Βιολετί + Πράσινο + Κεχριμπαρί + Κόκκινο + Ροζ + Γκρι Κουμπί A Κουμπί B Κουμπί X @@ -2435,10 +2460,13 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Οθόνη συνεδρίας + Παρουσίαση χωρίς αντιγραφή Ανάλυση Προσαρμογή παιχνιδιού 16:9 Πώς προσαρμόζονται τα παιχνίδια 16:9 σε αυτή την οθόνη. Από την επόμενη συνεδρία. Επιλέξτε Αντιστοίχιση οθόνης ή ένα προσαρμοσμένο μέγεθος πιο στενό από 16:9. + Αποφυγή εγκοπής + Κρατά την εικόνα μακριά από την εγκοπή της κάμερας. Εφαρμόζεται όταν επιστρέψεις στη συνεδρία. Διατήρηση αναλογιών Διάταση στην οθόνη Κλιμάκωση εικόνας @@ -3113,6 +3141,7 @@ Πειραματική παρακολούθηση κεφαλής για Pro 2. Η ρύθμιση της φωτεινότητας και της έντασης ήχου και η αλλαγή λειτουργίας οθόνης δεν υποστηρίζονται ακόμη. Cardboard VR Λειτουργία Cardboard + Εικόνες για το αριστερό και το δεξί μάτι, για γυαλιά VR κινητού. Εικόνα Εικονική οθόνη 3D δίπλα-δίπλα @@ -3135,6 +3164,7 @@ Δεν είναι διαθέσιμο σε αυτή τη συνεδρία. Το SteamVR δεν αποκρίθηκε· ελέγξτε το αρχείο καταγραφής της συνεδρίας. Λήψη στοιχείων + Οι λήψεις είναι κοινές με τη σελίδα Στοιχεία. Επιλέξτε παραπάνω μια έκδοση που έχει ληφθεί για να χρησιμοποιηθεί στην επόμενη εκκίνηση παιχνιδιού. Επιλέξτε έκδοση για λήψη Δημιουργός Εκδότης diff --git a/app/src/main/res/values-es/input_library.xml b/app/src/main/res/values-es/input_library.xml index 1b9378e4b9..a2271204a7 100644 --- a/app/src/main/res/values-es/input_library.xml +++ b/app/src/main/res/values-es/input_library.xml @@ -75,9 +75,14 @@ Copia independiente Iniciar el stick en el punto de toque Ocultar el stick cuando no se use + Herramientas + Auto (%1$s) + Personalizado (%1$s) Guardar como perfil nuevo Controles del perfil + Perfil Gestos del panel táctil del ratón + Si se asigna al puntero del ratón: toca para hacer clic, mantén para arrastrar y desplaza con dos dedos. %1$s tiene una anulación del menú rápido. Selecciona Auto allí para usar su perfil predeterminado y sus tres partes guardadas. Entrada de DroidDeck Se mantiene mientras el stick se mueve en cualquier dirección: se pulsa por encima del 55 %, se suelta por debajo del 35 %. Usa Teclas de dirección para asignar cada dirección por separado. Los comandos de DroidDeck se ejecutan una vez por desvío. El clic del stick se configura aparte. @@ -99,11 +104,17 @@ En modo Steam. Mantener Atrás también abre el acceso rápido. Restaurar valores predeterminados Mando virtual + El tipo de mando que ven Steam o el juego. Pantalla táctil + Cómo se manejan los toques en la pantalla del juego. Los botones del perfil mantienen sus acciones asignadas. Cursor táctil + Muestra un puntero para toques directos en la pantalla del juego. Tocar y mantener + Acción del ratón al mantener un dedo en la pantalla del juego. Toques del botón Atrás + Primera acción: un toque. Segunda acción: doble toque. Botón de alternar + Toca para mantener, toca de nuevo para soltar. Abrir un menú o cambiar de perfil suelta el botón. Forma Redondeada Píldora diff --git a/app/src/main/res/values-es/input_strings.xml b/app/src/main/res/values-es/input_strings.xml index 2e55137993..e6e5a5bec5 100644 --- a/app/src/main/res/values-es/input_strings.xml +++ b/app/src/main/res/values-es/input_strings.xml @@ -1,5 +1,6 @@ + Perfiles de entrada Perfiles Mando físico Pantalla principal @@ -22,6 +23,7 @@ Abrir el menú de Steam Abrir el acceso rápido de Steam Quitar control + Añadir control Botones específicos del dispositivo Asignar un botón físico Suelta el botón y elige Editar, Reintentar o Cancelar. B o Atrás cancela tras soltarlo. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index c5c083f7b9..354828c595 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. @@ -295,10 +294,14 @@ Táctil Botón lateral Controles en pantalla + Steam + QAM Auto muestra los controles cuando no hay ningún mando conectado. + Táctil de Steam (beta) + Los controles táctiles de Steam se activan en la próxima sesión de Steam Disposición táctil de Steam Exportar Imagen + Mueve, cambia de tamaño u oculta los controles táctiles de este juego; se guarda en Steam Mando Cómo ve Steam tu mando. Se aplica en la próxima sesión. Mando de Steam Deck @@ -426,6 +429,7 @@ Evita PulseAudio para menor latencia. Micrófono Para el chat de voz. + Activa o desactiva la captura del micrófono en esta sesión. No se ha podido cambiar el micrófono. Inténtalo de nuevo. Red Detección de redes Wi-Fi @@ -788,6 +792,7 @@ Teclado Latencia Modo de baja latencia + Aumenta el uso de CPU y batería Mando de baja latencia El mando informa a 1000 Hz en lugar de 250 Hz. Usa algo más de CPU. Táctil de baja latencia @@ -1346,8 +1351,12 @@ Opacidad %1$d%% Tamaño de botones + Sticks adaptables Vibración en juegos Zona muerta de la palanca + Botón Steam + Botón QAM + Botón de teclado Joy-Con como mandos de RV Mientras SteamVR está activo, cada Joy-Con es una mano. Apúntalo al frente y mantén Home o Captura para recentrarlo. Animaciones @@ -1477,6 +1486,8 @@ Trackpad Cerrar controles de la segunda pantalla Abrir menú de Steam + Trackpad derecho + Trackpad izquierdo Trackpad Mostrar teclado Ocultar teclado @@ -1515,8 +1526,11 @@ Teclado de Android Ocultar ✕ Tamaño en pantalla + Proporción de la pantalla que ocupa el teclado, cabecera incluida. Opacidad + Redúcela para ver el juego detrás del teclado. Teclas ocultas + Las teclas que apenas usas no aparecen en el teclado. Esc y fila de teclas de función Ins / Supr / Inicio / Fin / RePág / AvPág Teclas de dirección @@ -1737,6 +1751,8 @@ %1$s instalado - elígelo en el menú Espera a que termine la eliminación del runtime Juego + touchpad + directo El reemplazo falló: %1$s No se pudo guardar el perfil: %1$s El escritorio está en pausa @@ -2001,6 +2017,15 @@ Subir un nivel Elige una carpeta Elige un archivo + Azul Steam + Celeste + Blanco + Violeta + Verde + Ámbar + Rojo + Rosa + Gris Botón A Botón B Botón X @@ -2461,10 +2486,13 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Pantalla de la sesión + Presentación sin copia Resolución Ajuste de juegos 16:9 Cómo se ajustan los juegos 16:9 a esta pantalla. Próxima sesión. 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 @@ -3137,6 +3165,7 @@ %1$d min Cardboard VR Modo Cardboard + Vistas para el ojo izquierdo y el derecho para un visor de RV para móvil. Imagen Pantalla virtual 3D lado a lado @@ -3159,6 +3188,7 @@ No disponible en esta sesión. SteamVR no respondió; revisa el registro de la sesión. Descargar componentes + Las descargas se comparten con la página Componentes. Elige arriba una versión descargada para usarla al iniciar el próximo juego. Elige una versión para descargar Cliente de Steam FEX %1$s diff --git a/app/src/main/res/values-fi/input_library.xml b/app/src/main/res/values-fi/input_library.xml index 7f5cfd83e8..8fd745f70a 100644 --- a/app/src/main/res/values-fi/input_library.xml +++ b/app/src/main/res/values-fi/input_library.xml @@ -75,9 +75,14 @@ Itsenäinen kopio Aloita tikku kosketuskohdasta Piilota tikku, kun sitä ei käytetä + Työkalut + Automaattinen (%1$s) + Mukautettu (%1$s) Tallenna uutena profiilina Profiilin ohjaimet + Profiili Hiiren kosketuslevyn eleet + Kun määritetty hiiren osoittimelle: napauta klikataksesi, pidä painettuna vetääksesi ja vieritä kahdella sormella. Kohteella %1$s on pikavalikon ohitus. Valitse Automaattinen käyttääksesi sen oletusprofiilia ja kaikkia kolmea tallennettua osaa. DroidDeck-syöte Pidetään, kun tikkua liikutetaan mihin tahansa suuntaan: painetaan yli 55 %:ssa, vapautetaan alle 35 %:ssa. Määritä jokainen suunta erikseen Suuntanäppäimillä. DroidDeck-komennot suoritetaan kerran poikkeamaa kohti. Tikun napsautus määritetään erikseen. @@ -99,11 +104,17 @@ Steam-tilassa. Takaisin-painikkeen pitäminen avaa myös pikakäytön. Palauta oletukset Virtuaaliohjain + Ohjaintyyppi, jonka Steam tai peli näkee. Kosketusnäyttö + Miten pelinäytön kosketuksia käsitellään. Profiilin painikkeet säilyttävät määritetyt toimintonsa. Kosketuskursori + Näyttää osoittimen suorille kosketuksille pelinäytöllä. Kosketa ja pidä + Hiiren toiminto, kun pidät sormea pelinäytöllä. Takaisin-painikkeen napautukset + Ensimmäinen toiminto: yksi napautus. Toinen toiminto: kaksoisnapautus. Vaihtopainike + Napauta pitääksesi, napauta uudelleen vapauttaaksesi. Valikon avaaminen tai profiilin vaihto vapauttaa painikkeen. Muoto Pyöristetty Kapseli diff --git a/app/src/main/res/values-fi/input_strings.xml b/app/src/main/res/values-fi/input_strings.xml index d9212fb363..945b606896 100644 --- a/app/src/main/res/values-fi/input_strings.xml +++ b/app/src/main/res/values-fi/input_strings.xml @@ -1,5 +1,6 @@ + Syöttöprofiilit Profiilit Fyysinen ohjain Päänäyttö @@ -22,6 +23,7 @@ Avaa Steam-valikko Avaa Steamin pikakäyttö Poista ohjain + Lisää ohjain Laittekohtaiset painikkeet Määritä fyysinen painike Vapauta painike ja valitse Muokkaa, Yritä uudelleen tai Peruuta. B tai Takaisin peruuttaa vapauttamisen jälkeen. diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 4690cf37e1..48387e6806 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. @@ -295,10 +294,14 @@ Kosketus Sivupainike Näytön ohjaimet + Steam + QAM Automaattinen näyttää ohjaimet, kun yhtään ohjainta ei ole kytketty. + Steam-kosketus (beta) + Steamin kosketusohjaimet otetaan käyttöön seuraavassa Steam-istunnossa Steamin kosketusasettelu Vie Kuva + Siirrä, muuta kokoa tai piilota tämän pelin kosketusohjaimet; tallennetaan Steamiin Ohjain Miten Steam näkee ohjaimesi. Tulee voimaan seuraavassa istunnossa. Steam Deck -ohjain @@ -425,6 +428,7 @@ Ohittaa PulseAudion pienempää viivettä varten. Mikrofoni Äänichattia varten. + Kytke mikrofonin äänitys päälle tai pois tässä istunnossa. Mikrofonia ei voitu muuttaa. Yritä uudelleen. Verkko Wi-Fi-haku @@ -786,6 +790,7 @@ Näppäimistö Viive Matalan viiveen tila + Lisää CPU:n ja akun käyttöä Matalan viiveen ohjain Ohjain raportoi 1000 Hz:n taajuudella 250 Hz:n sijaan. Hieman enemmän CPU:ta. Matalan viiveen kosketus @@ -1339,8 +1344,12 @@ Peittävyys %1$d %% Painikkeiden koko + Mukautuvat sauvat Pelin tärinä Ohjaussauvan kuollut alue + Steam-painike + QAM-painike + Näppäimistöpainike Joy-Conit VR-ohjaimina Kun SteamVR on käynnissä, jokainen Joy-Con toimii kätenä. Osoita sillä eteenpäin ja pidä Home- tai Capture-painiketta pohjassa keskittääksesi sen uudelleen. Animaatiot @@ -1469,6 +1478,8 @@ Kosketuslevy Sulje toisen näytön ohjaimet Avaa Steam-valikko + Oikea kosketuslevy + Vasen kosketuslevy Kosketuslevy Näytä näppäimistö Piilota näppäimistö @@ -1507,8 +1518,11 @@ Android-näppäimistö Piilota ✕ Koko näytöllä + Näytön osuus, jonka näppäimistö vie, yläpalkki mukaan lukien. Peittävyys + Laske sitä, jotta peli näkyy näppäimistön takaa. Piilotetut näppäimet + Harvoin käyttämäsi näppäimet pysyvät pois näppäimistöstä. Esc ja funktiorivi Ins / Del / Home / End / PgUp / PgDn Nuolinäppäimet @@ -1721,6 +1735,8 @@ Asennettu %1$s - valitse se valikosta Odota, että ajoympäristön poisto päättyy Peli + kosketuslevy + suora Vaihto epäonnistui: %1$s Profiilin tallennus epäonnistui: %1$s Työpöytä on keskeytetty @@ -1976,6 +1992,15 @@ Ylös yksi taso Valitse kansio Valitse tiedosto + Steam-sininen + Taivaansininen + Valkoinen + Violetti + Vihreä + Meripihka + Punainen + Pinkki + Harmaa A-painike B-painike X-painike @@ -2435,10 +2460,13 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Istunnon näyttö + Kopioimaton esitys Tarkkuus 16:9-pelin sovitus Miten 16:9-pelit sovitetaan tähän näyttöön. Seuraava istunto. 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 @@ -3113,6 +3141,7 @@ Kokeellinen päänliikkeiden seuranta Pro 2:lle. Kirkkauden ja äänenvoimakkuuden säätöä sekä näyttötilan vaihtamista ei vielä tueta. Cardboard VR Cardboard-tila + Vasemman ja oikean silmän kuvat puhelimen VR-laseille. Kuva Virtuaalinen näyttö Rinnakkais-3D @@ -3135,6 +3164,7 @@ Ei käytettävissä tässä istunnossa. SteamVR ei vastannut; tarkista istunnon loki. Lataa komponentteja + Lataukset jaetaan Komponentit-sivun kanssa. Valitse yltä ladattu versio, niin sitä käytetään seuraavalla pelin käynnistyksellä. Valitse ladattava versio Kehittäjä Julkaisija diff --git a/app/src/main/res/values-fr/input_library.xml b/app/src/main/res/values-fr/input_library.xml index 24e1d67d47..0dbdf5dbca 100644 --- a/app/src/main/res/values-fr/input_library.xml +++ b/app/src/main/res/values-fr/input_library.xml @@ -75,9 +75,14 @@ Copie indépendante Démarrer le stick au point de contact Masquer le stick lorsqu\'il n\'est pas utilisé + Outils + Auto (%1$s) + Personnalisé (%1$s) Enregistrer comme nouveau profil Contrôles du profil + Profil Gestes du pavé tactile de la souris + Si assigné au pointeur de la souris : toucher pour cliquer, maintenir pour faire glisser, défiler avec deux doigts. %1$s a une dérogation de menu rapide. Sélectionnez Auto pour utiliser son profil par défaut et ses trois parties enregistrées. Entrée DroidDeck Maintenu lorsque le stick est déplacé dans n\'importe quelle direction : appui au-dessus de 55 %, relâchement sous 35 %. Utilisez Touches de direction pour assigner chaque direction séparément. Les commandes DroidDeck s\'exécutent une fois par déflexion. Le clic du stick se configure séparément. @@ -99,11 +104,17 @@ En mode Steam. Maintenir Retour ouvre aussi l\'accès rapide. Rétablir par défaut Manette virtuelle + Le type de manette vu par Steam ou le jeu. Écran tactile + Comment les touchers sur l\'écran du jeu sont gérés. Les boutons du profil gardent leurs actions assignées. Curseur tactile + Affiche un pointeur pour les touchers directs sur l\'écran du jeu. Toucher et maintenir + Action de la souris en maintenant un doigt sur l\'écran du jeu. Appuis du bouton Retour + Première action : appui simple. Deuxième action : appui double. Bouton à bascule + Touchez pour maintenir, touchez encore pour relâcher. Ouvrir un menu ou changer de profil relâche le bouton. Forme Arrondie Pilule diff --git a/app/src/main/res/values-fr/input_strings.xml b/app/src/main/res/values-fr/input_strings.xml index ef886b695a..eb2182ad4d 100644 --- a/app/src/main/res/values-fr/input_strings.xml +++ b/app/src/main/res/values-fr/input_strings.xml @@ -1,5 +1,6 @@ + Profils d\'entrée Profils Manette physique Écran principal @@ -22,6 +23,7 @@ Ouvrir le menu Steam Ouvrir l\'accès rapide Steam Supprimer le contrôle + Ajouter un contrôle Boutons propres à l\'appareil Assigner un bouton physique Relâchez le bouton, puis choisissez Modifier, Réessayer ou Annuler. B ou Retour annule après le relâchement. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index b69318e76c..90348a7edc 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 ». @@ -295,10 +294,14 @@ Tactile Bouton latéral Commandes à l\'écran + Steam + QAM Le mode automatique affiche les commandes à l\'écran lorsqu\'aucune manette n\'est connectée. + Tactile Steam (bêta) + Les commandes tactiles de Steam s\'activeront à la prochaine session Steam Disposition tactile Steam Exporter Image + Déplacez, redimensionnez ou masquez les commandes tactiles de ce jeu ; enregistré dans Steam Manette Comment Steam reconnaît votre manette. Prendra effet à la prochaine session. Manette Steam Deck @@ -426,6 +429,7 @@ Contourne PulseAudio pour réduire la latence. Microphone Utilisé pour le chat vocal. + Activer ou désactiver la capture du microphone pour cette session. Impossible de modifier le microphone. Veuillez réessayer. Réseau Découverte Wi-Fi @@ -788,6 +792,7 @@ Clavier Latence Mode faible latence + Augmente l\'utilisation du CPU et de la batterie Manette à faible latence La manette émet à 1000 Hz au lieu de 250 Hz. Un peu plus de CPU. Tactile à faible latence @@ -1345,8 +1350,12 @@ Opacité %1$d%% Taille des boutons + Joystick adaptatif Vibration du jeu Zone morte du stick + Bouton Steam + Bouton QAM + Bouton clavier Joy-Con comme manettes VR Pendant que SteamVR tourne, chaque Joy-Con devient une main. Pointez-le devant vous et maintenez Home ou Capture pour le recentrer. Animations @@ -1476,6 +1485,8 @@ Pavé tactile Fermer les commandes du deuxième écran Ouvrir le menu Steam + Pavé tactile droit + Pavé tactile gauche Pavé tactile Afficher le clavier Masquer le clavier @@ -1514,8 +1525,11 @@ Clavier Android Masquer ✕ Taille à l\'écran + Part de l\'écran occupée par le clavier, y compris l\'en-tête. Opacité + Réduisez-la pour voir le jeu derrière le clavier. Touches masquées + Les touches que vous utilisez rarement ne s\'affichent pas sur le clavier. Échap et rangée des touches de fonction Ins / Suppr / Début / Fin / PgPréc / PgSuiv Touches fléchées @@ -1736,6 +1750,8 @@ %1$s installé - choisissez-le dans le menu Attendez la fin de la suppression de l\'environnement d\'exécution Jeu + pavé tactile + direct Échec du remplacement : %1$s Échec de l\'enregistrement du profil : %1$s Le bureau est en pause @@ -2000,6 +2016,15 @@ Remonter d\'un niveau Choisir un dossier Choisir un fichier + Bleu Steam + Ciel + Blanc + Violet + Vert + Ambre + Rouge + Rose + Gris Bouton A Bouton B Bouton X @@ -2460,10 +2485,13 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Affichage de la session + Affichage sans copie Résolution Ajustement des jeux 16:9 Comment les jeux 16:9 s\'adaptent à cet écran. À la prochaine session. 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 @@ -3147,6 +3175,7 @@ %1$d min Cardboard VR Mode Cardboard + Vues pour l\'œil gauche et l\'œil droit, pour un casque VR pour téléphone. Image Écran virtuel 3D côte à côte @@ -3169,6 +3198,7 @@ Indisponible dans cette session. SteamVR ne répond pas ; consultez le journal de session. Télécharger des composants + Les téléchargements sont partagés avec la page « Composants ». Choisissez une version téléchargée ci-dessus pour l\'utiliser au prochain lancement du jeu. Choisissez une version à télécharger Espace libre insuffisant : %1$s nécessaires, seulement %2$s libres Espace insuffisant (%1$s libres, %2$s nécessaires) diff --git a/app/src/main/res/values-hi/input_library.xml b/app/src/main/res/values-hi/input_library.xml index 4496965c3c..7ba5438500 100644 --- a/app/src/main/res/values-hi/input_library.xml +++ b/app/src/main/res/values-hi/input_library.xml @@ -75,9 +75,14 @@ स्वतंत्र प्रति स्पर्श स्थान से स्टिक शुरू करें उपयोग में न हो तो स्टिक छिपाएँ + टूल + Auto (%1$s) + कस्टम (%1$s) नए प्रोफ़ाइल के रूप में सहेजें प्रोफ़ाइल नियंत्रण + प्रोफ़ाइल माउस टचपैड इशारे + माउस पॉइंटर पर असाइन होने पर: क्लिक के लिए टैप करें, खींचने के लिए दबाए रखें, और दो उँगलियों से स्क्रॉल करें। %1$s में क्विक-मेन्यू ओवरराइड है। वहाँ Auto चुनें ताकि उसका डिफ़ॉल्ट प्रोफ़ाइल और तीनों सहेजे भाग उपयोग हों। DroidDeck इनपुट स्टिक को किसी भी दिशा में हिलाने पर दबा रहता है: 55% से ऊपर दबाएँ, 35% से नीचे छोड़ें। प्रत्येक दिशा अलग असाइन करने के लिए दिशा कुंजियाँ उपयोग करें। DroidDeck क्रियाएँ प्रति झुकाव एक बार चलती हैं। स्टिक क्लिक अलग से सेट होता है। @@ -99,11 +104,17 @@ Steam मोड में। वापस दबाए रखने से क्विक एक्सेस भी खुलता है। डिफ़ॉल्ट पर पुनर्स्थापित करें वर्चुअल कंट्रोलर + Steam या गेम द्वारा देखा जाने वाला कंट्रोलर प्रकार। टचस्क्रीन + गेम स्क्रीन पर स्पर्श कैसे संभाले जाते हैं। प्रोफ़ाइल बटन अपनी असाइन की गई क्रियाएँ रखते हैं। टच कर्सर + गेम स्क्रीन पर सीधे स्पर्श के लिए पॉइंटर दिखाएँ। स्पर्श करें और दबाए रखें + गेम स्क्रीन पर उँगली दबाए रखने पर माउस क्रिया। वापस बटन टैप + पहली क्रिया: एक टैप। दूसरी क्रिया: दो टैप। टॉगल बटन + दबाए रखने के लिए टैप करें, छोड़ने के लिए फिर टैप करें। मेन्यू खोलने या प्रोफ़ाइल बदलने पर बटन छूट जाता है। आकार गोल गोली diff --git a/app/src/main/res/values-hi/input_strings.xml b/app/src/main/res/values-hi/input_strings.xml index 18f501391f..4a0fb0a0f2 100644 --- a/app/src/main/res/values-hi/input_strings.xml +++ b/app/src/main/res/values-hi/input_strings.xml @@ -1,5 +1,6 @@ + इनपुट प्रोफ़ाइल प्रोफ़ाइल भौतिक कंट्रोलर मुख्य स्क्रीन @@ -22,6 +23,7 @@ Steam मेन्यू खोलें Steam त्वरित पहुँच खोलें नियंत्रण हटाएँ + नियंत्रण जोड़ें डिवाइस-विशिष्ट बटन भौतिक बटन असाइन करें बटन छोड़ें, फिर संपादित करें, पुनः प्रयास करें या रद्द करें चुनें। छोड़ने के बाद B या वापस रद्द करता है। diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 7a32cca83c..bac24154ff 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 पेज पर सेट करें। @@ -295,10 +294,14 @@ टच साइड बटन ऑन-स्क्रीन कंट्रोल + Steam + QAM कोई कंट्रोलर कनेक्ट न होने पर ऑटो कंट्रोल दिखाता है। + Steam टच (बीटा) + Steam के टच कंट्रोल अगले Steam सेशन से शुरू होंगे Steam टच लेआउट निर्यात छवि + इस गेम के टच कंट्रोल को घुमाएं, आकार बदलें या छिपाएं; Steam में सेव होता है कंट्रोलर Steam आपके कंट्रोलर को किस तरह पहचानता है। अगले सेशन से लागू होता है। Steam Deck कंट्रोलर @@ -425,6 +428,7 @@ कम लेटेंसी के लिए PulseAudio को बायपास करता है। माइक्रोफ़ोन वॉइस चैट के लिए। + इस सेशन के लिए माइक्रोफ़ोन कैप्चर चालू या बंद करें। माइक्रोफ़ोन बदला नहीं जा सका। कृपया फिर कोशिश करें। नेटवर्क Wi-Fi खोज @@ -786,6 +790,7 @@ कीबोर्ड लेटेंसी लो लेटेंसी मोड + CPU और बैटरी का इस्तेमाल बढ़ाता है कम लेटेंसी कंट्रोलर कंट्रोलर 250 Hz के बजाय 1000 Hz पर रिपोर्ट करता है। थोड़ा ज़्यादा CPU। कम लेटेंसी टच @@ -1339,8 +1344,12 @@ ओपैसिटी %1$d%% बटन का आकार + एडैप्टिव स्टिक गेम वाइब्रेशन स्टिक का डेड ज़ोन + Steam बटन + QAM बटन + कीबोर्ड बटन Joy-Con को VR कंट्रोलर की तरह SteamVR चलते समय हर Joy-Con एक हाथ बन जाता है। उसे सामने की ओर करें और फिर से केंद्रित करने के लिए Home या Capture दबाए रखें। एनिमेशन @@ -1469,6 +1478,8 @@ ट्रैकपैड दूसरी स्क्रीन के कंट्रोल बंद करें Steam मेनू खोलें + दायां ट्रैकपैड + बायां ट्रैकपैड ट्रैकपैड कीबोर्ड दिखाएं कीबोर्ड छिपाएं @@ -1507,8 +1518,11 @@ Android कीबोर्ड छिपाएं ✕ स्क्रीन पर आकार + कीबोर्ड स्क्रीन का कितना हिस्सा घेरता है, हेडर समेत। अपारदर्शिता + कीबोर्ड के पीछे गेम दिखाने के लिए इसे घटाएँ। छिपी कुंजियाँ + जिन कुंजियों का आप कम इस्तेमाल करते हैं, वे कीबोर्ड पर नहीं रहतीं। Esc और फ़ंक्शन पंक्ति Ins / Del / Home / End / PgUp / PgDn कुंजियाँ तीर कुंजियाँ @@ -1721,6 +1735,8 @@ इंस्टॉल है %1$s - इसे मेनू में चुनें रनटाइम हटाना खत्म होने का इंतज़ार करें गेम + टचपैड + डायरेक्ट स्वैप विफल: %1$s प्रोफ़ाइल सेव विफल: %1$s डेस्कटॉप रुका हुआ है @@ -1976,6 +1992,15 @@ एक लेवल ऊपर फ़ोल्डर चुनें फ़ाइल चुनें + Steam ब्लू + स्काई + सफ़ेद + वायलेट + हरा + एम्बर + लाल + गुलाबी + धूसर A बटन B बटन X बटन @@ -2435,10 +2460,13 @@ ANDROID + LINUX %1$s। %2$s\n\n%3$s सेशन डिस्प्ले + बिना कॉपी प्रस्तुति रिज़ॉल्यूशन 16:9 गेम फ़िट 16:9 गेम इस डिस्प्ले में कैसे फ़िट होते हैं। अगले सेशन से। Match screen चुनें या 16:9 से पतला कस्टम आकार चुनें। + नॉच से बचें + तस्वीर को कैमरा कटआउट से दूर रखता है। सेशन में लौटने पर लागू होता है। अनुपात बनाए रखें डिस्प्ले में स्ट्रेच करें इमेज स्केलिंग @@ -3113,6 +3141,7 @@ Pro 2 के लिए प्रायोगिक हेड ट्रैकिंग। चमक और वॉल्यूम बदलना और डिस्प्ले मोड स्विच करना अभी समर्थित नहीं है। Cardboard VR Cardboard मोड + फ़ोन VR व्यूअर के लिए बाईं और दाईं आंख के व्यू। तस्वीर वर्चुअल स्क्रीन साइड-बाय-साइड 3D @@ -3135,6 +3164,7 @@ इस सेशन में उपलब्ध नहीं है। SteamVR ने जवाब नहीं दिया; सेशन लॉग देखें। कंपोनेंट डाउनलोड करें + डाउनलोड Components पेज के साथ साझा होते हैं। अगली बार गेम शुरू होने पर इस्तेमाल करने के लिए ऊपर डाउनलोड किया गया वर्शन चुनें। डाउनलोड करने के लिए वर्शन चुनें डेवलपर पब्लिशर diff --git a/app/src/main/res/values-hu/input_library.xml b/app/src/main/res/values-hu/input_library.xml index c728c2c9a5..a02e758852 100644 --- a/app/src/main/res/values-hu/input_library.xml +++ b/app/src/main/res/values-hu/input_library.xml @@ -75,9 +75,14 @@ Független másolat Kar indítása az érintési ponttól Kar elrejtése, ha nincs használatban + Eszközök + Automatikus (%1$s) + Egyéni (%1$s) Mentés új profilként Profil vezérlői + Profil Egér érintőfelület-gesztusok + Ha az egérkurzorhoz van rendelve: koppintson a kattintáshoz, tartsa nyomva a húzáshoz, és két ujjal görgessen. A(z) %1$s gyorsmenü-felülírással rendelkezik. Válassza ott az Automatikust, hogy az alapértelmezett profilját és mindhárom mentett részét használja. DroidDeck bemenet Nyomva tartva, amíg a kart bármely irányba mozgatja: nyomás 55% felett, elengedés 35% alatt. Az Iránybillentyűkkel külön rendelhető minden irány. A DroidDeck parancsok kitérésenként egyszer futnak. A kar kattintása külön állítható. @@ -99,11 +104,17 @@ Steam módban. A Vissza nyomva tartása a gyorselérést is megnyitja. Visszaállítás alapértelmezettre Virtuális vezérlő + A Steam vagy a játék által látott vezérlőtípus. Érintőképernyő + Hogyan kezelődnek a játék képernyőjén történő érintések. A profilgombok megtartják hozzárendelt műveleteiket. Érintéskurzor + Mutatót jelenít meg a játék képernyőjén történő közvetlen érintésekhez. Érintés és nyomva tartás + Egér művelet, amikor ujját a játék képernyőjén tartja. Vissza gomb koppintásai + Első művelet: egy koppintás. Második művelet: dupla koppintás. Kapcsológomb + Koppintson a tartáshoz, koppintson újra az elengedéshez. Menü megnyitása vagy profilváltás elengedi a gombot. Forma Lekerekített Kapszula diff --git a/app/src/main/res/values-hu/input_strings.xml b/app/src/main/res/values-hu/input_strings.xml index 628d43390d..1fb45dd72a 100644 --- a/app/src/main/res/values-hu/input_strings.xml +++ b/app/src/main/res/values-hu/input_strings.xml @@ -1,5 +1,6 @@ + Beviteli profilok Profilok Fizikai vezérlő Fő képernyő @@ -22,6 +23,7 @@ Steam menü megnyitása Steam gyorselérés megnyitása Vezérlőelem eltávolítása + Vezérlőelem hozzáadása Eszközspecifikus gombok Fizikai gomb hozzárendelése Engedje el a gombot, majd válassza a Szerkesztés, Újra vagy Mégse lehetőséget. A B vagy a Vissza elengedés után megszakítja. diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 466f522298..f2a0cf774d 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. @@ -295,10 +294,14 @@ Érintés Oldalsó gomb Képernyőn megjelenő vezérlők + Steam + QAM Az Automatikus megjeleníti a vezérlőket, ha nincs csatlakoztatott kontroller. + Steam érintés (béta) + A Steam érintésvezérlői a következő Steam-munkamenettől lépnek életbe Steam érintéskiosztás Exportálás Kép + Mozgassa, méretezze vagy rejtse el a játék érintésvezérlőit; a Steamben mentve Kontroller Hogyan látja a Steam a kontrollerét. A következő munkamenettől érvényes. Steam Deck kontroller @@ -425,6 +428,7 @@ Megkerüli a PulseAudiót a kisebb késleltetés érdekében. Mikrofon Hangos csevegéshez. + A mikrofonrögzítés be- vagy kikapcsolása ebben a munkamenetben. Nem sikerült módosítani a mikrofont. Próbálja újra. Hálózat Wi-Fi felderítés @@ -786,6 +790,7 @@ Billentyűzet Késleltetés Alacsony késleltetésű mód + Növeli a CPU- és akkumulátorhasználatot Alacsony késleltetésű kontroller A kontroller 250 Hz helyett 1000 Hz-en jelent. Kicsit több CPU. Alacsony késleltetésű érintés @@ -1339,8 +1344,12 @@ Átlátszatlanság %1$d%% Gombméret + Adaptív karok Játékvibráció Kar holtzónája + Steam gomb + QAM gomb + Billentyűzet gomb Joy-Conok VR-kontrollerként Amíg a SteamVR fut, minden Joy-Con egy kéz lesz. Irányítsa előre, és tartsa lenyomva a Home vagy a Capture gombot az újraközpontosításhoz. Animációk @@ -1469,6 +1478,8 @@ Érintőpad Második képernyős vezérlők bezárása Steam-menü megnyitása + Jobb érintőpad + Bal érintőpad Érintőpad Billentyűzet megjelenítése Billentyűzet elrejtése @@ -1507,8 +1518,11 @@ Android billentyűzet Elrejtés ✕ Méret a képernyőn + A képernyő hányadát foglalja el a billentyűzet, a fejlécet is beleszámítva. Átlátszatlanság + Csökkentsd, hogy lásd a billentyűzet mögötti játékot. Rejtett billentyűk + A ritkán használt billentyűk nem jelennek meg a billentyűzeten. Esc és a funkcióbillentyűk sora Ins / Del / Home / End / PgUp / PgDn Nyílbillentyűk @@ -1721,6 +1735,8 @@ %1$s telepítve – válassza ki a menüben Várja meg a futtatókörnyezet eltávolításának befejezését Játék + érintőpad + közvetlen A csere sikertelen: %1$s A profil mentése sikertelen: %1$s Az asztal szünetel @@ -1976,6 +1992,15 @@ Egy szinttel feljebb Válasszon mappát Válasszon fájlt + Steam kék + Égszínkék + Fehér + Lila + Zöld + Borostyán + Piros + Rózsaszín + Szürke A gomb B gomb X gomb @@ -2435,10 +2460,13 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Munkamenet kijelzője + Másolásmentes megjelenítés Felbontás 16:9 játék illesztése Hogyan illeszkednek a 16:9 játékok ehhez a kijelzőhöz. A következő munkamenettől. 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 @@ -3113,6 +3141,7 @@ Kísérleti fejkövetés a Pro 2-höz. A fényerő és a hangerő beállítása, valamint a megjelenítési mód váltása még nem támogatott. Cardboard VR Cardboard mód + Bal és jobb szem képe telefonos VR-szemüveghez. Kép Virtuális képernyő Egymás melletti 3D @@ -3135,6 +3164,7 @@ Ebben a munkamenetben nem érhető el. A SteamVR nem válaszolt; nézd meg a munkamenet naplóját. Összetevők letöltése + A letöltések közösek az Összetevők oldallal. Fent válassz egy letöltött verziót, hogy a következő játékindítástól azt használd. Válassz letöltendő verziót Fejlesztő Kiadó diff --git a/app/src/main/res/values-in/input_library.xml b/app/src/main/res/values-in/input_library.xml index 057e760644..28025b1073 100644 --- a/app/src/main/res/values-in/input_library.xml +++ b/app/src/main/res/values-in/input_library.xml @@ -75,9 +75,14 @@ Salinan independen Mulai stik di posisi sentuh Sembunyikan stik saat tidak digunakan + Alat + Otomatis (%1$s) + Khusus (%1$s) Simpan sebagai profil baru Kontrol profil + Profil Gestur touchpad mouse + Jika ditetapkan ke penunjuk mouse: ketuk untuk klik, tahan untuk menyeret, dan gulir dengan dua jari. %1$s memiliki penggantian menu cepat. Pilih Otomatis di sana untuk memakai profil bawaan dan ketiga bagian tersimpannya. Input DroidDeck Ditahan saat stik digerakkan ke segala arah: tekan di atas 55%, lepas di bawah 35%. Gunakan Tombol arah untuk menetapkan tiap arah secara terpisah. Perintah DroidDeck berjalan sekali per defleksi. Klik stik diatur terpisah. @@ -99,11 +104,17 @@ Di mode Steam. Menahan Kembali juga membuka akses cepat. Pulihkan ke bawaan Pengontrol virtual + Jenis pengontrol yang dilihat Steam atau game. Layar sentuh + Cara sentuhan di layar game ditangani. Tombol profil tetap memakai tindakan yang ditetapkan. Kursor sentuh + Tampilkan penunjuk untuk sentuhan langsung di layar game. Sentuh dan tahan + Tindakan mouse saat menahan jari di layar game. Ketukan tombol Kembali + Tindakan pertama: satu ketuk. Tindakan kedua: dua ketuk. Tombol sakelar + Ketuk untuk menahan, ketuk lagi untuk melepas. Membuka menu atau mengganti profil melepas tombol. Bentuk Membulat Pil diff --git a/app/src/main/res/values-in/input_strings.xml b/app/src/main/res/values-in/input_strings.xml index 427023a43c..c115e8a9e2 100644 --- a/app/src/main/res/values-in/input_strings.xml +++ b/app/src/main/res/values-in/input_strings.xml @@ -1,5 +1,6 @@ + Profil input Profil Pengontrol fisik Layar utama @@ -22,6 +23,7 @@ Buka menu Steam Buka akses cepat Steam Hapus kontrol + Tambah kontrol Tombol khusus perangkat Tetapkan tombol fisik Lepaskan tombol, lalu pilih Edit, Coba lagi, atau Batal. B atau Kembali membatalkan setelah dilepas. diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index ecaf67f00a..67516678dc 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. @@ -295,10 +294,14 @@ Sentuhan Tombol samping Kontrol di layar + Steam + QAM Otomatis menampilkan kontrol saat tidak ada pengontrol yang terhubung. + Sentuhan Steam (beta) + Kontrol sentuh Steam dimulai pada sesi Steam berikutnya Tata letak sentuh Steam Ekspor Gambar + Pindahkan, ubah ukuran, atau sembunyikan kontrol sentuh gim ini; disimpan ke Steam Pengontrol Cara Steam mendeteksi pengontrol Anda. Berlaku pada sesi berikutnya. Pengontrol Steam Deck @@ -424,6 +427,7 @@ Melewati PulseAudio untuk latensi yang lebih rendah. Mikrofon Untuk obrolan suara. + Aktifkan atau nonaktifkan perekaman mikrofon untuk sesi ini. Tidak dapat mengubah mikrofon. Coba lagi. Jaringan Pencarian Wi-Fi @@ -784,6 +788,7 @@ Keyboard Latensi Mode latensi rendah + Meningkatkan penggunaan CPU dan baterai Pengontrol latensi rendah Pengontrol melapor pada 1000 Hz, bukan 250 Hz. Sedikit lebih banyak CPU. Sentuh latensi rendah @@ -1333,8 +1338,12 @@ Opasitas %1$d%% Ukuran tombol + Stik adaptif Getaran gim Zona mati stik + Tombol Steam + Tombol QAM + Tombol keyboard Joy-Con sebagai pengontrol VR Saat SteamVR berjalan, setiap Joy-Con menjadi tangan. Arahkan ke depan lalu tahan Home atau Capture untuk memusatkannya kembali. Animasi @@ -1462,6 +1471,8 @@ Trackpad Tutup kontrol layar kedua Buka menu Steam + Trackpad kanan + Trackpad kiri Trackpad Tampilkan keyboard Sembunyikan keyboard @@ -1500,8 +1511,11 @@ Keyboard Android Sembunyikan ✕ Ukuran di layar + Porsi layar yang dipakai keyboard, termasuk header. Opasitas + Turunkan agar game di belakang keyboard terlihat. Tombol tersembunyi + Tombol yang jarang dipakai tidak ditampilkan di keyboard. Baris Esc dan fungsi Ins / Del / Home / End / PgUp / PgDn Tombol panah @@ -1706,6 +1720,8 @@ Terinstal %1$s - pilih di menu Tunggu penghapusan runtime selesai Game + touchpad + langsung Pergantian gagal: %1$s Penyimpanan profil gagal: %1$s Desktop dijeda @@ -1952,6 +1968,15 @@ Naik satu tingkat Pilih folder Pilih file + Biru Steam + Langit + Putih + Ungu + Hijau + Ambar + Merah + Merah muda + Abu-abu Tombol A Tombol B Tombol X @@ -2410,10 +2435,13 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Tampilan sesi + Presentasi tanpa salin Resolusi Penyesuaian gim 16:9 Cara gim 16:9 disesuaikan dengan tampilan ini. Berlaku pada sesi berikutnya. 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 @@ -3084,6 +3112,7 @@ Pelacakan kepala Pro 2 eksperimental. Pengaturan kecerahan, volume, dan pergantian mode tampilan belum didukung. Cardboard VR Mode Cardboard + Tampilan mata kiri dan kanan untuk kacamata VR ponsel. Gambar Layar virtual 3D berdampingan @@ -3106,6 +3135,7 @@ Tidak tersedia di sesi ini. SteamVR tidak merespons; periksa log sesi. Unduh komponen + Unduhan dipakai bersama halaman Komponen. Pilih versi yang sudah diunduh di atas untuk memakainya pada peluncuran gim berikutnya. Pilih versi untuk diunduh Pengembang Penerbit diff --git a/app/src/main/res/values-it/input_library.xml b/app/src/main/res/values-it/input_library.xml index cbe7403b1e..b825c1fb96 100644 --- a/app/src/main/res/values-it/input_library.xml +++ b/app/src/main/res/values-it/input_library.xml @@ -75,9 +75,14 @@ Copia indipendente Avvia lo stick nel punto toccato Nascondi lo stick quando non è in uso + Strumenti + Auto (%1$s) + Personalizzato (%1$s) Salva come nuovo profilo Controlli profilo + Profilo Gesti del touchpad del mouse + Se assegnato al puntatore del mouse: tocca per fare clic, tieni premuto per trascinare e scorri con due dita. %1$s ha una sostituzione del menu rapido. Seleziona Auto per usare il suo profilo predefinito e tutte e tre le parti salvate. Input DroidDeck Mantenuto mentre lo stick è mosso in qualsiasi direzione: pressione sopra il 55%, rilascio sotto il 35%. Usa Tasti direzionali per assegnare ogni direzione separatamente. I comandi DroidDeck vengono eseguiti una volta per deflessione. Il clic dello stick si configura a parte. @@ -99,11 +104,17 @@ In modalità Steam. Tenere premuto Indietro apre anche l\'accesso rapido. Ripristina i valori predefiniti Controller virtuale + Il tipo di controller visto da Steam o dal gioco. Touchscreen + Come vengono gestiti i tocchi sullo schermo di gioco. I pulsanti del profilo mantengono le azioni assegnate. Cursore tattile + Mostra un puntatore per i tocchi diretti sullo schermo di gioco. Tocca e tieni premuto + Azione del mouse quando tieni un dito sullo schermo di gioco. Tocchi del pulsante Indietro + Prima azione: tocco singolo. Seconda azione: doppio tocco. Pulsante a interruttore + Tocca per tenere premuto, tocca di nuovo per rilasciare. Aprire un menu o cambiare profilo rilascia il pulsante. Forma Arrotondata Pillola diff --git a/app/src/main/res/values-it/input_strings.xml b/app/src/main/res/values-it/input_strings.xml index 4805b049e8..a5e401d1c8 100644 --- a/app/src/main/res/values-it/input_strings.xml +++ b/app/src/main/res/values-it/input_strings.xml @@ -1,5 +1,6 @@ + Profili di input Profili Controller fisico Schermo principale @@ -22,6 +23,7 @@ Apri il menu Steam Apri l\'accesso rapido di Steam Rimuovi controllo + Aggiungi controllo Tasti specifici del dispositivo Assegna un tasto fisico Rilascia il tasto, poi scegli Modifica, Riprova o Annulla. B o Indietro annulla dopo il rilascio. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 3eb592f9d4..ce0632f450 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. @@ -295,10 +294,14 @@ Tocco Tasto laterale Controlli su schermo + Steam + QAM Auto mostra i controlli quando non è collegato nessun controller. + Touch di Steam (beta) + I controlli touch di Steam partono dalla prossima sessione Steam Layout touch di Steam Esporta Immagine + Sposta, ridimensiona o nascondi i controlli touch di questo gioco; vengono salvati su Steam Controller Come Steam vede il tuo controller. Si applica dalla prossima sessione. Controller di Steam Deck @@ -426,6 +429,7 @@ Bypassa PulseAudio per ridurre la latenza. Microfono Per la chat vocale. + Attiva o disattiva l\'acquisizione del microfono per questa sessione. Impossibile cambiare il microfono. Riprova. Rete Rilevamento Wi-Fi @@ -788,6 +792,7 @@ Tastiera Latenza Modalità bassa latenza + Aumenta l\'uso di CPU e batteria Controller a bassa latenza Il controller invia dati a 1000 Hz invece di 250 Hz. Un po\' più di CPU. Touch a bassa latenza @@ -1337,8 +1342,12 @@ Opacità %1$d%% Dimensione dei tasti + Levette adattive Vibrazione di gioco Zona morta dello stick + Tasto Steam + Tasto QAM + Tasto tastiera Joy-Con come controller VR Mentre SteamVR è in esecuzione, ogni Joy-Con diventa una mano. Puntalo in avanti e tieni premuto Home o Capture per ricentrarlo. Animazioni @@ -1468,6 +1477,8 @@ Trackpad Chiudi i controlli sul secondo schermo Apri il menu Steam + Trackpad destro + Trackpad sinistro Trackpad Mostra tastiera Nascondi tastiera @@ -1506,8 +1517,11 @@ Tastiera Android Nascondi ✕ Dimensioni sullo schermo + Porzione dello schermo occupata dalla tastiera, intestazione inclusa. Opacità + Riducila per vedere il gioco dietro la tastiera. Tasti nascosti + I tasti che usi raramente non compaiono sulla tastiera. Esc e riga dei tasti funzione Ins / Canc / Home / Fine / PgSu / PgGiù Tasti freccia @@ -1728,6 +1742,8 @@ Installato %1$s - sceglilo nel menu Attendi la fine della rimozione del runtime Gioco + touchpad + diretto Sostituzione non riuscita: %1$s Salvataggio del profilo non riuscito: %1$s Il desktop è in pausa @@ -1992,6 +2008,15 @@ Livello superiore Scegli una cartella Scegli un file + Blu Steam + Cielo + Bianco + Viola + Verde + Ambra + Rosso + Rosa + Grigio Pulsante A Pulsante B Pulsante X @@ -2452,10 +2477,13 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Schermo della sessione + Presentazione senza copia Risoluzione Adattamento giochi 16:9 Come i giochi 16:9 si adattano a questo schermo. Dalla prossima sessione. 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 @@ -3131,6 +3159,7 @@ Tracciamento sperimentale della testa per Pro 2. La regolazione di luminosità e volume e il cambio della modalità di visualizzazione non sono ancora supportati. Cardboard VR Modalità Cardboard + Immagini per l\'occhio sinistro e destro, per un visore VR per telefono. Immagine Schermo virtuale 3D affiancato @@ -3153,6 +3182,7 @@ Non disponibile in questa sessione. SteamVR non ha risposto; controlla il log della sessione. Scarica componenti + I download sono condivisi con la pagina Componenti. Scegli sopra una versione scaricata per usarla al prossimo avvio del gioco. Scegli una versione da scaricare Sviluppatore Editore diff --git a/app/src/main/res/values-ja/input_library.xml b/app/src/main/res/values-ja/input_library.xml index 5e58a3ebc1..f4294982be 100644 --- a/app/src/main/res/values-ja/input_library.xml +++ b/app/src/main/res/values-ja/input_library.xml @@ -75,9 +75,14 @@ 独立したコピー タッチ位置からスティックを開始 未使用時はスティックを隠す + ツール + 自動 (%1$s) + カスタム (%1$s) 新しいプロファイルとして保存 プロファイルコントロール + プロファイル マウスタッチパッドのジェスチャー + マウスポインターに割り当てた場合: タップでクリック、長押しでドラッグ、2 本指でスクロールします。 %1$s にはクイックメニューの上書きがあります。[自動] を選ぶと既定のプロファイルと保存済みの 3 つのパーツを使用します。 DroidDeck 入力 スティックをどの方向に動かしている間も保持されます: 55% を超えると押下、35% を下回ると解放。方向キーで各方向を個別に割り当てます。DroidDeck コマンドは 1 回の傾きにつき 1 回実行されます。スティックのクリックは別に設定します。 @@ -99,11 +104,17 @@ Steam モード時。戻るを長押しするとクイックアクセスも開きます。 既定に戻す 仮想コントローラー + Steam またはゲームが認識するコントローラーの種類。 タッチスクリーン + ゲーム画面のタッチの扱い方。プロファイルのボタンは割り当て済みのアクションを保ちます。 タッチカーソル + ゲーム画面への直接タッチにポインターを表示します。 タッチして長押し + ゲーム画面で指を押し続けたときのマウス動作。 戻るボタンのタップ + 1 つ目のアクション: シングルタップ。2 つ目のアクション: ダブルタップ。 トグルボタン + タップで保持、もう一度タップで解放。メニューを開くかプロファイルを切り替えるとボタンは解放されます。 形 角丸 ピル diff --git a/app/src/main/res/values-ja/input_strings.xml b/app/src/main/res/values-ja/input_strings.xml index e11c58003f..ac60ca8e51 100644 --- a/app/src/main/res/values-ja/input_strings.xml +++ b/app/src/main/res/values-ja/input_strings.xml @@ -1,5 +1,6 @@ + 入力プロファイル プロファイル 物理コントローラー メイン画面 @@ -22,6 +23,7 @@ Steam メニューを開く Steam クイックアクセスを開く コントロールを削除 + コントロールを追加 デバイス固有のボタン 物理ボタンを割り当て ボタンを離してから、編集・再試行・キャンセルのいずれかを選択します。B または戻るは離した後にキャンセルします。 diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 59a0a75596..2b37a68447 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とデスクトップで共有されます。「コンポーネント」ページで設定してください。 @@ -295,10 +294,14 @@ タッチ サイドボタン 画面コントローラー + Steam + QAM 自動では、コントローラーが接続されていないときに画面コントローラーを表示します。 + Steamタッチ(ベータ版) + Steamのタッチコントロールは次回のSteamセッションから有効になります Steamタッチのレイアウト エクスポート 画像 + このゲームのタッチコントロールを移動、サイズ変更、非表示にします。Steamに保存されます コントローラー Steamがコントローラーを認識する方法。次回のセッションで有効になります。 Steam Deckコントローラー @@ -424,6 +427,7 @@ PulseAudioをバイパスして遅延を減らします。 マイク ボイスチャットに使用します。 + このセッションのマイク入力をオンまたはオフにします。 マイクを変更できませんでした。もう一度お試しください。 ネットワーク Wi-Fi検出 @@ -784,6 +788,7 @@ キーボード 遅延 低遅延モード + CPUとバッテリーの使用量が増えます 低遅延コントローラー コントローラーが 250 Hz ではなく 1000 Hz で報告されます。CPU 使用率がわずかに上がります。 低遅延タッチ @@ -1333,8 +1338,12 @@ 不透明度 %1$d%% ボタンのサイズ + アダプティブスティック ゲームの振動 スティックのデッドゾーン + Steamボタン + QAMボタン + キーボードボタン Joy-ConをVRコントローラーとして使う SteamVRの実行中は各Joy-Conが手になります。前に向けてHOMEボタンかキャプチャーボタンを長押しすると、向きを合わせ直します。 アニメーション @@ -1462,6 +1471,8 @@ トラックパッド セカンドスクリーンコントロールを閉じる Steamメニューを開く + 右トラックパッド + 左トラックパッド トラックパッド キーボードを表示 キーボードを隠す @@ -1500,8 +1511,11 @@ Androidキーボード 隠す ✕ 画面上のサイズ + ヘッダーを含め、キーボードが画面に占める割合。 不透明度 + 下げると、キーボードの背後にあるゲームが見えます。 非表示のキー + ほとんど使わないキーはキーボードに表示されません。 Esc とファンクションキー列 Ins / Del / Home / End / PgUp / PgDn 矢印キー @@ -1706,6 +1720,8 @@ %1$sをインストールしました - メニューで選択してください 実行環境の削除が完了するまでお待ちください ゲーム + トラックパッド + ダイレクト 置き換えに失敗しました:%1$s プロファイルの保存に失敗しました:%1$s デスクトップは一時停止中です @@ -1952,6 +1968,15 @@ 1つ上の階層へ フォルダを選択 ファイルを選択 + Steamブルー + スカイ + ホワイト + バイオレット + グリーン + アンバー + レッド + ピンク + グレー Aボタン Bボタン Xボタン @@ -2410,10 +2435,13 @@ ANDROID + LINUX %1$s。%2$s\n\n%3$s セッションの表示 + ゼロコピー表示 解像度 16:9ゲームの表示 16:9のゲームをこのディスプレイにどう合わせるか。次回のセッションから。 「画面に合わせる」か、16:9より縦長のカスタムサイズを選んでください。 + ノッチを避ける + 映像をカメラの切り欠きから離します。セッションに戻ると反映されます。 縦横比を保持 画面いっぱいに引き伸ばす 画像のスケーリング @@ -3092,6 +3120,7 @@ %1$d分 Cardboard VR Cardboardモード + スマホ用VRビューアー向けの左右の目の映像です。 映像 仮想スクリーン サイドバイサイド3D @@ -3114,6 +3143,7 @@ このセッションでは利用できません。 SteamVRが応答しませんでした。セッションログを確認してください。 コンポーネントをダウンロード + ダウンロードは「コンポーネント」ページと共有されます。上でダウンロード済みのバージョンを選ぶと、次回のゲーム起動時に使用されます。 ダウンロードするバージョンを選択 画面の位置 上 diff --git a/app/src/main/res/values-ko/input_library.xml b/app/src/main/res/values-ko/input_library.xml index 6318f75ba0..c5030b8290 100644 --- a/app/src/main/res/values-ko/input_library.xml +++ b/app/src/main/res/values-ko/input_library.xml @@ -75,9 +75,14 @@ 독립 사본 터치한 위치에서 스틱 시작 사용하지 않을 때 스틱 숨기기 + 도구 + 자동 (%1$s) + 사용자 지정 (%1$s) 새 프로필로 저장 프로필 컨트롤 + 프로필 마우스 터치패드 제스처 + 마우스 포인터에 할당된 경우: 탭하여 클릭, 길게 눌러 드래그, 두 손가락으로 스크롤합니다. %1$s에는 빠른 메뉴 재정의가 있습니다. 자동을 선택하면 기본 프로필과 저장된 세 부분을 모두 사용합니다. DroidDeck 입력 스틱을 어느 방향으로든 움직이는 동안 유지됩니다: 55% 초과 시 누름, 35% 미만 시 해제. 방향 키로 각 방향을 따로 지정합니다. DroidDeck 명령은 기울기마다 한 번 실행됩니다. 스틱 클릭은 따로 설정합니다. @@ -99,11 +104,17 @@ Steam 모드에서. 뒤로를 길게 누르면 빠른 액세스도 열립니다. 기본값으로 복원 가상 컨트롤러 + Steam 또는 게임이 인식하는 컨트롤러 유형입니다. 터치스크린 + 게임 화면의 터치 처리 방식입니다. 프로필 버튼은 지정된 동작을 유지합니다. 터치 커서 + 게임 화면의 직접 터치에 포인터를 표시합니다. 터치 후 유지 + 게임 화면에서 손가락을 누르고 있을 때의 마우스 동작입니다. 뒤로 버튼 탭 + 첫 번째 동작: 한 번 탭. 두 번째 동작: 두 번 탭. 토글 버튼 + 탭하여 유지, 다시 탭하여 해제. 메뉴를 열거나 프로필을 전환하면 버튼이 해제됩니다. 모양 둥근 모서리 알약 diff --git a/app/src/main/res/values-ko/input_strings.xml b/app/src/main/res/values-ko/input_strings.xml index 21a1438442..b38fa335b5 100644 --- a/app/src/main/res/values-ko/input_strings.xml +++ b/app/src/main/res/values-ko/input_strings.xml @@ -1,5 +1,6 @@ + 입력 프로필 프로필 물리 컨트롤러 기본 화면 @@ -22,6 +23,7 @@ Steam 메뉴 열기 Steam 빠른 액세스 열기 컨트롤 제거 + 컨트롤 추가 기기별 버튼 물리 버튼 지정 버튼을 놓은 다음 편집, 다시 시도 또는 취소를 선택하세요. B 또는 뒤로는 놓은 후 취소합니다. diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 192985e199..ca9a31ec99 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과 데스크톱에서 공유됩니다. \"구성 요소\" 페이지에서 설정하세요. @@ -295,10 +294,14 @@ 터치 측면 버튼 화면 컨트롤 + Steam + QAM 자동 모드에서는 컨트롤러가 연결되지 않은 경우 화면 컨트롤을 표시합니다. + Steam 터치(베타) + Steam 터치 컨트롤은 다음 Steam 세션부터 적용됩니다 Steam 터치 레이아웃 내보내기 이미지 + 이 게임의 터치 컨트롤을 옮기거나 크기를 바꾸거나 숨깁니다. Steam에 저장됩니다 컨트롤러 Steam이 컨트롤러를 인식하는 방식입니다. 다음 세션에 적용됩니다. Steam Deck 컨트롤러 @@ -424,6 +427,7 @@ PulseAudio를 우회하여 지연 시간을 줄입니다. 마이크 음성 채팅에 사용됩니다. + 이 세션의 마이크 캡처를 켜거나 끕니다. 마이크를 변경할 수 없습니다. 다시 시도하세요. 네트워크 Wi-Fi 검색 @@ -784,6 +788,7 @@ 키보드 지연 저지연 모드 + CPU 및 배터리 사용량이 늘어납니다 저지연 컨트롤러 컨트롤러가 250 Hz 대신 1000 Hz로 보고됩니다. CPU 사용량이 약간 늘어납니다. 저지연 터치 @@ -1333,8 +1338,12 @@ 불투명도 %1$d%% 버튼 크기 + 적응형 스틱 게임 진동 스틱 데드존 + Steam 버튼 + QAM 버튼 + 키보드 버튼 Joy-Con을 VR 컨트롤러로 사용 SteamVR이 실행되는 동안 각 Joy-Con이 손이 됩니다. 앞을 향하게 한 채 HOME 또는 캡처 버튼을 길게 누르면 다시 가운데로 맞춥니다. 애니메이션 @@ -1462,6 +1471,8 @@ 터치패드 보조 화면 컨트롤 닫기 Steam 메뉴 열기 + 오른쪽 터치패드 + 왼쪽 터치패드 터치패드 키보드 표시 키보드 숨기기 @@ -1500,8 +1511,11 @@ Android 키보드 숨기기 ✕ 화면상 크기 + 헤더를 포함해 키보드가 화면에서 차지하는 비율입니다. 불투명도 + 낮추면 키보드 뒤의 게임이 보입니다. 숨긴 키 + 자주 쓰지 않는 키는 키보드에 표시되지 않습니다. Esc 및 기능 키 행 Ins / Del / Home / End / PgUp / PgDn 화살표 키 @@ -1706,6 +1720,8 @@ %1$s 설치됨 - 메뉴에서 선택하세요 런타임 제거가 끝날 때까지 기다려 주세요 게임 + 터치패드 + 직접 터치 교체 실패: %1$s 프로필 저장 실패: %1$s 데스크톱이 일시 중지됨 @@ -1952,6 +1968,15 @@ 상위 폴더로 폴더 선택 파일 선택 + Steam 블루 + 하늘색 + 흰색 + 보라색 + 초록색 + 호박색 + 빨간색 + 분홍색 + 회색 A 버튼 B 버튼 X 버튼 @@ -2410,10 +2435,13 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s 세션 디스플레이 + 제로카피 표시 해상도 16:9 게임 맞춤 16:9 게임을 이 디스플레이에 맞추는 방식입니다. 다음 세션부터 적용됩니다. 화면에 맞춤 또는 16:9보다 좁은 사용자 정의 크기를 선택하세요. + 노치 피하기 + 화면을 카메라 컷아웃 밖에 표시합니다. 세션으로 돌아오면 적용됩니다. 비율 유지 화면에 맞게 늘이기 이미지 스케일링 @@ -3092,6 +3120,7 @@ %1$d분 Cardboard VR Cardboard 모드 + 휴대폰 VR 뷰어용 왼쪽 및 오른쪽 눈 화면입니다. 화면 가상 스크린 사이드 바이 사이드 3D @@ -3114,6 +3143,7 @@ 이 세션에서는 사용할 수 없습니다. SteamVR이 응답하지 않았습니다. 세션 로그를 확인하세요. 구성 요소 다운로드 + 다운로드는 구성 요소 페이지와 공유됩니다. 위에서 다운로드한 버전을 선택하면 다음 게임 실행 시 사용됩니다. 다운로드할 버전 선택 화면 위치 위 diff --git a/app/src/main/res/values-ms/input_library.xml b/app/src/main/res/values-ms/input_library.xml index 601220737d..e14f8a4252 100644 --- a/app/src/main/res/values-ms/input_library.xml +++ b/app/src/main/res/values-ms/input_library.xml @@ -75,9 +75,14 @@ Salinan bebas Mulakan kayu pada kedudukan sentuhan Sembunyikan kayu apabila tidak digunakan + Alat + Auto (%1$s) + Tersuai (%1$s) Simpan sebagai profil baharu Kawalan profil + Profil Gerak isyarat pad sentuh tetikus + Apabila ditetapkan pada penuding tetikus: ketik untuk klik, tahan untuk seret, dan tatal dengan dua jari. %1$s mempunyai penggantian menu pantas. Pilih Auto di sana untuk menggunakan profil lalainya dan ketiga-tiga bahagian tersimpan. Input DroidDeck Ditetapkan semasa kayu digerakkan ke mana-mana arah: tekan melebihi 55%, lepas di bawah 35%. Gunakan Kekunci arah untuk menetapkan setiap arah secara berasingan. Perintah DroidDeck berjalan sekali setiap pesongan. Klik kayu ditetapkan secara berasingan. @@ -99,11 +104,17 @@ Dalam mod Steam. Menahan Kembali juga membuka akses pantas. Pulihkan kepada lalai Pengawal maya + Jenis pengawal yang dilihat oleh Steam atau permainan. Skrin sentuh + Bagaimana sentuhan pada skrin permainan dikendalikan. Butang profil kekal dengan tindakan yang ditetapkan. Kursor sentuh + Tunjukkan penuding untuk sentuhan langsung pada skrin permainan. Sentuh dan tahan + Tindakan tetikus apabila menahan jari pada skrin permainan. Ketikan butang Kembali + Tindakan pertama: satu ketikan. Tindakan kedua: dua ketikan. Butang togol + Ketik untuk menahan, ketik lagi untuk melepaskan. Membuka menu atau menukar profil melepaskan butang. Bentuk Bulat Pil diff --git a/app/src/main/res/values-ms/input_strings.xml b/app/src/main/res/values-ms/input_strings.xml index df6ae4c73b..e96a230e16 100644 --- a/app/src/main/res/values-ms/input_strings.xml +++ b/app/src/main/res/values-ms/input_strings.xml @@ -1,5 +1,6 @@ + Profil input Profil Pengawal fizikal Skrin utama @@ -22,6 +23,7 @@ Buka menu Steam Buka akses pantas Steam Alih keluar kawalan + Tambah kawalan Butang khusus peranti Tetapkan butang fizikal Lepaskan butang, kemudian pilih Edit, Cuba lagi atau Batal. B atau Kembali membatalkan selepas dilepaskan. diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index b13c7c7bb4..769c6f2c7a 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. @@ -295,10 +294,14 @@ Sentuhan Butang sisi Kawalan pada skrin + Steam + QAM Auto memaparkan kawalan apabila tiada pengawal disambungkan. + Sentuhan Steam (beta) + Kawalan sentuh Steam bermula pada sesi Steam seterusnya Susun atur sentuh Steam Eksport Imej + Gerakkan, ubah saiz atau sembunyikan kawalan sentuh permainan ini; disimpan ke Steam Pengawal Cara Steam mengesan pengawal anda. Berkuat kuasa pada sesi seterusnya. Pengawal Steam Deck @@ -424,6 +427,7 @@ Memintas PulseAudio untuk kependaman yang lebih rendah. Mikrofon Untuk sembang suara. + Hidupkan atau matikan tangkapan mikrofon untuk sesi ini. Tidak dapat menukar mikrofon. Sila cuba lagi. Rangkaian Penemuan Wi-Fi @@ -784,6 +788,7 @@ Papan kekunci Kependaman Mod kependaman rendah + Meningkatkan penggunaan CPU dan bateri Pengawal kependaman rendah Pengawal melapor pada 1000 Hz dan bukan 250 Hz. Sedikit lebih banyak CPU. Sentuh kependaman rendah @@ -1333,8 +1338,12 @@ Kelegapan %1$d%% Saiz butang + Stik adaptif Getaran permainan Zon mati kayu bedik + Butang Steam + Butang QAM + Butang papan kekunci Joy-Con sebagai pengawal VR Semasa SteamVR berjalan, setiap Joy-Con menjadi tangan. Halakan ke hadapan dan tahan Home atau Capture untuk memusatkannya semula. Animasi @@ -1462,6 +1471,8 @@ Trackpad Tutup kawalan skrin kedua Buka menu Steam + Trackpad kanan + Trackpad kiri Trackpad Papar papan kekunci Sembunyikan papan kekunci @@ -1500,8 +1511,11 @@ Papan kekunci Android Sembunyi ✕ Saiz pada skrin + Bahagian skrin yang digunakan papan kekunci, termasuk pengepala. Kelegapan + Turunkan untuk melihat permainan di belakang papan kekunci. Kekunci tersembunyi + Kekunci yang jarang digunakan tidak dipaparkan pada papan kekunci. Esc dan baris kekunci fungsi Ins / Del / Home / End / PgUp / PgDn Kekunci anak panah @@ -1706,6 +1720,8 @@ %1$s dipasang - pilih dalam menu Tunggu pengalihan keluar masa jalan selesai Permainan + touchpad + langsung Penukaran gagal: %1$s Penyimpanan profil gagal: %1$s Desktop dijeda @@ -1952,6 +1968,15 @@ Naik satu tahap Pilih folder Pilih fail + Biru Steam + Langit + Putih + Ungu + Hijau + Ambar + Merah + Merah jambu + Kelabu Butang A Butang B Butang X @@ -2410,10 +2435,13 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Paparan sesi + Paparan tanpa salinan Resolusi Suaian permainan 16:9 Cara permainan 16:9 disuaikan ke paparan ini. Sesi seterusnya. 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 @@ -3084,6 +3112,7 @@ Penjejakan kepala Pro 2 secara eksperimen. Pelarasan kecerahan, kelantangan dan pertukaran mod paparan belum disokong. Cardboard VR Mod Cardboard + Paparan mata kiri dan kanan untuk kaca mata VR telefon. Gambar Skrin maya 3D sebelah-menyebelah @@ -3106,6 +3135,7 @@ Tidak tersedia dalam sesi ini. SteamVR tidak memberi respons; semak log sesi. Muat turun komponen + Muat turun dikongsi dengan halaman Komponen. Pilih versi yang telah dimuat turun di atas untuk menggunakannya pada pelancaran permainan seterusnya. Pilih versi untuk dimuat turun Pembangun Penerbit diff --git a/app/src/main/res/values-nb/input_library.xml b/app/src/main/res/values-nb/input_library.xml index a9f1d865e3..340337947a 100644 --- a/app/src/main/res/values-nb/input_library.xml +++ b/app/src/main/res/values-nb/input_library.xml @@ -75,9 +75,14 @@ Uavhengig kopi Start stikka ved berøringspunktet Skjul stikka når den ikke brukes + Verktøy + Auto (%1$s) + Egendefinert (%1$s) Lagre som ny profil Profilkontroller + Profil Musestyreflatebevegelser + Når tilordnet musepekeren: trykk for å klikke, hold for å dra, og rull med to fingre. %1$s har en overstyring av hurtigmenyen. Velg Auto der for å bruke standardprofilen og alle tre lagrede delene. DroidDeck-inndata Holdes mens stikka flyttes i en hvilken som helst retning: trykk over 55 %, slipp under 35 %. Bruk Retningstaster for å tildele hver retning separat. DroidDeck-kommandoer kjøres én gang per utslag. Stikkklikket konfigureres separat. @@ -99,11 +104,17 @@ I Steam-modus. Å holde Tilbake åpner også hurtigtilgang. Tilbakestill til standard Virtuell kontroller + Kontrollertypen som Steam eller spillet ser. Berøringsskjerm + Hvordan berøringer på spillskjermen håndteres. Profilknappene beholder sine tilordnede handlinger. Berøringsmarkør + Vis en peker for direkte berøringer på spillskjermen. Berør og hold + Musehandling når du holder en finger på spillskjermen. Trykk på Tilbake-knappen + Første handling: enkelt trykk. Andre handling: dobbeltrykk. Veksleknapp + Trykk for å holde, trykk igjen for å slippe. Å åpne en meny eller bytte profil slipper knappen. Form Avrundet Pille diff --git a/app/src/main/res/values-nb/input_strings.xml b/app/src/main/res/values-nb/input_strings.xml index 01ec687375..92e1af4eff 100644 --- a/app/src/main/res/values-nb/input_strings.xml +++ b/app/src/main/res/values-nb/input_strings.xml @@ -1,5 +1,6 @@ + Inndataprofiler Profiler Fysisk kontroller Hovedskjerm @@ -22,6 +23,7 @@ Åpne Steam-menyen Åpne Steams hurtigtilgang Fjern kontroll + Legg til kontroll Enhetsspesifikke knapper Tildel en fysisk knapp Slipp knappen, og velg Rediger, Prøv igjen eller Avbryt. B eller Tilbake avbryter etter slipp. diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index 8715fddf80..2533182c77 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. @@ -295,10 +294,14 @@ Berøring Sideknapp Skjermkontroller + Steam + QAM Auto viser kontrollene når ingen kontroller er tilkoblet. + Steam-berøring (beta) + Steams berøringskontroller starter med neste Steam-sesjon Steam-berøringslayout Eksporter Bilde + Flytt, endre størrelse på eller skjul dette spillets berøringskontroller; lagres til Steam Kontroller Hvordan Steam ser kontrolleren din. Gjelder fra neste sesjon. Steam Deck-kontroller @@ -425,6 +428,7 @@ Går forbi PulseAudio for lavere ventetid. Mikrofon For talechat. + Slå mikrofonopptak av eller på for denne sesjonen. Kunne ikke endre mikrofonen. Prøv igjen. Nettverk Wi-Fi-oppdagelse @@ -786,6 +790,7 @@ Tastatur Forsinkelse Modus for lav forsinkelse + Øker CPU- og batteribruk Kontroller med lav forsinkelse Kontrolleren rapporterer ved 1000 Hz i stedet for 250 Hz. Litt mer CPU. Berøring med lav forsinkelse @@ -1339,8 +1344,12 @@ Opasitet %1$d%% Knappestørrelse + Adaptive stikker Spillvibrasjon Dødsone for styrespak + Steam-knapp + QAM-knapp + Tastatur-knapp Joy-Con som VR-kontrollere Mens SteamVR kjører, blir hver Joy-Con en hånd. Pek den fremover og hold inne Home eller Capture for å sentrere den på nytt. Animasjoner @@ -1469,6 +1478,8 @@ Styreflate Lukk kontroller for andre skjerm Åpne Steam-menyen + Høyre styreflate + Venstre styreflate Styreflate Vis tastatur Skjul tastatur @@ -1507,8 +1518,11 @@ Android-tastatur Skjul ✕ Størrelse på skjermen + Andelen av skjermen tastaturet tar, inkludert toppfeltet. Ugjennomsiktighet + Senk den for å se spillet bak tastaturet. Skjulte taster + Taster du sjelden bruker vises ikke på tastaturet. Esc og funksjonsrad Ins / Del / Home / End / PgUp / PgDn Piltaster @@ -1721,6 +1735,8 @@ Installert %1$s – velg den i menyen Vent til fjerning av kjøretiden er ferdig Spill + styreflate + direkte Bytting mislyktes: %1$s Lagring av profil mislyktes: %1$s Skrivebordet er pauset @@ -1976,6 +1992,15 @@ Opp ett nivå Velg en mappe Velg en fil + Steam-blå + Himmel + Hvit + Fiolett + Grønn + Amber + Rød + Rosa + Grå A-knapp B-knapp X-knapp @@ -2435,10 +2460,13 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Sesjonsskjerm + Presentasjon uten kopiering Oppløsning 16:9-spilltilpasning Hvordan 16:9-spill tilpasses denne skjermen. Fra neste sesjon. 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 @@ -3113,6 +3141,7 @@ Eksperimentell hodesporing for Pro 2. Justering av lysstyrke og volum samt bytte av visningsmodus støttes ikke ennå. Cardboard VR Cardboard-modus + Bilder for venstre og høyre øye til en VR-brille for mobil. Bilde Virtuell skjerm Side-ved-side-3D @@ -3135,6 +3164,7 @@ Ikke tilgjengelig i denne økten. SteamVR svarte ikke; sjekk sesjonsloggen. Last ned komponenter + Nedlastinger deles med Komponenter-siden. Velg en nedlastet versjon ovenfor for å bruke den fra neste spilløkt. Velg en versjon å laste ned Utvikler Utgiver diff --git a/app/src/main/res/values-nl/input_library.xml b/app/src/main/res/values-nl/input_library.xml index 3576c30353..48db0c68ed 100644 --- a/app/src/main/res/values-nl/input_library.xml +++ b/app/src/main/res/values-nl/input_library.xml @@ -75,9 +75,14 @@ Onafhankelijke kopie Stick starten op aanraakpunt Stick verbergen als die niet wordt gebruikt + Gereedschap + Auto (%1$s) + Aangepast (%1$s) Opslaan als nieuw profiel Profielbediening + Profiel Muis-touchpadgebaren + Bij toewijzing aan de muisaanwijzer: tik om te klikken, houd vast om te slepen en scroll met twee vingers. %1$s heeft een snelmenu-overschrijving. Kies daar Auto om het standaardprofiel en alle drie opgeslagen delen te gebruiken. DroidDeck-invoer Vastgehouden terwijl de stick in een willekeurige richting wordt bewogen: ingedrukt boven 55%, losgelaten onder 35%. Gebruik Richtingtoetsen om elke richting apart toe te wijzen. DroidDeck-opdrachten worden één keer per uitslag uitgevoerd. De stickklik wordt apart ingesteld. @@ -99,11 +104,17 @@ In spelmodus Steam. Terug ingedrukt houden opent ook snelle toegang. Terugzetten naar standaard Virtuele controller + Het controllertype dat Steam of het spel ziet. Touchscreen + Hoe aanrakingen op het spelscherm worden afgehandeld. Profielknoppen behouden hun toegewezen acties. Aanraakcursor + Toon een aanwijzer voor directe aanrakingen op het spelscherm. Aanraken en vasthouden + Muisactie wanneer je een vinger op het spelscherm houdt. Tikken op de terugknop + Eerste actie: één tik. Tweede actie: dubbeltik. Schakelknop + Tik om vast te houden, tik opnieuw om los te laten. Een menu openen of van profiel wisselen laat de knop los. Vorm Afgerond Pil diff --git a/app/src/main/res/values-nl/input_strings.xml b/app/src/main/res/values-nl/input_strings.xml index bed390c511..df68d569fe 100644 --- a/app/src/main/res/values-nl/input_strings.xml +++ b/app/src/main/res/values-nl/input_strings.xml @@ -1,5 +1,6 @@ + Invoerprofielen Profielen Fysieke controller Hoofdscherm @@ -22,6 +23,7 @@ Steam-menu openen Steam-sneltoegang openen Besturing verwijderen + Besturing toevoegen Apparaatspecifieke knoppen Een fysieke knop toewijzen Laat de knop los en kies Bewerken, Opnieuw of Annuleren. B of Terug annuleert na loslaten. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 1113322860..be6d86c508 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. @@ -295,10 +294,14 @@ Aanraken Zijknop Schermbediening + Steam + QAM Automatisch toont de bediening als er geen controller is verbonden. + Steam-aanraakbediening (bèta) + De aanraakbediening van Steam start bij de volgende Steam-sessie Steam-aanraakindeling Exporteren Afbeelding + Verplaats, schaal of verberg de aanraakbediening van deze game; opgeslagen in Steam Controller Hoe Steam je controller ziet. Geldt vanaf de volgende sessie. Steam Deck-controller @@ -425,6 +428,7 @@ Omzeilt PulseAudio voor minder vertraging. Microfoon Voor spraakchat. + Zet microfoonopname aan of uit voor deze sessie. Kan de microfoon niet wijzigen. Probeer het opnieuw. Netwerk Wi-Fi-detectie @@ -786,6 +790,7 @@ Toetsenbord Latentie Modus voor lage latentie + Verhoogt CPU- en batterijgebruik Controller met lage latentie De controller rapporteert op 1000 Hz in plaats van 250 Hz. Iets meer CPU. Aanraking met lage latentie @@ -1339,8 +1344,12 @@ Transparantie %1$d%% Knopgrootte + Adaptieve sticks Trillen in games Dode zone van stick + Steam-knop + QAM-knop + Toetsenbordknop Joy-Cons als VR-controllers Zolang SteamVR draait, wordt elke Joy-Con een hand. Richt hem naar voren en houd Home of Capture ingedrukt om hem opnieuw te centreren. Animaties @@ -1469,6 +1478,8 @@ Trackpad Bediening op tweede scherm sluiten Steam-menu openen + Rechtertrackpad + Linkertrackpad Trackpad Toetsenbord tonen Toetsenbord verbergen @@ -1507,8 +1518,11 @@ Android-toetsenbord Verbergen ✕ Grootte op scherm + Het deel van het scherm dat het toetsenbord inneemt, inclusief de header. Dekking + Verlaag deze om het spel achter het toetsenbord te zien. Verborgen toetsen + Toetsen die je zelden gebruikt staan niet op het toetsenbord. Esc en functierij Ins / Del / Home / End / PgUp / PgDn Pijltjestoetsen @@ -1721,6 +1735,8 @@ %1$s geïnstalleerd - kies hem in het menu Wacht tot de runtime is verwijderd Game + touchpad + direct Wisselen mislukt: %1$s Profiel opslaan mislukt: %1$s De desktop is gepauzeerd @@ -1976,6 +1992,15 @@ Eén niveau omhoog Kies een map Kies een bestand + Steam-blauw + Hemelsblauw + Wit + Violet + Groen + Amber + Rood + Roze + Grijs A-knop B-knop X-knop @@ -2435,10 +2460,13 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Sessiescherm + Weergave zonder kopie Resolutie 16:9-beeldvulling Hoe 16:9-games dit scherm vullen. Volgende sessie. 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 @@ -3113,6 +3141,7 @@ Experimentele hoofdtracking voor Pro 2. Het aanpassen van helderheid en volume en het wisselen van weergavemodus worden nog niet ondersteund. Cardboard VR Cardboard-modus + Beelden voor linker- en rechteroog voor een VR-bril voor je telefoon. Beeld Virtueel scherm Side-by-side 3D @@ -3135,6 +3164,7 @@ Niet beschikbaar in deze sessie. SteamVR reageerde niet; controleer het sessielog. Componenten downloaden + Downloads worden gedeeld met de pagina Componenten. Kies hierboven een gedownloade versie om die bij de volgende start van een game te gebruiken. Kies een versie om te downloaden Ontwikkelaar Uitgever diff --git a/app/src/main/res/values-pl/input_library.xml b/app/src/main/res/values-pl/input_library.xml index 8daf6a15b5..02c4db578b 100644 --- a/app/src/main/res/values-pl/input_library.xml +++ b/app/src/main/res/values-pl/input_library.xml @@ -75,9 +75,14 @@ Niezależna kopia Zacznij drążek w miejscu dotknięcia Ukryj drążek, gdy nie jest używany + Narzędzia + Auto (%1$s) + Niestandardowy (%1$s) Zapisz jako nowy profil Sterowanie profilu + Profil Gesty touchpada myszy + Po przypisaniu do wskaźnika myszy: dotknij, aby kliknąć, przytrzymaj, aby przeciągnąć, i przewijaj dwoma palcami. %1$s ma zastąpienie szybkiego menu. Wybierz tam Auto, aby użyć profilu domyślnego i wszystkich trzech zapisanych części. Wejście DroidDeck Przytrzymywane, gdy drążek jest wychylony w dowolnym kierunku: naciśnięcie powyżej 55%, zwolnienie poniżej 35%. Użyj Klawiszy kierunkowych, aby przypisać każdy kierunek osobno. Polecenia DroidDeck działają raz na wychylenie. Kliknięcie drążka ustawia się osobno. @@ -99,11 +104,17 @@ W trybie Steam. Przytrzymanie Wstecz otwiera też szybki dostęp. Przywróć domyślne Wirtualny kontroler + Typ kontrolera widziany przez Steam lub grę. Ekran dotykowy + Jak obsługiwane są dotknięcia na ekranie gry. Przyciski profilu zachowują przypisane akcje. Kursor dotyku + Pokazuj wskaźnik dla bezpośrednich dotknięć na ekranie gry. Dotknij i przytrzymaj + Akcja myszy przy przytrzymaniu palca na ekranie gry. Dotknięcia przycisku Wstecz + Pierwsza akcja: jedno dotknięcie. Druga akcja: dwukrotne dotknięcie. Przycisk przełączania + Dotknij, aby przytrzymać, dotknij ponownie, aby zwolnić. Otwarcie menu lub zmiana profilu zwalnia przycisk. Kształt Zaokrąglony Kapsułka diff --git a/app/src/main/res/values-pl/input_strings.xml b/app/src/main/res/values-pl/input_strings.xml index 7b775c2fff..fcd5fdf9dd 100644 --- a/app/src/main/res/values-pl/input_strings.xml +++ b/app/src/main/res/values-pl/input_strings.xml @@ -1,5 +1,6 @@ + Profile wejścia Profile Fizyczny kontroler Główny ekran @@ -22,6 +23,7 @@ Otwórz menu Steam Otwórz szybki dostęp Steam Usuń element sterujący + Dodaj element sterujący Przyciski specyficzne dla urządzenia Przypisz przycisk fizyczny Zwolnij przycisk, a następnie wybierz Edytuj, Ponów lub Anuluj. B lub Wstecz anuluje po zwolnieniu. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index ab4f7544e0..80486fc3cd 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. @@ -295,10 +294,14 @@ Dotyk Przycisk boczny Sterowanie ekranowe + Steam + QAM Auto pokazuje sterowanie, gdy nie jest podłączony żaden kontroler. + Dotyk Steam (beta) + Sterowanie dotykowe Steam zacznie działać od następnej sesji Steam Układ dotykowy Steam Eksportuj Obraz + Przesuwaj, zmieniaj rozmiar lub ukrywaj sterowanie dotykowe tej gry; zapisywane w Steam Kontroler Jak Steam widzi Twój kontroler. Działa od następnej sesji. Kontroler Steam Deck @@ -427,6 +430,7 @@ Omija PulseAudio, aby zmniejszyć opóźnienie. Mikrofon Do czatu głosowego. + Włącz lub wyłącz przechwytywanie mikrofonu w tej sesji. Nie udało się zmienić mikrofonu. Spróbuj ponownie. Sieć Wykrywanie Wi-Fi @@ -790,6 +794,7 @@ Klawiatura Opóźnienie Tryb niskiego opóźnienia + Zwiększa użycie CPU i baterii Kontroler o niskim opóźnieniu Kontroler raportuje z częstotliwością 1000 Hz zamiast 250 Hz. Nieco więcej CPU. Dotyk o niskim opóźnieniu @@ -1353,8 +1358,12 @@ Przezroczystość %1$d%% Rozmiar przycisków + Adaptacyjne gałki Wibracje gry Martwa strefa drążka + Przycisk Steam + Przycisk QAM + Przycisk klawiatury Joy-Cony jako kontrolery VR Gdy działa SteamVR, każdy Joy-Con staje się dłonią. Skieruj go przed siebie i przytrzymaj Home lub Capture, aby go wyśrodkować. Animacje @@ -1485,6 +1494,8 @@ Trackpad Zamknij sterowanie na drugim ekranie Otwórz menu Steam + Prawy trackpad + Lewy trackpad Trackpad Pokaż klawiaturę Ukryj klawiaturę @@ -1523,8 +1534,11 @@ Klawiatura Android Ukryj ✕ Rozmiar na ekranie + Część ekranu zajmowana przez klawiaturę, wliczając nagłówek. Krycie + Zmniejsz je, aby zobaczyć grę za klawiaturą. Ukryte klawisze + Klawisze, których rzadko używasz, nie pojawiają się na klawiaturze. Esc i rząd klawiszy funkcyjnych Ins / Del / Home / End / PgUp / PgDn Klawisze strzałek @@ -1753,6 +1767,8 @@ Zainstalowano %1$s – wybierz go w menu Poczekaj na zakończenie usuwania środowiska Gra + touchpad + bezpośredni Zamiana nie powiodła się: %1$s Zapis profilu nie powiódł się: %1$s Pulpit jest wstrzymany @@ -2026,6 +2042,15 @@ Poziom wyżej Wybierz folder Wybierz plik + Niebieski Steam + Błękitny + Biały + Fioletowy + Zielony + Bursztynowy + Czerwony + Różowy + Szary Przycisk A Przycisk B Przycisk X @@ -2487,10 +2512,13 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Ekran sesji + Prezentacja bez kopiowania Rozdzielczość Dopasowanie gier 16:9 Jak gry 16:9 mieszczą się na tym ekranie. Od następnej sesji. 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 @@ -3173,6 +3201,7 @@ Eksperymentalne śledzenie ruchów głowy dla Pro 2. Regulacja jasności i głośności oraz przełączanie trybu wyświetlania nie są jeszcze obsługiwane. Cardboard VR Tryb Cardboard + Obraz dla lewego i prawego oka do gogli VR na telefon. Obraz Wirtualny ekran 3D obok siebie @@ -3195,6 +3224,7 @@ Niedostępne w tej sesji. SteamVR nie odpowiada; sprawdź dziennik sesji. Pobierz komponenty + Pobrane pliki są wspólne ze stroną Komponenty. Wybierz powyżej pobraną wersję, aby użyć jej przy następnym uruchomieniu gry. Wybierz wersję do pobrania Producent Wydawca 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 71ebbb7ff3..ec88357260 100644 --- a/app/src/main/res/values-pt-rPT/input_library.xml +++ b/app/src/main/res/values-pt-rPT/input_library.xml @@ -75,9 +75,14 @@ Cópia independente Iniciar o analógico no ponto de toque Ocultar o analógico quando não está a ser usado + Ferramentas + Auto (%1$s) + Personalizado (%1$s) Guardar como novo perfil Controlos do perfil + Perfil Gestos do touchpad do rato + Quando atribuído ao ponteiro do rato: toque para clicar, mantenha para arrastar e desloque com dois dedos. %1$s tem uma substituição do menu rápido. Selecione Auto para usar o perfil predefinido e as três partes guardadas. Entrada DroidDeck Mantido enquanto o analógico é movido em qualquer direção: pressiona acima de 55%, liberta abaixo de 35%. Use Teclas de direção para atribuir cada direção em separado. Os comandos DroidDeck correm uma vez por desvio. O clique do analógico configura-se à parte. @@ -99,11 +104,17 @@ No modo Steam. Manter Voltar também abre o acesso rápido. Repor predefinições Comando virtual + O tipo de comando visto pelo Steam ou pelo jogo. Ecrã tátil + Como os toques no ecrã do jogo são tratados. Os botões do perfil mantêm as ações atribuídas. Cursor tátil + Mostra um ponteiro para toques diretos no ecrã do jogo. Tocar e manter + Ação do rato ao manter um dedo no ecrã do jogo. Toques do botão Voltar + Primeira ação: toque único. Segunda ação: duplo toque. Botão de alternância + Toque para manter, toque novamente para libertar. Abrir um menu ou mudar de perfil liberta o botão. Forma Arredondada Cápsula diff --git a/app/src/main/res/values-pt-rPT/input_strings.xml b/app/src/main/res/values-pt-rPT/input_strings.xml index 99c292f72c..0d81834854 100644 --- a/app/src/main/res/values-pt-rPT/input_strings.xml +++ b/app/src/main/res/values-pt-rPT/input_strings.xml @@ -1,5 +1,6 @@ + Perfis de entrada Perfis Comando físico Ecrã principal @@ -22,6 +23,7 @@ Abrir o menu do Steam Abrir o acesso rápido do Steam Remover controlo + Adicionar controlo Botões específicos do dispositivo Atribuir um botão físico Largue o botão e escolha Editar, Repetir ou Cancelar. B ou Voltar cancela após largar. diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 6bcf811881..19e92b33fd 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. @@ -295,10 +294,14 @@ Toque Botão lateral Controlos no ecrã + Steam + QAM Em Automático, os controlos aparecem quando não há nenhum comando ligado. + Controlos táteis do Steam (beta) + Os controlos táteis do Steam começam na próxima sessão do Steam Esquema tátil do Steam Exportar Imagem + Mova, redimensione ou oculte os controlos táteis deste jogo; é guardado no Steam Comando Como o Steam vê o seu comando. Aplica-se na próxima sessão. Comando Steam Deck @@ -426,6 +429,7 @@ Ignora o PulseAudio para reduzir a latência. Microfone Para chat de voz. + Ativa ou desativa a captura do microfone nesta sessão. Não foi possível alterar o microfone. Tente novamente. Rede Deteção de Wi-Fi @@ -788,6 +792,7 @@ Teclado Latência Modo de baixa latência + Aumenta o consumo de CPU e de bateria Comando de baixa latência O comando comunica a 1000 Hz em vez de 250 Hz. Um pouco mais de CPU. Toque de baixa latência @@ -1337,8 +1342,12 @@ Opacidade %1$d%% Tamanho dos botões + Analógicos adaptáveis Vibração do jogo Zona morta do manípulo + Botão Steam + Botão QAM + Botão do teclado Joy-Con como comandos de RV Enquanto o SteamVR está a correr, cada Joy-Con torna-se uma mão. Aponte-o para a frente e mantenha Home ou Capture premido para o recentrar. Animações @@ -1468,6 +1477,8 @@ Trackpad Fechar controlos do segundo ecrã Abrir menu Steam + Trackpad direito + Trackpad esquerdo Trackpad Mostrar teclado Ocultar teclado @@ -1506,8 +1517,11 @@ Teclado Android Ocultar ✕ Tamanho no ecrã + Percentagem do ecrã ocupada pelo teclado, incluindo o cabeçalho. Opacidade + Reduza-a para ver o jogo por trás do teclado. Teclas ocultas + As teclas que raramente usa não aparecem no teclado. Esc e linha das teclas de função Ins / Del / Home / End / PgUp / PgDn Teclas de direção @@ -1728,6 +1742,8 @@ %1$s instalado - escolha-o no menu Aguarde que a remoção do runtime termine Jogo + painel tátil + direto Falha na troca: %1$s Falha ao guardar o perfil: %1$s O ambiente de trabalho está em pausa @@ -2006,6 +2022,15 @@ Subir um nível Escolha uma pasta Escolha um ficheiro + Azul Steam + Céu + Branco + Violeta + Verde + Âmbar + Vermelho + Rosa + Cinzento Botão A Botão B Botão X @@ -2466,10 +2491,13 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Ecrã da sessão + Apresentação sem cópia Resolução Ajuste de jogos 16:9 Como os jogos 16:9 se ajustam a este ecrã. Próxima sessão. 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 @@ -3145,6 +3173,7 @@ Seguimento experimental dos movimentos da cabeça para Pro 2. O ajuste do brilho e do volume e a mudança do modo de ecrã ainda não são suportados. Cardboard VR Modo Cardboard + Imagens para o olho esquerdo e o direito, para uns óculos de RV para telemóvel. Imagem Ecrã virtual 3D lado a lado @@ -3167,6 +3196,7 @@ Indisponível nesta sessão. O SteamVR não respondeu; verifica o registo da sessão. Transferir componentes + As transferências são partilhadas com a página Componentes. Escolhe acima uma versão transferida para a usar quando iniciares o próximo jogo. Escolhe uma versão para transferir Programadora Editora diff --git a/app/src/main/res/values-pt/input_library.xml b/app/src/main/res/values-pt/input_library.xml index a742205641..93dd70368e 100644 --- a/app/src/main/res/values-pt/input_library.xml +++ b/app/src/main/res/values-pt/input_library.xml @@ -75,9 +75,14 @@ Cópia independente Iniciar o analógico no ponto de toque Ocultar o analógico quando não estiver em uso + Ferramentas + Auto (%1$s) + Personalizado (%1$s) Salvar como novo perfil Controles do perfil + Perfil Gestos do touchpad do mouse + Quando atribuído ao ponteiro do mouse: toque para clicar, segure para arrastar e role com dois dedos. %1$s tem uma substituição do menu rápido. Selecione Auto lá para usar o perfil padrão e as três partes salvas. Entrada do DroidDeck Mantido enquanto o analógico é movido em qualquer direção: pressiona acima de 55%, solta abaixo de 35%. Use Teclas de direção para atribuir cada direção separadamente. Os comandos do DroidDeck rodam uma vez por deflexão. O clique do analógico é configurado à parte. @@ -99,11 +104,17 @@ No modo Steam. Manter Voltar também abre o acesso rápido. Restaurar o padrão Controle virtual + O tipo de controle visto pelo Steam ou pelo jogo. Tela sensível ao toque + Como os toques na tela do jogo são tratados. Os botões do perfil mantêm as ações atribuídas. Cursor de toque + Mostra um ponteiro para toques diretos na tela do jogo. Tocar e segurar + Ação do mouse ao segurar um dedo na tela do jogo. Toques do botão Voltar + Primeira ação: toque único. Segunda ação: toque duplo. Botão de alternância + Toque para manter, toque de novo para soltar. Abrir um menu ou trocar de perfil solta o botão. Forma Arredondada Pílula diff --git a/app/src/main/res/values-pt/input_strings.xml b/app/src/main/res/values-pt/input_strings.xml index e4e5d2fca7..5847aa3ac4 100644 --- a/app/src/main/res/values-pt/input_strings.xml +++ b/app/src/main/res/values-pt/input_strings.xml @@ -1,5 +1,6 @@ + Perfis de entrada Perfis Controle físico Tela principal @@ -22,6 +23,7 @@ Abrir o menu do Steam Abrir o acesso rápido do Steam Remover controle + Adicionar controle Botões específicos do dispositivo Atribuir um botão físico Solte o botão e escolha Editar, Repetir ou Cancelar. B ou Voltar cancela após soltar. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index c93c0e9a25..aa4a3fec32 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. @@ -295,10 +294,14 @@ Toque Botão lateral Controles na tela + Steam + QAM No Automático, os controles na tela aparecem quando não há um controle conectado. + Toque da Steam (beta) + Os controles de toque da Steam começam na próxima sessão da Steam Layout de toque da Steam Exportar Imagem + Mova, redimensione ou oculte os controles de toque deste jogo; salvo na Steam Controle Como a Steam vê seu controle. Vale a partir da próxima sessão. Controle do Steam Deck @@ -426,6 +429,7 @@ Ignora o PulseAudio para reduzir a latência. Microfone Para chat de voz. + Ativa ou desativa a captura do microfone nesta sessão. Não foi possível alterar o microfone. Tente novamente. Rede Descoberta de Wi-Fi @@ -756,9 +760,12 @@ Modo de escala Nitidez da escala Perfil de efeitos + Escolha qual perfil terá os efeitos de tela editados. Jogo atual (automático) Redefinir efeitos + Define os efeitos deste perfil como desativados por padrão. Excluir configuração salva + Remove os efeitos salvos deste jogo para ele herdar o perfil padrão. Efeitos de tela Em tempo real. Custa um pouco de tempo de GPU enquanto algum efeito estiver ativado. Predefinições @@ -792,6 +799,7 @@ Teclado Latência Modo de baixa latência + Aumenta o uso de CPU e bateria Controle de baixa latência O controle envia dados a 1000 Hz em vez de 250 Hz. Um pouco mais de CPU. Toque de baixa latência @@ -1342,8 +1350,12 @@ Opacidade %1$d%% Tamanho dos botões + Analógicos adaptáveis Vibração do jogo Zona morta do analógico + Botão Steam + Botão QAM + Botão do teclado Joy-Cons como controles de RV Enquanto o SteamVR está rodando, cada Joy-Con vira uma mão. Aponte-o para a frente e segure Home ou Capture para recentralizá-lo. Animações @@ -1473,6 +1485,8 @@ Trackpad Fechar controles da segunda tela Abrir o menu Steam + Trackpad direito + Trackpad esquerdo Trackpad Mostrar teclado Ocultar teclado @@ -1511,8 +1525,11 @@ Teclado do Android Ocultar ✕ Tamanho na tela + Parte da tela ocupada pelo teclado, incluindo o cabeçalho. Opacidade + Reduza para ver o jogo atrás do teclado. Teclas ocultas + Teclas que você usa raramente não aparecem no teclado. Esc e fileira de teclas de função Ins / Del / Home / End / PgUp / PgDn Teclas de seta @@ -1733,6 +1750,8 @@ %1$s instalado - escolha-o no menu Aguarde a remoção do runtime terminar Jogo + touchpad + direto Falha na troca: %1$s Falha ao salvar o perfil: %1$s A área de trabalho está pausada @@ -2011,6 +2030,15 @@ Subir um nível Escolha uma pasta Escolha um arquivo + Azul Steam + Céu + Branco + Violeta + Verde + Âmbar + Vermelho + Rosa + Cinza Botão A Botão B Botão X @@ -2471,10 +2499,13 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Tela da sessão + Apresentação sem cópia Resolução Ajuste de jogos 16:9 Como os jogos 16:9 se ajustam a esta tela. Na próxima sessão. 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 @@ -3150,6 +3181,7 @@ Rastreamento experimental da cabeça para Pro 2. Os ajustes de brilho e volume e a troca do modo de exibição ainda não são compatíveis. Cardboard VR Modo Cardboard + Imagens para o olho esquerdo e o direito, para um óculos de RV de celular. Imagem Tela virtual 3D lado a lado @@ -3172,6 +3204,7 @@ Indisponível nesta sessão. O SteamVR não respondeu; veja o registro da sessão. Baixar componentes + Os downloads são compartilhados com a página Componentes. Escolha acima uma versão baixada para usá-la na próxima vez que um jogo for aberto. Escolha uma versão para baixar Desenvolvedora Publicadora diff --git a/app/src/main/res/values-ro/input_library.xml b/app/src/main/res/values-ro/input_library.xml index 3dbecd2cc8..7f2b804916 100644 --- a/app/src/main/res/values-ro/input_library.xml +++ b/app/src/main/res/values-ro/input_library.xml @@ -75,9 +75,14 @@ Copie independentă Pornește maneta la punctul de atingere Ascunde maneta când nu este folosită + Instrumente + Auto (%1$s) + Personalizat (%1$s) Salvează ca profil nou Comenzile profilului + Profil Gesturi touchpad mouse + Când este atribuit indicatorului mouse-ului: atinge pentru clic, ține pentru tragere și derulează cu două degete. %1$s are o suprascriere a meniului rapid. Selectează Auto acolo pentru a folosi profilul implicit și toate cele trei părți salvate. Intrare DroidDeck Ținut cât timp maneta este mișcată în orice direcție: apăsat peste 55%, eliberat sub 35%. Folosește Tastele direcționale pentru a atribui fiecare direcție separat. Comenzile DroidDeck rulează o dată per deviere. Clicul manetei se configurează separat. @@ -99,11 +104,17 @@ În modul Steam. Ținerea butonului Înapoi deschide și accesul rapid. Restabilește implicit Controller virtual + Tipul de controller văzut de Steam sau de joc. Ecran tactil + Cum sunt tratate atingerile pe ecranul jocului. Butoanele profilului își păstrează acțiunile atribuite. Cursor tactil + Afișează un indicator pentru atingeri directe pe ecranul jocului. Atinge și ține + Acțiunea mouse-ului când ții un deget pe ecranul jocului. Atingeri ale butonului Înapoi + Prima acțiune: o atingere. A doua acțiune: atingere dublă. Buton de comutare + Atinge pentru a ține, atinge din nou pentru a elibera. Deschiderea unui meniu sau schimbarea profilului eliberează butonul. Formă Rotunjit Capsulă diff --git a/app/src/main/res/values-ro/input_strings.xml b/app/src/main/res/values-ro/input_strings.xml index 1f99485414..1603f7b260 100644 --- a/app/src/main/res/values-ro/input_strings.xml +++ b/app/src/main/res/values-ro/input_strings.xml @@ -1,5 +1,6 @@ + Profiluri de intrare Profiluri Controller fizic Ecran principal @@ -22,6 +23,7 @@ Deschide meniul Steam Deschide accesul rapid Steam Elimină controlul + Adaugă control Butoane specifice dispozitivului Atribuie un buton fizic Eliberează butonul, apoi alege Editează, Reîncearcă sau Anulează. B sau Înapoi anulează după eliberare. diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index c843890ecb..fa7ba56548 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. @@ -295,10 +294,14 @@ Atingere Buton lateral Comenzi pe ecran + Steam + QAM Automat afișează comenzile când niciun controller nu este conectat. + Atingere Steam (beta) + Comenzile tactile Steam pornesc odată cu următoarea sesiune Steam Aranjament tactil Steam Exportă Imagine + Mută, redimensionează sau ascunde comenzile tactile ale acestui joc; salvate în Steam Controller Cum vede Steam controllerul tău. Se aplică la sesiunea următoare. Controller Steam Deck @@ -426,6 +429,7 @@ Evită PulseAudio pentru o latență mai mică. Microfon Pentru chat vocal. + Activează sau dezactivează captarea microfonului pentru această sesiune. Microfonul nu a putut fi schimbat. Încearcă din nou. Rețea Descoperire Wi-Fi @@ -788,6 +792,7 @@ Tastatură Latență Mod latență redusă + Crește consumul de CPU și baterie Controller cu latență mică Controllerul raportează la 1000 Hz în loc de 250 Hz. Consum CPU puțin mai mare. Atingere cu latență mică @@ -1346,8 +1351,12 @@ Opacitate %1$d%% Dimensiunea butoanelor + Manșe adaptive Vibrații de joc Zonă moartă a manetei + Butonul Steam + Butonul QAM + Butonul tastaturii Joy-Con ca controllere VR Cât timp rulează SteamVR, fiecare Joy-Con devine o mână. Îndreaptă-l înainte și ține apăsat Home sau Capture pentru a-l recentra. Animații @@ -1477,6 +1486,8 @@ Trackpad Închide comenzile celui de-al doilea ecran Deschide meniul Steam + Trackpad-ul drept + Trackpad-ul stâng Trackpad Arată tastatura Ascunde tastatura @@ -1515,8 +1526,11 @@ Tastatura Android Ascunde ✕ Dimensiune pe ecran + Partea din ecran ocupată de tastatură, inclusiv antetul. Opacitate + Reduceți-o pentru a vedea jocul din spatele tastaturii. Taste ascunse + Tastele pe care le folosiți rar nu apar pe tastatură. Esc și rândul tastelor funcționale Ins / Del / Home / End / PgUp / PgDn Tastele cu săgeți @@ -1737,6 +1751,8 @@ Instalat %1$s - alege-l în meniu Așteaptă să se termine eliminarea mediului de execuție Joc + touchpad + direct Comutarea a eșuat: %1$s Salvarea profilului a eșuat: %1$s Desktopul este pus pe pauză @@ -2001,6 +2017,15 @@ Un nivel mai sus Alege un folder Alege un fișier + Albastru Steam + Cer + Alb + Violet + Verde + Chihlimbariu + Roșu + Roz + Gri Butonul A Butonul B Butonul X @@ -2461,10 +2486,13 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Afișajul sesiunii + Prezentare fără copiere Rezoluție Potrivire joc 16:9 Cum se potrivesc jocurile 16:9 cu acest afișaj. Sesiunea următoare. 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 @@ -3143,6 +3171,7 @@ Urmărire experimentală a mișcărilor capului pentru Pro 2. Reglarea luminozității și a volumului și schimbarea modului de afișare nu sunt încă acceptate. Cardboard VR Mod Cardboard + Imagini pentru ochiul stâng și cel drept, pentru un vizor VR pentru telefon. Imagine Ecran virtual 3D alăturat @@ -3165,6 +3194,7 @@ Indisponibil în această sesiune. SteamVR nu a răspuns; verifică jurnalul sesiunii. Descarcă componente + Descărcările sunt comune cu pagina Componente. Alege mai sus o versiune descărcată pentru a o folosi la următoarea lansare a jocului. Alege o versiune de descărcat Dezvoltator Editor diff --git a/app/src/main/res/values-ru/input_library.xml b/app/src/main/res/values-ru/input_library.xml index b065fed79d..b4b9cfd9f6 100644 --- a/app/src/main/res/values-ru/input_library.xml +++ b/app/src/main/res/values-ru/input_library.xml @@ -75,9 +75,14 @@ Независимая копия Запускать стик от точки касания Скрывать стик, когда он не используется + Инструменты + Авто (%1$s) + Пользовательский (%1$s) Сохранить как новый профиль Управление профиля + Профиль Жесты тачпада мыши + Если назначено указателю мыши: касание — клик, удержание — перетаскивание, прокрутка двумя пальцами. Для %1$s задано переопределение быстрого меню. Выберите «Авто», чтобы использовать профиль по умолчанию и все три сохранённые части. Ввод DroidDeck Удерживается, пока стик отклонён в любом направлении: нажатие выше 55%, отпускание ниже 35%. Используйте «Клавиши направлений», чтобы назначить каждое направление отдельно. Команды DroidDeck срабатывают один раз за отклонение. Нажатие стика настраивается отдельно. @@ -99,11 +104,17 @@ В режиме Steam. Удержание «Назад» также открывает быстрый доступ. Вернуть по умолчанию Виртуальный контроллер + Тип контроллера, который видят Steam или игра. Сенсорный экран + Как обрабатываются касания на экране игры. Кнопки профиля сохраняют назначенные действия. Касание-курсор + Показывать указатель для прямых касаний на экране игры. Коснуться и удерживать + Действие мыши при удержании пальца на экране игры. Нажатия кнопки «Назад» + Первое действие: одно нажатие. Второе действие: двойное нажатие. Кнопка-переключатель + Коснитесь, чтобы удерживать, коснитесь снова, чтобы отпустить. Открытие меню или смена профиля отпускает кнопку. Форма Скруглённая Капсула diff --git a/app/src/main/res/values-ru/input_strings.xml b/app/src/main/res/values-ru/input_strings.xml index 4de6367b0b..9f041bfb21 100644 --- a/app/src/main/res/values-ru/input_strings.xml +++ b/app/src/main/res/values-ru/input_strings.xml @@ -1,5 +1,6 @@ + Профили ввода Профили Физический контроллер Основной экран @@ -22,6 +23,7 @@ Открыть меню Steam Открыть быстрый доступ Steam Удалить элемент + Добавить элемент Кнопки конкретного устройства Назначить физическую кнопку Отпустите кнопку и выберите «Изменить», «Повторить» или «Отмена». B или «Назад» отменяет после отпускания. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index e76e565d26..1cf83c57c5 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 и рабочего стола. Настройте на странице «Компоненты». @@ -295,10 +294,14 @@ Сенсорный ввод Боковая кнопка Экранные элементы управления + Steam + QAM Автоматический режим показывает экранные элементы управления, если контроллер не подключен. + Сенсорное управление Steam (бета) + Сенсорное управление Steam включится со следующей сессии Steam Сенсорная раскладка Steam Экспорт Изображение + Перемещайте, меняйте размер или скрывайте сенсорные кнопки этой игры; сохраняется в Steam Контроллер Как Steam распознает ваш контроллер. Вступит в силу в следующей сессии. Контроллер Steam Deck @@ -427,6 +430,7 @@ Обходит PulseAudio для снижения задержки. Микрофон Используется для голосового чата. + Включить или отключить захват микрофона в этой сессии. Не удалось изменить микрофон. Повторите попытку. Сеть Обнаружение Wi-Fi @@ -790,6 +794,7 @@ Клавиатура Задержка Режим низкой задержки + Увеличивает нагрузку на CPU и расход батареи Контроллер с низкой задержкой Контроллер опрашивается на 1000 Гц вместо 250 Гц. Немного больше нагрузки на CPU. Сенсор с низкой задержкой @@ -1353,8 +1358,12 @@ Непрозрачность %1$d%% Размер кнопок + Адаптивные стики Вибрация в играх Мёртвая зона стика + Кнопка Steam + Кнопка QAM + Кнопка клавиатуры Joy-Con как VR-контроллеры Пока работает SteamVR, каждый Joy-Con становится рукой. Направьте его вперёд и удерживайте Home или Capture, чтобы снова его отцентрировать. Анимации @@ -1485,6 +1494,8 @@ Тачпад Закрыть управление вторым экраном Открыть меню Steam + Правый тачпад + Левый тачпад Тачпад Показать клавиатуру Скрыть клавиатуру @@ -1523,8 +1534,11 @@ Клавиатура Android Скрыть ✕ Размер на экране + Какую часть экрана занимает клавиатура вместе с заголовком. Непрозрачность + Уменьшите, чтобы видеть игру за клавиатурой. Скрытые клавиши + Клавиши, которыми вы редко пользуетесь, не показываются на клавиатуре. Esc и ряд F-клавиш Ins / Del / Home / End / PgUp / PgDn Стрелки @@ -1753,6 +1767,8 @@ Установлен %1$s — выберите его в меню Дождитесь завершения удаления среды выполнения Игра + тачпад + прямой Ошибка замены: %1$s Ошибка сохранения профиля: %1$s Рабочий стол приостановлен @@ -2026,6 +2042,15 @@ На уровень вверх Выберите папку Выберите файл + Синий Steam + Небесный + Белый + Фиолетовый + Зеленый + Янтарный + Красный + Розовый + Серый Кнопка A Кнопка B Кнопка X @@ -2487,10 +2512,13 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Экран сессии + Вывод без копирования Разрешение Игры 16:9 Как игры 16:9 вписываются в этот экран. Вступит в силу в следующей сессии. Выберите «По размеру экрана» или свой размер уже 16:9. + Обходить вырез + Не выводит картинку под вырез камеры. Применяется при возврате в сессию. Сохранять пропорции Растянуть на экран Масштабирование изображения @@ -3178,6 +3206,7 @@ %1$d мин Cardboard VR Режим Cardboard + Изображения для левого и правого глаза для VR-очков под телефон. Изображение Виртуальный экран Стереопара 3D @@ -3200,6 +3229,7 @@ Недоступно в этой сессии. SteamVR не отвечает; проверьте журнал сессии. Скачать компоненты + Загрузки общие со страницей «Компоненты». Выберите выше скачанную версию, чтобы использовать её при следующем запуске игры. Выберите версию для скачивания Недостаточно свободного места: нужно %1$s, свободно только %2$s Недостаточно места (свободно %1$s, нужно %2$s) diff --git a/app/src/main/res/values-sv/input_library.xml b/app/src/main/res/values-sv/input_library.xml index 7272f5c8f3..15e3e12e03 100644 --- a/app/src/main/res/values-sv/input_library.xml +++ b/app/src/main/res/values-sv/input_library.xml @@ -75,9 +75,14 @@ Oberoende kopia Starta spaken vid beröringspunkten Dölj spaken när den inte används + Verktyg + Auto (%1$s) + Anpassad (%1$s) Spara som ny profil Profilstyrning + Profil Musstyrplattesgester + När tilldelad muspekaren: tryck för att klicka, håll för att dra och rulla med två fingrar. %1$s har en åsidosättning av snabbmenyn. Välj Auto där för att använda standardprofilen och alla tre sparade delarna. DroidDeck-inmatning Hålls medan spaken rörs i valfri riktning: tryck över 55 %, släpp under 35 %. Använd Riktningstangenter för att tilldela varje riktning separat. DroidDeck-kommandon körs en gång per utslag. Spakens klick konfigureras separat. @@ -99,11 +104,17 @@ I Steam-läge. Att hålla Tillbaka öppnar även snabbåtkomst. Återställ till standard Virtuell handkontroll + Den handkontrolltyp som Steam eller spelet ser. Pekskärm + Hur beröringar på spelskärmen hanteras. Profilknapparna behåller sina tilldelade åtgärder. Pekmarkör + Visa en pekare för direkta beröringar på spelskärmen. Tryck och håll + Musåtgärd när du håller ett finger på spelskärmen. Tryck på Tillbaka-knappen + Första åtgärden: ett tryck. Andra åtgärden: dubbeltryck. Växlingsknapp + Tryck för att hålla, tryck igen för att släppa. Att öppna en meny eller byta profil släpper knappen. Form Rundad Kapsel diff --git a/app/src/main/res/values-sv/input_strings.xml b/app/src/main/res/values-sv/input_strings.xml index eec793ffa1..ae79aa8645 100644 --- a/app/src/main/res/values-sv/input_strings.xml +++ b/app/src/main/res/values-sv/input_strings.xml @@ -1,5 +1,6 @@ + Inmatningsprofiler Profiler Fysisk handkontroll Huvudskärm @@ -22,6 +23,7 @@ Öppna Steam-menyn Öppna Steams snabbåtkomst Ta bort kontroll + Lägg till kontroll Enhetsspecifika knappar Tilldela en fysisk knapp Släpp knappen och välj Redigera, Försök igen eller Avbryt. B eller Tillbaka avbryter efter släpp. diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 1d9b647336..1669d9b650 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. @@ -295,10 +294,14 @@ Pekskärm Sidoknapp Skärmkontroller + Steam + QAM Auto visar kontrollerna när ingen handkontroll är ansluten. + Steam-pekstyrning (beta) + Steams pekstyrning startar med nästa Steam-session Steams peklayout Exportera Bild + Flytta, ändra storlek på eller dölj spelets pekkontroller; sparas i Steam Handkontroll Hur Steam ser din handkontroll. Gäller från nästa session. Steam Deck-kontroll @@ -425,6 +428,7 @@ Kringgår PulseAudio för lägre latens. Mikrofon För röstchatt. + Slå på eller av mikrofoninspelning för den här sessionen. Det gick inte att ändra mikrofonen. Försök igen. Nätverk Wi-Fi-identifiering @@ -786,6 +790,7 @@ Tangentbord Latens Läge för låg latens + Ökar CPU- och batteriförbrukningen Handkontroll med låg latens Handkontrollen rapporterar i 1000 Hz i stället för 250 Hz. Något mer CPU. Pekning med låg latens @@ -1339,8 +1344,12 @@ Opacitet %1$d %% Knappstorlek + Adaptiva spakar Spelvibration Styrspakens dödzon + Steam-knappen + QAM-knappen + Tangentbordsknappen Joy-Con som VR-handkontroller Medan SteamVR körs blir varje Joy-Con en hand. Rikta den framåt och håll in Home eller Capture för att centrera den igen. Animationer @@ -1469,6 +1478,8 @@ Styrplatta Stäng kontrollerna på andra skärmen Öppna Steam-menyn + Höger styrplatta + Vänster styrplatta Styrplatta Visa tangentbord Dölj tangentbord @@ -1507,8 +1518,11 @@ Android-tangentbord Dölj ✕ Storlek på skärmen + Andel av skärmen som tangentbordet tar upp, inklusive toppfältet. Opacitet + Sänk den för att se spelet bakom tangentbordet. Dolda tangenter + Tangenter du sällan använder hålls borta från tangentbordet. Raden med Esc och funktionstangenter Ins / Del / Home / End / PgUp / PgDn Piltangenter @@ -1721,6 +1735,8 @@ Installerad %1$s - välj den i menyn Vänta tills borttagningen av körmiljön är klar Spel + pekplatta + direkt Bytet misslyckades: %1$s Kunde inte spara profilen: %1$s Skrivbordet är pausat @@ -1976,6 +1992,15 @@ Upp en nivå Välj en mapp Välj en fil + Steamblå + Himmelsblå + Vit + Lila + Grön + Bärnsten + Röd + Rosa + Grå A-knappen B-knappen X-knappen @@ -2435,10 +2460,13 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Sessionsskärm + Presentation utan kopiering Upplösning 16:9-spelanpassning Hur 16:9-spel anpassas till den här skärmen. Nästa session. 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 @@ -3113,6 +3141,7 @@ Experimentell huvudspårning för Pro 2. Justering av ljusstyrka och volym samt byte av visningsläge stöds inte ännu. Cardboard VR Cardboard-läge + Bilder för vänster och höger öga till ett VR-headset för mobilen. Bild Virtuell skärm Sida vid sida-3D @@ -3135,6 +3164,7 @@ Inte tillgängligt i den här sessionen. SteamVR svarade inte; kontrollera sessionsloggen. Ladda ned komponenter + Nedladdningar delas med sidan Komponenter. Välj en nedladdad version ovan för att använda den nästa gång ett spel startas. Välj en version att ladda ned Utvecklare Utgivare diff --git a/app/src/main/res/values-th/input_library.xml b/app/src/main/res/values-th/input_library.xml index 8bc21ecfd7..ef2ae2702a 100644 --- a/app/src/main/res/values-th/input_library.xml +++ b/app/src/main/res/values-th/input_library.xml @@ -75,9 +75,14 @@ สำเนาอิสระ เริ่มก้านที่ตำแหน่งแตะ ซ่อนก้านเมื่อไม่ใช้งาน + เครื่องมือ + อัตโนมัติ (%1$s) + กำหนดเอง (%1$s) บันทึกเป็นโปรไฟล์ใหม่ การควบคุมโปรไฟล์ + โปรไฟล์ ท่าทางทัชแพดเมาส์ + เมื่อกำหนดให้ตัวชี้เมาส์: แตะเพื่อคลิก กดค้างเพื่อลาก และเลื่อนด้วยสองนิ้ว %1$s มีการแทนที่เมนูด่วน เลือกอัตโนมัติที่นั่นเพื่อใช้โปรไฟล์เริ่มต้นและทั้งสามส่วนที่บันทึกไว้ อินพุต DroidDeck ถูกกดค้างขณะก้านถูกเลื่อนไปทุกทิศทาง: กดเมื่อเกิน 55% ปล่อยเมื่อต่ำกว่า 35% ใช้ปุ่มทิศทางเพื่อกำหนดแต่ละทิศแยกกัน คำสั่ง DroidDeck ทำงานครั้งเดียวต่อการเอียง คลิกก้านตั้งค่าแยก @@ -99,11 +104,17 @@ ในโหมด Steam การกดย้อนกลับค้างจะเปิดการเข้าถึงด่วนด้วย คืนค่าเริ่มต้น คอนโทรลเลอร์เสมือน + ชนิดคอนโทรลเลอร์ที่ Steam หรือเกมมองเห็น หน้าจอสัมผัส + วิธีจัดการการสัมผัสบนหน้าจอเกม ปุ่มโปรไฟล์ยังคงการทำงานที่กำหนดไว้ เคอร์เซอร์สัมผัส + แสดงตัวชี้สำหรับการสัมผัสโดยตรงบนหน้าจอเกม แตะแล้วกดค้าง + การทำงานของเมาส์เมื่อกดนิ้วค้างบนหน้าจอเกม การแตะปุ่มย้อนกลับ + การทำงานแรก: แตะครั้งเดียว การทำงานที่สอง: แตะสองครั้ง ปุ่มสลับ + แตะเพื่อกดค้าง แตะอีกครั้งเพื่อปล่อย การเปิดเมนูหรือสลับโปรไฟล์จะปล่อยปุ่ม รูปร่าง มุมมน แคปซูล diff --git a/app/src/main/res/values-th/input_strings.xml b/app/src/main/res/values-th/input_strings.xml index 17a9eac493..de9275d0a6 100644 --- a/app/src/main/res/values-th/input_strings.xml +++ b/app/src/main/res/values-th/input_strings.xml @@ -1,5 +1,6 @@ + โปรไฟล์อินพุต โปรไฟล์ คอนโทรลเลอร์จริง หน้าจอหลัก @@ -22,6 +23,7 @@ เปิดเมนู Steam เปิดการเข้าถึงด่วนของ Steam ลบการควบคุม + เพิ่มการควบคุม ปุ่มเฉพาะอุปกรณ์ กำหนดปุ่มจริง ปล่อยปุ่ม แล้วเลือก แก้ไข ลองอีกครั้ง หรือยกเลิก B หรือย้อนกลับจะยกเลิกหลังปล่อย diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 72d7f7191f..d2067ebb29 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 @@ -295,10 +294,14 @@ การสัมผัส ปุ่มด้านข้าง ปุ่มควบคุมบนหน้าจอ + Steam + QAM อัตโนมัติจะแสดงปุ่มควบคุมเมื่อไม่มีคอนโทรลเลอร์เชื่อมต่ออยู่ + การสัมผัสของ Steam (ทดลอง) + ปุ่มสัมผัสของ Steam จะเริ่มใช้งานในเซสชัน Steam ถัดไป รูปแบบปุ่มสัมผัสของ Steam ส่งออก รูปภาพ + ย้าย ปรับขนาด หรือซ่อนปุ่มสัมผัสของเกมนี้ บันทึกไปยัง Steam คอนโทรลเลอร์ วิธีที่ Steam มองเห็นคอนโทรลเลอร์ของคุณ จะมีผลในเซสชันถัดไป คอนโทรลเลอร์ Steam Deck @@ -424,6 +427,7 @@ ข้าม PulseAudio เพื่อลดความหน่วง ไมโครโฟน สำหรับการแชทด้วยเสียง + เปิดหรือปิดการรับเสียงจากไมโครโฟนสำหรับเซสชันนี้ เปลี่ยนไมโครโฟนไม่ได้ โปรดลองอีกครั้ง เครือข่าย การค้นหา Wi-Fi @@ -784,6 +788,7 @@ แป้นพิมพ์ ความหน่วง โหมดหน่วงเวลาต่ำ + ใช้ CPU และแบตเตอรี่มากขึ้น คอนโทรลเลอร์ความหน่วงต่ำ คอนโทรลเลอร์รายงานที่ 1000 Hz แทน 250 Hz ใช้ CPU เพิ่มขึ้นเล็กน้อย การสัมผัสความหน่วงต่ำ @@ -1333,8 +1338,12 @@ ความโปร่งใส %1$d%% ขนาดปุ่ม + สติ๊กแบบปรับอัตโนมัติ การสั่นของเกม เดดโซนของแอนะล็อกสติ๊ก + ปุ่ม Steam + ปุ่ม QAM + ปุ่มแป้นพิมพ์ ใช้ Joy-Con เป็นคอนโทรลเลอร์ VR ขณะที่ SteamVR ทำงาน Joy-Con แต่ละตัวจะกลายเป็นมือ ชี้ไปข้างหน้าแล้วกด Home หรือ Capture ค้างไว้เพื่อจัดให้อยู่ตรงกลางอีกครั้ง ภาพเคลื่อนไหว @@ -1462,6 +1471,8 @@ แทร็กแพด ปิดการควบคุมหน้าจอที่สอง เปิดเมนู Steam + แทร็กแพดขวา + แทร็กแพดซ้าย แทร็กแพด แสดงแป้นพิมพ์ ซ่อนแป้นพิมพ์ @@ -1500,8 +1511,11 @@ แป้นพิมพ์ Android ซ่อน ✕ ขนาดบนหน้าจอ + สัดส่วนหน้าจอที่คีย์บอร์ดใช้ รวมแถบหัวด้วย ความทึบแสง + ลดค่านี้เพื่อให้เห็นเกมด้านหลังคีย์บอร์ด ปุ่มที่ซ่อนไว้ + ปุ่มที่ใช้ไม่บ่อยจะไม่แสดงบนคีย์บอร์ด Esc และแถวปุ่มฟังก์ชัน Ins / Del / Home / End / PgUp / PgDn ปุ่มลูกศร @@ -1706,6 +1720,8 @@ ติดตั้ง %1$s แล้ว - เลือกจากเมนู รอให้การลบรันไทม์เสร็จสิ้น เกม + ทัชแพด + โดยตรง สลับล้มเหลว: %1$s บันทึกโปรไฟล์ล้มเหลว: %1$s เดสก์ท็อปหยุดชั่วคราว @@ -1952,6 +1968,15 @@ ขึ้นหนึ่งระดับ เลือกโฟลเดอร์ เลือกไฟล์ + ฟ้า Steam + ฟ้าสดใส + ขาว + ม่วง + เขียว + อำพัน + แดง + ชมพู + เทา ปุ่ม A ปุ่ม B ปุ่ม X @@ -2410,10 +2435,13 @@ ANDROID + LINUX %1$s %2$s\n\n%3$s การแสดงผลของเซสชัน + การแสดงผลแบบไม่คัดลอก ความละเอียด การแสดงเกม 16:9 ให้พอดี วิธีที่เกม 16:9 แสดงพอดีกับหน้าจอนี้ มีผลในเซสชันถัดไป เลือกพอดีหน้าจอ หรือขนาดกำหนดเองที่แคบกว่า 16:9 + เลี่ยงรอยบาก + ไม่แสดงภาพทับช่องกล้อง มีผลเมื่อคุณกลับเข้าสู่เซสชัน คงสัดส่วนไว้ ยืดให้พอดีหน้าจอ การปรับขนาดภาพ @@ -3084,6 +3112,7 @@ การติดตามศีรษะแบบทดลองสำหรับ Pro 2 ยังไม่รองรับการปรับความสว่าง ระดับเสียง และการสลับโหมดการแสดงผล Cardboard VR โหมด Cardboard + ภาพสำหรับตาซ้ายและตาขวาสำหรับแว่น VR ของโทรศัพท์ ภาพ หน้าจอเสมือน 3D แบบเคียงข้าง @@ -3106,6 +3135,7 @@ ใช้ไม่ได้ในเซสชันนี้ SteamVR ไม่ตอบสนอง ตรวจสอบบันทึกเซสชัน ดาวน์โหลดคอมโพเนนต์ + ไฟล์ที่ดาวน์โหลดใช้ร่วมกับหน้า Components เลือกเวอร์ชันที่ดาวน์โหลดแล้วด้านบนเพื่อใช้ในการเปิดเกมครั้งถัดไป เลือกเวอร์ชันที่จะดาวน์โหลด ผู้พัฒนา ผู้จัดจำหน่าย diff --git a/app/src/main/res/values-tr/input_library.xml b/app/src/main/res/values-tr/input_library.xml index 910d56cdbd..563657c5d4 100644 --- a/app/src/main/res/values-tr/input_library.xml +++ b/app/src/main/res/values-tr/input_library.xml @@ -75,9 +75,14 @@ Bağımsız kopya Çubuğu dokunma noktasında başlat Kullanılmadığında çubuğu gizle + Araçlar + Otomatik (%1$s) + Özel (%1$s) Yeni profil olarak kaydet Profil kontrolleri + Profil Fare dokunmatik yüzey hareketleri + Fare işaretçisine atandığında: tıklamak için dokunun, sürüklemek için basılı tutun ve iki parmakla kaydırın. %1$s için hızlı menü geçersiz kılması var. Varsayılan profilini ve üç kayıtlı bölümünü kullanmak için orada Otomatik seçin. DroidDeck girişi Çubuk herhangi bir yöne hareket ettirildiğinde basılı tutulur: %55 üzerinde basılır, %35 altında bırakılır. Her yönü ayrı atamak için Yön tuşlarını kullanın. DroidDeck komutları her sapma için bir kez çalışır. Çubuk tıklaması ayrıca yapılandırılır. @@ -99,11 +104,17 @@ Steam modunda. Geri tuşunu basılı tutmak hızlı erişimi de açar. Varsayılana sıfırla Sanal denetleyici + Steam veya oyunun gördüğü denetleyici türü. Dokunmatik ekran + Oyun ekranındaki dokunuşların nasıl işlendiği. Profil düğmeleri atanmış eylemlerini korur. Dokunma imleci + Oyun ekranındaki doğrudan dokunuşlar için işaretçi göster. Dokun ve tut + Oyun ekranında parmağınızı tutarken fare eylemi. Geri düğmesi dokunuşları + İlk eylem: tek dokunuş. İkinci eylem: çift dokunuş. Aç/kapa düğmesi + Basılı tutmak için dokunun, bırakmak için tekrar dokunun. Menü açmak veya profil değiştirmek düğmeyi bırakır. Şekil Yuvarlatılmış Kapsül diff --git a/app/src/main/res/values-tr/input_strings.xml b/app/src/main/res/values-tr/input_strings.xml index d071c4b77e..1a3fa61cad 100644 --- a/app/src/main/res/values-tr/input_strings.xml +++ b/app/src/main/res/values-tr/input_strings.xml @@ -1,5 +1,6 @@ + Giriş profilleri Profiller Fiziksel denetleyici Ana ekran @@ -22,6 +23,7 @@ Steam menüsünü aç Steam hızlı erişimini aç Denetimi kaldır + Denetim ekle Cihaza özel düğmeler Fiziksel düğme ata Düğmeyi bırakın, ardından Düzenle, Yeniden dene veya İptal seçin. B veya Geri, bıraktıktan sonra iptal eder. diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 093ad5af33..015e080979 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. @@ -295,10 +294,14 @@ Dokunma Yan düğme Ekran üstü kontroller + Steam + QAM Otomatik, kumanda bağlı değilken kontrolleri gösterir. + Steam dokunmatik (beta) + Steam\'in dokunmatik kontrolleri sonraki Steam oturumunda başlar Steam dokunmatik düzeni Dışa aktar Görsel + Bu oyunun dokunmatik kontrollerini taşıyın, boyutlandırın veya gizleyin; Steam\'e kaydedilir Kumanda Steam\'in kumandanızı nasıl gördüğü. Sonraki oturumda uygulanır. Steam Deck kumandası @@ -425,6 +428,7 @@ Daha düşük gecikme için PulseAudio\'yu atlar. Mikrofon Sesli sohbet için. + Bu oturum için mikrofon kaydını açın veya kapatın. Mikrofon değiştirilemedi. Lütfen tekrar deneyin. Ağ Wi-Fi keşfi @@ -786,6 +790,7 @@ Klavye Gecikme Düşük gecikme modu + CPU ve pil kullanımını artırır Düşük gecikmeli kumanda Kumanda 250 Hz yerine 1000 Hz bildirir. CPU kullanımı biraz artar. Düşük gecikmeli dokunma @@ -1331,8 +1336,12 @@ Opaklık %1$d%% Düğme boyutu + Uyarlanabilir çubuklar Oyun titreşimi Çubuk ölü bölgesi + Steam düğmesi + QAM düğmesi + Klavye düğmesi VR kumandası olarak Joy-Con\'lar SteamVR çalışırken her Joy-Con bir el olur. Öne doğrultun ve yeniden ortalamak için Home veya Capture düğmesini basılı tutun. Animasyonlar @@ -1461,6 +1470,8 @@ Dokunmatik yüzey İkinci ekran kontrollerini kapat Steam menüsünü aç + Sağ dokunmatik yüzey + Sol dokunmatik yüzey Dokunmatik yüzey Klavyeyi göster Klavyeyi gizle @@ -1499,8 +1510,11 @@ Android klavyesi Gizle ✕ Ekrandaki boyut + Başlık dahil, klavyenin ekranda kapladığı oran. Opaklık + Klavyenin arkasındaki oyunu görmek için azaltın. Gizli tuşlar + Az kullandığınız tuşlar klavyede gösterilmez. Esc ve işlev tuşları sırası Ins / Del / Home / End / PgUp / PgDn Ok tuşları @@ -1713,6 +1727,8 @@ %1$s yüklendi - menüden seçin Çalışma ortamının kaldırılmasının bitmesini bekleyin Oyun + dokunmatik yüzey + doğrudan Değiştirme başarısız oldu: %1$s Profil kaydedilemedi: %1$s Masaüstü duraklatıldı @@ -1968,6 +1984,15 @@ Bir üst düzey Bir klasör seçin Bir dosya seçin + Steam mavisi + Gök mavisi + Beyaz + Mor + Yeşil + Kehribar + Kırmızı + Pembe + Gri A düğmesi B düğmesi X düğmesi @@ -2427,10 +2452,13 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Oturum ekranı + Kopyasız sunum Çözünürlük 16:9 oyun sığdırma 16:9 oyunların bu ekrana nasıl sığacağı. Sonraki oturumda. 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 @@ -3102,6 +3130,7 @@ Pro 2 için deneysel baş takibi. Parlaklık ve ses düzeyi ayarı ile ekran modu değiştirme henüz desteklenmiyor. Cardboard VR Cardboard modu + Telefon VR gözlüğü için sol ve sağ göz görüntüleri. Görüntü Sanal ekran Yan yana 3D @@ -3124,6 +3153,7 @@ Bu oturumda kullanılamaz. SteamVR yanıt vermedi; oturum günlüğünü kontrol et. Bileşenleri indir + İndirmeler Bileşenler sayfasıyla paylaşılır. Bir sonraki oyun başlatmada kullanmak için yukarıdan indirilmiş bir sürüm seç. İndirilecek sürümü seç Geliştirici Yayıncı diff --git a/app/src/main/res/values-uk/input_library.xml b/app/src/main/res/values-uk/input_library.xml index b5f93ba4b2..9993d25a57 100644 --- a/app/src/main/res/values-uk/input_library.xml +++ b/app/src/main/res/values-uk/input_library.xml @@ -75,9 +75,14 @@ Незалежна копія Починати стік від точки дотику Ховати стік, коли він не використовується + Інструменти + Авто (%1$s) + Користувацький (%1$s) Зберегти як новий профіль Керування профілю + Профіль Жести тачпада миші + Якщо призначено вказівнику миші: торкніться для кліку, утримуйте для перетягування та прокручуйте двома пальцями. Для %1$s задано перевизначення швидкого меню. Виберіть «Авто», щоб використати профіль за замовчуванням і всі три збережені частини. Введення DroidDeck Утримується, поки стік відхилено в будь-якому напрямку: натискання вище 55%, відпускання нижче 35%. Використовуйте «Клавіші напрямків», щоб призначити кожен напрямок окремо. Команди DroidDeck спрацьовують раз на відхилення. Натискання стіка налаштовується окремо. @@ -99,11 +104,17 @@ У режимі Steam. Утримання «Назад» також відкриває швидкий доступ. Відновити типове Віртуальний контролер + Тип контролера, який бачать Steam або гра. Сенсорний екран + Як обробляються дотики на екрані гри. Кнопки профілю зберігають призначені дії. Курсор дотику + Показувати вказівник для прямих дотиків на екрані гри. Торкнутися й утримувати + Дія миші при утриманні пальця на екрані гри. Натискання кнопки «Назад» + Перша дія: одне натискання. Друга дія: подвійне натискання. Кнопка-перемикач + Торкніться, щоб утримувати, торкніться ще раз, щоб відпустити. Відкриття меню або зміна профілю відпускає кнопку. Форма Заокруглена Капсула diff --git a/app/src/main/res/values-uk/input_strings.xml b/app/src/main/res/values-uk/input_strings.xml index 456963a24a..665ae8d468 100644 --- a/app/src/main/res/values-uk/input_strings.xml +++ b/app/src/main/res/values-uk/input_strings.xml @@ -1,5 +1,6 @@ + Профілі введення Профілі Фізичний контролер Головний екран @@ -22,6 +23,7 @@ Відкрити меню Steam Відкрити швидкий доступ Steam Видалити елемент + Додати елемент Кнопки конкретного пристрою Призначити фізичну кнопку Відпустіть кнопку, потім виберіть «Редагувати», «Повторити» або «Скасувати». B або «Назад» скасовує після відпускання. diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index cf87b41037..0ae16d9a5d 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 і робочого столу. Налаштовуються на сторінці «Компоненти». @@ -295,10 +294,14 @@ Сенсорне введення Бічна кнопка Екранне керування + Steam + QAM «Авто» показує екранне керування, коли контролер не під’єднано. + Сенсорне керування Steam (бета) + Сенсорне керування Steam увімкнеться з наступним сеансом Steam Розкладка сенсорного керування Steam Експорт Зображення + Переміщуйте, змінюйте розмір або приховуйте сенсорні елементи керування цієї гри; зберігається в Steam Контролер Яким Steam бачить ваш контролер. Застосовується в наступному сеансі. Контролер Steam Deck @@ -427,6 +430,7 @@ Обходить PulseAudio для меншої затримки. Мікрофон Для голосового чату. + Увімкнути або вимкнути захоплення мікрофона в цьому сеансі. Не вдалося змінити мікрофон. Спробуйте ще раз. Мережа Пошук Wi-Fi @@ -790,6 +794,7 @@ Клавіатура Затримка Режим низької затримки + Збільшує навантаження на CPU та витрату батареї Контролер із низькою затримкою Контролер звітує на 1000 Hz замість 250 Hz. Трохи більше навантаження на CPU. Дотик із низькою затримкою @@ -1353,8 +1358,12 @@ Непрозорість %1$d%% Розмір кнопок + Адаптивні стики Вібрація гри Мертва зона стіка + Кнопка Steam + Кнопка QAM + Кнопка клавіатури Joy-Con як VR-контролери Поки працює SteamVR, кожен Joy-Con стає рукою. Спрямуйте його вперед і утримуйте Home або Capture, щоб знову його відцентрувати. Анімації @@ -1485,6 +1494,8 @@ Трекпад Закрити керування на другому екрані Відкрити меню Steam + Правий трекпад + Лівий трекпад Трекпад Показати клавіатуру Сховати клавіатуру @@ -1523,8 +1534,11 @@ Клавіатура Android Сховати ✕ Розмір на екрані + Частка екрана, яку займає клавіатура, включно з заголовком. Непрозорість + Зменште, щоб бачити гру під клавіатурою. Приховані клавіші + Клавіші, якими ви рідко користуєтеся, не відображаються на клавіатурі. Esc і рядок функційних клавіш Ins / Del / Home / End / PgUp / PgDn Клавіші зі стрілками @@ -1753,6 +1767,8 @@ Встановлено %1$s — виберіть його в меню Дочекайтеся завершення видалення середовища Гра + тачпад + прямий Не вдалося замінити: %1$s Не вдалося зберегти профіль: %1$s Робочий стіл призупинено @@ -2026,6 +2042,15 @@ На рівень вище Виберіть папку Виберіть файл + Синій Steam + Небесний + Білий + Фіолетовий + Зелений + Бурштиновий + Червоний + Рожевий + Сірий Кнопка A Кнопка B Кнопка X @@ -2487,10 +2512,13 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Дисплей сеансу + Показ без копіювання Роздільна здатність Вписування гри 16:9 Як ігри 16:9 вписуються в цей дисплей. З наступного сеансу. Виберіть «Під екран» або власний розмір, вужчий за 16:9. + Обходити виріз + Не виводить зображення під виріз камери. Застосовується після повернення до сесії. Зберігати пропорції Розтягнути на весь дисплей Масштабування зображення @@ -3173,6 +3201,7 @@ Експериментальне відстеження рухів голови для Pro 2. Налаштування яскравості й гучності та перемикання режимів відображення ще не підтримуються. Cardboard VR Режим Cardboard + Зображення для лівого й правого ока для VR-окулярів під телефон. Зображення Віртуальний екран Стереопара 3D @@ -3195,6 +3224,7 @@ Недоступно в цій сесії. SteamVR не відповідає; перевірте журнал сесії. Завантажити компоненти + Завантаження спільні зі сторінкою «Компоненти». Виберіть вище завантажену версію, щоб використати її під час наступного запуску гри. Виберіть версію для завантаження Розробник Видавець diff --git a/app/src/main/res/values-vi/input_library.xml b/app/src/main/res/values-vi/input_library.xml index c225092768..71e6b034cc 100644 --- a/app/src/main/res/values-vi/input_library.xml +++ b/app/src/main/res/values-vi/input_library.xml @@ -75,9 +75,14 @@ Bản sao độc lập Bắt đầu cần tại điểm chạm Ẩn cần khi không dùng + Công cụ + Tự động (%1$s) + Tùy chỉnh (%1$s) Lưu thành hồ sơ mới Điều khiển hồ sơ + Hồ sơ Cử chỉ bàn di chuột + Khi gán cho con trỏ chuột: chạm để nhấp, giữ để kéo và cuộn bằng hai ngón. %1$s có ghi đè menu nhanh. Chọn Tự động ở đó để dùng hồ sơ mặc định và cả ba phần đã lưu. Đầu vào DroidDeck Giữ khi cần được đẩy theo mọi hướng: nhấn trên 55%, nhả dưới 35%. Dùng Phím hướng để gán từng hướng riêng. Lệnh DroidDeck chạy một lần mỗi lần lệch. Nhấp cần được cấu hình riêng. @@ -99,11 +104,17 @@ Ở chế độ Steam. Giữ Quay lại cũng mở truy cập nhanh. Khôi phục mặc định 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 + Cách xử lý các lần chạm trên màn hình trò chơi. Các nút hồ sơ giữ hành động đã gán. Con trỏ chạm + Hiện con trỏ cho các lần chạm trực tiếp trên màn hình trò chơi. Chạm và giữ + Hành động chuột khi giữ ngón tay trên màn hình trò chơi. Chạm nút Quay lại + Hành động thứ nhất: một lần chạm. Hành động thứ hai: hai lần chạm. Nút bật/tắt + Chạm để giữ, chạm lại để nhả. Mở menu hoặc đổi hồ sơ sẽ nhả nút. Hình dạng Bo tròn Viên nang diff --git a/app/src/main/res/values-vi/input_strings.xml b/app/src/main/res/values-vi/input_strings.xml index c7dcbbc482..3b2a6cff52 100644 --- a/app/src/main/res/values-vi/input_strings.xml +++ b/app/src/main/res/values-vi/input_strings.xml @@ -1,5 +1,6 @@ + Hồ sơ đầu vào Hồ sơ Tay cầm vật lý Màn hình chính @@ -22,6 +23,7 @@ Mở menu Steam Mở truy cập nhanh Steam Xóa điều khiển + Thêm điều khiển Nút riêng cho thiết bị Gán một nút vật lý Nhả nút, sau đó chọn Sửa, Thử lại hoặc Hủy. B hoặc Quay lại sẽ hủy sau khi nhả. diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 5b7328556e..a2601eb6c1 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. @@ -295,10 +294,14 @@ Chạm Nút bên Điều khiển trên màn hình + Steam + QAM Tự động hiện các nút điều khiển khi không có tay cầm kết nối. + Chạm Steam (beta) + Các nút chạm của Steam bắt đầu từ phiên Steam kế tiếp Bố cục chạm Steam Xuất Hình ảnh + Di chuyển, đổi kích thước hoặc ẩn các nút chạm của game này; được lưu vào Steam Tay cầm Cách Steam nhận dạng tay cầm của bạn. Áp dụng từ phiên sau. Tay cầm Steam Deck @@ -424,6 +427,7 @@ Bỏ qua PulseAudio để giảm độ trễ. Micro Dùng cho chat bằng giọng nói. + Bật hoặc tắt thu micro cho phiên này. Không thể thay đổi micro. Vui lòng thử lại. Mạng Dò tìm Wi-Fi @@ -784,6 +788,7 @@ Bàn phím Độ trễ Chế độ độ trễ thấp + Tăng mức dùng CPU và pin Tay cầm độ trễ thấp Tay cầm báo cáo ở 1000 Hz thay vì 250 Hz. Tốn thêm một chút CPU. Cảm ứng độ trễ thấp @@ -1333,8 +1338,12 @@ Độ mờ %1$d%% Kích thước nút + Cần thích ứng Rung khi chơi game Vùng chết của cần điều khiển + Nút Steam + Nút QAM + Nút bàn phím Dùng Joy-Con làm tay cầm VR Khi SteamVR đang chạy, mỗi Joy-Con trở thành một bàn tay. Hướng nó về phía trước rồi giữ Home hoặc Capture để căn giữa lại. Hiệu ứng chuyển động @@ -1462,6 +1471,8 @@ Trackpad Đóng điều khiển màn hình phụ Mở menu Steam + Trackpad phải + Trackpad trái Trackpad Hiện bàn phím Ẩn bàn phím @@ -1500,8 +1511,11 @@ Bàn phím Android Ẩn ✕ Kích thước trên màn hình + Tỷ lệ màn hình mà bàn phím chiếm, bao gồm cả thanh tiêu đề. Độ mờ + Giảm giá trị này để thấy game phía sau bàn phím. Phím ẩn + Những phím ít dùng sẽ không xuất hiện trên bàn phím. Esc và hàng phím chức năng Ins / Del / Home / End / PgUp / PgDn Phím mũi tên @@ -1706,6 +1720,8 @@ Đã cài %1$s - chọn nó trong menu Chờ việc gỡ runtime hoàn tất Game + touchpad + trực tiếp Thay thất bại: %1$s Lưu hồ sơ thất bại: %1$s Desktop đang tạm dừng @@ -1952,6 +1968,15 @@ Lên một cấp Chọn một thư mục Chọn một tệp + Xanh Steam + Xanh da trời + Trắng + Tím + Xanh lá + Hổ phách + Đỏ + Hồng + Xám Nút A Nút B Nút X @@ -2410,10 +2435,13 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Hiển thị phiên + Hiển thị không sao chép Độ phân giải Khớp game 16:9 Cách game 16:9 khớp với màn hình này. Từ phiên sau. 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 @@ -3084,6 +3112,7 @@ Theo dõi chuyển động đầu thử nghiệm cho Pro 2. Chưa hỗ trợ điều chỉnh độ sáng, âm lượng và chuyển chế độ hiển thị. Cardboard VR Chế độ Cardboard + Hình cho mắt trái và mắt phải dành cho kính VR điện thoại. Hình ảnh Màn hình ảo 3D cạnh nhau @@ -3106,6 +3135,7 @@ Không khả dụng trong phiên này. SteamVR không phản hồi; hãy xem nhật ký phiên. Tải thành phần + Bản tải xuống được dùng chung với trang Components. Chọn một phiên bản đã tải ở trên để dùng vào lần khởi chạy game kế tiếp. Chọn phiên bản để tải Nhà phát triển Nhà phát hành 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 ed67f34cf7..921f57c80d 100644 --- a/app/src/main/res/values-zh-rCN/input_library.xml +++ b/app/src/main/res/values-zh-rCN/input_library.xml @@ -75,9 +75,14 @@ 独立副本 从按下位置开始 不使用时隐藏摇杆 + 工具 + 自动 (%1$s) + 自定义 (%1$s) 另存为新配置 配置控制 + 配置 鼠标触控板手势 + 绑定到鼠标指针时:轻点点击、按住拖动、双指滚动。 %1$s 有快捷菜单覆盖。在那里选「自动」会使用它的默认配置和全部三个已保存部分。 DroidDeck 输入 摇杆朝任意方向推动期间保持:超过 55% 时按下,低于 35% 时松开。用「方向键」逐方向指定。DroidDeck 动作每次推动只执行一次。摇杆点击单独设置。 @@ -99,11 +104,17 @@ Steam 模式下。按住返回也会打开快捷菜单。 恢复默认 虚拟手柄 + Steam 或游戏看到的手柄类型。 触摸屏 + 游戏画面上的触摸如何处理。配置里的按键保持各自指定的动作。 触摸光标 + 在游戏画面上直接触摸时显示指针。 触摸并按住 + 手指按住游戏画面时的鼠标动作。 返回键点击 + 第一个动作:单击。第二个动作:双击。 开关按键 + 点一下按住,再点一下松开。打开菜单或切换配置会松开按键。 形状 圆角 胶囊 diff --git a/app/src/main/res/values-zh-rCN/input_strings.xml b/app/src/main/res/values-zh-rCN/input_strings.xml index 752003c421..dabfb3b4ee 100644 --- a/app/src/main/res/values-zh-rCN/input_strings.xml +++ b/app/src/main/res/values-zh-rCN/input_strings.xml @@ -1,5 +1,6 @@ + 输入配置 配置 物理手柄 主屏 @@ -22,6 +23,7 @@ 打开 Steam 菜单 打开 Steam 快捷菜单 移除控件 + 添加控件 本设备专用按键 指定物理按键 松开按键,然后选择编辑、重试或取消。松开后按 B 或返回可取消。 diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index eeddf20d4c..802aa28274 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 和桌面共享。在“组件”页面设置。 @@ -295,10 +294,14 @@ 触摸 侧键 屏幕控制 + Steam + QAM 自动模式会在未连接手柄时显示屏幕控制。 + Steam 触控(测试版) + Steam 的触控按键将从下次 Steam 会话开始生效 Steam 触控布局 导出 图片 + 移动、调整大小或隐藏此游戏的触控按键;保存到 Steam 手柄 决定 Steam 把你的手柄识别为哪种类型,将在下次会话生效。 Steam Deck 手柄 @@ -424,6 +427,7 @@ 绕过 PulseAudio 以降低延迟。 麦克风 用于语音聊天。 + 为此会话开启或关闭麦克风采集。 无法更改麦克风设置。请重试。 网络 Wi-Fi 网络发现 @@ -784,6 +788,7 @@ 键盘 延迟 低延迟模式 + 会增加 CPU 和电池消耗 低延迟手柄 手柄以 1000 Hz 而非 250 Hz 上报。CPU 占用略高。 低延迟触控 @@ -1416,8 +1421,12 @@ 不透明度 %1$d%% 按钮大小 + 自适应摇杆 游戏震动 摇杆死区 + Steam 按钮 + QAM 按钮 + 键盘按钮 将 Joy-Con 用作 VR 手柄 SteamVR 运行时,每个 Joy-Con 都会成为一只手。将其指向前方并按住 HOME 键或截图键即可重新居中。 动画 @@ -1545,6 +1554,8 @@ 触控板 关闭副屏控制 打开 Steam 菜单 + 右触控板 + 左触控板 触控板 显示键盘 隐藏键盘 @@ -1583,8 +1594,11 @@ Android 键盘 隐藏 ✕ 屏幕占比 + 键盘占屏幕的比例,含标题栏 不透明度 + 调低即可看见键盘后的游戏 隐藏按键 + 很少用的按键不显示在键盘上 Esc 和功能键行 Ins / Del / Home / End / PgUp / PgDn 方向键 @@ -1783,6 +1797,8 @@ 已安装 %1$s — 请在菜单中选择它 请等待运行时移除完成 游戏 + 触控板 + 直接 替换失败:%1$s 配置档案保存失败:%1$s 桌面已暂停 @@ -2029,6 +2045,15 @@ 返回上一级 选择文件夹 选择文件 + Steam 蓝 + 天蓝 + 白色 + 紫罗兰 + 绿色 + 琥珀 + 红色 + 粉色 + 灰色 A 键 B 键 X 键 @@ -2487,10 +2512,13 @@ Android + Linux %1$s。%2$s\n\n%3$s 会话显示 + 零拷贝呈现 分辨率 16:9 游戏适配 16:9 游戏如何适配此屏幕。下次会话生效。 请选择“匹配屏幕”或比 16:9 更窄的自定义尺寸。 + 避开刘海 + 让画面避开摄像头挖孔区域。返回会话时生效。 保持比例 拉伸至屏幕 画面缩放 @@ -3092,6 +3120,7 @@ %1$d 分钟 Cardboard VR Cardboard 模式 + 为手机 VR 眼镜提供左右眼画面。 画面 虚拟屏幕 左右并排 3D @@ -3114,6 +3143,7 @@ 此会话中不可用。 SteamVR 未响应;请查看会话日志。 下载组件 + 下载内容与“组件”页面共享。在上方选择已下载的版本,即可在下次启动游戏时使用。 选择要下载的版本 画面位置 置顶 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 05774dac0e..d997b2e0ca 100644 --- a/app/src/main/res/values-zh-rHK/input_library.xml +++ b/app/src/main/res/values-zh-rHK/input_library.xml @@ -75,9 +75,14 @@ 獨立副本 從按下位置開始 不使用時隱藏搖桿 + 工具 + 自動 (%1$s) + 自訂 (%1$s) 另存為新設定檔 設定檔控制 + 設定檔 滑鼠觸控板手勢 + 綁定到滑鼠指標時:輕點點擊、按住拖曳、雙指捲動。 %1$s 有快速選單覆寫。在那裡選「自動」會使用它的預設設定檔與全部三個已儲存部分。 DroidDeck 輸入 搖桿朝任意方向推動期間保持:超過 55% 時按下,低於 35% 時放開。用「方向鍵」逐方向指定。DroidDeck 動作每次推動只執行一次。搖桿點擊另外設定。 @@ -99,11 +104,17 @@ Steam 模式下。按住返回也會開啟快速選單。 恢復預設 虛擬控制器 + Steam 或遊戲看到的控制器類型。 觸控螢幕 + 遊戲畫面上的觸碰如何處理。設定檔裡的按鍵保持各自指定的動作。 觸碰游標 + 在遊戲畫面上直接觸碰時顯示指標。 觸碰並按住 + 手指按住遊戲畫面時的滑鼠動作。 返回鍵點擊 + 第一個動作:單擊。第二個動作:雙擊。 開關按鍵 + 點一下按住,再點一下放開。開啟選單或切換設定檔會放開按鍵。 形狀 圓角 膠囊 diff --git a/app/src/main/res/values-zh-rHK/input_strings.xml b/app/src/main/res/values-zh-rHK/input_strings.xml index 2ba76aa42e..713cc729e8 100644 --- a/app/src/main/res/values-zh-rHK/input_strings.xml +++ b/app/src/main/res/values-zh-rHK/input_strings.xml @@ -1,5 +1,6 @@ + 輸入設定檔 設定檔 實體控制器 主螢幕 @@ -22,6 +23,7 @@ 開啟 Steam 選單 開啟 Steam 快速選單 移除控制項 + 新增控制項 此裝置專用按鍵 指定實體按鍵 放開按鍵,然後選擇編輯、重試或取消。放開後按 B 或返回可取消。 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index a194530d52..b7b9481b52 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 和桌面共用,請在「組件」頁面設定。 @@ -295,10 +294,14 @@ 觸控 側鍵 螢幕控制 + Steam + QAM 「自動」會在未連接控制器時顯示螢幕控制。 + Steam 觸控(測試版) + Steam 的觸控控制會在下次 Steam 會話啟用 Steam 觸控佈局 匯出 圖片 + 移動、調整大小或隱藏此遊戲的觸控控制;會儲存至 Steam 控制器 Steam 如何識別你的控制器。下次會話生效。 Steam Deck 控制器 @@ -424,6 +427,7 @@ 繞過 PulseAudio 以減低延遲。 麥克風 用於語音聊天。 + 為此會話開啟或關閉麥克風收音。 無法變更麥克風設定,請再試一次。 網絡 Wi-Fi 探索 @@ -784,6 +788,7 @@ 鍵盤 延遲 低延遲模式 + 會增加 CPU 和電池用量 低延遲控制器 控制器以 1000 Hz 而非 250 Hz 回報。CPU 使用率略高。 低延遲觸控 @@ -1332,8 +1337,12 @@ 不透明度 %1$d%% 按鍵大小 + 自動調整搖桿 遊戲震動 搖桿死區 + Steam 按鈕 + QAM 按鈕 + 鍵盤按鈕 將 Joy-Con 用作 VR 控制器 SteamVR 執行時,每個 Joy-Con 都會變成一隻手。將它指向前方並按住 HOME 鍵或擷取鍵,即可重新置中。 動畫 @@ -1461,6 +1470,8 @@ 觸控板 關閉第二螢幕控制 開啟 Steam 選單 + 右側觸控板 + 左側觸控板 觸控板 顯示鍵盤 隱藏鍵盤 @@ -1499,8 +1510,11 @@ Android 鍵盤 隱藏 ✕ 畫面佔比 + 鍵盤佔用的畫面比例,包括標題列。 不透明度 + 調低即可看到鍵盤後方的遊戲畫面。 隱藏按鍵 + 少用的按鍵不會顯示在鍵盤上。 Esc 與功能鍵列 Ins / Del / Home / End / PgUp / PgDn 方向鍵 @@ -1705,6 +1719,8 @@ 已安裝 %1$s - 請在選單中選擇 請等待運行環境移除完成 遊戲 + 觸控板 + 直接 替換失敗:%1$s 設定檔儲存失敗:%1$s 桌面已暫停 @@ -1951,6 +1967,15 @@ 返回上一層 選擇資料夾 選擇檔案 + Steam 藍 + 天藍 + 白色 + 紫羅蘭 + 綠色 + 琥珀色 + 紅色 + 粉紅色 + 灰色 A 鍵 B 鍵 X 鍵 @@ -2407,10 +2432,13 @@ ANDROID + LINUX %1$s。%2$s\n\n%3$s 會話顯示 + 零複製呈現 解像度 16:9 遊戲顯示方式 16:9 遊戲如何配合此螢幕。下次會話生效。 請選擇「配合螢幕」或比 16:9 更窄的自訂尺寸。 + 避開瀏海 + 讓畫面避開鏡頭挖孔區域。返回工作階段時生效。 保持比例 拉伸至螢幕 畫面縮放 @@ -3089,6 +3117,7 @@ %1$d 分鐘 Cardboard VR Cardboard 模式 + 為手機 VR 眼鏡提供左右眼畫面。 畫面 虛擬螢幕 左右並排 3D @@ -3111,6 +3140,7 @@ 此工作階段中無法使用。 SteamVR 沒有回應;請查看工作階段日誌。 下載元件 + 下載內容與「元件」頁面共用。在上方選擇已下載的版本,即可在下次啟動遊戲時使用。 選擇要下載的版本 畫面位置 置頂 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 05774dac0e..d997b2e0ca 100644 --- a/app/src/main/res/values-zh-rTW/input_library.xml +++ b/app/src/main/res/values-zh-rTW/input_library.xml @@ -75,9 +75,14 @@ 獨立副本 從按下位置開始 不使用時隱藏搖桿 + 工具 + 自動 (%1$s) + 自訂 (%1$s) 另存為新設定檔 設定檔控制 + 設定檔 滑鼠觸控板手勢 + 綁定到滑鼠指標時:輕點點擊、按住拖曳、雙指捲動。 %1$s 有快速選單覆寫。在那裡選「自動」會使用它的預設設定檔與全部三個已儲存部分。 DroidDeck 輸入 搖桿朝任意方向推動期間保持:超過 55% 時按下,低於 35% 時放開。用「方向鍵」逐方向指定。DroidDeck 動作每次推動只執行一次。搖桿點擊另外設定。 @@ -99,11 +104,17 @@ Steam 模式下。按住返回也會開啟快速選單。 恢復預設 虛擬控制器 + Steam 或遊戲看到的控制器類型。 觸控螢幕 + 遊戲畫面上的觸碰如何處理。設定檔裡的按鍵保持各自指定的動作。 觸碰游標 + 在遊戲畫面上直接觸碰時顯示指標。 觸碰並按住 + 手指按住遊戲畫面時的滑鼠動作。 返回鍵點擊 + 第一個動作:單擊。第二個動作:雙擊。 開關按鍵 + 點一下按住,再點一下放開。開啟選單或切換設定檔會放開按鍵。 形狀 圓角 膠囊 diff --git a/app/src/main/res/values-zh-rTW/input_strings.xml b/app/src/main/res/values-zh-rTW/input_strings.xml index 2ba76aa42e..713cc729e8 100644 --- a/app/src/main/res/values-zh-rTW/input_strings.xml +++ b/app/src/main/res/values-zh-rTW/input_strings.xml @@ -1,5 +1,6 @@ + 輸入設定檔 設定檔 實體控制器 主螢幕 @@ -22,6 +23,7 @@ 開啟 Steam 選單 開啟 Steam 快速選單 移除控制項 + 新增控制項 此裝置專用按鍵 指定實體按鍵 放開按鍵,然後選擇編輯、重試或取消。放開後按 B 或返回可取消。 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 82c63ad01e..945485063e 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 和桌面共用。請在「元件」頁面設定。 @@ -295,10 +294,14 @@ 觸控 側鍵 螢幕控制 + Steam + QAM 自動模式會在未連接控制器時顯示螢幕控制。 + Steam 觸控(測試版) + Steam 觸控控制會在下次 Steam 工作階段啟用 Steam 觸控版面配置 匯出 圖片 + 移動、調整大小或隱藏這款遊戲的觸控控制;會儲存到 Steam 控制器 Steam 辨識你的控制器的方式。下次工作階段生效。 Steam Deck 控制器 @@ -424,6 +427,7 @@ 繞過 PulseAudio 以降低延遲。 麥克風 用於語音聊天。 + 為此工作階段開啟或關閉麥克風收音。 無法變更麥克風設定,請再試一次。 網路 Wi-Fi 探索 @@ -784,6 +788,7 @@ 鍵盤 延遲 低延遲模式 + 會增加 CPU 和電池用量 低延遲控制器 控制器以 1000 Hz 而非 250 Hz 回報。CPU 使用率略高。 低延遲觸控 @@ -1332,8 +1337,12 @@ 不透明度 %1$d%% 按鍵大小 + 自適應搖桿 遊戲震動 搖桿死區 + Steam 按鈕 + QAM 按鈕 + 鍵盤按鈕 將 Joy-Con 當作 VR 控制器 SteamVR 執行時,每個 Joy-Con 都會變成一隻手。將它指向前方並按住 HOME 鍵或擷取鍵,即可重新置中。 動畫 @@ -1461,6 +1470,8 @@ 觸控板 關閉第二螢幕控制 開啟 Steam 選單 + 右側觸控板 + 左側觸控板 觸控板 顯示鍵盤 隱藏鍵盤 @@ -1499,8 +1510,11 @@ Android 鍵盤 隱藏 ✕ 在螢幕上的大小 + 鍵盤佔用螢幕的比例,包含標題列。 不透明度 + 調低即可看見鍵盤後方的遊戲畫面。 隱藏按鍵 + 少用的按鍵不會顯示在鍵盤上。 Esc 與功能鍵列 Ins / Del / Home / End / PgUp / PgDn 方向鍵 @@ -1705,6 +1719,8 @@ 已安裝 %1$s - 請在選單中選擇 請等待執行環境移除完成 遊戲 + 觸控板 + 直接 換入失敗:%1$s 設定檔儲存失敗:%1$s 桌面已暫停 @@ -1951,6 +1967,15 @@ 返回上一層 選擇資料夾 選擇檔案 + Steam 藍 + 天藍 + 白色 + 紫羅蘭 + 綠色 + 琥珀 + 紅色 + 粉紅 + 灰色 A 按鈕 B 按鈕 X 按鈕 @@ -2407,10 +2432,13 @@ ANDROID + LINUX %1$s。%2$s\n\n%3$s 工作階段顯示 + 零複製呈現 解析度 16:9 遊戲顯示方式 16:9 遊戲如何配合此螢幕。下次工作階段生效。 請選擇「符合螢幕」或比 16:9 更窄的自訂尺寸。 + 避開瀏海 + 讓畫面避開鏡頭挖孔區域。返回工作階段時生效。 維持比例 延展至螢幕 畫面縮放 @@ -3089,6 +3117,7 @@ %1$d 分鐘 Cardboard VR Cardboard 模式 + 為手機 VR 眼鏡提供左右眼畫面。 畫面 虛擬螢幕 左右並排 3D @@ -3111,6 +3140,7 @@ 這個工作階段無法使用。 SteamVR 沒有回應;請查看工作階段記錄。 下載元件 + 下載內容與「元件」頁面共用。在上方選擇已下載的版本,即可在下次啟動遊戲時使用。 選擇要下載的版本 畫面位置 置頂 diff --git a/app/src/main/res/values/input_library.xml b/app/src/main/res/values/input_library.xml index 3217d0b9bb..b2969a042b 100644 --- a/app/src/main/res/values/input_library.xml +++ b/app/src/main/res/values/input_library.xml @@ -75,9 +75,14 @@ Independent copy Start stick at touch position Hide stick when not in use + Tools + Auto (%1$s) + Custom (%1$s) Save as new profile Profile controls + Profile Mouse touchpad gestures + When assigned to the mouse pointer: tap to click, hold to drag, and scroll with two fingers. %1$s has a quick-menu override. Select Auto there to use its default profile and all three saved parts. DroidDeck Input Held while the stick is moved in any direction: press above 55%, release below 35%. Use Direction keys to assign each direction separately. DroidDeck commands run once per deflection. The stick click is configured separately. @@ -95,15 +100,21 @@ Home / Guide Back · single tap Back · double tap - Back · 2× Steam, 1× Desktop + Back · twice in Steam, once in Desktop In Steam mode. Holding Back also opens quick access. Restore to default Virtual controller + The controller type seen by Steam or the game. Touchscreen + How touches on the game screen are handled. Profile buttons keep their assigned actions. Touch cursor + Show a pointer for direct touches on the game screen. Touch and hold + Mouse action when holding a finger on the game screen. Back button taps + First action: single tap. Second action: double tap. Toggle button + Tap to hold, tap again to release. Opening a menu or switching profiles releases the button. Shape Rounded Pill diff --git a/app/src/main/res/values/input_strings.xml b/app/src/main/res/values/input_strings.xml index 91b85c54b3..bc18c561a7 100644 --- a/app/src/main/res/values/input_strings.xml +++ b/app/src/main/res/values/input_strings.xml @@ -1,4 +1,5 @@ + Input profiles Profiles Physical controller Main screen @@ -21,6 +22,7 @@ Open Steam menu Open Steam quick access Remove control + Add control Device-specific buttons Assign a physical button Release the button, then choose Edit, Retry, or Cancel. B or Back cancels after release. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 0267b4c098..a57afab493 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. @@ -323,38 +322,16 @@ Touch Side button On-screen controls + Steam + QAM + Rear buttons + Trackpads Auto shows the controls when no controller is connected. - On-screen controls · %1$s - Layout - Gamepad - Steam layout - Edit layout - Show - More controller settings - Shortcuts, latency and the PC keyboard - Touches elsewhere - Remap buttons - Mouse - Keep editing - Discard - Hidden %1$d - Restore - Nothing hidden. Removed controls wait here. - Options - Click - %1$s · saved for %2$s - %1$s · default for games without their own - Saved for %1$s - %1$s · shared with other games - Just this game - + New for %1$s - Default - Games with their own layout - Use default - Controller in use. Touch the screen to show the controls. + Steam touch (beta) + Steam\'s touch controls start with the next Steam session Steam touch layout Image Export + Move, resize or hide this game\'s touch controls; saved to Steam Controller How Steam sees your controller. Applies next session. Steam Deck controller @@ -481,6 +458,7 @@ Bypasses PulseAudio for lower latency. Microphone For voice chat. + Turn microphone capture on or off for this session. Could not change the microphone. Please try again. Network Wi-Fi discovery @@ -730,6 +708,9 @@ Open Quick Access Menu Previous page Next page + Arrange pages + Reset + Done Performance HUD Frame rate Battery temperature @@ -810,9 +791,12 @@ Scaling mode Scaling sharpness Edit profile + Choose which profile to change screen effects for. Current session (automatic) Reset effects + Restore the default-off effect values for this profile. Delete saved override + Remove saved effects for this game so it inherits the Default profile. Screen effects Live. Costs a little GPU time while any effect is on. Presets @@ -825,6 +809,7 @@ Fake HDR Cardboard VR Cardboard mode + Left and right eye views for a phone VR viewer. Picture Virtual screen Side-by-side 3D @@ -871,6 +856,7 @@ Keyboard Latency Low latency mode + Increases CPU and battery usage Low-latency controller Pad reports at 1000 Hz instead of 250 Hz. Slightly more CPU. Low-latency touch @@ -920,6 +906,7 @@ Original Import and delete on the Components page. Download components + Downloads are shared with the Components page. Choose a downloaded version above to use it on the next game launch. Choose a version to download Done Needs attention @@ -1048,6 +1035,8 @@ Fullscreen Hides the Android status and navigation bars Shows the Android status and navigation bars + Controller haptics + A light tick when the D-pad, A or the shoulder buttons move or select in the launcher. Touch stays silent Dual screen launcher Automatic puts the launcher sections (Steam, Library, Stores and the rest) on the second screen of handhelds with a built-in one. On uses any second display. Off keeps the launcher on one screen. Dual screen sessions @@ -1501,8 +1490,12 @@ Opacity %1$d%% Button size + Adaptive sticks Game vibration Stick dead zone + Steam button + QAM button + Keyboard button Joy-Cons as VR controllers While SteamVR runs, each Joy-Con becomes a hand. Point it ahead and hold Home or Capture to recenter it. Animations @@ -1692,6 +1685,8 @@ Trackpad Close second-screen controls Open Steam menu + Right trackpad + Left trackpad Trackpad Show keyboard Hide keyboard @@ -1730,8 +1725,11 @@ Android keyboard Hide ✕ Size on screen + Share of the screen the keyboard takes, header included. Opacity + Lower it to see the game behind the keyboard. Hidden keys + Keys you rarely use stay off the keyboard. Esc and function row Ins / Del / Home / End / PgUp / PgDn Arrow keys @@ -1951,6 +1949,8 @@ Wait for runtime removal to finish Game + touchpad + direct Swap failed: %1$s Profile save failed: %1$s The desktop is paused @@ -2221,6 +2221,15 @@ Up one level Choose a folder Choose a file + Steam blue + Sky + White + Violet + Green + Amber + Red + Pink + Gray A button B button X button @@ -2713,10 +2722,13 @@ ANDROID + LINUX %1$s. %2$s\n\n%3$s Session display + Zero-copy presentation Resolution 16:9 game fit How 16:9 games fit this display. Next session. 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 @@ -4321,6 +4333,7 @@ Steam games use the Frame Limit in Steam\'s quick menu › Performance Open Report a problem + Shares this session\'s logs for a bug report Back opens this menu · Back twice opens Steam\'s menu Back opens this menu %1$s opens this menu diff --git a/app/src/test/java/com/droiddeck/launcher/input/ControlsChoiceTest.kt b/app/src/test/java/com/droiddeck/launcher/input/ControlsChoiceTest.kt deleted file mode 100644 index d38ce28925..0000000000 --- a/app/src/test/java/com/droiddeck/launcher/input/ControlsChoiceTest.kt +++ /dev/null @@ -1,125 +0,0 @@ -package com.droiddeck.launcher.input - -import android.content.Context -import androidx.compose.runtime.MutableState -import com.droiddeck.launcher.R -import com.droiddeck.launcher.SessionActivity -import com.droiddeck.launcher.session.SessionService -import com.droiddeck.launcher.session.SessionState -import org.junit.After -import org.junit.Assert.* -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith -import org.robolectric.Robolectric -import org.robolectric.RobolectricTestRunner -import org.robolectric.RuntimeEnvironment -import org.robolectric.annotation.Config -import org.robolectric.util.ReflectionHelpers - -@RunWith(RobolectricTestRunner::class) -@Config(sdk = [34], shadows = [JoyConPadTest.RecordingWriter::class]) -class ControlsChoiceTest { - private val context: Context get() = RuntimeEnvironment.getApplication() - - @Before fun reset() { - for (name in listOf("session", "game-controls", "input-profiles", "input-surfaces", "controller")) context.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().commit() - } - - @After fun mode() { SessionState.mode = SessionService.MODE_STEAM } - - private fun bigSticks(): String { - val id = "big-sticks" - InputLibraries.update(context) { library -> - val stick = InputSurfaceElement(InputControl.A, .4f, .4f, .1f, .1f, "jump", InputElementKind.BUTTON, "Jump") - library.withLayout(SavedInputLayout(id, "Big sticks", listOf(stick), screen = InputLayoutScreen.MAIN)) - .withPreset(SavedInputBindings("big-sticks.actions", "Big sticks", false, id, elements = mapOf("jump" to InputAction.Keys(listOf(57))))) - } - return id - } - - @Test fun aNewLayoutForOneGameCopiesTheLayoutAndItsActionsForThatGameOnly() { - val source = bigSticks() - ControlsChoice.choose(context, null, source, desktop = false) - val (layoutId, bindingsId) = ControlsChoice.newForGame(context, 7, "Castle Crashers", desktop = false) - val library = InputLibraries.read(context) - val copy = library.layouts.first { it.id == layoutId } - assertEquals("Castle Crashers", copy.name) - assertEquals(library.layouts.first { it.id == source }.elements, copy.elements) - assertEquals(InputAction.Keys(listOf(57)), library.preset(bindingsId).elements["jump"]) - assertEquals(layoutId, library.preset(bindingsId).layoutId) - assertEquals(bindingsId, GameControls.bindings(context, 7)) - assertEquals(layoutId, ControlsChoice.current(context, 7, steamMode = true)) - assertEquals(source, ControlsChoice.current(context, 8, steamMode = true)) - assertEquals(source, ControlsChoice.current(context, null, steamMode = true)) - assertEquals(Triple(InputProfile.GAME, layoutId, bindingsId), ControlsChoice.editTarget(context, 7, desktop = false)) - } - - @Test fun aCopyOfTheBuiltInGamepadKeepsFollowingTheKit() { - val extra = InputSurfaceElement(InputControl.A, .45f, .1f, .08f, .1f, "extra", InputElementKind.BUTTON, "Extra") - InputLibraries.update(context) { it.withLayout(it.layouts.first { l -> l.id == InputLibraries.OVERLAY }.copy(elements = listOf(extra), aspect = 2f)) } - val (layoutId, _) = ControlsChoice.newForGame(context, 7, "Castle Crashers", desktop = false) - val copy = InputLibraries.read(context).layouts.first { it.id == layoutId } - assertEquals(InputLibraries.OVERLAY, copy.origin) - assertTrue(OnScreenLayout.generated(copy)) - assertEquals(listOf(extra), copy.elements) - assertEquals(InputLibraries.OVERLAY, ControlsChoice.current(context, null, steamMode = false)) - } - - @Test fun onlyAGameWithItsOwnUnsharedLayoutEditsWithoutChangingOthers() { - assertFalse(ControlsChoice.shared(context, null)) - assertTrue(ControlsChoice.shared(context, 7)) - ControlsChoice.choose(context, 7, InputLibraries.OVERLAY, desktop = false) - assertTrue(ControlsChoice.shared(context, 7)) - ControlsChoice.newForGame(context, 7, "Castle Crashers", desktop = false) - assertFalse(ControlsChoice.shared(context, 7)) - ControlsChoice.choose(context, 8, ControlsChoice.current(context, 7, steamMode = false), desktop = false) - assertTrue(ControlsChoice.shared(context, 7)) - } - - @Test fun useDefaultForgetsTheGamesChoice() { - ControlsChoice.newForGame(context, 7, "Castle Crashers", desktop = false) - ControlsChoice.choose(context, 9, GameControls.STEAM, desktop = false, gameName = "Portal") - assertEquals(listOf("Castle Crashers" to "Castle Crashers", "Portal" to context.getString(R.string.osc_layout_steam)), - ControlsChoice.games(context).map { it.name to it.layout }) - ControlsChoice.useDefault(context, 7) - assertNull(GameControls.bindings(context, 7)) - assertEquals(InputLibraries.OVERLAY, ControlsChoice.current(context, 7, steamMode = true)) - assertEquals(listOf(9L), ControlsChoice.games(context).map { it.id }) - } - - @Test fun newIsOfferedOnlyForAGame() { - assertTrue(ControlsChoice.options(context, null, steamMode = true).none { it.first == ControlsChoice.NEW }) - assertEquals(ControlsChoice.NEW to context.getString(R.string.osc_layout_new_for, "Castle Crashers"), - ControlsChoice.options(context, 7, steamMode = true, gameName = "Castle Crashers").last()) - assertEquals(listOf(InputLibraries.OVERLAY, GameControls.STEAM), ControlsChoice.options(context, null, steamMode = true).map { it.first }.take(2)) - } - - @Test fun newForTheGameInTheControllerPageCopiesTheLayoutAndOpensTheEditorOnIt() { - SessionState.mode = SessionService.MODE_STEAM - val activity = Robolectric.buildActivity(SessionActivity::class.java).get() - ReflectionHelpers.getField>(activity, "frameGenActiveGameId\$delegate").value = 77L - ReflectionHelpers.getField>(activity, "frameGenActiveGameName\$delegate").value = "Castle Crashers" - ReflectionHelpers.callInstanceMethod(activity, "refreshInputProfile") - val options = ReflectionHelpers.getField>>>(activity, "layoutOptions\$delegate").value - assertEquals(ControlsChoice.NEW to "+ New for Castle Crashers", options.last()) - ReflectionHelpers.callInstanceMethod(activity, "chooseLayout", ReflectionHelpers.ClassParameter.from(String::class.java, ControlsChoice.NEW)) - val editor = ReflectionHelpers.getField?>>(activity, "layoutEditor\$delegate").value!! - assertEquals(GameControls.bindings(activity, 77), editor.third) - assertEquals("Castle Crashers", InputLibraries.read(activity).layouts.first { it.id == editor.second }.name) - assertEquals(editor.second, ReflectionHelpers.getField>(activity, "layoutChoice\$delegate").value) - assertEquals("Saved for Castle Crashers", ReflectionHelpers.getField(activity, "layoutEditorScope")) - assertNull(ReflectionHelpers.getField(activity, "layoutEditorSplit")) - assertNull(GameControls.bindings(activity, 78)) - assertEquals(InputLibraries.OVERLAY, ControlsChoice.current(activity, null, steamMode = true)) - } - - @Test fun aGameWithItsOwnLayoutCanGoBackToTheDefault() { - assertTrue(ControlsChoice.options(context, 42L, steamMode = true, gameName = "Game").none { it.first == ControlsChoice.DEFAULT }) - ControlsChoice.newForGame(context, 42L, "Game", desktop = false) - assertTrue(ControlsChoice.options(context, 42L, steamMode = true, gameName = "Game").first().first == ControlsChoice.DEFAULT) - ControlsChoice.choose(context, 42L, ControlsChoice.DEFAULT, desktop = false) - assertFalse(ControlsChoice.hasOwn(context, 42L)) - assertTrue(ControlsChoice.options(context, 42L, steamMode = true, gameName = "Game").none { it.first == ControlsChoice.DEFAULT }) - } -} diff --git a/app/src/test/java/com/droiddeck/launcher/input/ControlsPresenterTest.kt b/app/src/test/java/com/droiddeck/launcher/input/ControlsPresenterTest.kt deleted file mode 100644 index 053768577c..0000000000 --- a/app/src/test/java/com/droiddeck/launcher/input/ControlsPresenterTest.kt +++ /dev/null @@ -1,66 +0,0 @@ -package com.droiddeck.launcher.input - -import com.droiddeck.launcher.input.ControlsPresenter.Place -import com.droiddeck.launcher.input.ControlsPresenter.State -import com.droiddeck.launcher.input.OnScreenControls.Hidden -import com.droiddeck.launcher.session.SessionPrefs -import org.junit.Assert.* -import org.junit.Test - -class ControlsPresenterTest { - private val modes = listOf(SessionPrefs.OSC_AUTO, SessionPrefs.OSC_ALWAYS, SessionPrefs.OSC_NEVER) - - private fun states() = sequence { - for (mode in modes) for (bits in 0 until 128) { - fun bit(i: Int) = bits and (1 shl i) != 0 - yield(State(mode, desktop = bit(0), virtualPad = bit(1), covered = bit(2), controllerInUse = bit(3), hiddenByTap = bit(4), - steamLayout = bit(5), bottomScreen = bit(6))) - } - } - - @Test fun everyStateGetsThePlanTheRulesDescribe() { - for (state in states()) { - val plan = ControlsPresenter.plan(state) - val off = state.covered || !state.virtualPad || state.mode == SessionPrefs.OSC_NEVER || state.mode == SessionPrefs.OSC_AUTO && state.desktop - if (off) { - assertEquals(state.toString(), ControlsPresenter.Plan(Place.NONE), plan) - assertFalse(plan.shown) - continue - } - val place = if (state.bottomScreen) Place.BOTTOM else if (state.steamLayout) Place.STEAM else Place.MAIN - val hidden = if (state.hiddenByTap) Hidden.BY_TAP else if (state.mode == SessionPrefs.OSC_AUTO && state.controllerInUse) Hidden.BY_CONTROLLER else null - assertEquals(state.toString(), ControlsPresenter.Plan(place, hidden), plan) - assertEquals(state.toString(), hidden == null, plan.shown) - } - } - - private val playing = State(SessionPrefs.OSC_AUTO, desktop = false, virtualPad = true, covered = false, controllerInUse = false, - hiddenByTap = false, steamLayout = false, bottomScreen = false) - - @Test fun autoHidesForAControllerButAlwaysKeepsTheControls() { - assertEquals(ControlsPresenter.Plan(Place.MAIN), ControlsPresenter.plan(playing)) - assertEquals(Hidden.BY_CONTROLLER, ControlsPresenter.plan(playing.copy(controllerInUse = true)).hidden) - assertNull(ControlsPresenter.plan(playing.copy(mode = SessionPrefs.OSC_ALWAYS, controllerInUse = true)).hidden) - } - - @Test fun aTapHideWinsOverAControllerHide() { - assertEquals(Hidden.BY_TAP, ControlsPresenter.plan(playing.copy(controllerInUse = true, hiddenByTap = true)).hidden) - assertEquals(Hidden.BY_TAP, ControlsPresenter.plan(playing.copy(mode = SessionPrefs.OSC_ALWAYS, hiddenByTap = true)).hidden) - } - - @Test fun theSteamLayoutWinsOverTheBottomScreen() { - assertEquals(Place.BOTTOM, ControlsPresenter.plan(playing.copy(steamLayout = true, bottomScreen = true)).place) - assertEquals(Place.BOTTOM, ControlsPresenter.plan(playing.copy(bottomScreen = true)).place) - } - - @Test fun theDesktopShowsControlsOnlyWhenAlwaysIsChosen() { - assertEquals(Place.NONE, ControlsPresenter.plan(playing.copy(desktop = true)).place) - assertEquals(Place.MAIN, ControlsPresenter.plan(playing.copy(desktop = true, mode = SessionPrefs.OSC_ALWAYS)).place) - } - - @Test fun aCoveringPanelOrNoVirtualPadRemovesTheControls() { - assertEquals(Place.NONE, ControlsPresenter.plan(playing.copy(covered = true)).place) - assertEquals(Place.NONE, ControlsPresenter.plan(playing.copy(virtualPad = false, mode = SessionPrefs.OSC_ALWAYS)).place) - assertEquals(Place.NONE, ControlsPresenter.plan(playing.copy(mode = SessionPrefs.OSC_NEVER, steamLayout = true)).place) - } -} 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 96565c8a88..0bb917a5d7 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/InputLayoutToolsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/InputLayoutToolsTest.kt @@ -58,19 +58,25 @@ class InputLayoutToolsTest { @Test fun builtInGamepadDefaultsComeFromTheGamepadGenerator() { val library = InputLibraries.read(context) val gamepad = library.layouts.first { it.id == InputLibraries.OVERLAY } - val (defaults, aspect) = InputLibraries.defaultPositions(context, library, gamepad)!! - assertTrue(gamepad.elements.isEmpty()) - val (display, metrics) = InputLibraries.primaryDisplay(context) - val w = metrics.widthPixels; val h = metrics.heightPixels - assertEquals(KitLayout.elements(display, PadKit.current(context), w, h), defaults) - assertEquals(w.toFloat() / h, aspect, .0001f) - val copy = SavedInputLayout("mine", "Mine", origin = InputLibraries.OVERLAY) - assertEquals(defaults, InputLibraries.defaultPositions(context, library, copy)!!.first) - assertEquals(KitLayout.elements(display, PadKit.current(context), w, h, scale = 1.2f), - InputLibraries.defaultPositions(context, library, gamepad.copy(scale = 1.2f))!!.first) + val defaults = InputLibraries.defaultPositions(context, library, gamepad)!!.first + assertEquals(gamepad.elements.map { it.id }.toSet(), defaults.map { it.id }.toSet()) assertNull(InputLibraries.defaultPositions(context, library, SavedInputLayout("new", "New"))) } + @Test fun quickButtonsHideWithoutRemovingElementsAndPersist() { + val library = InputLibraries.read(context) + val gamepad = library.layouts.first { it.id == InputLibraries.OVERLAY } + assertTrue(InputCommand.KEYBOARD in gamepad.quickButtons) + assertTrue(InputLibraries.setQuickButton(context, gamepad.id, InputCommand.KEYBOARD, false)) + val hidden = InputLibraries.read(context).layouts.first { it.id == gamepad.id } + assertEquals(gamepad.elements, hidden.elements) + assertEquals(setOf(InputCommand.KEYBOARD), hidden.style.hidden) + val shown = hidden.style.shown(hidden.elements) + assertEquals(gamepad.elements.filterNot { it.id == "builtin:keyboard" }, shown) + assertTrue(InputLibraries.setQuickButton(context, gamepad.id, InputCommand.KEYBOARD, true)) + assertEquals(gamepad, InputLibraries.read(context).layouts.first { it.id == gamepad.id }) + } + @Test fun onlySteamQuickAccessAndKeyboardCanBeHidden() { val library = InputLibraries.read(context) val gamepad = library.layouts.first { it.id == InputLibraries.OVERLAY } @@ -81,6 +87,35 @@ class InputLayoutToolsTest { assertFalse(InputSurfaceStyle(hidden = QUICK_BUTTONS.toSet()).hides(custom)) } + private fun overlapping(elements: List, width: Int, height: Int): List> { + fun round(e: InputSurfaceElement) = e.buttonShape == InputButtonShape.CIRCLE && e.kind != InputElementKind.STICK + val result = mutableListOf>() + for ((i, a) in elements.withIndex()) for (b in elements.drop(i + 1)) { + val ax = (a.x + a.width / 2) * width; val ay = (a.y + a.height / 2) * height + val bx = (b.x + b.width / 2) * width; val by = (b.y + b.height / 2) * height + val hit = if (round(a) && round(b)) { + val ra = minOf(a.width * width, a.height * height) / 2; val rb = minOf(b.width * width, b.height * height) / 2 + kotlin.math.hypot(ax - bx, ay - by) < ra + rb - .5f + } else kotlin.math.abs(ax - bx) < (a.width + b.width) * width / 2 - .5f && kotlin.math.abs(ay - by) < (a.height + b.height) * height / 2 - .5f + if (hit) result += a.id to b.id + } + return result + } + + @Test fun generatedGamepadSpacingFollowsButtonSize() { + for ((w, h) in listOf(1920 to 1080, 1280 to 960)) { + val normal = LegacyGamepadLayout(context, w, h).elements() + for (scale in listOf(.8f, 1.25f)) { + val elements = LegacyGamepadLayout(context, w, h, scale = scale).elements() + assertEquals("$w x $h at $scale", emptyList>(), overlapping(elements, w, h)) + val face = listOf("legacy:a", "legacy:y").map { id -> elements.first { it.id == id } } + val faceNormal = listOf("legacy:a", "legacy:y").map { id -> normal.first { it.id == id } } + val gap = (face[0].y - face[1].y) / (faceNormal[0].y - faceNormal[1].y) + if (scale > 1f) assertTrue(gap > 1f) else assertTrue(gap < 1f) + } + } + } + @Test fun scalingACustomLayoutScalesTheGapsBetweenNeighbours() { val left = listOf(InputSurfaceElement(InputControl.A, .05f, .5f, .08f, .1f, "one", name = "One"), InputSurfaceElement(InputControl.A, .16f, .5f, .08f, .1f, "two", name = "Two")) @@ -96,4 +131,88 @@ 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) + val gamepad = InputLibraries.read(context).layouts.first { it.id == InputLibraries.OVERLAY } + val scaled = gamepad.copy(scale = 1.25f, elements = LegacyGamepadLayout(display, long, short, scale = 1.25f).regenerate(gamepad.elements)) + assertEquals(long to short, OnScreenLayout.generatedSize(context, scaled, long, short)) + val rotated = OnScreenLayout.elements(context, scaled, short, long, android.graphics.Rect()) + assertEquals(LegacyGamepadLayout(context, short, long, scale = 1.25f).regenerate(scaled.elements), rotated) + assertNull(OnScreenLayout.generatedSize(context, scaled.copy(scale = 1f), long, short)) + InputLibraries.update(context) { it.withLayout(scaled) } + assertEquals(1.25f, InputLibraries.read(context).layouts.first { it.id == gamepad.id }.scale) + } + + private fun assertCross(elements: List, width: Int, height: Int, ids: List) { + val (up, right, down, left) = ids.map { id -> elements.first { it.id == id }.let { (it.x + it.width / 2) * width to (it.y + it.height / 2) * height } } + val cx = (up.first + right.first + down.first + left.first) / 4 + val cy = (up.second + right.second + down.second + left.second) / 4 + assertEquals(up.first, down.first, 1f) + assertEquals(left.second, right.second, 1f) + assertTrue(up.second < down.second && left.first < right.first) + val reach = listOf(up, right, down, left).map { kotlin.math.hypot(it.first - cx, it.second - cy) } + reach.forEach { assertEquals(reach[0], it, 1f) } + } + + private fun assertGamepadShape(elements: List, width: Int, height: Int, label: String) { + assertCross(elements, width, height, listOf("legacy:y", "legacy:b", "legacy:a", "legacy:x")) + assertCross(elements, width, height, listOf("legacy:up", "legacy:right", "legacy:down", "legacy:left")) + assertEquals(label, emptyList>(), overlapping(elements, width, height)) + } + + private fun assertStickView(elements: List, width: Int, height: Int, label: String) { + for (control in listOf(InputControl.LS, InputControl.RS)) { + val stick = elements.first { it.control == control } + assertTrue("$label ${stick.id} keeps its widened travel width", stick.width * width >= stick.height * height * 1.25f - 1f) + assertTrue("$label ${stick.id} stays on screen", stick.x >= 0f && stick.x + stick.width <= 1.0001f) + } + } + + @Test fun sticksKeepTheirFullViewAtSurfaceEdges() { + for ((width, height) in listOf(2608 to 1200, 1920 to 1080, 1280 to 960)) { + ControllerPrefs.setLayout(context, width, height, mapOf("ls" to (0f to .5f), "rs" to (1f to .5f))) + val elements = LegacyGamepadLayout(context, width, height).elements() + assertStickView(elements, width, height, "$width x $height") + ControllerPrefs.resetLayout(context, width, height) + } + } + + @Test @Config(qualifiers = "w833dp-h468dp-land-369dpi") + fun buttonSizeKeepsTheGamepadShapeAtHandheldDensity() { + for ((w, h) in listOf(1920 to 1080, 1920 to 1200)) { + val normal = LegacyGamepadLayout(context, w, h).elements() + assertGamepadShape(normal, w, h, "$w x $h") + val right = setOf("legacy:a", "legacy:b", "legacy:x", "legacy:y", "legacy:rs", "legacy:rb", "legacy:rt", "legacy:start") + val left = setOf("legacy:up", "legacy:right", "legacy:down", "legacy:left", "legacy:ls", "legacy:lb", "legacy:lt", "legacy:select") + val moved = normal.map { e -> + when (e.id) { + in right -> e.copy(x = e.x + 21f / w, y = e.y + 18f / h) + in left -> e.copy(x = e.x - 20f / w, y = e.y + 15f / h) + else -> e + } + } + for (scale in listOf(.8f, 1.25f)) { + val generator = LegacyGamepadLayout(context, w, h, scale = scale) + assertGamepadShape(generator.elements(), w, h, "$w x $h generated at $scale") + val rescaled = generator.rescale(moved, LegacyGamepadLayout(context, w, h)) + assertGamepadShape(rescaled, w, h, "$w x $h moved at $scale") + val a = rescaled.first { it.id == "legacy:a" } + val generatedA = generator.elements().first { it.id == "legacy:a" } + assertEquals(generatedA.x + 21f / w, a.x, .001f) + assertEquals(generatedA.y + 18f / h, a.y, .001f) + assertEquals(moved, LegacyGamepadLayout(context, w, h).rescale(rescaled, generator).let { back -> + back.zip(moved).map { (b, m) -> if (kotlin.math.abs(b.x - m.x) < .001f && kotlin.math.abs(b.y - m.y) < .001f && kotlin.math.abs(b.width - m.width) < .001f) m else b } + }) + } + } + } + + @Test @Config(qualifiers = "w745dp-h343dp-land-420dpi") + fun wideHighDensityGamepadKeepsItsShape() { + val elements = LegacyGamepadLayout(context, 2608, 1200).elements() + assertGamepadShape(elements, 2608, 1200, "2608 x 1200") + } } 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 95f28ef13e..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() @@ -237,22 +333,144 @@ class InputLibraryTest { bindings = original.bindings.map { if (it.layoutId == InputLibraries.OVERLAY) it.copy(layoutId = null, elements = emptyMap(), clicks = emptyMap()) else it }) val raw = org.json.JSONObject(InputLibraries.encode(fixed)).put("version", 2).toString() prefs.edit().putString("library", raw).commit() - LegacyControllerPrefs.setOpacity(context, 60) + ControllerPrefs.setStickClick(context, false) + ControllerPrefs.setKeyboardButton(context, true) + val size = context.resources.displayMetrics + ControllerPrefs.setLayout(context, size.widthPixels, size.heightPixels, mapOf("a" to (.5f to .5f), "ls" to (.3f to .4f))) + ControllerPrefs.setLayout(context, 1600, 900, mapOf("ls" to (.3f to .4f))) val migrated = InputLibraries.read(context) val saved = prefs.getString("library", null) assertEquals(migrated, InputLibraries.read(context)) assertEquals(saved, prefs.getString("library", null)) assertFalse(migrated.layouts.any { it.template == InputLayoutTemplate.OVERLAY }) + assertTrue(migrated.layouts.any { it.id == "migrated.layout.1600x900" }) assertEquals(original.layout("game", InputRole.SECONDARY), migrated.layout("game", InputRole.SECONDARY)) assertEquals(original.preset(original.profile("game").binding(InputRole.PHYSICAL)), migrated.preset(migrated.profile("game").binding(InputRole.PHYSICAL))) val layout = migrated.layout("game", InputRole.PRIMARY)!! val preset = migrated.preset(migrated.profile("game").binding(InputRole.PRIMARY)) assertTrue(layout.editable) - assertTrue(OnScreenLayout.generated(layout)) - assertEquals(60, layout.style.opacity) - assertEquals(InputAction.Command(InputCommand.KEYBOARD), migrated.compile("game").elementAction(InputRole.PRIMARY, KitLayout.KEYBOARD_ID, InputControl.A)) - assertEquals(InputAction.Native(), migrated.compile("game").elementAction(InputRole.PRIMARY, KitLayout.DPAD_ID, InputControl.LS)) - assertEquals(InputAction.Native(), preset.action(InputSurfaceElement(InputControl.A, .1f, .1f, .1f, .1f))) + assertEquals(InputAction.Command(InputCommand.KEYBOARD), preset.elements["builtin:keyboard"]) + assertEquals(InputAction.Disabled, preset.clickAction(layout.elements.first { it.control == InputControl.LS })) + } + + @Test fun oldGamepadPlacementAndVisibilityBecomeEditableElements() { + ControllerPrefs.setLayout(context, 1200, 800, mapOf("ls" to (.4f to .5f))) + ControllerPrefs.setSteamButton(context, false) + ControllerPrefs.setTarget(context, "b", ControllerPrefs.OFF) + val elements = LegacyGamepadLayout(context, 1200, 800).elements() + val stick = elements.first { it.control == InputControl.LS } + assertEquals(.4f, stick.x + stick.width - stick.height * 800f / 1200f / 2f, .0001f) + assertEquals(.5f, stick.y + stick.height / 2f, .0001f) + assertFalse(elements.any { it.control == InputControl.GUIDE || it.control == InputControl.B }) + assertTrue(elements.all { it == it.bounded() }) + } + + @Test fun gamepadControlsAreRoundWithShoulderPillsAndACompactKeyboard() { + val elements = LegacyGamepadLayout(context, 1200, 800).elements() + val density = context.resources.displayMetrics.density + for (element in elements.filter { it.id.startsWith("legacy:") }) { + val shoulder = element.control in setOf(InputControl.LB, InputControl.RB, InputControl.LT, InputControl.RT) + assertEquals(element.control.id, if (shoulder) InputButtonShape.PILL else InputButtonShape.CIRCLE, element.buttonShape) + } + val keyboard = elements.single { it.id == "builtin:keyboard" } + assertEquals(InputButtonIcons.KEYBOARD, keyboard.icon) + assertEquals(InputButtonShape.CIRCLE, keyboard.buttonShape) + assertEquals(36 * density / 1200f, keyboard.width, .0001f) + assertEquals(90 * density / 1200f, keyboard.x + keyboard.width / 2f, .0001f) + assertEquals(1f - 34 * density / 800f, keyboard.y + keyboard.height / 2f, .0001f) + } + + @Test fun dpadButtonsMatchTheFaceButtonsInSizeAndSpacing() { + val elements = LegacyGamepadLayout(context, 1200, 800).elements() + fun centre(c: InputControl) = elements.single { it.id == "legacy:${c.id}" }.let { (it.x + it.width / 2f) * 1200 to (it.y + it.height / 2f) * 800 } + fun size(c: InputControl) = elements.single { it.id == "legacy:${c.id}" }.width * 1200 + assertEquals(size(InputControl.A), size(InputControl.UP), .01f) + assertEquals(centre(InputControl.A).second - centre(InputControl.Y).second, centre(InputControl.DOWN).second - centre(InputControl.UP).second, .01f) + assertEquals(centre(InputControl.B).first - centre(InputControl.X).first, centre(InputControl.RIGHT).first - centre(InputControl.LEFT).first, .01f) + } + + @Test fun anUntouchedSavedDpadIsResizedAroundItsCentreAndAMovedOneIsKept() { + val fresh = LegacyGamepadLayout(context, 1200, 800) + val target = fresh.elements().filter { it.control in setOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT) } + val cx = target.map { it.x + it.width / 2f }.average().toFloat() + val cy = target.map { it.y + it.height / 2f }.average().toFloat() + val scale = 26f / 30f + val old = target.map { e -> + val ex = cx + (e.x + e.width / 2f - cx) * 52f / 50f + val ey = cy + (e.y + e.height / 2f - cy) * 52f / 50f + e.copy(x = ex - e.width * scale / 2f, y = ey - e.height * scale / 2f, width = e.width * scale, height = e.height * scale, buttonShape = InputButtonShape.ROUNDED) + } + val restyled = fresh.restyle(old) + for ((want, got) in target.zip(restyled)) { + assertEquals(want.x, got.x, .0005f); assertEquals(want.y, got.y, .0005f) + assertEquals(want.width, got.width, .0005f); assertEquals(InputButtonShape.CIRCLE, got.buttonShape) + } + val moved = old.mapIndexed { i, e -> if (i == 0) e.copy(buttonShape = InputButtonShape.RECTANGLE) else e } + assertEquals(moved.drop(1).map { it.width }, fresh.restyle(moved).drop(1).map { it.width }) + val shifted = old.mapIndexed { i, e -> if (i == 0) e.copy(x = e.x + .03f) else e } + assertEquals(shifted.map { listOf(it.x, it.y, it.width, it.height) }, fresh.restyle(shifted).map { listOf(it.x, it.y, it.width, it.height) }) + } + + @Test fun stickTouchAreasReachFurtherOutwardButKeepTheirInnerEdge() { + val elements = LegacyGamepadLayout(context, 1200, 800).elements() + for (control in listOf(InputControl.LS, InputControl.RS)) { + val stick = elements.single { it.control == control } + assertEquals(control.id, stick.height * 800f * 1.25f, stick.width * 1200f, 1f) + } + val left = elements.single { it.control == InputControl.LS } + val right = elements.single { it.control == InputControl.RS } + ControllerPrefs.setLayout(context, 1200, 800, mapOf("ls" to (.3f to .5f), "rs" to (.7f to .5f))) + val placed = LegacyGamepadLayout(context, 1200, 800).elements() + val ls = placed.single { it.control == InputControl.LS } + val rs = placed.single { it.control == InputControl.RS } + assertEquals(.3f, ls.x + ls.width - ls.height * 800f / 1200f / 2f, .0001f) + assertEquals(.7f, rs.x + rs.height * 800f / 1200f / 2f, .0001f) + assertTrue(left.width > left.height * 800f / 1200f && right.width > right.height * 800f / 1200f) + } + + @Test fun adaptiveSticksToggleChangesOnlyTheSticksOfThatLayout() { + val library = InputLibraries.read(context) + val overlay = library.layouts.single { it.id == InputLibraries.OVERLAY } + assertEquals(true, overlay.adaptiveSticks) + InputLibraries.setAdaptiveSticks(context, overlay.id, false) + val off = InputLibraries.read(context) + val changed = off.layouts.single { it.id == overlay.id } + assertEquals(false, changed.adaptiveSticks) + assertFalse(ControllerPrefs.read(context).adaptiveSticks) + assertEquals(overlay.elements.filter { it.kind != InputElementKind.STICK }, changed.elements.filter { it.kind != InputElementKind.STICK }) + assertEquals(library.layouts.filter { it.id != overlay.id }, off.layouts.filter { it.id != overlay.id }) + assertNull(off.layouts.single { it.id == InputLibraries.DECK }.adaptiveSticks) + assertTrue(InputLibraries.setAdaptiveSticks(context, overlay.id, true)) + assertEquals(true, InputLibraries.read(context).layouts.single { it.id == overlay.id }.adaptiveSticks) + prefs.edit().putString("library", JSONObject().put("version", 99).toString()).commit() + assertFalse(InputLibraries.setAdaptiveSticks(context, overlay.id, false)) + assertTrue(ControllerPrefs.read(context).adaptiveSticks) + } + + @Test fun savedGamepadsFromTheFirstUnifiedBuildGetTheRoundLookOnce() { + val fresh = InputLibraries.read(context) + val overlay = fresh.layouts.single { it.id == InputLibraries.OVERLAY } + val old = overlay.copy(elements = overlay.elements.map { e -> + if (e.id == "builtin:keyboard") InputSurfaceElement(InputControl.A, .02f, .9f, .12f, .08f, "builtin:keyboard", name = "Keyboard") + else if (e.control == InputControl.A) e.copy(buttonShape = InputButtonShape.RECTANGLE, x = .5f) + else e.copy(buttonShape = InputButtonShape.ROUNDED) + }) + val custom = SavedInputLayout("mine", "Mine", listOf(InputSurfaceElement(InputControl.B, .1f, .1f, .1f, .1f))) + val stored = fresh.withLayout(old).withLayout(custom) + val renamed = InputSurfaceElement(InputControl.A, .02f, .9f, .12f, .08f, "builtin:keyboard", name = "Keys") + assertEquals(renamed, LegacyGamepadLayout(context, 1200, 800).restyle(listOf(renamed)).single()) + prefs.edit().putString("library", JSONObject(InputLibraries.encode(stored)).put("version", 8).toString()).commit() + val upgraded = InputLibraries.read(context) + val restyled = upgraded.layouts.single { it.id == InputLibraries.OVERLAY }.elements + assertEquals(overlay.elements.single { it.id == "builtin:keyboard" }, restyled.single { it.id == "builtin:keyboard" }) + assertEquals(InputButtonShape.RECTANGLE, restyled.single { it.control == InputControl.A && it.id.startsWith("legacy:") }.buttonShape) + assertEquals(.5f, restyled.single { it.control == InputControl.A && it.id.startsWith("legacy:") }.x, .0001f) + assertEquals(InputButtonShape.PILL, restyled.single { it.control == InputControl.LB }.buttonShape) + assertEquals(InputButtonShape.CIRCLE, restyled.single { it.control == InputControl.UP }.buttonShape) + assertEquals(InputButtonShape.ROUNDED, upgraded.layouts.single { it.id == "mine" }.elements.single().buttonShape) + assertEquals(upgraded, InputLibraries.read(context)) + for (desktop in listOf(false, true)) + assertEquals(InputAction.Command(InputCommand.KEYBOARD), upgraded.compileActive(desktop).elementAction(InputRole.PRIMARY, "builtin:keyboard", InputControl.A)) } @Test fun quickPartsAreModeSpecificAndDoNotEditSavedProfiles() { @@ -383,7 +601,7 @@ class InputLibraryTest { assertNull(fresh.layouts.single { it.id == InputLibraries.DECK }.style.tint) assertNull(fresh.layouts.single { it.id == InputLibraries.TRACKPAD }.style.tint) assertEquals(ControllerPrefs.STEAM_BLUE, fresh.layouts.single { it.id == InputLibraries.OVERLAY }.style.tint) - val red = 0xFFFF6FB5.toInt() + val red = ControllerPrefs.tints.last().first val blue = fresh.layouts.map { it.copy(style = it.style.copy(tint = if (it.id == InputLibraries.TRACKPAD) red else ControllerPrefs.STEAM_BLUE)) } val mine = SavedInputLayout("mine", "Mine", listOf(InputSurfaceElement(InputControl.B, .1f, .1f, .1f, .1f))) val old = JSONObject(InputLibraries.encode(blue.fold(fresh) { library, layout -> library.withLayout(layout) }.withLayout(mine))).put("version", 8) diff --git a/app/src/test/java/com/droiddeck/launcher/input/InputProfilesTest.kt b/app/src/test/java/com/droiddeck/launcher/input/InputProfilesTest.kt index fabc895da3..e5fc41f09a 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/InputProfilesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/InputProfilesTest.kt @@ -20,9 +20,9 @@ class InputProfilesTest { } @Test fun migrationKeepsLegacyTouchMappingSeparateFromPhysicalControls() { - LegacyControllerPrefs.setTarget(context, "a", "b") - LegacyControllerPrefs.setTarget(context, "x", "off") - LegacyControllerPrefs.setSelectSteam(context, true) + ControllerPrefs.setTarget(context, "a", "b") + ControllerPrefs.setTarget(context, "x", "off") + ControllerPrefs.setSelectSteam(context, true) val game = InputProfiles.read(context, InputProfile.GAME) assertEquals(InputAction.Native(InputControl.B), game.action(InputRole.PRIMARY, InputControl.A)) assertEquals(InputAction.Disabled, game.action(InputRole.PRIMARY, InputControl.X)) @@ -35,7 +35,7 @@ class InputProfilesTest { } @Test fun migrationPreservesSavedDesktopSelectBinding() { - LegacyControllerPrefs.setSelectSteam(context, true) + ControllerPrefs.setSelectSteam(context, true) context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE).edit().putString("profile.desktop", """{"version":1,"bindings":[{"role":"PHYSICAL","control":"select","action":{"type":"disabled"}}]}""").commit() assertEquals(InputAction.Disabled, InputProfiles.read(context, InputProfile.DESKTOP) @@ -68,8 +68,9 @@ class InputProfilesTest { .putString("profile.game", """{"version":999,"bindings":[]} """).commit() val profile = InputProfiles.read(context, InputProfile.GAME) assertEquals(InputProfile.defaults(InputProfile.GAME).bindings, profile.bindings) - assertEquals(InputProfile.defaults(InputProfile.GAME).elements, profile.elements) - assertEquals(InputAction.Command(InputCommand.KEYBOARD), profile.elementAction(InputRole.PRIMARY, KitLayout.KEYBOARD_ID, InputControl.A)) + assertEquals(mapOf( + InputRole.PRIMARY to mapOf("builtin:keyboard" to InputAction.Command(InputCommand.KEYBOARD)), + ), profile.elements) } @Test fun layoutsPersistIndependentOfBindingsAndStayInsideScreen() { diff --git a/app/src/test/java/com/droiddeck/launcher/input/InputSurfaceSourceTest.kt b/app/src/test/java/com/droiddeck/launcher/input/InputSurfaceSourceTest.kt index 4b3ddec3ef..9ccbafe5b2 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/InputSurfaceSourceTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/InputSurfaceSourceTest.kt @@ -171,60 +171,4 @@ class InputSurfaceSourceTest { surface.click(true); surface.click(false) assertEquals(listOf("button:272:true", "button:272:false"), events) } - - @Test fun theKitDpadPressesOnlyTheHeldDirectionAndKeepsEachDirectionsBinding() { - val dpad = InputSurfaceElement(InputControl.LS, .1f, .1f, .3f, .3f, KitLayout.DPAD_ID, InputElementKind.DPAD) - bridge.setInputProfile(InputProfile("test", bindings = mapOf(InputRole.SECONDARY to mapOf(InputControl.LEFT to InputAction.Keys(listOf(30)))))) - val pad = source(dpad) - pad.update(1f, 0f) - assertTrue(state().right) - assertFalse(state().up || state().down || state().left) - pad.update(0f, 0f) - assertFalse(state().right) - pad.update(-1f, 0f) - assertEquals("key:30:true", events.last()) - assertFalse(state().left) - pad.update(0f, 0f) - assertEquals("key:30:false", events.last()) - } - - @Test fun onScreenInputNeverCountsAsAControllerInHand() { - var physical = 0; var player = 0 - bridge.setOnPhysicalInput { physical++ } - bridge.setOnPlayerInput { player++ } - val stick = source(InputSurfaceElement(InputControl.LS, .1f, .1f, .3f, .3f, "legacy:ls", InputElementKind.STICK)) - stick.update(1f, 0f); stick.update(0f, 0f) - org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle() - assertEquals(0, physical) - assertTrue(player > 0) - } - - @Test fun theKitDpadUsesSavedDirectionButtonsAndCancellingNeverRunsADirectionCommand() { - val dpad = InputSurfaceElement(InputControl.LS, .1f, .1f, .3f, .3f, KitLayout.DPAD_ID, InputElementKind.DPAD) - bridge.setInputProfile(InputProfile("test", elements = mapOf(InputRole.SECONDARY to mapOf("legacy:up" to InputAction.Keys(listOf(103)), - "legacy:down" to InputAction.Command(InputCommand.KEYBOARD))))) - val pad = source(dpad) - pad.update(0f, -1f) - assertEquals("key:103:true", events.last()) - pad.update(0f, 0f) - assertEquals("key:103:false", events.last()) - events.clear() - pad.update(0f, 1f) - pad.cancel() - assertTrue(events.none { it.startsWith("KEYBOARD") }) - } - - @Test fun aDirectionHeldAcrossAProfileChangeWaitsForNeutral() { - val dpad = InputSurfaceElement(InputControl.LS, .1f, .1f, .3f, .3f, KitLayout.DPAD_ID, InputElementKind.DPAD) - bridge.setInputProfile(InputProfile("first", elements = mapOf(InputRole.SECONDARY to mapOf(KitLayout.DPAD_ID to InputAction.Directions(17, 32, 31, 30))))) - val pad = source(dpad) - pad.update(0f, -1f) - bridge.setInputProfile(InputProfile("second", elements = mapOf(InputRole.SECONDARY to mapOf("legacy:up" to InputAction.Keys(listOf(103)))))) - events.clear() - pad.update(0f, -1f) - assertTrue(events.none { it == "key:103:true" }) - pad.update(0f, 0f) - pad.update(0f, -1f) - assertEquals("key:103:true", events.last()) - } } diff --git a/app/src/test/java/com/droiddeck/launcher/input/KitLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/input/KitLayoutTest.kt deleted file mode 100644 index 944c830201..0000000000 --- a/app/src/test/java/com/droiddeck/launcher/input/KitLayoutTest.kt +++ /dev/null @@ -1,297 +0,0 @@ -package com.droiddeck.launcher.input - -import android.content.Context -import android.graphics.Rect -import org.junit.Assert.* -import org.junit.Test -import org.junit.runner.RunWith -import org.robolectric.RobolectricTestRunner -import org.robolectric.RuntimeEnvironment -import org.robolectric.annotation.Config -import kotlin.math.hypot - -private const val HANDHELD = "w833dp-h468dp-land-369dpi" - -@RunWith(RobolectricTestRunner::class) -@Config(sdk = [34], manifest = Config.NONE, qualifiers = HANDHELD) -class KitLayoutTest { - private val context: Context get() = RuntimeEnvironment.getApplication() - private val sizes = listOf(1080 to 1920, 1920 to 1080, 1240 to 1080, 2400 to 1080, 1080 to 2400, 1600 to 900, 1280 to 960) - - private fun px(e: InputSurfaceElement, w: Int, h: Int) = floatArrayOf(e.x * w, e.y * h, e.width * w, e.height * h) - private fun centre(e: InputSurfaceElement, w: Int, h: Int) = (e.x + e.width / 2) * w to (e.y + e.height / 2) * h - - private fun overlapping(elements: List, w: Int, h: Int): List> { - val result = mutableListOf>() - for ((i, a) in elements.withIndex()) for (b in elements.drop(i + 1)) { - val (ax, ay) = centre(a, w, h); val (bx, by) = centre(b, w, h) - val round = a.buttonShape == InputButtonShape.CIRCLE && b.buttonShape == InputButtonShape.CIRCLE - val hit = if (round) hypot(ax - bx, ay - by) < (minOf(a.width * w, a.height * h) + minOf(b.width * w, b.height * h)) / 2 - .5f - else kotlin.math.abs(ax - bx) < (a.width + b.width) * w / 2 - .5f && kotlin.math.abs(ay - by) < (a.height + b.height) * h / 2 - .5f - if (hit) result += a.id to b.id - } - return result - } - - private fun ids(kit: PadKit) = KitLayout.elements(context, kit, 1920, 1080).map { it.id }.toSet() - - @Test fun everyKitHasTheCommonControlsOnceEach() { - val common = setOf("legacy:lt", "legacy:lb", "legacy:rt", "legacy:rb", "legacy:a", "legacy:b", "legacy:x", "legacy:y", "legacy:ls", "legacy:rs", - "legacy:select", "legacy:start", "legacy:guide", "legacy:qam", KitLayout.DPAD_ID, KitLayout.KEYBOARD_ID) - for (kit in PadKit.entries) { - val elements = KitLayout.elements(context, kit, 1920, 1080) - assertEquals(kit.name, elements.size, elements.map { it.id }.distinct().size) - assertTrue(kit.name, elements.map { it.id }.containsAll(common)) - } - } - - @Test fun steamKitsAddGripsAndTrackpadsAndTheOthersAddStickClicks() { - val grips = setOf("legacy:l4", "legacy:l5", "legacy:r4", "legacy:r5") - val pads = setOf(InputControl.LEFT_PAD, InputControl.RIGHT_PAD) - val clicks = setOf("legacy:l3", "legacy:r3") - for (kit in PadKit.entries) { - val elements = KitLayout.elements(context, kit, 1920, 1080) - assertEquals(kit.name, kit.steam, elements.map { it.id }.containsAll(grips)) - assertEquals(kit.name, if (kit.steam) pads else emptySet(), elements.filter { it.kind == InputElementKind.TRACKPAD }.map { it.control }.toSet()) - assertEquals(kit.name, !kit.steam, elements.map { it.id }.containsAll(clicks)) - assertTrue(kit.name, elements.none { kit.steam && it.id in clicks || !kit.steam && it.id in grips }) - } - assertEquals(KitLayout.elements(context, PadKit.STEAM_DECK, 1920, 1080), KitLayout.elements(context, PadKit.STEAM_CONTROLLER, 1920, 1080)) - assertEquals(KitLayout.elements(context, PadKit.DUALSHOCK, 1920, 1080), KitLayout.elements(context, PadKit.DUALSENSE, 1920, 1080)) - assertNotEquals(ids(PadKit.STEAM_DECK), ids(PadKit.XBOX)) - } - - @Test fun onlySticksFloatAndTheDpadAndKeyboardAreKitElements() { - for (kit in PadKit.entries) { - val elements = KitLayout.elements(context, kit, 1920, 1080) - for (e in elements) assertEquals(e.id, e.kind == InputElementKind.STICK, e.floating) - assertEquals(InputElementKind.DPAD, elements.single { it.id == KitLayout.DPAD_ID }.kind) - assertEquals(InputButtonIcons.KEYBOARD, elements.single { it.id == KitLayout.KEYBOARD_ID }.icon) - for (shoulder in listOf("legacy:lt", "legacy:lb", "legacy:rt", "legacy:rb")) assertEquals(InputButtonShape.PILL, elements.single { it.id == shoulder }.buttonShape) - } - } - - @Test fun controlsStayOnScreenAndApartAtEverySize() { - for (kit in PadKit.entries) for ((w, h) in sizes) for (scale in listOf(.8f, 1f, 1.25f)) { - val elements = KitLayout.elements(context, kit, w, h, scale = scale) - for (e in elements) assertEquals("$kit $w x $h ${e.id}", e, e.bounded()) - assertEquals("$kit $w x $h at $scale", emptyList>(), overlapping(elements, w, h)) - } - } - - @Test fun buttonsAreRoundAndStayRoundOnEveryAspect() { - for (kit in PadKit.entries) for ((w, h) in sizes) { - for (e in KitLayout.elements(context, kit, w, h).filter { it.buttonShape == InputButtonShape.CIRCLE }) - assertEquals("$kit $w x $h ${e.id}", e.width * w, e.height * h, 1f) - } - } - - @Test fun theFaceButtonsFormACross() { - for (kit in PadKit.entries) { - val e = KitLayout.elements(context, kit, 2400, 1080).associateBy { it.id } - val (yx, yy) = centre(e.getValue("legacy:y"), 2400, 1080); val (ax, ay) = centre(e.getValue("legacy:a"), 2400, 1080) - val (xx, xy) = centre(e.getValue("legacy:x"), 2400, 1080); val (bx, by) = centre(e.getValue("legacy:b"), 2400, 1080) - assertEquals(yx, ax, .5f); assertEquals(xy, by, .5f) - assertTrue(yy < xy && xy < ay && xx < yx && yx < bx) - assertEquals(ay - yy, bx - xx, .5f) - } - } - - @Test fun safeInsetsMoveEdgeControlsInByTheInsetOnly() { - val safe = Rect(120, 0, 60, 0) - for (kit in PadKit.entries) { - val plain = KitLayout.elements(context, kit, 2400, 1080).associateBy { it.id } - val inset = KitLayout.elements(context, kit, 2400, 1080, safe) - for (e in inset) { - val (x, y, ew, eh) = px(e, 2400, 1080).toList() - assertTrue("$kit ${e.id}", x >= safe.left - .5f && y >= safe.top - .5f && x + ew <= 2400 - safe.right + .5f && y + eh <= 1080 - safe.bottom + .5f) - } - val a = plain.getValue("legacy:lt"); val b = inset.single { it.id == "legacy:lt" } - assertEquals(safe.left.toFloat(), (b.x - a.x) * 2400, .5f) - val r = plain.getValue("legacy:rt"); val s = inset.single { it.id == "legacy:rt" } - assertEquals(-safe.right.toFloat(), (s.x - r.x) * 2400, .5f) - } - } - - @Test fun widerScreensSpreadTheControlsInsteadOfStretchingThem() { - for (kit in PadKit.entries) { - val narrow = KitLayout.elements(context, kit, 1920, 1080).associateBy { it.id } - val wide = KitLayout.elements(context, kit, 2400, 1080).associateBy { it.id } - for ((id, n) in narrow) { - val v = wide.getValue(id) - assertEquals("$kit $id width", n.width * 1920, v.width * 2400, .5f) - assertEquals("$kit $id y", n.y * 1080, v.y * 1080, .5f) - val (nx, _) = centre(n, 1920, 1080); val (vx, _) = centre(v, 2400, 1080) - val shift = vx - nx - assertTrue("$kit $id moved $shift", listOf(0f, 240f, 480f).any { kotlin.math.abs(shift - it) < .5f }) - } - } - } - - @Test fun theCentreOfTheScreenStaysClear() { - for (kit in PadKit.entries) for ((w, h) in sizes.filter { it.first > it.second }) { - val box = android.graphics.RectF(w * .4f, h * .35f, w * .6f, h * .65f) - for (e in KitLayout.elements(context, kit, w, h)) { - val (x, y, ew, eh) = px(e, w, h).toList() - assertFalse("$kit $w x $h ${e.id}", android.graphics.RectF.intersects(box, android.graphics.RectF(x, y, x + ew, y + eh))) - } - } - } - - @Test @Config(qualifiers = "mdpi") - fun aBigScreenCapsTheControlsAtAHandheldHeight() { - val metrics = context.resources.displayMetrics - val dpi = metrics.ydpi.takeIf { it > metrics.densityDpi * .6f && it < metrics.densityDpi * 1.6f } ?: metrics.densityDpi.toFloat() - val small = KitLayout.elements(context, PadKit.XBOX, 1600, 900).single { it.id == "legacy:a" } - val big = KitLayout.elements(context, PadKit.XBOX, 3200, 1800).single { it.id == "legacy:a" } - assertEquals(small.height * 900, big.height * 1800, 1f) - val mm = small.height * 900 / dpi * 25.4f - assertEquals(116f / 900f * 80f, mm, .3f) - } - - @Test fun aHandheldScreenUsesTheFullReferenceSize() { - val a = KitLayout.elements(context, PadKit.XBOX, 1920, 1080).single { it.id == "legacy:a" } - assertEquals(116f * 1.2f, a.height * 1080, 1f) - } - - @Test fun noDefaultControlSitsUnderTheCornerButton() { - val density = context.resources.displayMetrics.density - val corner = android.graphics.RectF(4 * density, 1080 - 52 * density, 52 * density, 1080 - 4 * density) - for (kit in PadKit.entries) for (e in KitLayout.elements(context, kit, 1920, 1080)) { - val (cx, cy) = centre(e, 1920, 1080) - val r = minOf(e.width * 1920, e.height * 1080) / 2 - val nx = cx.coerceIn(corner.left, corner.right); val ny = cy.coerceIn(corner.top, corner.bottom) - val touches = if (e.buttonShape == InputButtonShape.CIRCLE) hypot(cx - nx, cy - ny) < r - 1f - else android.graphics.RectF.intersects(corner, android.graphics.RectF(e.x * 1920, e.y * 1080, (e.x + e.width) * 1920, (e.y + e.height) * 1080)) - assertFalse("$kit ${e.id} is under the corner button", touches) - } - } - - @Test fun clustersStayTogetherOnTallAndSquareScreens() { - val ratio = mapOf(PadKit.STEAM_DECK to 96f / 58f, PadKit.STEAM_CONTROLLER to 96f / 58f, PadKit.XBOX to 94f / 58f, - PadKit.DUALSHOCK to 96f / 58f, PadKit.DUALSENSE to 96f / 58f) - for (kit in PadKit.entries) for ((w, h) in listOf(1080 to 1920, 1240 to 1080, 2400 to 1080)) { - val e = KitLayout.elements(context, kit, w, h).associateBy { it.id } - val face = listOf("legacy:y", "legacy:x", "legacy:b", "legacy:a").map { centre(e.getValue(it), w, h) } - val cx = face.map { it.first }.average().toFloat(); val cy = face.map { it.second }.average().toFloat() - val radius = e.getValue("legacy:a").height * h / 2 - val spread = if (h > w) .3f / .17f else ratio.getValue(kit) - for ((x, y) in face) assertEquals("$kit $w x $h", radius * spread, hypot(x - cx, y - cy), 1f) - if (kit == PadKit.XBOX && h <= w) { - val (lx, ly) = centre(e.getValue("legacy:ls"), w, h); val (cx3, cy3) = centre(e.getValue("legacy:l3"), w, h) - val unit = e.getValue("legacy:ls").height * h / 208f - assertEquals("$w x $h", hypot(150f, 110f) * unit, hypot(cx3 - lx, cy3 - ly), 1f) - } - } - } - - @Test @Config(qualifiers = "mdpi") - fun smallControlsKeepTheirShapeOnABigLowDensityScreen() { - for (kit in PadKit.entries) { - val elements = KitLayout.elements(context, kit, 1920, 1080) - for (e in elements.filter { it.buttonShape == InputButtonShape.CIRCLE }) assertEquals("$kit ${e.id}", e.width * 1920, e.height * 1080, 1f) - assertEquals(kit.name, emptyList>(), overlapping(elements, 1920, 1080)) - } - } - - @Test fun theBottomLeftRowStartsRightOfTheCornerButtonWithGaps() { - val density = context.resources.displayMetrics.density - for (safe in listOf(Rect(), Rect(120, 0, 0, 40))) for (kit in PadKit.entries) for ((w, h) in sizes) { - val elements = KitLayout.elements(context, kit, w, h, safe) - val keyboard = elements.single { it.id == KitLayout.KEYBOARD_ID } - val row = elements.filter { e -> val cy = e.y + e.height / 2; cy > keyboard.y && cy < keyboard.y + keyboard.height && e.x + e.width / 2 < .5f } - .sortedBy { it.x } - assertEquals("$kit $w x $h", keyboard, row.first()) - assertTrue("$kit $w x $h $safe keyboard at ${keyboard.x * w}", keyboard.x * w >= safe.left + 52 * density - .5f) - for ((a, b) in row.zipWithNext()) assertTrue("$kit $w x $h ${a.id} ${b.id}", (b.x - a.x - a.width) * w >= 8 * density - .5f) - } - } - - @Test fun portraitSurfacesPutTheWholePadInTheLowerPartAboveABottomRow() { - val density = context.resources.displayMetrics.density - for (kit in PadKit.entries) for ((w, h) in listOf(1080 to 1920, 1200 to 2000, 1080 to 2400)) { - val elements = KitLayout.elements(context, kit, w, h) - val row = 60 * density - val area = minOf(h * .6f, w * 1.15f) - assertTrue("$kit $w x $h", elements.minOf { it.y } * h >= h - row - area - .5f) - assertTrue("$kit $w x $h", elements.maxOf { (it.y + it.height) * h } <= h + .5f) - val bottomRow = elements.filter { (it.y + it.height / 2) * h > h - row } - assertTrue("$kit $w x $h", bottomRow.any { it.id == KitLayout.KEYBOARD_ID } && bottomRow.any { it.control == InputControl.QAM }) - assertTrue("$kit $w x $h", bottomRow.minOf { it.x } * w >= 52 * density - .5f) - val stick = elements.first { it.id == "legacy:ls" } - assertTrue("$kit $w x $h", stick.width * w >= w * if (kit.steam) .2f else .3f) - assertTrue("$kit $w x $h", elements.any { it.id == "legacy:rs" }) - } - } - - @Test fun anEmptySurfaceHasNoControls() { - assertTrue(KitLayout.elements(context, PadKit.STEAM_DECK, 0, 1080).isEmpty()) - assertTrue(KitLayout.elements(context, PadKit.STEAM_DECK, 1920, 0).isEmpty()) - } - - @Test fun theDockedStripAddsGripsOnlyForSteamKitsAndNeverSystemButtons() { - val density = context.resources.displayMetrics.density - for (kit in PadKit.entries) { - val placed = KitLayout.dock(context, kit, 1080, 1300, true, InputControl.LS, InputControl.RS) - val boxes = GamepadGeometry.layout(1080f, 1300f, density, true, grips = kit.steam, trackpads = kit.steam) - assertEquals(kit.name, kit.steam && boxes.containsKey(GamepadGeometry.Slot.L4), placed.any { it.control == InputControl.L4 }) - assertEquals(kit.name, kit.steam, placed.any { it.control == InputControl.L4 }) - assertNull(placed.firstOrNull { it.control == InputControl.GUIDE || it.control == InputControl.QAM }) - assertEquals(1, placed.count { it.id == KitLayout.DPAD_ID }) - assertTrue(placed.none { it.floating }) - } - } - - @Test fun onlySteamKitsPutTrackpadsInTheDockedStrip() { - for (kit in PadKit.entries) { - val placed = KitLayout.dock(context, kit, 1080, 1300, true, InputControl.LS, InputControl.RIGHT_PAD).map { it.control } - assertEquals(kit.toString(), kit.steam, InputControl.RIGHT_PAD in placed && InputControl.LEFT_PAD in placed) - assertTrue(kit.toString(), InputControl.RS in placed && InputControl.LS in placed) - } - } - - @Test fun aSmallerPortraitPadKeepsTheGripsAndANarrowBottomRowNeverOverlaps() { - val grips = setOf("legacy:l4", "legacy:l5", "legacy:r4", "legacy:r5") - for (scale in listOf(.8f, 1f)) { - val ids = KitLayout.elements(context, PadKit.STEAM_DECK, 720, 1280, scale = scale).map { it.id } - assertTrue("$scale", ids.containsAll(grips)) - } - for (kit in PadKit.entries) { - val (w, h) = 720 to 1280 - val elements = KitLayout.elements(context, kit, w, h, Rect(120, 0, 0, 0)) - assertEquals(kit.toString(), emptyList>(), overlapping(elements, w, h)) - } - } - - @Test fun noKitControlIsSmallerThanTheOldGamepadOnAHandheld() { - val dp = context.resources.displayMetrics.density - for (kit in PadKit.entries) { - val e = KitLayout.elements(context, kit, 1920, 1080).associateBy { it.id } - assertTrue("$kit face", e.getValue("legacy:a").width * 1920 / 2 >= 30 * dp - 1) - assertTrue("$kit d-pad", e.getValue(KitLayout.DPAD_ID).width * 1920 / 2 >= 60 * dp) - assertTrue("$kit stick", e.getValue("legacy:ls").width * 1920 / 2 >= 40 * dp) - } - } - - @Test fun aTopCutoutNeverPushesTheShoulderRowIntoTheMiddleControls() { - for (kit in PadKit.entries) for (top in listOf(0, 20, 60, 120)) { - val elements = KitLayout.elements(context, kit, 1600, 900, Rect(0, top, 0, 0)) - val lb = elements.single { it.id == "legacy:lb" } - val middle = elements.filter { it.id == KitLayout.DPAD_ID || it.id == "legacy:y" } - for (m in middle) assertTrue("$kit $top ${m.id}", m.y * 900 >= (lb.y + lb.height) * 900 - .5f || m.x * 1600 >= (lb.x + lb.width) * 1600) - } - } - - @Test fun insetsThatLeaveLessRoomShrinkTheKitInsteadOfOverlappingIt() { - for (kit in PadKit.entries) for ((w, h, safe) in listOf(Triple(1600, 900, Rect(0, 60, 0, 0)), Triple(1600, 900, Rect(0, 730, 0, 0)), - Triple(1600, 900, Rect(0, 200, 0, 0)), Triple(1600, 900, Rect(0, 200, 0, 150)), Triple(1600, 900, Rect(0, 390, 0, 0)), - Triple(1920, 1080, Rect(80, 120, 80, 90)), Triple(2400, 1080, Rect(120, 30, 60, 40)))) { - val elements = KitLayout.elements(context, kit, w, h, safe) - assertEquals("$kit $w x $h $safe", emptyList>(), overlapping(elements, w, h)) - if (safe.top + safe.bottom <= 400) for (e in elements) { - val (x, y, ew, eh) = px(e, w, h).toList() - assertTrue("$kit $safe ${e.id}", x >= safe.left - .5f && y >= safe.top - .5f && x + ew <= w - safe.right + .5f && y + eh <= h - safe.bottom + .5f) - } - } - } -} diff --git a/app/src/test/java/com/droiddeck/launcher/input/LegacyControllerPrefs.kt b/app/src/test/java/com/droiddeck/launcher/input/LegacyControllerPrefs.kt deleted file mode 100644 index b055dc0b34..0000000000 --- a/app/src/test/java/com/droiddeck/launcher/input/LegacyControllerPrefs.kt +++ /dev/null @@ -1,14 +0,0 @@ -package com.droiddeck.launcher.input - -import android.content.Context - -/** Writes the controller settings older builds saved, so tests can seed the migrations that read them. */ -internal object LegacyControllerPrefs { - private fun edit(context: Context) = ControllerPrefs.prefs(context).edit() - - fun setTarget(context: Context, id: String, target: String) { edit(context).putString("map.$id", target).commit() } - fun target(context: Context, id: String): String = ControllerPrefs.read(context).mapping[id] ?: id - fun setSelectSteam(context: Context, on: Boolean) { edit(context).putBoolean("selectSteam", on).commit() } - fun setOpacity(context: Context, percent: Int) { edit(context).putInt("opacity", percent).commit() } - fun setStickClick(context: Context, on: Boolean) { edit(context).putBoolean("stickClick", on).commit() } -} diff --git a/app/src/test/java/com/droiddeck/launcher/input/OnScreenControlPrefsTest.kt b/app/src/test/java/com/droiddeck/launcher/input/OnScreenControlPrefsTest.kt deleted file mode 100644 index 6b8fd1fadf..0000000000 --- a/app/src/test/java/com/droiddeck/launcher/input/OnScreenControlPrefsTest.kt +++ /dev/null @@ -1,226 +0,0 @@ -package com.droiddeck.launcher.input - -import android.content.Context -import com.droiddeck.launcher.session.SessionPrefs -import org.json.JSONObject -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 = [34], manifest = Config.NONE) -class OnScreenControlPrefsTest { - private val context: Context get() = RuntimeEnvironment.getApplication() - private val session get() = context.getSharedPreferences("session", Context.MODE_PRIVATE) - private val library get() = context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE) - - @Before fun reset() { - for (name in listOf("session", "game-controls", "input-profiles", "input-surfaces", "controller")) context.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().commit() - } - - @Test fun oldShowModesMapOntoAutoAlwaysAndNever() { - assertEquals(SessionPrefs.OSC_AUTO, SessionPrefs.oscMode(context)) - for ((saved, mode) in listOf(SessionPrefs.OSC_AUTO to SessionPrefs.OSC_AUTO, SessionPrefs.OSC_ALWAYS to SessionPrefs.OSC_ALWAYS, - SessionPrefs.OSC_NEVER to SessionPrefs.OSC_NEVER, SessionPrefs.OSC_STEAM_QAM to SessionPrefs.OSC_ALWAYS, - SessionPrefs.OSC_STEAM_TOUCH to SessionPrefs.OSC_AUTO, "buttons" to SessionPrefs.OSC_AUTO)) { - session.edit().putString("osc", saved).commit() - assertEquals(saved, mode, SessionPrefs.oscMode(context)) - } - session.edit().putString("osc", SessionPrefs.OSC_STEAM_TOUCH).commit() - assertEquals(SessionPrefs.OSC_ALWAYS, SessionPrefs.oscMode(context, steamSession = true)) - SessionPrefs.setOscMode(context, SessionPrefs.OSC_AUTO) - assertEquals(SessionPrefs.OSC_AUTO, SessionPrefs.oscMode(context, steamSession = true)) - assertTrue(SessionPrefs.steamTouchLayout(context)) - } - - @Test fun theOldSteamTouchModeBecomesTheSteamLayoutUntilChanged() { - assertFalse(SessionPrefs.steamTouchLayout(context)) - session.edit().putString("osc", SessionPrefs.OSC_STEAM_TOUCH).commit() - assertTrue(SessionPrefs.steamTouchLayout(context)) - SessionPrefs.setSteamTouchLayout(context, false) - assertFalse(SessionPrefs.steamTouchLayout(context)) - session.edit().putString("osc", SessionPrefs.OSC_ALWAYS).putBoolean("steamTouchLayout", true).commit() - assertTrue(SessionPrefs.steamTouchLayout(context)) - } - - @Test fun eachGameKeepsItsOwnLayoutChoice() { - assertNull(GameControls.bindings(context, null)) - assertNull(GameControls.bindings(context, 7)) - GameControls.choose(context, 7, "mine.bindings", steam = false) - assertEquals("mine.bindings", GameControls.bindings(context, 7)) - assertNull(GameControls.bindings(context, 8)) - assertFalse(GameControls.steamLayout(context, 7)) - GameControls.choose(context, 7, null, steam = true) - assertNull(GameControls.bindings(context, 7)) - assertTrue(GameControls.steamLayout(context, 7)) - } - - @Test fun gamesWithoutAChoiceFollowTheDefaultSteamLayout() { - SessionPrefs.setSteamTouchLayout(context, true) - assertTrue(GameControls.steamLayout(context, null)) - assertTrue(GameControls.steamLayout(context, 9)) - GameControls.choose(context, 9, null, steam = false) - assertFalse(GameControls.steamLayout(context, 9)) - assertTrue(GameControls.steamLayout(context, 10)) - } - - @Test fun kitElementsWithoutSavedBindingsGetTheirDefaultActions() { - val profile = InputProfile("empty") - assertEquals(InputAction.Native(), profile.elementAction(InputRole.PRIMARY, KitLayout.DPAD_ID, InputControl.LS)) - assertEquals(InputAction.Command(InputCommand.KEYBOARD), profile.elementAction(InputRole.PRIMARY, KitLayout.KEYBOARD_ID, InputControl.A)) - assertEquals(InputAction.Native(), profile.elementAction(InputRole.PRIMARY, "legacy:a", InputControl.A)) - assertEquals(InputAction.Disabled, profile.elementAction(InputRole.PRIMARY, "custom:1", InputControl.A)) - val mapped = profile.copy(bindings = mapOf(InputRole.PRIMARY to mapOf(InputControl.A to InputAction.Keys(listOf(57)))), - elements = mapOf(InputRole.PRIMARY to mapOf(KitLayout.KEYBOARD_ID to InputAction.Disabled))) - assertEquals(InputAction.Keys(listOf(57)), mapped.elementAction(InputRole.PRIMARY, "legacy:a", InputControl.A)) - assertEquals(InputAction.Disabled, mapped.elementAction(InputRole.PRIMARY, KitLayout.KEYBOARD_ID, InputControl.A)) - - val bindings = SavedInputBindings("b", "B", false, "layout") - assertEquals(InputAction.Native(), bindings.action(InputSurfaceElement(InputControl.LS, 0f, 0f, .1f, .1f, KitLayout.DPAD_ID, InputElementKind.DPAD))) - assertEquals(InputAction.Command(InputCommand.KEYBOARD), bindings.action(InputSurfaceElement(InputControl.A, 0f, 0f, .1f, .1f, KitLayout.KEYBOARD_ID))) - assertEquals(InputAction.Disabled, bindings.action(InputSurfaceElement(InputControl.A, 0f, 0f, .1f, .1f, "custom:1"))) - } - - private fun storeAt(version: Int, change: (InputLibrary) -> InputLibrary) { - val stored = change(InputLibraries.read(context)) - library.edit().putString("library", JSONObject(InputLibraries.encode(stored)).put("version", version).toString()).commit() - } - - @Test fun gamepadsSavedByTheOldEditorFollowTheKitAgainOnce() { - val placed = KitLayout.elements(context, PadKit.STEAM_DECK, 1920, 1080) - val custom = SavedInputLayout("custom", "Custom", listOf(InputSurfaceElement(InputControl.B, .1f, .1f, .1f, .1f)), aspect = 2f) - storeAt(14) { lib -> - val overlay = lib.layouts.single { it.id == InputLibraries.OVERLAY } - lib.withLayout(overlay.copy(elements = placed, aspect = 16f / 9, scale = 1.25f)) - .withLayout(SavedInputLayout("copy", "Copy", placed, aspect = 16f / 9, origin = InputLibraries.OVERLAY)) - .withLayout(SavedInputLayout("migrated.layout.1600x900", "Gamepad", placed, aspect = 16f / 9)) - .withLayout(custom) - } - val before = InputLibraries.decode(library.getString("library", null)!!)!! - val upgraded = InputLibraries.read(context) - for (id in listOf(InputLibraries.OVERLAY, "copy", "migrated.layout.1600x900")) { - val layout = upgraded.layouts.single { it.id == id } - assertTrue(id, layout.elements.isEmpty()) - assertEquals(id, 0f, layout.aspect) - assertEquals(id, 1f, layout.scale) - assertTrue(id, OnScreenLayout.generated(layout)) - } - assertNull(upgraded.layouts.single { it.id == InputLibraries.OVERLAY }.origin) - assertEquals(InputLibraries.OVERLAY, upgraded.layouts.single { it.id == "migrated.layout.1600x900" }.origin) - assertEquals(custom, upgraded.layouts.single { it.id == "custom" }) - for (id in listOf(InputLibraries.DECK, InputLibraries.TRACKPAD)) assertEquals(before.layouts.single { it.id == id }, upgraded.layouts.single { it.id == id }) - assertEquals(upgraded, InputLibraries.read(context)) - val edited = upgraded.withLayout(upgraded.layouts.single { it.id == InputLibraries.OVERLAY }.copy(elements = placed, aspect = 16f / 9)) - InputLibraries.update(context) { edited } - assertEquals(placed, InputLibraries.read(context).layouts.single { it.id == InputLibraries.OVERLAY }.elements) - } - - @Test fun theKitUpgradeKeepsScreenKeysMergedIntoTheGamepad() { - val key = InputSurfaceElement(InputControl.A, .45f, .1f, .1f, .1f, "imported:0", name = "Find", alwaysShown = true) - storeAt(14) { lib -> - val overlay = lib.layouts.single { it.id == InputLibraries.OVERLAY } - val bindings = lib.preset(lib.activePart(false, InputRole.PRIMARY).bindings) - lib.withLayout(overlay.copy(elements = KitLayout.elements(context, PadKit.STEAM_DECK, 1920, 1080) + key, aspect = 16f / 9)) - .withPreset(bindings.copy(elements = bindings.elements + (key.id to InputAction.Keys(listOf(29, 33))))) - } - val upgraded = InputLibraries.read(context) - assertEquals(listOf(key.id), upgraded.layouts.single { it.id == InputLibraries.OVERLAY }.elements.map { it.id }.filter { it.startsWith("imported:") }) - assertEquals(InputAction.Keys(listOf(29, 33)), upgraded.compileActive(false).elementAction(InputRole.PRIMARY, key.id, InputControl.A)) - } - - @Test fun bindingsSavedForKitControlsSurviveTheKitUpgrade() { - storeAt(14) { lib -> - val overlay = lib.layouts.single { it.id == InputLibraries.OVERLAY } - val bindings = lib.preset(lib.activePart(false, InputRole.PRIMARY).bindings) - lib.withLayout(overlay.copy(elements = KitLayout.elements(context, PadKit.STEAM_DECK, 1920, 1080), aspect = 16f / 9)) - .withPreset(bindings.copy(elements = bindings.elements + ("legacy:a" to InputAction.Keys(listOf(57))), - clicks = bindings.clicks + ("legacy:ls" to InputAction.Disabled))) - } - val upgraded = InputLibraries.read(context) - assertTrue(OnScreenLayout.generated(upgraded.layouts.single { it.id == InputLibraries.OVERLAY })) - val profile = upgraded.compileActive(false) - assertEquals(InputAction.Keys(listOf(57)), profile.elementAction(InputRole.PRIMARY, "legacy:a", InputControl.A)) - assertEquals(InputAction.Disabled, profile.clicks[InputRole.PRIMARY]?.get("legacy:ls")) - } - - @Test fun changingShowKeepsTheSteamLayoutAnOlderBuildStoredThere() { - val prefs = context.getSharedPreferences("session", Context.MODE_PRIVATE) - prefs.edit().clear().putString("osc", SessionPrefs.OSC_STEAM_TOUCH).commit() - SessionPrefs.setOscMode(context, SessionPrefs.OSC_ALWAYS) - assertEquals(SessionPrefs.OSC_ALWAYS, SessionPrefs.oscMode(context)) - assertTrue(SessionPrefs.steamTouchLayout(context)) - } - - @Test fun aGamepadWithEveryKitControlRemovedStaysEmptyAndKeepsKitBindingsOnOtherEdits() { - val library = InputLibraries.read(context) - val overlay = library.layouts.single { it.id == InputLibraries.OVERLAY } - val key = InputSurfaceElement(InputControl.A, .4f, .4f, .1f, .1f, "imported:9", name = "Key") - val emptied = overlay.copy(elements = listOf(key), aspect = 16f / 9, kitless = true) - InputLibraries.update(context) { it.withLayout(emptied) } - val stored = InputLibraries.read(context).layouts.single { it.id == InputLibraries.OVERLAY } - assertFalse(OnScreenLayout.generated(stored)) - assertEquals(listOf("imported:9"), OnScreenLayout.elements(context, stored, 1920, 1080, android.graphics.Rect()).map { it.id }) - val bindings = library.preset(library.activePart(false, InputRole.PRIMARY).bindings) - val withKey = InputLibraries.update(context) { lib -> - lib.withLayout(overlay).withPreset(bindings.copy(elements = bindings.elements + ("legacy:a" to InputAction.Keys(listOf(30))))) - } - val dimmed = withKey.withLayout(overlay.copy(style = overlay.style.copy(opacity = 50))) - assertEquals(InputAction.Keys(listOf(30)), dimmed.preset(bindings.id).elements["legacy:a"]) - } - - @Test fun aSavedKitDpadKeepsItsDirectionOverrides() { - val library = InputLibraries.read(context) - val overlay = library.layouts.single { it.id == InputLibraries.OVERLAY } - val saved = overlay.copy(elements = KitLayout.elements(context, PadKit.XBOX, 1920, 1080), aspect = 16f / 9) - val bindings = library.preset(library.activePart(false, InputRole.PRIMARY).bindings) - val withUp = library.withLayout(saved).withPreset(bindings.copy(elements = bindings.elements + ("legacy:up" to InputAction.Keys(listOf(103))))) - val edited = withUp.withLayout(saved.copy(style = saved.style.copy(opacity = 60))).validate() - assertEquals(InputAction.Keys(listOf(103)), edited.preset(bindings.id).elements["legacy:up"]) - val noDpad = edited.withLayout(saved.copy(elements = saved.elements.filterNot { it.id == KitLayout.DPAD_ID })) - assertEquals(InputAction.Keys(listOf(103)), noDpad.preset(bindings.id).elements["legacy:up"]) - } - - @Test fun removingAKitControlFromAGamepadLayoutKeepsItsActionForReset() { - val library = InputLibraries.read(context) - val overlay = library.layouts.single { it.id == InputLibraries.OVERLAY } - val kit = KitLayout.elements(context, PadKit.XBOX, 1920, 1080) - val bindings = library.preset(library.activePart(false, InputRole.PRIMARY).bindings) - val withA = library.withLayout(overlay.copy(elements = kit, aspect = 16f / 9)) - .withPreset(bindings.copy(elements = bindings.elements + ("legacy:a" to InputAction.Keys(listOf(30))))) - val noA = withA.withLayout(overlay.copy(elements = kit.filterNot { it.id == "legacy:a" }, aspect = 16f / 9)).validate() - assertEquals(InputAction.Keys(listOf(30)), noA.preset(bindings.id).elements["legacy:a"]) - val kitless = noA.withLayout(overlay.copy(elements = emptyList(), kitless = true)).validate() - assertEquals(InputAction.Keys(listOf(30)), kitless.preset(bindings.id).elements["legacy:a"]) - val custom = SavedInputLayout("custom", "Custom", listOf(InputSurfaceElement(InputControl.B, .1f, .1f, .1f, .1f, "legacy:b"))) - assertNull(custom.element("legacy:a")) - assertNull(overlay.element("imported:404")) - } - - @Test fun aFailedRecoverySaveLeavesTheStoredLibraryAsItWas() { - val stored = JSONObject().put("version", 1).put("profiles", "broken").toString() - val real = context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE) - real.edit().clear().putString("library", stored).commit() - val failing = object : android.content.ContextWrapper(context) { - override fun getSharedPreferences(name: String, mode: Int): android.content.SharedPreferences { - val prefs = super.getSharedPreferences(name, mode) - return object : android.content.SharedPreferences by prefs { - override fun edit(): android.content.SharedPreferences.Editor { - val editor = prefs.edit() - return object : android.content.SharedPreferences.Editor by editor { - override fun putString(key: String?, value: String?) = apply { editor.putString(key, value) } - override fun remove(key: String?) = apply { editor.remove(key) } - override fun commit(): Boolean { editor.apply(); return false } - } - } - } - } - } - assertTrue(runCatching { InputLibraries.update(failing) { it } }.isFailure) - assertEquals(stored, real.getString("library", null)) - assertTrue(real.all.keys.none { it.startsWith("library-recovery.") }) - } -} diff --git a/app/src/test/java/com/droiddeck/launcher/input/OnScreenControlsTest.kt b/app/src/test/java/com/droiddeck/launcher/input/OnScreenControlsTest.kt index f295464992..2c9745693e 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/OnScreenControlsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/OnScreenControlsTest.kt @@ -1,13 +1,6 @@ package com.droiddeck.launcher.input import android.content.Context -import android.os.Looper -import android.view.ViewConfiguration -import com.droiddeck.launcher.session.SessionPrefs -import java.time.Duration -import org.robolectric.Shadows.shadowOf -import org.robolectric.Robolectric -import androidx.activity.ComponentActivity import android.view.MotionEvent import android.view.View import android.widget.FrameLayout @@ -112,11 +105,25 @@ class OnScreenControlsTest { view.updateLayout(SavedInputLayout("test", "Test", listOf(left.copy(floating = floating)), aspect = ASPECT)) measure(view) touch(MotionEvent.ACTION_DOWN, 3 to (230f to 300f)) - assertEquals(if (floating) 0f else .5f, state().leftX, .01f) + assertEquals(if (floating) 0f else .5f, state().leftX, .001f) touch(MotionEvent.ACTION_UP, 3 to (230f to 300f)) } } + @Test fun systemOnlyVisibilityMovesSteamAndQamToTheBottomCornersAndReleasesOtherButtons() { + val guide = InputSurfaceElement(InputControl.GUIDE, .4f, .7f, .1f, .2f) + view.updateLayout(SavedInputLayout("test", "Test", listOf(button, guide), aspect = ASPECT)) + measure(view) + touch(MotionEvent.ACTION_DOWN, 0 to (800f to 250f)) + view.setButtonsOnly(true) + measure(view) + assertFalse(state().isDown(PadState.A)) + assertFalse(view.takesTouchAt(800f, 250f)) + assertFalse(view.takesTouchAt(450f, 480f)) + assertTrue(view.takesTouchAt(44f, 556f)) + assertTrue(view.takesTouchAt(956f, 556f)) + } + @Test fun aCancelledSecondFingerDoesNotArmAStickClick() { touch(MotionEvent.ACTION_DOWN, 7 to (800f to 250f)) touch(MotionEvent.ACTION_POINTER_DOWN or (1 shl 8), 7 to (800f to 250f), 9 to (200f to 300f)) @@ -170,99 +177,54 @@ class OnScreenControlsTest { assertFalse(state().isDown(PadState.L3)) } - private val corner get() = 26 * context.resources.displayMetrics.density to 600 - 26 * context.resources.displayMetrics.density - - private fun tapCorner() { - val (x, y) = corner - touch(MotionEvent.ACTION_DOWN, 1 to (x to y)); touch(MotionEvent.ACTION_UP, 1 to (x to y)) - shadowOf(Looper.getMainLooper()).idle() + @Test fun theQuickToggleHidesEverythingButTheKeyboardAndShowsItAgain() { + val keyboard = InputSurfaceElement(InputControl.A, .4f, .4f, .1f, .1f, "builtin:keyboard", name = "Keyboard") + view.updateLayout(SavedInputLayout("test", "Test", listOf(left, button, keyboard), aspect = ASPECT)) measure(view) - } - - @Test fun tappingTheCornerHidesTheControlsAndTappingAgainShowsThem() { - val taps = mutableListOf() - view.onCornerTap = { taps += it } - touch(MotionEvent.ACTION_DOWN, 4 to (800f to 250f)) - assertTrue(state().isDown(PadState.A)) - val (x, y) = corner - assertTrue(view.cornerTakes(x, y)) - assertFalse(view.cornerTakes(800f, 250f)) - touch(MotionEvent.ACTION_POINTER_DOWN or (1 shl 8), 4 to (800f to 250f), 1 to (x to y)) - touch(MotionEvent.ACTION_POINTER_UP or (1 shl 8), 4 to (800f to 250f), 1 to (x to y)) - shadowOf(Looper.getMainLooper()).idle() - measure(view) - assertEquals(OnScreenControls.Hidden.BY_TAP, view.hidden) - assertFalse(state().isDown(PadState.A)) - assertFalse(view.takesTouchAt(800f, 250f)) + val density = context.resources.displayMetrics.density + val x = 34 * density + val y = 600 - 34 * density assertTrue(view.takesTouchAt(x, y)) - touch(MotionEvent.ACTION_UP, 4 to (800f to 250f)) - tapCorner() - assertNull(view.hidden) - assertTrue(view.takesTouchAt(800f, 250f)) - assertEquals(listOf(OnScreenControls.Hidden.BY_TAP, null), taps) - } - - @Test fun holdingTheCornerOpensTheMenuOnLiftWithoutHiding() { - var held = 0 - val taps = mutableListOf() - view.onCornerHold = { held++ } - view.onCornerTap = { taps += it } - val activity = Robolectric.buildActivity(ComponentActivity::class.java).setup().get() - activity.setContentView(view, FrameLayout.LayoutParams(1000, 600)) + touch(MotionEvent.ACTION_UP, 4 to (x to y)) + touch(MotionEvent.ACTION_DOWN, 5 to (x to y)); touch(MotionEvent.ACTION_CANCEL, 5 to (x to y)); touch(MotionEvent.ACTION_UP, 5 to (x to y)) + assertFalse(view.isQuickHidden) + touch(MotionEvent.ACTION_DOWN, 1 to (x to y)); touch(MotionEvent.ACTION_UP, 1 to (x to y)) measure(view) - val (x, y) = corner - touch(MotionEvent.ACTION_DOWN, 1 to (x to y)) - shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(ViewConfiguration.getLongPressTimeout() + 50L)) - assertEquals(0, held) - touch(MotionEvent.ACTION_UP, 1 to (x to y)) - shadowOf(Looper.getMainLooper()).idle() - assertEquals(1, held) - assertNull(view.hidden) - assertTrue(taps.isEmpty()) - touch(MotionEvent.ACTION_DOWN, 1 to (x to y)) - touch(MotionEvent.ACTION_CANCEL, 1 to (x to y)) - shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(ViewConfiguration.getLongPressTimeout() + 50L)) - touch(MotionEvent.ACTION_UP, 1 to (x to y)) - shadowOf(Looper.getMainLooper()).idle() - assertEquals(1, held) - assertNull(view.hidden) - assertTrue(taps.isEmpty()) - } - - @Test fun aControllerHideReleasesHeldControlsAndATapBringsThemBack() { - touch(MotionEvent.ACTION_DOWN, 4 to (800f to 250f)) - view.setHidden(OnScreenControls.Hidden.BY_CONTROLLER) - measure(view) - assertFalse(state().isDown(PadState.A)) + assertTrue(view.isQuickHidden) assertFalse(view.takesTouchAt(800f, 250f)) - touch(MotionEvent.ACTION_UP, 4 to (800f to 250f)) - tapCorner() - assertNull(view.hidden) - assertTrue(view.takesTouchAt(800f, 250f)) - } - - @Test fun theCornerIsGoneWithoutALayoutAndOnTheDockedStrip() { - val (x, y) = corner - view.updateLayout(null) + assertTrue(view.takesTouchAt(450f, 270f)) + touch(MotionEvent.ACTION_DOWN, 2 to (800f to 250f)); touch(MotionEvent.ACTION_UP, 2 to (800f to 250f)) + assertTrue(view.isQuickHidden) + touch(MotionEvent.ACTION_DOWN, 3 to (x to y)); touch(MotionEvent.ACTION_UP, 3 to (x to y)) measure(view) - assertFalse(view.cornerTakes(x, y)) - assertFalse(view.takesTouchAt(x, y)) - val docked = OnScreenControls(context, bridge, OnScreenLayout.Dock(false, grips = true)) - docked.updateLayout(SavedInputLayout("test", "Test", listOf(button), aspect = ASPECT)) - measure(docked) - assertFalse(docked.cornerTakes(x, y)) - docked.releaseAll() + assertFalse(view.isQuickHidden) + assertTrue(view.takesTouchAt(800f, 250f)) + view.setButtonsOnly(true) + measure(view) + touch(MotionEvent.ACTION_DOWN, 6 to (x to y)); touch(MotionEvent.ACTION_UP, 6 to (x to y)) + assertFalse(view.isQuickHidden) } - @Test fun switchingTheVirtualControllerRedrawsTheSameLayoutWithTheNewKit() { - assertEquals(PadKit.STEAM_DECK, view.inputSurface.kit) - SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DS4) + @Test fun hidingTheGamepadKeepsAlwaysShownKeysDrawnAndTouchable() { + val key = InputSurfaceElement(InputControl.A, .45f, .1f, .1f, .1f, "imported:0", name = "Find", alwaysShown = true) + view.updateLayout(SavedInputLayout("test", "Test", listOf(left, button, key), aspect = ASPECT)) + measure(view) + assertTrue(view.hasPinned) + view.setPinnedOnly(true) + measure(view) + assertTrue(view.takesTouchAt(500f, 90f)) + assertFalse(view.takesTouchAt(800f, 250f)) + assertFalse(view.takesTouchAt(200f, 300f)) + view.setPinnedOnly(false) + measure(view) + assertTrue(view.takesTouchAt(800f, 250f)) + assertTrue(view.takesTouchAt(500f, 90f)) + view.setQuickHidden(true) + measure(view) + assertTrue(view.takesTouchAt(500f, 90f)) + assertFalse(view.takesTouchAt(800f, 250f)) view.updateLayout(SavedInputLayout("test", "Test", listOf(left, button), aspect = ASPECT)) - assertEquals(PadKit.DUALSHOCK, view.inputSurface.kit) - SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_XBOX360) - view.reload() - assertEquals(PadKit.XBOX, view.inputSurface.kit) - SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK) + assertFalse(view.hasPinned) } private companion object { const val ASPECT = 1000f / 600f } 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 50b60fa051..79de797f02 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt @@ -27,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()) { @@ -39,6 +49,77 @@ 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()) + assertEquals(layout.elements.map { it.id }, placed.map { it.id }) + assertEquals(LegacyGamepadLayout(context, w, h).regenerate(layout.elements), placed) + for (id in listOf("legacy:a", "legacy:up", "legacy:guide")) assertSquare(placed.first { it.id == id }, w, h) + assertInside(placed, w, h) + } + } + + @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) + } + + @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))) + val generator = LegacyGamepadLayout(context, w, h) + val old = generator.elements(previousStickGeometry = true) + 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) + 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())) + } + @Test fun savingTheEditorFrameKeepsEveryControlWhereTheEditorShowsIt() { val w = 2608 val h = 1200 @@ -58,27 +139,6 @@ class OnScreenLayoutTest { } } - @Test fun onlyAnUntouchedBuiltInGamepadOrACopyOfOneFollowsTheKit() { - assertTrue(OnScreenLayout.generated(gamepad())) - assertTrue(OnScreenLayout.generated(SavedInputLayout("copy", "Copy", origin = InputLibraries.OVERLAY))) - assertFalse(OnScreenLayout.generated(SavedInputLayout("custom", "Custom"))) - assertFalse(OnScreenLayout.generated(SavedInputLayout("copy", "Copy", origin = InputLibraries.DECK))) - val edited = gamepad().copy(elements = listOf(InputSurfaceElement(InputControl.A, .5f, .5f, .1f, .1f)), aspect = 2f) - assertFalse(OnScreenLayout.generated(edited)) - assertEquals(listOf("legacy:a"), OnScreenLayout.elements(context, edited, 2000, 1000, Rect()).map { it.id }) - } - - @Test fun theBuiltInGamepadFollowsTheVirtualControllersKitAndScale() { - for ((type, kit) in listOf(SessionPrefs.CONTROLLER_DECK to PadKit.STEAM_DECK, SessionPrefs.CONTROLLER_XBOX360 to PadKit.XBOX, - SessionPrefs.CONTROLLER_DUALSENSE to PadKit.DUALSENSE)) { - SessionPrefs.setSteamController(context, type) - val safe = Rect(40, 0, 20, 10) - assertEquals(KitLayout.elements(context, kit, 2400, 1080, safe), OnScreenLayout.elements(context, gamepad(), 2400, 1080, safe)) - assertEquals(KitLayout.elements(context, kit, 2400, 1080, safe, 1.25f), OnScreenLayout.elements(context, gamepad().copy(scale = 1.25f), 2400, 1080, safe)) - } - assertEquals(emptyList(), OnScreenLayout.elements(context, null, 2400, 1080, Rect())) - } - @Test fun editorAndGameUseTheSamePixelRectsOnWideAndStandardScreens() { val layout = gamepad() for ((w, h) in listOf(2000 to 900, 1600 to 900)) { @@ -94,7 +154,7 @@ class OnScreenLayoutTest { @Test fun editedGeneratedAndCustomLayoutsKeepTheirPixelRectsAcrossRefreshes() { for ((w, h) in listOf(2000 to 900, 1600 to 900)) { val generated = gamepad() - val generatedEdit = KitLayout.elements(context, PadKit.current(context), w, h).map { if (it.id == "legacy:a") it.copy(x = .3f, y = .4f, width = .12f, height = .12f) else it } + val generatedEdit = generated.elements.map { if (it.id == "legacy:a") it.copy(x = .3f, y = .4f, width = .12f, height = .12f) else it } val generatedSaved = generated.copy(elements = generatedEdit, aspect = w.toFloat() / h) val generatedPixels = px(OnScreenLayout.elements(context, generatedSaved, w, h, Rect()).first { it.id == "legacy:a" }, w, h) val generatedRefresh = px(OnScreenLayout.editorElements(context, generatedSaved, w, h, edited = true).first { it.id == "legacy:a" }, w, h) @@ -106,6 +166,67 @@ class OnScreenLayoutTest { } } + @Test fun resetPositionsRestoresGeneratedGeometryAfterAnEdit() { + for ((w, h) in listOf(2000 to 900, 1600 to 900)) { + 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(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" }) + val a = placed.first { it.id == "legacy:a" } + assertEquals(.4f, a.opacity) + assertEquals("Jump", a.name) + 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) @@ -137,12 +258,32 @@ class OnScreenLayoutTest { assertInside(OnScreenLayout.elements(context, edge, 2400, 1080, safe), 2400, 1080, safe) } + @Test fun steamAndQamOnlyModePutsLargeButtonsInTheBottomCornersAndTheKeyboardBetween() { + val safe = Rect(80, 0, 30, 20) + val placed = OnScreenLayout.elements(context, gamepad(), 1000, 500, safe, buttonsOnly = true) + assertEquals(setOf(InputControl.GUIDE, InputControl.QAM, InputControl.A), placed.map { it.control }.toSet()) + val radius = 30 * density + val inset = 44 * density + fun centre(e: InputSurfaceElement) = (e.x + e.width / 2f) * 1000 to (e.y + e.height / 2f) * 500 + val guide = placed.first { it.control == InputControl.GUIDE } + val qam = placed.first { it.control == InputControl.QAM } + val keyboard = placed.first { it.id == "builtin:keyboard" } + assertEquals(2 * radius, guide.width * 1000, .5f) + assertEquals(80 + inset, centre(guide).first, .5f) + assertEquals(500 - 20 - inset, centre(guide).second, .5f) + assertEquals(1000 - 30 - inset, centre(qam).first, .5f) + assertEquals(500f, centre(keyboard).first, .5f) + assertEquals(500 - 20 - inset, centre(keyboard).second, .5f) + val user = SavedInputLayout("edited", "Edited", listOf(InputSurfaceElement(InputControl.A, .5f, .5f, .1f, .1f))) + assertEquals(setOf(InputControl.GUIDE, InputControl.QAM), OnScreenLayout.elements(context, user, 2000, 1000, Rect(), buttonsOnly = true).map { it.control }.toSet()) + } + @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)) - val steam = PadKit.current(context).steam - val boxes = GamepadGeometry.layout(w.toFloat(), h.toFloat(), density, portrait, grips = steam, trackpads = steam) + val boxes = GamepadGeometry.layout(w.toFloat(), h.toFloat(), density, portrait) val ls = placed.first { it.id == "legacy:ls" } val box = boxes.getValue(GamepadGeometry.Slot.LEFT_MAIN) assertEquals(box.left, ls.x * w, 1f) @@ -150,7 +291,7 @@ class OnScreenLayoutTest { assertEquals(box.height, ls.height * h, 1f) assertSquare(placed.first { it.id == "legacy:a" }, w, h) assertNull(placed.firstOrNull { it.control == InputControl.GUIDE || it.control == InputControl.QAM }) - assertEquals(steam && GamepadGeometry.Slot.L4 in boxes, placed.any { it.control == InputControl.L4 }) + assertEquals(portrait, placed.any { it.control == InputControl.L4 }) assertInside(placed, w, h) val solid = placed.filter { it.kind != InputElementKind.STICK } for (a in solid) for (b in solid) if (a !== b) { @@ -166,6 +307,41 @@ class OnScreenLayoutTest { assertEquals(.1f * 2208f / 1768 / .2f, fitted.width * 2208 / (fitted.height * 800), .01f) } + @Test fun thePortraitAndBelowGameKitsKeepDirectionalArtClearOfTheSticksAndFaceButtons() { + val directions = setOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT) + val face = setOf(InputControl.A, InputControl.B, InputControl.X, InputControl.Y) + val types = listOf(SessionPrefs.CONTROLLER_DECK, SessionPrefs.CONTROLLER_STEAM, SessionPrefs.CONTROLLER_XBOX360, + SessionPrefs.CONTROLLER_DS4, SessionPrefs.CONTROLLER_DUALSENSE) + val layout = gamepad() + val w = 1080 + for (type in types) { + SessionPrefs.setSteamController(context, type) + val steam = type == SessionPrefs.CONTROLLER_DECK || type == SessionPrefs.CONTROLLER_STEAM + val deckDock = if (steam) OnScreenLayout.Dock.deck(true, null) else OnScreenLayout.Dock(true, false) + for ((h, dock) in listOf(1920 to null, 1300 to deckDock, 385 to deckDock)) { + val placed = OnScreenLayout.elements(context, layout, w, h, Rect(), dock = dock, + rearButtons = true, trackpads = true) + assertInside(placed, w, h) + val dpad = placed.filter { it.control in directions } + assertEquals(4, dpad.size) + val rightEdge = dpad.maxOf { it.x + it.width } + val bottomEdge = dpad.maxOf { it.y + it.height } + assertTrue(type, placed.filter { it.control in face && it.id != "builtin:keyboard" }.all { it.x > rightEdge }) + assertTrue(type, placed.filter { it.kind == InputElementKind.STICK || it.kind == InputElementKind.TRACKPAD }.all { it.y > bottomEdge }) + if (dock == null) { + val row = placed.filter { it.control in shortcuts || it.id == "builtin:keyboard" } + assertEquals(5, row.size) + assertTrue(row.all { it.y > bottomEdge }) + assertEquals(steam, placed.any { it.kind == InputElementKind.TRACKPAD }) + } else { + assertFalse(placed.any { it.control == InputControl.GUIDE || it.control == InputControl.QAM }) + assertEquals(steam, placed.any { it.kind == InputElementKind.TRACKPAD }) + assertEquals(!steam, placed.any { it.control == InputControl.RS }) + } + } + } + } + private val legacyKeys = "29+33:0.3,0.7,44::Find::0.6:1:1:1" private fun importedOn(library: InputLibrary) = library.activeLayout(false, InputRole.PRIMARY)!!.elements.filter { it.id.startsWith("imported:") } @@ -184,15 +360,8 @@ class OnScreenLayoutTest { assertTrue(migrated.profiles.any { it.id == "migrated.screenkeys.0" }) assertTrue(prefs.getBoolean(LegacyScreenKeyMigration.MERGED, false)) assertEquals(migrated, InputLibraries.read(context)) - } - - @Test fun migratedScreenKeysAreDrawnNextToTheKitGamepad() { - prefs.edit().clear().commit() - ControllerPrefs.prefs(context).edit().putString("screenKeys", legacyKeys).commit() - val layout = InputLibraries.read(context).activeLayout(false, InputRole.PRIMARY)!! - val placed = OnScreenLayout.elements(context, layout, 2400, 1080, Rect()).map { it.id } - assertTrue(placed.contains("imported:0")) - assertTrue(placed.containsAll(listOf("legacy:a", KitLayout.DPAD_ID, "legacy:ls"))) + val placed = OnScreenLayout.elements(context, layout, 2400, 1080, Rect()) + assertEquals(layout.elements.map { it.id }, placed.map { it.id }) } @Test fun librariesMigratedBeforeTheMergeGetTheirScreenKeysBackOnceWithoutLosingEdits() { @@ -224,6 +393,20 @@ class OnScreenLayoutTest { assertEquals(selected, LegacyScreenKeyMigration.merge(selected, shown)) } + @Test fun alwaysShownKeysStayInButtonsOnlyModeAndLeaveTheUnfoldedStrip() { + val key = InputSurfaceElement(InputControl.A, .45f, .1f, .1f, .1f, "imported:0", name = "Find", alwaysShown = true) + val plain = InputSurfaceElement(InputControl.A, .45f, .4f, .1f, .1f, "imported:1", name = "Jump") + val layout = gamepad().let { it.copy(elements = it.elements + key + plain) } + val buttons = OnScreenLayout.elements(context, layout, 1000, 500, Rect(), buttonsOnly = true) + assertTrue(buttons.any { it.id == key.id }) + assertFalse(buttons.any { it.id == plain.id }) + assertEquals(OnScreenLayout.elements(context, gamepad(), 1000, 500, Rect(), buttonsOnly = true), buttons.filterNot { it.id == key.id }) + val strip = OnScreenLayout.elements(context, layout, 2208, 800, Rect(), dock = OnScreenLayout.Dock(false, grips = false)) + assertFalse(strip.any { it.id == key.id }) + assertTrue(strip.any { it.id == plain.id }) + assertTrue(OnScreenLayout.elements(context, layout, 1000, 500, Rect()).map { it.id }.containsAll(listOf(key.id, plain.id))) + } + @Test fun migratedScreenKeysAreAlwaysShownButOtherElementsAreNot() { prefs.edit().clear().commit() ControllerPrefs.prefs(context).edit().putString("screenKeys", legacyKeys).commit() @@ -254,6 +437,7 @@ class OnScreenLayoutTest { } @Test fun aDeckStripPutsTheDeckGamepadSurfacesInTheStickSlotsAndOtherPadsKeepSticks() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE) val stock = InputStockLayouts.layouts().first { it.id == DeckPanel.GAMEPAD.layout } val deck = OnScreenLayout.Dock.deck(false, stock) assertEquals(OnScreenLayout.Dock(false, true, InputControl.LS, InputControl.RIGHT_PAD), deck) @@ -310,4 +494,138 @@ class OnScreenLayoutTest { assertEquals(InputStockLayouts.layouts().filter { it.id != DeckPanel.GAMEPAD.layout }.map { it.elements }, others.filter { l -> InputStockLayouts.layouts().any { it.id == l.id } }.map { it.elements }) } + + private val kits = listOf(SessionPrefs.CONTROLLER_DECK, SessionPrefs.CONTROLLER_STEAM, SessionPrefs.CONTROLLER_XBOX360, + SessionPrefs.CONTROLLER_DS4, SessionPrefs.CONTROLLER_DUALSENSE) + + private fun List.at(control: InputControl) = single { it.id == "legacy:${control.id}" } + + @Test @Config(qualifiers = "w800dp-h450dp-land-320dpi") + fun everyKitPutsTriggersBesideTheirBumpers() { + for (kit in kits) { + SessionPrefs.setSteamController(context, kit) + val placed = OnScreenLayout.elements(context, gamepad(), 1600, 900, Rect(), rearButtons = true, trackpads = true) + val lt = placed.at(InputControl.LT); val lb = placed.at(InputControl.LB) + val rb = placed.at(InputControl.RB); val rt = placed.at(InputControl.RT) + for ((outer, inner) in listOf(lt to lb, rt to rb)) assertEquals(kit, outer.y + outer.height / 2f, inner.y + inner.height / 2f, .001f) + assertTrue(kit, lt.x + lt.width <= lb.x) + assertTrue(kit, rb.x + rb.width <= rt.x) + assertInside(placed, 1600, 900) + } + } + + @Test @Config(qualifiers = "w1280dp-h800dp-land-mdpi") + fun tabletOverlaysStayInTheLowerHalfOfTheScreen() { + for (kit in kits) { + SessionPrefs.setSteamController(context, kit) + val placed = OnScreenLayout.elements(context, gamepad(), 1280, 800, Rect(), rearButtons = true, trackpads = true) + for (e in placed) assertTrue("$kit ${e.id}", e.y >= .45f) + assertInside(placed, 1280, 800) + } + } + + @Test @Config(qualifiers = "w800dp-h450dp-land-320dpi") + fun phoneOverlaysStillUseTheFullHeight() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK) + val placed = OnScreenLayout.elements(context, gamepad(), 1600, 900, Rect()) + assertTrue(placed.at(InputControl.LT).y < .15f) + assertTrue(placed.at(InputControl.START).let { it.y + it.height } > .9f) + } + + @Test @Config(qualifiers = "w800dp-h450dp-land-320dpi") + fun aLayoutEditedInOneOrientationKeepsTheKitInTheOther() { + for (kit in kits) { + SessionPrefs.setSteamController(context, kit) + val layout = gamepad() + val landscape = OnScreenLayout.elements(context, layout, 1600, 900, Rect()) + val moved = landscape.map { if (it.control == InputControl.A) it.copy(x = .5f, y = .5f) else it } + val edited = layout.copy(elements = moved, aspect = 1600f / 900f) + assertEquals(kit, .5f, OnScreenLayout.elements(context, edited, 1600, 900, Rect()).at(InputControl.A).x, .001f) + val kitPortrait = OnScreenLayout.elements(context, layout, 900, 1600, Rect()) + val editedPortrait = OnScreenLayout.elements(context, edited, 900, 1600, Rect()) + for (control in listOf(InputControl.A, InputControl.LT, InputControl.RB, InputControl.LS, InputControl.UP)) + assertEquals("$kit ${control.id}", kitPortrait.at(control), editedPortrait.at(control)) + } + } + + @Test @Config(qualifiers = "w800dp-h450dp-land-320dpi") + fun eachOrientationKeepsItsOwnEdits() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_XBOX360) + val layout = gamepad() + val landscape = OnScreenLayout.elements(context, layout, 1600, 900, Rect()).map { if (it.control == InputControl.A) it.copy(x = .5f, y = .5f) else it } + val edited = OnScreenLayout.withFrame(context, layout, landscape, 1600f / 900f) + val portrait = OnScreenLayout.elements(context, edited, 900, 1600, Rect()).map { if (it.control == InputControl.B) it.copy(x = .1f, y = .2f) else it } + val both = OnScreenLayout.withFrame(context, edited, portrait, 900f / 1600f) + assertEquals(landscape.map { it.id to floatArrayOf(it.x, it.y).toList() }, both.elements.map { it.id to floatArrayOf(it.x, it.y).toList() }) + val wide = OnScreenLayout.elements(context, both, 1600, 900, Rect()) + val tall = OnScreenLayout.elements(context, both, 900, 1600, Rect()) + assertEquals(.5f, wide.at(InputControl.A).x, .001f) + assertEquals(.1f, tall.at(InputControl.B).x, .001f) + assertEquals(.2f, tall.at(InputControl.B).y, .001f) + val renamed = OnScreenLayout.withFrame(context, both, both.elements.map { if (it.control == InputControl.A) it.copy(name = "Jump") else it }, both.aspect) + assertEquals("Jump", OnScreenLayout.elements(context, renamed, 900, 1600, Rect()).at(InputControl.A).name) + assertEquals(.1f, OnScreenLayout.elements(context, renamed, 900, 1600, Rect()).at(InputControl.B).x, .001f) + val library = InputLibraries.read(context).withLayout(both) + assertEquals(both, InputLibraries.decode(InputLibraries.encode(library))!!.layouts.first { it.id == both.id }) + } + + @Test @Config(qualifiers = "w800dp-h450dp-land-320dpi") + fun aRemovedRearButtonStaysRemovedWhileTheOthersRemain() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK) + val layout = gamepad() + val displayed = OnScreenLayout.elements(context, layout, 1600, 900, Rect(), rearButtons = true, trackpads = true) + val frozen = OnScreenLayout.editorFrame(layout, displayed).filterNot { it.control == InputControl.L4 || it.control == InputControl.LEFT_PAD } + val edited = layout.copy(elements = frozen, aspect = 1600f / 900f) + for ((w, h) in listOf(1600 to 900, 900 to 1600)) { + val placed = OnScreenLayout.elements(context, edited, w, h, Rect(), rearButtons = true, trackpads = true).map { it.control } + assertFalse(InputControl.L4 in placed) + assertFalse(InputControl.LEFT_PAD in placed) + assertTrue(InputControl.R5 in placed) + assertTrue(InputControl.RIGHT_PAD in placed) + } + val hidden = OnScreenLayout.elements(context, edited, 1600, 900, Rect(), rearButtons = false, trackpads = false).map { it.control } + assertFalse(InputControl.R5 in hidden) + assertFalse(InputControl.RIGHT_PAD in hidden) + } + + @Test @Config(qualifiers = "w800dp-h450dp-land-320dpi") + fun aPortraitMainLayoutUsesTheStockControlsInLandscape() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_XBOX360) + val layout = gamepad() + val portrait = OnScreenLayout.elements(context, layout, 900, 1600, Rect()).map { if (it.control == InputControl.A) it.copy(x = .1f, y = .1f) else it } + val edited = layout.copy(elements = portrait, aspect = 900f / 1600f) + assertEquals(OnScreenLayout.elements(context, layout, 1600, 900, Rect()), OnScreenLayout.elements(context, edited, 1600, 900, Rect())) + assertEquals(.1f, OnScreenLayout.elements(context, edited, 900, 1600, Rect()).at(InputControl.A).x, .001f) + } + + @Test @Config(qualifiers = "w800dp-h450dp-land-320dpi") + fun aPortraitSaveKeepsOptionalControlsInThePortraitFrameOnly() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK) + val layout = gamepad() + val landscape = OnScreenLayout.elements(context, layout, 1600, 900, Rect()) + val edited = OnScreenLayout.withFrame(context, layout, landscape, 1600f / 900f) + val portrait = OnScreenLayout.elements(context, edited, 900, 1600, Rect(), rearButtons = true, trackpads = true) + .map { if (it.control == InputControl.B) it.copy(x = .1f, y = .2f) else it } + assertTrue(portrait.any { it.control == InputControl.L4 }) + val both = OnScreenLayout.withFrame(context, edited, portrait, 900f / 1600f) + assertTrue(both.elements.none { it.control == InputControl.L4 || it.control == InputControl.LEFT_PAD }) + assertTrue(both.rotated.any { it.control == InputControl.L4 }) + assertEquals(OnScreenLayout.elements(context, edited, 1600, 900, Rect(), rearButtons = true, trackpads = true), + OnScreenLayout.elements(context, both, 1600, 900, Rect(), rearButtons = true, trackpads = true)) + val tall = OnScreenLayout.elements(context, both, 900, 1600, Rect(), rearButtons = true, trackpads = true) + for (control in listOf(InputControl.L4, InputControl.LEFT_PAD, InputControl.B)) assertEquals(control.id, portrait.at(control), tall.at(control)) + assertTrue(OnScreenLayout.elements(context, both, 900, 1600, Rect(), rearButtons = false, trackpads = false) + .none { it.control == InputControl.L4 || it.control == InputControl.LEFT_PAD }) + } + + @Test fun stockControlsUseTheKitArtworkWhileAddedAndTrackpadControlsStillUseTheTint() { + for (kit in listOf(PadKit.XBOX, PadKit.DUALSENSE)) { + SessionPrefs.setSteamController(context, if (kit == PadKit.XBOX) SessionPrefs.CONTROLLER_XBOX360 else SessionPrefs.CONTROLLER_DUALSENSE) + val layout = gamepad() + assertTrue(kit.name, layout.elements.all { kit.artwork(it) }) + val added = InputSurfaceElement(InputControl.A, 0f, 0f, .1f, .1f, "custom", name = "Fire") + assertFalse(kit.artwork(added)) + assertFalse(kit.artwork(layout.elements.first { it.control == InputControl.A }.copy(image = "picture"))) + } + } } diff --git a/app/src/test/java/com/droiddeck/launcher/input/PadKitTest.kt b/app/src/test/java/com/droiddeck/launcher/input/PadKitTest.kt deleted file mode 100644 index 05c715e256..0000000000 --- a/app/src/test/java/com/droiddeck/launcher/input/PadKitTest.kt +++ /dev/null @@ -1,73 +0,0 @@ -package com.droiddeck.launcher.input - -import android.content.Context -import com.droiddeck.launcher.session.SessionPrefs -import org.junit.After -import org.junit.Assert.* -import org.junit.Test -import org.junit.runner.RunWith -import org.robolectric.RobolectricTestRunner -import org.robolectric.RuntimeEnvironment -import org.robolectric.annotation.Config - -@RunWith(RobolectricTestRunner::class) -@Config(sdk = [34], manifest = Config.NONE) -class PadKitTest { - private val context: Context get() = RuntimeEnvironment.getApplication() - @After fun reset() { context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() } - - @Test fun eachVirtualControllerGetsItsOwnKit() { - assertEquals(PadKit.STEAM_DECK, PadKit.of(SessionPrefs.CONTROLLER_DECK)) - assertEquals(PadKit.STEAM_CONTROLLER, PadKit.of(SessionPrefs.CONTROLLER_STEAM)) - assertEquals(PadKit.XBOX, PadKit.of(SessionPrefs.CONTROLLER_XBOX360)) - assertEquals(PadKit.DUALSHOCK, PadKit.of(SessionPrefs.CONTROLLER_DS4)) - assertEquals(PadKit.DUALSENSE, PadKit.of(SessionPrefs.CONTROLLER_DUALSENSE)) - assertEquals(PadKit.STEAM_DECK, PadKit.of(SessionPrefs.CONTROLLER_NONE)) - assertEquals(PadKit.STEAM_DECK, PadKit.of("switchpro")) - } - - @Test fun theKitFollowsTheChosenVirtualController() { - assertEquals(PadKit.STEAM_DECK, PadKit.current(context)) - SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DUALSENSE) - assertEquals(PadKit.DUALSENSE, PadKit.current(context)) - } - - @Test fun steamAndPlayStationKitsAreGroupedForTheirLayouts() { - assertEquals(setOf(PadKit.STEAM_DECK, PadKit.STEAM_CONTROLLER), PadKit.entries.filter { it.steam }.toSet()) - assertEquals(setOf(PadKit.DUALSHOCK, PadKit.DUALSENSE), PadKit.entries.filter { it.playStation }.toSet()) - assertFalse(PadKit.XBOX.steam || PadKit.XBOX.playStation) - } - - @Test fun faceGlyphsMatchTheRealControllers() { - assertEquals(FaceGlyphs.MONO_LETTERS, PadKit.STEAM_DECK.face) - assertEquals(FaceGlyphs.MONO_LETTERS, PadKit.STEAM_CONTROLLER.face) - assertEquals(FaceGlyphs.COLOR_LETTERS, PadKit.XBOX.face) - assertEquals(FaceGlyphs.COLOR_SYMBOLS, PadKit.DUALSHOCK.face) - assertEquals(FaceGlyphs.MONO_SYMBOLS, PadKit.DUALSENSE.face) - assertEquals(DpadStyle.ARROWS, PadKit.DUALSHOCK.dpad) - assertEquals(DpadStyle.ARROWS, PadKit.DUALSENSE.dpad) - } - - @Test fun onlyXboxNamesItsShouldersBumpersAndTriggers() { - val shoulders = listOf(InputControl.LB, InputControl.RB, InputControl.LT, InputControl.RT) - assertEquals(listOf("LB", "RB", "LT", "RT"), shoulders.map(PadKit.XBOX::label)) - for (kit in PadKit.entries - PadKit.XBOX) assertEquals(kit.name, listOf("L1", "R1", "L2", "R2"), shoulders.map(kit::label)) - for (kit in PadKit.entries) assertEquals(InputControl.A.label, kit.label(InputControl.A)) - } - - @Test fun playStationFaceButtonsAreNamedByTheirSymbols() { - val face = listOf(InputControl.A, InputControl.B, InputControl.X, InputControl.Y) - for (kit in listOf(PadKit.DUALSHOCK, PadKit.DUALSENSE)) { - assertEquals(kit.name, listOf("Cross", "Circle", "Square", "Triangle"), face.map(kit::name)) - assertEquals("L1", kit.name(InputControl.LB)) - val elements = KitLayout.elements(context, kit, 1920, 1080).associateBy { it.id } - assertEquals("Triangle", elements.getValue("legacy:y").name) - assertEquals("Cross", elements.getValue("legacy:a").name) - } - for (kit in listOf(PadKit.STEAM_DECK, PadKit.STEAM_CONTROLLER, PadKit.XBOX)) { - assertEquals(kit.name, face.map { it.label }, face.map(kit::name)) - assertEquals(kit.label(InputControl.LT), kit.name(InputControl.LT)) - assertEquals(InputControl.Y.label, KitLayout.elements(context, kit, 1920, 1080).single { it.id == "legacy:y" }.name) - } - } -} diff --git a/app/src/test/java/com/droiddeck/launcher/input/PhysicalInputBindingsTest.kt b/app/src/test/java/com/droiddeck/launcher/input/PhysicalInputBindingsTest.kt index f70c2ce88f..71a0985787 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/PhysicalInputBindingsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/PhysicalInputBindingsTest.kt @@ -24,8 +24,7 @@ class PhysicalInputBindingsTest { override fun command(command: InputCommand) { events += command.name } override fun requestMotion() {} }) - private val presses = ArrayList() - private val bindings = PhysicalInputBindings(router) { presses += it.deviceId } + private val bindings = PhysicalInputBindings(router) private fun device(id: Int): InputDevice { val device = InputDeviceBuilder.newBuilder().setId(id).setName("Thor extra keys").setDescriptor("keys-$id") @@ -56,7 +55,6 @@ class PhysicalInputBindingsTest { assertEquals(listOf("29 true", "30 true", "30 false", "29 false"), events) bindings.onKey(event(device.id, true), true) assertEquals("28 true", events.last()) - assertEquals(listOf(device.id, device.id), presses) } @Test fun releasesRemainConsumedAfterOpeningMenuAndVirtualKeysAreUntouched() { diff --git a/app/src/test/java/com/droiddeck/launcher/input/PhysicalShortcutsTest.kt b/app/src/test/java/com/droiddeck/launcher/input/PhysicalShortcutsTest.kt index 1726e81daa..d41aabbdd0 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/PhysicalShortcutsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/PhysicalShortcutsTest.kt @@ -177,8 +177,8 @@ class PhysicalShortcutsTest { } @Test fun resetAndRemovalPreserveOtherControllerSettings() { - LegacyControllerPrefs.setSelectSteam(context, true) - LegacyControllerPrefs.setTarget(context, "a", "b") + ControllerPrefs.setSelectSteam(context, true) + ControllerPrefs.setTarget(context, "a", "b") assign(key(), Action.STEAM) assign(key(KeyEvent.KEYCODE_BUTTON_2), Action.QAM) PhysicalShortcuts.remove(context, PhysicalShortcuts.read(context).first()) @@ -186,7 +186,7 @@ class PhysicalShortcutsTest { PhysicalShortcuts.remove(context, PhysicalShortcuts.read(context).single()) assertTrue(PhysicalShortcuts.read(context).isEmpty()) assertTrue(ControllerPrefs.read(context).selectSteam) - assertEquals("b", LegacyControllerPrefs.target(context, "a")) + assertEquals("b", ControllerPrefs.target(context, "a")) assign(key(), Action.STEAM) ControllerPrefs.resetAll(context) assertTrue(PhysicalShortcuts.read(context).isEmpty()) diff --git a/app/src/test/java/com/droiddeck/launcher/input/SelectProfileRoutingTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SelectProfileRoutingTest.kt index 9ccef58fdd..3cbdaacc4d 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/SelectProfileRoutingTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/SelectProfileRoutingTest.kt @@ -36,7 +36,7 @@ class SelectProfileRoutingTest { @Before fun setUp() { context.getSharedPreferences("input-profiles", 0).edit().clear().commit() context.getSharedPreferences("controller", 0).edit().clear().commit() - LegacyControllerPrefs.setSelectSteam(context, true) + ControllerPrefs.setSelectSteam(context, true) shadowOf(context.getSystemService(InputManager::class.java)).addInputDevice(device) bridge.setInputRouter(InputRouter(output)) bridge.setInputProfile(InputProfiles.active(context, desktop = false)) diff --git a/app/src/test/java/com/droiddeck/launcher/input/SessionKeyboardPadTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SessionKeyboardPadTest.kt index b3868afb13..7ba52e1683 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/SessionKeyboardPadTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/SessionKeyboardPadTest.kt @@ -80,8 +80,7 @@ class SessionKeyboardPadTest { ReflectionHelpers.setField(activity, "steamTouchOptions", SteamTouchConfig.Options(inputMode = SteamTouchConfig.INPUT_CONTROLLER)) SessionPrefs.setTouchMode(activity, SessionPrefs.TOUCH_DIRECT) - SessionPrefs.setOscMode(activity, SessionPrefs.OSC_ALWAYS) - SessionPrefs.setSteamTouchLayout(activity, true) + SessionPrefs.setOscMode(activity, SessionPrefs.OSC_STEAM_TOUCH) update() assertEquals(View.VISIBLE, steam.visibility) assertEquals(SessionPrefs.TOUCH_OFF, routedTouchMode()) @@ -96,22 +95,6 @@ class SessionKeyboardPadTest { assertEquals(SessionPrefs.TOUCH_OFF, routedTouchMode()) } - @Test fun hidingTheSteamLayoutForAControllerKeepsSteamsTouchControllerPlugged() { - SteamTouchDevice.prepare(directory) - val steam = SteamTouchControls(activity, SteamTouchDevice.current!!, {}, {}) - ReflectionHelpers.setField(activity, "steamTouchControls", steam) - SessionPrefs.setOscMode(activity, SessionPrefs.OSC_AUTO) - SessionPrefs.setSteamTouchLayout(activity, true) - ReflectionHelpers.setField(activity, "controlsHiddenByTap", true) - update() - assertEquals(View.GONE, steam.visibility) - assertTrue(SteamTouchDevice.current!!.plugged) - ReflectionHelpers.setField(activity, "controlsHiddenByTap", false) - update() - assertEquals(View.VISIBLE, steam.visibility) - assertTrue(SteamTouchDevice.current!!.plugged) - } - @Test fun endingTheAgentForgetsSteamsKeyboard() { steamKeyboard(true) AgentGuest.stop() diff --git a/app/src/test/java/com/droiddeck/launcher/input/ShowLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/input/ShowLayoutTest.kt deleted file mode 100644 index 34aa4bc095..0000000000 --- a/app/src/test/java/com/droiddeck/launcher/input/ShowLayoutTest.kt +++ /dev/null @@ -1,45 +0,0 @@ -package com.droiddeck.launcher.input - -import android.content.Context -import android.view.View -import com.droiddeck.launcher.session.SessionPrefs -import com.droiddeck.launcher.ui.InputSurfaceView -import org.junit.After -import org.junit.Assert.* -import org.junit.Test -import org.junit.runner.RunWith -import org.robolectric.RobolectricTestRunner -import org.robolectric.RuntimeEnvironment -import org.robolectric.annotation.Config - -@RunWith(RobolectricTestRunner::class) -@Config(sdk = [34], manifest = Config.NONE, qualifiers = "w833dp-h468dp-land-369dpi") -class ShowLayoutTest { - private val context: Context get() = RuntimeEnvironment.getApplication() - @After fun close() { context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() } - - private fun sized(view: View, w: Int, h: Int) { - view.measure(View.MeasureSpec.makeMeasureSpec(w, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(h, View.MeasureSpec.EXACTLY)) - view.layout(0, 0, w, h) - } - - @Test fun aGeneratedLayoutIsDrawnFromTheKitAtTheViewSize() { - SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_XBOX360) - val view = InputSurfaceView(context) - sized(view, 1240, 1080) - view.showLayout(SavedInputLayout(InputLibraries.OVERLAY, "Gamepad")) - assertEquals(KitLayout.elements(context, PadKit.XBOX, 1240, 1080), view.shownElements) - view.releaseInputs() - } - - @Test fun aSavedLayoutIsDrawnAsSaved() { - val saved = listOf(InputSurfaceElement(InputControl.A, .4f, .4f, .1f, .1f)) - val view = InputSurfaceView(context) - sized(view, 1240, 1080) - view.showLayout(SavedInputLayout("mine", "Mine", saved)) - assertEquals(saved, view.shownElements) - view.showLayout(null) - assertTrue(view.shownElements.isEmpty()) - view.releaseInputs() - } -} diff --git a/app/src/test/java/com/droiddeck/launcher/input/SteamControllerBleTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SteamControllerBleTest.kt index 57572c04b6..f97ca1bf88 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/SteamControllerBleTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/SteamControllerBleTest.kt @@ -25,7 +25,6 @@ import java.util.UUID @Config(sdk = [34], manifest = Config.NONE, shadows = [SteamControllerBleTest.Writer::class]) class SteamControllerBleTest { private val keys = ArrayList>() - private var presses = 0 private val router = InputRouter(object : InputOutput { override fun key(code: Int, down: Boolean) { keys += code to down } override fun button(code: Int, down: Boolean) {} @@ -43,7 +42,7 @@ class SteamControllerBleTest { Writer.features = 0 router.setProfile(InputProfile.defaults(InputProfile.GAME) .withBinding(InputRole.PHYSICAL, InputControl.A, InputAction.Keys(listOf(57)))) - controller = SteamControllerBle(RuntimeEnvironment.getApplication(), router) { presses++ } + controller = SteamControllerBle(RuntimeEnvironment.getApplication(), router) handler = ReflectionHelpers.getField(controller, "handler") shadowOf(handler.looper).pause() controller.start() @@ -61,23 +60,6 @@ class SteamControllerBleTest { drain(handler.looper) } - @Test fun newInputNotifiesOncePerPressOrStickDeflection() { - subscribe(controller) - val held = ByteArray(45).apply { this[1] = 1 } - val stick = held.copyOf().apply { this[10] = 80 } - state(ByteArray(45)) - assertEquals(0, presses) - state(held) - state(held) - assertEquals(1, presses) - state(stick) - state(stick) - assertEquals(2, presses) - state(ByteArray(45)) - state(held) - assertEquals(3, presses) - } - @Test fun stopReleasesAndDetachesInputBeforeQueuedCallbacksCanPublish() { state(ByteArray(45).apply { this[1] = 1 }) assertEquals(listOf(57 to true), keys) diff --git a/app/src/test/java/com/droiddeck/launcher/input/StickDeadZoneTest.kt b/app/src/test/java/com/droiddeck/launcher/input/StickDeadZoneTest.kt index 57d22b43d4..cfa85a0de0 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/StickDeadZoneTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/StickDeadZoneTest.kt @@ -61,7 +61,7 @@ class StickDeadZoneTest { val button = PhysicalShortcuts.Button("test-pad", "Test pad", KeyEvent.KEYCODE_BUTTON_MODE, 0) val binding = PhysicalShortcuts.Binding(button, PhysicalShortcuts.Action.QAM) PhysicalShortcuts.assign(context, button, binding.action) - LegacyControllerPrefs.setTarget(context, "a", "b") + ControllerPrefs.setTarget(context, "a", "b") ControllerPrefs.setRumble(context, false) for (percent in ControllerPrefs.deadZones) { ControllerPrefs.setDeadZone(context, percent) @@ -395,22 +395,27 @@ class StickDeadZoneTest { @Test fun neutralScreenStickPressClearsRetainedPhysicalInput() { val device = device() for (adaptive in listOf(false, true)) { + ControllerPrefs.setAdaptiveSticks(context, adaptive) + ControllerPrefs.setLayout(context, 1200, 800, mapOf("ls" to (0.45f to 0.5f), "rs" to (0.55f to 0.5f))) for (id in listOf("ls", "rs")) { motion(device, MotionEvent.AXIS_X to 0.6f, MotionEvent.AXIS_Z to 0.7f) val view = OnScreenControls(context, bridge) - val elements = KitLayout.elements(context, PadKit.STEAM_DECK, 1200, 800).map { if (it.kind == InputElementKind.STICK) it.copy(floating = adaptive) else it } - view.updateLayout(SavedInputLayout("test", "Test", elements, aspect = 1200f / 800f)) + val elements = LegacyGamepadLayout(context, 1200, 800).elements() + view.updateLayout(SavedInputLayout("test", "Test", elements)) view.measure(android.view.View.MeasureSpec.makeMeasureSpec(1200, android.view.View.MeasureSpec.EXACTLY), android.view.View.MeasureSpec.makeMeasureSpec(800, android.view.View.MeasureSpec.EXACTLY)) view.layout(0, 0, 1200, 800) - val control = elements.first { it.id == "legacy:$id" } - val x = (control.x + control.width / 2) * 1200 - val y = (control.y + control.height / 2) * 800 + val control = elements.first { it.control.id == id } + val left = (control.x * 1200).toInt() + val top = (control.y * 800).toInt() + val height = (control.height * 800).toInt() + val x = left + if (id == "ls") (control.width * 1200).toInt() - height / 2f else height / 2f + val y = top + height / 2f val down = MotionEvent.obtain(1000, 1000, MotionEvent.ACTION_DOWN, x, y, 0) try { assertTrue(view.dispatchTouchEvent(down)) } finally { down.recycle() } - assertEquals(0f, if (id == "ls") pad().leftX else pad().rightX, .05f) + assertEquals(0f, if (id == "ls") pad().leftX else pad().rightX, 0f) assertTrue((if (id == "ls") pad().rightX else pad().leftX) > 0f) bridge.setStickDeadZone(25) - assertEquals(0f, if (id == "ls") pad().leftX else pad().rightX, .05f) + assertEquals(0f, if (id == "ls") pad().leftX else pad().rightX, 0f) motion(device, MotionEvent.AXIS_X to 0.6f, MotionEvent.AXIS_Z to 0.7f) val button = elements.first { it.control == InputControl.A } val bx = (button.x + button.width / 2) * 1200 diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt index f74528c725..ea0c471faa 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt @@ -73,72 +73,6 @@ class BattleNetTest { assertEquals(crc or 0x80000000L, BattleNet.APP_ID) } - @Test fun theNewestD2rfixIsTheHighestFexThenTheHighestFix() { - val items = listOf( - item("FEXCore-2610-linux.wcp"), - item("FEXCore-2609-d2rfix25-linux.wcp"), - item("FEXCore-2610-d2rfix9-linux.wcp"), - item("FEXCore-2610-d2rfix28-linux.wcp"), - item("FEXCore-2509.1-d2rfix40-linux.wcp"), - ) - assertEquals("FEXCore-2610-d2rfix28-linux.wcp", BattleNet.newestD2rFix(items)?.file) - assertEquals("FEXCore-2610.1-d2rfix1-linux.wcp", BattleNet.newestD2rFix(items + item("FEXCore-2610.1-d2rfix1-linux.wcp"))?.file) - assertEquals("FexCore-2611-D2RFIX2-linux.wcp", BattleNet.newestD2rFix(items + item("FexCore-2611-D2RFIX2-linux.wcp"))?.file) - } - - @Test fun onlyFexD2rfixPackagesCount() { - assertNull(BattleNet.newestD2rFix(listOf(item("FEXCore-2610-linux.wcp"), item("FEXCore-2610-d2rfix28-linux.wcp", comp = "dxvk")))) - assertNull(BattleNet.d2rfix("FEXCore-2610-d2rfix28-linux.wcp.part")) - assertNull(BattleNet.d2rfix("FEXCore-2610-d2rfix-linux.wcp")) - assertEquals(listOf(2610L) to 28L, BattleNet.d2rfix("FEXCore-2610-d2rfix28-linux.wcp")) - } - - @Test fun theNewestStoredBuildIsSetForThePrefix() { - catalog("FEXCore-2609-d2rfix25-linux.wcp", "FEXCore-2610-d2rfix28-linux.wcp", "FEXCore-2610-linux.wcp") - store("FEXCore-2610-d2rfix28-linux.wcp") - - assertEquals("FEXCore-2610-d2rfix28-linux.wcp", BattleNet.ensureFex(context, ::noRefresh)) - - assertEquals(mapOf("fex" to "FEXCore-2610-d2rfix28-linux.wcp"), ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())) - assertEquals("FEXCore-2610-d2rfix28-linux.wcp", BattleNet.ensureFex(context, ::noRefresh)) - } - - @Test fun aNewerBuildReplacesTheOldOne() { - catalog("FEXCore-2609-d2rfix25-linux.wcp") - store("FEXCore-2609-d2rfix25-linux.wcp") - BattleNet.ensureFex(context, ::noRefresh) - catalog("FEXCore-2609-d2rfix25-linux.wcp", "FEXCore-2610-d2rfix28-linux.wcp") - store("FEXCore-2610-d2rfix28-linux.wcp") - - BattleNet.ensureFex(context, ::noRefresh) - - assertEquals("FEXCore-2610-d2rfix28-linux.wcp", ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())["fex"]) - } - - @Test fun aStaleListingIsFetchedAgain() { - catalog("FEXCore-2609-d2rfix25-linux.wcp", fetchedAt = 1) - store("FEXCore-2610-d2rfix28-linux.wcp") - - BattleNet.ensureFex(context) { listOf(item("FEXCore-2609-d2rfix25-linux.wcp"), item("FEXCore-2610-d2rfix28-linux.wcp")) } - - assertEquals("FEXCore-2610-d2rfix28-linux.wcp", ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())["fex"]) - } - - @Test fun aFailedFetchFallsBackOnTheCachedListing() { - catalog("FEXCore-2609-d2rfix25-linux.wcp", fetchedAt = 1) - store("FEXCore-2609-d2rfix25-linux.wcp") - - assertEquals("FEXCore-2609-d2rfix25-linux.wcp", BattleNet.ensureFex(context) { error("offline") }) - } - - @Test fun aListingWithoutD2rfixIsAnError() { - catalog("FEXCore-2610-linux.wcp") - var refreshed = 0 - assertThrows(IllegalStateException::class.java) { BattleNet.ensureFex(context) { refreshed++; emptyList() } } - assertEquals(1, refreshed) - assertEquals(emptyMap(), ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())) - } - @Test fun installedIsTheLauncherInThePrefix() { assertFalse(BattleNet.installed(context)) launcher().apply { parentFile!!.mkdirs(); writeText("MZ") } @@ -152,9 +86,9 @@ class BattleNetTest { } @Test fun removeTakesThePrefixItsMenuEntryAndCacheButNothingItLinksTo() { - catalog("FEXCore-2610-d2rfix28-linux.wcp") - store("FEXCore-2610-d2rfix28-linux.wcp") - BattleNet.ensureFex(context, ::noRefresh) + store("FEXCore-2610-linux.wcp") + ComponentsManager.setGameComponent(context, BattleNet.APP_ID.toString(), "fex", "FEXCore-2610-linux.wcp") + assertEquals(mapOf("fex" to "FEXCore-2610-linux.wcp"), ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())) val root = LinuxRuntime.rootDir(context) fun put(relative: String) = File(root, relative).apply { parentFile!!.mkdirs(); writeText("x") } launcher().apply { parentFile!!.mkdirs(); writeText("MZ") } @@ -176,7 +110,7 @@ class BattleNetTest { assertTrue(otherMenu.isFile) assertFalse(log.parentFile!!.exists()) assertTrue(otherPrefix.isFile) - assertNull(BattleNet.fexInUse(context)) + assertEquals(emptyMap(), ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())) outside.deleteRecursively() } @@ -481,6 +415,22 @@ class BattleNetTest { assertTrue(BattleNet.ensureVideoMemory(context)) } + @Test fun theProfileDefaultsAreSetForTheBattleNetProgramOrOnceInstalledAndNeverForAnythingElse() { + File(context.filesDir, "game-environment.json").delete() + val manager = context.getSystemService(android.app.ActivityManager::class.java) + org.robolectric.Shadows.shadowOf(manager).setMemoryInfo(android.app.ActivityManager.MemoryInfo().apply { totalMem = 11113L shl 20 }) + val scope = BattleNet.APP_ID.toString() + BattleNet.ensureDefaults(context, null) + assertNull(GameEnvironmentStore.read(context).games[scope]?.get("DXVK_CONFIG")) + BattleNet.ensureDefaults(context, BattleNet.PROGRAM) + assertEquals(BattleNet.videoMemoryOptions(2048), GameEnvironmentStore.read(context).games[scope]?.get("DXVK_CONFIG")) + assertTrue(com.droiddeck.launcher.session.SessionPrefs.battleNetNoSteamSet(context)) + File(context.filesDir, "game-environment.json").delete() + launcher().apply { parentFile!!.mkdirs(); writeText("MZ") } + BattleNet.ensureDefaults(context, null) + assertEquals(BattleNet.videoMemoryOptions(2048), GameEnvironmentStore.read(context).games[scope]?.get("DXVK_CONFIG")) + } + private fun launcher() = File(BattleNet.prefix(context), "pfx/drive_c/Program Files (x86)/Battle.net/Battle.net Launcher.exe") private fun varint(value: Long): ByteArray { @@ -496,21 +446,6 @@ class BattleNetTest { private fun varintField(number: Int, value: Long) = varint((number shl 3).toLong()) + varint(value) private fun message(vararg fields: ByteArray) = fields.fold(ByteArray(0)) { all, f -> all + f } - private fun noRefresh(context: Context): List = error("the cached listing was fresh") - - private fun item(file: String, comp: String = "fex") = ComponentsManager.CatalogItem( - file, comp, "FexCore-Linux", "https://github.com/The412Banner/Nightlies/releases/download/FexCore-Linux/$file", 4, "sha256:" + "ab".repeat(32), - ) - - private fun catalog(vararg files: String, fetchedAt: Long = System.currentTimeMillis() / 1000) { - val cache = File(context.filesDir, "components/catalog.json") - cache.parentFile!!.mkdirs() - val items = JSONArray() - for (file in files) items.put(JSONObject().put("file", file).put("comp", "fex").put("release", "FexCore-Linux") - .put("url", item(file).url).put("size", 4).put("digest", item(file).digest)) - cache.writeText(JSONObject().put("items", items).put("fetchedAt", fetchedAt).toString()) - } - private fun store(file: String) { val wcp = File(context.filesDir, "components/packages/$file") wcp.parentFile!!.mkdirs() diff --git a/app/src/test/java/com/droiddeck/launcher/session/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/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 74659f2b92..1835b6b85d 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionDisplayTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionDisplayTest.kt @@ -60,20 +60,6 @@ class SessionDisplayTest { assertEquals(864, SessionDisplay.unfoldedGameHeight(1920, 1080)) } - @Test fun unfoldedControlsFitTheGamesOwnAspectUnderTheCap() { - assertEquals(810, SessionDisplay.unfoldedGameHeight(1080, 1920, aspect = 4f / 3f)) - assertEquals(606, SessionDisplay.unfoldedGameHeight(1080, 1920, aspect = 16f / 9f)) - assertEquals((1920 * SessionDisplay.UNFOLDED_MAX_GAME_SHARE).toInt() and 1.inv(), SessionDisplay.unfoldedGameHeight(1080, 1920, aspect = 9f / 16f)) - assertEquals(SessionDisplay.unfoldedGameHeight(1080, 1920, aspect = .5f), SessionDisplay.unfoldedGameHeight(1080, 1920, aspect = .1f)) - assertEquals(810, SessionDisplay.unfoldedGameHeight(1080, 1920, 136, aspect = 4f / 3f)) - assertEquals(1240, SessionDisplay.unfoldedGameHeight(2448, 1848, 136, aspect = 16f / 9f)) - } - - @Test fun aTallScreenTakesTheTabRowFromTheControlsSoTheGameKeepsTheFullWidth() { - assertEquals(606, SessionDisplay.unfoldedGameHeight(1080, 1920, 146)) - assertEquals(1080, SessionDisplay.unfoldedGameHeight(1080, 2400, 146, aspect = 1f)) - } - @Test fun aTabRowUnderTheBarComesOutOfTheGameNotTheControls() { assertEquals(1376, SessionDisplay.unfoldedGameHeight(2448, 1848, 0)) assertEquals(1240, SessionDisplay.unfoldedGameHeight(2448, 1848, 136)) diff --git a/app/src/test/java/com/droiddeck/launcher/session/SettingsResetTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SettingsResetTest.kt index f7265a60c2..bc49532c66 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SettingsResetTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SettingsResetTest.kt @@ -9,7 +9,6 @@ import com.droiddeck.launcher.input.InputControl import com.droiddeck.launcher.input.InputProfile import com.droiddeck.launcher.input.InputProfiles import com.droiddeck.launcher.input.InputRole -import com.droiddeck.launcher.input.LegacyControllerPrefs import com.droiddeck.launcher.input.InputSurfaceLayout import org.junit.Assert.* import org.junit.Before @@ -53,7 +52,7 @@ class SettingsResetTest { SessionPrefs.setHudOpacity(app, 40) SessionPrefs.setDroidDeckHudConfig(app, "hudSize=mega,showFPSGraph=0") SessionPrefs.setDroidDeckHudPosition(app, 120f, 40f) - LegacyControllerPrefs.setOpacity(app, 40) + ControllerPrefs.setOpacity(app, 40) AppUiPrefs.setScale(app, 150) FrameGen.set(app, FrameGen.Mode(FrameGen.ENGINE_DDFG, 3)) prefs("steam_touch").edit().putBoolean("gyro", false).commit() @@ -155,7 +154,7 @@ class SettingsResetTest { val defaultGame = InputProfiles.read(app, InputProfile.GAME) val defaultDesktop = InputProfiles.read(app, InputProfile.DESKTOP) val defaultSurface = InputSurfaceLayout.read(app, InputProfile.DESKTOP) - LegacyControllerPrefs.setTarget(app, "a", "b") + ControllerPrefs.setTarget(app, "a", "b") InputProfiles.select(app, InputProfile.DESKTOP) InputProfiles.save(app, InputProfile.defaults(InputProfile.GAME) .withBinding(InputRole.PHYSICAL, InputControl.A, InputAction.Disabled)) 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/GamepadGeometryTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/GamepadGeometryTest.kt index 8eda0d4503..dbb153bce9 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/GamepadGeometryTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/GamepadGeometryTest.kt @@ -33,12 +33,12 @@ class GamepadGeometryTest { private val grips = setOf(Slot.L4, Slot.L5, Slot.R5, Slot.R4) private val portraitPanels get() = panels.take(3) + Panel("312dp phone portrait", 720, 1280, 369 / 160f) private fun portraitBoxes(panel: Panel) = - GamepadGeometry.layout(panel.width.toFloat(), panel.controlsHeight.toFloat(), panel.density, portraitDock = true, grips = true) + GamepadGeometry.layout(panel.width.toFloat(), panel.controlsHeight.toFloat(), panel.density, portraitDock = true) @Test fun everyControlIsPlacedAndPanelsOnlyWhenUpright() { for (panel in panels) { val upright = panel.height > panel.width - val expected = Slot.values().toSet() - grips - setOf(Slot.LEFT_TOUCH, Slot.RIGHT_TOUCH) - if (upright) emptySet() else setOf(Slot.PANELS) + val expected = Slot.values().toSet() - grips - if (upright) emptySet() else setOf(Slot.PANELS) assertEquals(panel.name, expected, boxes(panel).keys) } } @@ -94,7 +94,7 @@ class GamepadGeometryTest { @Test fun portraitDockPlacesAllControlsWithinThePanel() { for (panel in portraitPanels) { val b = portraitBoxes(panel) - assertEquals(panel.name, Slot.values().toSet() - setOf(Slot.STEAM, Slot.QAM, Slot.PANELS, Slot.LEFT_TOUCH, Slot.RIGHT_TOUCH), b.keys) + assertEquals(panel.name, Slot.values().toSet(), b.keys) for ((slot, box) in b) { val where = "${panel.name}: $slot $box" assertTrue(where, box.left >= 0f && box.top >= 0f) @@ -126,70 +126,20 @@ class GamepadGeometryTest { } } - @Test fun portraitDockPutsShouldersAndMenusInOneRowAboveTheGripsAndTheGamepad() { + @Test fun portraitDockMovesUtilitiesAndGripsAboveTheGamepad() { for (panel in portraitPanels) { val b = portraitBoxes(panel) - val row = listOf(Slot.LEFT_OUTER_SHOULDER, Slot.LEFT_INNER_SHOULDER, Slot.VIEW, Slot.MENU, Slot.RIGHT_INNER_SHOULDER, Slot.RIGHT_OUTER_SHOULDER) - for (slot in row) assertEquals("${panel.name}: $slot", 8 * panel.density, b.getValue(slot).top, 0.5f) - assertEquals(panel.name, row, row.sortedBy { b.getValue(it).cx }) + assertEquals(panel.name, 8 * panel.density, b.getValue(Slot.VIEW).top, 0.5f) assertTrue(panel.name, b.getValue(Slot.MENU).bottom < b.getValue(Slot.L4).top) - assertTrue(panel.name, b.getValue(Slot.L4).bottom < b.getValue(Slot.LEFT_SECOND).top) - assertTrue(panel.name, b.getValue(Slot.LEFT_SECOND).bottom < b.getValue(Slot.LEFT_MAIN).top) + assertTrue(panel.name, b.getValue(Slot.L4).bottom < b.getValue(Slot.LEFT_OUTER_SHOULDER).top) + assertTrue(panel.name, b.getValue(Slot.LEFT_OUTER_SHOULDER).bottom < b.getValue(Slot.LEFT_SECOND).top) } } - @Test fun aPortraitDockWithoutGripsGivesTheirRowToTheGamepad() { - for (panel in portraitPanels) { - val with = portraitBoxes(panel) - val without = GamepadGeometry.layout(panel.width.toFloat(), panel.controlsHeight.toFloat(), panel.density, portraitDock = true, grips = false) - assertTrue(panel.name, grips.none { it in without }) - assertTrue(panel.name, without.getValue(Slot.LEFT_SECOND).top < with.getValue(Slot.LEFT_SECOND).top) - assertTrue(panel.name, without.getValue(Slot.LEFT_SECOND).width >= with.getValue(Slot.LEFT_SECOND).width) - } - } - - @Test fun aShorterPortraitDockStillGetsTheUprightLayout() { - val (w, h, density) = Triple(1080f, 1010f, 369 / 160f) - val b = GamepadGeometry.layout(w, h, density, portraitDock = true, grips = false) - assertEquals(8 * density, b.getValue(Slot.VIEW).top, 0.5f) - assertTrue(b.getValue(Slot.RIGHT_SECOND).width >= w * 0.3f) - } - @Test fun shortPanelsKeepTheExistingLayoutEvenWhenPortraitDockIsRequested() { for ((width, height, density) in listOf(Triple(1920f, 1080f, 2f), Triple(720f, 600f, 2.3f))) { assertEquals(GamepadGeometry.layout(width, height, density), GamepadGeometry.layout(width, height, density, portraitDock = true)) } } - - @Test fun aPortraitDockWithTrackpadsPutsThemOutsideBothSticksWithoutOverlap() { - for (panel in portraitPanels) { - val b = GamepadGeometry.layout(panel.width.toFloat(), panel.controlsHeight.toFloat(), panel.density, portraitDock = true, trackpads = true) - val row = listOf(Slot.LEFT_TOUCH, Slot.LEFT_MAIN, Slot.RIGHT_MAIN, Slot.RIGHT_TOUCH) - assertEquals(panel.name, row, row.sortedBy { b.getValue(it).cx }) - val placed = b.entries.toList() - for (i in placed.indices) for (j in i + 1 until placed.size) - assertFalse("${panel.name}: ${placed[i].key} overlaps ${placed[j].key}", placed[i].value.overlaps(placed[j].value)) - for ((slot, box) in b) assertTrue("${panel.name}: $slot", box.bottom <= panel.controlsHeight + .5f && box.right <= panel.width + .5f) - } - } - - @Test fun landscapePanelsGiveTheGripsSlotsWithoutOverlap() { - for (panel in panels.filter { it.width > it.height }) { - val b = GamepadGeometry.layout(panel.width.toFloat(), panel.controlsHeight.toFloat(), panel.density, grips = true) - assertTrue(panel.name, grips.all { it in b }) - val placed = b.entries.toList() - for (i in placed.indices) for (j in i + 1 until placed.size) - assertFalse("${panel.name}: ${placed[i].key} overlaps ${placed[j].key}", placed[i].value.overlaps(placed[j].value)) - for ((slot, box) in b) assertTrue("${panel.name}: $slot", box.top >= -.5f && box.bottom <= panel.controlsHeight + .5f) - } - } - - @Test fun gripsNeverOverlapTheClustersOnSmallTallPanels() { - for ((w, h) in listOf(360f to 296f, 480f to 300f, 640f to 420f, 900f to 520f)) { - val b = GamepadGeometry.layout(w, h, 1f, grips = true) - for (g in grips.filter { it in b }) for ((slot, box) in b) if (slot != g) - assertFalse("$w x $h: $g overlaps $slot", b.getValue(g).overlaps(box)) - } - } } 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 0b85a15c64..ed1d58f2bd 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt @@ -9,7 +9,6 @@ import androidx.compose.foundation.verticalScroll import androidx.compose.ui.test.* import com.droiddeck.launcher.input.* import com.droiddeck.launcher.R -import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.SessionState import com.droiddeck.launcher.session.SessionService import org.junit.Assert.* @@ -36,8 +35,6 @@ class InputSettingsTest { context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE).edit().clear().commit() context.getSharedPreferences("input-surfaces", Context.MODE_PRIVATE).edit().clear().commit() context.getSharedPreferences("controller", Context.MODE_PRIVATE).edit().clear().commit() - context.getSharedPreferences("game-controls", Context.MODE_PRIVATE).edit().clear().commit() - context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() } @Test fun commandSymbolsAreSelectableForAnyCustomButton() { @@ -63,12 +60,42 @@ class InputSettingsTest { ModeSettingsActions(onResolution = {}, onHdr = {}, onTouch = {}, onSuspendPolicy = {}, onOsc = {}, onInputSettings = { opened++ }, onDirectAudio = {}, onMic = {}, onDismiss = {}), SheetTab.CONTROLS) } } - compose.onNodeWithText(context.getString(R.string.ctrl_edit)).performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.OnClick) + compose.onNodeWithTag("input-profile-expand").performClick() + compose.onNodeWithText(context.getString(R.string.ctrl_edit)).performClick() compose.runOnIdle { assertEquals(1, opened); mode.value = SessionService.MODE_DESKTOP } - compose.onNodeWithText(context.getString(R.string.ctrl_edit)).performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.OnClick) + compose.onNodeWithText(context.getString(R.string.ctrl_edit)).performClick() compose.runOnIdle { assertEquals(2, opened) } } + @Test fun quickMenuCombinesPartsWithoutChangingTheSavedProfile() { + val original = InputLibraries.read(context) + compose.setContent { DroidDeckTheme { + androidx.compose.foundation.layout.Column { InputQuickSettings(rememberMenuHost(), desktop = true) } + } } + compose.onNodeWithTag("setting-input-profile").assertExists() + compose.onNodeWithTag("setting-input-part-PHYSICAL").assertDoesNotExist() + compose.onNodeWithTag("input-profile-expand").performClick() + compose.onNodeWithTag("setting-input-part-PHYSICAL").assertExists() + compose.onNodeWithTag("setting-input-part-PRIMARY").assertExists() + compose.onNodeWithTag("setting-input-part-SECONDARY").performClick() + compose.onNodeWithText("Deck grips + trackpads").performScrollTo().performClick() + compose.runOnIdle { + val changed = InputLibraries.read(context) + assertEquals(InputStockLayouts.DECK, changed.activePart(true, InputRole.SECONDARY).bindings) + assertEquals(original.profiles, changed.profiles) + assertEquals(original.compileActive(false), changed.compileActive(false)) + } + compose.onNodeWithText(context.getString(R.string.input_save_combination)).performClick() + compose.onNode(hasSetTextAction()).performTextInput("Reading") + compose.onNodeWithText(context.getString(R.string.gesture_save_changes)).performClick() + compose.runOnIdle { + val saved = InputLibraries.read(context) + assertEquals("Reading", saved.profile(saved.activeId(true)).name) + assertTrue(saved.selection(true).parts.isEmpty()) + assertEquals(original.profile("desktop"), saved.profile("desktop")) + } + } + @Test fun actionDraftSurvivesRouteAndTypeChanges() { var saved: InputAction? = null compose.setContent { DroidDeckTheme { InputActionEditor(InputControl.RS, InputAction.Scroll(27f, true), "Right stick", {}, { saved = it }) } } @@ -87,7 +114,8 @@ class InputSettingsTest { @Test fun bindingEditorPersistsDisabledWithoutChangingTouchControls() { var changed = false compose.setContent { DroidDeckTheme { InputSettingsPage({}, { changed = true }) } } - compose.onNodeWithTag("input-remap").performScrollTo().performClick() + compose.onNodeWithTag("input-profile-game").performScrollTo().performClick() + compose.onNodeWithTag("input-part-physical").performScrollTo().performClick() compose.onNodeWithTag("input-binding-a").performScrollTo().performClick() compose.onNodeWithText("Disabled", substring = false).performScrollTo().performClick() compose.runOnIdle { assertFalse(changed) } @@ -106,9 +134,12 @@ class InputSettingsTest { val layout = library.layout(InputProfile.GAME, InputRole.SECONDARY)!! compose.setContent { DroidDeckTheme { InputSurfaceDialog(InputProfile.GAME, {}, { changed = true }, role = InputRole.PRIMARY, layoutId = layout.id, bindingsId = library.profile(InputProfile.GAME).binding(InputRole.SECONDARY)) } } - addButton(layout) - compose.onNodeWithText(context.getString(R.string.input_options)).assertExists() - compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick() + compose.onNodeWithTag("input-editor-tools").performClick() + compose.onNodeWithText(context.getString(R.string.input_editor_add)).performClick() + compose.onNodeWithText(context.getString(R.string.input_element_button), substring = false).performClick() + compose.onNodeWithTag("input-editor-tools").performClick() + compose.onNodeWithText(context.getString(R.string.input_properties)).assertExists() + compose.onNodeWithText(context.getString(R.string.input_editor_done)).performClick() compose.runOnIdle { assertTrue(changed) val updated = InputLibraries.read(context) @@ -118,106 +149,64 @@ class InputSettingsTest { } } - @Test fun remapButtonsOpensThePhysicalControllerAndBackReturnsToTheControllerPage() { + @Test fun aNewProfileIsIndependentAndDoesNotBecomeActive() { compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } - compose.onNodeWithTag("input-remap").performScrollTo().performClick() - compose.onNodeWithText(context.getString(R.string.input_physical).uppercase()).assertExists() + compose.onNodeWithText(context.getString(R.string.input_new_profile)).performScrollTo().performClick() + compose.onNodeWithTag("input-name").performTextInput("Minecraft") + compose.onNodeWithText(context.getString(R.string.gesture_save_changes)).performClick() + compose.runOnIdle { + val library = InputLibraries.read(context) + val created = library.profiles.single { it.name == "Minecraft" } + for (role in InputRole.entries) assertNotEquals(library.profile(InputProfile.GAME).binding(role), created.binding(role)) + assertNotEquals(library.layout(InputProfile.GAME, InputRole.SECONDARY)!!.id, library.layout(created.id, InputRole.SECONDARY)!!.id) + assertEquals(InputProfiles.AUTO, library.selected) + } + } + + @Test fun openingAProfileDoesNotActivateItAndBackKeepsItsContext() { + compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } + compose.onNodeWithTag("input-profile-desktop").performScrollTo().performClick() + compose.onNodeWithTag("input-part-physical").performScrollTo().performClick() compose.onNodeWithTag("input-binding-a").performScrollTo().performClick() - compose.onNodeWithText("Disabled", substring = false).performScrollTo().performClick() compose.onNodeWithTag("input-action-save").performClick() - compose.onNodeWithTag("input-remap-reset").performScrollTo().assertExists() - compose.onNodeWithText(context.getString(R.string.mode_back)).performClick() - compose.onNodeWithTag("osc-edit").assertExists() - compose.runOnIdle { - assertEquals(InputProfiles.AUTO, InputLibraries.read(context).selected) - assertEquals(InputAction.Disabled, InputProfiles.read(context, InputProfile.GAME).action(InputRole.PHYSICAL, InputControl.A)) - } - } - - @Test fun inGameRemapOpensStraightOnThePhysicalController() { - var closed = false - compose.setContent { DroidDeckTheme { InputSettingsPage({ closed = true }, remapOnly = true) } } compose.onNodeWithTag("input-binding-a").assertExists() - compose.onNodeWithTag("osc-edit").assertDoesNotExist() compose.onNodeWithText(context.getString(R.string.mode_back)).performClick() - compose.runOnIdle { assertTrue(closed) } + compose.onNodeWithTag("input-part-secondary").assertExists() + compose.runOnIdle { assertEquals(InputProfiles.AUTO, InputLibraries.read(context).selected) } } - @Test fun settingsShowTheInGameControllerPageForTheDefault() { + @Test fun profileCreationCanExplicitlyShareOnlyPhysicalControls() { compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } - compose.onNodeWithText(context.getString(R.string.osc_group_for, context.getString(R.string.osc_default)).uppercase()).assertExists() - for (label in listOf(R.string.osc_layout, R.string.osc_edit_layout, R.string.osc_show, R.string.input_touches, R.string.unfolded_controls, - R.string.input_virtual_controller, R.string.ctrl_rumble, R.string.ctrl_dead_zone, R.string.input_remap_buttons)) - compose.onNodeWithText(context.getString(label)).performScrollTo().assertExists() - for (removed in listOf(R.string.input_default_profiles, R.string.input_profiles, R.string.input_new_profile)) - compose.onNodeWithText(context.getString(removed)).assertDoesNotExist() - compose.onNodeWithTag("input-profile-game").assertDoesNotExist() - compose.onNodeWithTag("osc-${SessionPrefs.OSC_NEVER}").performScrollTo().performClick() - compose.runOnIdle { assertEquals(SessionPrefs.OSC_NEVER, SessionPrefs.oscMode(context)) } - } - - @Test fun choosingTheDefaultLayoutAppliesToGamesWithoutTheirOwn() { - InputLibraries.update(context) { it.copyLayout(InputLibraries.OVERLAY, "Big sticks", "big-sticks") } - ControlsChoice.newForGame(context, 7, "Castle Crashers", desktop = false) - compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } - compose.onNodeWithTag("setting-osc-layout").performScrollTo().performClick() - compose.onNodeWithText(context.getString(R.string.osc_layout_steam)).assertExists() - compose.onNodeWithText("Big sticks").performClick() + compose.onNodeWithText(context.getString(R.string.input_new_profile)).performScrollTo().performClick() + compose.onNodeWithTag("input-name").performTextInput("Shared controls") + compose.onNodeWithTag("input-share-physical").performClick() + compose.onNodeWithText(context.getString(R.string.gesture_save_changes)).performClick() compose.runOnIdle { - assertEquals("big-sticks", ControlsChoice.current(context, null, steamMode = true)) - assertEquals("big-sticks", ControlsChoice.current(context, 8, steamMode = true)) - assertNotEquals("big-sticks", ControlsChoice.current(context, 7, steamMode = true)) - assertEquals("big-sticks", InputLibraries.read(context).activeLayout(false, InputRole.PRIMARY)!!.id) + val library = InputLibraries.read(context) + val created = library.profiles.single { it.name == "Shared controls" } + assertEquals(library.profile("game").binding(InputRole.PHYSICAL), created.binding(InputRole.PHYSICAL)) + assertNotEquals(library.profile("game").binding(InputRole.SECONDARY), created.binding(InputRole.SECONDARY)) } - compose.onNodeWithTag("osc-edit").performScrollTo().performClick() - compose.onNodeWithText(context.getString(R.string.osc_scope_default, "Big sticks")).assertExists() - compose.onNodeWithTag("input-editor-split").assertDoesNotExist() } - @Test fun useDefaultReturnsAGameToTheDefaultLayout() { - ControlsChoice.newForGame(context, 42, "Castle Crashers", desktop = false) - compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } - compose.onNodeWithText(context.getString(R.string.osc_games_own).uppercase()).performScrollTo().assertExists() - compose.onNodeWithTag("osc-use-default-42").performScrollTo().performClick() - compose.runOnIdle { assertNull(GameControls.bindings(context, 42)) } - compose.onNodeWithText(context.getString(R.string.osc_games_own).uppercase()).assertDoesNotExist() - } - - @Test fun justThisGameSavesTheEditIntoTheGamesOwnCopy() { + @Test fun hidingEditorToolsPreservesPlacedElements() { val library = InputLibraries.read(context) - val layout = library.layout("game", InputRole.PRIMARY)!! - var closed = false - compose.setContent { DroidDeckTheme { InputSurfaceDialog("game", { closed = true }, {}, role = InputRole.PRIMARY, - layoutId = layout.id, bindingsId = library.profile("game").binding(InputRole.PRIMARY), - scope = context.getString(R.string.osc_scope_default, layout.name), - split = InputEditorSplit(context.getString(R.string.osc_just_this_game), "Gamepad · saved for Castle Crashers", - { lib, layoutId, bindingsId -> ControlsChoice.copyForGame(context, lib, 7, "Castle Crashers", false, layoutId, bindingsId) }, - { bindingsId -> ControlsChoice.useForGame(context, 7, "Castle Crashers", bindingsId) }) ) } } - compose.onNodeWithTag("input-editor-split").performClick() - compose.onNodeWithText("Gamepad · saved for Castle Crashers").assertExists() - compose.onNodeWithTag("input-editor-split").assertDoesNotExist() - pressPlus(2) - compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick() - compose.runOnIdle { - assertTrue(closed) - val saved = InputLibraries.read(context) - assertTrue(OnScreenLayout.generated(saved.layouts.first { it.id == layout.id })) - val own = saved.layouts.first { it.id == ControlsChoice.current(context, 7, steamMode = false) } - assertNotEquals(layout.id, own.id) - assertFalse(OnScreenLayout.generated(own)) - assertEquals(layout.id, ControlsChoice.current(context, 8, steamMode = false)) - } + val layout = library.layout("game", InputRole.SECONDARY)!! + compose.setContent { DroidDeckTheme { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY, + layoutId = layout.id, bindingsId = library.profile("game").binding(InputRole.SECONDARY)) } } + compose.onNodeWithTag("input-editor-tools").performClick() + compose.onNodeWithText(context.getString(R.string.input_editor_add)).performClick() + compose.onNodeWithText(context.getString(R.string.input_element_button)).performClick() + compose.onNodeWithTag("input-layout-canvas").performTouchInput { click(center) } + compose.onNodeWithTag("input-editor-tools").performClick() + compose.onNodeWithText(context.getString(R.string.input_hide_tools)).performClick() + compose.onNodeWithText(context.getString(R.string.input_editor_add)).assertDoesNotExist() + compose.onNodeWithTag("input-editor-tools").performClick() + compose.onNodeWithText(context.getString(R.string.input_editor_done)).performClick() + compose.runOnIdle { assertEquals(layout.elements.size + 1, InputLibraries.read(context).layout("game", InputRole.SECONDARY)!!.elements.size) } } - private val add get() = context.getString(R.string.input_editor_add) - - private fun addButton(layout: SavedInputLayout) { - compose.onNodeWithText(add).performScrollTo().performClick() - val clicks = listOf("legacy:l3", "legacy:r3").count { id -> layout.elements.none { it.id == id } } - compose.onAllNodesWithText(add)[1 + clicks + InputElementKind.entries.indexOf(InputElementKind.BUTTON)].performScrollTo().performClick() - } - - @Test fun theEditorToolbarStaysAboveTheCanvasAndAddOpensAndClosesItsList() { + @Test fun localToolsCanMoveAndExpandWithoutMovingTheCanvas() { val library = InputLibraries.read(context) compose.setContent { DroidDeckTheme { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY, layoutId = library.layout("game", InputRole.SECONDARY)!!.id, bindingsId = library.profile("game").binding(InputRole.SECONDARY)) } } @@ -227,75 +216,69 @@ class InputSettingsTest { assertEquals(android.view.WindowManager.LayoutParams.MATCH_PARENT, window.attributes.height) } val canvas = compose.onNodeWithTag("input-layout-canvas").fetchSemanticsNode().boundsInRoot - val tools = compose.onNodeWithTag("input-editor-tools").fetchSemanticsNode().boundsInRoot - assertTrue(tools.top >= canvas.top && tools.bottom < canvas.center.y) - val button = context.getString(R.string.input_element_button) - compose.onNodeWithText(button).assertDoesNotExist() - compose.onNodeWithText(add).performScrollTo().performClick() - compose.onNodeWithText(button).assertIsDisplayed() - compose.onAllNodesWithText(add).onFirst().performScrollTo().performClick() - compose.onNodeWithText(button).assertDoesNotExist() + val before = compose.onNodeWithTag("input-editor-tools").fetchSemanticsNode().boundsInRoot + compose.onNodeWithTag("input-editor-tools").performTouchInput { swipe(center, center + androidx.compose.ui.geometry.Offset(250f, 150f), 500) } + val after = compose.onNodeWithTag("input-editor-tools").fetchSemanticsNode().boundsInRoot + assertTrue(after.left > before.left + 100f) + compose.onNodeWithTag("input-editor-tools").performClick() + compose.onNodeWithText(context.getString(R.string.input_editor_add)).assertIsDisplayed() assertEquals(canvas, compose.onNodeWithTag("input-layout-canvas").fetchSemanticsNode().boundsInRoot) + compose.onNodeWithTag("input-editor-tools").performClick() + compose.onNodeWithText(context.getString(R.string.input_editor_add)).assertDoesNotExist() } - @Test @Config(qualifiers = "w833dp-h468dp-land-369dpi") - fun removedKitControlsWaitUnderHiddenAndRestoringThemKeepsTheGamepadGenerated() { - val library = InputLibraries.read(context) - val layout = library.layout("game", InputRole.PRIMARY)!! - val a = InputLibraries.defaultPositions(context, library, layout)!!.first.single { it.id == "legacy:a" } - compose.setContent { DroidDeckTheme { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY, - layoutId = layout.id, bindingsId = library.profile("game").binding(InputRole.PRIMARY)) } } - compose.onNodeWithText(context.getString(R.string.input_hidden_count, 0)).performScrollTo().performClick() - compose.onNodeWithText(context.getString(R.string.input_nothing_hidden)).assertExists() - compose.onNodeWithText(context.getString(R.string.input_hidden_count, 0)).performScrollTo().performClick() - compose.onNodeWithTag("input-layout-canvas").performTouchInput { click(percentOffset(a.x + a.width / 2, a.y + a.height / 2)) } - compose.onNodeWithText(context.getString(R.string.input_remove_element)).performClick() - compose.onNodeWithText(context.getString(R.string.input_hidden_count, 1)).performScrollTo().performClick() - compose.onNodeWithText(context.getString(R.string.input_restore)).performClick() - compose.onNodeWithText(context.getString(R.string.input_hidden_count, 0)).assertExists() - compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick() - compose.runOnIdle { assertTrue(OnScreenLayout.generated(InputLibraries.read(context).layouts.first { it.id == layout.id })) } + @Test fun deckPresetOffersItsRealElementsAndTheCommonEditor() { + InputLibraries.update(context) { it.useLayout("game", InputRole.SECONDARY, InputLibraries.DECK, shared = true) } + compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } + compose.onNodeWithTag("input-profile-game").performScrollTo().performClick() + compose.onNodeWithTag("input-part-secondary").performScrollTo().performClick() + compose.onNodeWithTag("input-element-legacy:l4").performScrollTo().assertIsDisplayed() + compose.onNodeWithTag("input-binding-a").assertDoesNotExist() } - @Test fun resetAfterResizingMakesTheGamepadFollowTheKitAgain() { - 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)) } } - val reset = compose.onNodeWithText(context.getString(R.string.hud_reset_button)) - reset.performScrollTo().assertIsNotEnabled() - pressPlus(2) - reset.performScrollTo().assertIsEnabled().performClick() - compose.onNodeWithTag("input-editor-scale").assertTextEquals("100%") - reset.performScrollTo().assertIsNotEnabled() - compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick() - compose.runOnIdle { assertTrue(OnScreenLayout.generated(InputLibraries.read(context).layouts.first { it.id == layout.id })) } + @Test fun mouseTrackpadPresetIsEditableLikeAnyOtherLayout() { + InputLibraries.update(context) { it.useLayout("game", InputRole.SECONDARY, InputLibraries.TRACKPAD, shared = true) } + compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } + compose.onNodeWithTag("input-profile-game").performScrollTo().performClick() + compose.onNodeWithTag("input-part-secondary").performScrollTo().performClick() + compose.onNodeWithTag("input-element-legacy:right-pad").performScrollTo().assertIsDisplayed() + compose.onNodeWithTag("input-surface-secondary").performScrollTo().assertIsDisplayed() + compose.onNodeWithTag("input-binding-a").assertDoesNotExist() } - @Test @Config(qualifiers = "w833dp-h468dp-land-369dpi") - fun removingAndRestoringAKitButtonKeepsItsAction() { - val library = InputLibraries.read(context) - val layout = library.layout("game", InputRole.PRIMARY)!! - val bindingsId = library.profile("game").binding(InputRole.PRIMARY) - InputLibraries.update(context) { lib -> lib.preset(bindingsId).let { b -> lib.withPreset(b.copy(elements = b.elements + ("legacy:a" to InputAction.Keys(listOf(30))))) } } - val a = InputLibraries.defaultPositions(context, library, layout)!!.first.single { it.id == "legacy:a" } - compose.setContent { DroidDeckTheme { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY, layoutId = layout.id, bindingsId = bindingsId) } } - compose.onNodeWithTag("input-layout-canvas").performTouchInput { click(percentOffset(a.x + a.width / 2, a.y + a.height / 2)) } - compose.onNodeWithText(context.getString(R.string.input_remove_element)).performClick() - compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick() - compose.runOnIdle { assertEquals(InputAction.Keys(listOf(30)), InputLibraries.read(context).preset(bindingsId).elements["legacy:a"]) } + @Test fun primaryScreenOffersItsActualElementsAndTheCommonEditor() { + compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } + compose.onNodeWithTag("input-profile-game").performScrollTo().performClick() + compose.onNodeWithTag("input-part-primary").performScrollTo().performClick() + compose.onNodeWithTag("input-element-legacy:a").performScrollTo().assertIsDisplayed() + compose.onNodeWithTag("input-binding-a").assertDoesNotExist() + compose.onNodeWithTag("input-surface-primary").performScrollTo().performClick() + compose.onNodeWithTag("input-editor-tools").performClick() + compose.onNodeWithText(context.getString(R.string.input_editor_add)).assertIsDisplayed() + compose.onNodeWithTag("input-layout-canvas").assertExists() } - @Test fun resetAndSaveKeepTheDpadDirectionOverrides() { - val library = InputLibraries.read(context) - val layout = library.layout("game", InputRole.PRIMARY)!! - val bindingsId = library.profile("game").binding(InputRole.PRIMARY) - InputLibraries.update(context) { lib -> lib.preset(bindingsId).let { b -> lib.withPreset(b.copy(elements = b.elements + ("legacy:up" to InputAction.Keys(listOf(103))))) } } - compose.setContent { DroidDeckTheme { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY, layoutId = layout.id, bindingsId = bindingsId) } } - pressPlus(2) - compose.onNodeWithText(context.getString(R.string.hud_reset_button)).performScrollTo().performClick() - compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick() - compose.runOnIdle { assertEquals(InputAction.Keys(listOf(103)), InputLibraries.read(context).preset(bindingsId).elements["legacy:up"]) } + @Test fun deviceSettingsAreInlineBelowProfiles() { + compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } + compose.onNodeWithTag("input-more").assertDoesNotExist() + compose.onNodeWithText(context.getString(R.string.ctrl_dead_zone)).performScrollTo().assertIsDisplayed() + compose.onNodeWithTag("input-profile-game").performScrollTo().assertIsDisplayed() + } + + @Test fun migratedPadClicksRemainEditableWithoutChangingMovement() { + compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } + compose.onNodeWithTag("input-profile-desktop").performScrollTo().performClick() + compose.onNodeWithTag("input-part-secondary").performScrollTo().performClick() + compose.onNodeWithTag("input-click-legacy:right-pad").performScrollTo().performClick() + compose.onNodeWithText("Disabled", substring = false).performScrollTo().performClick() + compose.onNodeWithTag("input-action-save").performClick() + compose.runOnIdle { + val library = InputLibraries.read(context) + val pad = library.layout("desktop", InputRole.SECONDARY)!!.elements.first { it.control == InputControl.RIGHT_PAD } + val profile = library.compile("desktop") + assertEquals(InputAction.Disabled, profile.elementClickAction(InputRole.SECONDARY, pad)) + assertEquals(InputAction.Pointer(), profile.elementAction(InputRole.SECONDARY, pad.id, pad.control)) + } } @Test @Config(sdk = [34]) fun secondarySettingsCanOpenAnActivityDialogAndCloseCleanly() { @@ -308,8 +291,8 @@ class InputSettingsTest { val host = androidx.compose.ui.platform.LocalContext.current.findActivity() as androidx.activity.ComponentActivity if (open.value) InputDisplayContent(host, display, { open.value = false }) { InputSettingsPage({ open.value = false }) } } } - compose.onNodeWithText(context.getString(R.string.input_read_timing)).performScrollTo().performClick() - compose.onNodeWithText(context.getString(R.string.common_close)).assertExists() + compose.onNodeWithText(context.getString(R.string.input_new_profile)).performScrollTo().performClick() + compose.onNodeWithTag("input-name").assertExists() compose.runOnIdle { assertTrue(ShadowDialog.getShownDialogs().filterIsInstance().any { it.isShowing && it.display.displayId == displayId }) val dialog = ShadowDialog.getShownDialogs().last { it !is Presentation && it.isShowing } @@ -437,14 +420,15 @@ class InputSettingsTest { 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.SECONDARY)) } } } - compose.onNodeWithText(context.getString(R.string.hud_reset_button)).performScrollTo().assertIsNotEnabled() - repeat(4) { compose.onNodeWithText("\u2212").performScrollTo().performClick() } - compose.onNodeWithTag("input-editor-scale").assertTextEquals("80%") + compose.onNodeWithTag("input-editor-tools").performClick() + compose.onNodeWithText(context.getString(R.string.input_reset_positions)).performScrollTo().assertIsNotEnabled() + compose.onNodeWithTag("input-editor-scale").performScrollTo().performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(80f) } compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick() val scaled = InputLibraries.read(context).layouts.first { it.id == layout.id } assertEquals(layout.elements.scaled(.8f), scaled.elements) compose.runOnIdle { round.value = 1 } - compose.onNodeWithText(context.getString(R.string.hud_reset_button)).performScrollTo().performClick() + compose.onNodeWithTag("input-editor-tools").performClick() + compose.onNodeWithText(context.getString(R.string.input_reset_positions)).performScrollTo().performClick() compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick() compose.runOnIdle { assertEquals(layout.elements, InputLibraries.read(context).layouts.first { it.id == layout.id }.elements) } } @@ -466,54 +450,162 @@ class InputSettingsTest { com.droiddeck.launcher.input.ControllerPrefs.setSnap(context, true) } - private fun pressPlus(times: Int) = repeat(times) { compose.onNodeWithText("+").performScrollTo().performClick() } + @Test fun quickButtonTogglesHideBuiltInButtonsWithoutDeletingThem() { + compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } + compose.onNodeWithTag("input-profile-game").performScrollTo().performClick() + compose.onNodeWithTag("input-part-primary").performScrollTo().performClick() + val before = InputLibraries.read(context).layout("game", InputRole.PRIMARY)!! + compose.onNodeWithTag("setting-quick-keyboard").performScrollTo().performClick() + compose.runOnIdle { + val after = InputLibraries.read(context).layout("game", InputRole.PRIMARY)!! + assertEquals(before.elements, after.elements) + assertEquals(setOf(InputCommand.KEYBOARD), after.style.hidden) + } + compose.onNodeWithTag("setting-quick-keyboard").performScrollTo().performClick() + compose.runOnIdle { assertTrue(InputLibraries.read(context).layout("game", InputRole.PRIMARY)!!.style.hidden.isEmpty()) } + } - @Test fun sizeButtonsScaleTheWholeGamepadAndUndoAsOneStep() { + @Test fun layoutsCanBeImportedAndExported() { + val source = java.io.File(context.cacheDir, "jump.icp").apply { + writeText("""{"name":"Jump keys","elements":[{"type":"BUTTON","shape":"CIRCLE","bindings":["KEY_SPACE"],"scale":1.0,"x":0.8,"y":0.7,"text":"Jump"}]}""") + } + val target = java.io.File(context.cacheDir, "out.icp").apply { delete() } + val registry = object : androidx.activity.result.ActivityResultRegistry() { + override fun onLaunch(requestCode: Int, contract: androidx.activity.result.contract.ActivityResultContract, input: I, + options: androidx.core.app.ActivityOptionsCompat?) { + dispatchResult(requestCode, android.net.Uri.fromFile(if (input is String) target else source)) + } + } + val owner = object : androidx.activity.result.ActivityResultRegistryOwner { override val activityResultRegistry = registry } + compose.setContent { androidx.compose.runtime.CompositionLocalProvider(androidx.activity.compose.LocalActivityResultRegistryOwner provides owner) { + DroidDeckTheme { InputSettingsPage({}) } + } } + compose.onNodeWithTag("input-profile-game").performScrollTo().performClick() + compose.onNodeWithTag("input-part-primary").performScrollTo().performClick() + compose.onNodeWithText(context.getString(R.string.input_saved_layouts)).performScrollTo().performClick() + compose.onNodeWithTag("layout-manage-${InputLibraries.OVERLAY}").performScrollTo().performClick() + compose.onNodeWithText(context.getString(R.string.screen_key_layout_export)).assertDoesNotExist() + compose.onNodeWithText(context.getString(R.string.common_close)).performClick() + compose.onNodeWithTag("input-layout-import").performScrollTo().performClick() + compose.waitUntil(5_000) { InputLibraries.read(context).layout("game", InputRole.PRIMARY)!!.name == "Jump keys" } + val imported = InputLibraries.read(context).layout("game", InputRole.PRIMARY)!! + assertEquals(InputLayoutScreen.MAIN, imported.screen) + assertEquals(InputAction.Keys(listOf(57)), InputLibraries.read(context).compile("game").elementAction(InputRole.PRIMARY, imported.elements.single().id, InputControl.A)) + compose.onNodeWithText(context.getString(R.string.input_saved_layouts)).performScrollTo().performClick() + compose.onNodeWithTag("layout-manage-${imported.id}").performScrollTo().performClick() + compose.onNodeWithText(context.getString(R.string.screen_key_layout_export)).performClick() + compose.waitUntil(5_000) { target.isFile && target.length() > 0 } + assertEquals(source.readText().let { org.json.JSONObject(it).getString("name") }, org.json.JSONObject(target.readText()).getString("name")) + assertEquals("KEY_SPACE", org.json.JSONObject(target.readText()).getJSONArray("elements").getJSONObject(0).getJSONArray("bindings").getString(0)) + } + + @Test fun buttonSizeRegeneratesTheGamepadAndUndoesAsOneStep() { val library = InputLibraries.read(context) val layout = library.layout("game", InputRole.PRIMARY)!! - assertTrue(OnScreenLayout.generated(layout)) - val defaults = InputLibraries.defaultPositions(context, library, layout)!!.first + val (_, metrics) = InputLibraries.primaryDisplay(context) + assertNotNull(OnScreenLayout.generatedSize(context, layout, metrics.widthPixels, metrics.heightPixels)) compose.setContent { DroidDeckTheme { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY, layoutId = layout.id, bindingsId = library.profile("game").binding(InputRole.PRIMARY)) } } - val scale = compose.onNodeWithTag("input-editor-scale") - scale.assertTextEquals("100%") - pressPlus(2) - scale.assertTextEquals("110%") + compose.onNodeWithTag("input-editor-tools").performClick() + val slider = compose.onNodeWithTag("input-editor-scale").performScrollTo() + slider.assert(SemanticsMatcher.expectValue(androidx.compose.ui.semantics.SemanticsProperties.StateDescription, "100%")) + for (value in listOf(110f, 125f)) slider.performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(value) } compose.onNodeWithText(context.getString(R.string.input_editor_undo)).performScrollTo().performClick() - scale.assertTextEquals("100%") - pressPlus(5) - scale.assertTextEquals("125%") + slider.assert(SemanticsMatcher.expectValue(androidx.compose.ui.semantics.SemanticsProperties.StateDescription, "100%")) + slider.performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(125f) } compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick() compose.runOnIdle { val saved = InputLibraries.read(context).layouts.first { it.id == layout.id } - assertFalse(OnScreenLayout.generated(saved)) - assertEquals(defaults.map { it.id }, saved.elements.map { it.id }) - assertTrue(saved.elements.first { it.id == "legacy:a" }.width > defaults.first { it.id == "legacy:a" }.width * 1.2f) + assertEquals(1.25f, saved.scale) + assertNotNull(OnScreenLayout.generatedSize(context, saved, metrics.widthPixels, metrics.heightPixels)) + assertNotEquals(layout.elements.first { it.id == "legacy:a" }.y, saved.elements.first { it.id == "legacy:a" }.y) + } + } + + @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 sizeButtonsKeepAMovedFaceClusterInShape() { + fun buttonSizeKeepsMovedGamepadGroupsInShape() { val face = setOf("legacy:a", "legacy:b", "legacy:x", "legacy:y") val original = InputLibraries.read(context) val gamepad = original.layout("game", InputRole.PRIMARY)!! - val (defaults, aspect) = InputLibraries.defaultPositions(context, original, gamepad)!! - val moved = gamepad.copy(elements = defaults.map { if (it.id in face) it.copy(x = it.x + .012f, y = it.y + .017f) else it }, aspect = aspect) + val moved = gamepad.copy(elements = gamepad.elements.map { if (it.id in face) it.copy(x = it.x + .012f, y = it.y + .017f) else it }) InputLibraries.update(context) { it.withLayout(moved) } + val (_, metrics) = InputLibraries.primaryDisplay(context) + assertNull(OnScreenLayout.generatedSize(context, moved, metrics.widthPixels, metrics.heightPixels)) val library = InputLibraries.read(context) compose.setContent { DroidDeckTheme { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY, layoutId = moved.id, bindingsId = library.profile("game").binding(InputRole.PRIMARY)) } } - pressPlus(5) + compose.onNodeWithTag("input-editor-tools").performClick() + compose.onNodeWithTag("input-editor-scale").performScrollTo().performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(125f) } compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick() compose.runOnIdle { val saved = InputLibraries.read(context).layouts.first { it.id == moved.id } - val w = saved.aspect * 1000; val h = 1000f + assertEquals(1.25f, saved.scale) + val w = metrics.widthPixels; val h = metrics.heightPixels fun centre(id: String) = saved.elements.first { it.id == id }.let { (it.x + it.width / 2) * w to (it.y + it.height / 2) * h } - val cross = face.associateWith(::centre) assertEquals(centre("legacy:y").first, centre("legacy:a").first, 1f) assertEquals(centre("legacy:x").second, centre("legacy:b").second, 1f) - assertTrue("$cross", centre("legacy:y").second < centre("legacy:x").second && centre("legacy:x").second < centre("legacy:a").second) - assertTrue("$cross", centre("legacy:x").first < centre("legacy:a").first && centre("legacy:a").first < centre("legacy:b").first) + assertTrue(centre("legacy:y").second < centre("legacy:x").second && centre("legacy:x").second < centre("legacy:a").second) + assertEquals(centre("legacy:a").second - centre("legacy:y").second, centre("legacy:b").first - centre("legacy:x").first, 1f) + assertEquals(centre("legacy:up").first, centre("legacy:down").first, 1f) + assertEquals(centre("legacy:left").second, centre("legacy:right").second, 1f) val before = moved.elements.first { it.id == "legacy:a" } assertTrue(saved.elements.first { it.id == "legacy:a" }.width > before.width * 1.2f) } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceEditorViewTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceEditorViewTest.kt index 192e70d5e1..a6cbb2ab95 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceEditorViewTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceEditorViewTest.kt @@ -1,15 +1,29 @@ package com.droiddeck.launcher.ui +import android.content.Context +import android.view.InputDevice import android.view.MotionEvent +import android.view.View +import android.view.ViewGroup import com.droiddeck.launcher.input.InputControl +import com.droiddeck.launcher.input.InputLibraries import com.droiddeck.launcher.input.InputSurfaceElement import com.droiddeck.launcher.input.OnScreenLayout +import com.droiddeck.launcher.input.PadKit import com.droiddeck.launcher.input.SavedInputLayout +import com.droiddeck.launcher.session.SessionPrefs +import com.droiddeck.launcher.session.SessionService +import com.droiddeck.launcher.session.SessionState +import org.junit.After import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @@ -18,8 +32,17 @@ class InputSurfaceEditorViewTest { private val context get() = RuntimeEnvironment.getApplication() private val layout = SavedInputLayout("custom", "Custom", listOf(InputSurfaceElement(InputControl.A, .1f, .2f, .2f, .2f)), aspect = 2f) + @Before fun reset() { + for (name in listOf("input-profiles", "input-surfaces", "controller", "session")) context.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().commit() + } + + @After fun restoreSession() { + SessionState.deckPad = false + SessionState.mode = SessionService.MODE_STEAM + } + private fun view() = InputSurfaceEditorView(context).apply { - layout(0, 0, 1000, 1000) + place(1000, 1000) sourceLayout = layout aspect = layout.aspect elements = layout.elements @@ -27,13 +50,47 @@ class InputSurfaceEditorViewTest { } private fun center() = OnScreenLayout.editorElements(context, layout, 1000, 1000).first().let { (it.x + it.width / 2) * 1000 to (it.y + it.height / 2) * 1000 } - @Suppress("UNCHECKED_CAST") - private fun InputSurfaceEditorView.rendered() = javaClass.getDeclaredField("visibleElements").also { it.isAccessible = true }.get(this) as List + private fun overlay() = InputLibraries.read(context).layouts.first { it.id == InputLibraries.OVERLAY } + + private fun editor(layout: SavedInputLayout, w: Int, h: Int) = InputSurfaceEditorView(context).apply { + sourceLayout = layout + aspect = layout.aspect + elements = layout.elements + snap = false + place(w, h) + } + + private fun field(target: Any, name: String) = target.javaClass.getDeclaredField(name).also { it.isAccessible = true }.get(target) + private fun InputSurfaceEditorView.controls() = (field(field(this, "preview")!!, "customCanvas") as ViewGroup).let { canvas -> (0 until canvas.childCount).map(canvas::getChildAt) } + private fun InputSurfaceEditorView.artworkDpad() = field(field(this, "preview")!!, "artworkDpad") as List<*> + private fun InputSurfaceEditorView.rects() = controls().map { listOf(it.left, it.top, it.width, it.height) } + + private fun InputSurfaceEditorView.assertControlsDrawnWhereDisplayed() { + val shown = rendered() + val views = controls() + assertEquals(shown.size, views.size) + for ((e, v) in shown.zip(views)) { + assertEquals(e.id, e.x * width, v.left.toFloat(), 1f) + assertEquals(e.id, e.y * height, v.top.toFloat(), 1f) + assertEquals(e.id, e.width * width, v.width.toFloat(), 1f) + assertEquals(e.id, e.height * height, v.height.toFloat(), 1f) + } + } private fun InputSurfaceEditorView.touch(action: Int, x: Float, y: Float) { MotionEvent.obtain(0, 10, action, x, y, 0).also { onTouchEvent(it); it.recycle() } } + private fun InputSurfaceEditorView.mouse(action: Int, x: Float, y: Float) { + val properties = MotionEvent.PointerProperties().apply { id = 0; toolType = MotionEvent.TOOL_TYPE_MOUSE } + val coords = MotionEvent.PointerCoords().apply { this.x = x; this.y = y; pressure = 1f } + val buttons = if (action == MotionEvent.ACTION_UP) 0 else MotionEvent.BUTTON_PRIMARY + MotionEvent.obtain(0, 10, action, 1, arrayOf(properties), arrayOf(coords), 0, buttons, 1f, 1f, 0, 0, InputDevice.SOURCE_MOUSE, 0) + .also { dispatchTouchEvent(it); it.recycle() } + } + + private fun InputSurfaceEditorView.centre(id: String) = rendered().first { it.id == id }.let { (it.x + it.width / 2) * width to (it.y + it.height / 2) * height } + @Test fun editingStartsInTheDisplayedFrame() { val view = view() var started: Pair, Float>? = null @@ -70,7 +127,112 @@ class InputSurfaceEditorViewTest { view.elements = renamed view.aspect = 2f assertEquals(OnScreenLayout.editorElements(context, layout.copy(elements = renamed, aspect = 2f), 1000, 1000), view.rendered()) - view.layout(0, 0, 800, 1000) + view.place(800, 1000) assertEquals(OnScreenLayout.editorElements(context, layout.copy(elements = renamed, aspect = 2f), 800, 1000), view.rendered()) } + + @Test fun theOverlayEditorDrawsTheKitArtworkWhereTheSessionPlacesIt() { + val layout = overlay() + assertNotNull(PadKit.forOverlay(context, layout)) + val view = editor(layout, 2400, 1504) + assertEquals(OnScreenLayout.editorElements(context, layout, 2400, 1504), view.rendered()) + view.assertControlsDrawnWhereDisplayed() + assertEquals(4, view.artworkDpad().size) + } + + @Config(qualifiers = "xhdpi") + @Test fun controlsAddedForTheScreenAreDrawnOnTheFirstFrameInBothOrientations() { + SessionState.mode = SessionService.MODE_STEAM + SessionState.deckPad = true + SessionPrefs.setOscRearButtons(context, true) + SessionPrefs.setOscTrackpads(context, true) + val layout = overlay() + for ((w, h) in listOf(2400 to 1504, 1504 to 2400)) { + val view = editor(layout, w, h) + assertTrue(view.rendered().size > layout.elements.size) + view.assertControlsDrawnWhereDisplayed() + assertEquals(4, view.artworkDpad().size) + } + } + + @Test fun displayedControlsStayPutAcrossRepeatedRefreshesAndResizes() { + val view = editor(overlay(), 2400, 1504) + val first = view.rendered() + val drawn = view.rects() + repeat(3) { + view.elements = view.elements + view.aspect = view.aspect + view.sourceLayout = view.sourceLayout + view.place(1504, 2400) + view.assertControlsDrawnWhereDisplayed() + view.place(2400, 1504) + assertEquals(first, view.rendered()) + assertEquals(drawn, view.rects()) + assertEquals(4, view.artworkDpad().size) + } + } + + @Test fun dpadPiecesRedrawWhenTheyLeaveOrRejoinTheKitCross() { + val view = editor(overlay(), 2400, 1504) + val stock = view.rendered() + view.aspect = 2400f / 1504 + val pieces = view.controls().filter { (it.tag as InputSurfaceElement).id in setOf("legacy:up", "legacy:right", "legacy:down", "legacy:left") } + assertEquals(4, pieces.size) + for ((moved, expected) in listOf(stock.map { if (it.id == "legacy:up") it.copy(y = it.y - .2f) else it } to 0, stock to 4)) { + pieces.forEach { shadowOf(it).clearWasInvalidated() } + view.elements = moved + view.place(2400, 1504) + assertEquals(expected, view.artworkDpad().size) + pieces.forEach { assertTrue((it.tag as InputSurfaceElement).id, shadowOf(it).wasInvalidated()) } + } + } + + @Test fun draggingMovesTheTouchedControlByTheDragDistance() { + val view = editor(overlay(), 2400, 1504) + val a = view.rendered().first { it.id == "legacy:a" } + val changes = mutableListOf() + view.onChange = { changes += it } + val (x, y) = view.centre(a.id) + view.touch(MotionEvent.ACTION_DOWN, x, y) + view.touch(MotionEvent.ACTION_MOVE, x - 240f, y - 150f) + view.touch(MotionEvent.ACTION_UP, x - 240f, y - 150f) + val moved = changes.last() + assertEquals(a.id, moved.id) + assertEquals(a.x - 240f / 2400, moved.x, .0001f) + assertEquals(a.y - 150f / 1504, moved.y, .0001f) + assertEquals(a.width, moved.width, .0001f) + } + + @Test fun aMouseSelectsDragsAndResizesLikeATouch() { + val view = editor(overlay(), 2400, 1504) + val a = view.rendered().first { it.id == "legacy:a" } + val changes = mutableListOf() + var selection: String? = null + view.onSelect = { selection = it } + view.onChange = { changes += it } + val (x, y) = view.centre(a.id) + view.mouse(MotionEvent.ACTION_DOWN, x, y) + view.mouse(MotionEvent.ACTION_UP, x, y) + assertEquals(a.id, selection) + view.mouse(MotionEvent.ACTION_DOWN, x, y) + view.mouse(MotionEvent.ACTION_MOVE, x - 240f, y) + view.mouse(MotionEvent.ACTION_UP, x - 240f, y) + assertEquals(a.x - 240f / 2400, changes.last().x, .0001f) + val right = (a.x + a.width) * 2400; val bottom = (a.y + a.height) * 1504 + view.mouse(MotionEvent.ACTION_DOWN, right, bottom) + view.mouse(MotionEvent.ACTION_MOVE, right + 60f, bottom + 60f) + view.mouse(MotionEvent.ACTION_UP, right + 60f, bottom + 60f) + val resized = changes.last() + assertEquals(a.id, resized.id) + assertEquals(a.width + 60f / 2400, resized.width, .0001f) + assertEquals(a.height + 60f / 1504, resized.height, .0001f) + } } + +internal fun InputSurfaceEditorView.place(w: Int, h: Int) { + measure(View.MeasureSpec.makeMeasureSpec(w, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(h, View.MeasureSpec.EXACTLY)) + layout(0, 0, w, h) +} + +@Suppress("UNCHECKED_CAST") +internal fun InputSurfaceEditorView.rendered() = javaClass.getDeclaredField("visibleElements").also { it.isAccessible = true }.get(this) as List diff --git a/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceTouchTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceTouchTest.kt index eaf9d65286..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)) @@ -134,23 +153,26 @@ class InputSurfaceTouchTest { touch(MotionEvent.ACTION_UP, 1 to (600f to 510f)) assertTrue(events.isEmpty()) show(a, b, stick) - view.setHidden(OnScreenControls.Hidden.BY_TAP) + view.setQuickHidden(true) measure(view) assertFalse(view.takesTouchAt(450f, 510f)) assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (450f to 510f))) assertTrue(events.isEmpty()) } - @Test fun hiddenControlsHideTheKeyboardShortcutUntilShownAgain() { - view.setHidden(OnScreenControls.Hidden.BY_CONTROLLER) + @Test fun keyboardShortcutWorksWithHiddenPadAndButtonsOnly() { + view.setQuickHidden(true) measure(view) assertFalse(view.takesTouchAt(800f, 240f)) - assertFalse(view.takesTouchAt(450f, 510f)) - view.setHidden(null) - measure(view) touch(MotionEvent.ACTION_DOWN, 1 to (450f to 510f)) touch(MotionEvent.ACTION_UP, 1 to (450f to 510f)) - assertEquals(listOf("KEYBOARD:PRIMARY"), events) + view.setButtonsOnly(true) + measure(view) + val (x, y) = centre(element(view, "builtin:keyboard")) + assertFalse(view.takesTouchAt(800f, 240f)) + touch(MotionEvent.ACTION_DOWN, 1 to (x to y)) + touch(MotionEvent.ACTION_UP, 1 to (x to y)) + assertEquals(listOf("KEYBOARD:PRIMARY", "KEYBOARD:PRIMARY"), events) } @Test fun hidingTheViewReleasesLatchedKeys() { @@ -178,14 +200,11 @@ class InputSurfaceTouchTest { touch(MotionEvent.ACTION_CANCEL, 1 to (800f to 240f), target = panel) } - @Test fun fixedSticksReachFullTiltInsideTheirRing() { + @Test fun classicSticksTravelTheirFullRadius() { show(stick.copy(buttonShape = InputButtonShape.CIRCLE)) - val reach = (100f - 3 * context.resources.displayMetrics.density) * .62f touch(MotionEvent.ACTION_DOWN, 1 to (200f to 300f)) - touch(MotionEvent.ACTION_MOVE, 1 to (200f + reach / 2 to 300f)) + touch(MotionEvent.ACTION_MOVE, 1 to (250f to 300f)) assertEquals(.5f, state().leftX, .01f) - touch(MotionEvent.ACTION_MOVE, 1 to (200f + reach to 300f)) - assertEquals(1f, state().leftX, .01f) touch(MotionEvent.ACTION_MOVE, 1 to (300f to 300f)) assertEquals(1f, state().leftX, .01f) touch(MotionEvent.ACTION_UP, 1 to (300f to 300f)) @@ -209,15 +228,14 @@ class InputSurfaceTouchTest { } @Test fun adaptiveSticksCaptureAroundThemAndTheLeftOneToTheEdge() { - val left = InputSurfaceElement(InputControl.LS, .3f, .3f, .2f, .4f, floating = true) - val right = InputSurfaceElement(InputControl.RS, .6f, .3f, .2f, .4f, floating = true) + val left = InputSurfaceElement(InputControl.LS, .3f, .3f, .2f, .4f, hideWhenIdle = true) + val right = InputSurfaceElement(InputControl.RS, .6f, .3f, .2f, .4f, hideWhenIdle = true) show(left, right) - val limit = (100f - 3 * context.resources.displayMetrics.density) * 1.71f assertTrue(view.takesTouchAt(10f, 300f)) - assertTrue(view.takesTouchAt(10f, 300f + limit - 4f)) - assertFalse(view.takesTouchAt(10f, 300f + limit + 4f)) - assertTrue(view.takesTouchAt(990f, 300f)) - assertFalse(view.takesTouchAt(990f, 300f + limit + 4f)) + assertTrue(view.takesTouchAt(10f, 390f)) + assertFalse(view.takesTouchAt(10f, 420f)) + assertTrue(view.takesTouchAt(795f, 300f)) + assertFalse(view.takesTouchAt(815f, 300f)) val missed = mutableListOf() view.onTouchMiss = { missed += it.getPointerId(0) } touch(MotionEvent.ACTION_DOWN, 1 to (50f to 300f)) @@ -225,9 +243,9 @@ class InputSurfaceTouchTest { assertEquals(listOf(2), missed) touch(MotionEvent.ACTION_MOVE, 1 to (150f to 300f), 2 to (60f to 310f)) assertTrue(state().leftX > .9f) - show(left.copy(floating = false), right.copy(floating = false)) + show(left.copy(hideWhenIdle = false), right.copy(hideWhenIdle = false)) assertFalse(view.takesTouchAt(10f, 300f)) - assertFalse(view.takesTouchAt(990f, 300f)) + assertFalse(view.takesTouchAt(815f, 300f)) } private fun element(root: View, id: String): View = descendants(root).first { (it.tag as? InputSurfaceElement)?.id == id } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/InputUiLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/InputUiLayoutTest.kt index 51df2679c6..9f28c9ccc1 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/InputUiLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputUiLayoutTest.kt @@ -55,12 +55,12 @@ class InputUiLayoutTest { } @Test @Config(qualifiers = "w360dp-h800dp") - fun phoneKeepsTheControllerPageAndRemappingReachable() { + fun phoneKeepsLibraryNavigationAndProfileEditingReachable() { compose.setContent { root = LocalView.current; DroidDeckTheme { Surface { BoxWithConstraints { CompositionLocalProvider(LocalNarrowPane provides (maxWidth < 600.dp)) { InputSettingsPage({}) } } } } } - compose.onNodeWithTag("osc-edit").performScrollTo().assertIsDisplayed() - compose.onNodeWithTag("input-remap").performScrollTo().assertIsDisplayed().performClick() + compose.onNodeWithTag("input-profile-desktop").performScrollTo().assertIsDisplayed().performClick() + compose.onNodeWithTag("input-part-physical").performScrollTo().assertIsDisplayed().performClick() compose.onNodeWithTag("input-binding-a").performScrollTo().assertIsDisplayed().performClick() compose.onNodeWithTag("input-action-save").assertIsDisplayed() screenshot("phone-properties") @@ -75,10 +75,10 @@ class InputUiLayoutTest { } @Test @Config(qualifiers = "w960dp-h600dp") - fun largeScreenShowsTheControllerPageInTheExistingTheme() { + fun largeScreenShowsTheProfileLibraryInTheExistingTheme() { compose.setContent { root = LocalView.current; DroidDeckTheme { Surface { InputSettingsPage({}) } } } - compose.onNodeWithTag("osc-edit").assertIsDisplayed() - screenshot("controller") + compose.onNodeWithTag("input-profile-game").assertIsDisplayed() + screenshot("profiles") } @Test @Config(qualifiers = "w960dp-h600dp") @@ -108,11 +108,11 @@ class InputUiLayoutTest { } } compose.onNodeWithText(context.getString(R.string.setup_tab_controller)).performClick() - compose.onNodeWithTag("osc-edit").assertIsDisplayed() - compose.onAllNodesWithText(context.getString(R.string.osc_edit_layout)).assertCountEquals(1) + compose.onNodeWithTag("input-profile-game").assertIsDisplayed() + compose.onNodeWithText(context.getString(R.string.ctrl_layout)).assertDoesNotExist() screenshot("controller-tab") - compose.onNodeWithTag("input-remap").performScrollTo().performClick() - compose.onNodeWithTag("input-binding-a").assertExists() + compose.onNodeWithTag("input-profile-game").performClick() + compose.onNodeWithTag("input-part-physical").performScrollTo().performClick() compose.onNodeWithText(context.getString(R.string.setup_tab_launcher)).assertIsDisplayed() screenshot("controller-physical") compose.runOnIdle { assertEquals(InputProfiles.AUTO, InputLibraries.read(context).selected) } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/PhysicalShortcutsDialogTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/PhysicalShortcutsDialogTest.kt index 6857cf7a78..864eb0ef64 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/PhysicalShortcutsDialogTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/PhysicalShortcutsDialogTest.kt @@ -16,7 +16,6 @@ import androidx.compose.foundation.layout.width import androidx.compose.ui.Modifier import com.droiddeck.launcher.R import com.droiddeck.launcher.input.ControllerPrefs -import com.droiddeck.launcher.input.LegacyControllerPrefs import com.droiddeck.launcher.input.PadBridgeRoutingTest import com.droiddeck.launcher.input.PhysicalShortcuts import org.junit.Assert.* @@ -128,7 +127,7 @@ class PhysicalShortcutsDialogTest { } @Test fun removalRestoresDefaultAndPreservesOtherAssignmentsAndControllerSettings() { - LegacyControllerPrefs.setSelectSteam(context, true) + ControllerPrefs.setSelectSteam(context, true) PhysicalShortcuts.assign(context, requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN))), PhysicalShortcuts.Action.STEAM) PhysicalShortcuts.assign(context, requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F2, KeyEvent.ACTION_DOWN))), diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt index adbbbe248a..019f47784c 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt @@ -29,4 +29,17 @@ class SessionDrawerPageTest { assertEquals(SessionDrawerPage.SESSION, with.step(SessionDrawerPage.AGENT, 1)) assertFalse(SessionDrawerPage.AGENT in sessionDrawerPages(hasAgent = false)) } + + @Test fun arrangeKeepsSavedOrderAndSlotsNewPagesAfterTheirNeighbour() { + val saved = listOf("SESSION", "HUD", "CONTROLLER") + val out = DrawerPages.arrange(saved) + assertEquals(SessionDrawerPage.entries.toSet(), out.toSet()) + assertEquals(listOf(SessionDrawerPage.SESSION, SessionDrawerPage.HUD), out.filter { it in setOf(SessionDrawerPage.SESSION, SessionDrawerPage.HUD) }) + assertTrue(out.indexOf(SessionDrawerPage.HUD) < out.indexOf(SessionDrawerPage.CONTROLLER)) + } + + @Test fun sessionPageCannotBeHidden() { + assertFalse(DrawerPages.hideable(SessionDrawerPage.SESSION)) + assertTrue(DrawerPages.hideable(SessionDrawerPage.HUD)) + } } 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 8085debe1f..c45b32d234 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt @@ -71,8 +71,11 @@ class SessionSecondScreenTest { @Test fun steamMenuKeepsTheExistingTrackpadAndTerminal() = checkModes(steam = true) + @Test fun desktopQuickMenuChangesTheRunningDesktopLayout() = checkQuickSelection(steam = false, desktop = true, direct = true) + @Test fun steamQuickMenuLeavesTheDesktopSelectionAlone() = checkQuickSelection(steam = true, desktop = false, direct = false) + @Test fun directGameQuickMenuLeavesTheDesktopSelectionAlone() = checkQuickSelection(steam = false, desktop = false, direct = true) @Test fun closingTheDockedDrawerKeepsTheSelectedControlsPanel() { SessionState.mode = SessionService.MODE_STEAM @@ -334,6 +337,43 @@ class SessionSecondScreenTest { compose.onNodeWithText(context.getString(R.string.mode_mic)).assertDoesNotExist() } + private fun checkQuickSelection(steam: Boolean, desktop: Boolean, direct: Boolean) { + SessionState.mode = if (desktop) SessionService.MODE_DESKTOP else if (steam) SessionService.MODE_STEAM else SessionService.MODE_RUN + val original = InputLibraries.update(context) { it.chooseLayout("desktop", InputRole.SECONDARY, InputLibraries.DECK) } + val activity = Robolectric.buildActivity(SessionActivity::class.java).get() + val display = activity.getSystemService(DisplayManager::class.java).getDisplay(Display.DEFAULT_DISPLAY) + val panel = SecondScreenPresentation(activity, display, {}, {}, {}) + val open = androidx.compose.runtime.mutableStateOf(true) + try { + panel.show() + panel.showMode(SecondScreenMode.CUSTOM_CONTROLS) + compose.setContent { + DroidDeckTheme { + SessionDrawer(open.value, SessionDrawerPage.CONTROLLER, false, {}, + actions(steam, emptyList(), desktop = desktop, direct = direct, + onInputSelection = { panel.refreshControls() }, onClose = { open.value = false })) + } + } + compose.onNodeWithTag("setting-input-profile").performScrollTo().performClick() + compose.onNodeWithText("Desktop").performScrollTo().performClick() + compose.onNodeWithTag("input-profile-expand").performScrollTo().performClick() + compose.onNodeWithTag("setting-input-part-SECONDARY").performScrollTo().performClick() + compose.onNodeWithText("Trackpad + keyboard").performScrollTo().performClick() + compose.onNode(hasContentDescription(context.getString(R.string.common_close)) and + SemanticsMatcher.expectValue(androidx.compose.ui.semantics.SemanticsProperties.Role, androidx.compose.ui.semantics.Role.Button)).performClick() + compose.runOnIdle { + val updated = InputLibraries.read(context) + assertEquals("desktop", updated.selection(desktop).profile) + assertEquals(InputLibraries.TRACKPAD, updated.activeLayout(desktop, InputRole.SECONDARY)?.id) + assertEquals(original.selection(!desktop), updated.selection(!desktop)) + assertEquals(original.profiles, updated.profiles) + val controls = descendants(panel.window!!.decorView).filterIsInstance().single() + val pads = descendants(controls).mapNotNull { it.tag as? InputSurfaceElement }.filter { it.kind == InputElementKind.TRACKPAD }.toList() + assertEquals(1, pads.size) + } + } finally { panel.closeControls() } + } + private fun checkModes(steam: Boolean) { SessionState.mode = if (steam) SessionService.MODE_STEAM else SessionService.MODE_DESKTOP val selected = mutableListOf() diff --git a/docs/development/low-memory.md b/docs/development/low-memory.md index a25c3e04ef..c530e1fef3 100644 --- a/docs/development/low-memory.md +++ b/docs/development/low-memory.md @@ -102,10 +102,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/memory-guard-ab.md b/docs/development/memory-guard-ab.md index 4ac8d1a214..ded09a59f4 100644 --- a/docs/development/memory-guard-ab.md +++ b/docs/development/memory-guard-ab.md @@ -1,20 +1,24 @@ # Keep-top guard A/B on dual screens -`KeepTopActivity` (#2763) covers every other display while a session is on top, so that -display's home is not its top activity. On the Thor, lmkd kills the bottom home under memory -pressure, Android relaunches it to the front (`wm_task_to_front`), the session loses the top -spot, drops to adj 50 and is killed in lmkd's next pass. +`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. -Android gives a translucent activity that is alone in its task an `ActivityRecordInputSink` -that consumes every touch inside the task bounds, whatever the window's flags say -(`ENABLE_TOUCH_OPAQUE_ACTIVITIES`, on for DroidDeck's target SDK; see -`services/core/java/com/android/server/wm/ActivityRecordInputSink.java`). The guard's -`FLAG_NOT_TOUCHABLE` therefore did nothing: with the dual-screen panel closed, the bottom -screen took no touch until the session ended, and the guard also stayed over it after Home. +It had three side effects: -The guard now takes touches itself. A touch removes it from that display. It comes back when -the session is top-resumed again, or after 5 s if the session kept the top spot (one touch on -the bottom screen, then back to the game). Stopping or entering PiP removes the guards. +- 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 @@ -25,6 +29,7 @@ build that has the debugging tools: 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 ``` @@ -39,6 +44,13 @@ event log of every probe. `--stop-mb`, holds it, and releases it. zram cannot compress that data and no app owns it, so lmkd keeps killing by adj. It records lmkd's `killinfo`, process deaths, focus loss and whether DroidDeck survived. +- `pressure --burst` takes everything above `--stop-mb` at once instead: it copies a 256 MiB + random file into the tmpfs with all copies running in parallel (about 5 GiB in 2 to 3 s on a + Thor), the way a game's GPU allocation burst lands on lmkd. +- `oom_score_adj` is read without `su`. Under pressure lmkd keeps killing the root manager app, + and a `su` call can then open its request screen on top of the game. +- If the bottom display has no home (a killed home is not always restarted), the visible app on + top of it stands in. - `--bottom-tap` must point at an inert spot of the bottom home; `--panel-close` at the panel's close button. Both are fractions of the bottom display. - `am start` of `SessionActivity` needs `--display 0`; without it, it creates a second @@ -88,3 +100,24 @@ moves it to the front, even with no guard. The Thor's focus steal does not happe Duo shows that the guard covers the same states as before, not that it saves the session. That needs a Thor: run `states` and `pressure --stop-mb` near its adj-50 level on `main` and on the fix, and look for `task_to_front` and `session_top_lost` before `droiddeck_died_at_adj` 50. + +## Results: AYN Thor (12 GB), Android 13 + +Builds: `main` (56986b5, guard with the #2910 touch yield) and `no-guard` (`main` with +`guardOtherDisplays` returning at once). The game was focused on the top screen in every run. + +| Pressure | Bottom app | no-guard | main | +| --- | --- | --- | --- | +| Fill to 650 MB free, hold 30 s | stock launcher | survived 1/1 usable run (launcher not reached) | survived 3/3 (launcher killed 80, 25, 0 times) | +| Fill to 550 MB free, hold 30 s | Cocoon as home | survived 3/3, Cocoon killed 387, 400, 84 times | survived 3/3, Cocoon killed 384, 127, 338 times | +| Burst to 400 MB free (about 5 GB in 2.5 to 3.4 s) | stock launcher | killed at adj 0 in 3/3 | killed at adj 0 in 3/3 | +| Burst to 1500 MB free (2.0 to 2.4 s) | stock launcher | survived 1/2, killed at adj 0 in 1/2 | killed at adj 0 in 2/2 | + +No run on either build lost the top spot (`wm_on_top_resumed_lost_called` for +`SessionActivity`), moved a task to the front, or killed DroidDeck at adj 50. A killed bottom +home is either restarted in place or its task disappears and the next app shows on the bottom +screen, without taking focus. A burst big enough to matter makes lmkd kill the foreground +session at adj 0, which no activity on another display can prevent. + +`kill -9` of the bottom app (`states`) is noisy on a Thor with many recent apps: each kill +surfaces the next app on the bottom screen, and every tap the tool sends there moves focus. diff --git a/docs/progress-log.md b/docs/progress-log.md index 462affde2a..5fcfa60707 100644 --- a/docs/progress-log.md +++ b/docs/progress-log.md @@ -1449,8 +1449,9 @@ State: **main = `90c7574`** (PR #14 merge), main build run 35895701784. No tag, - A runtime script must be named `bannerlator-*` or CI never packages it. - `gh release create --target` needs the full sha. - A proot bind is invisible to a program's "Computer" list; put what users need under home. -- The compositor decides its driver and its HDR gate once per app process - anything that changes - them applies after the app is fully closed, and the UI must say so. +- The compositor decides its driver once per app process - anything that changes it applies after + the app is fully closed, and the UI must say so. Its HDR gate follows what the device can present, + so the HDR setting itself switches during a session. - Bannerlator's File Manager ports mechanically (`port_fm.py` anchors) once the container hooks are cut; do not hand-edit 2,500 lines. - Deleting a release asset on GitHub can drop a sibling asset - re-list and restore. diff --git a/docs/settings-map.md b/docs/settings-map.md index cfbdf196de..a292309bc9 100644 --- a/docs/settings-map.md +++ b/docs/settings-map.md @@ -44,6 +44,7 @@ Links of the form `droiddeck://settings/
` open a Settings section direc | Launcher orientation | Settings › Launcher (`droiddeck://settings/launcher`) | rotate, portrait | | Session orientation | Settings › Launcher (`droiddeck://settings/launcher`) | rotate, portrait | | Fullscreen | Settings › Launcher (`droiddeck://settings/launcher`) | | +| Controller haptics | Settings › Launcher (`droiddeck://settings/launcher`) | vibration, rumble | | Dual screen launcher | Settings › Launcher (`droiddeck://settings/launcher`) | thor, second screen, bottom screen | | Warn when storage is low | Settings › Launcher (`droiddeck://settings/launcher`) | | | SteamGridDB API key | Settings › Launcher (`droiddeck://settings/launcher`) | artwork, steamgriddb | @@ -94,7 +95,7 @@ Links of the form `droiddeck://settings/
` open a Settings section direc | Setting | Where | Also matches | | --- | --- | --- | -| Session display | Steam or Desktop options (swipe up) › Display | resolution, scaling, hdr, refresh | +| Session display | Steam or Desktop options (swipe up) › Display | resolution, scaling, hdr, refresh, zero-copy | | Graphics drivers | Steam or Desktop options (swipe up) › Display | turnip, driver, gpu, adreno, mali | | Offline mode | Steam or Desktop options (swipe up) › Steam | offline, steam | | Microphone | Steam or Desktop options (swipe up) › Audio | microphone, voice | diff --git a/tools/build_local.sh b/tools/build_local.sh index 6f8d004ffa..4251997416 100755 --- a/tools/build_local.sh +++ b/tools/build_local.sh @@ -440,6 +440,13 @@ if [[ "${DROIDDECK_SKIP_RUST:-0}" != 1 ]]; then CARGO_TARGET_DIR="${cache_dir}/rockstar-target" bash tools/rockstar-launcher/build.sh "${rockstar_out}" save_step rockstar "${rockstar_key}" "${rockstar_out}" fi + epic_out="${linuxfs_dir}/usr/local/lib/droiddeck-epic" + epic_key=$(inputs_hash "x86_64-pc-windows-gnu" tools/epic-launcher/src tools/epic-launcher/Cargo.toml tools/epic-launcher/Cargo.lock tools/epic-launcher/build.sh) + if ! restore_step epic "${epic_key}" "${epic_out}"; then + command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1 || { echo "x86_64-w64-mingw32-gcc is required for EpicGamesLauncher.exe." >&2; exit 1; } + CARGO_TARGET_DIR="${cache_dir}/epic-target" bash tools/epic-launcher/build.sh "${epic_out}" + save_step epic "${epic_key}" "${epic_out}" + fi fi python3 tools/powervr/fetch.py bash tools/packs/build.sh app/build/packs diff --git a/tools/droiddeckctl b/tools/droiddeckctl index 50ff42423d..2a404c1c6c 100755 --- a/tools/droiddeckctl +++ b/tools/droiddeckctl @@ -412,10 +412,10 @@ def pacing(adb: str, serial: str, seconds: float) -> dict: try: time.sleep(seconds) dump = run_adb(adb, serial, *timestats, "-dump", timeout=60) + elapsed = time.monotonic() - started except ControlError as exc: raise ControlError(str(exc), "PACING_FAILED") from exc finally: - elapsed = time.monotonic() - started try: disabled = run_adb(adb, serial, *timestats, "-disable").returncode == 0 except ControlError: diff --git a/tools/epic-launcher/.gitignore b/tools/epic-launcher/.gitignore new file mode 100644 index 0000000000..b83d22266a --- /dev/null +++ b/tools/epic-launcher/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/tools/epic-launcher/Cargo.lock b/tools/epic-launcher/Cargo.lock new file mode 100644 index 0000000000..569575bb09 --- /dev/null +++ b/tools/epic-launcher/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "droiddeck-epic-launcher" +version = "0.1.0" diff --git a/tools/epic-launcher/Cargo.toml b/tools/epic-launcher/Cargo.toml new file mode 100644 index 0000000000..fb5974a4b2 --- /dev/null +++ b/tools/epic-launcher/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "droiddeck-epic-launcher" +version = "0.1.0" +edition = "2021" +license = "GPL-3.0-only" +publish = false + +[[bin]] +name = "EpicGamesLauncher" +path = "src/main.rs" + +[profile.release] +opt-level = "s" +lto = true +panic = "abort" +strip = true diff --git a/tools/epic-launcher/README.md b/tools/epic-launcher/README.md new file mode 100644 index 0000000000..97dbce402f --- /dev/null +++ b/tools/epic-launcher/README.md @@ -0,0 +1,13 @@ +# Epic Games Launcher parent stand-in + +`EpicGamesLauncher.exe` starts the game named by its first argument as its own child, passes the rest of its command line to the game unchanged, waits for the game and returns its exit code. + +Some Epic titles only accept a launch whose parent process is named `EpicGamesLauncher.exe`. Rockstar's launcher logs `Epic Games Launcher not detected as parent process.` and then treats the Epic copy as unowned. In DroidDeck the Epic client is a Linux program, so it can never be that parent. The check matches the process name, not its path: Heroic's stand-in works from `C:\windows\command` and from the game folder. + +`StoreLaunch` writes the Epic `.droiddeck-launch.bat` to run the game through this executable for the titles in `EPIC_PARENT_TITLES`, or for any Epic game whose per-game environment sets `DD_EPIC_PARENT=1`. `DD_EPIC_PARENT=0` turns it off. Without the staged executable the game starts directly, as before. + +`build.sh` builds it with the GNU Windows target for the `epic` add-on pack. The app fetches the pack when it starts signed in to Epic, or when a launch that needs it finds it missing, and stages it in the Linux runtime at `/usr/local/lib/droiddeck-epic`. + +```sh +cargo test --locked --manifest-path tools/epic-launcher/Cargo.toml +``` diff --git a/tools/epic-launcher/build.sh b/tools/epic-launcher/build.sh new file mode 100755 index 0000000000..5db23c420d --- /dev/null +++ b/tools/epic-launcher/build.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +out=${1:-"$here/../../app/src/main/assets/linuxfs/usr/local/lib/droiddeck-epic"} +target=x86_64-pc-windows-gnu +rustup target add "$target" >/dev/null 2>&1 || true +cargo build --manifest-path "$here/Cargo.toml" --release --locked --target "$target" +mkdir -p "$out" +install -m644 "${CARGO_TARGET_DIR:-$here/target}/$target/release/EpicGamesLauncher.exe" "$out/EpicGamesLauncher.exe" diff --git a/tools/epic-launcher/src/lib.rs b/tools/epic-launcher/src/lib.rs new file mode 100644 index 0000000000..f842dc13c2 --- /dev/null +++ b/tools/epic-launcher/src/lib.rs @@ -0,0 +1,110 @@ +const QUOTE: u16 = b'"' as u16; +const BACKSLASH: u16 = b'\\' as u16; + +fn blank(c: u16) -> bool { + c == b' ' as u16 || c == b'\t' as u16 +} + +fn trim_start(line: &[u16]) -> &[u16] { + let start = line.iter().position(|&c| !blank(c)).unwrap_or(line.len()); + &line[start..] +} + +/// Splits this program's command line into the game executable that follows the program name and +/// the rest of the line, which reaches the game unchanged. +pub fn split(line: &[u16]) -> Option<(Vec, &[u16])> { + let mut quoted = false; + let mut end = line.len(); + for (i, &c) in line.iter().enumerate() { + if c == QUOTE { + quoted = !quoted; + } else if blank(c) && !quoted { + end = i; + break; + } + } + let rest = trim_start(&line[end..]); + let mut exe = Vec::new(); + let mut quoted = false; + let mut slashes = 0; + let mut end = rest.len(); + for (i, &c) in rest.iter().enumerate() { + if c == BACKSLASH { + slashes += 1; + continue; + } + if c == QUOTE { + exe.extend(std::iter::repeat(BACKSLASH).take(slashes / 2)); + if slashes % 2 == 1 { + exe.push(QUOTE); + } else { + quoted = !quoted; + } + } else if blank(c) && !quoted { + exe.extend(std::iter::repeat(BACKSLASH).take(slashes)); + end = i; + slashes = 0; + break; + } else { + exe.extend(std::iter::repeat(BACKSLASH).take(slashes)); + exe.push(c); + } + slashes = 0; + } + exe.extend(std::iter::repeat(BACKSLASH).take(slashes)); + if exe.is_empty() { + return None; + } + Some((exe, trim_start(&rest[end..]))) +} + +#[cfg(test)] +mod tests { + use super::split; + + fn wide(s: &str) -> Vec { + s.encode_utf16().collect() + } + + fn parts(line: &str) -> Option<(String, String)> { + let line = wide(line); + split(&line).map(|(exe, rest)| (String::from_utf16(&exe).unwrap(), String::from_utf16(rest).unwrap())) + } + + #[test] + fn the_game_gets_the_rest_of_the_line_exactly_as_written() { + assert_eq!( + parts(r#""Z:\usr\local\lib\droiddeck-epic\EpicGamesLauncher.exe" "Z:\root\Games\Stores\Epic\Grand Theft Auto V\PlayGTAV.exe" -AUTH_LOGIN=unused -epicusername="A B" -nobattleye"#), + Some(( + r"Z:\root\Games\Stores\Epic\Grand Theft Auto V\PlayGTAV.exe".into(), + r#"-AUTH_LOGIN=unused -epicusername="A B" -nobattleye"#.into() + )) + ); + } + + #[test] + fn a_game_without_arguments_gets_none() { + assert_eq!(parts(r#"EpicGamesLauncher.exe "C:\Games\x.exe" "#), Some((r"C:\Games\x.exe".into(), String::new()))); + assert_eq!(parts(r"EpicGamesLauncher.exe C:\Games\x.exe"), Some((r"C:\Games\x.exe".into(), String::new()))); + } + + #[test] + fn the_program_name_follows_its_own_quoting_rules() { + assert_eq!(parts("\"C:\\a b\\\"EpicGamesLauncher.exe\tgame.exe -x"), Some(("game.exe".into(), "-x".into()))); + } + + #[test] + fn the_executable_follows_the_argument_quoting_rules() { + assert_eq!(parts(r#"e "C:\dir with\"part\"s\x.exe" -y"#), Some((r#"C:\dir with"part"s\x.exe"#.into(), "-y".into()))); + assert_eq!(parts(r#"e C:\a"b c"\x.exe -y"#), Some((r"C:\ab c\x.exe".into(), "-y".into()))); + assert_eq!(parts(r"e C:\games\ -y"), Some((r"C:\games\".into(), "-y".into()))); + } + + #[test] + fn a_missing_executable_is_refused() { + assert_eq!(parts("EpicGamesLauncher.exe"), None); + assert_eq!(parts("EpicGamesLauncher.exe "), None); + assert_eq!(parts(r#"EpicGamesLauncher.exe "" -x"#), None); + assert_eq!(parts(""), None); + } +} diff --git a/tools/epic-launcher/src/main.rs b/tools/epic-launcher/src/main.rs new file mode 100644 index 0000000000..0b3ac53837 --- /dev/null +++ b/tools/epic-launcher/src/main.rs @@ -0,0 +1,42 @@ +#[cfg(windows)] +fn main() { + use std::ffi::OsString; + use std::os::windows::ffi::OsStringExt; + use std::os::windows::process::CommandExt; + + #[link(name = "kernel32")] + extern "system" { + fn GetCommandLineW() -> *const u16; + } + + let line = unsafe { + let start = GetCommandLineW(); + let mut len = 0; + while *start.add(len) != 0 { + len += 1; + } + std::slice::from_raw_parts(start, len) + }; + let Some((exe, rest)) = droiddeck_epic_launcher::split(line) else { + eprintln!("usage: EpicGamesLauncher.exe [arguments]"); + std::process::exit(2); + }; + let exe = OsString::from_wide(&exe); + let mut command = std::process::Command::new(&exe); + if !rest.is_empty() { + command.raw_arg(OsString::from_wide(rest)); + } + match command.status() { + Ok(status) => std::process::exit(status.code().unwrap_or(1)), + Err(error) => { + eprintln!("EpicGamesLauncher: could not start {}: {error}", exe.to_string_lossy()); + std::process::exit(1); + } + } +} + +#[cfg(not(windows))] +fn main() { + eprintln!("EpicGamesLauncher.exe runs on Windows or Wine"); + std::process::exit(1); +} diff --git a/tools/gamescope/PATCHES.md b/tools/gamescope/PATCHES.md index 953bab4a0c..f5a569ddc8 100644 --- a/tools/gamescope/PATCHES.md +++ b/tools/gamescope/PATCHES.md @@ -358,3 +358,51 @@ and clears the held flag. wlroots counts repeated presses of one button and send reaches zero, so a second finger touching before the first lifted left the button pressed in the seat for good: the game saw a held click, and later taps only raised and lowered the count. A finger now presses the button only when no earlier finger holds it. `tools/tests/test_gamescope_touch_click.py` compiles the rule from this patch. + +## 0135 Wayland backend: a limit on the planes handed to the host + +`wayland_overlay_planes` says how many planes above the base one the host compositor shows without composing them +itself. With more layers than that, gamescope composites them into one picture, as it already does for a scaler or +`composite_force`. -1, the default, keeps every layer on its own plane. The app sets it while a host that shows the +game picture directly cannot give an overlay a display layer of its own, so the overlay is drawn into the game +picture here and the frame still reaches the display without a copy. + +## 0136 rendervulkan, Wayland backend: composite only into output images the host has released + +The composite output images were used in a fixed rotation of three, with no check that the host compositor had +released the one about to be written. A host that puts the buffer on the display itself, without copying it, was +still reading that image when the next composite wrote into it. A backend framebuffer now says whether the host +holds it, the Wayland backend answers from the buffer's release event, and the composite takes the next image the +host does not hold. Backends that are not a session get five images instead of three, so one is free while the +host holds two and the last and deferred pictures stay intact. Session backends keep three images and their order. + +## 0137 Wayland backend: the host's refresh rates and the app's target + +A nested session had one refresh rate, the host's, so Steam offered no refresh control and a frame limit never moved +the display. The backend binds the host's `droiddeck_refresh_v1`, takes the list of rates the host display can switch +between and returns it as the connector's dynamic refresh rates, so the rates reach Steam with the rest of the +display state and are sent again when the list changes. On every present it tells the host the refresh rate the +frame limit resolves to and the limit itself; the host switches its display and the new rate comes back through +`wl_output`, which the nested refresh already follows. A host without the global leaves all of this as it was. + +## 0138 Frame limiter: a limit the refresh rate does not divide is spread evenly + +The limiter held a window for a whole number of refreshes, the refresh rate divided by the limit and rounded down. A +limit of 45 or 40 on a 60 Hz display rounded to one refresh per frame, so the limit did nothing, and each frame was +timed from the moment the previous one was shown, so a late frame pushed every frame after it. The limited cycle is +now the exact time between frames at the limit, and each window keeps the time its next frame is due on that line. +A frame is released on the refresh nearest its due time: 45 on 60 Hz shows frames for one, one and two refreshes in +turn, 40 for one and two, and a limit that divides the refresh rate is paced as before. A frame that arrives most of a +refresh late, or more than a refresh early, starts the line again from that frame, so a stall is not followed by a +burst. `tools/tests/test_gamescope_limiter_cadence.py` compiles the two rules from this patch and runs them across +refresh rates and limits. + +## 0139 HDR output can be switched while a session runs + +The Wayland backend read `hdr_enabled` once, when the host compositor described its output, and kept the answer: a +session started with HDR off told its clients the display had no HDR for as long as it ran, and its environment +carried `DXVK_HDR=0`. Whether the display can show HDR now comes from the host's output description alone, and +`hdr_enabled` decides only whether HDR is used, so setting it during a session takes effect on the next frame in +either direction. The 10-bit output format is chosen only while HDR is enabled, so an SDR session keeps the 8-bit +output it had, and the output images are made again in the other format when the setting changes. On a display that can show HDR, a session that starts with HDR off leaves `DXVK_HDR` unset instead of +forcing it to 0, so a game started after HDR is switched on finds it. diff --git a/tools/gamescope/patches/0135-wayland-overlay-plane-limit.patch b/tools/gamescope/patches/0135-wayland-overlay-plane-limit.patch new file mode 100644 index 0000000000..7961ec5050 --- /dev/null +++ b/tools/gamescope/patches/0135-wayland-overlay-plane-limit.patch @@ -0,0 +1,20 @@ +diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp +index 372fc08..fe38c7d 100644 +--- a/src/Backends/WaylandBackend.cpp ++++ b/src/Backends/WaylandBackend.cpp +@@ -126,6 +126,7 @@ namespace gamescope + gamescope::ConVar cv_wayland_mouse_warp_without_keyboard_focus( "wayland_mouse_warp_without_keyboard_focus", true, "Should we only forward mouse warps to the app when we have keyboard focus?" ); + gamescope::ConVar cv_wayland_mouse_relmotion_without_keyboard_focus( "wayland_mouse_relmotion_without_keyboard_focus", false, "Should we only forward mouse relative motion to the app when we have keyboard focus?" ); + gamescope::ConVar cv_wayland_use_modifiers( "wayland_use_modifiers", true, "Use DMA-BUF modifiers?" ); ++ gamescope::ConVar cv_wayland_overlay_planes( "wayland_overlay_planes", -1, "How many planes above the base one the host shows without composing them itself; more are composited here into one. -1 for no limit." ); + + gamescope::ConVar cv_wayland_hdr10_saturation_scale( "wayland_hdr10_saturation_scale", 1.0, "Saturation scale for HDR10 content by gamut expansion. 1.0 - 1.2 is a good range to play with." ); + +@@ -1102,6 +1103,7 @@ namespace gamescope + eLayer0Filter == GamescopeUpscaleFilter::PIXEL ) && !bLayer0ScreenSize; + + bNeedsFullComposite |= cv_composite_force; ++ bNeedsFullComposite |= cv_wayland_overlay_planes >= 0 && pFrameInfo->layers.count() > 1 + cv_wayland_overlay_planes; + bNeedsFullComposite |= pFrameInfo->useFSRLayer0; + bNeedsFullComposite |= pFrameInfo->useNISLayer0; + bNeedsFullComposite |= pFrameInfo->useSGSRLayer0; diff --git a/tools/gamescope/patches/0136-composite-into-released-output-images.patch b/tools/gamescope/patches/0136-composite-into-released-output-images.patch new file mode 100644 index 0000000000..2f827f8703 --- /dev/null +++ b/tools/gamescope/patches/0136-composite-into-released-output-images.patch @@ -0,0 +1,218 @@ +diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp +index fe38c7d..be99e6d 100644 +--- a/src/Backends/WaylandBackend.cpp ++++ b/src/Backends/WaylandBackend.cpp +@@ -503,6 +503,8 @@ namespace gamescope + wl_buffer *GetHostBuffer() const { return m_pHostBuffer; } + wlr_buffer *GetClientBuffer() const { return m_pClientBuffer; } + ++ bool HeldByHost() const override { return m_bCompositorAcquired; } ++ + void Wayland_Buffer_Release( wl_buffer *pBuffer ); + static const wl_buffer_listener s_BufferListener; + +diff --git a/src/backend.h b/src/backend.h +index fbfa7c7..30b42ca 100644 +--- a/src/backend.h ++++ b/src/backend.h +@@ -288,6 +288,8 @@ namespace gamescope + virtual void SetReleasePoint( std::shared_ptr pReleasePoint ) = 0; + + virtual IBackendFb *EnsureImported() = 0; ++ ++ virtual bool HeldByHost() const { return false; } + }; + + class IBackendPlane +diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp +index 0835bfe..42cc9c4 100644 +--- a/src/rendervulkan.cpp ++++ b/src/rendervulkan.cpp +@@ -3644,15 +3644,12 @@ static bool vulkan_make_output_images( VulkanOutput_t *pOutput ) + outputImageflags.bSampled = true; // for pipewire blits + outputImageflags.bOutputImage = true; + +- pOutput->outputImages.resize(3); // extra image for partial composition. +- pOutput->outputImagesPartialOverlay.resize(3); ++ const uint32_t uImageCount = GetBackend()->IsSessionBased() ? 3u : 5u; + +- pOutput->outputImages[0] = nullptr; +- pOutput->outputImages[1] = nullptr; +- pOutput->outputImages[2] = nullptr; +- pOutput->outputImagesPartialOverlay[0] = nullptr; +- pOutput->outputImagesPartialOverlay[1] = nullptr; +- pOutput->outputImagesPartialOverlay[2] = nullptr; ++ pOutput->outputImages.clear(); ++ pOutput->outputImagesPartialOverlay.clear(); ++ pOutput->outputImages.resize( uImageCount ); ++ pOutput->outputImagesPartialOverlay.resize( uImageCount ); + + uint32_t uDRMFormat = pOutput->uOutputFormat; + +@@ -3662,28 +3659,14 @@ static bool vulkan_make_output_images( VulkanOutput_t *pOutput ) + if ( g_uOutputRotation & 1u ) + std::swap( uOutputWidth, uOutputHeight ); + +- pOutput->outputImages[0] = new CVulkanTexture(); +- bool bSuccess = pOutput->outputImages[0]->BInit( uOutputWidth, uOutputHeight, 1u, uDRMFormat, outputImageflags ); +- if ( bSuccess != true ) +- { +- vk_log.errorf( "failed to allocate buffer for KMS" ); +- return false; +- } +- +- pOutput->outputImages[1] = new CVulkanTexture(); +- bSuccess = pOutput->outputImages[1]->BInit( uOutputWidth, uOutputHeight, 1u, uDRMFormat, outputImageflags ); +- if ( bSuccess != true ) ++ for ( uint32_t i = 0; i < uImageCount; i++ ) + { +- vk_log.errorf( "failed to allocate buffer for KMS" ); +- return false; +- } +- +- pOutput->outputImages[2] = new CVulkanTexture(); +- bSuccess = pOutput->outputImages[2]->BInit( uOutputWidth, uOutputHeight, 1u, uDRMFormat, outputImageflags ); +- if ( bSuccess != true ) +- { +- vk_log.errorf( "failed to allocate buffer for KMS" ); +- return false; ++ pOutput->outputImages[i] = new CVulkanTexture(); ++ if ( !pOutput->outputImages[i]->BInit( uOutputWidth, uOutputHeight, 1u, uDRMFormat, outputImageflags ) ) ++ { ++ vk_log.errorf( "failed to allocate buffer for KMS" ); ++ return false; ++ } + } + + // Oh no. +@@ -3696,28 +3679,14 @@ static bool vulkan_make_output_images( VulkanOutput_t *pOutput ) + { + uint32_t uPartialDRMFormat = pOutput->uOutputFormatOverlay; + +- pOutput->outputImagesPartialOverlay[0] = new CVulkanTexture(); +- bool bSuccess = pOutput->outputImagesPartialOverlay[0]->BInit( uOutputWidth, uOutputHeight, 1u, uPartialDRMFormat, outputImageflags, nullptr, 0, 0, pOutput->outputImages[0].get() ); +- if ( bSuccess != true ) +- { +- vk_log.errorf( "failed to allocate buffer for KMS" ); +- return false; +- } +- +- pOutput->outputImagesPartialOverlay[1] = new CVulkanTexture(); +- bSuccess = pOutput->outputImagesPartialOverlay[1]->BInit( uOutputWidth, uOutputHeight, 1u, uPartialDRMFormat, outputImageflags, nullptr, 0, 0, pOutput->outputImages[1].get() ); +- if ( bSuccess != true ) ++ for ( uint32_t i = 0; i < uImageCount; i++ ) + { +- vk_log.errorf( "failed to allocate buffer for KMS" ); +- return false; +- } +- +- pOutput->outputImagesPartialOverlay[2] = new CVulkanTexture(); +- bSuccess = pOutput->outputImagesPartialOverlay[2]->BInit( uOutputWidth, uOutputHeight, 1u, uPartialDRMFormat, outputImageflags, nullptr, 0, 0, pOutput->outputImages[2].get() ); +- if ( bSuccess != true ) +- { +- vk_log.errorf( "failed to allocate buffer for KMS" ); +- return false; ++ pOutput->outputImagesPartialOverlay[i] = new CVulkanTexture(); ++ if ( !pOutput->outputImagesPartialOverlay[i]->BInit( uOutputWidth, uOutputHeight, 1u, uPartialDRMFormat, outputImageflags, nullptr, 0, 0, pOutput->outputImages[i].get() ) ) ++ { ++ vk_log.errorf( "failed to allocate buffer for KMS" ); ++ return false; ++ } + } + } + +@@ -3755,6 +3724,8 @@ bool vulkan_remake_output_images() + g_device.waitIdle(); + + pOutput->nOutImage = 0; ++ pOutput->nLastOutImage = 0; ++ pOutput->nDeferredOutImage = 0; + + // Delete screenshot/capture textures to be remade if needed + for (auto& pScreenshotTexture : pOutput->pScreenshotTextures) +@@ -4604,6 +4575,30 @@ namespace + + ReshadeEffectPipeline *g_pLastReshadeEffect = nullptr; + ++static bool vulkan_output_image_held( uint32_t nImage ) ++{ ++ for ( const auto &pImage : { g_output.outputImages[ nImage ], g_output.outputImagesPartialOverlay[ nImage ] } ) ++ { ++ if ( pImage != nullptr && pImage->GetBackendFb() != nullptr && pImage->GetBackendFb()->HeldByHost() ) ++ return true; ++ } ++ return false; ++} ++ ++static uint32_t vulkan_free_output_image( uint32_t nFirst ) ++{ ++ const uint32_t uCount = g_output.outputImages.size(); ++ for ( uint32_t i = 0; i < uCount; i++ ) ++ { ++ const uint32_t nImage = ( nFirst + i ) % uCount; ++ if ( uCount > 3 && ( nImage == g_output.nLastOutImage || nImage == g_output.nDeferredOutImage ) ) ++ continue; ++ if ( !vulkan_output_image_held( nImage ) ) ++ return nImage; ++ } ++ return nFirst; ++} ++ + std::optional vulkan_composite( struct FrameInfo_t *frameInfo, gamescope::Rc pPipewireTexture, bool partial, gamescope::Rc pOutputOverride, bool increment, std::unique_ptr pInCommandBuffer ) + { + EOTF outputTF = frameInfo->outputEncodingEOTF; +@@ -4643,6 +4638,9 @@ std::optional vulkan_composite( struct FrameInfo_t *frameInfo, gamesco + if ( !pOutputOverride && !vulkan_ensure_output_images() ) + return std::nullopt; + ++ if ( !pOutputOverride && !GetBackend()->UsesVulkanSwapchain() ) ++ g_output.nOutImage = vulkan_free_output_image( g_output.nOutImage ); ++ + gamescope::Rc compositeImage; + if ( pOutputOverride ) + compositeImage = pOutputOverride; +@@ -4877,7 +4875,9 @@ std::optional vulkan_composite( struct FrameInfo_t *frameInfo, gamesco + + if ( !GetBackend()->UsesVulkanSwapchain() && pOutputOverride == nullptr && increment ) + { +- g_output.nOutImage = ( g_output.nOutImage + 1 ) % 3; ++ g_output.nDeferredOutImage = g_output.nLastOutImage; ++ g_output.nLastOutImage = g_output.nOutImage; ++ g_output.nOutImage = ( g_output.nOutImage + 1 ) % g_output.outputImages.size(); + } + + return sequence; +@@ -4931,19 +4931,7 @@ bool vulkan_format_supports_features(VkFormat format, VkFormatFeatureFlags featu + + gamescope::Rc vulkan_get_last_output_image( bool partial, bool defer ) + { +- // Get previous image ( +2 ) +- // 1 2 3 +- // | +- // | +- uint32_t nRegularImage = ( g_output.nOutImage + 2 ) % 3; +- +- // Get previous previous image ( +1 ) +- // 1 2 3 +- // | +- // | +- uint32_t nDeferredImage = ( g_output.nOutImage + 1 ) % 3; +- +- uint32_t nOutImage = defer ? nDeferredImage : nRegularImage; ++ uint32_t nOutImage = defer ? g_output.nDeferredOutImage : g_output.nLastOutImage; + + if ( partial ) + { +diff --git a/src/rendervulkan.hpp b/src/rendervulkan.hpp +index e0ede11..8ae3b71 100644 +--- a/src/rendervulkan.hpp ++++ b/src/rendervulkan.hpp +@@ -591,6 +591,8 @@ struct VulkanOutput_t + std::vector> presentationImages; + + uint32_t nOutImage; // swapchain index in nested mode, or ping/pong between two RTs ++ uint32_t nLastOutImage = 0; ++ uint32_t nDeferredOutImage = 0; + std::vector> outputImages; + std::vector> outputImagesPartialOverlay; + gamescope::OwningRc temporaryHackyBlankImage; diff --git a/tools/gamescope/patches/0137-wayland-backend-host-refresh-rates.patch b/tools/gamescope/patches/0137-wayland-backend-host-refresh-rates.patch new file mode 100644 index 0000000000..04860928c4 --- /dev/null +++ b/tools/gamescope/patches/0137-wayland-backend-host-refresh-rates.patch @@ -0,0 +1,293 @@ +diff --git a/protocol/droiddeck-refresh-v1.xml b/protocol/droiddeck-refresh-v1.xml +new file mode 100644 +index 0000000..c4464a0 +--- /dev/null ++++ b/protocol/droiddeck-refresh-v1.xml +@@ -0,0 +1,81 @@ ++ ++ ++ ++ Copyright 2026 DroidDeck contributors ++ ++ Permission is hereby granted, free of charge, to any person obtaining a ++ copy of this software and associated documentation files (the "Software"), ++ to deal in the Software without restriction, including without limitation ++ the rights to use, copy, modify, merge, publish, distribute, sublicense, ++ and/or sell copies of the Software, and to permit persons to whom the ++ Software is furnished to do so, subject to the following conditions: ++ ++ The above copyright notice and this permission notice (including the next ++ paragraph) shall be included in all copies or substantial portions of the ++ Software. ++ ++ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ++ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ++ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ++ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ++ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ++ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ++ DEALINGS IN THE SOFTWARE. ++ ++ ++ ++ ++ A nested compositor paces its clients against the refresh rate of the ++ panel it is shown on. When its clients are held to a frame rate the ++ panel's current rate does not divide evenly, frames are shown for an ++ uneven number of refreshes. This interface lets the nested compositor ++ see every refresh rate the panel can run at its current size and ask ++ for the one that suits the frame rate it is pacing to. ++ ++ On bind the compositor sends one rate event per refresh rate, lowest ++ first, followed by done. The list is sent again, in full, whenever it ++ changes (a different panel, or a limit the user placed on the panel's ++ rate). The rate the panel is running at is still reported the standard ++ way, through wl_output.mode. ++ ++ A request is a preference, not a guarantee: the user, the platform or ++ another output mirroring the panel may hold the panel at another rate. ++ The client reads the result from wl_output.mode. ++ ++ ++ ++ ++ The preference set through this object is dropped. ++ ++ ++ ++ ++ ++ refresh is the panel rate the client would like, in Hz, taken from ++ the advertised list; 0 withdraws the preference. frame_rate is the ++ frame rate the client holds its content to, in frames per second, or ++ 0 when the content is not held to a rate. The compositor may multiply ++ the content's frame rate itself (generated frames); when it does, it ++ picks the advertised rate that the multiplied frame rate divides ++ evenly instead of the requested one. ++ ++ ++ ++ ++ ++ ++ ++ Sent once per rate, lowest first, in Hz rounded to the nearest whole ++ number. ++ ++ ++ ++ ++ ++ ++ Ends a list of rate events. The rates received since the previous ++ done replace the earlier list. ++ ++ ++ ++ +diff --git a/protocol/meson.build b/protocol/meson.build +index cf8fbd1..71fe31b 100644 +--- a/protocol/meson.build ++++ b/protocol/meson.build +@@ -43,6 +43,8 @@ protocols = [ + 'gamescope-private.xml', + 'gamescope-action-binding.xml', + ++ 'droiddeck-refresh-v1.xml', ++ + # wlroots protocols + 'wlr-layer-shell-unstable-v1.xml', + ] +diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp +index be99e6d..9862641 100644 +--- a/src/Backends/WaylandBackend.cpp ++++ b/src/Backends/WaylandBackend.cpp +@@ -38,6 +38,7 @@ + #include + #include + #include ++#include + #include "wlr_end.hpp" + + #include "drm_include.h" +@@ -705,6 +706,10 @@ namespace gamescope + virtual bool UsesVulkanSwapchain() const override; + + virtual bool IsSessionBased() const override; ++ virtual bool HackTemporarySetDynamicRefresh( int nRefresh ) override; ++ ++ std::span GetHostRefreshRates() const; ++ void SyncHostRefreshTarget(); + virtual bool SupportsExplicitSync() const override; + + virtual bool IsPaused() const override; +@@ -778,6 +783,10 @@ namespace gamescope + void Wayland_Output_Geometry( wl_output *pOutput, int32_t nX, int32_t nY, int32_t nPhysicalWidth, int32_t nPhysicalHeight, int32_t nSubpixel, const char *pMake, const char *pModel, int32_t nTransform ); + void Wayland_Output_Mode( wl_output *pOutput, uint32_t uFlags, int32_t nWidth, int32_t nHeight, int32_t nRefresh ); + void Wayland_Output_Done( wl_output *pOutput ); ++ ++ void Wayland_Refresh_Rate( droiddeck_refresh_v1 *pRefresh, uint32_t uRefresh ); ++ void Wayland_Refresh_Done( droiddeck_refresh_v1 *pRefresh ); ++ static const droiddeck_refresh_v1_listener s_RefreshListener; + void Wayland_Output_Scale( wl_output *pOutput, int32_t nFactor ); + void Wayland_Output_Name( wl_output *pOutput, const char *pName ); + void Wayland_Output_Description( wl_output *pOutput, const char *pDescription ); +@@ -829,6 +838,12 @@ namespace gamescope + OwningRc m_pOwnedBlackFb; + OwningRc m_pBlackTexture; + wp_presentation *m_pPresentation = nullptr; ++ droiddeck_refresh_v1 *m_pHostRefresh = nullptr; ++ std::array m_HostRefreshRates{}; ++ std::atomic m_uHostRefreshRateCount = { 0 }; ++ std::vector m_PendingHostRefreshRates; ++ int m_nSentHostRefresh = 0; ++ int m_nSentHostFrameRate = 0; + frog_color_management_factory_v1 *m_pFrogColorMgmtFactory = nullptr; + wp_color_manager_v1 *m_pWPColorManager = nullptr; + wp_image_description_v1 *m_pWPImageDescriptions[ GamescopeAppTextureColorspace_Count ]{}; +@@ -890,6 +905,11 @@ namespace gamescope + .global = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_Registry_Global ), + .global_remove = WAYLAND_NULL(), + }; ++ const droiddeck_refresh_v1_listener CWaylandBackend::s_RefreshListener = ++ { ++ .rate = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_Refresh_Rate ), ++ .done = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_Refresh_Done ), ++ }; + const wl_output_listener CWaylandBackend::s_OutputListener = + { + .geometry = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_Output_Geometry ), +@@ -1087,6 +1107,7 @@ namespace gamescope + { + droiddeck::frame_trace::Record( droiddeck::frame_trace::Event::OutputPresent ); + UpdateFullscreenState(); ++ m_pBackend->SyncHostRefreshTarget(); + + bool bNeedsFullComposite = false; + +@@ -1244,7 +1265,7 @@ namespace gamescope + } + std::span CWaylandConnector::GetValidDynamicRefreshRates() const + { +- return std::span{}; ++ return m_pBackend->GetHostRefreshRates(); + } + + void CWaylandConnector::GetNativeColorimetry( +@@ -2396,6 +2417,52 @@ namespace gamescope + return false; + } + ++ std::span CWaylandBackend::GetHostRefreshRates() const ++ { ++ const uint32_t uCount = m_uHostRefreshRateCount; ++ if ( uCount < 2 ) ++ return std::span{}; ++ return std::span{ m_HostRefreshRates.data(), uCount }; ++ } ++ ++ bool CWaylandBackend::HackTemporarySetDynamicRefresh( int nRefresh ) ++ { ++ if ( !m_pHostRefresh ) ++ return false; ++ SyncHostRefreshTarget(); ++ return true; ++ } ++ ++ void CWaylandBackend::SyncHostRefreshTarget() ++ { ++ if ( !m_pHostRefresh ) ++ return; ++ const int nFrameRate = steamcompmgr_get_app_target_fps(); ++ const int nRefresh = steamcompmgr_get_app_dynamic_refresh(); ++ if ( nRefresh == m_nSentHostRefresh && nFrameRate == m_nSentHostFrameRate ) ++ return; ++ xdg_log.infof( "Asking the host for %dhz at %dfps", nRefresh, nFrameRate ); ++ droiddeck_refresh_v1_set_target( m_pHostRefresh, nRefresh, nFrameRate ); ++ m_nSentHostRefresh = nRefresh; ++ m_nSentHostFrameRate = nFrameRate; ++ } ++ ++ void CWaylandBackend::Wayland_Refresh_Rate( droiddeck_refresh_v1 *pRefresh, uint32_t uRefresh ) ++ { ++ m_PendingHostRefreshRates.push_back( uRefresh ); ++ } ++ void CWaylandBackend::Wayland_Refresh_Done( droiddeck_refresh_v1 *pRefresh ) ++ { ++ std::sort( m_PendingHostRefreshRates.begin(), m_PendingHostRefreshRates.end() ); ++ const uint32_t uCount = std::min( m_PendingHostRefreshRates.size(), m_HostRefreshRates.size() ); ++ m_uHostRefreshRateCount = 0; ++ std::copy_n( m_PendingHostRefreshRates.begin(), uCount, m_HostRefreshRates.begin() ); ++ m_uHostRefreshRateCount = uCount; ++ m_PendingHostRefreshRates.clear(); ++ steamcompmgr_display_rates_changed(); ++ force_repaint(); ++ } ++ + bool CWaylandBackend::SupportsExplicitSync() const + { + // GAMESCOPE_DISABLE_EXPLICIT_SYNC=1: a kernel without DRM_IOCTL_SYNCOBJ_EVENTFD (before +@@ -2647,6 +2714,11 @@ namespace gamescope + wl_output_add_listener( pOutput , &s_OutputListener, this ); + m_pOutputs.emplace( std::make_pair( std::move( pOutput ), WaylandOutputInfo{} ) ); + } ++ else if ( !strcmp( pInterface, droiddeck_refresh_v1_interface.name ) ) ++ { ++ m_pHostRefresh = (droiddeck_refresh_v1 *)wl_registry_bind( pRegistry, uName, &droiddeck_refresh_v1_interface, 1u ); ++ droiddeck_refresh_v1_add_listener( m_pHostRefresh, &s_RefreshListener, this ); ++ } + else if ( !strcmp( pInterface, frog_color_management_factory_v1_interface.name ) ) + { + m_pFrogColorMgmtFactory = (frog_color_management_factory_v1 *)wl_registry_bind( pRegistry, uName, &frog_color_management_factory_v1_interface, 1u ); +diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp +index 38b304b..d7d11b3 100644 +--- a/src/steamcompmgr.cpp ++++ b/src/steamcompmgr.cpp +@@ -1229,6 +1229,25 @@ static int g_nCombinedAppRefreshCycleOverride[gamescope::GAMESCOPE_SCREEN_TYPE_C + bool g_nCombinedAppRefreshCycleChangeRefresh[gamescope::GAMESCOPE_SCREEN_TYPE_COUNT] = { true, true }; + bool g_nCombinedAppRefreshCycleChangeFPS[gamescope::GAMESCOPE_SCREEN_TYPE_COUNT] = { true, true }; + ++int steamcompmgr_get_app_target_fps() ++{ ++ return g_nSteamCompMgrTargetFPS; ++} ++ ++int steamcompmgr_get_app_dynamic_refresh() ++{ ++ if ( !GetBackend()->GetCurrentConnector() ) ++ return 0; ++ return g_nDynamicRefreshRate[ GetBackend()->GetCurrentConnector()->GetScreenType() ]; ++} ++ ++static std::atomic g_bDisplayRatesChanged = { false }; ++ ++void steamcompmgr_display_rates_changed() ++{ ++ g_bDisplayRatesChanged = true; ++} ++ + static void _update_app_target_refresh_cycle() + { + if ( !GetBackend()->GetCurrentConnector() ) +@@ -9703,7 +9722,8 @@ void update_vrr_atoms(xwayland_ctx_t *root_ctx, bool force, bool* needs_flush = + *needs_flush = true; + } + +- if ( g_nOutputRefresh != g_nCurrentRefreshRate_CachedValue || force ) ++ const bool bDisplayRatesChanged = g_bDisplayRatesChanged.exchange( false ); ++ if ( g_nOutputRefresh != g_nCurrentRefreshRate_CachedValue || bDisplayRatesChanged || force ) + { + int32_t nRefresh = gamescope::ConvertmHzToHz( g_nOutputRefresh ); + XChangeProperty(root_ctx->dpy, root_ctx->root, root_ctx->atoms.gamescopeDisplayRefreshRateFeedback, XA_CARDINAL, 32, PropModeReplace, +diff --git a/src/steamcompmgr.hpp b/src/steamcompmgr.hpp +index ff54d8e..9e0bb79 100644 +--- a/src/steamcompmgr.hpp ++++ b/src/steamcompmgr.hpp +@@ -202,4 +202,7 @@ MouseCursor *steamcompmgr_get_server_cursor(uint32_t serverId); + + extern gamescope::ConVar cv_tearing_enabled; + ++extern int steamcompmgr_get_app_target_fps(); ++extern int steamcompmgr_get_app_dynamic_refresh(); ++extern void steamcompmgr_display_rates_changed(); + extern void steamcompmgr_set_app_refresh_cycle_override( gamescope::GamescopeScreenType type, int override_fps, bool change_refresh, bool change_fps_cap ); diff --git a/tools/gamescope/patches/0138-limiter-even-cadence.patch b/tools/gamescope/patches/0138-limiter-even-cadence.patch new file mode 100644 index 0000000000..429aa78933 --- /dev/null +++ b/tools/gamescope/patches/0138-limiter-even-cadence.patch @@ -0,0 +1,67 @@ +diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp +index d7d11b3..cfec551 100644 +--- a/src/steamcompmgr.cpp ++++ b/src/steamcompmgr.cpp +@@ -7188,6 +7188,19 @@ init_runtime_info() + update_runtime_info(); + } + ++static uint64_t limiter_latch_target( uint64_t ulPreviousTarget, uint64_t ulLatched, uint64_t ulLimitedCycle, uint64_t ulRefreshCycle ) ++{ ++ const uint64_t ulTarget = ulPreviousTarget + ulLimitedCycle; ++ const bool bLate = ulTarget + ulRefreshCycle * 3 / 4 < ulLatched; ++ const bool bEarly = ulTarget > ulLatched + ulRefreshCycle; ++ return ( bLate || bEarly ) ? ulLatched : ulTarget; ++} ++ ++static bool limiter_holds_vblank( uint64_t ulTarget, uint64_t ulNow, uint64_t ulLimitedCycle, uint64_t ulRefreshCycle ) ++{ ++ return ulNow + ulRefreshCycle / 2 < ulTarget + ulLimitedCycle; ++} ++ + static void + steamcompmgr_flush_frame_done( steamcompmgr_win_t *w ) + { +@@ -7206,6 +7219,9 @@ steamcompmgr_flush_frame_done( steamcompmgr_win_t *w ) + + w->last_commit_first_latch_time = timespec_to_nanos(now); + ++ w->limiter_latch_target_time = limiter_latch_target( w->limiter_latch_target_time, w->last_commit_first_latch_time, ++ g_SteamCompMgrLimitedAppRefreshCycle, g_SteamCompMgrAppRefreshCycle ); ++ + // Acknowledge commit once. + wlserver_lock(); + +@@ -7258,8 +7274,7 @@ static bool steamcompmgr_should_vblank_window( bool bShouldLimitFPS, uint64_t vb + { + if ( w && now ) + { +- uint64_t schedule = w->last_commit_first_latch_time + g_SteamCompMgrLimitedAppRefreshCycle; +- if ( now + g_SteamCompMgrAppRefreshCycle / 2 < schedule ) ++ if ( limiter_holds_vblank( w->limiter_latch_target_time, now, g_SteamCompMgrLimitedAppRefreshCycle, g_SteamCompMgrAppRefreshCycle ) ) + bSendCallback = false; + } + else +@@ -11047,9 +11062,7 @@ steamcompmgr_main(int argc, char **argv) + } + else + { +- int nVblankDivisor = nRealRefreshHz / nTargetFPS; +- +- g_SteamCompMgrLimitedAppRefreshCycle = g_SteamCompMgrAppRefreshCycle * nVblankDivisor; ++ g_SteamCompMgrLimitedAppRefreshCycle = g_SteamCompMgrAppRefreshCycle * nRealRefreshHz / nTargetFPS; + } + } + } +diff --git a/src/steamcompmgr_shared.hpp b/src/steamcompmgr_shared.hpp +index 0fcc80b..3c74d62 100644 +--- a/src/steamcompmgr_shared.hpp ++++ b/src/steamcompmgr_shared.hpp +@@ -146,6 +146,7 @@ struct steamcompmgr_win_t { + bool outdatedInteractiveFocus = false; + + uint64_t last_commit_first_latch_time = 0; ++ uint64_t limiter_latch_target_time = 0; + uint64_t last_commit_present_time = 0; + + bool hasHwndStyle = false; diff --git a/tools/gamescope/patches/0139-hdr-switch-live.patch b/tools/gamescope/patches/0139-hdr-switch-live.patch new file mode 100644 index 0000000000..3c1b839620 --- /dev/null +++ b/tools/gamescope/patches/0139-hdr-switch-live.patch @@ -0,0 +1,54 @@ +diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp +index 9862641..e9d2923 100644 +--- a/src/Backends/WaylandBackend.cpp ++++ b/src/Backends/WaylandBackend.cpp +@@ -1972,7 +1972,7 @@ namespace gamescope + { + auto *pHDRInfo = &m_pConnector->m_HDRInfo; + if (m_pBackend->SupportsColorManagement()) { +- pHDRInfo->bExposeHDRSupport = ( cv_hdr_enabled && m_pConnector->m_uMaxTargetLuminance > m_pConnector->m_uReferenceLuminance ); ++ pHDRInfo->bExposeHDRSupport = ( m_pConnector->m_uMaxTargetLuminance > m_pConnector->m_uReferenceLuminance ); + pHDRInfo->eOutputEncodingEOTF = pHDRInfo->bExposeHDRSupport ? EOTF_PQ : EOTF_Gamma22; + } + +@@ -2282,7 +2282,7 @@ namespace gamescope + + assert( u8BitFormat != DRM_FORMAT_INVALID ); + +- *pPrimaryPlaneFormat = u10BitFormat != DRM_FORMAT_INVALID ? u10BitFormat : u8BitFormat; ++ *pPrimaryPlaneFormat = ( cv_hdr_enabled && u10BitFormat != DRM_FORMAT_INVALID ) ? u10BitFormat : u8BitFormat; + *pOverlayPlaneFormat = u8BitFormat; + } + +@@ -2493,13 +2493,17 @@ namespace gamescope + + // XXX: We should do this a better way that handles per-window and appid stuff + // down the line +- if ( cv_hdr_enabled && GetCurrentConnector()->GetHDRInfo().bExposeHDRSupport ) ++ if ( !GetCurrentConnector()->GetHDRInfo().bExposeHDRSupport ) ++ { ++ setenv( "DXVK_HDR", "0", true ); ++ } ++ else if ( cv_hdr_enabled ) + { + setenv( "DXVK_HDR", "1", true ); + } + else + { +- setenv( "DXVK_HDR", "0", true ); ++ unsetenv( "DXVK_HDR" ); + } + + WritePatchedEdid( GetCurrentConnector()->GetRawEDID(), GetCurrentConnector()->GetHDRInfo(), false ); +diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp +index 42cc9c4..d0d21f0 100644 +--- a/src/rendervulkan.cpp ++++ b/src/rendervulkan.cpp +@@ -3735,6 +3735,7 @@ bool vulkan_remake_output_images() + + if ( vulkan_defer_output_images() ) + { ++ GetBackend()->GetPreferredOutputFormat( &pOutput->uOutputFormat, &pOutput->uOutputFormatOverlay ); + pOutput->outputImages.clear(); + pOutput->outputImagesPartialOverlay.clear(); + pOutput->temporaryHackyBlankImage = vulkan_create_debug_blank_texture(); diff --git a/tools/gamescope/release.env b/tools/gamescope/release.env index bf5211b032..c2ff293485 100644 --- a/tools/gamescope/release.env +++ b/tools/gamescope/release.env @@ -1,3 +1,3 @@ GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components -GAMESCOPE_TAG=gamescope-3.16.29-p23 -GAMESCOPE_SHA256=f5f2b8f658234ad2910a1be53c238188db7e7b2a9079f8cc5fa9ea006bebbe7e +GAMESCOPE_TAG=gamescope-3.16.29-zerocopy-8df683f1-qa +GAMESCOPE_SHA256=609198c39b125094a65e1703ffcfd6538e88c9784a1a6596bf673f2e5dc7af80 diff --git a/tools/linuxfs/desktop/droiddeck-desktop b/tools/linuxfs/desktop/droiddeck-desktop index d063bab657..f715ad18d7 100644 --- a/tools/linuxfs/desktop/droiddeck-desktop +++ b/tools/linuxfs/desktop/droiddeck-desktop @@ -24,7 +24,7 @@ if [ -n "${DD_DEBUG_DIR:-}" ]; then exec >>"$DD_DEBUG_DIR/desktop.log" 2>&1 echo "== droiddeck-desktop $(date -u '+%Y-%m-%d %H:%M:%S UTC') ${DD_WIDTH:-1280}x${DD_HEIGHT:-720}" fi -find "$XDG_RUNTIME_DIR" -mindepth 1 -maxdepth 1 ! -name 'wayland-0*' ! -name 'keymap.xkb' -exec rm -rf {} + 2>/dev/null +find "$XDG_RUNTIME_DIR" -mindepth 1 -maxdepth 1 ! -name 'wayland-0*' ! -name 'keymap.xkb' ! -name 'droiddeck-display-buffers' -exec rm -rf {} + 2>/dev/null chmod 700 "$XDG_RUNTIME_DIR" 2>/dev/null mkdir -p /tmp/.X11-unix /tmp/.ICE-unix && chmod 1777 /tmp/.X11-unix /tmp/.ICE-unix 2>/dev/null export DD_DESKTOP=1 diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet b/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet index 066f9c572e..0cddb3fb4b 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet @@ -37,9 +37,6 @@ USER_PREFERENCES = "UserPreferencesMask" WINE_USER_PREFERENCES = bytes((0x10, 0x00, 0x00, 0x80, 0x12, 0x00, 0x00, 0x00)) CLIENT_AREA_ANIMATION = (4, 0x02) WALLPAPER_MAX = (1280, 720) -FEX_REQUEST = "battlenet-fex.request" -FEX_RESULT = "battlenet-fex.result" -FEX_WAIT = 120 START_GRACE = 90 POLL = 2 STOP_WAIT = 5 @@ -779,32 +776,6 @@ def write_menu(path=MENU): say("menu entry not written: %s" % error) -def ask_fex(launch_dir, wait=FEX_WAIT): - if not launch_dir or not os.path.isdir(launch_dir): - say("not inside a DroidDeck session; FEX stays as Components has it") - return None - result = os.path.join(launch_dir, FEX_RESULT) - request = os.path.join(launch_dir, FEX_REQUEST) - try: - os.unlink(result) - except OSError: - pass - with open(request + ".tmp", "w", encoding="utf-8") as f: - f.write("appid=%s\n" % APP_ID) - os.replace(request + ".tmp", request) - deadline = time.monotonic() + wait - while time.monotonic() < deadline: - try: - with open(result, encoding="utf-8") as f: - answer = f.read().strip() - except OSError: - time.sleep(0.5) - continue - os.unlink(result) - return answer - return None - - def wine_processes(pfx, proc="/proc"): want = os.path.realpath(pfx).rstrip("/") found = [] @@ -1148,8 +1119,6 @@ def stop_leftovers(pfx): def open_client(root, reinstall=False): pfx = os.path.join(prefix(root), "pfx") write_menu() - answer = ask_fex(os.environ.get("DD_LAUNCH_DIR")) - say("FEX: %s" % (answer or "no answer from the app; Components' choice stays")) if running(pfx): say("Battle.net is already running in its prefix; waiting for it to close") wait_while_open(pfx, grace=0) @@ -1238,8 +1207,6 @@ def launch(root, code): try: own = None if lock is not None and not running(pfx): - answer = ask_fex(os.environ.get("DD_LAUNCH_DIR")) - say("FEX: %s" % (answer or "no answer from the app; Components' choice stays")) verb = None if stop_leftovers(pfx) else "run" configure(root, LIBRARY) own = start(launcher(root), verb) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat index b39682bc29..32a9889b87 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat @@ -66,19 +66,32 @@ BRIGHTNESS_JS = r""" """.replace("__BINDING__", BRIGHTNESS_BINDING) +def control_request(name, text, directory): + path = os.path.join(directory, name) + with open(path + ".tmp", "w") as target: + target.write(text + "\n") + os.replace(path + ".tmp", path) + + def brightness_request(payload, directory=CONTROLS_DIR): try: value = float(payload) if not math.isfinite(value) or not 0 <= value <= 1: return - path = os.path.join(directory, "brightness.request") - with open(path + ".tmp", "w") as target: - target.write(str(value) + "\n") - os.replace(path + ".tmp", path) + control_request("brightness.request", str(value), directory) except (ValueError, TypeError, OSError): return +def hdr_request(payload, directory=CONTROLS_DIR): + if payload not in ("0", "1"): + return + try: + control_request("hdr.request", payload, directory) + except OSError: + return + + INSTALL_JS = r""" (() => { if (window.__droiddeckCompat) return "present"; @@ -256,6 +269,49 @@ TOUR_JS = r""" return "off"; })() """ +SET_SETTING_JS = r"""(field, value) => { + const bytes = []; + for (let n of [field * 8, value]) { + while (n > 127) { bytes.push((n & 127) | 128); n = Math.floor(n / 128); } + bytes.push(n); + } + return SteamClient.Settings.SetSetting(btoa(String.fromCharCode(...bytes))); + }""" +HDR_BINDING = "droiddeckHdrChanged" +HDR_JS = r""" +(() => { + if (window.__droiddeckHdr) return "present"; + const settings = window.settingsStore; + if (typeof settings?.clientSettings?.gamescope_hdr_enabled !== "boolean" || + typeof SteamClient.Settings?.SetSetting !== "function") return "unavailable"; + const write = __SET_SETTING__; + const HOLD_MS = 3000; + const self = { known: settings.clientSettings.gamescope_hdr_enabled, pending: null, until: 0 }; + self.set = value => { + if (typeof value !== "boolean") return true; + self.known = value; + if (settings.clientSettings.gamescope_hdr_enabled === value && self.pending === null) return true; + self.pending = value; + self.until = performance.now() + HOLD_MS; + write(21015, value ? 1 : 0); + return true; + }; + self.check = () => { + const value = settings.clientSettings.gamescope_hdr_enabled; + if (typeof value !== "boolean") return; + if (self.pending !== null) { + if (value !== self.pending && performance.now() < self.until) return; + self.pending = null; + } + if (value === self.known) return; + self.known = value; + if (typeof window.__BINDING__ === "function") window.__BINDING__(value ? "1" : "0"); + }; + self.interval = setInterval(self.check, 500); + window.__droiddeckHdr = self; + return "installed"; +})() +""".replace("__BINDING__", HDR_BINDING).replace("__SET_SETTING__", SET_SETTING_JS) FRAME_LIMIT_JS = r""" (() => { if (window.__droiddeckFrameLimit) return "present"; @@ -281,14 +337,7 @@ FRAME_LIMIT_JS = r""" } if (!service || !settings?.clientSettings || typeof SteamClient.Settings?.SetSetting !== "function") return "unavailable"; const self = { timer: null }; - const write = value => { - const bytes = []; - for (let n of [21002 * 8, value]) { - while (n > 127) { bytes.push((n & 127) | 128); n = Math.floor(n / 128); } - bytes.push(n); - } - return SteamClient.Settings.SetSetting(btoa(String.fromCharCode(...bytes))); - }; + const write = value => (__SET_SETTING__)(21002, value); self.check = async () => { let rates; try { @@ -316,7 +365,7 @@ FRAME_LIMIT_JS = r""" window.__droiddeckFrameLimit = self; return "installed"; })() -""" +""".replace("__SET_SETTING__", SET_SETTING_JS) WINDOW_BINDING = "droiddeckWindowAction" WINDOW_TARGET = "createflags=18" WINDOW_MOVES = {"nw": 0, "n": 1, "ne": 2, "e": 3, "se": 4, "s": 5, "sw": 6, "w": 7, "move": 8} @@ -923,6 +972,9 @@ class Helper: self.controls_installed = False self.frame_limit_state = None self.frame_limit_retry = 0 + self.hdr_state = None + self.hdr_installed = False + self.hdr_retry = 0 self.windows = {} self.windows_retry = 0 @@ -983,6 +1035,29 @@ class Helper: except (Closed, OSError, ValueError): del self.windows[ident] + def sync_hdr(self): + try: + with open(os.path.join(CONTROLS_DIR, "state.json")) as source: + value = json.load(source).get("hdr") + if not isinstance(value, bool): + return + if not self.hdr_installed: + if time.monotonic() < self.hdr_retry: + return + self.page.call("Runtime.addBinding", {"name": HDR_BINDING}) + self.hdr_installed = self.page.evaluate(HDR_JS) in ("installed", "present") + if not self.hdr_installed: + self.hdr_retry = time.monotonic() + 10 + return + if value != self.hdr_state: + if self.page.evaluate("window.__droiddeckHdr ? window.__droiddeckHdr.set(%s) : false" % json.dumps(value)) is True: + self.hdr_state = value + else: + self.hdr_state = None + self.hdr_installed = False + except (OSError, ValueError, TypeError, AttributeError): + pass + def sync_frame_limit(self): if self.frame_limit_state in ("installed", "present") or time.monotonic() < self.frame_limit_retry: return @@ -1095,6 +1170,9 @@ class Helper: self.controls_installed = False self.frame_limit_state = None self.frame_limit_retry = 0 + self.hdr_state = None + self.hdr_installed = False + self.hdr_retry = 0 self.sync_controls() return True @@ -1231,6 +1309,8 @@ class Helper: for e in events: if called(e, BRIGHTNESS_BINDING): brightness_request(e.get("params", {}).get("payload")) + if called(e, HDR_BINDING): + hdr_request(e.get("params", {}).get("payload")) if called(e, FILE_BINDING) and isinstance(e.get("params", {}).get("payload"), str): self.open_chooser(e["params"]["payload"]) return events @@ -1260,6 +1340,7 @@ class Helper: while True: self.sync_controls() self.sync_frame_limit() + self.sync_hdr() self.sync_windows() sources = [self.page.ws] + ([watcher] if watcher.fileno() >= 0 else []) sources += [page.ws for page in self.windows.values()] diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch b/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch index 5031cb93dc..76bdb395f0 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch @@ -5,6 +5,7 @@ import binascii import json import os import re +import runpy import shlex import shutil import stat @@ -337,6 +338,13 @@ UBISOFT_INSTALLER_URL = "https://static3.cdn.ubi.com/orbit/launcher_installer/Ub ROCKSTAR_SERVICE = Path("/usr/local/lib/droiddeck-rockstar") SERVICE_WAIT = 300.0 ROCKSTAR_FOLDER = "drive_c/Program Files/Rockstar Games/Launcher" +EPIC_SDK_SETUP = ROCKSTAR_FOLDER + "/Redistributables/SocialClub/Social-Club-Setup.exe" +SDK_SOURCE = ".droiddeck-sdk-source" +SDK_SETUP_LIMIT = 256 * 1024 * 1024 +EPIC_PARENT = Path("/usr/local/lib/droiddeck-epic/EpicGamesLauncher.exe") +EPIC_PARENT_ON = 'set "DD_P=1"' +EPIC_PARENT_SWITCH = "DD_EPIC_PARENT" +EPIC_SERVICE_WAIT = 60.0 ROCKSTAR_TITLES = {"gta3": "Grand Theft Auto III", "gtavc": "Grand Theft Auto: Vice City", "gtasa": "GTA: San Andreas", "gta4": "Grand Theft Auto IV", "lanoire": "LANoireMTL"} @@ -394,10 +402,9 @@ def rockstar_sdk(folder, sidecar): return False -def rockstar_registry(folder, title, compat_data, proton, sdk_arch=None): +def rockstar_registry(folder, title, compat_data, proton, sdk_arch=None, launcher=True): pfx = Path(compat_data) / "pfx" - launcher = r"C:\Program Files\Rockstar Games\Launcher" - values = [(r"Rockstar Games\Launcher", launcher)] + values = [(r"Rockstar Games\Launcher", r"C:\Program Files\Rockstar Games\Launcher")] if launcher else [] if title: values.append(("Rockstar Games\\" + title, windows_path(str(folder)))) entries = [("Software\\" + view + key, value) for view in ("", "Wow6432Node\\") for key, value in values] @@ -420,23 +427,29 @@ def rockstar_registry(folder, title, compat_data, proton, sdk_arch=None): return result.returncode == 0 -def rockstar_runtime(folder, exe, compat_data, arch): +def rockstar_runtime(folder, exe, compat_data, arch, installer=None): if arch == "x86": - rockstar_runtime(folder, exe, compat_data, "x64") + rockstar_runtime(folder, exe, compat_data, "x64", installer) pfx = Path(compat_data) / "pfx" target = pfx / "drive_c" / ("Program Files (x86)" if arch == "x86" else "Program Files") / "Rockstar Games/Social Club" if not target.resolve().is_relative_to(pfx.resolve()): raise ValueError("invalid Social Club destination") required = ("socialclub.dll", "socialclub.pak") + (("SocialClubHelper.exe",) if arch == "x64" else ()) marker = target / ".droiddeck-installing" - if all((target / name).is_file() for name in required) and not marker.exists(): + source_file, stamp = target / SDK_SOURCE, None + if installer is not None: + info = installer.stat() + stamp = "%d %d %s" % (info.st_size, info.st_mtime_ns, installer) + current = stamp is None or source_file.is_file() and not source_file.is_symlink() and source_file.read_text(errors="replace") == stamp + if all((target / name).is_file() for name in required) and not marker.exists() and current: return "present" - root = folder.resolve() - installers = [base / sub / "Social-Club-Setup.exe" for base in (root, exe.parent) - for sub in ("Redistributables", "Installers")] - installer = next((p for p in installers if p.is_file() and p.resolve().is_relative_to(root) and p.stat().st_size <= 256 * 1024 * 1024), None) if installer is None: - return "game-runtime" + root = folder.resolve() + installers = [base / sub / "Social-Club-Setup.exe" for base in (root, exe.parent) + for sub in ("Redistributables", "Installers")] + installer = next((p for p in installers if p.is_file() and p.resolve().is_relative_to(root) and p.stat().st_size <= SDK_SETUP_LIMIT), None) + if installer is None: + return "game-runtime" tool = shutil.which("7z") if not tool: return "no-unpacker" @@ -488,15 +501,67 @@ def rockstar_runtime(folder, exe, compat_data, arch): raise os.replace(stage_path, output) marker.unlink() + if stamp is not None: + source_file.unlink(missing_ok=True) + source_file.write_text(stamp) return "installed" -def fetch_service(service, store, launch_dir, ask_app=None): +def epic_parent_switch(sidecar, env=None): + own = sidecar.get("env") if isinstance(sidecar.get("env"), dict) else {} + if EPIC_PARENT_SWITCH in own: + return str(own[EPIC_PARENT_SWITCH]).replace('"', "") + env = os.environ if env is None else env + try: + game_env = runpy.run_path(str(Path(__file__).resolve().with_name("droiddeck-game-env"))) + try: + config = json.loads((Path(env.get("HOME") or "/root") / ".config/droiddeck/game-environment.json").read_text(encoding="utf-8")) + except FileNotFoundError: + config = {"version": 1} + env = game_env["apply_config"](env, config, game_env["game_id"](env)) + except (OSError, ValueError, KeyError, TypeError, AttributeError): + pass + return env.get(EPIC_PARENT_SWITCH, "") + + +def wants_epic_parent(folder, switch): + if switch in ("0", "1"): + return switch == "1" + try: + return EPIC_PARENT_ON in (folder / LAUNCHER).read_text(errors="replace").splitlines() + except OSError: + return False + + +def epic_rockstar_sdk(folder, sidecar, compat_data, proton): + if not compat_data: + return None + pfx = Path(compat_data) / "pfx" + root = folder.resolve() + exe = (folder / str(sidecar.get("exe") or "").replace("\\", "/")).resolve() + if not exe.is_relative_to(root): + return None + setups = [(pfx / EPIC_SDK_SETUP, pfx)] + [(base / sub / "Social-Club-Setup.exe", root) for base in (root, exe.parent) + for sub in ("Redistributables", "Installers")] + setup = next((path for path, inside in setups if path.is_file() and path.resolve().is_relative_to(inside.resolve()) + and path.stat().st_size <= SDK_SETUP_LIMIT), None) + if setup is None: + return None + made = "present" if (pfx / "user.reg").is_file() else create_prefix(compat_data, proton) + if made not in ("created", "present"): + return "prefix-" + made + state = rockstar_runtime(folder, exe, compat_data, "x64", setup) + if state in ("present", "installed") and not rockstar_registry(folder, None, compat_data, proton, sdk_arch="x64", launcher=False): + return state + " registry-unavailable" + return state + + +def fetch_service(service, store, launch_dir, ask_app=None, timeout=SERVICE_WAIT): if service.is_file(): return True if not launch_dir: return False - answer = (ask_app or ask)(Path(launch_dir) / "stores", {"op": "store-service", "store": store}, timeout=SERVICE_WAIT) + answer = (ask_app or ask)(Path(launch_dir) / "stores", {"op": "store-service", "store": store}, timeout=timeout) return isinstance(answer, dict) and bool(answer.get("ok")) and service.is_file() @@ -1650,6 +1715,15 @@ def main(argv): pass log("ubisoft %s: not prepared (%s), starting directly" % (game, e)) if store == "epic": + try: + if launch_dir and not EPIC_PARENT.is_file() and wants_epic_parent(folder, epic_parent_switch(sidecar)): + got = fetch_service(EPIC_PARENT, "epic", launch_dir, timeout=EPIC_SERVICE_WAIT) + log("epic parent stand-in: " + ("staged" if got else "unavailable")) + sdk = epic_rockstar_sdk(folder, sidecar, compat_data, os.environ.get("DD_STORE_PROTON", "")) + except (OSError, ValueError, subprocess.TimeoutExpired) as error: + sdk = "failed (%s)" % type(error).__name__ + if sdk: + log("epic rockstar sdk: " + sdk) handled = os.environ.get(EPIC_HANDLED) == "1" and (folder / EPIC_ARGS).is_file() if not handled: drop_stale(folder) diff --git a/tools/linuxfs/preload/inputudev.c b/tools/linuxfs/preload/inputudev.c index 823614bfd3..3dcb5a1049 100644 --- a/tools/linuxfs/preload/inputudev.c +++ b/tools/linuxfs/preload/inputudev.c @@ -1045,7 +1045,15 @@ static void *own_udev_symbol(const char *name) { } static void *dlvsym_any(const char *name) { +#if defined(__aarch64__) + static const char *versions[] = {"GLIBC_2.17", "GLIBC_2.34"}; +#elif defined(__x86_64__) + static const char *versions[] = {"GLIBC_2.2.5", "GLIBC_2.34"}; +#elif defined(__i386__) + static const char *versions[] = {"GLIBC_2.0", "GLIBC_2.34"}; +#else static const char *versions[] = {"GLIBC_2.17", "GLIBC_2.2.5", "GLIBC_2.0", "GLIBC_2.34"}; +#endif size_t i; void *resolved = NULL; diff --git a/tools/linuxfs/preload/net.c b/tools/linuxfs/preload/net.c index f7c9db9406..de3cfdaee7 100644 --- a/tools/linuxfs/preload/net.c +++ b/tools/linuxfs/preload/net.c @@ -111,6 +111,9 @@ typedef int (*accept4_fn)(int, struct sockaddr *, socklen_t *, int); static unsigned guarded_port(void); __attribute__((visibility("hidden"))) int dd_udevmon_stand_in(int fd); +__attribute__((visibility("hidden"))) int dd_udevmon_bind(int fd, const struct sockaddr *addr, socklen_t len, + int (*real_bind)(int, const struct sockaddr *, socklen_t), + int *rc); __attribute__((visibility("hidden"))) int dd_nl_bind(int fd, const struct sockaddr *addr, socklen_t len, int *rc); __attribute__((visibility("hidden"))) int dd_nl_connect(int fd, const struct sockaddr *addr, @@ -121,6 +124,7 @@ int bind(int fd, const struct sockaddr *addr, socklen_t len) { int nl_rc; if (!real) real = (bind_fn)dlsym(RTLD_NEXT, "bind"); if (dd_nl_bind(fd, addr, len, &nl_rc)) return nl_rc; + if (dd_udevmon_bind(fd, addr, len, real, &nl_rc)) return nl_rc; if (dd_udevmon_stand_in(fd)) { if (addr == NULL || len < sizeof(struct sockaddr_nl) || addr->sa_family != AF_NETLINK) { errno = EINVAL; diff --git a/tools/linuxfs/preload/udevmon.c b/tools/linuxfs/preload/udevmon.c index d3af29ef43..43b426ce30 100644 --- a/tools/linuxfs/preload/udevmon.c +++ b/tools/linuxfs/preload/udevmon.c @@ -14,6 +14,7 @@ #include #include #include +#include #include struct stand_in { @@ -40,6 +41,19 @@ static ino_t socket_inode(int fd) { return fstat(fd, &st) == 0 ? st.st_ino : 0; } +static struct stand_in *available_stand_in(void) { + for (size_t i = 0; i < sizeof(stand_ins) / sizeof(stand_ins[0]); i++) { + struct stand_in *entry = &stand_ins[i]; + if (entry->fd == -1) return entry; + if (entry->inode != socket_inode(entry->fd)) { + close(entry->peer); + entry->fd = -1; + return entry; + } + } + return NULL; +} + static int is_stand_in(int fd) { int found = 0; if (fd < 0) @@ -86,14 +100,11 @@ static int make_stand_in(int type) { } fcntl(sv[1], F_SETFD, FD_CLOEXEC); pthread_mutex_lock(&lock); - for (size_t i = 0; i < sizeof(stand_ins) / sizeof(stand_ins[0]); i++) { - if (stand_ins[i].fd == -1) { - stand_ins[i].fd = sv[0]; - stand_ins[i].peer = sv[1]; - stand_ins[i].inode = socket_inode(sv[0]); - pthread_mutex_unlock(&lock); - return sv[0]; - } + struct stand_in *entry = available_stand_in(); + if (entry != NULL) { + *entry = (struct stand_in){.fd = sv[0], .peer = sv[1], .inode = socket_inode(sv[0])}; + pthread_mutex_unlock(&lock); + return sv[0]; } pthread_mutex_unlock(&lock); close(sv[0]); @@ -146,6 +157,58 @@ __attribute__((visibility("hidden"))) int dd_udevmon_stand_in(int fd) { return is_stand_in(fd); } +static int subscribed(int fd) { +#ifdef UDEVMON_TEST + if (getenv("DD_UDEVMON_REFUSE") != NULL) return 0; +#endif + struct sockaddr_nl nl; + socklen_t len = sizeof(nl); + memset(&nl, 0, sizeof(nl)); + return getsockname(fd, (struct sockaddr *)&nl, &len) == 0 && nl.nl_groups != 0; +} + +/* Android lets an app open a uevent socket but not join its multicast groups, and libudev joins none + when no udev daemon runs, so a monitor bound there hears nothing. Such a socket is replaced, under + the same descriptor, by a stand-in. */ +__attribute__((visibility("hidden"))) int dd_udevmon_bind(int fd, const struct sockaddr *addr, socklen_t len, + int (*real_bind)(int, const struct sockaddr *, socklen_t), + int *rc) { + int protocol = -1; + socklen_t protocol_len = sizeof(protocol); + if (addr == NULL || len < sizeof(struct sockaddr_nl) || addr->sa_family != AF_NETLINK) return 0; + if (is_stand_in(fd) || is_wine_process()) return 0; + if (getsockopt(fd, SOL_SOCKET, SO_PROTOCOL, &protocol, &protocol_len) != 0 || protocol != NETLINK_KOBJECT_UEVENT) + return 0; + *rc = real_bind(fd, addr, len); + int refused = errno; + if (subscribed(fd)) { + errno = refused; + return 1; + } + int status = fcntl(fd, F_GETFL); + int descriptor = fcntl(fd, F_GETFD); + int sv[2]; + if (status < 0 || descriptor < 0 || socketpair(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0, sv) != 0) { + errno = refused; + return 1; + } + pthread_mutex_lock(&lock); + struct stand_in *entry = available_stand_in(); + if (entry == NULL || dup3(sv[0], fd, (descriptor & FD_CLOEXEC) ? O_CLOEXEC : 0) < 0) { + pthread_mutex_unlock(&lock); + close(sv[0]); + close(sv[1]); + errno = refused; + return 1; + } + close(sv[0]); + if (status & O_NONBLOCK) fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK); + *entry = (struct stand_in){.fd = fd, .peer = sv[1], .inode = socket_inode(fd)}; + pthread_mutex_unlock(&lock); + *rc = 0; + return 1; +} + int getsockname(int fd, struct sockaddr *addr, socklen_t *len) { static int (*real_getsockname)(int, struct sockaddr *, socklen_t *); struct sockaddr_nl nl; diff --git a/tools/linuxfs/preload/zram.c b/tools/linuxfs/preload/zram.c index c732ee7e34..2efbcc1ecd 100644 --- a/tools/linuxfs/preload/zram.c +++ b/tools/linuxfs/preload/zram.c @@ -1,8 +1,9 @@ #define _GNU_SOURCE -#include +#pragma GCC optimize("no-stack-protector", "no-tree-loop-distribute-patterns") #include #include #include +#include #include #include #include @@ -10,6 +11,9 @@ #include #include #include +#if defined(__i386__) +#include +#endif #include @@ -31,14 +35,157 @@ #define ZR_INLINE_CHUNKS 512UL #define ZR_FAILED (~0UL) #define ZR_FUTEX_WAIT 0 -#define ZR_FUTEX_WAKE 1 #define ZR_PATH (sizeof(ZR_CTL) + sizeof(".hold.") + 20) +#define ZR_STACK (128UL << 10) +#define ZR_THREAD (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM | \ + CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID) +#define ZR_TEXT(x) #x +#define ZR_NR(x) ZR_TEXT(x) +#define ZR_CALL(n, a, b, c, d, e, f, ...) \ + zr_call((long)(n), (long)(a), (long)(b), (long)(c), (long)(d), (long)(e), (long)(f)) +#define zr_sys(...) ZR_CALL(__VA_ARGS__, 0, 0, 0, 0, 0, 0, 0) + +#if defined(__aarch64__) +#define ZR_MMAP SYS_mmap +__asm__(".pushsection .text\n" + ".p2align 2\n" + ".hidden zr_call\n" + ".type zr_call, %function\n" + "zr_call:\n" + " mov x8, x0\n" + " mov x0, x1\n" + " mov x1, x2\n" + " mov x2, x3\n" + " mov x3, x4\n" + " mov x4, x5\n" + " mov x5, x6\n" + " svc #0\n" + " ret\n" + ".size zr_call, . - zr_call\n" + ".hidden zr_clone\n" + ".type zr_clone, %function\n" + "zr_clone:\n" + " mov x5, x2\n" + " mov x2, x3\n" + " mov x3, x4\n" + " mov x4, x5\n" + " mov x8, #" ZR_NR(SYS_clone) "\n" + " svc #0\n" + " cbnz x0, 1f\n" + " mov x29, xzr\n" + " mov x30, xzr\n" + " bl zr_thread\n" + " mov x0, xzr\n" + " mov x8, #" ZR_NR(SYS_exit) "\n" + " svc #0\n" + " brk #0\n" + "1:\n" + " ret\n" + ".size zr_clone, . - zr_clone\n" + ".popsection\n"); +#elif defined(__x86_64__) +#define ZR_MMAP SYS_mmap +__asm__(".pushsection .text\n" + ".p2align 4\n" + ".hidden zr_call\n" + ".type zr_call, @function\n" + "zr_call:\n" + " mov %rdi, %rax\n" + " mov %rsi, %rdi\n" + " mov %rdx, %rsi\n" + " mov %rcx, %rdx\n" + " mov %r8, %r10\n" + " mov %r9, %r8\n" + " mov 8(%rsp), %r9\n" + " syscall\n" + " ret\n" + ".size zr_call, . - zr_call\n" + ".hidden zr_clone\n" + ".type zr_clone, @function\n" + "zr_clone:\n" + " mov %rdx, %r10\n" + " mov %rcx, %rdx\n" + " mov $" ZR_NR(SYS_clone) ", %eax\n" + " syscall\n" + " test %rax, %rax\n" + " jnz 1f\n" + " xor %ebp, %ebp\n" + " call zr_thread\n" + " xor %edi, %edi\n" + " mov $" ZR_NR(SYS_exit) ", %eax\n" + " syscall\n" + " hlt\n" + "1:\n" + " ret\n" + ".size zr_clone, . - zr_clone\n" + ".popsection\n"); +#elif defined(__i386__) +#define ZR_MMAP SYS_mmap2 +__asm__(".pushsection .text\n" + ".p2align 4\n" + ".hidden zr_call\n" + ".type zr_call, @function\n" + "zr_call:\n" + " push %ebp\n" + " push %edi\n" + " push %esi\n" + " push %ebx\n" + " mov 20(%esp), %eax\n" + " mov 24(%esp), %ebx\n" + " mov 28(%esp), %ecx\n" + " mov 32(%esp), %edx\n" + " mov 36(%esp), %esi\n" + " mov 40(%esp), %edi\n" + " mov 44(%esp), %ebp\n" + " int $0x80\n" + " pop %ebx\n" + " pop %esi\n" + " pop %edi\n" + " pop %ebp\n" + " ret\n" + ".size zr_call, . - zr_call\n" + ".hidden zr_clone\n" + ".type zr_clone, @function\n" + "zr_clone:\n" + " push %ebx\n" + " push %esi\n" + " push %edi\n" + " mov 16(%esp), %ebx\n" + " mov 20(%esp), %ecx\n" + " mov 24(%esp), %edi\n" + " mov 28(%esp), %edx\n" + " mov 32(%esp), %esi\n" + " mov $" ZR_NR(SYS_clone) ", %eax\n" + " int $0x80\n" + " test %eax, %eax\n" + " jnz 1f\n" + " xor %ebp, %ebp\n" + " call zr_thread\n" + " xor %ebx, %ebx\n" + " mov $" ZR_NR(SYS_exit) ", %eax\n" + " int $0x80\n" + " hlt\n" + "1:\n" + " pop %edi\n" + " pop %esi\n" + " pop %ebx\n" + " ret\n" + ".size zr_clone, . - zr_clone\n" + ".popsection\n"); +#else +#error "zram.c needs a raw system call for this architecture" +#endif + +long zr_call(long n, long a, long b, long c, long d, long e, long f) __attribute__((visibility("hidden"))); +long zr_clone(long flags, char *stack, int *child, int *parent, void *tls) __attribute__((visibility("hidden"))); +void zr_thread(void) __attribute__((visibility("hidden"))); -static long (*zr_sys)(long, ...); static unsigned long zr_page; -static int zr_busy; -static int zr_pending; -static int zr_worker; +static unsigned zr_requests; +static int zr_stack_busy; +static int zr_tid; +static long zr_filters; +static char *zr_stack; static char zr_maps[8192]; static uint64_t zr_entries[ZR_BATCH]; static struct iovec zr_iov[ZR_BATCH]; @@ -55,6 +202,18 @@ static uint16_t zr_gen = 1; static unsigned long zr_cursor; static unsigned long zr_visits; +static int zr_prefix(const char *text, const char *prefix) { + while (*prefix) + if (*text++ != *prefix++) return 0; + return 1; +} + +static char *zr_find(char *text, char c, size_t n) { + for (; n > 0; n--, text++) + if (*text == c) return text; + return NULL; +} + static int zr_open(const char *path) { return (int)zr_sys(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC, 0); } @@ -116,7 +275,7 @@ static int zr_eligible(const char *line, int compress, unsigned long *start, uns while (*p && *p != ' ') p++; while (*p == ' ') p++; } - return *p == 0 || strncmp(p, "[heap]", 6) == 0 || strncmp(p, "[anon:", 6) == 0; + return *p == 0 || zr_prefix(p, "[heap]") || zr_prefix(p, "[anon:"); } static void zr_read_back(int pagemap, unsigned long start, unsigned long end) { @@ -150,7 +309,7 @@ static unsigned long zr_count(int pagemap, unsigned long start, unsigned long en do { if (zr_sys(SYS_lseek, pagemap, (long)(start / zr_page * sizeof(uint64_t)), SEEK_SET) < 0) return ZR_FAILED; got = zr_sys(SYS_read, pagemap, zr_entries, size); - } while (got < 0 && errno == EINTR); + } while (got == -EINTR); if (got != size) return ZR_FAILED; for (long i = 0; i < got / (long)sizeof(uint64_t); i++) if (zr_entries[i] & bit) count++; @@ -170,8 +329,7 @@ static struct zr_slot *zr_slot(unsigned long addr, int create) { } } if (!create) return NULL; - memset(&zr_slots[home], 0, sizeof(zr_slots[home])); - zr_slots[home].key = key; + zr_slots[home] = (struct zr_slot){.key = key}; return &zr_slots[home]; } @@ -241,13 +399,13 @@ static unsigned long zr_walk(int mode, unsigned long want, unsigned long lo, uns size_t have = 0; while (done < want && zr_visits > 0) { long n = zr_sys(SYS_read, maps, zr_maps + have, sizeof(zr_maps) - 1 - have); - if (n < 0 && errno == EINTR) continue; + if (n == -EINTR) continue; if (n <= 0) break; have += (size_t)n; zr_maps[have] = 0; char *line = zr_maps; char *nl; - while (done < want && zr_visits > 0 && (nl = memchr(line, '\n', have - (size_t)(line - zr_maps))) != NULL) { + while (done < want && zr_visits > 0 && (nl = zr_find(line, '\n', have - (size_t)(line - zr_maps))) != NULL) { *nl = 0; unsigned long s, e; if (zr_eligible(line, mode != 0, &s, &e) && e > s) { @@ -258,7 +416,7 @@ static unsigned long zr_walk(int mode, unsigned long want, unsigned long lo, uns line = nl + 1; } have -= (size_t)(line - zr_maps); - memmove(zr_maps, line, have); + for (size_t i = 0; i < have; i++) zr_maps[i] = line[i]; if (have == sizeof(zr_maps) - 1) have = 0; } if (pagemap >= 0) zr_sys(SYS_close, pagemap); @@ -298,15 +456,88 @@ static void zr_request(int worker) { zr_ack((long)(done * (zr_page / 1024)), 1); } -static void *zr_worker_main(void *unused) { - (void)unused; - prctl(PR_SET_NAME, "zr-worker", 0, 0, 0); - for (;;) { - while (!__atomic_exchange_n(&zr_pending, 0, __ATOMIC_SEQ_CST)) - zr_sys(SYS_futex, &zr_pending, ZR_FUTEX_WAIT, 0, NULL, NULL, 0); - zr_request(1); +static void zr_drain(int worker) { + unsigned seen; + do { + seen = __atomic_load_n(&zr_requests, __ATOMIC_ACQUIRE); + zr_request(worker); + } while (!__atomic_compare_exchange_n(&zr_requests, &seen, 0, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)); +} + +void zr_thread(void) { + zr_sys(SYS_prctl, PR_SET_NAME, "zr-worker"); + zr_drain(1); +} + +static void *zr_tls(void *desc) { +#if defined(__aarch64__) + (void)desc; + return __builtin_thread_pointer(); +#elif defined(__x86_64__) + (void)desc; + void *self; + __asm__("mov %%fs:0, %0" : "=r"(self)); + return self; +#else + struct user_desc *entry = desc; + unsigned short selector; + __asm__("mov %%gs, %0" : "=r"(selector)); + entry->entry_number = selector >> 3; + return zr_sys(SYS_get_thread_area, entry) == 0 ? entry : NULL; +#endif +} + +static long zr_field(const char *text, const char *key) { + for (const char *line = text; *line; line++) { + if ((line == text || line[-1] == '\n') && zr_prefix(line, key)) { + long value = 0; + for (const char *k = key; *k; k++) line++; + while (*line == ' ' || *line == '\t') line++; + for (; *line >= '0' && *line <= '9'; line++) value = value * 10 + (*line - '0'); + return value; + } } - return NULL; + return -1; +} + +static int zr_status(long *threads, long *filters) { + int fd = zr_open("/proc/thread-self/status"); + if (fd < 0) return 0; + long have = 0, n; + while (have < (long)sizeof(zr_maps) - 1 && + ((n = zr_sys(SYS_read, fd, zr_maps + have, sizeof(zr_maps) - 1 - (size_t)have)) > 0 || n == -EINTR)) + if (n > 0) have += n; + zr_sys(SYS_close, fd); + zr_maps[have] = 0; + *threads = zr_field(zr_maps, "Threads:"); + *filters = zr_field(zr_maps, "Seccomp_filters:"); + return have > 0; +} + +static int zr_start(void) { + long threads, filters; + if (!zr_status(&threads, &filters) || threads < 2 || filters > zr_filters) return 0; + if (zr_stack == NULL) { + long base = zr_sys(ZR_MMAP, 0, ZR_STACK, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK | MAP_NORESERVE, -1, 0); + if ((unsigned long)base > -4096UL) return 0; + zr_stack = (char *)base; + } + struct { long sec, nsec; } wait = {0, 5000000}; + for (int i = 0; i < 20 && __atomic_load_n(&zr_stack_busy, __ATOMIC_ACQUIRE); i++) + zr_sys(SYS_futex, &zr_stack_busy, ZR_FUTEX_WAIT, 1, &wait, NULL, 0); + if (__atomic_load_n(&zr_stack_busy, __ATOMIC_ACQUIRE)) return 0; + uint64_t desc[4] = {0}; + void *tls = zr_tls(desc); + if (tls == NULL) return 0; + uint64_t all = ~0ULL, previous; + if (zr_sys(SYS_rt_sigprocmask, SIG_SETMASK, &all, &previous, sizeof(all)) != 0) return 0; + __atomic_store_n(&zr_stack_busy, 1, __ATOMIC_RELEASE); + long tid = zr_clone(ZR_THREAD, zr_stack + ZR_STACK, &zr_stack_busy, &zr_tid, tls); + zr_sys(SYS_rt_sigprocmask, SIG_SETMASK, &previous, NULL, sizeof(previous)); + if (tid > 0) return 1; + __atomic_store_n(&zr_stack_busy, 0, __ATOMIC_RELEASE); + return 0; } static void zr_handler(int sig, siginfo_t *info, void *context) { @@ -314,34 +545,23 @@ static void zr_handler(int sig, siginfo_t *info, void *context) { (void)context; if (info == NULL || info->si_code != SI_USER) return; int saved = errno; - __atomic_store_n(&zr_pending, 1, __ATOMIC_SEQ_CST); - if (__atomic_load_n(&zr_worker, __ATOMIC_ACQUIRE)) { - zr_sys(SYS_futex, &zr_pending, ZR_FUTEX_WAKE, 1, NULL, NULL, 0); - } else while (__atomic_load_n(&zr_pending, __ATOMIC_SEQ_CST) - && !__atomic_exchange_n(&zr_busy, 1, __ATOMIC_SEQ_CST)) { - __atomic_store_n(&zr_pending, 0, __ATOMIC_SEQ_CST); - zr_request(0); - __atomic_store_n(&zr_busy, 0, __ATOMIC_SEQ_CST); - } + if (__atomic_fetch_add(&zr_requests, 1, __ATOMIC_ACQ_REL) == 0 && !zr_start()) zr_drain(0); errno = saved; } static void zr_child(void) { - __atomic_store_n(&zr_busy, 0, __ATOMIC_SEQ_CST); - __atomic_store_n(&zr_pending, 0, __ATOMIC_SEQ_CST); - __atomic_store_n(&zr_worker, 0, __ATOMIC_RELEASE); + __atomic_store_n(&zr_requests, 0, __ATOMIC_RELEASE); + __atomic_store_n(&zr_stack_busy, 0, __ATOMIC_RELEASE); } __attribute__((constructor)) static void zr_init(void) { - void *libc = dlopen("libc.so.6", RTLD_LAZY | RTLD_NOLOAD); - if (libc == NULL) return; - zr_sys = (long (*)(long, ...))dlsym(libc, "syscall"); - if (zr_sys == NULL) return; int fd = zr_open(ZR_CTL); if (fd < 0) return; zr_sys(SYS_close, fd); long page = sysconf(_SC_PAGESIZE); zr_page = page > 0 ? (unsigned long)page : 4096UL; + long threads; + if (!zr_status(&threads, &zr_filters)) zr_filters = -1; struct sigaction old; if (sigaction(SIGURG, NULL, &old) != 0) return; if ((old.sa_flags & SA_SIGINFO) || old.sa_handler != SIG_DFL) return; @@ -350,21 +570,5 @@ __attribute__((constructor)) static void zr_init(void) { sa.sa_sigaction = zr_handler; sa.sa_flags = SA_SIGINFO | SA_RESTART; sigemptyset(&sa.sa_mask); - if (sigaction(SIGURG, &sa, NULL) == 0) { - pthread_atfork(NULL, NULL, zr_child); - pthread_attr_t attr; - if (pthread_attr_init(&attr) == 0) { - pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); - pthread_t thread; - sigset_t blocked; - sigset_t previous; - if (sigfillset(&blocked) == 0 && - pthread_sigmask(SIG_SETMASK, &blocked, &previous) == 0) { - if (pthread_create(&thread, &attr, zr_worker_main, NULL) == 0) - __atomic_store_n(&zr_worker, 1, __ATOMIC_RELEASE); - pthread_sigmask(SIG_SETMASK, &previous, NULL); - } - pthread_attr_destroy(&attr); - } - } + if (sigaction(SIGURG, &sa, NULL) == 0) pthread_atfork(NULL, NULL, zr_child); } diff --git a/tools/memory_guard_ab.py b/tools/memory_guard_ab.py index 0bcd81d6d6..9aa2fa21a7 100755 --- a/tools/memory_guard_ab.py +++ b/tools/memory_guard_ab.py @@ -26,30 +26,52 @@ PACKAGE = "com.droiddeck.launcher" SESSION = f"{PACKAGE}/.SessionActivity" HOG_PATH = "/data/local/tmp/dd-memory-hog.sh" HOG_MOUNT = "/dev/dd-memory-hog" +SEED_PATH = "/data/local/tmp/dd-memory-burst.bin" +# oom_score_adj is read without su: under pressure lmkd kills the root manager app, and each su call +# can then open its request screen on top of the game. # Incompressible data in a private tmpfs: zram cannot shrink it and no app owns it, so lmkd keeps # killing by oom_score_adj while it is held. HOG = f"""#!/system/bin/sh -stop_mb=$1; hold=$2 -cleanup() {{ rm -f {HOG_MOUNT}/f*; umount {HOG_MOUNT} 2>/dev/null; }} +stop_mb=$1; hold=$2; mode=$3 +cleanup() {{ kill $(jobs -p) 2>/dev/null; rm -f {HOG_MOUNT}/f*; umount {HOG_MOUNT} 2>/dev/null; }} trap 'cleanup; exit 1' HUP INT TERM mkdir -p {HOG_MOUNT} grep -q ' {HOG_MOUNT} ' /proc/mounts || mount -t tmpfs -o size=16g tmpfs {HOG_MOUNT} -i=0 +i=0; failed=0 +if [ "$mode" = burst ]; then + [ "$(stat -c %s {SEED_PATH} 2>/dev/null)" = 268435456 ] || + {{ head -c 268435456 /dev/urandom > {SEED_PATH}.tmp && mv {SEED_PATH}.tmp {SEED_PATH}; }} || + {{ rm -f {SEED_PATH}.tmp; cleanup; exit 1; }} + cat {SEED_PATH} > /dev/null + avail=$(awk '/MemAvailable/ {{print int($2/1024)}}' /proc/meminfo) + echo "avail=$avail" + take=$((avail - stop_mb)) + [ "$take" -gt 0 ] || {{ echo "nothing to take"; cleanup; exit 2; }} + n=$((take / 256)); rest=$((take % 256)); pids="" + echo "burst_mb=$take start=$(date +%s%N)" + while [ $i -lt $n ]; do cat {SEED_PATH} > {HOG_MOUNT}/f$i & pids="$pids $!"; i=$((i+1)); done + [ "$rest" -gt 0 ] && {{ head -c $((rest * 1048576)) {SEED_PATH} > {HOG_MOUNT}/f$i & pids="$pids $!"; }} + for pid in $pids; do wait "$pid" || failed=1; done + echo "burst_done=$(date +%s%N)" + echo "avail=$(awk '/MemAvailable/ {{print int($2/1024)}}' /proc/meminfo)" + i=512 +fi while [ $i -lt 512 ]; do avail=$(awk '/MemAvailable/ {{print int($2/1024)}}' /proc/meminfo) echo "avail=$avail" [ "$avail" -le "$stop_mb" ] && break - head -c 33554432 /dev/urandom > {HOG_MOUNT}/f$i || break + head -c 33554432 /dev/urandom > {HOG_MOUNT}/f$i || {{ failed=1; break; }} i=$((i+1)) done +[ "$failed" = 0 ] || {{ echo "write failed"; cleanup; exit 1; }} sleep "$hold" cleanup echo released """ # Stops a writer left by an interrupted run before its files go, so the unmount does not fail. The # bracketed patterns keep pkill from matching the shell that runs this line. -HOG_CLEANUP = (f"pkill -f '[d]d-memory-hog.sh'; pkill -f '[h]ead -c 33554432'; sleep 1; rm -f {HOG_MOUNT}/f*; " +HOG_CLEANUP = (f"pkill -f '[d]d-memory-hog.sh'; pkill -f '[h]ead -c 33554432'; pkill -f '[d]d-memory-burst.bin'; sleep 1; rm -f {HOG_MOUNT}/f*; " f"umount {HOG_MOUNT} 2>/dev/null; true") def focused_display(input_dump: str) -> int | None: @@ -58,7 +80,7 @@ def focused_display(input_dump: str) -> int | None: def activity_count(activities_dump: str, activity: str) -> int: - return len(re.findall(r"Hist\s+#\d+: ActivityRecord\{\S+ u\d+ " + re.escape(activity) + r" ", activities_dump)) + return len(re.findall(r"Hist\s+#\d+: ActivityRecord\{\S+ u\d+ " + re.escape(activity) + r"[ }]", activities_dump)) def guard_count(activities_dump: str) -> int: @@ -85,7 +107,8 @@ def panel_windows(windows_dump: str, display: int) -> int: def bottom_home(activities_dump: str, session_display: int) -> tuple[int, str] | None: - display = None + """The visible home on another display, else the visible app on top of it.""" + display, top = None, None for line in activities_dump.splitlines(): section = re.match(r"Display #(\d+) \(activities", line) if section: @@ -96,7 +119,10 @@ def bottom_home(activities_dump: str, session_display: int) -> tuple[int, str] | home = re.search(r"type=home A=\d+:(\S+) .*visible=true", line) if home: return display, home.group(1) - return None + app = re.search(r"type=standard A=\d+:([\w.]+) .*visible=true", line) + if app and top is None and not app.group(1).startswith(PACKAGE): + top = display, app.group(1) + return top def logical_size(displays_dump: str, display: int) -> tuple[int, int] | None: @@ -151,8 +177,11 @@ class Device: return self.sh(f"su -c {shlex.quote(command)}", timeout=timeout) def ctl(self, *args: str, timeout: int = 300) -> subprocess.CompletedProcess[str]: - return subprocess.run([str(TOOLS / "droiddeckctl"), "--adb", self.adb, "--serial", self.serial, *args], - capture_output=True, text=True, timeout=timeout) + command = [str(TOOLS / "droiddeckctl"), "--adb", self.adb, "--serial", self.serial, *args] + try: + return subprocess.run(command, capture_output=True, text=True, timeout=timeout) + except subprocess.TimeoutExpired: + return subprocess.CompletedProcess(command, -1, "", f"timed out after {timeout} s") def phase(self) -> str | None: match = re.search(r'"phase":\s*"(\w+)"', self.ctl("state").stdout) @@ -208,7 +237,8 @@ class Bench: def prepare(self, apk: str | None): self.d.sh("input keyevent KEYCODE_WAKEUP") - self.d.ctl("stop") + if self.d.ctl("stop", timeout=120).returncode != 0: + self.d.sh(f"am force-stop {PACKAGE}") if apk: env = dict(os.environ, ADB_SERIAL=self.d.serial) subprocess.run([str(TOOLS / "deploy_local.sh"), apk], env=env, check=True, capture_output=True) @@ -234,7 +264,7 @@ class Bench: "guards": guard_count(activities), "sessions": session_count(activities), "panel": panel_windows(self.d.sh("dumpsys window windows"), display), - "adj": int(self.d.su(f"cat /proc/{pid}/oom_score_adj").strip() or -9999), + "adj": int(self.d.sh(f"cat /proc/{pid}/oom_score_adj").strip() or -9999), "pid": pid, } @@ -251,7 +281,8 @@ class Bench: before = self.snapshot() _, home = self.bottom() self.d.run("logcat", "-b", "events", "-c") - samples = self.d.su(f"kill -9 $(pidof {home}); for i in $(seq 50); do cat /proc/{before['pid']}/oom_score_adj" + self.d.su(f"kill -9 $(pidof {home})") + samples = self.d.sh(f"for i in $(seq 50); do cat /proc/{before['pid']}/oom_score_adj" " 2>/dev/null || echo DEAD; sleep 0.1; done").split() events = self.d.run("logcat", "-b", "events", "-d") (self.out / f"{self.label}-{state}-events.txt").write_text(events) @@ -297,7 +328,7 @@ class Bench: self.probe("using_bottom_now") self.game_front() - def pressure(self, run: str, stop_mb: int, hold: int): + def pressure(self, run: str, stop_mb: int, hold: int, burst: bool = False) -> bool: with tempfile.NamedTemporaryFile("w", suffix=".sh", delete=False) as script: script.write(HOG) try: @@ -305,16 +336,18 @@ class Bench: finally: os.unlink(script.name) self.d.sh(f"chmod 755 {HOG_PATH}") - self.game_front() self.close_panel() + self.game_front() + self.tap(self.session_display, (0.36, 0.11)) + time.sleep(2) before = self.snapshot() self.d.run("logcat", "-b", "events", "-c") - hog = subprocess.Popen([self.d.adb, "-s", self.d.serial, "shell", f"su -c '{HOG_PATH} {int(stop_mb)} {int(hold)}'"], + hog = subprocess.Popen([self.d.adb, "-s", self.d.serial, "shell", f"su -c '{HOG_PATH} {int(stop_mb)} {int(hold)} {'burst' if burst else 'fill'}'"], stdout=subprocess.PIPE, text=True) samples = [] try: while hog.poll() is None: - samples.append(self.d.su(f"cat /proc/{before['pid']}/oom_score_adj 2>/dev/null || echo DEAD").strip()) + samples.append(self.d.sh(f"cat /proc/{before['pid']}/oom_score_adj 2>/dev/null || echo DEAD").strip()) time.sleep(0.5) output = hog.stdout.read() if hog.stdout else "" finally: @@ -324,12 +357,19 @@ class Bench: time.sleep(3) events = self.d.run("logcat", "-b", "events", "-d") (self.out / f"{self.label}-{run}-events.txt").write_text(events) + workload_ok = hog.returncode == 0 and "released" in output.splitlines() + if not workload_ok: + print(f"memory-guard-ab: {run}: the memory hog failed (exit {hog.returncode}): " + f"{output.strip().splitlines()[-1] if output.strip() else 'no output'}", file=sys.stderr) available = [int(value) for value in re.findall(r"avail=(\d+)", output)] + took = re.search(r"start=(\d+).*?burst_done=(\d+)", output, re.S) self.write("pressure", { - "run": run, "stop_mb": stop_mb, "hold_s": hold, **{k: v for k, v in before.items() if k != "pid"}, + "run": run, "workload_ok": workload_ok, "mode": "burst" if burst else "fill", "stop_mb": stop_mb, "hold_s": hold, + "burst_ms": (int(took.group(2)) - int(took.group(1))) // 1_000_000 if took else None, **{k: v for k, v in before.items() if k != "pid"}, "min_available_mb": min(available) if available else None, "adj_max": max_adj(samples), "droiddeck_alive": self.d.pid() == before["pid"], "phase": self.d.phase(), **summarize_events(events), }) + return workload_ok def fraction_pair(text: str) -> tuple[float, float]: @@ -355,6 +395,8 @@ def main() -> int: pressure.add_argument("--stop-mb", type=int, default=650, help="stop filling at this MemAvailable") pressure.add_argument("--hold", type=int, default=30) pressure.add_argument("--runs", type=int, default=1) + pressure.add_argument("--burst", action="store_true", + help="take everything above --stop-mb at once instead of filling 32 MiB at a time") summarize = commands.add_parser("summarize", help="summarize a saved events log") summarize.add_argument("events", type=Path) args = parser.parse_args() @@ -376,9 +418,19 @@ def main() -> int: bench.prepare(args.apk) bench.states() else: + completed = 0 for run in range(args.runs): - bench.prepare(args.apk if run == 0 else None) - bench.pressure(f"stop{args.stop_mb}-{run + 1}", args.stop_mb, args.hold) + try: + bench.prepare(args.apk if run == 0 else None) + except RuntimeError as exc: + print(f"memory-guard-ab: run {run + 1} skipped: {exc}", file=sys.stderr) + continue + if bench.pressure(f"{'burst' if args.burst else 'stop'}{args.stop_mb}-{run + 1}", args.stop_mb, + args.hold, args.burst): + completed += 1 + if completed == 0: + print("memory-guard-ab: no pressure run completed", file=sys.stderr) + return 1 except RuntimeError as exc: print(f"memory-guard-ab: {exc}", file=sys.stderr) return 1 diff --git a/tools/packs/build.sh b/tools/packs/build.sh index 2b34c7fc6f..062fbd5270 100755 --- a/tools/packs/build.sh +++ b/tools/packs/build.sh @@ -11,6 +11,8 @@ linuxfs="$repo/app/src/main/assets/linuxfs/usr/local/lib" source "$here/tracking/release.env" # shellcheck source=butler/release.env source "$here/butler/release.env" +# shellcheck source=zstd/release.env +source "$here/zstd/release.env" work=$(mktemp -d) trap 'rm -rf "$work"' EXIT @@ -21,6 +23,22 @@ fetch() { bash "$here/fetch-verified.sh" "$@" } +zstd_version() { "$1" -V 2>/dev/null | sed -n 's/.* v\([0-9][0-9.]*\),.*/\1/p'; } +zstd=$(command -v zstd || true) +if [ -z "$zstd" ] || [ "$(zstd_version "$zstd")" != "$ZSTD_VERSION" ]; then + zstd="${DROIDDECK_PACK_CACHE:-"$HOME/.cache/droiddeck-pack-inputs"}/zstd-$ZSTD_VERSION/zstd" + if [ ! -x "$zstd" ] || [ "$(zstd_version "$zstd")" != "$ZSTD_VERSION" ]; then + fetch "https://github.com/facebook/zstd/releases/download/v$ZSTD_VERSION/zstd-$ZSTD_VERSION.tar.gz" \ + "$ZSTD_SHA256" "$work/zstd.tar.gz" + tar -xzf "$work/zstd.tar.gz" -C "$work" + make -s -C "$work/zstd-$ZSTD_VERSION" -j"$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 2)" zstd-release >/dev/null + mkdir -p "$(dirname "$zstd")" + install -m755 "$work/zstd-$ZSTD_VERSION/programs/zstd" "$zstd.part.$$" + mv -f "$zstd.part.$$" "$zstd" + fi +fi +[ "$(zstd_version "$zstd")" = "$ZSTD_VERSION" ] || { echo "packs need zstd $ZSTD_VERSION, $zstd is not it" >&2; exit 1; } + pack() { local name=$1 src=$2 shift 2 @@ -47,7 +65,7 @@ with tarfile.open(dest, "w", format=tarfile.USTAR_FORMAT) as tar: with open(path, "rb") as f: tar.addfile(info, f) EOF - zstd -q -19 -f "$work/$name.tar" -o "$out/$name.tar.zst" + "$zstd" -q -19 -f "$work/$name.tar" -o "$out/$name.tar.zst" echo "$name $(sha256 "$out/$name.tar.zst") $(wc -c < "$out/$name.tar.zst" | tr -d ' ')" } @@ -80,6 +98,7 @@ pack powervr "$repo/app/src/main/assets/hybris" runtime.tzst version.txt [ ! -f "$linuxfs/droiddeck-ubisoft/droiddeck-upc.exe" ] || pack ubisoft "$linuxfs/droiddeck-ubisoft" droiddeck-upc.exe [ ! -f "$linuxfs/droiddeck-rockstar/Launcher64.exe" ] || pack rockstar "$linuxfs/droiddeck-rockstar" Launcher32.exe Launcher64.exe [ ! -f "$linuxfs/droiddeck-dirt/ws2_32.dll" ] || pack dirt "$linuxfs/droiddeck-dirt" ws2_32.dll +[ ! -f "$linuxfs/droiddeck-epic/EpicGamesLauncher.exe" ] || pack epic "$linuxfs/droiddeck-epic" EpicGamesLauncher.exe mkdir "$work/butler" fetch "https://broth.itch.zone/butler/linux-arm64/${BUTLER_VERSION}/archive/default" \ diff --git a/tools/packs/zstd/release.env b/tools/packs/zstd/release.env new file mode 100644 index 0000000000..4f69b092bf --- /dev/null +++ b/tools/packs/zstd/release.env @@ -0,0 +1,2 @@ +ZSTD_VERSION=1.5.5 +ZSTD_SHA256=9c4396cc829cfae319a6e2615202e82aad41372073482fce286fac78646d3ee4 diff --git a/tools/release/runtime_inputs.py b/tools/release/runtime_inputs.py index 4b02d29c26..89488e1ba5 100644 --- a/tools/release/runtime_inputs.py +++ b/tools/release/runtime_inputs.py @@ -15,18 +15,18 @@ MANIFEST = Path('app/build/runtime-inputs.json') PACKS = Path('app/build/packs') PACKED = {'assets/linuxfs/usr/local/lib/droiddeck-xbox/': 'xbox', 'assets/linuxfs/usr/local/lib/droiddeck-comet/': 'comet', 'assets/linuxfs/usr/local/lib/droiddeck-ubisoft/': 'ubisoft', 'assets/linuxfs/usr/local/lib/droiddeck-rockstar/': 'rockstar', - 'assets/linuxfs/usr/local/lib/droiddeck-dirt/': 'dirt', + 'assets/linuxfs/usr/local/lib/droiddeck-dirt/': 'dirt', 'assets/linuxfs/usr/local/lib/droiddeck-epic/': 'epic', 'assets/directaudio/': 'directaudio', 'assets/hybris/': 'powervr'} # DrWeb flags proot itself as Tool.Linux.Proot; the app runs the pack's copy through Android's linker. PACKED_FILES = {'lib/arm64-v8a/libproot.so': ('proot', 'libproot.so')} # The loader is execve'd, which targetSdk 29+ allows only from the APK's native library directory. PROOT_LOADER = {'lib/arm64-v8a/libproot-loader.so': 'libproot-loader.so'} PACKED_LIBRARIES = ['lib/arm64-v8a/libopencv_java4.so', 'lib/arm64-v8a/libmediapipe_tasks_jni.so'] -PACK_NAMES = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt'] +PACK_NAMES = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt', 'epic'] SOURCE_PATHS = ['app/build.gradle', 'app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/assets/pulseaudio.tzst', 'tools/linuxfs', 'tools/proot', 'tools/aaudio-sink', 'tools/directaudio', 'tools/packs', 'tools/gamescope/release.env', 'tools/droiddeck-esync/release.env', - 'tools/mangoapp', 'tools/msitools', 'tools/pipewire', 'tools/comet', 'tools/xbox', 'tools/dirt-ws2', 'tools/ubisoft-launcher', 'tools/rockstar-launcher', 'tools/components', 'tools/ci', 'tools/build_local.sh', + 'tools/mangoapp', 'tools/msitools', 'tools/pipewire', 'tools/comet', 'tools/xbox', 'tools/dirt-ws2', 'tools/ubisoft-launcher', 'tools/rockstar-launcher', 'tools/epic-launcher', 'tools/components', 'tools/ci', 'tools/build_local.sh', 'tools/powervr', 'tools/hybris', 'tools/dxvk', 'tools/vulkan-wsi', 'tools/release/runtime_inputs.py', 'app/src/main/assets/desktop-removal', 'tools/quest', 'tools/vr/src', 'tools/vr/driver_droiddeck', 'tools/vr/layer', 'tools/vr/build.sh', @@ -49,12 +49,15 @@ def digest(path): def sources(root): - files = [] + files, builds = [], set() for name in SOURCE_PATHS: path = root / name files.extend(path.rglob('*') if path.is_dir() else [path]) + if path.is_dir(): + builds.update(manifest.parent / 'target' for manifest in path.rglob('Cargo.toml')) return {path.relative_to(root).as_posix(): digest(path) for path in sorted(set(files)) - if path.is_file() and '__pycache__' not in path.parts and path.suffix != '.pyc'} + if path.is_file() and '__pycache__' not in path.parts and path.suffix != '.pyc' + and not any(build in path.parents for build in builds)} def outputs(root): @@ -227,7 +230,7 @@ def windows_binaries(package): def check_apk(apk, root=ROOT): data = verify(root) packs = {name: pack_digests(root, name) for name in PACK_NAMES - if name not in ('ubisoft', 'rockstar', 'dirt') or (root / PACKS / (name + '.tar.zst')).is_file()} + if name not in ('ubisoft', 'rockstar', 'dirt', 'epic') or (root / PACKS / (name + '.tar.zst')).is_file()} for name, rel in PROOT_LOADER.items(): if packs['proot'].get(rel) != data['outputs'][name]['sha256']: raise ValueError('Add-on pack proot is missing or has a stale ' + rel) diff --git a/tools/tests/test_battlenet.py b/tools/tests/test_battlenet.py index ece44f60d6..52ba9e8d46 100644 --- a/tools/tests/test_battlenet.py +++ b/tools/tests/test_battlenet.py @@ -6,7 +6,6 @@ import re import runpy import shutil import tempfile -import threading import time import unittest from unittest import mock @@ -93,8 +92,6 @@ class IdTest(unittest.TestCase): self.assertEqual(int(BNET["APP_ID"]), zlib.crc32(b'"droiddeck-battlenet"Battle.net') | 0x80000000) found = re.search(r"const val APP_ID = (\d+)L", KOTLIN.read_text()) self.assertEqual(found.group(1), BNET["APP_ID"]) - for name in ("FEX_REQUEST", "FEX_RESULT"): - self.assertIn('const val %s = "%s"' % (name, BNET[name]), KOTLIN.read_text()) class ProtonRunOptionsTest(Temp): @@ -761,36 +758,6 @@ class TidyTest(unittest.TestCase): self.assertEqual(self.stopped, []) -class FexRequestTest(Temp): - def answer(self, text, delay=0.2): - def respond(): - request = self.tmp / BNET["FEX_REQUEST"] - deadline = time.monotonic() + 5 - while not request.exists() and time.monotonic() < deadline: - time.sleep(0.02) - self.requested = request.read_text() - request.unlink() - time.sleep(delay) - (self.tmp / (BNET["FEX_RESULT"] + ".tmp")).write_text(text + "\n") - os.replace(self.tmp / (BNET["FEX_RESULT"] + ".tmp"), self.tmp / BNET["FEX_RESULT"]) - thread = threading.Thread(target=respond) - thread.start() - self.addCleanup(thread.join) - - def test_the_apps_answer_comes_back(self): - (self.tmp / BNET["FEX_RESULT"]).write_text("ok an-old-answer\n") - self.answer("ok FEXCore-2610-d2rfix28-linux.wcp") - self.assertEqual(BNET["ask_fex"](str(self.tmp), wait=5), "ok FEXCore-2610-d2rfix28-linux.wcp") - self.assertEqual(self.requested, "appid=%s\n" % BNET["APP_ID"]) - self.assertFalse((self.tmp / BNET["FEX_RESULT"]).exists()) - - def test_no_answer_or_no_session_starts_without_one(self): - with mock.patch.dict(BNET, {"say": lambda message: None}): - self.assertIsNone(BNET["ask_fex"](str(self.tmp), wait=0.3)) - self.assertIsNone(BNET["ask_fex"](None)) - self.assertIsNone(BNET["ask_fex"](str(self.tmp / "gone"))) - - class OpenTest(Temp): def setUp(self): super().setUp() @@ -799,7 +766,6 @@ class OpenTest(Temp): self.alive = [] self.menu = self.tmp / "droiddeck-battlenet.desktop" patcher = mock.patch.dict(BNET, { - "ask_fex": lambda launch_dir, wait=0: "ok fex.wcp", "say": lambda message: None, "notify": lambda *a, **k: self.calls.append(("notify", a[0])), "wine_processes": lambda pfx, proc="/proc": list(self.alive), "stop": lambda processes, wait=0: self.calls.append(("stop", [pid for pid, _ in processes])) or self.alive.clear(), @@ -988,7 +954,6 @@ class Harness(Temp): self.states = [] self.last = [] patcher = mock.patch.dict(BNET, { - "ask_fex": lambda launch_dir, wait=0: self.calls.append(("fex",)) or "ok fex.wcp", "say": lambda message: None, "notify": lambda *a, **k: self.calls.append(("notify", a[0])), "wine_processes": self.processes, "stop": lambda processes, wait=0: self.calls.append(("stop", sorted(pid for pid, _ in processes))), @@ -1019,7 +984,7 @@ class LaunchTest(Harness): self.states = [[], [], up, up + [(40, self.GAME)], up, up] self.assertEqual(BNET["launch"](self.root, "Fen"), 0) self.assertEqual(self.calls, [ - ("fex",), ("start", "Battle.net Launcher.exe", None), + ("start", "Battle.net Launcher.exe", None), ("spawn", "Battle.net.exe", "run", ["--exec=launch Fen"]), ("stop", [10, 11, 12, 13, 14, 30]), ]) @@ -1034,7 +999,7 @@ class LaunchTest(Harness): with mock.patch.dict(BNET, {"GAME_SETTLE": 0}): self.assertEqual(BNET["launch"](self.root, "Fen"), 0) self.assertEqual(self.calls, [ - ("fex",), ("start", "Battle.net Launcher.exe", None), + ("start", "Battle.net Launcher.exe", None), ("spawn", "Battle.net.exe", "run", ["--exec=launch Fen"]), ("stop", [10, 11, 12, 13, 14, 30]), ("stop", [50]), diff --git a/tools/tests/test_cdp_guard.py b/tools/tests/test_cdp_guard.py index 9dc5891f36..0fc023e872 100644 --- a/tools/tests/test_cdp_guard.py +++ b/tools/tests/test_cdp_guard.py @@ -19,7 +19,8 @@ class CdpGuardTest(unittest.TestCase): subprocess.run(["cc", "-shared", "-fPIC", "-O2", str(SOURCE), str(SOURCE.parent / "binfmt.c"), str(SOURCE.parent / "webhelper.c"), str(Path(__file__).with_name("netlink_stubs.c")), "-x", "c", "-", "-ldl", "-o", str(cls.library)], - input=b"int dd_udevmon_stand_in(int fd) { return 0; }", check=True, capture_output=True) + input=b"int dd_udevmon_stand_in(int fd) { return 0; }\n" + b"int dd_udevmon_bind(int fd, const void *addr, unsigned len, void *real, int *rc) { return 0; }", check=True, capture_output=True) @classmethod def tearDownClass(cls): diff --git a/tools/tests/test_desktop_display_buffers.py b/tools/tests/test_desktop_display_buffers.py new file mode 100644 index 0000000000..0c3defcb83 --- /dev/null +++ b/tools/tests/test_desktop_display_buffers.py @@ -0,0 +1,29 @@ +from pathlib import Path +import re +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] +DESKTOP = ROOT / "tools/linuxfs/desktop/droiddeck-desktop" +SOURCE = ROOT / "app/src/main/cpp/waylandcomp/src/display_buffers.c" + + +class DesktopDisplayBuffersTest(unittest.TestCase): + def test_clearing_the_runtime_directory_keeps_what_the_compositor_serves(self): + socket = re.search(r'#define DISPLAY_BUFFERS_SOCKET "([^"]+)"', SOURCE.read_text()).group(1) + lines = [line for line in DESKTOP.read_text().splitlines() if line.startswith('find "$XDG_RUNTIME_DIR"')] + self.assertEqual(len(lines), 1) + with tempfile.TemporaryDirectory() as directory: + runtime = Path(directory) / "runtime" + (runtime / "dbus-1").mkdir(parents=True) + kept = ["wayland-0", "wayland-0.lock", "keymap.xkb", socket] + for name in kept + ["wayland-1", "pipewire-0", "dbus-1/session"]: + (runtime / name).write_text("") + subprocess.run(["bash", "-c", lines[0]], env={"XDG_RUNTIME_DIR": str(runtime), "PATH": "/usr/bin:/bin"}, + check=True, timeout=20) + self.assertEqual(sorted(path.name for path in runtime.iterdir()), sorted(kept)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_effects_source_resolution.py b/tools/tests/test_effects_source_resolution.py index aae6052cec..cd63c69d64 100644 --- a/tools/tests/test_effects_source_resolution.py +++ b/tools/tests/test_effects_source_resolution.py @@ -26,7 +26,7 @@ class EffectsSourceResolutionTest(unittest.TestCase): header = (REPO / 'app/src/main/cpp/waylandcomp/src/vk_present.h').read_text() effects = (REPO / 'app/src/main/cpp/waylandcomp/src/effects_chain.c').read_text() functions = '\n'.join(function(source, signature) for signature in ( - 'static void release_external_client_image(', 'static void release_external_client_draws(', + 'static int foreign_image(', 'static void release_external_client_image(', 'static void release_external_client_draws(', 'static int map_draw(', 'static int draw_to_blit(', 'static int draw_to_scene_blit(', 'static int effects_source_draw(', 'static void effects_source_note(', @@ -113,7 +113,7 @@ TYPES = r''' #include #include #include -typedef int VkImage, VkDeviceMemory, VkFormat, VkCommandBuffer, VkResult, VkFilter; +typedef int VkImage, VkDeviceMemory, VkFormat, VkCommandBuffer, VkResult, VkFilter, VkBuffer; typedef int VkImageLayout, VkPipelineStageFlags, VkImageUsageFlags; typedef uint64_t VkDeviceSize; typedef struct { unsigned width, height; } VkExtent2D; @@ -126,6 +126,13 @@ typedef struct { VkImageSubresourceLayers dstSubresource; VkOffset3D dstOffsets[2]; } VkImageBlit; +typedef struct { + VkDeviceSize bufferOffset; + unsigned bufferRowLength, bufferImageHeight; + VkImageSubresourceLayers imageSubresource; + VkOffset3D imageOffset; + struct { unsigned width, height, depth; } imageExtent; +} VkBufferImageCopy; typedef struct { int sType, flags; } VkCommandBufferBeginInfo; typedef struct { int sType, oldLayout, newLayout, srcQueueFamilyIndex, dstQueueFamilyIndex; @@ -161,6 +168,8 @@ typedef struct AHardwareBuffer AHardwareBuffer; STUBS = r''' +static void stage_linear_dmabufs(VkCommandBuffer cmd, const struct vkp_draw *draws, int count) { (void)cmd; (void)draws; (void)count; } +static int vkp_linear_dmabuf_foreign_image(int dmabuf, int staged) { return dmabuf && !staged; } static void quarantine_pending_work(VkResult result, const char *where) { (void)result; (void)where; } static int noop(int handle, ...) { return VK_SUCCESS; } static VkImageMemoryBarrier recorded_barriers[64]; @@ -194,7 +203,7 @@ static struct { float kx, ky, off_x, off_y; int rx, ry, rw, rh; } g_map; static struct { VkImage img; int w, h; } g_scene; struct vkp_img_slot { VkImage img; int w, h; }; static struct vkp_img_slot g_hdrscene, g_fgscene; -static struct { int active, rw, rh; VkImage result; } g_pass; +static struct { int active, rw, rh, ngen; VkImage result; VkImage gens[VKP_FG_MAX_GENERATIONS]; } g_pass; static struct { int64_t present_ns, present_max_ns; unsigned presents; } g_perf; static int effects_active = 1, framegen, cardboard; struct fx_settings { int scaling, cas_on, cas_pct; }; @@ -359,7 +368,7 @@ static void run_path(int offscreen, const struct vkp_draw *draw, int n, const st assert(n > 0 && n <= 4); memcpy(before, draw, n * sizeof(*draw)); int rw = 0, rh = 0; - assert((offscreen ? pass_begin_impl(1920, 1080, draw, n, hdr, &rw, &rh) + assert((offscreen ? pass_begin_impl(1920, 1080, draw, n, hdr, 0, &rw, &rh) : render_impl(1920, 1080, draw, n, hdr, NULL)) == 0); assert(memcmp(draw, before, n * sizeof(*draw)) == 0); if (offscreen) assert(rw == (fail_effects ? effects_w : (int)g_extent.width) && @@ -384,7 +393,7 @@ static void check_path(int offscreen) { run_path(offscreen, &draw, 1, NULL); check_input(1280, 720); reset(); draw = fullscreen(); draw.dw = 1280; draw.dh = 720; int rw, rh; - assert((offscreen ? pass_begin_impl(1280, 720, &draw, 1, NULL, &rw, &rh) + assert((offscreen ? pass_begin_impl(1280, 720, &draw, 1, NULL, 0, &rw, &rh) : render_impl(1280, 720, &draw, 1, NULL, NULL)) == 0); check_input(1280, 720); } diff --git a/tools/tests/test_gamescope_limiter_cadence.py b/tools/tests/test_gamescope_limiter_cadence.py new file mode 100644 index 0000000000..79a4319adb --- /dev/null +++ b/tools/tests/test_gamescope_limiter_cadence.py @@ -0,0 +1,118 @@ +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +PATCH = ROOT / "tools/gamescope/patches/0138-limiter-even-cadence.patch" + + +def added_source(): + return "\n".join(line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")) + + +def block(text, start): + begin = text.index(start) + return text[begin:text.index("\n}", begin) + 3] + + +PREAMBLE = r''' +#include +#include +#include +#include +''' + +MAIN = r''' +struct Run { + std::vector gaps; + int frames = 0; +}; + +static Run run(int hz, int fps, int vblanks, uint64_t latency) { + const uint64_t cycle = 1000000000ull / hz; + const uint64_t limited = cycle * hz / fps; + uint64_t target = 0; + int last = -1; + Run r; + for (int i = 0; i < vblanks; i++) { + const uint64_t now = (1000ull + i) * cycle; + if (limiter_holds_vblank(target, now, limited, cycle)) continue; + target = limiter_latch_target(target, now + latency, limited, cycle); + if (last >= 0) r.gaps.push_back(i - last); + last = i; + r.frames++; + } + return r; +} + +static void check(int hz, int fps, uint64_t latency) { + const int vblanks = hz * 20; + const Run r = run(hz, fps, vblanks, latency); + const int low = hz / fps; + const int high = (hz + fps - 1) / fps; + for (int gap : r.gaps) { + if (gap != low && gap != high) { + std::printf("%d Hz at %d fps: a frame was held for %d refreshes\n", hz, fps, gap); + assert(false); + } + } + const int expected = fps * 20; + if (r.frames < expected - 1 || r.frames > expected + 1) { + std::printf("%d Hz at %d fps: %d frames, expected %d\n", hz, fps, r.frames, expected); + assert(false); + } +} + +int main() { + const int rates[] = {60, 90, 120, 144, 165}; + const int limits[] = {24, 30, 36, 40, 45, 48, 50, 60, 72, 80, 90, 100, 120, 144}; + for (int hz : rates) { + for (int fps : limits) { + if (fps > hz) continue; + check(hz, fps, 0); + check(hz, fps, 1000000000ull / hz / 4); + } + } + + const Run even = run(60, 30, 600, 0); + for (int gap : even.gaps) assert(gap == 2); + const Run full = run(120, 120, 600, 0); + for (int gap : full.gaps) assert(gap == 1); + const Run two_of_three = run(60, 40, 600, 0); + for (size_t i = 1; i < two_of_three.gaps.size(); i++) assert(two_of_three.gaps[i] != two_of_three.gaps[i - 1]); + + const uint64_t cycle = 16666666, limited = cycle * 60 / 45; + assert(limiter_latch_target(1000 * cycle, 1500 * cycle, limited, cycle) == 1500 * cycle); + assert(limiter_latch_target(1500 * cycle, 1000 * cycle, limited, cycle) == 1000 * cycle); + assert(limiter_latch_target(1000 * cycle, 1001 * cycle, limited, cycle) == 1000 * cycle + limited); + return 0; +} +''' + + +class GamescopeLimiterCadenceTest(unittest.TestCase): + def test_a_limit_the_refresh_rate_does_not_divide_is_spread_evenly(self): + compiler = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++") + if not compiler: + self.skipTest("no C++ compiler") + added = added_source() + source = PREAMBLE + block(added, "static uint64_t limiter_latch_target") + block(added, "static bool limiter_holds_vblank") + MAIN + with tempfile.TemporaryDirectory() as tmp: + src = Path(tmp) / "limiter_cadence.cpp" + exe = Path(tmp) / "limiter_cadence" + src.write_text(source) + subprocess.run([compiler, "-std=c++17", "-Wall", "-Werror", "-UNDEBUG", str(src), "-o", str(exe)], check=True) + subprocess.run([str(exe)], check=True) + + def test_the_limited_cycle_is_no_longer_a_whole_number_of_refreshes(self): + added = added_source() + self.assertIn("g_SteamCompMgrAppRefreshCycle * nRealRefreshHz / nTargetFPS", added) + removed = "\n".join(line[1:] for line in PATCH.read_text().splitlines() if line.startswith("-") and not line.startswith("---")) + self.assertIn("nVblankDivisor", removed) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_hdr_live_switch.py b/tools/tests/test_hdr_live_switch.py new file mode 100644 index 0000000000..4468be5048 --- /dev/null +++ b/tools/tests/test_hdr_live_switch.py @@ -0,0 +1,87 @@ +from pathlib import Path +import re +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +PATCH = ROOT / "tools/gamescope/patches/0139-hdr-switch-live.patch" +APP = ROOT / "app/src/main/java/com/droiddeck/launcher" +RES = ROOT / "app/src/main/res" + + +def lines(prefix): + return [line[1:] for line in PATCH.read_text().splitlines() + if line.startswith(prefix) and not line.startswith(prefix * 3)] + + +class HdrLiveSwitchTest(unittest.TestCase): + def test_display_capability_does_not_depend_on_the_setting(self): + added = [line for line in lines("+") if "bExposeHDRSupport =" in line] + self.assertEqual(len(added), 1) + self.assertNotIn("cv_hdr_enabled", added[0]) + self.assertIn("m_uMaxTargetLuminance > m_pConnector->m_uReferenceLuminance", added[0]) + + def test_sdr_keeps_the_8_bit_output(self): + added = [line for line in lines("+") if "*pPrimaryPlaneFormat" in line] + self.assertEqual(len(added), 1) + self.assertRegex(added[0], r"cv_hdr_enabled && u10BitFormat != DRM_FORMAT_INVALID \) \? u10BitFormat : u8BitFormat") + + def test_remade_output_images_pick_the_format_again(self): + text = PATCH.read_text() + hunk = text[text.index("src/rendervulkan.cpp"):] + added = [line[1:] for line in hunk.splitlines() if line.startswith("+") and not line.startswith("+++")] + self.assertEqual([line.strip() for line in added], + ["GetBackend()->GetPreferredOutputFormat( &pOutput->uOutputFormat, &pOutput->uOutputFormatOverlay );"]) + self.assertIn("if ( vulkan_defer_output_images() )", hunk[:hunk.index(added[0])]) + + def test_capable_display_does_not_force_dxvk_hdr_off(self): + added = "\n".join(lines("+")) + self.assertIn('unsetenv( "DXVK_HDR" )', added) + off = added.index('setenv( "DXVK_HDR", "0", true )') + self.assertIn("!GetCurrentConnector()->GetHDRInfo().bExposeHDRSupport", added[:off]) + + def test_the_gate_follows_the_display_not_the_setting(self): + text = (APP / "SessionActivity.kt").read_text() + start = text.index("val attached = CompositorHost.isStarted") + block = text[start:text.index("DriverSetupLog.write", start)] + request = block[block.index("nativeSetHdrRequest("):block.index("Log.i", block.index("nativeSetHdrRequest("))] + self.assertNotIn("SessionPrefs.hdr", block[:block.index("if (!SessionState.running)")]) + self.assertIn("capable, false", request) + self.assertIn("SessionState.hdrCapable && SessionPrefs.hdr(this, mode)", block) + + def test_both_switches_apply_to_the_running_session(self): + helper = (APP / "session/SessionHdr.kt").read_text() + self.assertIn('setGamescopeConvar(app, "hdr_enabled", if (on) 1 else 0)', helper) + self.assertIn("nativeSetHdrOutput(on)", helper) + self.assertIn("nativeSetZeroCopy(on || SessionPrefs.zeroCopy(context, mode))", helper) + self.assertIn("SessionPrefs.prefMode(SessionState.mode) != mode", helper) + for name in ("SessionActivity.kt", "FrontEndActivity.kt"): + text = (APP / name).read_text() + self.assertEqual(len(re.findall(r"onHdr = \{ on -> com\.droiddeck\.launcher\.session\.SessionHdr\.set\(", text)), 1, name) + self.assertNotIn("SessionPrefs.setHdr(", text, name) + + def test_a_saved_opt_out_applies_before_the_gate_opens(self): + native = (ROOT / "app/src/main/cpp/waylandcomp/src/wl_color_mgmt.c").read_text() + switch = native[native.index("void droiddeck_color_set_output(int on)"):] + switch = switch[:switch.index("if (gate != 1)")] + self.assertLess(switch.index("pthread_mutex_lock(&g_output_mu)"), switch.index("atomic_store(&g_output_wanted, on)")) + self.assertLess(switch.index("atomic_exchange(&g_output_on, on)"), switch.index("pthread_mutex_unlock(&g_output_mu)")) + opened = native[native.index("atomic_store(&g_gate, 1);") - 40:] + opened = opened[:opened.index("pthread_mutex_unlock(&g_output_mu)")] + self.assertIn("pthread_mutex_lock(&g_output_mu)", opened) + self.assertIn("if (mode == 3 || !atomic_load(&g_output_wanted)) atomic_store(&g_output_on, 0);", opened) + text = (APP / "SessionActivity.kt").read_text() + self.assertNotIn("if (attached) WaylandCompositor.nativeSetHdrOutput", text) + + def test_retries_stay_with_the_session_that_asked(self): + helper = (APP / "session/SessionHdr.kt").read_text() + self.assertIn("val session = SessionState.sessionId", helper) + self.assertIn("SessionState.sessionId == session", helper) + + def test_no_restart_hint_is_left(self): + for path in list(RES.glob("values*/strings.xml")) + list(APP.rglob("*.kt")): + self.assertNotIn("mode_hdr_restart", path.read_text(), str(path)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_hdr_steam_sync.py b/tools/tests/test_hdr_steam_sync.py new file mode 100644 index 0000000000..c550a892d8 --- /dev/null +++ b/tools/tests/test_hdr_steam_sync.py @@ -0,0 +1,185 @@ +import json +from pathlib import Path +import runpy +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] +BIN = ROOT / "tools/linuxfs/overlay/usr/local/bin" +APP = ROOT / "app/src/main/java/com/droiddeck/launcher" +LIVE = runpy.run_path(str(BIN / "droiddeck-steam-compat")) + +HARNESS = r""" +const assert = require('assert'); +globalThis.window = globalThis; +globalThis.btoa = text => Buffer.from(text, 'binary').toString('base64'); +let now = 0, tick = null; +Object.defineProperty(globalThis, 'performance', { value: { now: () => now }, configurable: true }); +globalThis.setInterval = callback => { tick = callback; return 1; }; +const varints = bytes => { const out = []; let value = 0, shift = 0; + for (const b of bytes) { value += (b & 127) * 2 ** shift; shift += 7; if (b < 128) { out.push(value); value = 0; shift = 0; } } + return out; }; +const writes = [], told = []; +let apply = true; +globalThis.settingsStore = { clientSettings: { gamescope_hdr_enabled: false } }; +globalThis.SteamClient = { Settings: { SetSetting(encoded) { + const [key, value] = varints([...Buffer.from(encoded, 'base64')]); + assert.strictEqual(key, 21015 * 8); + writes.push(value); + if (apply) settingsStore.clientSettings.gamescope_hdr_enabled = value === 1; +} } }; +window.droiddeckHdrChanged = value => told.push(value); +const script = require('fs').readFileSync(process.argv[2], 'utf8'); +assert.strictEqual(eval(script), 'installed'); +assert.strictEqual(eval(script), 'present'); +const bridge = window.__droiddeckHdr; +tick(); +assert.deepStrictEqual(told, [], 'an unchanged client setting is not reported'); +assert.strictEqual(bridge.set(true), true); +assert.deepStrictEqual(writes, [1]); +tick(); +assert.deepStrictEqual(told, [], 'a value the app set is not reported back to it'); +assert.strictEqual(bridge.set(true), true); +assert.deepStrictEqual(writes, [1], 'an equal value is not written again'); +settingsStore.clientSettings.gamescope_hdr_enabled = false; +tick(); +assert.deepStrictEqual(told, ['0'], 'a change made in the client reaches the app'); +tick(); +assert.deepStrictEqual(told, ['0']); +settingsStore.clientSettings.gamescope_hdr_enabled = true; +tick(); +assert.deepStrictEqual(told, ['0', '1']); +apply = false; +bridge.set(false); +assert.deepStrictEqual(writes, [1, 0]); +now += 500; tick(); +assert.deepStrictEqual(told, ['0', '1'], 'the old value is not reported while a write is settling'); +now += 3000; tick(); +assert.deepStrictEqual(told, ['0', '1', '1'], 'a write the client did not take is reported as its real value'); +assert.strictEqual(bridge.set('yes'), true); +assert.deepStrictEqual(writes, [1, 0]); +bridge.set(false); +bridge.set(true); +assert.deepStrictEqual(writes, [1, 0, 0, 1], 'a newer opposite value is written while the earlier write is settling'); +settingsStore.clientSettings.gamescope_hdr_enabled = false; +now += 500; tick(); +settingsStore.clientSettings.gamescope_hdr_enabled = true; +now += 500; tick(); +assert.deepStrictEqual(told, ['0', '1', '1'], 'the earlier write landing late is not reported to the app'); +delete globalThis.__droiddeckHdr; +delete settingsStore.clientSettings.gamescope_hdr_enabled; +assert.strictEqual(eval(script), 'unavailable'); +""" + + +class HdrSteamSyncTest(unittest.TestCase): + def test_bridge_keeps_the_client_setting_and_the_app_equal(self): + with tempfile.TemporaryDirectory() as directory: + script = Path(directory) / "bridge.js" + script.write_text(LIVE["HDR_JS"]) + test = Path(directory) / "test.js" + test.write_text(HARNESS) + result = subprocess.run(["node", str(test), str(script)], capture_output=True, text=True, timeout=20) + self.assertEqual(result.returncode, 0, result.stderr) + + def test_requests_accept_only_on_and_off(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "hdr.request" + for value in ["2", "true", "", None, 1]: + LIVE["hdr_request"](value, directory) + self.assertFalse(path.exists()) + LIVE["hdr_request"]("1", directory) + self.assertEqual(path.read_text(), "1\n") + LIVE["hdr_request"]("0", directory) + self.assertEqual(path.read_text(), "0\n") + + def helper(self, directory): + helper = LIVE["Helper"]("/steam", 0) + calls = [] + + class Page: + answer = True + + def call(self, method, params=None): + calls.append((method, params)) + + def evaluate(self, expression): + calls.append(expression) + return "installed" if expression == LIVE["HDR_JS"] else self.answer + + helper.page = Page() + return helper, calls + + def test_the_app_state_is_applied_once_per_change(self): + with tempfile.TemporaryDirectory() as directory: + globals_ = LIVE["Helper"].sync_hdr.__globals__ + previous = globals_["CONTROLS_DIR"] + try: + globals_["CONTROLS_DIR"] = directory + helper, calls = self.helper(directory) + path = Path(directory) / "state.json" + helper.sync_hdr() + path.write_text(json.dumps({"brightness": 0.5})) + helper.sync_hdr() + self.assertEqual(calls, [], "a session that cannot show HDR leaves the client setting alone") + path.write_text(json.dumps({"brightness": 0.5, "hdr": True})) + helper.sync_hdr() + helper.sync_hdr() + self.assertEqual(calls[0], ("Runtime.addBinding", {"name": LIVE["HDR_BINDING"]})) + self.assertEqual(calls[1], LIVE["HDR_JS"]) + self.assertEqual(calls[2:], ["window.__droiddeckHdr ? window.__droiddeckHdr.set(true) : false"]) + path.write_text(json.dumps({"brightness": 0.7, "hdr": True})) + helper.sync_hdr() + self.assertEqual(len(calls), 3) + path.write_text(json.dumps({"hdr": False})) + helper.sync_hdr() + self.assertEqual(calls[3], "window.__droiddeckHdr ? window.__droiddeckHdr.set(false) : false") + helper.page.answer = False + path.write_text(json.dumps({"hdr": True})) + helper.sync_hdr() + self.assertFalse(helper.hdr_installed) + self.assertIsNone(helper.hdr_state) + helper.page.answer = True + path.write_text(json.dumps({"hdr": False})) + helper.sync_hdr() + self.assertEqual(calls[-1], "window.__droiddeckHdr ? window.__droiddeckHdr.set(false) : false") + finally: + globals_["CONTROLS_DIR"] = previous + + def test_a_client_without_the_setting_is_left_alone(self): + with tempfile.TemporaryDirectory() as directory: + globals_ = LIVE["Helper"].sync_hdr.__globals__ + previous = globals_["CONTROLS_DIR"] + try: + globals_["CONTROLS_DIR"] = directory + helper, calls = self.helper(directory) + helper.page.evaluate = lambda expression: calls.append(expression) or "unavailable" + (Path(directory) / "state.json").write_text(json.dumps({"hdr": True})) + helper.sync_hdr() + self.assertEqual(calls, [("Runtime.addBinding", {"name": LIVE["HDR_BINDING"]}), LIVE["HDR_JS"]]) + self.assertFalse(helper.hdr_installed) + self.assertIsNone(helper.hdr_state) + helper.sync_hdr() + self.assertEqual(len(calls), 2, "a client without the setting is not asked again straight away") + finally: + globals_["CONTROLS_DIR"] = previous + + def test_the_app_publishes_and_takes_the_shared_value(self): + controls = (APP / "runtime/DeviceControlsComponent.kt").read_text() + self.assertIn('if (SessionState.hdrCapable) controls.put("hdr", SessionState.hdr)', controls) + self.assertIn('"hdr.request" -> if (text == "0" || text == "1")', controls) + self.assertIn('SessionHdr.set(context, SessionPrefs.prefMode(SessionState.mode), text == "1")', controls) + self.assertIn('"hdr.request")', controls[controls.index("REQUESTS = setOf"):]) + session = (APP / "SessionActivity.kt").read_text() + self.assertIn("if (key == SessionPrefs.hdrKey(hdrPrefMode()))", session) + self.assertIn("registerOnSharedPreferenceChangeListener(hdrPrefListener)", session) + self.assertIn("unregisterOnSharedPreferenceChangeListener(hdrPrefListener)", session) + + def test_frame_limit_writes_share_the_setting_writer(self): + self.assertIn("(21002, value)", LIVE["FRAME_LIMIT_JS"]) + self.assertNotIn("__SET_SETTING__", LIVE["FRAME_LIMIT_JS"] + LIVE["HDR_JS"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_inputudev_preload.py b/tools/tests/test_inputudev_preload.py index c1d970fd1d..8e4cf66e80 100644 --- a/tools/tests/test_inputudev_preload.py +++ b/tools/tests/test_inputudev_preload.py @@ -77,6 +77,66 @@ char *realpath(const char *path, char *resolved) { } """ +LOCKED = r""" +#include +#include + +extern int busy; + +__attribute__((constructor)) static void start(void) { + busy = 1; + syscall(SYS_getpid); + busy = 0; +} +""" + +ARENA = r""" +#include +#include +#include + +static _Alignas(64) unsigned char arena[1 << 23]; +static size_t used; +int busy; +static int busy_allocations; + +void *memalign(size_t align, size_t size) { + uintptr_t start; + if (busy) busy_allocations++; + if (align < 16) align = 16; + start = ((uintptr_t)(arena + used) + 16 + align - 1) & ~(uintptr_t)(align - 1); + if (start + size > (uintptr_t)(arena + sizeof(arena))) return NULL; + ((size_t *)start)[-1] = size; + used = start + size - (uintptr_t)arena; + return (void *)start; +} + +void *malloc(size_t size) { return memalign(16, size); } +void *aligned_alloc(size_t align, size_t size) { return memalign(align, size); } +int posix_memalign(void **out, size_t align, size_t size) { return (*out = memalign(align, size)) ? 0 : 12; } +void free(void *p) { (void)p; } + +void *calloc(size_t n, size_t size) { + void *p = malloc(n * size); + if (p) memset(p, 0, n * size); + return p; +} + +void *realloc(void *p, size_t size) { + void *q = malloc(size); + if (p && q) { + size_t old = ((size_t *)p)[-1]; + memcpy(q, p, old < size ? old : size); + } + return q; +} + +int main(void) { + printf("allocations %d\n", busy_allocations); + return 0; +} +""" + UDEV = r""" #include #include @@ -414,7 +474,7 @@ class InputUdevPreloadTest(unittest.TestCase): if "__GLIBC__" not in compile_c("-dM", "-E", "-x", "c", "-include", "limits.h", "/dev/null"): raise unittest.SkipTest("needs a glibc toolchain") sources = (("once.c", ONCE), ("first.c", FIRST), ("second.c", SECOND), ("chain.c", CHAIN), ("mark.c", MARK), - ("udev.c", UDEV), ("program.c", PROGRAM)) + ("udev.c", UDEV), ("program.c", PROGRAM), ("locked.c", LOCKED), ("arena.c", ARENA)) for name, text in sources: (build / name).write_text(text) cls.lib = cls.dir / "libddsession.so" @@ -427,6 +487,11 @@ class InputUdevPreloadTest(unittest.TestCase): compile_c("-shared", "-fPIC", "-O2", "-o", str(cls.udev), str(build / "udev.c")) cls.program = cls.dir / "program" compile_c("-O0", "-o", str(cls.program), str(build / "program.c"), str(cls.dir / "libfirst.so"), "-ldl") + compile_c("-shared", "-fPIC", "-O0", "-o", str(cls.dir / "liblocked.so"), str(build / "locked.c")) + cls.arena = cls.dir / "arena" + compile_c("-O0", "-rdynamic", "-o", str(cls.arena), str(build / "arena.c"), "-Wl,--no-as-needed", + str(cls.dir / "liblocked.so"), + f"-Wl,-rpath,{cls.dir}") cls.pads = cls.pad_dir("pads", "event0") @classmethod @@ -449,6 +514,12 @@ class InputUdevPreloadTest(unittest.TestCase): def test_a_lookup_from_another_preloads_initialiser_does_not_reenter_it(self): self.assertEqual(self.run_program("once", "libonce.so"), ["readlink 1"]) + def test_a_first_wrapped_call_inside_the_programs_allocator_does_not_allocate(self): + result = subprocess.run([str(self.arena)], env=dict(os.environ, LD_PRELOAD=str(self.lib)), capture_output=True, + text=True, timeout=20) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.splitlines(), ["allocations 0"]) + def test_the_real_lookup_still_sees_the_original_caller(self): self.assertEqual(self.run_program("next", "libfirst.so", "libsecond.so"), ["next 2"]) diff --git a/tools/tests/test_memory_guard_ab.py b/tools/tests/test_memory_guard_ab.py index 6d75f7206f..96565efffa 100644 --- a/tools/tests/test_memory_guard_ab.py +++ b/tools/tests/test_memory_guard_ab.py @@ -66,6 +66,15 @@ class DumpParsingTest(unittest.TestCase): def test_the_bottom_home_is_the_visible_home_on_another_display(self): self.assertEqual((2, "rip.moth.cocoonshell"), ab.bottom_home(ACTIVITIES, 0)) + def test_android_13_activity_records_are_counted(self): + self.assertEqual(1, ab.session_count( + " * Hist #1: ActivityRecord{e1ec207 u0 com.droiddeck.launcher/.SessionActivity} t14519}\n")) + + def test_the_visible_app_stands_in_when_no_home_is_on_the_other_display(self): + dump = ("Display #4 (activities from top to bottom):\n" + " * Task{21f60d6 #14493 type=standard A=10113:com.discord U=0 visible=true visibleRequested=true mode=fullscreen}\n") + self.assertEqual((4, "com.discord"), ab.bottom_home(dump, 0)) + def test_no_bottom_home_without_another_display(self): self.assertIsNone(ab.bottom_home(ACTIVITIES.split("\n\n")[1], 0)) @@ -80,6 +89,25 @@ class DumpParsingTest(unittest.TestCase): self.assertIsNone(ab.logical_size(DISPLAYS, 5)) +class HogScriptTest(unittest.TestCase): + def test_both_modes_start_the_fill_counter(self): + script = ab.HOG.splitlines() + counter = next(n for n, line in enumerate(script) if line.startswith("i=0")) + self.assertLess(counter, script.index('if [ "$mode" = burst ]; then')) + self.assertLess(counter, next(n for n, line in enumerate(script) if line.startswith("while [ $i -lt 512 ]"))) + + + def test_a_failed_write_never_reports_released(self): + script = ab.HOG.splitlines() + check = script.index('[ "$failed" = 0 ] || { echo "write failed"; cleanup; exit 1; }') + self.assertLess(check, script.index("echo released")) + self.assertIn("failed=1", ab.HOG.split("echo released")[0]) + + def test_a_burst_takes_the_remainder_below_one_chunk(self): + self.assertIn("rest=$((take % 256))", ab.HOG) + self.assertIn('echo "nothing to take"', ab.HOG) + + class SummaryTest(unittest.TestCase): def test_max_adj_skips_samples_after_death(self): self.assertEqual(50, ab.max_adj(["0", "50", "DEAD", ""])) diff --git a/tools/tests/test_output_refresh.py b/tools/tests/test_output_refresh.py index 8896d3e551..96817b2f4f 100644 --- a/tools/tests/test_output_refresh.py +++ b/tools/tests/test_output_refresh.py @@ -44,10 +44,11 @@ static struct surface surface = { .xdg_toplevel = 1, .toplevel_committed = 1 }; static int g_input_pipe[2] = {-1, -1}; static atomic_int g_output_refresh_mhz = 60000; static atomic_int g_output_refresh_pending; +static atomic_int g_panel_rates_pending; static int g_output_announced_refresh_mhz = 60000; static int g_output_w = 1920, g_output_h = 1080; static int flushes, resizes, pointers, ticks; -static int scale_changes, scale_mode, scale_alignment, renders; +static int scale_changes, scale_mode, scale_alignment, renders, rate_notifies; static void *g_display; #define WL_OUTPUT_MODE_CURRENT 1 #define WL_OUTPUT_MODE_PREFERRED 2 @@ -77,6 +78,7 @@ static void vk_present_set_scale_mode(int mode, int alignment) { scale_changes++; scale_mode = mode; scale_alignment = alignment; } static void schedule_render(void) { renders++; } +static void refresh_notify_rates(void) { rate_notifies++; } ''' CHECKS = r''' @@ -138,6 +140,11 @@ int main(void) { droiddeck_wayland_set_output_refresh_rate(90000); drain(); expect(6, 90000, 1); assert(scale_changes == 2 && scale_mode == 1 && scale_alignment == 3 && renders == 2); + atomic_store(&g_panel_rates_pending, 1); + drain(); + assert(rate_notifies == 1 && !atomic_load(&g_panel_rates_pending)); + drain(); + assert(rate_notifies == 1); close(g_input_pipe[0]); close(g_input_pipe[1]); puts("PASS"); } diff --git a/tools/tests/test_render_on_commit.py b/tools/tests/test_render_on_commit.py index c0b8c436d5..66abb89d7f 100644 --- a/tools/tests/test_render_on_commit.py +++ b/tools/tests/test_render_on_commit.py @@ -26,7 +26,7 @@ static struct wl_event_source *g_render_idle, *g_fallback_timer; static int g_fallback_armed, g_dirty, g_hud_fresh, framegen; static void *g_hud_surface; static int64_t g_dirty_since_ns, g_last_vsync_ns, g_tick_vsync_ns, g_hud_last_ns, g_rendered_tick_ns; -static int g_tick_held; +static int g_tick_held, g_tick_spare, g_scene_queues; static int64_t g_hold_missed_ns; #define HOLD_RETRY_NS 1000000000LL static int64_t g_refresh_ns = 16666667; @@ -254,6 +254,15 @@ int main(void) { clock_ns += 200000000LL; schedule_render(); assert(idles_added == idles && g_fallback_armed == 1 && timers_armed == 1); + g_rendered_tick_ns = g_tick_vsync_ns; + g_tick_spare = 0; g_scene_queues = 1; + assert(!tick_takes_scene()); + g_tick_spare = 1; + assert(tick_takes_scene()); + g_scene_queues = 0; + assert(!tick_takes_scene()); + g_rendered_tick_ns = g_tick_vsync_ns - 1; + assert(tick_takes_scene()); puts("PASS"); return 0; } @@ -270,7 +279,7 @@ class RenderOnCommitTest(unittest.TestCase): render = extract_function(source, 'render_scene') self.assertIn('g_rendered_tick_ns = g_tick_vsync_ns;', render) self.assertIn('g_tick_held = 0;', render) - functions = ('scene_held_for_limit', 'commit_renders_on', 'render_on_commit', 'schedule_render', 'scene_waits_for_game', 'on_commit_idle', + functions = ('scene_held_for_limit', 'commit_renders_on', 'tick_takes_scene', 'render_on_commit', 'schedule_render', 'scene_waits_for_game', 'on_commit_idle', 'bfi_blocked', 'bfi_update', 'bfi_tick', 'on_vsync') harness = PREAMBLE + '\n'.join(extract_function(source, name) for name in functions) + CHECKS with tempfile.TemporaryDirectory(prefix='droiddeck-render-on-commit-') as folder: diff --git a/tools/tests/test_runtime_inputs.py b/tools/tests/test_runtime_inputs.py index 954ea76f66..92f2ae1c79 100644 --- a/tools/tests/test_runtime_inputs.py +++ b/tools/tests/test_runtime_inputs.py @@ -137,6 +137,19 @@ class RuntimeInputsTest(unittest.TestCase): with self.assertRaisesRegex(ValueError, 'sources changed'): runtime.verify(self.root) + def test_cargo_output_beside_a_windows_helper_is_not_a_source(self): + crate = self.root / 'tools/epic-launcher' + (crate / 'src').mkdir(parents=True) + (crate / 'Cargo.toml').write_text('[package]\n') + (crate / 'src/lib.rs').write_text('old') + runtime.record(self.root) + (crate / 'target/debug').mkdir(parents=True) + (crate / 'target/debug/build.log').write_text('local cargo test') + runtime.verify(self.root) + (crate / 'src/lib.rs').write_text('new') + with self.assertRaisesRegex(ValueError, 'sources changed'): + runtime.verify(self.root) + def test_missing_quest_driver_cannot_be_attested(self): (self.root / 'app/build/prepared-assets/graphics_driver/adrenotools-turnip25.1.0-quest1.tzst').unlink() with self.assertRaisesRegex(ValueError, 'quest1.tzst'): @@ -248,6 +261,21 @@ class RuntimeInputsTest(unittest.TestCase): runtime.check_apk(apk, self.root) runtime.check_apk(self.current_apk(self.root / 'current.apk'), self.root) + def test_an_apk_still_carrying_the_epic_parent_stand_in_is_rejected(self): + epic = self.root / 'app/src/main/assets/linuxfs/usr/local/lib/droiddeck-epic' + epic.mkdir(parents=True) + (epic / 'EpicGamesLauncher.exe').write_bytes(b'MZ parent') + self.packs() + name = 'assets/linuxfs/usr/local/lib/droiddeck-epic/EpicGamesLauncher.exe' + self.assertIn(name, runtime.outputs(self.root)) + apk = self.current_apk(self.root / 'bundled.apk', {name: b'MZ parent'}) + with self.assertRaisesRegex(ValueError, 'epic pack provides'): + runtime.check_apk(apk, self.root) + runtime.check_apk(self.current_apk(self.root / 'current.apk'), self.root) + self.pack('epic', {'EpicGamesLauncher.exe': b'MZ older parent'}) + with self.assertRaisesRegex(ValueError, 'epic is missing or has a stale'): + runtime.check_apk(self.current_apk(self.root / 'current.apk'), self.root) + def test_an_apk_still_carrying_the_powervr_runtime_is_rejected(self): apk = self.current_apk(self.root / 'bundled.apk', {'assets/hybris/runtime.tzst': b'runtime'}) with self.assertRaisesRegex(ValueError, 'powervr pack provides'): diff --git a/tools/tests/test_store_launch_rockstar.py b/tools/tests/test_store_launch_rockstar.py index 277d2a9f2b..ccd12e24d5 100644 --- a/tools/tests/test_store_launch_rockstar.py +++ b/tools/tests/test_store_launch_rockstar.py @@ -292,5 +292,150 @@ class RockstarLaunch(unittest.TestCase): self.assertIn('Grand Theft Auto: Vice City', text) +SDK_FILES = {'socialclub.dll': b'sdk dll', 'socialclub.pak': b'sdk pak', 'SocialClubHelper.exe': b'sdk helper'} + + +class EpicRockstarLaunch(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.root = Path(temp.name) + self.folder = self.root / 'Grand Theft Auto V' + self.folder.mkdir() + (self.folder / 'PlayGTAV.exe').write_bytes(b'MZ') + self.sidecar = {'store': 'epic', 'id': '9d2d0eb64d5c44529cece33fe2a46482', 'title': 'Grand Theft Auto V', 'exe': 'PlayGTAV.exe'} + (self.folder / '.droiddeck-store.json').write_text(json.dumps(self.sidecar)) + self.prefix = self.root / 'prefix' + (self.prefix / 'pfx').mkdir(parents=True) + (self.prefix / 'pfx/user.reg').write_text('WINE REGISTRY Version 2\n') + (self.prefix / 'pfx/system.reg').write_text('WINE REGISTRY Version 2\n') + self.sdk = self.prefix / 'pfx/drive_c/Program Files/Rockstar Games/Social Club' + self.unpacked = [] + + def unpacker(self, command, **kwargs): + if command[1] == 'l': + listing = ''.join('Path = x64/%s\nSize = %d\n\n' % (name, len(data)) for name, data in SDK_FILES.items()) + return type('Listing', (), {'returncode': 0, 'stdout': listing.encode()})() + self.unpacked.append(Path(command[-2])) + out = Path(next(arg[2:] for arg in command if arg.startswith('-o'))) / 'x64' + out.mkdir(parents=True) + for name, data in SDK_FILES.items(): + (out / name).write_bytes(data + b' from ' + Path(command[-2]).read_bytes()) + return type('Done', (), {'returncode': 0})() + + def stage(self): + with patch.object(store.shutil, 'which', return_value='/bin/7z'), patch.object(store.subprocess, 'run', side_effect=self.unpacker), \ + patch.object(store, 'wait_for_server', return_value=True), \ + patch.object(store, 'create_prefix', side_effect=AssertionError('the prefix already exists')): + return store.epic_rockstar_sdk(self.folder, self.sidecar, str(self.prefix), '') + + def test_the_launchers_own_sdk_installer_is_staged_so_it_never_runs_it(self): + setup = self.prefix / 'pfx' / store.EPIC_SDK_SETUP + setup.parent.mkdir(parents=True) + setup.write_bytes(b'launcher setup') + (self.folder / 'Installers').mkdir() + (self.folder / 'Installers/Social-Club-Setup.exe').write_bytes(b'older game setup') + self.assertEqual('installed', self.stage()) + self.assertEqual([setup], self.unpacked) + self.assertEqual(b'sdk dll from launcher setup', (self.sdk / 'socialclub.dll').read_bytes()) + text = (self.prefix / 'pfx/system.reg').read_text() + self.assertIn(r'[Software\\Wow6432Node\\Rockstar Games\\Rockstar Games Social Club]', text) + self.assertIn(r'"InstallFolder"="C:\\Program Files\\Rockstar Games\\Social Club"', text) + self.assertNotIn(r'Rockstar Games\\Launcher]', text) + self.assertEqual('present', self.stage()) + self.assertEqual([setup], self.unpacked) + + def test_an_updated_launcher_installer_is_staged_again(self): + setup = self.prefix / 'pfx' / store.EPIC_SDK_SETUP + setup.parent.mkdir(parents=True) + setup.write_bytes(b'launcher setup') + self.assertEqual('installed', self.stage()) + setup.write_bytes(b'newer launcher setup') + self.assertEqual('installed', self.stage()) + self.assertEqual(b'sdk dll from newer launcher setup', (self.sdk / 'socialclub.dll').read_bytes()) + + def test_before_the_launcher_is_installed_the_games_installer_is_used(self): + (self.folder / 'Redistributables').mkdir() + (self.folder / 'Redistributables/Social-Club-Setup.exe').write_bytes(b'game setup') + self.assertEqual('installed', self.stage()) + self.assertEqual(b'sdk dll from game setup', (self.sdk / 'socialclub.dll').read_bytes()) + self.assertNotIn(r'Rockstar Games\\Launcher]', (self.prefix / 'pfx/system.reg').read_text()) + + def test_other_epic_games_are_left_alone(self): + self.assertIsNone(self.stage()) + self.assertEqual([], self.unpacked) + self.assertFalse(self.sdk.exists()) + self.assertEqual('WINE REGISTRY Version 2\n', (self.prefix / 'pfx/system.reg').read_text()) + + def test_an_installer_linked_from_outside_the_game_is_ignored(self): + outside = self.root / 'outside.exe' + outside.write_bytes(b'not the game') + (self.folder / 'Installers').mkdir() + (self.folder / 'Installers/Social-Club-Setup.exe').symlink_to(outside) + self.assertIsNone(self.stage()) + self.assertEqual([], self.unpacked) + + def game_environment(self, shared=None, games=None): + config = self.root / 'home/.config/droiddeck/game-environment.json' + config.parent.mkdir(parents=True, exist_ok=True) + config.write_text(json.dumps({'version': 1, 'shared': shared or {}, 'games': games or {}})) + + def launch(self, bat, parent, compat_data=''): + (self.folder / '.droiddeck-launch.bat').write_text(bat) + calls = [] + env = {'DD_LAUNCH_DIR': str(self.root / 'launch'), 'STEAM_COMPAT_DATA_PATH': compat_data, 'HOME': str(self.root / 'home'), + 'DD_EPIC_PARENT': ''} + with patch.dict(os.environ, env), patch.object(store, 'EPIC_PARENT', parent), \ + patch.object(store, 'client_wanted', return_value=False), \ + patch.object(store, 'ask', side_effect=lambda channel, request, timeout=0, claim=False: calls.append((request['op'], timeout)) or {'ok': False}): + store.main([str(self.folder / '.droiddeck-launch.bat')]) + return calls + + def test_a_title_that_needs_the_parent_fetches_the_stand_in_before_its_code(self): + bat = '@echo off\r\nsetlocal\r\nset "DD_P=1"\r\n' + calls = self.launch(bat, self.root / 'missing/EpicGamesLauncher.exe') + self.assertEqual([('store-service', store.EPIC_SERVICE_WAIT), 'epic-code', 'cloud-down'], + [calls[0]] + [op for op, _ in calls[1:]]) + staged = self.root / 'EpicGamesLauncher.exe' + staged.write_bytes(b'MZ') + self.assertEqual(['epic-code', 'cloud-down'], [op for op, _ in self.launch(bat, staged)]) + + def test_other_epic_games_do_not_fetch_the_stand_in(self): + bat = '@echo off\r\nsetlocal\r\nset "DD_P="\r\nif "%DD_EPIC_PARENT%"=="1" set "DD_P=1"\r\n' + calls = self.launch(bat, self.root / 'missing/EpicGamesLauncher.exe') + self.assertEqual(['epic-code', 'cloud-down'], [op for op, _ in calls]) + + def test_the_games_own_switch_decides_whether_the_stand_in_is_fetched(self): + compat_data = str(self.root / 'compatdata/4089453117') + missing = self.root / 'missing/EpicGamesLauncher.exe' + self.game_environment(games={'4089453117': {'DD_EPIC_PARENT': '1'}}) + self.assertEqual('store-service', self.launch('@echo off\r\nset "DD_P="\r\n', missing, compat_data)[0][0]) + self.game_environment(games={'4089453117': {'DD_EPIC_PARENT': '0'}}) + self.assertEqual(['epic-code', 'cloud-down'], [op for op, _ in self.launch('@echo off\r\nset "DD_P=1"\r\n', missing, compat_data)]) + self.game_environment(games={'4089453117': {'DD_EPIC_PARENT': None}}, shared={'DD_EPIC_PARENT': '0'}) + self.assertEqual('store-service', self.launch('@echo off\r\nset "DD_P=1"\r\n', missing, compat_data)[0][0]) + + def test_the_sidecars_own_environment_wins_like_it_does_in_the_batch(self): + compat_data = str(self.root / 'compatdata/4089453117') + missing = self.root / 'missing/EpicGamesLauncher.exe' + sidecar = self.folder / '.droiddeck-store.json' + sidecar.write_text(json.dumps(dict(self.sidecar, env={'DD_EPIC_PARENT': '1'}))) + self.assertEqual('store-service', self.launch('@echo off\r\nset "DD_P="\r\n', missing, compat_data)[0][0]) + self.game_environment(games={'4089453117': {'DD_EPIC_PARENT': '1'}}) + sidecar.write_text(json.dumps(dict(self.sidecar, env={'DD_EPIC_PARENT': '"0"'}))) + self.assertEqual(['epic-code', 'cloud-down'], [op for op, _ in self.launch('@echo off\r\nset "DD_P=1"\r\n', missing, compat_data)]) + + def test_the_switch_is_read_the_way_the_game_will_see_it(self): + env = {'HOME': str(self.root / 'home'), 'STEAM_COMPAT_DATA_PATH': str(self.root / 'compatdata/4089453117')} + self.assertEqual('', store.epic_parent_switch({}, env)) + self.assertEqual('1', store.epic_parent_switch({}, dict(env, DD_EPIC_PARENT='1'))) + self.game_environment(shared={'DD_EPIC_PARENT': '1'}, games={'4089453117': {'DD_EPIC_PARENT': '0'}, '7': {'DD_EPIC_PARENT': '1'}}) + self.assertEqual('0', store.epic_parent_switch({}, env)) + self.assertEqual('1', store.epic_parent_switch({'env': {'DD_EPIC_PARENT': '1'}}, env)) + self.assertEqual('1', store.epic_parent_switch({}, dict(env, STEAM_COMPAT_DATA_PATH=str(self.root / 'compatdata/12')))) + (self.root / 'home/.config/droiddeck/game-environment.json').write_text('{"version": 9}') + self.assertEqual('1', store.epic_parent_switch({}, dict(env, DD_EPIC_PARENT='1'))) + + if __name__ == '__main__': unittest.main() diff --git a/tools/tests/test_udevmon_preload.py b/tools/tests/test_udevmon_preload.py new file mode 100644 index 0000000000..ae100ecfbb --- /dev/null +++ b/tools/tests/test_udevmon_preload.py @@ -0,0 +1,112 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload" + +PROGRAM = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char **argv) { + unsigned groups = argc > 1 ? (unsigned)atoi(argv[1]) : 2; + const char *mode = argc > 2 ? argv[2] : ""; + if (!strcmp(mode, "churn")) { + for (int i = 0; i < 16; i++) { + int closed = socket(AF_NETLINK, SOCK_RAW, NETLINK_KOBJECT_UEVENT); + struct sockaddr_nl unsubscribed = {.nl_family = AF_NETLINK}; + if (closed < 0 || bind(closed, (struct sockaddr *)&unsubscribed, sizeof(unsubscribed)) != 0) return 3; + close(closed); + if (open("/dev/null", O_RDONLY) != closed) return 4; + } + } + int fd = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC | SOCK_NONBLOCK, NETLINK_KOBJECT_UEVENT); + if (fd < 0) { printf("socket failed\n"); return 2; } + struct sockaddr_nl nl = {.nl_family = AF_NETLINK, .nl_groups = groups}; + printf("bind %d\n", bind(fd, (struct sockaddr *)&nl, sizeof(nl))); + if (!strcmp(mode, "rebind")) { + nl.nl_pid = (unsigned)getpid() + 1; + printf("rebind %d\n", bind(fd, (struct sockaddr *)&nl, sizeof(nl))); + } + printf("cloexec %d nonblock %d\n", (fcntl(fd, F_GETFD) & FD_CLOEXEC) != 0, (fcntl(fd, F_GETFL) & O_NONBLOCK) != 0); + int (*inject)(const char *, const char *, const char *, const char *, unsigned, unsigned) = + (int (*)(const char *, const char *, const char *, const char *, unsigned, unsigned))dlsym(RTLD_DEFAULT, "dd_udevmon_inject"); + int sent = inject("add", "/devices/droiddeck/usb4/4-1:1.3/0003:054C:09CC.0005/hidraw/hidraw20", "hidraw", + "/dev/hidraw20", 245, 20); + printf("sent %d\n", sent); + struct pollfd p = {.fd = fd, .events = POLLIN}; + if (sent > 0 && poll(&p, 1, 1000) == 1) { + char buf[2048]; + struct sockaddr_nl from; + struct iovec iov = {.iov_base = buf, .iov_len = sizeof(buf)}; + struct msghdr msg = {.msg_name = &from, .msg_namelen = sizeof(from), .msg_iov = &iov, .msg_iovlen = 1}; + ssize_t n = recvmsg(fd, &msg, 0); + int found = 0; + for (ssize_t i = 0; n > 0 && i < n; i += (ssize_t)strlen(buf + i) + 1) + if (!strcmp(buf + i, "ACTION=add") || !strcmp(buf + i, "DEVNAME=/dev/hidraw20")) found++; + printf("received %s fields %d\n", n > 0 && !memcmp(buf, "libudev", 8) ? "libudev" : "nothing", found); + } + return 0; +} +""" + + +@unittest.skipUnless(shutil.which("gcc") and os.uname().machine == "x86_64", "needs gcc on an x86-64 host") +class UdevMonitorPreloadTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tmp = Path(tempfile.mkdtemp()) + cls.library = cls.tmp / "libudevmon.so" + subprocess.run(["gcc", "-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror", "-DUDEVMON_TEST", "-DBINFMT_TEST", + '-DBINFMT_HANDLER="/bin/false"', "-o", str(cls.library), "-pthread"] + + [str(PRELOAD / name) for name in ("binfmt.c", "net.c", "udevmon.c", "pathcache.c", "perms.c", "webhelper.c")] + + [str(Path(__file__).with_name("netlink_stubs.c")), "-ldl"], check=True) + source = cls.tmp / "program.c" + source.write_text(PROGRAM) + cls.program = cls.tmp / "program" + subprocess.run(["gcc", "-O2", "-o", str(cls.program), str(source), "-ldl"], check=True) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, True) + + def run_program(self, *args, refuse=False): + env = dict(os.environ, LD_PRELOAD=str(self.library)) + env.pop("DD_UDEVMON_REFUSE", None) + if refuse: + env["DD_UDEVMON_REFUSE"] = "1" + return subprocess.run([str(self.program), *args], env=env, capture_output=True, text=True, check=True).stdout.splitlines() + + def test_a_monitor_the_system_will_not_subscribe_hears_the_sessions_events(self): + out = self.run_program(refuse=True) + self.assertEqual(["bind 0", "cloexec 1 nonblock 1", "sent 1", "received libudev fields 2"], out) + + def test_a_monitor_the_system_subscribes_stays_on_the_real_socket(self): + self.assertEqual(["bind 0", "cloexec 1 nonblock 1", "sent 0"], self.run_program()) + + def test_a_monitor_bound_without_groups_hears_the_sessions_events(self): + out = self.run_program("0") + self.assertEqual(["bind 0", "cloexec 1 nonblock 1", "sent 1", "received libudev fields 2"], out) + + def test_failed_rebind_leaves_the_original_subscription_in_place(self): + out = self.run_program("2", "rebind") + self.assertEqual(["bind 0", "rebind -1", "cloexec 1 nonblock 1", "sent 0"], out) + + def test_closed_monitors_do_not_exhaust_stand_in_slots(self): + out = self.run_program("0", "churn") + self.assertEqual(["bind 0", "cloexec 1 nonblock 1", "sent 1", "received libudev fields 2"], out) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_vk_linear_dmabuf.py b/tools/tests/test_vk_linear_dmabuf.py new file mode 100644 index 0000000000..a91df519c6 --- /dev/null +++ b/tools/tests/test_vk_linear_dmabuf.py @@ -0,0 +1,139 @@ +import os +from pathlib import Path +import re +import shutil +import subprocess +import tempfile +import unittest + +from tools.tests.test_vk_external_image_sync import vulkan_include_args +from tools.tests.test_vk_pending_completion import function + +TESTS = Path(__file__).resolve().parent +SRC = TESTS.parents[1] / "app/src/main/cpp/waylandcomp/src" + +LAYER_HARNESS = r''' +#include +#include +#include +#include "vk_external_image_sync.h" +#include "vk_linear_dmabuf.h" + +typedef struct AHardwareBuffer AHardwareBuffer; +%(image)s +struct vkp_draw { + struct vkp_image *img; + float sx, sy, sw, sh; + int dx, dy, dw, dh; + int blend; +}; +struct draw_list { struct vkp_draw *d; int n, cap; }; +static const uint32_t g_qfam = 2; +%(foreign)s +%(is_dmabuf)s +%(width)s +%(height)s +static int black_fill_below(const struct draw_list *dl, int n) { (void)dl; (void)n; return 0; } +%(candidate)s + +static int candidate(struct vkp_image *img) { + struct vkp_draw d = {.img = img, .sw = 1560, .sh = 720, .dw = 1560, .dh = 720}; + struct draw_list dl = {.d = &d, .n = 1, .cap = 1}; + return layer_candidate(&dl, 1560, 720); +} + +static int foreign_pair(struct vkp_image *img) { + struct vkp_external_client_barrier_pair pair; + return vkp_external_client_barrier_pair(img->image, g_qfam, foreign_image(img), img->blit_dst, &pair); +} + +int main(void) { + struct vkp_image staged = {.w = 1560, .h = 720, .dmabuf = 1, .staged = 1}; + assert(candidate(&staged) == 0); + assert(!foreign_pair(&staged)); + + struct vkp_image client = {.w = 1560, .h = 720, .dmabuf = 1}; + assert(candidate(&client) == 0); + assert(foreign_pair(&client)); + + struct vkp_image shm = {.w = 1560, .h = 720}; + assert(candidate(&shm) == -1); + assert(!foreign_pair(&shm)); + + struct vkp_image layer = {.w = 1560, .h = 720, .dmabuf = 1, .blit_dst = 1}; + assert(candidate(&layer) == -1); + assert(!foreign_pair(&layer)); + return 0; +} +''' + + +def compile_and_run(test, source, tmp, name): + compiler = shutil.which(os.environ.get("CC", "cc")) + if not compiler: + test.fail("A C compiler is required for the linear dma-buf regression tests") + program = Path(tmp) / name + command = [ + compiler, + "-std=c11", + "-Wall", + "-Wextra", + "-Werror", + "-UNDEBUG", + "-I", + str(SRC), + *vulkan_include_args(), + str(source), + "-o", + str(program), + ] + built = subprocess.run(command, capture_output=True, text=True) + test.assertEqual(built.returncode, 0, built.stdout + built.stderr) + ran = subprocess.run([str(program)], capture_output=True, text=True, timeout=30) + test.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr) + + +class VkLinearDmabufTest(unittest.TestCase): + def test_linear_dmabuf_copy(self): + with tempfile.TemporaryDirectory(prefix="droiddeck-vk-linear-") as tmp: + compile_and_run(self, TESTS / "vk_linear_dmabuf_test.c", tmp, "vk-linear-dmabuf") + + def test_readback_orders_general_transition_after_staging_copy(self): + body = function((SRC / "vk_present.c").read_text(), "vkp_image_readback") + stage = body.index("stage_linear_dmabuf(cmd, src);") + barrier = body.index("vkp_linear_dmabuf_readback_stage(src->in_general)") + self.assertLess(stage, barrier) + self.assertIn(".srcAccessMask = vkp_linear_dmabuf_readback_access(src->in_general)", body[stage:barrier]) + self.assertNotIn("CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT", body) + + def test_modifier_query_needs_drm_modifier_extension(self): + body = function((SRC / "vk_present.c").read_text(), "vkp_image_import_dmabuf") + query = re.search(r"const int modifier_sampled = (.*?);", body, re.S) + self.assertIsNotNone(query, "modifier_sampled not found in vkp_image_import_dmabuf") + terms = [t.strip() for t in query.group(1).split("&&")] + self.assertIn("g_drm_modifiers", terms) + self.assertLess(terms.index("g_drm_modifiers"), terms.index("modifier_importable(img->fmt, modifier, sampled_usage)")) + self.assertIn("!as_blit_dst", terms) + self.assertIn("g_vk.GetPhysicalDeviceImageFormatProperties2", terms) + + def test_staged_client_image_stays_layer_candidate(self): + vk = (SRC / "vk_present.c").read_text() + comp = (SRC / "compositor.c").read_text() + image = re.search(r"^struct vkp_image \{.*?^\};", vk, re.M | re.S) + self.assertIsNotNone(image, "struct vkp_image not found in vk_present.c") + harness = LAYER_HARNESS % { + "image": image.group(0), + "foreign": function(vk, "foreign_image"), + "is_dmabuf": function(vk, "vkp_image_is_dmabuf"), + "width": function(vk, "vkp_image_width"), + "height": function(vk, "vkp_image_height"), + "candidate": function(comp, "layer_candidate"), + } + with tempfile.TemporaryDirectory(prefix="droiddeck-vk-linear-layer-") as tmp: + source = Path(tmp) / "layer_candidate_test.c" + source.write_text(harness) + compile_and_run(self, source, tmp, "vk-linear-layer") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_vk_pending_completion.py b/tools/tests/test_vk_pending_completion.py index d0a4ad594c..8f3dc48eb0 100644 --- a/tools/tests/test_vk_pending_completion.py +++ b/tools/tests/test_vk_pending_completion.py @@ -56,16 +56,20 @@ static VkResult wait_fn(uintptr_t dev, unsigned n, const VkFence *f, int all, ui static void unmap_fn(uintptr_t dev, uintptr_t mem) { (void)dev; (void)mem; ++unmapped; } static void destroy_fn(uintptr_t dev, uintptr_t img, void *allocator) { (void)dev; (void)img; (void)allocator; ++destroyed; } static void free_fn(uintptr_t dev, uintptr_t mem, void *allocator) { (void)dev; (void)mem; (void)allocator; ++freed_memory; } +static unsigned destroyed_buffers; +static void destroy_buffer_fn(uintptr_t dev, uintptr_t buf, void *allocator) { (void)dev; (void)buf; (void)allocator; ++destroyed_buffers; } +#define VK_NULL_HANDLE 0 static struct { VkResult (*WaitForFences)(uintptr_t, unsigned, const VkFence *, int, uint64_t); void (*UnmapMemory)(uintptr_t, uintptr_t); void (*DestroyImage)(uintptr_t, uintptr_t, void *); void (*FreeMemory)(uintptr_t, uintptr_t, void *); -} g_vk = {wait_fn, unmap_fn, destroy_fn, free_fn}; + void (*DestroyBuffer)(uintptr_t, uintptr_t, void *); +} g_vk = {wait_fn, unmap_fn, destroy_fn, free_fn, destroy_buffer_fn}; typedef struct AHardwareBuffer AHardwareBuffer; static int released_buffers; static void AHardwareBuffer_release(AHardwareBuffer *b) { (void)b; ++released_buffers; } -struct vkp_image { uintptr_t image, mem; void *map; AHardwareBuffer *android_buffer; }; +struct vkp_image { uintptr_t image, mem; void *map; AHardwareBuffer *android_buffer; uintptr_t linear_buf, linear_mem; int staged, in_general; }; static void blendp_forget_image(uintptr_t image) { (void)image; ++forgotten; } /* PRODUCTION_FUNCTIONS */ static struct vkp_image *image(void) { @@ -173,7 +177,7 @@ class VkPendingCompletionTest(unittest.TestCase): self.assertEqual(ran.returncode,0,ran.stdout+ran.stderr) def test_unknown_completion_retains_gpu_resources(self): - self.compile_and_run(HARNESS, ['quarantine_pending_work', 'timed_wait', 'vkp_image_destroy']) + self.compile_and_run(HARNESS, ['quarantine_pending_work', 'timed_wait', 'destroy_image_objects', 'vkp_image_destroy']) def test_failed_device_idle_does_not_destroy_swapchain(self): # LOGE's arguments must be evaluated as real production logging does. diff --git a/tools/tests/test_zram_preload.py b/tools/tests/test_zram_preload.py index 6ee4aa0b76..74d155bc1f 100644 --- a/tools/tests/test_zram_preload.py +++ b/tools/tests/test_zram_preload.py @@ -18,7 +18,14 @@ PROGRAM = r""" #include #include #include +#include +#include +#include +#include +#include #include +#include +#include #include #include #include @@ -31,14 +38,15 @@ static unsigned char *shared; static volatile sig_atomic_t urg_tid; static volatile sig_atomic_t usr_tid; static int urg_count, usr_count; -static int worker_tid; static int worker_delivery; _Static_assert(__atomic_always_lock_free(sizeof(int), 0), "signal state must be lock-free"); static void signal_tid(int sig) { sig_atomic_t tid = (sig_atomic_t)syscall(SYS_gettid); - if (tid == __atomic_load_n(&worker_tid, __ATOMIC_RELAXED)) + char name[16] = {0}; + prctl(PR_GET_NAME, name, 0, 0, 0); + if (!strcmp(name, "zr-worker")) __atomic_store_n(&worker_delivery, 1, __ATOMIC_RELAXED); if (sig == SIGURG) { __atomic_store_n(&urg_tid, tid, __ATOMIC_RELAXED); @@ -123,6 +131,75 @@ static long trim(char mode, long kb) { exit(5); } +static int workers(void) { + DIR *dir = opendir("/proc/self/task"); + struct dirent *entry; + int count = 0; + while (dir && (entry = readdir(dir)) != NULL) { + if (entry->d_name[0] == '.') continue; + char path[64], name[32] = {0}; + snprintf(path, sizeof(path), "/proc/self/task/%s/comm", entry->d_name); + FILE *comm = fopen(path, "r"); + if (comm && fgets(name, sizeof(name), comm) && !strcmp(name, "zr-worker\n")) count++; + if (comm) fclose(comm); + } + if (dir) closedir(dir); + return count; +} + +static void without_threads(void) { + struct rlimit limit; + if (getrlimit(RLIMIT_NPROC, &limit)) _exit(15); + limit.rlim_cur = 0; + if (setrlimit(RLIMIT_NPROC, &limit)) _exit(15); +} + +static void *park(void *arg) { + (void)arg; + for (;;) pause(); + return NULL; +} + +static void parked(void) { + pthread_t thread; + sigset_t urg, previous; + sigemptyset(&urg); + sigaddset(&urg, SIGURG); + pthread_sigmask(SIG_BLOCK, &urg, &previous); + if (pthread_create(&thread, NULL, park, NULL)) _exit(16); + pthread_sigmask(SIG_SETMASK, &previous, NULL); +} + +static void filter_clone(unsigned long allowed) { + struct sock_filter rules[] = { + BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SYS_clone, 0, 3), + BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, args[0])), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, allowed, 1, 0), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_KILL_PROCESS), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW), + }; + struct sock_fprog program = {sizeof(rules) / sizeof(rules[0]), rules}; + if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) || prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &program)) _exit(17); +} + +static volatile int sandbox_ready; + +static void *sandbox(void *arg) { + (void)arg; + sigset_t urg; + sigemptyset(&urg); + sigaddset(&urg, SIGURG); + filter_clone(0); + pthread_sigmask(SIG_UNBLOCK, &urg, NULL); + sandbox_ready = 1; + for (;;) pause(); + return NULL; +} + +static const unsigned long thread_clone = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | + CLONE_SYSVSEM | CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID; + static uint64_t sum(const unsigned char *p, size_t n) { uint64_t s = 0; for (size_t i = 0; i < n; i += 64) s = s * 31 + p[i]; @@ -155,6 +232,7 @@ int main(int argc, char **argv) { memset(shared, 0, size); pthread_t t[2]; for (uintptr_t i = 0; i < 2; i++) pthread_create(&t[i], NULL, writer, (void *)i); + parked(); struct sigaction sa; sigaction(SIGURG, NULL, &sa); printf("handler %d\n", (sa.sa_flags & SA_SIGINFO) ? 1 : 0); @@ -164,27 +242,21 @@ int main(int argc, char **argv) { memset(&signal_action, 0, sizeof(signal_action)); signal_action.sa_handler = signal_tid; sigemptyset(&signal_action.sa_mask); - sigaction(SIGURG, &signal_action, NULL); sigaction(SIGUSR1, &signal_action, NULL); + int fd = open(ctl, O_WRONLY | O_TRUNC); + if (fd < 0 || write(fd, "1", 1) != 1) return 10; + close(fd); printf("ready %d\n", getpid()); fflush(stdout); - int id; - if (scanf("%d", &id) != 1) return 10; - __atomic_store_n(&worker_tid, id, __ATOMIC_RELAXED); - printf("armed 1\n"); - fflush(stdout); for (int round = 1; round <= 100; round++) { int i; - for (i = 0; i < 5000 && - (__atomic_load_n(&urg_count, __ATOMIC_ACQUIRE) < round || - __atomic_load_n(&usr_count, __ATOMIC_ACQUIRE) < round); i++) usleep(1000); + for (i = 0; i < 5000 && __atomic_load_n(&usr_count, __ATOMIC_ACQUIRE) < round; i++) usleep(1000); if (i == 5000) return 11; printf("received %d\n", round); fflush(stdout); } stop = 1; for (int i = 0; i < 2; i++) pthread_join(t[i], NULL); - printf("urg %d\n", __atomic_load_n(&urg_tid, __ATOMIC_RELAXED)); printf("usr %d\n", __atomic_load_n(&usr_tid, __ATOMIC_RELAXED)); printf("worker %d\n", __atomic_load_n(&worker_delivery, __ATOMIC_RELAXED)); return 0; @@ -199,6 +271,13 @@ int main(int argc, char **argv) { int status_code; waitpid(child, &status_code, 0); printf("childack %d\n", WIFEXITED(status_code) && WEXITSTATUS(status_code) == 0); + } else if (!strcmp(argv[4], "threads")) { + stop = 1; + for (int i = 0; i < 2; i++) pthread_join(t[i], NULL); + printf("idle %d\n", workers()); + request('1'); + printf("after %d\n", workers()); + return 0; } else if (!strcmp(argv[4], "trim")) { stop = 1; for (int i = 0; i < 2; i++) pthread_join(t[i], NULL); @@ -301,8 +380,47 @@ int main(int argc, char **argv) { _exit(0); } waitpid(child, NULL, 0); + child = fork(); + if (child < 0) exit(6); + if (child == 0) { + parked(); + without_threads(); + for (size_t i = 0; i < size; i += page) data[i]++; + printf("nothread_trim %ld\n", trim('2', 1L << 30)); + fflush(stdout); + _exit(0); + } + waitpid(child, NULL, 0); printf("worker_trim %ld\n", trim('2', 1L << 30)); return 0; + } else if (!strcmp(argv[4], "sandboxed")) { + stop = 1; + for (int i = 0; i < 2; i++) pthread_join(t[i], NULL); + filter_clone(thread_clone); + printf("sandboxed_trim %ld\n", trim('2', 1L << 30)); + return 0; + } else if (!strcmp(argv[4], "thread-sandboxed")) { + stop = 1; + for (int i = 0; i < 2; i++) pthread_join(t[i], NULL); + sigset_t urg; + sigemptyset(&urg); + sigaddset(&urg, SIGURG); + pthread_sigmask(SIG_BLOCK, &urg, NULL); + pthread_t thread; + if (pthread_create(&thread, NULL, sandbox, NULL)) exit(16); + while (!sandbox_ready) usleep(1000); + printf("thread_sandboxed_trim %ld\n", trim('2', 1L << 30)); + return 0; + } else if (!strcmp(argv[4], "filtered")) { + fflush(stdout); + filter_clone(thread_clone); + execl("/proc/self/exe", argv[0], argv[1], argv[2], "0", "filtered-trim", (char *)NULL); + return 18; + } else if (!strcmp(argv[4], "filtered-trim")) { + stop = 1; + for (int i = 0; i < 2; i++) pthread_join(t[i], NULL); + printf("filtered_trim %ld\n", trim('2', 1L << 30)); + return 0; } else if (!strcmp(argv[4], "burst")) { send_request('0'); usleep(10000); @@ -313,6 +431,7 @@ int main(int argc, char **argv) { pid_t child = fork(); if (child < 0) exit(8); if (child == 0) { + without_threads(); if (!strcmp(argv[4], "timed-inline-single")) { if (munmap(data, size) || munmap(shared, size)) _exit(12); data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); @@ -463,6 +582,11 @@ class ZramPreloadTest(unittest.TestCase): self.assertEqual([1], out["intact"]) self.assertEqual(6, len(out["out"])) + def test_a_process_keeps_no_extra_thread_while_nothing_is_paged_out(self): + out = self.run_program(None, 8, 0, "threads") + self.assertEqual([0], out["idle"]) + self.assertEqual([0], out["after"]) + def test_process_signals_do_not_reach_zram_worker(self): environment = dict(os.environ, LD_PRELOAD=str(self.lib)) process = subprocess.Popen([str(self.steam), str(self.ctl), "1", "0", "signals"], @@ -471,30 +595,16 @@ class ZramPreloadTest(unittest.TestCase): process.stdout.readline() ready = process.stdout.readline().split() self.assertEqual("ready", ready[0]) - worker = None - task_dir = Path("/proc") / ready[1] / "task" - for task in task_dir.iterdir(): - if (task / "comm").read_text().strip() == "zr-worker": - worker = int(task.name) - break - self.assertIsNotNone(worker) - self.assertEqual(os.sched_getscheduler(process.pid), os.sched_getscheduler(worker)) - process.stdin.write(f"{worker}\n") - process.stdin.flush() - self.assertEqual("armed 1", process.stdout.readline().strip()) - for _ in range(100): + for round in range(100): os.kill(process.pid, signal.SIGURG) os.kill(process.pid, signal.SIGUSR1) - self.assertEqual(f"received {_ + 1}", process.stdout.readline().strip()) + self.assertEqual(f"received {round + 1}", process.stdout.readline().strip()) process.stdin.close() process.wait(timeout=10) output = process.stdout.read() values = dict(line.split() for line in output.splitlines()) - self.assertNotEqual(0, int(values["urg"])) self.assertNotEqual(0, int(values["usr"])) self.assertEqual(0, int(values["worker"])) - self.assertNotEqual(worker, int(values["urg"])) - self.assertNotEqual(worker, int(values["usr"])) finally: if process.poll() is None: process.kill() @@ -577,10 +687,33 @@ class ZramPreloadTest(unittest.TestCase): @unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap") def test_process_without_a_worker_trims_in_small_steps(self): + if os.geteuid() == 0: + self.skipTest("the thread limit does not apply to root") + out = self.run_program(None, 48, 0, "trim-fork") + self.assertTrue(16 * 1024 < out["nothread_trim"][0] <= 32 * 1024, out) + self.assertGreater(out["worker_trim"][0], 64 * 1024, out) + + @unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap") + def test_a_single_threaded_process_trims_without_starting_a_thread(self): out = self.run_program(None, 48, 0, "trim-fork") self.assertTrue(16 * 1024 < out["inline_trim"][0] <= 32 * 1024, out) self.assertGreater(out["worker_trim"][0], 64 * 1024, out) + @unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap") + def test_a_process_that_sandboxed_itself_trims_without_starting_a_thread(self): + out = self.run_program(None, 48, 0, "sandboxed") + self.assertTrue(16 * 1024 < out["sandboxed_trim"][0] <= 32 * 1024, out) + + @unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap") + def test_a_thread_that_sandboxed_itself_trims_without_starting_a_thread(self): + out = self.run_program(None, 48, 0, "thread-sandboxed") + self.assertTrue(16 * 1024 < out["thread_sandboxed_trim"][0] <= 32 * 1024, out) + + @unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap") + def test_the_worker_passes_a_filter_that_only_allows_thread_clones(self): + out = self.run_program(None, 48, 0, "filtered") + self.assertGreater(out["filtered_trim"][0], 40 * 1024, out) + def test_worker_acknowledges_back_to_back_requests(self): out = self.run_program(None, 48, 0, "burst") self.assertEqual([1], out["burstack"]) diff --git a/tools/tests/vk_linear_dmabuf_test.c b/tools/tests/vk_linear_dmabuf_test.c new file mode 100644 index 0000000000..3abb66da19 --- /dev/null +++ b/tools/tests/vk_linear_dmabuf_test.c @@ -0,0 +1,106 @@ +#include +#include +#include + +#include "vk_linear_dmabuf.h" + +static void check_padded_rows(void) { + VkBufferImageCopy copy; + memset(©, 0xa5, sizeof(copy)); + const VkDeviceSize need = vkp_linear_dmabuf_copy(VK_FORMAT_R8G8B8A8_UNORM, 1560, 720, 6400, 0, ©); + assert(copy.bufferRowLength == 1600); + assert(copy.bufferRowLength != 1560); + assert(copy.bufferOffset == 0); + assert(copy.bufferImageHeight == 720); + assert(copy.imageSubresource.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT); + assert(copy.imageSubresource.mipLevel == 0); + assert(copy.imageSubresource.baseArrayLayer == 0); + assert(copy.imageSubresource.layerCount == 1); + assert(copy.imageOffset.x == 0 && copy.imageOffset.y == 0 && copy.imageOffset.z == 0); + assert(copy.imageExtent.width == 1560); + assert(copy.imageExtent.height == 720); + assert(copy.imageExtent.depth == 1); + assert(need == (VkDeviceSize)6400 * 719 + 1560 * 4); +} + +static void check_offset_and_wide_texels(void) { + VkBufferImageCopy copy; + const VkDeviceSize need = vkp_linear_dmabuf_copy(VK_FORMAT_R16G16B16A16_SFLOAT, 1920, 1080, 15360, 4096, ©); + assert(copy.bufferRowLength == 1920); + assert(copy.bufferOffset == 4096); + assert(need == 4096 + (VkDeviceSize)15360 * 1079 + 1920 * 8); + + assert(vkp_linear_dmabuf_copy(VK_FORMAT_B8G8R8A8_UNORM, 1, 1, 64, 0, ©) == 4); + assert(copy.bufferRowLength == 16); +} + +static void check_rejected_layouts(void) { + VkBufferImageCopy copy; + assert(vkp_linear_dmabuf_copy(VK_FORMAT_R8G8B8A8_UNORM, 1560, 720, 6236, 0, ©) == 0); + assert(vkp_linear_dmabuf_copy(VK_FORMAT_R8G8B8A8_UNORM, 1560, 720, 6402, 0, ©) == 0); + assert(vkp_linear_dmabuf_copy(VK_FORMAT_R8G8B8A8_UNORM, 1560, 720, 6400, 2, ©) == 0); + assert(vkp_linear_dmabuf_copy(VK_FORMAT_R16G16B16A16_SFLOAT, 1560, 720, 6240, 0, ©) == 0); + assert(vkp_linear_dmabuf_copy(VK_FORMAT_R8G8B8A8_UNORM, 0, 720, 6400, 0, ©) == 0); + assert(vkp_linear_dmabuf_copy(VK_FORMAT_R8G8B8A8_UNORM, 1560, 0, 6400, 0, ©) == 0); + assert(vkp_linear_dmabuf_copy(VK_FORMAT_R8G8B8A8_UNORM, 1560, 720, 6400, 0, NULL) == 0); +} + +static void check_path_choice(void) { + const uint64_t linear = 0; + const uint64_t qcom_compressed = 0x0500000000000001ULL; + assert(vkp_linear_dmabuf_through_buffer(0, linear, 0)); + assert(!vkp_linear_dmabuf_through_buffer(1, linear, 0)); + assert(!vkp_linear_dmabuf_through_buffer(1, qcom_compressed, 0)); + assert(!vkp_linear_dmabuf_through_buffer(0, qcom_compressed, 0)); + assert(!vkp_linear_dmabuf_through_buffer(0, linear, 1)); + assert(!vkp_linear_dmabuf_through_buffer(1, linear, 1)); +} + +static void check_foreign_image(void) { + assert(vkp_linear_dmabuf_foreign_image(1, 0)); + assert(!vkp_linear_dmabuf_foreign_image(1, 1)); + assert(!vkp_linear_dmabuf_foreign_image(0, 0)); + assert(!vkp_linear_dmabuf_foreign_image(0, 1)); +} + +static void check_readback_order(void) { + assert(vkp_linear_dmabuf_readback_stage(1) & VK_PIPELINE_STAGE_TRANSFER_BIT); + assert(vkp_linear_dmabuf_readback_access(1) & VK_ACCESS_TRANSFER_WRITE_BIT); + assert(vkp_linear_dmabuf_readback_stage(0) == VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT); + assert(vkp_linear_dmabuf_readback_access(0) == 0); +} + +static void check_ownership(void) { + const VkBuffer buffer = (VkBuffer)(uintptr_t)0x4321; + const uint32_t queue_family = 3; + const VkBufferMemoryBarrier acquire = vkp_linear_dmabuf_ownership(buffer, queue_family, 1); + assert(acquire.sType == VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER); + assert(acquire.pNext == NULL); + assert(acquire.srcQueueFamilyIndex == VK_QUEUE_FAMILY_FOREIGN_EXT); + assert(acquire.dstQueueFamilyIndex == queue_family); + assert(acquire.srcAccessMask == 0); + assert(acquire.dstAccessMask == VK_ACCESS_TRANSFER_READ_BIT); + assert(acquire.buffer == buffer); + assert(acquire.offset == 0); + assert(acquire.size == VK_WHOLE_SIZE); + + const VkBufferMemoryBarrier release = vkp_linear_dmabuf_ownership(buffer, queue_family, 0); + assert(release.sType == VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER); + assert(release.srcQueueFamilyIndex == queue_family); + assert(release.dstQueueFamilyIndex == VK_QUEUE_FAMILY_FOREIGN_EXT); + assert(release.srcAccessMask == VK_ACCESS_TRANSFER_READ_BIT); + assert(release.dstAccessMask == 0); + assert(release.buffer == buffer); + assert(release.size == VK_WHOLE_SIZE); +} + +int main(void) { + check_padded_rows(); + check_offset_and_wide_texels(); + check_rejected_layouts(); + check_path_choice(); + check_foreign_image(); + check_readback_order(); + check_ownership(); + return 0; +} diff --git a/tools/tests/vk_terminal_callers_test.c b/tools/tests/vk_terminal_callers_test.c index 2398608bd2..ebf8fbf096 100644 --- a/tools/tests/vk_terminal_callers_test.c +++ b/tools/tests/vk_terminal_callers_test.c @@ -110,7 +110,7 @@ struct damage_list { int n; }; struct surface { struct vkp_image *shm_img; struct wl_resource *resource; - int buf_w, buf_h, buf_alpha, has_content; + int buf_w, buf_h, buf_alpha, has_content, black_fill; /* Read by take_shm's game-frame detection; with no damage it stays off here. */ int src_set; float src[4]; struct damage_list damage_buf, damage_local;