diff --git a/README.md b/README.md index 8290b3ef6a..ce30c25358 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ Compatibility and performance vary by device; hardware validation is limited. De ## Credits and licence -GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). Epic Games and GOG support build on [Phobos’s](https://github.com/phobos665) adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl), respectively. Battle.net support is [@kayakyakr](https://github.com/kayakyakr)'s: it runs Blizzard's own Battle.net client, downloaded from Blizzard and not included, in Proton, and shows the key art from each game's [Battle.net Shop](https://shop.battle.net) page; without the Steam client its games see DroidDeck's pad as an Xbox 360 controller through `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`. Its games install from Stores through Blizzard's own Agent and the local HTTP API it serves, driven the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) drives it, with the requests described on [wowdev.wiki](https://wowdev.wiki/Agent); how other launchers find, install and start Blizzard games was read in [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader, without taking their code. The registry entries a GOG game's install script (`goggame-.script`) sets are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher)'s GOG setup (GPL-3.0) reads them. LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. x86 AppImages, and any whose own runtime cannot unpack them, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence, which also starts the arm64 emulator AppImages whose own runtime cannot run its extractor on Android. x86 AppImages packed with [sharun](https://github.com/VHSgunzo/sharun) by VHSgunzo (MIT) start because DroidDeck's own [FEX](https://github.com/FEX-Emu/FEX) build (MIT) puts the platform name under `AT_PLATFORM`, which sharun's [userland-execve](https://crates.io/crates/userland-execve) loader (MIT) requires; FEX filed it under `AT_BASE_PLATFORM`. The Steam client's audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink` with its request size kept to its ring so clients are not asked to queue 100 ms ahead. mmap ring-buffer controller input was developed by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). Why the x86-64 Steam client refused the arm64 client's sign-in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest). x86 programs that link OpenSSL 3 under FEX use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt) platform. Hooks written with `WriteProcessMemory` into code [FEX](https://github.com/FEX-Emu/FEX) has translated go through `/proc//mem` again when the kernel refuses `process_vm_writev`, as [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` wrote them before Wine 11. x86 Linux games under FEX get the same `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes into the Steam Linux Runtime, so ALSA plays through PulseAudio. Games render with [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's own per-render-pass choice between tile memory and system memory, while the Steam client keeps `TU_DEBUG=sysmem`; [FEX](https://github.com/FEX-Emu/FEX)'s code disk cache was checked in its source and is already on through Proton. The proot fast path picks the guest name of a host file bound under several names in the order [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later) sorts its bindings, so links and `/proc/self/fd` read back as they do through proot. The session's [PipeWire](https://gitlab.freedesktop.org/pipewire/pipewire) (MIT) opens its sockets with the per-socket access settings documented in its `module-access.c`, and [WirePlumber](https://gitlab.freedesktop.org/pipewire/wireplumber) (MIT) keeps those clients at full permissions through its `access.rules`. Wine write watches use the userfaultfd support in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/ntdll/unix/virtual.c` (LGPL-2.1-or-later): libblsession gives it the arm64 syscall number and answers its `PAGEMAP_SCAN` from `/proc/self/pagemap` where Android refuses the ioctl. Wine on arm64 sets a thread's full context by raising `SIGUSR2` from `syscall_dispatcher_return_slowpath` in [Wine](https://gitlab.winehq.org/wine/wine)'s `dlls/ntdll/unix/signal_arm64.c` (LGPL-2.1-or-later); libblsession runs that handler in place on a frame laid out as the [Linux](https://github.com/torvalds/linux) kernel's `arch/arm64/kernel/signal.c` builds it and returns through `rt_sigreturn`, so proot does not stop the thread for it. Wine's process list reads each process's memory counters from `/proc//status` in `fill_vm_counters` ([Wine](https://gitlab.winehq.org/wine/wine) `dlls/ntdll/unix/process.c`, LGPL-2.1-or-later), so libblsession gives those reads the kernel's file instead of a copy with `TracerPid` cleared. droiddeck-ntsync is checked against the object, wait and error semantics documented for the [Linux](https://github.com/torvalds/linux) ntsync driver in `Documentation/userspace-api/ntsync.rst` (GPL-2.0). Xbox games load the Windows modules of [@domsvoboda](https://github.com/domsvoboda)'s [xodus-nexus](https://github.com/domsvoboda/xodus-nexus) runtime (LGPL-2.1-or-later), including its `wintypes.dll`, whose `ApiInformation` answer Minecraft for Windows needs to start; how Minecraft installs GameInput under Wine was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT). [ReSkate](https://github.com/Dingo-Shenanigans/ReSkate) (GPL-3.0) by Dingo Shenanigans is set up with the Steam launch option from its README and starts at D3D12 feature level 12_1, as its game crashes at 12_2 here. See [LICENSE](LICENSE). Steam and Proton belong to Valve Corporation; this project is not affiliated with Valve. +GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). Epic Games and GOG support build on [Phobos’s](https://github.com/phobos665) adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl), respectively. Battle.net support is [@kayakyakr](https://github.com/kayakyakr)'s: it runs Blizzard's own Battle.net client, downloaded from Blizzard and not included, in Proton, and shows the key art from each game's [Battle.net Shop](https://shop.battle.net) page; without the Steam client its games see DroidDeck's pad as an Xbox 360 controller through `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`. Its games install from Stores through Blizzard's own Agent and the local HTTP API it serves, driven the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) drives it, with the requests described on [wowdev.wiki](https://wowdev.wiki/Agent); how other launchers find, install and start Blizzard games was read in [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader, without taking their code. The registry entries a GOG game's install script (`goggame-.script`) sets are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher)'s GOG setup (GPL-3.0) reads them. LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. x86 AppImages, and any whose own runtime cannot unpack them, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence, which also starts the arm64 emulator AppImages whose own runtime cannot run its extractor on Android. x86 AppImages packed with [sharun](https://github.com/VHSgunzo/sharun) by VHSgunzo (MIT) start because DroidDeck's own [FEX](https://github.com/FEX-Emu/FEX) build (MIT) puts the platform name under `AT_PLATFORM`, which sharun's [userland-execve](https://crates.io/crates/userland-execve) loader (MIT) requires; FEX filed it under `AT_BASE_PLATFORM`. The Steam client's audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink` with its request size kept to its ring so clients are not asked to queue 100 ms ahead. The in-game performance HUD is [@The412Banner](https://github.com/The412Banner)'s [FusionHUD](https://github.com/The412Banner/FusionHUD) (GPL-3.0 with an attribution term), Bannerlator's HUD; its frame rate, frame times and readings are taken from the same sources, and worked out the same way, as Valve's [MangoHud](https://github.com/flightlessmango/MangoHud) build (MIT) that runs Steam's performance overlay in a DroidDeck session, with the frame times shared by gamescope patch 0125; when gamescope sends no frames for two seconds, the HUD counts the frames DroidDeck's compositor shows instead, which stop at the screen's refresh rate. mmap ring-buffer controller input was developed by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). Why the x86-64 Steam client refused the arm64 client's sign-in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest). x86 programs that link OpenSSL 3 under FEX use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt) platform. Hooks written with `WriteProcessMemory` into code [FEX](https://github.com/FEX-Emu/FEX) has translated go through `/proc//mem` again when the kernel refuses `process_vm_writev`, as [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` wrote them before Wine 11. x86 Linux games under FEX get the same `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes into the Steam Linux Runtime, so ALSA plays through PulseAudio. Games render with [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's own per-render-pass choice between tile memory and system memory, while the Steam client keeps `TU_DEBUG=sysmem`; [FEX](https://github.com/FEX-Emu/FEX)'s code disk cache was checked in its source and is already on through Proton. The proot fast path picks the guest name of a host file bound under several names in the order [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later) sorts its bindings, so links and `/proc/self/fd` read back as they do through proot. The session's [PipeWire](https://gitlab.freedesktop.org/pipewire/pipewire) (MIT) opens its sockets with the per-socket access settings documented in its `module-access.c`, and [WirePlumber](https://gitlab.freedesktop.org/pipewire/wireplumber) (MIT) keeps those clients at full permissions through its `access.rules`. Wine write watches use the userfaultfd support in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/ntdll/unix/virtual.c` (LGPL-2.1-or-later): libblsession gives it the arm64 syscall number and answers its `PAGEMAP_SCAN` from `/proc/self/pagemap` where Android refuses the ioctl. Wine on arm64 sets a thread's full context by raising `SIGUSR2` from `syscall_dispatcher_return_slowpath` in [Wine](https://gitlab.winehq.org/wine/wine)'s `dlls/ntdll/unix/signal_arm64.c` (LGPL-2.1-or-later); libblsession runs that handler in place on a frame laid out as the [Linux](https://github.com/torvalds/linux) kernel's `arch/arm64/kernel/signal.c` builds it and returns through `rt_sigreturn`, so proot does not stop the thread for it. Wine's process list reads each process's memory counters from `/proc//status` in `fill_vm_counters` ([Wine](https://gitlab.winehq.org/wine/wine) `dlls/ntdll/unix/process.c`, LGPL-2.1-or-later), so libblsession gives those reads the kernel's file instead of a copy with `TracerPid` cleared. droiddeck-ntsync is checked against the object, wait and error semantics documented for the [Linux](https://github.com/torvalds/linux) ntsync driver in `Documentation/userspace-api/ntsync.rst` (GPL-2.0). Xbox games load the Windows modules of [@domsvoboda](https://github.com/domsvoboda)'s [xodus-nexus](https://github.com/domsvoboda/xodus-nexus) runtime (LGPL-2.1-or-later), including its `wintypes.dll`, whose `ApiInformation` answer Minecraft for Windows needs to start; how Minecraft installs GameInput under Wine was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT). [ReSkate](https://github.com/Dingo-Shenanigans/ReSkate) (GPL-3.0) by Dingo Shenanigans is set up with the Steam launch option from its README and starts at D3D12 feature level 12_1, as its game crashes at 12_2 here. See [LICENSE](LICENSE). Steam and Proton belong to Valve Corporation; this project is not affiliated with Valve. XR glasses support builds on WinNative's VITURE glasses work. VITURE protocol details were checked against [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) by [@wheaney](https://github.com/wheaney), including the VITURE protocol header it ships, [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) by [@badicsalex](https://github.com/badicsalex) and the [go-macos/iokit VITURE package](https://pkg.go.dev/github.com/go-macos/iokit/viture); the optional VITURE SDK belongs to VITURE and is not included. RayNeo support adapts [@informalTechCode](https://github.com/informalTechCode)'s [RayNeo-Air-Series-3DoF-Scaffold](https://github.com/informalTechCode/RayNeo-Air-Series-3DoF-Scaffold) (Apache-2.0) and references [@verncat](https://github.com/verncat)'s [RayNeo-Air-3S-Pro-OpenVR](https://github.com/verncat/RayNeo-Air-3S-Pro-OpenVR) (MIT) and [Monado](https://gitlab.freedesktop.org/monado/monado) (BSL-1.0); see [docs/third-party/rayneo](docs/third-party/rayneo/README.md). XREAL 1S support references [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) and [xrealOneDeviceKit](https://github.com/wheaney/xrealOneDeviceKit) by @wheaney, [xreal_one_driver](https://github.com/rohitsangwan01/xreal_one_driver) by [@rohitsangwan01](https://github.com/rohitsangwan01) (MIT) and [xr-tools](https://github.com/0xcaff/xr-tools) by [@0xcaff](https://github.com/0xcaff). Rokid support follows the Rokid protocol notes in [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) and @badicsalex's [Void Computing write-ups](https://voidcomputing.hu/blog/worse-better-prettier/), and [Monado](https://gitlab.freedesktop.org/monado/monado)'s Rokid driver. The REDMAGIC glasses-display findings draw on [@mekhontsev](https://github.com/mekhontsev)'s [MagicDesk investigation](https://github.com/mekhontsev/magicdesk/blob/main/docs/xr-resolution-fix.md) and [@Coding-BR](https://github.com/Coding-BR)'s [decompiled Nubia kernel](https://github.com/Coding-BR/android_kernel_nubia_sm8850_qwjujube). VITURE, RayNeo, XREAL, Rokid and REDMAGIC are trademarks of their owners; this project is not affiliated with them. diff --git a/app/src/main/cpp/waylandcomp/CMakeLists.txt b/app/src/main/cpp/waylandcomp/CMakeLists.txt index c2bfc86434..a4de38ca14 100644 --- a/app/src/main/cpp/waylandcomp/CMakeLists.txt +++ b/app/src/main/cpp/waylandcomp/CMakeLists.txt @@ -33,6 +33,8 @@ add_library(droiddeckwayland SHARED generated/banner-ahb-v1-protocol.c src/framegen_bridge.c src/framegen_jni.c + src/hudframes.c + src/hudframes_jni.c ) target_compile_options(droiddeckwayland PRIVATE $<$:-Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers>) diff --git a/app/src/main/cpp/waylandcomp/src/hudframes.c b/app/src/main/cpp/waylandcomp/src/hudframes.c new file mode 100644 index 0000000000..5a6fc4e99b --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/hudframes.c @@ -0,0 +1,99 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "hudframes.h" + +/* Layout written by gamescope patch 0125 (tools/gamescope/patches). */ +#define HUD_FRAMES_MAGIC 0x46484444u +#define HUD_FRAMES_HEADER 128u +#define HUD_FRAMES_ENTRY 16u + +struct hud_frames { + const uint8_t *map; + size_t size; + uint64_t seen; +}; + +static uint32_t load32(const uint8_t *p) { return __atomic_load_n((const uint32_t *)p, __ATOMIC_ACQUIRE); } +static uint64_t load64(const uint8_t *p) { return __atomic_load_n((const uint64_t *)p, __ATOMIC_ACQUIRE); } + +struct hud_frames *hud_frames_open(const char *path) { + int fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return NULL; + struct stat st; + void *map = MAP_FAILED; + if (fstat(fd, &st) == 0 && st.st_size >= (off_t)HUD_FRAMES_HEADER) + map = mmap(NULL, (size_t)st.st_size, PROT_READ, MAP_SHARED, fd, 0); + close(fd); + if (map == MAP_FAILED) return NULL; + struct hud_frames *h = calloc(1, sizeof(*h)); + if (!h) { + munmap(map, (size_t)st.st_size); + return NULL; + } + h->map = map; + h->size = (size_t)st.st_size; + return h; +} + +void hud_frames_close(struct hud_frames *h) { + if (!h) return; + munmap((void *)h->map, h->size); + free(h); +} + +static uint32_t capacity(const struct hud_frames *h) { + if (load32(h->map) != HUD_FRAMES_MAGIC) return 0; + uint32_t cap; + memcpy(&cap, h->map + 8, 4); + if (cap == 0 || HUD_FRAMES_HEADER + (size_t)cap * HUD_FRAMES_ENTRY > h->size) return 0; + return cap; +} + +int hud_frames_poll(struct hud_frames *h, int64_t *frametimes, int64_t *times, int max) { + uint32_t cap = capacity(h); + if (!cap || max <= 0) return -1; + uint64_t count = load64(h->map + 16); + if (count < h->seen) h->seen = 0; + uint64_t from = h->seen; + if (count - from > cap) from = count - cap; + if (count - from > (uint64_t)max) from = count - (uint64_t)max; + int n = 0; + for (uint64_t i = from; i < count; i++, n++) { + const uint8_t *e = h->map + HUD_FRAMES_HEADER + (i % cap) * HUD_FRAMES_ENTRY; + memcpy(&frametimes[n], e, 8); + memcpy(×[n], e + 8, 8); + } + /* The writer may have lapped the ring while we copied: drop what it overwrote. */ + uint64_t after = load64(h->map + 16); + uint64_t valid = after > cap ? after - cap : 0; + if (from < valid) { + int skip = (int)(valid - from < (uint64_t)n ? valid - from : (uint64_t)n); + memmove(frametimes, frametimes + skip, (size_t)(n - skip) * sizeof(int64_t)); + memmove(times, times + skip, (size_t)(n - skip) * sizeof(int64_t)); + n -= skip; + } + h->seen = count; + return n; +} + +int hud_frames_info(const struct hud_frames *h, int32_t *info, char *engine, size_t engine_len) { + if (!capacity(h) || engine_len == 0) return 0; + for (int tries = 0; tries < 8; tries++) { + uint32_t seq = load32(h->map + 24); + if (seq & 1u) continue; + memcpy(&info[0], h->map + 12, 4); + memcpy(&info[1], h->map + 28, 16); + size_t n = engine_len - 1 < 40 ? engine_len - 1 : 40; + memcpy(engine, h->map + 44, n); + engine[n] = '\0'; + __atomic_thread_fence(__ATOMIC_ACQUIRE); + if (__atomic_load_n((const uint32_t *)(h->map + 24), __ATOMIC_RELAXED) == seq) return 1; + } + return 0; +} diff --git a/app/src/main/cpp/waylandcomp/src/hudframes.h b/app/src/main/cpp/waylandcomp/src/hudframes.h new file mode 100644 index 0000000000..d0b1ff5bd1 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/hudframes.h @@ -0,0 +1,16 @@ +#ifndef DROIDDECK_HUDFRAMES_H +#define DROIDDECK_HUDFRAMES_H + +#include +#include + +struct hud_frames; + +struct hud_frames *hud_frames_open(const char *path); +void hud_frames_close(struct hud_frames *h); +/* New frames since the last poll, oldest first; -1 while the file holds no valid ring. */ +int hud_frames_poll(struct hud_frames *h, int64_t *frametimes, int64_t *times, int max); +/* info: pid, output width, output height, refresh mHz, Steam focused. */ +int hud_frames_info(const struct hud_frames *h, int32_t *info, char *engine, size_t engine_len); + +#endif diff --git a/app/src/main/cpp/waylandcomp/src/hudframes_jni.c b/app/src/main/cpp/waylandcomp/src/hudframes_jni.c new file mode 100644 index 0000000000..7bd9149d98 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/hudframes_jni.c @@ -0,0 +1,55 @@ +#include +#include +#include + +#include "hudframes.h" + +JNIEXPORT jlong JNICALL +Java_com_droiddeck_launcher_hud_HudFrames_nativeOpen(JNIEnv *env, jclass clazz, jstring path) { + (void)clazz; + const char *p = path ? (*env)->GetStringUTFChars(env, path, NULL) : NULL; + if (!p) return 0; + struct hud_frames *h = hud_frames_open(p); + (*env)->ReleaseStringUTFChars(env, path, p); + return (jlong)(intptr_t)h; +} + +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_hud_HudFrames_nativeClose(JNIEnv *env, jclass clazz, jlong handle) { + (void)env; (void)clazz; + hud_frames_close((struct hud_frames *)(intptr_t)handle); +} + +JNIEXPORT jint JNICALL +Java_com_droiddeck_launcher_hud_HudFrames_nativePoll(JNIEnv *env, jclass clazz, jlong handle, + jlongArray frametimes, jlongArray times) { + (void)clazz; + struct hud_frames *h = (struct hud_frames *)(intptr_t)handle; + if (!h || !frametimes || !times) return -1; + jsize max = (*env)->GetArrayLength(env, frametimes); + jsize max2 = (*env)->GetArrayLength(env, times); + if (max2 < max) max = max2; + if (max <= 0) return -1; + int64_t *ft = malloc(sizeof(int64_t) * (size_t)max); + int64_t *tm = malloc(sizeof(int64_t) * (size_t)max); + int n = ft && tm ? hud_frames_poll(h, ft, tm, max) : -1; + if (n > 0) { + (*env)->SetLongArrayRegion(env, frametimes, 0, n, (const jlong *)ft); + (*env)->SetLongArrayRegion(env, times, 0, n, (const jlong *)tm); + } + free(ft); + free(tm); + return n; +} + +JNIEXPORT jstring JNICALL +Java_com_droiddeck_launcher_hud_HudFrames_nativeInfo(JNIEnv *env, jclass clazz, jlong handle, jintArray info) { + (void)clazz; + const struct hud_frames *h = (const struct hud_frames *)(intptr_t)handle; + if (!h || !info || (*env)->GetArrayLength(env, info) < 5) return NULL; + int32_t values[5]; + char engine[41]; + if (!hud_frames_info(h, values, engine, sizeof(engine))) return NULL; + (*env)->SetIntArrayRegion(env, info, 0, 5, (const jint *)values); + return (*env)->NewStringUTF(env, engine); +} diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 6159d45ca9..bba1da4476 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -90,7 +90,8 @@ import com.droiddeck.launcher.input.TouchscreenGestures import com.droiddeck.launcher.input.ScrollTouchGestures import com.droiddeck.launcher.runtime.LinuxRuntime import com.droiddeck.launcher.session.LoadingState -import com.droiddeck.launcher.session.PerfHud +import com.droiddeck.launcher.hud.FusionHudConfig +import com.droiddeck.launcher.hud.FusionHudHost import com.droiddeck.launcher.session.PerfMode import com.droiddeck.launcher.session.SteamRepair import com.droiddeck.launcher.session.GameEnvironmentStore @@ -158,7 +159,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private lateinit var surfaceView: SurfaceView private lateinit var sessionOverlay: ComposeView private lateinit var loading: LoadingState - private lateinit var hud: PerfHud + private lateinit var hud: FusionHudHost private lateinit var memoryHud: com.droiddeck.launcher.session.MemoryHud private var padBridge: PadBridge? = null private var joyConVr: com.droiddeck.launcher.input.JoyConVr? = null @@ -333,9 +334,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private var achievementsInFront by mutableStateOf(null) private var achievementsOpen by mutableStateOf(false) private var hudOn by mutableStateOf(true) - private var hudFps by mutableStateOf(true) - private var hudBattery by mutableStateOf(true) - private var hudGraph by mutableStateOf(true) + private var hudConfig by mutableStateOf>(emptyMap()) private var hudColor by mutableStateOf(SessionPrefs.HUD_COLOR_MINT) private var hudOpacity by mutableStateOf(SessionPrefs.HUD_OPACITY_DEFAULT) private var upscaler by mutableStateOf(0) @@ -641,7 +640,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { val needProton = protonUser && com.droiddeck.launcher.runtime.DesktopCatalog.protonSeedNeeded(this) if (needRuntime || needResume || needDesktop || needProton) installThenStart(needRuntime, needDesktop, needProton, needResume) } - hud = PerfHud(this) + hud = FusionHudHost(this) + hud.onConfigChanged = { hudConfig = FusionHudConfig.load(this) } + hud.attach(root, root.childCount) memoryHud = com.droiddeck.launcher.session.MemoryHud(this) hud.onPresentingWindowChanged = { if (FrameGen.engine(this) != FrameGen.ENGINE_OFF) CompositorHost.rearmFrameGen { applyFrameGen() } @@ -729,6 +730,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { onDispose { com.droiddeck.launcher.glasses.GlassesMenuMirror.setSessionMenuVisible(this@SessionActivity, false) } } androidx.compose.runtime.LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, pipUi) { updatePointerCapture() } + androidx.compose.runtime.LaunchedEffect(pipUi) { hud.setHidden(pipUi) } androidx.compose.runtime.LaunchedEffect(AgentGuest.steamKeyboard) { updateOnScreenControls() } androidx.compose.runtime.LaunchedEffect(picturePosition, SessionState.running, pipUi, cardboard.enabled) { applyGameAlignment() } DroidDeckTheme { @@ -744,9 +746,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) { CursorOverlay({ cursorPos }, cursorVisible, resources.displayMetrics.density, cursorImage, cursorHotX, cursorHotY, cursorImageScale) - val hudLines = listOf(hud.text, memoryHud.text).filter { it.isNotEmpty() } - if (hudLines.isNotEmpty() || hud.graph.size >= 2) - HudText(hudLines.joinToString("\n"), hud.graph, hudColor, hudOpacity) + if (memoryHud.text.isNotEmpty()) HudText(memoryHud.text, hudColor, hudOpacity) val phonePanel = glassesOutputActive && !loading.visible && !drawerOpen && !pcKeyboardOpen if (phonePanel) GlassesPhonePanel(glasses, steamVrStatus == SteamVr.Status.RUNNING, headTracking) if (trackingRecovery != null && !drawerOpen && !pcKeyboardOpen && !loading.visible) { @@ -943,11 +943,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { isHomeApp = isHomeApp, androidApps = androidApps, hudOn = hudOn, - hudFps = hudFps, - hudBattery = hudBattery, - hudGraph = hudGraph, - hudColor = hudColor, - hudOpacity = hudOpacity, + hudConfig = hudConfig, upscaler = upscaler, upscaleSharpness = upscaleSharpness, effects = effects, cardboard = cardboard, @@ -978,11 +974,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { secondScreenDisplays = secondScreenDisplays, selectedSecondScreenDisplay = selectedSecondScreenDisplay, onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() }, - onHudFps = { on -> SessionPrefs.setHudShowFps(this@SessionActivity, on); hudFps = on; hud.refresh() }, - onHudBattery = { on -> SessionPrefs.setHudShowBattery(this@SessionActivity, on); hudBattery = on; hud.refresh() }, - onHudGraph = { on -> SessionPrefs.setHudShowGraph(this@SessionActivity, on); hudGraph = on; hud.refresh() }, - onHudColor = { color -> SessionPrefs.setHudColor(this@SessionActivity, color); hudColor = color }, - onHudOpacity = { percent -> SessionPrefs.setHudOpacity(this@SessionActivity, percent); hudOpacity = percent }, + onHudSetting = { key, value -> hudConfig = FusionHudConfig.set(this@SessionActivity, key, value); hud.applyConfig() }, + onHudReset = { hudConfig = FusionHudConfig.reset(this@SessionActivity); hud.applyConfig() }, + onHudExport = { exportHudDiagnostics() }, onUpscaler = { m -> SessionPrefs.setUpscaler(this@SessionActivity, m); upscaler = m WaylandCompositor.nativeSetUpscaler(m) @@ -1604,6 +1598,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { else getString(R.string.load_starting_steam) } + private fun exportHudDiagnostics() { + glassesScope.launch { + val file = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { hud.exportDiagnostics() } + android.widget.Toast.makeText(this@SessionActivity, + if (file != null) getString(R.string.hud_export_done, file.path) else getString(R.string.hud_export_failed), + android.widget.Toast.LENGTH_LONG).show() + } + } + private fun shareCurrentSessionLogs() { val folder = SessionPaths.current() ?: SessionPaths.lastEnded() if (folder == null || !folder.isDirectory) { @@ -1629,9 +1632,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { unfoldedControlsWithController = SessionPrefs.unfoldedControlsWithController(this) picturePosition = SessionPrefs.picturePosition(this) hudOn = SessionPrefs.hudEnabled(this) - hudFps = SessionPrefs.hudShowFps(this) - hudBattery = SessionPrefs.hudShowBattery(this) - hudGraph = SessionPrefs.hudShowGraph(this) + hudConfig = FusionHudConfig.load(this) hudColor = SessionPrefs.hudColor(this) hudOpacity = SessionPrefs.hudOpacity(this) upscaler = SessionPrefs.upscaler(this) @@ -3280,6 +3281,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { super.onStart() if (runtimeRemovalBlocked) return started = true + if (::hud.isInitialized) hud.setBackgrounded(false) refreshActivityDisplayId() displayManager.registerDisplayListener(displayListener, Handler(Looper.getMainLooper())) for (name in arrayOf("peak_refresh_rate", "min_refresh_rate")) { @@ -3297,6 +3299,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun onStop() { if (runtimeRemovalBlocked) { super.onStop(); return } started = false + if (::hud.isInitialized) hud.setBackgrounded(true) updateHandCamera() displayManager.unregisterDisplayListener(displayListener) contentResolver.unregisterContentObserver(refreshSettingObserver) diff --git a/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckMark.kt b/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckMark.kt new file mode 100644 index 0000000000..dd21683f0e --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckMark.kt @@ -0,0 +1,53 @@ +package com.droiddeck.launcher.hud + +import android.graphics.Canvas +import android.graphics.Matrix +import android.graphics.Paint +import android.graphics.Path + +/** artwork/droiddeck-mark.svg: the split D with its circular cut-out and the blue orb. */ +internal object DroidDeckMark { + private const val VIEW_X = -55.98f + const val VIEW_W = 239.92f + const val VIEW_H = 223.72f + + private val body: Path by lazy { + val d = Path().apply { + moveTo(-31.98f, 0f) + lineTo(63.97f, 0f) + cubicTo(125.81f, 0f, 175.93f, 50.08f, 175.93f, 111.86f) + cubicTo(175.93f, 173.64f, 125.81f, 223.72f, 63.97f, 223.72f) + lineTo(-31.98f, 223.72f) + close() + } + val cut = Path().apply { + addCircle(63.98f, 111.86f, 71.81f, Path.Direction.CW) + addRect(56.055f, 0f, 71.885f, 45f, Path.Direction.CW) + addRect(56.055f, 178.72f, 71.885f, 223.72f, Path.Direction.CW) + } + d.op(cut, Path.Op.DIFFERENCE) + d.offset(-VIEW_X, 0f) + d + } + + private val scaled = Path() + private val matrix = Matrix() + private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL } + + fun widthFor(height: Float): Float = height * VIEW_W / VIEW_H + + /** Where the drawn mark starts and ends inside [widthFor]: the artwork has empty space on both sides. */ + fun inkLeftFor(height: Float): Float = (-31.98f - VIEW_X) * height / VIEW_H + fun inkRightFor(height: Float): Float = (175.93f - VIEW_X) * height / VIEW_H + + fun draw(canvas: Canvas, left: Float, top: Float, height: Float, bodyColor: Int, orbColor: Int) { + val s = height / VIEW_H + matrix.setScale(s, s) + matrix.postTranslate(left, top) + body.transform(matrix, scaled) + paint.color = bodyColor + canvas.drawPath(scaled, paint) + paint.color = orbColor + canvas.drawCircle(left + (63.98f - VIEW_X) * s, top + 111.86f * s, 55.98f * s, paint) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/hud/FusionHudConfig.kt b/app/src/main/java/com/droiddeck/launcher/hud/FusionHudConfig.kt new file mode 100644 index 0000000000..4ba8333bdb --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/hud/FusionHudConfig.kt @@ -0,0 +1,53 @@ +package com.droiddeck.launcher.hud + +import android.content.Context +import com.droiddeck.launcher.session.SessionPrefs + +/** FusionHUD's settings as one "key=value,…" string (FusionHudView.applyConfig), stored in SessionPrefs. */ +internal object FusionHudConfig { + /** Bannerlator's Fusion defaults (DeckOverlaySettings), with the FPS graph from the old DroidDeck HUD. */ + val DEFAULTS: Map = linkedMapOf( + "hudSize" to "minimal", "hudLocked" to "0", "hudScale" to "100", "hudOpacity" to "80", "hudColor" to "mid", + "hudOutline" to "40", "hudOutlineAccent" to "1", + "showFPS" to "1", "showFPSGraph" to "1", "showCPUUsage" to "1", "showCPULoad" to "1", "showGPULoad" to "1", + "showVram" to "1", "showRAM" to "1", "showPower" to "1", "showTemp" to "1", "showBatteryTemp" to "1", + "showGpuTemp" to "0", "showBattery" to "0", "showLow001" to "1", "fpsDecimal" to "1", "showPerCore" to "1", + "showSwap" to "1", "showNet" to "1", "showResolution" to "1", "showProton" to "1", "showSession" to "1", + "showClock" to "1", "showEngine" to "1", "showRenderer" to "1", "showGpuModel" to "1", + "tempUnit" to "c", "tempBands" to "1", "tempAuto" to "1", "tempRedCpu" to "90", "tempRedGpu" to "90", "tempRedBat" to "48", + ) + + /** Switches Bannerlator sets together (DeckOverlaySettings twins). */ + private val TWINS = mapOf("showCPUUsage" to "showCPULoad", "showTemp" to "showBatteryTemp", "showEngine" to "showRenderer") + + fun load(context: Context): MutableMap { + val values = LinkedHashMap(DEFAULTS) + val stored = SessionPrefs.fusionHudConfig(context) + if (stored == null) { + values["showFPS"] = flag(SessionPrefs.hudShowFps(context)) + values["showFPSGraph"] = flag(SessionPrefs.hudShowGraph(context)) + values["hudOpacity"] = SessionPrefs.hudOpacity(context).toString() + } else { + for (entry in KeyValueSet(stored)) if (entry.size == 2 && entry[0] in DEFAULTS) values[entry[0]] = entry[1] + } + return values + } + + fun encode(values: Map): String = values.entries.joinToString(",") { "${it.key}=${it.value}" } + + fun set(context: Context, key: String, value: String): Map { + val values = load(context) + if (key !in DEFAULTS) return values + values[key] = value + TWINS[key]?.let { values[it] = value } + SessionPrefs.setFusionHudConfig(context, encode(values)) + return values + } + + fun reset(context: Context): Map { + SessionPrefs.setFusionHudConfig(context, encode(DEFAULTS)) + return DEFAULTS + } + + private fun flag(on: Boolean) = if (on) "1" else "0" +} diff --git a/app/src/main/java/com/droiddeck/launcher/hud/FusionHudHost.kt b/app/src/main/java/com/droiddeck/launcher/hud/FusionHudHost.kt new file mode 100644 index 0000000000..69c0c3526f --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/hud/FusionHudHost.kt @@ -0,0 +1,232 @@ +package com.droiddeck.launcher.hud + +import android.content.Context +import android.os.Environment +import android.os.Handler +import android.os.Looper +import android.view.Choreographer +import android.view.View +import android.view.ViewGroup +import android.widget.FrameLayout +import com.droiddeck.launcher.gpu.FrameGen +import com.droiddeck.launcher.gpu.GpuInfo +import com.droiddeck.launcher.runtime.LinuxRuntime +import com.droiddeck.launcher.session.SessionPrefs +import com.droiddeck.launcher.wayland.WaylandCompositor +import java.io.File +import kotlin.math.roundToInt + +/** + * FusionHUD on the session screen, in place of the old text HUD: the view, the frame feed from gamescope + * (MangoHud's frame times) and MangoHud's readings, started with the session's first frame. + */ +class FusionHudHost(context: Context) { + private val context = context.applicationContext + private val handler = Handler(Looper.getMainLooper()) + private val feed = GameFrameFeed(File(LinuxRuntime.rootDir(this.context), HudFrames.PATH)) + private val readings = MangoReadings(File(this.context.filesDir, "session"), LinuxRuntime.rootDir(this.context)) + private var view: FusionHudView? = null + private var parent: ViewGroup? = null + private var running = false + private var hidden = false + private var backgrounded = false + private var polling = false + private var wantX = Float.NaN + private var wantY = Float.NaN + private var engine = "" + private var gpuName = "" + private var protonPid = 0 + private var proton = "" + @Volatile private var lastWindow: String? = null + + var onPresentingWindowChanged: (() -> Unit)? = null + + /** The HUD itself changed a setting: a tap cycles the size, a long press locks it. */ + var onConfigChanged: (() -> Unit)? = null + + private val listener = object : WaylandCompositor.GameListener { + override fun onGameSurface(window: String?, gpuName: String?) { + if (!gpuName.isNullOrBlank()) handler.post { this@FusionHudHost.gpuName = cleanGpuName(gpuName) } + if (window != null && window != lastWindow) { + lastWindow = window + handler.post { onPresentingWindowChanged?.invoke() } + } + } + + override fun onGameFrame() { + feed.onCompositorFrame(System.nanoTime()) + } + } + + private val frameCallback = object : Choreographer.FrameCallback { + override fun doFrame(frameTimeNanos: Long) { + if (!running || !polling) return + if (feed.poll(System.nanoTime())) view?.onFrames() + Choreographer.getInstance().postFrameCallback(this) + } + } + + private val enabled: Boolean + get() = SessionPrefs.hudEnabled(context) && + !File(Environment.getExternalStorageDirectory(), "Download/droiddeck-no-hud").exists() + + /** Adds the HUD to [root] at [index] (above the game surface, under the session overlay). */ + fun attach(root: FrameLayout, index: Int) { + if (view != null) return + val hud = FusionHudView(root.context) + hud.setFrameStats(feed.stats) + hud.setMangoReadings(readings) + hud.setGpuModel(cleanGpuName(GpuInfo.detect().displayName(context))) + hud.onRefresh = Runnable { refreshLabels(hud) } + hud.setOnMovedListener { x, y -> + wantX = x; wantY = y + keepOnScreen(hud) + wantX = hud.x; wantY = hud.y + SessionPrefs.setFusionHudPosition(context, hud.x, hud.y) + } + hud.setOnSizeCycledListener { size -> FusionHudConfig.set(context, "hudSize", size); onConfigChanged?.invoke() } + hud.setOnLockChangedListener { locked -> + FusionHudConfig.set(context, "hudLocked", if (locked) "1" else "0") + onConfigChanged?.invoke() + } + hud.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> if (!hud.isDragging) keepOnScreen(hud) } + hud.visibility = View.GONE + val margin = (16 * root.resources.displayMetrics.density).roundToInt() + root.addView(hud, index, FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { + leftMargin = margin + topMargin = margin + }) + SessionPrefs.fusionHudPosition(context)?.let { (x, y) -> wantX = x; wantY = y; hud.post { keepOnScreen(hud) } } + view = hud + parent = root + applyConfig() + } + + fun applyConfig() { + view?.applyConfig(FusionHudConfig.encode(FusionHudConfig.load(context))) + } + + fun refresh() { + applyConfig() + if (!enabled) stop() else if (!running) start() + } + + fun start() { + if (running || !enabled || view == null) return + running = true + WaylandCompositor.setGameListener(listener) + applyShown() + } + + fun stop() { + running = false + showing = false + polling = false + Choreographer.getInstance().removeFrameCallback(frameCallback) + WaylandCompositor.clearGameListener(listener) + feed.close() + view?.visibility = View.GONE + } + + /** Picture-in-picture and similar: keep running, draw nothing. */ + fun setHidden(hide: Boolean) { + hidden = hide + applyShown() + } + + /** The session screen is stopped (another app in front): draw nothing and stop reading sensors. */ + fun setBackgrounded(stopped: Boolean) { + backgrounded = stopped + applyShown() + } + + private fun applyShown() { + if (!running) return + val show = !hidden && !backgrounded + view?.visibility = if (show) View.VISIBLE else View.GONE + showing = show + // Frames are read once per display frame only while the HUD is drawn. + if (show != polling) { + polling = show + if (show) Choreographer.getInstance().postFrameCallback(frameCallback) + else Choreographer.getInstance().removeFrameCallback(frameCallback) + } + } + + /** A sensor report (FusionHUD's diagnostics) in Downloads/DroidDeck; null when it can't be written. */ + fun exportDiagnostics(): File? = runCatching { + val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "DroidDeck") + dir.mkdirs() + val stamp = java.text.SimpleDateFormat("yyyyMMdd-HHmmss", java.util.Locale.US).format(java.util.Date()) + val file = File(dir, "HUD-diagnostics-$stamp.txt") + // Its own reader: the HUD's CPU load is the change since its previous sample, which an export must + // not move. Two samples half a second apart, MangoHud's sampling period. + val metrics = HudMetrics(context) + metrics.setMangoReadings(MangoReadings(File(context.filesDir, "session"), LinuxRuntime.rootDir(context))) + metrics.snapshot() + Thread.sleep(500) + val mango = metrics.snapshot() + file.writeText(metrics.also { it.setMangoReadings(null) }.buildDiagnosticsReport(context) + "\n== As the HUD shows them (MangoHud's sources) ==\n" + + "CPU ${mango.cpuPercent}% ${mango.cpuTempC}°C, GPU ${mango.gpuPercent}% ${mango.gpuClockMhz}MHz ${mango.gpuTempC}°C, " + + "RAM ${mango.ramUsedText()}/${mango.ramTotalText()}, VRAM ${mango.vramText()}, battery ${mango.battery.percent}% " + + "${mango.battery.watts}W charging=${mango.battery.charging}\n" + + "CPU temperature zones: ${LinuxRuntime.cpuTempZones().joinToString { it.name }}\n" + + "Frames: ${if (feed.engine.isNotEmpty() || feed.pid > 0) "gamescope (pid ${feed.pid}, ${feed.engine})" else "compositor"}, " + + "fps ${feed.stats.fps}\n") + file + }.getOrNull() + + private fun refreshLabels(hud: FusionHudView) { + if (feed.engine.isNotBlank() && !feed.steamFocused) engine = feed.engine + hud.setEngineLabel(engine) + if (gpuName.isNotBlank()) hud.setGpuModel(gpuName) + hud.setResolution(if (feed.outputWidth > 0 && feed.outputHeight > 0) buildString { + append(feed.outputWidth).append('x').append(feed.outputHeight) + if (feed.refreshMilliHz > 0) append(" @ ").append((feed.refreshMilliHz + 499) / 1000).append("Hz") + } else "") + val pid = feed.pid + if (pid > 0 && pid != protonPid) { + protonPid = pid + proton = protonName(pid) ?: proton + } + hud.setWineVersion(proton) + hud.setPresentedFps(presentedFps()) + } + + private fun presentedFps(): Float { + if (FrameGen.mode(context).engine == FrameGen.ENGINE_OFF) return 0f + val stats = runCatching { WaylandCompositor.nativeFrameGenStats() }.getOrNull() ?: return 0f + return if (stats.size > 3 && stats[3] > 1f) stats[3] else 0f + } + + // The HUD is clamped from where the user left it (wantX/wantY, set on a drop or restore), not from where + // it is drawn: a window that shrinks and grows back (picture-in-picture, a fold) must not leave it in the + // corner the small window pushed it to. + private fun keepOnScreen(v: View) { + val p = v.parent as? View ?: return + if (p.width <= 0 || p.height <= 0 || v.width <= 0 || v.height <= 0) return + if (wantX.isNaN()) { wantX = v.x; wantY = v.y } + val maxX = (p.width - v.width).toFloat().coerceAtLeast(0f) + val maxY = (p.height - v.height).toFloat().coerceAtLeast(0f) + val x = wantX.coerceIn(0f, maxX) + val y = wantY.coerceIn(0f, maxY) + if (v.x != x) v.x = x + if (v.y != y) v.y = y + } + + companion object { + /** True while the HUD is on screen; DroidDeck keeps sampling VRAM for it (GpuMemComponent). */ + @Volatile @JvmStatic var showing = false + private set + + /** "Adreno (TM) 750" as the driver names it, "Adreno 750" as DroidDeck does elsewhere. */ + internal fun cleanGpuName(name: String): String = name.replace("(TM)", "").replace(Regex("\\s+"), " ").trim() + + /** The Proton build of a game process: the first STEAM_COMPAT_TOOL_PATHS entry's folder. */ + internal fun protonName(pid: Int): String? = runCatching { + val environ = File("/proc/$pid/environ").readBytes().toString(Charsets.UTF_8).split('\u0000') + val paths = environ.firstOrNull { it.startsWith("STEAM_COMPAT_TOOL_PATHS=") }?.substringAfter('=') ?: return null + paths.split(':').firstOrNull { it.isNotBlank() }?.trimEnd('/')?.substringAfterLast('/') + }.getOrNull()?.takeIf { it.isNotBlank() } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/hud/FusionHudModels.kt b/app/src/main/java/com/droiddeck/launcher/hud/FusionHudModels.kt new file mode 100644 index 0000000000..ea4c336afe --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/hud/FusionHudModels.kt @@ -0,0 +1,86 @@ +/* + * FusionHUD — a lightweight in-game performance HUD for Android / Winlator overlays. + * Copyright (C) The412Banner + * + * Licensed under the GNU General Public License v3.0 (see LICENSE), with an + * ADDITIONAL attribution requirement under GPL-3.0 §7(b) (see ATTRIBUTION.md): + * any use, fork, or distribution must preserve credit to "The412Banner" and a + * link to https://github.com/The412Banner/FusionHUD in the project documentation + * AND in the in-app credits/about screen. + * + * Ported to DroidDeck from FusionHUD (Bannerlator's HUD); DroidDeck changes are marked in the code. + */ + +package com.droiddeck.launcher.hud + +/** + * Size modes for the Fusion HUD (the 4th selectable in-game overlay style). One shared color-coded + * visual language, four amounts of detail — see the approved mockup. The config value is the lower-case + * token stored under the `hudSize` key; the label is the user-facing string. + */ +enum class FusionSize(val token: String, val label: String) { + FULL("full", "Full"), + TILES("tiles", "Tiles"), + PILL("pill", "Pill"), + MINIMAL("minimal", "Minimal"), + MEGA("mega", "Mega"); + + /** Next size in the tap-cycle: Full → Tiles → Pill → Minimal → Mega → Full. */ + fun next(): FusionSize { + val all = values() + return all[(ordinal + 1) % all.size] + } + + /** + * The metric toggle chips this size actually renders — the SINGLE source of truth queried by BOTH + * config surfaces ({@code FpsCounterConfigDialog} + in-game {@code XServerDrawer} HudContent) so the + * chip list can't drift from what the view draws. Chip ids are the chip LABELS used in the UI. + * (Hiding a chip is purely UI; buildConfig() still emits every key — strip-invariant.) + */ + fun supportedChips(): Set = when (this) { + MINIMAL -> MINIMAL_CHIPS + PILL -> PILL_CHIPS + FULL, TILES -> STANDARD_CHIPS + MEGA -> MEGA_CHIPS + } + + companion object { + fun from(token: String?): FusionSize = + values().firstOrNull { it.token.equals(token, ignoreCase = true) } ?: FULL + + // Chip-label ids (must match the labels the config UIs build). "Clock" is a small subtle + // corner readout available in EVERY size, so it's in all sets. + // The API/engine label ("Engine" chip) shows on the FPS row in EVERY size, so it's in all sets. + // "Wrapper" and "DX ver" are Mega-only: the wrapper appears solely below Mega's frametime graph, + // and "DX ver" gates the DX-version suffix on Mega's FPS-row engine label. + val MINIMAL_CHIPS = setOf("FPS", "FPS graph", "0.01% low", "FPS .1", "Engine", "Clock") + val PILL_CHIPS = setOf("FPS", "FPS graph", "GPU", "CPU", "VRAM", "RAM", "Battery", "GPU model", "FPS .1", "Engine", "Clock") + val STANDARD_CHIPS = setOf( + "FPS", "FPS graph", "GPU", "GPU temp", "CPU", "VRAM", "RAM", "Power", "Temp", + "Battery", "GPU model", "Engine", "0.01% low", "FPS .1", "Clock", + ) + val MEGA_ONLY = setOf( + "Per-core", "Swap", "Network", "Resolution", "Proton", "Wrapper", "DX ver", "Session", + ) + val MEGA_CHIPS = STANDARD_CHIPS + MEGA_ONLY + } +} + +/** + * The Wayland HDR state the Fusion HUD shows on its own line, directly under the latency · display-server + * line (the host sets it with [FusionHudView.setHdrState]). [NONE] = no line at all: every session whose + * HDR gate is closed (X11, SDR screens, HDR off) keeps the HUD exactly as it was. + */ +object FusionHdr { + const val NONE = 0 + const val ON = 1 // HDR frames on screen with HDR headroom + const val NO_HEADROOM = 2 // HDR frames on screen, but the display gives them no headroom (5 s+) + const val OFF = 3 // the drawer's HDR output switch is off (tone-mapped to SDR) + const val READY = 4 // HDR open for the session, no HDR frames on screen right now + const val TONEMAPPED = 5 // HDR output on, but the frames are shown tone-mapped (frame generation + // on a screen that offers no HDR10 swapchain) + const val NOT_ON_THIS_SCREEN = 6 // HDR open for the session, but the screen the game is on NOW + // reports no HDR10 (the TV was unplugged mid-game). The offer to the + // game cannot be withdrawn once made, so the gate stays open for the + // session — but "ready" would be a lie on a panel that cannot show it. +} diff --git a/app/src/main/java/com/droiddeck/launcher/hud/FusionHudView.kt b/app/src/main/java/com/droiddeck/launcher/hud/FusionHudView.kt new file mode 100644 index 0000000000..95d0581132 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/hud/FusionHudView.kt @@ -0,0 +1,1373 @@ +/* + * FusionHUD — a lightweight in-game performance HUD for Android / Winlator overlays. + * Copyright (C) The412Banner + * + * Licensed under the GNU General Public License v3.0 (see LICENSE), with an + * ADDITIONAL attribution requirement under GPL-3.0 §7(b) (see ATTRIBUTION.md): + * any use, fork, or distribution must preserve credit to "The412Banner" and a + * link to https://github.com/The412Banner/FusionHUD in the project documentation + * AND in the in-app credits/about screen. + * + * Ported to DroidDeck from FusionHUD (Bannerlator's HUD); DroidDeck changes are marked in the code. + */ + +package com.droiddeck.launcher.hud + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.BlurMaskFilter +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.graphics.Path +import android.graphics.RectF +import android.graphics.Typeface +import android.text.format.DateFormat +import android.view.MotionEvent +import android.view.View +import androidx.annotation.VisibleForTesting +import androidx.compose.ui.graphics.toArgb +import com.droiddeck.launcher.ui.Themes +import java.util.Date +import java.util.Locale +import java.util.function.BiConsumer +import java.util.function.Consumer +import kotlin.math.max +import kotlin.math.min +import kotlin.math.roundToInt +import kotlin.math.sqrt +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull + +/** + * Fusion HUD — the 4th selectable in-game overlay. One color-coded visual language rendered at four + * SIZE modes (Full / Tiles / Pill / Minimal / Mega), all driven by [FrameStats] (gamescope's frame times + * read by MangoHud's rules) + a single cached [HudMetrics.Snapshot]. Pure Canvas drawing. + * + * DroidDeck: the readouts refresh every 500 ms (MangoHud's sampling period) on a Main-dispatcher + * coroutine, collecting the snapshot on Dispatchers.IO; the frame graph is redrawn whenever new frames + * arrive ([onFrames]), as MangoHud draws it. + * + * Gestures go through [HudLockController]: long-press toggles the position lock (with a lock/unlock + * badge fade), a tap cycles the size (Full→Tiles→Pill→Minimal→Full), and a drag repositions — tap + + * drag are frozen while locked. + */ +class FusionHudView(context: Context) : View(context) { + + private var frames: FrameStats? = null + internal fun setFrameStats(stats: FrameStats?) { frames = stats } + internal fun setMangoReadings(readings: MangoReadings?) { metrics.setMangoReadings(readings) } + + // Frames per second actually reaching the panel while DroidDeck's frame generation adds frames the + // game never made; 0 = nothing is adding frames, and the readout is the game's rate alone. + private var presentedFps = 0f + fun setPresentedFps(fps: Float) { presentedFps = fps } + + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + private var updateJob: Job? = null + private val metrics = HudMetrics(context) + + private val density = resources.displayMetrics.density + + // ---- Config ----------------------------------------------------------- + private var size = FusionSize.FULL + private var scale = 1f + private var bgOpacity = 0.8f + private var outlineIntensity = 0.4f + private var outlineFollowAccent = true + private var colorIntensity = 1f + private var tempDisplay = HudMetrics.TempDisplay.from(null) + + private var showFPS = true + private var showEngine = true + private var showGpuModel = true + private var showCPU = true + private var showGPU = true + private var showCpuTemp = true + private var showGpuTemp = false + private var showVram = true + private var showRAM = true + private var showBattery = true + private var showPower = true + private var showBatteryTemp = false + private var showGraph = false + private var showLow001 = true + private var fpsDecimal = true + private var showClockTime = true // subtle corner/footer clock, available in EVERY size + // Mega-only rows + private var showPerCore = true + private var showSwap = true + private var showNet = true + private var showResolution = true + private var showProton = true + private var showWrapper = true + private var showDxVer = true + private var showSession = true + + private var engineLabel = "" + private var displayServer = "" // "X11" / "Wayland": which display server the game runs on + private var hdrState = FusionHdr.NONE // Wayland HDR, on its own line under latency · display server + private var gpuModel = "" + // The GPU name a Wayland session reports to games instead of the real adapter ("" = none). It has + // to travel separately from gpuModel: Wayland hands the spoof to DXVK and leaves the Vulkan device + // alone, so everything the host reads back is still the real chip. On X11 the driver wrapper renames + // the device itself, so there gpuModel already IS the spoofed name and this stays empty. + private var gpuSpoofName = "" + // Stack-layer version strings (Mega bottom band + DX version on the engine row); fed by the host. + private var wineVersion = "" // "Proton 10.0-4" + private var graphicsWrapper = "" // graphics-driver wrapper package, e.g. "GameNative", "bcn_layer 20260719" + private var dxvkVersion = "" // DXVK version, appended to a DXVK engine row + private var vkd3dVersion = "" // VKD3D version, appended to a VKD3D engine row + + // ---- Live data (updated on the refresh coroutine, read on draw) -------- + private var snap: HudMetrics.Snapshot? = null + private var fpsNow = 0f + private var fpsAvg = 0f + private var lows: FrameStats.Lows = FrameStats.Lows.EMPTY + private var graphMinMs = 0f + private var graphMaxMs = 0f + private val graphBuf = FloatArray(FrameStats.GRAPH_FRAMES) + private val graphPath = Path() + private var resolution = "" + + // DroidDeck look: the theme's main colour for the FPS label, graph and accent outline, the theme's + // surface behind the readouts, a DroidDeck header (wordmark) on Full/Tiles/Minimal/Mega and the logo + // chip on the Pill. + private var accent = 0xFF1A9FFF.toInt() + private var surfaceRgb = 0x121417 + private var headerMark: RectF? = null + private var chipRect: RectF? = null + + // Every size sits in the DroidDeck mark's D: a straight left side split by the orb, round on the + // right. Its fixed layers (fill, header band, watermark, glowing outline) go into a bitmap, because + // Android before 9 skips glow on shapes drawn with hardware acceleration. + private var dPanel: RectF? = null + private var dRadius = 0f + private var dDividerTop = -1f + private var dFrame: Bitmap? = null + private var dFrameKey = "" + private val glowPaint = Paint(Paint.ANTI_ALIAS_FLAG) + + // ---- Colors (mockup) -------------------------------------------------- + private val colGpu = 0xFF5EE08A.toInt() + private val colCpu = 0xFF58A6FF.toInt() + private val colVram = 0xFFC98BFF.toInt() + private val colRam = 0xFFFF7BC0.toInt() + private val colBat = 0xFFFFAB5E.toInt() + private var colFps = 0xFF1A9FFF.toInt() + private var colGraph = 0xFF5CB8FF.toInt() + private val colValue = 0xFFF2F5F9.toInt() + private val colDim = 0xFF9AA4B2.toInt() + private val colLo = 0xFFE4E8EE.toInt() + private val colDisp = 0xFF4DD0E1.toInt() // display server (X11 / Wayland) + private val colHdr = 0xFFFFD54F.toInt() // HDR on screen + + // ---- Paints ----------------------------------------------------------- + private val measurePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + typeface = Typeface.create(Typeface.MONOSPACE, Typeface.BOLD) + } + private val drawPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + typeface = Typeface.create(Typeface.MONOSPACE, Typeface.BOLD) + } + private val bgPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL } + private val strokePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE } + private val tilePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL } + private val graphPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + style = Paint.Style.STROKE; strokeCap = Paint.Cap.ROUND; strokeJoin = Paint.Join.ROUND + color = colGraph + } + private val headerPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL } + private val wordmarkPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + typeface = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD) + } + + // ---- Built geometry --------------------------------------------------- + private class Glyph(val x: Float, val baseline: Float, val text: String, val color: Int, val sizePx: Float, val sans: Boolean = false, val glow: Boolean = false) { + fun moved(dx: Float, dy: Float) = Glyph(x + dx, baseline + dy, text, color, sizePx, sans, glow) + } + private class Span(val text: String, val color: Int, val sizePx: Float, val glow: Boolean = false) + /** + * A "label + value-run" row for the aligned grid sizes (Full / Mega). When [inline] is true the row + * opts OUT of the shared label column — its value run is placed directly after the label — so a long + * label (the graphics-wrapper on the FPS row) can't widen the column and shove every value right. + */ + private class HudRow(val label: Span, val vals: List, val inline: Boolean = false) + private val glyphs = ArrayList() + private val tileRects = ArrayList() + private var graphRect: RectF? = null + private var contentW = 0f + private var contentH = 0f + + // ---- Listeners -------------------------------------------------------- + private var onMovedListener: BiConsumer? = null + private var onSizeCycledListener: Consumer? = null + private var onLockChangedListener: Consumer? = null + fun setOnMovedListener(l: BiConsumer?) { onMovedListener = l } + fun setOnSizeCycledListener(l: Consumer?) { onSizeCycledListener = l } + fun setOnLockChangedListener(l: Consumer?) { onLockChangedListener = l } + + private val lockController = HudLockController(context, this, object : HudLockController.Callbacks { + override fun onTap() { cycleSize() } + override fun onMoved(x: Float, y: Float) { onMovedListener?.accept(x, y) } + override fun onLockChanged(locked: Boolean) { onLockChangedListener?.accept(locked) } + }) + + // ---- Public surface (symmetric with the other overlays) --------------- + fun setEngineLabel(s: String?) { if ((s ?: "") != engineLabel) { engineLabel = s ?: ""; post { rebuildAndInvalidate() } } } + fun setGpuModel(s: String?) { if ((s ?: "") != gpuModel) { gpuModel = s ?: ""; post { rebuildAndInvalidate() } } } + /** This session's Wayland GPU-name spoof (null / empty = none, the default): the GPU row names it + * in place of the real model, marked so it can't be read as the chip that is really rendering. */ + fun setGpuSpoofName(s: String?) { gpuSpoofName = s ?: ""; post { rebuildAndInvalidate() } } + fun setDisplayServer(s: String?) { displayServer = s ?: ""; post { rebuildAndInvalidate() } } + /** [FusionHdr] code; [FusionHdr.NONE] (the default) draws no HDR line anywhere. Any thread. */ + fun setHdrState(state: Int) { + val v = if (state in FusionHdr.ON..FusionHdr.NOT_ON_THIS_SCREEN) state else FusionHdr.NONE + post { if (v != hdrState) { hdrState = v; rebuildAndInvalidate() } } + } + fun setWineVersion(s: String?) { if ((s ?: "") != wineVersion) { wineVersion = s ?: ""; post { rebuildAndInvalidate() } } } + fun setGraphicsWrapper(s: String?) { graphicsWrapper = s ?: ""; post { rebuildAndInvalidate() } } + fun setDxWrapper(dxvk: String?, vkd3d: String?) { + dxvkVersion = dxvk ?: ""; vkd3dVersion = vkd3d ?: ""; post { rebuildAndInvalidate() } + } + + /** The game's output from gamescope ("1280x720 @ 144Hz"), as MangoHud shows it; "" = this display. */ + fun setResolution(s: String?) { resolution = s ?: "" } + + private val periodDone = Channel(Channel.CONFLATED) + private var seenFpsUpdates = 0L + + /** New frames arrived: redraw the graph (MangoHud redraws it every frame), and the readouts when a + * sampling period completed, at the moment MangoHud redraws its own. */ + fun onFrames() { + val updates = frames?.fpsUpdates ?: 0L + if (updates != seenFpsUpdates) { + seenFpsUpdates = updates + periodDone.trySend(Unit) + } + if (graphRect != null) invalidate() + } + + /** Fusion has no orientation (tap cycles size instead); kept for a symmetric host surface. */ + fun setVertical(vertical: Boolean) { /* no-op */ } + fun isVertical(): Boolean = false + + private fun cycleSize() { + size = size.next() + onSizeCycledListener?.accept(size.token) + rebuildAndInvalidate() + } + + fun applyConfig(configString: String?) { + if (configString.isNullOrEmpty()) return + val cfg = KeyValueSet(configString) + + size = FusionSize.from(cfg.get("hudSize", "minimal")) + showFPS = cfg.get("showFPS", "1") == "1" + showEngine = cfg.get("showEngine", "1") == "1" + showGpuModel = cfg.get("showGpuModel", "1") == "1" + showCPU = cfg.get("showCPUUsage", cfg.get("showCPULoad", "1")) == "1" + showGPU = cfg.get("showGPULoad", "1") == "1" + showCpuTemp = cfg.get("showTemp", "1") == "1" + showGpuTemp = cfg.get("showGpuTemp", "0") == "1" + showVram = cfg.get("showVram", "1") == "1" + showRAM = cfg.get("showRAM", "1") == "1" + showBattery = cfg.get("showBattery", "1") == "1" + showPower = cfg.get("showPower", "1") == "1" + showBatteryTemp = cfg.get("showBatteryTemp", "0") == "1" + showGraph = cfg.get("showFPSGraph", "0") == "1" + showLow001 = cfg.get("showLow001", "1") == "1" + fpsDecimal = cfg.get("fpsDecimal", "1") == "1" + showClockTime = cfg.get("showClock", "1") == "1" // Fusion clock defaults ON + showPerCore = cfg.get("showPerCore", "1") == "1" + showSwap = cfg.get("showSwap", "1") == "1" + showNet = cfg.get("showNet", "1") == "1" + showResolution = cfg.get("showResolution", "1") == "1" + showProton = cfg.get("showProton", "1") == "1" + showWrapper = cfg.get("showWrapper", "1") == "1" + showDxVer = cfg.get("showDxVer", "1") == "1" + showSession = cfg.get("showSession", "1") == "1" + tempDisplay = HudMetrics.TempDisplay.from(cfg) + lockController.setLocked(cfg.get("hudLocked", "0") == "1") + + colorIntensity = when (cfg.get("hudColor", "vivid")) { + "soft" -> 0.72f; "mid" -> 0.88f; else -> 1.0f + } + outlineIntensity = (parseOutline(cfg.get("hudOutline", "40")) / 100f).coerceIn(0f, 1f) + outlineFollowAccent = cfg.get("hudOutlineAccent", "1") == "1" + scale = (parseIntOr(cfg.get("hudScale", "100"), 100).coerceIn(50, 200)) / 100f + bgOpacity = (parseIntOr(cfg.get("hudOpacity", "80"), 80).coerceIn(0, 100)) / 100f + applyTheme() + + rebuildAndInvalidate() + } + + // ---- Lifecycle: self-refresh ------------------------------------------ + override fun onAttachedToWindow() { + super.onAttachedToWindow() + if (isShown) startUpdates() + } + + override fun onDetachedFromWindow() { + stopUpdates() + super.onDetachedFromWindow() + } + + // The host hides the HUD with GONE (HUD off, picture-in-picture) and keeps it attached: read the + // sensors only while it shows. + override fun onVisibilityChanged(changedView: View, visibility: Int) { + super.onVisibilityChanged(changedView, visibility) + if (isAttachedToWindow && isShown) startUpdates() else stopUpdates() + } + + private fun stopUpdates() { + updateJob?.cancel(); updateJob = null + } + + private fun startUpdates() { + if (updateJob?.isActive == true) return + updateJob = scope.launch { + while (isActive) { + val stats = frames + val now = System.nanoTime() + val collected = withContext(Dispatchers.IO) { + Pair(metrics.snapshot(), stats?.lows(now) ?: FrameStats.Lows.EMPTY) + } + snap = collected.first + lows = collected.second + fpsNow = stats?.fps ?: 0f + fpsAvg = stats?.averageFps() ?: 0f + graphMinMs = stats?.graphMinMs() ?: 0f + graphMaxMs = stats?.graphMaxMs() ?: 0f + onRefresh?.run() + rebuildAndInvalidate() + // Without frames (a still screen) MangoHud redraws nothing; the HUD keeps refreshing. + withTimeoutOrNull(REFRESH_MS) { periodDone.receive() } + } + } + } + + /** Runs on the main thread just before each readout refresh, for the host's labels. */ + var onRefresh: Runnable? = null + + private fun applyTheme() { + val palette = Themes.current(context) + accent = palette.primary.toArgb() + surfaceRgb = palette.surface.toArgb() and 0xFFFFFF + colFps = accent + colGraph = lighten(accent, 0.3f) + } + + private fun lighten(color: Int, amount: Float): Int = Color.rgb( + (Color.red(color) + (255 - Color.red(color)) * amount).roundToInt(), + (Color.green(color) + (255 - Color.green(color)) * amount).roundToInt(), + (Color.blue(color) + (255 - Color.blue(color)) * amount).roundToInt(), + ) + + private fun rebuildAndInvalidate() { + rebuild() + requestLayout() + invalidate() + } + + // ---- Text helpers ----------------------------------------------------- + private fun blend(color: Int): Int { + val i = colorIntensity.coerceIn(0f, 1f) + if (i >= 0.999f) return color + val hsv = FloatArray(3) + Color.colorToHSV(color, hsv) + hsv[1] *= i + return Color.HSVToColor(Color.alpha(color), hsv) + } + + private fun sp(v: Float) = v * density * scale + private fun measure(text: String, sizePx: Float): Float { measurePaint.textSize = sizePx; return measurePaint.measureText(text) } + private fun lineH(sizePx: Float): Float { measurePaint.textSize = sizePx; val fm = measurePaint.fontMetrics; return fm.descent - fm.ascent } + private fun ascent(sizePx: Float): Float { measurePaint.textSize = sizePx; return measurePaint.fontMetrics.ascent } + + private fun runWidth(spans: List): Float { + var w = 0f + for (s in spans) w += measure(s.text, s.sizePx) + return w + } + + private fun placeRun(startX: Float, baseline: Float, spans: List, glow: Boolean = false): Float { + var x = startX + for (s in spans) { + glyphs.add(Glyph(x, baseline, s.text, blend(s.color), s.sizePx, glow = glow || s.glow)) + x += measure(s.text, s.sizePx) + } + return x + } + + private fun one(v: Float): String = + if (fpsDecimal) String.format(Locale.US, "%.1f", v) else v.roundToInt().toString() + + // Shows "30->118" while something downstream of the game is adding frames. + // The game's own rate stays visible next to the panel rate, because the gap + // between the two is precisely what frame generation is doing. + private fun fpsText(v: Float): String = + if (differs(v)) "${one(v)}\u2192${one(presentedFps)}" else one(v) + + // Either direction: up = frames added (LSFG Native), down = frames lost + // between the guest and the panel, which is the failure win-fg can hit + // and which a single number hides completely. + private fun differs(v: Float): Boolean = + presentedFps > 0f && kotlin.math.abs(presentedFps - v) > maxOf(1f, v * 0.10f) + + private fun fmt1(v: Float): String = String.format(Locale.US, "%.1f", v) + private fun lowText(v: Float): String? = if (v <= 0f) null else fmt1(v) + + // number (white, or "—" muted when null) + unit (muted, smaller) + private fun numUnit(num: String?, unit: String, numPx: Float, unitPx: Float): List = + if (num == null) listOf(Span("—", colDim, numPx), Span(unit, colDim, unitPx)) + else listOf(Span(num, colValue, numPx), Span(unit, colDim, unitPx)) + + // "0.2GiB"/"75%"/"1938MHz" → white number + muted suffix + private fun valueUnit(text: String, numPx: Float, unitPx: Float): List { + val i = text.indexOfFirst { !(it.isDigit() || it == '.' || it == '-') } + return if (i <= 0) listOf(Span(text, colValue, numPx)) + else listOf(Span(text.substring(0, i), colValue, numPx), Span(text.substring(i), colDim, unitPx)) + } + + private fun tempSpans(c: Int?, sensor: HudMetrics.TempSensor, numPx: Float, unitPx: Float): List { + if (c == null) return emptyList() + val txt = HudMetrics.formatTemp(c.toFloat(), tempDisplay, false) // "81°C" + val col = HudMetrics.tempColor( + c.toFloat(), metrics.resolveThresholds(sensor, tempDisplay), tempDisplay, colValue) + val i = txt.indexOf('°') + return if (i <= 0) listOf(Span(txt, col, numPx)) + else listOf(Span(txt.substring(0, i), col, numPx), Span(txt.substring(i), colDim, unitPx)) + } + + private fun gap(unitPx: Float) = Span(" ", colDim, unitPx) + + /** The frame-rate number in neon, as on Minimal. */ + private fun glowing(spans: List): List = + spans.mapIndexed { i, s -> if (i == 0) Span(s.text, s.color, s.sizePx, glow = true) else s } + + // ---- Wayland HDR state (one line of its own; nothing at all for FusionHdr.NONE) ---- + /** The state as a full line: "HDR", "HDR (no headroom)", "HDR off", "HDR ready", "HDR tone-mapped", + * "HDR not on this screen". */ + private fun hdrLine(px: Float): List = when (hdrState) { + FusionHdr.ON -> listOf(Span("HDR", colHdr, px)) + FusionHdr.NO_HEADROOM -> listOf(Span("HDR", colHdr, px), Span(" (no headroom)", colBat, px)) + FusionHdr.OFF -> listOf(Span("HDR off", colDim, px)) + FusionHdr.READY -> listOf(Span("HDR ready", colDim, px)) + FusionHdr.TONEMAPPED -> listOf(Span("HDR", colDim, px), Span(" tone-mapped", colBat, px)) + FusionHdr.NOT_ON_THIS_SCREEN -> listOf(Span("HDR", colDim, px), Span(" not on this screen", colBat, px)) + else -> emptyList() + } + /** The value after an "HDR" label (Full / Mega): "on", "no headroom", "off", "ready", "tone-mapped", + * "not on this screen". */ + private fun hdrValue(px: Float): List = when (hdrState) { + FusionHdr.ON -> listOf(Span("on", colHdr, px)) + FusionHdr.NO_HEADROOM -> listOf(Span("no headroom", colBat, px)) + FusionHdr.OFF -> listOf(Span("off", colDim, px)) + FusionHdr.READY -> listOf(Span("ready", colDim, px)) + FusionHdr.TONEMAPPED -> listOf(Span("tone-mapped", colBat, px)) + FusionHdr.NOT_ON_THIS_SCREEN -> listOf(Span("not on this screen", colBat, px)) + else -> emptyList() + } + private fun hdrText(): String = hdrLine(1f).joinToString("") { it.text } + + // ---- GPU model (with the Wayland GPU-name spoof) ---- + /** What the GPU row names: the spoofed GPU when this session reports one, else the real model. */ + private fun gpuNameText(): String = gpuSpoofName.ifBlank { gpuModel } + /** The GPU row's value run. A spoofed name carries a marker in the same warning colour the HDR line + * qualifies its state with, so the row can't be read as the chip that is really rendering: + * "GeForce GTX 1080 (spoof)", and where the line is tightest (the pill) "GeForce GTX 1080 spoof". */ + private fun gpuModelSpans(px: Float, color: Int, compact: Boolean = false): List { + val name = Span(gpuNameText(), color, px) + if (gpuSpoofName.isBlank()) return listOf(name) + return listOf(name, Span(if (compact) " spoof" else " (spoof)", colBat, px)) + } + + private val inkRect = android.graphics.Rect() + + // ---- Layout builders -------------------------------------------------- + private fun rebuild() { + glyphs.clear(); tileRects.clear(); graphRect = null + headerMark = null; chipRect = null; dPanel = null; dDividerTop = -1f + val s = snap + if (s == null) { contentW = 0f; contentH = 0f; return } + when (size) { + FusionSize.FULL -> { buildFull(s); intoPanel(sp(10f), header = true) } + FusionSize.TILES -> { buildTiles(s); intoPanel(sp(9f), header = true) } + FusionSize.PILL -> { buildPill(s); intoPanel(sp(10f), header = false) } + FusionSize.MINIMAL -> buildMinimal(s) + FusionSize.MEGA -> { buildMega(s); intoPanel(sp(10f), header = true) } + } + } + + // ---- DroidDeck panel, header and chip ----------------------------------- + /** The clock sits in the header on every size but the Pill, which keeps it under the FPS. */ + private fun footerClock(): Boolean = showClockTime && size == FusionSize.PILL + + private fun measureSans(text: String, sizePx: Float): Float { wordmarkPaint.textSize = sizePx; return wordmarkPaint.measureText(text) } + + private fun panelInset() = sp(8f) // room for the glow around the panel + private fun panelLeft() = sp(13f) // the orb and its glow stick out of the left side + private fun contentLeft() = panelLeft() + sp(16f) + + /** The DroidDeck mark, "DroidDeck" and the clock across the top, starting on [left], with the same + * space above and below the mark. Returns the header's bottom edge and its right end. */ + private fun addPanelHeader(left: Float, inner: Float): Pair { + val wordPx = sp(10f); val clockPx = sp(9.5f); val gapH = sp(7f) + wordmarkPaint.textSize = wordPx + val markH = wordmarkPaint.fontMetrics.let { it.descent - it.ascent } * 0.95f + val markTop = inner + gapH + val markLeft = left - DroidDeckMark.inkLeftFor(markH) + headerMark = RectF(markLeft, markTop, markLeft + DroidDeckMark.widthFor(markH), markTop + markH) + val midY = markTop + markH / 2f + var x = markLeft + DroidDeckMark.inkRightFor(markH) + sp(6f) + wordmarkPaint.getTextBounds("DroidDeck", 0, 9, inkRect) + glyphs.add(Glyph(x, midY - inkRect.exactCenterY(), "DroidDeck", blend(colValue), wordPx, sans = true)) + x += measureSans("DroidDeck", wordPx) + if (showClockTime) { + measurePaint.textSize = clockPx + measurePaint.getTextBounds("0", 0, 1, inkRect) + val base = midY - inkRect.exactCenterY() + x += sp(6f) + glyphs.add(Glyph(x, base, "·", blend(colDim), clockPx)) + x += measure("·", clockPx) + sp(6f) + val t = clockTimeString() + glyphs.add(Glyph(x, base, t, blend(colDim), clockPx)) + x += measure(t, clockPx) + } + dDividerTop = markTop + markH + gapH + return Pair(dDividerTop + max(1f, density), x) + } + + /** + * Moves a size's content, laid out from [pad] at the origin, into the panel: under the header, or after + * the logo chip on the Pill. Lines that start on the content's left edge are lined up by their ink, so + * the logo, labels and numbers share one edge. + */ + private fun intoPanel(pad: Float, header: Boolean) { + if (contentW <= 0f || contentH <= 0f) return + for (i in glyphs.indices) { + val g = glyphs[i] + if (kotlin.math.abs(g.x - pad) < 0.5f) glyphs[i] = g.moved(-inkLeft(g.text, g.sizePx), 0f) + } + val stroke = outlineWidth(); val inner = panelInset() + stroke + var left = contentLeft() + val content = glyphs.size + var top = inner + sp(10f) + var headerRight = 0f + if (header) { + val (bottom, right) = addPanelHeader(left, inner) + top = bottom + sp(8f); headerRight = right + } else { + val chip = sp(22f) + chipRect = RectF(left, 0f, left + chip, chip) + left += chip + sp(8f) + } + val dx = left - pad; val dy = top - pad + for (i in 0 until content) glyphs[i] = glyphs[i].moved(dx, dy) + for (r in tileRects) r.offset(dx, dy) + graphRect?.offset(dx, dy) + val panel = RectF(panelLeft(), panelInset(), max(contentW - pad + dx, headerRight) + sp(18f), + contentH - pad + dy + sp(10f) + stroke) + chipRect?.let { it.offsetTo(it.left, panel.centerY() - it.height() / 2f) } + finishPanel(panel, halfRound = !header) + } + + /** Closes the panel around everything placed so far, widened until no line, tile or graph reaches the + * round side: a half circle on the short sizes (Pill, Minimal), large round corners on the tall ones. */ + private fun finishPanel(panel: RectF, halfRound: Boolean) { + val r = if (halfRound) panel.height() / 2f else min(panel.height() / 2f, sp(56f)) + val margin = outlineWidth() + sp(4f) + fun curveIn(top: Float, bottom: Float): Float { + val d = max(max(panel.top + r - top, bottom - (panel.bottom - r)), 0f) + return if (d <= 0f) 0f else if (d >= r) r else r - sqrt(r * r - d * d) + } + var right = panel.right + for (g in glyphs) { + val paint = if (g.sans) wordmarkPaint else measurePaint + paint.textSize = g.sizePx + paint.getTextBounds(g.text, 0, g.text.length, inkRect) + if (inkRect.isEmpty) continue + right = max(right, g.x + inkRect.right + curveIn(g.baseline + inkRect.top, g.baseline + inkRect.bottom) + margin) + } + graphRect?.let { right = max(right, it.right + curveIn(it.top, it.bottom) + margin) } + for (t in tileRects) right = max(right, t.right + curveIn(t.top, t.bottom) + margin) + panel.right = max(right, panel.left + sp(6f) + r) + dPanel = panel; dRadius = r + contentW = panel.right + panelInset() + contentH = panel.bottom + panelInset() + } + + // ---- Shared small-info helpers ---------------------------------------- + private fun clockTimeString(): String = DateFormat.getTimeFormat(context).format(Date()) + + private fun elapsedString(): String { + val sec = (frames?.sessionSeconds(System.nanoTime()) ?: 0f).toInt().coerceAtLeast(0) + val h = sec / 3600; val m = (sec % 3600) / 60; val s = sec % 60 + return if (h > 0) String.format(Locale.US, "%d:%02d:%02d", h, m, s) + else String.format(Locale.US, "%02d:%02d", m, s) + } + + /** + * The FPS row's API/engine label — the DX→Vulkan translator ([engineLabel]: "DXVK"/"VKD3D"/"Zink"), + * gated by the "Engine" chip. This is short and shows in EVERY size. Falls back to a bare "FPS" when + * the toggle is off or no engine label is set. (The graphics WRAPPER is separate — Mega-only, drawn + * below the frametime graph — not on the FPS row.) + */ + private fun apiLabel(): String = + if (showEngine && engineLabel.isNotBlank()) engineLabel else "FPS" + + /** The DX-wrapper version WITH its engine name (e.g. "DXVK 2.4.1", "VKD3D 2.14"), or "" if none. + * Used for the Mega stack line below the graph. */ + private fun dxVersionLabeled(): String = when { + engineLabel.contains("VKD3D", true) && vkd3dVersion.isNotBlank() -> "VKD3D $vkd3dVersion" + engineLabel.contains("DXVK", true) && dxvkVersion.isNotBlank() -> "DXVK $dxvkVersion" + else -> "" + } + + /** The DX-wrapper version for the current engine, or "" (used for the Tiles "API" tile sub-line). */ + private fun dxVersion(): String = when { + engineLabel.contains("VKD3D", true) -> vkd3dVersion + engineLabel.contains("DXVK", true) -> dxvkVersion + else -> "" + } + + /** Resolution + refresh, e.g. "1280x720 @ 120Hz". Read from the current display (Main thread). */ + private fun resolutionString(): String { + if (resolution.isNotBlank()) return resolution + val dm = resources.displayMetrics + val hz = (display?.refreshRate ?: 0f) + val base = "${dm.widthPixels}x${dm.heightPixels}" + return if (hz >= 1f) "$base @ ${hz.roundToInt()}Hz" else base + } + + /** A subtle, low-emphasis time-of-day tucked into the bottom-right of any size. Grows contentH slightly. */ + private fun addSubtleClock(pad: Float, leftAligned: Boolean = false) { + if (!footerClock()) return + val px = sp(9.5f) + val t = clockTimeString() + val w = measure(t, px) + val footerTop = contentH - pad // reuse the bottom padding band as the footer line + val baseline = footerTop - ascent(px) + // Right-aligned footer; on the Pill it sits on the left edge, under the FPS. + val x = if (leftAligned) pad else (contentW - pad - w).coerceAtLeast(pad) + glyphs.add(Glyph(x, baseline, t, blend(colDim), px)) + contentH = footerTop + lineH(px) + pad * 0.5f + contentW = max(contentW, pad + w + pad) + } + + private fun buildFull(s: HudMetrics.Snapshot) { + val rowPx = sp(12f); val unitPx = rowPx * 0.62f + val pad = sp(10f); val lineGap = sp(4f); val lvGap = sp(8f) + val rows = ArrayList() + + if (showGpuModel && gpuNameText().isNotBlank()) + rows.add(HudRow(Span("GPU", colGpu, rowPx), gpuModelSpans(rowPx, colValue))) + if (displayServer.isNotBlank()) + rows.add(HudRow(Span("DISP", colDisp, rowPx), listOf(Span(displayServer, colValue, rowPx)))) + if (hdrState != FusionHdr.NONE) + rows.add(HudRow(Span("HDR", colHdr, rowPx), hdrValue(rowPx))) + if (showGPU) { + val v = ArrayList() + v += numUnit(s.gpuPercent?.toString(), "%", rowPx, unitPx) + if (showGpuTemp) tempSpans(s.gpuTempC, HudMetrics.TempSensor.GPU, rowPx, unitPx) + .let { if (it.isNotEmpty()) { v += gap(unitPx); v += it } } + v += gap(unitPx); v += numUnit(s.gpuClockMhz?.toString(), "MHz", rowPx, unitPx) + rows.add(HudRow(Span("GPU", colGpu, rowPx), v)) + } + if (showCPU) { + val v = ArrayList() + v += numUnit(s.cpuPercent?.toString(), "%", rowPx, unitPx) + if (showCpuTemp) tempSpans(s.cpuTempC, HudMetrics.TempSensor.CPU, rowPx, unitPx) + .let { if (it.isNotEmpty()) { v += gap(unitPx); v += it } } + v += gap(unitPx); v += numUnit(s.cpuClockMhz?.toString(), "MHz", rowPx, unitPx) + rows.add(HudRow(Span("CPU", colCpu, rowPx), v)) + } + if (showVram && s.vramText() != null) + rows.add(HudRow(Span("VRAM", colVram, rowPx), valueUnit(s.vramText()!!, rowPx, unitPx))) + if (showRAM) { + val v = ArrayList() + v += valueUnit(s.ramUsedText(), rowPx, unitPx) + v += gap(unitPx); v += numUnit(s.ramPercent.roundToInt().toString(), "%", rowPx, unitPx) + rows.add(HudRow(Span("RAM", colRam, rowPx), v)) + } + if (showBattery || showPower || showBatteryTemp) { + val v = ArrayList(); var any = false + if (showBattery && s.battery.percent != null) { v += numUnit(s.battery.percent.toString(), "%", rowPx, unitPx); any = true } + if (showBatteryTemp) tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, rowPx, unitPx) + .let { if (it.isNotEmpty()) { if (any) v += gap(unitPx); v += it; any = true } } + if (showPower && s.battery.watts > 0f) { if (any) v += gap(unitPx); v += numUnit(fmt1(s.battery.watts), "W", rowPx, unitPx); any = true } + if (any) rows.add(HudRow(Span("BAT", colBat, rowPx), v)) + } + if (showFPS) { + val v = ArrayList() + v += glowing(numUnit(fpsText(fpsNow), "FPS", rowPx, unitPx)) + v += gap(unitPx); v += numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", rowPx, unitPx) + // Short API/engine label ("DXVK"/"VKD3D"/"Zink", else "FPS") — a normal aligned row. + rows.add(HudRow(Span(apiLabel(), colFps, rowPx), v)) + rows.add(HudRow(Span("AVG", colLo, rowPx), numUnit(fmt1(fpsAvg), "FPS", rowPx, unitPx))) + rows.add(HudRow(Span("1%", colLo, rowPx), numUnit(lowText(lows.low1Fps), "FPS", rowPx, unitPx))) + rows.add(HudRow(Span("0.1%", colLo, rowPx), numUnit(lowText(lows.low01Fps), "FPS", rowPx, unitPx))) + if (showLow001) + rows.add(HudRow(Span("0.01%", colLo, rowPx), numUnit(lowText(lows.low001Fps), "FPS", rowPx, unitPx))) + } + + var labelCol = 0f + for (r in rows) if (!r.inline) labelCol = max(labelCol, measure(r.label.text, rowPx)) + val h = lineH(rowPx); val asc = ascent(rowPx) + var y = pad; var maxRight = pad + for (r in rows) { + val baseline = y - asc + placeRun(pad, baseline, listOf(r.label)) + val valX = if (r.inline) pad + measure(r.label.text, rowPx) + lvGap + else pad + labelCol + lvGap + val end = placeRun(valX, baseline, r.vals) + maxRight = max(maxRight, end) + y += h + lineGap + } + + if (showFPS && showGraph) { + // Frametime min/max line + green graph. "Frametime" is far wider than the short-label grid + // column, so place the stat AFTER the ACTUAL label width (not labelCol) — otherwise the two + // overlap and render as "Frametimemin:.. max:..". + val ftPx = unitPx * 1.15f + val baseline = y - asc + placeRun(pad, baseline, listOf(Span("Frametime", colFps, ftPx))) + val stat = "min:${fmt1(graphMinMs)} max:${fmt1(graphMaxMs)}" + val statX = pad + max(labelCol, measure("Frametime", ftPx)) + lvGap + val end = placeRun(statX, baseline, listOf(Span(stat, colDim, unitPx))) + maxRight = max(maxRight, end) + y += h + lineGap + val gh = sp(22f) + val right = max(maxRight, pad + sp(160f)) + graphRect = RectF(pad, y, right, y + gh) + maxRight = max(maxRight, right) + y += gh + } + + contentW = maxRight + pad + contentH = y + pad + addSubtleClock(pad) + } + + private fun buildTiles(s: HudMetrics.Snapshot) { + val keyPx = sp(10f); val valPx = sp(18f); val subPx = sp(10f); val unitPx = sp(11f) + val pad = sp(9f); val innerPad = sp(8f); val tileGap = sp(6f); val lineGap = sp(4f) + + class Tile(val key: String, val keyColor: Int, val value: List, val sub: String?, val wide: Boolean) + val tiles = ArrayList() + + if (showFPS) tiles.add(Tile("FPS", colFps, listOf(Span(fpsText(fpsNow), colValue, valPx, glow = true)), + "${fmt1(fpsAvg)} avg · ${lowText(lows.low1Fps) ?: "—"} 1%", false)) + if (showFPS) tiles.add(Tile("FRAME", colDim, numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", valPx, unitPx), + "${fmt1(graphMinMs)} – ${fmt1(graphMaxMs)}", false)) + if (showGPU) tiles.add(Tile("GPU", colGpu, numUnit(s.gpuPercent?.toString(), "%", valPx, unitPx), + if (showGpuTemp && s.gpuTempC != null) HudMetrics.formatTemp(s.gpuTempC.toFloat(), tempDisplay, false) + else s.gpuClockMhz?.let { "${it}MHz" }, false)) + if (showCPU) tiles.add(Tile("CPU", colCpu, numUnit(s.cpuPercent?.toString(), "%", valPx, unitPx), + listOfNotNull(if (showCpuTemp) s.cpuTempC?.let { HudMetrics.formatTemp(it.toFloat(), tempDisplay, false) } else null, + s.cpuClockMhz?.toString()).joinToString(" · ").ifBlank { null }, false)) + if (showVram && s.vramText() != null) tiles.add(Tile("VRAM", colVram, valueUnit(s.vramText()!!, valPx, unitPx), null, false)) + if (showRAM) tiles.add(Tile("RAM", colRam, numUnit(s.ramPercent.roundToInt().toString(), "%", valPx, unitPx), + "${s.ramUsedText()} / ${s.ramTotalText()}", false)) + // API/engine tile — short translator name (DXVK/VKD3D/Zink) with the DX version on the sub-line; + // a normal half-width tile that naturally fills the empty slot beside RAM. Gated by "Engine". + if (showEngine && engineLabel.isNotBlank()) + tiles.add(Tile("API", colFps, listOf(Span(engineLabel, colValue, valPx)), + dxVersion().ifBlank { null }, false)) + if (displayServer.isNotBlank()) + tiles.add(Tile("DISPLAY", colDisp, listOf(Span(displayServer, colValue, valPx)), + if (hdrState != FusionHdr.NONE) hdrText() else null, false)) + if (showGpuModel && gpuNameText().isNotBlank()) + tiles.add(Tile("GPU", colGpu, gpuModelSpans(valPx, colValue), null, true)) + if (showBattery || showPower || showBatteryTemp) { + val parts = ArrayList(); var any = false + if (showBattery && s.battery.percent != null) { parts += numUnit(s.battery.percent.toString(), "%", valPx, unitPx); any = true } + if (showBatteryTemp && s.battery.tempC != null) { if (any) parts += Span(" · ", colDim, subPx); parts += tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, valPx, unitPx); any = true } + if (showPower && s.battery.watts > 0f) { if (any) parts += Span(" · ", colDim, subPx); parts += numUnit(fmt1(s.battery.watts), "W", valPx, unitPx); any = true } + if (any) tiles.add(Tile("BAT", colBat, parts, null, true)) + } + if (tiles.isEmpty()) { contentW = 0f; contentH = 0f; return } + + val keyH = lineH(keyPx); val valH = lineH(valPx); val subH = lineH(subPx) + fun tileW(t: Tile) = max(max(measure(t.key, keyPx), runWidth(t.value)), + t.sub?.let { measure(it, subPx) } ?: 0f) + innerPad * 2 + var normalW = 0f + for (t in tiles) if (!t.wide) normalW = max(normalW, tileW(t)) + if (normalW == 0f) for (t in tiles) normalW = max(normalW, tileW(t) / 2f) + val tileH = innerPad * 2 + keyH + lineGap + valH + lineGap + subH // uniform (room for a sub line) + val fullW = normalW * 2 + tileGap + + var x = pad; var y = pad; var col = 0 + fun place(t: Tile, tx: Float, ty: Float, tw: Float) { + tileRects.add(RectF(tx, ty, tx + tw, ty + tileH)) + var by = ty + innerPad - ascent(keyPx) + placeRun(tx + innerPad, by, listOf(Span(t.key, t.keyColor, keyPx))) + by = ty + innerPad + keyH + lineGap - ascent(valPx) + placeRun(tx + innerPad, by, t.value) + if (t.sub != null) { + by = ty + innerPad + keyH + lineGap + valH + lineGap - ascent(subPx) + placeRun(tx + innerPad, by, listOf(Span(t.sub, colDim, subPx))) + } + } + for (t in tiles) { + if (t.wide) { + if (col != 0) { y += tileH + tileGap; col = 0; x = pad } + place(t, pad, y, fullW) + y += tileH + tileGap; col = 0; x = pad + } else { + place(t, x, y, normalW) + col++; x += normalW + tileGap + if (col == 2) { col = 0; x = pad; y += tileH + tileGap } + } + } + if (col != 0) y += tileH + tileGap + if (showFPS && showGraph) { + graphRect = RectF(pad, y, pad + fullW, y + sp(22f)) + y += sp(22f) + tileGap + } + contentW = pad + fullW + pad + contentH = y + (pad - tileGap) + addSubtleClock(pad) + } + + private fun buildPill(s: HudMetrics.Snapshot) { + val bigPx = sp(30f); val bigUnitPx = bigPx * 0.36f; val stkPx = sp(11.5f) + val pad = sp(10f); val midGap = sp(12f); val stkLineGap = sp(3f) + + val left = ArrayList() + // "30->118" is roughly three times the width of "30", and the pill's + // number is set at 30sp precisely because it is the one big thing on a + // small overlay. Shrink it while it carries both figures so the pill + // does not balloon across the screen; it is still the largest element. + val generating = differs(fpsNow) + val fpsPx = if (generating) bigPx * 0.55f else bigPx + left += Span(fpsText(fpsNow), colValue, fpsPx, glow = true) + left += Span("fps", colDim, if (generating) bigUnitPx * 0.8f else bigUnitPx) + + val stack = ArrayList>() + // The GPU name normally heads the stack. A name wider than every stat under it (a Wayland spoof + // such as "Radeon RX 6800/6800 XT / 6900 XT spoof") would set the stack's width and stretch the + // whole capsule around empty space, so that name gets its own line across the top of the pill + // instead, starting over the API caption (see nameOnTop below). + val gpuName = if (showGpuModel && gpuNameText().isNotBlank()) gpuModelSpans(stkPx, colDim, compact = true) else null + run { + val l = ArrayList() + if (showGPU) { l += Span("GPU ${s.gpuPercent ?: "—"}%", colGpu, stkPx) } + if (showCPU) { if (l.isNotEmpty()) l += Span(" · ", colDim, stkPx); l += Span("CPU ${s.cpuPercent ?: "—"}%", colCpu, stkPx) } + if (l.isNotEmpty()) stack.add(l) + } + // RAM % (system-wide) takes the slot the latency row used to occupy, matching the GPU/CPU idiom + // on the row above it. colRam keeps RAM's identity colour consistent with the Full/Tiles sizes. + if (showRAM) { + val l = ArrayList() + l += Span("RAM ${s.ramPercent.roundToInt()}%", colRam, stkPx) + // Battery temperature as a "BAT" chip right after RAM (pill-only placement, per user + // request). Colour-banded warm→red via tempSpans/TempSensor.BATTERY — the exact same + // danger bands the GPU/CPU temps use. Only shown when the battery-temp toggle is on + // and a reading is available; the other sizes keep battery temp in the battery row. + if (showBatteryTemp && s.battery.tempC != null) { + l += Span(" · ", colDim, stkPx) + l += Span("BAT ", colBat, stkPx) + l += tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, stkPx, stkPx * 0.62f) + } + stack.add(l) + } + if (showBattery || showPower) { + val l = ArrayList(); var any = false + if (showBattery && s.battery.percent != null) { l += Span("BAT ${s.battery.percent}%", colBat, stkPx); any = true } + if (showPower && s.battery.watts > 0f) { if (any) l += Span(" · ", colDim, stkPx); l += Span("${fmt1(s.battery.watts)}W", colDim, stkPx) } + if (any) stack.add(l) + } + // Latency (+ the display server, + optional VRAM) drops to the bottom of the stack, under the + // battery row. The display server sits here, not on the GPU-model line: that line is the + // pill's widest and ran into the capsule's rounded edge. + run { + val l = ArrayList() + l += Span("${fmt1(1000f / max(fpsNow, 1f))}ms", colDim, stkPx) + if (displayServer.isNotBlank()) { l += Span(" · ", colDim, stkPx); l += Span(displayServer, colDisp, stkPx) } + if (showVram && s.vramText() != null) { l += Span(" · ", colDim, stkPx); l += Span("${s.vramText()} vram", colDim, stkPx) } + stack.add(l) + } + // Wayland HDR state on its OWN line directly under the latency · display-server line (it ran off + // the capsule's right edge as "40.3ms · Wayland · HDR (no headroom)"). Only in HDR sessions. + if (hdrState != FusionHdr.NONE) stack.add(hdrLine(stkPx)) + + var statsW = 0f + for (l in stack) statsW = max(statsW, runWidth(l)) + val nameOnTop = gpuName != null && runWidth(gpuName) > statsW + if (gpuName != null && !nameOnTop) stack.add(0, gpuName) + + // Left column: a small API/engine caption (DXVK/VKD3D/Zink) above the big FPS and the clock below + // it, all on the left edge, so the left reads API · FPS · clock top-to-bottom. + val apiStr = apiLabel() + val hasApi = apiStr != "FPS" + val apiH = if (hasApi) lineH(stkPx) else 0f + val apiGap = if (hasApi) stkLineGap else 0f + + val leftW = runWidth(left); val leftH = lineH(bigPx) + val apiW = if (hasApi) measure(apiStr, stkPx) else 0f + val leftBlockW = max(leftW, apiW) + val leftColH = apiH + apiGap + leftH + val stkH = lineH(stkPx) + var stackW = 0f + for (l in stack) stackW = max(stackW, runWidth(l)) + val stackTotalH = stack.size * stkH + (stack.size - 1).coerceAtLeast(0) * stkLineGap + val innerH = max(leftColH, stackTotalH) + val topLineH = if (nameOnTop) stkH + stkLineGap else 0f + contentW = pad + leftBlockW + midGap + stackW + pad + contentH = pad + topLineH + innerH + pad + + // left column (API caption + big FPS), vertically centered as a block + var ly = pad + topLineH + (innerH - leftColH) / 2f + if (hasApi) { + placeRun(pad, ly - ascent(stkPx), listOf(Span(apiStr, colFps, stkPx))) + ly += apiH + apiGap + } + placeRun(pad, ly - ascent(bigPx), left) + // stack, vertically centered + var sy = pad + topLineH + (innerH - stackTotalH) / 2f + for (l in stack) { + placeRun(pad + leftBlockW + midGap, sy - ascent(stkPx), l) + sy += stkH + stkLineGap + } + addSubtleClock(pad, leftAligned = true) + if (nameOnTop && gpuName != null) { + // Left-aligned over the API caption; the pill only widens if the name is wider than the + // API/FPS column + stats. + val end = placeRun(pad, pad - ascent(stkPx), gpuName) + contentW = max(contentW, end + pad) + } + } + + // One column as wide as the widest row: the logo, FPS, lows, graph and engine line start on its left + // edge (ink, not advance), and the header keeps the same space above and below the logo. + private fun buildMinimal(s: HudMetrics.Snapshot) { + val bigPx = sp(34f); val bigUnitPx = bigPx * 0.32f; val subPx = sp(11.5f); val footPx = sp(9.5f) + val stroke = outlineWidth() + val left = contentLeft() + val inner = panelInset() + stroke + + // Same reasoning as the pill: 34sp is sized for one number, not two. + val minGenerating = differs(fpsNow) + val big = listOf( + Span(fpsText(fpsNow), colValue, if (minGenerating) bigPx * 0.55f else bigPx), + Span("fps", colDim, if (minGenerating) bigUnitPx * 0.8f else bigUnitPx)) + val sub = ArrayList() + sub += Span("1% ", colDim, subPx); sub += Span(lowText(lows.low1Fps) ?: "—", colFps, subPx) + sub += Span(" · 0.1% ", colDim, subPx); sub += Span(lowText(lows.low01Fps) ?: "—", colFps, subPx) + if (showLow001) { + sub += Span(" · 0.01% ", colDim, subPx); sub += Span(lowText(lows.low001Fps) ?: "—", colFps, subPx) + } + val footerLabel = listOf(if (showEngine) engineLabel else "", displayServer) + .filter { it.isNotBlank() }.joinToString(" · ") + val hdr = if (hdrState != FusionHdr.NONE) hdrLine(footPx) else emptyList() + + val (headerBottom, headerRight) = addPanelHeader(left, inner) + val x = headerRight + + val colW = maxOf(runWidth(big), runWidth(sub), x - left, + max(measure(footerLabel, footPx), runWidth(hdr)), if (showGraph) sp(120f) else 0f) + val bigBase = headerBottom + sp(8f) + capHeight(big[0].sizePx) + placeRun(left - inkLeft(big[0].text, big[0].sizePx), bigBase, big, glow = true) + val subBase = bigBase + sp(10f) + capHeight(subPx) + placeRun(left - inkLeft(sub[0].text, subPx), subBase, sub) + var last = subBase + if (showGraph) { + val top = subBase + sp(9f) + graphRect = RectF(left, top, left + colW, top + sp(24f)) + last = top + sp(24f) + } + if (footerLabel.isNotBlank()) { + val base = last + sp(8f) + capHeight(footPx) + glyphs.add(Glyph(left - inkLeft(footerLabel, footPx), base, footerLabel, blend(colDim), footPx)) + last = base + } + if (hdr.isNotEmpty()) { + val base = last + sp(6f) + capHeight(footPx) + placeRun(left - inkLeft(hdr[0].text, footPx), base, hdr) + last = base + } + measurePaint.textSize = footPx + val panel = RectF(panelLeft(), panelInset(), left + colW + sp(34f), last + measurePaint.fontMetrics.descent + sp(9f) + stroke) + + finishPanel(panel, halfRound = true) + } + + private fun capHeight(px: Float): Float { + measurePaint.textSize = px + measurePaint.getTextBounds("0", 0, 1, inkRect) + return -inkRect.top.toFloat() + } + + private fun inkLeft(text: String, px: Float): Float { + if (text.isEmpty()) return 0f + measurePaint.textSize = px + measurePaint.getTextBounds(text, 0, text.length, inkRect) + return inkRect.left.toFloat() + } + + /** Places a column of "label + value" rows; returns (bottomY, rightX). Appends glyphs. Rows flagged + * [HudRow.inline] opt out of the shared label column (value follows the label directly). */ + private fun layoutColumn(rows: List, x: Float, y0: Float, + rowPx: Float, lineGap: Float, lvGap: Float): Pair { + if (rows.isEmpty()) return Pair(y0, x) + var labelCol = 0f + for (r in rows) if (!r.inline) labelCol = max(labelCol, measure(r.label.text, rowPx)) + val h = lineH(rowPx); val asc = ascent(rowPx) + var y = y0; var right = x + for (r in rows) { + val baseline = y - asc + placeRun(x, baseline, listOf(r.label)) + val valX = if (r.inline) x + measure(r.label.text, rowPx) + lvGap + else x + labelCol + lvGap + val end = placeRun(valX, baseline, r.vals) + right = max(right, end) + y += h + lineGap + } + return Pair(y - lineGap, right) + } + + /** Places wrapping " · "-separated info fragments within maxWidth; returns (bottomY, rightX). */ + private fun layoutWrap(fragments: List>, x: Float, y0: Float, maxWidth: Float, + px: Float, lineGap: Float): Pair { + if (fragments.isEmpty()) return Pair(y0, x) + val h = lineH(px); val asc = ascent(px) + val sepW = measure(" · ", px) + var cx = x; var y = y0; var right = x; var firstOnLine = true + for (frag in fragments) { + val w = runWidth(frag) + if (!firstOnLine && (cx + sepW + w - x) > maxWidth) { y += h + lineGap; cx = x; firstOnLine = true } + if (!firstOnLine) { placeRun(cx, y - asc, listOf(Span(" · ", colDim, px))); cx += sepW } + val end = placeRun(cx, y - asc, frag) + cx = end; right = max(right, end); firstOnLine = false + } + return Pair(y + h, right) + } + + private fun buildMega(s: HudMetrics.Snapshot) { + val rowPx = sp(11.5f); val unitPx = rowPx * 0.62f; val bandPx = sp(9.5f) + val pad = sp(10f); val lineGap = sp(3.5f); val lvGap = sp(7f); val gutter = sp(16f) + + // ---- LEFT column: GPU, aggregate CPU, then per-core rows ---- + val left = ArrayList() + if (showGpuModel && gpuNameText().isNotBlank()) + left.add(HudRow(Span("GPU", colGpu, rowPx), gpuModelSpans(rowPx, colValue))) + if (showGPU) { + val v = ArrayList() + v += numUnit(s.gpuPercent?.toString(), "%", rowPx, unitPx) + if (showGpuTemp) tempSpans(s.gpuTempC, HudMetrics.TempSensor.GPU, rowPx, unitPx) + .let { if (it.isNotEmpty()) { v += gap(unitPx); v += it } } + v += gap(unitPx); v += numUnit(s.gpuClockMhz?.toString(), "MHz", rowPx, unitPx) + left.add(HudRow(Span("GPU", colGpu, rowPx), v)) + } + if (showCPU) { + val v = ArrayList() + v += numUnit(s.cpuPercent?.toString(), "%", rowPx, unitPx) + if (showCpuTemp) tempSpans(s.cpuTempC, HudMetrics.TempSensor.CPU, rowPx, unitPx) + .let { if (it.isNotEmpty()) { v += gap(unitPx); v += it } } + v += gap(unitPx); v += numUnit(s.cpuClockMhz?.toString(), "MHz", rowPx, unitPx) + left.add(HudRow(Span("CPU", colCpu, rowPx), v)) + } + if (showPerCore) { + val pct = s.perCorePercent; val clk = s.perCoreClockMhz + val n = max(pct.size, clk.size) + for (i in 0 until n) { + val v = ArrayList() + v += numUnit(if (i < pct.size && pct[i] >= 0) pct[i].toString() else null, "%", rowPx, unitPx) + v += gap(unitPx) + v += numUnit(if (i < clk.size && clk[i] > 0) clk[i].toString() else null, "MHz", rowPx, unitPx) + left.add(HudRow(Span("C$i", colCpu, rowPx), v)) + } + } + + // ---- RIGHT column: VRAM, RAM, SWP, NET, BAT, engine, lows ---- + val right = ArrayList() + if (showVram && s.vramText() != null) + right.add(HudRow(Span("VRAM", colVram, rowPx), valueUnit(s.vramText()!!, rowPx, unitPx))) + if (showRAM) { + val v = ArrayList() + v += valueUnit(s.ramUsedText(), rowPx, unitPx) + v += Span("/", colDim, unitPx); v += valueUnit(s.ramTotalText(), rowPx, unitPx) + v += gap(unitPx); v += numUnit(s.ramPercent.roundToInt().toString(), "%", rowPx, unitPx) + right.add(HudRow(Span("RAM", colRam, rowPx), v)) + } + if (showSwap && s.swapUsedText() != null) { + val v = ArrayList() + v += valueUnit(s.swapUsedText()!!, rowPx, unitPx) + s.swapTotalText()?.let { v += Span("/", colDim, unitPx); v += valueUnit(it, rowPx, unitPx) } + right.add(HudRow(Span("SWP", colRam, rowPx), v)) + } + if (showNet && s.netDownBps != null) { + val d = (s.netDownBps ?: 0L) / 1024L + val u = (s.netUpBps ?: 0L) / 1024L + val v = ArrayList() + v += Span("↓", colDim, unitPx); v += Span(d.toString(), colValue, rowPx) + v += Span(" ↑", colDim, unitPx); v += Span(u.toString(), colValue, rowPx) + v += Span("KB/s", colDim, unitPx) + right.add(HudRow(Span("NET", colFps, rowPx), v)) + } + if (showBattery || showPower || showBatteryTemp) { + val v = ArrayList(); var any = false + if (showBattery && s.battery.percent != null) { v += numUnit(s.battery.percent.toString(), "%", rowPx, unitPx); any = true } + if (showBatteryTemp) tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, rowPx, unitPx) + .let { if (it.isNotEmpty()) { if (any) v += gap(unitPx); v += it; any = true } } + if (showPower && s.battery.watts > 0f) { if (any) v += gap(unitPx); v += numUnit(fmt1(s.battery.watts), "W", rowPx, unitPx); any = true } + if (any) right.add(HudRow(Span("BAT", colBat, rowPx), v)) + } + if (showFPS) { + val v = ArrayList() + v += glowing(numUnit(fpsText(fpsNow), "FPS", rowPx, unitPx)) + v += gap(unitPx); v += numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", rowPx, unitPx) + // FPS/engine row: just the short API label. The DX version moved to the stack lines + // below the frametime graph (see below), so this row stays compact. + right.add(HudRow(Span(apiLabel(), colFps, rowPx), v)) + right.add(HudRow(Span("AVG", colLo, rowPx), numUnit(fmt1(fpsAvg), "FPS", rowPx, unitPx))) + right.add(HudRow(Span("1%", colLo, rowPx), numUnit(lowText(lows.low1Fps), "FPS", rowPx, unitPx))) + right.add(HudRow(Span("0.1%", colLo, rowPx), numUnit(lowText(lows.low01Fps), "FPS", rowPx, unitPx))) + if (showLow001) + right.add(HudRow(Span("0.01%", colLo, rowPx), numUnit(lowText(lows.low001Fps), "FPS", rowPx, unitPx))) + } + + // ---- Two columns side by side (each reflows independently) ---- + val (leftBottom, leftRight) = layoutColumn(left, pad, pad, rowPx, lineGap, lvGap) + val rightX = (if (left.isEmpty()) pad else leftRight + gutter) + val (rightBottom, rightRight) = layoutColumn(right, rightX, pad, rowPx, lineGap, lvGap) + var y = max(leftBottom, rightBottom) + var maxRight = max(leftRight, rightRight) + + // ---- Bottom band spanning both columns: res · Proton · elapsed ---- + // (The graphics wrapper moved to the FPS-row label above, so it's no longer in this band.) + val band = ArrayList>() + if (showResolution) band.add(listOf(Span("RES ", colDim, bandPx), Span(resolutionString(), colValue, bandPx))) + if (displayServer.isNotBlank()) band.add(listOf(Span("DISP ", colDim, bandPx), Span(displayServer, colDisp, bandPx))) + if (hdrState != FusionHdr.NONE) band.add(listOf(Span("HDR ", colDim, bandPx)) + hdrValue(bandPx)) + if (showProton && wineVersion.isNotBlank()) band.add(listOf(Span(wineVersion, colVram, bandPx))) + if (showSession) band.add(listOf(Span("elapsed ", colDim, bandPx), Span(elapsedString(), colValue, bandPx))) + if (band.isNotEmpty()) { + y += sp(4f) + val (bBottom, bRight) = layoutWrap(band, pad, y, max(maxRight - pad, sp(180f)), bandPx, lineGap) + y = bBottom; maxRight = max(maxRight, bRight) + } + + // ---- Full-width frametime graph ---- + if (showGraph) { + y += sp(3f) + val gh = sp(22f) + val gr = max(maxRight, pad + sp(220f)) + graphRect = RectF(pad, y, gr, y + gh) + maxRight = max(maxRight, gr) + y += gh + } + + // ---- Stack-layer lines BELOW the frametime graph, subtle (same size/style as the bottom + // band): the DX-wrapper version first (e.g. "DXVK 2.4.1-…", gated by "DX ver"), then the + // graphics wrapper beneath it (e.g. "Original", gated by "Wrapper"). ---- + val dxLine = dxVersionLabeled() + val hasDx = showDxVer && dxLine.isNotBlank() + if (hasDx) { + y += sp(4f) + maxRight = max(maxRight, placeRun(pad, y - ascent(bandPx), listOf(Span(dxLine, colDim, bandPx)))) + y += lineH(bandPx) + } + if (showWrapper && graphicsWrapper.isNotBlank()) { + y += if (hasDx) sp(1f) else sp(4f) + maxRight = max(maxRight, placeRun(pad, y - ascent(bandPx), listOf(Span(graphicsWrapper, colDim, bandPx)))) + y += lineH(bandPx) + } + + contentW = maxRight + pad + contentH = y + pad + addSubtleClock(pad) // subtle time-of-day, consistent with the other sizes + } + + // ---- Measure / draw --------------------------------------------------- + override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { + setMeasuredDimension( + resolveSize(contentW.roundToInt(), widthMeasureSpec), + resolveSize(contentH.roundToInt(), heightMeasureSpec), + ) + } + + override fun onDraw(canvas: Canvas) { + if (contentW <= 0f || contentH <= 0f) { lockController.drawBadge(canvas); return } + + dPanel?.let { panel -> panelFrame(panel)?.let { canvas.drawBitmap(it, 0f, 0f, null) } } + + // Tile backings + if (tileRects.isNotEmpty()) { + tilePaint.color = Color.argb((14 * bgOpacity).roundToInt().coerceIn(8, 40), 255, 255, 255) + val tr = sp(6f) + for (rect in tileRects) canvas.drawRoundRect(rect, tr, tr, tilePaint) + } + + chipRect?.let { drawChip(canvas, it) } + + // Text + for (g in glyphs) { + val paint = if (g.sans) wordmarkPaint else drawPaint + paint.textSize = g.sizePx + paint.color = g.color + if (g.glow) paint.setShadowLayer(sp(6f), 0f, 0f, withAlpha(colGraph, 217)) + canvas.drawText(g.text, g.x, g.baseline, paint) + if (g.glow) paint.clearShadowLayer() + } + headerMark?.let { DroidDeckMark.draw(canvas, it.left, it.top, it.height(), blend(colValue), accent) } + + // Frametime graph + graphRect?.let { drawGraph(canvas, it) } + + lockController.drawBadge(canvas) + } + + // MangoHud's frametime graph: the last 200 frames on a fixed 0-50 ms scale, longer frames clipped + // to 49.9 ms (hud_elements.cpp TransformForward_Custom). + private fun drawGraph(canvas: Canvas, rect: RectF) { + val stats = frames ?: return + stats.graph(graphBuf) + val step = rect.width() / (graphBuf.size - 1) + graphPath.rewind() + for (i in graphBuf.indices) { + val px = rect.left + i * step + val py = rect.bottom - min(graphBuf[i], GRAPH_CLIP_MS) / FrameStats.GRAPH_MAX_MS * rect.height() + if (i == 0) graphPath.moveTo(px, py) else graphPath.lineTo(px, py) + } + if (dPanel != null) { + // Neon without a blur: a blur would be redrawn with every frame. + graphPaint.strokeWidth = sp(4.5f) + graphPaint.color = withAlpha(blend(colGraph), 56) + canvas.drawPath(graphPath, graphPaint) + } + graphPaint.strokeWidth = sp(1.6f) + graphPaint.color = blend(colGraph) + canvas.drawPath(graphPath, graphPaint) + } + + private fun outlineWidth(): Float = if (outlineIntensity > 0f) outlineIntensity * sp(3.5f) else 0f + private fun outlineColor(): Int = if (outlineFollowAccent) accent else Color.rgb(200, 200, 200) + private fun panelColor(): Int = Color.argb((bgOpacity.coerceIn(0f, 1f) * 255f).roundToInt(), + Color.red(surfaceRgb), Color.green(surfaceRgb), Color.blue(surfaceRgb)) + private fun withAlpha(color: Int, alpha: Int): Int = + Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color)) + + /** The D: straight left side with small corners, round on the right with radius [rad] (a half circle + * when it is half the height). [split] > 0 leaves that much open above and below the middle of the + * left side, where the orb sits. */ + private fun dShape(l: Float, t: Float, r: Float, b: Float, rad: Float, corner: Float, split: Float): Path { + val cy = (t + b) / 2f + return Path().apply { + if (split > 0f) moveTo(l, cy + split) else moveTo(l, t + corner) + lineTo(l, b - corner); quadTo(l, b, l + corner, b) + lineTo(r - rad, b) + arcTo(r - 2f * rad, b - 2f * rad, r, b, 90f, -90f, false) + lineTo(r, t + rad) + arcTo(r - 2f * rad, t, r, t + 2f * rad, 0f, -90f, false) + lineTo(l + corner, t); quadTo(l, t, l, t + corner) + if (split > 0f) lineTo(l, cy - split) else close() + } + } + + /** Where the inside of the outline's round side is at height [y]. */ + private fun roundEdgeX(p: RectF, y: Float, stroke: Float): Float { + val r = dRadius - stroke + val cx = p.right - dRadius + val dy = p.top + dRadius - y + return if (dy <= 0f) p.right - stroke else if (dy >= r) cx else cx + sqrt(r * r - dy * dy) + } + + private fun panelFrame(panel: RectF): Bitmap? { + if (width <= 0 || height <= 0) return null + val stroke = outlineWidth() + val key = "$width,$height,$panel,$dRadius,$dDividerTop,$stroke,$accent,$surfaceRgb,$bgOpacity,${outlineColor()}" + if (key == dFrameKey) dFrame?.let { return it } + val bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) + val c = Canvas(bmp) + val corner = sp(6f) + val body = dShape(panel.left, panel.top, panel.right, panel.bottom, dRadius, corner, 0f) + bgPaint.color = panelColor() + c.drawPath(body, bgPaint) + c.save() + c.clipPath(body) + if (dDividerTop >= 0f) { + val dividerBottom = dDividerTop + max(1f, density) + headerPaint.shader = android.graphics.LinearGradient(panel.left, 0f, panel.right, 0f, + withAlpha(accent, 46), withAlpha(accent, 0), android.graphics.Shader.TileMode.CLAMP) + c.drawRect(panel.left, panel.top, panel.right, dividerBottom, headerPaint) + headerPaint.shader = null + headerPaint.color = withAlpha(accent, 90) + c.drawRect(panel.left, dDividerTop, roundEdgeX(panel, dDividerTop, stroke), dividerBottom, headerPaint) + } + // The watermark fills the half circle on the short sizes and sits on the right of the tall ones. + val halfRound = dRadius >= panel.height() / 2f - 0.5f + val wmH = if (halfRound) panel.height() * 0.92f else min(panel.height(), panel.width()) * 0.55f + DroidDeckMark.draw(c, panel.right - DroidDeckMark.widthFor(wmH) - (if (halfRound) panel.height() * 0.02f else sp(10f)), + panel.centerY() - wmH / 2f, wmH, Color.argb(20, 255, 255, 255), withAlpha(accent, 20)) + c.restore() + if (stroke > 0f) { + val h = stroke / 2f + val outline = dShape(panel.left + h, panel.top + h, panel.right - h, panel.bottom - h, dRadius - h, corner, sp(9f)) + val blur = BlurMaskFilter((sp(3.2f) - 0.5f).coerceAtLeast(0.5f) / 0.57735f, BlurMaskFilter.Blur.NORMAL) + glowPaint.strokeWidth = stroke + // Two blurred passes under the sharp one, as the 4-in-1 preview's neon. + for (pass in 0..2) { + glowPaint.maskFilter = if (pass < 2) blur else null + glowPaint.style = Paint.Style.STROKE; glowPaint.color = outlineColor() + c.drawPath(outline, glowPaint) + glowPaint.style = Paint.Style.FILL; glowPaint.color = accent + c.drawCircle(panel.left + h, panel.centerY(), sp(5.5f), glowPaint) + } + glowPaint.maskFilter = null + } + dFrame = bmp; dFrameKey = key + return bmp + } + + @VisibleForTesting + internal fun showForTest(snapshot: HudMetrics.Snapshot, engine: String, nowNs: Long) { + engineLabel = engine + snap = snapshot + lows = frames?.lows(nowNs) ?: FrameStats.Lows.EMPTY + fpsNow = frames?.fps ?: 0f + rebuild() + } + + @VisibleForTesting internal fun panelForTest(): RectF? = dPanel + @VisibleForTesting internal fun panelRadiusForTest(): Float = dRadius + @VisibleForTesting internal fun graphForTest(): RectF? = graphRect + + private fun drawChip(canvas: Canvas, rect: RectF) { + val r = sp(6f) + headerPaint.shader = null + headerPaint.color = Color.argb(235, Color.red(surfaceRgb), Color.green(surfaceRgb), Color.blue(surfaceRgb)) + canvas.drawRoundRect(rect, r, r, headerPaint) + strokePaint.strokeWidth = sp(1f) + strokePaint.color = accent + val h = strokePaint.strokeWidth / 2f + canvas.drawRoundRect(rect.left + h, rect.top + h, rect.right - h, rect.bottom - h, r, r, strokePaint) + val markH = rect.height() * 0.6f + val markW = DroidDeckMark.widthFor(markH) + DroidDeckMark.draw(canvas, rect.centerX() - markW / 2f, rect.centerY() - markH / 2f, markH, blend(colValue), accent) + } + + override fun onTouchEvent(event: MotionEvent): Boolean = lockController.onTouchEvent(event) + + internal val isDragging: Boolean get() = lockController.isDragging() + + private companion object { + const val REFRESH_MS = 500L + const val GRAPH_CLIP_MS = 49.9f + + fun parseIntOr(s: String?, d: Int): Int = try { s?.trim()?.toInt() ?: d } catch (e: Exception) { d } + + fun parseOutline(v: String?): Int = when (v?.trim()?.lowercase(Locale.US)) { + null -> 40; "off" -> 0; "soft" -> 40; "strong" -> 70 + else -> v.trim().toIntOrNull()?.coerceIn(0, 100) ?: 40 + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt b/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt new file mode 100644 index 0000000000..fcca0aaa2e --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt @@ -0,0 +1,262 @@ +package com.droiddeck.launcher.hud + +import java.io.File +import kotlin.math.roundToInt + +/** + * Frame statistics by MangoHud's rules, so the HUD and Steam's performance overlay agree: MangoHud + * overlay.cpp update_hud_info_with_frametime and hud_elements.cpp fps() / frame_timing(). The FPS is the + * frames counted over a sampling period of at least 500 ms, the frame time next to it is 1000 / FPS, and + * the graph holds the last 200 frame times (zeros until filled) on a fixed 0-50 ms scale, min and max + * taken over those 200. Average and lows are FusionHUD's own readouts. + */ +internal class FrameStats { + private val graph = FloatArray(GRAPH_FRAMES) + private var graphHead = 0 + private var lastPresentNs = 0L + private var lastFpsUpdateNs = 0L + private var framesSinceUpdate = 0 + + private val lowsRing = LongArray(LOWS_FRAMES) + private var lowsHead = 0 + private var lowsSize = 0 + private var cachedLows = Lows.EMPTY + private var cachedLowsNs = 0L + + private var sessionStartNs = 0L + private var sessionFrames = 0L + + @Volatile var fps = 0f + private set + + /** Completed sampling periods; MangoHud redraws its readouts when one completes. */ + @Volatile var fpsUpdates = 0L + private set + + /** Frames added so far; the HUD redraws its graph when this moves. */ + @Volatile var count = 0L + private set + + @Synchronized + fun add(frametimeNs: Long, timeNs: Long) { + if (frametimeNs <= 0L) return + if (lastPresentNs != 0L) { + graph[graphHead] = frametimeNs / 1e6f + graphHead = (graphHead + 1) % GRAPH_FRAMES + } + val elapsed = timeNs - lastFpsUpdateNs + if (elapsed >= FPS_PERIOD_NS) { + fps = (1e9 * framesSinceUpdate / elapsed).toFloat() + framesSinceUpdate = 0 + lastFpsUpdateNs = timeNs + fpsUpdates++ + } + lastPresentNs = timeNs + framesSinceUpdate++ + + if (frametimeNs < PAUSE_NS) { + lowsRing[lowsHead] = frametimeNs + lowsHead = (lowsHead + 1) % LOWS_FRAMES + if (lowsSize < LOWS_FRAMES) lowsSize++ + if (sessionStartNs == 0L) sessionStartNs = timeNs - frametimeNs + sessionFrames++ + } + count++ + } + + @Synchronized + fun reset() { + graph.fill(0f) + graphHead = 0 + lastPresentNs = 0L + lastFpsUpdateNs = 0L + framesSinceUpdate = 0 + lowsHead = 0 + lowsSize = 0 + cachedLows = Lows.EMPTY + cachedLowsNs = 0L + sessionStartNs = 0L + sessionFrames = 0L + fps = 0f + count++ + } + + /** MangoHud's frame time readout: 1000 / FPS. */ + fun frametimeMs(): Float = 1000f / maxOf(fps, 1f) + + /** The graph, oldest first, into [out] (GRAPH_FRAMES long). */ + @Synchronized + fun graph(out: FloatArray) { + for (i in 0 until GRAPH_FRAMES) out[i] = graph[(graphHead + i) % GRAPH_FRAMES] + } + + @Synchronized + fun graphMinMs(): Float = graph.min() + + @Synchronized + fun graphMaxMs(): Float = graph.max() + + /** Average over the frames this session, from the first frame to [nowNs]'s last frame. */ + @Synchronized + fun averageFps(): Float { + if (sessionFrames < 2 || lastPresentNs <= sessionStartNs) return 0f + return (1e9 * sessionFrames / (lastPresentNs - sessionStartNs)).toFloat() + } + + @Synchronized + fun sessionSeconds(nowNs: Long): Float = if (sessionStartNs == 0L) 0f else (nowNs - sessionStartNs) / 1e9f + + class Lows(val low1Fps: Float, val low01Fps: Float, val low001Fps: Float) { + companion object { + val EMPTY = Lows(0f, 0f, 0f) + } + } + + /** FPS at the 99th, 99.9th and 99.99th percentile frame time of the last LOWS_FRAMES frames. */ + fun lows(nowNs: Long): Lows { + val copy: LongArray + synchronized(this) { + if (cachedLows !== Lows.EMPTY && nowNs - cachedLowsNs < LOWS_RECOMPUTE_NS) return cachedLows + if (lowsSize < 2) return Lows.EMPTY + copy = LongArray(lowsSize) + val start = (lowsHead - lowsSize + LOWS_FRAMES) % LOWS_FRAMES + for (i in 0 until lowsSize) copy[i] = lowsRing[(start + i) % LOWS_FRAMES] + } + copy.sort() + fun at(p: Double): Float { + val ft = copy[(p * (copy.size - 1)).roundToInt().coerceIn(0, copy.size - 1)] + return if (ft > 0) (1e9 / ft).toFloat() else 0f + } + val result = Lows(at(0.99), at(0.999), at(0.9999)) + synchronized(this) { + cachedLows = result + cachedLowsNs = nowNs + } + return result + } + + companion object { + const val GRAPH_FRAMES = 200 + const val GRAPH_MAX_MS = 50f + const val FPS_PERIOD_NS = 500_000_000L + const val LOWS_FRAMES = 8192 + private const val PAUSE_NS = 1_000_000_000L + private const val LOWS_RECOMPUTE_NS = 250_000_000L + } +} + +/** + * Feeds [stats] with the frame times gamescope shares (the ones MangoHud shows). Sessions without the + * shared file, or where gamescope stopped sending, fall back to the frames DroidDeck's compositor shows, + * which stop at the screen's refresh rate. + */ +internal class GameFrameFeed(private val file: File, val stats: FrameStats = FrameStats()) { + private var handle = 0L + private var nextOpenNs = 0L + private var lastRingFrameNs = 0L + private var lastInfoNs = 0L + private val frametimes = LongArray(HudFrames.CAPACITY) + private val times = LongArray(HudFrames.CAPACITY) + private val info = IntArray(5) + @Volatile private var fromGamescope = false + private var lastCompositorNs = 0L + @Volatile private var compositorFrames = 0L // written by the compositor thread only + private var seenCompositorFrames = 0L + + @Volatile var engine = "" + private set + @Volatile var steamFocused = false + private set + @Volatile var pid = 0 + private set + @Volatile var outputWidth = 0 + private set + @Volatile var outputHeight = 0 + private set + @Volatile var refreshMilliHz = 0 + private set + + /** Main thread, once per display frame. True when new frames arrived. */ + fun poll(nowNs: Long): Boolean { + val compositorAdded = compositorFrames != seenCompositorFrames + seenCompositorFrames = compositorFrames + if (handle == 0L) { + if (nowNs < nextOpenNs) return compositorAdded + nextOpenNs = nowNs + REOPEN_NS + handle = runCatching { HudFrames.nativeOpen(file.path) }.getOrDefault(0L) + if (handle == 0L) return compositorAdded + // Frames already in the file were written before this reader started. + HudFrames.nativePoll(handle, frametimes, times) + } + val n = HudFrames.nativePoll(handle, frametimes, times) + if (n > 0) { + if (!fromGamescope) { + stats.reset() + fromGamescope = true + } + for (i in 0 until n) stats.add(frametimes[i], times[i]) + lastRingFrameNs = times[n - 1] + } else if (lastRingFrameNs != 0L && nowNs - lastRingFrameNs > LIVE_NS) { + fromGamescope = false + } + // A new session writes the file again from the start; reopen when gamescope has gone quiet. + if (n <= 0 && nowNs - maxOf(lastRingFrameNs, nextOpenNs - REOPEN_NS) > STALE_NS) close() + if (nowNs - lastInfoNs >= INFO_NS) { + lastInfoNs = nowNs + readInfo() + } + return n > 0 || compositorAdded + } + + /** Compositor thread: one frame shown on the panel. */ + fun onCompositorFrame(nowNs: Long) { + if (fromGamescope) { + lastCompositorNs = 0L + return + } + val last = lastCompositorNs + lastCompositorNs = nowNs + if (last != 0L) { + stats.add(nowNs - last, nowNs) + compositorFrames++ + } + } + + fun close() { + if (handle != 0L) HudFrames.nativeClose(handle) + handle = 0L + } + + private fun readInfo() { + val name = if (handle != 0L && fromGamescope) HudFrames.nativeInfo(handle, info) else null + if (name == null) { + engine = "" + return + } + pid = info[0] + outputWidth = info[1] + outputHeight = info[2] + refreshMilliHz = info[3] + steamFocused = info[4] != 0 + engine = engineLabel(name) + } + + companion object { + private const val REOPEN_NS = 2_000_000_000L + private const val LIVE_NS = 2_000_000_000L + private const val STALE_NS = 5_000_000_000L + private const val INFO_NS = 500_000_000L + + /** DroidDeck's mangoapp's names for gamescope's engine field (Valve's 20260902.1 build, app/main.cpp + * engine_type_from_str and overlay.h engines); gamescope sends "gamescope" when it knows none. */ + fun engineLabel(name: String): String = when (name) { + "DXVK" -> "DXVK" + "vkd3d" -> "VKD3D" + "mesa zink" -> "ZINK" + "Damavand" -> "DAMAVAND" + "Feral3D" -> "Feral3D" + "gamescope", "" -> "GAMESCOPE" + else -> "VULKAN" + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/hud/HudFrames.kt b/app/src/main/java/com/droiddeck/launcher/hud/HudFrames.kt new file mode 100644 index 0000000000..63a9a7945d --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/hud/HudFrames.kt @@ -0,0 +1,17 @@ +package com.droiddeck.launcher.hud + +/** Reader for the frame-times file gamescope patch 0125 writes (hudframes.c). */ +internal object HudFrames { + init { + System.loadLibrary("droiddeckwayland") + } + + /** Under the Linux root: the session exports /run/droiddeck-hud/frames to gamescope. */ + const val PATH = "run/droiddeck-hud/frames" + const val CAPACITY = 1024 + + @JvmStatic external fun nativeOpen(path: String): Long + @JvmStatic external fun nativeClose(handle: Long) + @JvmStatic external fun nativePoll(handle: Long, frametimes: LongArray, times: LongArray): Int + @JvmStatic external fun nativeInfo(handle: Long, info: IntArray): String? +} diff --git a/app/src/main/java/com/droiddeck/launcher/hud/HudLockController.java b/app/src/main/java/com/droiddeck/launcher/hud/HudLockController.java new file mode 100644 index 0000000000..c5d75b4e5f --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/hud/HudLockController.java @@ -0,0 +1,265 @@ +/* + * FusionHUD — a lightweight in-game performance HUD for Android / Winlator overlays. + * Copyright (C) The412Banner + * + * Licensed under the GNU General Public License v3.0 (see LICENSE), with an + * ADDITIONAL attribution requirement under GPL-3.0 §7(b) (see ATTRIBUTION.md): + * any use, fork, or distribution must preserve credit to "The412Banner" and a + * link to https://github.com/The412Banner/FusionHUD in the project documentation + * AND in the in-app credits/about screen. + * + * Ported to DroidDeck from FusionHUD (Bannerlator's HUD); DroidDeck changes are marked in the code. + */ + +package com.droiddeck.launcher.hud; + +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.graphics.Path; +import android.graphics.RectF; +import android.os.SystemClock; +import android.view.GestureDetector; +import android.view.MotionEvent; +import android.view.View; + +import java.util.function.BiConsumer; +import java.util.function.Consumer; + +/** + * Shared touch + lock behaviour for every in-game performance HUD (classic FrameRating(+Horizontal), + * GameHub PerfHudView, GameNative PerformanceHudView, and the Fusion HUD). One place so the four + * overlays can't drift: + * + *
    + *
  • tap → {@link Callbacks#onTap()} (orientation-toggle for the first three; size-cycle for + * Fusion) — a no-op that only re-flashes the lock badge while locked.
  • + *
  • drag → moves the host view and, on release, {@link Callbacks#onMoved} to persist the + * position — disabled (frozen) while locked.
  • + *
  • long-press → toggles {@code hudLocked}, persisted via {@link Callbacks#onLockChanged} + * and kept in sync with the "Lock in place" menu chip. Works locked or unlocked (so a long-press + * always unlocks).
  • + *
+ * + *

On every lock/unlock (and on a blocked gesture while locked) a small padlock badge fades in → + * holds → fades out in a corner of the panel. The fade is driven by a self-reposting Runnable that + * invalidates only while visible — nothing runs on the present path, nothing animates at rest. + * + *

All methods are Main-thread only (touch + draw), matching the epoll-thread rule: the views feed + * this from {@code onTouchEvent}/{@code dispatchDraw}, never from a present tick. + */ +public class HudLockController { + + public interface Callbacks { + /** Unlocked single tap: orientation-toggle (classic/gamehub/gamenative) or size-cycle (fusion). */ + void onTap(); + /** Drag released (unlocked): persist the new (x, y). */ + void onMoved(float x, float y); + /** Lock toggled by long-press: persist {@code hudLocked} + sync the menu chip. */ + void onLockChanged(boolean locked); + } + + // Fade timing (ms): in → hold → out. Lock/unlock hold ~1.5 s; a blocked-gesture re-flash is shorter. + private static final long FADE_IN_MS = 160; + private static final long HOLD_TOGGLE_MS = 1500; + private static final long HOLD_REFLASH_MS = 750; + private static final long FADE_OUT_MS = 420; + private static final long FRAME_MS = 32; + + private final View view; + private final Callbacks cb; + private final GestureDetector detector; + + private boolean locked = false; + + // Drag state + private float downRawX, downRawY, startX, startY; + private boolean dragging = false; + + // Fade state + private long fadeStart = 0; + private long holdMs = HOLD_TOGGLE_MS; + private boolean fadeShowLocked = false; + + private final Paint iconFill = new Paint(Paint.ANTI_ALIAS_FLAG); + private final Paint iconStroke = new Paint(Paint.ANTI_ALIAS_FLAG); + + public HudLockController(Context context, View view, Callbacks cb) { + this.view = view; + this.cb = cb; + this.detector = new GestureDetector(context, new Listener()); + this.detector.setIsLongpressEnabled(true); + iconFill.setStyle(Paint.Style.FILL); + iconStroke.setStyle(Paint.Style.STROKE); + iconStroke.setStrokeCap(Paint.Cap.ROUND); + iconStroke.setStrokeJoin(Paint.Join.ROUND); + } + + /** Set lock state from config (applyConfig) WITHOUT firing the persist callback. */ + public void setLocked(boolean locked) { this.locked = locked; } + + public boolean isLocked() { return locked; } + + public boolean isDragging() { return dragging; } + + /** Feed from the host view's onTouchEvent. Always consumes (mirrors the legacy manual handlers). */ + public boolean onTouchEvent(MotionEvent event) { + detector.onTouchEvent(event); + int action = event.getActionMasked(); + if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) { + if (dragging && !locked) cb.onMoved(view.getX(), view.getY()); + dragging = false; + } + return true; + } + + private final class Listener extends GestureDetector.SimpleOnGestureListener { + @Override + public boolean onDown(MotionEvent e) { + downRawX = e.getRawX(); + downRawY = e.getRawY(); + startX = view.getX(); + startY = view.getY(); + dragging = false; + return true; + } + + @Override + public void onLongPress(MotionEvent e) { + // Long-press always toggles — this is the only gesture that still works while locked. + locked = !locked; + cb.onLockChanged(locked); + flash(locked, HOLD_TOGGLE_MS); + } + + @Override + public boolean onSingleTapUp(MotionEvent e) { + if (locked) { + flash(true, HOLD_REFLASH_MS); // intentionally locked — remind the user + } else { + cb.onTap(); + } + return true; + } + + @Override + public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { + if (locked) { + if (!dragging) flash(true, HOLD_REFLASH_MS); + dragging = true; // mark so the blocked drag doesn't fall through to a tap + return true; + } + view.setX(startX + (e2.getRawX() - downRawX)); + view.setY(startY + (e2.getRawY() - downRawY)); + dragging = true; + return true; + } + } + + // ---- Fade badge ------------------------------------------------------- + private void flash(boolean showLocked, long hold) { + fadeShowLocked = showLocked; + holdMs = hold; + fadeStart = SystemClock.elapsedRealtime(); + view.removeCallbacks(fadeTick); + view.post(fadeTick); + } + + private final Runnable fadeTick = new Runnable() { + @Override + public void run() { + view.invalidate(); + if (currentAlpha() > 0f) view.postDelayed(this, FRAME_MS); + } + }; + + private float currentAlpha() { + if (fadeStart == 0) return 0f; + long e = SystemClock.elapsedRealtime() - fadeStart; + if (e < 0) return 0f; + if (e < FADE_IN_MS) return e / (float) FADE_IN_MS; + long holdEnd = FADE_IN_MS + holdMs; + if (e < holdEnd) return 1f; + long outEnd = holdEnd + FADE_OUT_MS; + if (e < outEnd) return 1f - (e - holdEnd) / (float) FADE_OUT_MS; + return 0f; + } + + private static int withAlpha(int color, float a) { + return Color.argb(Math.round(255 * a), Color.red(color), Color.green(color), Color.blue(color)); + } + + /** + * Draw the padlock badge in the top-right of the panel if a fade is in progress. Call from the + * host's onDraw (plain View) or dispatchDraw (ViewGroup), after the content. + * + *

No background box: the glyph is drawn twice — a slightly expanded, thicker semi-transparent + * black "halo" pass for legibility on any game frame, then the white glyph on top — so it reads as + * a floating icon, not an opaque tile. + */ + public void drawBadge(Canvas canvas) { + float a = currentAlpha(); + if (a <= 0f) return; + float d = view.getResources().getDisplayMetrics().density; + float size = 15f * d; + float margin = 4f * d; + float right = view.getWidth() - margin; + float left = right - size; + float top = margin; + + float cx = (left + right) / 2f; + float bottom = top + size; + float bodyTop = top + size * 0.46f; + float bodyLeft = left + size * 0.14f; + float bodyRight = right - size * 0.14f; + float r = size * 0.2f; + float shackleTop = top + size * 0.08f; + + // Pass 1: dark halo (expanded body, thicker shackle) for contrast; Pass 2: white glyph. + drawLock(canvas, cx, bodyTop, bodyLeft, bodyRight, bottom, r, shackleTop, d, + Color.argb(Math.round(150 * a), 0, 0, 0), 3.0f * d, 0.9f * d, false); + drawLock(canvas, cx, bodyTop, bodyLeft, bodyRight, bottom, r, shackleTop, d, + withAlpha(0xFFFFFFFF, a), 1.7f * d, 0f, true); + } + + /** One padlock pass. {@code halo} inflates the body/shackle in dark; the white pass punches the keyhole. */ + private void drawLock(Canvas canvas, float cx, float bodyTop, float bodyLeft, float bodyRight, + float bottom, float r, float shackleTop, float d, + int color, float strokeW, float expand, boolean punchKeyhole) { + iconFill.setColor(color); + iconStroke.setColor(color); + iconStroke.setStrokeWidth(strokeW); + + // Body + canvas.drawRoundRect(bodyLeft - expand, bodyTop - expand, bodyRight + expand, bottom + expand, + 2.4f * d, 2.4f * d, iconFill); + if (punchKeyhole) { + int prev = iconFill.getColor(); + iconFill.setColor(Color.argb(Color.alpha(color), 0, 0, 0)); + canvas.drawCircle(cx, (bodyTop + bottom) / 2f, 1.6f * d, iconFill); + iconFill.setColor(prev); + } + + RectF arc = new RectF(cx - r, shackleTop, cx + r, shackleTop + 2f * r); + if (fadeShowLocked) { + // Closed: both legs run straight down into the body. + Path p = new Path(); + p.addArc(arc, 180f, 180f); + p.moveTo(cx - r, shackleTop + r); p.lineTo(cx - r, bodyTop); + p.moveTo(cx + r, shackleTop + r); p.lineTo(cx + r, bodyTop); + canvas.drawPath(p, iconStroke); + } else { + // Open, clearly to the LEFT: the RIGHT leg stays seated in the body; the arc + LEFT leg + // hinge up-and-left off the right attachment so the left leg lifts well clear of the body. + canvas.drawLine(cx + r, shackleTop + r, cx + r, bodyTop, iconStroke); // fixed right leg + Path p = new Path(); + p.addArc(arc, 180f, 180f); + p.moveTo(cx - r, shackleTop + r); p.lineTo(cx - r, bodyTop); // full-length left leg + canvas.save(); + canvas.rotate(-42f, cx + r, shackleTop + r); + canvas.drawPath(p, iconStroke); + canvas.restore(); + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/hud/HudMetrics.java b/app/src/main/java/com/droiddeck/launcher/hud/HudMetrics.java new file mode 100644 index 0000000000..88cbc87074 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/hud/HudMetrics.java @@ -0,0 +1,1628 @@ +/* + * FusionHUD — a lightweight in-game performance HUD for Android / Winlator overlays. + * Copyright (C) The412Banner + * + * Licensed under the GNU General Public License v3.0 (see LICENSE), with an + * ADDITIONAL attribution requirement under GPL-3.0 §7(b) (see ATTRIBUTION.md): + * any use, fork, or distribution must preserve credit to "The412Banner" and a + * link to https://github.com/The412Banner/FusionHUD in the project documentation + * AND in the in-app credits/about screen. + * + * Ported to DroidDeck from FusionHUD (Bannerlator's HUD); DroidDeck changes are marked in the code. + */ + +package com.droiddeck.launcher.hud; + +import android.app.ActivityManager; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.BatteryManager; +import android.os.Build; +import android.os.SystemClock; + + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; + +/** + * Shared live-metric collector for every performance HUD overlay. This is the single, device-complete + * implementation of the sysfs / Android readers — no overlay should re-read sysfs itself, so the GPU + * discovery / thermal / battery logic never diverges. + * + *

Ported and hardened from GameNative's {@code PerformanceHudView} readers, which are far more + * device-complete than the two-fixed-path versions previously inlined in the classic overlays: + *

    + *
  • GPU load — ~10 static candidates plus a dynamic {@code /sys/class/devfreq} + + * {@code /sys/devices/virtual/devfreq} walk for gpu/mali/g3d/kgsl nodes; handles gpubusy + * (busy/total), Mali gpuinfo (delta-ms/wall-ms, needs state between calls) and generic percent + * nodes. Discovery cached.
  • + *
  • CPU usage — {@code /proc/stat} aggregate delta with a scaling-frequency fallback for devices + * where {@code /proc/stat} is restricted.
  • + *
  • Thermal — prioritized CPU zone discovery (cpu-silicon > cpu-0 > cpu > soc > + * s5p-tmu > cputop > tsens > cluster > big/little) and a separate prioritized GPU zone + * discovery plus kgsl/mali direct paths. milli-°C normalization + 1..150 sanity clamp.
  • + *
  • Battery — % capacity, power W, runtime-left estimate (charge_counter / current_now, smoothed), + * battery temperature, plus the dual-battery current-sum for the classic overlays.
  • + *
+ * + *

Every getter is null / absent-safe: nullable getters return {@code null} when a metric cannot be + * read (the overlay hides that row, matching GameNative behavior); the legacy non-null getters return + * 0 in that case. Not thread-safe; call from a single refresh thread per instance. + */ +public class HudMetrics { + private final Context context; + + public HudMetrics(Context context) { this.context = context; } + + // DroidDeck: the readings Steam's performance overlay shows come from MangoReadings, so both agree. + private MangoReadings mango; + public void setMangoReadings(MangoReadings readings) { mango = readings; } + + // ======================================================================= + // CPU usage + // ======================================================================= + private Long lastCpuTotal = null; + private Long lastCpuIdle = null; + + /** + * Overall device CPU usage 0..100 computed from the /proc/stat delta since the last call, with a + * scaling-frequency fallback. Returns null only when neither source is readable. + */ + public Integer getCpuUsagePercent() { + String line = readFirstLine("/proc/stat"); + if (line != null) { + String[] parts = line.trim().split("\\s+"); + if (parts.length >= 5 && "cpu".equals(parts[0])) { + long total = 0, idle = 0, iowait = 0; + boolean ok = true; + for (int i = 1; i < parts.length; i++) { + try { + long v = Long.parseLong(parts[i]); + total += v; + if (i == 4) idle = v; + else if (i == 5) iowait = v; + } catch (NumberFormatException e) { ok = false; break; } + } + if (ok) { + long idleTotal = idle + iowait; + Long prevTotal = lastCpuTotal, prevIdle = lastCpuIdle; + lastCpuTotal = total; + lastCpuIdle = idleTotal; + if (prevTotal != null && prevIdle != null) { + long dTotal = total - prevTotal; + long dIdle = idleTotal - prevIdle; + if (dTotal > 0) { + long usage = (Math.max(0, dTotal - dIdle) * 100L) / dTotal; + return clampPercent((int) usage); + } + } + // First sample seeds the delta — fall through to the frequency estimate so the + // very first read still returns something. + } + } + } + return readCpuUsagePercentFromFrequency(); + } + + private Integer readCpuUsagePercentFromFrequency() { + long currentTotal = 0, maxTotal = 0; + int cores = Runtime.getRuntime().availableProcessors(); + for (int i = 0; i < cores; i++) { + Long cur = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/scaling_cur_freq"); + Long max = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/cpuinfo_max_freq"); + if (cur != null && max != null && max > 0L) { + currentTotal += Math.max(0, Math.min(cur, max)); + maxTotal += max; + } + } + if (maxTotal <= 0L) return null; + return clampPercent((int) ((currentTotal * 100L) / maxTotal)); + } + + /** Legacy non-null accessor (0 when unavailable). Kept for {@code PerfHudView}. */ + public float getCPUUsage() { + Integer p = getCpuUsagePercent(); + return p == null ? 0f : p; + } + + // ======================================================================= + // GPU load + // ======================================================================= + private List gpuUsagePathsCache = null; + private Long lastMaliGpuInfoMs = null; + private long lastMaliGpuInfoWallMs = 0L; + + /** GPU utilisation 0..100, or null when no readable source is found on this device. */ + public Integer getGpuUsagePercent() { + for (String path : discoverGpuUsagePaths()) { + Integer p = readGpuUsageSample(path); + if (p != null) return p; + } + return null; + } + + /** Legacy non-null accessor (0 when unavailable). Kept for {@code PerfHudView}. */ + public int getGPULoad() { + Integer p = getGpuUsagePercent(); + return p == null ? 0 : p; + } + + private List discoverGpuUsagePaths() { + if (gpuUsagePathsCache != null) return gpuUsagePathsCache; + LinkedHashSet candidates = new LinkedHashSet<>(); + + for (String p : GPU_USAGE_STATIC_PATHS) { + if (new File(p).canRead()) candidates.add(p); + } + + // Vendor platform nodes with hashed/addressed names we can't hard-code (e.g. + // /sys/devices/platform/13000000.mali/utilisation, .../gpusysfs/gpu_busy, panfrost, sgpu). + File platformDir = new File("/sys/devices/platform"); + File[] platformNodes = platformDir.listFiles(File::isDirectory); + if (platformNodes != null) { + for (File node : platformNodes) { + String name = node.getName().toLowerCase(Locale.US); + boolean looksLikeGpu = false; + for (String t : GPU_NODE_TOKENS) { + if (name.contains(t)) { looksLikeGpu = true; break; } + } + if (!looksLikeGpu) continue; + for (String fileName : GPU_USAGE_FILES) { + File f = new File(node, fileName); + if (f.canRead()) candidates.add(f.getPath()); + } + } + } + + File[] devfreqRoots = { + new File("/sys/class/devfreq"), + new File("/sys/devices/virtual/devfreq"), + }; + for (File root : devfreqRoots) { + if (!root.isDirectory()) continue; + File[] nodeDirs = root.listFiles(File::isDirectory); + if (nodeDirs == null) continue; + for (File node : nodeDirs) { + String nodePath = node.getPath().toLowerCase(Locale.US); + boolean looksLikeGpu = false; + for (String t : GPU_NODE_TOKENS) { + if (nodePath.contains(t)) { looksLikeGpu = true; break; } + } + for (String fileName : GPU_USAGE_FILES) { + File f = new File(node, fileName); + if (!f.canRead()) continue; + if (looksLikeGpu || fileName.equals("gpu_busy_percentage") + || fileName.equals("gpu_busy_percent") || fileName.equals("gpuinfo")) { + candidates.add(f.getPath()); + } + } + } + } + + gpuUsagePathsCache = new ArrayList<>(candidates); + return gpuUsagePathsCache; + } + + // Ordered, world-readable-when-present GPU utilisation nodes across the vendors we've seen: + // Adreno KGSL, Mali (misc + Exynos vendor), PowerVR, and amdgpu-style sysfs (Samsung Xclipse / + // "sgpu", AMD-on-Exynos). readGpuUsageSample() knows how to parse each filename shape. + private static final String[] GPU_USAGE_STATIC_PATHS = { + "/sys/class/kgsl/kgsl-3d0/gpubusy", + "/sys/class/kgsl/kgsl-3d0/gpu_busy_percentage", + "/sys/class/kgsl/kgsl-3d0/devfreq/gpu_load", + "/sys/class/misc/mali0/device/utilisation", + "/sys/class/misc/mali0/device/utilization", + "/sys/class/misc/mali0/device/gpuinfo", + "/sys/devices/platform/mali/utilization", + "/sys/kernel/gpu/gpu_busy", + "/sys/devices/platform/gpusysfs/gpu_busy", // Exynos Mali vendor node + "/sys/class/misc/pvrsrvkm/device/utilisation", + "/sys/class/pvr/utilisation", // PowerVR (Rogue) sysfs + "/sys/class/pvr/gpu_utilisation", + "/sys/class/drm/card0/device/gpu_busy_percent", // amdgpu / Xclipse (sgpu), 0..100 + "/sys/class/devfreq/gpu/load", + // ── Additive cross-vendor fallbacks (appended LAST: tried only after every path above + // misses, so a device that already resolves — e.g. Adreno kgsl — never reaches these). ── + "/sys/kernel/ged/hal/gpu_utilization", // MediaTek GED: " " → loading% + "/sys/module/ged/parameters/gpu_loading", // MediaTek GED module param, plain percent + }; + // Percent-bearing filenames scanned under each devfreq / platform GPU node. + private static final String[] GPU_USAGE_FILES = { + "gpu_busy_percentage", "gpu_busy_percent", "gpu_load", "utilisation", "utilization", + "load", "gpu_busy", "gpuinfo", + }; + // Substrings that mark a devfreq / platform node as the GPU, across vendors. + private static final String[] GPU_NODE_TOKENS = { + "gpu", "mali", "g3d", "kgsl", "panfrost", "pvr", "powervr", "xclipse", "sgpu", + }; + + private Integer readGpuUsageSample(String path) { + String fileName = path.substring(path.lastIndexOf('/') + 1); + switch (fileName) { + case "gpubusy": { + String raw = readFirstLine(path); + if (raw == null) return null; + String[] parts = raw.trim().split("\\s+"); + if (parts.length < 2) return null; + Long busy = parseLong(parts[0]); + Long total = parseLong(parts[1]); + if (busy == null || total == null || total <= 0L) return null; + return clampPercent((int) ((busy * 100L) / total)); + } + case "gpuinfo": { + // Mali multi-line node: the GPU busy time (ms) is the last token of line 1. Utilisation + // is the delta over wall-clock delta between two reads, so it needs state. + String line = readNthLine(path, 1); + if (line == null) return null; + String[] toks = line.trim().split("\\s+"); + Long gpuMs = parseLong(toks[toks.length - 1]); + if (gpuMs == null) return null; + long now = SystemClock.elapsedRealtime(); + Long prevMs = lastMaliGpuInfoMs; + long prevWall = lastMaliGpuInfoWallMs; + lastMaliGpuInfoMs = gpuMs; + lastMaliGpuInfoWallMs = now; + if (prevMs == null || prevWall <= 0L) return null; + long wallDelta = now - prevWall; + if (wallDelta <= 0L) return null; + long gpuDelta = Math.max(0L, gpuMs - prevMs); + return clampPercent((int) ((gpuDelta * 100L) / wallDelta)); + } + default: + return readPercentFromLine(path); + } + } + + private Integer readPercentFromLine(String path) { + String raw = readFirstLine(path); + if (raw == null) return null; + for (String tok : raw.trim().split("\\s+")) { + String digits = tok.replaceAll("[^0-9]", ""); + if (!digits.isEmpty()) { + Integer v = parseInt(digits); + return v == null ? null : clampPercent(v); + } + } + return null; + } + + // ======================================================================= + // RAM + // ======================================================================= + public float getRAMPercent() { + ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); + ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo(); + am.getMemoryInfo(mi); + if (mi.totalMem <= 0) return 0; + return (mi.totalMem - mi.availMem) * 100f / mi.totalMem; + } + + /** Used RAM as "x.xGB" (or "yMB" below 1 GB), matching GameNative's HUD text. */ + public String getUsedRamText() { + ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); + if (am == null) return "—"; + ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo(); + am.getMemoryInfo(mi); + long usedBytes = Math.max(0L, mi.totalMem - mi.availMem); + double usedGb = usedBytes / (1024.0 * 1024.0 * 1024.0); + if (usedGb >= 1.0) return String.format(Locale.US, "%.1fGB", usedGb); + return (usedBytes / (1024L * 1024L)) + "MB"; + } + + // ======================================================================= + // Temperature + // ======================================================================= + private List thermalZonesCache = null; // each entry: {type, tempPath} + + /** Legacy non-null CPU-temperature accessor in °C (0 when unavailable). Kept for {@code PerfHudView}. */ + public float getTemperature() { + Integer t = getCpuTempC(); + return t == null ? 0f : t; + } + + /** Hottest representative CPU temperature in °C, or null when no CPU zone is readable. */ + public Integer getCpuTempC() { + return readTemperatureC(discoverPrioritizedCpuTempPaths()); + } + + /** GPU temperature in °C, or null when no GPU sensor is readable. */ + public Integer getGpuTempC() { + ArrayList paths = new ArrayList<>(); + paths.add("/sys/class/kgsl/kgsl-3d0/temp"); + paths.add("/sys/class/kgsl/kgsl-3d0/devfreq/temp"); + paths.add("/sys/class/misc/mali0/device/temp"); + paths.add("/sys/kernel/gpu/temp"); + paths.addAll(discoverPrioritizedGpuTempPaths()); + return readTemperatureC(paths); + } + + private List discoverPrioritizedCpuTempPaths() { + return prioritizePaths(type -> { + if (type.contains("gpu")) return null; // never mistake a GPU zone for CPU + if (type.contains("cpu-silicon")) return 0; + if (type.contains("cpu-0")) return 1; + if (type.contains("cpuss")) return 2; // Qualcomm cpuss composite + if (type.contains("mtktscpu")) return 2; // MediaTek CPU thermal + if (type.contains("cpu")) return 2; // cpu, cpu-*-usr, cpu_thermal, cpu_center + if (type.contains("s5p-tmu")) return 3; // Exynos TMU + if (type.contains("soc")) return 4; + if (type.contains("cputop")) return 5; + if (type.contains("tsens")) return 6; // Qualcomm tsens aggregate + if (type.contains("cluster")) return 7; + if (type.contains("big") || type.contains("little")) return 8; + return null; + }); + } + + private List discoverPrioritizedGpuTempPaths() { + return prioritizePaths(type -> { + if (type.contains("gpu-silicon")) return 0; + if (type.contains("gpuss")) return 1; // Qualcomm gpuss + if (type.contains("mtktsgpu")) return 1; // MediaTek GPU thermal + if (type.contains("gpu-virt")) return 2; + if (type.contains("gpu")) return 2; + if (type.contains("g3d")) return 3; // Exynos Mali (g3d) + if (type.contains("kgsl")) return 4; + if (type.contains("mali")) return 5; + if (type.contains("xclipse") || type.contains("sgpu")) return 6; + return null; + }); + } + + private interface Ranker { Integer rank(String type); } + + private List prioritizePaths(Ranker ranker) { + List zones = discoverAllThermalZones(); + ArrayList order = new ArrayList<>(); // {index, rank} + for (int i = 0; i < zones.size(); i++) { + Integer r = ranker.rank(zones.get(i)[0]); + if (r != null) order.add(new int[]{i, r}); + } + // Sort by rank, then by path for determinism. + order.sort((a, b) -> { + if (a[1] != b[1]) return Integer.compare(a[1], b[1]); + return zones.get(a[0])[1].compareTo(zones.get(b[0])[1]); + }); + ArrayList result = new ArrayList<>(); + for (int[] e : order) result.add(zones.get(e[0])[1]); + return result; + } + + private List discoverAllThermalZones() { + if (thermalZonesCache != null) return thermalZonesCache; + ArrayList zones = new ArrayList<>(); + LinkedHashSet seenPaths = new LinkedHashSet<>(); + File[] thermalDirs = { + new File("/sys/class/thermal"), + new File("/sys/devices/virtual/thermal"), + }; + for (File dir : thermalDirs) { + File[] zoneDirs = dir.listFiles((d, name) -> name.startsWith("thermal_zone")); + if (zoneDirs == null) continue; + for (File zone : zoneDirs) { + if (!zone.isDirectory()) continue; + String type = readFirstLine(new File(zone, "type").getPath()); + if (type == null) continue; + type = type.trim().toLowerCase(Locale.US); + String tempPath = new File(zone, "temp").getPath(); + if (seenPaths.add(tempPath)) zones.add(new String[]{type, tempPath}); + } + } + thermalZonesCache = zones; + return zones; + } + + private Integer readTemperatureC(List paths) { + LinkedHashSet seen = new LinkedHashSet<>(); + for (String path : paths) { + if (!seen.add(path)) continue; + Integer raw = readIntFromLine(path); + if (raw == null) continue; + // Round to nearest degree for milli-°C sources; sanity-clamp to reject offline sensors. + int celsius = raw > 1000 ? (raw + 500) / 1000 : raw; + if (celsius >= 1 && celsius <= 150) return celsius; + } + return null; + } + + /** The first path in {@code paths} that yields a plausible reading, or null. */ + private String resolveTempPath(List paths) { + LinkedHashSet seen = new LinkedHashSet<>(); + for (String path : paths) { + if (!seen.add(path)) continue; + Integer raw = readIntFromLine(path); + if (raw == null) continue; + int celsius = raw > 1000 ? (raw + 500) / 1000 : raw; + if (celsius >= 1 && celsius <= 150) return path; + } + return null; + } + + // ======================================================================= + // Temperature danger bands (green / amber / red) + // ======================================================================= + + public enum TempSensor { CPU, GPU, BATTERY } + + /** Amber and red onset in °C. Always °C internally — conversion happens at format time only. */ + public static final class Thresholds { + public final int amberC; + public final int redC; + Thresholds(int amberC, int redC) { this.amberC = amberC; this.redC = redC; } + } + + public static final int TEMP_COLOR_OK = 0xFF66BB6A; + public static final int TEMP_COLOR_AMBER = 0xFFFFB74D; + public static final int TEMP_COLOR_RED = 0xFFEF5350; + + // Tier-2 fallbacks, used when the device declares no usable trip points. Battery is the only one + // with a well-grounded number (Li-ion); CPU/GPU vary enough between parts that these are a + // deliberately conservative guess — which is exactly why trip points are preferred. + private static final int DEFAULT_RED_CPU = 90; + private static final int DEFAULT_RED_GPU = 90; + private static final int DEFAULT_RED_BAT = 48; + + /** Amber sits a proportional step below red, which scales sensibly across both CPU/GPU and battery ranges. */ + public static int amberForRed(int redC) { + return Math.round(redC * 0.88f); + } + + /** Parsed temperature display options, shared by every overlay so they can't disagree. */ + public static final class TempDisplay { + public final boolean fahrenheit; + public final boolean colorBands; + public final boolean auto; + public final int redCpu, redGpu, redBat; + + public TempDisplay(boolean fahrenheit, boolean colorBands, boolean auto, + int redCpu, int redGpu, int redBat) { + this.fahrenheit = fahrenheit; + this.colorBands = colorBands; + this.auto = auto; + this.redCpu = redCpu; + this.redGpu = redGpu; + this.redBat = redBat; + } + + public static TempDisplay from(KeyValueSet cfg) { + if (cfg == null) return new TempDisplay(false, true, true, + DEFAULT_RED_CPU, DEFAULT_RED_GPU, DEFAULT_RED_BAT); + return new TempDisplay( + cfg.get("tempUnit", "c").equalsIgnoreCase("f"), + !cfg.get("tempBands", "1").equals("0"), + !cfg.get("tempAuto", "1").equals("0"), + parseInt(cfg.get("tempRedCpu", ""), DEFAULT_RED_CPU), + parseInt(cfg.get("tempRedGpu", ""), DEFAULT_RED_GPU), + parseInt(cfg.get("tempRedBat", ""), DEFAULT_RED_BAT)); + } + + int manualRedFor(TempSensor s) { + switch (s) { + case GPU: return redGpu; + case BATTERY: return redBat; + default: return redCpu; + } + } + + private static int parseInt(String s, int fallback) { + try { return s == null || s.isEmpty() ? fallback : Integer.parseInt(s.trim()); } + catch (NumberFormatException e) { return fallback; } + } + } + + // Trip points are a device constant — resolve once per sensor and keep it. + private final java.util.EnumMap autoThresholdCache = + new java.util.EnumMap<>(TempSensor.class); + private final java.util.EnumSet autoThresholdResolved = + java.util.EnumSet.noneOf(TempSensor.class); + + /** + * Bands for a sensor. Manual mode uses the user's red point; Auto prefers the device's OWN + * declared thermal trip points (per-device truth — a handheld with active cooling and a phone on + * the same SoC throttle at very different points) and falls back to {@link #DEFAULT_RED_CPU} etc. + */ + public Thresholds resolveThresholds(TempSensor sensor, TempDisplay display) { + if (display != null && !display.auto) { + int red = display.manualRedFor(sensor); + return new Thresholds(amberForRed(red), red); + } + if (!autoThresholdResolved.contains(sensor)) { + autoThresholdResolved.add(sensor); + Thresholds fromDevice = readTripPointThresholds(sensor); + if (fromDevice != null) autoThresholdCache.put(sensor, fromDevice); + } + Thresholds cached = autoThresholdCache.get(sensor); + if (cached != null) return cached; + int red = sensor == TempSensor.GPU ? DEFAULT_RED_GPU + : sensor == TempSensor.BATTERY ? DEFAULT_RED_BAT + : DEFAULT_RED_CPU; + return new Thresholds(amberForRed(red), red); + } + + /** + * Bands from the kernel's declared trip points for the zone we actually read this sensor from: + * amber ← the lowest sane {@code passive} trip, red ← the lowest sane {@code hot}/{@code critical}. + * + *

Returns null unless a usable red point is found. Two real traps this guards against: some + * zones aren't temperature sensors at all (a Snapdragon's {@code pm8550-bcl-lvl0} battery-current + * limiter reports {@code trip_point_0_temp = 1} with type {@code passive}), and the GPU is often + * read from a non-thermal_zone node ({@code /sys/class/kgsl/...}) that has no trip points. + */ + private Thresholds readTripPointThresholds(TempSensor sensor) { + String tempPath; + switch (sensor) { + case GPU: + tempPath = resolveTempPath(discoverPrioritizedGpuTempPaths()); + break; + case BATTERY: + return null; // battery temp comes from BatteryManager, not a thermal zone + default: + tempPath = resolveTempPath(discoverPrioritizedCpuTempPaths()); + } + if (tempPath == null) return null; + File zoneDir = new File(tempPath).getParentFile(); + if (zoneDir == null) return null; + + File[] tripTemps = zoneDir.listFiles( + (d, name) -> name.startsWith("trip_point_") && name.endsWith("_temp")); + if (tripTemps == null || tripTemps.length == 0) return null; + + Integer amber = null, red = null; + for (File tripTemp : tripTemps) { + Integer raw = readIntFromLine(tripTemp.getPath()); + if (raw == null) continue; + int celsius = raw > 1000 ? (raw + 500) / 1000 : raw; + // Reject anything that isn't plausibly a thermal trip — this is what filters out the + // battery-current-limiter zones whose "trip point" is a level index, not a temperature. + if (celsius < 20 || celsius > 120) continue; + + String typePath = tripTemp.getPath().replaceAll("_temp$", "_type"); + String type = readFirstLine(typePath); + if (type == null) continue; + type = type.trim().toLowerCase(Locale.US); + + if (type.contains("critical") || type.contains("hot")) { + if (red == null || celsius < red) red = celsius; + } else if (type.contains("passive")) { + if (amber == null || celsius < amber) amber = celsius; + } + } + if (red == null) return null; + if (amber == null || amber >= red) amber = amberForRed(red); + return new Thresholds(amber, red); + } + + /** Band colour for a reading, or {@code fallbackColor} when banding is off or the value is unusable. */ + public static int tempColor(Float celsius, Thresholds t, TempDisplay display, int fallbackColor) { + if (celsius == null || t == null || display == null || !display.colorBands) return fallbackColor; + if (celsius >= t.redC) return TEMP_COLOR_RED; + if (celsius >= t.amberC) return TEMP_COLOR_AMBER; + return TEMP_COLOR_OK; + } + + /** Formats a °C reading in the user's unit. Thresholds stay °C; only display converts. */ + public static String formatTemp(float celsius, TempDisplay display, boolean oneDecimal) { + boolean f = display != null && display.fahrenheit; + float value = f ? celsius * 9f / 5f + 32f : celsius; + String unit = f ? "°F" : "°C"; + return oneDecimal + ? String.format(Locale.ENGLISH, "%.1f%s", value, unit) + : String.format(Locale.ENGLISH, "%d%s", Math.round(value), unit); + } + + // ======================================================================= + // Battery + // ======================================================================= + public static final class Battery { + public final float watts; + public final boolean charging; + public final Integer percent; // 0..100 or null + public final Integer tempC; // rounded °C or null + public final String runtimeText; // "LEFT 2h 5m" / "LEFT CHG" / null + + Battery(float watts, boolean charging) { + this(watts, charging, null, null, null); + } + Battery(float watts, boolean charging, Integer percent, Integer tempC, String runtimeText) { + this.watts = watts; + this.charging = charging; + this.percent = percent; + this.tempC = tempC; + this.runtimeText = runtimeText; + } + } + + /** power_supply current_now channels (µA) for the dual-battery sum. */ + private static final String[] CURRENT_CHANNELS = { + "/sys/class/power_supply/battery/current_now", + "/sys/class/power_supply/bms/current_now", + "/sys/class/power_supply/main/current_now", + }; + + /** power_supply voltage_now channels (µV) — fallback when {@code EXTRA_VOLTAGE} reads 0 on some + * OEM firmwares (e.g. HONOR Magic), which otherwise leaves wattage stuck at 0.0W. */ + private static final String[] VOLTAGE_CHANNELS = { + "/sys/class/power_supply/battery/voltage_now", + "/sys/class/power_supply/bms/voltage_now", + "/sys/class/power_supply/main/voltage_now", + }; + /** power_supply power_now channels (µW) — last-resort direct power reading when neither the + * BatteryManager voltage nor {@code voltage_now} is available. */ + private static final String[] POWER_CHANNELS = { + "/sys/class/power_supply/battery/power_now", + "/sys/class/power_supply/bms/power_now", + "/sys/class/power_supply/main/power_now", + }; + + /** First readable long across a channel list, or null. */ + private static Long readLongFromChannels(String[] paths) { + for (String p : paths) { + Long v = readLongFromLine(p); + if (v != null) return v; + } + return null; + } + + /** + * ADDITIVE charging fallback from {@code /sys/class/power_supply/*}, consulted ONLY when the + * framework gave no usable charge state ({@code EXTRA_STATUS == UNKNOWN} or a null battery intent). + * A charger/input supply reporting {@code online == 1} — or the battery's own {@code status} reading + * "Charging"/"Full" — means charging. Returns TRUE when charging is positively detected, FALSE when a + * status/online node is readable but not charging, or null when nothing usable exists (so the caller + * keeps its own default). Never reached on devices whose BatteryManager reports a real status + * (e.g. Adreno phones/handhelds), so it cannot change their reading. + */ + private static Boolean readChargingFromPowerSupply() { + File[] supplies = new File("/sys/class/power_supply").listFiles(); + if (supplies == null || supplies.length == 0) return null; + Boolean sawSignal = null; + for (File supply : supplies) { + String name = supply.getName().toLowerCase(Locale.US); + String type = readFirstLine(new File(supply, "type").getPath()); + type = type == null ? "" : type.trim().toLowerCase(Locale.US); + boolean isBattery = type.equals("battery") || name.equals("battery") || name.equals("bms"); + if (isBattery) { + // The battery's own status string is the most direct charge-state signal. + String st = readFirstLine(new File(supply, "status").getPath()); + if (st == null) continue; + st = st.trim().toLowerCase(Locale.US); + sawSignal = Boolean.FALSE; // "discharging"/"not charging" both land here + if (st.equals("charging") || st.equals("full")) return Boolean.TRUE; + } else { + // A charger / power-input supply (ac/usb/wireless/mains/dc): online==1 → external power in. + Long online = readLongFromLine(new File(supply, "online").getPath()); + if (online == null) continue; + sawSignal = Boolean.FALSE; + if (online == 1L) return Boolean.TRUE; + } + } + return sawSignal; + } + + private Double smoothedBatteryRuntimeHours = null; + private static final double MAX_RUNTIME_HOURS = 72.0; + private static final double RUNTIME_SMOOTHING_OLD_WEIGHT = 0.65; + private static final double RUNTIME_SMOOTHING_NEW_WEIGHT = 0.35; + + /** + * Legacy discharge-only power reading used by the classic overlays + {@code PerfHudView}: + * watts are reported only while discharging (0 when charging). When {@code dualBattery} is set the + * per-cell current channels are summed to correct devices that report only one cell's current. + */ + public Battery getBattery(boolean dualBattery) { + Intent status = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); + boolean charging = false; + int voltageMv = 0; + if (status != null) { + charging = status.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0; + voltageMv = status.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0); + } else { + // ADDITIVE: no battery intent → best-effort power_supply charge probe (default stays false). + // Never reached on devices that deliver ACTION_BATTERY_CHANGED (e.g. Adreno). + Boolean sysCharging = readChargingFromPowerSupply(); + if (sysCharging != null) charging = sysCharging; + } + long microAmps; + if (dualBattery) { + long sum = 0; int n = 0; + for (String path : CURRENT_CHANNELS) { + Long v = readLongFromLine(path); + if (v != null) { sum += Math.abs(v); n++; } + } + microAmps = n > 0 ? -sum : readCurrentNowFallback(); + } else { + microAmps = readCurrentNowFallback(); + } + // current_now's SIGN convention is device-dependent — many OEMs (Xiaomi/Poco especially) + // report discharge as POSITIVE, the opposite of the AOSP convention. Gating wattage on the + // sign therefore reads 0W on battery on those devices (and only shows a value while charging). + // Use the magnitude for the power figure; the reliable charge DIRECTION is EXTRA_PLUGGED (the + // `charging` flag), which the HUD already uses for the PWR/CHG label. + // EXTRA_VOLTAGE reads 0 on some OEM firmwares even though current is fine — fall back to the + // power_supply voltage_now (µV → mV) so wattage isn't stuck at 0. + if (voltageMv <= 0) { + Long uv = readLongFromChannels(VOLTAGE_CHANNELS); + if (uv != null && uv > 0) voltageMv = (int) (Math.abs(uv) / 1000L); + } + // current unit auto-detected (mA vs µA) — see currentRawToAmps. + float watts = (voltageMv / 1000f) * currentRawToAmps(microAmps); + return new Battery(watts, charging); + } + + /** + * Full GameNative-parity battery snapshot for the GameNative-style HUD: %, power W (magnitude, + * regardless of charge/discharge), smoothed runtime-left estimate, and temperature. + */ + public Battery collectBattery() { + BatteryManager bm = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE); + if (bm == null) return new Battery(0f, false); + + Integer percent = null; + int cap = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY); + if (cap >= 0 && cap <= 100) percent = cap; + + Intent status = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); + if (status == null) { + // No battery intent at all → additive power_supply charge probe (default stays false). + Boolean sysCharging = readChargingFromPowerSupply(); + return new Battery(0f, sysCharging != null && sysCharging, percent, null, null); + } + + int st = status.getIntExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_UNKNOWN); + boolean charging = st == BatteryManager.BATTERY_STATUS_CHARGING || st == BatteryManager.BATTERY_STATUS_FULL; + // ADDITIVE: only when the framework reports no usable charge state do we consult power_supply. + // A device that reports CHARGING/DISCHARGING/FULL/NOT_CHARGING (e.g. Adreno) never enters this. + if (st == BatteryManager.BATTERY_STATUS_UNKNOWN) { + Boolean sysCharging = readChargingFromPowerSupply(); + if (sysCharging != null) charging = sysCharging; + } + long currentMicroAmps = Math.abs(bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW)); + long chargeCounter = bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER); + int voltageMv = status.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0); + + Integer tempC = null; + int rawTemp = status.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0); + if (rawTemp > 0) tempC = Math.round(rawTemp / 10f); + + // EXTRA_VOLTAGE reads 0 on some OEM firmwares (e.g. HONOR Magic) even though capacity, temp + // and current all work — which left wattage stuck at 0.0W. Fall back to the power_supply + // voltage_now (µV → mV); if voltage is still unavailable, use power_now (µW) directly. + if (voltageMv <= 0) { + Long uv = readLongFromChannels(VOLTAGE_CHANNELS); + if (uv != null && uv > 0) voltageMv = (int) (Math.abs(uv) / 1000L); + } + // Wattage = current × voltage, with current UNIT auto-detected (CURRENT_NOW is nominally µA but + // many OEMs — e.g. this HONOR — report mA; see batteryCurrentAmps). currentMicroAmps above stays + // as-is for the runtime estimate (a ratio, so unit-independent). If neither current nor voltage + // resolves, fall back to power_now (µW) directly. + float amps = batteryCurrentAmps(bm); + float watts = 0f; + if (amps > 0f && voltageMv > 0) { + watts = (voltageMv / 1000f) * amps; + } else { + Long uw = readLongFromChannels(POWER_CHANNELS); // µW + if (uw != null && uw != 0L) watts = (float) (Math.abs(uw) / 1_000_000.0); + } + + String runtimeText; + if (charging) { + smoothedBatteryRuntimeHours = null; + runtimeText = "LEFT CHG"; + } else if (currentMicroAmps <= 0L || chargeCounter <= 0L) { + runtimeText = null; + } else { + double rawHours = (double) chargeCounter / (double) currentMicroAmps; + if (!Double.isFinite(rawHours) || rawHours <= 0.0 || rawHours > MAX_RUNTIME_HOURS) { + runtimeText = null; + } else { + double smoothed = smoothedBatteryRuntimeHours == null ? rawHours + : (smoothedBatteryRuntimeHours * RUNTIME_SMOOTHING_OLD_WEIGHT) + + (rawHours * RUNTIME_SMOOTHING_NEW_WEIGHT); + smoothedBatteryRuntimeHours = smoothed; + runtimeText = "LEFT " + formatRuntimeHours(smoothed); + } + } + return new Battery(watts, charging, percent, tempC, runtimeText); + } + + private static String formatRuntimeHours(double hours) { + int totalMinutes = Math.max(1, (int) Math.round(hours * 60.0)); + int wholeHours = totalMinutes / 60; + int minutes = totalMinutes % 60; + if (wholeHours > 0 && minutes > 0) return wholeHours + "h " + minutes + "m"; + if (wholeHours > 0) return wholeHours + "h"; + return minutes + "m"; + } + + private long readCurrentNowFallback() { + BatteryManager bm = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE); + return bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW); + } + + /** Raw battery current reading → AMPS, with unit AUTO-DETECT. {@code BATTERY_PROPERTY_CURRENT_NOW} + * (and {@code current_now}) are nominally µA, but many OEMs report mA — a small number, whereas a + * real µA reading is always huge. So a magnitude < 20000 means the device gave mA. Without this, + * wattage on mA-reporting devices came out ~1000× too small → 0.0W even though current & voltage are + * fine. Sentinel/zero → 0. (Heuristic mirrors Ludashi-plus WinlatorHUD.getBatteryCurrentAmps().) */ + private static float currentRawToAmps(long raw) { + if (raw == 0L || raw == Long.MIN_VALUE) return 0f; + long a = Math.abs(raw); + return a < 20000L ? a / 1000f : a / 1_000_000f; // mA → A, else µA → A + } + + /** Battery current in AMPS for the wattage calc: framework property first, then power_supply + * {@code current_now} sysfs (battery/bms/main) when it's unsupported ({@code Long.MIN_VALUE}) or 0. */ + private float batteryCurrentAmps(BatteryManager bm) { + long raw = (bm != null) ? bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW) : 0L; + if (raw == 0L || raw == Long.MIN_VALUE) { + Long sys = readLongFromChannels(CURRENT_CHANNELS); + raw = (sys != null) ? sys : 0L; + } + return currentRawToAmps(raw); + } + + // ======================================================================= + // Clock frequencies (best-effort, nullable) + // ======================================================================= + + /** Peak CPU core clock in MHz (max scaling_cur_freq across cores), or null when unreadable. */ + public Integer getCpuClockMhz() { + int cores = Runtime.getRuntime().availableProcessors(); + long maxKhz = 0; + for (int i = 0; i < cores; i++) { + Long cur = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/scaling_cur_freq"); + if (cur != null && cur > maxKhz) maxKhz = cur; + } + if (maxKhz <= 0) return null; + return (int) (maxKhz / 1000L); // kHz → MHz + } + + private List gpuClockPathsCache = null; + private static final String[] GPU_CLOCK_PATHS = { + "/sys/class/kgsl/kgsl-3d0/gpuclk", // Adreno, Hz + "/sys/class/kgsl/kgsl-3d0/devfreq/cur_freq", // Adreno devfreq, Hz + "/sys/class/kgsl/kgsl-3d0/clock_mhz", // some kernels, already MHz + "/sys/kernel/gpu/gpu_clock", // Mali vendor node, MHz + "/sys/devices/platform/gpusysfs/gpu_clock", // Exynos Mali vendor node, MHz + "/sys/class/misc/mali0/device/clock", // Mali, kHz/MHz + "/sys/class/devfreq/gpu/cur_freq", // generic devfreq gpu, Hz + // ── Additive cross-vendor fallbacks (appended LAST: only reached when every node above + // is unreadable, so Adreno/Mali devices that already resolve are unaffected). ── + "/sys/kernel/ged/hal/current_freqency", // MediaTek GED (vendor's spelling), kHz + "/sys/kernel/ged/hal/gpu_clock", // MediaTek GED alt, MHz + }; + + private List discoverGpuClockPaths() { + if (gpuClockPathsCache != null) return gpuClockPathsCache; + LinkedHashSet found = new LinkedHashSet<>(); + for (String p : GPU_CLOCK_PATHS) if (new File(p).canRead()) found.add(p); + // Vendor-agnostic devfreq walk: any gpu/mali/panfrost/xclipse/sgpu node's cur_freq (Hz). + File[] devfreqRoots = { + new File("/sys/class/devfreq"), + new File("/sys/devices/virtual/devfreq"), + }; + for (File root : devfreqRoots) { + if (!root.isDirectory()) continue; + File[] nodeDirs = root.listFiles(File::isDirectory); + if (nodeDirs == null) continue; + for (File node : nodeDirs) { + String nodePath = node.getPath().toLowerCase(Locale.US); + boolean looksLikeGpu = false; + for (String t : GPU_NODE_TOKENS) { + if (nodePath.contains(t)) { looksLikeGpu = true; break; } + } + if (!looksLikeGpu) continue; + File f = new File(node, "cur_freq"); + if (f.canRead()) found.add(f.getPath()); + } + } + gpuClockPathsCache = new ArrayList<>(found); + return gpuClockPathsCache; + } + + /** GPU clock in MHz (Adreno KGSL / devfreq / Mali nodes), or null when no source reports it. */ + public Integer getGpuClockMhz() { + for (String p : discoverGpuClockPaths()) { + Long raw = readLongFromLine(p); + if (raw == null || raw <= 0) continue; + long mhz; + if (raw >= 1_000_000L) mhz = raw / 1_000_000L; // Hz + else if (raw >= 10_000L) mhz = raw / 1_000L; // kHz (defensive) + else mhz = raw; // already MHz + if (mhz >= 1 && mhz <= 3000) return (int) mhz; + } + return null; + } + + // ======================================================================= + // VRAM (best-effort, Java-only sysfs — no native rebuild) + // ======================================================================= + // Covered here in pure Java: Adreno KGSL (bytes mapped/allocated) and amdgpu-style drm nodes + // (Samsung Xclipse / "sgpu", AMD-on-Exynos), which expose mem_info_vram_used/_total directly. + // TODO(native): VK_EXT_memory_budget as a vendor-agnostic fallback for Mali/PowerVR, which expose + // no world-readable VRAM node. FEASIBILITY (checked 2026-07): the compositor's Vulkan layer + // (app/src/main/cpp/winlator/vulkan.c) creates an EPHEMERAL VkInstance/VkPhysicalDevice inside + // getRenderer() and destroys it every call — it holds no reusable device and loads only the + // properties/extension entrypoints, not vkGetPhysicalDeviceMemoryProperties2. Wiring the budget + // query therefore means a new JNI method + enabling VK_KHR_get_physical_device_properties2 / + // VK_EXT_memory_budget at instance create + an NDK rebuild — out of scope for a source-only pass. + // CAVEAT to document if/when added: this HUD is an app-side overlay, NOT in the game's Vulkan + // device, so an app-created instance reports the DEVICE-WIDE heap budget (a GPU-memory-pressure + // proxy), not the game's per-process VRAM. Devices with no readable node return null → HUD hides VRAM. + private List vramUsedPathsCache = null; + private static final String[] VRAM_USED_PATHS = { + "/sys/class/kgsl/kgsl-3d0/gpumem_mapped", // bytes currently mapped to the GPU + "/sys/class/kgsl/kgsl-3d0/page_alloc", // bytes allocated to the KGSL page pool + "/sys/class/kgsl/kgsl-3d0/mapped", // alt name on some kernels + "/sys/class/drm/card0/device/mem_info_vram_used",// amdgpu / Xclipse (sgpu), bytes + "/sys/class/kgsl/kgsl-3d0/page_alloc_max", // high-water fallback + }; + // Total-VRAM companions (amdgpu exposes one; used only by the diagnostics report). + private static final String[] VRAM_TOTAL_PATHS = { + "/sys/class/drm/card0/device/mem_info_vram_total", + }; + + /** Used GPU memory in bytes from Adreno KGSL sysfs, or null when this device exposes nothing readable. */ + public Long getVramUsedBytes() { + if (vramUsedPathsCache == null) { + ArrayList found = new ArrayList<>(); + for (String p : VRAM_USED_PATHS) if (new File(p).canRead()) found.add(p); + vramUsedPathsCache = found; + } + for (String p : vramUsedPathsCache) { + Long b = sanitizeVramBytes(readLongFromLine(p)); + if (b != null) return b; + } + return null; + } + + private static Long sanitizeVramBytes(Long v) { + if (v == null) return null; + if (v < (1L << 20)) return null; // < 1 MiB → idle-zero / not a byte count + if (v > 64L * (1L << 30)) return null; // > 64 GiB → not bytes + return v; + } + + /** Used GPU memory as "x.xGiB" (or "yMiB"), or null when no VRAM source is readable. */ + public String getVramUsedText() { + Long b = getVramUsedBytes(); + return b == null ? null : formatGiB(b); + } + + private static String formatGiB(long bytes) { + return String.format(Locale.US, "%.1fGiB", bytes / (1024.0 * 1024.0 * 1024.0)); + } + + // ======================================================================= + // Single cached snapshot — read EVERYTHING once per HUD refresh + // ======================================================================= + + /** + * Immutable point-in-time reading of every metric the Fusion HUD draws. Collected in one pass by + * {@link #snapshot()} so the view never touches sysfs / BatteryManager during draw (the user's + * explicit ask: one collection pass, cached, so gameplay isn't strained). All numeric fields are + * raw (nullable when unreadable); the view formats + colours them. + */ + public static final class Snapshot { + public final Integer cpuPercent; // 0..100 or null + public final Integer gpuPercent; // 0..100 or null + public final Integer cpuClockMhz; // MHz or null + public final Integer gpuClockMhz; // MHz or null + public final Integer cpuTempC; // °C or null + public final Integer gpuTempC; // °C or null + public final long ramUsedBytes; + public final long ramTotalBytes; + public final float ramPercent; // 0..100 + public final Long vramUsedBytes; // bytes or null + public final Battery battery; // never null + // ---- Mega-only extras ---- + public final int[] perCorePercent; // per-core 0..100, -1 unknown (never null; may be empty) + public final int[] perCoreClockMhz; // per-core MHz, 0 unknown (never null; may be empty) + public final Long swapUsedBytes; // bytes or null (no swap) + public final Long swapTotalBytes; // bytes or null + public final Long netDownBps; // bytes/sec down, or null (first sample / unreadable) + public final Long netUpBps; // bytes/sec up, or null + + Snapshot(Integer cpuPercent, Integer gpuPercent, Integer cpuClockMhz, Integer gpuClockMhz, + Integer cpuTempC, Integer gpuTempC, long ramUsedBytes, long ramTotalBytes, + float ramPercent, Long vramUsedBytes, Battery battery, + int[] perCorePercent, int[] perCoreClockMhz, Long swapUsedBytes, Long swapTotalBytes, + Long netDownBps, Long netUpBps) { + this.cpuPercent = cpuPercent; + this.gpuPercent = gpuPercent; + this.cpuClockMhz = cpuClockMhz; + this.gpuClockMhz = gpuClockMhz; + this.cpuTempC = cpuTempC; + this.gpuTempC = gpuTempC; + this.ramUsedBytes = ramUsedBytes; + this.ramTotalBytes = ramTotalBytes; + this.ramPercent = ramPercent; + this.vramUsedBytes = vramUsedBytes; + this.battery = battery; + this.perCorePercent = perCorePercent != null ? perCorePercent : new int[0]; + this.perCoreClockMhz = perCoreClockMhz != null ? perCoreClockMhz : new int[0]; + this.swapUsedBytes = swapUsedBytes; + this.swapTotalBytes = swapTotalBytes; + this.netDownBps = netDownBps; + this.netUpBps = netUpBps; + } + + public String ramUsedText() { return formatBytesGb(ramUsedBytes); } + public String ramTotalText() { return formatBytesGb(ramTotalBytes); } + public String vramText() { return vramUsedBytes == null ? null : formatGiB(vramUsedBytes); } + public String swapUsedText() { return swapUsedBytes == null ? null : formatBytesGb(swapUsedBytes); } + public String swapTotalText() { return swapTotalBytes == null ? null : formatBytesGb(swapTotalBytes); } + + private static String formatBytesGb(long bytes) { + return String.format(Locale.US, "%.1fGiB", bytes / (1024.0 * 1024.0 * 1024.0)); + } + } + + /** One collection pass over every metric. Call from the HUD's own ~1 s refresh thread, never draw. */ + public Snapshot snapshot() { + if (mango != null) return mangoSnapshot(mango); + Integer cpu = getCpuUsagePercent(); + Integer gpu = getGpuUsagePercent(); + Integer cpuClk = getCpuClockMhz(); + Integer gpuClk = getGpuClockMhz(); + Integer cpuTemp = getCpuTempC(); + Integer gpuTemp = getGpuTempC(); + + long usedBytes = 0, totalBytes = 0; + float ramPct = 0f; + ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); + if (am != null) { + ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo(); + am.getMemoryInfo(mi); + totalBytes = Math.max(0L, mi.totalMem); + usedBytes = Math.max(0L, mi.totalMem - mi.availMem); + ramPct = totalBytes > 0 ? usedBytes * 100f / totalBytes : 0f; + } + + Long vram = getVramUsedBytes(); + Battery battery = collectBattery(); + + int[] perCorePct = readPerCorePercent(); + int[] perCoreClk = getPerCoreClockMhz(); + long[] swap = getSwapBytes(); + long[] net = readNetRateBps(); + + return new Snapshot(cpu, gpu, cpuClk, gpuClk, cpuTemp, gpuTemp, + usedBytes, totalBytes, ramPct, vram, battery, + perCorePct, perCoreClk, + swap == null ? null : swap[0], swap == null ? null : swap[1], + net == null ? null : net[0], net == null ? null : net[1]); + } + + // DroidDeck: the same snapshot with MangoHud's sources and rounding (see MangoReadings). + private Snapshot mangoSnapshot(MangoReadings m) { + MangoReadings.Cpu cpu = m.cpu(); + MangoReadings.Memory mem = m.memory(); + long used = mem != null ? mem.getUsedBytes() : 0L; + long total = mem != null ? mem.getTotalBytes() : 0L; + Battery android = collectBattery(); + MangoReadings.Battery bat = m.battery(); + Battery battery = bat == null ? android : new Battery(bat.getWatts(), bat.getCharging(), + bat.getPercent() != null ? bat.getPercent() : android.percent, android.tempC, android.runtimeText); + long[] net = readNetRateBps(); + return new Snapshot(cpu != null ? cpu.getPercent() : null, m.gpuPercent(), getCpuClockMhz(), m.gpuClockMhz(), + m.cpuTempC(), m.gpuTempC(), used, total, total > 0 ? used * 100f / total : 0f, m.vramBytes(), battery, + cpu != null ? cpu.getPerCore() : new int[0], getPerCoreClockMhz(), + mem != null && mem.getSwapTotalBytes() > 0 ? mem.getSwapUsedBytes() : null, + mem != null && mem.getSwapTotalBytes() > 0 ? mem.getSwapTotalBytes() : null, + net == null ? null : net[0], net == null ? null : net[1]); + } + + // ======================================================================= + // Mega-view extras: per-core CPU, swap, network (best-effort, nullable) + // ======================================================================= + + /** Per-core clock in MHz (each core's {@code scaling_cur_freq}); 0 for a core that can't be read. */ + public int[] getPerCoreClockMhz() { + int cores = Runtime.getRuntime().availableProcessors(); + int[] out = new int[Math.max(0, cores)]; + for (int i = 0; i < out.length; i++) { + Long cur = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/scaling_cur_freq"); + out[i] = (cur != null && cur > 0) ? (int) (cur / 1000L) : 0; + } + return out; + } + + // Per-core /proc/stat deltas — one prev sample per core, seeded on the first read. + private long[] lastCoreTotal = null; + private long[] lastCoreIdle = null; + + /** Per-core CPU usage 0..100 from the {@code cpuN} /proc/stat deltas; -1 for a core not yet sampled. */ + public int[] readPerCorePercent() { + int cores = Runtime.getRuntime().availableProcessors(); + int[] out = new int[Math.max(0, cores)]; + java.util.Arrays.fill(out, -1); + if (lastCoreTotal == null || lastCoreTotal.length != cores) { + lastCoreTotal = new long[cores]; + lastCoreIdle = new long[cores]; + java.util.Arrays.fill(lastCoreTotal, -1L); + } + try (BufferedReader r = new BufferedReader(new FileReader("/proc/stat"))) { + String line; + while ((line = r.readLine()) != null) { + if (!line.startsWith("cpu")) break; // cpu lines are first; stop at the block end + if (line.length() < 4 || !Character.isDigit(line.charAt(3))) continue; // skip aggregate "cpu " + String[] parts = line.trim().split("\\s+"); + int core; + try { core = Integer.parseInt(parts[0].substring(3)); } catch (Exception e) { continue; } + if (core < 0 || core >= cores) continue; + long total = 0, idle = 0; + boolean ok = true; + for (int i = 1; i < parts.length; i++) { + try { + long v = Long.parseLong(parts[i]); + total += v; + if (i == 4) idle = v; // idle + else if (i == 5) idle += v; // + iowait + } catch (NumberFormatException e) { ok = false; break; } + } + if (!ok) continue; + long prevTotal = lastCoreTotal[core], prevIdle = lastCoreIdle[core]; + lastCoreTotal[core] = total; + lastCoreIdle[core] = idle; + if (prevTotal >= 0) { + long dTotal = total - prevTotal, dIdle = idle - prevIdle; + if (dTotal > 0) out[core] = clampPercent((int) ((Math.max(0, dTotal - dIdle) * 100L) / dTotal)); + } + } + } catch (Exception ignored) {} + // Frequency fallback for any core /proc/stat couldn't give us — restricted on some firmwares + // (e.g. HONOR / Android 16), which is also why the aggregate getCpuUsagePercent() falls back. + // scaling_cur_freq / cpuinfo_max_freq is a load proxy (per-core clocks ARE readable there), and + // it also seeds the very first sample. Cores with a real /proc/stat delta keep it (no regression). + for (int i = 0; i < out.length; i++) { + if (out[i] >= 0) continue; + Long cur = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/scaling_cur_freq"); + Long max = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/cpuinfo_max_freq"); + if (cur != null && max != null && max > 0L) + out[i] = clampPercent((int) ((Math.max(0L, Math.min(cur, max)) * 100L) / max)); + } + return out; + } + + /** Swap {used, total} in bytes from /proc/meminfo, or null when there is no swap. */ + public long[] getSwapBytes() { + long totalKb = -1, freeKb = -1; + try (BufferedReader r = new BufferedReader(new FileReader("/proc/meminfo"))) { + String line; + while ((line = r.readLine()) != null && (totalKb < 0 || freeKb < 0)) { + if (line.startsWith("SwapTotal:")) totalKb = parseMeminfoKb(line); + else if (line.startsWith("SwapFree:")) freeKb = parseMeminfoKb(line); + } + } catch (Exception e) { return null; } + if (totalKb <= 0) return null; + long used = Math.max(0L, (totalKb - Math.max(0L, freeKb))) * 1024L; + return new long[]{used, totalKb * 1024L}; + } + + private static long parseMeminfoKb(String line) { + String[] parts = line.trim().split("\\s+"); + if (parts.length < 2) return -1; + Long v = parseLong(parts[1]); + return v == null ? -1 : v; + } + + // Net rate: cumulative rx/tx bytes + the wall-clock of the previous read → bytes/sec. + private long lastNetRx = -1, lastNetTx = -1, lastNetWallMs = 0; + + /** Network {down, up} in bytes/sec (all interfaces except loopback), or null on the first/failed read. */ + public long[] readNetRateBps() { + long rx = 0, tx = 0; + boolean any = false; + try (BufferedReader r = new BufferedReader(new FileReader("/proc/net/dev"))) { + String line; + while ((line = r.readLine()) != null) { + int colon = line.indexOf(':'); + if (colon < 0) continue; + String iface = line.substring(0, colon).trim(); + if (iface.equals("lo") || iface.isEmpty()) continue; + String[] f = line.substring(colon + 1).trim().split("\\s+"); + if (f.length < 9) continue; + Long rxB = parseLong(f[0]); + Long txB = parseLong(f[8]); + if (rxB == null || txB == null) continue; + rx += rxB; tx += txB; any = true; + } + } catch (Exception e) { return null; } + if (!any) return null; + long now = SystemClock.elapsedRealtime(); + long prevRx = lastNetRx, prevTx = lastNetTx, prevWall = lastNetWallMs; + lastNetRx = rx; lastNetTx = tx; lastNetWallMs = now; + if (prevRx < 0 || prevWall <= 0) return null; // seed + long dt = now - prevWall; + if (dt <= 0) return null; + long down = Math.max(0L, (rx - prevRx) * 1000L / dt); + long up = Math.max(0L, (tx - prevTx) * 1000L / dt); + return new long[]{down, up}; + } + + // ======================================================================= + // Diagnostics report (invoked ONLY on user tap — never on the HUD refresh path) + // ======================================================================= + + /** + * One-tap plain-text device report for the "Export HUD diagnostics" action: for every metric it + * lists the resolved source path/API + current value, or MISS + the exact candidates it tried, + * followed by an "exists on this device" dump (thermal zone types, devfreq/kgsl/mali nodes) so a + * device owner can send back the real path for anything that missed. Does a short prime+sample so + * delta-based readers (CPU%/GPU%/net) report a live value. Run OFF the main thread. + */ + public String buildDiagnosticsReport(Context ctxIn) { + final Context ctx = ctxIn != null ? ctxIn : this.context; + // Prime the delta-based readers, wait, then take a live sample. + snapshot(); + try { Thread.sleep(350L); } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); } + Snapshot s = snapshot(); + + StringBuilder sb = new StringBuilder(); + sb.append("DroidDeck FusionHUD diagnostics\n"); + sb.append("Generated: ") + .append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(new Date())).append('\n'); + sb.append("Device: ").append(Build.MANUFACTURER).append(' ').append(Build.MODEL).append('\n'); + sb.append("Board/HW: ").append(Build.BOARD).append(" / ").append(Build.HARDWARE).append('\n'); + sb.append("SoC: ").append(socString()).append('\n'); + sb.append("Android: ").append(Build.VERSION.RELEASE) + .append(" (API ").append(Build.VERSION.SDK_INT).append(")\n"); + sb.append("CPU cores: ").append(Runtime.getRuntime().availableProcessors()).append('\n'); + sb.append("GPU renderer: ").append(safeGpu(() -> com.droiddeck.launcher.gpu.GpuInfo.Companion.detect().displayName(ctx))).append('\n'); + + sb.append("\n== Metrics ==\n"); + + // ---- CPU ---- + boolean procStat = new File("/proc/stat").canRead(); + if (s.cpuPercent != null) { + metricHit(sb, "CPU %", s.cpuPercent + "%", + procStat ? "/proc/stat (cpu aggregate delta)" + : "/sys/devices/system/cpu/cpu*/cpufreq/scaling_cur_freq (freq estimate)"); + } else { + metricMiss(sb, "CPU %", "/proc/stat", + "/sys/devices/system/cpu/cpu*/cpufreq/scaling_cur_freq"); + } + + // Per-core % + StringBuilder cores = new StringBuilder(); + for (int i = 0; i < s.perCorePercent.length; i++) { + if (i > 0) cores.append(' '); + int v = s.perCorePercent[i]; + cores.append('c').append(i).append('=').append(v < 0 ? "?" : (v + "%")); + } + if (s.perCorePercent.length > 0) + metricHit(sb, "Per-core %", cores.toString(), "/proc/stat (per-cpu lines)"); + else + metricMiss(sb, "Per-core %", "/proc/stat"); + + // Per-core clock + StringBuilder coreClk = new StringBuilder(); + for (int i = 0; i < s.perCoreClockMhz.length; i++) { + if (i > 0) coreClk.append(' '); + int v = s.perCoreClockMhz[i]; + coreClk.append('c').append(i).append('=').append(v <= 0 ? "?" : (v + "MHz")); + } + if (s.cpuClockMhz != null) + metricHit(sb, "CPU clock", s.cpuClockMhz + "MHz (peak); " + coreClk, + "/sys/devices/system/cpu/cpu*/cpufreq/scaling_cur_freq"); + else + metricMiss(sb, "CPU clock", "/sys/devices/system/cpu/cpu*/cpufreq/scaling_cur_freq"); + + // CPU temp + String cpuTempPath = resolveTempPath(discoverPrioritizedCpuTempPaths()); + if (s.cpuTempC != null && cpuTempPath != null) + metricHit(sb, "CPU temp", s.cpuTempC + "°C", cpuTempPath); + else + metricMiss(sb, "CPU temp", + "/sys/class/thermal/thermal_zone*/temp (types: cpu*/cpuss/tsens/mtktscpu/s5p-tmu/soc)"); + + // ---- GPU ---- + String gpuUsagePath = firstReadableGpuUsagePath(); + if (s.gpuPercent != null && gpuUsagePath != null) + metricHit(sb, "GPU %", s.gpuPercent + "%", gpuUsagePath); + else + metricMissList(sb, "GPU %", discoverGpuUsagePaths(), GPU_USAGE_STATIC_PATHS); + + String gpuClockPath = firstReadableGpuClockPath(); + if (s.gpuClockMhz != null && gpuClockPath != null) + metricHit(sb, "GPU clock", s.gpuClockMhz + "MHz", gpuClockPath); + else + metricMissList(sb, "GPU clock", discoverGpuClockPaths(), GPU_CLOCK_PATHS); + + String gpuTempPath = resolveTempPath(discoverPrioritizedGpuTempPaths()); + if (s.gpuTempC != null) + metricHit(sb, "GPU temp", s.gpuTempC + "°C", + gpuTempPath != null ? gpuTempPath : "kgsl/mali direct temp node"); + else + metricMiss(sb, "GPU temp", + "/sys/class/kgsl/kgsl-3d0/temp", "/sys/class/misc/mali0/device/temp", + "/sys/class/thermal/thermal_zone*/temp (types: gpu*/gpuss/g3d/kgsl/mali/mtktsgpu)"); + + // ---- Memory ---- + metricHit(sb, "RAM", s.ramUsedText() + " / " + s.ramTotalText() + + " (" + Math.round(s.ramPercent) + "%)", "ActivityManager.MemoryInfo"); + if (s.swapUsedBytes != null) + metricHit(sb, "SWAP", s.swapUsedText() + " / " + s.swapTotalText(), "/proc/meminfo"); + else + metricMiss(sb, "SWAP", "/proc/meminfo (SwapTotal=0 or unreadable)"); + + // VRAM + String vramPath = firstReadableVramUsedPath(); + if (s.vramUsedBytes != null && vramPath != null) { + Long total = readFirstReadableLong(VRAM_TOTAL_PATHS); + String v = s.vramText() + (total != null ? " / " + formatGiB(total) : ""); + metricHit(sb, "VRAM", v, vramPath); + } else { + metricMissList(sb, "VRAM (Java sysfs; Vulkan budget = native TODO)", + new ArrayList<>(), VRAM_USED_PATHS); + } + + // ---- Net ---- + if (s.netDownBps != null) + metricHit(sb, "NET", formatRate(s.netDownBps) + " down / " + formatRate(s.netUpBps) + " up", + "/proc/net/dev"); + else + metricMiss(sb, "NET", "/proc/net/dev (first sample or unreadable)"); + + // ---- Battery ---- + Battery b = s.battery; + StringBuilder bat = new StringBuilder(); + bat.append(b.percent != null ? b.percent + "%" : "?%") + .append(", ").append(String.format(Locale.US, "%.1fW", b.watts)) + .append(b.charging ? " (charging)" : "") + .append(", temp ").append(b.tempC != null ? b.tempC + "°C" : "?") + .append(b.runtimeText != null ? ", " + b.runtimeText : ""); + metricHit(sb, "Battery", bat.toString(), "BatteryManager + /sys/class/power_supply"); + + // ---- Exists-on-device dump ---- + appendExistsDump(sb); + return sb.toString(); + } + + private static String socString() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + return Build.SOC_MANUFACTURER + " " + Build.SOC_MODEL; + } + return "(SoC id needs Android 12+; HW=" + Build.HARDWARE + ")"; + } + + private interface GpuStr { String get(); } + private static String safeGpu(GpuStr fn) { + try { String v = fn.get(); return v == null ? "(null)" : v; } + catch (Throwable t) { return "(unavailable: " + t.getClass().getSimpleName() + ")"; } + } + + private String firstReadableGpuUsagePath() { + for (String p : discoverGpuUsagePaths()) if (readGpuUsageSample(p) != null) return p; + return null; + } + + private String firstReadableGpuClockPath() { + for (String p : discoverGpuClockPaths()) { + Long raw = readLongFromLine(p); + if (raw != null && raw > 0) return p; + } + return null; + } + + private String firstReadableVramUsedPath() { + if (vramUsedPathsCache == null) getVramUsedBytes(); // builds the cache + if (vramUsedPathsCache == null) return null; + for (String p : vramUsedPathsCache) if (sanitizeVramBytes(readLongFromLine(p)) != null) return p; + return null; + } + + private static Long readFirstReadableLong(String[] paths) { + for (String p : paths) { + Long v = readLongFromLine(p); + if (v != null && v > 0) return v; + } + return null; + } + + private static String formatRate(Long bps) { + if (bps == null) return "?"; + double kb = bps / 1024.0; + if (kb >= 1024.0) return String.format(Locale.US, "%.1fMB/s", kb / 1024.0); + return String.format(Locale.US, "%.0fKB/s", kb); + } + + private static void metricHit(StringBuilder sb, String name, String value, String source) { + sb.append(name).append(": ").append(value).append("\n source: ").append(source).append('\n'); + } + + private static void metricMiss(StringBuilder sb, String name, String... candidates) { + sb.append(name).append(": MISS\n tried: "); + for (int i = 0; i < candidates.length; i++) { + if (i > 0) sb.append("\n "); + sb.append(candidates[i]); + } + sb.append('\n'); + } + + private static void metricMissList(StringBuilder sb, String name, List discovered, String[] statics) { + LinkedHashSet all = new LinkedHashSet<>(); + if (discovered != null) all.addAll(discovered); + for (String p : statics) all.add(p); + sb.append(name).append(": MISS\n tried: "); + boolean first = true; + for (String p : all) { + if (!first) sb.append("\n "); + sb.append(p); + first = false; + } + if (first) sb.append("(no candidates)"); + sb.append('\n'); + } + + private void appendExistsDump(StringBuilder sb) { + sb.append("\n== Exists on this device (send these back for any MISS above) ==\n"); + sb.append("-- /sys/class/thermal/thermal_zone*/type --\n"); + List zones = discoverAllThermalZones(); + if (zones.isEmpty()) sb.append(" (none readable)\n"); + for (String[] z : zones) sb.append(" ").append(z[1]).append(" type=").append(z[0]).append('\n'); + appendDevfreqListing(sb, "/sys/class/devfreq"); + appendDevfreqListing(sb, "/sys/devices/virtual/devfreq"); + appendReadableFiles(sb, "/sys/class/kgsl/kgsl-3d0"); + appendReadableFiles(sb, "/sys/class/misc/mali0/device"); + appendReadableFiles(sb, "/sys/class/drm/card0/device"); + appendPowerSupplyDump(sb); + appendGpuNoRootProbes(sb); + } + + /** Probes for a ROOT-FREE GPU-load path on locked-sysfs Adreno devices (SM8750/HONOR etc.): + * (1) can the app open the KGSL device node? The sysfs mirror (/sys/class/kgsl) is SELinux-blocked + * (vendor_sysfs_kgsl), but /dev/kgsl-3d0 is labeled gpu_device and is normally app-openable — + * that's the door for reading GPU busy via ioctl perf-counters instead of sysfs. + * (2) is there an app-readable devfreq node under /sys/devices/platform that bypasses the blocked + * /sys/class/kgsl symlink (a free win for at least the clock). */ + private void appendGpuNoRootProbes(StringBuilder sb) { + sb.append("-- GPU no-root reachability probes --\n"); + sb.append(" /dev/kgsl-3d0 open O_RDWR: ") + .append(probeOpen("/dev/kgsl-3d0", android.system.OsConstants.O_RDWR)).append('\n'); + sb.append(" /dev/kgsl-3d0 open O_RDONLY: ") + .append(probeOpen("/dev/kgsl-3d0", android.system.OsConstants.O_RDONLY)).append('\n'); + sb.append(" /dev/dri/renderD128 O_RDWR: ") + .append(probeOpen("/dev/dri/renderD128", android.system.OsConstants.O_RDWR)).append('\n'); + boolean found = false; + File[] roots = { new File("/sys/devices/platform/soc"), new File("/sys/devices/platform") }; + for (File root : roots) { + File[] nodes = root.listFiles(); + if (nodes == null) continue; + for (File soc : nodes) { + if (!soc.getName().contains("kgsl-3d0")) continue; + File[] inner = new File(soc, "devfreq").listFiles(); + if (inner == null) continue; + for (File node : inner) { + found = true; + Long cur = readLongFromLine(node + "/cur_freq"); + Long load = readLongFromLine(node + "/gpu_load"); + if (load == null) load = readLongFromLine(node + "/load"); + sb.append(" devfreq ").append(node.getAbsolutePath()) + .append(": cur_freq=").append(cur == null ? "—" : cur.toString()) + .append(" load=").append(load == null ? "—" : load.toString()).append('\n'); + } + } + } + if (!found) sb.append(" devfreq (platform kgsl): (no app-readable node found)\n"); + } + + /** open()+close() a path with the given flags, reporting OK or the errno class — used to test + * whether the app's sandbox can reach a device node without root. */ + private static String probeOpen(String path, int flags) { + java.io.FileDescriptor fd = null; + try { + fd = android.system.Os.open(path, flags, 0); + return "OK"; + } catch (Throwable t) { + return t.getClass().getSimpleName() + ": " + t.getMessage(); + } finally { + if (fd != null) try { android.system.Os.close(fd); } catch (Throwable ignored) {} + } + } + + /** Battery-wattage inputs: which power_supply nodes this app can actually READ, and their raw + * values. Confirms the voltage_now / power_now fallback for devices where EXTRA_VOLTAGE is 0. */ + private void appendPowerSupplyDump(StringBuilder sb) { + sb.append("-- /sys/class/power_supply (battery watts inputs) --\n"); + File[] nodes = new File("/sys/class/power_supply").listFiles(); + if (nodes == null || nodes.length == 0) { sb.append(" (absent / unreadable)\n"); return; } + boolean any = false; + for (File node : nodes) { + Long v = readLongFromLine(node + "/voltage_now"); + Long c = readLongFromLine(node + "/current_now"); + Long p = readLongFromLine(node + "/power_now"); + if (v == null && c == null && p == null) continue; + any = true; + sb.append(" ").append(node.getName()) + .append(": voltage_now=").append(v == null ? "—" : v + "µV") + .append(" current_now=").append(c == null ? "—" : c + "µA") + .append(" power_now=").append(p == null ? "—" : p + "µW") + .append('\n'); + } + if (!any) sb.append(" (nodes present but voltage_now/current_now/power_now unreadable)\n"); + } + + private static void appendDevfreqListing(StringBuilder sb, String rootPath) { + File root = new File(rootPath); + File[] nodes = root.listFiles(File::isDirectory); + sb.append("-- ").append(rootPath).append(" --\n"); + if (nodes == null || nodes.length == 0) { sb.append(" (absent / empty)\n"); return; } + for (File node : nodes) { + sb.append(" ").append(node.getName()).append("/: ").append(readableFileNames(node)).append('\n'); + } + } + + private static void appendReadableFiles(StringBuilder sb, String dirPath) { + File dir = new File(dirPath); + sb.append("-- ").append(dirPath).append(" --\n"); + if (!dir.isDirectory()) { sb.append(" (absent / unreadable)\n"); return; } + sb.append(" ").append(readableFileNames(dir)).append('\n'); + } + + private static String readableFileNames(File dir) { + File[] files = dir.listFiles(); + if (files == null) return "(unreadable)"; + StringBuilder names = new StringBuilder(); + for (File f : files) { + if (f.isFile() && f.canRead()) { + if (names.length() > 0) names.append(", "); + names.append(f.getName()); + } + } + return names.length() == 0 ? "(no readable files)" : names.toString(); + } + + // ======================================================================= + // Low-level helpers + // ======================================================================= + private static int clampPercent(int v) { return v < 0 ? 0 : (v > 100 ? 100 : v); } + + private static String readFirstLine(String path) { + try (BufferedReader r = new BufferedReader(new FileReader(path))) { + return r.readLine(); + } catch (Exception e) { + return null; + } + } + + private static String readNthLine(String path, int lineIndex) { + try (BufferedReader r = new BufferedReader(new FileReader(path))) { + String line = null; + for (int i = 0; i <= lineIndex; i++) { + line = r.readLine(); + if (line == null) return null; + } + return line; + } catch (Exception e) { + return null; + } + } + + private static Long readLongFromLine(String path) { + String line = readFirstLine(path); + return line == null ? null : parseLong(line.trim()); + } + + private static Integer readIntFromLine(String path) { + String line = readFirstLine(path); + return line == null ? null : parseInt(line.trim()); + } + + private static Long parseLong(String s) { + try { return Long.parseLong(s); } catch (Exception e) { return null; } + } + + private static Integer parseInt(String s) { + try { return Integer.parseInt(s); } catch (Exception e) { return null; } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/hud/KeyValueSet.java b/app/src/main/java/com/droiddeck/launcher/hud/KeyValueSet.java new file mode 100644 index 0000000000..1c3a1ba9b9 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/hud/KeyValueSet.java @@ -0,0 +1,132 @@ +/* + * FusionHUD — a lightweight in-game performance HUD for Android / Winlator overlays. + * Copyright (C) The412Banner + * + * Licensed under the GNU General Public License v3.0 (see LICENSE), with an + * ADDITIONAL attribution requirement under GPL-3.0 §7(b) (see ATTRIBUTION.md): + * any use, fork, or distribution must preserve credit to "The412Banner" and a + * link to https://github.com/The412Banner/FusionHUD in the project documentation + * AND in the in-app credits/about screen. + * + * Ported to DroidDeck from FusionHUD (Bannerlator's HUD); DroidDeck changes are marked in the code. + */ + +package com.droiddeck.launcher.hud; + +import androidx.annotation.NonNull; + +import java.util.Iterator; + +public class KeyValueSet implements Iterable { + private String data = ""; + + // Default constructor for an empty KeyValueSet + public KeyValueSet() { + this.data = ""; + } + + // Constructor to initialize with a string representation of key-value pairs + public KeyValueSet(String data) { + this.data = data != null && !data.isEmpty() ? data : ""; + } + + // Helper method to find the start and end indices of a key in the data string + private int[] indexOfKey(String key) { + int start = 0; + int end = data.indexOf(","); + if (end == -1) end = data.length(); + + while (start < end) { + int index = data.indexOf("=", start); + String currKey = data.substring(start, index); + if (currKey.equals(key)) return new int[]{start, end}; + start = end + 1; + end = data.indexOf(",", start); + if (end == -1) end = data.length(); + } + + return null; + } + + // Method to get the value associated with a key, or an empty string if the key is not present + public String get(String key) { + for (String[] keyValue : this) if (keyValue[0].equals(key)) return keyValue[1]; + return ""; + } + + // Method to get the value associated with a key, or a fallback value if the key is not present + public String get(String key, String fallback) { + for (String[] keyValue : this) if (keyValue[0].equals(key)) return keyValue[1]; + return fallback; + } + + // Method to get a boolean value associated with a key, or a fallback value if the key is not present + public boolean getBoolean(String key, boolean fallback) { + String value = get(key); + if (value.isEmpty()) return fallback; + return value.equals("1") || value.equals("t") || value.equalsIgnoreCase("true"); + } + + // Method to get a float value associated with a key, or a fallback value if the key is not present + public float getFloat(String key, float fallback) { + String value = get(key); + try { + if (!value.isEmpty()) return Float.parseFloat(value); + } catch (NumberFormatException e) { + // Ignore exception and return fallback + } + return fallback; + } + + // Method to set a value for a key in the key-value data + public void put(String key, Object value) { + int[] range = indexOfKey(key); + if (range != null) { + data = data.substring(0, range[0]) + key + "=" + value + data.substring(range[1]); + } else { + data = (!data.isEmpty() ? data + "," : "") + key + "=" + value; + } + } + + // Method to set a float value for a key in the key-value data + public void put(String key, float value) { + put(key, String.valueOf(value)); + } + + // Iterator implementation for key-value pairs in the format [key, value] + @NonNull + @Override + public Iterator iterator() { + final int[] start = {0}; + final int[] end = {data.indexOf(",")}; + // A single-item config (no comma) gives indexOf == -1, making hasNext() (start < end) + // immediately false so the sole pair was never iterated (get() then returned the + // fallback). Guard it exactly as next() already does. An empty string still yields + // end == 0 → no iteration, which is correct. + if (end[0] == -1) end[0] = data.length(); + final String[] item = new String[2]; + return new Iterator() { + @Override + public boolean hasNext() { + return start[0] < end[0]; + } + + @Override + public String[] next() { + int index = data.indexOf("=", start[0]); + item[0] = data.substring(start[0], index); + item[1] = data.substring(index + 1, end[0]); + start[0] = end[0] + 1; + end[0] = data.indexOf(",", start[0]); + if (end[0] == -1) end[0] = data.length(); + return item; + } + }; + } + + @NonNull + @Override + public String toString() { + return data; + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/hud/MangoReadings.kt b/app/src/main/java/com/droiddeck/launcher/hud/MangoReadings.kt new file mode 100644 index 0000000000..828bcc0f5a --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/hud/MangoReadings.kt @@ -0,0 +1,157 @@ +package com.droiddeck.launcher.hud + +import com.droiddeck.launcher.runtime.LinuxRuntime +import java.io.File + +/** + * The readings Steam's performance overlay shows in a DroidDeck session (Valve's mangohud 20260902.1, + * tools/mangoapp), taken from the files the session hands it and computed the same way, so the two + * overlays agree. Sources and formulas follow that build: cpu.cpp calculateCPUData, deckard_temp.cpp, + * msm.cpp getQcomGpuInfo, memory.cpp update_meminfo and battery.cpp getPercent / getPower. + */ +internal class MangoReadings(private val sessionDir: File, private val rootDir: File) { + class Cpu(val percent: Int, val perCore: IntArray) + class Memory(val usedBytes: Long, val totalBytes: Long, val swapUsedBytes: Long, val swapTotalBytes: Long) + class Battery(val percent: Int?, val watts: Float, val charging: Boolean) + + private val cpuTimes = HashMap() + private val cpuPercents = HashMap() + + /** Total and per-core load from the session's /proc/stat (DroidDeck's stand-in when the app can't read it). */ + @JvmOverloads + fun cpu(stat: File = statFile()): Cpu? { + val lines = runCatching { stat.readLines() }.getOrNull() ?: return null + var total: Int? = null + val cores = ArrayList() + for (line in lines) { + if (!line.startsWith("cpu")) break + val parts = line.split(WHITESPACE) + if (parts.size < 11) continue + val values = LongArray(10) { parts[it + 1].toLongOrNull() ?: 0L } + val percent = cpuPercent(parts[0], values) + if (parts[0] == "cpu") total = percent else cores.add(percent) + } + return total?.let { Cpu(it, cores.toIntArray()) } + } + + private fun statFile(): File = + File(sessionDir, "proc-stat").takeIf { !File("/proc/stat").canRead() && it.isFile } ?: File("/proc/stat") + + private fun cpuPercent(key: String, v: LongArray): Int { + // user nice system idle iowait irq softirq steal guest guest_nice; guest time is already in user. + val user = v[0] - v[8] + val nice = v[1] - v[9] + val systemAll = v[2] + v[5] + v[6] + val idleAll = v[3] + v[4] + val virt = v[8] + v[9] + val totalTime = user + nice + systemAll + idleAll + v[7] + virt + val now = longArrayOf(user, nice, systemAll, v[7], virt, totalTime) + val last = cpuTimes.put(key, now) ?: LongArray(6) + fun period(i: Int) = if (now[i] > last[i]) now[i] - last[i] else 0L + val totalPeriod = period(5).toFloat() + if (totalPeriod == 0f) return cpuPercents[key] ?: 0 + val busy = period(1) * 100f / totalPeriod + period(0) * 100f / totalPeriod + + period(2) * 100f / totalPeriod + (period(3) + period(4)) * 100f / totalPeriod + return busy.coerceIn(0f, 100f).toInt().also { cpuPercents[key] = it } + } + + /** Average of the zones the session types cpuN-thermal, truncated. */ + fun cpuTempC(): Int? { + var sum = 0f + var count = 0 + for (zone in LinuxRuntime.cpuTempZones()) { + val milli = readLong(File(zone, "temp")) ?: continue + sum += milli / 1000f + count++ + } + return if (count == 0) null else (sum / count).toInt() + } + + fun gpuPercent(): Int? { + val feed = fresh(File(sessionDir, "sys/kgsl-3d0/perf_now")) + val source = feed ?: LinuxRuntime.gpuLoadSource()?.let(::File) ?: return null + return leadingNumber(source)?.toInt()?.coerceIn(0, 100) + } + + fun gpuClockMhz(): Int? { + val feed = fresh(File(sessionDir, "sys/kgsl-3d0/cur_freq")) + val source = feed ?: listOf("$KGSL/devfreq/cur_freq", "$KGSL/gpuclk").map(::File).firstOrNull { it.canRead() } ?: return null + val hz = leadingNumber(source) ?: return null + return (hz / 1_000_000.0).toInt().takeIf { it > 0 } + } + + fun gpuTempC(): Int? { + val milli = LinuxRuntime.gpuTempSource()?.let { readLong(File(it)) } ?: return null + return (milli / 1000.0).toInt() + } + + /** MemTotal - MemAvailable and SwapTotal - SwapFree from /proc/meminfo. */ + fun memory(): Memory? { + val kb = HashMap() + runCatching { + File("/proc/meminfo").forEachLine { line -> + val colon = line.indexOf(':') + if (colon > 0) line.substring(colon + 1).trim().split(WHITESPACE).firstOrNull()?.toLongOrNull() + ?.let { kb[line.substring(0, colon)] = it } + } + } + val total = kb["MemTotal"] ?: return null + val available = kb["MemAvailable"] ?: return null + val swapTotal = kb["SwapTotal"] ?: 0L + val swapFree = kb["SwapFree"] ?: 0L + return Memory((total - available) * 1024, total * 1024, (swapTotal - swapFree) * 1024, swapTotal * 1024) + } + + /** The KGSL total DroidDeck shares with the session (GpuMemComponent). */ + fun vramBytes(): Long? = fresh(File(rootDir, VRAM_FILE), VRAM_FRESH_MS)?.let(::readLong) + + /** BAT* under the session's power_supply (BatteryComponent): no watts while charging, full or unknown. */ + fun battery(): Battery? { + val dirs = File(sessionDir, "sys/power_supply").listFiles { f -> f.name.contains("BAT") }?.sortedBy { it.name } + if (dirs.isNullOrEmpty()) return null + var chargeNow = 0f + var chargeFull = 0f + var watts = 0f + var charging = false + for (dir in dirs) { + val status = runCatching { File(dir, "status").readLines().firstOrNull() }.getOrNull() + if (status == "Charging" || status == "Unknown" || status == "Full") charging = true + val now = File(dir, "charge_now").takeIf { it.exists() } ?: File(dir, "energy_now") + val full = File(dir, "charge_full").takeIf { it.exists() } ?: File(dir, "energy_full") + if (now.exists()) { + chargeNow += (readFloat(now) ?: 0f) / 1_000_000f + chargeFull += (readFloat(full) ?: 0f) / 1_000_000f + } else { + chargeNow += (readFloat(File(dir, "capacity")) ?: 0f) / 100f + chargeFull = dirs.size.toFloat() + } + if (!charging) { + val power = File(dir, "power_now") + watts += if (power.exists()) kotlin.math.abs(readFloat(power) ?: 0f) / 1_000_000f + else kotlin.math.abs((readFloat(File(dir, "current_now")) ?: 0f) * (readFloat(File(dir, "voltage_now")) ?: 0f)) / 1e12f + } + } + val percent = if (chargeFull > 0f) Math.round(chargeNow / chargeFull * 100f) else null + return Battery(percent, if (charging) 0f else watts, charging) + } + + private fun fresh(file: File, maxAgeMs: Long = FEED_FRESH_MS): File? = + file.takeIf { it.isFile && System.currentTimeMillis() - it.lastModified() < maxAgeMs } + + + companion object { + private const val KGSL = "/sys/class/kgsl/kgsl-3d0" + const val VRAM_FILE = "run/droiddeck-hud/gpu-mem" + private const val FEED_FRESH_MS = 10_000L + private const val VRAM_FRESH_MS = 15_000L + private val WHITESPACE = Regex("\\s+") + + private fun readLong(file: File): Long? = runCatching { file.readText().trim().toLong() }.getOrNull() + private fun readFloat(file: File): Float? = runCatching { file.readLines().first().trim().toFloat() }.getOrNull() + + /** std::stod on the first line: the leading number, "6 %" -> 6. */ + fun leadingNumber(file: File): Double? = runCatching { + Regex("^\\s*-?\\d+(\\.\\d+)?").find(file.readLines().first())?.value?.trim()?.toDouble() + }.getOrNull() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java index d02fdf0c2f..7bef53729b 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java +++ b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java @@ -341,9 +341,9 @@ public final class LinuxRuntime { } public static String cpuTempSource() { - for (java.util.Map.Entry e : new java.util.TreeMap<>(thermalZones()).entrySet()) { - File temp = new File(e.getValue(), "temp"); - if (e.getKey().contains("cpu") && !e.getKey().contains("gpu") && temp.canRead()) return temp.getPath(); + for (File zone : cpuTempZones()) { + File temp = new File(zone, "temp"); + if (temp.canRead()) return temp.getPath(); } return null; } @@ -353,7 +353,7 @@ public final class LinuxRuntime { return firstReadable(kgsl + "temp", kgsl + "devfreq/temp", thermalZone("gpu")); } - private static String gpuLoadSource() { + public static String gpuLoadSource() { String kgsl = "/sys/class/kgsl/kgsl-3d0/"; return firstReadable(kgsl + "gpu_busy_percentage", kgsl + "devfreq/gpu_load"); } @@ -367,7 +367,7 @@ public final class LinuxRuntime { "/sys/devices/platform/soc@0/3d00000.gpu/devfreq/3d00000.gpu/cur_freq"}, {gpuTemp, "/sys/class/thermal/thermal_zone28/temp"}, {gpuTemp, "/sys/class/thermal/thermal_zone26/temp"}, - {thermalZone("ddr"), "/sys/class/thermal/thermal_zone22/temp"}, + {ddrTempSource(), "/sys/class/thermal/thermal_zone22/temp"}, }; for (String[] stat : stats) { boolean fed = false; @@ -384,6 +384,36 @@ public final class LinuxRuntime { return path != null ? path : "none"; } + private static String ddrTempSource() { + return thermalZone("ddr"); + } + + // MangoHud reads the GPU and DDR temperatures from these zone numbers (bindAdrenoStats). On phones + // where they are CPU zones, their type follows the temperature put there, so they stay out of the + // CPU average. + private static java.util.Map replacedZoneTypes() { + java.util.Map replaced = new java.util.HashMap<>(); + if (gpuTempSource() != null) { + replaced.put("thermal_zone28", "gpu-thermal"); + replaced.put("thermal_zone26", "gpu-thermal"); + } + if (ddrTempSource() != null) replaced.put("thermal_zone22", "ddr-thermal"); + return replaced; + } + + /** The zones the session's MangoHud averages for the CPU temperature (all typed cpuN-thermal there). */ + public static List cpuTempZones() { + java.util.Map replaced = replacedZoneTypes(); + List zones = new ArrayList<>(); + for (java.util.Map.Entry zone : new java.util.TreeMap<>(thermalZones()).entrySet()) { + String type = zone.getKey(); + if (type.contains("cpu") && !type.contains("gpu") && !replaced.containsKey(zone.getValue().getName())) { + zones.add(zone.getValue()); + } + } + return zones; + } + private static void bindCpuTemps(List cmd, File root) { File name = new File(root, "etc/droiddeck/cpu-thermal-type"); try { @@ -391,9 +421,18 @@ public final class LinuxRuntime { } catch (IOException e) { return; } + java.util.Map replaced = replacedZoneTypes(); for (java.util.Map.Entry zone : thermalZones().entrySet()) { String type = zone.getKey(); - if (type.contains("cpu") && !type.contains("gpu") && !type.matches("cpu\\d-(top-)?thermal")) { + String other = replaced.get(zone.getValue().getName()); + if (other != null) { + File typeFile = new File(root, "etc/droiddeck/" + other + "-type"); + try { + if (!typeFile.isFile()) Files.write(typeFile.toPath(), (other + "\n").getBytes(StandardCharsets.US_ASCII)); + bind(cmd, typeFile.getPath() + ":" + new File(zone.getValue(), "type").getPath()); + } catch (IOException ignored) { + } + } else if (type.contains("cpu") && !type.contains("gpu") && !type.matches("cpu\\d-(top-)?thermal")) { bind(cmd, name.getPath() + ":" + new File(zone.getValue(), "type").getPath()); } } diff --git a/app/src/main/java/com/droiddeck/launcher/session/GpuMemComponent.kt b/app/src/main/java/com/droiddeck/launcher/session/GpuMemComponent.kt index 449c2bb7ff..e95af8b155 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/GpuMemComponent.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/GpuMemComponent.kt @@ -21,7 +21,7 @@ class GpuMemComponent(private val file: File, private val root: File) : SessionP thread = Thread({ while (running) { try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break } - if (running && OverlayShown.check(root)) sample()?.let { write(it) } + if (running && (OverlayShown.check(root) || com.droiddeck.launcher.hud.FusionHudHost.showing)) sample()?.let { write(it) } } }, "gpu-mem").apply { isDaemon = true; start() } } diff --git a/app/src/main/java/com/droiddeck/launcher/session/PerfHud.kt b/app/src/main/java/com/droiddeck/launcher/session/PerfHud.kt deleted file mode 100644 index 6453f65f9c..0000000000 --- a/app/src/main/java/com/droiddeck/launcher/session/PerfHud.kt +++ /dev/null @@ -1,178 +0,0 @@ -package com.droiddeck.launcher.session - -import android.content.Context -import android.content.Intent -import android.content.IntentFilter -import android.os.BatteryManager -import android.os.Environment -import android.os.Handler -import android.os.Looper -import android.os.SystemClock -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import com.droiddeck.launcher.R -import com.droiddeck.launcher.gpu.FrameGen -import com.droiddeck.launcher.gpu.Lossless -import com.droiddeck.launcher.wayland.WaylandCompositor -import java.io.File -import java.util.Locale -import java.util.concurrent.atomic.AtomicInteger - -class PerfHud(context: Context) { - var text by mutableStateOf("") - private set - var graph by mutableStateOf(FloatArray(0)) - private set - - private val context = context.applicationContext - private val frames = AtomicInteger() - private var lastTick = 0L - private var lastFps = 0f - private var running = false - private val handler = Handler(Looper.getMainLooper()) - private val samples = FloatArray(GRAPH) - private var graphBase = 0L - private var graphSeen = 0L - - @Volatile private var showFps = true - @Volatile private var showBattery = true - @Volatile private var showGraph = true - - private val enabled: Boolean - get() = SessionPrefs.hudEnabled(context) - && !File(Environment.getExternalStorageDirectory(), "Download/droiddeck-no-hud").exists() - - private val anyPart: Boolean - get() = showFps || showBattery || showGraph - - var onPresentingWindowChanged: (() -> Unit)? = null - private var lastWindow: String? = null - - private val listener = object : WaylandCompositor.GameListener { - override fun onGameSurface(window: String?, gpuName: String?) { - if (window != null && window != lastWindow) { - lastWindow = window - handler.post { onPresentingWindowChanged?.invoke() } - } - } - override fun onGameFrame() { - frames.incrementAndGet() - } - } - - private val tick = object : Runnable { - override fun run() { - if (!running) return - val now = SystemClock.elapsedRealtime() - val dt = (now - lastTick).coerceAtLeast(1L) / 1000f - lastTick = now - lastFps = frames.getAndSet(0) / dt - text = readout(lastFps) - if (showGraph) publishGraph() else clearGraph() - handler.postDelayed(this, TICK_MS) - } - } - - fun refresh() { - readOptions() - if (!enabled || !anyPart) { - stop() - return - } - if (!running) start() else { - if (!showGraph) clearGraph() else publishGraph() - text = readout(lastFps) - } - } - - fun start() { - readOptions() - if (!enabled || !anyPart || running) return - running = true - lastTick = SystemClock.elapsedRealtime() - frames.set(0) - graphBase = shownTotal() - graphSeen = graphBase - WaylandCompositor.setGameListener(listener) - handler.postDelayed(tick, TICK_MS) - } - - fun stop() { - running = false - handler.removeCallbacks(tick) - WaylandCompositor.clearGameListener(listener) - text = "" - graph = FloatArray(0) - } - - private fun readOptions() { - showFps = SessionPrefs.hudShowFps(context) - showBattery = SessionPrefs.hudShowBattery(context) - showGraph = SessionPrefs.hudShowGraph(context) - } - - private fun readout(fpsValue: Float): String { - val parts = ArrayList(2) - if (showFps) parts.add(line(fpsValue)) - if (showBattery) batteryCelsius(readBatteryDeci())?.let { parts.add(it) } - return parts.joinToString("\n") - } - - private fun readBatteryDeci(): Int { - val sticky = runCatching { - context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED)) - }.getOrNull() ?: return 0 - return sticky.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0) - } - - private fun shownTotal(): Long = try { WaylandCompositor.nativeHudFrameTimes(samples) } catch (t: Throwable) { 0L } - - private fun clearGraph() { - graphBase = shownTotal() - graphSeen = graphBase - if (graph.isNotEmpty()) graph = FloatArray(0) - } - - private fun publishGraph() { - val total = shownTotal() - if (total == graphSeen && graph.isNotEmpty()) return - graphSeen = total - graph = recent(samples, total, graphBase) - } - - private fun line(base: Float): String { - val mode = FrameGen.mode(context) - if (mode.engine == FrameGen.ENGINE_OFF) return fps(base) - val lsfg = mode.engine == FrameGen.ENGINE_LSFG - val name = if (lsfg) "LSFG" else "DD-FG" - val label = FrameGen.label(context, mode) - if (lsfg && Lossless.cacheFile(context)?.isFile != true) return context.getString(R.string.hud_fg_needs_lossless, name) - val stats = try { WaylandCompositor.nativeFrameGenStats() } catch (t: Throwable) { null } - val problem = try { WaylandCompositor.nativeFrameGenProblem() } catch (t: Throwable) { -1 } - return when { - problem == 1 -> context.getString(R.string.hud_fg_unsupported, name) - problem == 2 -> context.getString(R.string.hud_fg_failed, name) - stats != null && stats[3] > 1f -> String.format(Locale.US, "%s %.0f → %.0f fps", label, base, stats[3]) - else -> context.getString(R.string.hud_fg_starting, label, fps(base)) - } - } - - private fun fps(value: Float) = String.format(Locale.US, "%.0f fps", value) - - companion object { - private const val TICK_MS = 1_000L - private const val GRAPH = 128 - internal const val GRAPH_MAX_MS = 50f - - internal fun recent(samples: FloatArray, total: Long, base: Long): FloatArray { - val filled = minOf(total, samples.size.toLong()).toInt() - val shown = minOf(filled.toLong(), (total - base).coerceAtLeast(0L)).toInt() - if (shown < 2) return FloatArray(0) - return FloatArray(shown) { samples[filled - shown + it].coerceIn(0f, GRAPH_MAX_MS) } - } - - internal fun batteryCelsius(deci: Int): String? = - if (deci <= 0) null else String.format(Locale.US, "%.1f°C", deci / 10f) - } -} 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 ed55f0019b..2df87e166d 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -233,6 +233,20 @@ object SessionPrefs { prefs(context).edit().putInt("hudOpacity", percent.coerceIn(HUD_OPACITY_RANGE)).apply() } + fun fusionHudConfig(context: Context): String? = prefs(context).getString("fusionHud", null) + + fun setFusionHudConfig(context: Context, config: String) { + prefs(context).edit().putString("fusionHud", config).apply() + } + + fun fusionHudPosition(context: Context): Pair? = + prefs(context).getString("fusionHudPos", null)?.split(',')?.mapNotNull { it.toFloatOrNull() } + ?.takeIf { it.size == 2 }?.let { it[0] to it[1] } + + fun setFusionHudPosition(context: Context, x: Float, y: Float) { + prefs(context).edit().putString("fusionHudPos", "$x,$y").apply() + } + const val HUD_COLOR_MINT = "mint" val HUD_COLORS = listOf(HUD_COLOR_MINT, "white", "sky", "amber", "violet") val HUD_OPACITY_RANGE = 30..100 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 83a82a13b4..b1a5f5e996 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt @@ -14,7 +14,7 @@ object SettingsReset { "orientation", "launcherFullscreen", "animations", "theme", "runSteamAtStartup", "addedGamesArt", "gameStoresEnabled", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature", "storesInstallLanguage", - "hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "backActionsInverted", "backDoubleTapMs", "touch", "osc", "shape", "steamController", + "hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "fusionHud", "fusionHudPos", "backActionsInverted", "backDoubleTapMs", "touch", "osc", "shape", "steamController", "gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController", "stretch16x9", "picturePosition", "gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop", diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FusionHudSettings.kt b/app/src/main/java/com/droiddeck/launcher/ui/FusionHudSettings.kt new file mode 100644 index 0000000000..1721693180 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/FusionHudSettings.kt @@ -0,0 +1,133 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import com.droiddeck.launcher.R +import com.droiddeck.launcher.hud.FusionSize + +/** Bannerlator's Fusion HUD settings (DeckOverlaySettings): one row per key of the HUD's config string. */ +@Composable +internal fun FusionHudSettings(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) { + val cfg = a.hudConfig + fun on(key: String) = cfg[key] == "1" + fun int(key: String, fallback: Int) = cfg[key]?.toIntOrNull() ?: fallback + + SettingsGroup(stringResource(R.string.drawer_hud), detail = stringResource(R.string.hud_matches_steam_overlay)) { + ToggleRow(host, "hud", stringResource(R.string.drawer_hud), null, a.hudOn, chipModifier = track("hud"), onChange = a.onHud) + if (!a.hudOn) return@SettingsGroup + val size = FusionSize.from(cfg["hudSize"]) + ChoiceRow(host, "hud-size", stringResource(R.string.hud_size), stringResource(R.string.hud_size_hint), + listOf( + FusionSize.FULL to stringResource(R.string.hud_size_full), + FusionSize.TILES to stringResource(R.string.hud_size_tiles), + FusionSize.PILL to stringResource(R.string.hud_size_pill), + FusionSize.MINIMAL to stringResource(R.string.hud_size_minimal), + FusionSize.MEGA to stringResource(R.string.hud_size_mega), + ), + size, chipModifier = track("hud-size")) { a.onHudSetting("hudSize", it.token) } + ToggleRow(host, "hud-locked", stringResource(R.string.hud_locked), stringResource(R.string.hud_locked_hint), on("hudLocked"), + chipModifier = track("hud-locked")) { a.onHudSetting("hudLocked", flag(it)) } + } + if (!a.hudOn) return + + SettingsGroup(stringResource(R.string.hud_group_look)) { + SliderRow(stringResource(R.string.hud_scale), null, int("hudScale", 100), 50..150, step = 5, format = { "$it%" }, + modifier = track("hud-scale")) { a.onHudSetting("hudScale", it.toString()) } + SliderRow(stringResource(R.string.drawer_hud_opacity), null, int("hudOpacity", 80), 0..100, step = 5, format = { "$it%" }, + modifier = track("hud-opacity")) { a.onHudSetting("hudOpacity", it.toString()) } + ChoiceRow(host, "hud-color", stringResource(R.string.drawer_hud_color), null, + listOf("soft" to stringResource(R.string.hud_color_soft), "mid" to stringResource(R.string.hud_color_mid), + "vivid" to stringResource(R.string.hud_color_vivid)), + cfg["hudColor"] ?: "mid", chipModifier = track("hud-color")) { a.onHudSetting("hudColor", it) } + SliderRow(stringResource(R.string.hud_outline), null, int("hudOutline", 40), 0..100, step = 10, + modifier = track("hud-outline")) { a.onHudSetting("hudOutline", it.toString()) } + ChoiceRow(host, "hud-outline-color", stringResource(R.string.hud_outline_color), null, + listOf("0" to stringResource(R.string.hud_outline_gray), "1" to stringResource(R.string.hud_outline_theme)), + if (cfg["hudOutlineAccent"] == "0") "0" else "1", chipModifier = track("hud-outline-color")) { a.onHudSetting("hudOutlineAccent", it) } + } + + val size = FusionSize.from(cfg["hudSize"]) + val chips = size.supportedChips() + EXTRA[size].orEmpty() + SettingsGroup(stringResource(R.string.hud_group_metrics)) { + for (metric in METRICS) { + if (metric.chip !in chips || metric.chip in HIDDEN[size].orEmpty()) continue + ToggleRow(host, "hud-${metric.key}", stringResource(metric.label), null, on(metric.key), + chipModifier = track("hud-${metric.key}")) { a.onHudSetting(metric.key, flag(it)) } + } + } + + val tempsShown = ("Temp" in chips && on("showTemp")) || ("GPU temp" in chips && on("showGpuTemp")) + if (tempsShown) SettingsGroup(stringResource(R.string.hud_group_temps)) { + ChoiceRow(host, "hud-temp-unit", stringResource(R.string.hud_temp_unit), null, + listOf("c" to "°C", "f" to "°F"), if (cfg["tempUnit"].equals("f", true)) "f" else "c", + chipModifier = track("hud-temp-unit")) { a.onHudSetting("tempUnit", it) } + val bands = when { + cfg["tempBands"] == "0" -> "0" + cfg["tempAuto"] == "0" -> "2" + else -> "1" + } + ChoiceRow(host, "hud-temp-bands", stringResource(R.string.hud_temp_bands), stringResource(R.string.hud_temp_bands_hint), + listOf("0" to stringResource(R.string.hud_temp_bands_off), "1" to stringResource(R.string.hud_temp_bands_auto), + "2" to stringResource(R.string.hud_temp_bands_manual)), + bands, chipModifier = track("hud-temp-bands")) { + a.onHudSetting("tempBands", if (it == "0") "0" else "1") + a.onHudSetting("tempAuto", if (it == "2") "0" else "1") + } + if (bands == "2") { + SliderRow(stringResource(R.string.hud_temp_red_cpu), null, int("tempRedCpu", 90), 50..110, format = { "$it°C" }, + modifier = track("hud-red-cpu")) { a.onHudSetting("tempRedCpu", it.toString()) } + SliderRow(stringResource(R.string.hud_temp_red_gpu), null, int("tempRedGpu", 90), 50..110, format = { "$it°C" }, + modifier = track("hud-red-gpu")) { a.onHudSetting("tempRedGpu", it.toString()) } + SliderRow(stringResource(R.string.hud_temp_red_battery), null, int("tempRedBat", 48), 35..60, format = { "$it°C" }, + modifier = track("hud-red-battery")) { a.onHudSetting("tempRedBat", it.toString()) } + } + } + + SettingsGroup(stringResource(R.string.hud_group_more), detail = stringResource(R.string.hud_credit)) { + ActionRow(stringResource(R.string.hud_export), stringResource(R.string.hud_export_hint), + stringResource(R.string.hud_export_button), onClick = a.onHudExport, modifier = track("hud-export")) + ActionRow(stringResource(R.string.hud_reset), null, stringResource(R.string.hud_reset_button), + onClick = a.onHudReset, modifier = track("hud-reset")) + } +} + +private fun flag(on: Boolean) = if (on) "1" else "0" + +// The Pill also draws the battery temperature and watts. +private val EXTRA = mapOf(FusionSize.PILL to setOf("Temp", "Power")) + +private class HudMetric(val chip: String, val key: String, val label: Int) + +// FusionSize.supportedChips() names; Wrapper and DX version have nothing to show in DroidDeck. +private val METRICS = listOf( + HudMetric("FPS", "showFPS", R.string.drawer_hud_fps), + HudMetric("FPS graph", "showFPSGraph", R.string.hud_metric_graph), + HudMetric("FPS .1", "fpsDecimal", R.string.hud_metric_decimal), + HudMetric("0.01% low", "showLow001", R.string.hud_metric_low001), + HudMetric("Engine", "showEngine", R.string.hud_metric_engine), + HudMetric("GPU model", "showGpuModel", R.string.hud_metric_gpu_model), + HudMetric("GPU", "showGPULoad", R.string.hud_metric_gpu), + HudMetric("GPU temp", "showGpuTemp", R.string.hud_metric_gpu_temp), + HudMetric("CPU", "showCPUUsage", R.string.hud_metric_cpu), + HudMetric("Per-core", "showPerCore", R.string.hud_metric_per_core), + HudMetric("Temp", "showTemp", R.string.hud_metric_temp), + HudMetric("RAM", "showRAM", R.string.hud_metric_ram), + HudMetric("VRAM", "showVram", R.string.hud_metric_vram), + HudMetric("Swap", "showSwap", R.string.hud_metric_swap), + HudMetric("Battery", "showBattery", R.string.hud_metric_battery), + HudMetric("Power", "showPower", R.string.hud_metric_power), + HudMetric("Network", "showNet", R.string.hud_metric_network), + HudMetric("Resolution", "showResolution", R.string.hud_metric_resolution), + HudMetric("Proton", "showProton", R.string.hud_metric_proton), + HudMetric("Session", "showSession", R.string.hud_metric_session), + HudMetric("Clock", "showClock", R.string.hud_metric_clock), +) + +// Switches a size lists but never draws (FusionHudView): the Pill and Minimal always show the FPS, the +// Pill has no graph, Tiles has no graph and no 0.01% low. +private val HIDDEN = mapOf( + FusionSize.PILL to setOf("FPS", "FPS graph"), + FusionSize.MINIMAL to setOf("FPS"), + FusionSize.TILES to setOf("FPS graph", "0.01% low"), +) 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 fb123fbd85..e7db9c561a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt @@ -4,7 +4,8 @@ internal enum class SessionDrawerPage(val firstControl: String) { CONTROLLER("touch"), GLASSES("glasses-game"), SECOND_SCREEN("second-screen:none"), - DISPLAY("hud"), + DISPLAY("fg"), + HUD("hud"), EFFECTS("look"), VR("steamvr"), GAMES("anisotropy"), diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionLoading.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionLoading.kt index f3dfbcf82d..85a1462949 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionLoading.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionLoading.kt @@ -18,7 +18,6 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.semantics.Role import com.droiddeck.launcher.frontend.Library import com.droiddeck.launcher.session.LoadingState -import com.droiddeck.launcher.session.PerfHud import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import androidx.compose.animation.core.FastOutSlowInEasing @@ -81,8 +80,8 @@ import androidx.compose.ui.text.style.TextOverflow @Composable -fun HudText(text: String, graph: FloatArray = FloatArray(0), color: String = "mint", opacity: Int = 70) { - if (text.isEmpty() && graph.size < 2) return +fun HudText(text: String, color: String = "mint", opacity: Int = 70) { + if (text.isEmpty()) return val accent = hudInk(color) val wash = (opacity.coerceIn(30, 100) / 100f) val ink = accent.copy(alpha = (0.5f + wash * 0.5f).coerceIn(0.62f, 1f)) @@ -99,49 +98,13 @@ fun HudText(text: String, graph: FloatArray = FloatArray(0), color: String = "mi ) .padding(horizontal = 8.dp, vertical = 5.dp), ) { - if (text.isNotEmpty()) Text( + Text( text, fontFamily = FontFamily.Monospace, fontSize = 12.sp, color = ink, textAlign = TextAlign.End, ) - if (graph.size >= 2) { - if (text.isNotEmpty()) Spacer(Modifier.height(4.dp)) - HudGraph(graph, accent, wash) - } - } - } -} - -@Composable -private fun HudGraph(samples: FloatArray, accent: Color, wash: Float) { - Canvas(Modifier.width(148.dp).height(44.dp)) { - val maxMs = PerfHud.GRAPH_MAX_MS - val step = size.width / (samples.size - 1) - fun yOf(ms: Float) = size.height * (1f - (ms / maxMs).coerceIn(0f, 1f)) - val fillAlpha = wash * 0.5f - val fill = Path().apply { - moveTo(0f, size.height) - samples.forEachIndexed { i, ms -> lineTo(i * step, yOf(ms)) } - lineTo(size.width, size.height) - close() - } - drawPath( - fill, - Brush.verticalGradient(listOf(HUD_SLOW.copy(alpha = fillAlpha), accent.copy(alpha = fillAlpha * 0.45f))), - ) - val guide = yOf(16.7f) - drawLine(Color.White.copy(alpha = 0.32f), Offset(0f, guide), Offset(size.width, guide), strokeWidth = 1f) - for (i in 0 until samples.lastIndex) { - val tone = ((samples[i] - 8f) / 25f).coerceIn(0f, 1f) - drawLine( - mix(accent, HUD_SLOW, tone).copy(alpha = 0.55f + wash * 0.4f), - Offset(i * step, yOf(samples[i])), - Offset((i + 1) * step, yOf(samples[i + 1])), - strokeWidth = 2.5f, - cap = StrokeCap.Round, - ) } } } @@ -156,17 +119,6 @@ private fun hudInk(color: String): Color = Color( }.toInt(), ) -private fun mix(from: Color, to: Color, t: Float): Color { - val u = t.coerceIn(0f, 1f) - return Color( - red = from.red + (to.red - from.red) * u, - green = from.green + (to.green - from.green) * u, - blue = from.blue + (to.blue - from.blue) * u, - alpha = 1f, - ) -} - -private val HUD_SLOW = Color(0xFFFF5C6C.toInt()) private class LoadStage(@androidx.annotation.StringRes val label: Int, @androidx.annotation.StringRes val detail: Int) 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 70bc1d1a2e..094c07326f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -42,6 +42,7 @@ import androidx.compose.material.icons.outlined.Pause import androidx.compose.material.icons.outlined.PictureInPictureAlt import androidx.compose.material.icons.automirrored.outlined.ExitToApp import androidx.compose.material.icons.outlined.Settings +import androidx.compose.material.icons.outlined.Speed import androidx.compose.material.icons.outlined.SportsEsports import androidx.compose.material3.Icon import androidx.compose.material3.RadioButton @@ -157,6 +158,7 @@ private val SessionDrawerPage.title: Int get() = when (this) { SessionDrawerPage.GLASSES -> R.string.drawer_page_glasses SessionDrawerPage.SECOND_SCREEN -> R.string.drawer_second_screen SessionDrawerPage.DISPLAY -> R.string.drawer_page_display + SessionDrawerPage.HUD -> R.string.drawer_hud SessionDrawerPage.VR -> R.string.vr_title SessionDrawerPage.EFFECTS -> R.string.drawer_page_effects SessionDrawerPage.GAMES -> R.string.game_settings_title @@ -168,6 +170,7 @@ private val SessionDrawerPage.icon get() = when (this) { SessionDrawerPage.GLASSES -> GlassesIcon SessionDrawerPage.SECOND_SCREEN -> Icons.Outlined.ScreenShare SessionDrawerPage.DISPLAY -> Icons.Outlined.DesktopWindows + SessionDrawerPage.HUD -> Icons.Outlined.Speed SessionDrawerPage.VR -> VrHeadsetIcon SessionDrawerPage.EFFECTS -> Icons.Outlined.AutoFixHigh SessionDrawerPage.GAMES -> Icons.Outlined.Layers @@ -201,11 +204,7 @@ class DrawerActions( val isHomeApp: Boolean, val androidApps: List, val hudOn: Boolean, - val hudFps: Boolean = true, - val hudBattery: Boolean = true, - val hudGraph: Boolean = true, - val hudColor: String = SessionPrefs.HUD_COLOR_MINT, - val hudOpacity: Int = SessionPrefs.HUD_OPACITY_DEFAULT, + val hudConfig: Map = emptyMap(), val frameGen: FrameGen.Mode, val lossless: Lossless.State, val oscMode: String, @@ -238,11 +237,9 @@ class DrawerActions( val secondScreenDisplays: List, val selectedSecondScreenDisplay: Int, val onHud: (Boolean) -> Unit, - val onHudFps: (Boolean) -> Unit = {}, - val onHudBattery: (Boolean) -> Unit = {}, - val onHudGraph: (Boolean) -> Unit = {}, - val onHudColor: (String) -> Unit = {}, - val onHudOpacity: (Int) -> Unit = {}, + val onHudSetting: (String, String) -> Unit = { _, _ -> }, + val onHudReset: () -> Unit = {}, + val onHudExport: () -> Unit = {}, val onFrameGenPick: (FrameGen.Mode) -> Unit, val onImportLossless: () -> Unit, val onKeyboard: () -> Unit, @@ -495,34 +492,9 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(pageScroll.getValue(page)), ) { CompositionLocalProvider(LocalChipMinWidth provides 96.dp, LocalCompactSettings provides true) { when (page) { + SessionDrawerPage.HUD -> FusionHudSettings(host, a) { key -> focus.track(page, key) } SessionDrawerPage.DISPLAY -> { SettingsGroup(stringResource(R.string.drawer_page_display)) { - ToggleRow(host, "hud", stringResource(R.string.drawer_hud), null, a.hudOn, - chipModifier = focus.track(page, "hud"), onChange = a.onHud) - if (a.hudOn) { - ToggleRow(host, "hud-fps", stringResource(R.string.drawer_hud_fps), null, a.hudFps, - chipModifier = focus.track(page, "hud-fps"), onChange = a.onHudFps) - ToggleRow(host, "hud-battery", stringResource(R.string.drawer_hud_battery), null, a.hudBattery, - chipModifier = focus.track(page, "hud-battery"), onChange = a.onHudBattery) - ToggleRow(host, "hud-graph", stringResource(R.string.drawer_hud_graph), null, a.hudGraph, - chipModifier = focus.track(page, "hud-graph"), onChange = a.onHudGraph) - ChoiceRow( - host, "hud-color", stringResource(R.string.drawer_hud_color), null, - listOf( - SessionPrefs.HUD_COLOR_MINT to stringResource(R.string.drawer_hud_color_mint), - "white" to stringResource(R.string.drawer_hud_color_white), - "sky" to stringResource(R.string.drawer_hud_color_sky), - "amber" to stringResource(R.string.drawer_hud_color_amber), - "violet" to stringResource(R.string.drawer_hud_color_violet), - ), - a.hudColor, chipModifier = focus.track(page, "hud-color"), onPick = a.onHudColor, - ) - SliderRow( - stringResource(R.string.drawer_hud_opacity), null, a.hudOpacity, - SessionPrefs.HUD_OPACITY_RANGE, step = 10, format = { "$it%" }, - modifier = focus.track(page, "hud-opacity"), onChange = a.onHudOpacity, - ) - } val fgOpen = host.open == "fg" val fgLabel = FrameGen.label(LocalContext.current, a.frameGen) SettingsRow(stringResource(R.string.frame_gen_title), null, highlighted = fgOpen) { diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 613ec6a92a..dbb7c252fc 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -615,6 +615,65 @@ كهرماني بنفسجي العتامة + يأتي معدل الإطارات وأزمنة الإطارات والقراءات من المصادر نفسها التي تستخدمها طبقة الأداء في Steam. + الحجم + النقر على HUD يغيّر حجمه أيضًا. + كامل + مربعات + كبسولة + مصغّر + ضخم + تثبيت في مكانه + اسحب HUD لتحريكه؛ والضغط مطولًا يثبّته أو يلغي تثبيته. + المظهر + الحجم على الشاشة + هادئ + متوسط + زاهٍ + الحد الخارجي + لون الحد الخارجي + رمادي + لون المظهر + القراءات + مخطط زمن الإطار + معدل الإطارات بخانة عشرية + أدنى 0.01% + محرك الرسومات + اسم GPU + حمل GPU + درجة حرارة GPU + حمل CPU + CPU لكل نواة + درجات الحرارة + الذاكرة + ذاكرة الرسومات + ذاكرة التبديل + مستوى البطارية + استهلاك الطاقة + الشبكة + الدقة + إصدار Proton + مدة الجلسة + الساعة + درجات الحرارة + الوحدة + ألوان التحذير + تتحول درجات الحرارة إلى الكهرماني ثم الأحمر كلما اقتربت من الحد. + إيقاف + تلقائي + يدوي + CPU بالأحمر عند + GPU بالأحمر عند + البطارية بالأحمر عند + المزيد + تشخيص HUD + يحفظ تقريرًا عن كل مستشعر يقرؤه HUD في Downloads/DroidDeck. + حفظ + تم الحفظ في %1$s + تعذّر حفظ تقرير HUD. + إعادة ضبط إعدادات HUD + إعادة ضبط + FusionHUD من The412Banner، github.com/The412Banner/FusionHUD (GPL-3.0). وضع التحجيم حدة التحجيم مؤثرات الشاشة 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 dcb85c824a..e7b0873864 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -602,6 +602,65 @@ Ámbar Violeta Opacidad + La tasa de fotogramas, los tiempos de fotograma y las lecturas provienen de las mismas fuentes que la superposición de rendimiento de Steam. + Tamaño + Tocar el HUD también cambia su tamaño. + Completo + Mosaicos + Píldora + Mínimo + Mega + Fijar posición + Arrastra el HUD para moverlo; una pulsación larga lo bloquea o lo desbloquea. + Aspecto + Tamaño en pantalla + Suave + Medio + Intenso + Contorno + Color del contorno + Gris + Color del tema + Lecturas + Gráfico de tiempos de fotograma + Tasa de fotogramas con decimal + 0.01% más bajo + Motor gráfico + Nombre de la GPU + Carga de la GPU + Temperatura de la GPU + Carga de la CPU + CPU por núcleo + Temperaturas + Memoria + Memoria gráfica + Memoria de intercambio + Nivel de batería + Consumo de energía + Red + Resolución + Versión de Proton + Tiempo de sesión + Reloj + Temperaturas + Unidad + Colores de aviso + Las temperaturas se vuelven ámbar y luego rojas al acercarse al límite. + Desactivado + Automático + Manual + CPU en rojo a partir de + GPU en rojo a partir de + Batería en rojo a partir de + Más + Diagnóstico del HUD + Guarda en Downloads/DroidDeck un informe de cada sensor que lee el HUD. + Guardar + Guardado en %1$s + No se pudo guardar el informe del HUD. + Restablecer ajustes del HUD + Restablecer + FusionHUD de The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0). Modo de escalado Nitidez del escalado Efectos de pantalla diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index dc272497cd..dd3a364d07 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -607,6 +607,65 @@ Кехлибарено Виолетово Прозрачност + Честотата на кадрите, времената на кадрите и показанията идват от същите източници като наслагването за производителност на Steam. + Размер + Докосването на HUD също променя размера му. + Пълен + Плочки + Хапче + Минимален + Мега + Заключване на място + Плъзнете HUD, за да го преместите; продължително натискане го заключва или отключва. + Визия + Размер на екрана + Мек + Среден + Наситен + Контур + Цвят на контура + Сив + Цвят на темата + Показания + Графика на времето на кадрите + Честота на кадрите с десетичен знак + 0.01% най-ниски + Графичен двигател + Име на GPU + Натоварване на GPU + Температура на GPU + Натоварване на CPU + CPU по ядра + Температури + Памет + Графична памет + Swap памет + Ниво на батерията + Консумация на енергия + Мрежа + Разделителна способност + Версия на Proton + Продължителност на сесията + Часовник + Температури + Мерна единица + Предупредителни цветове + Температурите стават кехлибарени, а после червени, когато наближат границата. + Изкл. + Автоматично + Ръчно + CPU в червено от + GPU в червено от + Батерия в червено от + Повече + Диагностика на HUD + Записва в Downloads/DroidDeck отчет за всеки сензор, който HUD чете. + Запиши + Записано в %1$s + Отчетът за HUD не можа да бъде записан. + Нулиране на настройките на HUD + Нулиране + FusionHUD от The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0). Режим на мащабиране Острота на мащабиране Ефекти на екрана diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index fae43cbee4..441b8c1b0b 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -611,6 +611,65 @@ Ambrová Fialová Průhlednost + Snímková frekvence, časy snímků a naměřené hodnoty pocházejí ze stejných zdrojů jako výkonnostní překryv Steamu. + Velikost + Klepnutím na HUD se také změní jeho velikost. + Plný + Dlaždice + Pilulka + Minimální + Mega + Zamknout na místě + Přetažením HUD přesunete; dlouhým stiskem ho zamknete nebo odemknete. + Vzhled + Velikost na obrazovce + Jemná + Střední + Sytá + Obrys + Barva obrysu + Šedá + Barva tématu + Údaje + Graf časů snímků + Snímková frekvence s desetinným místem + 0.01% nejnižší + Grafický engine + Název GPU + Vytížení GPU + Teplota GPU + Vytížení CPU + CPU po jádrech + Teploty + Paměť + Grafická paměť + Odkládací paměť + Stav baterie + Příkon + Síť + Rozlišení + Verze Protonu + Doba relace + Hodiny + Teploty + Jednotka + Varovné barvy + Teploty se při přiblížení k limitu zbarví nejprve ambrově, pak červeně. + Vypnuto + Automaticky + Manuální + CPU červeně od + GPU červeně od + Baterie červeně od + Více + Diagnostika HUD + Uloží do Downloads/DroidDeck zprávu o všech senzorech, které HUD čte. + Uložit + Uloženo do %1$s + Zprávu HUD se nepodařilo uložit. + Obnovit nastavení HUD + Obnovit + FusionHUD od The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0). Režim škálování Ostrost škálování Efekty obrazovky diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 79b1d12167..08e584f351 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -607,6 +607,65 @@ Ravgul Violet Gennemsigtighed + Billedhastighed, billedtider og målinger kommer fra de samme kilder som Steams ydelsesoverlay. + Størrelse + Et tryk på HUD ændrer også størrelsen. + Fuld + Fliser + Pille + Minimal + Mega + Lås fast + Træk i HUD for at flytte det; et langt tryk låser eller frigør det. + Udseende + Størrelse på skærmen + Blød + Mellem + Kraftig + Kontur + Konturfarve + Grå + Temafarve + Målinger + Billedtidsgraf + Billedhastighed med decimal + 0.01% laveste + Grafikmotor + GPU-navn + GPU-belastning + GPU-temperatur + CPU-belastning + CPU pr. kerne + Temperaturer + Hukommelse + Grafikhukommelse + Swap-hukommelse + Batteriniveau + Strømforbrug + Netværk + Opløsning + Proton-version + Sessionstid + Ur + Temperaturer + Enhed + Advarselsfarver + Temperaturer bliver ravgule og derefter røde, når de nærmer sig grænsen. + Fra + Automatisk + Manuel + CPU rød ved + GPU rød ved + Batteri rødt ved + Mere + HUD-diagnostik + Gemmer en rapport over alle sensorer, som HUD læser, i Downloads/DroidDeck. + Gem + Gemt i %1$s + HUD-rapporten kunne ikke gemmes. + Nulstil HUD-indstillinger + Nulstil + FusionHUD af The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0). Skaleringstilstand Skaleringsskarphed Skærmeffekter diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 57ef60848d..bb1b9df8c6 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -607,6 +607,65 @@ Bernstein Violett Deckkraft + Bildrate, Frametimes und Messwerte stammen aus denselben Quellen wie das Leistungs-Overlay von Steam. + Größe + Tippen auf das HUD ändert auch seine Größe. + Voll + Kacheln + Kapsel + Minimal + Mega + Position sperren + Ziehe das HUD, um es zu verschieben; langes Drücken sperrt oder entsperrt es. + Aussehen + Größe auf dem Bildschirm + Dezent + Mittel + Kräftig + Kontur + Konturfarbe + Grau + Designfarbe + Messwerte + Frametime-Diagramm + Bildrate mit Nachkommastelle + 0.01%-Tiefstwert + Grafik-Engine + GPU-Name + GPU-Auslastung + GPU-Temperatur + CPU-Auslastung + CPU pro Kern + Temperaturen + Arbeitsspeicher + Grafikspeicher + Swap-Speicher + Akkustand + Leistungsaufnahme + Netzwerk + Auflösung + Proton-Version + Sitzungsdauer + Uhrzeit + Temperaturen + Einheit + Warnfarben + Temperaturen werden erst bernsteinfarben, dann rot, wenn sie sich dem Grenzwert nähern. + Aus + Automatisch + Manuell + CPU rot ab + GPU rot ab + Akku rot ab + Mehr + HUD-Diagnose + Speichert einen Bericht zu allen Sensoren, die das HUD ausliest, unter Downloads/DroidDeck. + Speichern + Gespeichert unter %1$s + Der HUD-Bericht konnte nicht gespeichert werden. + HUD-Einstellungen zurücksetzen + Zurücksetzen + FusionHUD von The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0). Skalierungsmodus Skalierungsschärfe Bildschirmeffekte diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 246347ec49..3d07287309 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -607,6 +607,65 @@ Κεχριμπαρί Βιολετί Διαφάνεια + Ο ρυθμός καρέ, οι χρόνοι καρέ και οι μετρήσεις προέρχονται από τις ίδιες πηγές με την επικάλυψη απόδοσης του Steam. + Μέγεθος + Το πάτημα στο HUD αλλάζει επίσης το μέγεθός του. + Πλήρες + Πλακίδια + Κάψουλα + Ελάχιστο + Μέγα + Κλείδωμα θέσης + Σύρετε το HUD για να το μετακινήσετε· ένα παρατεταμένο πάτημα το κλειδώνει ή το ξεκλειδώνει. + Εμφάνιση + Μέγεθος στην οθόνη + Απαλό + Μεσαίο + Έντονο + Περίγραμμα + Χρώμα περιγράμματος + Γκρι + Χρώμα θέματος + Μετρήσεις + Γράφημα χρόνου καρέ + Ρυθμός καρέ με δεκαδικό + 0.01% χαμηλότερα + Μηχανή γραφικών + Όνομα GPU + Φόρτος GPU + Θερμοκρασία GPU + Φόρτος CPU + CPU ανά πυρήνα + Θερμοκρασίες + Μνήμη + Μνήμη γραφικών + Μνήμη swap + Στάθμη μπαταρίας + Κατανάλωση ισχύος + Δίκτυο + Ανάλυση + Έκδοση Proton + Χρόνος συνεδρίας + Ρολόι + Θερμοκρασίες + Μονάδα + Χρώματα προειδοποίησης + Οι θερμοκρασίες γίνονται κεχριμπαρί και μετά κόκκινες καθώς πλησιάζουν το όριο. + Ανενεργό + Αυτόματο + Μη αυτόματο + CPU κόκκινο από + GPU κόκκινο από + Μπαταρία κόκκινο από + Περισσότερα + Διαγνωστικά HUD + Αποθηκεύει στο Downloads/DroidDeck μια αναφορά για κάθε αισθητήρα που διαβάζει το HUD. + Αποθήκευση + Αποθηκεύτηκε στο %1$s + Δεν ήταν δυνατή η αποθήκευση της αναφοράς HUD. + Επαναφορά ρυθμίσεων HUD + Επαναφορά + FusionHUD από The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0). Λειτουργία κλιμάκωσης Οξύτητα κλιμάκωσης Εφέ οθόνης diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 2aff92715f..19383a1201 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -611,6 +611,65 @@ Ámbar Violeta Opacidad + La tasa de fotogramas, los tiempos de fotograma y las lecturas provienen de las mismas fuentes que la superposición de rendimiento de Steam. + Tamaño + Tocar el HUD también cambia su tamaño. + Completo + Mosaicos + Píldora + Mínimo + Mega + Fijar posición + Arrastra el HUD para moverlo; una pulsación larga lo bloquea o lo desbloquea. + Aspecto + Tamaño en pantalla + Suave + Medio + Intenso + Contorno + Color del contorno + Gris + Color del tema + Lecturas + Gráfico de tiempos de fotograma + Tasa de fotogramas con decimal + 0.01% más bajo + Motor gráfico + Nombre de la GPU + Carga de la GPU + Temperatura de la GPU + Carga de la CPU + CPU por núcleo + Temperaturas + Memoria + Memoria gráfica + Memoria de intercambio + Nivel de batería + Consumo de energía + Red + Resolución + Versión de Proton + Tiempo de sesión + Reloj + Temperaturas + Unidad + Colores de aviso + Las temperaturas se vuelven ámbar y luego rojas al acercarse al límite. + Desactivado + Automático + Manual + CPU en rojo a partir de + GPU en rojo a partir de + Batería en rojo a partir de + Más + Diagnóstico del HUD + Guarda en Downloads/DroidDeck un informe de cada sensor que lee el HUD. + Guardar + Guardado en %1$s + No se ha podido guardar el informe del HUD. + Restablecer ajustes del HUD + Restablecer + FusionHUD de The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0). Modo de escalado Nitidez del escalado Efectos de pantalla diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 9802f3716d..ab2e2eec38 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -607,6 +607,65 @@ Meripihka Violetti Peittävyys + Kuvataajuus, kuva-ajat ja lukemat tulevat samoista lähteistä kuin Steamin suorituskykynäkymässä. + Koko + HUD:n napauttaminen muuttaa myös sen kokoa. + Täysi + Ruudut + Kapseli + Minimaalinen + Mega + Lukitse paikalleen + Siirrä HUD:ia vetämällä; pitkä painallus lukitsee tai vapauttaa sen. + Ulkoasu + Koko näytöllä + Pehmeä + Keskitaso + Kirkas + Ääriviiva + Ääriviivan väri + Harmaa + Teeman väri + Lukemat + Kuva-aikakäyrä + Kuvataajuus desimaalilla + 0.01% alin + Grafiikkamoottori + GPU:n nimi + GPU:n kuorma + GPU:n lämpötila + CPU:n kuorma + CPU ytimittäin + Lämpötilat + Muisti + Näytönohjaimen muisti + Swap-tila + Akun varaus + Virrankulutus + Verkko + Tarkkuus + Proton-versio + Istunnon kesto + Kello + Lämpötilat + Yksikkö + Varoitusvärit + Lämpötilat muuttuvat meripihkanvärisiksi ja sitten punaisiksi, kun ne lähestyvät rajaa. + Pois + Automaattinen + Manuaalinen + CPU:n punainen raja + GPU:n punainen raja + Akun punainen raja + Lisää + HUD-diagnostiikka + Tallentaa raportin kaikista HUD:n lukemista antureista kansioon Downloads/DroidDeck. + Tallenna + Tallennettu: %1$s + HUD-raporttia ei voitu tallentaa. + Palauta HUD-asetukset + Palauta + FusionHUD, tekijä The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0). Skaalaustila Skaalauksen terävyys Näyttötehosteet diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 6799322814..19b01d1132 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -611,6 +611,65 @@ Ambre Violet Opacité + La fréquence d\'images, les temps d\'image et les mesures proviennent des mêmes sources que la superposition de performances de Steam. + Taille + Toucher le HUD change aussi sa taille. + Complet + Tuiles + Pilule + Minimal + Méga + Verrouiller la position + Faites glisser le HUD pour le déplacer ; un appui long le verrouille ou le déverrouille. + Apparence + Taille à l\'écran + Douce + Moyenne + Vive + Contour + Couleur du contour + Gris + Couleur du thème + Mesures + Graphique des temps d\'image + Fréquence d\'images avec une décimale + 0.01% les plus bas + Moteur graphique + Nom du GPU + Charge du GPU + Température du GPU + Charge du CPU + CPU par cœur + Températures + Mémoire + Mémoire graphique + Mémoire d\'échange + Niveau de batterie + Consommation + Réseau + Résolution + Version de Proton + Durée de session + Horloge + Températures + Unité + Couleurs d\'alerte + Les températures passent à l\'ambre, puis au rouge, à l\'approche de la limite. + Désactivé + Automatique + Manuel + CPU en rouge à + GPU en rouge à + Batterie en rouge à + Plus + Diagnostic du HUD + Enregistre dans Downloads/DroidDeck un rapport sur chaque capteur lu par le HUD. + Enregistrer + Enregistré dans %1$s + Impossible d\'enregistrer le rapport du HUD. + Réinitialiser les paramètres du HUD + Réinitialiser + FusionHUD par The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0). Mode de mise à l\'échelle Netteté de la mise à l\'échelle Effets d\'écran diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index b5397925f1..3cc6b66f47 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -607,6 +607,65 @@ एम्बर वायलेट ओपैसिटी + फ़्रेम दर, फ़्रेम टाइम और रीडिंग उन्हीं स्रोतों से आती हैं जिनसे Steam का परफ़ॉर्मेंस ओवरले उन्हें लेता है। + आकार + HUD पर टैप करने से भी उसका आकार बदलता है। + फ़ुल + टाइल्स + पिल + मिनिमल + मेगा + जगह पर लॉक करें + HUD को खिसकाने के लिए उसे ड्रैग करें; देर तक दबाने से वह लॉक या अनलॉक होता है। + लुक + स्क्रीन पर आकार + हल्का + मध्यम + चटख + आउटलाइन + आउटलाइन का रंग + ग्रे + थीम का रंग + रीडिंग + फ़्रेम टाइम ग्राफ़ + दशमलव सहित फ़्रेम दर + 0.01% लो + ग्राफ़िक्स इंजन + GPU का नाम + GPU लोड + GPU तापमान + CPU लोड + प्रति कोर CPU + तापमान + मेमोरी + ग्राफ़िक्स मेमोरी + स्वैप + बैटरी लेवल + पावर खपत + नेटवर्क + रिज़ॉल्यूशन + Proton वर्शन + सेशन का समय + घड़ी + तापमान + इकाई + चेतावनी रंग + सीमा के पास पहुंचने पर तापमान पहले एम्बर, फिर लाल हो जाता है। + बंद + ऑटोमैटिक + मैनुअल + CPU लाल सीमा + GPU लाल सीमा + बैटरी लाल सीमा + ज़्यादा + HUD डायग्नोस्टिक्स + HUD जिन सेंसर को पढ़ता है, उन सबकी रिपोर्ट Downloads/DroidDeck में सेव करता है। + सेव करें + %1$s में सहेजा गया + HUD रिपोर्ट सेव नहीं हो सकी। + HUD सेटिंग रीसेट करें + रीसेट करें + The412Banner का FusionHUD, github.com/The412Banner/FusionHUD (GPL-3.0)। स्केलिंग मोड स्केलिंग शार्पनेस स्क्रीन इफ़ेक्ट diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 82e9332a04..ef165eff42 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -607,6 +607,65 @@ Borostyán Lila Átlátszatlanság + A képkockasebesség, a képkockaidők és a mért értékek ugyanazokból a forrásokból származnak, mint a Steam teljesítményátfedése. + Méret + A HUD-ra koppintva is változik a mérete. + Teljes + Csempék + Kapszula + Minimális + Mega + Rögzítés a helyén + Húzd a HUD-ot az áthelyezéshez; hosszú nyomással rögzítheted vagy feloldhatod. + Megjelenés + Méret a képernyőn + Lágy + Közepes + Élénk + Körvonal + Körvonal színe + Szürke + Témaszín + Mért értékek + Képkockaidő-grafikon + Képkockasebesség tizedesjeggyel + 0.01% legalacsonyabb + Grafikus motor + GPU neve + GPU-terhelés + GPU-hőmérséklet + CPU-terhelés + CPU magonként + Hőmérsékletek + Memória + Grafikus memória + Swap-memória + Akkuszint + Energiafelvétel + Hálózat + Felbontás + Proton-verzió + Munkamenet ideje + Óra + Hőmérsékletek + Mértékegység + Figyelmeztető színek + A hőmérsékletek a határhoz közeledve előbb borostyánszínűre, majd pirosra váltanak. + Ki + Automatikus + Manuális + CPU piros határa + GPU piros határa + Akku piros határa + Több + HUD-diagnosztika + Jelentést ment a HUD által olvasott összes érzékelőről a Downloads/DroidDeck mappába. + Mentés + Mentve: %1$s + Nem sikerült menteni a HUD-jelentést. + HUD-beállítások visszaállítása + Visszaállítás + FusionHUD, készítette: The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0). Méretezési mód Méretezési élesség Képernyőeffektek diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index a677a94ece..de10dd0746 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -605,6 +605,65 @@ Ambar Ungu Opasitas + Laju bingkai, waktu bingkai, dan pembacaan berasal dari sumber yang sama dengan overlay performa Steam. + Ukuran + Mengetuk HUD juga mengubah ukurannya. + Penuh + Ubin + Pil + Minimal + Mega + Kunci posisi + Seret HUD untuk memindahkannya; tekan lama untuk mengunci atau membuka kuncinya. + Tampilan + Ukuran di layar + Lembut + Sedang + Cerah + Garis tepi + Warna garis tepi + Abu-abu + Warna tema + Pembacaan + Grafik waktu bingkai + Laju bingkai dengan desimal + 0.01% terendah + Mesin grafis + Nama GPU + Beban GPU + Suhu GPU + Beban CPU + CPU per inti + Suhu + Memori + Memori grafis + Memori swap + Level baterai + Konsumsi daya + Jaringan + Resolusi + Versi Proton + Durasi sesi + Jam + Suhu + Satuan + Warna peringatan + Suhu berubah menjadi ambar, lalu merah, saat mendekati batas. + Nonaktif + Otomatis + Manual + CPU merah pada + GPU merah pada + Baterai merah pada + Lainnya + Diagnostik HUD + Menyimpan laporan semua sensor yang dibaca HUD ke Downloads/DroidDeck. + Simpan + Disimpan di %1$s + Tidak dapat menyimpan laporan HUD. + Setel ulang setelan HUD + Setel ulang + FusionHUD oleh The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0). Mode penskalaan Ketajaman penskalaan Efek layar diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 287d96bac7..1c686719ae 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -609,6 +609,65 @@ Ambra Viola Opacità + Frequenza fotogrammi, tempi dei fotogrammi e valori provengono dalle stesse fonti dell\'overlay prestazioni di Steam. + Dimensione + Toccare l\'HUD ne cambia anche la dimensione. + Completo + Riquadri + Pillola + Minimo + Mega + Blocca in posizione + Trascina l\'HUD per spostarlo; una pressione prolungata lo blocca o lo sblocca. + Aspetto + Dimensione sullo schermo + Tenue + Medio + Vivace + Contorno + Colore contorno + Grigio + Colore del tema + Valori + Grafico tempi fotogramma + Frequenza fotogrammi con decimale + 0.01% più basso + Motore grafico + Nome GPU + Carico GPU + Temperatura GPU + Carico CPU + CPU per core + Temperature + Memoria + Memoria grafica + Memoria swap + Livello batteria + Consumo energetico + Rete + Risoluzione + Versione Proton + Durata sessione + Orologio + Temperature + Unità + Colori di avviso + Le temperature diventano ambra, poi rosse, man mano che si avvicinano al limite. + Disattivato + Automatico + Manuale + CPU in rosso da + GPU in rosso da + Batteria in rosso da + Altro + Diagnostica HUD + Salva in Downloads/DroidDeck un rapporto su ogni sensore letto dall\'HUD. + Salva + Salvato in %1$s + Impossibile salvare il rapporto dell\'HUD. + Ripristina impostazioni HUD + Ripristina + FusionHUD di The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0). Modalità di ridimensionamento Nitidezza del ridimensionamento Effetti schermo diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index c81f41605d..c087ca3346 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -607,6 +607,65 @@ アンバー バイオレット 不透明度 + フレームレート、フレームタイム、各測定値は、Steamのパフォーマンスオーバーレイと同じソースから取得しています。 + サイズ + HUDをタップしてもサイズを切り替えられます。 + フル + タイル + カプセル + ミニマル + メガ + 位置を固定 + HUDはドラッグで移動できます。長押しで固定または解除します。 + 外観 + 画面上のサイズ + ソフト + 標準 + ビビッド + アウトライン + アウトラインの色 + グレー + テーマカラー + 表示項目 + フレームタイムグラフ + フレームレートの小数表示 + 0.01%最低値 + グラフィックスエンジン + GPU名 + GPU使用率 + GPU温度 + CPU使用率 + コアごとのCPU + 温度 + メモリ + グラフィックスメモリ + スワップ + バッテリー残量 + 消費電力 + ネットワーク + 解像度 + Protonバージョン + セッション時間 + 時計 + 温度 + 単位 + 警告色 + 温度が上限に近づくと、アンバー、次に赤で表示されます。 + オフ + 自動 + 手動 + CPUを赤にする温度 + GPUを赤にする温度 + バッテリーを赤にする温度 + その他 + HUD診断 + HUDが読み取るすべてのセンサーのレポートをDownloads/DroidDeckに保存します。 + 保存 + %1$s に保存しました + HUDレポートを保存できませんでした。 + HUD設定をリセット + リセット + FusionHUD 作者:The412Banner、github.com/The412Banner/FusionHUD (GPL-3.0)。 スケーリングモード スケーリングのシャープネス 画面エフェクト diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index aef296fabf..89d20eef5c 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -607,6 +607,65 @@ 호박색 보라색 불투명도 + 프레임 속도, 프레임 타임, 측정값은 Steam 성능 오버레이와 같은 소스에서 가져옵니다. + 크기 + HUD를 탭해도 크기가 바뀝니다. + 전체 + 타일 + 캡슐 + 미니멀 + 메가 + 위치 고정 + HUD를 드래그하여 이동하고, 길게 눌러 고정하거나 해제합니다. + 외관 + 화면상 크기 + 은은함 + 보통 + 선명함 + 외곽선 + 외곽선 색상 + 회색 + 테마 색상 + 측정값 + 프레임 타임 그래프 + 소수점 프레임 속도 + 0.01% 최저 + 그래픽 엔진 + GPU 이름 + GPU 사용률 + GPU 온도 + CPU 사용률 + 코어별 CPU + 온도 + 메모리 + 그래픽 메모리 + 스왑 + 배터리 잔량 + 소비 전력 + 네트워크 + 해상도 + Proton 버전 + 세션 시간 + 시계 + 온도 + 단위 + 경고 색상 + 온도가 한도에 가까워지면 호박색, 그다음 빨간색으로 바뀝니다. + 끔 + 자동 + 수동 + CPU 빨간색 기준 + GPU 빨간색 기준 + 배터리 빨간색 기준 + 기타 + HUD 진단 + HUD가 읽는 모든 센서의 보고서를 Downloads/DroidDeck에 저장합니다. + 저장 + %1$s에 저장됨 + HUD 보고서를 저장할 수 없습니다. + HUD 설정 초기화 + 초기화 + FusionHUD 제작: The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0). 스케일링 모드 스케일링 선명도 화면 효과 diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index 3d99b37c4b..545961c877 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -605,6 +605,65 @@ Ambar Ungu Kelegapan + Kadar bingkai, masa bingkai dan bacaan datang daripada sumber yang sama dengan tindanan prestasi Steam. + Saiz + Mengetik HUD juga menukar saiznya. + Penuh + Jubin + Pil + Minimal + Mega + Kunci di tempat + Seret HUD untuk mengalihkannya; tekan lama untuk mengunci atau membuka kuncinya. + Rupa + Saiz pada skrin + Lembut + Sederhana + Terang + Garis luar + Warna garis luar + Kelabu + Warna tema + Bacaan + Graf masa bingkai + Kadar bingkai dengan perpuluhan + 0.01% terendah + Enjin grafik + Nama GPU + Beban GPU + Suhu GPU + Beban CPU + CPU setiap teras + Suhu + Memori + Memori grafik + Memori swap + Tahap bateri + Penggunaan kuasa + Rangkaian + Resolusi + Versi Proton + Tempoh sesi + Jam + Suhu + Unit + Warna amaran + Suhu bertukar ambar, kemudian merah, apabila menghampiri had. + Mati + Automatik + Manual + CPU merah pada + GPU merah pada + Bateri merah pada + Lagi + Diagnostik HUD + Menyimpan laporan setiap sensor yang dibaca HUD ke Downloads/DroidDeck. + Simpan + Disimpan di %1$s + Tidak dapat menyimpan laporan HUD. + Set semula tetapan HUD + Set semula + FusionHUD oleh The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0). Mod penskalaan Ketajaman penskalaan Kesan skrin diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index 4030458fd5..5816e96e64 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -607,6 +607,65 @@ Amber Fiolett Opasitet + Bildefrekvens, bildetider og måleverdier kommer fra de samme kildene som Steams ytelsesoverlegg. + Størrelse + Et trykk på HUD-en endrer også størrelsen. + Full + Fliser + Pille + Minimal + Mega + Lås på plass + Dra HUD-en for å flytte den; et langt trykk låser eller låser den opp. + Utseende + Størrelse på skjermen + Myk + Middels + Kraftig + Kontur + Konturfarge + Grå + Temafarge + Måleverdier + Bildetidsgraf + Bildefrekvens med desimal + 0.01% laveste + Grafikkmotor + GPU-navn + GPU-belastning + GPU-temperatur + CPU-belastning + CPU per kjerne + Temperaturer + Minne + Grafikkminne + Swap-minne + Batterinivå + Strømforbruk + Nettverk + Oppløsning + Proton-versjon + Sesjonstid + Klokke + Temperaturer + Enhet + Varselfarger + Temperaturer blir ravgule og så røde når de nærmer seg grensen. + Av + Automatisk + Manuell + CPU rød ved + GPU rød ved + Batteri rødt ved + Mer + HUD-diagnostikk + Lagrer en rapport over alle sensorer HUD-en leser, i Downloads/DroidDeck. + Lagre + Lagret i %1$s + Kunne ikke lagre HUD-rapporten. + Tilbakestill HUD-innstillinger + Tilbakestill + FusionHUD av The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0). Skaleringsmodus Skaleringsskarphet Skjermeffekter diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 541cf6c2ed..83983288a1 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -607,6 +607,65 @@ Amber Violet Transparantie + Beeldsnelheid, frametijden en meetwaarden komen uit dezelfde bronnen als de prestatie-overlay van Steam. + Grootte + Tikken op de HUD verandert ook de grootte. + Volledig + Tegels + Pil + Minimaal + Mega + Vastzetten + Sleep de HUD om hem te verplaatsen; lang drukken zet hem vast of los. + Weergave + Grootte op scherm + Zacht + Gemiddeld + Fel + Contour + Contourkleur + Grijs + Themakleur + Meetwaarden + Frametijdgrafiek + Beeldsnelheid met decimaal + 0.01% laagste + Grafische engine + GPU-naam + GPU-belasting + GPU-temperatuur + CPU-belasting + CPU per kern + Temperaturen + Geheugen + Grafisch geheugen + Swapgeheugen + Accuniveau + Stroomverbruik + Netwerk + Resolutie + Proton-versie + Sessieduur + Klok + Temperaturen + Eenheid + Waarschuwingskleuren + Temperaturen worden eerst amber en dan rood naarmate ze de limiet naderen. + Uit + Automatisch + Handmatig + CPU rood vanaf + GPU rood vanaf + Accu rood vanaf + Meer + HUD-diagnose + Slaat een rapport van elke sensor die de HUD uitleest op in Downloads/DroidDeck. + Opslaan + Opgeslagen in %1$s + Kan het HUD-rapport niet opslaan. + HUD-instellingen resetten + Resetten + FusionHUD door The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0). Schaalmodus Schaalscherpte Schermeffecten diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index a751416aa3..a0183446a1 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -611,6 +611,65 @@ Bursztynowy Fioletowy Przezroczystość + Liczba klatek, czasy klatek i odczyty pochodzą z tych samych źródeł co nakładka wydajności Steam. + Rozmiar + Dotknięcie HUD również zmienia jego rozmiar. + Pełny + Kafelki + Pigułka + Minimalny + Mega + Zablokuj w miejscu + Przeciągnij HUD, aby go przesunąć; długie naciśnięcie blokuje go lub odblokowuje. + Wygląd + Rozmiar na ekranie + Stonowany + Średni + Żywy + Obrys + Kolor obrysu + Szary + Kolor motywu + Odczyty + Wykres czasu klatek + Liczba klatek z miejscem po przecinku + 0.01% najniższych + Silnik graficzny + Nazwa GPU + Obciążenie GPU + Temperatura GPU + Obciążenie CPU + CPU na rdzeń + Temperatury + Pamięć + Pamięć graficzna + Pamięć wymiany + Poziom baterii + Pobór mocy + Sieć + Rozdzielczość + Wersja Protona + Czas sesji + Zegar + Temperatury + Jednostka + Kolory ostrzeżeń + Temperatury zmieniają kolor na bursztynowy, a potem czerwony, gdy zbliżają się do limitu. + Wył. + Automatycznie + Ręcznie + CPU na czerwono od + GPU na czerwono od + Bateria na czerwono od + Więcej + Diagnostyka HUD + Zapisuje w Downloads/DroidDeck raport ze wszystkich czujników odczytywanych przez HUD. + Zapisz + Zapisano w %1$s + Nie udało się zapisać raportu HUD. + Zresetuj ustawienia HUD + Resetuj + FusionHUD autorstwa The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0). Tryb skalowania Ostrość skalowania Efekty ekranowe diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 2499fee187..bc5860412f 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -609,6 +609,65 @@ Âmbar Violeta Opacidade + A taxa de fotogramas, os tempos de fotograma e as leituras vêm das mesmas fontes que a sobreposição de desempenho da Steam. + Tamanho + Tocar no HUD também altera o tamanho. + Completo + Mosaicos + Pílula + Mínimo + Mega + Bloquear posição + Arraste o HUD para o mover; um toque longo bloqueia-o ou desbloqueia-o. + Aspeto + Tamanho no ecrã + Suave + Média + Viva + Contorno + Cor do contorno + Cinzento + Cor do tema + Leituras + Gráfico de tempo de fotograma + Taxa de fotogramas com decimal + 0.01% mais baixo + Motor gráfico + Nome da GPU + Utilização da GPU + Temperatura da GPU + Utilização da CPU + CPU por núcleo + Temperaturas + Memória + Memória gráfica + Memória swap + Nível da bateria + Consumo de energia + Rede + Resolução + Versão do Proton + Tempo de sessão + Relógio + Temperaturas + Unidade + Cores de aviso + As temperaturas ficam âmbar e depois vermelhas à medida que se aproximam do limite. + Desativado + Automático + Manual + CPU a vermelho a partir de + GPU a vermelho a partir de + Bateria a vermelho a partir de + Mais + Diagnóstico do HUD + Guarda em Downloads/DroidDeck um relatório de cada sensor que o HUD lê. + Guardar + Guardado em %1$s + Não foi possível guardar o relatório do HUD. + Repor definições do HUD + Repor + FusionHUD por The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0). Modo de escala Nitidez da escala Efeitos de ecrã diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index c29b9923b1..a844a47e1a 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -609,6 +609,65 @@ Âmbar Violeta Opacidade + Taxa de quadros, tempos de quadro e leituras vêm das mesmas fontes que a sobreposição de desempenho da Steam. + Tamanho + Tocar no HUD também altera o tamanho. + Completo + Blocos + Pílula + Mínimo + Mega + Travar posição + Arraste o HUD para movê-lo; um toque longo o trava ou destrava. + Aparência + Tamanho na tela + Suave + Média + Viva + Contorno + Cor do contorno + Cinza + Cor do tema + Leituras + Gráfico de tempo de quadro + Taxa de quadros com decimal + 0.01% mais baixo + Motor gráfico + Nome da GPU + Uso da GPU + Temperatura da GPU + Uso da CPU + CPU por núcleo + Temperaturas + Memória + Memória gráfica + Memória swap + Nível da bateria + Consumo de energia + Rede + Resolução + Versão do Proton + Tempo de sessão + Relógio + Temperaturas + Unidade + Cores de alerta + As temperaturas ficam âmbar e depois vermelhas ao se aproximarem do limite. + Desativado + Automático + Manual + CPU em vermelho a partir de + GPU em vermelho a partir de + Bateria em vermelho a partir de + Mais + Diagnóstico do HUD + Salva em Downloads/DroidDeck um relatório de cada sensor que o HUD lê. + Salvar + Salvo em %1$s + Não foi possível salvar o relatório do HUD. + Redefinir configurações do HUD + Redefinir + FusionHUD por The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0). Modo de escala Nitidez da escala Efeitos de tela diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index 432b10a23a..8b1d43d4ac 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -609,6 +609,65 @@ Chihlimbariu Violet Opacitate + Rata de cadre, timpii de cadru și valorile citite provin din aceleași surse ca suprapunerea de performanță Steam. + Dimensiune + Atingerea HUD-ului îi schimbă și dimensiunea. + Complet + Plăci + Pastilă + Minimal + Mega + Blochează pe loc + Trage HUD-ul pentru a-l muta; o apăsare lungă îl blochează sau îl deblochează. + Aspect + Dimensiune pe ecran + Discretă + Medie + Vie + Contur + Culoare contur + Gri + Culoarea temei + Valori + Grafic timp de cadru + Rată de cadre cu zecimală + 0.01% cele mai mici + Motor grafic + Nume GPU + Încărcare GPU + Temperatură GPU + Încărcare CPU + CPU pe nucleu + Temperaturi + Memorie + Memorie grafică + Memorie swap + Nivel baterie + Consum de energie + Rețea + Rezoluție + Versiune Proton + Durata sesiunii + Ceas + Temperaturi + Unitate + Culori de avertizare + Temperaturile devin chihlimbarii, apoi roșii, pe măsură ce se apropie de limită. + Dezactivat + Automat + Manual + CPU roșu de la + GPU roșu de la + Baterie roșie de la + Mai mult + Diagnosticare HUD + Salvează în Downloads/DroidDeck un raport despre fiecare senzor citit de HUD. + Salvează + Salvat în %1$s + Raportul HUD nu a putut fi salvat. + Resetează setările HUD + Resetează + FusionHUD de The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0). Mod de scalare Claritatea scalării Efecte de ecran diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 22984a66ae..eadcd1bfe6 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -613,6 +613,65 @@ Янтарный Фиолетовый Непрозрачность + Частота кадров, время кадров и показания берутся из тех же источников, что и оверлей производительности Steam. + Размер + Касание HUD тоже меняет его размер. + Полный + Плитки + Капсула + Минимальный + Мега + Закрепить на месте + Перетащите HUD, чтобы переместить его; долгое нажатие закрепляет или открепляет его. + Внешний вид + Размер на экране + Мягкий + Средний + Яркий + Контур + Цвет контура + Серый + Цвет темы + Показатели + График времени кадров + Частота кадров с десятыми + 0.01% минимальных + Графический движок + Название GPU + Загрузка GPU + Температура GPU + Загрузка CPU + CPU по ядрам + Температуры + Память + Видеопамять + Подкачка + Заряд батареи + Потребляемая мощность + Сеть + Разрешение + Версия Proton + Время сессии + Часы + Температуры + Единицы + Цвета предупреждений + Температуры становятся янтарными, затем красными по мере приближения к пределу. + Выкл. + Автоматически + Вручную + CPU: красный от + GPU: красный от + Батарея: красный от + Еще + Диагностика HUD + Сохраняет в Downloads/DroidDeck отчет по всем датчикам, которые считывает HUD. + Сохранить + Сохранено: %1$s + Не удалось сохранить отчет HUD. + Сбросить настройки HUD + Сбросить + FusionHUD от The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0). Режим масштабирования Резкость масштабирования Экранные эффекты diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 4a81483b68..c740bfc886 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -607,6 +607,65 @@ Amber Lila Opacitet + Bildfrekvens, bildtider och mätvärden kommer från samma källor som Steams prestandaöverlägg. + Storlek + Ett tryck på HUD:en ändrar också dess storlek. + Full + Rutor + Piller + Minimal + Mega + Lås på plats + Dra HUD:en för att flytta den; ett långt tryck låser eller låser upp den. + Utseende + Storlek på skärmen + Mjuk + Mellan + Livfull + Kontur + Konturfärg + Grå + Temafärg + Mätvärden + Bildtidsgraf + Bildfrekvens med decimal + 0.01% lägsta + Grafikmotor + GPU-namn + GPU-belastning + GPU-temperatur + CPU-belastning + CPU per kärna + Temperaturer + Minne + Grafikminne + Växlingsminne + Batterinivå + Strömförbrukning + Nätverk + Upplösning + Proton-version + Sessionstid + Klocka + Temperaturer + Enhet + Varningsfärger + Temperaturer blir bärnstensfärgade och sedan röda när de närmar sig gränsen. + Av + Automatiskt + Manuell + CPU röd vid + GPU röd vid + Batteri rött vid + Mer + HUD-diagnostik + Sparar en rapport över alla sensorer som HUD:en läser i Downloads/DroidDeck. + Spara + Sparad i %1$s + Det gick inte att spara HUD-rapporten. + Återställ HUD-inställningar + Återställ + FusionHUD av The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0). Skalningsläge Skalningsskärpa Skärmeffekter diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 14b9f97e7b..e319fd5ac2 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -605,6 +605,65 @@ อำพัน ม่วง ความโปร่งใส + อัตราเฟรม เวลาเฟรม และค่าที่อ่านได้มาจากแหล่งเดียวกับโอเวอร์เลย์ประสิทธิภาพของ Steam + ขนาด + การแตะ HUD จะเปลี่ยนขนาดด้วย + เต็ม + ไทล์ + แคปซูล + มินิมอล + เมกะ + ล็อกตำแหน่ง + ลาก HUD เพื่อย้าย กดค้างเพื่อล็อกหรือปลดล็อก + รูปลักษณ์ + ขนาดบนหน้าจอ + อ่อน + ปานกลาง + สด + เส้นขอบ + สีเส้นขอบ + เทา + สีธีม + ค่าที่แสดง + กราฟเวลาเฟรม + อัตราเฟรมแบบทศนิยม + 0.01% ต่ำสุด + เอนจินกราฟิก + ชื่อ GPU + โหลด GPU + อุณหภูมิ GPU + โหลด CPU + CPU รายคอร์ + อุณหภูมิ + หน่วยความจำ + หน่วยความจำกราฟิก + พื้นที่สว็อป + ระดับแบตเตอรี่ + การใช้พลังงาน + เครือข่าย + ความละเอียด + เวอร์ชัน Proton + เวลาเซสชัน + นาฬิกา + อุณหภูมิ + หน่วย + สีเตือน + อุณหภูมิจะเปลี่ยนเป็นสีอำพันแล้วเป็นสีแดงเมื่อใกล้ถึงขีดจำกัด + ปิด + อัตโนมัติ + กำหนดเอง + CPU แดงที่ + GPU แดงที่ + แบตเตอรี่แดงที่ + เพิ่มเติม + การวินิจฉัย HUD + บันทึกรายงานของเซนเซอร์ทุกตัวที่ HUD อ่านไปที่ Downloads/DroidDeck + บันทึก + บันทึกไปที่ %1$s แล้ว + บันทึกรายงาน HUD ไม่ได้ + รีเซ็ตการตั้งค่า HUD + รีเซ็ต + FusionHUD โดย The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0) โหมดการปรับขนาด ความคมชัดของการปรับขนาด เอฟเฟกต์หน้าจอ diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 2b2a99bf7c..307ad12e44 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -607,6 +607,65 @@ Kehribar Mor Opaklık + Kare hızı, kare süreleri ve ölçümler, Steam\'in performans katmanıyla aynı kaynaklardan gelir. + Boyut + HUD\'a dokunmak da boyutunu değiştirir. + Tam + Kutucuklar + Hap + Minimal + Mega + Yerinde kilitle + Taşımak için HUD\'u sürükleyin; uzun basmak onu kilitler veya kilidini açar. + Görünüm + Ekrandaki boyut + Yumuşak + Orta + Canlı + Dış hat + Dış hat rengi + Gri + Tema rengi + Ölçümler + Kare süresi grafiği + Ondalıklı kare hızı + 0.01% en düşük + Grafik motoru + GPU adı + GPU yükü + GPU sıcaklığı + CPU yükü + Çekirdek başına CPU + Sıcaklıklar + Bellek + Grafik belleği + Takas alanı + Pil seviyesi + Güç tüketimi + Ağ + Çözünürlük + Proton sürümü + Oturum süresi + Saat + Sıcaklıklar + Birim + Uyarı renkleri + Sıcaklıklar sınıra yaklaştıkça önce kehribar, sonra kırmızı olur. + Kapalı + Otomatik + Manuel + CPU kırmızı eşiği + GPU kırmızı eşiği + Pil kırmızı eşiği + Daha fazla + HUD tanılaması + HUD\'un okuduğu her sensörün raporunu Downloads/DroidDeck klasörüne kaydeder. + Kaydet + %1$s konumuna kaydedildi + HUD raporu kaydedilemedi. + HUD ayarlarını sıfırla + Sıfırla + FusionHUD, yapımcı: The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0). Ölçekleme modu Ölçekleme keskinliği Ekran efektleri diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 1890077a99..966ad55fc4 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -611,6 +611,65 @@ Бурштиновий Фіолетовий Непрозорість + Частота кадрів, час кадрів і показники беруться з тих самих джерел, що й оверлей продуктивності Steam. + Розмір + Дотик до HUD також змінює його розмір. + Повний + Плитки + Капсула + Мінімальний + Мега + Закріпити на місці + Перетягніть HUD, щоб перемістити його; довге натискання закріплює або відкріплює його. + Вигляд + Розмір на екрані + М\'який + Середній + Яскравий + Контур + Колір контуру + Сірий + Колір теми + Показники + Графік часу кадрів + Частота кадрів із десятими + 0.01% мінімальних + Графічний рушій + Назва GPU + Навантаження GPU + Температура GPU + Навантаження CPU + CPU за ядрами + Температури + Пам\'ять + Відеопам\'ять + Підкачка + Заряд батареї + Споживана потужність + Мережа + Роздільна здатність + Версія Proton + Час сеансу + Годинник + Температури + Одиниці + Кольори попередження + Температури стають бурштиновими, а потім червоними, коли наближаються до межі. + Вимк. + Автоматично + Вручну + CPU: червоний від + GPU: червоний від + Батарея: червоний від + Більше + Діагностика HUD + Зберігає в Downloads/DroidDeck звіт про всі датчики, які зчитує HUD. + Зберегти + Збережено: %1$s + Не вдалося зберегти звіт HUD. + Скинути налаштування HUD + Скинути + FusionHUD від The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0). Режим масштабування Чіткість масштабування Ефекти екрана diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 54692b076e..d715523311 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -605,6 +605,65 @@ Hổ phách Tím Độ mờ + Tốc độ khung hình, thời gian khung hình và các chỉ số lấy từ cùng nguồn với lớp phủ hiệu năng của Steam. + Kích thước + Chạm vào HUD cũng thay đổi kích thước của nó. + Đầy đủ + Ô + Dạng viên + Tối giản + Mega + Khóa vị trí + Kéo HUD để di chuyển; nhấn giữ để khóa hoặc mở khóa. + Giao diện + Kích thước trên màn hình + Dịu + Vừa + Rực rỡ + Viền + Màu viền + Xám + Màu giao diện + Chỉ số + Biểu đồ thời gian khung hình + Tốc độ khung hình có số thập phân + 0.01% thấp nhất + Engine đồ họa + Tên GPU + Tải GPU + Nhiệt độ GPU + Tải CPU + CPU theo từng lõi + Nhiệt độ + Bộ nhớ + Bộ nhớ đồ họa + Bộ nhớ swap + Mức pin + Công suất tiêu thụ + Mạng + Độ phân giải + Phiên bản Proton + Thời gian phiên + Đồng hồ + Nhiệt độ + Đơn vị + Màu cảnh báo + Nhiệt độ chuyển sang màu hổ phách, rồi đỏ khi gần đến giới hạn. + Tắt + Tự động + Thủ công + CPU đỏ từ + GPU đỏ từ + Pin đỏ từ + Thêm + Chẩn đoán HUD + Lưu báo cáo về mọi cảm biến mà HUD đọc vào Downloads/DroidDeck. + Lưu + Đã lưu vào %1$s + Không thể lưu báo cáo HUD. + Đặt lại thiết lập HUD + Đặt lại + FusionHUD của The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0). Chế độ chia tỷ lệ Độ sắc nét khi chia tỷ lệ Hiệu ứng màn hình diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 2b312597cb..53db0abde6 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -607,6 +607,65 @@ 琥珀 紫罗兰 不透明度 + 帧率、帧时间和各项读数与 Steam 性能叠加层来自相同的数据源。 + 大小 + 轻点 HUD 也可以切换大小。 + 完整 + 磁贴 + 胶囊 + 极简 + 超大 + 锁定位置 + 拖动 HUD 可移动位置;长按可锁定或解锁。 + 外观 + 屏幕显示大小 + 柔和 + 适中 + 鲜艳 + 描边 + 描边颜色 + 灰色 + 主题色 + 读数 + 帧时间图表 + 帧率显示小数 + 0.01% 最低帧 + 图形引擎 + GPU 名称 + GPU 负载 + GPU 温度 + CPU 负载 + CPU 各核心 + 温度 + 内存 + 显存 + 交换空间 + 电池电量 + 功耗 + 网络 + 分辨率 + Proton 版本 + 会话时长 + 时钟 + 温度 + 单位 + 警告颜色 + 温度接近上限时会先变为琥珀色,再变为红色。 + 关 + 自动 + 手动 + CPU 变红温度 + GPU 变红温度 + 电池变红温度 + 更多 + HUD 诊断 + 将 HUD 读取的所有传感器报告保存到 Downloads/DroidDeck。 + 保存 + 已保存到 %1$s + 无法保存 HUD 报告。 + 重置 HUD 设置 + 重置 + FusionHUD,作者 The412Banner,github.com/The412Banner/FusionHUD (GPL-3.0)。 缩放模式 缩放锐度 屏幕效果 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 632221ac7e..aa0bdffc88 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -607,6 +607,65 @@ 琥珀色 紫羅蘭 不透明度 + 幀率、幀時間和各項讀數與 Steam 效能疊加層來自相同的來源。 + 大小 + 輕按 HUD 亦可切換大小。 + 完整 + 方塊 + 膠囊 + 極簡 + 超大 + 鎖定位置 + 拖曳 HUD 可移動位置;長按可鎖定或解鎖。 + 外觀 + 螢幕顯示大小 + 柔和 + 適中 + 鮮豔 + 描邊 + 描邊顏色 + 灰色 + 主題色 + 讀數 + 幀時間圖表 + 幀率顯示小數 + 0.01% 最低幀 + 圖形引擎 + GPU 名稱 + GPU 負載 + GPU 溫度 + CPU 負載 + CPU 各核心 + 溫度 + 記憶體 + 顯示記憶體 + 交換空間 + 電池電量 + 功耗 + 網絡 + 解像度 + Proton 版本 + 會話時長 + 時鐘 + 溫度 + 單位 + 警告顏色 + 溫度接近上限時會先變成琥珀色,再變成紅色。 + 關閉 + 自動 + 手動 + CPU 變紅溫度 + GPU 變紅溫度 + 電池變紅溫度 + 更多 + HUD 診斷 + 將 HUD 讀取的所有感應器報告儲存到 Downloads/DroidDeck。 + 儲存 + 已儲存到 %1$s + 無法儲存 HUD 報告。 + 重設 HUD 設定 + 重設 + FusionHUD,作者 The412Banner,github.com/The412Banner/FusionHUD (GPL-3.0)。 縮放模式 縮放銳利度 畫面效果 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 018e3e78bf..63213ea6e9 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -607,6 +607,65 @@ 琥珀 紫羅蘭 不透明度 + 幀率、幀時間和各項讀數與 Steam 效能疊加層來自相同的來源。 + 大小 + 輕觸 HUD 也可以切換大小。 + 完整 + 圖塊 + 膠囊 + 極簡 + 超大 + 鎖定位置 + 拖曳 HUD 可移動位置;長按可鎖定或解鎖。 + 外觀 + 螢幕顯示大小 + 柔和 + 適中 + 鮮豔 + 描邊 + 描邊顏色 + 灰色 + 主題色 + 讀數 + 幀時間圖表 + 幀率顯示小數 + 0.01% 最低幀 + 圖形引擎 + GPU 名稱 + GPU 負載 + GPU 溫度 + CPU 負載 + CPU 各核心 + 溫度 + 記憶體 + 顯示記憶體 + 交換空間 + 電池電量 + 功耗 + 網路 + 解析度 + Proton 版本 + 工作階段時間 + 時鐘 + 溫度 + 單位 + 警告顏色 + 溫度接近上限時會先變成琥珀色,再變成紅色。 + 關閉 + 自動 + 手動 + CPU 變紅溫度 + GPU 變紅溫度 + 電池變紅溫度 + 更多 + HUD 診斷 + 將 HUD 讀取的所有感測器報告儲存到 Downloads/DroidDeck。 + 儲存 + 已儲存到 %1$s + 無法儲存 HUD 報告。 + 重設 HUD 設定 + 重設 + FusionHUD,作者 The412Banner,github.com/The412Banner/FusionHUD (GPL-3.0)。 縮放模式 縮放銳利度 畫面效果 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index fd3550e646..ad87e966de 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -666,6 +666,65 @@ Amber Violet Opacity + Frame rate, frame times and readings come from the same sources as Steam\'s performance overlay. + Size + Tapping the HUD also changes its size. + Full + Tiles + Pill + Minimal + Mega + Lock in place + Drag the HUD to move it; a long press locks or unlocks it. + Look + Size on screen + Soft + Medium + Vivid + Outline + Outline color + Gray + Theme color + Readings + Frame time graph + Frame rate with a decimal + 0.01% low + Graphics engine + GPU name + GPU load + GPU temperature + CPU load + CPU per core + Temperatures + Memory + Graphics memory + Swap + Battery level + Power draw + Network + Resolution + Proton version + Session time + Clock + Temperatures + Unit + Warning colors + Temperatures turn amber, then red, as they near the limit. + Off + Automatic + Manual + CPU red at + GPU red at + Battery red at + More + HUD diagnostics + Saves a report of every sensor the HUD reads to Downloads/DroidDeck. + Save + Saved to %1$s + Couldn\'t save the HUD report. + Reset HUD settings + Reset + FusionHUD by The412Banner, github.com/The412Banner/FusionHUD (GPL-3.0). Scaling mode Scaling sharpness Screen effects diff --git a/app/src/test/java/com/droiddeck/launcher/hud/FrameStatsTest.kt b/app/src/test/java/com/droiddeck/launcher/hud/FrameStatsTest.kt new file mode 100644 index 0000000000..ac9348f527 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/hud/FrameStatsTest.kt @@ -0,0 +1,138 @@ +package com.droiddeck.launcher.hud + +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import kotlin.random.Random + +class FrameStatsTest { + /** MangoHud's update_hud_info_with_frametime and fps()/frame_timing(), line by line (overlay.cpp). */ + private class Mango { + val frametimeData = ArrayList(List(200) { 0f }) + var lastPresentTime = 0L + var lastFpsUpdate = 0L + var framesSinceUpdate = 0L + var fps = 0.0 + + fun update(frametimeNs: Long, now: Long) { + val elapsed = now - lastFpsUpdate + if (lastPresentTime != 0L) { + frametimeData.add(frametimeNs / 1000000f) + frametimeData.removeAt(0) + } + if (elapsed >= 500000000L) { + fps = 1000000000.0 * framesSinceUpdate / elapsed + framesSinceUpdate = 0 + lastFpsUpdate = now + } + lastPresentTime = now + framesSinceUpdate++ + } + } + + @Test fun readingsMatchMangoHudFrameByFrame() { + val random = Random(7) + val stats = FrameStats() + val mango = Mango() + var now = 5_000_000_000L + val graph = FloatArray(FrameStats.GRAPH_FRAMES) + repeat(20_000) { i -> + val frametime = when { + i % 977 == 0 -> 100_000_000L + i % 131 == 0 -> 33_000_000L + else -> 2_700_000L + random.nextLong(-400_000L, 400_000L) + } + now += frametime + stats.add(frametime, now) + mango.update(frametime, now) + assertEquals("fps at frame $i", mango.fps.toFloat(), stats.fps, 0.0001f) + assertEquals(1000f / maxOf(mango.fps.toFloat(), 1f), stats.frametimeMs(), 0.0001f) + if (i % 499 == 0 || i < 210) { + stats.graph(graph) + assertArrayEquals("graph at frame $i", mango.frametimeData.toFloatArray(), graph, 0f) + assertEquals(mango.frametimeData.min(), stats.graphMinMs(), 0f) + assertEquals(mango.frametimeData.max(), stats.graphMaxMs(), 0f) + } + } + } + + @Test fun compositorFramesWakeTheHudWhenGamescopeSharesNone() { + val feed = GameFrameFeed(java.io.File("/nonexistent/droiddeck-hud/frames")) + var now = 1_000_000_000L + assertFalse(feed.poll(now)) + feed.onCompositorFrame(now) + now += 16_666_667L + feed.onCompositorFrame(now) + assertTrue(feed.poll(now)) + assertFalse(feed.poll(now + 1)) + } + + @Test fun aCompletedPeriodIsCountedWhenMangoHudWouldRedraw() { + val stats = FrameStats() + var now = 1_000_000_000L + stats.add(10_000_000L, now) + assertEquals(1L, stats.fpsUpdates) + repeat(49) { now += 10_000_000L; stats.add(10_000_000L, now) } + assertEquals(1L, stats.fpsUpdates) + now += 10_000_000L; stats.add(10_000_000L, now) + assertEquals(2L, stats.fpsUpdates) + assertEquals(100f, stats.fps, 0.01f) + } + + @Test fun aSteadyRateReadsExactlyWithoutMillisecondRounding() { + val stats = FrameStats() + var now = 1_000_000_000L + val frametime = 16_666_667L + repeat(600) { now += frametime; stats.add(frametime, now) } + assertEquals(60f, stats.fps, 0.01f) + val lows = stats.lows(now) + assertEquals(60f, lows.low1Fps, 0.01f) + assertEquals(60f, lows.low01Fps, 0.01f) + assertEquals(60f, stats.averageFps(), 0.01f) + } + + @Test fun stuttersShowInTheGraphAndTheLows() { + val stats = FrameStats() + var now = 1_000_000_000L + repeat(1000) { i -> + val frametime = if (i % 100 == 50) 100_000_000L else 2_700_000L + now += frametime + stats.add(frametime, now) + } + assertEquals(100f, stats.graphMaxMs(), 0.001f) + assertEquals(2.7f, stats.graphMinMs(), 0.001f) + assertEquals(10f, stats.lows(now).low01Fps, 0.01f) + assertEquals(370.37f, stats.lows(now).low1Fps, 0.01f) + } + + @Test fun pausesStayOutOfTheAverageAndLowsButNotTheGraph() { + val stats = FrameStats() + var now = 1_000_000_000L + repeat(300) { now += 10_000_000L; stats.add(10_000_000L, now) } + now += 3_000_000_000L + stats.add(3_000_000_000L, now) + assertEquals(100f, stats.lows(now).low01Fps, 0.01f) + assertEquals(3000f, stats.graphMaxMs(), 0.01f) + } + + @Test fun resetStartsOver() { + val stats = FrameStats() + var now = 1_000_000_000L + repeat(300) { now += 10_000_000L; stats.add(10_000_000L, now) } + stats.reset() + assertEquals(0f, stats.fps, 0f) + assertEquals(0f, stats.graphMaxMs(), 0f) + assertEquals(FrameStats.Lows.EMPTY, stats.lows(now)) + } + + @Test fun engineNamesFollowMangoHud() { + assertEquals("DXVK", GameFrameFeed.engineLabel("DXVK")) + assertEquals("VKD3D", GameFrameFeed.engineLabel("vkd3d")) + assertEquals("ZINK", GameFrameFeed.engineLabel("mesa zink")) + assertEquals("GAMESCOPE", GameFrameFeed.engineLabel("gamescope")) + assertEquals("GAMESCOPE", GameFrameFeed.engineLabel("")) + assertEquals("VULKAN", GameFrameFeed.engineLabel("UnityEngine")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/hud/FusionHudPanelTest.kt b/app/src/test/java/com/droiddeck/launcher/hud/FusionHudPanelTest.kt new file mode 100644 index 0000000000..f27a77cfe6 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/hud/FusionHudPanelTest.kt @@ -0,0 +1,68 @@ +package com.droiddeck.launcher.hud + +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Color +import android.view.View +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode +import java.io.ByteArrayOutputStream +import java.util.Base64 +import kotlin.math.roundToInt +import kotlin.math.sqrt + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33], qualifiers = "xhdpi") +@GraphicsMode(GraphicsMode.Mode.NATIVE) +class FusionHudPanelTest { + @Test fun minimalIsTheSizeTheHudStartsWith() { + assertEquals(FusionSize.MINIMAL, FusionSize.from(FusionHudConfig.DEFAULTS["hudSize"])) + } + + @Test fun everySizeDrawsTheDPanelWithEverythingInsideIt() { + val stats = FrameStats() + var now = 1_000_000_000L + repeat(2_000) { i -> + val frametime = if (i == 1_700) 25_600_000L else 2_850_000L + now += frametime + stats.add(frametime, now) + } + val snapshot = HudMetrics.Snapshot(64, 52, 3302, 1050, 89, 79, 10_800_000_000L, 16_000_000_000L, 67f, + 1_800_000_000L, HudMetrics.Battery(16f, false, 79, 34, null), + intArrayOf(91, 91, 48, 50, 48, 19, 17, 73), intArrayOf(2265, 2265, 3148, 3148, 3148, 2956, 2956, 3302), + 2_700_000_000L, 6_400_000_000L, 31_000L, 9_000L) + + for (size in FusionSize.values()) { + val view = FusionHudView(RuntimeEnvironment.getApplication()) + view.applyConfig(FusionHudConfig.encode(FusionHudConfig.DEFAULTS + ("hudSize" to size.token))) + view.setFrameStats(stats) + view.showForTest(snapshot, "DXVK", now) + val unspecified = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) + view.measure(unspecified, unspecified) + view.layout(0, 0, view.measuredWidth, view.measuredHeight) + val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888) + view.draw(Canvas(bitmap)) + + val png = ByteArrayOutputStream().also { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) } + println("FUSIONHUD-${size.token.uppercase()}-PNG ${Base64.getEncoder().encodeToString(png.toByteArray())}") + + val panel = view.panelForTest()!! + assertTrue("$size panel inside the view", + panel.left > 0f && panel.top > 0f && panel.right < view.width && panel.bottom < view.height) + view.graphForTest()?.let { graph -> + val r = view.panelRadiusForTest() + val d = maxOf(panel.top + r - graph.top, graph.bottom - (panel.bottom - r), 0f) + val edge = panel.right - r + sqrt(r * r - d * d) + assertTrue("$size graph clears the round side", graph.right <= edge) + } + val orb = bitmap.getPixel(panel.left.roundToInt() + 1, panel.centerY().roundToInt()) + assertTrue("$size orb on the left side", Color.blue(orb) > 200 && Color.alpha(orb) > 200) + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/hud/MangoReadingsTest.kt b/app/src/test/java/com/droiddeck/launcher/hud/MangoReadingsTest.kt new file mode 100644 index 0000000000..246d972969 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/hud/MangoReadingsTest.kt @@ -0,0 +1,70 @@ +package com.droiddeck.launcher.hud + +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File + +class MangoReadingsTest { + @get:Rule val tmp = TemporaryFolder() + + private fun readings() = MangoReadings(tmp.root, tmp.root) + + @Test fun cpuLoadFollowsMangoHudsFormulaAndTruncates() { + val stat = File(tmp.root, "stat") + val m = readings() + // user nice system idle iowait irq softirq steal guest guest_nice + stat.writeText("cpu 1000 100 500 8000 400 50 50 0 200 0\ncpu0 500 50 250 4000 200 25 25 0 100 0\ncpu1 500 50 250 4000 200 25 25 0 100 0\nintr 0\n") + m.cpu(stat) + stat.writeText("cpu 1500 100 700 8600 500 60 70 10 300 0\ncpu0 900 50 400 4100 250 30 35 10 200 0\ncpu1 600 50 300 4500 250 30 35 0 100 0\nintr 0\n") + val cpu = m.cpu(stat)!! + // busy = user-guest 400 + nice 0 + system+irq+softirq 230 + steal 10 + guest 100 = 740 of 1440 (idle+iowait 700) + assertEquals((740 * 100f / 1440).toInt(), cpu.percent) + assertEquals(51, cpu.percent) + assertArrayEquals(intArrayOf(((300 + 165 + 10 + 100) * 100f / (300 + 165 + 10 + 100 + 150)).toInt(), ((100 + 65) * 100f / (100 + 65 + 550)).toInt()), cpu.perCore) + } + + @Test fun anUnchangedCounterKeepsTheLastLoad() { + val stat = File(tmp.root, "stat") + val m = readings() + stat.writeText("cpu 100 0 0 100 0 0 0 0 0 0\n") + m.cpu(stat) + stat.writeText("cpu 200 0 0 100 0 0 0 0 0 0\n") + assertEquals(100, m.cpu(stat)!!.percent) + assertEquals(100, m.cpu(stat)!!.percent) + } + + private fun battery(status: String, chargeNow: Long, chargeFull: Long, powerUw: Long) { + val dir = File(tmp.root, "sys/power_supply/BAT1").apply { mkdirs() } + File(dir, "status").writeText("$status\n") + File(dir, "charge_now").writeText("$chargeNow\n") + File(dir, "charge_full").writeText("$chargeFull\n") + File(dir, "power_now").writeText("$powerUw\n") + } + + @Test fun batteryHidesWattsWhileChargingAsMangoHudDoes() { + battery("Discharging", 3_622_942, 3_854_193, 8_760_000) + val discharging = readings().battery()!! + assertEquals(94, discharging.percent) + assertEquals(8.76f, discharging.watts, 0.001f) + assertFalse(discharging.charging) + battery("Charging", 3_622_942, 3_854_193, 8_760_000) + val charging = readings().battery()!! + assertEquals(0f, charging.watts, 0f) + assertTrue(charging.charging) + } + + @Test fun noBatteryFolderMeansNoReading() { + assertNull(readings().battery()) + } + + @Test fun gpuLoadIsTheLeadingNumber() { + val f = File(tmp.root, "perf_now").apply { writeText(" 6 %\n") } + assertEquals(6.0, MangoReadings.leadingNumber(f)!!, 0.0) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/PerfHudGraphTest.kt b/app/src/test/java/com/droiddeck/launcher/session/PerfHudGraphTest.kt deleted file mode 100644 index bf607d3678..0000000000 --- a/app/src/test/java/com/droiddeck/launcher/session/PerfHudGraphTest.kt +++ /dev/null @@ -1,18 +0,0 @@ -package com.droiddeck.launcher.session - -import org.junit.Assert.assertArrayEquals -import org.junit.Assert.assertEquals -import org.junit.Test - -class PerfHudGraphTest { - @Test fun theGraphShowsOnlyFramesFromThisHudRun() { - val samples = floatArrayOf(9f, 9f, 9f, 9f, 9f, 16.7f, 33.4f, 16.6f) - assertArrayEquals(floatArrayOf(16.7f, 33.4f, 16.6f), PerfHud.recent(samples, 105, 102), 0f) - assertEquals(0, PerfHud.recent(samples, 103, 102).size) - } - - @Test fun anEarlySessionShowsWhatWasShownSoFar() { - val samples = floatArrayOf(16.6f, 16.7f, 120f, 0f, 0f, 0f) - assertArrayEquals(floatArrayOf(16.6f, 16.7f, 50f), PerfHud.recent(samples, 3, 0), 0f) - } -} 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 8ad756aff6..db1d2b827b 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SettingsResetTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SettingsResetTest.kt @@ -40,6 +40,8 @@ class SettingsResetTest { SessionPrefs.setHudShowGraph(app, false) SessionPrefs.setHudColor(app, "amber") SessionPrefs.setHudOpacity(app, 40) + SessionPrefs.setFusionHudConfig(app, "hudSize=mega,showFPSGraph=0") + SessionPrefs.setFusionHudPosition(app, 120f, 40f) ControllerPrefs.setOpacity(app, 40) AppUiPrefs.setScale(app, 150) FrameGen.set(app, FrameGen.Mode(FrameGen.ENGINE_DDFG, 3)) @@ -64,8 +66,8 @@ class SettingsResetTest { assertTrue(SessionPrefs.hudShowGraph(app)) assertEquals(SessionPrefs.HUD_COLOR_MINT, SessionPrefs.hudColor(app)) assertEquals(SessionPrefs.HUD_OPACITY_DEFAULT, SessionPrefs.hudOpacity(app)) - assertEquals("32.4°C", PerfHud.batteryCelsius(324)) - assertNull(PerfHud.batteryCelsius(0)) + assertNull(SessionPrefs.fusionHudConfig(app)) + assertNull(SessionPrefs.fusionHudPosition(app)) assertEquals(100, ControllerPrefs.read(app).opacity) assertEquals(AppUiPrefs.DEFAULT_SCALE, AppUiPrefs.scale(app)) assertEquals(FrameGen.Mode.OFF.engine, FrameGen.engine(app)) 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 c1d5ad10dd..35561a41d5 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt @@ -19,7 +19,8 @@ class SessionDrawerPageTest { assertEquals(SessionDrawerPage.DISPLAY, connected.step(SessionDrawerPage.SECOND_SCREEN, 1)) assertEquals(sessionDrawerPages(false), connected.filter { it != SessionDrawerPage.SECOND_SCREEN }) for (pages in listOf(connected, sessionDrawerPages(false))) { - assertEquals(SessionDrawerPage.EFFECTS, pages.step(SessionDrawerPage.DISPLAY, 1)) + assertEquals(SessionDrawerPage.HUD, pages.step(SessionDrawerPage.DISPLAY, 1)) + assertEquals(SessionDrawerPage.EFFECTS, pages.step(SessionDrawerPage.HUD, 1)) assertEquals(SessionDrawerPage.VR, pages.step(SessionDrawerPage.EFFECTS, 1)) assertEquals(SessionDrawerPage.GAMES, pages.step(SessionDrawerPage.VR, 1)) assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.GAMES, 1)) diff --git a/tools/gamescope/PATCHES.md b/tools/gamescope/PATCHES.md index a57c3bc82b..32317c4fa6 100644 --- a/tools/gamescope/PATCHES.md +++ b/tools/gamescope/PATCHES.md @@ -199,3 +199,13 @@ is marked done at once - no duplicate fence, no epoll add or delete, no waiter w loop handles it in the same pass, after the import (FIFO commits still wait for a vblank). The `commit_ready_check` convar (default on, `gamescopectl commit_ready_check 0`) turns it off; the `xwm` log counts fences ready at import and waited for, every 10 s. + +## 0125 steamcompmgr: share mangoapp's frame times with DroidDeck's HUD + +DroidDeck's in-app HUD shows the same frame rate and frame times as Steam's performance overlay. +DroidDeck's mangoapp (Valve's 20260902.1 build) reads the field at byte 16 of gamescope's messages as +its frame time; gamescope 3.16.29 puts `app_frametime_ns` there, the time between signalled commits of +the connector's windows (`mangoapp_nudge_app_frame`). With `DROIDDECK_HUD_FRAMES` set (droiddeck-session +sets `/run/droiddeck-hud/frames`), gamescope maps that file and writes the same commits of connector 0, +whether or not a mangoapp runs, plus the focused pid, output size, refresh, Steam focus and engine name. +The layout is in the comment above `droiddeck_hud_frames_map`; the app reads it in `hudframes.c`. diff --git a/tools/gamescope/patches/0125-droiddeck-hud-frame-times.patch b/tools/gamescope/patches/0125-droiddeck-hud-frame-times.patch new file mode 100644 index 0000000000..8fdbbf824c --- /dev/null +++ b/tools/gamescope/patches/0125-droiddeck-hud-frame-times.patch @@ -0,0 +1,227 @@ +diff --git a/src/commit.cpp b/src/commit.cpp +index f2e0f0c..fbfb550 100644 +--- a/src/commit.cpp ++++ b/src/commit.cpp +@@ -86,6 +86,8 @@ void commit_t::Signal() + mangoapp_nudge_app_frame( k_uMangoappLegacyMsgType, now ); + if ( m_uMangoMsgType != 0 ) + mangoapp_nudge_app_frame( m_uMangoMsgType, now ); ++ if ( m_bDroidDeckHudFrame ) ++ droiddeck_hud_app_frame( now ); + } + + void commit_t::OnPollHangUp() +@@ -113,7 +115,7 @@ bool commit_t::CloseFenceInternal() + return true; + } + +-void commit_t::SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr &pDoneCommits ) ++void commit_t::SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr &pDoneCommits, bool bDroidDeckHudFrame ) + { + std::unique_lock lock( m_WaitableCommitStateMutex ); + CloseFenceInternal(); +@@ -121,6 +123,7 @@ void commit_t::SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, c + m_nCommitFence = nFence; + m_bMangoNudge = bMangoNudge; + m_uMangoMsgType = uMangoMsgType; ++ m_bDroidDeckHudFrame = bDroidDeckHudFrame; + m_pDoneCommits = pDoneCommits; + } + +diff --git a/src/commit.h b/src/commit.h +index 8603a9a..ae767b6 100644 +--- a/src/commit.h ++++ b/src/commit.h +@@ -35,7 +35,7 @@ struct commit_t final : public gamescope::RcObject, public gamescope::IWaitable, + + // Returns true if we had a fence that was closed. + bool CloseFenceInternal(); +- void SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr &pDoneCommits ); ++ void SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr &pDoneCommits, bool bDroidDeckHudFrame = false ); + + bool ShouldPreemptivelyUpscale( GamescopeUpscaleFilter eFilter, GamescopeUpscaleScaler eScaler ); + +@@ -82,5 +82,6 @@ struct commit_t final : public gamescope::RcObject, public gamescope::IWaitable, + bool m_bMangoNudge = false; + // Typed mangoapp stream to nudge, 0 for none, never the legacy type. + uint32_t m_uMangoMsgType = 0; ++ bool m_bDroidDeckHudFrame = false; + std::shared_ptr m_pDoneCommits; // I hate this + }; +diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp +index 0aef598..1473148 100644 +--- a/src/steamcompmgr.cpp ++++ b/src/steamcompmgr.cpp +@@ -57,6 +57,7 @@ + #include + #include + #include ++#include + #include + #include + #include +@@ -8359,6 +8360,8 @@ static TempUpscaleImage_t *GetTempUpscaleImage( global_focus_t *pFocus, uint32_t + + gamescope::ConVar cv_surface_update_force_only_current_surface( "surface_update_force_only_current_surface", false, "Force updates to apply only to the current surface, ignoring commits for other surfaces." ); + ++static bool droiddeck_hud_frames_wanted(); ++ + gamescope::ConVar cv_commit_ready_check( "commit_ready_check", true, "Check a new commit's fence at import; a finished frame is marked done in the same pass instead of through the image waiter." ); + + // Set when update_wayland_res marks a commit done itself, so the main loop handles it in the same pass. +@@ -8519,6 +8522,16 @@ void update_wayland_res(const std::shared_ptr &doneCommits, st + uMangoMsgType = pMangoFocus->externalOverlayWindow->uMangoappMsgType; + } + ++ // The commits the typed stream of connector 0 counts, whether or not a mangoapp runs. ++ bool bDroidDeckHudFrame = false; ++ if ( pUpscaleFocus && !w->isSteamStreamingClient ) ++ bDroidDeckHudFrame = pUpscaleFocus->ulVirtualFocusKey == 0; ++ else if ( w->isSteamStreamingClientVideo ) ++ { ++ auto iter = g_VirtualConnectorFocuses.find( 0 ); ++ bDroidDeckHudFrame = iter != g_VirtualConnectorFocuses.end() && iter->second.focusWindow && iter->second.focusWindow->isSteamStreamingClient; ++ } ++ + bool bValidPreemptiveScale = reslistentry.pAcquirePoint && pUpscaleFocus && cv_upscale_preemptive; + bool bPreemptiveUpscale = bValidPreemptiveScale && newCommit->ShouldPreemptivelyUpscale( pUpscaleFocus->eUpscaleFilter, pUpscaleFocus->eUpscaleScaler ); + +@@ -8650,7 +8663,7 @@ void update_wayland_res(const std::shared_ptr &doneCommits, st + + gpuvis_trace_printf( "pushing wait for commit %lu win %lx", newCommit->commitID, w->type == steamcompmgr_win_type_t::XWAYLAND ? w->xwayland().id : 0 ); + { +- newCommit->SetFence( fence, mango_nudge, uMangoMsgType, doneCommits ); ++ newCommit->SetFence( fence, mango_nudge, uMangoMsgType, doneCommits, bDroidDeckHudFrame && droiddeck_hud_frames_wanted() ); + if ( bKnownReady ) + { + newCommit->Signal(); +@@ -9865,6 +9878,109 @@ static void publish_mangoapp_connector_snapshots() + } + } + ++// DroidDeck's own HUD reads the frame times DroidDeck's mangoapp shows from a shared file named by ++// DROIDDECK_HUD_FRAMES, also while no mangoapp runs. That mangoapp (Valve's 20260902.1 build) reads the ++// field at byte 16 of each message as its frame time, which is app_frametime_ns here: one time per ++// signalled commit of the connector's windows (mangoapp_nudge_app_frame). The file gets the same commits ++// of connector 0. Little-endian: 0 magic, 4 version, 8 capacity, 12 pid, 16 frames written (u64), ++// 24 info sequence (odd while the info is written), 28 output width, 32 height, 36 refresh mHz, 40 Steam ++// focused, 44 engine (40 bytes), then from 128 one { frametime ns, monotonic time ns } pair per frame, ++// a ring of capacity. ++static constexpr uint32_t k_uDroidDeckHudFramesMagic = 0x46484444; ++static constexpr uint32_t k_uDroidDeckHudFramesVersion = 1; ++static constexpr uint32_t k_uDroidDeckHudFramesCapacity = 1024; ++static constexpr size_t k_zDroidDeckHudFramesHeader = 128; ++static constexpr size_t k_zDroidDeckHudFramesSize = k_zDroidDeckHudFramesHeader + k_uDroidDeckHudFramesCapacity * 16; ++static std::mutex s_DroidDeckHudFramesMutex; ++ ++static uint8_t *droiddeck_hud_frames_map() ++{ ++ static uint8_t *s_pMap = nullptr; ++ static bool s_bTried = false; ++ if ( s_bTried ) ++ return s_pMap; ++ s_bTried = true; ++ ++ const char *pszPath = getenv( "DROIDDECK_HUD_FRAMES" ); ++ if ( !pszPath || !*pszPath ) ++ return nullptr; ++ int fd = open( pszPath, O_RDWR | O_CREAT | O_CLOEXEC, 0644 ); ++ if ( fd < 0 ) ++ { ++ xwm_log.errorf_errno( "DroidDeck HUD frames: open %s", pszPath ); ++ return nullptr; ++ } ++ void *pMap = MAP_FAILED; ++ if ( ftruncate( fd, k_zDroidDeckHudFramesSize ) == 0 ) ++ pMap = mmap( nullptr, k_zDroidDeckHudFramesSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 ); ++ close( fd ); ++ if ( pMap == MAP_FAILED ) ++ { ++ xwm_log.errorf_errno( "DroidDeck HUD frames: map %s", pszPath ); ++ return nullptr; ++ } ++ uint8_t *pBytes = static_cast( pMap ); ++ __atomic_store_n( reinterpret_cast( pBytes ), 0u, __ATOMIC_RELEASE ); ++ memset( pBytes + 4, 0, k_zDroidDeckHudFramesSize - 4 ); ++ memcpy( pBytes + 4, &k_uDroidDeckHudFramesVersion, 4 ); ++ memcpy( pBytes + 8, &k_uDroidDeckHudFramesCapacity, 4 ); ++ __atomic_store_n( reinterpret_cast( pBytes ), k_uDroidDeckHudFramesMagic, __ATOMIC_RELEASE ); ++ xwm_log.infof( "DroidDeck HUD frames: %s", pszPath ); ++ s_pMap = pBytes; ++ return s_pMap; ++} ++ ++static bool droiddeck_hud_frames_wanted() ++{ ++ std::unique_lock lock( s_DroidDeckHudFramesMutex ); ++ return droiddeck_hud_frames_map() != nullptr; ++} ++ ++// Signal() runs on the image waiter thread or, for a frame finished at import, on steamcompmgr's. ++void droiddeck_hud_app_frame( uint64_t ulNow ) ++{ ++ std::unique_lock lock( s_DroidDeckHudFramesMutex ); ++ uint8_t *pMap = droiddeck_hud_frames_map(); ++ if ( !pMap ) ++ return; ++ static uint64_t s_ulLastFrame = 0; ++ uint64_t ulLast = s_ulLastFrame; ++ s_ulLastFrame = ulNow; ++ if ( !ulLast || ulNow <= ulLast ) ++ return; ++ uint64_t *pCount = reinterpret_cast( pMap + 16 ); ++ uint64_t ulCount = __atomic_load_n( pCount, __ATOMIC_RELAXED ); ++ uint64_t ulFrame[2] = { ulNow - ulLast, ulNow }; ++ memcpy( pMap + k_zDroidDeckHudFramesHeader + ( ulCount % k_uDroidDeckHudFramesCapacity ) * 16, ulFrame, sizeof( ulFrame ) ); ++ __atomic_store_n( pCount, ulCount + 1, __ATOMIC_RELEASE ); ++} ++ ++static void publish_droiddeck_hud_info() ++{ ++ std::unique_lock lock( s_DroidDeckHudFramesMutex ); ++ uint8_t *pMap = droiddeck_hud_frames_map(); ++ if ( !pMap ) ++ return; ++ auto focusIter = g_VirtualConnectorFocuses.find( 0 ); ++ global_focus_t *pFocus = focusIter != g_VirtualConnectorFocuses.end() ? &focusIter->second : GetCurrentFocus(); ++ if ( !pFocus ) ++ return; ++ ++ uint32_t *pSeq = reinterpret_cast( pMap + 24 ); ++ uint32_t uSeq = __atomic_load_n( pSeq, __ATOMIC_RELAXED ); ++ __atomic_store_n( pSeq, uSeq + 1, __ATOMIC_RELAXED ); ++ __atomic_thread_fence( __ATOMIC_RELEASE ); ++ uint32_t uPid = uint32_t( pFocus->nFocusWindowPid ); ++ uint32_t uOutput[4] = { g_nOutputWidth, g_nOutputHeight, uint32_t( g_nOutputRefresh ), window_is_steam( pFocus->inputFocusWindow ) ? 1u : 0u }; ++ char szEngine[40] = {}; ++ if ( pFocus->pFocusWindowEngine ) ++ pFocus->pFocusWindowEngine->copy( szEngine, sizeof( szEngine ) - 1 ); ++ memcpy( pMap + 12, &uPid, 4 ); ++ memcpy( pMap + 28, uOutput, sizeof( uOutput ) ); ++ memcpy( pMap + 44, szEngine, sizeof( szEngine ) ); ++ __atomic_store_n( pSeq, uSeq + 2, __ATOMIC_RELEASE ); ++} ++ + // mangohudctl posts one control message for every instance to act on. + static void relay_mangoapp_control() + { +@@ -10843,6 +10959,7 @@ steamcompmgr_main(int argc, char **argv) + + publish_mangoapp_snapshot(); + publish_mangoapp_connector_snapshots(); ++ publish_droiddeck_hud_info(); + relay_mangoapp_control(); + + if ( bIsVBlankFromTimer ) +diff --git a/src/steamcompmgr.hpp b/src/steamcompmgr.hpp +index bd62fd1..7a7119f 100644 +--- a/src/steamcompmgr.hpp ++++ b/src/steamcompmgr.hpp +@@ -173,6 +173,7 @@ static constexpr uint32_t MangoappControlMsgType( uint32_t uMsgType ) + static_assert( MangoappControlMsgType( k_uMangoappLegacyMsgType ) == k_uMangoappControlMsgType ); + + extern void mangoapp_update( uint64_t visible_frametime, uint64_t app_frametime_ns, uint64_t latency_ns, uint32_t uMsgType = k_uMangoappLegacyMsgType ); ++extern void droiddeck_hud_app_frame( uint64_t ulNow ); + extern void mangoapp_nudge_app_frame( uint32_t uMsgType, uint64_t ulNow ); + extern void mangoapp_set_connector_snapshots( std::unordered_map snapshots ); + extern void mangoapp_drop_stream( uint32_t uMsgType ); diff --git a/tools/gamescope/release.env b/tools/gamescope/release.env index 996f24a812..a73f1985b8 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-p18 -GAMESCOPE_SHA256=a79d8acc5628973c807a43524638c20e7d5c101a4fc3bcb8b5068631e6f6fe55 +GAMESCOPE_TAG=gamescope-3.16.29-p19 +GAMESCOPE_SHA256=e7333c6a2b95708b199c2c5bd0973e3f0e711e2dc746950cc648c2515ea2926b diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session index ada9cba2ec..4b45e854b1 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session @@ -257,6 +257,8 @@ if [ -z "${BL_INSIDE:-}" ]; then args+=(--mangoapp) echo "== gamescope: mangoapp on ($(command -v mangoapp), config $MANGOHUD_CONFIGFILE)" fi + # gamescope writes the frame times the app's HUD shows here (patch 0125). + mkdir -p /run/droiddeck-hud && export DROIDDECK_HUD_FRAMES=/run/droiddeck-hud/frames export BL_INSIDE=1 # A fixed path: left to itself gamescope creates a new limiter state file on every start. rm -f "${XDG_RUNTIME_DIR:-/tmp}"/gamescope-limiter-* diff --git a/tools/tests/test_hud_frames.py b/tools/tests/test_hud_frames.py new file mode 100644 index 0000000000..381c18e37e --- /dev/null +++ b/tools/tests/test_hud_frames.py @@ -0,0 +1,136 @@ +from pathlib import Path +import os +import shutil +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +PATCH = ROOT / "tools/gamescope/patches/0125-droiddeck-hud-frame-times.patch" +READER = ROOT / "app/src/main/cpp/waylandcomp/src/hudframes.c" + + +def patch_writer(): + added = [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")] + text = "\n".join(added) + start = text.index("// DroidDeck's own HUD reads") + end = text.index("\n}\n", text.index("static void publish_droiddeck_hud_info()", start)) + 3 + return text[start:end] + + +PREAMBLE = r''' +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +extern "C" { +#include "hudframes.h" +} + +struct steamcompmgr_win_t { int appID; }; +struct global_focus_t { + uint64_t ulBasePlaneCommitID = 0; + pid_t nFocusWindowPid = 0; + std::shared_ptr pFocusWindowEngine; + steamcompmgr_win_t *inputFocusWindow = nullptr; +}; +static std::unordered_map g_VirtualConnectorFocuses; +static global_focus_t *GetCurrentFocus() { return nullptr; } +static bool window_is_steam(steamcompmgr_win_t *w) { return w && w->appID == 769; } +static uint64_t g_now = 1000000000ull; +static uint64_t get_time_in_nanos() { return g_now; } +static uint32_t g_nOutputWidth = 1280, g_nOutputHeight = 720; +static int g_nOutputRefresh = 144000; +struct Log { + void infof(const char *, ...) {} + void errorf_errno(const char *fmt, ...) { va_list a; va_start(a, fmt); vfprintf(stderr, fmt, a); va_end(a); } +} xwm_log; +''' + +MAIN = r''' +static void frame(uint64_t step) { g_now += step; droiddeck_hud_app_frame(g_now); } + +int main(int argc, char **argv) { + setenv("DROIDDECK_HUD_FRAMES", argv[1], 1); + assert(droiddeck_hud_frames_wanted()); + global_focus_t &focus = g_VirtualConnectorFocuses[0]; + focus.nFocusWindowPid = 4242; + focus.pFocusWindowEngine = std::make_shared("DXVK"); + steamcompmgr_win_t game{ 12345 }; + focus.inputFocusWindow = &game; + publish_droiddeck_hud_info(); + + droiddeck_hud_app_frame(g_now); + struct hud_frames *h = hud_frames_open(argv[1]); + assert(h); + int64_t ft[2048], tm[2048]; + assert(hud_frames_poll(h, ft, tm, 2048) == 0); + + const uint64_t steps[] = { 2700000, 2800000, 41600000, 6944000 }; + for (uint64_t step : steps) frame(step); + int n = hud_frames_poll(h, ft, tm, 2048); + assert(n == 4); + for (int i = 0; i < 4; i++) assert((uint64_t)ft[i] == steps[i]); + assert((uint64_t)tm[3] == g_now); + assert(hud_frames_poll(h, ft, tm, 2048) == 0); + + int32_t info[5]; + char engine[41]; + assert(hud_frames_info(h, info, engine, sizeof(engine))); + assert(info[0] == 4242 && info[1] == 1280 && info[2] == 720 && info[3] == 144000 && info[4] == 0); + assert(strcmp(engine, "DXVK") == 0); + game.appID = 769; + publish_droiddeck_hud_info(); + assert(hud_frames_info(h, info, engine, sizeof(engine)) && info[4] == 1); + + for (int i = 0; i < 3000; i++) frame(1000000 + i); + n = hud_frames_poll(h, ft, tm, 2048); + assert(n == 1024); + assert(ft[1023] == 1000000 + 2999); + assert(ft[0] == 1000000 + 2999 - 1023); + + for (int i = 0; i < 10; i++) frame(2000000); + assert(hud_frames_poll(h, ft, tm, 4) == 4 && ft[3] == 2000000); + hud_frames_close(h); + puts("ok"); + return 0; +} +''' + + +@unittest.skipUnless(shutil.which("cc") and shutil.which("c++"), "needs a C and C++ compiler") +class HudFramesTest(unittest.TestCase): + def test_gamescope_writer_and_app_reader_agree(self): + with tempfile.TemporaryDirectory() as tmp: + tmp = Path(tmp) + source = tmp / "writer.cpp" + source.write_text(PREAMBLE + patch_writer() + MAIN) + include = READER.parent + subprocess.run(["cc", "-std=gnu11", "-Wall", "-Wextra", "-Werror", "-c", str(READER), "-o", str(tmp / "reader.o")], check=True) + subprocess.run(["c++", "-std=c++20", "-Wall", "-Werror", "-Wno-unused-function", f"-I{include}", str(source), str(tmp / "reader.o"), + "-o", str(tmp / "hudframes")], check=True) + result = subprocess.run([str(tmp / "hudframes"), str(tmp / "frames")], capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.strip(), "ok") + self.assertEqual(os.path.getsize(tmp / "frames"), 128 + 1024 * 16) + + def test_session_points_gamescope_at_the_file_the_app_reads(self): + session = (ROOT / "tools/linuxfs/overlay/usr/local/bin/droiddeck-session").read_text() + self.assertIn("export DROIDDECK_HUD_FRAMES=/run/droiddeck-hud/frames", session) + app = (ROOT / "app/src/main/java/com/droiddeck/launcher/hud/HudFrames.kt").read_text() + self.assertIn('"run/droiddeck-hud/frames"', app) + + +if __name__ == "__main__": + unittest.main()