mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-04 20:15:44 +00:00
Compare commits
93
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e6e3673709 | ||
|
|
268dcef559 | ||
|
|
66abf0c707 | ||
|
|
5be04466af | ||
|
|
63ad5a722f | ||
|
|
f896d7fa75 | ||
|
|
995cbc411c | ||
|
|
5045002de1 | ||
|
|
e75505c019 | ||
|
|
264c0fc0f6 | ||
|
|
0f93fd75c4 | ||
|
|
4deff589e5 | ||
|
|
97853d0fde | ||
|
|
2d5061c986 | ||
|
|
6dab2cef17 | ||
|
|
3a4866e2ea | ||
|
|
499b06ff2c | ||
|
|
abca04336a | ||
|
|
5eaa6a76cc | ||
|
|
42df3a78b3 | ||
|
|
30e009a651 | ||
|
|
9e28a11270 | ||
|
|
ed3cfaf9c6 | ||
|
|
082ea000dc | ||
|
|
a251e8cc23 | ||
|
|
60184418ba | ||
|
|
125e39ea9c | ||
|
|
ee8911a382 | ||
|
|
3be85906e9 | ||
|
|
e76592ba4e | ||
|
|
0a07926ef3 | ||
|
|
b63feb5eaa | ||
|
|
d691bcf832 | ||
|
|
583f34fc55 | ||
|
|
88719f25d2 | ||
|
|
ac132a23e2 | ||
|
|
85dd8beae1 | ||
|
|
b07eca3c06 | ||
|
|
6eef0721c9 | ||
|
|
e3c3471d2f | ||
|
|
a81d1a4d4e | ||
|
|
28067b3bbe | ||
|
|
8088e47d14 | ||
|
|
6673a892e2 | ||
|
|
8cf01ebb77 | ||
|
|
7e47db2e2a | ||
|
|
484afffffd | ||
|
|
0b1af34a5f | ||
|
|
2ff682a4f5 | ||
|
|
18f6305977 | ||
|
|
7bc3529722 | ||
|
|
9cc56631cd | ||
|
|
a5b035b247 | ||
|
|
a8cebd024b | ||
|
|
7c49eef79f | ||
|
|
c8c5e22a34 | ||
|
|
fa4a54f64a | ||
|
|
83980035c6 | ||
|
|
8f7cdb7106 | ||
|
|
9a1334b73b | ||
|
|
ab949a4a5a | ||
|
|
b91e8fdeab | ||
|
|
021e7153fa | ||
|
|
524292f457 | ||
|
|
92c1560f63 | ||
|
|
41615d2460 | ||
|
|
bc1a010411 | ||
|
|
d31f234f74 | ||
|
|
6ffe675a57 | ||
|
|
fb5af9d35e | ||
|
|
b75060c280 | ||
|
|
67d391958f | ||
|
|
4770d11e39 | ||
|
|
f69e2d0171 | ||
|
|
b0a8c2065d | ||
|
|
d4fd7ac5c3 | ||
|
|
ed661d7007 | ||
|
|
265335d550 | ||
|
|
2b0d633535 | ||
|
|
3b917c0db3 | ||
|
|
58968c9286 | ||
|
|
5736297987 | ||
|
|
26e2f26ec9 | ||
|
|
23bb361006 | ||
|
|
ee3876b965 | ||
|
|
5d6f9c7d74 | ||
|
|
d5d3aa2ae4 | ||
|
|
31c943c82a | ||
|
|
3b9abf6302 | ||
|
|
161a93a4b3 | ||
|
|
7d3d338fb9 | ||
|
|
a3da6f0bda | ||
|
|
b726e19fa4 |
No files matched your search
@@ -274,6 +274,9 @@ jobs:
|
||||
if: steps.comet.outputs.cache-hit != 'true'
|
||||
run: python3 tools/components/prepare.py comet
|
||||
|
||||
- name: Build the DiRT 3 / DiRT Showdown ws2_32 stand-in
|
||||
run: python3 tools/components/prepare.py dirt-ws2
|
||||
|
||||
- name: Prepare graphics driver variants
|
||||
run: python3 tools/quest/build-driver.py "$ANDROID_HOME/ndk/$NDK_VERSION"
|
||||
- name: Record and pack prepared components
|
||||
@@ -433,6 +436,7 @@ jobs:
|
||||
id: build-label
|
||||
env:
|
||||
PR_NUMBER: ${{ github.event.pull_request.number }}
|
||||
PR_TITLE: ${{ github.event.pull_request.title }}
|
||||
PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
BUILD_REF: ${{ github.ref_name }}
|
||||
BUILD_SHA: ${{ github.sha }}
|
||||
@@ -451,6 +455,7 @@ jobs:
|
||||
echo "label=$label" >> "$GITHUB_OUTPUT"
|
||||
echo "DROIDDECK_SOURCE_COMMIT=${PR_HEAD_SHA:-$BUILD_SHA}" >> "$GITHUB_ENV"
|
||||
echo "DROIDDECK_PR_NUMBER=${PR_NUMBER:-0}" >> "$GITHUB_ENV"
|
||||
echo "DROIDDECK_PR_TITLE=${PR_TITLE//$'\n'/ }" >> "$GITHUB_ENV"
|
||||
echo "Build: \`$label\`" >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
- name: Rust toolchain for the store engines (aarch64-linux-android)
|
||||
@@ -760,7 +765,7 @@ jobs:
|
||||
checks:
|
||||
name: Compile and test APK
|
||||
needs: [build, python-tests]
|
||||
if: ${{ always() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) }}
|
||||
if: ${{ !cancelled() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) }}
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
|
||||
@@ -61,7 +61,7 @@ jobs:
|
||||
jq -r --arg n "$2" '.assets // [] | .[] | select(.name == $n) | .digest // empty'
|
||||
}
|
||||
commit=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$BUILD_RUN" --jq .head_sha 2>/dev/null || echo "$GITHUB_SHA")
|
||||
for name in proot directaudio tracking xbox comet; do
|
||||
for name in proot directaudio tracking xbox comet butler; do
|
||||
file="packs/$name.tar.zst"
|
||||
[ -f "$file" ] || { echo "::error::$name.tar.zst is missing from Build APK run $BUILD_RUN"; exit 1; }
|
||||
sha=$(sha256sum "$file" | cut -d' ' -f1)
|
||||
|
||||
@@ -7,72 +7,148 @@
|
||||
|
||||
DroidDeck brings the SteamOS experience to Android: Valve's Steam client in Big Picture on your Adreno handheld, with Windows games through Valve's ARM64 Proton.
|
||||
|
||||
<p align="center"><a href="https://discord.gg/JRGAvawjsm"><img src="https://img.shields.io/badge/Discord-Join%20the%20community-5865F2?logo=discord&logoColor=white" alt="Join the DroidDeck Discord"></a></p>
|
||||
<p align="center"><b>100% open source. No ads. No telemetry. No source withheld.</b></p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://www.star-history.com/droid-deck/droiddeck"><img src="https://api.star-history.com/badge?repo=Droid-Deck/DroidDeck&type=rank&theme=dark" alt="Star History Rank" /></a>
|
||||
<a href="https://github.com/Droid-Deck/DroidDeck/releases/download/0.6.7/DroidDeck-0.6.7.apk"><img src="https://img.shields.io/badge/Download-DroidDeck%200.6.7%20APK-3DDC84?style=for-the-badge&logo=android&logoColor=white" alt="Download DroidDeck 0.6.7"></a>
|
||||
<a href="https://discord.gg/JRGAvawjsm"><img src="https://img.shields.io/badge/Discord-Join%20us-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="Join the DroidDeck Discord"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://trendshift.io/repositories/267852?utm_source=trendshift-badge&utm_medium=badge&utm_campaign=badge-trendshift-267852" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/267852/daily?language=C" alt="Droid-Deck%2FDroidDeck | Trendshift" width="250" height="55"/></a>
|
||||
<a href="https://trendshift.io/repositories/267852?utm_source=trendshift-badge&utm_medium=badge&utm_campaign=badge-trendshift-267852" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/267852/daily?language=Kotlin" alt="Droid-Deck%2FDroidDeck | Trendshift" width="250" height="55"/></a>
|
||||
<a href="https://www.star-history.com/droid-deck/droiddeck"><img src="https://api.star-history.com/badge?repo=Droid-Deck/DroidDeck&type=rank&theme=dark" alt="Star History Rank"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://trendshift.io/repositories/267852?utm_source=trendshift-badge&utm_medium=badge&utm_campaign=badge-trendshift-267852" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/267852/weekly?language=C" alt="Droid-Deck%2FDroidDeck | Trendshift" width="250" height="55"/></a>
|
||||
<a href="https://trendshift.io/repositories/267852?utm_source=trendshift-badge&utm_medium=badge&utm_campaign=badge-trendshift-267852" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/267852/weekly?language=Kotlin" alt="Droid-Deck%2FDroidDeck | Trendshift" width="250" height="55"/></a>
|
||||
<a href="https://trendshift.io/repositories/267852"><img src="https://trendshift.io/api/badge/trendshift/repositories/267852/daily?language=C" alt="Droid-Deck%2FDroidDeck | Trendshift" width="250" height="55"></a>
|
||||
<a href="https://trendshift.io/repositories/267852"><img src="https://trendshift.io/api/badge/trendshift/repositories/267852/daily?language=Kotlin" alt="Droid-Deck%2FDroidDeck | Trendshift" width="250" height="55"></a>
|
||||
</p>
|
||||
|
||||
<p align="center"><img src="docs/releases/media/0.2.0/launch-into-steam.gif" width="80%" alt="Tapping DroidDeck on the Android home screen and landing in Steam Big Picture"></p>
|
||||
<p align="center"><img src="docs/media/steam-to-desktop.gif" width="100%" alt="On a Retroid Pocket Duo: Play Steam from the DroidDeck launcher, open Pac-Man in Steam Big Picture and play it, exit the game, then Switch to Desktop from the Power menu"></p>
|
||||
|
||||
> Note: DroidDeck does not have a stand-alone website. Do not click on any download links from websites claiming to be the DroidDeck team.
|
||||
> DroidDeck has no website. Only download it from this repository's [Releases](https://github.com/Droid-Deck/DroidDeck/releases).
|
||||
|
||||
## Requirements and install
|
||||
<p align="center">
|
||||
<img src="docs/releases/media/0.6.7/library.gif" width="49%" alt="The Library switching source chips, changing the card size and opening the Filter menu">
|
||||
<img src="docs/releases/media/0.3.0/in-game.gif" width="49%" alt="A Windows game running through Proton with the on-screen controls">
|
||||
<img src="docs/releases/media/0.4.0/multi-controller.gif" width="49%" alt="Two controllers playing split screen on one handheld">
|
||||
<img src="docs/releases/media/0.6.7/ubuntu-desktop-discover.jpg" width="49%" alt="The Kubuntu desktop with Discover open">
|
||||
</p>
|
||||
|
||||
Use Android 9 or newer on a supported Adreno device (730 or newer, or 8xx). Adreno 6xx is experimental: DirectX 11 uses DXVK 2 and may run, and DirectX 12 games can still crash. Mali, Xclipse, PowerVR, and Adreno 710 are unsupported. No root is required. Allow about 3 GB for the runtime and 1.1 GB more for the desktop and emulators. Install the APK from [Releases](https://github.com/Droid-Deck/DroidDeck/releases), install the Linux runtime, then press **Play** and sign in. Steam downloads on first launch. Install **Desktop & apps** to use the desktop and emulators. The **Store** installs Linux apps and games from Flathub (ARM64 builds) with Flatpak; with additional options to install Appimages and set up scripts. **Stores** (Setup › Stores › "Show Stores in the rail") signs in to GOG, Epic Games and Amazon Games and downloads games into the Games storage. Epic keeps its direct API install path. Opening Epic Stores prepares Epic’s official Linux launcher preview. When installed, Epic games launched from DroidDeck use that client, and games installed in the client are imported into DroidDeck’s library and shortcuts. The x86-64 client runs through FEX on ARM and DroidDeck retains its Proton hooks; this preview and ARM setup are outside Epic’s listed Linux support. The cog on a store’s chip row sets its opening tab and download speed tier.
|
||||
## Install
|
||||
|
||||
On Android 14 and newer, before Steam launches, you must turn on **Disable child process restrictions** in Developer options. If this option is not available in developer settings (Android 12 and 13 devices), first launch of Steam will present a "Fix it for me" button, which will help automate the setup process.
|
||||
1. Android 9 or newer on Adreno 730 or newer, or any 8xx. Adreno 6xx is experimental. Mali, Xclipse, PowerVR and Adreno 710 are unsupported. No root needed.
|
||||
2. About 3 GB free for the runtime, plus 1.1 GB for the desktop and emulators.
|
||||
3. Install the [APK](https://github.com/Droid-Deck/DroidDeck/releases/download/0.6.7/DroidDeck-0.6.7.apk), install the Linux runtime, press **Play** and sign in to Steam.
|
||||
4. On Android 14 and newer, turn on **Disable child process restrictions** in Developer options. On Android 12 and 13, Steam's first launch shows a **Fix it for me** button that walks you through it.
|
||||
|
||||
## Smart glasses
|
||||
Smart glasses setup is in the [support matrix](docs/smart-glasses-support.md). Release notes are in [docs/releases](docs/releases).
|
||||
|
||||
Use **Setup → Smart glasses** for app-wide virtual-screen settings across DroidDeck menus, launchers, desktop sessions, and games. Supported VITURE, RayNeo, XREAL, and Rokid connections provide 3DoF; Luma Ultra adds optional experimental 6DoF and stereo-assisted hand/Joy-Con tracking. Model support and SDK requirements differ: see the [smart-glasses support matrix](docs/smart-glasses-support.md) for supported devices, controls, setup, and limitations.
|
||||
|
||||
## Community
|
||||
|
||||
Join the [DroidDeck Discord](https://discord.gg/JRGAvawjsm) for help, Preview builds, and device reports. Bug reports go in its **#bug-reports** forum; attach the zip from **Share logs** (Setup, or the session drawer) so the logs come with it.
|
||||
Help, Preview builds and device reports are on [Discord](https://discord.gg/JRGAvawjsm). For bugs, post in **#bug-reports** with the zip from **Share logs**.
|
||||
|
||||
## Build
|
||||
|
||||
Run `tools/build_local.sh` with Docker, Java 17, the Android SDK/NDK, Rust through rustup, GitHub CLI, Python 3, and `zstd` installed. It prepares the same native libraries, pinned components and audio sinks as CI, then checks the APK's assets, JNI exports and dependencies. The APK is at `app/build/outputs/apk/release/app-release.apk`. Set `DROIDDECK_PA13_SOURCE_DIR` to an existing PulseAudio 13.0 source directory to skip downloading it. Set `DROIDDECK_SIGNING_ENV` to a signing environment file to install over a release build; relative keystore paths resolve beside that file. To install on an attached device, run `tools/deploy_local.sh`.
|
||||
Needs Docker, Java 17, the Android SDK and NDK, Rust via rustup, GitHub CLI, Python 3 and `zstd`.
|
||||
|
||||
After preparation, ordinary `./gradlew :app:assembleRelease` builds can reuse the verified inputs. If native sources, component pins or staged files change, packaging stops with instructions to rerun the helper. Generated audio stays under `app/build/`; the tracked base bundle is never modified. `./gradlew -PskipRust=true :app:testDebugUnitTest` needs no native preparation. For an APK without store engines, use `DROIDDECK_SKIP_RUST=1 tools/build_local.sh`; it omits cached engine libraries too.
|
||||
```bash
|
||||
tools/build_local.sh
|
||||
```
|
||||
|
||||
For the prepared Windows checkout, run `./tools/run_windows.ps1` (optionally with `-Serial <adb-serial>`), or select **DroidDeck XR** in Android Studio and run the **app** module on the connected phone. Machine-specific options live in the ignored `local.properties`: `droiddeck.python` selects a Python executable, `droiddeck.skipRust=true` omits the optional store download engines, and `droiddeck.debugApplicationIdSuffix=.xr` installs **DroidDeck XR Dev** alongside the signed release. The development app has its own runtime and Steam login. The local Java selection is in `.gradle/config.properties`.
|
||||
The APK lands in `app/build/outputs/apk/release/`. Install it with `tools/deploy_local.sh`. After the first run, `./gradlew :app:assembleRelease` reuses the prepared inputs. Unit tests run with `./gradlew -PskipRust=true :app:testDebugUnitTest`, and the helper and preload suite with `bash tools/test_local.sh`.
|
||||
|
||||
`python tools/prepare_windows_runtime.py` restores this checkout's audited runtime inputs from the pinned CI APK, three locally rebuilt preload libraries, and the checksum-pinned Gamescope archive in `build/windows-setup/`. Start Docker Desktop's Linux engine first: preparation now rebuilds DroidDeck's ARM64 VR driver and Vulkan layer from current source and runs their native regression tests. The compiler image is built automatically on first use. Vulkan headers come from the NDK beside `--llvm-strip`, or from an explicit `--vk-include <NDK-sysroot-include>` directory.
|
||||
|
||||
To reuse that build, pass `--rebuilt-vr build/windows-setup/vr`. Preparation verifies its `vr-build.json` against the current Git revision, source files, Vulkan headers, output checksums, and ARM64 architecture; missing or stale builds fail instead of falling back to the donor's VR libraries. The script checks the actual donor CI merge tree, still rejects unrelated unaudited runtime changes, and records component provenance in `app/build/windows-runtime-provenance.json`. Preserve these ignored preparation files when rebuilding locally; `clean` removes the prepared assets and their verification manifest.
|
||||
|
||||
Run the helper and preload regression suite with `bash tools/test_local.sh`. On macOS it runs in Linux through Docker, matching the helpers' runtime and CI instead of compiling Linux preloads against macOS headers.
|
||||
On Windows, see `tools/run_windows.ps1` and `tools/prepare_windows_runtime.py`.
|
||||
|
||||
## Limits
|
||||
|
||||
Compatibility and performance vary by device; hardware validation is limited. Desktop compositing uses software rendering. Firefox sandboxing is reduced under proot. Logs are kept app-private (`files/logs/`, the last 30 sessions); **Share logs** packs the newest session, with the stores and tool logs, into one scrubbed zip.
|
||||
Compatibility and performance vary by device. Desktop compositing is software rendered, and Firefox sandboxing is reduced under proot.
|
||||
|
||||
## 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-<id>.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/<pid>/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 isLine truncated
|
||||
DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. VITURE, RayNeo, XREAL, Rokid, REDMAGIC, Nintendo Switch and Joy-Con are trademarks of their owners. This project is not affiliated with any of them.
|
||||
|
||||
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.
|
||||
<details>
|
||||
<summary><b>Runtime, Wine and Proton</b></summary>
|
||||
|
||||
Joy-Con VR controllers port the arm model of Google's [Google VR SDK for Unity](https://github.com/googlevr/gvr-unity-sdk) (Apache-2.0), adapt the hand skeleton of Valve's [OpenVR](https://github.com/ValveSoftware/openvr) `handskeletonsimulation` sample (BSD-3-Clause), which follows Moshi Turner's hand simulation in [Monado](https://gitlab.freedesktop.org/monado/monado), and use the Index controller offsets from Monado's `vive_poses.c` (BSL-1.0). Joy-Con behaviour was researched in Linux's [hid-nintendo](https://github.com/torvalds/linux/blob/master/drivers/hid/hid-nintendo.c) driver by Daniel J. Ogorchock, [@dekuNukem](https://github.com/dekuNukem)'s [Nintendo_Switch_Reverse_Engineering](https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering), [SDL](https://github.com/libsdl-org/SDL) and the Android Open Source Project, and checked against [ALVR](https://github.com/alvr-org/ALVR), [OpenComposite](https://gitlab.com/znixian/OpenOVR), [PSMoveSteamVRBridge](https://github.com/HipsterSloth/PSMoveSteamVRBridge), [@F8LEFT](https://github.com/F8LEFT)'s [JoyConVr](https://github.com/F8LEFT/JoyConVr), [@krnelpan1c](https://github.com/krnelpan1c)'s [Daydream-Controller-SteamVR](https://github.com/krnelpan1c/Daydream-Controller-SteamVR), [@yoyobuae](https://github.com/yoyobuae)'s [joyconvr](https://github.com/yoyobuae/joyconvr), [Moonlight](https://github.com/moonlight-stream/moonlight-android) and [Dolphin](https://github.com/dolphin-emu/dolphin); see [docs/third-party/joycon](docs/third-party/joycon/README.md). Nintendo Switch and Joy-Con are trademarks of Nintendo; this project is not affiliated with Nintendo.
|
||||
- Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05.
|
||||
- mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)).
|
||||
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT). FEX's code disk cache was checked in its source.
|
||||
- x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence.
|
||||
- x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes.
|
||||
- `WriteProcessMemory` hooks fall back to `/proc/<pid>/mem` the way [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` did before Wine 11.
|
||||
- Wine write watches use userfaultfd support in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/ntdll/unix/virtual.c` (LGPL-2.1-or-later). libblsession supplies the arm64 syscall number and answers `PAGEMAP_SCAN` from `/proc/self/pagemap`.
|
||||
- libblsession runs Wine's arm64 `SIGUSR2` context handler (`dlls/ntdll/unix/signal_arm64.c`, LGPL-2.1-or-later) in place on a frame laid out like [Linux](https://github.com/torvalds/linux)'s `arch/arm64/kernel/signal.c`, and serves `fill_vm_counters` in `dlls/ntdll/unix/process.c` the kernel's own `/proc/<pid>/status`.
|
||||
- droiddeck-ntsync follows the [Linux](https://github.com/torvalds/linux) ntsync semantics in `Documentation/userspace-api/ntsync.rst` (GPL-2.0).
|
||||
- The proot fast path orders bindings like [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later).
|
||||
- Games use [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's per render pass memory choice. The Steam client keeps `TU_DEBUG=sysmem`.
|
||||
- Black Ops III and Dark Souls Remastered start without [umu-protonfixes](https://github.com/Open-Wine-Components/umu-protonfixes) (BSD-2-Clause), whose `311210.py` and `570940.py` fail under ARM64 Proton.
|
||||
- [ReSkate](https://github.com/Dingo-Shenanigans/ReSkate) (GPL-3.0) by Dingo Shenanigans uses the launch option from its README and D3D12 feature level 12_1.
|
||||
- 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).
|
||||
|
||||
Camera hand tracking runs Google's [MediaPipe](https://github.com/google-ai-edge/mediapipe) Tasks Vision library with its Pose Landmarker (Lite) model, BlazePose GHUM 3D, and its Hand Landmarker model (all Apache-2.0), on frames from AndroidX [CameraX](https://developer.android.com/jetpack/androidx/releases/camera) (Apache-2.0); MediaPipe's usage reports are switched off. The design was checked against [@F8LEFT](https://github.com/F8LEFT)'s [JoyConVr](https://github.com/F8LEFT/JoyConVr) camera app (MIT), and the short Joy-Con movements follow the accelerometer mode of the [Google VR SDK for Unity](https://github.com/googlevr/gvr-unity-sdk)'s arm model, Eric Foxlin's zero-velocity updates and Frosio, Pedersini and Borghese's accelerometer autocalibration, and the camera and Joy-Con are joined by a Kalman filter (R. E. Kalman, 1960). Bare camera hands take their gestures after [ALVR](https://github.com/alvr-org/ALVR)'s `hand_gestures.rs` (MIT) and Meta Quest's menu pinch, with distances checked on photos from the [HaGRID](https://github.com/hukenovs/hagrid) gesture set (CC BY-SA 4.0, not included), fit the palm with Horn's quaternion method (1987) and smooth it with the 1€ filter (Casiez, Roussel and Vogel, 2012); the white glove model follows Valve's OpenVR render model reference and Index controller poses, is meshed with surface nets (Gibson, 1998; Mikola Lysenko) and blends and shades it with Inigo Quilez's smooth minimum and distance-field ambient occlusion, porting his polygon distance (MIT); see [docs/third-party/handtracking](docs/third-party/handtracking/README.md).
|
||||
</details>
|
||||
|
||||
The Store installs and runs apps with [Flatpak](https://github.com/flatpak/flatpak) (LGPL-2.1). Its sandbox goes through DroidDeck's own bubblewrap shim, which follows how Flatpak hands bwrap its environment. Chromium and Electron apps from Flathub start their browser processes through [zypak](https://github.com/refi64/zypak) by [@refi64](https://github.com/refi64) (BSD-3-Clause); its source was read to see that it always spawns them through Flatpak's spawn portal, which is why DroidDeck starts them directly without Chromium's sandbox instead.
|
||||
<details>
|
||||
<summary><b>Stores</b></summary>
|
||||
|
||||
Remote Play from a PC to the arm64 Steam client goes through a stand-in for the V4L2 decoder and the libdrm dumb buffers that Steam's `streaming_client` expects: each frame is decoded by Android's MediaCodec through the app, or by the [FFmpeg](https://ffmpeg.org) (LGPL-2.1-or-later) that ships in Steam's own runtime, into dma-heap buffers that its Vulkan renderer imports. The Qualcomm low-latency decoder settings follow [Moonlight](https://github.com/moonlight-stream/moonlight-android) (GPL-3.0).
|
||||
- Epic Games and GOG build on [Phobos](https://github.com/phobos665)'s adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl). GOG install script registry entries are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher) (GPL-3.0) reads them.
|
||||
- Epic's official Linux launcher preview runs through FEX. That setup is outside Epic's listed Linux support.
|
||||
- Battle.net is by [@kayakyakr](https://github.com/kayakyakr). It runs Blizzard's own client in Proton (downloaded from Blizzard, not included) and shows key art from the [Battle.net Shop](https://shop.battle.net). Without Steam, its games see the pad as an Xbox 360 controller via `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`.
|
||||
- Battle.net installs drive Blizzard's Agent the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) does, with requests from [wowdev.wiki](https://wowdev.wiki/Agent). Read without taking code: [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader.
|
||||
- Xbox games load [@domsvoboda](https://github.com/domsvoboda)'s [xodus-nexus](https://github.com/domsvoboda/xodus-nexus) modules (LGPL-2.1-or-later), including `wintypes.dll`. Minecraft's GameInput setup was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT).
|
||||
- The itch.io butler pack ships butler's `7z.so`, itch.io's build of [7-Zip](https://www.7-zip.org) by Igor Pavlov (LGPL-2.1, unRAR restriction on RAR code), unmodified. Other archives use Apache Commons Compress and the runtime's bsdtar (libarchive).
|
||||
- The Store uses [Flatpak](https://github.com/flatpak/flatpak) (LGPL-2.1) through DroidDeck's own bubblewrap shim. Chromium and Electron apps start directly, since [zypak](https://github.com/refi64/zypak) by [@refi64](https://github.com/refi64) (BSD-3-Clause) always uses Flatpak's spawn portal.
|
||||
|
||||
Steam's Browse buttons open a GTK 3 file chooser through PyGObject (LGPL-2.1-or-later). It runs under Steam's own `reaper` with Steam's app ID, which [gamescope](https://github.com/ValveSoftware/gamescope) (BSD-2-Clause) reads from the process tree (`GetAppIdFromReaper` in `src/Utils/Process.cpp`) to show it over Steam.
|
||||
</details>
|
||||
|
||||
Black Ops III and Dark Souls Remastered start without [umu-protonfixes](https://github.com/Open-Wine-Components/umu-protonfixes) (BSD-2-Clause), whose fixes for them (`311210.py` sets ALSA audio, `570940.py` installs VC++ 2017) fail under ARM64 Proton.
|
||||
<details>
|
||||
<summary><b>Audio, video and HUD</b></summary>
|
||||
|
||||
- Steam 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`.
|
||||
- The DroidDeck HUD is [@The412Banner](https://github.com/The412Banner)'s [FusionHUD](https://github.com/The412Banner/FusionHUD) (GPL-3.0 with an attribution term). Its readings match Valve's [MangoHud](https://github.com/flightlessmango/MangoHud) build (MIT), with frame times from gamescope patch 0125.
|
||||
- LSFG frame generation comes from Camille LaVey and the [Eden](https://eden-emu.dev) project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported 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.
|
||||
- Remote Play decodes through Android's MediaCodec or the [FFmpeg](https://ffmpeg.org) (LGPL-2.1-or-later) in Steam's runtime. Qualcomm low latency settings follow [Moonlight](https://github.com/moonlight-stream/moonlight-android) (GPL-3.0).
|
||||
- [PipeWire](https://gitlab.freedesktop.org/pipewire/pipewire) (MIT) sockets use the settings in its `module-access.c`, and [WirePlumber](https://gitlab.freedesktop.org/pipewire/wireplumber) (MIT) keeps those clients at full permissions.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Desktop</b></summary>
|
||||
|
||||
- The KDE pacman repository snapshots [Arch Linux ARM](https://archlinuxarm.org) and installs with [pacman](https://gitlab.archlinux.org/pacman/pacman) (GPL-2.0-or-later).
|
||||
- [KWin](https://invent.kde.org/plasma/kwin) (GPL-2.0-or-later) is patched to pass on the scroll data its `wayland_backend.cpp` leaves as a TODO.
|
||||
- Read without taking code: [Qt](https://code.qt.io/cgit/qt/qtbase.git)'s `qwaylandinputdevice.cpp` and `qguiapplication.cpp`, [Konsole](https://invent.kde.org/utilities/konsole)'s `TerminalDisplay.cpp`, and [Mesa](https://gitlab.freedesktop.org/mesa/mesa)'s `u_threaded_context.c` and `zink_resource.c`.
|
||||
- The Steam Keyboard window rule follows Valve's `steamdeck-kde-presets` with [Bazzite](https://github.com/ublue-os/bazzite)'s `0001-steam-virtual-keyboard.patch`.
|
||||
- Steam's Browse buttons open a GTK 3 file chooser via PyGObject (LGPL-2.1-or-later), shown over Steam by [gamescope](https://github.com/ValveSoftware/gamescope) (BSD-2-Clause) through `GetAppIdFromReaper`.
|
||||
- The AYN Odin 2 phantom second display was confirmed by [@SapphireRhodonite](https://github.com/SapphireRhodonite)'s [WatermelonDS 0.0.5](https://github.com/SapphireRhodonite/WatermelonDS/releases/tag/0.0.5) notes and [iiSU #363](https://github.com/iisu-network/iiSU/issues/363), without taking their code.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Smart glasses</b></summary>
|
||||
|
||||
- Builds on WinNative's VITURE work. Protocol checked against [@wheaney](https://github.com/wheaney)'s [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver), [@badicsalex](https://github.com/badicsalex)'s [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) and [go-macos/iokit](https://pkg.go.dev/github.com/go-macos/iokit/viture). The optional VITURE SDK is not included.
|
||||
- RayNeo 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 references XRLinuxDriver and [xrealOneDeviceKit](https://github.com/wheaney/xrealOneDeviceKit) by @wheaney, [@rohitsangwan01](https://github.com/rohitsangwan01)'s [xreal_one_driver](https://github.com/rohitsangwan01/xreal_one_driver) (MIT) and [@0xcaff](https://github.com/0xcaff)'s [xr-tools](https://github.com/0xcaff/xr-tools).
|
||||
- Rokid follows ar-drivers-rs, @badicsalex's [Void Computing write-ups](https://voidcomputing.hu/blog/worse-better-prettier/) and Monado's Rokid driver.
|
||||
- REDMAGIC 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).
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>VR, Joy-Con and hand tracking</b></summary>
|
||||
|
||||
- Joy-Con VR ports the arm model from Google's [GVR SDK for Unity](https://github.com/googlevr/gvr-unity-sdk) (Apache-2.0) and adapts the hand skeleton from Valve's [OpenVR](https://github.com/ValveSoftware/openvr) `handskeletonsimulation` sample (BSD-3-Clause), which follows Moshi Turner's work in Monado. Index offsets come from Monado's `vive_poses.c` (BSL-1.0).
|
||||
- Joy-Con research: Linux's [hid-nintendo](https://github.com/torvalds/linux/blob/master/drivers/hid/hid-nintendo.c) by Daniel J. Ogorchock, [@dekuNukem](https://github.com/dekuNukem)'s [Nintendo_Switch_Reverse_Engineering](https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering), [SDL](https://github.com/libsdl-org/SDL) and AOSP. Checked against [ALVR](https://github.com/alvr-org/ALVR), [OpenComposite](https://gitlab.com/znixian/OpenOVR), [PSMoveSteamVRBridge](https://github.com/HipsterSloth/PSMoveSteamVRBridge), [@F8LEFT](https://github.com/F8LEFT)'s [JoyConVr](https://github.com/F8LEFT/JoyConVr), [@krnelpan1c](https://github.com/krnelpan1c)'s [Daydream-Controller-SteamVR](https://github.com/krnelpan1c/Daydream-Controller-SteamVR), [@yoyobuae](https://github.com/yoyobuae)'s [joyconvr](https://github.com/yoyobuae/joyconvr), [Moonlight](https://github.com/moonlight-stream/moonlight-android) and [Dolphin](https://github.com/dolphin-emu/dolphin). See [docs/third-party/joycon](docs/third-party/joycon/README.md).
|
||||
- Camera hand tracking runs Google's [MediaPipe](https://github.com/google-ai-edge/mediapipe) Pose Landmarker (Lite), BlazePose GHUM 3D and Hand Landmarker (Apache-2.0) on [CameraX](https://developer.android.com/jetpack/androidx/releases/camera) frames (Apache-2.0), with usage reports off. Checked against JoyConVr's camera app (MIT).
|
||||
- Tracking math: the GVR arm model's accelerometer mode, Eric Foxlin's zero velocity updates, Frosio, Pedersini and Borghese's accelerometer autocalibration, a Kalman filter (Kalman, 1960), Horn's quaternion method (1987) and the 1€ filter (Casiez, Roussel and Vogel, 2012).
|
||||
- Gestures follow [ALVR](https://github.com/alvr-org/ALVR)'s `hand_gestures.rs` (MIT) and Meta Quest's menu pinch, tuned on [HaGRID](https://github.com/hukenovs/hagrid) photos (CC BY-SA 4.0, not included).
|
||||
- The glove model follows OpenVR's render model reference, is meshed with surface nets (Gibson, 1998; Mikola Lysenko), and uses Inigo Quilez's smooth minimum, distance field ambient occlusion and polygon distance (MIT). See [docs/third-party/handtracking](docs/third-party/handtracking/README.md).
|
||||
|
||||
</details>
|
||||
|
||||
## Star history
|
||||
|
||||
<a href="https://www.star-history.com/#Droid-Deck/DroidDeck&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Droid-Deck/DroidDeck&type=Date&theme=dark">
|
||||
<img alt="Star history chart" src="https://api.star-history.com/svg?repos=Droid-Deck/DroidDeck&type=Date" width="100%">
|
||||
</picture>
|
||||
</a>
|
||||
+9
-3
@@ -78,6 +78,10 @@ def escapedBuildLabel = buildLabel.replace('\\', '\\\\').replace('"', '\\"')
|
||||
def sourceCommit = providers.environmentVariable('DROIDDECK_SOURCE_COMMIT').getOrNull()
|
||||
?: providers.environmentVariable('GITHUB_SHA').getOrNull() ?: gitValue(['rev-parse', 'HEAD']) ?: ''
|
||||
def prNumber = (providers.environmentVariable('DROIDDECK_PR_NUMBER').getOrNull() ?: '0').with { it.isInteger() ? it : '0' }
|
||||
def prTitle = providers.environmentVariable('DROIDDECK_PR_TITLE').getOrNull() ?: ''
|
||||
def buildBranch = providers.environmentVariable('GITHUB_HEAD_REF').getOrNull()?.trim()
|
||||
?: gitValue(['branch', '--show-current']) ?: ''
|
||||
def escapeJava = { String value -> value.replace('\\', '\\\\').replace('"', '\\"').replace('\n', ' ').replace('\r', ' ') }
|
||||
def ciBuild = providers.environmentVariable('GITHUB_ACTIONS').getOrNull() == 'true'
|
||||
def releaseSigner = rootProject.file('keystore/release-signer.sha256').text.trim()
|
||||
def commitTime = (gitValue(['show', '-s', '--format=%ct', '--end-of-options', sourceCommit]) ?: '0').with { it.isLong() ? it : '0' }
|
||||
@@ -90,7 +94,7 @@ def trackingPack = rootProject.file('tools/packs/tracking/release.env').readLine
|
||||
def prootPackPin = rootProject.file('tools/packs/proot/release.env').readLines()
|
||||
.findAll { it.contains('=') && !it.startsWith('#') }
|
||||
.collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] }
|
||||
def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet'].collectEntries { name ->
|
||||
def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler'].collectEntries { name ->
|
||||
def pack = file("build/packs/${name}.tar.zst")
|
||||
if (!pack.isFile()) {
|
||||
if (ciBuild) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs")
|
||||
@@ -130,11 +134,13 @@ android {
|
||||
applicationId "com.droiddeck.launcher"
|
||||
minSdkVersion 26
|
||||
targetSdkVersion 28
|
||||
versionCode 16
|
||||
versionName "0.6.7"
|
||||
versionCode 17
|
||||
versionName "0.6.9"
|
||||
buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\""
|
||||
buildConfigField "String", "SOURCE_COMMIT", "\"${sourceCommit}\""
|
||||
buildConfigField "int", "PR_NUMBER", "${prNumber}"
|
||||
buildConfigField "String", "PR_TITLE", "\"${escapeJava(prTitle)}\""
|
||||
buildConfigField "String", "BUILD_BRANCH", "\"${escapeJava(buildBranch)}\""
|
||||
buildConfigField "boolean", "CI_BUILD", "${ciBuild}"
|
||||
buildConfigField "String", "RELEASE_SIGNER", "\"${releaseSigner}\""
|
||||
buildConfigField "long", "COMMIT_TIME", "${commitTime}L * 1000L"
|
||||
|
||||
@@ -69,6 +69,20 @@
|
||||
</intent-filter>
|
||||
<meta-data android:name="android.accessibilityservice" android:resource="@xml/home_button_service" />
|
||||
</service>
|
||||
<service android:name=".session.BottomNotificationListener"
|
||||
android:label="@string/bottom_notifications_listener"
|
||||
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.service.notification.NotificationListenerService" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
<receiver android:name=".core.ShortcutsListingReceiver" android:exported="false"
|
||||
android:process=":shortcuts_sync">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
<meta-data android:name="com.oculus.supportedDevices" android:value="quest2|quest3|quest3s" />
|
||||
<activity android:name=".QuestXrActivity" android:exported="true" android:launchMode="singleTask"
|
||||
android:permission="android.permission.DUMP"
|
||||
@@ -99,6 +113,7 @@
|
||||
android:exported="true"
|
||||
android:screenOrientation="user"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density|keyboard|keyboardHidden|navigation">
|
||||
<layout android:defaultWidth="1024dp" android:defaultHeight="640dp" />
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
|
||||
@@ -2124,7 +2124,21 @@ void droiddeck_stream_frame(AHardwareBuffer *ahb) {
|
||||
|
||||
unsigned droiddeck_stream_frames(void) { return atomic_load(&g_stream_frames); }
|
||||
|
||||
static int64_t g_scene_due_ns;
|
||||
|
||||
static int scene_held_for_limit(int64_t now, int64_t due, int limit, int unpaced) {
|
||||
if (limit <= 0 || unpaced || due <= 0) return 0;
|
||||
return now < due - 1000000LL;
|
||||
}
|
||||
|
||||
static int64_t scene_next_due(int64_t now, int64_t due, int limit) {
|
||||
if (limit <= 0) return 0;
|
||||
const int64_t interval = 1000000000LL / limit;
|
||||
return due > 0 && now - due < interval ? due + interval : now + interval;
|
||||
}
|
||||
|
||||
static void render_scene(void) {
|
||||
g_scene_due_ns = scene_next_due(now_ns(), g_scene_due_ns, g_fps_limit);
|
||||
if (atomic_load(&g_stream_on)) { g_dirty_since_ns = 0; render_stream(); return; }
|
||||
struct draw_list dl = {0};
|
||||
struct surface *s;
|
||||
@@ -2302,7 +2316,9 @@ static void render_scene(void) {
|
||||
|
||||
static int on_fallback_timer(void *data) {
|
||||
g_fallback_armed = 0;
|
||||
if (g_dirty) render_scene();
|
||||
if (!g_dirty) return 0;
|
||||
if (scene_held_for_limit(now_ns(), g_scene_due_ns, g_fps_limit, g_release_unpaced)) schedule_render();
|
||||
else render_scene();
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -2377,6 +2393,7 @@ static void on_vsync(int64_t frame_time_ns) {
|
||||
g_tick_held = 1;
|
||||
return;
|
||||
}
|
||||
if (g_dirty && scene_held_for_limit(now, g_scene_due_ns, g_fps_limit, g_release_unpaced)) return;
|
||||
if (g_dirty && !scene_waits_for_game(now)) render_scene();
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,8 @@ class App : Application() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
com.droiddeck.launcher.ui.Themes.loadGradient(this)
|
||||
com.droiddeck.launcher.ui.BuildWatermark.install(this)
|
||||
HomeApp.trackRecents(this)
|
||||
// Helper processes must not initialize the main USB provider or guest graphics context.
|
||||
val process = if (android.os.Build.VERSION.SDK_INT >= 28) Application.getProcessName()
|
||||
else (getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)
|
||||
@@ -34,8 +36,10 @@ class App : Application() {
|
||||
com.droiddeck.launcher.stores.StoresState.init(this)
|
||||
return
|
||||
}
|
||||
if (process == "$packageName:vr_recovery" || process == "$packageName:rgb_diagnostic") return
|
||||
if (process == "$packageName:vr_recovery" || process == "$packageName:rgb_diagnostic" ||
|
||||
process == "$packageName:shortcuts_sync") return
|
||||
CrashHandler.install(this)
|
||||
com.droiddeck.launcher.core.SteamIntegration.syncShortcutsListing(this)
|
||||
com.droiddeck.launcher.session.QuestExperimental.initialize(this)
|
||||
com.droiddeck.launcher.session.SessionPrefs.applyNtsyncDefault(this)
|
||||
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
|
||||
|
||||
@@ -109,6 +109,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var ready by mutableStateOf(false)
|
||||
private var removalPending by mutableStateOf(false)
|
||||
private var available by mutableStateOf<LinuxRuntimeInstaller.Release?>(null)
|
||||
private var catalogFresh = false
|
||||
private var componentsQueueBusy by mutableStateOf(false)
|
||||
private var busy by mutableStateOf(false)
|
||||
private var stage by mutableStateOf("")
|
||||
private var percent by mutableIntStateOf(-1)
|
||||
@@ -193,7 +195,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var navRequest by mutableStateOf<String?>(null)
|
||||
private var storesShowMature by mutableStateOf(false)
|
||||
private var storesSort by mutableStateOf(SessionPrefs.STORES_SORTS.first())
|
||||
private var storesView by mutableStateOf(SessionPrefs.STORES_VIEWS.first())
|
||||
private var storesView by mutableStateOf(SessionPrefs.DEFAULT_STORES_VIEW)
|
||||
private var mic by mutableStateOf(false)
|
||||
private var wifiDiscovery by mutableStateOf(false)
|
||||
private var wifiDiscoveryPermission by mutableStateOf(false)
|
||||
@@ -322,7 +324,10 @@ class FrontEndActivity : ComponentActivity() {
|
||||
SteamIntegration.Feature.SHORTCUTS -> {
|
||||
if (!integrationState.shortcuts) shortcutsTried = true
|
||||
if (!HomeApp.isDefault(this)) configureIntegration(SteamIntegration.Feature.HOME)
|
||||
else integrationSettings(SteamIntegration.shortcutSettings(this), android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS)
|
||||
else {
|
||||
SteamIntegration.setShortcutsListed(this, true)
|
||||
integrationSettings(SteamIntegration.shortcutSettings(this), android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -537,6 +542,11 @@ class FrontEndActivity : ComponentActivity() {
|
||||
override fun onDisplayRemoved(displayId: Int) = refreshSecondScreenDisplays()
|
||||
override fun onDisplayChanged(displayId: Int) = refreshSecondScreenDisplays()
|
||||
}
|
||||
private val secondScreenTouchListener = object : android.hardware.input.InputManager.InputDeviceListener {
|
||||
override fun onInputDeviceAdded(deviceId: Int) = refreshSecondScreenDisplays()
|
||||
override fun onInputDeviceRemoved(deviceId: Int) = refreshSecondScreenDisplays()
|
||||
override fun onInputDeviceChanged(deviceId: Int) = refreshSecondScreenDisplays()
|
||||
}
|
||||
|
||||
private val homeRoleRequest = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
|
||||
refreshHomeAppState()
|
||||
@@ -666,7 +676,23 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var shortcutPicker by mutableStateOf(false)
|
||||
private var shortcutLibraryScanning by mutableStateOf(false)
|
||||
@Volatile private var libraryScanGeneration = 0
|
||||
@Volatile private var lastComponentRestore = 0L
|
||||
@Volatile private var componentRestoreRetry = false
|
||||
private val componentRestoreLock = Any()
|
||||
|
||||
private fun retryComponentRestore() {
|
||||
val run = synchronized(componentRestoreLock) {
|
||||
componentRestoreRetry = false
|
||||
val now = android.os.SystemClock.elapsedRealtime()
|
||||
(!isDestroyed && now - lastComponentRestore >= COMPONENT_RESTORE_MS).also { if (it) lastComponentRestore = now }
|
||||
}
|
||||
if (run) Thread({
|
||||
runCatching { com.droiddeck.launcher.frontend.AutoComponents.restoreMissing(this) }.onFailure { Log.w(TAG, "components: restore failed", it) }
|
||||
}, "components-restore").start()
|
||||
}
|
||||
private var pendingGameLink: String? = null
|
||||
private var gameLinkReading = false
|
||||
private var gameLinkTried = false
|
||||
private var gameSyncFolder by mutableStateOf<String?>(null)
|
||||
private fun pickGameExport(game: Library.SteamGame?) {
|
||||
onSavePicked = { folder ->
|
||||
@@ -707,16 +733,25 @@ class FrontEndActivity : ComponentActivity() {
|
||||
shortcutLibraryScanning = true
|
||||
} else shortcutLibraryScanning = false
|
||||
pendingGameLink = null
|
||||
gameLinkReading = false
|
||||
gameLinkTried = false
|
||||
if (GameLaunchIntent.accepts(request.action)) {
|
||||
gameLinkReading = true
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
|
||||
val copy = Intent(request)
|
||||
Thread({
|
||||
val id = GameLaunchIntent.read(this, copy)
|
||||
ui.post {
|
||||
if (intent === request && !isDestroyed) {
|
||||
gameLinkReading = false
|
||||
pendingGameLink = id
|
||||
if (id == null) {
|
||||
syncDualPanel()
|
||||
android.widget.Toast.makeText(this, R.string.game_link_invalid, android.widget.Toast.LENGTH_LONG).show()
|
||||
} else refresh()
|
||||
} else {
|
||||
handleGameLink(steamGames, scanned = false)
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
}, "game-launch-file").start()
|
||||
@@ -919,15 +954,21 @@ class FrontEndActivity : ComponentActivity() {
|
||||
ui.postDelayed(poll, SESSION_SWITCH_POLL_MS)
|
||||
}
|
||||
|
||||
private fun handleGameLink(games: List<Library.SteamGame>) {
|
||||
private fun handleGameLink(games: List<Library.SteamGame>, scanned: Boolean = true) {
|
||||
if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) return
|
||||
val id = pendingGameLink ?: return
|
||||
if (!scanned && games.none { it.gameIdString == id }) return
|
||||
gameLinkTried = true
|
||||
ui.postDelayed({
|
||||
if (!isDestroyed && lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) syncDualPanel()
|
||||
}, LINK_PANEL_MS)
|
||||
val game = games.firstOrNull { it.gameIdString == id }
|
||||
if (game == null) {
|
||||
pendingGameLink = null
|
||||
intent.data = null
|
||||
intent.action = Intent.ACTION_MAIN
|
||||
intent.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
|
||||
syncDualPanel()
|
||||
android.widget.Toast.makeText(this, R.string.game_link_missing, android.widget.Toast.LENGTH_LONG).show()
|
||||
} else if (launchGame(game, returnHome = true)) {
|
||||
pendingGameLink = null
|
||||
@@ -1498,6 +1539,9 @@ class FrontEndActivity : ComponentActivity() {
|
||||
super.onNewIntent(intent)
|
||||
setIntent(intent)
|
||||
if (intent.action == SteamIntegration.ACTION_SETUP) {
|
||||
gameLinkReading = false
|
||||
pendingGameLink = null
|
||||
syncDualPanel()
|
||||
readIntegrationIntent(intent)
|
||||
return
|
||||
}
|
||||
@@ -1530,9 +1574,28 @@ class FrontEndActivity : ComponentActivity() {
|
||||
startSession(Intent(this, SessionActivity::class.java).putExtra(SessionActivity.EXTRA_STEAMVR, steamVr), steamSession = true)
|
||||
}
|
||||
|
||||
@Suppress("OVERRIDE_DEPRECATION")
|
||||
override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) {
|
||||
val outside = com.droiddeck.launcher.ui.DualScreenPanel.shownOn >= 0 &&
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.opensOutside(packageName, intent.component?.packageName ?: intent.`package` ?: intent.resolveActivity(packageManager)?.packageName)
|
||||
if (outside) {
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, true)
|
||||
window.decorView.postDelayed({ if (hasWindowFocus()) com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false) }, 1500)
|
||||
}
|
||||
try {
|
||||
super.startActivityForResult(intent, requestCode, options)
|
||||
} catch (e: RuntimeException) {
|
||||
if (outside) com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
if (hasFocus) applyLauncherFullscreen()
|
||||
if (hasFocus) {
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
|
||||
applyLauncherFullscreen()
|
||||
}
|
||||
}
|
||||
|
||||
private fun applyLauncherFullscreen() {
|
||||
@@ -1591,15 +1654,19 @@ class FrontEndActivity : ComponentActivity() {
|
||||
|
||||
override fun onPause() {
|
||||
compatLaunchVisible = false
|
||||
if (android.os.Build.VERSION.SDK_INT >= 29) com.droiddeck.launcher.ui.DualScreenPanel.ownerPaused(taskId, true)
|
||||
super.onPause()
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
compatLaunchVisible = true
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.ownerPaused(taskId, false)
|
||||
orientation = SessionPrefs.orientation(this)
|
||||
launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
||||
requestedOrientation = launcherOrientation
|
||||
SteamIntegration.syncShortcutsListing(this)
|
||||
refreshWifiDiscovery()
|
||||
com.droiddeck.launcher.stores.StoresState.refresh(this)
|
||||
com.droiddeck.launcher.stores.StoresState.libraryListener = { refreshAddedGames(); refresh() }
|
||||
@@ -1614,14 +1681,21 @@ class FrontEndActivity : ComponentActivity() {
|
||||
drivers.checkOnOpen()
|
||||
resumeInterruptedPackages()
|
||||
protons.checkUpdates()
|
||||
if (!SessionState.running) Thread({
|
||||
val applied = runCatching { ComponentsManager.applyQueued(this) }.getOrDefault(emptyList())
|
||||
if (applied.isNotEmpty()) ui.post {
|
||||
android.widget.Toast.makeText(this, getString(R.string.main_applied, applied.joinToString(", ")), android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
ui.post { if (showComponents) components.refreshComponents() }
|
||||
}, "components-queue").start()
|
||||
else if (showComponents) components.refreshComponents()
|
||||
catalogFresh = false
|
||||
if (!SessionState.running && !componentsQueueBusy && !LinuxRuntimeInstaller.isBusy()) {
|
||||
componentsQueueBusy = true
|
||||
Thread({
|
||||
val applied = runCatching { ComponentsManager.applyQueued(this) }.getOrDefault(emptyList())
|
||||
if (applied.isNotEmpty()) ui.post {
|
||||
android.widget.Toast.makeText(this, getString(R.string.main_applied, applied.joinToString(", ")), android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
ui.post {
|
||||
componentsQueueBusy = false
|
||||
if (showComponents) components.refreshComponents()
|
||||
autoUpdateRuntime()
|
||||
}
|
||||
}, "components-queue").start()
|
||||
} else if (showComponents) components.refreshComponents()
|
||||
oscMode = SessionPrefs.oscMode(this)
|
||||
refreshController()
|
||||
refreshHomeAppState()
|
||||
@@ -1644,6 +1718,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
addDataScheme("file")
|
||||
})
|
||||
displayManager.registerDisplayListener(secondScreenDisplayListener, ui)
|
||||
getSystemService(android.hardware.input.InputManager::class.java)?.registerInputDeviceListener(secondScreenTouchListener, ui)
|
||||
launcherStarted = true
|
||||
refreshSecondScreenDisplays()
|
||||
getSystemService(android.content.pm.LauncherApps::class.java).registerCallback(packageCallback, ui)
|
||||
@@ -1687,8 +1762,9 @@ class FrontEndActivity : ComponentActivity() {
|
||||
com.droiddeck.launcher.stores.StoresState.libraryListener = null
|
||||
com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = null
|
||||
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
|
||||
getSystemService(android.hardware.input.InputManager::class.java)?.unregisterInputDeviceListener(secondScreenTouchListener)
|
||||
launcherStarted = false
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.hide()
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
|
||||
flood = null
|
||||
returning = null
|
||||
floodProgress = 0f
|
||||
@@ -1723,8 +1799,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
// The launcher can itself be shown on a non-default display (DeX, an external monitor); that one is not a "second screen".
|
||||
val ownDisplayId = if (android.os.Build.VERSION.SDK_INT >= 30) display?.displayId ?: android.view.Display.DEFAULT_DISPLAY else @Suppress("DEPRECATION") windowManager.defaultDisplay.displayId
|
||||
dualScreenMode = SessionPrefs.dualScreenMode(this)
|
||||
secondScreenDisplays = if (dualScreenMode == com.droiddeck.launcher.input.DualScreen.MODE_OFF) emptyList()
|
||||
else SecondScreenDisplays.available(displayManager, ownDisplayId)
|
||||
secondScreenDisplays = SecondScreenDisplays.available(displayManager, ownDisplayId)
|
||||
dualScreenDevice = com.droiddeck.launcher.input.DualScreen.anyDisplay(displayManager, ownDisplayId) != null
|
||||
dualScreenLauncher = SessionPrefs.dualScreenLauncher(this)
|
||||
dualScreenControls = SessionPrefs.dualScreenSessionControls(this)
|
||||
@@ -1734,14 +1809,20 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
private fun syncDualPanel() {
|
||||
if (launchPending()) return
|
||||
if (launcherStarted && dualDisplayId >= 0) com.droiddeck.launcher.ui.DualScreenPanel.show(this, dualDisplayId, taskId)
|
||||
else com.droiddeck.launcher.ui.DualScreenPanel.hide()
|
||||
else com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
|
||||
}
|
||||
|
||||
private fun launchPending(): Boolean = gameLinkReading || (pendingGameLink != null && !gameLinkTried)
|
||||
|
||||
private fun launchAndroidApp(app: HomeApp.LaunchableApp, displayId: Int?) {
|
||||
val onOwnScreen = displayId == null || displayId == (display?.displayId ?: Display.DEFAULT_DISPLAY)
|
||||
if (onOwnScreen) com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, true)
|
||||
try {
|
||||
HomeApp.launch(this, app, displayId)
|
||||
} catch (_: Exception) {
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
|
||||
val label = secondScreenDisplays.firstOrNull { it.id == displayId }?.label
|
||||
val message = when {
|
||||
displayId == null || displayId == Display.DEFAULT_DISPLAY -> getString(R.string.android_app_open_failed_primary, app.label)
|
||||
@@ -2423,6 +2504,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
installed = LinuxRuntimeInstaller.installedVersion(this)
|
||||
ready = LinuxRuntime.isInstalled(this)
|
||||
removalPending = LinuxRuntimeInstaller.hasRemovalPending(this)
|
||||
ui.post { autoUpdateRuntime() }
|
||||
frameGenLabel = FrameGen.label(this)
|
||||
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
|
||||
logsEnabled = SessionPrefs.logsEnabled(this)
|
||||
@@ -2465,15 +2547,32 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
val scannedArch = SessionPrefs.activeSteamClientArch(this)
|
||||
val scannedX64 = scannedArch == "x86_64"
|
||||
val games = if (ready) Library.launchableGames(this, arch = scannedArch) else emptyList()
|
||||
val games = if (ready || com.droiddeck.launcher.runtime.LinuxRuntime.hasRootfs(this)) Library.launchableGames(this, arch = scannedArch) else emptyList()
|
||||
val all = games.distinctBy { it.gameId }
|
||||
if (ready && scanGeneration == libraryScanGeneration) com.droiddeck.launcher.frontend.LibraryCache.save(this, all, scannedX64)
|
||||
val endedSession = SessionState.sessionId.takeIf { !SessionState.running && it != null && it != componentSweepSession }
|
||||
if (ready && (!componentSweepDone || endedSession != null)) {
|
||||
val sweepDue = ready && (!componentSweepDone || endedSession != null)
|
||||
if (sweepDue) {
|
||||
componentSweepDone = true
|
||||
endedSession?.let { componentSweepSession = it }
|
||||
ui.postDelayed({ Thread({ com.droiddeck.launcher.frontend.AutoComponents.sweep(this, all) }, "components-sweep").start() }, 10_000)
|
||||
}
|
||||
val restoreDue = synchronized(componentRestoreLock) {
|
||||
val now = android.os.SystemClock.elapsedRealtime()
|
||||
val due = ready && (lastComponentRestore == 0L || now - lastComponentRestore >= COMPONENT_RESTORE_MS)
|
||||
if (due) {
|
||||
lastComponentRestore = now
|
||||
} else if (ready && !componentRestoreRetry) {
|
||||
componentRestoreRetry = true
|
||||
ui.postDelayed({ retryComponentRestore() }, (COMPONENT_RESTORE_MS - (now - lastComponentRestore)).coerceAtLeast(0L))
|
||||
}
|
||||
due
|
||||
}
|
||||
if (restoreDue || sweepDue) ui.postDelayed({
|
||||
Thread({
|
||||
if (restoreDue) runCatching { com.droiddeck.launcher.frontend.AutoComponents.restoreMissing(this) }.onFailure { Log.w(TAG, "components: restore failed", it) }
|
||||
if (sweepDue) com.droiddeck.launcher.frontend.AutoComponents.sweep(this, all)
|
||||
}, "components-restore").start()
|
||||
}, 10_000)
|
||||
ui.post {
|
||||
if (scanGeneration == libraryScanGeneration) {
|
||||
val current = steamGames.filter { it.library != Library.ADDED }.associateBy { it.appId }
|
||||
@@ -2567,7 +2666,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private fun runtimeChangesBlocked(): Boolean =
|
||||
busy || LinuxRuntimeInstaller.isBusy() || SessionState.running ||
|
||||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) ||
|
||||
protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null ||
|
||||
protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null || componentsQueueBusy ||
|
||||
components.compBusy != null || saveBusy != null || com.droiddeck.launcher.store.UserAppsState.working != null
|
||||
|
||||
private fun removeDesktop() {
|
||||
@@ -2627,15 +2726,32 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}, "runtime-operation").start()
|
||||
}
|
||||
|
||||
private fun autoUpdateRuntime() {
|
||||
val release = available?.takeIf { catalogFresh } ?: return
|
||||
if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED) || runtimeChangesBlocked() || removalPending) return
|
||||
if (release.version == installed || installed == null) return
|
||||
if (com.droiddeck.launcher.runtime.RuntimeAutoUpdate.claim(this, installed, release.version)) {
|
||||
Log.i(TAG, "runtime: updating $installed to ${release.version} by itself")
|
||||
install(release)
|
||||
}
|
||||
}
|
||||
|
||||
private fun checkCatalog() {
|
||||
val release = LinuxRuntimeInstaller.fetchRelease()
|
||||
Log.i(TAG, "catalog: " + (release?.version ?: "unreachable"))
|
||||
ui.post { if (release != null) available = release }
|
||||
ui.post {
|
||||
if (release == null) return@post
|
||||
available = release
|
||||
catalogFresh = true
|
||||
autoUpdateRuntime()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "MainActivity"
|
||||
private const val MEDIA_SETTLE_MS = 1500L
|
||||
private const val COMPONENT_RESTORE_MS = 60_000L
|
||||
private const val LINK_PANEL_MS = 1500L
|
||||
private const val SESSION_SWITCH_WAIT_MS = 30_000L
|
||||
private const val SESSION_SWITCH_POLL_MS = 250L
|
||||
private const val KEY_PENDING_SWITCH = "pending_switch"
|
||||
|
||||
@@ -147,8 +147,62 @@ object HomeApp {
|
||||
.getShortcutIconDrawable(info, context.resources.displayMetrics.densityDpi)?.toBitmap(px, px)
|
||||
}.getOrNull()
|
||||
|
||||
fun trackRecents(app: android.app.Application) {
|
||||
app.registerActivityLifecycleCallbacks(object : android.app.Application.ActivityLifecycleCallbacks {
|
||||
override fun onActivityCreated(activity: android.app.Activity, savedInstanceState: android.os.Bundle?) = Unit
|
||||
override fun onActivityStarted(activity: android.app.Activity) = Unit
|
||||
override fun onActivityResumed(activity: android.app.Activity) = syncRecents(activity)
|
||||
override fun onActivityPaused(activity: android.app.Activity) { if (activity is FrontEndActivity) syncRecents(activity) }
|
||||
override fun onActivityStopped(activity: android.app.Activity) = Unit
|
||||
override fun onActivitySaveInstanceState(activity: android.app.Activity, outState: android.os.Bundle) = Unit
|
||||
override fun onActivityDestroyed(activity: android.app.Activity) = Unit
|
||||
})
|
||||
}
|
||||
|
||||
private fun syncRecents(activity: android.app.Activity) =
|
||||
keepOutOfRecents(activity, activity is FrontEndActivity && !SessionState.running && isDefault(activity))
|
||||
|
||||
internal enum class RecentsStep { HIDE, SHOW, FORGET, NONE }
|
||||
|
||||
internal fun recentsStep(hidden: Boolean, owned: Boolean, excluded: Boolean): RecentsStep = when {
|
||||
hidden && !excluded -> RecentsStep.HIDE
|
||||
!hidden && owned && excluded -> RecentsStep.SHOW
|
||||
!hidden && owned -> RecentsStep.FORGET
|
||||
else -> RecentsStep.NONE
|
||||
}
|
||||
|
||||
fun keepOutOfRecents(activity: android.app.Activity, hidden: Boolean) {
|
||||
val prefs = activity.getSharedPreferences("home-recents", Context.MODE_PRIVATE)
|
||||
val owned = prefs.getStringSet("tasks", null).orEmpty()
|
||||
val id = activity.taskId.toString()
|
||||
if (!hidden && id !in owned) return
|
||||
runCatching {
|
||||
@Suppress("DEPRECATION")
|
||||
fun idOf(task: android.app.ActivityManager.AppTask) =
|
||||
if (Build.VERSION.SDK_INT >= 29) task.taskInfo.taskId else task.taskInfo.persistentId
|
||||
val tasks = activity.getSystemService(android.app.ActivityManager::class.java).appTasks
|
||||
val task = tasks.firstOrNull { idOf(it) == activity.taskId } ?: return
|
||||
val excluded = task.taskInfo.baseIntent.flags and Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS != 0
|
||||
val step = recentsStep(hidden, id in owned, excluded)
|
||||
if (step == RecentsStep.NONE) return
|
||||
if (step != RecentsStep.FORGET) task.setExcludeFromRecents(step == RecentsStep.HIDE)
|
||||
val live = tasks.map { idOf(it).toString() }.toSet()
|
||||
val next = owned.filter { it in live && it != id }.toMutableSet()
|
||||
if (step == RecentsStep.HIDE) next += id
|
||||
prefs.edit().putStringSet("tasks", next).apply()
|
||||
}
|
||||
}
|
||||
|
||||
fun startShortcut(context: Context, info: ShortcutInfo) {
|
||||
context.getSystemService(LauncherApps::class.java).startShortcut(info, null, null)
|
||||
val task = generateSequence(context) { (it as? android.content.ContextWrapper)?.baseContext }
|
||||
.filterIsInstance<android.app.Activity>().firstOrNull()?.taskId
|
||||
task?.let { com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(it, true) }
|
||||
try {
|
||||
context.getSystemService(LauncherApps::class.java).startShortcut(info, null, null)
|
||||
} catch (e: Exception) {
|
||||
task?.let { com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(it, false) }
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
fun openAppInfo(context: Context, app: LaunchableApp) {
|
||||
|
||||
@@ -75,6 +75,8 @@ import com.droiddeck.launcher.input.ControllerPrefs
|
||||
import com.droiddeck.launcher.input.SessionClipboard
|
||||
import com.droiddeck.launcher.input.OnScreenControls
|
||||
import com.droiddeck.launcher.input.PadBridge
|
||||
import com.droiddeck.launcher.input.PhysicalShortcuts
|
||||
import com.droiddeck.launcher.input.PhysicalShortcutRouter
|
||||
import com.droiddeck.launcher.input.PadMouse
|
||||
import com.droiddeck.launcher.input.PadState
|
||||
import com.droiddeck.launcher.input.ScreenKeys
|
||||
@@ -90,8 +92,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.hud.FusionHudConfig
|
||||
import com.droiddeck.launcher.hud.FusionHudHost
|
||||
import com.droiddeck.launcher.hud.DroidDeckHudConfig
|
||||
import com.droiddeck.launcher.hud.DroidDeckHudHost
|
||||
import com.droiddeck.launcher.session.PerfMode
|
||||
import com.droiddeck.launcher.session.SteamRepair
|
||||
import com.droiddeck.launcher.session.GameEnvironmentStore
|
||||
@@ -118,6 +120,10 @@ import com.droiddeck.launcher.ui.LoadingOverlay
|
||||
import com.droiddeck.launcher.ui.SessionDrawer
|
||||
import com.droiddeck.launcher.ui.SessionPausedOverlay
|
||||
import com.droiddeck.launcher.ui.SecondScreenPresentation
|
||||
import com.droiddeck.launcher.ui.BottomDashboard
|
||||
import com.droiddeck.launcher.ui.BottomPage
|
||||
import com.droiddeck.launcher.ui.sessionBottomPages
|
||||
import com.droiddeck.launcher.ui.BottomPageActions
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
import com.droiddeck.launcher.wayland.CompositorHost
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
@@ -159,9 +165,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private lateinit var surfaceView: SurfaceView
|
||||
private lateinit var sessionOverlay: ComposeView
|
||||
private lateinit var loading: LoadingState
|
||||
private lateinit var hud: FusionHudHost
|
||||
private lateinit var hud: DroidDeckHudHost
|
||||
private lateinit var memoryHud: com.droiddeck.launcher.session.MemoryHud
|
||||
private var padBridge: PadBridge? = null
|
||||
private val physicalShortcuts = PhysicalShortcutRouter()
|
||||
private var joyConVr: com.droiddeck.launcher.input.JoyConVr? = null
|
||||
private var handCamera: com.droiddeck.launcher.handtracking.HandCamera? = null
|
||||
private var padMotion: com.droiddeck.launcher.input.PadMotion? = null
|
||||
@@ -211,7 +218,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private lateinit var touchscreenGestures: TouchscreenGestures
|
||||
private var gestureConfig = com.droiddeck.launcher.input.TouchGestureConfig()
|
||||
private var gestureGame: String? = null
|
||||
private var gameStarts by mutableIntStateOf(0)
|
||||
private var gestureSettingsOpen by mutableStateOf(false)
|
||||
private var steamImportAsk by mutableStateOf<com.droiddeck.launcher.session.SteamImportPrompt.Ask?>(null)
|
||||
private var steamImportAnswered: String? = null
|
||||
private var directHoldBehavior by mutableStateOf(com.droiddeck.launcher.input.TouchGestureConfig.MOUSE_BEHAVIOR_CLICK)
|
||||
private var screenKeyPickerOpen by mutableStateOf(false)
|
||||
private var screenKeyBind: List<Int>? = null
|
||||
@@ -351,9 +361,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private var drawerDefaultProton by mutableStateOf<String?>(null)
|
||||
private val drawerComponentMenu by lazy { ComponentsMenu(this, uiHandler) }
|
||||
private var drawerGameProfileId by mutableStateOf<Long?>(null)
|
||||
private var fpsLimit by mutableStateOf(SessionState.fpsLimit)
|
||||
|
||||
private fun noSteamSession(): Boolean = SessionState.mode == SessionService.MODE_RUN &&
|
||||
SessionState.program in setOf(com.droiddeck.launcher.session.NoSteamLaunch.PROTON_RUN, com.droiddeck.launcher.session.NoSteamLaunch.EPIC)
|
||||
SessionState.program in setOf(
|
||||
com.droiddeck.launcher.session.NoSteamLaunch.PROTON_RUN, com.droiddeck.launcher.session.NoSteamLaunch.EPIC,
|
||||
com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET,
|
||||
)
|
||||
private val drawerGameInventory = GameProfileInventoryCache<Library.SteamGame>()
|
||||
private var drawerGameInventoryRevision = 0L
|
||||
private var drawerGameFexPresetSaving by mutableStateOf(false)
|
||||
@@ -430,6 +444,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private val cardboardPrefListener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
|
||||
if (key == SessionPrefs.CARDBOARD_KEY) uiHandler.post { applyCardboard(SessionPrefs.cardboard(this)) }
|
||||
}
|
||||
private val shortcutPrefListener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
|
||||
if (key == null || key == PhysicalShortcuts.KEY) {
|
||||
physicalShortcuts.bindings = PhysicalShortcuts.read(this)
|
||||
}
|
||||
}
|
||||
private var textureAnisotropy by mutableStateOf(0)
|
||||
private var textureLodBias by mutableStateOf(TextureFiltering.LOD_BIAS_OFF)
|
||||
private var drawerTextureAnisotropy by mutableStateOf<Int?>(null)
|
||||
@@ -439,6 +458,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) }
|
||||
}
|
||||
private var frameGen by mutableStateOf(FrameGen.Mode.OFF)
|
||||
private var frameGenPip = false
|
||||
private val frameGenRequests = java.util.concurrent.atomic.AtomicInteger()
|
||||
private var fexPreset by mutableStateOf("")
|
||||
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
|
||||
private var steamDownloadsInBackground by mutableStateOf(false)
|
||||
@@ -448,6 +469,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private var secondScreenDisplays by mutableStateOf<List<SecondScreenDisplay>>(emptyList())
|
||||
private var selectedSecondScreenDisplay by mutableStateOf(SessionState.secondScreenDisplay)
|
||||
private var started = false
|
||||
private var dualControlsProvisional: Boolean
|
||||
get() = SessionState.secondScreenProvisional
|
||||
set(value) { SessionState.secondScreenProvisional = value }
|
||||
private var sessionActivityDisplayId = Display.DEFAULT_DISPLAY
|
||||
private lateinit var displayManager: DisplayManager
|
||||
private var secondScreenPresentation: SecondScreenPresentation? = null
|
||||
@@ -514,8 +538,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
refreshControls()
|
||||
updatePointerCapture()
|
||||
updateHandCamera()
|
||||
refreshSecondScreenDisplays()
|
||||
}
|
||||
override fun onInputDeviceRemoved(deviceId: Int) {
|
||||
physicalShortcuts.onDeviceRemoved(deviceId)
|
||||
Log.i(TAG, "input device $deviceId disconnected")
|
||||
backQamInput.onDeviceRemoved(deviceId)
|
||||
joyConVr?.refresh()
|
||||
@@ -524,10 +550,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
refreshControls()
|
||||
updatePointerCapture()
|
||||
updateHandCamera()
|
||||
refreshSecondScreenDisplays()
|
||||
}
|
||||
override fun onInputDeviceChanged(deviceId: Int) {
|
||||
joyConVr?.refresh()
|
||||
refreshControls()
|
||||
refreshSecondScreenDisplays()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -560,6 +588,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
SessionState.steamUi = intent.getStringExtra(SessionService.EXTRA_STEAM_UI)
|
||||
SessionState.steamUrl = intent.getStringExtra(SessionService.EXTRA_STEAM_URL)
|
||||
SessionState.steamVr = intent.getBooleanExtra(EXTRA_STEAMVR, false)
|
||||
SessionState.secondScreenAutoOpened = false
|
||||
SessionState.secondScreenProvisional = false
|
||||
} else if (intent.getBooleanExtra(EXTRA_STEAMVR, false) && SessionState.mode == SessionService.MODE_STEAM) {
|
||||
SessionState.steamVr = true
|
||||
}
|
||||
@@ -569,6 +599,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
com.droiddeck.launcher.gpu.SteamVrHealth.begin(this, SessionState.sessionId)
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
if (!SessionState.running) {
|
||||
SessionState.fpsLimit = 0
|
||||
fpsLimit = 0
|
||||
}
|
||||
applyOutputPacing()
|
||||
if (!SessionState.running) SessionState.followScreen = followChoice()
|
||||
applyFollowOrientation(resources.configuration)
|
||||
@@ -717,8 +751,8 @@ 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 = FusionHudHost(this)
|
||||
hud.onConfigChanged = { hudConfig = FusionHudConfig.load(this) }
|
||||
hud = DroidDeckHudHost(this)
|
||||
hud.onConfigChanged = { hudConfig = DroidDeckHudConfig.load(this) }
|
||||
hud.passesTouchAt = ::controlTakesTouchAt
|
||||
hud.attach(root, root.childCount)
|
||||
memoryHud = com.droiddeck.launcher.session.MemoryHud(this)
|
||||
@@ -808,7 +842,14 @@ 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(pipUi) {
|
||||
hud.setHidden(pipUi)
|
||||
applyOutputPacing()
|
||||
if (pipUi != frameGenPip) {
|
||||
frameGenPip = pipUi
|
||||
if (FrameGen.engine(this@SessionActivity) != FrameGen.ENGINE_OFF && ::surfaceView.isInitialized) applyFrameGen()
|
||||
}
|
||||
}
|
||||
androidx.compose.runtime.LaunchedEffect(AgentGuest.steamKeyboard) { updateOnScreenControls() }
|
||||
androidx.compose.runtime.LaunchedEffect(AgentGuest.desktopTextField) { onDesktopTextField(AgentGuest.desktopTextField) }
|
||||
androidx.compose.runtime.LaunchedEffect(pipUi, pcKeyboardOpen) { updateDesktopKeyboardButton() }
|
||||
@@ -891,7 +932,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (nextGame != gestureGame) { gestureGame = nextGame; refreshGestureConfig() }
|
||||
if (nextGame != gestureGame) {
|
||||
if (nextGame != null) gameStarts++
|
||||
gestureGame = nextGame
|
||||
refreshGestureConfig()
|
||||
}
|
||||
if (secondScreenDisplays.isNotEmpty()) kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
|
||||
runCatching { com.droiddeck.launcher.session.TelemetryOutput.applyAutomatic(this@SessionActivity, nextGame) }
|
||||
}
|
||||
}
|
||||
LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, pipUi, SessionState.suspended) {
|
||||
if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || pipUi || SessionState.suspended) {
|
||||
@@ -902,6 +950,29 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
}
|
||||
com.droiddeck.launcher.ui.GestureFeedback(recognizedGesture)
|
||||
LaunchedEffect(Unit) {
|
||||
val root = LinuxRuntime.rootDir(this@SessionActivity)
|
||||
while (true) {
|
||||
val ask = if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM) {
|
||||
kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { com.droiddeck.launcher.session.SteamImportPrompt.read(root) }
|
||||
} else null
|
||||
steamImportAsk = ask?.takeIf { it.token != steamImportAnswered }
|
||||
kotlinx.coroutines.delay(1500)
|
||||
}
|
||||
}
|
||||
steamImportAsk?.takeIf { !loading.visible }?.let { ask ->
|
||||
androidx.compose.runtime.key(ask.token) {
|
||||
com.droiddeck.launcher.ui.SteamImportDialog(ask.games) { now ->
|
||||
val root = LinuxRuntime.rootDir(this@SessionActivity)
|
||||
Thread({
|
||||
if (com.droiddeck.launcher.session.SteamImportPrompt.answer(root, ask.token, now)) runOnUiThread {
|
||||
steamImportAnswered = ask.token
|
||||
if (steamImportAsk?.token == ask.token) steamImportAsk = null
|
||||
}
|
||||
}, "steam-import-answer").start()
|
||||
}
|
||||
}
|
||||
}
|
||||
if (gestureSettingsOpen) com.droiddeck.launcher.ui.TouchGestureDialog(
|
||||
game = gestureGame,
|
||||
onDismiss = { gestureSettingsOpen = false },
|
||||
@@ -1118,11 +1189,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
touchAuto = getString(if (usingTouchpad()) R.string.session_touch_auto_touchpad else R.string.session_touch_auto_direct),
|
||||
fexPreset = fexPreset,
|
||||
secondScreenMode = secondScreenMode,
|
||||
dashboardAvailable = bottomPages().isNotEmpty(),
|
||||
secondScreenDisplays = secondScreenDisplays,
|
||||
selectedSecondScreenDisplay = selectedSecondScreenDisplay,
|
||||
onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() },
|
||||
onHudSetting = { key, value -> hudConfig = FusionHudConfig.set(this@SessionActivity, key, value); hud.applyConfig() },
|
||||
onHudReset = { hudConfig = FusionHudConfig.reset(this@SessionActivity); hud.applyConfig() },
|
||||
onHudSetting = { key, value -> hudConfig = DroidDeckHudConfig.set(this@SessionActivity, key, value); hud.applyConfig() },
|
||||
onHudReset = { hudConfig = DroidDeckHudConfig.reset(this@SessionActivity); hud.applyConfig() },
|
||||
onHudExport = { exportHudDiagnostics() },
|
||||
onUpscaler = { m ->
|
||||
SessionPrefs.setUpscaler(this@SessionActivity, m); upscaler = m
|
||||
@@ -1155,6 +1227,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
textureLodBias = it
|
||||
}
|
||||
},
|
||||
fpsLimit = fpsLimit,
|
||||
onFpsLimit = { fps ->
|
||||
SessionState.fpsLimit = fps
|
||||
fpsLimit = fps
|
||||
applyOutputPacing()
|
||||
},
|
||||
onFrameGenPick = { mode ->
|
||||
FrameGen.set(this@SessionActivity, mode)
|
||||
readPrefs()
|
||||
@@ -1255,7 +1333,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
screenLayoutsOpen = true
|
||||
},
|
||||
onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() },
|
||||
onSecondScreenMode = { mode -> if (docked) drawerOpen = false; typingReturnMode = null; selectSecondScreenMode(mode) },
|
||||
onSecondScreenMode = { mode ->
|
||||
if (docked) drawerOpen = false
|
||||
typingReturnMode = null
|
||||
if (mode != SecondScreenMode.NONE) SessionPrefs.setSecondScreenPanel(this@SessionActivity, mode.id)
|
||||
selectSecondScreenMode(mode)
|
||||
},
|
||||
onSecondScreenDisplay = ::selectSecondScreenDisplay,
|
||||
onLaunchAndroidApp = { app, displayId ->
|
||||
drawerOpen = false
|
||||
@@ -1751,7 +1834,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
unfoldedControlsWithController = SessionPrefs.unfoldedControlsWithController(this)
|
||||
picturePosition = SessionPrefs.picturePosition(this)
|
||||
hudOn = SessionPrefs.hudEnabled(this)
|
||||
hudConfig = FusionHudConfig.load(this)
|
||||
hudConfig = DroidDeckHudConfig.load(this)
|
||||
hudColor = SessionPrefs.hudColor(this)
|
||||
hudOpacity = SessionPrefs.hudOpacity(this)
|
||||
upscaler = SessionPrefs.upscaler(this)
|
||||
@@ -1788,6 +1871,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
|
||||
oscMode = SessionPrefs.oscMode(this)
|
||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||
physicalShortcuts.bindings = PhysicalShortcuts.read(this)
|
||||
backDoubleTapMs = SessionPrefs.backDoubleTapMs(this)
|
||||
lowLatency = SessionPrefs.lowLatency(this)
|
||||
evdevMouseOn = SessionPrefs.evdevMouse(this)
|
||||
@@ -2168,10 +2252,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private fun mirrorRefreshLimit(): Int =
|
||||
GlassesRendering.mirrorRefreshLimit(glassesSettings, glasses, glassesScreen != null)
|
||||
|
||||
private fun outputFpsLimit(): Int = SessionPrefs.compositorFpsLimit(mirrorRefreshLimit())
|
||||
private fun outputFpsLimit(): Int = outputFpsLimit(pipUi)
|
||||
|
||||
private fun outputFpsLimit(pip: Boolean): Int =
|
||||
SessionPrefs.compositorFpsLimit(mirrorRefreshLimit(), if (noSteamSession()) SessionState.fpsLimit else 0, pip)
|
||||
|
||||
private fun applyOutputPacing() {
|
||||
Log.i(TAG, "perf: " + PerfMode.apply(this, outputFpsLimit(), mirrorRefreshLimit()))
|
||||
Log.i(TAG, "perf: " + PerfMode.apply(this, outputFpsLimit(false), mirrorRefreshLimit()))
|
||||
if (CompositorHost.isStarted) {
|
||||
val hz = refreshHz()
|
||||
val changed = kotlin.math.abs(SessionState.refreshHz - hz) > 0.1f
|
||||
@@ -2183,8 +2270,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
private fun applyFrameGen() {
|
||||
val hz = refreshHz()
|
||||
val pip = pipUi && mirrorRefreshLimit() <= 0
|
||||
val request = frameGenRequests.incrementAndGet()
|
||||
Thread({
|
||||
val problem = FrameGen.apply(this, hz)
|
||||
val problem = synchronized(frameGenRequests) {
|
||||
if (request != frameGenRequests.get()) return@Thread
|
||||
if (pip) FrameGen.apply(this, FrameGen.Mode.OFF, hz) else FrameGen.apply(this, hz)
|
||||
}
|
||||
val state = Lossless.state(this)
|
||||
runOnUiThread {
|
||||
lossless = state
|
||||
@@ -2405,6 +2497,26 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
if (pipUi) return true
|
||||
if (screenKeyTextFocus) return super.dispatchKeyEvent(event)
|
||||
if (physicalShortcuts.onKey(
|
||||
event,
|
||||
enabled = SessionState.running && !SessionState.suspended &&
|
||||
!(drawerOpen && event.keyCode == KeyEvent.KEYCODE_BUTTON_A) &&
|
||||
!(drawerOpen && PhysicalShortcuts.isDrawerNavigationKey(event)) &&
|
||||
(event.deviceId to event.keyCode) !in resumeKeysDown &&
|
||||
!(::loading.isInitialized && (loading.visible || loading.ended)) &&
|
||||
!pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen,
|
||||
steam = SessionState.mode == SessionService.MODE_STEAM,
|
||||
) { action ->
|
||||
pendingBackAction?.let(uiHandler::removeCallbacks)
|
||||
pendingBackAction = null
|
||||
drawerControllerActive = true
|
||||
Log.i(TAG, "physical shortcut ${action.name} device=${event.deviceId} key=${event.keyCode} scan=${event.scanCode}")
|
||||
when (action) {
|
||||
PhysicalShortcuts.Action.STEAM -> sendSteamGuide()
|
||||
PhysicalShortcuts.Action.QAM -> triggerSteamQam()
|
||||
PhysicalShortcuts.Action.DROIDDECK -> drawerOpen = !drawerOpen
|
||||
}
|
||||
}) return true
|
||||
val pad = com.droiddeck.launcher.input.JoyCon.normalize(event)
|
||||
if (pad !== event) return dispatchKeyEvent(pad)
|
||||
val fromController = PadBridge.isControllerKeyEvent(event)
|
||||
@@ -2737,6 +2849,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
override fun onWheel(steps: Int) { sendSceneWheel(steps) }
|
||||
override fun onScroll(dx: Float, dy: Float) = fingerScroll(dx, dy)
|
||||
override fun onScrollEnd() = fingerScrollEnd()
|
||||
override fun onThreeFingerTap(): Boolean {
|
||||
uiHandler.post { togglePcKeyboard() }
|
||||
return true
|
||||
}
|
||||
override fun onZoom(steps: Int) {
|
||||
WaylandCompositor.nativeSendKey(KEY_LEFTCTRL, 1)
|
||||
sendSceneWheel(steps)
|
||||
@@ -2909,19 +3025,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private fun refreshSecondScreenDisplays() {
|
||||
if (!::displayManager.isInitialized) return
|
||||
val primaryId = shownOnDisplayId
|
||||
val dualOff = SessionPrefs.dualScreenMode(this) == com.droiddeck.launcher.input.DualScreen.MODE_OFF
|
||||
val candidates = SecondScreenDisplays.available(displayManager, primaryId)
|
||||
.filter { !dualOff && (glassesScreen == null || it.id != glasses.displayId) }
|
||||
.filter { glassesScreen == null || it.id != glasses.displayId }
|
||||
val oldIds = secondScreenDisplays.map { it.id }.toSet()
|
||||
secondScreenDisplays = candidates
|
||||
val newIds = candidates.map { it.id }.toSet()
|
||||
if (secondScreenMode != SecondScreenMode.NONE && oldIds.isNotEmpty() && selectedSecondScreenDisplay !in newIds) {
|
||||
closeSecondScreen(reset = true)
|
||||
SessionState.secondScreenAutoOpened = false
|
||||
return
|
||||
}
|
||||
if (selectedSecondScreenDisplay !in newIds) selectedSecondScreenDisplay = candidates.firstOrNull()?.id ?: -1
|
||||
if (secondScreenMode != SecondScreenMode.NONE && candidates.isEmpty()) closeSecondScreen(reset = true)
|
||||
else if (started && secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode)
|
||||
if (secondScreenMode != SecondScreenMode.NONE && candidates.isEmpty()) {
|
||||
closeSecondScreen(reset = true)
|
||||
SessionState.secondScreenAutoOpened = false
|
||||
} else if (started && secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode)
|
||||
else if (started && !ended && ::loading.isInitialized && !loading.visible) openDualScreenControls()
|
||||
updateKeyboardRoute()
|
||||
}
|
||||
|
||||
@@ -2932,7 +3051,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (secondScreenDisplays.none { it.id == target.displayId }) return
|
||||
SessionState.secondScreenAutoOpened = true
|
||||
selectedSecondScreenDisplay = target.displayId
|
||||
selectSecondScreenMode(if (SessionState.deckPad) SecondScreenMode.DECK_CONTROLS else SecondScreenMode.KEYBOARD_TRACKPAD)
|
||||
selectSecondScreenMode(SecondScreenMode.opening(SessionPrefs.secondScreenPanel(this), SessionState.deckPad, bottomPages().isNotEmpty()))
|
||||
dualControlsProvisional = ::loading.isInitialized && loading.visible
|
||||
}
|
||||
|
||||
private fun settleDualScreenControls() {
|
||||
if (!dualControlsProvisional || pipUi || !started || (::loading.isInitialized && loading.visible)) return
|
||||
dualControlsProvisional = false
|
||||
if (secondScreenMode == SecondScreenMode.NONE) return
|
||||
val wanted = SecondScreenMode.opening(SessionPrefs.secondScreenPanel(this), SessionState.deckPad, bottomPages().isNotEmpty())
|
||||
if (wanted != secondScreenMode) selectSecondScreenMode(wanted) else secondScreenPresentation?.retryTerminal()
|
||||
}
|
||||
|
||||
private fun selectSecondScreenDisplay(displayId: Int) {
|
||||
@@ -2943,6 +3071,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
private fun selectSecondScreenMode(mode: SecondScreenMode) {
|
||||
dualControlsProvisional = false
|
||||
if (mode == SecondScreenMode.NONE) {
|
||||
closeSecondScreen(reset = true)
|
||||
return
|
||||
@@ -3000,8 +3129,85 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
menu = {
|
||||
DroidDeckTheme { SessionMenu(docked = true) }
|
||||
},
|
||||
dashboard = if (bottomPages().isEmpty()) null else ({
|
||||
DroidDeckTheme {
|
||||
BottomDashboard(
|
||||
bottomPages(), SessionPrefs.bottomPage(this),
|
||||
gameStarts = gameStarts,
|
||||
onPage = { SessionPrefs.setBottomPage(this, it) },
|
||||
onClose = { selectSecondScreenMode(SecondScreenMode.NONE) },
|
||||
onMenu = if (dockDrawer()) ({ drawerOpen = true }) else null,
|
||||
)
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
/** Pages for the bottom-screen dashboard; the dashboard is offered only while at least one exists. */
|
||||
private fun bottomPages(): List<BottomPage> = sessionBottomPages(BottomPageActions(
|
||||
takeScreenshot = ::captureScreenshot,
|
||||
fps = { if (::hud.isInitialized) hud.liveFps else null },
|
||||
openSettings = ::openSettingsBelow,
|
||||
runningGame = { gestureGame },
|
||||
))
|
||||
|
||||
// A settings page opened on the bottom screen sits under the dashboard window, so the dashboard hides
|
||||
// until the setting is on; choosing Dashboard in the menu again shows it sooner.
|
||||
private fun openSettingsBelow(intent: android.content.Intent, done: () -> Boolean) {
|
||||
val presentation = secondScreenPresentation ?: return
|
||||
val options = android.app.ActivityOptions.makeBasic().setLaunchDisplayId(presentation.display.displayId)
|
||||
val opened = listOf(intent, android.content.Intent(android.provider.Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)).any {
|
||||
runCatching { startActivity(android.content.Intent(it).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK), options.toBundle()) }
|
||||
.onFailure { e -> Log.w(TAG, "could not open ${it.action} on display ${presentation.display.displayId}", e) }
|
||||
.isSuccess
|
||||
}
|
||||
if (!opened) return
|
||||
presentation.hide()
|
||||
var checks = 0
|
||||
uiHandler.postDelayed(object : Runnable {
|
||||
override fun run() {
|
||||
if (secondScreenPresentation !== presentation || presentation.isShowing) return
|
||||
if (done()) {
|
||||
presentation.show()
|
||||
return
|
||||
}
|
||||
if (++checks < SETTINGS_WATCH_CHECKS) uiHandler.postDelayed(this, SETTINGS_WATCH_MS)
|
||||
}
|
||||
}, SETTINGS_WATCH_MS)
|
||||
}
|
||||
|
||||
/** Copies the game frame (no overlay) at the size it is shown and saves it to Pictures/DroidDeck. */
|
||||
private fun captureScreenshot(onDone: (Boolean) -> Unit) {
|
||||
val width = if (::surfaceView.isInitialized) surfaceView.width else 0
|
||||
val height = if (::surfaceView.isInitialized) surfaceView.height else 0
|
||||
if (width <= 0 || height <= 0 || surfaceView.holder.surface?.isValid != true) {
|
||||
onDone(false)
|
||||
return
|
||||
}
|
||||
val bitmap = try {
|
||||
android.graphics.Bitmap.createBitmap(width, height, android.graphics.Bitmap.Config.ARGB_8888)
|
||||
} catch (_: OutOfMemoryError) {
|
||||
onDone(false)
|
||||
return
|
||||
}
|
||||
try {
|
||||
android.view.PixelCopy.request(surfaceView, bitmap, { result ->
|
||||
if (result != android.view.PixelCopy.SUCCESS) {
|
||||
bitmap.recycle()
|
||||
onDone(false)
|
||||
return@request
|
||||
}
|
||||
Thread {
|
||||
val saved = com.droiddeck.launcher.session.BottomScreenshots.save(applicationContext, bitmap)
|
||||
bitmap.recycle()
|
||||
runOnUiThread { onDone(saved) }
|
||||
}.start()
|
||||
}, uiHandler)
|
||||
} catch (_: IllegalArgumentException) {
|
||||
bitmap.recycle()
|
||||
onDone(false)
|
||||
}
|
||||
}
|
||||
|
||||
private fun tapSteamButton() {
|
||||
if (SessionState.mode == SessionService.MODE_STEAM) {
|
||||
padBridge?.applyTouch { st -> st.press(com.droiddeck.launcher.input.PadState.GUIDE, true) }
|
||||
@@ -3721,7 +3927,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
updateOnScreenControls()
|
||||
if (resumed) { sessionClipboard.start(); updatePadMotion() }
|
||||
if (started) refreshSecondScreenDisplays()
|
||||
if (started) {
|
||||
settleDualScreenControls()
|
||||
refreshSecondScreenDisplays()
|
||||
}
|
||||
if (CompositorHost.isStarted) applyFrameGen()
|
||||
}
|
||||
}
|
||||
@@ -3757,9 +3966,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
for (name in arrayOf("peak_refresh_rate", "min_refresh_rate")) {
|
||||
contentResolver.registerContentObserver(android.provider.Settings.System.getUriFor(name), false, refreshSettingObserver)
|
||||
}
|
||||
settleDualScreenControls()
|
||||
refreshSecondScreenDisplays()
|
||||
if (secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode)
|
||||
else if (::loading.isInitialized && !loading.visible) openDualScreenControls()
|
||||
else openDualScreenControls()
|
||||
startedScreens++
|
||||
SessionService.setActivityVisible(this, true, sessionActivityDisplayId)
|
||||
Glasses.rescan()
|
||||
@@ -3824,6 +4034,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
(getSystemService(INPUT_SERVICE) as? InputManager)
|
||||
?.registerInputDeviceListener(deviceListener, Handler(Looper.getMainLooper()))
|
||||
refreshSecondScreenDisplays()
|
||||
if (SessionState.guestPid > 1) padBridge?.syncConnectedControllers()
|
||||
joyConVr?.refresh()
|
||||
onScreenControls?.reload()
|
||||
@@ -3842,6 +4053,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
updatePointerCapture()
|
||||
if (!pipUi) sessionClipboard.start()
|
||||
updatePadMotion()
|
||||
ControllerPrefs.prefs(this).registerOnSharedPreferenceChangeListener(shortcutPrefListener)
|
||||
readPrefs()
|
||||
refreshControls()
|
||||
if (::pip.isInitialized) pip.resumed()
|
||||
@@ -3852,6 +4064,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
override fun onPause() {
|
||||
com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this)
|
||||
if (runtimeRemovalBlocked) { super.onPause(); return }
|
||||
physicalShortcuts.clear()
|
||||
backQamInput.cancel()
|
||||
capturePausedFrame()
|
||||
sessionClipboard.stop()
|
||||
@@ -3875,6 +4088,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
updatePadMotion()
|
||||
keyboard?.takeIf { it.shown }?.hide()
|
||||
SessionPrefs.sessionPrefs(this).unregisterOnSharedPreferenceChangeListener(cardboardPrefListener)
|
||||
ControllerPrefs.prefs(this).unregisterOnSharedPreferenceChangeListener(shortcutPrefListener)
|
||||
updateHeadTracker()
|
||||
super.onPause()
|
||||
}
|
||||
@@ -4283,7 +4497,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
loading.visible = false
|
||||
hud.start()
|
||||
memoryHud.start()
|
||||
if (started) openDualScreenControls()
|
||||
if (started) {
|
||||
settleDualScreenControls()
|
||||
openDualScreenControls()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4386,6 +4603,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private const val TEXT_FIELD_TAP_MS = 1_000L
|
||||
private const val PAUSED_FRAME_MAX_EDGE = 1920f
|
||||
private const val PAUSED_FRAME_REDRAW_MS = 150L
|
||||
private const val SETTINGS_WATCH_MS = 1_000L
|
||||
private const val SETTINGS_WATCH_CHECKS = 600
|
||||
private const val TAG = "SessionActivity"
|
||||
private var startedScreens = 0
|
||||
@Volatile private var activeInstallWorker: Any? = null
|
||||
|
||||
@@ -23,6 +23,9 @@ class AgentStartActivity : Activity() {
|
||||
Thread({
|
||||
try {
|
||||
AgentBridgeProvider.awaitRecovery()
|
||||
val until = android.os.SystemClock.elapsedRealtime() + RUNTIME_WAIT_MS
|
||||
while (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isBusy() && !isFinishing &&
|
||||
android.os.SystemClock.elapsedRealtime() < until) Thread.sleep(RUNTIME_POLL_MS)
|
||||
runOnUiThread {
|
||||
if (!isFinishing) startSession(request)
|
||||
}
|
||||
@@ -51,6 +54,11 @@ class AgentStartActivity : Activity() {
|
||||
}
|
||||
|
||||
private fun startSession(request: JSONObject) {
|
||||
if (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isBusy()) {
|
||||
Log.w(TAG, "the Linux runtime is being installed or changed")
|
||||
finish()
|
||||
return
|
||||
}
|
||||
try {
|
||||
AgentAccess.requireStart(this, request)
|
||||
} catch (e: AgentException) {
|
||||
@@ -107,5 +115,7 @@ class AgentStartActivity : Activity() {
|
||||
companion object {
|
||||
const val EXTRA_REQUEST = "request"
|
||||
private const val TAG = "AgentStartActivity"
|
||||
private const val RUNTIME_WAIT_MS = 15 * 60_000L
|
||||
private const val RUNTIME_POLL_MS = 500L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.droiddeck.launcher.audio
|
||||
|
||||
import android.media.AudioAttributes
|
||||
import android.media.AudioFormat
|
||||
import android.media.AudioTrack
|
||||
import android.util.Log
|
||||
|
||||
object DirectAudioTiming {
|
||||
private const val TAG = "DirectAudioTiming"
|
||||
const val PERIOD_ENV = "AUDIO_DIRECT_PERIOD_MS"
|
||||
const val BUFFER_ENV = "AUDIO_DIRECT_MS"
|
||||
const val SLOW_OUTPUT_PERIOD_MS = 20
|
||||
const val SLOW_OUTPUT_BUFFER_MS = 60
|
||||
|
||||
fun environment(lowLatencyOutput: Boolean): List<String> =
|
||||
if (lowLatencyOutput) emptyList()
|
||||
else listOf("$PERIOD_ENV=$SLOW_OUTPUT_PERIOD_MS", "$BUFFER_ENV=$SLOW_OUTPUT_BUFFER_MS")
|
||||
|
||||
fun lowLatencyOutput(): Boolean = try {
|
||||
val track = AudioTrack.Builder()
|
||||
.setAudioAttributes(AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_GAME)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
|
||||
.build())
|
||||
.setAudioFormat(AudioFormat.Builder()
|
||||
.setEncoding(AudioFormat.ENCODING_PCM_FLOAT)
|
||||
.setSampleRate(48000)
|
||||
.setChannelMask(AudioFormat.CHANNEL_OUT_STEREO)
|
||||
.build())
|
||||
.setPerformanceMode(AudioTrack.PERFORMANCE_MODE_LOW_LATENCY)
|
||||
.setTransferMode(AudioTrack.MODE_STREAM)
|
||||
.build()
|
||||
try {
|
||||
track.performanceMode == AudioTrack.PERFORMANCE_MODE_LOW_LATENCY
|
||||
} finally {
|
||||
track.release()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "audio: could not check for low-latency output; DirectAudio keeps its defaults", e)
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -146,5 +146,7 @@ internal class AddonPack(
|
||||
listOf("version", "xodus-cli", "xodus-service"))
|
||||
val COMET = AddonPack("comet", BuildConfig.PACK_COMET_SHA256, BuildConfig.PACK_COMET_SIZE,
|
||||
listOf("version", "comet"))
|
||||
val BUTLER = AddonPack("butler", BuildConfig.PACK_BUTLER_SHA256, BuildConfig.PACK_BUTLER_SIZE,
|
||||
listOf("version", "butler", "7z.so", "libc7zip.so"))
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,8 @@ object GameEnvironmentOptions {
|
||||
Option("MESA_EXTENSION_MAX_YEAR", "", 0, Type.TEXT),
|
||||
Option("MESA_GL_VERSION_OVERRIDE", "", 0, Type.TEXT),
|
||||
Option("PULSE_LATENCY_MSEC", "", 0, Type.NUMBER),
|
||||
Option("AUDIO_DIRECT_MS", "", 0, Type.NUMBER),
|
||||
Option("AUDIO_DIRECT_PERIOD_MS", "", 0, Type.NUMBER),
|
||||
Option("DROIDDECK_GAME_CORES", "", R.string.game_env_cores, Type.TEXT),
|
||||
Option("DROIDDECK_ANTICHEAT_OFFLINE", "1", R.string.game_env_anticheat_offline, Type.TOGGLE, listOf("0", "1")),
|
||||
Option("WINE_LARGE_ADDRESS_AWARE", "0", 0, Type.TOGGLE, listOf("0", "1")),
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
|
||||
class ShortcutsListingReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (intent.action == Intent.ACTION_MY_PACKAGE_REPLACED) SteamIntegration.syncShortcutsListing(context)
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import android.accessibilityservice.AccessibilityServiceInfo
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.provider.Settings
|
||||
import android.view.accessibility.AccessibilityManager
|
||||
@@ -55,6 +56,33 @@ object SteamIntegration {
|
||||
return mode == android.app.AppOpsManager.MODE_ERRORED || mode == android.app.AppOpsManager.MODE_IGNORED
|
||||
}
|
||||
|
||||
private fun shortcutsComponent(context: Context) = ComponentName(context, HomeButtonService::class.java)
|
||||
|
||||
fun shortcutsChosen(context: Context): Boolean = shortcutsSelection(context) == true
|
||||
|
||||
private fun shortcutsSelection(context: Context): Boolean? {
|
||||
val target = shortcutsComponent(context)
|
||||
val enabled = runCatching {
|
||||
Settings.Secure.getString(context.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES)
|
||||
}.getOrElse { return null }.orEmpty()
|
||||
return enabled.split(':').any { ComponentName.unflattenFromString(it.trim()) == target }
|
||||
}
|
||||
|
||||
fun setShortcutsListed(context: Context, listed: Boolean) {
|
||||
val packages = context.packageManager
|
||||
val component = shortcutsComponent(context)
|
||||
val state = if (listed) PackageManager.COMPONENT_ENABLED_STATE_ENABLED else PackageManager.COMPONENT_ENABLED_STATE_DISABLED
|
||||
runCatching {
|
||||
if (packages.getComponentEnabledSetting(component) != state) {
|
||||
packages.setComponentEnabledSetting(component, state, PackageManager.DONT_KILL_APP)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun syncShortcutsListing(context: Context) {
|
||||
shortcutsSelection(context)?.let { setShortcutsListed(context, it) }
|
||||
}
|
||||
|
||||
fun dismissSuggestion(context: Context) {
|
||||
SessionPrefs.sessionPrefs(context).edit().putBoolean("steam_integration_seen", true).apply()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.provider.Settings
|
||||
|
||||
object AllFilesAccess {
|
||||
fun missing(sdk: Int = Build.VERSION.SDK_INT, granted: () -> Boolean = { Environment.isExternalStorageManager() }): Boolean =
|
||||
sdk >= Build.VERSION_CODES.R && !granted()
|
||||
|
||||
fun open(context: Context) {
|
||||
val app = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, Uri.parse("package:" + context.packageName))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
runCatching { context.startActivity(app) }.recoverCatching {
|
||||
context.startActivity(Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -498,6 +498,25 @@ fun FileManagerScreen(
|
||||
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
|
||||
}
|
||||
val drives = remember(storageTick) { StorageRoots.list(context) }
|
||||
var accessDrive by remember { mutableStateOf<String?>(null) }
|
||||
fun unreadable(drive: StorageRoot) {
|
||||
if (AllFilesAccess.missing()) accessDrive = drive.label
|
||||
else Toast.makeText(context, context.getString(R.string.fm_drive_not_readable, drive.label), Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
accessDrive?.let { label ->
|
||||
OutlinedAlertDialog(
|
||||
onDismissRequest = { accessDrive = null },
|
||||
title = { Text(stringResource(R.string.fm_drive_access_title, label)) },
|
||||
text = { Text(stringResource(R.string.fm_drive_access_text)) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
accessDrive = null
|
||||
AllFilesAccess.open(context)
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.upd_open_settings)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { accessDrive = null }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
val linuxRoot = remember(storageTick) {
|
||||
com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context).takeIf { File(it, "usr").isDirectory }
|
||||
}
|
||||
@@ -747,11 +766,7 @@ fun FileManagerScreen(
|
||||
if (drive.readable) {
|
||||
openDrive(drive.dir)
|
||||
} else {
|
||||
Toast.makeText(
|
||||
context,
|
||||
context.getString(R.string.fm_drive_not_readable, drive.label),
|
||||
Toast.LENGTH_SHORT,
|
||||
).show()
|
||||
unreadable(drive)
|
||||
}
|
||||
},
|
||||
modifier = Modifier.focusGlide(),
|
||||
@@ -1072,7 +1087,7 @@ fun FileManagerScreen(
|
||||
add(locItem(stringResource(R.string.fm_drive_internal), Icons.Filled.Smartphone, File("/storage/emulated/0")))
|
||||
drives.filter { it.removable }.forEach { d ->
|
||||
add(RailItem(d.label, Icons.Filled.SdStorage, !showFavorites && currentRoot.absolutePath == d.dir.absolutePath) {
|
||||
showFavorites = false; if (d.readable) openDrive(d.dir)
|
||||
showFavorites = false; if (d.readable) openDrive(d.dir) else unreadable(d)
|
||||
})
|
||||
}
|
||||
linuxRoot?.let { add(locItem(stringResource(R.string.fm_drive_linux), Icons.Filled.Terminal, it)) }
|
||||
|
||||
@@ -287,14 +287,17 @@ object AddedGameArt {
|
||||
var sgdbDown = false
|
||||
var changed = false
|
||||
for (game in games) {
|
||||
if (forgetOtherAppsArt(context, game)) changed = true
|
||||
val cache = cacheDir(context, game)
|
||||
val start = missing(context, game)
|
||||
val again = refetch(cache) intersect start
|
||||
if (again.isEmpty()) File(cache, REFETCH).delete()
|
||||
val full = Slot.COVER in start
|
||||
val allowed = if (full) Slot.values().toSet() else EXTRAS
|
||||
val allowed = if (full) Slot.values().toSet() else EXTRAS + again
|
||||
var need = start intersect allowed
|
||||
if (need.isEmpty() || (need == setOf(Slot.ICON) && sgdbKey.isEmpty())) continue
|
||||
val cache = cacheDir(context, game)
|
||||
val tried = File(cache, EXTRAS_TRIED)
|
||||
if (!full && tried.isFile && tried.lastModified() >= keyChangedAt && System.currentTimeMillis() - tried.lastModified() < RETRY_AFTER_MS) continue
|
||||
if (!full && again.isEmpty() && tried.isFile && tried.lastModified() >= keyChangedAt && System.currentTimeMillis() - tried.lastModified() < RETRY_AFTER_MS) continue
|
||||
cache.mkdirs()
|
||||
if (Slot.LOGO in need && game.source != Library.ADDED && runCatching { sources.storeLogo(game) }.getOrDefault(false)) {
|
||||
changed = true
|
||||
@@ -324,11 +327,42 @@ object AddedGameArt {
|
||||
asked = false
|
||||
}
|
||||
}
|
||||
if ((missing(context, game) intersect EXTRAS).isEmpty()) tried.delete() else if (asked) tried.writeText("")
|
||||
val left = missing(context, game)
|
||||
if (again.isNotEmpty()) keepRefetch(cache, again intersect left)
|
||||
if ((left intersect EXTRAS).isEmpty()) tried.delete() else if (asked) tried.writeText("")
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
internal const val REFETCH = "refetch"
|
||||
|
||||
private fun refetch(cache: File): Set<Slot> =
|
||||
runCatching { File(cache, REFETCH).readText() }.getOrDefault("").split(',').mapNotNull { key -> Slot.values().firstOrNull { it.key == key } }.toSet()
|
||||
|
||||
private fun keepRefetch(cache: File, slots: Set<Slot>) {
|
||||
if (slots.isEmpty()) File(cache, REFETCH).delete() else File(cache, REFETCH).writeText(slots.joinToString(",") { it.key })
|
||||
}
|
||||
|
||||
internal fun forgetOtherAppsArt(context: Context, game: AddedGames.Game): Boolean {
|
||||
val cache = cacheDir(context, game)
|
||||
val recorded = SteamMatch.get(context, game.folder.path)?.takeIf { it.appId != null }
|
||||
val legacy = runCatching { File(cache, "steam-appid").readText().trim().toInt() }.getOrNull()?.takeIf { it > 0 }
|
||||
val before = recorded?.appId ?: legacy ?: return false
|
||||
val identity = runCatching { GameIdentifier.identify(game.exe) }.getOrNull()
|
||||
val now = identity?.appId
|
||||
val fromFiles = recorded?.certainty == SteamMatch.Certainty.FILES || before == GameIdentifier.SPACEWAR
|
||||
if (now == before || (now == null && !fromFiles)) return false
|
||||
SteamMatch.put(context, game.folder.path,
|
||||
if (identity != null && now != null) SteamMatch.Match(now, SteamMatch.Certainty.FILES, identity.source.name.lowercase(), System.currentTimeMillis())
|
||||
else SteamMatch.Match(null, SteamMatch.Certainty.NONE, "", 0))
|
||||
val dropped = Slot.values().filter { File(cache, SteamGridDb.cacheName(it)).delete() }.toSet()
|
||||
Slot.values().forEach { File(cache, SteamGridDb.cacheName(it) + ".src").delete() }
|
||||
listOf("sgdb-id", "steam-appid", EXTRAS_TRIED).forEach { File(cache, it).delete() }
|
||||
keepRefetch(cache, refetch(cache) + dropped)
|
||||
Log.i(TAG, "${game.name}: its files no longer name Steam app $before; its art is fetched again")
|
||||
return dropped.isNotEmpty()
|
||||
}
|
||||
|
||||
internal fun steamMatch(context: Context, game: AddedGames.Game, search: (String) -> Int?): SteamMatch.Match {
|
||||
if (game.source == Store.BATTLENET.id) {
|
||||
val id = game.storeId?.let(BattleNet::title)?.steam
|
||||
|
||||
@@ -161,6 +161,25 @@ object AddedGames {
|
||||
"appxmanifest.xml" to Regex("<Application\\b[^>]*?\\bExecutable\\s*=\\s*\"([^\"]+)\"", RegexOption.IGNORE_CASE),
|
||||
)
|
||||
|
||||
private val GAME_PARTS = setOf(
|
||||
"bin", "bin32", "bin64", "binaries", "x64", "x86", "win64", "win32", "windows",
|
||||
"launcher", "game", "engine", "system", "data", "app",
|
||||
)
|
||||
|
||||
internal fun groupGames(folder: File): List<File>? {
|
||||
val files = folder.listFiles() ?: return null
|
||||
if (files.any { it.isFile && it.name.endsWith(".exe", ignoreCase = true) && !skipExe(it.name) }) return null
|
||||
if (declaredExes(folder).isNotEmpty()) return null
|
||||
val dirs = files.filter { it.isDirectory && !it.name.startsWith(".") && !isSteamLibraryFolder(it.name) }.sortedBy { it.name.lowercase() }
|
||||
if (dirs.any { it.name.lowercase() in GAME_PARTS || GameExePicker.auxiliaryDir(it) }) return null
|
||||
return dirs.filter { rank(it).exes.isNotEmpty() }.takeIf { it.size >= 2 }
|
||||
}
|
||||
|
||||
private fun expand(folder: File, entries: Set<String>): List<File> =
|
||||
if (folder.path in entries) listOf(folder) else groupGames(folder) ?: listOf(folder)
|
||||
|
||||
private fun entryFolders(context: Context): Set<String> = AddedExes.list(context).map { it.folder }.toSet()
|
||||
|
||||
/** The card's Steam libraries: the arm64 client's steamapps and the x86-64 client's own folder beside it. */
|
||||
internal fun isSteamLibraryFolder(name: String): Boolean =
|
||||
name.equals("steamapps", ignoreCase = true) || name == com.droiddeck.launcher.session.GameStorage.X64_CARD_DIR
|
||||
@@ -173,6 +192,7 @@ object AddedGames {
|
||||
GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
|
||||
)
|
||||
val removed = SessionPrefs.removedAddedGames(context).toSet()
|
||||
val entries = entryFolders(context)
|
||||
for (dir in folders.distinctBy { it.absolutePath }) {
|
||||
if (!dir.isDirectory) { Log.w(TAG, "$dir is not a folder; skipped"); continue }
|
||||
val steamInstalls = steamInstallDirs(dir)
|
||||
@@ -180,7 +200,7 @@ object AddedGames {
|
||||
if (folder.name.lowercase() in steamInstalls || isSteamLibraryFolder(folder.name)) continue
|
||||
if (folder.path in removed) continue
|
||||
if (folder.name == "Games" && StoreInstallRoot.roots(context).any { it.absolutePath == folder.absolutePath }) continue
|
||||
scanGame(context, folder, out)
|
||||
for (game in expand(folder, entries)) if (game.path !in removed) scanGame(context, game, out)
|
||||
}
|
||||
}
|
||||
for (entry in AddedExes.list(context)) {
|
||||
@@ -232,8 +252,9 @@ object AddedGames {
|
||||
val entries = AddedExes.list(context)
|
||||
fun owns(f: File) = holds(f) && sameGame(f, currentExe(context, entries, f), exe)
|
||||
entries.map { File(it.folder) }.filter(::owns).maxByOrNull { canonical(it).length }?.let { return it }
|
||||
SessionPrefs.removedAddedGames(context).map { File(it) }.filter(::owns).maxByOrNull { canonical(it).length }?.let { return it }
|
||||
SessionPrefs.removedAddedGames(context).map { File(it) }.filter { owns(it) && groupGames(it) == null }.maxByOrNull { canonical(it).length }?.let { return it }
|
||||
StoreInstallRoot.gameFolders(context).firstOrNull(::holds)?.let { return it }
|
||||
val removed = SessionPrefs.removedAddedGames(context)
|
||||
val dirs = listOfNotNull(
|
||||
GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
|
||||
GameStorage.effective(context)?.let { File(it.path) },
|
||||
@@ -242,7 +263,10 @@ object AddedGames {
|
||||
val base = canonical(dir)
|
||||
if (!inside(path, base)) continue
|
||||
val first = path.removePrefix("$base/").substringBefore('/')
|
||||
File(dir, first).takeIf { it.isDirectory && !isSteamLibraryFolder(first) }?.let { return it }
|
||||
val top = File(dir, first).takeIf { it.isDirectory && !isSteamLibraryFolder(first) && it.path !in removed } ?: continue
|
||||
val group = groupGames(top) ?: return top
|
||||
if (top.path in entries.map { it.folder }) return null
|
||||
return group.firstOrNull(::holds)
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -295,10 +319,11 @@ object AddedGames {
|
||||
if (guestPath(app, dir) == null) bindFolder(app, dir)
|
||||
val removed = SessionPrefs.removedAddedGames(app).toSet()
|
||||
val listed = listedFolders(app, removed)
|
||||
val entries = entryFolders(app)
|
||||
var already = 0
|
||||
val fresh = ArrayList<String>()
|
||||
val added = ArrayList<Game>()
|
||||
for (sub in dir.listFiles { f -> f.isDirectory && (showHidden || !f.name.startsWith(".")) }?.sortedBy { it.name.lowercase() }.orEmpty()) {
|
||||
for (sub in dir.listFiles { f -> f.isDirectory && (showHidden || !f.name.startsWith(".")) }?.sortedBy { it.name.lowercase() }.orEmpty().flatMap { expand(it, entries) }) {
|
||||
val path = canonical(sub)
|
||||
if (listed.any { it == path || inside(path, it) || inside(it, path) }) { already++; continue }
|
||||
onChecking(sub.name)
|
||||
@@ -332,6 +357,7 @@ object AddedGames {
|
||||
|
||||
private fun listedFolders(context: Context, removed: Set<String>): List<String> {
|
||||
val out = ArrayList<String>()
|
||||
val entries = entryFolders(context)
|
||||
GamesFolderMigration.run(context)
|
||||
val dirs = listOfNotNull(
|
||||
GameStorage.effective(context)?.let { File(it.path) },
|
||||
@@ -341,7 +367,7 @@ object AddedGames {
|
||||
for (folder in dir.listFiles { f -> f.isDirectory }.orEmpty()) {
|
||||
if (folder.path in removed || isSteamLibraryFolder(folder.name)) continue
|
||||
if (folder.name == "Games" && StoreInstallRoot.roots(context).any { it.absolutePath == folder.absolutePath }) continue
|
||||
out.add(canonical(folder))
|
||||
expand(folder, entries).filter { it.path !in removed }.forEach { out.add(canonical(it)) }
|
||||
}
|
||||
}
|
||||
AddedExes.list(context).filter { it.folder !in removed }.forEach { out.add(canonical(File(it.folder))) }
|
||||
|
||||
@@ -89,7 +89,13 @@ object AutoComponents {
|
||||
|
||||
private fun enqueue(context: Context, job: Job) {
|
||||
if (!queuedKeys.add(job.key)) {
|
||||
if (job.asked && jobs.removeIf { it.key == job.key && !it.asked }) jobs.add(job)
|
||||
synchronized(jobs) {
|
||||
val old = jobs.firstOrNull { it.key == job.key }
|
||||
if (old != null && ((job.asked && !old.asked) || (job.inSession && !old.inSession)) && jobs.remove(old)) {
|
||||
jobs.add(Job(old.game ?: job.game, old.component, old.asked || job.asked,
|
||||
if (job.asked && !old.asked) job.seq else old.seq, old.pics ?: job.pics, old.inSession || job.inSession))
|
||||
}
|
||||
}
|
||||
if (runNow && !draining) drain(context)
|
||||
return
|
||||
}
|
||||
@@ -105,10 +111,7 @@ object AutoComponents {
|
||||
|
||||
@VisibleForTesting internal var gameRunning: () -> Boolean = { gameProcessRunning() }
|
||||
|
||||
private fun gameProcessRunning(): Boolean = File("/proc").listFiles()?.any { p ->
|
||||
p.name.all(Char::isDigit) && runCatching { String(File(p, "cmdline").readBytes()).replace('\u0000', ' ') }.getOrNull()
|
||||
?.let { it.contains("SteamLaunch AppId=") || it.contains("proton waitforexitandrun") } == true
|
||||
} == true
|
||||
private fun gameProcessRunning(): Boolean = com.droiddeck.launcher.session.SteamGameProcess.running()
|
||||
|
||||
fun queueInSession(context: Context, game: Library.SteamGame) {
|
||||
if (appKey(game) == null) return
|
||||
@@ -185,18 +188,19 @@ object AutoComponents {
|
||||
val catalog = (catalogOf(context, false) ?: catalogOf(context, true))?.associateBy { it.name } ?: return
|
||||
val wanted = autoPicks(findings, catalog)
|
||||
val user = WinComponents.selection(context, key).user
|
||||
val before = WinComponents.selection(context, key).auto
|
||||
val installed = installedOf(context)
|
||||
val kept = LinkedHashMap<String, WinComponents.AutoReason>()
|
||||
val missing = ArrayList<String>()
|
||||
for ((id, reason) in wanted) {
|
||||
if (user[id] == false) { kept[id] = reason; continue }
|
||||
if (id in installed) { kept[id] = reason; continue }
|
||||
if (id in before) kept[id] = reason
|
||||
synchronized(waiting) { waiting.getOrPut(id) { ArrayList() }.let { if (it.none { g -> appKey(g) == key }) it.add(game) } }
|
||||
queueDownload(context, id, asked, inSession)
|
||||
missing.add(id)
|
||||
}
|
||||
if (inSession) Pending.set(context, key, missing)
|
||||
val before = WinComponents.selection(context, key).auto
|
||||
if (inSession) Pending.set(context, key, (Pending.ids(context, key).filter { it !in installed && it !in wanted } + missing).distinct())
|
||||
if (before.keys != kept.keys) {
|
||||
WinComponents.setAuto(context, key, kept)
|
||||
Log.i(TAG, "${game.name}: on by itself ${kept.keys.joinToString().ifEmpty { "(none)" }}")
|
||||
@@ -235,6 +239,16 @@ object AutoComponents {
|
||||
write(context, games)
|
||||
}
|
||||
|
||||
@Synchronized fun ids(context: Context, key: String): List<String> =
|
||||
read(context).optJSONArray(key)?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty()
|
||||
|
||||
@Synchronized fun add(context: Context, key: String, ids: List<String>) {
|
||||
val games = read(context)
|
||||
val have = games.optJSONArray(key)?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty()
|
||||
games.put(key, JSONArray((have + ids).distinct()))
|
||||
write(context, games)
|
||||
}
|
||||
|
||||
@Synchronized fun drop(context: Context, id: String) {
|
||||
val games = read(context)
|
||||
for (k in games.keys().asSequence().toList()) {
|
||||
@@ -317,6 +331,32 @@ object AutoComponents {
|
||||
|
||||
fun beforeLaunch(context: Context, game: Library.SteamGame) = queueGame(context, game, asked = false)
|
||||
|
||||
fun restoreMissing(context: Context): List<String> {
|
||||
val selections = WinComponents.selections(context)
|
||||
if (selections.isEmpty()) return emptyList()
|
||||
val catalog = (catalogOf(context, false) ?: catalogOf(context, true))?.associateBy { it.name } ?: return emptyList()
|
||||
val installed = installedOf(context)
|
||||
val lostFor = selections.mapValues { (_, selection) ->
|
||||
withParts(selection.effective.filter { WinComponents.validId(it) }, catalog).filter { it !in installed && it in catalog }
|
||||
}.filterValues { it.isNotEmpty() }
|
||||
if (lostFor.isEmpty()) return emptyList()
|
||||
val lost = lostFor.values.flatten().distinct()
|
||||
Log.i(TAG, "wincomp: reinstalling ${lost.joinToString()}, picked for games but missing from the runtime")
|
||||
lostFor.forEach { (key, ids) -> Pending.add(context, key, ids) }
|
||||
lost.forEach { queueDownload(context, it, asked = true, inSession = true) }
|
||||
return lost
|
||||
}
|
||||
|
||||
private fun withParts(ids: List<String>, catalog: Map<String, WinComponents.Component>): List<String> {
|
||||
val out = LinkedHashSet<String>()
|
||||
fun visit(id: String, depth: Int) {
|
||||
if (depth > 8 || !out.add(id)) return
|
||||
catalog[id]?.dependencies?.forEach { visit(it, depth + 1) }
|
||||
}
|
||||
ids.forEach { visit(it, 0) }
|
||||
return out.toList()
|
||||
}
|
||||
|
||||
fun refreshLater(context: Context, game: Library.SteamGame) = queueGame(context, game, asked = true)
|
||||
|
||||
fun sweep(context: Context, games: List<Library.SteamGame>) {
|
||||
|
||||
@@ -89,6 +89,8 @@ object GameExePicker {
|
||||
return score
|
||||
}
|
||||
|
||||
internal fun auxiliaryDir(dir: File): Boolean = skipDir(dir, dir.name)
|
||||
|
||||
private fun skipDir(dir: File, relative: String): Boolean {
|
||||
val name = dir.name.lowercase().trim()
|
||||
if (name in SKIP_DIRS || SKIP_DIR_PREFIX.any { name.startsWith(it) }) return true
|
||||
|
||||
@@ -5,6 +5,7 @@ import java.io.File
|
||||
object GameIdentifier {
|
||||
|
||||
private const val MAX_PARENT_DEPTH = 6
|
||||
internal const val SPACEWAR = 480
|
||||
|
||||
enum class Source { STEAM_APPID_TXT, STEAM_MANIFEST_ACF, STEAM_EMU_INI, GOG_INFO, PE_VERSION, FILENAME, NONE }
|
||||
enum class Confidence { HIGH, MEDIUM, LOW }
|
||||
@@ -92,7 +93,7 @@ object GameIdentifier {
|
||||
for (candidate in arrayOf(File(dir, "steam_appid.txt"), File(dir, "steam_settings/steam_appid.txt"))) {
|
||||
val id = readSmallTextFile(candidate)?.removePrefix("\uFEFF")?.trim()
|
||||
?.takeWhile { it.isDigit() }?.toIntOrNull()
|
||||
if (id != null && id > 0) return id
|
||||
if (id != null && id > 0 && id != SPACEWAR) return id
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -111,7 +112,7 @@ object GameIdentifier {
|
||||
for (f in candidates) {
|
||||
val text = readSmallTextFile(f) ?: continue
|
||||
val id = re.find(text)?.groupValues?.getOrNull(1)?.toIntOrNull()
|
||||
if (id != null && id > 0) return id
|
||||
if (id != null && id > 0 && id != SPACEWAR) return id
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -133,7 +134,8 @@ object GameIdentifier {
|
||||
val match = manifests.firstOrNull { m ->
|
||||
val text = readSmallTextFile(m) ?: return@firstOrNull false
|
||||
val installdir = vdfValue(text, "installdir")
|
||||
gameFolder != null && installdir != null && installdir.equals(gameFolder, ignoreCase = true)
|
||||
gameFolder != null && installdir != null && installdir.equals(gameFolder, ignoreCase = true) &&
|
||||
vdfValue(text, "appid")?.toIntOrNull() != SPACEWAR
|
||||
} ?: return null
|
||||
|
||||
val text = readSmallTextFile(match) ?: return null
|
||||
|
||||
@@ -24,15 +24,33 @@ object GamesFolderMigration {
|
||||
for (root in roots) {
|
||||
var n = 0
|
||||
val steamInstalls = AddedGames.steamInstallDirs(root.host)
|
||||
for (folder in root.host.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() }.orEmpty()) {
|
||||
if (AddedGames.isSteamLibraryFolder(folder.name) || folder.name.lowercase() in steamInstalls) continue
|
||||
if (folder.absolutePath in storeRoots || StoreGameSidecar.read(folder) != null) continue
|
||||
if (folder.path in entries) continue
|
||||
val picked = SessionPrefs.addedGameExe(context, folder.path).takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
|
||||
val exe = picked ?: AddedGames.rank(folder).exes.firstOrNull() ?: continue
|
||||
AddedExes.put(context, AddedExes.Entry(folder.path, exe.path, picked = picked != null))
|
||||
entries.add(folder.path)
|
||||
if (folder.path !in removed) n++
|
||||
for (top in root.host.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() }.orEmpty()) {
|
||||
if (AddedGames.isSteamLibraryFolder(top.name) || top.name.lowercase() in steamInstalls) continue
|
||||
if (top.absolutePath in storeRoots || StoreGameSidecar.read(top) != null) continue
|
||||
if (top.path in entries) continue
|
||||
val topPick = SessionPrefs.addedGameExe(context, top.path).takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
|
||||
val groups = AddedGames.groupGames(top)
|
||||
val played = topPick ?: groups?.let { AddedGames.rank(top).exes.firstOrNull() }
|
||||
val owner = played?.let { exe -> top.listFiles { f -> f.isDirectory }?.firstOrNull { exe.path.startsWith(it.path + File.separator) } }
|
||||
val folders = when {
|
||||
groups == null -> listOf(top)
|
||||
topPick == null || owner in groups -> groups
|
||||
owner == null || owner.name.startsWith(".") || AddedGames.isSteamLibraryFolder(owner.name) -> listOf(top)
|
||||
else -> (groups + owner).sortedBy { it.name.lowercase() }
|
||||
}
|
||||
for (folder in folders) {
|
||||
if (folder.absolutePath in storeRoots || StoreGameSidecar.read(folder) != null) continue
|
||||
if (folder.path in entries) continue
|
||||
val picked = SessionPrefs.addedGameExe(context, folder.path).takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
|
||||
?: topPick?.takeIf { it.path.startsWith(folder.path + File.separator) }
|
||||
val ranked = AddedGames.rank(folder).exes.firstOrNull()
|
||||
val exe = picked ?: played?.takeIf { folder == owner } ?: ranked ?: continue
|
||||
AddedExes.put(context, AddedExes.Entry(folder.path, exe.path, picked = picked != null || exe != ranked))
|
||||
entries.add(folder.path)
|
||||
if (folder != top && folder == owner) SessionPrefs.inheritAddedGame(context, top.path, folder.path)
|
||||
if (folder != top && top.path in removed) SessionPrefs.setAddedGameRemoved(context, folder.path, true)
|
||||
else if (folder.path !in removed) n++
|
||||
}
|
||||
}
|
||||
Log.i(TAG, "games: migrated ${root.host} → $n games")
|
||||
}
|
||||
|
||||
@@ -101,15 +101,22 @@ object Library {
|
||||
libraries: List<File> = steamLibraries(context).map { it.first },
|
||||
): File? {
|
||||
val ids = listOf(appId.toString(), java.lang.Integer.toString(appId.toInt())).distinct()
|
||||
return prefixRoots(context, libraries, preferredLibrary).asSequence()
|
||||
.flatMap { root -> ids.asSequence().map { id -> File(root, "steamapps/compatdata/$id/pfx") } }
|
||||
.firstOrNull { it.isDirectory }
|
||||
}
|
||||
|
||||
/** Every steamapps/compatdata folder, in the libraries [protonPrefix] searches. */
|
||||
fun compatdataDirs(context: Context, libraries: List<File> = steamLibraries(context).map { it.first }): List<File> =
|
||||
prefixRoots(context, libraries).map { File(it, "steamapps/compatdata") }.filter { it.isDirectory }
|
||||
|
||||
private fun prefixRoots(context: Context, libraries: List<File>, preferredLibrary: File? = null): List<File> {
|
||||
val secondary = libraries.drop(1).mapNotNull { runCatching { it.canonicalPath }.getOrNull() }.toSet()
|
||||
fun prefixRoot(root: File): File = if (runCatching { root.canonicalPath }.getOrNull() in secondary)
|
||||
SecondaryLibrary.privateRoot(context.filesDir, root).takeIf { File(it, "steamapps/compatdata").isDirectory } ?: root
|
||||
else root
|
||||
val roots = (listOfNotNull(preferredLibrary) + libraries).map(::prefixRoot)
|
||||
return (listOfNotNull(preferredLibrary) + libraries).map(::prefixRoot)
|
||||
.distinctBy { runCatching { it.canonicalPath }.getOrDefault(it.absolutePath) }
|
||||
return roots.asSequence()
|
||||
.flatMap { root -> ids.asSequence().map { id -> File(root, "steamapps/compatdata/$id/pfx") } }
|
||||
.firstOrNull { it.isDirectory }
|
||||
}
|
||||
|
||||
fun steamGames(
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.stores.SteamLiveShortcuts
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.StandardCopyOption
|
||||
|
||||
object SteamLaunchOptions {
|
||||
private const val TAG = "SteamLaunchOptions"
|
||||
private val STEAM = listOf("UserLocalConfigStore", "Software", "Valve", "Steam")
|
||||
|
||||
fun current(context: Context, appId: Int): String =
|
||||
SteamLiveShortcuts.launchOptions(context, appId.toLong()) ?: steam(SessionPrefs.activeSteamRoot(context), appId).orEmpty()
|
||||
|
||||
enum class Saved { YES, NO, DESKTOP }
|
||||
|
||||
fun set(context: Context, appId: Int, options: String, shown: String): Saved {
|
||||
val value = options.trim()
|
||||
if (SessionState.running && SessionState.mode == SessionService.MODE_DESKTOP) return Saved.DESKTOP
|
||||
if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM) {
|
||||
val live = SteamLiveShortcuts.launchOptions(context, appId.toLong()) ?: return Saved.NO
|
||||
if (live.trim() != shown.trim()) return Saved.NO
|
||||
return if (SteamLiveShortcuts.setLaunchOptions(context, appId.toLong(), value)) Saved.YES else Saved.NO
|
||||
}
|
||||
val home = SessionPrefs.activeSteamRoot(context)
|
||||
if (steam(home, appId).orEmpty().trim() != shown.trim()) return Saved.NO
|
||||
return if (write(home, appId, value)) Saved.YES else Saved.NO
|
||||
}
|
||||
|
||||
internal fun steam(steamHome: File, appId: Int): String? {
|
||||
val config = AddedGames.accountConfig(steamHome) ?: return null
|
||||
val text = runCatching { File(config, "localconfig.vdf").readText() }.getOrNull() ?: return null
|
||||
return launchOptions(text, appId)
|
||||
}
|
||||
|
||||
internal fun write(steamHome: File, appId: Int, options: String): Boolean {
|
||||
val config = AddedGames.accountConfig(steamHome)?.let { File(it, "localconfig.vdf") } ?: return false
|
||||
val text = runCatching { config.readText() }.getOrNull() ?: return false
|
||||
val updated = withLaunchOptions(text, appId, options) ?: return false
|
||||
if (updated == text) return true
|
||||
val staged = File(config.parentFile, config.name + ".staged")
|
||||
return try {
|
||||
staged.writeText(updated)
|
||||
if (config.readText() != text) {
|
||||
staged.delete()
|
||||
return false
|
||||
}
|
||||
Files.move(staged.toPath(), config.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
staged.delete()
|
||||
Log.w(TAG, "could not write launch options to ${config.path}", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
internal fun launchOptions(text: String, appId: Int): String? {
|
||||
val app = section(text, STEAM + "apps" + appId.toString()) ?: return null
|
||||
return entries(text, app.valueStart, app.end).firstOrNull { !it.section && it.key.equals("LaunchOptions", true) }
|
||||
?.let { unescape(text.substring(it.valueStart + 1, it.end)) }
|
||||
}
|
||||
|
||||
internal fun withLaunchOptions(text: String, appId: Int, options: String): String? {
|
||||
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
|
||||
var updated = text
|
||||
var path = STEAM
|
||||
for (key in listOf("apps", appId.toString())) {
|
||||
updated = withSection(updated, section(updated, path) ?: return null, key, newline) ?: return null
|
||||
path = path + key
|
||||
}
|
||||
val app = section(updated, path) ?: return null
|
||||
val value = "\"" + escape(options) + "\""
|
||||
entries(updated, app.valueStart, app.end).firstOrNull { !it.section && it.key.equals("LaunchOptions", true) }?.let {
|
||||
return updated.replaceRange(it.valueStart, it.end + 1, value)
|
||||
}
|
||||
val lineStart = closingLine(updated, app) ?: return null
|
||||
val indent = updated.substring(lineStart, app.end) + "\t"
|
||||
return updated.substring(0, lineStart) + indent + "\"LaunchOptions\"\t\t" + value + newline + updated.substring(lineStart)
|
||||
}
|
||||
|
||||
private class Entry(val key: String, val valueStart: Int, val end: Int, val section: Boolean)
|
||||
|
||||
private fun section(text: String, path: List<String>): Entry? {
|
||||
var found: Entry? = null
|
||||
for (key in path) {
|
||||
found = entries(text, found?.valueStart ?: -1, found?.end ?: text.length)
|
||||
.firstOrNull { it.section && it.key.equals(key, true) } ?: return null
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
private fun entries(text: String, open: Int, close: Int): List<Entry> {
|
||||
val found = ArrayList<Entry>()
|
||||
var key: String? = null
|
||||
var i = open + 1
|
||||
while (i < close) {
|
||||
when {
|
||||
text[i] == '"' -> {
|
||||
val end = stringEnd(text, i) ?: return found
|
||||
if (key == null) key = unescape(text.substring(i + 1, end)) else { found += Entry(key, i, end, false); key = null }
|
||||
i = end + 1
|
||||
}
|
||||
text[i] == '{' -> {
|
||||
val end = sectionEnd(text, i) ?: return found
|
||||
key?.let { found += Entry(it, i, end, true) }
|
||||
key = null
|
||||
i = end + 1
|
||||
}
|
||||
text.startsWith("//", i) -> i = text.indexOf('\n', i).let { if (it < 0) close else it }
|
||||
else -> i++
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
private fun stringEnd(text: String, open: Int): Int? {
|
||||
var i = open + 1
|
||||
while (i < text.length) {
|
||||
when (text[i]) {
|
||||
'\\' -> i += 2
|
||||
'"' -> return i
|
||||
else -> i++
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun sectionEnd(text: String, open: Int): Int? {
|
||||
var depth = 0
|
||||
var i = open
|
||||
while (i < text.length) {
|
||||
when (text[i]) {
|
||||
'"' -> i = stringEnd(text, i) ?: return null
|
||||
'{' -> depth++
|
||||
'}' -> if (--depth == 0) return i
|
||||
}
|
||||
i++
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun withSection(text: String, parent: Entry, key: String, newline: String): String? {
|
||||
if (entries(text, parent.valueStart, parent.end).any { it.section && it.key.equals(key, true) }) return text
|
||||
val lineStart = closingLine(text, parent) ?: return null
|
||||
val indent = text.substring(lineStart, parent.end) + "\t"
|
||||
return text.substring(0, lineStart) + "$indent\"$key\"$newline$indent{$newline$indent}$newline" + text.substring(lineStart)
|
||||
}
|
||||
|
||||
private fun closingLine(text: String, section: Entry): Int? {
|
||||
val lineStart = text.lastIndexOf('\n', section.end - 1) + 1
|
||||
return lineStart.takeIf { lineStart > section.valueStart && text.substring(lineStart, section.end).all { it == '\t' || it == ' ' } }
|
||||
}
|
||||
|
||||
private fun escape(value: String) = value.replace("\\", "\\\\").replace("\"", "\\\"")
|
||||
|
||||
private fun unescape(value: String) = value.replace(Regex("\\\\(.)"), "$1")
|
||||
}
|
||||
@@ -45,15 +45,15 @@ object SteamMatch {
|
||||
identity?.appId?.let { id ->
|
||||
return Match(id, Certainty.FILES, identity.source.name.lowercase(), now).also { put(context, key, it) }
|
||||
}
|
||||
val known = get(context, key)
|
||||
val known = get(context, key)?.takeUnless { it.appId == GameIdentifier.SPACEWAR }
|
||||
if (known != null && known.certainty == Certainty.NAME) return known
|
||||
if (known != null && known.certainty == Certainty.NONE && now - known.checkedAt < RETRY_AFTER_MS) return known
|
||||
legacy?.takeIf { it.isFile }?.let { runCatching { it.readText().trim().toInt() }.getOrNull() }?.takeIf { it > 0 }?.let { id ->
|
||||
legacy?.takeIf { it.isFile }?.let { runCatching { it.readText().trim().toInt() }.getOrNull() }?.takeIf { it > 0 && it != GameIdentifier.SPACEWAR }?.let { id ->
|
||||
return Match(id, Certainty.NAME, "store search", now).also { put(context, key, it) }
|
||||
}
|
||||
if (search == null) return known?.takeIf { it.certainty != Certainty.FILES } ?: Match(null, Certainty.NONE, "", 0)
|
||||
val id = runCatching { search(name) }.getOrNull()
|
||||
val match = if (id != null && id > 0) Match(id, Certainty.NAME, "store search", now) else Match(null, Certainty.NONE, "", now)
|
||||
val match = if (id != null && id > 0 && id != GameIdentifier.SPACEWAR) Match(id, Certainty.NAME, "store search", now) else Match(null, Certainty.NONE, "", now)
|
||||
put(context, key, match)
|
||||
return match
|
||||
}
|
||||
|
||||
+7
-7
@@ -3,14 +3,14 @@ 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 {
|
||||
/** DroidDeck HUD's settings as one "key=value,…" string (DroidDeckHudView.applyConfig), stored in SessionPrefs. */
|
||||
internal object DroidDeckHudConfig {
|
||||
/**
|
||||
* Bannerlator's Fusion defaults (DeckOverlaySettings), with the FPS graph from the old DroidDeck HUD. The HUD starts
|
||||
* Bannerlator's defaults (DeckOverlaySettings), with the FPS graph from the old DroidDeck HUD. The HUD starts
|
||||
* locked, so like the old HUD it lets touches through until it is unlocked to move it.
|
||||
*/
|
||||
val DEFAULTS: Map<String, String> = linkedMapOf(
|
||||
"hudSize" to "minimal", "hudLocked" to "1", "hudScale" to "100", "hudOpacity" to "80", "hudColor" to "mid",
|
||||
"hudSize" to "minimal", "hudLocked" to "1", "hudScale" to "100", "hudDock" to "none", "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",
|
||||
@@ -25,7 +25,7 @@ internal object FusionHudConfig {
|
||||
|
||||
fun load(context: Context): MutableMap<String, String> {
|
||||
val values = LinkedHashMap(DEFAULTS)
|
||||
val stored = SessionPrefs.fusionHudConfig(context)
|
||||
val stored = SessionPrefs.droidDeckHudConfig(context)
|
||||
if (stored == null) {
|
||||
values["showFPS"] = flag(SessionPrefs.hudShowFps(context))
|
||||
values["showFPSGraph"] = flag(SessionPrefs.hudShowGraph(context))
|
||||
@@ -43,12 +43,12 @@ internal object FusionHudConfig {
|
||||
if (key !in DEFAULTS) return values
|
||||
values[key] = value
|
||||
TWINS[key]?.let { values[it] = value }
|
||||
SessionPrefs.setFusionHudConfig(context, encode(values))
|
||||
SessionPrefs.setDroidDeckHudConfig(context, encode(values))
|
||||
return values
|
||||
}
|
||||
|
||||
fun reset(context: Context): Map<String, String> {
|
||||
SessionPrefs.setFusionHudConfig(context, encode(DEFAULTS))
|
||||
SessionPrefs.setDroidDeckHudConfig(context, encode(DEFAULTS))
|
||||
return DEFAULTS
|
||||
}
|
||||
|
||||
+135
-14
@@ -6,26 +6,28 @@ import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.Choreographer
|
||||
import android.view.View
|
||||
import android.view.animation.PathInterpolator
|
||||
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.ui.Motion
|
||||
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
|
||||
* DroidDeck HUD 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) {
|
||||
class DroidDeckHudHost(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 view: DroidDeckHudView? = null
|
||||
private var parent: ViewGroup? = null
|
||||
private var running = false
|
||||
private var hidden = false
|
||||
@@ -41,6 +43,9 @@ class FusionHudHost(context: Context) {
|
||||
|
||||
var onPresentingWindowChanged: (() -> Unit)? = null
|
||||
|
||||
/** The frame rate the HUD shows; null while the HUD is off and not counting frames. */
|
||||
val liveFps: Float? get() = if (polling) feed.stats.fps else null
|
||||
|
||||
/** The HUD itself changed a setting: a tap cycles the size, a long press locks it. */
|
||||
var onConfigChanged: (() -> Unit)? = null
|
||||
|
||||
@@ -49,7 +54,7 @@ class FusionHudHost(context: Context) {
|
||||
|
||||
private val listener = object : WaylandCompositor.GameListener {
|
||||
override fun onGameSurface(window: String?, gpuName: String?) {
|
||||
if (!gpuName.isNullOrBlank()) handler.post { this@FusionHudHost.gpuName = cleanGpuName(gpuName) }
|
||||
if (!gpuName.isNullOrBlank()) handler.post { this@DroidDeckHudHost.gpuName = cleanGpuName(gpuName) }
|
||||
if (window != null && window != lastWindow) {
|
||||
lastWindow = window
|
||||
handler.post { onPresentingWindowChanged?.invoke() }
|
||||
@@ -76,20 +81,26 @@ class FusionHudHost(context: Context) {
|
||||
/** 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)
|
||||
val hud = DroidDeckHudView(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
|
||||
dockEdgeFor(hud)?.let { edge -> setDock(hud, edge); return@setOnMovedListener }
|
||||
keepOnScreen(hud)
|
||||
wantX = hud.x; wantY = hud.y
|
||||
SessionPrefs.setFusionHudPosition(context, hud.x, hud.y)
|
||||
SessionPrefs.setDroidDeckHudPosition(context, hud.x, hud.y)
|
||||
}
|
||||
hud.setOnSizeCycledListener { size -> DroidDeckHudConfig.set(context, "hudSize", size); onConfigChanged?.invoke() }
|
||||
hud.setOnDockChangedListener { token -> setDock(hud, DroidDeckHudDock.from(token)) }
|
||||
hud.setOnScaledListener { percent ->
|
||||
DroidDeckHudConfig.set(context, "hudScale", percent.toString())
|
||||
onConfigChanged?.invoke()
|
||||
}
|
||||
hud.setOnSizeCycledListener { size -> FusionHudConfig.set(context, "hudSize", size); onConfigChanged?.invoke() }
|
||||
hud.setOnLockChangedListener { locked ->
|
||||
FusionHudConfig.set(context, "hudLocked", if (locked) "1" else "0")
|
||||
DroidDeckHudConfig.set(context, "hudLocked", if (locked) "1" else "0")
|
||||
onConfigChanged?.invoke()
|
||||
}
|
||||
hud.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> if (!hud.isDragging) keepOnScreen(hud) }
|
||||
@@ -100,14 +111,14 @@ class FusionHudHost(context: Context) {
|
||||
leftMargin = margin
|
||||
topMargin = margin
|
||||
})
|
||||
SessionPrefs.fusionHudPosition(context)?.let { (x, y) -> wantX = x; wantY = y; hud.post { keepOnScreen(hud) } }
|
||||
SessionPrefs.droidDeckHudPosition(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)))
|
||||
view?.applyConfig(DroidDeckHudConfig.encode(DroidDeckHudConfig.load(context)))
|
||||
}
|
||||
|
||||
fun refresh() {
|
||||
@@ -157,7 +168,7 @@ class FusionHudHost(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
/** A sensor report (FusionHUD's diagnostics) in Downloads/DroidDeck; null when it can't be written. */
|
||||
/** A sensor report (DroidDeck HUD'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()
|
||||
@@ -180,7 +191,7 @@ class FusionHudHost(context: Context) {
|
||||
file
|
||||
}.getOrNull()
|
||||
|
||||
private fun refreshLabels(hud: FusionHudView) {
|
||||
private fun refreshLabels(hud: DroidDeckHudView) {
|
||||
if (feed.engine.isNotBlank() && !feed.steamFocused) engine = feed.engine
|
||||
hud.setEngineLabel(engine)
|
||||
if (gpuName.isNotBlank()) hud.setGpuModel(gpuName)
|
||||
@@ -203,6 +214,105 @@ class FusionHudHost(context: Context) {
|
||||
return if (stats.size > 3 && stats[3] > 1f) stats[3] else 0f
|
||||
}
|
||||
|
||||
/** The edge the HUD was dropped over, once a good part of it hangs past that edge; null when it stays. */
|
||||
private fun dockEdgeFor(v: View): DroidDeckHudDock? {
|
||||
val p = v.parent as? View ?: return null
|
||||
if (p.width <= 0 || p.height <= 0 || v.width <= 0 || v.height <= 0) return null
|
||||
val over = mapOf(
|
||||
DroidDeckHudDock.LEFT to -v.x / v.width,
|
||||
DroidDeckHudDock.RIGHT to (v.x + v.width - p.width) / v.width,
|
||||
DroidDeckHudDock.TOP to -v.y / v.height,
|
||||
DroidDeckHudDock.BOTTOM to (v.y + v.height - p.height) / v.height,
|
||||
).maxByOrNull { it.value } ?: return null
|
||||
return over.key.takeIf { over.value >= DOCK_OVERHANG }
|
||||
}
|
||||
|
||||
/** Tucks the HUD against [edge] as its FPS tab, or with [DroidDeckHudDock.NONE] brings it back out from where it was docked. */
|
||||
private fun setDock(hud: DroidDeckHudView, edge: DroidDeckHudDock) {
|
||||
if (edge == hud.dock) return
|
||||
animateDock(hud, edge) { commitDock(hud, edge) }
|
||||
}
|
||||
|
||||
private fun commitDock(hud: DroidDeckHudView, edge: DroidDeckHudDock) {
|
||||
if (edge == DroidDeckHudDock.NONE) {
|
||||
when (hud.dock) {
|
||||
DroidDeckHudDock.LEFT -> wantX = 0f
|
||||
DroidDeckHudDock.RIGHT -> wantX = Float.MAX_VALUE
|
||||
DroidDeckHudDock.TOP -> wantY = 0f
|
||||
DroidDeckHudDock.BOTTOM -> wantY = Float.MAX_VALUE
|
||||
DroidDeckHudDock.NONE -> {}
|
||||
}
|
||||
} else {
|
||||
val p = hud.parent as? View
|
||||
if (p != null) {
|
||||
wantX = wantX.coerceIn(0f, p.width.toFloat())
|
||||
wantY = wantY.coerceIn(0f, p.height.toFloat())
|
||||
}
|
||||
SessionPrefs.setDroidDeckHudPosition(context, wantX, wantY)
|
||||
}
|
||||
DroidDeckHudConfig.set(context, "hudDock", edge.token)
|
||||
applyConfig()
|
||||
hud.post { keepOnScreen(hud) }
|
||||
onConfigChanged?.invoke()
|
||||
}
|
||||
|
||||
/**
|
||||
* One shape contracts into the tab, and the tab expands back out to the HUD: the view is scaled onto the
|
||||
* tab's exact rectangle, and the layouts swap at that same size and place. Timing and curve are the
|
||||
* launcher's own ([Motion]), and off when animations are off.
|
||||
*/
|
||||
private fun animateDock(hud: DroidDeckHudView, edge: DroidDeckHudDock, commit: () -> Unit) {
|
||||
hud.animate().cancel()
|
||||
hud.scaleX = 1f; hud.scaleY = 1f; hud.alpha = 1f
|
||||
val p = hud.parent as? View
|
||||
if (Motion.scale == 0f || p == null || !hud.isLaidOut || hud.width <= 0) { commit(); return }
|
||||
if (edge != DroidDeckHudDock.NONE) {
|
||||
val (tabW, tabH) = hud.dockTabSize()
|
||||
val (tabX, tabY) = settled(p, edge, tabW, tabH)
|
||||
val sx = tabW / hud.width; val sy = tabH / hud.height
|
||||
hud.pivotX = pivotFor(hud.x, tabX, sx) - hud.x
|
||||
hud.pivotY = pivotFor(hud.y, tabY, sy) - hud.y
|
||||
hud.animate().scaleX(sx).scaleY(sy).setDuration(Motion.ms(300).toLong()).setInterpolator(EASE)
|
||||
.withEndAction {
|
||||
commit()
|
||||
hud.scaleX = 1f; hud.scaleY = 1f
|
||||
hud.x = tabX; hud.y = tabY
|
||||
hud.alpha = 0.5f
|
||||
hud.animate().alpha(1f).setDuration(Motion.ms(120).toLong()).start()
|
||||
}.start()
|
||||
} else {
|
||||
val tabX = hud.x; val tabY = hud.y
|
||||
val tabW = hud.width.toFloat(); val tabH = hud.height.toFloat()
|
||||
commit()
|
||||
val w = hud.contentWidth; val h = hud.contentHeight
|
||||
val (x, y) = settled(p, DroidDeckHudDock.NONE, w, h)
|
||||
hud.x = x; hud.y = y
|
||||
val sx = tabW / w; val sy = tabH / h
|
||||
hud.pivotX = pivotFor(x, tabX, sx) - x
|
||||
hud.pivotY = pivotFor(y, tabY, sy) - y
|
||||
hud.scaleX = sx; hud.scaleY = sy
|
||||
hud.animate().scaleX(1f).scaleY(1f).setDuration(Motion.ms(360).toLong()).setInterpolator(EASE).start()
|
||||
}
|
||||
}
|
||||
|
||||
/** The pivot, in parent coordinates, that scaling by [scale] takes a span starting at [from] onto one starting at [to]. */
|
||||
private fun pivotFor(from: Float, to: Float, scale: Float): Float =
|
||||
if (scale > 0.999f) from else (to - from * scale) / (1f - scale)
|
||||
|
||||
/** Where a [w] x [h] HUD or tab sits once [keepOnScreen] has settled it against [dock]. */
|
||||
private fun settled(p: View, dock: DroidDeckHudDock, w: Float, h: Float): Pair<Float, Float> {
|
||||
val maxX = (p.width - w).coerceAtLeast(0f); val maxY = (p.height - h).coerceAtLeast(0f)
|
||||
var x = wantX.coerceIn(0f, maxX); var y = wantY.coerceIn(0f, maxY)
|
||||
when (dock) {
|
||||
DroidDeckHudDock.LEFT -> x = 0f
|
||||
DroidDeckHudDock.RIGHT -> x = maxX
|
||||
DroidDeckHudDock.TOP -> y = 0f
|
||||
DroidDeckHudDock.BOTTOM -> y = maxY
|
||||
DroidDeckHudDock.NONE -> {}
|
||||
}
|
||||
return Pair(x, y)
|
||||
}
|
||||
|
||||
// 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.
|
||||
@@ -212,13 +322,24 @@ class FusionHudHost(context: Context) {
|
||||
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)
|
||||
var x = wantX.coerceIn(0f, maxX)
|
||||
var y = wantY.coerceIn(0f, maxY)
|
||||
when (v.let { it as? DroidDeckHudView }?.dock) {
|
||||
DroidDeckHudDock.LEFT -> x = 0f
|
||||
DroidDeckHudDock.RIGHT -> x = maxX
|
||||
DroidDeckHudDock.TOP -> y = 0f
|
||||
DroidDeckHudDock.BOTTOM -> y = maxY
|
||||
else -> {}
|
||||
}
|
||||
if (v.x != x) v.x = x
|
||||
if (v.y != y) v.y = y
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** How much of the HUD, as a share of its own size, must hang past a screen edge for it to dock there. */
|
||||
private const val DOCK_OVERHANG = 0.4f
|
||||
private val EASE = PathInterpolator(0.2f, 0.8f, 0.2f, 1f)
|
||||
|
||||
/** True while the HUD is on screen; DroidDeck keeps sampling VRAM for it (GpuMemComponent). */
|
||||
@Volatile @JvmStatic var showing = false
|
||||
private set
|
||||
+16
-7
@@ -14,11 +14,11 @@
|
||||
package com.droiddeck.launcher.hud
|
||||
|
||||
/**
|
||||
* Size modes for the Fusion HUD (the 4th selectable in-game overlay style). One shared color-coded
|
||||
* Size modes for the DroidDeck 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) {
|
||||
enum class DroidDeckHudSize(val token: String, val label: String) {
|
||||
FULL("full", "Full"),
|
||||
TILES("tiles", "Tiles"),
|
||||
PILL("pill", "Pill"),
|
||||
@@ -26,7 +26,7 @@ enum class FusionSize(val token: String, val label: String) {
|
||||
MEGA("mega", "Mega");
|
||||
|
||||
/** Next size in the tap-cycle: Full → Tiles → Pill → Minimal → Mega → Full. */
|
||||
fun next(): FusionSize {
|
||||
fun next(): DroidDeckHudSize {
|
||||
val all = values()
|
||||
return all[(ordinal + 1) % all.size]
|
||||
}
|
||||
@@ -45,7 +45,7 @@ enum class FusionSize(val token: String, val label: String) {
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun from(token: String?): FusionSize =
|
||||
fun from(token: String?): DroidDeckHudSize =
|
||||
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
|
||||
@@ -66,12 +66,21 @@ enum class FusionSize(val token: String, val label: String) {
|
||||
}
|
||||
}
|
||||
|
||||
/** The screen edge the HUD is tucked against, where only its FPS tab shows ([NONE] = floating free). */
|
||||
enum class DroidDeckHudDock(val token: String) {
|
||||
NONE("none"), LEFT("left"), RIGHT("right"), TOP("top"), BOTTOM("bottom");
|
||||
|
||||
companion object {
|
||||
fun from(token: String?): DroidDeckHudDock = values().firstOrNull { it.token == token } ?: NONE
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* The Wayland HDR state the DroidDeck HUD shows on its own line, directly under the latency · display-server
|
||||
* line (the host sets it with [DroidDeckHudView.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 {
|
||||
object DroidDeckHudHdr {
|
||||
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+)
|
||||
+127
-46
@@ -23,6 +23,7 @@ import android.graphics.Path
|
||||
import android.graphics.RectF
|
||||
import android.graphics.Typeface
|
||||
import android.text.format.DateFormat
|
||||
import android.view.GestureDetector
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import androidx.annotation.VisibleForTesting
|
||||
@@ -32,6 +33,7 @@ import java.util.Date
|
||||
import java.util.Locale
|
||||
import java.util.function.BiConsumer
|
||||
import java.util.function.Consumer
|
||||
import java.util.function.IntConsumer
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.roundToInt
|
||||
@@ -47,7 +49,7 @@ import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
|
||||
/**
|
||||
* Fusion HUD — the 4th selectable in-game overlay. One color-coded visual language rendered at four
|
||||
* DroidDeck 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.
|
||||
*
|
||||
@@ -60,7 +62,7 @@ import kotlinx.coroutines.withTimeoutOrNull
|
||||
* drag are frozen while locked. A locked HUD lets a touch through where an on-screen control under it
|
||||
* takes it ([passesTouchAt]); everywhere else it keeps the touch, so a long press there unlocks it.
|
||||
*/
|
||||
class FusionHudView(context: Context) : View(context) {
|
||||
class DroidDeckHudView(context: Context) : View(context) {
|
||||
|
||||
private var frames: FrameStats? = null
|
||||
internal fun setFrameStats(stats: FrameStats?) { frames = stats }
|
||||
@@ -78,7 +80,7 @@ class FusionHudView(context: Context) : View(context) {
|
||||
private val density = resources.displayMetrics.density
|
||||
|
||||
// ---- Config -----------------------------------------------------------
|
||||
private var size = FusionSize.FULL
|
||||
private var size = DroidDeckHudSize.FULL
|
||||
private var scale = 1f
|
||||
private var bgOpacity = 0.8f
|
||||
private var outlineIntensity = 0.4f
|
||||
@@ -114,7 +116,7 @@ class FusionHudView(context: Context) : View(context) {
|
||||
|
||||
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 hdrState = DroidDeckHudHdr.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
|
||||
@@ -146,7 +148,13 @@ class FusionHudView(context: Context) : View(context) {
|
||||
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
|
||||
// Pushed past a screen edge, the HUD shrinks to a tab with the FPS that stays at that edge.
|
||||
var dock = DroidDeckHudDock.NONE
|
||||
private set
|
||||
private var tabRect: RectF? = null
|
||||
private val tabPath = Path()
|
||||
|
||||
// Every size sits in the DroidDeck mark's D: a straight left side, 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
|
||||
@@ -213,11 +221,41 @@ class FusionHudView(context: Context) : View(context) {
|
||||
fun setOnMovedListener(l: BiConsumer<Float, Float>?) { onMovedListener = l }
|
||||
fun setOnSizeCycledListener(l: Consumer<String>?) { onSizeCycledListener = l }
|
||||
fun setOnLockChangedListener(l: Consumer<Boolean>?) { onLockChangedListener = l }
|
||||
private var onDockChangedListener: Consumer<String>? = null
|
||||
private var onScaledListener: IntConsumer? = null
|
||||
fun setOnDockChangedListener(l: Consumer<String>?) { onDockChangedListener = l }
|
||||
/** A pinch settled on this size, in percent. */
|
||||
fun setOnScaledListener(l: IntConsumer?) { onScaledListener = 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) }
|
||||
override fun onPinch(factor: Float) {
|
||||
val next = (scale * factor).coerceIn(MIN_SCALE, MAX_SCALE)
|
||||
if (next == scale) return
|
||||
scale = next
|
||||
rebuildAndInvalidate()
|
||||
}
|
||||
override fun onPinchEnd() { onScaledListener?.accept((scale * 100f).roundToInt()) }
|
||||
})
|
||||
|
||||
// A docked tab always takes touches, locked or not: a tap or a pull away from the edge brings the HUD back.
|
||||
private val dockDetector = GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() {
|
||||
override fun onDown(e: MotionEvent): Boolean = true
|
||||
override fun onSingleTapUp(e: MotionEvent): Boolean { onDockChangedListener?.accept(DroidDeckHudDock.NONE.token); return true }
|
||||
override fun onScroll(e1: MotionEvent?, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean {
|
||||
if (e1 == null) return false
|
||||
val inward = when (dock) {
|
||||
DroidDeckHudDock.LEFT -> e2.rawX - e1.rawX
|
||||
DroidDeckHudDock.RIGHT -> e1.rawX - e2.rawX
|
||||
DroidDeckHudDock.TOP -> e2.rawY - e1.rawY
|
||||
DroidDeckHudDock.BOTTOM -> e1.rawY - e2.rawY
|
||||
DroidDeckHudDock.NONE -> 0f
|
||||
}
|
||||
if (inward > 12f * density) onDockChangedListener?.accept(DroidDeckHudDock.NONE.token)
|
||||
return true
|
||||
}
|
||||
})
|
||||
|
||||
// ---- Public surface (symmetric with the other overlays) ---------------
|
||||
@@ -227,9 +265,9 @@ class FusionHudView(context: Context) : View(context) {
|
||||
* 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. */
|
||||
/** [DroidDeckHudHdr] code; [DroidDeckHudHdr.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
|
||||
val v = if (state in DroidDeckHudHdr.ON..DroidDeckHudHdr.NOT_ON_THIS_SCREEN) state else DroidDeckHudHdr.NONE
|
||||
post { if (v != hdrState) { hdrState = v; rebuildAndInvalidate() } }
|
||||
}
|
||||
fun setWineVersion(s: String?) { if ((s ?: "") != wineVersion) { wineVersion = s ?: ""; post { rebuildAndInvalidate() } } }
|
||||
@@ -255,7 +293,7 @@ class FusionHudView(context: Context) : View(context) {
|
||||
if (graphRect != null) invalidate()
|
||||
}
|
||||
|
||||
/** Fusion has no orientation (tap cycles size instead); kept for a symmetric host surface. */
|
||||
/** The HUD has no orientation (tap cycles size instead); kept for a symmetric host surface. */
|
||||
fun setVertical(vertical: Boolean) { /* no-op */ }
|
||||
fun isVertical(): Boolean = false
|
||||
|
||||
@@ -269,7 +307,7 @@ class FusionHudView(context: Context) : View(context) {
|
||||
if (configString.isNullOrEmpty()) return
|
||||
val cfg = KeyValueSet(configString)
|
||||
|
||||
size = FusionSize.from(cfg.get("hudSize", "minimal"))
|
||||
size = DroidDeckHudSize.from(cfg.get("hudSize", "minimal"))
|
||||
showFPS = cfg.get("showFPS", "1") == "1"
|
||||
showEngine = cfg.get("showEngine", "1") == "1"
|
||||
showGpuModel = cfg.get("showGpuModel", "1") == "1"
|
||||
@@ -285,7 +323,7 @@ class FusionHudView(context: Context) : View(context) {
|
||||
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
|
||||
showClockTime = cfg.get("showClock", "1") == "1" // the clock defaults ON
|
||||
showPerCore = cfg.get("showPerCore", "1") == "1"
|
||||
showSwap = cfg.get("showSwap", "1") == "1"
|
||||
showNet = cfg.get("showNet", "1") == "1"
|
||||
@@ -296,6 +334,7 @@ class FusionHudView(context: Context) : View(context) {
|
||||
showSession = cfg.get("showSession", "1") == "1"
|
||||
tempDisplay = HudMetrics.TempDisplay.from(cfg)
|
||||
lockController.setLocked(cfg.get("hudLocked", "1") == "1")
|
||||
dock = DroidDeckHudDock.from(cfg.get("hudDock", "none"))
|
||||
|
||||
colorIntensity = when (cfg.get("hudColor", "vivid")) {
|
||||
"soft" -> 0.72f; "mid" -> 0.88f; else -> 1.0f
|
||||
@@ -453,27 +492,27 @@ class FusionHudView(context: Context) : View(context) {
|
||||
private fun glowing(spans: List<Span>): List<Span> =
|
||||
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) ----
|
||||
// ---- Wayland HDR state (one line of its own; nothing at all for DroidDeckHudHdr.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<Span> = 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))
|
||||
DroidDeckHudHdr.ON -> listOf(Span("HDR", colHdr, px))
|
||||
DroidDeckHudHdr.NO_HEADROOM -> listOf(Span("HDR", colHdr, px), Span(" (no headroom)", colBat, px))
|
||||
DroidDeckHudHdr.OFF -> listOf(Span("HDR off", colDim, px))
|
||||
DroidDeckHudHdr.READY -> listOf(Span("HDR ready", colDim, px))
|
||||
DroidDeckHudHdr.TONEMAPPED -> listOf(Span("HDR", colDim, px), Span(" tone-mapped", colBat, px))
|
||||
DroidDeckHudHdr.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<Span> = 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))
|
||||
DroidDeckHudHdr.ON -> listOf(Span("on", colHdr, px))
|
||||
DroidDeckHudHdr.NO_HEADROOM -> listOf(Span("no headroom", colBat, px))
|
||||
DroidDeckHudHdr.OFF -> listOf(Span("off", colDim, px))
|
||||
DroidDeckHudHdr.READY -> listOf(Span("ready", colDim, px))
|
||||
DroidDeckHudHdr.TONEMAPPED -> listOf(Span("tone-mapped", colBat, px))
|
||||
DroidDeckHudHdr.NOT_ON_THIS_SCREEN -> listOf(Span("not on this screen", colBat, px))
|
||||
else -> emptyList()
|
||||
}
|
||||
private fun hdrText(): String = hdrLine(1f).joinToString("") { it.text }
|
||||
@@ -495,26 +534,65 @@ class FusionHudView(context: Context) : View(context) {
|
||||
// ---- Layout builders --------------------------------------------------
|
||||
private fun rebuild() {
|
||||
glyphs.clear(); tileRects.clear(); graphRect = null
|
||||
headerMark = null; chipRect = null; dPanel = null; dDividerTop = -1f
|
||||
headerMark = null; chipRect = null; dPanel = null; dDividerTop = -1f; tabRect = null
|
||||
val s = snap
|
||||
if (s == null) { contentW = 0f; contentH = 0f; return }
|
||||
if (dock != DroidDeckHudDock.NONE) { buildDockTab(); 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) }
|
||||
DroidDeckHudSize.FULL -> { buildFull(s); intoPanel(sp(10f), header = true) }
|
||||
DroidDeckHudSize.TILES -> { buildTiles(s); intoPanel(sp(9f), header = true) }
|
||||
DroidDeckHudSize.PILL -> { buildPill(s); intoPanel(sp(10f), header = false) }
|
||||
DroidDeckHudSize.MINIMAL -> buildMinimal(s)
|
||||
DroidDeckHudSize.MEGA -> { buildMega(s); intoPanel(sp(10f), header = true) }
|
||||
}
|
||||
}
|
||||
|
||||
/** The docked tab: the FPS alone, in a box square on the edge it sits against. */
|
||||
private fun buildDockTab() {
|
||||
val numPx = sp(20f)
|
||||
val spans = tabSpans()
|
||||
val padX = sp(9f); val padY = sp(7f)
|
||||
placeRun(padX, padY + capHeight(numPx), spans)
|
||||
val (w, h) = dockTabSize()
|
||||
contentW = w; contentH = h
|
||||
tabRect = RectF(0f, 0f, contentW, contentH)
|
||||
}
|
||||
|
||||
private fun tabSpans() = listOf(Span(one(fpsNow), colValue, sp(20f)), Span("fps", colDim, sp(8.5f)))
|
||||
|
||||
/** The size the docked tab has, so the HUD can contract to exactly that shape before the tab replaces it. */
|
||||
internal fun dockTabSize(): Pair<Float, Float> =
|
||||
Pair(runWidth(tabSpans()) + 2f * sp(9f), capHeight(sp(20f)) + 2f * sp(7f))
|
||||
|
||||
private fun drawTab(canvas: Canvas, rect: RectF) {
|
||||
val r = sp(8f); val stroke = max(outlineWidth(), sp(1.5f)); val h = stroke / 2f
|
||||
val round = floatArrayOf(r, r, r, r, r, r, r, r)
|
||||
val edge = when (dock) {
|
||||
DroidDeckHudDock.LEFT -> intArrayOf(0, 3)
|
||||
DroidDeckHudDock.RIGHT -> intArrayOf(1, 2)
|
||||
DroidDeckHudDock.TOP -> intArrayOf(0, 1)
|
||||
DroidDeckHudDock.BOTTOM -> intArrayOf(2, 3)
|
||||
DroidDeckHudDock.NONE -> intArrayOf()
|
||||
}
|
||||
for (corner in edge) { round[corner * 2] = 0f; round[corner * 2 + 1] = 0f }
|
||||
tabPath.rewind()
|
||||
tabPath.addRoundRect(rect.left + h, rect.top + h, rect.right - h, rect.bottom - h, round, Path.Direction.CW)
|
||||
headerPaint.shader = null
|
||||
headerPaint.color = withAlpha(panelColor(), max(Color.alpha(panelColor()), 200))
|
||||
canvas.drawPath(tabPath, headerPaint)
|
||||
strokePaint.strokeWidth = stroke
|
||||
strokePaint.color = outlineColor()
|
||||
canvas.drawPath(tabPath, strokePaint)
|
||||
}
|
||||
|
||||
// ---- 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 footerClock(): Boolean = showClockTime && size == DroidDeckHudSize.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 panelLeft() = sp(13f) // the outline's glow sticks 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
|
||||
@@ -672,7 +750,7 @@ class FusionHudView(context: Context) : View(context) {
|
||||
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)
|
||||
if (hdrState != DroidDeckHudHdr.NONE)
|
||||
rows.add(HudRow(Span("HDR", colHdr, rowPx), hdrValue(rowPx)))
|
||||
if (showGPU) {
|
||||
val v = ArrayList<Span>()
|
||||
@@ -784,7 +862,7 @@ class FusionHudView(context: Context) : View(context) {
|
||||
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 (hdrState != DroidDeckHudHdr.NONE) hdrText() else null, false))
|
||||
if (showGpuModel && gpuNameText().isNotBlank())
|
||||
tiles.add(Tile("GPU", colGpu, gpuModelSpans(valPx, colValue), null, true))
|
||||
if (showBattery || showPower || showBatteryTemp) {
|
||||
@@ -893,7 +971,7 @@ class FusionHudView(context: Context) : View(context) {
|
||||
}
|
||||
// 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))
|
||||
if (hdrState != DroidDeckHudHdr.NONE) stack.add(hdrLine(stkPx))
|
||||
|
||||
var statsW = 0f
|
||||
for (l in stack) statsW = max(statsW, runWidth(l))
|
||||
@@ -963,7 +1041,7 @@ class FusionHudView(context: Context) : View(context) {
|
||||
}
|
||||
val footerLabel = listOf(if (showEngine) engineLabel else "", displayServer)
|
||||
.filter { it.isNotBlank() }.joinToString(" · ")
|
||||
val hdr = if (hdrState != FusionHdr.NONE) hdrLine(footPx) else emptyList()
|
||||
val hdr = if (hdrState != DroidDeckHudHdr.NONE) hdrLine(footPx) else emptyList()
|
||||
|
||||
val (headerBottom, headerRight) = addPanelHeader(left, inner)
|
||||
val x = headerRight
|
||||
@@ -1143,7 +1221,7 @@ class FusionHudView(context: Context) : View(context) {
|
||||
val band = ArrayList<List<Span>>()
|
||||
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 (hdrState != DroidDeckHudHdr.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()) {
|
||||
@@ -1204,6 +1282,7 @@ class FusionHudView(context: Context) : View(context) {
|
||||
}
|
||||
|
||||
chipRect?.let { drawChip(canvas, it) }
|
||||
tabRect?.let { drawTab(canvas, it) }
|
||||
|
||||
// Text
|
||||
for (g in glyphs) {
|
||||
@@ -1253,19 +1332,17 @@ class FusionHudView(context: Context) : View(context) {
|
||||
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
|
||||
* when it is half the height). */
|
||||
private fun dShape(l: Float, t: Float, r: Float, b: Float, rad: Float, corner: Float): Path {
|
||||
return Path().apply {
|
||||
if (split > 0f) moveTo(l, cy + split) else moveTo(l, t + corner)
|
||||
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()
|
||||
close()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1285,7 +1362,7 @@ class FusionHudView(context: Context) : View(context) {
|
||||
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)
|
||||
val body = dShape(panel.left, panel.top, panel.right, panel.bottom, dRadius, corner)
|
||||
bgPaint.color = panelColor()
|
||||
c.drawPath(body, bgPaint)
|
||||
c.save()
|
||||
@@ -1307,7 +1384,7 @@ class FusionHudView(context: Context) : View(context) {
|
||||
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 outline = dShape(panel.left + h, panel.top + h, panel.right - h, panel.bottom - h, dRadius - h, corner)
|
||||
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.
|
||||
@@ -1315,8 +1392,6 @@ class FusionHudView(context: Context) : View(context) {
|
||||
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
|
||||
}
|
||||
@@ -1358,15 +1433,21 @@ class FusionHudView(context: Context) : View(context) {
|
||||
|
||||
// Declining the down event hands the whole gesture to the views under the HUD.
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
if (dock != DroidDeckHudDock.NONE) return dockDetector.onTouchEvent(event)
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN && lockController.isLocked() &&
|
||||
passesTouchAt?.invoke(event.rawX, event.rawY) == true) return false
|
||||
return lockController.onTouchEvent(event)
|
||||
}
|
||||
|
||||
internal val contentWidth: Float get() = contentW
|
||||
internal val contentHeight: Float get() = contentH
|
||||
|
||||
internal val isDragging: Boolean get() = lockController.isDragging()
|
||||
|
||||
private companion object {
|
||||
const val REFRESH_MS = 500L
|
||||
const val MIN_SCALE = 0.5f
|
||||
const val MAX_SCALE = 2f
|
||||
const val GRAPH_CLIP_MS = 49.9f
|
||||
|
||||
fun parseIntOr(s: String?, d: Int): Int = try { s?.trim()?.toInt() ?: d } catch (e: Exception) { d }
|
||||
@@ -8,7 +8,7 @@ import kotlin.math.roundToInt
|
||||
* 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.
|
||||
* taken over those 200. Average and lows are DroidDeck HUD's own readouts.
|
||||
*/
|
||||
internal class FrameStats {
|
||||
private val graph = FloatArray(GRAPH_FRAMES)
|
||||
|
||||
@@ -22,6 +22,7 @@ import android.graphics.RectF;
|
||||
import android.os.SystemClock;
|
||||
import android.view.GestureDetector;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.ScaleGestureDetector;
|
||||
import android.view.View;
|
||||
|
||||
import java.util.function.BiConsumer;
|
||||
@@ -29,17 +30,17 @@ 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
|
||||
* GameHub PerfHudView, GameNative PerformanceHudView, and the DroidDeck HUD). One place so the four
|
||||
* overlays can't drift:
|
||||
*
|
||||
* <ul>
|
||||
* <li><b>tap</b> → {@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.</li>
|
||||
* the DroidDeck HUD) — a no-op that only re-flashes the lock badge while locked.</li>
|
||||
* <li><b>drag</b> → moves the host view and, on release, {@link Callbacks#onMoved} to persist the
|
||||
* position — disabled (frozen) while locked.</li>
|
||||
* <li><b>long-press</b> → 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); a locked {@code FusionHudView} passes touches on only over on-screen controls.</li>
|
||||
* always unlocks); a locked {@code DroidDeckHudView} passes touches on only over on-screen controls.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>On every lock/unlock (and on a blocked gesture while locked) a small padlock badge fades in →
|
||||
@@ -52,12 +53,16 @@ import java.util.function.Consumer;
|
||||
public class HudLockController {
|
||||
|
||||
public interface Callbacks {
|
||||
/** Unlocked single tap: orientation-toggle (classic/gamehub/gamenative) or size-cycle (fusion). */
|
||||
/** Unlocked single tap: orientation-toggle (classic/gamehub/gamenative) or size-cycle (DroidDeck HUD). */
|
||||
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);
|
||||
/** Two-finger pinch (unlocked): the change since the previous event, above 1 when the fingers spread. */
|
||||
default void onPinch(float factor) {}
|
||||
/** The fingers came off a pinch: persist the new size. */
|
||||
default void onPinchEnd() {}
|
||||
}
|
||||
|
||||
// Fade timing (ms): in → hold → out. Lock/unlock hold ~1.5 s; a blocked-gesture re-flash is shorter.
|
||||
@@ -70,12 +75,15 @@ public class HudLockController {
|
||||
private final View view;
|
||||
private final Callbacks cb;
|
||||
private final GestureDetector detector;
|
||||
private final ScaleGestureDetector scaleDetector;
|
||||
|
||||
private boolean locked = false;
|
||||
|
||||
// Drag state
|
||||
private float downRawX, downRawY, startX, startY;
|
||||
private boolean dragging = false;
|
||||
// A pinch ends the gesture's drag and tap: the finger left down after it must not move the HUD.
|
||||
private boolean pinched = false;
|
||||
|
||||
// Fade state
|
||||
private long fadeStart = 0;
|
||||
@@ -90,6 +98,8 @@ public class HudLockController {
|
||||
this.cb = cb;
|
||||
this.detector = new GestureDetector(context, new Listener());
|
||||
this.detector.setIsLongpressEnabled(true);
|
||||
this.scaleDetector = new ScaleGestureDetector(context, new PinchListener());
|
||||
this.scaleDetector.setQuickScaleEnabled(false);
|
||||
iconFill.setStyle(Paint.Style.FILL);
|
||||
iconStroke.setStyle(Paint.Style.STROKE);
|
||||
iconStroke.setStrokeCap(Paint.Cap.ROUND);
|
||||
@@ -105,6 +115,7 @@ public class HudLockController {
|
||||
|
||||
/** Feed from the host view's onTouchEvent. Always consumes (mirrors the legacy manual handlers). */
|
||||
public boolean onTouchEvent(MotionEvent event) {
|
||||
scaleDetector.onTouchEvent(event);
|
||||
detector.onTouchEvent(event);
|
||||
int action = event.getActionMasked();
|
||||
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
|
||||
@@ -122,6 +133,7 @@ public class HudLockController {
|
||||
startX = view.getX();
|
||||
startY = view.getY();
|
||||
dragging = false;
|
||||
pinched = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -135,6 +147,7 @@ public class HudLockController {
|
||||
|
||||
@Override
|
||||
public boolean onSingleTapUp(MotionEvent e) {
|
||||
if (pinched) return true;
|
||||
if (locked) {
|
||||
flash(true, HOLD_REFLASH_MS); // intentionally locked — remind the user
|
||||
} else {
|
||||
@@ -145,6 +158,7 @@ public class HudLockController {
|
||||
|
||||
@Override
|
||||
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
|
||||
if (pinched) return true;
|
||||
if (locked) {
|
||||
if (!dragging) flash(true, HOLD_REFLASH_MS);
|
||||
dragging = true; // mark so the blocked drag doesn't fall through to a tap
|
||||
@@ -157,6 +171,27 @@ public class HudLockController {
|
||||
}
|
||||
}
|
||||
|
||||
private final class PinchListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
|
||||
@Override
|
||||
public boolean onScaleBegin(ScaleGestureDetector d) {
|
||||
if (locked) return false;
|
||||
pinched = true;
|
||||
dragging = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onScale(ScaleGestureDetector d) {
|
||||
cb.onPinch(d.getScaleFactor());
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onScaleEnd(ScaleGestureDetector d) {
|
||||
cb.onPinchEnd();
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Fade badge -------------------------------------------------------
|
||||
private void flash(boolean showLocked, long hold) {
|
||||
fadeShowLocked = showLocked;
|
||||
|
||||
@@ -1006,7 +1006,7 @@ public class HudMetrics {
|
||||
// =======================================================================
|
||||
|
||||
/**
|
||||
* Immutable point-in-time reading of every metric the Fusion HUD draws. Collected in one pass by
|
||||
* Immutable point-in-time reading of every metric the DroidDeck 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.
|
||||
@@ -1268,7 +1268,7 @@ public class HudMetrics {
|
||||
Snapshot s = snapshot();
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("DroidDeck FusionHUD diagnostics\n");
|
||||
sb.append("DroidDeck HUD 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');
|
||||
|
||||
@@ -4,7 +4,11 @@ import android.content.Context
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.os.Build
|
||||
import android.view.Display
|
||||
import android.view.InputDevice
|
||||
import android.view.MotionEvent
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
object DualScreen {
|
||||
const val MODE_AUTO = "auto"
|
||||
@@ -13,17 +17,54 @@ object DualScreen {
|
||||
val modes = listOf(MODE_AUTO, MODE_ON, MODE_OFF)
|
||||
private const val TYPE_INTERNAL = 1
|
||||
private val knownModels = setOf("retroid pocket duo", "ayn thor")
|
||||
private val touchedDisplays = mutableSetOf<Int>()
|
||||
|
||||
fun builtInDisplay(displayManager: DisplayManager, primaryDisplayId: Int): Display? =
|
||||
fun builtInDisplay(displayManager: DisplayManager, primaryDisplayId: Int): Display? {
|
||||
val primary = displayManager.getDisplay(primaryDisplayId)
|
||||
val awake = primary?.state != Display.STATE_OFF
|
||||
val panels = if (awake) touchPanels() else emptyList()
|
||||
return internalDisplay(displayManager, primaryDisplayId) {
|
||||
if (awake && it.state == Display.STATE_OFF) return@internalDisplay false
|
||||
synchronized(touchedDisplays) {
|
||||
if (awake && hasOwnTouchPanel(size(it), primary?.let(::size), panels)) touchedDisplays += it.displayId
|
||||
it.displayId in touchedDisplays
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun internalDisplay(displayManager: DisplayManager, primaryDisplayId: Int, accept: (Display) -> Boolean = { true }): Display? =
|
||||
displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION).firstOrNull {
|
||||
it.isValid && it.displayId != primaryDisplayId && (it.flags and Display.FLAG_PRESENTATION) != 0 &&
|
||||
isBuiltIn(displayType(it), Build.MODEL)
|
||||
isBuiltIn(displayType(it), Build.MODEL) && accept(it)
|
||||
}
|
||||
|
||||
internal fun hasOwnTouchPanel(display: Pair<Int, Int>, primary: Pair<Int, Int>?, panels: List<Pair<Int, Int>>): Boolean {
|
||||
val matching = panels.count { covers(it, display) }
|
||||
return if (primary != null && covers(primary, display)) matching >= 2 else matching >= 1
|
||||
}
|
||||
|
||||
private fun covers(panel: Pair<Int, Int>, display: Pair<Int, Int>): Boolean =
|
||||
(near(panel.first, display.first) && near(panel.second, display.second)) ||
|
||||
(near(panel.first, display.second) && near(panel.second, display.first))
|
||||
|
||||
private fun near(a: Int, b: Int) = abs(a - b) <= 2
|
||||
|
||||
private fun size(display: Display): Pair<Int, Int> =
|
||||
display.mode.let { it.physicalWidth to it.physicalHeight }
|
||||
|
||||
private fun touchPanels(): List<Pair<Int, Int>> =
|
||||
InputDevice.getDeviceIds().toList().mapNotNull { id ->
|
||||
val device = InputDevice.getDevice(id) ?: return@mapNotNull null
|
||||
if (device.isVirtual || !device.supportsSource(InputDevice.SOURCE_TOUCHSCREEN)) return@mapNotNull null
|
||||
val x = device.getMotionRange(MotionEvent.AXIS_X, InputDevice.SOURCE_TOUCHSCREEN) ?: return@mapNotNull null
|
||||
val y = device.getMotionRange(MotionEvent.AXIS_Y, InputDevice.SOURCE_TOUCHSCREEN) ?: return@mapNotNull null
|
||||
(x.max - x.min + 1f).roundToInt() to (y.max - y.min + 1f).roundToInt()
|
||||
}
|
||||
|
||||
fun display(context: Context, displayManager: DisplayManager, primaryDisplayId: Int): Display? =
|
||||
when (SessionPrefs.dualScreenMode(context)) {
|
||||
MODE_OFF -> null
|
||||
MODE_ON -> builtInDisplay(displayManager, primaryDisplayId) ?: anyDisplay(displayManager, primaryDisplayId)
|
||||
MODE_ON -> internalDisplay(displayManager, primaryDisplayId) ?: anyDisplay(displayManager, primaryDisplayId)
|
||||
else -> builtInDisplay(displayManager, primaryDisplayId)
|
||||
}
|
||||
|
||||
|
||||
@@ -60,6 +60,7 @@ class HomeButtonService : AccessibilityService(), InputManager.InputDeviceListen
|
||||
|
||||
override fun onUnbind(intent: Intent?): Boolean {
|
||||
HomeButtonShortcuts.release()
|
||||
com.droiddeck.launcher.core.SteamIntegration.syncShortcutsListing(this)
|
||||
return super.onUnbind(intent)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import android.view.InputDevice
|
||||
import android.view.KeyEvent
|
||||
import androidx.annotation.StringRes
|
||||
import com.droiddeck.launcher.R
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONException
|
||||
import org.json.JSONObject
|
||||
|
||||
object PhysicalShortcuts {
|
||||
internal const val KEY = "physicalShortcuts"
|
||||
private const val TAG = "PhysicalShortcuts"
|
||||
|
||||
enum class Action(@StringRes val label: Int) {
|
||||
STEAM(R.string.drawer_steam_menu),
|
||||
QAM(R.string.drawer_open_qam),
|
||||
DROIDDECK(R.string.shortcuts_dd_menu),
|
||||
}
|
||||
|
||||
data class Button(
|
||||
val device: String,
|
||||
val name: String,
|
||||
val keyCode: Int,
|
||||
val scanCode: Int,
|
||||
) {
|
||||
fun matches(event: KeyEvent): Boolean =
|
||||
event.device?.let { device == identity(it) } == true &&
|
||||
keyCode == event.keyCode && scanCode == event.scanCode
|
||||
|
||||
fun sameInput(other: Button): Boolean =
|
||||
device == other.device && keyCode == other.keyCode && scanCode == other.scanCode
|
||||
|
||||
val label: String
|
||||
get() = KeyEvent.keyCodeToString(keyCode).removePrefix("KEYCODE_").removePrefix("BUTTON_")
|
||||
|
||||
}
|
||||
|
||||
data class Binding(val button: Button, val action: Action)
|
||||
|
||||
private fun identity(device: InputDevice): String =
|
||||
"${device.vendorId}:${device.productId}:${device.descriptor.ifBlank { device.name }}"
|
||||
|
||||
fun isVolumeKey(event: KeyEvent): Boolean = when (event.keyCode) {
|
||||
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> true
|
||||
else -> false
|
||||
}
|
||||
|
||||
fun isDrawerNavigationKey(event: KeyEvent): Boolean = when (event.keyCode) {
|
||||
KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN,
|
||||
KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT -> true
|
||||
else -> false
|
||||
}
|
||||
|
||||
fun button(event: KeyEvent): Button? {
|
||||
val device = event.device ?: return null
|
||||
if (device.isVirtual || isVolumeKey(event)) return null
|
||||
when (event.keyCode) {
|
||||
KeyEvent.KEYCODE_HOME, KeyEvent.KEYCODE_POWER, KeyEvent.KEYCODE_SLEEP,
|
||||
KeyEvent.KEYCODE_WAKEUP, KeyEvent.KEYCODE_APP_SWITCH -> return null
|
||||
}
|
||||
if (event.keyCode == KeyEvent.KEYCODE_UNKNOWN && event.scanCode <= 0) return null
|
||||
return Button(identity(device), device.name, event.keyCode, event.scanCode)
|
||||
}
|
||||
|
||||
fun read(context: Context): List<Binding> {
|
||||
val raw = ControllerPrefs.prefs(context).getString(KEY, null) ?: return emptyList()
|
||||
return try {
|
||||
val array = JSONArray(raw)
|
||||
buildList {
|
||||
for (i in 0 until array.length()) {
|
||||
try {
|
||||
val entry = array.getJSONObject(i)
|
||||
val action = Action.entries.firstOrNull { it.name == entry.getString("action") }
|
||||
val code = entry.getInt("keyCode")
|
||||
val scan = entry.getInt("scanCode")
|
||||
val device = entry.getString("device")
|
||||
if (action == null || device.isBlank() || code < 0 || scan < 0) {
|
||||
Log.w(TAG, "Ignoring invalid shortcut at index $i")
|
||||
continue
|
||||
}
|
||||
val binding = Binding(Button(device, entry.getString("name"), code, scan), action)
|
||||
if (none { it.button.sameInput(binding.button) }) add(binding)
|
||||
} catch (e: JSONException) {
|
||||
Log.w(TAG, "Ignoring malformed shortcut at index $i", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: JSONException) {
|
||||
Log.w(TAG, "Could not read physical shortcuts; reset shortcuts to restore defaults", e)
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
fun assign(context: Context, button: Button, action: Action) {
|
||||
val bindings = read(context).filterNot {
|
||||
it.button.sameInput(button) || (it.button.device == button.device && it.action == action)
|
||||
} + Binding(button, action)
|
||||
write(context, bindings)
|
||||
}
|
||||
|
||||
fun remove(context: Context, binding: Binding) {
|
||||
write(context, read(context).filterNot { it == binding })
|
||||
}
|
||||
|
||||
private fun write(context: Context, bindings: List<Binding>) {
|
||||
val array = JSONArray()
|
||||
bindings.forEach {
|
||||
array.put(JSONObject().put("device", it.button.device).put("name", it.button.name)
|
||||
.put("keyCode", it.button.keyCode).put("scanCode", it.button.scanCode).put("action", it.action.name))
|
||||
}
|
||||
ControllerPrefs.prefs(context).edit().putString(KEY, array.toString()).apply()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class PhysicalShortcutRouter {
|
||||
var bindings: List<PhysicalShortcuts.Binding> = emptyList()
|
||||
private data class Press(val device: Int, val keyCode: Int, val scanCode: Int)
|
||||
private val held = mutableSetOf<Press>()
|
||||
|
||||
fun onKey(event: KeyEvent, enabled: Boolean, steam: Boolean, perform: (PhysicalShortcuts.Action) -> Unit): Boolean {
|
||||
val press = Press(event.deviceId, event.keyCode, event.scanCode)
|
||||
if (event.action == KeyEvent.ACTION_UP) return held.remove(press)
|
||||
if (event.action != KeyEvent.ACTION_DOWN) return false
|
||||
if (press in held) return true
|
||||
if (!enabled || bindings.isEmpty()) return false
|
||||
val button = PhysicalShortcuts.button(event) ?: return false
|
||||
val binding = bindings.firstOrNull { it.button.sameInput(button) } ?: return false
|
||||
if (!steam && binding.action != PhysicalShortcuts.Action.DROIDDECK) return false
|
||||
held.add(press)
|
||||
if (event.repeatCount == 0) perform(binding.action)
|
||||
return true
|
||||
}
|
||||
|
||||
fun onDeviceRemoved(deviceId: Int) {
|
||||
held.removeAll { it.device == deviceId }
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
held.clear()
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ class PointerGestures {
|
||||
fun onScroll(dx: Float, dy: Float) {}
|
||||
fun onScrollEnd() {}
|
||||
fun onZoom(steps: Int) {}
|
||||
fun onThreeFingerTap(): Boolean = false
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
@@ -10,6 +10,22 @@ enum class SecondScreenMode(val id: String, @StringRes val label: Int) {
|
||||
KEYBOARD_TRACKPAD("keyboard-trackpad", R.string.second_mode_keyboard_trackpad),
|
||||
TERMINAL("terminal", R.string.second_mode_terminal),
|
||||
DECK_CONTROLS("deck-controls", R.string.second_mode_deck_controls),
|
||||
DASHBOARD("dashboard", R.string.second_mode_dashboard);
|
||||
|
||||
companion object {
|
||||
fun opening(remembered: String?, deckPad: Boolean, dashboard: Boolean = false): SecondScreenMode {
|
||||
entries.firstOrNull {
|
||||
it != NONE && it.id == remembered && (it != DECK_CONTROLS || deckPad) && (it != DASHBOARD || dashboard)
|
||||
}?.let { return it }
|
||||
// No pick yet: the dashboard. A pick that can't open right now keeps the old fallback.
|
||||
val picked = entries.any { it != NONE && it.id == remembered }
|
||||
return when {
|
||||
dashboard && !picked -> DASHBOARD
|
||||
deckPad -> DECK_CONTROLS
|
||||
else -> KEYBOARD_TRACKPAD
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class SecondScreenDisplay(val id: Int, val label: String)
|
||||
|
||||
@@ -240,7 +240,8 @@ class TouchpadGestures(
|
||||
}
|
||||
if (desktop && scrolled && event.pointerCount == 2) listener.onScrollEnd()
|
||||
if (fingers >= 3) {
|
||||
if (event.pointerCount == 2 && secondWasTap && !scrolled && event.eventTime - downAt < TouchTiming.TAP_MS * 2)
|
||||
if (event.pointerCount == 2 && secondWasTap && !scrolled && event.eventTime - downAt < TouchTiming.TAP_MS * 2 &&
|
||||
!listener.onThreeFingerTap())
|
||||
click(PointerGestures.BTN_MIDDLE)
|
||||
if (event.pointerCount == 2) secondWasTap = false
|
||||
} else if (twoFingers && secondWasTap && event.eventTime - secondDownAt < TouchTiming.TAP_MS && !scrolled) {
|
||||
|
||||
@@ -75,7 +75,10 @@ object BwrapSpawner {
|
||||
}
|
||||
}
|
||||
|
||||
class Plan(val root: File, val binds: List<Bind>, val cwd: String, val argv: List<String>, val env: Map<String, String>)
|
||||
class Plan(
|
||||
val root: File, val binds: List<Bind>, val cwd: String, val argv: List<String>, val env: Map<String, String>,
|
||||
val envTool: String = "/usr/bin/env",
|
||||
)
|
||||
|
||||
data class Bind(val host: String, val guest: String) {
|
||||
val spec: String get() = if (host == guest) host else "$host:$guest"
|
||||
@@ -179,12 +182,13 @@ object BwrapSpawner {
|
||||
val argv = request.getJSONArray("argv").let { a -> (0 until a.length()).map { a.getString(it) } }
|
||||
val env = LinkedHashMap<String, String>()
|
||||
request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> env[k] = e.getString(k) } }
|
||||
if (binds.any { it.guest == "/dev" }) gpu(rootfs, root, env)?.forEach { addBind(it) }
|
||||
val envTool = request.optString("envTool").takeIf { it.startsWith("/") }
|
||||
if (envTool == null && binds.any { it.guest == "/dev" }) gpu(rootfs, root, env)?.forEach { addBind(it) }
|
||||
val libc = listOf("/usr/lib/aarch64-linux-gnu/libc.so.6", "/lib/aarch64-linux-gnu/libc.so.6").map { hostPath(binds, root.path, it) }
|
||||
if (preloadFits(rootfs, libc.firstOrNull { File(it).isFile } ?: libc.first())) preload(session, rootfs, env).forEach { addBind(it) }
|
||||
if (envTool == null && preloadFits(rootfs, libc.firstOrNull { File(it).isFile } ?: libc.first())) preload(session, rootfs, env).forEach { addBind(it) }
|
||||
zypakShims(binds, root, dir).forEach { addBind(it) }
|
||||
browserSandboxes(env)
|
||||
return Plan(root, binds, request.optString("cwd", "/").ifEmpty { "/" }, argv, env)
|
||||
return Plan(root, binds, request.optString("cwd", "/").ifEmpty { "/" }, argv, env, envTool ?: "/usr/bin/env")
|
||||
}
|
||||
|
||||
private const val GPU_DIR = "/run/droiddeck-gpu"
|
||||
@@ -325,7 +329,7 @@ object BwrapSpawner {
|
||||
val verbose = plan.env["DROIDDECK_PROOT_VERBOSE"]?.toIntOrNull()
|
||||
if (verbose != null) { cmd.add(1, "-v"); cmd.add(2, verbose.toString()) }
|
||||
plan.binds.forEach { cmd.add("-b"); cmd.add(it.spec) }
|
||||
cmd.add("/usr/bin/env")
|
||||
cmd.add(plan.envTool)
|
||||
cmd.add("-i")
|
||||
plan.env.forEach { (k, v) -> cmd.add("$k=$v") }
|
||||
cmd.addAll(plan.argv)
|
||||
|
||||
@@ -19,7 +19,7 @@ object FlatpakManager {
|
||||
@Volatile var busy: String? = null
|
||||
private set
|
||||
|
||||
class App(val id: String, val name: String, val icon: File?, val branch: String, val summary: String?)
|
||||
class App(val id: String, val name: String, val icon: File?, val branch: String, val summary: String?, val arch: String = "aarch64")
|
||||
|
||||
fun ready(context: Context): Boolean {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
@@ -33,24 +33,33 @@ object FlatpakManager {
|
||||
else -> "aarch64"
|
||||
}
|
||||
|
||||
internal fun arches(native: String = arch()): List<String> = if (native == "aarch64") listOf("aarch64", "x86_64") else listOf(native)
|
||||
|
||||
internal fun installedBranch(appDir: File, native: String = arch()): Pair<String, File>? =
|
||||
arches(native).firstNotNullOfOrNull { arch ->
|
||||
File(appDir, arch).listFiles()?.firstOrNull { File(it, "active").exists() }?.let { arch to it }
|
||||
}
|
||||
|
||||
fun foreign(app: App, native: String = arch()): Boolean = app.arch != native
|
||||
|
||||
fun launchArgs(app: App, native: String = arch()): List<String> = if (foreign(app, native)) listOf("--arch=${app.arch}", app.id) else listOf(app.id)
|
||||
|
||||
fun installedApps(context: Context): List<App> {
|
||||
val apps = File(LinuxRuntime.rootDir(context), "$USER_DIR/app")
|
||||
val arch = arch()
|
||||
return apps.listFiles()?.mapNotNull { dir ->
|
||||
val id = dir.name
|
||||
val archDir = File(dir, arch)
|
||||
val branch = archDir.listFiles()?.firstOrNull { File(it, "active").exists() } ?: return@mapNotNull null
|
||||
val (arch, branch) = installedBranch(dir) ?: return@mapNotNull null
|
||||
val active = File(branch, "active")
|
||||
val export = File(active, "export/share")
|
||||
val desktop = FileUtils.readString(File(export, "applications/$id.desktop"))
|
||||
val name = desktop?.let { entry(it, "Name") } ?: id.substringAfterLast('.')
|
||||
val summary = desktop?.let { entry(it, "Comment") }
|
||||
App(id, name, icon(export, id), branch.name, summary)
|
||||
App(id, name, icon(export, id), branch.name, summary, arch)
|
||||
}?.sortedBy { it.name.lowercase() } ?: emptyList()
|
||||
}
|
||||
|
||||
fun isInstalled(context: Context, id: String): Boolean =
|
||||
File(LinuxRuntime.rootDir(context), "$USER_DIR/app/$id/${arch()}").listFiles()?.any { File(it, "active").exists() } == true
|
||||
installedBranch(File(LinuxRuntime.rootDir(context), "$USER_DIR/app/$id")) != null
|
||||
|
||||
private fun entry(desktop: String, key: String): String? {
|
||||
var inMain = false
|
||||
@@ -117,7 +126,11 @@ object FlatpakManager {
|
||||
when (o.optString("e")) {
|
||||
"op" -> { step = stage(context, o); onProgress(step, overall(o, 0)) }
|
||||
"progress" -> onProgress(step, overall(o, o.optInt("percent")))
|
||||
"error" -> { error = o.optString("message"); Log.w(TAG, "$verb $id: $error") }
|
||||
"error" -> {
|
||||
error = if (o.optString("code") == "arch") context.getString(R.string.flatpakmgr_wrong_arch, o.optString("id"), o.optString("arch"))
|
||||
else o.optString("message")
|
||||
Log.w(TAG, "$verb $id: ${o.optString("message")}")
|
||||
}
|
||||
"warning" -> Log.w(TAG, "$verb $id: ${o.optString("message")}")
|
||||
"done" -> onDone(o)
|
||||
}
|
||||
|
||||
@@ -113,12 +113,16 @@ public final class LinuxRuntime {
|
||||
}
|
||||
|
||||
public static boolean isInstalled(Context context) {
|
||||
return hasRootfs(context) && (patchedProot(context) || rootfsProotReady(context));
|
||||
}
|
||||
|
||||
/** The rootfs alone: enough to read the game library, while the proot pack can still be downloading. */
|
||||
public static boolean hasRootfs(Context context) {
|
||||
if (LinuxRuntimeInstaller.isRemoving() || LinuxRuntimeInstaller.hasRemovalPending(context)) return false;
|
||||
File root = rootDir(context);
|
||||
return (new File(root, "usr/bin/gamescope").isFile() || new File(root, "usr/games/gamescope").isFile())
|
||||
&& (new File(root, SESSION_SCRIPT.substring(1)).isFile()
|
||||
|| new File(root, LegacyNames.SESSION_SCRIPT.substring(1)).isFile())
|
||||
&& (patchedProot(context) || rootfsProotReady(context));
|
||||
|| new File(root, LegacyNames.SESSION_SCRIPT.substring(1)).isFile());
|
||||
}
|
||||
|
||||
public static File vulkanIcd(Context context) {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.BuildConfig
|
||||
|
||||
object RuntimeAutoUpdate {
|
||||
private const val PREFS = "runtime-auto-update"
|
||||
const val MAX_ATTEMPTS = 3
|
||||
const val RETRY_MS = 10 * 60_000L
|
||||
|
||||
fun due(installed: String?, release: String?, attempts: Int, lastAt: Long = 0L, now: Long = lastAt + RETRY_MS): Boolean =
|
||||
installed != null && !release.isNullOrEmpty() && release != installed && attempts < MAX_ATTEMPTS &&
|
||||
(attempts == 0 || now - lastAt !in 0 until RETRY_MS)
|
||||
|
||||
fun key(appVersion: Int, release: String) = "$appVersion:$release"
|
||||
|
||||
fun claim(context: Context, installed: String?, release: String?, now: Long = System.currentTimeMillis()): Boolean {
|
||||
if (release.isNullOrEmpty()) return false
|
||||
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
val key = key(BuildConfig.VERSION_CODE, release)
|
||||
synchronized(this) {
|
||||
val attempts = prefs.getInt(key, 0)
|
||||
if (!due(installed, release, attempts, prefs.getLong("$key@at", 0L), now)) return false
|
||||
val edit = prefs.edit()
|
||||
prefs.all.keys.filterNot { it.startsWith("${BuildConfig.VERSION_CODE}:") }.forEach { edit.remove(it) }
|
||||
edit.putInt(key, attempts + 1).putLong("$key@at", now).apply()
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -80,7 +80,7 @@ public final class RuntimeFileTree {
|
||||
* be carried.
|
||||
*/
|
||||
static java.util.List<String> userPaths(File tree) throws IOException {
|
||||
java.util.List<String> paths = new java.util.ArrayList<>(java.util.Arrays.asList("root", "opt/appimages/user", "opt/droiddeck-apps"));
|
||||
java.util.List<String> paths = new java.util.ArrayList<>(java.util.Arrays.asList("root", "opt/appimages/user", "opt/droiddeck-apps", "opt/droiddeck/wincomponents"));
|
||||
for (String n : children(new File(tree, "usr/local/share/applications"))) {
|
||||
if (n.endsWith(".desktop") && (n.startsWith("droiddeck-app-") || n.startsWith("droiddeck-appimage-")))
|
||||
paths.add("usr/local/share/applications/" + n);
|
||||
|
||||
@@ -97,7 +97,8 @@ object UserApps {
|
||||
App(
|
||||
"flatpak:${app.id}", Kind.FLATPAK, readName(custom) ?: app.name,
|
||||
File(custom, "icon.png").takeIf { it.isFile } ?: app.icon ?: FlathubApi.iconUrl(app.id),
|
||||
app.summary, FlatpakManager.LAUNCHER, listOf(app.id),
|
||||
app.summary, FlatpakManager.LAUNCHER, FlatpakManager.launchArgs(app),
|
||||
arch = app.arch.takeIf { FlatpakManager.foreign(app) },
|
||||
)
|
||||
}
|
||||
return (scripts + images + flatpaks).sortedBy { it.name.lowercase() }
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.app.Notification
|
||||
import android.content.Context
|
||||
import android.service.notification.NotificationListenerService
|
||||
import android.service.notification.StatusBarNotification
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
|
||||
/** One notification for the bottom-screen list. Kept in memory only; never written to disk or logs. */
|
||||
data class BottomNotification(val key: String, val app: String, val title: String, val text: String, val postedAt: Long)
|
||||
|
||||
/**
|
||||
* Notifications from other apps for the bottom screen, so a message can be read without leaving the game.
|
||||
* Works only after the user allows DroidDeck notification access in Android settings.
|
||||
*/
|
||||
object BottomNotifications {
|
||||
val items = mutableStateListOf<BottomNotification>()
|
||||
|
||||
fun granted(context: Context): Boolean =
|
||||
context.packageName in NotificationManagerCompat.getEnabledListenerPackages(context)
|
||||
|
||||
internal fun keep(own: String, pkg: String, ongoing: Boolean, groupSummary: Boolean, title: String, text: String): Boolean =
|
||||
pkg != own && !ongoing && !groupSummary && (title.isNotBlank() || text.isNotBlank())
|
||||
|
||||
internal fun add(list: MutableList<BottomNotification>, item: BottomNotification) {
|
||||
list.removeAll { it.key == item.key }
|
||||
list.add(0, item)
|
||||
while (list.size > MAX_ITEMS) list.removeAt(list.lastIndex)
|
||||
}
|
||||
|
||||
fun clear() = items.clear()
|
||||
|
||||
internal fun post(context: Context, sbn: StatusBarNotification) {
|
||||
val n = sbn.notification ?: return
|
||||
val extras = n.extras
|
||||
val title = extras?.getCharSequence(Notification.EXTRA_TITLE)?.toString().orEmpty()
|
||||
val text = (extras?.getCharSequence(Notification.EXTRA_BIG_TEXT) ?: extras?.getCharSequence(Notification.EXTRA_TEXT))?.toString().orEmpty()
|
||||
if (!keep(context.packageName, sbn.packageName, sbn.isOngoing, (n.flags and Notification.FLAG_GROUP_SUMMARY) != 0, title, text)) return
|
||||
val app = runCatching {
|
||||
val pm = context.packageManager
|
||||
pm.getApplicationLabel(pm.getApplicationInfo(sbn.packageName, 0)).toString()
|
||||
}.getOrDefault(sbn.packageName)
|
||||
add(items, BottomNotification(sbn.key, app, title, text, sbn.postTime))
|
||||
}
|
||||
|
||||
internal fun remove(key: String) {
|
||||
items.removeAll { it.key == key }
|
||||
}
|
||||
|
||||
private const val MAX_ITEMS = 30
|
||||
}
|
||||
|
||||
class BottomNotificationListener : NotificationListenerService() {
|
||||
override fun onListenerConnected() {
|
||||
runCatching { activeNotifications }.getOrNull()?.sortedBy { it.postTime }?.forEach { BottomNotifications.post(this, it) }
|
||||
}
|
||||
|
||||
override fun onNotificationPosted(sbn: StatusBarNotification) = BottomNotifications.post(this, sbn)
|
||||
|
||||
override fun onNotificationRemoved(sbn: StatusBarNotification) = BottomNotifications.remove(sbn.key)
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.provider.MediaStore
|
||||
import java.io.File
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
/** A screenshot for the bottom-screen gallery: one DroidDeck took (a MediaStore [uri]) or one Steam saved (a [file]). */
|
||||
data class BottomShot(val uri: Uri?, val file: File?, val takenAt: Long, val steam: Boolean) {
|
||||
val model: Any get() = uri ?: file!!
|
||||
}
|
||||
|
||||
/** Game frames DroidDeck saves to Pictures/DroidDeck, plus the screenshots Steam keeps under userdata. */
|
||||
object BottomScreenshots {
|
||||
private const val FOLDER = "DroidDeck"
|
||||
private const val QUALITY = 95
|
||||
private const val LIMIT = 120
|
||||
|
||||
internal fun fileName(at: Long): String =
|
||||
"DroidDeck_" + SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date(at)) + ".jpg"
|
||||
|
||||
fun save(context: Context, bitmap: Bitmap, at: Long = System.currentTimeMillis()): Boolean = runCatching {
|
||||
val name = fileName(at)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
val resolver = context.contentResolver
|
||||
val values = ContentValues().apply {
|
||||
put(MediaStore.Images.Media.DISPLAY_NAME, name)
|
||||
put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
|
||||
put(MediaStore.Images.Media.DATE_TAKEN, at)
|
||||
put(MediaStore.Images.Media.RELATIVE_PATH, "${Environment.DIRECTORY_PICTURES}/$FOLDER")
|
||||
put(MediaStore.Images.Media.IS_PENDING, 1)
|
||||
}
|
||||
val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) ?: return false
|
||||
val written = runCatching {
|
||||
resolver.openOutputStream(uri)?.use { bitmap.compress(Bitmap.CompressFormat.JPEG, QUALITY, it) } == true
|
||||
}.getOrDefault(false)
|
||||
if (!written) {
|
||||
resolver.delete(uri, null, null)
|
||||
return false
|
||||
}
|
||||
resolver.update(uri, ContentValues().apply { put(MediaStore.Images.Media.IS_PENDING, 0) }, null, null)
|
||||
true
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), FOLDER)
|
||||
if (!dir.isDirectory && !dir.mkdirs()) return false
|
||||
val file = File(dir, name)
|
||||
file.outputStream().use { bitmap.compress(Bitmap.CompressFormat.JPEG, QUALITY, it) }
|
||||
android.media.MediaScannerConnection.scanFile(context, arrayOf(file.path), arrayOf("image/jpeg"), null)
|
||||
true
|
||||
}
|
||||
}.getOrDefault(false)
|
||||
|
||||
/** Newest first, at most [LIMIT]. */
|
||||
fun list(context: Context, runtimeRoot: File): List<BottomShot> =
|
||||
(own(context) + steam(runtimeRoot)).sortedByDescending { it.takenAt }.take(LIMIT)
|
||||
|
||||
private fun own(context: Context): List<BottomShot> = runCatching {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
|
||||
@Suppress("DEPRECATION")
|
||||
val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), FOLDER)
|
||||
return dir.listFiles { f -> f.isFile && f.name.endsWith(".jpg", true) }.orEmpty()
|
||||
.map { BottomShot(null, it, it.lastModified(), steam = false) }
|
||||
}
|
||||
val shots = ArrayList<BottomShot>()
|
||||
context.contentResolver.query(
|
||||
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
|
||||
arrayOf(MediaStore.Images.Media._ID, MediaStore.Images.Media.DATE_TAKEN, MediaStore.Images.Media.DATE_ADDED),
|
||||
"${MediaStore.Images.Media.RELATIVE_PATH} = ?", arrayOf("${Environment.DIRECTORY_PICTURES}/$FOLDER/"),
|
||||
"${MediaStore.Images.Media.DATE_ADDED} DESC",
|
||||
)?.use { c ->
|
||||
while (c.moveToNext() && shots.size < LIMIT) {
|
||||
val taken = c.getLong(1).takeIf { it > 0L } ?: (c.getLong(2) * 1000L)
|
||||
shots += BottomShot(android.content.ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, c.getLong(0)),
|
||||
null, taken, steam = false)
|
||||
}
|
||||
}
|
||||
shots
|
||||
}.getOrDefault(emptyList())
|
||||
|
||||
/** The .jpg files in userdata/<account>/760/remote/<app>/screenshots of each Steam home; the thumbnails folder is skipped. */
|
||||
internal fun steam(runtimeRoot: File): List<BottomShot> =
|
||||
SteamDownloadMonitor.STEAM_HOMES.flatMap { home ->
|
||||
File(runtimeRoot, "$home/userdata").listFiles { f -> f.isDirectory }.orEmpty().flatMap { account ->
|
||||
File(account, "760/remote").listFiles { f -> f.isDirectory }.orEmpty().flatMap { app ->
|
||||
File(app, "screenshots").listFiles { f -> f.isFile && f.name.endsWith(".jpg", true) }.orEmpty().toList()
|
||||
}
|
||||
}
|
||||
}.map { BottomShot(null, it, it.lastModified(), steam = true) }
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
/** One reading from a racing game's telemetry. Fractions are 0..1; null means the game does not send it. */
|
||||
data class Telemetry(
|
||||
val source: String,
|
||||
val speedKmh: Float? = null,
|
||||
val rpm: Float? = null,
|
||||
val maxRpm: Float? = null,
|
||||
val gear: String? = null,
|
||||
val throttle: Float? = null,
|
||||
val brake: Float? = null,
|
||||
val lap: Int? = null,
|
||||
val laps: Int? = null,
|
||||
val position: Int? = null,
|
||||
val fuel: Float? = null,
|
||||
val currentLapS: Float? = null,
|
||||
val lastLapS: Float? = null,
|
||||
val bestLapS: Float? = null,
|
||||
/** G-force as the game sends it (lateral, longitudinal) and steering from -1 (left) to 1 (right). */
|
||||
val gLat: Float? = null,
|
||||
val gLon: Float? = null,
|
||||
val steer: Float? = null,
|
||||
/** Front left, front right, rear left, rear right. */
|
||||
val tireTempsC: List<Float>? = null,
|
||||
val turboBar: Float? = null,
|
||||
val engineTempC: Float? = null,
|
||||
val oilTempC: Float? = null,
|
||||
/** OutGauge dashboard lights that are on, as GameTelemetry.DL_* bits. */
|
||||
val lights: Int? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* Racing telemetry games send over UDP to 127.0.0.1. Each format has its own port, the one the game or
|
||||
* its common tools use by default:
|
||||
* - [CODEMASTERS_PORT]: DiRT Rally 1/2, DiRT 4, GRID ("extradata 3" float array), DiRT Showdown (152-byte packet).
|
||||
* - [FORZA_PORT]: Forza Motorsport 7/2023 and Forza Horizon 4/5 "Data Out" (Sled and Dash).
|
||||
* - [OUTGAUGE_PORT]: BeamNG.drive and Live for Speed OutGauge.
|
||||
*/
|
||||
object GameTelemetry {
|
||||
const val CODEMASTERS_PORT = 20777
|
||||
const val FORZA_PORT = 5300
|
||||
const val OUTGAUGE_PORT = 4444
|
||||
val PORTS = listOf(CODEMASTERS_PORT, FORZA_PORT, OUTGAUGE_PORT)
|
||||
|
||||
// Games send to 127.0.0.1; on Android InetAddress.getLoopbackAddress() is ::1, which IPv4 packets never reach.
|
||||
val LISTEN_ADDRESS: java.net.InetAddress = java.net.InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1))
|
||||
|
||||
fun parse(port: Int, data: ByteArray, length: Int): Telemetry? = runCatching {
|
||||
val buf = ByteBuffer.wrap(data, 0, length).order(ByteOrder.LITTLE_ENDIAN)
|
||||
when (port) {
|
||||
CODEMASTERS_PORT -> codemasters(buf, length)
|
||||
FORZA_PORT -> forza(buf, length)
|
||||
OUTGAUGE_PORT -> outGauge(buf, length)
|
||||
else -> null
|
||||
}
|
||||
}.getOrNull()
|
||||
|
||||
private const val MPS_TO_KMH = 3.6f
|
||||
private const val GRAVITY = 9.81f
|
||||
|
||||
// OutGauge DashLights / ShowLights bits (Live for Speed InSim; BeamNG uses the same values).
|
||||
const val DL_SHIFT = 1
|
||||
const val DL_HANDBRAKE = 4
|
||||
const val DL_PITSPEED = 8
|
||||
const val DL_TC = 16
|
||||
const val DL_ABS = 1024
|
||||
|
||||
// Float indexes of the Codemasters packet; engine rpm values are sent divided by 10. Older games
|
||||
// (DiRT Showdown) send only the first 38 floats, so lap count, position, fuel and max rpm are missing there.
|
||||
private const val CM_LAP_TIME = 1
|
||||
private const val CM_SPEED = 7
|
||||
private const val CM_THROTTLE = 29
|
||||
private const val CM_STEER = 30
|
||||
private const val CM_BRAKE = 31
|
||||
private const val CM_GEAR = 33
|
||||
private const val CM_G_LAT = 34
|
||||
private const val CM_G_LON = 35
|
||||
private const val CM_LAP = 36
|
||||
private const val CM_RPM = 37
|
||||
private const val CM_POSITION = 39
|
||||
private const val CM_FUEL = 45
|
||||
private const val CM_FUEL_CAPACITY = 46
|
||||
private const val CM_LAPS = 60
|
||||
private const val CM_LAST_LAP = 62
|
||||
private const val CM_MAX_RPM = 63
|
||||
private const val CM_MIN_FLOATS = 38
|
||||
|
||||
internal fun codemasters(buf: ByteBuffer, length: Int): Telemetry? {
|
||||
if (length < CM_MIN_FLOATS * 4) return null
|
||||
val floats = length / 4
|
||||
fun f(i: Int) = if (i < floats) buf.getFloat(i * 4) else 0f
|
||||
val gear = f(CM_GEAR).toInt()
|
||||
val capacity = f(CM_FUEL_CAPACITY)
|
||||
return Telemetry(
|
||||
source = "Codemasters",
|
||||
speedKmh = f(CM_SPEED) * MPS_TO_KMH,
|
||||
rpm = f(CM_RPM) * 10f,
|
||||
maxRpm = (f(CM_MAX_RPM) * 10f).takeIf { it > 0f },
|
||||
// Neutral is 0; DiRT Rally 2.0 reports reverse as 10, older games as -1.
|
||||
gear = when {
|
||||
gear == 0 -> "N"
|
||||
gear < 0 || gear == 10 -> "R"
|
||||
else -> gear.toString()
|
||||
},
|
||||
throttle = f(CM_THROTTLE).coerceIn(0f, 1f),
|
||||
brake = f(CM_BRAKE).coerceIn(0f, 1f),
|
||||
lap = f(CM_LAP).toInt() + 1,
|
||||
laps = f(CM_LAPS).toInt().takeIf { it > 0 },
|
||||
position = f(CM_POSITION).toInt().takeIf { it > 0 },
|
||||
fuel = if (capacity > 0f) (f(CM_FUEL) / capacity).coerceIn(0f, 1f) else null,
|
||||
currentLapS = f(CM_LAP_TIME).takeIf { it > 0f },
|
||||
lastLapS = f(CM_LAST_LAP).takeIf { it > 0f },
|
||||
gLat = f(CM_G_LAT),
|
||||
gLon = f(CM_G_LON),
|
||||
steer = f(CM_STEER).coerceIn(-1f, 1f),
|
||||
)
|
||||
}
|
||||
|
||||
// Forza "Data Out": Sled is 232 bytes; the Dash block follows it (FM7 311, FM 2023 331). Horizon 4/5 send
|
||||
// 324 bytes with 12 extra bytes before the Dash block.
|
||||
private const val FORZA_SLED = 232
|
||||
private const val FORZA_FM7 = 311
|
||||
private const val FORZA_HORIZON = 324
|
||||
private const val FORZA_FM2023 = 331
|
||||
private const val HORIZON_SHIFT = 12
|
||||
|
||||
internal fun forza(buf: ByteBuffer, length: Int): Telemetry? {
|
||||
if (length < FORZA_SLED) return null
|
||||
val racing = buf.getInt(0) != 0
|
||||
val maxRpm = buf.getFloat(8)
|
||||
val rpm = buf.getFloat(16)
|
||||
val dash = when (length) {
|
||||
FORZA_FM7, FORZA_FM2023 -> FORZA_SLED
|
||||
FORZA_HORIZON -> FORZA_SLED + HORIZON_SHIFT
|
||||
else -> -1
|
||||
}
|
||||
if (dash < 0) return Telemetry(source = "Forza", rpm = rpm, maxRpm = maxRpm.takeIf { it > 0f })
|
||||
if (!racing) return Telemetry(source = "Forza")
|
||||
val gear = buf.get(dash + 75).toInt() and 0xFF
|
||||
// Tire temperatures are read as Fahrenheit, as community Data Out parsers do; not checked on a device.
|
||||
val tiresF = (0 until 4).map { buf.getFloat(dash + 24 + it * 4) }
|
||||
return Telemetry(
|
||||
source = "Forza",
|
||||
speedKmh = buf.getFloat(dash + 12) * MPS_TO_KMH,
|
||||
rpm = rpm,
|
||||
maxRpm = maxRpm.takeIf { it > 0f },
|
||||
gear = if (gear == 0) "R" else gear.toString(),
|
||||
throttle = (buf.get(dash + 71).toInt() and 0xFF) / 255f,
|
||||
brake = (buf.get(dash + 72).toInt() and 0xFF) / 255f,
|
||||
lap = (buf.getShort(dash + 68).toInt() and 0xFFFF) + 1,
|
||||
position = (buf.get(dash + 70).toInt() and 0xFF).takeIf { it > 0 },
|
||||
fuel = buf.getFloat(dash + 44).coerceIn(0f, 1f),
|
||||
currentLapS = buf.getFloat(dash + 60).takeIf { it > 0f },
|
||||
lastLapS = buf.getFloat(dash + 56).takeIf { it > 0f },
|
||||
bestLapS = buf.getFloat(dash + 52).takeIf { it > 0f },
|
||||
gLat = buf.getFloat(20) / GRAVITY,
|
||||
gLon = buf.getFloat(28) / GRAVITY,
|
||||
steer = (buf.get(dash + 76).toFloat() / 127f).coerceIn(-1f, 1f),
|
||||
tireTempsC = tiresF.takeIf { f -> f.any { it > 0f } }?.map { (it - 32f) * 5f / 9f },
|
||||
)
|
||||
}
|
||||
|
||||
// OutGauge: 92 bytes, or 96 with the optional id at the end.
|
||||
private const val OUTGAUGE_SIZE = 92
|
||||
|
||||
internal fun outGauge(buf: ByteBuffer, length: Int): Telemetry? {
|
||||
if (length < OUTGAUGE_SIZE) return null
|
||||
val gear = buf.get(10).toInt() and 0xFF
|
||||
return Telemetry(
|
||||
source = "OutGauge",
|
||||
speedKmh = buf.getFloat(12) * MPS_TO_KMH,
|
||||
rpm = buf.getFloat(16),
|
||||
gear = when (gear) {
|
||||
0 -> "R"
|
||||
1 -> "N"
|
||||
else -> (gear - 1).toString()
|
||||
},
|
||||
throttle = buf.getFloat(48).coerceIn(0f, 1f),
|
||||
brake = buf.getFloat(52).coerceIn(0f, 1f),
|
||||
fuel = buf.getFloat(28).coerceIn(0f, 1f),
|
||||
turboBar = buf.getFloat(20).takeIf { it != 0f },
|
||||
engineTempC = buf.getFloat(24).takeIf { it != 0f },
|
||||
oilTempC = buf.getFloat(36).takeIf { it != 0f },
|
||||
lights = buf.getInt(44).takeIf { buf.getInt(40) != 0 },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Games that publish their state locally without any setup: War Thunder's web page and Elite Dangerous' Status.json. */
|
||||
object GameStatusFiles {
|
||||
const val WAR_THUNDER_STATE = "http://127.0.0.1:8111/state"
|
||||
private const val ELITE_APP = "359320"
|
||||
private const val ELITE_STATUS = "pfx/drive_c/users/steamuser/Saved Games/Frontier Developments/Elite Dangerous/Status.json"
|
||||
const val WAR_THUNDER_ROWS = 12
|
||||
|
||||
/** War Thunder's own labels (for example "TAS, km/h") with their values, while a match runs. */
|
||||
internal fun warThunder(json: String): List<Pair<String, String>> {
|
||||
val state = org.json.JSONObject(json)
|
||||
if (!state.optBoolean("valid", false)) return emptyList()
|
||||
return state.keys().asSequence().filter { it != "valid" }.mapNotNull { key ->
|
||||
val value = state.opt(key) as? Number ?: return@mapNotNull null
|
||||
key to if (value.toDouble() % 1.0 == 0.0) value.toLong().toString() else "%.1f".format(java.util.Locale.US, value.toDouble())
|
||||
}.toList()
|
||||
}
|
||||
|
||||
fun eliteStatusFile(runtimeRoot: java.io.File, mounts: Map<String, java.io.File>): java.io.File? {
|
||||
val libraries = SteamDownloadMonitor.manifests(runtimeRoot, mounts).mapNotNull { it.parentFile } +
|
||||
SteamDownloadMonitor.STEAM_HOMES.map { java.io.File(runtimeRoot, "$it/steamapps") }
|
||||
return libraries.distinct().map { java.io.File(it, "compatdata/$ELITE_APP/$ELITE_STATUS") }.firstOrNull { it.isFile }
|
||||
}
|
||||
|
||||
data class Elite(val fuelMain: Double?, val fuelReserve: Double?, val cargo: Double?, val pips: List<Int>?, val legal: String?, val balance: Long?)
|
||||
|
||||
/** Null while Elite is at its menus (Status.json then carries only the timestamp and flags). */
|
||||
internal fun elite(json: String): Elite? {
|
||||
val s = org.json.JSONObject(json)
|
||||
val fuel = s.optJSONObject("Fuel")
|
||||
val pips = s.optJSONArray("Pips")?.let { a -> (0 until a.length()).map { a.optInt(it) } }
|
||||
if (fuel == null && pips == null && !s.has("Cargo") && !s.has("Balance")) return null
|
||||
return Elite(
|
||||
fuelMain = fuel?.optDouble("FuelMain")?.takeIf { !it.isNaN() },
|
||||
fuelReserve = fuel?.optDouble("FuelReservoir")?.takeIf { !it.isNaN() },
|
||||
cargo = s.optDouble("Cargo").takeIf { !it.isNaN() },
|
||||
pips = pips,
|
||||
legal = s.optString("LegalState").takeIf { it.isNotEmpty() },
|
||||
balance = if (s.has("Balance")) s.optLong("Balance") else null,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -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) || com.droiddeck.launcher.hud.FusionHudHost.showing)) sample()?.let { write(it) }
|
||||
if (running && (OverlayShown.check(root) || com.droiddeck.launcher.hud.DroidDeckHudHost.showing)) sample()?.let { write(it) }
|
||||
}
|
||||
}, "gpu-mem").apply { isDaemon = true; start() }
|
||||
}
|
||||
|
||||
@@ -170,6 +170,7 @@ object SessionFiles {
|
||||
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
|
||||
"usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst",
|
||||
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
|
||||
"usr/local/lib/droiddeck-dirt/ws2_32.dll" to "usr/local/lib/droiddeck-dirt/ws2_32.dll",
|
||||
) + mangoapp + msitools.map { it to it } + vr + fexPreloads).filter { (asset, _) ->
|
||||
val dir = asset.substringBeforeLast('/')
|
||||
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
|
||||
@@ -290,6 +291,7 @@ object SessionFiles {
|
||||
"stage session=$startsSession pending=$force choice=${SessionPrefs.bootMovie(context)} movie=${startupMovie?.path} " +
|
||||
"staged=$bigPictureMovieInstalled done=$done steam=${home.path} config: $before -> ${startupMoviePath(config)}",
|
||||
)
|
||||
if (startsSession) disableIdleSleep(home)
|
||||
if (!done) allDone = false
|
||||
if (!bigPictureMovieInstalled) allInstalled = false
|
||||
if (done && home.path.contains(".droiddeck-x64") == activeIsX64) seen = if (bigPictureMovieInstalled) BOOT_MOVIE_PATH else ""
|
||||
@@ -528,6 +530,43 @@ object SessionFiles {
|
||||
}
|
||||
}
|
||||
|
||||
private val IDLE_SLEEP_TIMERS = listOf("IdleSuspendBatterySeconds", "IdleSuspendACSeconds")
|
||||
|
||||
/**
|
||||
* Sets Steam's Power > "Sleep after" (battery and plugged in) to Disabled at every session start: Android
|
||||
* owns the device's sleep, and a client that suspends inside the session only shows a black screen. Dimming stays the user's. Runs
|
||||
* only before the client starts, which rewrites its config on exit.
|
||||
*/
|
||||
internal fun disableIdleSleep(steamHome: File): Boolean {
|
||||
val config = File(steamHome, "config/config.vdf")
|
||||
val text = runCatching { config.readText() }.getOrNull() ?: return false
|
||||
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
|
||||
val steam = findSteamBlock(text) ?: return false
|
||||
val system = findObject(text, "system", steam.open + 1, steam.close)
|
||||
val updated = if (system != null) {
|
||||
val block = text.substring(system.keyStart, system.close + 1)
|
||||
text.replaceRange(system.keyStart, system.close + 1, IDLE_SLEEP_TIMERS.fold(block) { acc, key -> setScalar(acc, key, "0", newline) })
|
||||
} else {
|
||||
val lineStart = text.lastIndexOf('\n', steam.close).let { if (it < 0) 0 else it + 1 }
|
||||
val indent = text.substring(lineStart, steam.close).takeWhile { it == '\t' || it == ' ' } + "\t"
|
||||
val section = (listOf(indent + "\"system\"", indent + "{") +
|
||||
IDLE_SLEEP_TIMERS.map { "$indent\t\"$it\"\t\t\"0\"" } + (indent + "}")).joinToString(newline) + newline
|
||||
text.substring(0, lineStart) + section + text.substring(lineStart)
|
||||
}
|
||||
val staged = File(config.parentFile, config.name + ".staged")
|
||||
return try {
|
||||
if (updated != text) {
|
||||
staged.writeText(updated)
|
||||
if (!staged.renameTo(config)) { staged.delete(); return false }
|
||||
}
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
staged.delete()
|
||||
Log.w(TAG, "could not disable Steam's idle sleep", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/** Adds the `Customization` section Steam reads, next to the `Software` section, when the config has none. */
|
||||
private fun withCustomization(text: String, path: String, newline: String): String {
|
||||
val root = findObject(text, "InstallConfigStore", 0, text.length) ?: return text
|
||||
|
||||
@@ -94,6 +94,50 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("dualScreenMode", mode).apply()
|
||||
}
|
||||
|
||||
fun secondScreenPanel(context: Context): String? = prefs(context).getString("secondScreenPanel", null)
|
||||
|
||||
fun setSecondScreenPanel(context: Context, mode: String) {
|
||||
prefs(context).edit().putString("secondScreenPanel", mode).apply()
|
||||
}
|
||||
|
||||
fun bottomPage(context: Context): String? = prefs(context).getString("bottomPage", null)
|
||||
|
||||
fun setBottomPage(context: Context, page: String) {
|
||||
prefs(context).edit().putString("bottomPage", page).apply()
|
||||
}
|
||||
|
||||
fun statsStrip(context: Context): String? = prefs(context).getString("statsStrip", null)
|
||||
|
||||
fun setStatsStrip(context: Context, id: String) {
|
||||
prefs(context).edit().putString("statsStrip", id).apply()
|
||||
}
|
||||
|
||||
fun statsSpeedUnit(context: Context): String? = prefs(context).getString("statsSpeedUnit", null)
|
||||
|
||||
fun setStatsSpeedUnit(context: Context, id: String) {
|
||||
prefs(context).edit().putString("statsSpeedUnit", id).apply()
|
||||
}
|
||||
|
||||
fun statsDash(context: Context): String? = prefs(context).getString("statsDash", null)
|
||||
|
||||
fun setStatsDash(context: Context, id: String) {
|
||||
prefs(context).edit().putString("statsDash", id).apply()
|
||||
}
|
||||
|
||||
/** In-game stats "Send dashboard data" Automatic: on unless the user switched it off. */
|
||||
fun telemetryAuto(context: Context): Boolean = prefs(context).getBoolean("telemetryAuto", true)
|
||||
|
||||
fun setTelemetryAuto(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("telemetryAuto", on).apply()
|
||||
}
|
||||
|
||||
/** Games the user switched off by hand, as TelemetryOutput keys; Automatic leaves them alone. */
|
||||
fun telemetryOff(context: Context): Set<String> = prefs(context).getStringSet("telemetryOff", null)?.toSet().orEmpty()
|
||||
|
||||
fun setTelemetryOff(context: Context, keys: Set<String>) {
|
||||
prefs(context).edit().putStringSet("telemetryOff", keys.toSet()).apply()
|
||||
}
|
||||
|
||||
fun dualScreenLauncher(context: Context): Boolean = prefs(context).getBoolean("dualScreenLauncher", true)
|
||||
|
||||
fun setDualScreenLauncher(context: Context, on: Boolean) {
|
||||
@@ -141,10 +185,10 @@ object SessionPrefs {
|
||||
}
|
||||
|
||||
fun storesView(context: Context): String =
|
||||
prefs(context).getString("storesView", null)?.takeIf { it in STORES_VIEWS } ?: STORES_VIEWS.first()
|
||||
prefs(context).getString("storesView", null)?.takeIf { it in STORES_VIEWS } ?: DEFAULT_STORES_VIEW
|
||||
|
||||
fun setStoresView(context: Context, view: String) {
|
||||
prefs(context).edit().putString("storesView", if (view in STORES_VIEWS) view else STORES_VIEWS.first()).apply()
|
||||
prefs(context).edit().putString("storesView", if (view in STORES_VIEWS) view else DEFAULT_STORES_VIEW).apply()
|
||||
}
|
||||
|
||||
fun libraryCardLevel(context: Context): Int = prefs(context).getInt("libraryCardLevel", 2)
|
||||
@@ -193,6 +237,7 @@ object SessionPrefs {
|
||||
|
||||
val STORES_SORTS = listOf("lastPlayed", "recentlyInstalled", "titleAsc", "titleDesc", "sizeDesc", "sizeAsc", "releaseDateDesc")
|
||||
val STORES_VIEWS = listOf("cards", "capsules", "list")
|
||||
const val DEFAULT_STORES_VIEW = "capsules"
|
||||
|
||||
fun storesInstallTarget(context: Context): String = prefs(context).getString("storesInstallTarget", "") ?: ""
|
||||
|
||||
@@ -241,7 +286,7 @@ object SessionPrefs {
|
||||
prefs(context).edit().putInt("gameStoresParallel", count.coerceIn(1, 3)).apply()
|
||||
}
|
||||
|
||||
fun hudEnabled(context: Context): Boolean = prefs(context).getBoolean(hudKey(context), !mangoappSession(context))
|
||||
fun hudEnabled(context: Context): Boolean = prefs(context).getBoolean(hudKey(context), false)
|
||||
|
||||
fun setHudEnabled(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean(hudKey(context), on).apply()
|
||||
@@ -279,18 +324,18 @@ object SessionPrefs {
|
||||
prefs(context).edit().putInt("hudOpacity", percent.coerceIn(HUD_OPACITY_RANGE)).apply()
|
||||
}
|
||||
|
||||
fun fusionHudConfig(context: Context): String? = prefs(context).getString("fusionHud", null)
|
||||
fun droidDeckHudConfig(context: Context): String? = prefs(context).getString("__KEEP_droidDeckHud__", null)
|
||||
|
||||
fun setFusionHudConfig(context: Context, config: String) {
|
||||
prefs(context).edit().putString("fusionHud", config).apply()
|
||||
fun setDroidDeckHudConfig(context: Context, config: String) {
|
||||
prefs(context).edit().putString("__KEEP_droidDeckHud__", config).apply()
|
||||
}
|
||||
|
||||
fun fusionHudPosition(context: Context): Pair<Float, Float>? =
|
||||
prefs(context).getString("fusionHudPos", null)?.split(',')?.mapNotNull { it.toFloatOrNull() }
|
||||
fun droidDeckHudPosition(context: Context): Pair<Float, Float>? =
|
||||
prefs(context).getString("__KEEP_droidDeckHudPos__", 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()
|
||||
fun setDroidDeckHudPosition(context: Context, x: Float, y: Float) {
|
||||
prefs(context).edit().putString("__KEEP_droidDeckHudPos__", "$x,$y").apply()
|
||||
}
|
||||
|
||||
const val HUD_COLOR_MINT = "mint"
|
||||
@@ -435,11 +480,15 @@ object SessionPrefs {
|
||||
|
||||
/**
|
||||
* Shader pre-caching as the launcher last set it, until a session reports it written into the
|
||||
* client's config.vdf; after that the client's own toggle is the user's again.
|
||||
* client's config.vdf; after that the client's own toggle is the user's again. A client that
|
||||
* has never written a config.vdf starts with pre-caching off.
|
||||
*/
|
||||
fun pendingShaderPrecache(context: Context): Boolean? {
|
||||
val prefs = prefs(context)
|
||||
if (!prefs.contains("shaderPrecache")) return null
|
||||
if (!prefs.contains("shaderPrecache")) {
|
||||
if (steamConfig(context).exists()) return null
|
||||
prefs.edit().putBoolean("shaderPrecache", false).apply()
|
||||
}
|
||||
val on = prefs.getBoolean("shaderPrecache", true)
|
||||
val applied = shaderPrecacheApplied(context)
|
||||
val written = runCatching { applied.readText().trim() }.getOrNull() ?: return on
|
||||
@@ -454,9 +503,12 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("shaderPrecache", on).apply()
|
||||
}
|
||||
|
||||
private fun steamConfig(context: Context) =
|
||||
java.io.File(steamRoot(context, steamClientArch(context)), "config/config.vdf")
|
||||
|
||||
fun shaderPrecache(context: Context): Boolean = pendingShaderPrecache(context)
|
||||
?: runCatching { com.droiddeck.launcher.storage.SteamStorage.shaderPrecache(
|
||||
java.io.File(steamRoot(context, steamClientArch(context)), "config/config.vdf").readText()) }.getOrDefault(true)
|
||||
steamConfig(context).readText()) }.getOrDefault(true)
|
||||
|
||||
fun stretch16x9(context: Context): Boolean = prefs(context).getBoolean("stretch16x9", false)
|
||||
|
||||
@@ -1009,21 +1061,34 @@ object SessionPrefs {
|
||||
if (previous != null && !p.contains("addedAppId:$folderPath")) {
|
||||
val moved = movedAddedGame(p.all, previous, folderPath)
|
||||
moved.keys.forEach { edit.remove(it) }
|
||||
moved.values.forEach { (name, value) ->
|
||||
when (value) {
|
||||
is String -> edit.putString(name, value)
|
||||
is Long -> edit.putLong(name, value)
|
||||
is Int -> edit.putInt(name, value)
|
||||
is Boolean -> edit.putBoolean(name, value)
|
||||
is Float -> edit.putFloat(name, value)
|
||||
}
|
||||
}
|
||||
moved.values.forEach { (name, value) -> edit.putValue(name, value) }
|
||||
val removed = removedAddedGames(context)
|
||||
if (previous in removed) edit.putString("removedAddedGames", removed.map { if (it == previous) folderPath else it }.joinToString("\n"))
|
||||
}
|
||||
edit.apply()
|
||||
}
|
||||
|
||||
fun inheritAddedGame(context: Context, from: String, to: String) = synchronized(addedGameLock) {
|
||||
val p = prefs(context)
|
||||
val all = p.all
|
||||
val edit = p.edit()
|
||||
all.filterKeys { it.startsWith("added") && it.endsWith(":$from") }.forEach { (name, value) ->
|
||||
val key = name.removeSuffix(from) + to
|
||||
if (key !in all) edit.putValue(key, value)
|
||||
}
|
||||
edit.apply()
|
||||
}
|
||||
|
||||
private fun android.content.SharedPreferences.Editor.putValue(name: String, value: Any?) {
|
||||
when (value) {
|
||||
is String -> putString(name, value)
|
||||
is Long -> putLong(name, value)
|
||||
is Int -> putInt(name, value)
|
||||
is Boolean -> putBoolean(name, value)
|
||||
is Float -> putFloat(name, value)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun movedAddedGame(all: Map<String, *>, from: String, to: String): Map<String, Pair<String, Any?>> =
|
||||
all.filterKeys { it.startsWith("added") && it.endsWith(":$from") }.mapValues { (name, value) ->
|
||||
val moved = if (value is String && (value == from || value.startsWith("$from/"))) to + value.removePrefix(from) else value
|
||||
@@ -1081,12 +1146,26 @@ object SessionPrefs {
|
||||
/** Compositor frame limit that releases buffers to the game unpaced. */
|
||||
const val FPS_UNPACED = -1
|
||||
|
||||
/** The drawer's frame limit slider: its first stop is Off. */
|
||||
const val FPS_LIMIT_OFF = 15
|
||||
const val FPS_LIMIT_MAX = 120
|
||||
|
||||
/**
|
||||
* Buffers go back to the game as soon as they are replaced instead of once per refresh;
|
||||
* Steam's Frame Limit in the Quick Access menu caps games. Mirroring still follows the glasses' refresh rate.
|
||||
* Steam's Frame Limit in the Quick Access menu caps Steam games, and the drawer's limit caps games
|
||||
* launched without Steam. Mirroring still follows the glasses' refresh rate.
|
||||
*/
|
||||
fun compositorFpsLimit(mirrorRefreshLimit: Int): Int =
|
||||
if (mirrorRefreshLimit <= 0) FPS_UNPACED else mirrorRefreshLimit
|
||||
const val PIP_FPS = 30
|
||||
|
||||
fun compositorFpsLimit(mirrorRefreshLimit: Int, sessionLimit: Int = 0, pip: Boolean = false): Int {
|
||||
val limit = when {
|
||||
mirrorRefreshLimit <= 0 && sessionLimit <= 0 -> FPS_UNPACED
|
||||
mirrorRefreshLimit <= 0 -> sessionLimit
|
||||
sessionLimit <= 0 -> mirrorRefreshLimit
|
||||
else -> minOf(mirrorRefreshLimit, sessionLimit)
|
||||
}
|
||||
return if (pip && mirrorRefreshLimit <= 0 && (limit <= 0 || limit > PIP_FPS)) PIP_FPS else limit
|
||||
}
|
||||
|
||||
val upscalerChoices = listOf(
|
||||
0 to "Linear", 2 to "Nearest", 4 to "AMD FSR 1", 3 to "Snapdragon GSR",
|
||||
|
||||
@@ -73,7 +73,9 @@ class SessionService : Service() {
|
||||
private var downloadMonitorTask: Runnable? = null
|
||||
private var downloadActive = false
|
||||
private var clientInstallActive = false
|
||||
@Volatile private var steamLibraryMounts = emptyMap<String, File>()
|
||||
private var steamLibraryMounts: Map<String, File>
|
||||
get() = SessionState.steamLibraryMounts
|
||||
set(value) { SessionState.steamLibraryMounts = value }
|
||||
private var suspendDownloadNow = false
|
||||
private var suspendPolicy = SessionPrefs.SUSPEND_MANUAL
|
||||
private var steamDownloadsInBackground = false
|
||||
@@ -334,6 +336,7 @@ class SessionService : Service() {
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
SessionState.mode = intent?.getStringExtra(EXTRA_MODE) ?: MODE_STEAM
|
||||
SessionState.fpsLimit = 0
|
||||
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
|
||||
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
|
||||
activityVisible = true
|
||||
@@ -535,10 +538,6 @@ class SessionService : Service() {
|
||||
// gamescope's WSI layer and winex11 reuse their per-present window checks for this long.
|
||||
guest.add("DROIDDECK_WSI_BYPASS_CHECK_MS=100")
|
||||
guest.add("WINE_OFFSCREEN_CHECK_MS=100")
|
||||
// gamescope turns buffers around slower than an uncapped game draws; more images keep it drawing.
|
||||
// The WSI layer goes back to its default count while Steam's Frame Limit holds the game.
|
||||
guest.add("GAMESCOPE_WSI_MIN_IMAGE_COUNT=8")
|
||||
guest.add("GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT=1")
|
||||
guest.add("BL_REFRESH=" + Math.round(SessionState.refreshHz))
|
||||
guest.add("BL_LOG=" + sessionLog.path)
|
||||
guest.add("BL_DEBUG_DIR=" + sessionDir.path)
|
||||
@@ -546,7 +545,6 @@ class SessionService : Service() {
|
||||
val fakeInputDir = File(sessionRoot, "dev/input").apply { mkdirs() }
|
||||
val controllersOn = !File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()
|
||||
SessionState.deckPad = false
|
||||
SessionState.secondScreenAutoOpened = false
|
||||
deckBinds = emptyList()
|
||||
inputSysfs = null
|
||||
if (controllersOn) {
|
||||
@@ -720,6 +718,7 @@ class SessionService : Service() {
|
||||
if (!pulse.setMicSuspended(false)) Log.w(TAG, "could not resume microphone source")
|
||||
},
|
||||
zramControl = File(filesDir, "${LinuxRuntime.DIR}/tmp/.bl-zram"),
|
||||
clockControl = File(filesDir, "${LinuxRuntime.DIR}/tmp/.bl-clock"),
|
||||
pagedOut = { processes, unacknowledged, residentKb, swapKb, swapBeforeKb, millis ->
|
||||
Log.i(TAG, "paged out $processes processes ($unacknowledged unacknowledged) in $millis ms: " +
|
||||
"resident ${residentKb / 1024} MB, zram ${swapBeforeKb / 1024} -> ${swapKb / 1024} MB")
|
||||
@@ -821,7 +820,7 @@ class SessionService : Service() {
|
||||
if (!SessionPrefs.zramClient(this)) guest.add("BL_ZRAM_CLIENT=0")
|
||||
}
|
||||
SessionPrefs.vramCapMb(this).takeIf { it > 0 }?.let { guest.add("BL_VRAM_MB=$it") }
|
||||
guest.add("BANNER_AUDIO_DIRECT_DECAY=0")
|
||||
guest.add("AUDIO_DIRECT_DECAY=0")
|
||||
val extra = extraEnv() + agentEnvironment
|
||||
if (extra.none { it.startsWith("TU_DEBUG=") }) guest.add("$GAME_TU_DEBUG=" + (tuOverride ?: if (tuDriver) "sysmem" else ""))
|
||||
extra.forEach { guest.add(it) }
|
||||
@@ -844,7 +843,7 @@ class SessionService : Service() {
|
||||
val wantsMic = SessionPrefs.micEnabled(this) &&
|
||||
checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
|
||||
guest.add("BL_MIC_ENABLED=" + if (wantsMic) "1" else "0")
|
||||
guest.add("BANNER_AUDIO_DIRECT_MIC=" + if (wantsMic) "1" else "0")
|
||||
guest.add("AUDIO_DIRECT_MIC=" + if (wantsMic) "1" else "0")
|
||||
val audioDir = File(filesDir, "directaudio").apply { mkdirs() }
|
||||
val relaySocket = File(audioDir, "relay.sock")
|
||||
val micFifo = if (wantsMic) File(audioDir, "mic.fifo") else null
|
||||
@@ -872,7 +871,11 @@ class SessionService : Service() {
|
||||
}
|
||||
if (wantsDirectAudio) {
|
||||
guest.add("BL_DIRECTAUDIO=/" + SessionFiles.DIRECTAUDIO_DIR)
|
||||
guest.add("BANNER_AUDIO_DIRECT_RELAY=" + relaySocket.absolutePath)
|
||||
guest.add("AUDIO_DIRECT_RELAY=" + relaySocket.absolutePath)
|
||||
val lowLatency = com.droiddeck.launcher.audio.DirectAudioTiming.lowLatencyOutput()
|
||||
val timing = com.droiddeck.launcher.audio.DirectAudioTiming.environment(lowLatency)
|
||||
guest.addAll(timing)
|
||||
Log.i(TAG, "audio: Android output " + (if (lowLatency) "is low-latency; DirectAudio keeps its defaults" else "is not low-latency; DirectAudio uses " + timing.joinToString(" ")))
|
||||
}
|
||||
Log.i(TAG, "audio: client DirectAudio (in-process sink)" + (if (wantsDirectAudio) " + DirectAudio for games" else "")
|
||||
+ (if (wantsMic) " + microphone" else "") +
|
||||
@@ -1039,7 +1042,7 @@ class SessionService : Service() {
|
||||
Log.w(TAG, "added games: ${root.host} is not a readable folder this session")
|
||||
}
|
||||
}
|
||||
for ((host, guest) in com.droiddeck.launcher.stores.StoreInstallRoot.externalRoots(this)) {
|
||||
for ((host, guest) in com.droiddeck.launcher.stores.StoreInstallRoot.externalRootsForXodus(this)) {
|
||||
if (host.isDirectory && host.canRead()) {
|
||||
File(LinuxRuntime.rootDir(this), guest.removePrefix("/")).mkdirs()
|
||||
binds.add(host.path + ":" + guest)
|
||||
@@ -1338,17 +1341,7 @@ class SessionService : Service() {
|
||||
|
||||
/** A Steam game is running: the client runs each one under its reaper, and Proton's script
|
||||
* waits on the game with waitforexitandrun. Read from the command lines, as ComponentsManager does. */
|
||||
private fun steamGameRunning(): Boolean {
|
||||
val procs = File("/proc").listFiles() ?: return false
|
||||
for (p in procs) {
|
||||
if (!p.name.all(Char::isDigit)) continue
|
||||
val cmd = runCatching { File(p, "cmdline").readBytes() }.getOrNull() ?: continue
|
||||
if (cmd.isEmpty()) continue
|
||||
val text = String(cmd).replace('\u0000', ' ')
|
||||
if (text.contains("SteamLaunch AppId=") || text.contains("waitforexitandrun")) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
private fun steamGameRunning(): Boolean = SteamGameProcess.running()
|
||||
|
||||
private fun resumeSession(panelVisible: Boolean = true) {
|
||||
if (SessionState.suspended) SessionState.resumeRequested = true
|
||||
|
||||
@@ -92,6 +92,10 @@ object SessionState {
|
||||
@Volatile var secondScreenMode = com.droiddeck.launcher.input.SecondScreenMode.NONE
|
||||
@Volatile var secondScreenDisplay = -1
|
||||
@Volatile var secondScreenAutoOpened = false
|
||||
@Volatile var secondScreenProvisional = false
|
||||
|
||||
/** Guest library paths on removable storage and the host folders they are mounted from, set by SessionService. */
|
||||
@Volatile var steamLibraryMounts: Map<String, java.io.File> = emptyMap()
|
||||
|
||||
@Volatile
|
||||
var mode = "steam"
|
||||
@@ -108,6 +112,10 @@ object SessionState {
|
||||
@Volatile
|
||||
var upscaleRatio: Float = 0f
|
||||
|
||||
/** Frame limit chosen in the drawer for a game launched without Steam; 0 is off. */
|
||||
@Volatile
|
||||
var fpsLimit: Int = 0
|
||||
|
||||
@Volatile
|
||||
var firstFrameSeen = false
|
||||
|
||||
|
||||
@@ -3,6 +3,9 @@ package com.droiddeck.launcher.session
|
||||
import android.os.Process
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.io.RandomAccessFile
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import java.util.concurrent.ExecutorService
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.RejectedExecutionException
|
||||
@@ -19,6 +22,8 @@ internal class SessionSuspendController(
|
||||
private val nowMillis: () -> Long = { System.nanoTime() / 1_000_000 },
|
||||
private val executor: ExecutorService = Executors.newSingleThreadExecutor(),
|
||||
private val zramControl: File? = null,
|
||||
private val clockControl: File? = null,
|
||||
private val nowNanos: () -> Long = System::nanoTime,
|
||||
private val pagedOut: (processes: Int, unacknowledged: Int, residentKb: Long, swapKb: Long, swapBeforeKb: Long, millis: Long) -> Unit =
|
||||
{ _, _, _, _, _, _ -> },
|
||||
) {
|
||||
@@ -43,6 +48,7 @@ internal class SessionSuspendController(
|
||||
@Volatile private var closing = false
|
||||
@Volatile private var cancelled = false
|
||||
private var frozen = emptyList<ProcessRecord>()
|
||||
private var frozenSince: Long? = null
|
||||
|
||||
fun freeze(pageOut: Boolean = false, completion: (Boolean) -> Unit) {
|
||||
cancelled = false
|
||||
@@ -93,6 +99,7 @@ internal class SessionSuspendController(
|
||||
} catch (_: Exception) {
|
||||
} finally {
|
||||
frozen = records.values.toList()
|
||||
if (complete && frozenSince == null) frozenSince = nowNanos()
|
||||
if (!complete) {
|
||||
if (restoreSafely(frozen)) frozen = emptyList()
|
||||
runAudio(resumeAudio)
|
||||
@@ -111,6 +118,7 @@ internal class SessionSuspendController(
|
||||
fun resume(completion: (Boolean) -> Unit) {
|
||||
submit({
|
||||
val records = frozen
|
||||
advanceClock()
|
||||
runAudio(resumeAudio)
|
||||
val resumed = restoreSafely(records)
|
||||
if (resumed) frozen = emptyList()
|
||||
@@ -121,6 +129,7 @@ internal class SessionSuspendController(
|
||||
fun closeAndResume(completion: () -> Unit) {
|
||||
closing = true
|
||||
submit({
|
||||
advanceClock()
|
||||
if (restoreSafely(frozen)) frozen = emptyList()
|
||||
completion()
|
||||
executor.shutdown()
|
||||
@@ -135,6 +144,23 @@ internal class SessionSuspendController(
|
||||
}
|
||||
}
|
||||
|
||||
private fun advanceClock() {
|
||||
val since = frozenSince ?: return
|
||||
frozenSince = null
|
||||
val control = clockControl?.takeIf { it.isFile && it.length() >= Long.SIZE_BYTES } ?: return
|
||||
try {
|
||||
RandomAccessFile(control, "rw").use { file ->
|
||||
val bytes = ByteArray(Long.SIZE_BYTES)
|
||||
file.readFully(bytes)
|
||||
val shift = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).long.coerceAtLeast(0L) +
|
||||
(nowNanos() - since).coerceAtLeast(0L)
|
||||
file.seek(0L)
|
||||
file.write(ByteBuffer.allocate(Long.SIZE_BYTES).order(ByteOrder.LITTLE_ENDIAN).putLong(shift).array())
|
||||
}
|
||||
} catch (_: IOException) {
|
||||
}
|
||||
}
|
||||
|
||||
private fun runAudio(action: () -> Unit) {
|
||||
try {
|
||||
action()
|
||||
|
||||
@@ -15,7 +15,7 @@ object SettingsReset {
|
||||
"dualScreenMode", "dualScreenLauncher", "dualScreenSessionControls",
|
||||
"gameStoresEnabled", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
|
||||
"storesInstallLanguage",
|
||||
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "fusionHud", "fusionHudPos", "backActionsInverted", "backDoubleTapMs", "touch", "osc", "shape", "steamController",
|
||||
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backActionsInverted", "backDoubleTapMs", "touch", "osc", "shape", "steamController",
|
||||
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
|
||||
"stretch16x9", "picturePosition", "railLabels",
|
||||
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
|
||||
@@ -26,7 +26,7 @@ object SettingsReset {
|
||||
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
|
||||
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds",
|
||||
"bootMovieApplyNext", "bootMovieSteamSeen",
|
||||
"questDefaultsV1",
|
||||
"questDefaultsV1", "telemetryAuto", "telemetryOff", "statsStrip", "statsDash", "statsSpeedUnit",
|
||||
)
|
||||
|
||||
internal val SESSION_PREFIXES = listOf(
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
/** The In-game stats page's top strip, picked on the page (tap or the Layout row) and remembered. */
|
||||
enum class StatsStrip(val id: String) {
|
||||
PANEL("panel"), TILES("tiles"), RINGS("rings");
|
||||
|
||||
fun next(): StatsStrip = entries[(ordinal + 1) % entries.size]
|
||||
|
||||
companion object {
|
||||
fun from(id: String?): StatsStrip = entries.firstOrNull { it.id == id } ?: PANEL
|
||||
}
|
||||
}
|
||||
|
||||
/** Speeds on the racing dashes; telemetry arrives in km/h. */
|
||||
enum class SpeedUnit(val id: String, val label: String, val perKmh: Float) {
|
||||
AUTO("auto", "", 1f), KMH("kmh", "km/h", 1f), MPH("mph", "mph", 0.621371f);
|
||||
|
||||
/** Auto is mph where road speed limits are signed in mph, by the device's region, else km/h. */
|
||||
fun resolve(country: String): SpeedUnit = if (this != AUTO) this else if (country.uppercase() in MPH_REGIONS) MPH else KMH
|
||||
|
||||
fun next(): SpeedUnit = entries[(ordinal + 1) % entries.size]
|
||||
|
||||
companion object {
|
||||
/** The United States and its territories, the United Kingdom and its Crown Dependencies, Liberia, the Bahamas, Belize. */
|
||||
private val MPH_REGIONS = setOf("US", "PR", "GU", "VI", "AS", "MP", "GB", "IM", "JE", "GG", "LR", "BS", "BZ")
|
||||
|
||||
fun from(id: String?): SpeedUnit = entries.firstOrNull { it.id == id } ?: AUTO
|
||||
}
|
||||
}
|
||||
|
||||
/** The racing dash under the strip; Auto picks one by the game's data format. */
|
||||
enum class StatsDash(val id: String) {
|
||||
AUTO("auto"), SPEEDOMETER("speedometer"), CIRCUIT("circuit"), TRACE("trace"), DIALS("dials"), GLANCE("glance");
|
||||
|
||||
/** The dash to draw for data from [source] (Telemetry.source). */
|
||||
fun resolve(source: String): StatsDash = if (this != AUTO) this else when (source) {
|
||||
"Forza" -> CIRCUIT
|
||||
"OutGauge" -> DIALS
|
||||
else -> SPEEDOMETER
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val DRAWN = listOf(SPEEDOMETER, CIRCUIT, TRACE, DIALS, GLANCE)
|
||||
|
||||
fun from(id: String?): StatsDash = entries.firstOrNull { it.id == id } ?: AUTO
|
||||
|
||||
/** A tap on the dash moves on from the one on screen, so Auto never looks like a tap did nothing. */
|
||||
fun tapped(shown: StatsDash): StatsDash = DRAWN[(DRAWN.indexOf(shown) + 1).mod(DRAWN.size)]
|
||||
}
|
||||
}
|
||||
@@ -101,34 +101,6 @@ internal class SteamDownloadMonitor {
|
||||
now - lastContentActivityAt <= CONTENT_ACTIVITY_GRACE_MS
|
||||
}
|
||||
|
||||
private fun manifests(runtimeRoot: File, mounts: Map<String, File>): List<File> {
|
||||
val steamRoots = linkedSetOf<File>()
|
||||
for (home in STEAM_HOMES) {
|
||||
val primary = File(runtimeRoot, home)
|
||||
steamRoots += primary
|
||||
val libraryFolders = File(primary, "steamapps/libraryfolders.vdf")
|
||||
runCatching {
|
||||
PATH.findAll(libraryFolders.readText()).forEach { match ->
|
||||
steamRoots += hostPath(runtimeRoot, match.groupValues[1], mounts)
|
||||
}
|
||||
}
|
||||
}
|
||||
return steamRoots.flatMap { root ->
|
||||
File(root, "steamapps").listFiles { file ->
|
||||
file.isFile && file.name.startsWith("appmanifest_") && file.name.endsWith(".acf")
|
||||
}.orEmpty().toList()
|
||||
}
|
||||
}
|
||||
|
||||
private fun hostPath(runtimeRoot: File, guest: String, mounts: Map<String, File>): File {
|
||||
val path = guest.trimEnd('/')
|
||||
for ((mount, host) in mounts) {
|
||||
if (path == mount) return host
|
||||
if (path.startsWith("$mount/")) return File(host, path.removePrefix("$mount/"))
|
||||
}
|
||||
return File(runtimeRoot, path.removePrefix("/"))
|
||||
}
|
||||
|
||||
private fun read(file: File): ManifestState {
|
||||
val text = runCatching { file.readText() }.getOrDefault("")
|
||||
val flags = value(text, "StateFlags")?.toLongOrNull() ?: 0L
|
||||
@@ -137,9 +109,6 @@ internal class SteamDownloadMonitor {
|
||||
return ManifestState(downloaded, flags != 4L && (total <= 0L || downloaded < total))
|
||||
}
|
||||
|
||||
private fun value(text: String, key: String): String? =
|
||||
Regex("\"$key\"\\s+\"([^\"]*)\"").find(text)?.groupValues?.get(1)
|
||||
|
||||
companion object {
|
||||
fun clientInstallPending(runtimeRoot: File): Boolean {
|
||||
val home = File(runtimeRoot, "root")
|
||||
@@ -149,12 +118,43 @@ internal class SteamDownloadMonitor {
|
||||
return !(stamped && File(steam, "steamrtarm64/steam").isFile) || File(home, ".bl-steam-repair").exists()
|
||||
}
|
||||
|
||||
internal fun manifests(runtimeRoot: File, mounts: Map<String, File>): List<File> {
|
||||
val steamRoots = linkedSetOf<File>()
|
||||
for (home in STEAM_HOMES) {
|
||||
val primary = File(runtimeRoot, home)
|
||||
steamRoots += primary
|
||||
val libraryFolders = File(primary, "steamapps/libraryfolders.vdf")
|
||||
runCatching {
|
||||
PATH.findAll(libraryFolders.readText()).forEach { match ->
|
||||
steamRoots += hostPath(runtimeRoot, match.groupValues[1], mounts)
|
||||
}
|
||||
}
|
||||
}
|
||||
return steamRoots.flatMap { root ->
|
||||
File(root, "steamapps").listFiles { file ->
|
||||
file.isFile && file.name.startsWith("appmanifest_") && file.name.endsWith(".acf")
|
||||
}.orEmpty().toList()
|
||||
}
|
||||
}
|
||||
|
||||
private fun hostPath(runtimeRoot: File, guest: String, mounts: Map<String, File>): File {
|
||||
val path = guest.trimEnd('/')
|
||||
for ((mount, host) in mounts) {
|
||||
if (path == mount) return host
|
||||
if (path.startsWith("$mount/")) return File(host, path.removePrefix("$mount/"))
|
||||
}
|
||||
return File(runtimeRoot, path.removePrefix("/"))
|
||||
}
|
||||
|
||||
internal fun value(text: String, key: String): String? =
|
||||
Regex("\"$key\"\\s+\"([^\"]*)\"").find(text)?.groupValues?.get(1)
|
||||
|
||||
private const val MANIFEST_PROGRESS_GRACE_MS = 8_000L
|
||||
private const val CONTENT_ACTIVITY_GRACE_MS = 90_000L
|
||||
private const val MIN_RECEIVE_BYTES_PER_SEC = 64L * 1024L
|
||||
private val PATH = Regex("\"path\"\\s+\"([^\"]+)\"")
|
||||
private val STEAM_HOMES = listOf("root/.local/share/Steam", "root/.droiddeck-x64/.local/share/Steam")
|
||||
private val CONTENT_UPDATE = Regex("""AppID (\d+) (App|Workshop|Shader) update changed : (.*)""")
|
||||
internal val STEAM_HOMES = listOf("root/.local/share/Steam", "root/.droiddeck-x64/.local/share/Steam")
|
||||
internal val CONTENT_UPDATE = Regex("""AppID (\d+) (App|Workshop|Shader) update changed : (.*)""")
|
||||
private val CURRENT_RATE = Regex("""Current download rate: ([\d.]+) Mbps""")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
|
||||
/** A Steam download or update the client is working on. [total] is 0 while Steam has not sized it yet. */
|
||||
data class SteamDownload(
|
||||
val appId: String,
|
||||
val name: String,
|
||||
val done: Long,
|
||||
val total: Long,
|
||||
val shader: Boolean = false,
|
||||
val paused: Boolean = false,
|
||||
)
|
||||
|
||||
/** Reads Steam's own appmanifests and content log, the same files [SteamDownloadMonitor] watches. */
|
||||
object SteamDownloads {
|
||||
fun read(runtimeRoot: File, mounts: Map<String, File> = emptyMap(), client: String? = null): List<SteamDownload> {
|
||||
val names = HashMap<String, String>()
|
||||
val apps = SteamDownloadMonitor.manifests(runtimeRoot, mounts).mapNotNull { file ->
|
||||
val text = runCatching { file.readText() }.getOrNull() ?: return@mapNotNull null
|
||||
val id = SteamDownloadMonitor.value(text, "appid") ?: file.name.removePrefix("appmanifest_").removeSuffix(".acf")
|
||||
val name = SteamDownloadMonitor.value(text, "name") ?: id
|
||||
names[id] = name
|
||||
fromManifest(id, name, text)
|
||||
}
|
||||
val homes = client?.let { listOf(if (it == "x86_64") SteamDownloadMonitor.STEAM_HOMES[1] else SteamDownloadMonitor.STEAM_HOMES[0]) }
|
||||
?: SteamDownloadMonitor.STEAM_HOMES
|
||||
val log = homes.map { File(runtimeRoot, "$it/logs/content_log.txt") }.filter { it.isFile }.maxByOrNull { it.lastModified() }
|
||||
val shaders = log?.let { runningShaderUpdates(tail(it)) }.orEmpty()
|
||||
.map { SteamDownload(it, names[it] ?: it, 0L, 0L, shader = true) }
|
||||
return apps + shaders
|
||||
}
|
||||
|
||||
internal fun fromManifest(id: String, name: String, text: String): SteamDownload? {
|
||||
val flags = SteamDownloadMonitor.value(text, "StateFlags")?.toLongOrNull() ?: 0L
|
||||
if (flags == FULLY_INSTALLED) return null
|
||||
val done = SteamDownloadMonitor.value(text, "BytesDownloaded")?.toLongOrNull() ?: 0L
|
||||
val total = SteamDownloadMonitor.value(text, "BytesToDownload")?.toLongOrNull() ?: 0L
|
||||
if (total > 0L && done >= total) return null
|
||||
if ((flags and UPDATE_REQUIRED) == 0L && total <= 0L) return null
|
||||
return SteamDownload(id, name, done, total, paused = (flags and UPDATE_PAUSED) != 0L)
|
||||
}
|
||||
|
||||
/** App ids whose latest shader-cache line in the content log says the update is still running. */
|
||||
internal fun runningShaderUpdates(lines: Sequence<String>): List<String> {
|
||||
val state = LinkedHashMap<String, Boolean>()
|
||||
for (line in lines) {
|
||||
if ("Client version:" in line) state.clear()
|
||||
val match = SteamDownloadMonitor.CONTENT_UPDATE.find(line) ?: continue
|
||||
if (match.groupValues[2] != "Shader") continue
|
||||
val running = match.groupValues[3].let { "Running Update" in it && "Stopping" !in it }
|
||||
state[match.groupValues[1]] = running
|
||||
}
|
||||
return state.filterValues { it }.keys.toList()
|
||||
}
|
||||
|
||||
private fun tail(file: File): Sequence<String> = runCatching {
|
||||
RandomAccessFile(file, "r").use { raf ->
|
||||
val start = (raf.length() - TAIL_BYTES).coerceAtLeast(0L)
|
||||
raf.seek(start)
|
||||
val bytes = ByteArray((raf.length() - start).toInt())
|
||||
raf.readFully(bytes)
|
||||
String(bytes, Charsets.ISO_8859_1).lineSequence().drop(if (start > 0L) 1 else 0).toList().asSequence()
|
||||
}
|
||||
}.getOrDefault(emptySequence())
|
||||
|
||||
private const val FULLY_INSTALLED = 4L
|
||||
private const val UPDATE_REQUIRED = 2L
|
||||
private const val UPDATE_PAUSED = 512L
|
||||
private const val TAIL_BYTES = 256L * 1024L
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.io.File
|
||||
|
||||
object SteamGameProcess {
|
||||
fun matches(cmdline: ByteArray): Boolean {
|
||||
val args = String(cmdline).split('\u0000')
|
||||
for (i in args.indices) {
|
||||
if (args[i] == "waitforexitandrun") return true
|
||||
if (args[i] == "SteamLaunch" && args.getOrNull(i + 1)?.startsWith("AppId=") == true) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
fun running(proc: File = File("/proc")): Boolean = proc.listFiles()?.any { p ->
|
||||
p.name.all(Char::isDigit) && runCatching { File(p, "cmdline").readBytes() }.getOrNull()?.let(::matches) == true
|
||||
} == true
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
object SteamImportPrompt {
|
||||
data class Ask(val token: String, val games: List<String>)
|
||||
|
||||
private fun folder(root: File) = File(root, "root/.cache/droiddeck")
|
||||
|
||||
fun read(root: File): Ask? {
|
||||
val text = runCatching { File(folder(root), "steam-import.json").readText() }.getOrNull() ?: return null
|
||||
val json = runCatching { JSONObject(text) }.getOrNull() ?: return null
|
||||
val token = json.optString("token").takeIf { it.isNotEmpty() } ?: return null
|
||||
val list = json.optJSONArray("games")
|
||||
val games = if (list == null) emptyList() else (0 until list.length()).mapNotNull { list.optString(it).takeIf(String::isNotBlank) }
|
||||
return Ask(token, games)
|
||||
}
|
||||
|
||||
fun answer(root: File, token: String, now: Boolean): Boolean = runCatching {
|
||||
val dir = folder(root).apply { mkdirs() }
|
||||
val temp = File(dir, "steam-import.answer.tmp")
|
||||
temp.writeText(JSONObject().put("token", token).put("choice", if (now) "now" else "later").toString())
|
||||
temp.renameTo(File(dir, "steam-import.answer"))
|
||||
}.getOrDefault(false)
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.database.sqlite.SQLiteDatabase
|
||||
import java.io.File
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.SecretKeyFactory
|
||||
import javax.crypto.spec.IvParameterSpec
|
||||
import javax.crypto.spec.PBEKeySpec
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
/** A cookie for one https host, in the form CookieManager.setCookie takes. */
|
||||
data class WebCookie(val host: String, val header: String)
|
||||
|
||||
/**
|
||||
* The web sign-in the Steam client in the session already has, so the bottom-screen chat opens signed in.
|
||||
* Steam's built-in browser keeps it in its Chromium cookie store under config/htmlcache. With no keyring
|
||||
* (SteamOS and DroidDeck) Chromium encrypts values as "v10": AES-128-CBC, key PBKDF2-SHA1("peanuts",
|
||||
* "saltysalt", 1 round), IV of 16 spaces. Values are never logged.
|
||||
*/
|
||||
object SteamWebLogin {
|
||||
val HOSTS = listOf("steamcommunity.com", "steam-chat.com")
|
||||
private const val COOKIES = "config/htmlcache/Default/Cookies"
|
||||
private const val V10 = "v10"
|
||||
// From cookie store version 24 Chromium puts the SHA-256 of the host before each value.
|
||||
private const val HOST_HASH_VERSION = 24
|
||||
private const val HOST_HASH_BYTES = 32
|
||||
|
||||
private val key: SecretKeySpec by lazy {
|
||||
val spec = PBEKeySpec("peanuts".toCharArray(), "saltysalt".toByteArray(), 1, 128)
|
||||
SecretKeySpec(SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec).encoded, "AES")
|
||||
}
|
||||
|
||||
internal fun decrypt(encrypted: ByteArray, hostHashed: Boolean): String? = runCatching {
|
||||
if (encrypted.size <= V10.length || String(encrypted, 0, V10.length, Charsets.US_ASCII) != V10) return null
|
||||
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
|
||||
cipher.init(Cipher.DECRYPT_MODE, key, IvParameterSpec(ByteArray(16) { ' '.code.toByte() }))
|
||||
val plain = cipher.doFinal(encrypted, V10.length, encrypted.size - V10.length)
|
||||
val value = if (hostHashed && plain.size >= HOST_HASH_BYTES) plain.copyOfRange(HOST_HASH_BYTES, plain.size) else plain
|
||||
String(value, Charsets.UTF_8)
|
||||
}.getOrNull()
|
||||
|
||||
/** Steam's own pages send the sign-in with its "||" separator percent-encoded. */
|
||||
internal fun header(name: String, value: String, httpOnly: Boolean): String {
|
||||
val v = if (name == "steamLoginSecure") value.replace("||", "%7C%7C") else value
|
||||
return "$name=$v; Path=/; Secure" + if (httpOnly) "; HttpOnly" else ""
|
||||
}
|
||||
|
||||
/** Empty when the client has no web sign-in, for example before the first login. */
|
||||
fun read(runtimeRoot: File, client: String?, scratch: File): List<WebCookie> {
|
||||
val homes = client?.let { listOf(if (it == "x86_64") SteamDownloadMonitor.STEAM_HOMES[1] else SteamDownloadMonitor.STEAM_HOMES[0]) }
|
||||
?: SteamDownloadMonitor.STEAM_HOMES
|
||||
val store = homes.map { File(runtimeRoot, "$it/$COOKIES") }.filter { it.isFile }.maxByOrNull { it.lastModified() }
|
||||
?: return emptyList()
|
||||
// A copy, journal included: Steam keeps the store open and may be in the middle of a write.
|
||||
scratch.deleteRecursively()
|
||||
if (!scratch.mkdirs()) return emptyList()
|
||||
return try {
|
||||
val copy = File(scratch, "Cookies")
|
||||
store.copyTo(copy, overwrite = true)
|
||||
File(store.path + "-journal").takeIf { it.length() > 0L }?.copyTo(File(scratch, "Cookies-journal"), overwrite = true)
|
||||
SQLiteDatabase.openDatabase(copy.path, null, SQLiteDatabase.OPEN_READWRITE).use { db ->
|
||||
val version = db.rawQuery("SELECT value FROM meta WHERE key = 'version'", null).use { if (it.moveToFirst()) it.getString(0).toIntOrNull() else null } ?: 0
|
||||
val marks = HOSTS.joinToString { "?" }
|
||||
db.rawQuery("SELECT host_key, name, value, encrypted_value, is_httponly FROM cookies WHERE host_key IN ($marks)", HOSTS.toTypedArray()).use { c ->
|
||||
val out = ArrayList<WebCookie>()
|
||||
while (c.moveToNext()) {
|
||||
val name = c.getString(1)
|
||||
val value = c.getString(2).takeUnless { it.isNullOrEmpty() }
|
||||
?: decrypt(c.getBlob(3) ?: continue, version >= HOST_HASH_VERSION) ?: continue
|
||||
out += WebCookie(c.getString(0), header(name, value, c.getInt(4) != 0))
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
emptyList()
|
||||
} finally {
|
||||
scratch.deleteRecursively()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Codemasters games keep their UDP / motion output in My Games/<game>/hardwaresettings/hardware_settings_config.xml
|
||||
* inside the game's Proton prefix and read it when the game starts. Turning it on points that element at the
|
||||
* In-game stats listener; the file as it was is kept beside it, and its element is put back when turned off.
|
||||
*/
|
||||
object TelemetryOutput {
|
||||
data class Game(val name: String, val prefixId: String, val file: File, val on: Boolean)
|
||||
|
||||
data class MenuGame(val name: String, val setting: String, val port: Int)
|
||||
|
||||
/** Games whose output is only a setting in the game's own menus, by Steam app id. */
|
||||
val MENU_GAMES: Map<Int, MenuGame> = mapOf(
|
||||
1293830 to MenuGame("Forza Horizon 4", "Data Out", GameTelemetry.FORZA_PORT),
|
||||
1551360 to MenuGame("Forza Horizon 5", "Data Out", GameTelemetry.FORZA_PORT),
|
||||
2440510 to MenuGame("Forza Motorsport", "Data Out", GameTelemetry.FORZA_PORT),
|
||||
284160 to MenuGame("BeamNG.drive", "OutGauge", GameTelemetry.OUTGAUGE_PORT),
|
||||
)
|
||||
|
||||
internal const val ORIGINAL_SUFFIX = ".droiddeck-original"
|
||||
private const val MY_GAMES = "pfx/drive_c/users/steamuser/Documents/My Games"
|
||||
private const val CONFIG = "hardwaresettings/hardware_settings_config.xml"
|
||||
private const val ADDRESS = "127.0.0.1"
|
||||
private const val EXTRADATA = "3"
|
||||
private val TAGS = listOf("udp", "motion")
|
||||
// Byte-for-byte: every byte maps to one char and back, whatever the file's own encoding is.
|
||||
private val BYTES = Charsets.ISO_8859_1
|
||||
|
||||
fun scan(compatdata: List<File>): List<Game> = compatdata.asSequence()
|
||||
.flatMap { root -> root.listFiles { f -> f.isDirectory }.orEmpty().asSequence() }
|
||||
.flatMap { prefix -> File(prefix, MY_GAMES).listFiles { f -> f.isDirectory }.orEmpty().asSequence().map { prefix to it } }
|
||||
.mapNotNull { (prefix, game) ->
|
||||
val file = File(game, CONFIG)
|
||||
val text = runCatching { file.readText(BYTES) }.getOrNull() ?: return@mapNotNull null
|
||||
val element = element(text) ?: return@mapNotNull null
|
||||
Game(game.name, prefix.name, file, pointsHere(element.value))
|
||||
}
|
||||
.sortedBy { it.name.lowercase() }
|
||||
.toList()
|
||||
|
||||
/** Turns the game's output on or off; false when the file could not be read or written. */
|
||||
fun set(game: Game, on: Boolean): Boolean = runCatching {
|
||||
val file = game.file
|
||||
val original = File(file.path + ORIGINAL_SUFFIX)
|
||||
val xml = file.readText(BYTES)
|
||||
val next = if (on) {
|
||||
if (!original.exists()) file.copyTo(original)
|
||||
turnedOn(xml)
|
||||
} else {
|
||||
turnedOff(xml, original.takeIf { it.isFile }?.readText(BYTES))
|
||||
}
|
||||
checkNotNull(next)
|
||||
val tmp = File(file.path + ".droiddeck-tmp")
|
||||
tmp.writeText(next, BYTES)
|
||||
check(tmp.renameTo(file))
|
||||
if (!on) original.delete()
|
||||
true
|
||||
}.getOrDefault(false)
|
||||
|
||||
/** Automatic: turns the output on for every found game the user has not switched off and that is not running. */
|
||||
fun applyAutomatic(context: Context, running: String?) {
|
||||
if (!SessionPrefs.telemetryAuto(context)) return
|
||||
automaticTargets(scan(Library.compatdataDirs(context)), SessionPrefs.telemetryOff(context), running).forEach { set(it, true) }
|
||||
}
|
||||
|
||||
internal fun key(game: Game) = "${game.prefixId}/${game.name}"
|
||||
|
||||
internal fun automaticTargets(games: List<Game>, off: Set<String>, running: String?): List<Game> =
|
||||
games.filter { !it.on && key(it) !in off && !isRunning(it.prefixId, running) }
|
||||
|
||||
/** Games DroidDeck changed, which go back to their own setting when Automatic is switched off. */
|
||||
internal fun restoreTargets(games: List<Game>, running: String?): List<Game> =
|
||||
games.filter { File(it.file.path + ORIGINAL_SUFFIX).isFile && !isRunning(it.prefixId, running) }
|
||||
|
||||
/** Whether [running] (the focused Steam app id, or another key for non-Steam programs) may be the game in [prefixId]. */
|
||||
internal fun isRunning(prefixId: String, running: String?): Boolean {
|
||||
val id = running?.toLongOrNull() ?: return running != null
|
||||
return prefixId == id.toString() || prefixId == id.toInt().toString()
|
||||
}
|
||||
|
||||
internal fun element(xml: String): MatchResult? = TAGS.firstNotNullOfOrNull { tag -> tagRegex(tag).find(xml) }
|
||||
|
||||
internal fun pointsHere(element: String): Boolean =
|
||||
attr(element, "enabled") == "true" && attr(element, "ip") == ADDRESS &&
|
||||
attr(element, "port") == GameTelemetry.CODEMASTERS_PORT.toString() &&
|
||||
(attr(element, "extradata") ?: EXTRADATA) == EXTRADATA
|
||||
|
||||
internal fun turnedOn(xml: String): String? {
|
||||
val element = element(xml) ?: return null
|
||||
var on = withAttr(element.value, "enabled", "true")
|
||||
on = withAttr(on, "ip", ADDRESS)
|
||||
on = withAttr(on, "port", GameTelemetry.CODEMASTERS_PORT.toString())
|
||||
if (attr(on, "extradata") != null) on = withAttr(on, "extradata", EXTRADATA)
|
||||
return xml.replaceRange(element.range, on)
|
||||
}
|
||||
|
||||
internal fun turnedOff(xml: String, original: String?): String? {
|
||||
val element = element(xml) ?: return null
|
||||
val tag = element.value.drop(1).takeWhile { !it.isWhitespace() }
|
||||
val before = original?.let { tagRegex(tag).find(it)?.value }
|
||||
return xml.replaceRange(element.range, before ?: withAttr(element.value, "enabled", "false"))
|
||||
}
|
||||
|
||||
internal fun attr(element: String, name: String): String? =
|
||||
Regex("\\s$name=\"([^\"]*)\"").find(element)?.groupValues?.get(1)
|
||||
|
||||
internal fun withAttr(element: String, name: String, value: String): String {
|
||||
val existing = Regex("(\\s$name=\")[^\"]*\"")
|
||||
if (existing.containsMatchIn(element)) return existing.replace(element) { it.groupValues[1] + value + "\"" }
|
||||
val selfClosing = element.endsWith("/>")
|
||||
val body = element.dropLast(if (selfClosing) 2 else 1).trimEnd()
|
||||
return "$body $name=\"$value\"" + if (selfClosing) " />" else ">"
|
||||
}
|
||||
|
||||
private fun tagRegex(tag: String) = Regex("<$tag\\s[^>]*>")
|
||||
}
|
||||
@@ -92,6 +92,28 @@ object SteamLiveShortcuts {
|
||||
if (evaluate(context, js) != null) Log.i(TAG, "live shortcuts: updated $id")
|
||||
}
|
||||
|
||||
fun launchOptions(context: Context, appId: Long): String? {
|
||||
if (!clientRunning()) return null
|
||||
val js = """
|
||||
new Promise(done => {
|
||||
let handle = null, answer;
|
||||
const finish = d => { clearTimeout(timer); try { handle?.unregister(); } catch (e) {} done(d); };
|
||||
const timer = setTimeout(() => finish(null), 4000);
|
||||
handle = SteamClient.Apps.RegisterForAppDetails(${appId and 0xFFFFFFFFL}, d => { answer = d; if (handle) finish(d); });
|
||||
if (answer !== undefined) finish(answer);
|
||||
}).then(d => typeof d?.strLaunchOptions === 'string' ? d.strLaunchOptions : null)
|
||||
""".trimIndent()
|
||||
return evaluate(context, js)
|
||||
}
|
||||
|
||||
fun setLaunchOptions(context: Context, appId: Long, options: String): Boolean {
|
||||
if (!clientRunning()) return false
|
||||
val id = appId and 0xFFFFFFFFL
|
||||
val done = evaluate(context, "(async () => { SteamClient.Apps.SetAppLaunchOptions($id, ${JSONObject.quote(options)}); return 1; })()") != null
|
||||
if (done) Log.i(TAG, "live: launch options for $id")
|
||||
return done
|
||||
}
|
||||
|
||||
fun setArt(context: Context, appId: Long, assetType: Int?, file: java.io.File?, iconPath: String? = null) {
|
||||
if (!clientRunning()) return
|
||||
val id = appId and 0xFFFFFFFFL
|
||||
|
||||
@@ -137,10 +137,7 @@ object StoreInstallRoot {
|
||||
.filter { !isInternal(context, it) && (library == null || !it.absolutePath.startsWith("$library/")) }
|
||||
.map { root ->
|
||||
val base = guestFor(context, root)
|
||||
val guest = if (used.add(base)) base else {
|
||||
val suffix = "%08x".format(CRC32().apply { update(root.absolutePath.toByteArray()) }.value)
|
||||
"$base-$suffix".also { used.add(it) }
|
||||
}
|
||||
val guest = if (used.add(base)) base else "$base-${pathKey(root)}".also { used.add(it) }
|
||||
root to guest
|
||||
}
|
||||
}
|
||||
@@ -168,15 +165,20 @@ object StoreInstallRoot {
|
||||
|
||||
/** Xodus has its own PRoot mount table and cannot see the selected Steam library's SD bind. */
|
||||
fun externalRootsForXodus(context: Context): List<Pair<File, String>> {
|
||||
val roots = externalRoots(context).toMutableList()
|
||||
val roots = externalRoots(context)
|
||||
val selectedLibrary = GameStorage.effective(context)?.let { File(it.path, ON_VOLUME) }
|
||||
?.takeUnless { isInternal(context, it) }
|
||||
if (selectedLibrary != null && roots.none { it.first.absolutePath == selectedLibrary.absolutePath }) {
|
||||
roots += selectedLibrary to guestFor(context, selectedLibrary)
|
||||
}
|
||||
return roots
|
||||
?.takeUnless { isInternal(context, it) } ?: return roots
|
||||
return withSelectedLibrary(roots, selectedLibrary, guestFor(context, selectedLibrary))
|
||||
}
|
||||
|
||||
internal fun withSelectedLibrary(roots: List<Pair<File, String>>, library: File, base: String): List<Pair<File, String>> {
|
||||
if (roots.any { it.first.absolutePath == library.absolutePath }) return roots
|
||||
val guest = if (roots.none { it.second == base }) base else "$base-${pathKey(library)}"
|
||||
return roots + (library to guest)
|
||||
}
|
||||
|
||||
private fun pathKey(root: File): String = "%08x".format(CRC32().apply { update(root.absolutePath.toByteArray()) }.value)
|
||||
|
||||
fun externalBindSpecs(context: Context): List<String> = externalBindSpecs(externalRoots(context), LinuxRuntime.rootDir(context))
|
||||
|
||||
fun externalBindSpecsForXodus(context: Context): List<String> =
|
||||
@@ -192,7 +194,7 @@ object StoreInstallRoot {
|
||||
private fun guestFor(context: Context, root: File): String {
|
||||
val sm = context.getSystemService(StorageManager::class.java)
|
||||
val uuid = runCatching { sm?.getStorageVolume(root)?.uuid }.getOrNull()?.takeIf { it.isNotBlank() }?.replace(Regex("[^A-Za-z0-9-]"), "")
|
||||
val key = uuid ?: "%08x".format(CRC32().apply { update(root.absolutePath.toByteArray()) }.value)
|
||||
val key = uuid ?: pathKey(root)
|
||||
return "$GUEST_EXTERNAL/$key"
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.droiddeck.launcher.stores.itch
|
||||
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.nio.file.Files
|
||||
|
||||
internal object ItchArchives {
|
||||
private val PACKED = setOf("zip", "7z", "rar", "tar", "gz", "bz2", "xz")
|
||||
|
||||
fun kind(file: File, filename: String): String {
|
||||
val extension = filename.substringAfterLast('.', "").lowercase()
|
||||
if (extension == "exe") return "exe"
|
||||
return signature(file) ?: extension
|
||||
}
|
||||
|
||||
private fun signature(file: File): String? {
|
||||
val head = runCatching { FileInputStream(file).use { input -> ByteArray(300).also { input.read(it) } } }.getOrNull()
|
||||
?: return null
|
||||
fun at(i: Int, vararg bytes: Int) = bytes.indices.all { head.getOrNull(i + it) == bytes[it].toByte() }
|
||||
return when {
|
||||
at(0, 0x50, 0x4B) -> "zip"
|
||||
at(0, 0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C) -> "7z"
|
||||
at(0, 0x52, 0x61, 0x72, 0x21) -> "rar"
|
||||
at(0, 0x1F, 0x8B) -> "gz"
|
||||
at(0, 0x42, 0x5A, 0x68) -> "bz2"
|
||||
at(0, 0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00) -> "xz"
|
||||
at(257, 0x75, 0x73, 0x74, 0x61, 0x72) -> "tar"
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
fun inner(folder: File): File? {
|
||||
val found = ArrayList<File>()
|
||||
fun walk(dir: File, depth: Int) {
|
||||
val files = dir.listFiles() ?: return
|
||||
for (file in files) {
|
||||
if (Files.isSymbolicLink(file.toPath())) continue
|
||||
if (file.isFile && signature(file) in PACKED) found.add(file)
|
||||
else if (file.isDirectory && depth < 2 && !file.name.startsWith(".")) walk(file, depth + 1)
|
||||
}
|
||||
}
|
||||
walk(folder, 0)
|
||||
return found.maxByOrNull { it.length() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package com.droiddeck.launcher.stores.itch
|
||||
|
||||
import com.droiddeck.launcher.stores.StoreNet
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
internal object ItchBuilds {
|
||||
private const val BASE = "https://api.itch.io"
|
||||
private const val MAX_STEPS = 4
|
||||
|
||||
class Step(val buildId: Long, val patchFile: Long, val patchSize: Long, val signatureFile: Long)
|
||||
|
||||
fun buildId(upload: JSONObject): String {
|
||||
val value = upload.opt("build_id") ?: upload.opt("buildId")
|
||||
return when (value) {
|
||||
is Number -> value.toLong().takeIf { it > 0 }?.toString().orEmpty()
|
||||
is String -> value.takeIf { it.all(Char::isDigit) }?.toLongOrNull()?.takeIf { it > 0 }?.toString().orEmpty()
|
||||
else -> ""
|
||||
}
|
||||
}
|
||||
|
||||
fun path(key: String, from: String, to: String, downloadKeyId: String): List<Step>? {
|
||||
val fromId = from.toLongOrNull() ?: return null
|
||||
val toId = to.toLongOrNull() ?: return null
|
||||
val reply = ItchApi.get("/builds/$fromId/upgrade-paths/$toId" + keyQuery(downloadKeyId), key) ?: return null
|
||||
return steps(reply, fromId, toId) { filesOf(key, it, downloadKeyId) }
|
||||
}
|
||||
|
||||
fun steps(reply: JSONObject, fromId: Long, toId: Long, filesFor: (JSONObject) -> JSONArray?): List<Step>? {
|
||||
val builds = (reply.optJSONObject("upgrade_path") ?: reply.optJSONObject("upgradePath"))?.optJSONArray("builds") ?: return null
|
||||
val ids = (0 until builds.length()).mapNotNull { builds.optJSONObject(it) }
|
||||
val after = ids.filter { it.optLong("id") != fromId }
|
||||
if (after.isEmpty() || after.size > MAX_STEPS || after.last().optLong("id") != toId) return null
|
||||
val steps = after.map { build ->
|
||||
val files = filesFor(build) ?: return null
|
||||
val patch = pick(files, "patch") ?: return null
|
||||
val signature = pick(files, "signature")
|
||||
Step(build.optLong("id"), patch.optLong("id"), patch.optLong("size"), signature?.optLong("id") ?: 0L)
|
||||
}
|
||||
return steps.takeIf { it.last().signatureFile > 0 }
|
||||
}
|
||||
|
||||
fun fileUrl(buildId: Long, fileId: Long, downloadKeyId: String): String =
|
||||
"$BASE/wharf/builds/$buildId/files/$fileId/download" + keyQuery(downloadKeyId)
|
||||
|
||||
fun download(url: String, key: String, target: File, cancelled: AtomicBoolean, progress: (Long) -> Unit): Boolean {
|
||||
val first = open(url, key)
|
||||
try {
|
||||
val code = first.responseCode
|
||||
val location = first.getHeaderField("Location")
|
||||
if (code in 300..399 && location != null) {
|
||||
first.disconnect()
|
||||
val next = URL(URL(url), location).toString()
|
||||
if (!next.startsWith("https://")) return false
|
||||
return save(open(next, null), target, cancelled, progress)
|
||||
}
|
||||
return save(first, target, cancelled, progress)
|
||||
} finally {
|
||||
runCatching { first.disconnect() }
|
||||
}
|
||||
}
|
||||
|
||||
private fun save(conn: HttpURLConnection, target: File, cancelled: AtomicBoolean, progress: (Long) -> Unit): Boolean {
|
||||
try {
|
||||
if (conn.responseCode !in 200..299) return false
|
||||
var done = 0L
|
||||
val buffer = ByteArray(128 * 1024)
|
||||
conn.inputStream.use { input ->
|
||||
FileOutputStream(target).use { out ->
|
||||
while (true) {
|
||||
if (cancelled.get()) return false
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
out.write(buffer, 0, read)
|
||||
done += read
|
||||
progress(done)
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
} finally {
|
||||
runCatching { conn.disconnect() }
|
||||
}
|
||||
}
|
||||
|
||||
private fun open(url: String, key: String?): HttpURLConnection =
|
||||
(URL(url).openConnection() as HttpURLConnection).apply {
|
||||
connectTimeout = 30_000
|
||||
readTimeout = 60_000
|
||||
instanceFollowRedirects = false
|
||||
setRequestProperty("User-Agent", StoreNet.BROWSER_UA)
|
||||
setRequestProperty("Accept", "*/*")
|
||||
if (key != null) setRequestProperty("Authorization", "Bearer $key")
|
||||
}
|
||||
|
||||
private fun filesOf(key: String, build: JSONObject, downloadKeyId: String): JSONArray? =
|
||||
build.optJSONArray("files")
|
||||
?: ItchApi.get("/builds/${build.optLong("id")}" + keyQuery(downloadKeyId), key)?.optJSONObject("build")?.optJSONArray("files")
|
||||
|
||||
private fun pick(files: JSONArray, type: String): JSONObject? {
|
||||
val all = (0 until files.length()).mapNotNull { files.optJSONObject(it) }
|
||||
.filter { it.optString("type") == type && it.optString("state", "uploaded") == "uploaded" }
|
||||
return all.firstOrNull { subType(it) == "optimized" } ?: all.firstOrNull { subType(it) == "default" }
|
||||
}
|
||||
|
||||
private fun subType(file: JSONObject): String = file.optString("sub_type", file.optString("subType", "default"))
|
||||
|
||||
private fun keyQuery(downloadKeyId: String): String = if (downloadKeyId.isBlank()) "" else "?download_key_id=$downloadKeyId"
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import com.droiddeck.launcher.stores.StoreInstalls
|
||||
import com.droiddeck.launcher.stores.StoreNet
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||
import org.apache.commons.compress.MemoryLimitException
|
||||
import org.apache.commons.compress.archivers.sevenz.SevenZFile
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream
|
||||
import org.apache.commons.compress.archivers.zip.ZipFile
|
||||
@@ -25,6 +26,7 @@ import java.io.FileInputStream
|
||||
import java.io.FileOutputStream
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.nio.file.Files
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
internal class ItchInstaller(
|
||||
@@ -60,12 +62,31 @@ internal class ItchInstaller(
|
||||
val scratch = StoreInstallRoot.scratchDir(app, Store.ITCH, item.id)
|
||||
scratch.mkdirs()
|
||||
val archive = File(scratch, filename.ifBlank { "download.bin" })
|
||||
val buildId = ItchBuilds.buildId(upload)
|
||||
val exe = try {
|
||||
handle.stage(DownloadStage.DOWNLOAD)
|
||||
download(key, downloadKeyId, uploadId, upload.optString("updated_at", upload.optString("updatedAt")), archive, size, handle)
|
||||
if (cancelled.get()) return null
|
||||
handle.stage(DownloadStage.INSTALL)
|
||||
install(archive, filename, handle, resuming)
|
||||
var patched = updating && !resuming && previous?.isInstalled == true &&
|
||||
patch(key, downloadKeyId, uploadId, buildId, size, scratch, handle)
|
||||
if (cancelled.get()) {
|
||||
if (patched) dropCaches(scratch)
|
||||
return null
|
||||
}
|
||||
var picked: String? = null
|
||||
if (patched) {
|
||||
picked = install(archive, filename, handle, resuming, true)
|
||||
if (picked == null) {
|
||||
if (cancelled.get()) return null
|
||||
handle.log("itch.io: the patched copy of ${item.title} has no exe, doing a full update")
|
||||
patched = false
|
||||
}
|
||||
}
|
||||
if (!patched) {
|
||||
handle.stage(DownloadStage.DOWNLOAD)
|
||||
download(key, downloadKeyId, uploadId, upload.optString("updated_at", upload.optString("updatedAt")), archive, size, handle)
|
||||
if (cancelled.get()) return null
|
||||
handle.stage(DownloadStage.INSTALL)
|
||||
picked = install(archive, filename, handle, resuming, false)
|
||||
}
|
||||
picked
|
||||
} catch (t: Throwable) {
|
||||
if (!cancelled.get()) dropCaches(scratch)
|
||||
throw t
|
||||
@@ -88,7 +109,7 @@ internal class ItchInstaller(
|
||||
installedAt = System.currentTimeMillis(),
|
||||
cover = item.imageUrl,
|
||||
hero = item.imageUrl,
|
||||
extra = mapOf("gameId" to gameId, "downloadKeyId" to downloadKeyId, "uploadId" to uploadId),
|
||||
extra = mapOf("gameId" to gameId, "downloadKeyId" to downloadKeyId, "uploadId" to uploadId, "buildId" to buildId),
|
||||
cloud = false,
|
||||
)
|
||||
StoreInstalls.complete(app, folder, sidecar) { done, steps -> handle.stageProgress(done.toLong(), steps.toLong()) }
|
||||
@@ -178,23 +199,50 @@ internal class ItchInstaller(
|
||||
}
|
||||
}
|
||||
|
||||
private fun install(archive: File, filename: String, handle: DownloadQueue.JobHandle, resuming: Boolean): String? {
|
||||
private fun patch(key: String, downloadKeyId: String, uploadId: String, buildId: String, fullSize: Long, scratch: File, handle: DownloadQueue.JobHandle): Boolean {
|
||||
val installed = previous?.extra.orEmpty()
|
||||
val from = installed["buildId"].orEmpty()
|
||||
if (installed["uploadId"] != uploadId || from.isBlank() || buildId.isBlank() || from == buildId) return false
|
||||
val out = File(folder, ItchStaging.DIR)
|
||||
ItchStaging.delete(out)
|
||||
scratch.mkdirs()
|
||||
val outcome = try {
|
||||
ItchPatch.run(app, key, downloadKeyId, from, buildId, fullSize, folder, out, scratch, handle, cancelled)
|
||||
} catch (t: Exception) {
|
||||
ItchPatch.Outcome.Failed("${t.javaClass.simpleName} ${t.message}")
|
||||
}
|
||||
when (outcome) {
|
||||
ItchPatch.Outcome.Applied -> {
|
||||
handle.log("itch.io: patched ${item.title} from build $from to $buildId")
|
||||
return true
|
||||
}
|
||||
ItchPatch.Outcome.Cancelled -> Unit
|
||||
is ItchPatch.Outcome.Failed -> handle.log("itch.io: no patch for ${item.title}, doing a full update (${outcome.reason})")
|
||||
}
|
||||
ItchStaging.delete(out)
|
||||
return false
|
||||
}
|
||||
|
||||
private fun install(archive: File, filename: String, handle: DownloadQueue.JobHandle, resuming: Boolean, patched: Boolean = false): String? {
|
||||
work = if (updating) File(folder, ItchStaging.DIR) else folder
|
||||
if (updating) ItchStaging.delete(work)
|
||||
if (updating && !patched) ItchStaging.delete(work)
|
||||
work.mkdirs()
|
||||
if (resuming) clearPartialInstall()
|
||||
val exe = try {
|
||||
when (val kind = sniff(archive, filename)) {
|
||||
"zip" -> unzip(archive, handle)
|
||||
"7z" -> sevenZip(archive, handle)
|
||||
"rar" -> unrar(archive, handle)
|
||||
"exe" -> copy(archive, File(work, filename.ifBlank { "game.exe" }))
|
||||
"tar" -> untar(archive, null, handle)
|
||||
"gz", "bz2", "xz" -> untar(archive, kind, handle) ?: single(archive, kind, handle)
|
||||
else -> copy(archive, File(work, filename.ifBlank { "game" }))
|
||||
}
|
||||
if (!patched) unpack(archive, filename, handle)
|
||||
val hint = filename.substringBeforeLast('.')
|
||||
StoreExe.pick(work, hint.ifBlank { null }, item.title)
|
||||
var picked = StoreExe.pick(work, hint.ifBlank { null }, item.title)
|
||||
var passes = 0
|
||||
while (picked.isBlank() && passes < 2 && !cancelled.get()) {
|
||||
val inner = ItchArchives.inner(work) ?: break
|
||||
handle.log("itch.io: no exe yet, unpacking ${inner.name}")
|
||||
unpack(inner, inner.name, handle)
|
||||
if (cancelled.get()) break
|
||||
inner.delete()
|
||||
picked = StoreExe.pick(work, inner.name.substringBeforeLast('.').takeIf { it.endsWith(".exe", ignoreCase = true) }, item.title)
|
||||
passes++
|
||||
}
|
||||
picked
|
||||
} catch (t: Throwable) {
|
||||
if (updating) ItchStaging.delete(work)
|
||||
throw t
|
||||
@@ -221,21 +269,20 @@ internal class ItchInstaller(
|
||||
return exe
|
||||
}
|
||||
|
||||
private fun sniff(file: File, filename: String): String {
|
||||
val extension = filename.substringAfterLast('.', "").lowercase()
|
||||
if (extension == "exe") return "exe"
|
||||
val head = runCatching { FileInputStream(file).use { input -> ByteArray(300).also { input.read(it) } } }.getOrNull()
|
||||
?: return extension
|
||||
fun at(i: Int, vararg bytes: Int) = bytes.indices.all { head.getOrNull(i + it) == bytes[it].toByte() }
|
||||
return when {
|
||||
at(0, 0x50, 0x4B) -> "zip"
|
||||
at(0, 0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C) -> "7z"
|
||||
at(0, 0x52, 0x61, 0x72, 0x21) -> "rar"
|
||||
at(0, 0x1F, 0x8B) -> "gz"
|
||||
at(0, 0x42, 0x5A, 0x68) -> "bz2"
|
||||
at(0, 0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00) -> "xz"
|
||||
at(257, 0x75, 0x73, 0x74, 0x61, 0x72) -> "tar"
|
||||
else -> extension
|
||||
private fun unpack(archive: File, filename: String, handle: DownloadQueue.JobHandle) {
|
||||
when (val kind = ItchArchives.kind(archive, filename)) {
|
||||
"zip" -> unzip(archive, handle)
|
||||
"7z" -> try {
|
||||
sevenZip(archive, handle)
|
||||
} catch (e: MemoryLimitException) {
|
||||
handle.log("itch.io: ${archive.name} needs more memory than the app has, unpacking it in the runtime")
|
||||
unrar(archive, handle, kind)
|
||||
}
|
||||
"rar" -> unrar(archive, handle, kind)
|
||||
"exe" -> copy(archive, File(work, filename.ifBlank { "game.exe" }))
|
||||
"tar" -> untar(archive, null, handle)
|
||||
"gz", "bz2", "xz" -> untar(archive, kind, handle) ?: single(archive, kind, handle)
|
||||
else -> copy(archive, File(work, filename.ifBlank { "game" }))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -247,12 +294,12 @@ internal class ItchInstaller(
|
||||
}
|
||||
|
||||
// No JVM library reads RAR5; the runtime's bsdtar (libarchive) does.
|
||||
private fun unrar(archive: File, handle: DownloadQueue.JobHandle) {
|
||||
if (!LinuxRuntime.isInstalled(app)) throw IllegalStateException(app.getString(R.string.stores_itch_archive, "rar"))
|
||||
private fun unrar(archive: File, handle: DownloadQueue.JobHandle, kind: String) {
|
||||
if (!LinuxRuntime.isInstalled(app)) throw IllegalStateException(app.getString(R.string.stores_itch_archive, kind))
|
||||
val binds = if (listOf(app.filesDir, app.cacheDir).any { work.absolutePath.startsWith(it.absolutePath + "/") }) null
|
||||
else listOf(work.absolutePath)
|
||||
fun bsdtar(args: List<String>, onLine: (String) -> Unit) =
|
||||
GuestCommand.run(app, listOf("/usr/bin/bsdtar") + args, logName = "itch-unrar", extraBinds = binds, fastPath = true) { line ->
|
||||
GuestCommand.run(app, listOf("/usr/bin/bsdtar") + args, logName = "itch-unrar", extraBinds = binds, fastPath = true, cancelled = cancelled) { line ->
|
||||
if (!line.startsWith("proot ")) onLine(line)
|
||||
}
|
||||
var entries = 0L
|
||||
@@ -276,28 +323,31 @@ internal class ItchInstaller(
|
||||
val total = archive.length()
|
||||
var written = 0L
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
SevenZFile.builder().setFile(archive).get().use { seven ->
|
||||
while (true) {
|
||||
if (cancelled.get()) return
|
||||
val entry = seven.nextEntry ?: break
|
||||
val file = target(entry.name)
|
||||
if (file == null) {
|
||||
handle.log("itch.io: skipped an entry outside the game folder")
|
||||
continue
|
||||
}
|
||||
if (entry.isDirectory) {
|
||||
file.mkdirs()
|
||||
continue
|
||||
}
|
||||
file.parentFile?.mkdirs()
|
||||
FileOutputStream(file).use { out ->
|
||||
while (true) {
|
||||
if (cancelled.get()) return
|
||||
val read = seven.read(buffer, 0, buffer.size)
|
||||
if (read < 0) break
|
||||
out.write(buffer, 0, read)
|
||||
written += read
|
||||
handle.stageProgress(written, total)
|
||||
val limitKb = (Runtime.getRuntime().maxMemory() / 4 / 1024).coerceIn(32L * 1024, Int.MAX_VALUE.toLong()).toInt()
|
||||
Files.newByteChannel(archive.toPath()).use { channel ->
|
||||
SevenZFile.builder().setSeekableByteChannel(channel).setMaxMemoryLimitKb(limitKb).get().use { seven ->
|
||||
while (true) {
|
||||
if (cancelled.get()) return
|
||||
val entry = seven.nextEntry ?: break
|
||||
val file = target(entry.name)
|
||||
if (file == null) {
|
||||
handle.log("itch.io: skipped an entry outside the game folder")
|
||||
continue
|
||||
}
|
||||
if (entry.isDirectory) {
|
||||
file.mkdirs()
|
||||
continue
|
||||
}
|
||||
file.parentFile?.mkdirs()
|
||||
FileOutputStream(file).use { out ->
|
||||
while (true) {
|
||||
if (cancelled.get()) return
|
||||
val read = seven.read(buffer, 0, buffer.size)
|
||||
if (read < 0) break
|
||||
out.write(buffer, 0, read)
|
||||
written += read
|
||||
handle.stageProgress(written, total)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
package com.droiddeck.launcher.stores.itch
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.core.AddonPack
|
||||
import com.droiddeck.launcher.runtime.GuestCommand
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.stores.StoreInstalls
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||
import java.io.File
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
internal object ItchPatch {
|
||||
private const val DIR = "/usr/local/lib/droiddeck-butler"
|
||||
|
||||
sealed interface Outcome {
|
||||
data object Applied : Outcome
|
||||
data object Cancelled : Outcome
|
||||
data class Failed(val reason: String) : Outcome
|
||||
}
|
||||
|
||||
fun ready(context: Context): Boolean {
|
||||
if (!AddonPack.BUTLER.available || !LinuxRuntime.isInstalled(context)) return false
|
||||
if (!AddonPack.BUTLER.installed(context)) {
|
||||
AddonPack.BUTLER.ensure(context)
|
||||
return false
|
||||
}
|
||||
return stage(context)
|
||||
}
|
||||
|
||||
private val stageLock = Any()
|
||||
|
||||
private fun stage(context: Context): Boolean = synchronized(stageLock) { stageLocked(context) }
|
||||
|
||||
private fun stageLocked(context: Context): Boolean {
|
||||
val pack = AddonPack.BUTLER.dir(context)
|
||||
val root = File(LinuxRuntime.rootDir(context), DIR.removePrefix("/"))
|
||||
val packaged = File(pack, "version").readText()
|
||||
if (runCatching { File(root, "version").readText() }.getOrNull() == packaged && File(root, "butler").isFile) return true
|
||||
root.mkdirs()
|
||||
pack.listFiles().orEmpty().filter { it.isFile && it.name != "version" && it.name != AddonPack.COMPLETE }.forEach { source ->
|
||||
val staged = File(root, source.name + ".staged")
|
||||
source.inputStream().use { input -> staged.outputStream().use { input.copyTo(it) } }
|
||||
staged.setExecutable(true, false)
|
||||
check(staged.renameTo(File(root, source.name)))
|
||||
}
|
||||
File(root, "version").writeText(packaged)
|
||||
return true
|
||||
}
|
||||
|
||||
fun run(
|
||||
app: Context, key: String, downloadKeyId: String, from: String, to: String, fullSize: Long, installed: File, out: File, scratch: File,
|
||||
handle: DownloadQueue.JobHandle, cancelled: AtomicBoolean,
|
||||
): Outcome {
|
||||
if (!ready(app)) return Outcome.Failed("the patch tool is not ready")
|
||||
val steps = ItchBuilds.path(key, from, to, downloadKeyId) ?: return Outcome.Failed("no patch path from build $from to $to")
|
||||
if (fullSize > 0 && steps.sumOf { it.patchSize } > fullSize) return Outcome.Failed("the patches are larger than a full download")
|
||||
val dir = File(scratch, "patches").apply { deleteRecursively(); mkdirs() }
|
||||
try {
|
||||
handle.stage(DownloadStage.DOWNLOAD)
|
||||
val total = steps.sumOf { it.patchSize }
|
||||
var finished = 0L
|
||||
val patches = steps.mapIndexed { index, step ->
|
||||
val file = File(dir, "$index.pwr")
|
||||
val base = finished
|
||||
val ok = ItchBuilds.download(ItchBuilds.fileUrl(step.buildId, step.patchFile, downloadKeyId), key, file, cancelled) {
|
||||
handle.progress(base + it, total)
|
||||
}
|
||||
if (cancelled.get()) return Outcome.Cancelled
|
||||
if (!ok) return Outcome.Failed("build ${step.buildId}: the patch did not download")
|
||||
finished += step.patchSize
|
||||
file
|
||||
}
|
||||
val last = steps.last()
|
||||
val signature = File(dir, "final.sig")
|
||||
val got = ItchBuilds.download(ItchBuilds.fileUrl(last.buildId, last.signatureFile, downloadKeyId), key, signature, cancelled) {}
|
||||
if (cancelled.get()) return Outcome.Cancelled
|
||||
if (!got) return Outcome.Failed("build ${last.buildId}: the signature did not download")
|
||||
handle.stage(DownloadStage.INSTALL)
|
||||
return apply(app, patches, signature, installed, out, scratch, cancelled)
|
||||
} finally {
|
||||
StoreInstalls.deleteTree(dir)
|
||||
}
|
||||
}
|
||||
|
||||
private fun apply(app: Context, patches: List<File>, signature: File, installed: File, out: File, scratch: File, cancelled: AtomicBoolean): Outcome {
|
||||
var source = installed
|
||||
var intermediate: File? = null
|
||||
try {
|
||||
patches.forEachIndexed { index, patch ->
|
||||
val finalStep = index == patches.lastIndex
|
||||
val target = if (finalStep) out else File(scratch, "patched-$index")
|
||||
ItchStaging.delete(target)
|
||||
target.mkdirs()
|
||||
val staging = File(scratch, "butler-staging-$index").apply { deleteRecursively(); mkdirs() }
|
||||
val args = mutableListOf("$DIR/butler", "apply", "--assume-yes", "--staging-dir", staging.absolutePath, "-d", target.absolutePath)
|
||||
if (finalStep) args += listOf("--signature", signature.absolutePath)
|
||||
args += listOf(patch.absolutePath, source.absolutePath)
|
||||
val binds = listOf(installed, out, scratch).map { it.absolutePath }
|
||||
.filter { path -> listOf(app.filesDir, app.cacheDir).none { path.startsWith(it.absolutePath + "/") } }
|
||||
.distinct().takeIf { it.isNotEmpty() }
|
||||
val tail = ArrayDeque<String>()
|
||||
val code = try {
|
||||
GuestCommand.run(app, args, logName = "itch-butler", extraBinds = binds, fastPath = true, cancelled = cancelled) { line ->
|
||||
if (!line.startsWith("proot ")) {
|
||||
if (tail.size == 4) tail.removeFirst()
|
||||
tail.addLast(line)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
StoreInstalls.deleteTree(staging)
|
||||
}
|
||||
if (cancelled.get()) return Outcome.Cancelled
|
||||
if (code != 0) return Outcome.Failed("butler exited $code: ${tail.joinToString(" | ")}")
|
||||
intermediate?.let { StoreInstalls.deleteTree(it) }
|
||||
intermediate = if (finalStep) null else target
|
||||
source = target
|
||||
}
|
||||
return Outcome.Applied
|
||||
} finally {
|
||||
intermediate?.let { StoreInstalls.deleteTree(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -68,6 +68,7 @@ import com.droiddeck.launcher.frontend.AddedGames
|
||||
import com.droiddeck.launcher.frontend.LogoPosition
|
||||
import com.droiddeck.launcher.frontend.SteamGameArt
|
||||
import com.droiddeck.launcher.frontend.SteamGridDb
|
||||
import com.droiddeck.launcher.frontend.SteamLaunchOptions
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -191,7 +192,7 @@ internal fun SteamGameArtEditor(
|
||||
game: com.droiddeck.launcher.frontend.Library.SteamGame, onClose: () -> Unit, onChanged: () -> Unit,
|
||||
) {
|
||||
val target = remember(game.appId) { ArtTarget.of(game) }
|
||||
ArtOnlyEditor(game.name, target, game, { SteamGameArt.describe(it, game) }, onClose, onChanged)
|
||||
ArtOnlyEditor(game.name, target, game, { SteamGameArt.describe(it, game) }, onClose, onChanged, launchAppId = game.appId)
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -207,18 +208,25 @@ internal fun StoreGameArtEditor(folder: String, name: String, onClose: () -> Uni
|
||||
@Composable
|
||||
private fun ArtOnlyEditor(
|
||||
name: String, target: ArtTarget?, refresh: Any?, describe: (Context) -> List<AddedGameArt.SlotState>,
|
||||
onClose: () -> Unit, onChanged: () -> Unit,
|
||||
onClose: () -> Unit, onChanged: () -> Unit, launchAppId: Int? = null,
|
||||
) {
|
||||
val app = LocalContext.current.applicationContext
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val scope = rememberCoroutineScope()
|
||||
val shown = rememberShown(onClose)
|
||||
val close = { shown.targetState = false }
|
||||
var version by remember { mutableIntStateOf(0) }
|
||||
var arts by remember { mutableStateOf<List<AddedGameArt.SlotState>>(emptyList()) }
|
||||
var artSlot by remember { mutableStateOf<AddedGameArt.Slot?>(null) }
|
||||
var logoOpen by remember { mutableStateOf(false) }
|
||||
var launchOptions by remember { mutableStateOf<String?>(null) }
|
||||
var launchVersion by remember { mutableIntStateOf(0) }
|
||||
var editingLaunch by remember { mutableStateOf<String?>(null) }
|
||||
var launchSaving by remember { mutableStateOf(false) }
|
||||
var launchError by remember { mutableStateOf<Int?>(null) }
|
||||
val position = rememberLogoPosition(target, version)
|
||||
LaunchedEffect(version, refresh) { if (target != null) arts = withContext(Dispatchers.IO) { describe(app) } }
|
||||
LaunchedEffect(launchAppId, launchVersion) { if (launchAppId != null) launchOptions = withContext(Dispatchers.IO) { SteamLaunchOptions.current(app, launchAppId) } }
|
||||
val first = remember { FocusRequester() }
|
||||
LaunchedEffect(Unit) { focusWithinFrames({ false }) { first } }
|
||||
AppDialog(shown, close, "artEditor", wide = false, maxWidth = 460.dp) {
|
||||
@@ -228,10 +236,19 @@ private fun ArtOnlyEditor(
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
modifier = Modifier.fillMaxWidth().heightIn(max = maxHeight).verticalScroll(rememberScrollState()),
|
||||
) {
|
||||
Text(stringResource(R.string.edit_artwork), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 4.dp, top = 2.dp))
|
||||
if (launchAppId != null) {
|
||||
FieldRow(stringResource(R.string.edit_launch_options), focus = first, onClick = { if (!launchSaving) launchOptions?.let { editingLaunch = it } }) {
|
||||
val options = launchOptions
|
||||
if (options == null || launchSaving) Loading() else ValueText(options.ifEmpty { "—" }, muted = options.isEmpty())
|
||||
}
|
||||
val error = launchError
|
||||
if (error != null) Text(stringResource(error), fontSize = 12.sp, color = colors.error, modifier = Modifier.padding(start = 4.dp))
|
||||
else Text(stringResource(R.string.edit_launch_options_steam_hint), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 4.dp))
|
||||
}
|
||||
Text(stringResource(R.string.edit_artwork), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 4.dp, top = if (launchAppId != null) 8.dp else 2.dp))
|
||||
for (slot in AddedGameArt.Slot.values()) key(slot) {
|
||||
val state = arts.firstOrNull { it.slot == slot }
|
||||
FieldRow(slot.label(), focus = if (slot == AddedGameArt.Slot.COVER) first else null, onClick = { if (target != null) artSlot = slot }) {
|
||||
FieldRow(slot.label(), focus = if (slot == AddedGameArt.Slot.COVER && launchAppId == null) first else null, onClick = { if (target != null) artSlot = slot }) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
SlotThumb(slot, state?.file)
|
||||
if (state != null) ValueText(artSourceLabel(state.source), muted = true) else Loading()
|
||||
@@ -241,6 +258,27 @@ private fun ArtOnlyEditor(
|
||||
PickerRow(Icons.Outlined.Tune, stringResource(R.string.art_adjust_logo), logoPositionSummary(position?.value), enabled = target != null && position != null) { logoOpen = true }
|
||||
}
|
||||
}
|
||||
val before = editingLaunch
|
||||
if (before != null && launchAppId != null) TextEntryDialog(stringResource(R.string.edit_launch_options), before, onDismiss = { editingLaunch = null }) { value ->
|
||||
if (launchSaving || value == before.trim()) return@TextEntryDialog
|
||||
launchSaving = true
|
||||
scope.launch {
|
||||
try {
|
||||
val saved = withContext(Dispatchers.IO) { SteamLaunchOptions.set(app, launchAppId, value, before) }
|
||||
launchError = when (saved) {
|
||||
SteamLaunchOptions.Saved.YES -> null
|
||||
SteamLaunchOptions.Saved.DESKTOP -> R.string.edit_launch_options_desktop
|
||||
SteamLaunchOptions.Saved.NO -> R.string.edit_launch_options_not_saved
|
||||
}
|
||||
if (saved == SteamLaunchOptions.Saved.YES) launchOptions = value else {
|
||||
launchOptions = null
|
||||
launchVersion++
|
||||
}
|
||||
} finally {
|
||||
launchSaving = false
|
||||
}
|
||||
}
|
||||
}
|
||||
val chosen = target ?: return
|
||||
artSlot?.let { slot ->
|
||||
ArtChooserDialog(chosen, slot, arts.firstOrNull { it.slot == slot }, onBack = { artSlot = null }, onCloseAll = { artSlot = null; close() }) { version++; onChanged() }
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.media.AudioManager
|
||||
import android.view.ViewGroup
|
||||
import android.webkit.CookieManager
|
||||
import android.webkit.RenderProcessGoneDetail
|
||||
import android.webkit.WebResourceRequest
|
||||
import android.webkit.WebSettings
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalLifecycleOwner
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.session.SteamWebLogin
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import kotlin.coroutines.resume
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
private const val STEAM_CHAT = "https://steamcommunity.com/chat"
|
||||
private const val CHAT_PAGE_SCALE = 0.75f
|
||||
private val STEAM_HOSTS = listOf("steamcommunity.com", "steam-chat.com", "steampowered.com", "steamstatic.com", "steamcontent.com")
|
||||
|
||||
/** Steam chat stays on Steam's own sites; anything else is not opened on the bottom screen. */
|
||||
internal fun steamChatAllows(host: String?): Boolean =
|
||||
host != null && STEAM_HOSTS.any { host == it || host.endsWith(".$it") }
|
||||
|
||||
/** The desktop chat fits the bottom panel better than the phone site; keep WebView's Chrome version. */
|
||||
internal fun desktopUserAgent(webView: String?): String {
|
||||
val chrome = webView?.let { Regex("Chrome/[\\d.]+").find(it)?.value } ?: "Chrome/127.0.6533.103"
|
||||
return "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) $chrome Safari/537.36"
|
||||
}
|
||||
|
||||
/**
|
||||
* At the panel's own scale Steam's desktop chat gets about 600x300 CSS pixels and its friends list collapses, so the
|
||||
* page is laid out [cssWidth] wide and drawn at [scale]. Steam's site header (the rows before .chat_main_flex; its
|
||||
* class name is generated) is hidden to leave the height to the friends list and the chat. The group chat list keeps
|
||||
* a fixed 114 px height and an empty-list note that cover the online friends, so it shrinks to its rows (at most a
|
||||
* quarter of the panel) and the note is hidden.
|
||||
*/
|
||||
internal fun steamChatFitScript(cssWidth: Int, scale: Float): String {
|
||||
val zoom = "%.2f".format(java.util.Locale.US, scale)
|
||||
return "(function(){var m=document.querySelector('meta[name=viewport]');" +
|
||||
"if(!m){m=document.createElement('meta');m.name='viewport';document.head.appendChild(m);}" +
|
||||
"m.content='width=$cssWidth, initial-scale=$zoom';" +
|
||||
"if(!document.getElementById('dd-chat-fit')){var s=document.createElement('style');s.id='dd-chat-fit';" +
|
||||
"s.textContent='$STEAM_CHAT_FIT_CSS';document.head.appendChild(s);}" +
|
||||
"window.dispatchEvent(new Event('resize'));})()"
|
||||
}
|
||||
|
||||
internal const val STEAM_CHAT_FIT_CSS = ".chat_main>:has(~.chat_main_flex){display:none!important}" +
|
||||
".ChatRoomList_Empty{display:none!important}" +
|
||||
".chatRoomListContainer{height:auto!important;max-height:25vh!important}"
|
||||
|
||||
@Composable
|
||||
fun BottomChatPage() {
|
||||
val context = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
var chatOpen by remember { mutableStateOf(true) }
|
||||
// Set when Android ended the page's renderer; the chat opens again once DroidDeck is back in front.
|
||||
var stopped by remember { mutableStateOf(false) }
|
||||
val lifecycle = LocalLifecycleOwner.current.lifecycle
|
||||
DisposableEffect(lifecycle) {
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_RESUME && stopped) {
|
||||
stopped = false
|
||||
chatOpen = true
|
||||
}
|
||||
}
|
||||
lifecycle.addObserver(observer)
|
||||
onDispose { lifecycle.removeObserver(observer) }
|
||||
}
|
||||
// null while the Steam client's sign-in is being copied, then whether there was one.
|
||||
var fromSteam by remember { mutableStateOf<Boolean?>(null) }
|
||||
LaunchedEffect(chatOpen) {
|
||||
if (!chatOpen) {
|
||||
fromSteam = null
|
||||
return@LaunchedEffect
|
||||
}
|
||||
val cookies = withContext(Dispatchers.IO) {
|
||||
SteamWebLogin.read(LinuxRuntime.rootDir(context), SessionState.steamClientArch, File(context.cacheDir, "steam-web-login"))
|
||||
}
|
||||
val manager = CookieManager.getInstance()
|
||||
for (c in cookies) suspendCancellableCoroutine { cont -> manager.setCookie("https://${c.host}", c.header) { cont.resume(Unit) } }
|
||||
manager.flush()
|
||||
fromSteam = cookies.any { it.header.startsWith("steamLoginSecure=") }
|
||||
}
|
||||
Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
if (!chatOpen) {
|
||||
VoiceRow(context)
|
||||
Column(Modifier.weight(1f).fillMaxWidth().padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically)) {
|
||||
if (stopped) Text(stringResource(R.string.bottom_chat_stopped), fontSize = 13.sp, color = colors.onSurfaceVariant, textAlign = TextAlign.Center)
|
||||
Text(stringResource(R.string.bottom_chat_why), fontSize = 15.sp, color = colors.onBackground, textAlign = TextAlign.Center)
|
||||
BottomPillButton(stringResource(R.string.bottom_chat_open), "bottom-chat-open") {
|
||||
stopped = false
|
||||
chatOpen = true
|
||||
}
|
||||
}
|
||||
} else {
|
||||
VoiceRow(context, onClose = { chatOpen = false },
|
||||
note = if (fromSteam == false) stringResource(R.string.bottom_chat_not_signed_in) else "")
|
||||
Box(Modifier.weight(1f).fillMaxWidth().clip(RoundedCornerShape(14.dp))) {
|
||||
if (fromSteam != null) SteamChatView(onStopped = {
|
||||
stopped = true
|
||||
chatOpen = false
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** With [onClose] set the chat is open: the row also carries Close and leaves out the long mic hint. */
|
||||
@Composable
|
||||
private fun VoiceRow(context: Context, onClose: (() -> Unit)? = null, note: String = "") {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val audio = remember { context.getSystemService(Context.AUDIO_SERVICE) as AudioManager }
|
||||
val max = remember { audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC).coerceAtLeast(1) }
|
||||
var volume by remember { mutableIntStateOf(audio.getStreamVolume(AudioManager.STREAM_MUSIC)) }
|
||||
fun step(direction: Int) {
|
||||
// No flags: Android's volume panel would cover the game on the main screen.
|
||||
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, direction, 0)
|
||||
volume = audio.getStreamVolume(AudioManager.STREAM_MUSIC)
|
||||
}
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
if (onClose != null) BottomPillButton(stringResource(R.string.bottom_chat_close), "bottom-chat-close", onClose)
|
||||
if (SessionState.micAvailable) {
|
||||
val on = SessionState.micEnabled
|
||||
BottomPillButton(stringResource(if (on) R.string.bottom_chat_mic_on else R.string.bottom_chat_mic_off), "bottom-chat-mic") {
|
||||
SessionService.setMicEnabled(context, !on)
|
||||
}
|
||||
}
|
||||
val hint = if (onClose == null && !SessionState.micAvailable) stringResource(R.string.bottom_chat_mic_unavailable) else note
|
||||
Text(hint, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 3, modifier = Modifier.weight(1f))
|
||||
Text(stringResource(R.string.bottom_chat_volume, volume * 100 / max), fontSize = 14.sp, color = colors.onSurfaceVariant)
|
||||
BottomPillButton("−", "bottom-chat-volume-down") { step(AudioManager.ADJUST_LOWER) }
|
||||
BottomPillButton("+", "bottom-chat-volume-up") { step(AudioManager.ADJUST_RAISE) }
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
@Composable
|
||||
private fun SteamChatView(onStopped: () -> Unit) {
|
||||
AndroidView(factory = { ctx ->
|
||||
WebView(ctx).apply {
|
||||
// AndroidView's default WRAP_CONTENT height gives the page a 0 px tall viewport, which collapses Steam
|
||||
// chat's full-height layout (measured on the Retroid Pocket Duo: html and every container 0 px).
|
||||
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
|
||||
setBackgroundColor(0xFF0A0B0D.toInt())
|
||||
settings.javaScriptEnabled = true
|
||||
settings.domStorageEnabled = true
|
||||
settings.allowFileAccess = false
|
||||
settings.allowContentAccess = false
|
||||
settings.useWideViewPort = true
|
||||
settings.loadWithOverviewMode = true
|
||||
settings.userAgentString = desktopUserAgent(runCatching { WebSettings.getDefaultUserAgent(ctx) }.getOrNull())
|
||||
CookieManager.getInstance().setAcceptCookie(true)
|
||||
webViewClient = object : WebViewClient() {
|
||||
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean =
|
||||
!steamChatAllows(request.url.host)
|
||||
|
||||
override fun onPageFinished(view: WebView, url: String) {
|
||||
val scale = view.resources.displayMetrics.density * CHAT_PAGE_SCALE
|
||||
if (view.width > 0) view.evaluateJavascript(steamChatFitScript((view.width / scale).roundToInt(), CHAT_PAGE_SCALE), null)
|
||||
}
|
||||
|
||||
// Android ends the page's renderer once DroidDeck goes to picture-in-picture ("isolated not needed"
|
||||
// on the Retroid Pocket Duo); the page cannot come back, so the chat closes and reopens on resume.
|
||||
override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean {
|
||||
onStopped()
|
||||
return true
|
||||
}
|
||||
}
|
||||
loadUrl(STEAM_CHAT)
|
||||
}
|
||||
}, modifier = Modifier.fillMaxSize(), onRelease = { view ->
|
||||
CookieManager.getInstance().flush()
|
||||
view.destroy()
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Close
|
||||
import androidx.compose.material.icons.outlined.Menu
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
/** A page the bottom screen can show while the game runs on the main screen. */
|
||||
class BottomPage(
|
||||
val id: String,
|
||||
@StringRes val label: Int,
|
||||
val icon: ImageVector,
|
||||
val content: @Composable () -> Unit,
|
||||
)
|
||||
|
||||
internal fun pickBottomPage(remembered: String?, ids: List<String>): String? =
|
||||
ids.firstOrNull { it == remembered } ?: ids.firstOrNull { it == DEFAULT_PAGE } ?: ids.firstOrNull()
|
||||
|
||||
/** The page a game start switches to; not saved, so the page the user picked still opens next time. */
|
||||
internal fun pageForGameStart(ids: List<String>): String? = GAME_PAGE.takeIf { it in ids }
|
||||
|
||||
private const val DEFAULT_PAGE = "chat"
|
||||
private const val GAME_PAGE = "telemetry"
|
||||
|
||||
/** Tabs show their names while every tab still fits at [TAB_WIDTH]; otherwise only the open tab keeps its name. */
|
||||
internal fun bottomTabsWithLabels(widthDp: Float, tabs: Int): Boolean = tabs * TAB_WIDTH + 2 * BAR_BUTTON <= widthDp
|
||||
|
||||
private const val TAB_WIDTH = 132f
|
||||
private const val BAR_BUTTON = 56f
|
||||
|
||||
@Composable
|
||||
fun BottomDashboard(
|
||||
pages: List<BottomPage>,
|
||||
remembered: String?,
|
||||
onPage: (String) -> Unit,
|
||||
onClose: () -> Unit,
|
||||
onMenu: (() -> Unit)?,
|
||||
gameStarts: Int = 0,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
var current by remember { mutableStateOf(pickBottomPage(remembered, pages.map { it.id })) }
|
||||
val startsWhenOpened = remember { gameStarts }
|
||||
LaunchedEffect(gameStarts) {
|
||||
if (gameStarts != startsWhenOpened) pageForGameStart(pages.map { it.id })?.let { current = it }
|
||||
}
|
||||
val page = pages.firstOrNull { it.id == current } ?: pages.firstOrNull()
|
||||
BoxWithConstraints(Modifier.fillMaxSize().background(colors.background)) {
|
||||
val labels = bottomTabsWithLabels(maxWidth.value, pages.size)
|
||||
Column(Modifier.fillMaxSize().padding(horizontal = 12.dp, vertical = 10.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Row(Modifier.fillMaxWidth().height(48.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
BarButton(Icons.Outlined.Close, stringResource(R.string.deck_close), "bottom-close", onClose)
|
||||
Row(Modifier.weight(1f).horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
pages.forEach { p ->
|
||||
PageTab(p, p.id == page?.id, labels) {
|
||||
current = p.id
|
||||
onPage(p.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (onMenu != null) BarButton(Icons.Outlined.Menu, stringResource(R.string.touch_droiddeck_menu), "bottom-menu", onMenu)
|
||||
}
|
||||
Box(Modifier.weight(1f).fillMaxWidth()) {
|
||||
if (page != null) page.content()
|
||||
else Text(stringResource(R.string.bottom_dashboard_empty), fontSize = 15.sp, color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.align(Alignment.Center))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun BarButton(icon: ImageVector, label: String, tag: String, onClick: () -> Unit) {
|
||||
val pal = LocalPalette.current
|
||||
Box(
|
||||
Modifier.size(44.dp).clip(RoundedCornerShape(22.dp)).background(pal.surface).border(1.dp, pal.line, RoundedCornerShape(22.dp))
|
||||
.semantics { contentDescription = label }.clickable(role = Role.Button, onClick = onClick).testTag(tag),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(icon, contentDescription = null, tint = MaterialTheme.colorScheme.onBackground, modifier = Modifier.size(22.dp))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PageTab(page: BottomPage, selected: Boolean, label: Boolean, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val shape = RoundedCornerShape(20.dp)
|
||||
val name = stringResource(page.label)
|
||||
Row(
|
||||
Modifier.height(44.dp).clip(shape)
|
||||
.background(if (selected) pal.signal else Color.Transparent)
|
||||
.border(1.dp, if (selected) pal.signal else pal.line, shape)
|
||||
.semantics { contentDescription = name }
|
||||
.clickable(role = Role.Tab, onClick = onClick).testTag("bottom-page-${page.id}")
|
||||
.padding(horizontal = 14.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
val tint = if (selected) colors.background else colors.onBackground
|
||||
Icon(page.icon, contentDescription = null, tint = tint, modifier = Modifier.size(20.dp))
|
||||
if (label || selected) Text(name, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = tint, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.session.SteamDownload
|
||||
import com.droiddeck.launcher.session.SteamDownloads
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.download.DownloadState
|
||||
import com.droiddeck.launcher.stores.formatBytes
|
||||
import com.droiddeck.launcher.stores.formatSpeed
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/** Bytes per second between two reads of the same download; 0 when it did not move or restarted. */
|
||||
internal fun downloadRate(previousDone: Long, previousAt: Long, done: Long, at: Long): Long =
|
||||
if (previousDone < 0L || done <= previousDone || at <= previousAt) 0L else (done - previousDone) * 1000L / (at - previousAt)
|
||||
|
||||
private const val STEAM_POLL_MS = 2_000L
|
||||
|
||||
private class SteamRow(val download: SteamDownload, val rate: Long)
|
||||
|
||||
@Composable
|
||||
fun BottomDownloadsPage() {
|
||||
val context = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
var steam by remember { mutableStateOf<List<SteamRow>>(emptyList()) }
|
||||
LaunchedEffect(Unit) {
|
||||
var last = emptyMap<String, Pair<Long, Long>>()
|
||||
while (true) {
|
||||
val now = System.currentTimeMillis()
|
||||
val read = withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
SteamDownloads.read(LinuxRuntime.rootDir(context), SessionState.steamLibraryMounts, SessionState.steamClientArch)
|
||||
}.getOrDefault(emptyList())
|
||||
}
|
||||
steam = read.map { d ->
|
||||
val before = last[d.appId]
|
||||
SteamRow(d, if (before == null) 0L else downloadRate(before.first, before.second, d.done, now))
|
||||
}
|
||||
last = read.associate { it.appId to (it.done to now) }
|
||||
delay(STEAM_POLL_MS)
|
||||
}
|
||||
}
|
||||
val store = StoresState.downloads.filter { it.isActive }
|
||||
if (steam.isEmpty() && store.isEmpty()) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(stringResource(R.string.bottom_downloads_none), fontSize = 15.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
return
|
||||
}
|
||||
LazyColumn(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
items(steam, key = { "steam:${it.download.appId}:${it.download.shader}" }) { row ->
|
||||
val d = row.download
|
||||
val detail = when {
|
||||
d.shader -> stringResource(R.string.bottom_downloads_shader)
|
||||
d.paused -> stringResource(R.string.bottom_downloads_paused)
|
||||
d.total <= 0L -> stringResource(R.string.bottom_downloads_queued)
|
||||
else -> listOf("${formatBytes(d.done)} / ${formatBytes(d.total)}", formatSpeed(row.rate)).filter { it.isNotEmpty() }.joinToString(" · ")
|
||||
}
|
||||
BottomDownloadRow(d.name, stringResource(R.string.bottom_downloads_steam), detail,
|
||||
if (d.total > 0L) (d.done.toFloat() / d.total).coerceIn(0f, 1f) else null)
|
||||
}
|
||||
items(store, key = { "store:${it.key}" }) { entry ->
|
||||
val e = StoresState.download(entry.key) ?: entry
|
||||
val detail = when (e.state) {
|
||||
DownloadState.PAUSED -> stringResource(R.string.bottom_downloads_paused)
|
||||
DownloadState.QUEUED -> stringResource(R.string.bottom_downloads_queued)
|
||||
else -> listOf(
|
||||
if (e.bytesTotal > 0L) "${formatBytes(e.bytesDone)} / ${formatBytes(e.bytesTotal)}" else "",
|
||||
formatSpeed(e.speedBps),
|
||||
).filter { it.isNotEmpty() }.joinToString(" · ")
|
||||
}
|
||||
BottomDownloadRow(e.name, e.store.label, detail, e.stageFraction.takeIf { it >= 0f })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun BottomDownloadRow(name: String, source: String, detail: String, fraction: Float?) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Column(
|
||||
Modifier.fillMaxWidth().clip(RoundedCornerShape(14.dp)).background(pal.surface).padding(horizontal = 14.dp, vertical = 10.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(name, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
|
||||
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
Text(source, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, modifier = Modifier.padding(start = 8.dp))
|
||||
}
|
||||
if (fraction != null) LinearProgressIndicator(progress = { fraction }, modifier = Modifier.fillMaxWidth(), color = pal.signal)
|
||||
else LinearProgressIndicator(modifier = Modifier.fillMaxWidth(), color = pal.signal)
|
||||
if (detail.isNotEmpty()) Text(detail, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.Intent
|
||||
import android.provider.Settings
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.session.BottomNotifications
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
/** DroidDeck's own switch on Android 11 and later; the list of all apps before that. */
|
||||
internal fun notificationAccessIntent(context: android.content.Context): Intent =
|
||||
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
|
||||
Intent(Settings.ACTION_NOTIFICATION_LISTENER_DETAIL_SETTINGS).putExtra(
|
||||
Settings.EXTRA_NOTIFICATION_LISTENER_COMPONENT_NAME,
|
||||
android.content.ComponentName(context, com.droiddeck.launcher.session.BottomNotificationListener::class.java).flattenToString(),
|
||||
)
|
||||
} else Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)
|
||||
|
||||
@Composable
|
||||
fun BottomNotificationsPage(openSettings: ((Intent, () -> Boolean) -> Unit)?) {
|
||||
val context = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
var granted by remember { mutableStateOf(BottomNotifications.granted(context)) }
|
||||
LaunchedEffect(Unit) {
|
||||
while (true) {
|
||||
granted = BottomNotifications.granted(context)
|
||||
delay(2_000L)
|
||||
}
|
||||
}
|
||||
if (!granted) {
|
||||
Column(Modifier.fillMaxSize().padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically)) {
|
||||
Text(stringResource(R.string.bottom_notifications_why), fontSize = 15.sp, color = colors.onBackground, textAlign = TextAlign.Center)
|
||||
BottomPillButton(stringResource(R.string.bottom_notifications_allow), "bottom-notifications-allow") {
|
||||
val intent = notificationAccessIntent(context)
|
||||
if (openSettings != null) openSettings(intent) { BottomNotifications.granted(context) }
|
||||
else runCatching { context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
val shown = BottomNotifications.items
|
||||
if (shown.isEmpty()) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(stringResource(R.string.bottom_notifications_none), fontSize = 15.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
return
|
||||
}
|
||||
val timeFormat = remember { android.text.format.DateFormat.getTimeFormat(context) }
|
||||
Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(stringResource(R.string.bottom_notifications_count, shown.size), fontSize = 13.sp, color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.weight(1f))
|
||||
BottomPillButton(stringResource(R.string.bottom_notifications_clear), "bottom-notifications-clear") { BottomNotifications.clear() }
|
||||
}
|
||||
LazyColumn(Modifier.weight(1f).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
items(shown.toList(), key = { it.key }) { n ->
|
||||
Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(14.dp)).background(pal.surface).padding(horizontal = 14.dp, vertical = 10.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(n.app, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = pal.signal, maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
Text(timeFormat.format(java.util.Date(n.postedAt)), fontSize = 12.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
if (n.title.isNotBlank()) Text(n.title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
|
||||
maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
if (n.text.isNotBlank()) Text(n.text, fontSize = 14.sp, color = colors.onBackground, maxLines = 4, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun BottomPillButton(label: String, tag: String, onClick: () -> Unit) {
|
||||
val pal = LocalPalette.current
|
||||
Box(
|
||||
Modifier.height(40.dp).clip(RoundedCornerShape(20.dp)).background(pal.signal.copy(alpha = 0.16f))
|
||||
.clickable(role = Role.Button, onClick = onClick).testTag(tag).padding(horizontal = 16.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = pal.signal, maxLines = 1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Download
|
||||
import androidx.compose.material.icons.outlined.Forum
|
||||
import androidx.compose.material.icons.outlined.Speed
|
||||
import androidx.compose.material.icons.outlined.Notifications
|
||||
import androidx.compose.material.icons.outlined.PhotoLibrary
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
/** What the bottom-screen pages can ask the running session to do. */
|
||||
class BottomPageActions(
|
||||
val takeScreenshot: ((onDone: (Boolean) -> Unit) -> Unit)? = null,
|
||||
val fps: () -> Float? = { null },
|
||||
/** Opens an Android settings page on the bottom screen; the dashboard comes back once [done] is true. */
|
||||
val openSettings: ((intent: android.content.Intent, done: () -> Boolean) -> Unit)? = null,
|
||||
/** The focused game's Steam app id as text (or another key for non-Steam programs); null in the Steam menus. */
|
||||
val runningGame: () -> String? = { null },
|
||||
)
|
||||
|
||||
/** The pages the bottom-screen dashboard offers during a session, in tab order. */
|
||||
fun sessionBottomPages(actions: BottomPageActions): List<BottomPage> = listOf(
|
||||
BottomPage("telemetry", R.string.bottom_page_telemetry, Icons.Outlined.Speed) { BottomTelemetryPage(actions.fps, actions.runningGame) },
|
||||
BottomPage("downloads", R.string.bottom_page_downloads, Icons.Outlined.Download) { BottomDownloadsPage() },
|
||||
BottomPage("notifications", R.string.bottom_page_notifications, Icons.Outlined.Notifications) { BottomNotificationsPage(actions.openSettings) },
|
||||
BottomPage("screenshots", R.string.bottom_page_screenshots, Icons.Outlined.PhotoLibrary) { BottomScreenshotsPage(actions.takeScreenshot) },
|
||||
BottomPage("chat", R.string.bottom_page_chat, Icons.Outlined.Forum) { BottomChatPage() },
|
||||
)
|
||||
@@ -0,0 +1,110 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.grid.GridCells
|
||||
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
|
||||
import androidx.compose.foundation.lazy.grid.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import coil.compose.AsyncImage
|
||||
import coil.request.ImageRequest
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.BottomScreenshots
|
||||
import com.droiddeck.launcher.session.BottomShot
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
private const val SHOTS_POLL_MS = 5_000L
|
||||
|
||||
@Composable
|
||||
fun BottomScreenshotsPage(takeScreenshot: ((onDone: (Boolean) -> Unit) -> Unit)?) {
|
||||
val context = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
var shots by remember { mutableStateOf<List<BottomShot>>(emptyList()) }
|
||||
var refresh by remember { mutableIntStateOf(0) }
|
||||
var open by remember { mutableStateOf<BottomShot?>(null) }
|
||||
var status by remember { mutableStateOf<Int?>(null) }
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(refresh) {
|
||||
while (true) {
|
||||
shots = withContext(Dispatchers.IO) { BottomScreenshots.list(context, LinuxRuntime.rootDir(context)) }
|
||||
delay(SHOTS_POLL_MS)
|
||||
}
|
||||
}
|
||||
LaunchedEffect(status) {
|
||||
if (status != null) {
|
||||
delay(3_000L)
|
||||
status = null
|
||||
}
|
||||
}
|
||||
open?.let { shot ->
|
||||
Box(Modifier.fillMaxSize().clip(RoundedCornerShape(14.dp)).background(androidx.compose.ui.graphics.Color.Black)
|
||||
.clickable(role = Role.Button) { open = null }.testTag("bottom-shot-full")) {
|
||||
AsyncImage(ImageRequest.Builder(context).data(shot.model).build(), contentDescription = null,
|
||||
contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize())
|
||||
}
|
||||
return
|
||||
}
|
||||
Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(status?.let { stringResource(it) } ?: stringResource(R.string.bottom_shots_where), fontSize = 13.sp,
|
||||
color = colors.onSurfaceVariant, maxLines = 2, modifier = Modifier.weight(1f).padding(end = 8.dp))
|
||||
if (takeScreenshot != null) BottomPillButton(stringResource(R.string.bottom_shots_take), "bottom-shots-take") {
|
||||
if (!busy) {
|
||||
busy = true
|
||||
takeScreenshot { ok ->
|
||||
busy = false
|
||||
status = if (ok) R.string.bottom_shots_saved else R.string.bottom_shots_failed
|
||||
refresh++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (shots.isEmpty()) {
|
||||
Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
|
||||
Text(stringResource(R.string.bottom_shots_none), fontSize = 15.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
} else {
|
||||
LazyVerticalGrid(GridCells.Adaptive(150.dp), Modifier.weight(1f).fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
items(shots, key = { it.model.toString() }) { shot ->
|
||||
AsyncImage(
|
||||
ImageRequest.Builder(context).data(shot.model).size(480, 270).build(), contentDescription = null,
|
||||
contentScale = ContentScale.Crop,
|
||||
modifier = Modifier.fillMaxWidth().aspectRatio(16f / 9f).clip(RoundedCornerShape(10.dp))
|
||||
.background(LocalPalette.current.surface).clickable(role = Role.Button) { open = shot },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.res.Resources
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.selection.toggleable
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.SwitchDefaults
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.hud.HudMetrics
|
||||
import com.droiddeck.launcher.hud.MangoReadings
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.GameStatusFiles
|
||||
import com.droiddeck.launcher.session.GameTelemetry
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.session.SpeedUnit
|
||||
import com.droiddeck.launcher.session.StatsDash
|
||||
import com.droiddeck.launcher.session.StatsStrip
|
||||
import com.droiddeck.launcher.session.Telemetry
|
||||
import com.droiddeck.launcher.session.TelemetryOutput
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.net.DatagramPacket
|
||||
import java.net.DatagramSocket
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.InetSocketAddress
|
||||
import java.net.SocketTimeoutException
|
||||
import java.net.URL
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
private const val DRAW_MS = 66L
|
||||
private const val TELEMETRY_STALE_MS = 3_000L
|
||||
private const val METRICS_MS = 1_000L
|
||||
private const val THUNDER_MS = 500L
|
||||
private const val THUNDER_RETRY_MS = 3_000L
|
||||
private const val ELITE_MS = 1_000L
|
||||
private const val ELITE_SEARCH_MS = 10_000L
|
||||
private const val OUTPUT_SCAN_MS = 3_000L
|
||||
/** Top strip history: one reading a second for 30 s. */
|
||||
private const val PERF_N = 30
|
||||
|
||||
/** What arrives on one telemetry port; written only by that port's listener. */
|
||||
private class PortTraffic {
|
||||
@Volatile var packets = 0L
|
||||
@Volatile var length = 0
|
||||
@Volatile var readable = true
|
||||
}
|
||||
|
||||
private data class UnknownTraffic(val port: Int, val packets: Long, val length: Int)
|
||||
|
||||
@Composable
|
||||
fun BottomTelemetryPage(fps: () -> Float?, runningGame: () -> String? = { null }) {
|
||||
val context = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val scope = rememberCoroutineScope()
|
||||
var outputs by remember { mutableStateOf<List<TelemetryOutput.Game>>(emptyList()) }
|
||||
var menuGames by remember { mutableStateOf<List<TelemetryOutput.MenuGame>>(emptyList()) }
|
||||
var running by remember { mutableStateOf<String?>(null) }
|
||||
var outputFailed by remember { mutableStateOf<String?>(null) }
|
||||
var rescan by remember { mutableIntStateOf(0) }
|
||||
var auto by remember { mutableStateOf(SessionPrefs.telemetryAuto(context)) }
|
||||
val latest = remember { AtomicReference<Pair<Long, Telemetry>?>(null) }
|
||||
var race by remember { mutableStateOf<Telemetry?>(null) }
|
||||
var fpsNow by remember { mutableStateOf<Float?>(null) }
|
||||
var device by remember { mutableStateOf<HudMetrics.Snapshot?>(null) }
|
||||
var thunder by remember { mutableStateOf<List<Pair<String, String>>>(emptyList()) }
|
||||
var elite by remember { mutableStateOf<GameStatusFiles.Elite?>(null) }
|
||||
var busyPorts by remember { mutableStateOf<Set<Int>>(emptySet()) }
|
||||
val traffic = remember { GameTelemetry.PORTS.associateWith { PortTraffic() } }
|
||||
var unknown by remember { mutableStateOf<List<UnknownTraffic>>(emptyList()) }
|
||||
var strip by remember { mutableStateOf(StatsStrip.from(SessionPrefs.statsStrip(context))) }
|
||||
var dash by remember { mutableStateOf(StatsDash.from(SessionPrefs.statsDash(context))) }
|
||||
var speedUnit by remember { mutableStateOf(SpeedUnit.from(SessionPrefs.statsSpeedUnit(context))) }
|
||||
val shownUnit = speedUnit.resolve(Resources.getSystem().configuration.locales[0].country)
|
||||
val fpsHistory = remember { History(PERF_N) }
|
||||
val cpuHistory = remember { History(PERF_N) }
|
||||
val gpuHistory = remember { History(PERF_N) }
|
||||
val wattsHistory = remember { History(PERF_N) }
|
||||
val throttleTrace = remember { History(TRACE_N) }
|
||||
val brakeTrace = remember { History(TRACE_N) }
|
||||
val speedTrace = remember { History(TRACE_N) }
|
||||
var perfTick by remember { mutableIntStateOf(0) }
|
||||
var traceTick by remember { mutableIntStateOf(0) }
|
||||
var clock by remember { mutableStateOf("") }
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
for (port in GameTelemetry.PORTS) launch(Dispatchers.IO) {
|
||||
val socket = runCatching {
|
||||
DatagramSocket(null).apply {
|
||||
reuseAddress = true
|
||||
soTimeout = 500
|
||||
bind(InetSocketAddress(GameTelemetry.LISTEN_ADDRESS, port))
|
||||
}
|
||||
}.getOrNull()
|
||||
if (socket == null) {
|
||||
withContext(Dispatchers.Main) { busyPorts = busyPorts + port }
|
||||
return@launch
|
||||
}
|
||||
val seen = traffic.getValue(port)
|
||||
socket.use {
|
||||
val data = ByteArray(2048)
|
||||
val packet = DatagramPacket(data, data.size)
|
||||
while (isActive) {
|
||||
try {
|
||||
packet.length = data.size
|
||||
it.receive(packet)
|
||||
val t = GameTelemetry.parse(port, data, packet.length)
|
||||
seen.packets++
|
||||
seen.length = packet.length
|
||||
seen.readable = t != null
|
||||
if (t != null) latest.set(System.currentTimeMillis() to t)
|
||||
} catch (_: SocketTimeoutException) {
|
||||
} catch (_: java.io.IOException) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
while (isActive) {
|
||||
val reading = latest.get()
|
||||
race = reading?.takeIf { System.currentTimeMillis() - it.first < TELEMETRY_STALE_MS }?.second
|
||||
race?.let { r ->
|
||||
throttleTrace.add(r.throttle ?: 0f)
|
||||
brakeTrace.add(r.brake ?: 0f)
|
||||
speedTrace.add(r.speedKmh ?: 0f)
|
||||
traceTick++
|
||||
}
|
||||
fpsNow = fps()
|
||||
unknown = traffic.filter { (_, t) -> t.packets > 0 && !t.readable }.map { (port, t) -> UnknownTraffic(port, t.packets, t.length) }
|
||||
delay(DRAW_MS)
|
||||
}
|
||||
}
|
||||
LaunchedEffect(Unit) {
|
||||
val metrics = HudMetrics(context).apply { setMangoReadings(MangoReadings(File(context.filesDir, "session"), LinuxRuntime.rootDir(context))) }
|
||||
while (isActive) {
|
||||
device = withContext(Dispatchers.IO) { runCatching { metrics.snapshot() }.getOrNull() }
|
||||
fps()?.takeIf { it > 0f }?.let { fpsHistory.add(it) }
|
||||
device?.let { s ->
|
||||
s.cpuPercent?.let { cpuHistory.add(it.toFloat()) }
|
||||
s.gpuPercent?.let { gpuHistory.add(it.toFloat()) }
|
||||
s.battery?.watts?.takeIf { it > 0f }?.let { wattsHistory.add(it) }
|
||||
}
|
||||
clock = java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT).format(java.util.Date())
|
||||
perfTick++
|
||||
delay(METRICS_MS)
|
||||
}
|
||||
}
|
||||
LaunchedEffect(Unit) {
|
||||
while (isActive) {
|
||||
val rows = withContext(Dispatchers.IO) { runCatching { GameStatusFiles.warThunder(httpGet(GameStatusFiles.WAR_THUNDER_STATE)) }.getOrNull() }
|
||||
thunder = rows.orEmpty()
|
||||
delay(if (rows == null) THUNDER_RETRY_MS else THUNDER_MS)
|
||||
}
|
||||
}
|
||||
LaunchedEffect(Unit) {
|
||||
var file: File? = null
|
||||
var searchedAt = 0L
|
||||
while (isActive) {
|
||||
val now = System.currentTimeMillis()
|
||||
if (file == null && now - searchedAt > ELITE_SEARCH_MS) {
|
||||
searchedAt = now
|
||||
file = withContext(Dispatchers.IO) {
|
||||
runCatching { GameStatusFiles.eliteStatusFile(LinuxRuntime.rootDir(context), SessionState.steamLibraryMounts) }.getOrNull()
|
||||
}
|
||||
}
|
||||
val f = file
|
||||
// Status.json changes while Elite runs; one older than a minute belongs to an earlier session.
|
||||
elite = if (f != null && now - f.lastModified() < 60_000L) {
|
||||
withContext(Dispatchers.IO) { runCatching { GameStatusFiles.elite(f.readText()) }.getOrNull() }
|
||||
} else null
|
||||
delay(ELITE_MS)
|
||||
}
|
||||
}
|
||||
LaunchedEffect(Unit) {
|
||||
menuGames = withContext(Dispatchers.IO) {
|
||||
runCatching { Library.steamGames(context).mapNotNull { TelemetryOutput.MENU_GAMES[it.appId] }.distinct() }.getOrDefault(emptyList())
|
||||
}
|
||||
}
|
||||
LaunchedEffect(rescan) {
|
||||
while (isActive) {
|
||||
outputs = withContext(Dispatchers.IO) { runCatching { TelemetryOutput.scan(Library.compatdataDirs(context)) }.getOrDefault(emptyList()) }
|
||||
running = runningGame()
|
||||
delay(OUTPUT_SCAN_MS)
|
||||
}
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
perfTick.let {
|
||||
StatsStripView(strip, StripData(fpsNow, device, fpsHistory.snapshot(), cpuHistory.snapshot(), gpuHistory.snapshot(), wattsHistory.snapshot(), clock)) {
|
||||
strip = strip.next()
|
||||
SessionPrefs.setStatsStrip(context, strip.id)
|
||||
}
|
||||
}
|
||||
race?.let { r ->
|
||||
val shown = dash.resolve(r.source)
|
||||
traceTick.let {
|
||||
RaceDashView(shown, r, TraceData(throttleTrace.snapshot(), brakeTrace.snapshot(), speedTrace.snapshot()), shownUnit) {
|
||||
dash = StatsDash.tapped(shown)
|
||||
SessionPrefs.setStatsDash(context, dash.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (thunder.isNotEmpty()) {
|
||||
if (FlightLabels.drawable(thunder)) FlightDash(thunder)
|
||||
else TelemetryCard(stringResource(R.string.bottom_telemetry_war_thunder)) { ValueGrid(thunder.take(GameStatusFiles.WAR_THUNDER_ROWS)) }
|
||||
}
|
||||
elite?.let { e ->
|
||||
if (e.pips != null || e.fuelMain != null) ShipDash(e)
|
||||
else TelemetryCard(stringResource(R.string.bottom_telemetry_elite)) {
|
||||
ValueGrid(listOfNotNull(
|
||||
e.fuelMain?.let { stringResource(R.string.bottom_telemetry_fuel) to "%.1f t".format(it) },
|
||||
e.cargo?.let { stringResource(R.string.bottom_telemetry_cargo) to "%.0f t".format(it) },
|
||||
e.pips?.takeIf { it.size == 3 }?.let { p ->
|
||||
stringResource(R.string.bottom_telemetry_pips) to p.joinToString(" · ") { "%.1f".format(it / 2f) }
|
||||
},
|
||||
e.legal?.let { stringResource(R.string.bottom_telemetry_legal) to it },
|
||||
e.balance?.let { stringResource(R.string.bottom_telemetry_balance) to "%,d CR".format(it) },
|
||||
))
|
||||
}
|
||||
}
|
||||
if (race == null && thunder.isEmpty() && elite == null) {
|
||||
Text(stringResource(R.string.bottom_telemetry_help),
|
||||
fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 4.dp))
|
||||
}
|
||||
if (outputs.isNotEmpty() || menuGames.isNotEmpty()) TelemetryCard(stringResource(R.string.bottom_telemetry_send_title)) {
|
||||
if (outputs.isNotEmpty()) SwitchRow(stringResource(R.string.bottom_telemetry_send_auto), stringResource(R.string.bottom_telemetry_send_auto_hint), auto, true) { want ->
|
||||
scope.launch {
|
||||
withContext(Dispatchers.IO) {
|
||||
SessionPrefs.setTelemetryAuto(context, want)
|
||||
if (want) TelemetryOutput.applyAutomatic(context, running)
|
||||
else TelemetryOutput.restoreTargets(outputs, running).forEach { TelemetryOutput.set(it, false) }
|
||||
}
|
||||
auto = want
|
||||
rescan++
|
||||
}
|
||||
}
|
||||
for (game in outputs) {
|
||||
val locked = TelemetryOutput.isRunning(game.prefixId, running)
|
||||
val hint = if (locked) stringResource(R.string.bottom_telemetry_send_close, game.name) else null
|
||||
SwitchRow(game.name, hint, game.on, !locked) { want ->
|
||||
scope.launch {
|
||||
val ok = withContext(Dispatchers.IO) {
|
||||
val key = TelemetryOutput.key(game)
|
||||
val off = SessionPrefs.telemetryOff(context)
|
||||
SessionPrefs.setTelemetryOff(context, if (want) off - key else off + key)
|
||||
TelemetryOutput.set(game, want)
|
||||
}
|
||||
outputFailed = if (ok) null else game.name
|
||||
rescan++
|
||||
}
|
||||
}
|
||||
}
|
||||
for (game in menuGames) {
|
||||
Text(stringResource(R.string.bottom_telemetry_send_menu, game.name, game.setting, game.port), fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
if (outputs.isNotEmpty()) Text(stringResource(R.string.bottom_telemetry_send_note), fontSize = 12.sp, color = colors.onSurfaceVariant)
|
||||
outputFailed?.let { Text(stringResource(R.string.bottom_telemetry_send_failed, it), fontSize = 12.sp, color = colors.error) }
|
||||
}
|
||||
for (u in unknown) {
|
||||
Text(stringResource(R.string.bottom_telemetry_unknown_format, u.port, u.packets, u.length), fontSize = 13.sp,
|
||||
color = colors.error, modifier = Modifier.padding(horizontal = 4.dp))
|
||||
}
|
||||
if (busyPorts.isNotEmpty()) {
|
||||
Text(stringResource(R.string.bottom_telemetry_port_busy, busyPorts.sorted().joinToString()), fontSize = 13.sp,
|
||||
color = colors.error, modifier = Modifier.padding(horizontal = 4.dp))
|
||||
}
|
||||
ChoiceRow(stringResource(R.string.stats_speed_units),
|
||||
if (speedUnit == SpeedUnit.AUTO) stringResource(R.string.stats_speed_units_auto, shownUnit.label) else speedUnit.label) {
|
||||
speedUnit = speedUnit.next()
|
||||
SessionPrefs.setStatsSpeedUnit(context, speedUnit.id)
|
||||
}
|
||||
Text(stringResource(R.string.stats_tap_hint), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 4.dp))
|
||||
}
|
||||
}
|
||||
|
||||
private fun httpGet(url: String): String {
|
||||
val c = URL(url).openConnection() as HttpURLConnection
|
||||
c.connectTimeout = 300
|
||||
c.readTimeout = 500
|
||||
return try {
|
||||
c.inputStream.bufferedReader().use { it.readText() }
|
||||
} finally {
|
||||
c.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Composable
|
||||
private fun ChoiceRow(title: String, value: String, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Row(Modifier.fillMaxWidth().clickable(role = Role.Button, onClick = onClick).padding(horizontal = 4.dp, vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(title, fontSize = 15.sp, color = colors.onBackground, modifier = Modifier.weight(1f))
|
||||
Text(value, fontSize = 15.sp, fontWeight = FontWeight.Bold, color = LocalPalette.current.primary)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SwitchRow(title: String, hint: String?, checked: Boolean, enabled: Boolean, onChange: (Boolean) -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Row(
|
||||
Modifier.fillMaxWidth().toggleable(checked, enabled = enabled, role = Role.Switch, onValueChange = onChange).padding(vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f).padding(end = 12.dp)) {
|
||||
Text(title, fontSize = 15.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
if (hint != null) Text(hint, fontSize = 12.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
val pal = LocalPalette.current
|
||||
Switch(checked, null, enabled = enabled, colors = SwitchDefaults.colors(
|
||||
disabledCheckedTrackColor = pal.primary.copy(alpha = 0.45f),
|
||||
disabledCheckedThumbColor = colors.background,
|
||||
disabledCheckedBorderColor = pal.primary.copy(alpha = 0.45f),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Composable
|
||||
private fun TelemetryCard(title: String, content: @Composable () -> Unit) {
|
||||
val pal = LocalPalette.current
|
||||
Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(14.dp)).background(pal.surface).padding(12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(title, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = pal.signal)
|
||||
content()
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ValueGrid(rows: List<Pair<String, String>>) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
rows.chunked(2).forEach { pair ->
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
pair.forEach { (k, v) ->
|
||||
Row(Modifier.weight(1f)) {
|
||||
Text(k, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
Text(v, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1)
|
||||
}
|
||||
}
|
||||
if (pair.size == 1) Box(Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun lapTime(seconds: Float): String {
|
||||
val total = kotlin.math.round(seconds * 1000.0).toLong()
|
||||
return "%d:%02d.%03d".format(total / 60_000, total / 1000 % 60, total % 1000)
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Typeface
|
||||
import android.os.Bundle
|
||||
import android.text.TextPaint
|
||||
import android.text.TextUtils
|
||||
import android.util.TypedValue
|
||||
import android.view.Gravity
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.FrameLayout
|
||||
import com.droiddeck.launcher.BuildConfig
|
||||
import com.droiddeck.launcher.QuestXrActivity
|
||||
|
||||
/** A faint bottom-right tag on every screen of a test or local build; stable and preview builds draw none. */
|
||||
object BuildWatermark {
|
||||
private const val TITLE_LIMIT = 80
|
||||
|
||||
fun lines(
|
||||
pr: Int = BuildConfig.PR_NUMBER,
|
||||
ci: Boolean = BuildConfig.CI_BUILD,
|
||||
commit: String = BuildConfig.SOURCE_COMMIT,
|
||||
title: String = BuildConfig.PR_TITLE,
|
||||
branch: String = BuildConfig.BUILD_BRANCH,
|
||||
): List<String>? {
|
||||
if (ci && pr <= 0) return null
|
||||
val hash = commit.take(7).ifEmpty { "unknown" }
|
||||
val head = if (pr > 0) "PR-$pr | $hash" else "LOCAL | $hash"
|
||||
val detail = (if (pr > 0) title else branch).trim()
|
||||
return if (detail.isEmpty()) listOf(head) else listOf(head, truncate(detail))
|
||||
}
|
||||
|
||||
private fun truncate(text: String) =
|
||||
if (text.length <= TITLE_LIMIT) text else text.take(TITLE_LIMIT - 1).trimEnd() + "…"
|
||||
|
||||
fun install(app: Application) {
|
||||
val lines = lines() ?: return
|
||||
app.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
|
||||
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
|
||||
if (activity is QuestXrActivity) return
|
||||
val decor = activity.window.decorView as? ViewGroup ?: return
|
||||
if (decor.findViewWithTag<View>(TAG) != null) return
|
||||
val margin = (8 * activity.resources.displayMetrics.density).toInt()
|
||||
decor.addView(
|
||||
MarkView(activity, lines).apply { tag = TAG },
|
||||
FrameLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT,
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT,
|
||||
Gravity.BOTTOM or Gravity.END,
|
||||
).apply { setMargins(margin, margin, margin, margin) },
|
||||
)
|
||||
}
|
||||
|
||||
override fun onActivityStarted(activity: Activity) = Unit
|
||||
override fun onActivityResumed(activity: Activity) = Unit
|
||||
override fun onActivityPaused(activity: Activity) = Unit
|
||||
override fun onActivityStopped(activity: Activity) = Unit
|
||||
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
|
||||
override fun onActivityDestroyed(activity: Activity) = Unit
|
||||
})
|
||||
}
|
||||
|
||||
private const val TAG = "build-watermark"
|
||||
|
||||
private class MarkView(context: Context, private val lines: List<String>) : View(context) {
|
||||
private var shown = lines
|
||||
private val paint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
color = 0xE6FFFFFF.toInt()
|
||||
typeface = Typeface.MONOSPACE
|
||||
textSize = TypedValue.applyDimension(
|
||||
TypedValue.COMPLEX_UNIT_SP, 9f, context.resources.displayMetrics,
|
||||
)
|
||||
setShadowLayer(1.5f * context.resources.displayMetrics.density, 0f, 0f, 0xFF000000.toInt())
|
||||
textAlign = Paint.Align.RIGHT
|
||||
}
|
||||
private val backdrop = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = 0x66303030 }
|
||||
private val lineHeight get() = paint.fontSpacing
|
||||
|
||||
init {
|
||||
isClickable = false
|
||||
isFocusable = false
|
||||
importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO
|
||||
setLayerType(LAYER_TYPE_SOFTWARE, null)
|
||||
}
|
||||
|
||||
override fun onMeasure(widthSpec: Int, heightSpec: Int) {
|
||||
val pad = paddingForShadow() * 2
|
||||
val limit = if (MeasureSpec.getMode(widthSpec) == MeasureSpec.UNSPECIFIED) Float.MAX_VALUE
|
||||
else (MeasureSpec.getSize(widthSpec) - pad).coerceAtLeast(0).toFloat()
|
||||
shown = lines.map { TextUtils.ellipsize(it, paint, limit, TextUtils.TruncateAt.END).toString() }
|
||||
val width = shown.maxOf { paint.measureText(it) }.toInt() + pad
|
||||
setMeasuredDimension(width, (lineHeight * shown.size).toInt() + pad)
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
val pad = paddingForShadow()
|
||||
val radius = 3f * resources.displayMetrics.density
|
||||
canvas.drawRoundRect(0f, 0f, width.toFloat(), height.toFloat(), radius, radius, backdrop)
|
||||
shown.forEachIndexed { i, line ->
|
||||
canvas.drawText(line, width - pad.toFloat(), pad - paint.ascent() + lineHeight * i, paint)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onTouchEvent(event: android.view.MotionEvent) = false
|
||||
|
||||
private fun paddingForShadow() = (3 * resources.displayMetrics.density).toInt()
|
||||
}
|
||||
}
|
||||
@@ -93,6 +93,9 @@ fun ControllerMappingPage(mapping: Map<String, String>, onPick: (String, String)
|
||||
lede = stringResource(R.string.ctrl_mapping_lede),
|
||||
onBack = onBack,
|
||||
) {
|
||||
SettingsGroup(stringResource(R.string.shortcuts_title)) {
|
||||
PhysicalShortcutRows()
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.ctrl_onscreen_buttons)) {
|
||||
val targets = ControllerPrefs.targets.map { (id, label) -> id to stringResource(label) }
|
||||
for ((id, name) in ControllerPrefs.mappable) {
|
||||
|
||||
+17
-17
@@ -4,11 +4,11 @@ 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
|
||||
import com.droiddeck.launcher.hud.DroidDeckHudSize
|
||||
|
||||
/** Bannerlator's Fusion HUD settings (DeckOverlaySettings): one row per key of the HUD's config string. */
|
||||
/** Bannerlator's DroidDeck HUD settings (DeckOverlaySettings): one row per key of the HUD's config string. */
|
||||
@Composable
|
||||
internal fun FusionHudSettings(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
|
||||
internal fun DroidDeckHudSettings(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
|
||||
@@ -16,14 +16,14 @@ internal fun FusionHudSettings(host: MenuHost, a: DrawerActions, track: (String)
|
||||
SettingsGroup(stringResource(R.string.drawer_hud)) {
|
||||
ToggleRow(host, "hud", stringResource(R.string.drawer_hud), null, a.hudOn, chipModifier = track("hud"), onChange = a.onHud)
|
||||
if (!a.hudOn) return@SettingsGroup
|
||||
val size = FusionSize.from(cfg["hudSize"])
|
||||
val size = DroidDeckHudSize.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),
|
||||
DroidDeckHudSize.FULL to stringResource(R.string.hud_size_full),
|
||||
DroidDeckHudSize.TILES to stringResource(R.string.hud_size_tiles),
|
||||
DroidDeckHudSize.PILL to stringResource(R.string.hud_size_pill),
|
||||
DroidDeckHudSize.MINIMAL to stringResource(R.string.hud_size_minimal),
|
||||
DroidDeckHudSize.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"),
|
||||
@@ -47,7 +47,7 @@ internal fun FusionHudSettings(host: MenuHost, a: DrawerActions, track: (String)
|
||||
if (cfg["hudOutlineAccent"] == "0") "0" else "1", chipModifier = track("hud-outline-color")) { a.onHudSetting("hudOutlineAccent", it) }
|
||||
}
|
||||
|
||||
val size = FusionSize.from(cfg["hudSize"])
|
||||
val size = DroidDeckHudSize.from(cfg["hudSize"])
|
||||
val chips = size.supportedChips() + EXTRA[size].orEmpty()
|
||||
SettingsGroup(stringResource(R.string.hud_group_metrics)) {
|
||||
for (metric in METRICS) {
|
||||
@@ -84,7 +84,7 @@ internal fun FusionHudSettings(host: MenuHost, a: DrawerActions, track: (String)
|
||||
}
|
||||
}
|
||||
|
||||
SettingsGroup(stringResource(R.string.hud_group_more), detail = stringResource(R.string.hud_credit)) {
|
||||
SettingsGroup(stringResource(R.string.hud_group_more)) {
|
||||
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),
|
||||
@@ -95,11 +95,11 @@ internal fun FusionHudSettings(host: MenuHost, a: DrawerActions, track: (String)
|
||||
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 val EXTRA = mapOf(DroidDeckHudSize.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.
|
||||
// DroidDeckHudSize.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),
|
||||
@@ -124,10 +124,10 @@ private val METRICS = listOf(
|
||||
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
|
||||
// Switches a size lists but never draws (DroidDeckHudView): 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"),
|
||||
DroidDeckHudSize.PILL to setOf("FPS", "FPS graph"),
|
||||
DroidDeckHudSize.MINIMAL to setOf("FPS"),
|
||||
DroidDeckHudSize.TILES to setOf("FPS graph", "0.01% low"),
|
||||
)
|
||||
@@ -69,6 +69,8 @@ object DualScreenPanel {
|
||||
private var launching = false
|
||||
set(value) { field = value; available = value || activity != null }
|
||||
private var ownerTask = -1
|
||||
private var ownerYielded = false
|
||||
private var ownerPaused = false
|
||||
|
||||
var typing by mutableStateOf<TypingRequest?>(null)
|
||||
private set
|
||||
@@ -114,10 +116,12 @@ object DualScreenPanel {
|
||||
}
|
||||
|
||||
fun show(context: Context, display: Int, task: Int) {
|
||||
if (shownOn == display) return
|
||||
if (shownOn == display) { ownerTask = task; return }
|
||||
hide()
|
||||
displayId = display
|
||||
ownerTask = task
|
||||
ownerYielded = false
|
||||
ownerPaused = false
|
||||
launching = true
|
||||
val intent = Intent(context, DualScreenActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION)
|
||||
@@ -134,6 +138,10 @@ object DualScreenPanel {
|
||||
activity = null
|
||||
}
|
||||
|
||||
fun hide(task: Int) {
|
||||
if (ownerTask == task || ownerTask < 0) hide()
|
||||
}
|
||||
|
||||
internal fun attach(host: DualScreenActivity): Boolean {
|
||||
if (!launching && activity == null) return false
|
||||
if (activity !== host) activity?.finishAndRemoveTask()
|
||||
@@ -142,11 +150,43 @@ object DualScreenPanel {
|
||||
return true
|
||||
}
|
||||
|
||||
internal fun returnFocus(context: Context) {
|
||||
val task = ownerTask.takeIf { it >= 0 } ?: return
|
||||
// The panel resumes when an app opens over the owner on the primary screen; pulling the owner back would hide that app.
|
||||
fun yieldTo(task: Int, app: Boolean) {
|
||||
if (ownerTask == task) ownerYielded = app
|
||||
}
|
||||
|
||||
fun opensOutside(own: String, target: String?): Boolean = target != null && target != own
|
||||
|
||||
fun ownerPaused(task: Int, paused: Boolean) {
|
||||
if (ownerTask == task) ownerPaused = paused
|
||||
}
|
||||
|
||||
internal fun focusTask(fromPanel: Boolean): Int? {
|
||||
if (ownerYielded || (ownerPaused && !fromPanel)) return null
|
||||
return ownerTask.takeIf { it >= 0 }
|
||||
}
|
||||
|
||||
internal fun tookFocus(fresh: Boolean, touchedAt: Long, now: Long): Boolean =
|
||||
fresh || now - touchedAt in 0..TOUCH_FOCUS_MS
|
||||
|
||||
private const val TOUCH_FOCUS_MS = 1000L
|
||||
|
||||
internal fun returnFocus(context: Context, fromPanel: Boolean = false) {
|
||||
val task = focusTask(fromPanel) ?: return
|
||||
runCatching { (context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager).moveTaskToFront(task, 0) }
|
||||
}
|
||||
|
||||
internal fun reclaimFocus(context: Context) {
|
||||
val task = focusTask(false) ?: return
|
||||
val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager
|
||||
runCatching {
|
||||
manager.appTasks.firstOrNull {
|
||||
@Suppress("DEPRECATION")
|
||||
(if (android.os.Build.VERSION.SDK_INT >= 29) it.taskInfo.taskId else it.taskInfo.persistentId) == task
|
||||
}?.moveToFront() ?: manager.moveTaskToFront(task, 0)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun detach(host: DualScreenActivity) {
|
||||
if (activity === host) {
|
||||
activity = null
|
||||
@@ -162,7 +202,7 @@ class DualScreenActivity : ComponentActivity() {
|
||||
finishAndRemoveTask()
|
||||
return
|
||||
}
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
applyImmersiveMode()
|
||||
setContent {
|
||||
val model = DualScreenPanel.model
|
||||
@@ -185,10 +225,10 @@ class DualScreenActivity : ComponentActivity() {
|
||||
runCatching { (getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager).moveTaskToFront(taskId, 0) }
|
||||
} else {
|
||||
unfocusPending = true
|
||||
DualScreenPanel.returnFocus(this)
|
||||
DualScreenPanel.returnFocus(this, fromPanel = true)
|
||||
window.decorView.postDelayed({
|
||||
if (!unfocusPending || DualScreenPanel.typingShown) return@postDelayed
|
||||
if (window.decorView.hasWindowFocus()) DualScreenPanel.returnFocus(this) else dropFocus()
|
||||
if (window.decorView.hasWindowFocus()) DualScreenPanel.returnFocus(this, fromPanel = true) else dropFocus()
|
||||
}, 400)
|
||||
}
|
||||
}
|
||||
@@ -197,7 +237,6 @@ class DualScreenActivity : ComponentActivity() {
|
||||
|
||||
private fun dropFocus() {
|
||||
unfocusPending = false
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
@@ -205,10 +244,32 @@ class DualScreenActivity : ComponentActivity() {
|
||||
if (!DualScreenPanel.typingShown) DualScreenPanel.returnFocus(this)
|
||||
}
|
||||
|
||||
private var topResumed = false
|
||||
private var fresh = true
|
||||
private var touchedAt = Long.MIN_VALUE
|
||||
|
||||
override fun onTopResumedActivityChanged(isTopResumedActivity: Boolean) {
|
||||
super.onTopResumedActivityChanged(isTopResumedActivity)
|
||||
topResumed = isTopResumedActivity
|
||||
val took = DualScreenPanel.tookFocus(fresh, touchedAt, android.os.SystemClock.uptimeMillis())
|
||||
fresh = false
|
||||
if (isTopResumedActivity && !DualScreenPanel.typingShown) DualScreenPanel.returnFocus(this, fromPanel = took)
|
||||
}
|
||||
|
||||
override fun dispatchTouchEvent(event: android.view.MotionEvent): Boolean {
|
||||
if (event.actionMasked == android.view.MotionEvent.ACTION_DOWN) {
|
||||
touchedAt = event.downTime
|
||||
if (topResumed && !DualScreenPanel.typingShown) DualScreenPanel.returnFocus(this, fromPanel = true)
|
||||
}
|
||||
return super.dispatchTouchEvent(event)
|
||||
}
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
if (hasFocus) applyImmersiveMode()
|
||||
else if (unfocusPending && !DualScreenPanel.typingShown) dropFocus()
|
||||
if (hasFocus) {
|
||||
applyImmersiveMode()
|
||||
if (!DualScreenPanel.typingShown) DualScreenPanel.reclaimFocus(this)
|
||||
} else if (unfocusPending && !DualScreenPanel.typingShown) dropFocus()
|
||||
}
|
||||
|
||||
@Suppress("OVERRIDE_DEPRECATION")
|
||||
@@ -221,6 +282,7 @@ class DualScreenActivity : ComponentActivity() {
|
||||
if (event.action == KeyEvent.ACTION_UP && !event.isCanceled) DualScreenPanel.finishTyping()
|
||||
return true
|
||||
}
|
||||
if (topResumed && !DualScreenPanel.typingShown && event.action == KeyEvent.ACTION_DOWN) DualScreenPanel.returnFocus(this, fromPanel = true)
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
|
||||
|
||||
@@ -465,7 +465,8 @@ private fun UserAppPage(app: UserApps.App, s: FrontEndState, a: FrontEndActions,
|
||||
val ctx = LocalContext.current
|
||||
val narrow = LocalNarrowPane.current
|
||||
var editing by rememberSaveable(app.key) { mutableStateOf(false) }
|
||||
val x86 = (app.arch == "x86_64" || app.arch == "i386") && app.fex != com.droiddeck.launcher.runtime.LinuxFex.OFF
|
||||
val x86 = (app.arch == "x86_64" || app.arch == "i386") && app.fex != com.droiddeck.launcher.runtime.LinuxFex.OFF &&
|
||||
app.kind != UserApps.Kind.FLATPAK
|
||||
val fexReady by produceState<Boolean?>(null, app.key, x86, s.sessionRunning) {
|
||||
value = if (x86) kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { com.droiddeck.launcher.runtime.LinuxFex.ready(ctx) } else true
|
||||
}
|
||||
|
||||
@@ -202,7 +202,6 @@ internal fun BusyChip(s: FrontEndState) {
|
||||
internal fun RuntimeChip(s: FrontEndState) = when {
|
||||
s.busy -> Chip(if (s.percent >= 0) stringResource(R.string.setup_runtime_progress, s.stage, s.percent) else s.stage, ok = false)
|
||||
s.removalPending -> Chip(stringResource(R.string.runtime_removal_incomplete), ok = false)
|
||||
!s.ready -> Chip(stringResource(R.string.games_runtime_first_play), ok = false)
|
||||
s.available != null && s.available != s.installed -> Chip(stringResource(R.string.games_runtime_update), ok = false)
|
||||
else -> Chip(stringResource(R.string.games_runtime_ready), ok = true)
|
||||
}
|
||||
|
||||
@@ -166,7 +166,7 @@ class FrontEndState(
|
||||
val sgdbUserKey: Boolean = false,
|
||||
val storesShowMature: Boolean = false,
|
||||
val storesSort: String = SessionPrefs.STORES_SORTS.first(),
|
||||
val storesView: String = SessionPrefs.STORES_VIEWS.first(),
|
||||
val storesView: String = SessionPrefs.DEFAULT_STORES_VIEW,
|
||||
val storeDownloadsActive: Int = 0,
|
||||
val updates: UpdatesState = UpdatesState(),
|
||||
)
|
||||
|
||||
@@ -614,25 +614,35 @@ private fun GameMoreMenu(g: Library.SteamGame, a: FrontEndActions) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun IconAction(icon: androidx.compose.ui.graphics.vector.ImageVector, label: String, id: String, danger: Boolean = false, enabled: Boolean = true, onClick: () -> Unit) {
|
||||
internal fun IconAction(icon: androidx.compose.ui.graphics.vector.ImageVector, label: String, id: String, danger: Boolean = false, enabled: Boolean = true, frosted: Boolean = false, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val shape = if (LocalPillButtons.current) CircleShape else Shape12
|
||||
val pill = LocalPillButtons.current
|
||||
val shape = if (pill) CircleShape else Shape12
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src) && enabled
|
||||
val accent = if (danger) colors.error else pal.signal
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.paneItem(id).downToFirstTile().size(if (LocalPillButtons.current) 40.dp else 44.dp).clip(shape)
|
||||
.background(if (hot) accent.copy(alpha = if (danger) 0.22f else 0.14f) else if (danger) Color.Black.copy(alpha = 0.34f) else Color.White.copy(alpha = 0.03f))
|
||||
.glideBorder(hot, shape, accent, pal.line2)
|
||||
.alpha(if (enabled) 1f else 0.45f)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = androidx.compose.ui.semantics.Role.Button, enabled = enabled, onClick = onClick)
|
||||
.controllerConfirm(enabled = enabled, onClick = onClick)
|
||||
.semantics { contentDescription = label },
|
||||
) {
|
||||
Icon(icon, contentDescription = null, tint = if (danger && hot) colors.error else if (danger) Color.White else colors.onBackground, modifier = Modifier.size(18.dp))
|
||||
val fill = when {
|
||||
hot -> accent.copy(alpha = if (danger) 0.22f else 0.14f)
|
||||
pill -> Color.White.copy(alpha = 0.09f)
|
||||
danger -> Color.Black.copy(alpha = 0.34f)
|
||||
else -> Color.White.copy(alpha = 0.03f)
|
||||
}
|
||||
val button: @Composable () -> Unit = {
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.paneItem(id).downToFirstTile().size(if (pill) 40.dp else 44.dp).clip(shape)
|
||||
.background(fill)
|
||||
.glideBorder(hot, shape, accent, if (pill) Color.White.copy(alpha = 0.14f) else pal.line2)
|
||||
.alpha(if (enabled) 1f else 0.45f)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = androidx.compose.ui.semantics.Role.Button, enabled = enabled, onClick = onClick)
|
||||
.controllerConfirm(enabled = enabled, onClick = onClick)
|
||||
.semantics { contentDescription = label },
|
||||
) {
|
||||
Icon(icon, contentDescription = null, tint = if (danger && hot) colors.error else if (danger && !pill) Color.White else colors.onBackground, modifier = Modifier.size(18.dp))
|
||||
}
|
||||
}
|
||||
if (frosted) Box(Modifier.glass(CircleShape)) { button() } else button()
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -645,7 +655,7 @@ private fun RemoveButton(title: String, game: Library.SteamGame?, installed: Ins
|
||||
val gone = StoresState.uninstalling[key]
|
||||
if (gone != null) {
|
||||
val uninstalling = stringResource(R.string.stores_uninstalling)
|
||||
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(44.dp).clip(Shape12).background(Color.Black.copy(alpha = 0.34f)).semantics { contentDescription = uninstalling }) {
|
||||
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(40.dp).glass(CircleShape).semantics { contentDescription = uninstalling }) {
|
||||
if (gone > 0f) CircularProgressIndicator(progress = { gone }, strokeWidth = 2.dp, color = colors.error, trackColor = colors.error.copy(alpha = 0.22f), modifier = Modifier.size(20.dp))
|
||||
else CircularProgressIndicator(strokeWidth = 2.dp, color = colors.error, modifier = Modifier.size(20.dp))
|
||||
}
|
||||
@@ -659,7 +669,7 @@ private fun RemoveButton(title: String, game: Library.SteamGame?, installed: Ins
|
||||
val busy = StoresState.download(key)?.isActive == true || (installed.sidecar.store == Store.XBOX && XboxContent.busy(installed.sidecar.id))
|
||||
val placed = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
|
||||
Box(Modifier.onGloballyPositioned { placed[0] = it }) {
|
||||
IconAction(Icons.Outlined.Delete, remove, "game:remove", danger = true, enabled = !busy) {
|
||||
IconAction(Icons.Outlined.Delete, remove, "game:remove", danger = true, enabled = !busy, frosted = true) {
|
||||
val at = placed[0]?.takeIf { it.isAttached }?.boundsInRoot() ?: return@IconAction
|
||||
var confirmed = false
|
||||
Steps.ask(StepAsk(anchor = at, side = StepSide.Left, accent = colors.error, items = 3, pillCorner = 12.dp, maxWidth = 340.dp,
|
||||
@@ -682,7 +692,7 @@ private fun RemoveButton(title: String, game: Library.SteamGame?, installed: Ins
|
||||
var asking by remember(g.gameId) { mutableStateOf(false) }
|
||||
val shortcut = kind == GameRemoval.Kind.SHORTCUT
|
||||
val label = stringResource(if (shortcut) R.string.edit_remove else R.string.common_uninstall)
|
||||
IconAction(Icons.Outlined.Delete, label, "game:remove", danger = true) { asking = true }
|
||||
IconAction(Icons.Outlined.Delete, label, "game:remove", danger = true, frosted = true) { asking = true }
|
||||
if (asking) ConfirmDialog(
|
||||
title = if (shortcut) stringResource(R.string.games_remove_title, g.name) else stringResource(R.string.stores_uninstall_title, g.name),
|
||||
text = when {
|
||||
|
||||
@@ -23,7 +23,7 @@ import com.droiddeck.launcher.stores.itch.ItchUpdates
|
||||
@Composable
|
||||
internal fun ItchCheckButton(installed: InstalledStoreGame) {
|
||||
val ctx = LocalContext.current
|
||||
IconAction(Icons.Filled.Refresh, stringResource(R.string.store_check_updates), "game:check-updates", enabled = ItchUpdates.checkingKey == null) {
|
||||
IconAction(Icons.Filled.Refresh, stringResource(R.string.store_check_updates), "game:check-updates", enabled = ItchUpdates.checkingKey == null, frosted = true) {
|
||||
ItchUpdates.checkGame(ctx, installed)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -306,6 +306,7 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
if (steam && s.steamController in listOf(SessionPrefs.CONTROLLER_DECK, SessionPrefs.CONTROLLER_STEAM)) {
|
||||
Note(stringResource(R.string.back_native_qam_hint))
|
||||
}
|
||||
PhysicalShortcutRows()
|
||||
}
|
||||
}
|
||||
if (tab == SheetTab.AUDIO && steam) {
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.util.Log
|
||||
import android.view.KeyEvent
|
||||
import android.view.Window
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.compose.ui.window.DialogWindowProvider
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.input.PhysicalShortcuts
|
||||
|
||||
@Composable
|
||||
internal fun PhysicalShortcutRows(
|
||||
onChanged: () -> Unit = {},
|
||||
modifierFor: (PhysicalShortcuts.Action) -> Modifier = { Modifier },
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
var bindings by remember { mutableStateOf(PhysicalShortcuts.read(context)) }
|
||||
var editing by remember { mutableStateOf<PhysicalShortcuts.Action?>(null) }
|
||||
Column {
|
||||
for (action in PhysicalShortcuts.Action.entries) {
|
||||
val assigned = bindings.filter { it.action == action }
|
||||
SettingsRow(
|
||||
stringResource(action.label),
|
||||
assigned.joinToString { "${it.button.label} · ${it.button.name}" }.ifEmpty { null },
|
||||
) {
|
||||
SecondaryButton(
|
||||
stringResource(if (assigned.isEmpty()) R.string.game_settings_default else R.string.ctrl_custom),
|
||||
compact = true,
|
||||
modifier = modifierFor(action).width(LocalChipMinWidth.current)
|
||||
.testTag("shortcuts-assign-${action.name}"),
|
||||
) { editing = action }
|
||||
}
|
||||
}
|
||||
}
|
||||
editing?.let { action ->
|
||||
PhysicalShortcutsDialog(action, onDismiss = { editing = null }, onChanged = {
|
||||
bindings = PhysicalShortcuts.read(context)
|
||||
onChanged()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun PhysicalShortcutsDialog(
|
||||
action: PhysicalShortcuts.Action,
|
||||
onDismiss: () -> Unit,
|
||||
onChanged: () -> Unit = {},
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val bindings = remember { PhysicalShortcuts.read(context) }
|
||||
var candidate by remember { mutableStateOf<PhysicalShortcuts.Button?>(null) }
|
||||
var listening by remember { mutableStateOf(true) }
|
||||
var capturedDevice by remember { mutableStateOf(-1) }
|
||||
Dialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(dismissOnBackPress = !listening, usePlatformDefaultWidth = false),
|
||||
) {
|
||||
CaptureShortcutKeys { event ->
|
||||
if (listening && event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0 &&
|
||||
(event.keyCode == KeyEvent.KEYCODE_BACK || event.keyCode == KeyEvent.KEYCODE_BUTTON_B)) {
|
||||
listening = false
|
||||
onDismiss()
|
||||
true
|
||||
} else if (!listening || PhysicalShortcuts.isVolumeKey(event)) {
|
||||
false
|
||||
} else {
|
||||
if (candidate == null && event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||
PhysicalShortcuts.button(event)?.let { button ->
|
||||
candidate = button
|
||||
capturedDevice = event.deviceId
|
||||
Log.i("PhysicalShortcuts", "capture device=${button.name} key=${event.keyCode} " +
|
||||
"scan=${event.scanCode} source=0x${event.source.toString(16)}")
|
||||
}
|
||||
} else if (event.action == KeyEvent.ACTION_UP && event.deviceId == capturedDevice &&
|
||||
candidate?.matches(event) == true) {
|
||||
listening = false
|
||||
candidate?.let { button ->
|
||||
if (bindings.none { it.button.sameInput(button) && it.action != action }) {
|
||||
PhysicalShortcuts.assign(context, button, action)
|
||||
onChanged()
|
||||
onDismiss()
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
CompositionLocalProvider(LocalFrontFocus provides null) {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
modifier = Modifier.padding(12.dp).widthIn(max = 560.dp).fillMaxWidth()
|
||||
.heightIn(max = (LocalConfiguration.current.screenHeightDp - 24).dp),
|
||||
) {
|
||||
Column(
|
||||
Modifier.verticalScroll(rememberScrollState()).padding(18.dp).controllerBack(onDismiss),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Text(stringResource(R.string.shortcuts_capture, stringResource(action.label)),
|
||||
style = MaterialTheme.typography.titleLarge)
|
||||
val button = candidate
|
||||
if (button == null) {
|
||||
Text(stringResource(R.string.shortcuts_press))
|
||||
} else {
|
||||
Text(stringResource(R.string.shortcuts_detected, button.name, button.label))
|
||||
if (listening) {
|
||||
Text(stringResource(R.string.shortcuts_release))
|
||||
} else {
|
||||
val replacements = bindings.filter {
|
||||
it.button.sameInput(button) || (it.button.device == button.device && it.action == action)
|
||||
}
|
||||
for (conflict in replacements) {
|
||||
Text("${conflict.button.label} · ${conflict.button.name}")
|
||||
Text(stringResource(R.string.shortcuts_conflict, stringResource(conflict.action.label)))
|
||||
}
|
||||
SecondaryButton(stringResource(R.string.shortcuts_save), modifier = Modifier.testTag("shortcuts-save")) {
|
||||
PhysicalShortcuts.assign(context, button, action)
|
||||
onChanged()
|
||||
onDismiss()
|
||||
}
|
||||
}
|
||||
SecondaryButton(stringResource(R.string.shortcuts_retry), modifier = Modifier.testTag("shortcuts-retry")) {
|
||||
candidate = null
|
||||
capturedDevice = -1
|
||||
listening = true
|
||||
}
|
||||
}
|
||||
Text(stringResource(R.string.shortcuts_limitations), style = MaterialTheme.typography.bodySmall)
|
||||
for (binding in bindings.filter { it.action == action }) {
|
||||
ActionRow(
|
||||
stringResource(R.string.shortcuts_detected, binding.button.name, binding.button.label),
|
||||
null, stringResource(R.string.ctrl_reset), {
|
||||
PhysicalShortcuts.remove(context, binding)
|
||||
onChanged()
|
||||
onDismiss()
|
||||
},
|
||||
modifier = Modifier.testTag("shortcuts-remove"),
|
||||
)
|
||||
}
|
||||
SecondaryButton(stringResource(R.string.common_close), modifier = Modifier.testTag("shortcuts-cancel"),
|
||||
onClick = onDismiss)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CaptureShortcutKeys(onKey: (KeyEvent) -> Boolean) {
|
||||
val currentOnKey by rememberUpdatedState(onKey)
|
||||
val window = (LocalView.current.parent as DialogWindowProvider).window
|
||||
DisposableEffect(window) {
|
||||
val previous = window.callback
|
||||
// Capture before dialog navigation so Back and gamepad buttons can be assigned.
|
||||
window.callback = object : Window.Callback by previous {
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean =
|
||||
currentOnKey(event) || previous.dispatchKeyEvent(event)
|
||||
}
|
||||
onDispose { window.callback = previous }
|
||||
}
|
||||
}
|
||||
@@ -56,9 +56,11 @@ class SecondScreenPresentation(
|
||||
private val onKeyboardClosed: () -> Unit = {},
|
||||
private val onMenu: (() -> Unit)? = null,
|
||||
private val menu: (@androidx.compose.runtime.Composable () -> Unit)? = null,
|
||||
private val dashboard: (@androidx.compose.runtime.Composable () -> Unit)? = null,
|
||||
) : Presentation(sessionActivity, display) {
|
||||
private val frame = FrameLayout(context)
|
||||
private var menuView: androidx.compose.ui.platform.ComposeView? = null
|
||||
private var dashboardView: androidx.compose.ui.platform.ComposeView? = null
|
||||
var menuShown = false
|
||||
private set
|
||||
private val root = LinearLayout(context).apply {
|
||||
@@ -141,6 +143,10 @@ class SecondScreenPresentation(
|
||||
if (created) renderMode()
|
||||
}
|
||||
|
||||
fun retryTerminal() {
|
||||
if (created && isShowing && currentMode == SecondScreenMode.TERMINAL && terminalSession == null) renderMode()
|
||||
}
|
||||
|
||||
val showsKeyboard: Boolean get() = isShowing && !menuShown && currentMode == SecondScreenMode.KEYBOARD_TRACKPAD
|
||||
|
||||
val showsControls: Boolean get() = isShowing && currentMode != SecondScreenMode.NONE
|
||||
@@ -151,12 +157,7 @@ class SecondScreenPresentation(
|
||||
menuShown = on
|
||||
if (on) {
|
||||
keyboardHost?.takeIf { it.shown }?.hide()
|
||||
window?.decorView?.let { decor ->
|
||||
decor.setViewTreeLifecycleOwner(sessionActivity)
|
||||
decor.setViewTreeViewModelStoreOwner(sessionActivity)
|
||||
decor.setViewTreeSavedStateRegistryOwner(sessionActivity)
|
||||
decor.setViewTreeOnBackPressedDispatcherOwner(sessionActivity)
|
||||
}
|
||||
ownComposeViews()
|
||||
val view = menuView ?: androidx.compose.ui.platform.ComposeView(context).apply {
|
||||
isFocusable = true
|
||||
isFocusableInTouchMode = true
|
||||
@@ -175,12 +176,22 @@ class SecondScreenPresentation(
|
||||
}
|
||||
}
|
||||
|
||||
private fun ownComposeViews() {
|
||||
window?.decorView?.let { decor ->
|
||||
decor.setViewTreeLifecycleOwner(sessionActivity)
|
||||
decor.setViewTreeViewModelStoreOwner(sessionActivity)
|
||||
decor.setViewTreeSavedStateRegistryOwner(sessionActivity)
|
||||
decor.setViewTreeOnBackPressedDispatcherOwner(sessionActivity)
|
||||
}
|
||||
}
|
||||
|
||||
fun focusMenu(): Boolean = menuView?.requestFocus() == true
|
||||
|
||||
fun dispatchMenuKey(event: KeyEvent): Boolean = menuView?.dispatchKeyEvent(event) == true
|
||||
|
||||
fun closeControls() {
|
||||
showMenu(false)
|
||||
closeDashboard()
|
||||
closeTerminal()
|
||||
keyboardHost?.hide()
|
||||
keyboardHost = null
|
||||
@@ -188,7 +199,8 @@ class SecondScreenPresentation(
|
||||
}
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
val forward = menuShown || currentMode != SecondScreenMode.TERMINAL || PadBridge.isControllerKeyEvent(event)
|
||||
val ownKeys = currentMode == SecondScreenMode.TERMINAL || currentMode == SecondScreenMode.DASHBOARD
|
||||
val forward = menuShown || !ownKeys || PadBridge.isControllerKeyEvent(event)
|
||||
if (forward && sessionActivity.dispatchKeyEvent(event)) return true
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
@@ -214,19 +226,37 @@ class SecondScreenPresentation(
|
||||
keyboardButton = null
|
||||
keyboardPending = false
|
||||
closeTerminal()
|
||||
closeDashboard()
|
||||
root.removeAllViews()
|
||||
val mode = if (currentMode == SecondScreenMode.DECK_CONTROLS && !SessionState.deckPad) SecondScreenMode.NONE
|
||||
else currentMode
|
||||
val mode = when {
|
||||
currentMode == SecondScreenMode.DECK_CONTROLS && !SessionState.deckPad -> SecondScreenMode.NONE
|
||||
currentMode == SecondScreenMode.DASHBOARD && dashboard == null -> SecondScreenMode.NONE
|
||||
else -> currentMode
|
||||
}
|
||||
if (mode == SecondScreenMode.NONE) return
|
||||
|
||||
when (mode) {
|
||||
SecondScreenMode.KEYBOARD_TRACKPAD -> renderKeyboardAndTrackpad()
|
||||
SecondScreenMode.TERMINAL -> renderTerminal()
|
||||
SecondScreenMode.DECK_CONTROLS -> root.addView(DeckControlsPanel(context, onClose, onSteamMenu, onQam, pad, onMenu = onMenu), weightParams())
|
||||
SecondScreenMode.DASHBOARD -> renderDashboard()
|
||||
SecondScreenMode.NONE -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
private fun renderDashboard() {
|
||||
val content = dashboard ?: return
|
||||
ownComposeViews()
|
||||
val view = androidx.compose.ui.platform.ComposeView(context).apply { setContent { content() } }
|
||||
dashboardView = view
|
||||
root.addView(view, weightParams())
|
||||
}
|
||||
|
||||
private fun closeDashboard() {
|
||||
dashboardView?.disposeComposition()
|
||||
dashboardView = null
|
||||
}
|
||||
|
||||
private fun renderKeyboardAndTrackpad() {
|
||||
val panel = FrameLayout(context)
|
||||
panel.addView(trackpadView(), FrameLayout.LayoutParams(-1, -1))
|
||||
|
||||
@@ -31,6 +31,7 @@ import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.material.icons.outlined.Close
|
||||
import androidx.compose.material.icons.outlined.Terminal
|
||||
import androidx.compose.material.icons.outlined.Dashboard
|
||||
import androidx.compose.material.icons.outlined.Keyboard
|
||||
import androidx.compose.material.icons.outlined.AutoFixHigh
|
||||
import androidx.compose.material.icons.outlined.ExpandMore
|
||||
@@ -240,6 +241,7 @@ class DrawerActions(
|
||||
val textureAnisotropy: Int? = 0,
|
||||
val textureLodBias: String? = TextureFiltering.LOD_BIAS_OFF,
|
||||
val secondScreenMode: SecondScreenMode,
|
||||
val dashboardAvailable: Boolean = false,
|
||||
val secondScreenDisplays: List<SecondScreenDisplay>,
|
||||
val selectedSecondScreenDisplay: Int,
|
||||
val onHud: (Boolean) -> Unit,
|
||||
@@ -247,6 +249,8 @@ class DrawerActions(
|
||||
val onHudReset: () -> Unit = {},
|
||||
val onHudExport: () -> Unit = {},
|
||||
val onFrameGenPick: (FrameGen.Mode) -> Unit,
|
||||
val fpsLimit: Int = 0,
|
||||
val onFpsLimit: (Int) -> Unit = {},
|
||||
val onImportLossless: () -> Unit,
|
||||
val onKeyboard: () -> Unit,
|
||||
val onHardwareKeyboard: () -> Unit,
|
||||
@@ -531,10 +535,11 @@ 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.HUD -> DroidDeckHudSettings(host, a) { key -> focus.track(page, key) }
|
||||
SessionDrawerPage.DISPLAY -> {
|
||||
SettingsGroup(stringResource(R.string.drawer_page_display)) {
|
||||
val fgOpen = host.open == "fg"
|
||||
val offLabel = stringResource(R.string.frame_gen_off)
|
||||
val fgLabel = FrameGen.label(LocalContext.current, a.frameGen)
|
||||
SettingsRow(stringResource(R.string.frame_gen_title), null, highlighted = fgOpen) {
|
||||
Box {
|
||||
@@ -542,6 +547,13 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
FrameGenMenu(host, a.frameGen, a.lossless, a.onFrameGenPick, a.onImportLossless)
|
||||
}
|
||||
}
|
||||
if (a.direct) SliderRow(
|
||||
stringResource(R.string.drawer_frame_limit), stringResource(R.string.drawer_frame_limit_note),
|
||||
a.fpsLimit.takeIf { it > 0 } ?: SessionPrefs.FPS_LIMIT_OFF,
|
||||
SessionPrefs.FPS_LIMIT_OFF..SessionPrefs.FPS_LIMIT_MAX, step = 5,
|
||||
format = { if (it <= SessionPrefs.FPS_LIMIT_OFF) offLabel else it.toString() },
|
||||
modifier = focus.track(page, "fps-limit"),
|
||||
onChange = { a.onFpsLimit(if (it <= SessionPrefs.FPS_LIMIT_OFF) 0 else it) })
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.display_image_scaling)) {
|
||||
ChoiceRow(host, "upscaler", stringResource(R.string.display_filter), null,
|
||||
@@ -635,6 +647,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
if (a.steam) ChoiceRow(host, "back-double-tap", stringResource(R.string.back_double_tap_window), null,
|
||||
SessionPrefs.BACK_DOUBLE_TAP_MS_OPTIONS.map { it to stringResource(R.string.back_tap_ms, it) },
|
||||
a.backDoubleTapMs, chipModifier = focus.track(page, "back-double-tap"), onPick = a.onBackDoubleTapMs)
|
||||
PhysicalShortcutRows(modifierFor = { focus.track(page, "physical-shortcut-${it.name}") })
|
||||
if (a.steam && a.unfoldedControls != null) ToggleRow(host, "unfolded-controls", stringResource(R.string.unfolded_controls),
|
||||
stringResource(R.string.unfolded_controls_hint), a.unfoldedControls,
|
||||
chipModifier = focus.track(page, "unfolded-controls"), onChange = a.onUnfoldedControls)
|
||||
@@ -856,6 +869,8 @@ private fun StopSessionButton(modifier: Modifier = Modifier, onClick: () -> Unit
|
||||
val fill by animateColorAsState(if (hot) colors.error.copy(alpha = 0.18f) else Color.Transparent, Motion.tw(220), label = "dangerFill")
|
||||
val shape = RoundedCornerShape(20.dp)
|
||||
val stopDescription = stringResource(R.string.stop_session)
|
||||
val stopLabel = stringResource(R.string.drawer_stop)
|
||||
var iconOnly by remember(stopLabel, androidx.compose.ui.platform.LocalConfiguration.current.screenWidthDp) { mutableStateOf(false) }
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
modifier = modifier.heightIn(min = 44.dp).semantics { contentDescription = stopDescription }.testTag("drawer-stop")
|
||||
@@ -865,7 +880,10 @@ private fun StopSessionButton(modifier: Modifier = Modifier, onClick: () -> Unit
|
||||
.padding(start = 12.dp, end = 14.dp),
|
||||
) {
|
||||
Icon(Icons.Outlined.PowerSettingsNew, contentDescription = null, tint = colors.error, modifier = Modifier.size(18.dp))
|
||||
Text(stringResource(R.string.drawer_stop), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.error)
|
||||
if (!iconOnly) Text(
|
||||
stopLabel, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.error,
|
||||
maxLines = 1, softWrap = false, onTextLayout = { if (it.hasVisualOverflow) iconOnly = true },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -877,6 +895,7 @@ private fun BottomScreenModes(a: DrawerActions, modifier: Modifier, onPick: () -
|
||||
if (com.droiddeck.launcher.session.SessionState.deckPad) add(SecondScreenMode.DECK_CONTROLS to Icons.Outlined.SportsEsports)
|
||||
add(SecondScreenMode.KEYBOARD_TRACKPAD to Icons.Outlined.Keyboard)
|
||||
add(SecondScreenMode.TERMINAL to Icons.Outlined.Terminal)
|
||||
if (a.dashboardAvailable) add(SecondScreenMode.DASHBOARD to Icons.Outlined.Dashboard)
|
||||
}
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
@@ -1174,7 +1193,8 @@ private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String)
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val modes = listOf(SecondScreenMode.NONE, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL) +
|
||||
if (com.droiddeck.launcher.session.SessionState.deckPad) listOf(SecondScreenMode.DECK_CONTROLS) else emptyList()
|
||||
(if (com.droiddeck.launcher.session.SessionState.deckPad) listOf(SecondScreenMode.DECK_CONTROLS) else emptyList()) +
|
||||
(if (a.dashboardAvailable) listOf(SecondScreenMode.DASHBOARD) else emptyList())
|
||||
SettingsGroup(stringResource(R.string.drawer_second_screen_mode)) {
|
||||
Column(Modifier.fillMaxWidth().selectableGroup()) {
|
||||
modes.forEach { mode ->
|
||||
@@ -1780,7 +1800,7 @@ private fun StopConfirm(
|
||||
.padding(start = 12.dp, end = 14.dp),
|
||||
) {
|
||||
Icon(Icons.Outlined.PowerSettingsNew, contentDescription = null, tint = colors.error, modifier = Modifier.size(18.dp))
|
||||
Text(stringResource(R.string.drawer_stop), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.error)
|
||||
Text(stringResource(R.string.drawer_stop), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.error, maxLines = 1, softWrap = false)
|
||||
}
|
||||
val maxW = with(density) { StepBoxMaxWidth.toPx() }.coerceAtMost(p.right)
|
||||
Column(
|
||||
|
||||
@@ -0,0 +1,588 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.geometry.CornerRadius
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Size
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Path
|
||||
import androidx.compose.ui.graphics.StrokeCap
|
||||
import androidx.compose.ui.graphics.StrokeJoin
|
||||
import androidx.compose.ui.graphics.drawscope.DrawScope
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.TextMeasurer
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.drawText
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.rememberTextMeasurer
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.session.GameStatusFiles
|
||||
import com.droiddeck.launcher.session.GameTelemetry
|
||||
import com.droiddeck.launcher.session.SpeedUnit
|
||||
import com.droiddeck.launcher.session.StatsDash
|
||||
import com.droiddeck.launcher.session.Telemetry
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.floor
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.roundToInt
|
||||
import kotlin.math.sin
|
||||
|
||||
private val DASH_H = 290.dp
|
||||
/** Pedal and speed trace length: 150 readings at the page's 66 ms draw rate, about 10 s. */
|
||||
internal const val TRACE_N = 150
|
||||
|
||||
internal class TraceData(val throttle: List<Float>, val brake: List<Float>, val speed: List<Float>)
|
||||
|
||||
/** The racing dash in [style] with speeds in [unit] (km/h or mph); a tap moves to the next one. */
|
||||
@Composable
|
||||
internal fun RaceDashView(style: StatsDash, t: Telemetry, trace: TraceData, unit: SpeedUnit, onTap: () -> Unit) {
|
||||
Box(Modifier.fillMaxWidth().clickable(onClick = onTap)) {
|
||||
when (style) {
|
||||
StatsDash.AUTO, StatsDash.SPEEDOMETER -> SpeedometerDash(t, unit)
|
||||
StatsDash.CIRCUIT -> CircuitDash(t, unit)
|
||||
StatsDash.TRACE -> TraceDash(t, trace, unit)
|
||||
StatsDash.DIALS -> DialsDash(t, unit)
|
||||
StatsDash.GLANCE -> GlanceDash(t, unit)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun polar(cx: Float, cy: Float, r: Float, deg: Float): Offset {
|
||||
val a = Math.toRadians((deg - 90f).toDouble())
|
||||
return Offset(cx + r * cos(a).toFloat(), cy + r * sin(a).toFloat())
|
||||
}
|
||||
|
||||
private const val DIAL_START = -125f
|
||||
private const val DIAL_SWEEP = 250f
|
||||
|
||||
private fun dialAngle(v: Float, max: Float) = DIAL_START + DIAL_SWEEP * (v / max).coerceIn(0f, 1f)
|
||||
|
||||
/** A 250° dial face: track, optional red zone from [red], ticks and numbers every [major]. */
|
||||
private fun DrawScope.dialFace(
|
||||
cx: Float, cy: Float, r: Float, max: Float, major: Float, label: (Float) -> String,
|
||||
measurer: TextMeasurer, labelStyle: TextStyle, tick: Color, minor: Color, track: Color, red: Float?, redColor: Color,
|
||||
) {
|
||||
val box = Size(2 * r, 2 * r)
|
||||
val tl = Offset(cx - r, cy - r)
|
||||
drawArc(track, DIAL_START - 90f, DIAL_SWEEP, false, topLeft = tl, size = box, style = Stroke(6.dp.toPx(), cap = StrokeCap.Round))
|
||||
if (red != null && red < max) {
|
||||
drawArc(redColor, dialAngle(red, max) - 90f, dialAngle(max, max) - dialAngle(red, max), false, topLeft = tl, size = box, style = Stroke(6.dp.toPx()))
|
||||
}
|
||||
val steps = (max / (major / 2f)).roundToInt()
|
||||
for (i in 0..steps) {
|
||||
val v = i * major / 2f
|
||||
val isMajor = i % 2 == 0
|
||||
val deg = dialAngle(v, max)
|
||||
drawLine(if (isMajor) tick else minor, polar(cx, cy, r - (if (isMajor) 14.dp else 7.dp).toPx(), deg), polar(cx, cy, r - 2.dp.toPx(), deg),
|
||||
strokeWidth = (if (isMajor) 2.5f else 1.2f).dp.toPx())
|
||||
if (isMajor) {
|
||||
val layout = measurer.measure(label(v), labelStyle)
|
||||
val p = polar(cx, cy, r - 27.dp.toPx(), deg)
|
||||
drawText(layout, topLeft = Offset(p.x - layout.size.width / 2f, p.y - layout.size.height / 2f))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun DrawScope.needle(cx: Float, cy: Float, len: Float, deg: Float, color: Color, hub: Color) {
|
||||
drawLine(color, Offset(cx, cy), polar(cx, cy, len, deg), strokeWidth = 4.dp.toPx(), cap = StrokeCap.Round)
|
||||
drawCircle(hub, radius = 7.dp.toPx(), center = Offset(cx, cy))
|
||||
}
|
||||
|
||||
private fun speedValue(t: Telemetry, unit: SpeedUnit): Float = (t.speedKmh ?: 0f) * unit.perKmh
|
||||
|
||||
private fun speedScale(speed: Float, unit: SpeedUnit): Float =
|
||||
if (unit == SpeedUnit.MPH) (if (speed > 130f) 200f else 140f) else (if (speed > 210f) 320f else 220f)
|
||||
|
||||
private fun rpmScale(t: Telemetry): Float = max(t.maxRpm ?: 9000f, t.rpm ?: 0f)
|
||||
|
||||
private fun speedText(t: Telemetry, unit: SpeedUnit) = t.speedKmh?.let { "%.0f".format(it * unit.perKmh) } ?: "–"
|
||||
|
||||
@Composable
|
||||
private fun unitAndGear(t: Telemetry, unit: SpeedUnit) = "${unit.label} · ${stringResource(R.string.stats_gear)} ${t.gear ?: "–"}"
|
||||
|
||||
@Composable
|
||||
private fun SpeedometerDash(t: Telemetry, unit: SpeedUnit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val accent = LocalPalette.current.primary
|
||||
Row(Modifier.fillMaxWidth().height(DASH_H), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
StatsCard(stringResource(R.string.stats_speed), Modifier.weight(1.55f).fillMaxHeight()) {
|
||||
Box(Modifier.fillMaxWidth().weight(1f)) {
|
||||
SpeedDial(t, unit, Modifier.fillMaxSize())
|
||||
Column(Modifier.align(Alignment.BottomCenter), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Text(speedText(t, unit), fontSize = 44.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = accent)
|
||||
Text(unitAndGear(t, unit), fontSize = 16.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = colors.onBackground)
|
||||
Text(t.rpm?.let { "%,.0f rpm".format(it) } ?: "", fontSize = 11.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
Column(Modifier.weight(1f).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
StatsCard(stringResource(R.string.stats_pedals), Modifier.fillMaxWidth().weight(1f)) { Pedals(t, Modifier.fillMaxWidth().weight(1f)) }
|
||||
if (t.gLat != null && t.gLon != null) {
|
||||
StatsCard(stringResource(R.string.stats_gforce), Modifier.fillMaxWidth().weight(1f)) { GForce(t, Modifier.fillMaxWidth().weight(1f)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SpeedDial(t: Telemetry, unit: SpeedUnit, modifier: Modifier) {
|
||||
val pal = LocalPalette.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val measurer = rememberTextMeasurer()
|
||||
val labelStyle = TextStyle(color = colors.onSurfaceVariant, fontSize = 11.sp, fontFamily = FontFamily.Monospace)
|
||||
val speed = speedValue(t, unit)
|
||||
val vmax = speedScale(speed, unit)
|
||||
val rpmFraction = ((t.rpm ?: 0f) / rpmScale(t)).coerceIn(0f, 1f)
|
||||
Canvas(modifier) {
|
||||
val r = min(size.width * 0.42f, size.height * 0.47f)
|
||||
val cx = size.width / 2f
|
||||
val cy = r + 12.dp.toPx()
|
||||
dialFace(cx, cy, r, vmax, 20f, { "%.0f".format(it) }, measurer, labelStyle, colors.onBackground, colors.onSurfaceVariant, pal.line, null, StatsColors.brake)
|
||||
val rr = r + 9.dp.toPx()
|
||||
val box = Size(2 * rr, 2 * rr)
|
||||
val tl = Offset(cx - rr, cy - rr)
|
||||
drawArc(pal.line, DIAL_START - 90f, DIAL_SWEEP, false, topLeft = tl, size = box, style = Stroke(5.dp.toPx(), cap = StrokeCap.Round))
|
||||
if (rpmFraction > 0f) drawArc(if (rpmFraction > 0.9f) StatsColors.brake else pal.primary, DIAL_START - 90f, DIAL_SWEEP * rpmFraction, false,
|
||||
topLeft = tl, size = box, style = Stroke(5.dp.toPx(), cap = StrokeCap.Round))
|
||||
needle(cx, cy, r - 16.dp.toPx(), dialAngle(speed, vmax), colors.onBackground, pal.primary)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Pedals(t: Telemetry, modifier: Modifier) {
|
||||
Row(modifier, horizontalArrangement = Arrangement.SpaceEvenly) {
|
||||
PedalBar("THR", t.throttle, StatsColors.throttle)
|
||||
PedalBar("BRK", t.brake, StatsColors.brake)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PedalBar(label: String, value: Float?, color: Color) {
|
||||
val pal = LocalPalette.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Column(Modifier.fillMaxHeight(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
Text(value?.let { "${(it * 100).roundToInt()}%" } ?: "–", fontSize = 11.sp, fontFamily = FontFamily.Monospace, color = colors.onBackground)
|
||||
Box(Modifier.weight(1f).width(26.dp).clip(RoundedCornerShape(6.dp)).background(pal.line)) {
|
||||
Box(Modifier.fillMaxWidth().fillMaxHeight((value ?: 0f).coerceIn(0f, 1f)).align(Alignment.BottomCenter).background(color))
|
||||
}
|
||||
Text(label, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GForce(t: Telemetry, modifier: Modifier) {
|
||||
val pal = LocalPalette.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val g = kotlin.math.hypot(t.gLat ?: 0f, t.gLon ?: 0f)
|
||||
Box(modifier) {
|
||||
Canvas(Modifier.fillMaxSize()) {
|
||||
val steerH = if (t.steer != null) 10.dp.toPx() else 0f
|
||||
val r = min(size.width / 2f, (size.height - steerH) / 2f) - 2.dp.toPx()
|
||||
val cx = size.width / 2f
|
||||
val cy = (size.height - steerH) / 2f
|
||||
for (k in listOf(1f, 0.62f, 0.24f)) drawCircle(pal.line, radius = r * k, center = Offset(cx, cy), style = Stroke(1.dp.toPx()))
|
||||
drawLine(pal.line, Offset(cx - r, cy), Offset(cx + r, cy), strokeWidth = 1.dp.toPx())
|
||||
drawLine(pal.line, Offset(cx, cy - r), Offset(cx, cy + r), strokeWidth = 1.dp.toPx())
|
||||
val gx = (t.gLat ?: 0f).coerceIn(-2f, 2f) / 2f * r
|
||||
val gy = (t.gLon ?: 0f).coerceIn(-2f, 2f) / 2f * r
|
||||
drawCircle(colors.onBackground, radius = 6.dp.toPx(), center = Offset(cx + gx, cy - gy))
|
||||
t.steer?.let { s ->
|
||||
val y = size.height - 3.dp.toPx()
|
||||
drawLine(pal.line, Offset(cx - r, y), Offset(cx + r, y), strokeWidth = 5.dp.toPx(), cap = StrokeCap.Round)
|
||||
drawLine(pal.primary, Offset(cx, y), Offset(cx + s * r, y), strokeWidth = 5.dp.toPx(), cap = StrokeCap.Round)
|
||||
}
|
||||
}
|
||||
Text("%.1f G".format(g), fontSize = 11.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant, modifier = Modifier.align(Alignment.TopEnd))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CircuitDash(t: Telemetry, unit: SpeedUnit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val accent = LocalPalette.current.primary
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
StatsCard(null, Modifier.fillMaxWidth()) { ShiftLights(t, Modifier.fillMaxWidth().height(20.dp)) }
|
||||
Row(Modifier.fillMaxWidth().height(DASH_H - 48.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
StatsCard(stringResource(R.string.stats_timing), Modifier.weight(1f).fillMaxHeight()) {
|
||||
KvRow(stringResource(R.string.bottom_telemetry_lap), t.lap?.let { lap -> t.laps?.let { "$lap / $it" } ?: "$lap" } ?: "–")
|
||||
KvRow(stringResource(R.string.bottom_telemetry_position), t.position?.let { "P$it" } ?: "–")
|
||||
KvRow(stringResource(R.string.bottom_telemetry_this_lap), t.currentLapS?.let { lapTime(it) } ?: "–")
|
||||
KvRow(stringResource(R.string.bottom_telemetry_last_lap), t.lastLapS?.let { lapTime(it) } ?: "–")
|
||||
t.bestLapS?.let { KvRow(stringResource(R.string.stats_best_lap), lapTime(it), accent) }
|
||||
}
|
||||
StatsCard("", Modifier.weight(1.2f).fillMaxHeight()) {
|
||||
Column(Modifier.fillMaxWidth().weight(1f), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
|
||||
Text(speedText(t, unit), fontSize = 72.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = accent)
|
||||
Text(unitAndGear(t, unit), fontSize = 24.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = colors.onBackground)
|
||||
Text(t.rpm?.let { rpm -> t.maxRpm?.let { "%,.0f / %,.0f rpm".format(rpm, it) } ?: "%,.0f rpm".format(rpm) } ?: "",
|
||||
fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
val fuel = t.fuel
|
||||
val tires = t.tireTempsC?.takeIf { it.size == 4 }
|
||||
if (fuel != null || tires != null) Column(Modifier.weight(0.9f).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
if (fuel != null) StatsCard(stringResource(R.string.bottom_telemetry_fuel), Modifier.fillMaxWidth().weight(1f)) {
|
||||
Bar(fuel, colors.onBackground, Modifier.fillMaxWidth().height(14.dp))
|
||||
Text("${(fuel * 100).roundToInt()}%", fontSize = 13.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant)
|
||||
}
|
||||
if (tires != null) StatsCard(stringResource(R.string.stats_tires), Modifier.fillMaxWidth().weight(1.3f)) { Tires(tires, Modifier.fillMaxWidth().weight(1f)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ShiftLights(t: Telemetry, modifier: Modifier) {
|
||||
val pal = LocalPalette.current
|
||||
val ratio = ((t.rpm ?: 0f) / rpmScale(t)).coerceIn(0f, 1f)
|
||||
val lit = (((ratio - 0.6f) / 0.35f).coerceIn(0f, 1f) * 15).roundToInt()
|
||||
val flash = ratio > 0.95f && (System.currentTimeMillis() / 120) % 2 == 0L
|
||||
Canvas(modifier) {
|
||||
val step = size.width / 15f
|
||||
val r = min(size.height / 2f, step / 2f - 2.dp.toPx())
|
||||
for (i in 0 until 15) {
|
||||
val c = when {
|
||||
flash -> pal.primary
|
||||
i >= lit -> pal.line
|
||||
i < 5 -> StatsColors.shiftGreen
|
||||
i < 10 -> StatsColors.warn
|
||||
i < 13 -> StatsColors.brake
|
||||
else -> pal.primary
|
||||
}
|
||||
drawCircle(c, radius = r, center = Offset(step * i + step / 2f, size.height / 2f))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun KvRow(label: String, value: String, valueColor: Color = MaterialTheme.colorScheme.onBackground) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(label, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(1f), maxLines = 1)
|
||||
Text(value, fontSize = 15.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = valueColor, maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Bar(fraction: Float, color: Color, modifier: Modifier) {
|
||||
Box(modifier.clip(RoundedCornerShape(5.dp)).background(LocalPalette.current.line)) {
|
||||
Box(Modifier.fillMaxWidth(fraction.coerceIn(0f, 1f)).fillMaxHeight().background(color))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Tires(tires: List<Float>, modifier: Modifier) {
|
||||
Column(modifier, verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Row(Modifier.fillMaxWidth().weight(1f), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
TireBox(tires[0], Modifier.weight(1f).fillMaxHeight())
|
||||
TireBox(tires[1], Modifier.weight(1f).fillMaxHeight())
|
||||
}
|
||||
Row(Modifier.fillMaxWidth().weight(1f), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
TireBox(tires[2], Modifier.weight(1f).fillMaxHeight())
|
||||
TireBox(tires[3], Modifier.weight(1f).fillMaxHeight())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TireBox(c: Float, modifier: Modifier) {
|
||||
val bg = when {
|
||||
c > 100f -> Color(0xFF5A2A2C)
|
||||
c < 70f -> Color(0xFF1D3550)
|
||||
else -> Color(0xFF23352B)
|
||||
}
|
||||
Box(modifier.clip(RoundedCornerShape(6.dp)).background(bg), contentAlignment = Alignment.Center) {
|
||||
Text("%.0f".format(c), fontSize = 13.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = MaterialTheme.colorScheme.onBackground)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TraceDash(t: Telemetry, trace: TraceData, unit: SpeedUnit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
StatsCard(stringResource(R.string.stats_trace), Modifier.fillMaxWidth().height(168.dp)) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(14.dp)) {
|
||||
Legend(StatsColors.throttle, "${stringResource(R.string.stats_throttle)} ${t.throttle?.let { (it * 100).roundToInt() } ?: 0}%")
|
||||
Legend(StatsColors.brake, "${stringResource(R.string.stats_brake)} ${t.brake?.let { (it * 100).roundToInt() } ?: 0}%")
|
||||
}
|
||||
TraceChart(listOf(trace.throttle to StatsColors.throttle, trace.brake to StatsColors.brake), 1f, Modifier.fillMaxWidth().weight(1f))
|
||||
}
|
||||
val speeds = trace.speed.map { it * unit.perKmh }
|
||||
val top = max(if (unit == SpeedUnit.MPH) 125f else 200f, (speeds.maxOrNull() ?: 0f) * 1.1f)
|
||||
StatsCard(stringResource(R.string.stats_speed_chart, unit.label), Modifier.fillMaxWidth().height(114.dp)) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(14.dp)) {
|
||||
Legend(StatsColors.speed, "${stringResource(R.string.stats_speed)} ${speedText(t, unit)}")
|
||||
Text("0 – %.0f".format(top), fontSize = 11.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant)
|
||||
}
|
||||
TraceChart(listOf(speeds to StatsColors.speed), top, Modifier.fillMaxWidth().weight(1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Legend(color: Color, text: String) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp)) {
|
||||
Box(Modifier.size(8.dp).clip(CircleShape).background(color))
|
||||
Text(text, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = MaterialTheme.colorScheme.onBackground, maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TraceChart(series: List<Pair<List<Float>, Color>>, max: Float, modifier: Modifier) {
|
||||
val pal = LocalPalette.current
|
||||
Canvas(modifier) {
|
||||
for (k in listOf(0f, 0.5f, 1f)) {
|
||||
val y = size.height - k * size.height
|
||||
drawLine(pal.line, Offset(0f, y), Offset(size.width, y), strokeWidth = 1.dp.toPx())
|
||||
}
|
||||
for ((values, color) in series) {
|
||||
if (values.size < 2) continue
|
||||
val path = Path()
|
||||
val offset = TRACE_N - values.size
|
||||
values.forEachIndexed { i, v ->
|
||||
val x = (i + offset) / (TRACE_N - 1f) * size.width
|
||||
val y = size.height - (v / max).coerceIn(0f, 1f) * size.height
|
||||
if (i == 0) path.moveTo(x, y) else path.lineTo(x, y)
|
||||
}
|
||||
drawPath(path, color, style = Stroke(width = 2.dp.toPx(), cap = StrokeCap.Round, join = StrokeJoin.Round))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DialsDash(t: Telemetry, unit: SpeedUnit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val rpmMax = (rpmScale(t) / 1000f).let { kotlin.math.ceil(it) * 1000f }
|
||||
val hasExtras = t.lights != null || t.turboBar != null || t.engineTempC != null || t.oilTempC != null
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Row(Modifier.fillMaxWidth().height(if (hasExtras) DASH_H - 56.dp else DASH_H), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
StatsCard("", Modifier.weight(1f).fillMaxHeight()) {
|
||||
val speed = speedValue(t, unit)
|
||||
ArcDial(speed, speedScale(speed, unit), if (unit == SpeedUnit.MPH) 20f else 40f, { "%.0f".format(it) }, null,
|
||||
speedText(t, unit), unit.label, Modifier.fillMaxWidth().weight(1f))
|
||||
}
|
||||
StatsCard("", Modifier.weight(1f).fillMaxHeight()) {
|
||||
ArcDial(t.rpm ?: 0f, rpmMax, 1000f, { "%.0f".format(it / 1000f) }, t.maxRpm?.let { it * 0.9f },
|
||||
t.rpm?.let { "%,.0f".format(it) } ?: "–", "rpm × 1000 · ${t.gear ?: "–"}", Modifier.fillMaxWidth().weight(1f))
|
||||
}
|
||||
}
|
||||
if (hasExtras) StatsCard(stringResource(R.string.stats_lights), Modifier.fillMaxWidth()) {
|
||||
Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
t.lights?.let { on ->
|
||||
Lamp(stringResource(R.string.stats_lamp_shift), on and GameTelemetry.DL_SHIFT != 0, LocalPalette.current.primary)
|
||||
Lamp(stringResource(R.string.stats_lamp_handbrake), on and GameTelemetry.DL_HANDBRAKE != 0, StatsColors.brake)
|
||||
Lamp(stringResource(R.string.stats_lamp_pit), on and GameTelemetry.DL_PITSPEED != 0, StatsColors.warn)
|
||||
Lamp(stringResource(R.string.stats_lamp_tc), on and GameTelemetry.DL_TC != 0, StatsColors.warn)
|
||||
Lamp(stringResource(R.string.stats_lamp_abs), on and GameTelemetry.DL_ABS != 0, StatsColors.warn)
|
||||
}
|
||||
t.turboBar?.let { Lamp(stringResource(R.string.stats_turbo, "%.1f".format(it)), false, colors.onBackground) }
|
||||
t.engineTempC?.let { Lamp(stringResource(R.string.stats_engine_temp, "%.0f".format(it)), false, colors.onBackground) }
|
||||
t.oilTempC?.let { Lamp(stringResource(R.string.stats_oil_temp, "%.0f".format(it)), false, colors.onBackground) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ArcDial(value: Float, max: Float, major: Float, label: (Float) -> String, red: Float?, readout: String, unit: String, modifier: Modifier) {
|
||||
val pal = LocalPalette.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val measurer = rememberTextMeasurer()
|
||||
val labelStyle = TextStyle(color = colors.onSurfaceVariant, fontSize = 11.sp, fontFamily = FontFamily.Monospace)
|
||||
Box(modifier) {
|
||||
Canvas(Modifier.fillMaxSize()) {
|
||||
val r = min(size.width * 0.46f, size.height * 0.5f)
|
||||
val cx = size.width / 2f
|
||||
val cy = r + 6.dp.toPx()
|
||||
dialFace(cx, cy, r, max, major, label, measurer, labelStyle, colors.onBackground, colors.onSurfaceVariant, pal.line, red, StatsColors.brake)
|
||||
needle(cx, cy, r - 18.dp.toPx(), dialAngle(value, max), colors.onBackground, pal.primary)
|
||||
}
|
||||
Column(Modifier.align(Alignment.BottomCenter), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Text(readout, fontSize = 22.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = colors.onBackground)
|
||||
Text(unit, fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Lamp(label: String, on: Boolean, color: Color) {
|
||||
val pal = LocalPalette.current
|
||||
val shape = RoundedCornerShape(8.dp)
|
||||
Text(label, fontSize = 12.sp, fontFamily = FontFamily.Monospace, fontWeight = if (on) FontWeight.Bold else FontWeight.Normal,
|
||||
color = if (on) MaterialTheme.colorScheme.background else MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1,
|
||||
modifier = Modifier.clip(shape).background(if (on) color else Color.Transparent).border(1.dp, if (on) color else pal.line, shape)
|
||||
.padding(horizontal = 10.dp, vertical = 4.dp))
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GlanceDash(t: Telemetry, unit: SpeedUnit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val accent = LocalPalette.current.primary
|
||||
val ratio = ((t.rpm ?: 0f) / rpmScale(t)).coerceIn(0f, 1f)
|
||||
Row(Modifier.fillMaxWidth().height(DASH_H), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
EdgeBar(t.throttle, StatsColors.throttle)
|
||||
StatsCard("", Modifier.weight(1f).fillMaxHeight()) {
|
||||
Bar(ratio, if (ratio > 0.9f) StatsColors.brake else accent, Modifier.fillMaxWidth().height(14.dp))
|
||||
Column(Modifier.fillMaxWidth().weight(1f), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
|
||||
Text(speedText(t, unit), fontSize = 110.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = accent, lineHeight = 112.sp)
|
||||
Text(unitAndGear(t, unit), fontSize = 34.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = colors.onBackground)
|
||||
}
|
||||
}
|
||||
EdgeBar(t.brake, StatsColors.brake)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EdgeBar(value: Float?, color: Color) {
|
||||
Box(Modifier.width(14.dp).fillMaxHeight().clip(RoundedCornerShape(5.dp)).background(LocalPalette.current.line)) {
|
||||
Box(Modifier.fillMaxWidth().fillMaxHeight((value ?: 0f).coerceIn(0f, 1f)).align(Alignment.BottomCenter).background(color))
|
||||
}
|
||||
}
|
||||
|
||||
/** War Thunder's own labels the Flight layout places; others stay in the list. */
|
||||
internal object FlightLabels {
|
||||
const val IAS = "IAS, km/h"
|
||||
const val ALTITUDE = "H, m"
|
||||
const val G = "Ny"
|
||||
const val FUEL = "Mfuel, kg"
|
||||
const val THROTTLE = "throttle 1, %"
|
||||
|
||||
fun drawable(rows: List<Pair<String, String>>): Boolean = rows.any { it.first == IAS || it.first == ALTITUDE }
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun FlightDash(rows: List<Pair<String, String>>) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val v = rows.toMap()
|
||||
fun num(key: String) = v[key]?.toFloatOrNull()
|
||||
Row(Modifier.fillMaxWidth().height(DASH_H), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
StatsCard(FlightLabels.IAS, Modifier.weight(1f).fillMaxHeight()) {
|
||||
num(FlightLabels.IAS)?.let { Tape(it, 10f, 50f, Modifier.fillMaxWidth().weight(1f)) } ?: Text("–", color = colors.onSurfaceVariant)
|
||||
}
|
||||
Column(Modifier.weight(1.3f).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
StatsCard(FlightLabels.THROTTLE, Modifier.fillMaxWidth().weight(1f)) {
|
||||
val thr = num(FlightLabels.THROTTLE)
|
||||
Bar((thr ?: 0f) / 110f, StatsColors.throttle, Modifier.fillMaxWidth().height(16.dp))
|
||||
Text(thr?.let { "%.0f%%".format(it) } ?: "–", fontSize = 13.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant)
|
||||
}
|
||||
StatsCard(FlightLabels.G, Modifier.fillMaxWidth().weight(1f)) {
|
||||
Text(num(FlightLabels.G)?.let { "%.1f".format(it) } ?: "–", fontSize = 34.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace,
|
||||
color = colors.onBackground)
|
||||
num(FlightLabels.FUEL)?.let { Text("${FlightLabels.FUEL} %.0f".format(it), fontSize = 12.sp, color = colors.onSurfaceVariant) }
|
||||
}
|
||||
}
|
||||
StatsCard(FlightLabels.ALTITUDE, Modifier.weight(1f).fillMaxHeight()) {
|
||||
num(FlightLabels.ALTITUDE)?.let { Tape(it, 100f, 500f, Modifier.fillMaxWidth().weight(1f)) } ?: Text("–", color = colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Tape(value: Float, step: Float, every: Float, modifier: Modifier) {
|
||||
val pal = LocalPalette.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val measurer = rememberTextMeasurer()
|
||||
val small = TextStyle(color = colors.onSurfaceVariant, fontSize = 11.sp, fontFamily = FontFamily.Monospace)
|
||||
val big = TextStyle(color = colors.onBackground, fontSize = 18.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace)
|
||||
Canvas(modifier) {
|
||||
val cy = size.height / 2f
|
||||
val px = (size.height / 2f) / (step * 4f)
|
||||
val boxH = 32.dp.toPx()
|
||||
var m = floor((value - step * 5f) / step) * step
|
||||
while (m < value + step * 6f) {
|
||||
val y = cy - (m - value) * px
|
||||
if (y in 0f..size.height) {
|
||||
val labelled = abs((m / every).roundToInt() * every - m) < 0.01f
|
||||
drawLine(colors.onSurfaceVariant, Offset(size.width * 0.74f, y), Offset(size.width, y), strokeWidth = (if (labelled) 2.5f else 1f).dp.toPx())
|
||||
if (labelled && abs(y - cy) > boxH * 0.75f) {
|
||||
val layout = measurer.measure("%.0f".format(m), small)
|
||||
drawText(layout, topLeft = Offset(size.width * 0.70f - layout.size.width, y - layout.size.height / 2f))
|
||||
}
|
||||
}
|
||||
m += step
|
||||
}
|
||||
drawRoundRect(pal.primary, topLeft = Offset(1.dp.toPx(), cy - boxH / 2f), size = Size(size.width - 2.dp.toPx(), boxH),
|
||||
cornerRadius = CornerRadius(8.dp.toPx()), style = Stroke(2.dp.toPx()))
|
||||
val layout = measurer.measure("%.0f".format(value), big)
|
||||
drawText(layout, topLeft = Offset(size.width / 2f - layout.size.width / 2f, cy - layout.size.height / 2f))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun ShipDash(e: GameStatusFiles.Elite) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Row(Modifier.fillMaxWidth().height(210.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
StatsCard(stringResource(R.string.stats_power), Modifier.weight(1.2f).fillMaxHeight()) {
|
||||
e.pips?.takeIf { it.size == 3 }?.let { Pips(it, Modifier.fillMaxWidth().weight(1f)) } ?: Text("–", color = colors.onSurfaceVariant)
|
||||
}
|
||||
Column(Modifier.weight(1f).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
StatsCard(stringResource(R.string.stats_fuel_t), Modifier.fillMaxWidth().weight(1f)) {
|
||||
e.fuelMain?.let { Text(stringResource(R.string.stats_fuel_main, "%.1f".format(it)), fontSize = 15.sp, fontWeight = FontWeight.Bold,
|
||||
fontFamily = FontFamily.Monospace, color = colors.onBackground) }
|
||||
e.fuelReserve?.let { Text(stringResource(R.string.stats_fuel_reserve, "%.2f".format(it)), fontSize = 12.sp, color = colors.onSurfaceVariant) }
|
||||
}
|
||||
StatsCard("", Modifier.fillMaxWidth().weight(1f)) {
|
||||
e.cargo?.let { KvRow(stringResource(R.string.bottom_telemetry_cargo), "%.0f t".format(it)) }
|
||||
e.legal?.let { KvRow(stringResource(R.string.bottom_telemetry_legal), it, if (it == "Clean") StatsColors.gpu else StatsColors.warn) }
|
||||
e.balance?.let { KvRow(stringResource(R.string.bottom_telemetry_balance), "%,d CR".format(it)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Pips(pips: List<Int>, modifier: Modifier) {
|
||||
val pal = LocalPalette.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val measurer = rememberTextMeasurer()
|
||||
val style = TextStyle(color = colors.onSurfaceVariant, fontSize = 12.sp, fontWeight = FontWeight.Bold)
|
||||
val names = listOf("SYS", "ENG", "WEP")
|
||||
Canvas(modifier) {
|
||||
val colW = size.width / 3f
|
||||
val pipW = colW * 0.62f
|
||||
val labelH = 18.dp.toPx()
|
||||
val pipH = (size.height - labelH) / 4f - 4.dp.toPx()
|
||||
for (col in 0 until 3) {
|
||||
val x = col * colW + (colW - pipW) / 2f
|
||||
// Status.json counts half pips: 0..8 per system.
|
||||
val value = pips[col] / 2f
|
||||
for (i in 0 until 4) {
|
||||
val y = size.height - labelH - (i + 1) * (pipH + 4.dp.toPx())
|
||||
drawRoundRect(pal.line, topLeft = Offset(x, y), size = Size(pipW, pipH), cornerRadius = CornerRadius(4.dp.toPx()))
|
||||
val fill = (value - i).coerceIn(0f, 1f)
|
||||
if (fill > 0f) drawRoundRect(pal.primary, topLeft = Offset(x, y), size = Size(pipW * fill, pipH), cornerRadius = CornerRadius(4.dp.toPx()))
|
||||
}
|
||||
val layout = measurer.measure(names[col], style)
|
||||
drawText(layout, topLeft = Offset(col * colW + colW / 2f - layout.size.width / 2f, size.height - layout.size.height))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.RowScope
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.drawBehind
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Size
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Path
|
||||
import androidx.compose.ui.graphics.StrokeCap
|
||||
import androidx.compose.ui.graphics.StrokeJoin
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
|
||||
import androidx.compose.ui.graphics.lerp
|
||||
import androidx.compose.ui.graphics.nativeCanvas
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.hud.DroidDeckMark
|
||||
import com.droiddeck.launcher.hud.HudMetrics
|
||||
import com.droiddeck.launcher.session.StatsStrip
|
||||
import kotlin.math.max
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/** FusionHUD's metric colors, so the bottom screen reads like the HUD on the top screen. */
|
||||
internal object StatsColors {
|
||||
val cpu = Color(0xFF58A6FF)
|
||||
val gpu = Color(0xFF5EE08A)
|
||||
val ram = Color(0xFFFF7BC0)
|
||||
val bat = Color(0xFFFFAB5E)
|
||||
// Throttle and brake stay apart for red-green colour blindness (checked against the dark surface).
|
||||
val throttle = Color(0xFF14A39A)
|
||||
val brake = Color(0xFFE5484D)
|
||||
val speed = Color(0xFF2E8FD6)
|
||||
val warn = Color(0xFFF2C94C)
|
||||
val shiftGreen = Color(0xFF2FB36A)
|
||||
val badge = Color(0xFF0B0D10)
|
||||
}
|
||||
|
||||
/** The last [capacity] readings, oldest first. */
|
||||
internal class History(private val capacity: Int) {
|
||||
private val values = ArrayDeque<Float>(capacity)
|
||||
fun add(v: Float) {
|
||||
if (values.size == capacity) values.removeFirst()
|
||||
values.addLast(v)
|
||||
}
|
||||
fun snapshot(): List<Float> = values.toList()
|
||||
}
|
||||
|
||||
private val MARK_RATIO = DroidDeckMark.widthFor(1f)
|
||||
|
||||
/** The DroidDeck mark (the split D with the blue orb), the same artwork the HUD draws. */
|
||||
@Composable
|
||||
internal fun DroidDeckLogo(height: Dp, modifier: Modifier = Modifier, body: Color = Color.White, orb: Color = LocalPalette.current.primary) {
|
||||
Canvas(modifier.size(height * MARK_RATIO, height)) {
|
||||
val b = body.toArgb()
|
||||
val o = orb.toArgb()
|
||||
drawIntoCanvas { DroidDeckMark.draw(it.nativeCanvas, 0f, 0f, size.height, b, o) }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LogoBadge(size: Dp) {
|
||||
val shape = RoundedCornerShape(size * 0.22f)
|
||||
Box(Modifier.size(size).clip(shape).background(StatsColors.badge).border(2.dp, LocalPalette.current.primary, shape), contentAlignment = Alignment.Center) {
|
||||
DroidDeckLogo(size * 0.62f)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LogoHeader(clock: String) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.padding(horizontal = 2.dp)) {
|
||||
DroidDeckLogo(16.dp)
|
||||
Text("DroidDeck", fontSize = 13.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
|
||||
if (clock.isNotEmpty()) Text("· $clock", fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun Sparkline(values: List<Float>, min: Float, max: Float, color: Color, modifier: Modifier) {
|
||||
Canvas(modifier) {
|
||||
if (values.size < 2 || max <= min) return@Canvas
|
||||
val path = Path()
|
||||
values.forEachIndexed { i, v ->
|
||||
val x = i / (values.size - 1f) * size.width
|
||||
val y = size.height - ((v - min) / (max - min)).coerceIn(0f, 1f) * (size.height - 2f) - 1f
|
||||
if (i == 0) path.moveTo(x, y) else path.lineTo(x, y)
|
||||
}
|
||||
drawPath(path, color, style = Stroke(width = 2.dp.toPx(), cap = StrokeCap.Round, join = StrokeJoin.Round))
|
||||
}
|
||||
}
|
||||
|
||||
/** A readout card: dark surface, a thin accent edge and the DroidDeck mark before the title ("" = mark only). */
|
||||
@Composable
|
||||
internal fun StatsCard(title: String?, modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit) {
|
||||
val pal = LocalPalette.current
|
||||
val shape = RoundedCornerShape(14.dp)
|
||||
Column(
|
||||
modifier.clip(shape).background(pal.surface).border(1.dp, pal.primary.copy(alpha = 0.22f), shape).padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
if (title != null) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
DroidDeckLogo(12.dp, body = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
if (title.isNotEmpty()) Text(title.uppercase(), fontSize = 11.sp, fontWeight = FontWeight.SemiBold, color = pal.primary, letterSpacing = 0.6.sp,
|
||||
maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
content()
|
||||
}
|
||||
}
|
||||
|
||||
/** What the top strip shows; histories hold one reading a second, oldest first. */
|
||||
internal class StripData(
|
||||
val fps: Float?,
|
||||
val device: HudMetrics.Snapshot?,
|
||||
val fpsHistory: List<Float>,
|
||||
val cpuHistory: List<Float>,
|
||||
val gpuHistory: List<Float>,
|
||||
val wattsHistory: List<Float>,
|
||||
val clock: String,
|
||||
)
|
||||
|
||||
private fun percentTemp(percent: Int?, temp: Int?): String =
|
||||
listOfNotNull(percent?.let { "$it%" }, temp?.let { "$it°" }).joinToString(" · ").ifEmpty { "–" }
|
||||
|
||||
private fun batteryText(s: HudMetrics.Snapshot?): String =
|
||||
listOfNotNull(s?.battery?.percent?.let { "$it%" }, s?.battery?.watts?.takeIf { it > 0f }?.let { "%.1f W".format(it) }).joinToString(" · ").ifEmpty { "–" }
|
||||
|
||||
private fun fpsText(fps: Float?): String = fps?.takeIf { it > 0f }?.let { "%.1f".format(it) } ?: "–"
|
||||
|
||||
/** The top strip; a tap moves to the next style. */
|
||||
@Composable
|
||||
internal fun StatsStripView(style: StatsStrip, d: StripData, onTap: () -> Unit) {
|
||||
Box(Modifier.fillMaxWidth().clickable(onClick = onTap)) {
|
||||
when (style) {
|
||||
StatsStrip.PANEL -> PanelStrip(d)
|
||||
StatsStrip.TILES -> TilesStrip(d)
|
||||
StatsStrip.RINGS -> RingsStrip(d)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PanelStrip(d: StripData) {
|
||||
val pal = LocalPalette.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val accent = pal.primary
|
||||
val shape = RoundedCornerShape(18.dp)
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clip(shape).background(pal.surface).border(2.dp, accent, shape).padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
LogoBadge(40.dp)
|
||||
Column(Modifier.widthIn(min = 84.dp)) {
|
||||
Row(verticalAlignment = Alignment.Bottom) {
|
||||
Text(fpsText(d.fps), fontSize = 30.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = accent, maxLines = 1)
|
||||
Text(" fps", fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(bottom = 4.dp))
|
||||
}
|
||||
Text(d.fps?.takeIf { it > 0f }?.let { "%.1f ms".format(1000f / it) } ?: stringResource(R.string.stats_fps_needs_hud),
|
||||
fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant, maxLines = 1)
|
||||
}
|
||||
Sparkline(d.fpsHistory.map { 1000f / max(it, 1f) }, 8f, 34f, lerp(accent, Color.White, 0.3f), Modifier.weight(1f).height(44.dp))
|
||||
Column(verticalArrangement = Arrangement.spacedBy(1.dp)) {
|
||||
MetricRow("CPU", percentTemp(d.device?.cpuPercent, d.device?.cpuTempC), StatsColors.cpu)
|
||||
MetricRow("GPU", percentTemp(d.device?.gpuPercent, d.device?.gpuTempC), StatsColors.gpu)
|
||||
MetricRow("RAM", d.device?.let { "${it.ramPercent.roundToInt()}%" } ?: "–", StatsColors.ram)
|
||||
MetricRow("BAT", batteryText(d.device), StatsColors.bat)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MetricRow(label: String, value: String, color: Color) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(label, fontSize = 11.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = color, modifier = Modifier.width(36.dp))
|
||||
Text(value, fontSize = 13.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = MaterialTheme.colorScheme.onBackground, maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TilesStrip(d: StripData) {
|
||||
val accent = LocalPalette.current.primary
|
||||
val s = d.device
|
||||
val gpuPercent: Int? = s?.gpuPercent
|
||||
val gpuTemp: Int? = s?.gpuTempC
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
LogoHeader(d.clock)
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
HistoryTile("FPS", accent, fpsText(d.fps), "fps", d.fpsHistory, 75f)
|
||||
HistoryTile("CPU", StatsColors.cpu, s?.cpuPercent?.let { "$it%" } ?: "–", s?.cpuTempC?.let { "$it°" } ?: "", d.cpuHistory, 100f)
|
||||
HistoryTile("GPU", StatsColors.gpu, gpuPercent?.let { "$it%" } ?: gpuTemp?.let { "$it°" } ?: "–",
|
||||
if (gpuPercent != null) gpuTemp?.let { "$it°" } ?: "" else "", d.gpuHistory, 100f)
|
||||
HistoryTile(stringResource(R.string.bottom_telemetry_battery).uppercase(), StatsColors.bat, s?.battery?.percent?.let { "$it%" } ?: "–",
|
||||
s?.battery?.watts?.takeIf { it > 0f }?.let { "%.1fW".format(it) } ?: "", d.wattsHistory, 10f)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RowScope.HistoryTile(label: String, color: Color, value: String, unit: String, history: List<Float>, max: Float) {
|
||||
val pal = LocalPalette.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Column(
|
||||
Modifier.weight(1f).clip(RoundedCornerShape(12.dp)).background(pal.surface)
|
||||
.drawBehind { drawRect(color, topLeft = Offset.Zero, size = Size(size.width, 3.dp.toPx())) }
|
||||
.padding(start = 10.dp, end = 10.dp, top = 9.dp, bottom = 6.dp),
|
||||
) {
|
||||
Text(label, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = color, letterSpacing = 0.8.sp, maxLines = 1)
|
||||
Row(verticalAlignment = Alignment.Bottom) {
|
||||
Text(value, fontSize = 22.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = colors.onBackground, maxLines = 1)
|
||||
if (unit.isNotEmpty()) Text(" $unit", fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, modifier = Modifier.padding(bottom = 3.dp))
|
||||
}
|
||||
Sparkline(history, 0f, max, color, Modifier.fillMaxWidth().height(24.dp))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RingsStrip(d: StripData) {
|
||||
val s = d.device
|
||||
val gpuPercent: Int? = s?.gpuPercent
|
||||
val gpuTemp: Int? = s?.gpuTempC
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
LogoHeader(d.clock)
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
RingTile("CPU", StatsColors.cpu, s?.cpuPercent?.let { it / 100f }, s?.cpuPercent?.let { "$it%" } ?: "–", s?.cpuTempC?.let { "$it °C" } ?: "")
|
||||
RingTile("GPU", StatsColors.gpu, gpuPercent?.let { it / 100f }, gpuPercent?.let { "$it%" } ?: gpuTemp?.let { "$it°" } ?: "–",
|
||||
if (gpuPercent != null) gpuTemp?.let { "$it °C" } ?: "" else "")
|
||||
RingTile("RAM", StatsColors.ram, s?.ramPercent?.let { it / 100f }, s?.let { "${it.ramPercent.roundToInt()}%" } ?: "–",
|
||||
s?.let { "%.1f of %.1f GB".format(it.ramUsedBytes / 1e9, it.ramTotalBytes / 1e9) } ?: "")
|
||||
RingTile(stringResource(R.string.bottom_telemetry_battery).uppercase(), StatsColors.bat, s?.battery?.percent?.let { it / 100f },
|
||||
s?.battery?.percent?.let { "$it%" } ?: "–", s?.battery?.watts?.takeIf { it > 0f }?.let { "%.1f W".format(it) } ?: "")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RowScope.RingTile(label: String, color: Color, fraction: Float?, center: String, sub: String) {
|
||||
val pal = LocalPalette.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Row(
|
||||
Modifier.weight(1f).clip(RoundedCornerShape(12.dp)).background(pal.surface).padding(8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Box(Modifier.size(52.dp), contentAlignment = Alignment.Center) {
|
||||
Canvas(Modifier.fillMaxSize()) {
|
||||
val w = 6.dp.toPx()
|
||||
val tl = Offset(w / 2, w / 2)
|
||||
val sz = Size(size.width - w, size.height - w)
|
||||
drawArc(pal.line, 0f, 360f, false, topLeft = tl, size = sz, style = Stroke(width = w))
|
||||
if (fraction != null) drawArc(color, -90f, (fraction.coerceIn(0f, 1f) * 360f).coerceAtLeast(1f), false, topLeft = tl, size = sz,
|
||||
style = Stroke(width = w, cap = StrokeCap.Round))
|
||||
}
|
||||
Text(center, fontSize = 12.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = colors.onBackground, maxLines = 1)
|
||||
}
|
||||
Column {
|
||||
Text(label, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = color, letterSpacing = 0.8.sp, maxLines = 1)
|
||||
if (sub.isNotEmpty()) Text(sub, fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -142,7 +142,7 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
|
||||
scrim = { if (games.size >= WALL_MIN_GAMES) WallFade() },
|
||||
words = {
|
||||
val runtimeStatus: @Composable () -> Unit = {
|
||||
if (s.busy || !s.ready || (s.available != null && s.available != s.installed)) RuntimeChip(s)
|
||||
if (s.busy || (s.available != null && s.available != s.installed)) RuntimeChip(s)
|
||||
else if (s.integration.suggested && signedIn && !com.droiddeck.launcher.core.PhantomProcessLimit.blocksSteam(s.phantomProcessStatus))
|
||||
IntegrationSuggestion(s.integration, { a.onSteamIntegration(null) }, a.onDismissIntegration)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.RestartAlt
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
@Composable
|
||||
internal fun SteamImportDialog(games: List<String>, onAnswer: (Boolean) -> Unit) {
|
||||
val now = remember { booleanArrayOf(false) }
|
||||
val shown = rememberShown { onAnswer(now[0]) }
|
||||
val close = { shown.targetState = false }
|
||||
val focus = remember { FocusRequester() }
|
||||
LaunchedEffect(Unit) { runCatching { focus.requestFocus() } }
|
||||
val names = if (games.size <= 3) games.joinToString(", ")
|
||||
else stringResource(R.string.steam_import_names_more, games.take(3).joinToString(", "), games.size - 3)
|
||||
AppDialog(shown, close, "steamImport", wide = false, maxWidth = 520.dp) {
|
||||
DialogTitleRow(stringResource(R.string.steam_import_title), close) {
|
||||
Icon(Icons.Filled.RestartAlt, null, tint = LocalPalette.current.signal, modifier = Modifier.size(20.dp))
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.steam_import_body, names),
|
||||
fontSize = 13.sp, lineHeight = 18.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp, androidx.compose.ui.Alignment.End), modifier = Modifier.fillMaxWidth()) {
|
||||
SecondaryButton(stringResource(R.string.steam_import_later)) { now[0] = false; close() }
|
||||
PrimaryButton(stringResource(R.string.steam_import_now), modifier = Modifier.focusRequester(focus), onClick = { now[0] = true; close() })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -124,6 +124,18 @@ internal enum class StepSide {
|
||||
Right,
|
||||
}
|
||||
|
||||
internal fun fitStepSide(preferred: StepSide, pill: Rect, hostWidth: Float, wanted: Float): StepSide {
|
||||
val leftRoom = pill.right
|
||||
val rightRoom = hostWidth - pill.left
|
||||
val room = if (preferred == StepSide.Left) leftRoom else rightRoom
|
||||
val other = if (preferred == StepSide.Left) rightRoom else leftRoom
|
||||
return if (room >= wanted || other <= room) preferred else if (preferred == StepSide.Left) StepSide.Right else StepSide.Left
|
||||
}
|
||||
|
||||
internal fun stepReach(side: StepSide, pill: Rect, hostWidth: Float, width: Int): Pair<Float, Float> =
|
||||
if (side == StepSide.Left) pill.left to (pill.right - width).coerceAtLeast(0f)
|
||||
else pill.right to (pill.left + width).coerceAtMost(hostWidth)
|
||||
|
||||
internal class StepOutScope(private val items: List<Animatable<Float, AnimationVector1D>>, val first: FocusRequester, val open: Boolean, val maxHeight: Dp) {
|
||||
fun Modifier.stepItem(i: Int): Modifier = graphicsLayer {
|
||||
val v = items[i.coerceIn(0, items.lastIndex)].value
|
||||
@@ -141,7 +153,7 @@ private val OutFillet = 10.dp
|
||||
internal fun StepOut(
|
||||
open: Boolean,
|
||||
pill: Rect,
|
||||
side: StepSide,
|
||||
preferredSide: StepSide,
|
||||
accent: Color,
|
||||
onDismiss: () -> Unit,
|
||||
onClosed: () -> Unit,
|
||||
@@ -166,6 +178,7 @@ internal fun StepOut(
|
||||
val opener = remember { arrayOfNulls<GlideSource>(1) }
|
||||
val openNow = androidx.compose.runtime.rememberUpdatedState(open)
|
||||
var moving by remember { mutableStateOf(false) }
|
||||
val placed = remember { arrayOfNulls<Any>(3) }
|
||||
if (moving) VeilRing()
|
||||
val pull = with(density) { OutPull.toPx() }
|
||||
val corner = pillCorner?.let { with(density) { it.toPx() } } ?: minOf(pill.height, pill.width) / 2f
|
||||
@@ -177,13 +190,18 @@ internal fun StepOut(
|
||||
maxOf(hostHeight - pill.bottom - pull, pill.top - pull).coerceAtLeast(44.dp.toPx()).toDp()
|
||||
}
|
||||
val up = measured?.let { pill.bottom + pull + it.height > hostHeight && pill.top - pull - it.height >= 0f } ?: false
|
||||
val wantedW = with(density) { maxWidth.toPx() }
|
||||
val side = fitStepSide(preferredSide, pill, hostWidth, wantedW)
|
||||
val room = if (side == StepSide.Left) pill.right else hostWidth - pill.left
|
||||
val maxW = with(density) { maxWidth.toPx() }.coerceAtMost(room).coerceAtLeast(pill.width)
|
||||
LaunchedEffect(open, measured) {
|
||||
if (!open && !grown) { onClosed(); return@LaunchedEffect }
|
||||
val maxW = wantedW.coerceAtMost(room).coerceAtLeast(pill.width)
|
||||
LaunchedEffect(open, measured, side, pill, hostWidth) {
|
||||
val moved = placed[0] == open && placed[1] == measured
|
||||
val flipped = placed[2] != null && placed[2] != side
|
||||
placed[0] = open; placed[1] = measured; placed[2] = side
|
||||
if (!open && !grown) { if (!moved) onClosed(); return@LaunchedEffect }
|
||||
val c = measured ?: return@LaunchedEffect
|
||||
val rest = if (side == StepSide.Left) pill.left else pill.right
|
||||
val out = if (side == StepSide.Left) (pill.right - c.width).coerceAtLeast(0f) else (pill.left + c.width).coerceAtMost(hostWidth)
|
||||
val (rest, out) = stepReach(side, pill, hostWidth, c.width)
|
||||
if (grown && flipped) edge.snapTo(if (open) out else rest)
|
||||
val boxBottom = pill.bottom + pull + c.height
|
||||
if (open) {
|
||||
if (!grown) {
|
||||
@@ -202,11 +220,6 @@ internal fun StepOut(
|
||||
pieces.forEachIndexed { i, a ->
|
||||
launch { delay(Motion.ms(260 + i * 55).toLong()); a.animateTo(1f, Motion.tw(220)) }
|
||||
}
|
||||
if (inputMode.inputMode == InputMode.Keyboard) launch {
|
||||
delay(Motion.ms(300).toLong())
|
||||
withFrameNanos { }
|
||||
runCatching { first.requestFocus() }
|
||||
}
|
||||
}
|
||||
} else {
|
||||
opener[0]?.let { o -> if (inputMode.inputMode == InputMode.Keyboard) runCatching { o.requester.requestFocus() } }
|
||||
@@ -225,6 +238,13 @@ internal fun StepOut(
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(open, measured) {
|
||||
if (!open || measured == null || inputMode.inputMode != InputMode.Keyboard) return@LaunchedEffect
|
||||
delay(Motion.ms(300).toLong())
|
||||
withFrameNanos { }
|
||||
runCatching { first.requestFocus() }
|
||||
}
|
||||
|
||||
LaunchedEffect(open, grown, inputMode.inputMode) {
|
||||
if (open && grown && inputMode.inputMode == InputMode.Keyboard) { withFrameNanos { }; runCatching { first.requestFocus() } }
|
||||
}
|
||||
@@ -245,8 +265,7 @@ internal fun StepOut(
|
||||
else stepPathRight(path, pill, edge.value, bottom.value, pill.bottom + pull, boxCorner, fillet, corner)
|
||||
if (up) path.transform(Matrix().apply { this[1, 1] = -1f; this[3, 1] = pill.top + pill.bottom })
|
||||
val a = measured?.let { c ->
|
||||
val rest = if (side == StepSide.Left) pill.left else pill.right
|
||||
val out = if (side == StepSide.Left) (pill.right - c.width).coerceAtLeast(0f) else (pill.left + c.width).coerceAtMost(hostWidth)
|
||||
val (rest, out) = stepReach(side, pill, hostWidth, c.width)
|
||||
val down = pill.bottom + pull + c.height - pill.bottom
|
||||
val across = kotlin.math.abs(out - rest)
|
||||
val fd = if (down < 1f) 1f else (bottom.value - pill.bottom) / down
|
||||
|
||||
@@ -39,7 +39,7 @@ internal fun StepsLayer(origin: Offset) {
|
||||
androidx.activity.compose.BackHandler(enabled = Steps.open) { Steps.fold() }
|
||||
key(ask) {
|
||||
StepOut(
|
||||
open = Steps.open, pill = ask.anchor.translate(-origin), side = ask.side, accent = ask.accent,
|
||||
open = Steps.open, pill = ask.anchor.translate(-origin), preferredSide = ask.side, accent = ask.accent,
|
||||
onDismiss = { Steps.fold() }, onClosed = { Steps.closed(ask) },
|
||||
pillCorner = ask.pillCorner, maxWidth = ask.maxWidth, items = ask.items, handle = ask.handle, content = ask.content,
|
||||
)
|
||||
|
||||
@@ -395,7 +395,7 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
|
||||
StoresMotion.step?.let { ask ->
|
||||
key(ask) {
|
||||
StepOut(
|
||||
open = StoresMotion.stepOpen, pill = ask.anchor.translate(-hostAt), side = ask.side, accent = ask.accent,
|
||||
open = StoresMotion.stepOpen, pill = ask.anchor.translate(-hostAt), preferredSide = ask.side, accent = ask.accent,
|
||||
onDismiss = { StoresMotion.fold() }, onClosed = { StoresMotion.closed(ask) },
|
||||
pillCorner = ask.pillCorner, maxWidth = ask.maxWidth, items = ask.items, handle = ask.handle, content = ask.content,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="shortcuts_title">اختصارات الأزرار الفعلية</string>
|
||||
<string name="shortcuts_dd_menu">قائمة DroidDeck</string>
|
||||
<string name="shortcuts_capture">تعيين: %1$s</string>
|
||||
<string name="shortcuts_press">اضغط على زر ثم حرره. يُحفظ التعيين تلقائيًا.</string>
|
||||
<string name="shortcuts_release">أفلت الزر للمتابعة.</string>
|
||||
<string name="shortcuts_detected">%1$s: %2$s</string>
|
||||
<string name="shortcuts_conflict">هذا الزر معيّن بالفعل إلى: %1$s</string>
|
||||
<string name="shortcuts_save">إعادة تعيين</string>
|
||||
<string name="shortcuts_retry">تجربة زر آخر</string>
|
||||
<string name="shortcuts_limitations">قد لا يتوفر زر الشاشة الرئيسية وبعض الأزرار الإضافية.</string>
|
||||
</resources>
|
||||
@@ -81,13 +81,17 @@
|
||||
<string name="game_env_vkd3d_config">خيارات VKD3D لـ D3D12. يعطّل nodxr تتبع الأشعة؛ استخدمه فقط للعبة تحتاج إليه.</string>
|
||||
<string name="game_env_proton_log">اضبطه على 1 للحصول على سجل تشخيص Proton. قد يقلل التسجيل من الأداء ويستهلك مساحة التخزين.</string>
|
||||
<string name="game_env_wined3d">اضبطه على 1 لاستخدام WineD3D المعتمد على OpenGL بدلًا من DXVK لاختبار توافق D3D9–11.</string>
|
||||
<string name="game_env_wined3d_renderer">أداة العرض لـ DirectDraw وDirect3D 1-7 والألعاب التي تعمل عبر WineD3D. يتخطّى Vulkan مسار OpenGL عبر Zink، وهو أسرع بكثير لألعاب DirectDraw وDirect3D 7 القديمة على Adreno.</string>
|
||||
<string name="game_env_dxvk_d3d8">اضبطه على 1 لتشغيل Direct3D 8 عبر DXVK بدلًا من WineD3D. أسرع في اختبار Direct3D 8 ضمن AIO Graphics Test على Adreno.</string>
|
||||
<string name="game_env_no_ntsync">اضبطه على 1 لإبعاد هذه اللعبة عن ntsync (droiddeck-ntsync أو برنامج تشغيل في النواة)؛ فتستخدم droiddeck-esync حيث تتوفر حزمة، وإلا droiddeck-fsync.</string>
|
||||
<string name="game_env_no_esync">اضبطه على 1 لإيقاف droiddeck-esync لهذه اللعبة؛ فتستخدم droiddeck-fsync بدلًا منه، أو droiddeck-ntsync إذا كان fsync متوقفًا أيضًا.</string>
|
||||
<string name="game_env_no_fsync">اضبطه على 1 لإبعاد هذه اللعبة عن droiddeck-fsync؛ فتستخدم droiddeck-esync حيث تتوفر حزمة، وإلا droiddeck-ntsync.</string>
|
||||
<string name="game_env_fsync_first">اضبطه على 1 لتشغيل هذه اللعبة على droiddeck-fsync، أو على 0 لتقديم droiddeck-esync حيث تتوفر حزمة تناسب إصدار Proton الخاص بها.</string>
|
||||
<string name="game_env_xalia">اضبطه على 0 لتعطيل مساعد التنقل بوحدة التحكم في Proton لهذه اللعبة.</string>
|
||||
<string name="game_env_anticheat_offline">مفعَّل افتراضيًا. يشغّل لعبة Easy Anti-Cheat دون مكافحة الغش عندما تدعم اللعبة اللعب بلا اتصال. أوقفه للتشغيل عبر Easy Anti-Cheat كالمعتاد. تبقى الأوضاع عبر الإنترنت التي تتطلب Easy Anti-Cheat غير متاحة.</string>
|
||||
<string name="game_env_hud">تراكب DXVK لـ D3D9–11. القيمة fps تعرض معدل الإطارات، وتركه دون تعيين يخفيه.</string>
|
||||
<string name="game_env_dxvk_config">إعدادات DXVK مفصولة بفواصل منقوطة. تستخدم الإصدارات الحديثة dxvk.maxFrameRate لتحديد الإطارات؛ يُفضَّل استخدام محدِّد الإطارات الخاص بالجلسة للعب العادي.</string>
|
||||
<string name="game_env_cores">أنوية CPU لهذه اللعبة، مثل 0-4 أو 0,2,4، بدلًا من أنوية الألعاب في الجلسة. عدد أقل من الأنوية يعني حرارة أقل.</string>
|
||||
<string name="game_env_vkd3d_limit">حد معدل الإطارات في D3D12. القيمة 0 تلغي الحد.</string>
|
||||
<string name="game_env_glthread">تعدد مؤشرات الترابط في OpenGL ضمن Mesa. قد تساعد القيمة true ألعاب OpenGL المقيدة بأداء CPU؛ جرّبها لكل لعبة.</string>
|
||||
<string name="sync_backend_title">مزامنة Wine</string>
|
||||
@@ -175,6 +179,8 @@
|
||||
<string name="app_fex_hint">يشغّل FEX برامج Linux المخصصة لـ x86 على جهاز ARM64 هذا. يستخدمه الخيار «تلقائي» عندما يكون البرنامج مبنيًا لـ x86.</string>
|
||||
<string name="app_fex_x86">%1$s عبر FEX</string>
|
||||
<string name="app_fex_not_ready">هذا البرنامج مبني لأجهزة كمبيوتر %1$s ويعمل عبر FEX، الذي لم يتم إعداده بعد. افتح Steam مرة واحدة أثناء تسجيل الدخول: سيجعله DroidDeck يُنزّل FEX وSteam Linux Runtime اللازمة، ثم يُفتح هذا البرنامج.</string>
|
||||
<string name="session_proot_missing">تعذّر تنزيل proot الخاص بـ DroidDeck. تحقّق من الاتصال وحاول مرة أخرى. لم تبدأ الجلسة لأن proot الاحتياطي أبطأ من أن يصلح للعب.</string>
|
||||
<string name="session_directaudio_missing">تعذّر تنزيل DirectAudio، لذا يستخدم صوت الألعاب المسار الأبطأ في هذه الجلسة.</string>
|
||||
<string name="session_end_program">هذا البرنامج</string>
|
||||
<string name="session_end_steam_download">تعذّر تنزيل عميل Steam. قد تكون شبكتك أو VPN تحظر خوادم Steam؛ تحقّق من الاتصال وحاول مرة أخرى.</string>
|
||||
<string name="session_end_steam_setup">تعذّر إعداد عميل Steam. تحقّق من الاتصال والمساحة الفارغة، ثم حاول مرة أخرى.</string>
|
||||
@@ -293,6 +299,11 @@
|
||||
<string name="mode_controller_x360">وحدة تحكم Xbox 360</string>
|
||||
<string name="mode_controller_note">Deck: زر «الوصول السريع» والجيروسكوب. Steam Controller: الشيء نفسه، مع استشعار القبضة على الأزرار الخلفية. DualShock 4 وDualSense: الجيروسكوب، ولوحتا التتبع كلوحة اللمس الخاصة بها. Xbox 360: افتح «الوصول السريع» باستخدام Guide+A.</string>
|
||||
<string name="mode_back">زر الرجوع</string>
|
||||
<string name="back_native_qam_hint">اضغط مطوّلًا على زر الرجوع لمدة 700 ملّي ثانية، أو اضغط عليه مطوّلًا مع زر آخر لاختصارات Steam.</string>
|
||||
<string name="back_double_tap_window">مهلة النقر المزدوج</string>
|
||||
<string name="back_tap_ms">%1$d ملّي ثانية</string>
|
||||
<string name="brightness_permission_title">السماح بالتحكّم في السطوع</string>
|
||||
<string name="brightness_permission_text">اضبط التحكّم في السطوع في DroidDeck.</string>
|
||||
<string name="back_menu_then_qam">القائمة ← الوصول السريع</string>
|
||||
<string name="back_qam_then_menu">الوصول السريع ← القائمة</string>
|
||||
<string name="mode_session">الجلسة</string>
|
||||
@@ -316,6 +327,12 @@
|
||||
<string name="mode_decky_current">محدَّث · %1$s</string>
|
||||
<string name="mode_decky_loader">المُحمِّل</string>
|
||||
<string name="mode_decky_install_latest">تثبيت أحدث إصدار</string>
|
||||
<string name="decky_channel">قناة التحديث</string>
|
||||
<string name="decky_channel_hint">إصدارات Decky Loader التي تُثبَّت. يستخدم مُحدِّث Decky نفسه القناة ذاتها.</string>
|
||||
<string name="decky_channel_stable">مستقرة</string>
|
||||
<string name="decky_channel_prerelease">إصدار تجريبي مسبق</string>
|
||||
<string name="decky_channel_testing">اختبار</string>
|
||||
<string name="decky_channel_failed">تعذّر حفظ قناة تحديث Decky</string>
|
||||
<string name="mode_decky_on">يبدأ مع Steam. أثناء تفعيله، قد تتمكن التطبيقات الأخرى على هذا الجهاز من التحكم في Steam.</string>
|
||||
<string name="mode_decky_off">متوقف. يبقى منفذ تصحيح الأخطاء عن بُعد في Steam مغلقًا.</string>
|
||||
<string name="mode_decky_remove_title">هل تريد إلغاء تثبيت Decky Loader؟</string>
|
||||
@@ -323,6 +340,10 @@
|
||||
<string name="mode_client">العميل</string>
|
||||
<string name="mode_mangoapp">تراكب الأداء</string>
|
||||
<string name="mode_mangoapp_hint">أوقفه إذا تعطلت الألعاب أو أصبحت شاشتها سوداء في وضع Deck. يُطبَّق في الجلسة التالية.</string>
|
||||
<string name="mode_return_after_game">العودة إلى DroidDeck بعد اللعبة</string>
|
||||
<string name="mode_return_after_game_hint">عند إغلاق لعبة بدأتها من DroidDeck أو من مشغّل آخر، يُغلَق Steam بشكل سليم (بعد اكتمال الحفظ السحابي) وتعود إلى هناك. عند الإيقاف: تبقى في Steam.</string>
|
||||
<string name="mode_shader_precache">التخزين المسبق للمظلِّلات</string>
|
||||
<string name="mode_shader_precache_hint">ينزّل Steam مظلِّلات مُعدّة مسبقًا لألعابك ويعالجها في الخلفية، فتقلّ التقطّعات في الألعاب. يوفّر الإيقاف البيانات والتخزين والبطارية، وتبني الألعاب المظلِّلات أثناء اللعب بدلًا من ذلك. هو الإعداد نفسه في Steam ضمن التنزيلات > التخزين المسبق للمظلِّلات. يُطبَّق في الجلسة التالية.</string>
|
||||
<string name="mode_steam_repair">إصلاح عميل Steam</string>
|
||||
<string name="mode_steam_repair_hint">يُنزّل عميل Steam مجددًا في المرة التالية التي يبدأ فيها Steam. استخدمه إذا بقي Steam على شاشة التحميل. يتم الاحتفاظ بالألعاب وتسجيل الدخول والإعدادات.</string>
|
||||
<string name="mode_steam_repair_queued">سيتم تنزيل عميل Steam مجددًا في المرة التالية التي يبدأ فيها Steam.</string>
|
||||
@@ -394,6 +415,8 @@
|
||||
<string name="mode_directaudio_hint">يتجاوز PulseAudio لتقليل زمن الاستجابة.</string>
|
||||
<string name="mode_mic">الميكروفون</string>
|
||||
<string name="mode_mic_hint">للدردشة الصوتية.</string>
|
||||
<string name="drawer_mic_hint">شغّل التقاط الميكروفون أو أوقفه لهذه الجلسة.</string>
|
||||
<string name="drawer_mic_failed">تعذّر تغيير الميكروفون. يُرجى المحاولة مرة أخرى.</string>
|
||||
<string name="mode_network">الشبكة</string>
|
||||
<string name="mode_wifi_discovery">اكتشاف Wi-Fi</string>
|
||||
<string name="mode_wifi_discovery_hint">عرض أسماء شبكات Wi-Fi والشبكات القريبة في Steam.</string>
|
||||
@@ -559,6 +582,16 @@
|
||||
<string name="perf_gsrealtime">gamescope: طابور GPU بأولوية الوقت الفعلي</string>
|
||||
<string name="perf_gsrealtime_hint">يعطي الأولوية لعمل GPU الخاص بالمُركِّب. قد يحسّن انتظام الإطارات على حساب أداء الألعاب قليلًا.</string>
|
||||
<string name="perf_gpu">GPU</string>
|
||||
<string name="perf_memory">الذاكرة</string>
|
||||
<string name="perf_cap_off">إيقاف</string>
|
||||
<string name="perf_cap_auto">افتراضي برنامج التشغيل</string>
|
||||
<string name="perf_zram_client">ضغط Steam أثناء تشغيل لعبة</string>
|
||||
<string name="perf_zram_client_hint">بعد 20 ثانية من بدء اللعبة، يُضغط عميل Steam في zRAM لترك ذاكرة أكبر للعبة، ثم يُقرأ مجددًا عند إغلاقها. أوقف هذا الخيار إذا كانت الجلسة تُغلَق بعد بدء الألعاب بقليل. يظل حد RAM أعلاه يضغط Steam عندما تتجاوزه الجلسة.</string>
|
||||
<string name="perf_ram_cap">حد RAM</string>
|
||||
<string name="perf_ram_cap_hint">يُطبَّق أثناء تشغيل عميل Steam، في جلسة Steam أو من سطح المكتب. عندما تستخدم الجلسة أكثر من هذا الحد، يُضغط Steam ثم عمليات الجلسة المدعومة الأخرى في zRAM. حد مرن: لا يُغلَق شيء، لكن قد تتقطّع الألعاب أثناء استعادة الصفحات.</string>
|
||||
<string name="perf_ram_cap_unavailable">يتطلب مساحة تبديل zRAM، وهي غير متوفرة على هذا الجهاز.</string>
|
||||
<string name="perf_vram_cap">حد VRAM</string>
|
||||
<string name="perf_vram_cap_hint">ذاكرة الفيديو التي يُبلغ بها DXVK ألعاب Direct3D، فتخصّص للأنسجة مساحة أقل. تظل إعدادات DXVK الخاصة باللعبة هي الأولى. يسري في الجلسة التالية.</string>
|
||||
<string name="perf_gpuclock">تثبيت GPU على أعلى تردد له</string>
|
||||
<string name="perf_gpuclock_hint">لـ Adreno فقط. تقطّع أقل، مع استهلاك أكبر للبطارية والحرارة.</string>
|
||||
<string name="perf_fixes">إصلاحات الجلسة</string>
|
||||
@@ -577,6 +610,8 @@
|
||||
<string name="perf_fastpath">مسار proot السريع</string>
|
||||
<string name="perf_fastpath_needs_seccomp">يحتاج إلى مرشّح seccomp في proot.</string>
|
||||
<string name="perf_fastpath_hint">عمليات بحث أسرع عن الملفات وتقطّع أقل. أوقفه إذا تعذّر على برنامج العثور على ملفاته.</string>
|
||||
<string name="perf_cursor_composite">رسم المؤشر داخل gamescope</string>
|
||||
<string name="perf_cursor_composite_hint">يرسم Gamescope المؤشر بنفسه بدلًا من تسليمه إلى Android. فعّله لمؤشر تتحكّم فيه وحدة التحكم. الإيقاف أسرع على الهاتف. يُطبَّق في الجلسة التالية.</string>
|
||||
<string name="perf_identity">هوية الجلسة</string>
|
||||
<string name="perf_hostname">اسم المضيف</string>
|
||||
<string name="perf_hostname_hint">الاسم الذي يراه Steam لهذا الجهاز. اتركه خاليًا للاستعادة إلى %1$s.</string>
|
||||
@@ -591,6 +626,8 @@
|
||||
<string name="driver_delete_plain">تُزال ملفاته من التطبيق.</string>
|
||||
<string name="driver_delete_in_use">تُزال ملفاته. إنه قيد الاستخدام، فيتولى الافتراضي مكانه.</string>
|
||||
<string name="drawer_page_display">العرض</string>
|
||||
<string name="drawer_frame_limit">حد الإطارات</string>
|
||||
<string name="drawer_frame_limit_note">يحدّ هذه اللعبة. تنتقل الشاشة إلى معدل تحديث يقبل القسمة على الحد إن وُجد، وقد تبدو الحدود الأخرى غير منتظمة. تستخدم ألعاب Steam حد الإطارات في Steam ضمن قائمة الوصول السريع.</string>
|
||||
<string name="drawer_page_effects">المؤثرات</string>
|
||||
<string name="drawer_page_controls">عناصر التحكم</string>
|
||||
<string name="drawer_page_components">المكوّنات</string>
|
||||
@@ -672,7 +709,6 @@
|
||||
<string name="hud_export_failed">تعذّر حفظ تقرير HUD.</string>
|
||||
<string name="hud_reset">إعادة ضبط إعدادات HUD</string>
|
||||
<string name="hud_reset_button">إعادة ضبط</string>
|
||||
<string name="hud_credit">FusionHUD من The412Banner، github.com/The412Banner/FusionHUD (GPL-3.0).</string>
|
||||
<string name="drawer_scaling">وضع التحجيم</string>
|
||||
<string name="drawer_scaling_sharpness">حدة التحجيم</string>
|
||||
<string name="drawer_effects">مؤثرات الشاشة</string>
|
||||
@@ -707,6 +743,8 @@
|
||||
<string name="drawer_touch_auto">تلقائي (%1$s)</string>
|
||||
<string name="drawer_keyboard">لوحة المفاتيح</string>
|
||||
<string name="drawer_latency">زمن الاستجابة</string>
|
||||
<string name="drawer_low_latency">وضع زمن الاستجابة المنخفض</string>
|
||||
<string name="drawer_low_latency_hint">يزيد استهلاك CPU والبطارية</string>
|
||||
<string name="drawer_low_latency_controller">وحدة تحكم بزمن استجابة منخفض</string>
|
||||
<string name="drawer_low_latency_controller_hint">تبلغ وحدة التحكم بمعدل 1000 هرتز بدلًا من 250 هرتز. استهلاك معالج أعلى قليلًا.</string>
|
||||
<string name="drawer_low_latency_touch">لمس بزمن استجابة منخفض</string>
|
||||
@@ -803,6 +841,10 @@
|
||||
<string name="setup_session">الجلسة</string>
|
||||
<string name="setup_logs">سجلات الجلسة</string>
|
||||
<string name="setup_logs_hint">تُحفَظ بعد كل جلسة</string>
|
||||
<string name="setup_game_debug_logs">سجلات تصحيح الألعاب</string>
|
||||
<string name="setup_game_debug_logs_hint">تضمين بيانات تشخيص Proton وWine والرسومات عند تشغيل اللعبة التالية. قد يقلّل الأداء ويستهلك مساحة تخزين أكبر.</string>
|
||||
<string name="setup_game_debug_logs_restart">أعِد تشغيل هذه الجلسة لحفظ سجلات تصحيح الألعاب</string>
|
||||
<string name="setup_logging_update_failed">تعذّر تحديث التسجيل. تحقّق من المفتاح وحاول مرة أخرى.</string>
|
||||
<string name="setup_agent_commands">أدوات تصحيح الأخطاء</string>
|
||||
<string name="setup_latest_logs">أحدث سجلات الجلسة</string>
|
||||
<string name="setup_saved_logs">سجلات الجلسة المحفوظة</string>
|
||||
@@ -835,6 +877,11 @@
|
||||
<string name="setup_home_on">يمكن أن يكون DroidDeck تطبيق الشاشة الرئيسية</string>
|
||||
<string name="setup_home_off">لا يُعرَض DroidDeck أبدًا كتطبيق للشاشة الرئيسية</string>
|
||||
<string name="setup_orientation">الاتجاه</string>
|
||||
<string name="setup_launcher_orientation">اتجاه المشغّل</string>
|
||||
<string name="setup_launcher_orientation_auto">اتّباع تدوير الجهاز</string>
|
||||
<string name="setup_orientation_portrait">عمودي</string>
|
||||
<string name="setup_session_orientation">اتجاه الجلسة</string>
|
||||
<string name="setup_session_orientation_hint">يُطبَّق على Steam والألعاب وسطح المكتب ومحرّر وحدة التحكم. تدور الدقّات المُعدّة مسبقًا مع الجلسة، ويبقى العرض والارتفاع المخصّصان كما أُدخلا.</string>
|
||||
<string name="setup_orientation_auto">أفقي تلقائي</string>
|
||||
<string name="setup_orientation_landscape">أفقي</string>
|
||||
<string name="setup_orientation_reverse">أفقي معكوس</string>
|
||||
@@ -1011,6 +1058,14 @@
|
||||
<string name="gate_step1">افتح الإعدادات ← خيارات المطوّرين ← تصحيح الأخطاء اللاسلكي وفعِّله</string>
|
||||
<string name="gate_step2">اضغط على «إقران جهاز برمز إقران»</string>
|
||||
<string name="gate_step3">أدخل الرمز في إشعار DroidDeck</string>
|
||||
<string name="pairguide_build_number">في «لمحة عن الهاتف»، انقر على «رقم الإصدار» 7 مرات</string>
|
||||
<string name="pairguide_wireless">فعّل «تصحيح الأخطاء اللاسلكي»</string>
|
||||
<string name="pairguide_pair">افتح «تصحيح الأخطاء اللاسلكي»، ثم انقر على «إقران الجهاز باستخدام رمز الإقران»</string>
|
||||
<string name="pairguide_child_process">فعّل «إيقاف قيود العمليات الفرعية»</string>
|
||||
<string name="pairguide_row_child_process">إيقاف قيود العمليات الفرعية</string>
|
||||
<string name="pairguide_row_build_number">رقم الإصدار</string>
|
||||
<string name="pairguide_row_wireless">تصحيح الأخطاء اللاسلكي</string>
|
||||
<string name="pairguide_row_pair">إقران الجهاز باستخدام رمز الإقران</string>
|
||||
<string name="gate_waiting">في انتظار نافذة الإقران المنبثقة…</string>
|
||||
<string name="gate_code_needed">تم العثور على النافذة المنبثقة. أدخل رمزها في الإشعار.</string>
|
||||
<string name="gate_status">الحالة</string>
|
||||
@@ -1149,7 +1204,6 @@
|
||||
<string name="games_never_played">لم يتم تشغيلها أبدًا</string>
|
||||
<string name="games_runtime_busy_percent">بيئة التشغيل مشغولة · %1$d%%</string>
|
||||
<string name="games_runtime_busy">بيئة التشغيل مشغولة</string>
|
||||
<string name="games_runtime_first_play">تُثبَّت بيئة التشغيل عند أول تشغيل</string>
|
||||
<string name="games_runtime_update">يتوفر تحديث لبيئة التشغيل</string>
|
||||
<string name="games_runtime_ready">● بيئة التشغيل جاهزة</string>
|
||||
<string name="games_internal">التخزين الداخلي</string>
|
||||
@@ -1166,6 +1220,9 @@
|
||||
<string name="gpu_hide_other">إخفاء برامج التشغيل لوحدات GPU الأخرى</string>
|
||||
<string name="gpu_show_other">إظهار برامج التشغيل لوحدات GPU الأخرى</string>
|
||||
<string name="gpu_advanced">متقدّم</string>
|
||||
<string name="gpu_ubwc_title">توافق UBWC</string>
|
||||
<string name="gpu_ubwc_hint">جرّب التشغيل أو الإيقاف إذا ظهرت خطوط أو وميض في Steam أو Android. يُطبَّق على برنامجَي التشغيل كليهما بعد إعادة تشغيل DroidDeck.</string>
|
||||
<string name="gpu_ubwc_restart">أعِد تشغيل DroidDeck للتطبيق.</string>
|
||||
<string name="gpu_set_with_display">يُضبَط مع برنامج تشغيل العرض معًا: يحمل %1$s كلاهما.</string>
|
||||
<string name="gpu_set_with_runtime">يُضبَط مع برنامج تشغيل بيئة التشغيل معًا: يحمل %1$s كلاهما.</string>
|
||||
<string name="gpu_runtime_hint">يُستخدَم في الألعاب وسطح المكتب.</string>
|
||||
@@ -1274,10 +1331,15 @@
|
||||
<string name="pip_auto">الدخول تلقائيًا إلى وضع نافذة ضمن النافذة</string>
|
||||
<string name="unfolded_controls">عناصر التحكّم على الشاشة غير المطوية</string>
|
||||
<string name="unfolded_controls_hint">عند فتح الجهاز، تظهر اللعبة فوق لوحتَي اللمس والمقابض الخلفية بأسلوب Steam Deck. وعند طيّه، تُعرض اللعبة بملء الشاشة.</string>
|
||||
<string name="unfolded_controls_with_controller">إبقاؤها مع وحدة التحكم</string>
|
||||
<string name="unfolded_controls_with_controller_hint">إظهار عناصر التحكّم باللمس هذه أيضًا أثناء توصيل وحدة تحكم.</string>
|
||||
<string name="pip_suspended">معلَّقة</string>
|
||||
<string name="pip_not_ready">تتوفّر ميزة نافذة ضمن النافذة عندما تصبح الجلسة جاهزة.</string>
|
||||
<string name="pip_permission">اسمح بميزة نافذة ضمن النافذة لتطبيق DroidDeck في إعدادات Android.</string>
|
||||
<string name="pip_unavailable">تعذّر على Android فتح نافذة ضمن النافذة.</string>
|
||||
<string name="game_more">المزيد</string>
|
||||
<string name="game_edit_art">تعديل الصور</string>
|
||||
<string name="stores_in_steam_label">في Steam</string>
|
||||
<string name="game_shortcut">اختصار</string>
|
||||
<string name="game_shortcut_add">إضافة إلى الشاشة الرئيسية</string>
|
||||
<string name="game_shortcut_choose">اختيار لعبة</string>
|
||||
@@ -1301,6 +1363,10 @@
|
||||
|
||||
<string name="main_wait_runtime">انتظر حتى تنتهي عملية بيئة التشغيل</string>
|
||||
<string name="main_wait_proton_install">انتظر حتى ينتهي تثبيت أداة التوافق</string>
|
||||
<string name="load_compat_title">جارٍ تجهيز أدوات التوافق</string>
|
||||
<string name="load_compat_wait">في انتظار اكتمال إعداد التوافق</string>
|
||||
<string name="load_compat_hint">ستبدأ جلستك عند اكتمال الإعداد.</string>
|
||||
<string name="load_compat_progress">%1$s · %2$d%%</string>
|
||||
<string name="main_wait_desktop_install">انتظر حتى ينتهي تثبيت تطبيق سطح المكتب</string>
|
||||
<string name="main_wait_install_game">انتظر حتى ينتهي التثبيت قبل تشغيل لعبة</string>
|
||||
<string name="main_saves_close_session">أغلِق جلسة Steam أولاً حتى لا تحفظ اللعبة فوق الملفات المستورَدة</string>
|
||||
@@ -1353,6 +1419,9 @@
|
||||
<string name="main_install_anyway">التثبيت على أي حال</string>
|
||||
<string name="main_remove_runtime_title">إزالة بيئة تشغيل Linux</string>
|
||||
<string name="main_remove_runtime_text">سيؤدي هذا إلى حذف بيئة التشغيل وعميل Steam بداخلها وكل لعبة مثبَّتة فيها.</string>
|
||||
<string name="runtime_actions_title">بيئة تشغيل Linux</string>
|
||||
<string name="runtime_actions_text">يعيد الإصلاح تثبيت ملفات النظام في بيئة التشغيل ويحتفظ بـ Steam وألعابك وإعداداتك. تُثبَّت الإضافات مثل سطح المكتب مجددًا عند استخدامها لاحقًا. أما الإزالة فتحذف كل شيء.</string>
|
||||
<string name="runtime_repair">إصلاح بيئة التشغيل</string>
|
||||
<string name="main_applied">تم التطبيق: %1$s</string>
|
||||
<string name="android_app_open_failed_primary">تعذّر فتح %1$s على الشاشة الأساسية</string>
|
||||
<string name="android_app_open_failed_on">تعذّر فتح %1$s على %2$s</string>
|
||||
@@ -1494,6 +1563,15 @@
|
||||
<string name="session_runtime_catalog_unreachable">تعذّر الوصول إلى كتالوج بيئة التشغيل. تحقَّق من الاتصال واضغط على «تشغيل» مرة أخرى.</string>
|
||||
<string name="session_runtime_install_failed">لم يتم تثبيت بيئة تشغيل Linux. تحقَّق من بيئة التشغيل في «الإعداد» واضغط على «تشغيل» مرة أخرى.</string>
|
||||
<string name="session_desktop_install_failed">لم يتم تثبيت سطح المكتب (%1$s). تحقَّق من الاتصال واضغط على «سطح المكتب» مرة أخرى.</string>
|
||||
<string name="session_package_resume_failed">تعذّر إكمال تثبيت توقّف قبل انتهائه (%1$s). تحقّق من الاتصال والمساحة، ثم حاول مرة أخرى.</string>
|
||||
<plurals name="session_end_runtime_damaged">
|
||||
<item quantity="zero">بيئة تشغيل Linux تالفة: %1$d رابط مكتبة يشير إلى ملفات مفقودة (%2$s وغيرها)، وعادةً بعد توقّف تثبيت قبل انتهائه. يحتفظ الإصلاح بألعابك وإعداداتك.</item>
|
||||
<item quantity="one">بيئة تشغيل Linux تالفة: رابط مكتبة واحد يشير إلى ملف مفقود (%2$s)، وعادةً بعد توقّف تثبيت قبل انتهائه. يحتفظ الإصلاح بألعابك وإعداداتك.</item>
|
||||
<item quantity="two">بيئة تشغيل Linux تالفة: رابطا مكتبة يشيران إلى ملفات مفقودة (%2$s وغيره)، وعادةً بعد توقّف تثبيت قبل انتهائه. يحتفظ الإصلاح بألعابك وإعداداتك.</item>
|
||||
<item quantity="few">بيئة تشغيل Linux تالفة: %1$d روابط مكتبات تشير إلى ملفات مفقودة (%2$s وغيرها)، وعادةً بعد توقّف تثبيت قبل انتهائه. يحتفظ الإصلاح بألعابك وإعداداتك.</item>
|
||||
<item quantity="many">بيئة تشغيل Linux تالفة: %1$d رابطًا لمكتبات تشير إلى ملفات مفقودة (%2$s وغيرها)، وعادةً بعد توقّف تثبيت قبل انتهائه. يحتفظ الإصلاح بألعابك وإعداداتك.</item>
|
||||
<item quantity="other">بيئة تشغيل Linux تالفة: %1$d رابط مكتبة يشير إلى ملفات مفقودة (%2$s وغيرها)، وعادةً بعد توقّف تثبيت قبل انتهائه. يحتفظ الإصلاح بألعابك وإعداداتك.</item>
|
||||
</plurals>
|
||||
<string name="session_ended_named">توقّف %1$s بشكل غير متوقَّع. شارِك السجلات مع بلاغ عن الخطأ، أو حاوِل مرة أخرى.</string>
|
||||
<string name="session_ended_program">توقّف البرنامج بشكل غير متوقَّع. شارِك السجلات مع بلاغ عن الخطأ، أو حاوِل مرة أخرى.</string>
|
||||
<string name="session_ended_desktop">توقّف سطح المكتب بشكل غير متوقَّع. شارِك السجلات مع بلاغ عن الخطأ، أو حاوِل مرة أخرى.</string>
|
||||
@@ -1512,6 +1590,17 @@
|
||||
<string name="mode_decky_plugins_hint">ثبِّت ملف ZIP لإضافة في جلسة Steam التالية.</string>
|
||||
<string name="mode_decky_plugin_downloading">جارٍ التنزيل…</string>
|
||||
<string name="mode_decky_plugin_install_zip">التثبيت من ملف ZIP</string>
|
||||
<string name="decky_zip_warning_title">تثبيت إضافة من جهة خارجية</string>
|
||||
<string name="decky_zip_warning_text">لم يراجع فريق Decky Loader هذه الإضافة. قد تحتوي على برامج ضارة، مثل برامج لسرقة حساب Steam الخاص بك أو إلحاق الضرر بجهازك. بتثبيت هذه الإضافة، فإنك توافق على تحمّل جميع المخاطر على جهازك.</string>
|
||||
<string name="decky_zip_warning_continue">متابعة</string>
|
||||
<plurals name="decky_zip_warning_wait">
|
||||
<item quantity="zero">يُرجى الانتظار %1$d ثانية</item>
|
||||
<item quantity="one">يُرجى الانتظار ثانية واحدة</item>
|
||||
<item quantity="two">يُرجى الانتظار ثانيتين</item>
|
||||
<item quantity="few">يُرجى الانتظار %1$d ثوانٍ</item>
|
||||
<item quantity="many">يُرجى الانتظار %1$d ثانية</item>
|
||||
<item quantity="other">يُرجى الانتظار %1$d ثانية</item>
|
||||
</plurals>
|
||||
<string name="store_cat_games">الألعاب</string>
|
||||
<string name="store_cat_audio_video">الصوت والفيديو</string>
|
||||
<string name="store_cat_graphics">الرسومات</string>
|
||||
@@ -1693,6 +1782,8 @@
|
||||
<string name="fm_accept">موافق</string>
|
||||
<string name="fm_decline">رفض</string>
|
||||
<string name="fm_drive_not_readable">تم تركيب %1$s لكن تتعذّر قراءته حاليًا</string>
|
||||
<string name="fm_drive_access_title">السماح بالوصول إلى %1$s</string>
|
||||
<string name="fm_drive_access_text">يتيح Android لتطبيق DroidDeck رؤية محرك الأقراص هذا دون قراءته. فعّل الوصول إلى جميع الملفات لتطبيق DroidDeck ثم عُد.</string>
|
||||
<string name="fm_list_view">عرض القائمة</string>
|
||||
<string name="fm_grid_view">عرض الشبكة</string>
|
||||
<string name="fm_search">بحث</string>
|
||||
@@ -1802,6 +1893,7 @@
|
||||
<string name="flatpakmgr_not_ready">أعِدّ Flatpak أولاً</string>
|
||||
<string name="flatpakmgr_starting">جارٍ البدء</string>
|
||||
<string name="flatpakmgr_exit_status">خرج Flatpak بالحالة %1$d</string>
|
||||
<string name="flatpakmgr_wrong_arch">تم بناء %1$s لمعمارية %2$s، ولا يستطيع DroidDeck تشغيلها. تحتاج تطبيقات Flatpak هنا إلى إصدار لمعمارية ARM64 أو x86_64.</string>
|
||||
<string name="flatpakmgr_installing">جارٍ تثبيت %1$s</string>
|
||||
<string name="flatpakmgr_updating">جارٍ تحديث %1$s</string>
|
||||
<string name="flatpakmgr_removing">جارٍ إزالة %1$s</string>
|
||||
@@ -1895,6 +1987,7 @@
|
||||
<string name="adbpair_applying">جارٍ تطبيق الإعداد…</string>
|
||||
<string name="adbpair_command_failed">فشل أمر تصحيح الأخطاء اللاسلكي</string>
|
||||
<string name="adbpair_channel_name">إعداد تصحيح الأخطاء اللاسلكي</string>
|
||||
<string name="adbpair_progress_channel_name">تقدّم إعداد تصحيح الأخطاء اللاسلكي</string>
|
||||
<string name="adbpair_channel_description">يطلب رمز إقران تصحيح الأخطاء اللاسلكي أثناء فتح الإعدادات</string>
|
||||
<string name="adbpair_title_pair">إقران تصحيح الأخطاء اللاسلكي</string>
|
||||
<string name="adbpair_waiting_text">فعِّل تصحيح الأخطاء اللاسلكي، ثم اضغط على «إقران الجهاز برمز الإقران».</string>
|
||||
@@ -2003,6 +2096,7 @@
|
||||
<string name="gpuinfo_not_adreno">وحدة GPU ليست من نوع Adreno</string>
|
||||
<string name="gpuinfo_supported">مدعوم</string>
|
||||
<string name="gpuinfo_experimental">تجريبي: برامج تشغيله إصدارات اختبارية</string>
|
||||
<string name="gpuinfo_a850_experimental">دعم تجريبي لـ Adreno 850: يتطلب برامج تشغيل تجريبية متوافقة للعرض والألعاب، ولم يُتحقَّق منه على هذا الجهاز</string>
|
||||
<string name="gpuinfo_below_tested">أقل من العتاد المُختبَر (Adreno 725 وأحدث): قد لا يعمل</string>
|
||||
<string name="gpuinfo_unsupported">غير مدعوم: يحتاج DroidDeck إلى وحدة GPU من نوع Adreno (Snapdragon)</string>
|
||||
|
||||
@@ -2205,6 +2299,13 @@
|
||||
<string name="stores_resume">استئناف</string>
|
||||
<string name="stores_refresh">تحديث</string>
|
||||
<string name="stores_sort">ترتيب</string>
|
||||
<string name="setup_rail_labels">تسميات الشريط الجانبي</string>
|
||||
<string name="setup_rail_labels_hint">إظهار الأسماء أسفل رموز الشريط الجانبي. أوقفه للحصول على شريط جانبي أنحف.</string>
|
||||
<string name="library_display">العرض</string>
|
||||
<string name="library_display_larger">بطاقات أكبر</string>
|
||||
<string name="library_display_smaller">بطاقات أصغر</string>
|
||||
<string name="library_display_title">إظهار العنوان</string>
|
||||
<string name="library_display_size">إظهار الحجم</string>
|
||||
<string name="stores_sort_last_played">لُعب مؤخرًا</string>
|
||||
<string name="stores_sort_recently_installed">ثُبت مؤخرًا</string>
|
||||
<string name="stores_sort_title_asc">العنوان أ–ي</string>
|
||||
@@ -2331,6 +2432,9 @@
|
||||
<string name="stores_download_manager">مدير التنزيلات</string>
|
||||
<string name="stores_parallel">عدد التنزيلات المتزامنة</string>
|
||||
<string name="stores_install_where">التثبيت في</string>
|
||||
<string name="stores_install_language">لغة اللعبة</string>
|
||||
<string name="stores_install_language_hint">يثبّت GOG وEpic هذه اللغة. خيار «النظام» يتبع لغة التطبيق.</string>
|
||||
<string name="stores_install_language_system">النظام</string>
|
||||
<string name="stores_install_title">تثبيت %1$s:</string>
|
||||
<string name="stores_target_internal">التخزين الداخلي</string>
|
||||
<string name="stores_target_free">%1$s متاحة</string>
|
||||
@@ -2369,6 +2473,9 @@
|
||||
<string name="edit_target">الهدف</string>
|
||||
<string name="edit_start_in">بدء التشغيل في</string>
|
||||
<string name="edit_launch_options">خيارات التشغيل</string>
|
||||
<string name="edit_launch_options_steam_hint">مشتركة مع خصائص Steam: أي تغيير في أحدهما يظهر في كليهما.</string>
|
||||
<string name="edit_launch_options_not_saved">تعذّر حفظ خيارات التشغيل في Steam. حاول مرة أخرى.</string>
|
||||
<string name="edit_launch_options_desktop">قد يكون Steam مفتوحًا في جلسة سطح المكتب. غيّر خيارات التشغيل من خصائصه، أو أغلق الجلسة أولًا.</string>
|
||||
<string name="edit_artwork">الصور الفنية</string>
|
||||
<string name="edit_other_exe">ملف exe آخر…</string>
|
||||
<string name="edit_remove">إزالة</string>
|
||||
@@ -2504,6 +2611,7 @@
|
||||
<string name="setup_download_source_custom">بادئة خاصة</string>
|
||||
<string name="setup_download_mirror">الموقع</string>
|
||||
<string name="setup_download_prefix">البادئة</string>
|
||||
<string name="setup_download_proxy">وكيل HTTP</string>
|
||||
<string name="flathub_eyebrow">تطبيقات Linux</string>
|
||||
<string name="flathub_name">Flathub</string>
|
||||
<string name="flathub_line">تطبيقات سطح المكتب لسطح مكتب Linux، تُفتح من سطح المكتب.</string>
|
||||
@@ -2652,6 +2760,22 @@
|
||||
<string name="glasses_tracking_flat_hint">يُبقي الوضع «تلقائي» لعبة 2D هذه ثابتة أمامك. اختر «شاشة افتراضية» في «العرض» لاستخدام تتبّع الرأس.</string>
|
||||
<string name="glasses_tracking_sbs_hint">يُطبَّق تتبّع الرأس على الشاشة الافتراضية أو على لعبة SteamVR قيد التشغيل.</string>
|
||||
<string name="glasses_hardware">الجهاز</string>
|
||||
<string name="vr_controllers_tab">وحدات التحكم</string>
|
||||
<string name="vr_controllers_group">وحدات تحكم SteamVR</string>
|
||||
<string name="vr_controllers_emulate">ذراع الألعاب في VR</string>
|
||||
<string name="vr_controllers_emulate_hint">يدا VR اللتان تؤدي وحدة التحكم دورهما. تُطبَّق التغييرات فورًا، حتى أثناء تشغيل SteamVR. تظل وحدات Joy-Con والأيدي المتتبَّعة تتولى جانبها.</string>
|
||||
<string name="vr_controllers_off">ذراع ألعاب عادية</string>
|
||||
<string name="vr_controllers_index">وحدات تحكم Valve Index</string>
|
||||
<string name="vr_controllers_touch">وحدات تحكم Meta Quest 3</string>
|
||||
<string name="vr_controllers_vive">عصيّ HTC Vive</string>
|
||||
<string name="vr_controllers_sticks">تبدأ العصا بـ</string>
|
||||
<string name="vr_controllers_sticks_hint">اضغط على العصوين معًا أثناء VR للتبديل.</string>
|
||||
<string name="vr_controllers_sticks_game">تحريكك داخل اللعبة</string>
|
||||
<string name="vr_controllers_sticks_hands">تحريك اليدين</string>
|
||||
<string name="vr_controllers_buttons">الأزرار</string>
|
||||
<string name="vr_controllers_buttons_stick">الزنادات زنادات، والأزرار الكتفية للإمساك، وA/B وX/Y هي أزرار الوجه لكل يد، والنقر على العصا ينقر عصا الإبهام، وGuide يفتح قائمة SteamVR. أعلى وأسفل لوحة الاتجاهات يقرّبان اليدين أو يبعدانهما.</string>
|
||||
<string name="vr_controllers_buttons_vive">العصوان لوحتا لمس، والضغط عليهما بـ A/X أو بالنقر على العصا. الزنادات زنادات، والأزرار الكتفية للإمساك، وStart وSelect للقائمة، وGuide يفتح قائمة SteamVR.</string>
|
||||
<string name="vr_controllers_buttons_off">بلا أيدٍ في VR. تتلقّى الألعاب التي تدعم ذراع الألعاب، وقائمة SteamVR، وحدة التحكم كالمعتاد.</string>
|
||||
<string name="glasses_brightness">السطوع</string>
|
||||
<string name="glasses_volume">مستوى الصوت</string>
|
||||
<string name="glasses_sunblock">حجب الشمس</string>
|
||||
@@ -2709,6 +2833,12 @@
|
||||
<string name="hand_camera_placement">وضع الكاميرا</string>
|
||||
<string name="hand_camera_placement_hint">تحقّق من أن الكاميرا تراك قبل اللعب.</string>
|
||||
<string name="hand_camera_check">تحقّق</string>
|
||||
<string name="tracking_pack_title">تنزيل تتبّع اليدين</string>
|
||||
<string name="tracking_pack_hint">يتطلب تتبّع اليدين تنزيلًا لمرة واحدة بحجم %1$s.</string>
|
||||
<string name="tracking_pack_download">تنزيل</string>
|
||||
<string name="tracking_pack_retry">إعادة المحاولة</string>
|
||||
<string name="tracking_pack_downloading">جارٍ تنزيل تتبّع اليدين… %1$d%%</string>
|
||||
<string name="tracking_pack_failed">تعذّر تنزيل تتبّع اليدين. تحقّق من اتصالك وحاول مرة أخرى.</string>
|
||||
<string name="hand_camera_check_title">وضع الكاميرا</string>
|
||||
<string name="hand_camera_how_rear">ضع الجهاز واقفًا على بُعد 1.5 إلى 2 متر تقريبًا بارتفاع الصدر، مع توجيه الكاميرا الخلفية نحوك. ثم ادخل إلى مجال الرؤية ويداك ممدودتان.</string>
|
||||
<string name="hand_camera_how_front">ضع الجهاز واقفًا على بُعد 1.5 إلى 2 متر تقريبًا بارتفاع الصدر، مع توجيه الشاشة نحوك. ثم ادخل إلى مجال الرؤية ويداك ممدودتان.</string>
|
||||
@@ -2780,6 +2910,21 @@
|
||||
<string name="storage_safe_hint">بيئات تشغيل غير مستخدمة وبقايا وسجلات قديمة</string>
|
||||
<string name="storage_clean_up">جارٍ التنظيف…</string>
|
||||
<string name="storage_session_running">أوقف الجلسة لتنظيف التخزين أو حذف شيء. تبقى الأحجام ظاهرة.</string>
|
||||
<string name="storage_default_group">موقع التثبيت</string>
|
||||
<string name="storage_default_title">التخزين الافتراضي</string>
|
||||
<string name="storage_default_hint">تُثبَّت ألعاب المتاجر الجديدة في الموقع المحدد. تبقى الألعاب الحالية في مكانها. تحتفظ مكتبات Steam بإعدادها الخاص.</string>
|
||||
<string name="storage_default_ask">السؤال في كل مرة</string>
|
||||
<string name="storage_default_ask_detail">اختر وجهة لكل تثبيت</string>
|
||||
<string name="storage_default_internal">مساحة التخزين الداخلية</string>
|
||||
<string name="storage_default_external">مساحة التخزين الخارجية</string>
|
||||
<string name="storage_default_external_detail">%1$s · %2$s متاحة</string>
|
||||
<string name="storage_default_external_missing">غير متصل</string>
|
||||
<string name="storage_default_folder">مجلد · %1$s</string>
|
||||
<string name="storage_default_folder_free">%1$s متاحة</string>
|
||||
<string name="storage_default_folder_missing">غير متصل</string>
|
||||
<string name="storage_default_choose_folder">اختيار مجلد…</string>
|
||||
<string name="storage_default_choose_folder_detail">استخدم أي مجلد على بطاقة SD أو محرك USB</string>
|
||||
<string name="storage_default_note">توضع الألعاب في مجلد Games داخل الموقع المحدد. لا تُنقل الألعاب الحالية.</string>
|
||||
<string name="storage_where">إلى أين يذهب</string>
|
||||
<string name="storage_games">ألعاب Steam</string>
|
||||
<string name="storage_game_data">بيانات الألعاب</string>
|
||||
@@ -2929,6 +3074,9 @@
|
||||
<string name="storage_data_installed">الألعاب المثبَّتة</string>
|
||||
<string name="storage_data_parts">البادئة %1$s · الشيدرات %2$s · الورشة %3$s</string>
|
||||
<string name="storage_clear_shaders">مسح الشيدرات</string>
|
||||
<string name="storage_reset_prefix">إعادة ضبط البادئة</string>
|
||||
<string name="storage_reset_prefix_title">هل تريد إعادة ضبط بادئة %1$s؟</string>
|
||||
<string name="storage_reset_prefix_confirm">يحذف بادئة Wine الخاصة بها (%1$s) في %2$s ويعيد إنشاءها عند التشغيل التالي. تُفقد عمليات الحفظ والإعدادات والحزم القابلة لإعادة التوزيع المثبَّتة داخلها، وتبقى حفظات Steam Cloud في حسابك.</string>
|
||||
<string name="storage_data_leftovers">ألعاب محذوفة</string>
|
||||
<string name="storage_steam_app">تطبيق Steam %1$d</string>
|
||||
<string name="storage_leftover_unsure_detail">البادئة تحتوي على ملفات، ربما حفظات محلية</string>
|
||||
@@ -3238,6 +3386,10 @@
|
||||
<string name="spatial_saved_views_hint">يمكن إعادة حساب المشاهدات المحفوظة. ابدأ معايرة جديدة لالتقاطها في نظام إحداثيات التتبع الحالي.</string>
|
||||
<string name="spatial_model_checksum_error">المجموع الاختباري لنموذج تتبع اليدين غير مطابق</string>
|
||||
<string name="spatial_opencv_load_error">تعذر تحميل OpenCV</string>
|
||||
<string name="session_end_steam_sigill">توقّف Steam بسبب تعليمة غير صالحة (SIGILL). قد تكون مشكلة توافق في تعليمات CPU أو تعطّلًا في العميل. شارك السجلات مع تفاصيل جهازك.</string>
|
||||
<string name="session_end_steam_try_x64">يمكنك تجربة إعدادات Steam → عميل Steam → x86-64 (تجريبي). يتطلب تنزيلًا إضافيًا وقد يعمل بشكل أبطأ.</string>
|
||||
<string name="session_end_vulkan_device">تعذّر على برنامج تشغيل رسومات Linux العثور على جهاز Vulkan صالح للاستخدام. تحقّق من أن برنامج تشغيل GPU المحدد لـ Linux يدعم هذا الـ GPU.</string>
|
||||
<string name="session_end_gpu_unsupported">لا يمكن بدء هذه الجلسة لأن هذا الـ GPU ليس له برنامج تشغيل Vulkan متوافق لـ Linux في الإعداد الحالي. لا يمكن لبرامج تشغيل Adreno Turnip تفعيل دعم وحدات MediaTek/Mali GPU.</string>
|
||||
<string name="setup_group_memory">الذاكرة</string>
|
||||
<string name="setup_clear_cached">إغلاق التطبيقات المخزّنة مؤقتًا قبل الجلسة</string>
|
||||
<string name="setup_clear_cached_hint">عند بدء الجلسة، يُغلق DroidDeck التطبيقات التي يُبقيها Android في الخلفية، لتحصل اللعبة على ذاكرة أكبر. يجب تفعيل تصحيح الأخطاء اللاسلكي.</string>
|
||||
@@ -3261,6 +3413,12 @@
|
||||
<string name="epic_client_open">فتح</string>
|
||||
<string name="epic_client_install">تثبيت</string>
|
||||
<string name="game_tab_about">حول</string>
|
||||
<string name="game_resources_browser">يُفتح في متصفحك</string>
|
||||
<string name="game_resource_guides">الأدلة</string>
|
||||
<string name="game_resource_protondb_detail">تقارير توافق Linux / Proton</string>
|
||||
<string name="game_resource_steam_cloud">Steam Cloud</string>
|
||||
<string name="game_resource_steam_cloud_detail">للألعاب التي تُحفظ بياناتها في حساب Steam الخاص بك</string>
|
||||
<string name="game_resource_search">البحث في الويب</string>
|
||||
<string name="game_tab_install">تثبيت</string>
|
||||
<string name="game_install_location">الموقع</string>
|
||||
<string name="game_install_folder">مجلد</string>
|
||||
@@ -3277,6 +3435,11 @@
|
||||
<string name="stores_eyebrow_pass">متاحة مع %1$s</string>
|
||||
<string name="stores_owned_in_library">الألعاب المملوكة في المكتبة</string>
|
||||
<string name="library_filter_added">مُضافة</string>
|
||||
<string name="library_filter">تصفية</string>
|
||||
<string name="library_filter_installed">المثبَّتة فقط</string>
|
||||
<string name="library_filter_all_owned">كل الألعاب المملوكة</string>
|
||||
<string name="library_no_installed_matches">لا توجد ألعاب مثبَّتة تطابق عوامل التصفية هذه.</string>
|
||||
<string name="library_browse_owned">تصفّح الألعاب المملوكة</string>
|
||||
<string name="game_tab_launch">التشغيل</string>
|
||||
<string name="game_tab_saves_cloud">الحفظ والسحابة</string>
|
||||
<string name="game_launch_shortcut">اختصار Steam</string>
|
||||
@@ -3294,6 +3457,28 @@
|
||||
<string name="stores_itch_update_replaced">استبدل المطوّر هذا الإصدار بـ %1$s. هل تريد التحديث إليه؟</string>
|
||||
<string name="xbox_filter_cloud">سحابية</string>
|
||||
<string name="stores_xbox_cloud_settings">إعدادات السحابة</string>
|
||||
<string name="integration_title">تكامل Steam</string>
|
||||
<string name="integration_count">%1$d من %2$d مفعّلة</string>
|
||||
<string name="integration_set_up">إعداد</string>
|
||||
<string name="integration_location">الموقع الجغرافي</string>
|
||||
<string name="integration_app_info">معلومات التطبيق</string>
|
||||
<string name="integration_wifi">أسماء شبكات Wi-Fi</string>
|
||||
<string name="integration_brightness">السطوع</string>
|
||||
<string name="integration_home">DroidDeck كشاشة رئيسية</string>
|
||||
<string name="integration_shortcuts">اختصارات زر الشاشة الرئيسية</string>
|
||||
<string name="integration_wifi_hint">إظهار الشبكات في Steam · يتطلب الوصول إلى الموقع الجغرافي، دون تتبّع أبدًا</string>
|
||||
<string name="integration_wifi_on">تظهر الشبكات في Steam</string>
|
||||
<string name="integration_wifi_location_off">الموقع الجغرافي متوقف</string>
|
||||
<string name="integration_wifi_denied">رُفض الوصول إلى الموقع الجغرافي · اسمح به في معلومات التطبيق</string>
|
||||
<string name="integration_brightness_hint">شريط التمرير في Steam يضبط سطوع الشاشة</string>
|
||||
<string name="integration_home_hint">زر الشاشة الرئيسية يفتح قائمة Steam أثناء الجلسة</string>
|
||||
<string name="integration_shortcuts_hint">اضغط مطوّلًا على زر الشاشة الرئيسية لاختصارات Steam Guide</string>
|
||||
<string name="integration_shortcuts_needs_home">يتطلب DroidDeck كشاشة رئيسية</string>
|
||||
<string name="integration_shortcuts_maybe_restricted">غير متاح في Android؟ معلومات التطبيق → ⋮ → السماح بالإعدادات المحظورة</string>
|
||||
<string name="integration_shortcuts_restricted">محظور من Android · معلومات التطبيق → ⋮ → السماح بالإعدادات المحظورة</string>
|
||||
<string name="integration_shortcuts_service">زر الشاشة الرئيسية في DroidDeck</string>
|
||||
<string name="integration_shortcuts_service_description">يمرّر ضغطات زر الشاشة الرئيسية إلى Steam Guide عندما تكون جلسة Steam في المقدمة ويكون DroidDeck تطبيق الشاشة الرئيسية الافتراضي. لا يقرأ محتوى الشاشة.</string>
|
||||
<string name="integration_brightness_needed">فعّل «السطوع» من الإعداد → تكامل Steam</string>
|
||||
<string name="apps_search_hint">البحث في التطبيقات</string>
|
||||
<string name="apps_no_match">لا توجد تطبيقات تطابق ”%1$s“.</string>
|
||||
<string name="apps_add_widget">إضافة أداة</string>
|
||||
@@ -3346,9 +3531,35 @@
|
||||
<string name="desktop_restore_done_body">التطبيقات التي أضفتها مثبتة مرة أخرى.</string>
|
||||
<string name="desktop_restore_failed_title">تعذّرت استعادة بعض البرامج</string>
|
||||
<string name="desktop_restore_failed_body">راجع ~/.cache/droiddeck/apt-restore.log ثم جرّب sudo apt install في Konsole.</string>
|
||||
<string name="gog_full_files">التحسينات الأصلية غير متاحة. يتضمن التنزيل ملفات بديلة كاملة.</string>
|
||||
<string name="gog_recover">التحقق من نتيجة التصحيح</string>
|
||||
<string name="slow_usb_title">اتصال USB بطيء</string>
|
||||
<string name="slow_usb_cable">%1$s متصل عبر %2$s (%3$s ميغابت/ث، حوالي %4$d ميغابايت/ث)، لذا ستُحمَّل الألعاب عليه ببطء. استخدم كابل USB 3 بسرعة 5 جيجابت/ث أو أكثر، أو جرّب قلب قابس USB-C، أو استخدم محركًا أسرع.</string>
|
||||
<string name="slow_usb_port">%1$s متصل عبر %2$s (%3$s ميغابت/ث، حوالي %4$d ميغابايت/ث). لا يدعم منفذ USB في هذا الجهاز سرعة أعلى، لذا ستُحمَّل الألعاب عليه ببطء. قد تكون الذاكرة الداخلية أو بطاقة microSD أسرع.</string>
|
||||
<string name="slow_usb_never">عدم الإظهار مرة أخرى</string>
|
||||
<string name="slow_usb_dismiss">إغلاق</string>
|
||||
<string name="steam_import_title">هل تريد إعادة تشغيل Steam لإضافة ألعابك؟</string>
|
||||
<string name="steam_import_body">يمكن لـ Steam إدراج هذه الألعاب التي تملكها كألعاب مثبتة: %1$s. يجب إعادة تشغيله لإظهارها. أعد التشغيل الآن، أو ستُضاف في المرة القادمة التي يبدأ فيها Steam.</string>
|
||||
<string name="steam_import_names_more">%1$s و%2$d أخرى</string>
|
||||
<string name="steam_import_now">إعادة التشغيل الآن</string>
|
||||
<string name="steam_import_later">لاحقًا</string>
|
||||
<string name="gog_maintenance">إدارة تثبيت GOG</string>
|
||||
<string name="gog_check">التحقق من وجود تحديثات</string>
|
||||
<string name="gog_repair">التحقق/الإصلاح</string>
|
||||
<string name="gog_patches">تصحيحات بلا اتصال</string>
|
||||
<string name="gog_refresh">تنزيل المثبِّت الكامل بلا اتصال</string>
|
||||
<string name="gog_update">التحديث إلى %1$s</string>
|
||||
<string name="gog_resume">استئناف صيانة GOG</string>
|
||||
<string name="gog_open_patch">فتح مثبِّت التصحيح</string>
|
||||
<string name="gog_patch_in_session">أكمِل مثبِّت التصحيح أو ألغِه في جلسة Linux.</string>
|
||||
<string name="gog_patch_requirements">اختر تصحيحًا يناسب الإصدار المثبَّت ولغتك. قد لا تظهر كل إصدارات المصدر المدعومة.</string>
|
||||
<string name="gog_no_patches">لا تتوفّر لدى GOG تصحيحات Windows مستقلة لهذه اللعبة.</string>
|
||||
<string name="gog_managed_files">قد تُستبدل ملفات اللعبة المعدَّلة.</string>
|
||||
<string name="gog_patch_installer_note">يُفتح المثبِّت في جلسة Linux الخاصة بك.</string>
|
||||
<string name="gog_download_label">التنزيل</string>
|
||||
<string name="gog_space_label">مساحة إضافية</string>
|
||||
<string name="gog_space_estimate_label">المساحة التقديرية</string>
|
||||
<string name="gog_repair_action">إصلاح الملفات</string>
|
||||
<string name="gog_refresh_action">تحديث التثبيت</string>
|
||||
<string name="gog_select_patch">اختيار</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="shortcuts_title">Atajos de botones físicos</string>
|
||||
<string name="shortcuts_dd_menu">Menú de DroidDeck</string>
|
||||
<string name="shortcuts_capture">Asignar: %1$s</string>
|
||||
<string name="shortcuts_press">Presiona y suelta un botón. La asignación se guarda automáticamente.</string>
|
||||
<string name="shortcuts_release">Suelta el botón para continuar.</string>
|
||||
<string name="shortcuts_detected">%1$s: %2$s</string>
|
||||
<string name="shortcuts_conflict">Este botón ya está asignado a: %1$s</string>
|
||||
<string name="shortcuts_save">Reasignar</string>
|
||||
<string name="shortcuts_retry">Probar otro botón</string>
|
||||
<string name="shortcuts_limitations">El botón Inicio y algunos botones adicionales pueden no estar disponibles.</string>
|
||||
</resources>
|
||||
Loaded 100 of 267 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user