mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 04:25:38 +00:00
Compare commits
68
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
332c4ea751 | ||
|
|
41b065e89c | ||
|
|
bc35bb5d43 | ||
|
|
c378489f45 | ||
|
|
ef4e43032c | ||
|
|
62f49756bf | ||
|
|
510c7e35e6 | ||
|
|
57578501e5 | ||
|
|
53b5fde2ff | ||
|
|
6f5db08efb | ||
|
|
d9efc1efee | ||
|
|
f44e3c46e1 | ||
|
|
51e911f9a8 | ||
|
|
f0f17b9b63 | ||
|
|
830c753312 | ||
|
|
a0a68f7280 | ||
|
|
455bf0fba9 | ||
|
|
8df90c30dd | ||
|
|
4de4c65c2a | ||
|
|
bb1cbf95c0 | ||
|
|
7e2d13b641 | ||
|
|
5bdf0d6b04 | ||
|
|
13493d44c3 | ||
|
|
4d7ceb2325 | ||
|
|
a984d11742 | ||
|
|
749ade4a45 | ||
|
|
fa5506df35 | ||
|
|
dde1a55d00 | ||
|
|
c446566f42 | ||
|
|
2e2b950964 | ||
|
|
53d643dd00 | ||
|
|
6a5dfe1486 | ||
|
|
da127d1b4c | ||
|
|
9b68b33e73 | ||
|
|
1f60e57749 | ||
|
|
eaaecf0661 | ||
|
|
d08afbd878 | ||
|
|
36135327f5 | ||
|
|
d65912f0c5 | ||
|
|
5d945d7784 | ||
|
|
ee1b3b26e1 | ||
|
|
9c02233b06 | ||
|
|
f98c272300 | ||
|
|
744a42d324 | ||
|
|
30da4d2bcd | ||
|
|
e492a78f55 | ||
|
|
538b5c5270 | ||
|
|
be5bec2d44 | ||
|
|
fd9de4a21e | ||
|
|
1b3814a587 | ||
|
|
78f95c5a0c | ||
|
|
db56cff880 | ||
|
|
24f0b97c08 | ||
|
|
3b6b304f55 | ||
|
|
c48297e0d1 | ||
|
|
b887e8653d | ||
|
|
9fc48515c1 | ||
|
|
63d1e4d61d | ||
|
|
fbb334263c | ||
|
|
3fd6b1f00d | ||
|
|
5978a13f09 | ||
|
|
c71ba6da96 | ||
|
|
cce742766d | ||
|
|
4922d309c8 | ||
|
|
aa1a8da39a | ||
|
|
73e158ab3b | ||
|
|
0a8358d11f | ||
|
|
1f1873a18e |
No files matched your search
@@ -10,5 +10,3 @@ tools/mangoapp/mangoapp text eol=lf
|
||||
app/src/main/assets/desktop-removal/*.json text eol=lf
|
||||
app/src/main/assets/desktop-removal/*.txt text eol=lf
|
||||
*.pdf binary
|
||||
# Patches are applied by the Linux build roots and pinned by hash.
|
||||
tools/qualcomm/**/*.patch text eol=lf
|
||||
@@ -494,6 +494,16 @@ jobs:
|
||||
- name: Build the add-on packs
|
||||
run: bash tools/packs/build.sh app/build/packs
|
||||
|
||||
- name: Note when the proot pack pin is behind this build
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# shellcheck disable=SC1091
|
||||
source tools/packs/proot/release.env
|
||||
sha=$(sha256sum app/build/packs/proot.tar.zst | cut -d' ' -f1)
|
||||
if [ "$sha" != "$PROOT_PACK_SHA256" ]; then
|
||||
echo "::warning::built proot pack $sha does not match tools/packs/proot/release.env ($PROOT_PACK_SHA256). This build publishes the pack it just built. Source builds keep downloading the pinned pack until release.env is updated."
|
||||
fi
|
||||
|
||||
- name: Build
|
||||
id: build
|
||||
env:
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
# Rules
|
||||
|
||||
- Comments should be rare, factual, and explain only non-obvious external constraints or business invariants.
|
||||
- Always compile APKs with the prepared Linux runtime assets and valid add-on pack checksums so a fresh installation on another phone can install the runtime. Never use `reuseInstalledRuntime` or rely on runtime files already installed on a connected device. Run APK runtime-input verification before sharing a build.
|
||||
@@ -61,7 +61,7 @@ Compatibility and performance vary by device; hardware validation is limited. De
|
||||
|
||||
## Credits and licence
|
||||
|
||||
GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). Epic Games and GOG support build on [Phobos’s](https://github.com/phobos665) adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl), respectively. Battle.net support is [@kayakyakr](https://github.com/kayakyakr)'s: it runs Blizzard's own Battle.net client, downloaded from Blizzard and not included, in Proton, and shows the key art from each game's [Battle.net Shop](https://shop.battle.net) page; without the Steam client its games see DroidDeck's pad as an Xbox 360 controller through `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`. 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. The Steam client's audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink` with its request size kept to its ring so clients are not asked to queue 100 ms ahead. mmap ring-buffer controller input was developed by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). Why the x86-64 Steam client refused the arm64 client's sign-in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest). x86 programs that link OpenSSL 3 under FEX use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt) platform. Hooks written with `WriteProcessMemory` into code [FEX](https://github.com/FEX-Emu/FEX) has translated go through `/proc/<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 is already on through Proton. The proot fast path picks the guest name of a host file bound under several names in the order [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later) sorts its bindings, so links and `/proc/self/fd` read back as they do through proot. The session's [PipeWire](https://gitlab.freedesktop.org/pipewire/pipewire) (MIT) opens its sockets with the per-socket access settings documented in its `module-access.c`, and [WirePlumber](https://gitlab.freedesktop.org/pipewire/wireplumber) (MIT) keeps those clients at full permissions through its `access.rules`. Wine write watches use the userfaultfd support in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/ntdll/unix/virtual.c` (LGPL-2.1-or-later): libblsession gives it the arm64 syscall number and answers its `PAGEMAP_SCAN` from `/proc/self/pagemap` where Android refuses the ioctl. Wine on arm64 sets a thread's full context by raising `SIGUSR2` from `syscall_dispatcher_return_slowpath` in [Wine](https://gitlab.winehq.org/wine/wine)'s `dlls/ntdll/unix/signal_arm64.c` (LGPL-2.1-or-later); libblsession runs that handler in place on a frame laid out as the [Linux](https://github.com/torvalds/linux) kernel's `arch/arm64/kernel/signal.c` builds it and returns through `rt_sigreturn`, so proot does not stop the thread for it. Wine's process list reads each process's memory counters from `/proc/<pid>/status` in `fill_vm_counters` ([Wine](https://gitlab.winehq.org/wine/wine) `dlls/ntdll/unix/process.c`, LGPL-2.1-or-later), so libblsession gives those reads the kernel's file instead of a copy with `TracerPid` cleared. droiddeck-ntsync is checked against the object, wait and error semantics documented for the [Linux](https://github.com/torvalds/linux) ntsync driverLine truncated
|
||||
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. 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 is already on through Proton. The proot fast path picks the guest name of a host file bound under several names in the order [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later) sorts its bindings, so links and `/proc/self/fd` read back as they do through proot. The session's [PipeWire](https://gitlab.freedesktop.org/pipewire/pipewire) (MIT) opens its sockets with the per-socket access settings documented in its `module-access.c`, and [WirePlumber](https://gitlab.freedesktop.org/pipewire/wireplumber) (MIT) keeps those clients at full permissions through its `access.rules`. Wine write watches use the userfaultLine truncated
|
||||
|
||||
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.
|
||||
|
||||
|
||||
+60
-61
@@ -79,12 +79,6 @@ def sourceCommit = providers.environmentVariable('DROIDDECK_SOURCE_COMMIT').getO
|
||||
?: providers.environmentVariable('GITHUB_SHA').getOrNull() ?: gitValue(['rev-parse', 'HEAD']) ?: ''
|
||||
def prNumber = (providers.environmentVariable('DROIDDECK_PR_NUMBER').getOrNull() ?: '0').with { it.isInteger() ? it : '0' }
|
||||
def ciBuild = providers.environmentVariable('GITHUB_ACTIONS').getOrNull() == 'true'
|
||||
if (project.hasProperty('reuseInstalledRuntime')) throw new GradleException('All APKs require prepared Linux runtime packages; runtime reuse is not allowed')
|
||||
def qualcommRuntime = new groovy.json.JsonSlurper().parse(rootProject.file('tools/qualcomm/runtime.json'))
|
||||
def qualcommSources = fileTree(rootProject.file('tools/qualcomm')) { include '*.py', '*.c', '*.json', '*.sh', '**/*.patch' }
|
||||
def qualcommDigest = java.security.MessageDigest.getInstance('SHA-256')
|
||||
qualcommSources.files.sort { it.name }.each { qualcommDigest.update(it.bytes) }
|
||||
def qualcommRevision = qualcommDigest.digest().encodeHex().toString()
|
||||
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' }
|
||||
def desktopKde = rootProject.file('tools/desktop-kde/release.env').readLines()
|
||||
@@ -93,10 +87,18 @@ def desktopKde = rootProject.file('tools/desktop-kde/release.env').readLines()
|
||||
def trackingPack = rootProject.file('tools/packs/tracking/release.env').readLines()
|
||||
.findAll { it.contains('=') && !it.startsWith('#') }
|
||||
.collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] }
|
||||
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 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")
|
||||
// A source build that did not compile proot still pins a published pack, so the app
|
||||
// downloads the patched binary instead of falling back to the rootfs copy.
|
||||
if (name == 'proot' && prootPackPin.PROOT_PACK_SHA256) {
|
||||
return [(name): [sha256: prootPackPin.PROOT_PACK_SHA256, size: (prootPackPin.PROOT_PACK_SIZE ?: '0') as long]]
|
||||
}
|
||||
return [(name): [sha256: '', size: 0L]]
|
||||
}
|
||||
def digest = java.security.MessageDigest.getInstance('SHA-256')
|
||||
@@ -134,9 +136,6 @@ android {
|
||||
buildConfigField "String", "SOURCE_COMMIT", "\"${sourceCommit}\""
|
||||
buildConfigField "int", "PR_NUMBER", "${prNumber}"
|
||||
buildConfigField "boolean", "CI_BUILD", "${ciBuild}"
|
||||
buildConfigField "String", "QUALCOMM_BRIDGE_SHA256", "\"${qualcommRuntime.sha256}\""
|
||||
buildConfigField "String", "QUALCOMM_GAMESCOPE_SHA256", "\"${qualcommRuntime.gamescope.member_sha256}\""
|
||||
buildConfigField "String", "QUALCOMM_FIXES_REVISION", "\"${qualcommRevision}\""
|
||||
buildConfigField "String", "RELEASE_SIGNER", "\"${releaseSigner}\""
|
||||
buildConfigField "long", "COMMIT_TIME", "${commitTime}L * 1000L"
|
||||
buildConfigField "String", "VARIANT_SUFFIXES", "\"${variantSuffixes}\""
|
||||
@@ -263,16 +262,6 @@ def stageSessionScripts = tasks.register('stageSessionScripts', Copy) {
|
||||
from(rootProject.file('tools/linuxfs/overlay')) {
|
||||
include 'usr/local/bin/droiddeck-*', 'usr/local/bin/steam-compatibility', 'usr/bin/**'
|
||||
}
|
||||
from(rootProject.file('tools/linuxfs/desktop')) {
|
||||
include 'droiddeck-gpu', 'droiddeck-desktop', 'droiddeck-desktop-gpu', 'kwin_wayland_wrapper'
|
||||
into 'usr/local/bin'
|
||||
}
|
||||
from(rootProject.file('tools/linuxfs/desktop/firefox-droiddeck.js')) {
|
||||
into 'usr/lib/firefox/defaults/pref'
|
||||
rename { 'droiddeck.js' }
|
||||
}
|
||||
from(rootProject.file('tools/linuxfs/desktop/droiddeck-clipboard.desktop')) { into 'etc/xdg/autostart' }
|
||||
from(rootProject.file('tools/mangoapp/mangoapp')) { into 'usr/local/bin' }
|
||||
into(layout.projectDirectory.dir('src/main/assets/linuxfs'))
|
||||
}
|
||||
tasks.named('preBuild').configure { dependsOn(stageSessionScripts) }
|
||||
@@ -286,35 +275,6 @@ def stageRuntimeAssets = tasks.register('stageRuntimeAssets', Sync) {
|
||||
into(runtimeAssetsDir)
|
||||
}
|
||||
android.sourceSets.main.assets.setSrcDirs([runtimeAssetsDir])
|
||||
def fetchQualcommBuilds = tasks.register('fetchQualcommBuilds', Exec) {
|
||||
workingDir rootProject.projectDir
|
||||
commandLine pythonExecutable, 'tools/qualcomm/fetch_runtime.py', '--builds-only',
|
||||
'--cache', rootProject.file('build/qualcomm-cache').absolutePath
|
||||
}
|
||||
def stageQualcommRuntime = tasks.register('stageQualcommRuntime', Exec) {
|
||||
dependsOn fetchQualcommBuilds
|
||||
workingDir rootProject.projectDir
|
||||
inputs.files(qualcommSources)
|
||||
if (qualcommRuntime.gamescope.build) {
|
||||
inputs.file(rootProject.file(qualcommRuntime.gamescope.build.binary))
|
||||
inputs.file(rootProject.file(qualcommRuntime.gamescope.build.source))
|
||||
}
|
||||
if (qualcommRuntime.mesa) {
|
||||
inputs.dir(rootProject.file(qualcommRuntime.mesa.directory))
|
||||
}
|
||||
if (qualcommRuntime.wsi?.build) {
|
||||
inputs.dir(rootProject.file(qualcommRuntime.wsi.build.directory))
|
||||
}
|
||||
inputs.property('ndkVersion', android.ndkVersion)
|
||||
outputs.dir(layout.buildDirectory.dir('qualcommAssets'))
|
||||
commandLine pythonExecutable, 'tools/qualcomm/fetch_runtime.py',
|
||||
'--output', layout.buildDirectory.dir('qualcommAssets/qualcomm').get().asFile.absolutePath,
|
||||
'--cache', rootProject.file('build/qualcomm-cache').absolutePath,
|
||||
'--ndk', android.ndkDirectory.absolutePath
|
||||
}
|
||||
android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('qualcommAssets'))
|
||||
tasks.named('preBuild').configure { dependsOn(stageQualcommRuntime) }
|
||||
tasks.matching { it.name.toLowerCase(Locale.ROOT).contains('lint') }.configureEach { dependsOn(stageQualcommRuntime) }
|
||||
if (vitureSdkDir) android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('vitureAssets'))
|
||||
if (uvcDir) {
|
||||
def stageUvcNotices = tasks.register('stageUvcNotices', Copy) {
|
||||
@@ -332,19 +292,7 @@ def verifyRuntimeInputs = tasks.register('verifyRuntimeInputs', Exec) {
|
||||
commandLine pythonExecutable, 'tools/release/runtime_inputs.py', 'verify'
|
||||
}
|
||||
tasks.configureEach { task ->
|
||||
if (task.name == 'packageRelease') {
|
||||
task.dependsOn(verifyRuntimeInputs)
|
||||
}
|
||||
if (task.name == 'packageDebug') task.dependsOn(verifyRuntimeInputs)
|
||||
}
|
||||
|
||||
['Debug', 'Release'].each { variant ->
|
||||
def verifyApk = tasks.register("verify${variant}PackagedRuntime", Exec) {
|
||||
workingDir rootProject.projectDir
|
||||
commandLine pythonExecutable, 'tools/release/runtime_inputs.py', 'apk',
|
||||
layout.buildDirectory.file("outputs/apk/${variant.toLowerCase()}/app-${variant.toLowerCase()}.apk").get().asFile.absolutePath
|
||||
}
|
||||
tasks.matching { it.name == "assemble${variant}" }.configureEach { finalizedBy(verifyApk) }
|
||||
if (task.name in ['packageDebug', 'packageRelease']) task.dependsOn(verifyRuntimeInputs)
|
||||
}
|
||||
|
||||
def rustCrateDir = layout.projectDirectory.dir('src/main/rust/stores')
|
||||
@@ -377,6 +325,57 @@ def buildRustStores = tasks.register('buildRustStores', Exec) {
|
||||
if (!skipRust) android.sourceSets.main.jniLibs.srcDir(rustJniLibsDir)
|
||||
tasks.named('preBuild').configure { dependsOn(buildRustStores) }
|
||||
|
||||
// GeForce NOW: DroidDeck's streamer host (libdroiddeckgfn.so, src/main/rust/gfn) and OpenNOW's
|
||||
// core service (external/opennow, MIT, by Zortos). The core is a program the app runs as a child
|
||||
// process, so it ships as libopennowcore.so in the native library directory (the one place the
|
||||
// app may exec from), like the Mali bridge server.
|
||||
def gfnCrateDir = layout.projectDirectory.dir('src/main/rust/gfn')
|
||||
def openNowCoreDir = rootProject.layout.projectDirectory.dir('external/opennow/native/opennow-core')
|
||||
def gfnJniLibsDir = layout.buildDirectory.dir('gfnJniLibs')
|
||||
def gfnCargoEnvironment = { Exec task ->
|
||||
def cargoBin = "${System.getProperty('user.home')}/.cargo/bin"
|
||||
task.environment 'PATH', "${cargoBin}${File.pathSeparator}${System.getenv('PATH')}"
|
||||
task.environment 'ANDROID_NDK_HOME', android.ndkDirectory.absolutePath
|
||||
task.environment 'CARGO_TERM_COLOR', 'never'
|
||||
// bindgen (the mtu crate) otherwise passes an unversioned Android triple, which the NDK headers reject.
|
||||
task.environment 'BINDGEN_EXTRA_CLANG_ARGS_aarch64_linux_android', '--target=aarch64-linux-android29'
|
||||
}
|
||||
def buildGfnHost = tasks.register('buildGfnHost', Exec) {
|
||||
description = 'Cross-compiles the GeForce NOW streamer host (libdroiddeckgfn.so) with cargo-ndk.'
|
||||
onlyIf { !skipRust }
|
||||
inputs.dir(gfnCrateDir.dir('src'))
|
||||
inputs.files(gfnCrateDir.file('Cargo.toml'), gfnCrateDir.file('Cargo.lock'))
|
||||
inputs.dir(rootProject.file('external/opennow/native/opennow-streamer/crates'))
|
||||
inputs.property('ndkVersion', android.ndkVersion)
|
||||
outputs.dir(gfnJniLibsDir)
|
||||
workingDir gfnCrateDir
|
||||
gfnCargoEnvironment(it)
|
||||
commandLine 'rustup', 'run', 'stable', 'cargo', 'ndk', '--target', 'arm64-v8a', '--platform', '29',
|
||||
'--output-dir', gfnJniLibsDir.get().asFile.absolutePath,
|
||||
'build', '--release', '--locked'
|
||||
}
|
||||
def buildOpenNowCore = tasks.register('buildOpenNowCore', Exec) {
|
||||
description = "Cross-compiles OpenNOW's core service and stages it as libopennowcore.so."
|
||||
onlyIf { !skipRust }
|
||||
inputs.dir(openNowCoreDir.dir('src'))
|
||||
inputs.files(openNowCoreDir.file('Cargo.toml'), openNowCoreDir.file('Cargo.lock'))
|
||||
inputs.property('ndkVersion', android.ndkVersion)
|
||||
outputs.file(gfnJniLibsDir.map { it.file('arm64-v8a/libopennowcore.so') })
|
||||
workingDir openNowCoreDir
|
||||
gfnCargoEnvironment(it)
|
||||
commandLine 'rustup', 'run', 'stable', 'cargo', 'ndk', '--target', 'arm64-v8a', '--platform', '29',
|
||||
'build', '--release', '--locked', '--bin', 'opennow-core'
|
||||
doLast {
|
||||
def built = openNowCoreDir.file('target/aarch64-linux-android/release/opennow-core').asFile
|
||||
def staged = gfnJniLibsDir.get().file('arm64-v8a/libopennowcore.so').asFile
|
||||
staged.parentFile.mkdirs()
|
||||
java.nio.file.Files.copy(built.toPath(), staged.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING)
|
||||
}
|
||||
}
|
||||
buildOpenNowCore.configure { mustRunAfter(buildGfnHost) }
|
||||
if (!skipRust) android.sourceSets.main.jniLibs.srcDir(gfnJniLibsDir)
|
||||
tasks.named('preBuild').configure { dependsOn(buildGfnHost, buildOpenNowCore) }
|
||||
|
||||
dependencies {
|
||||
implementation "org.opencv:opencv:${trackingPack.OPENCV_VERSION}"
|
||||
implementation 'org.khronos.openxr:openxr_loader_for_android:1.1.49'
|
||||
|
||||
@@ -27,6 +27,8 @@
|
||||
<uses-permission android:name="android.permission.VIBRATE" />
|
||||
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
||||
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
|
||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
@@ -73,7 +75,7 @@
|
||||
<activity
|
||||
android:name=".FrontEndActivity"
|
||||
android:exported="true"
|
||||
android:screenOrientation="sensorLandscape"
|
||||
android:screenOrientation="user"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density|keyboard|keyboardHidden|navigation">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
@@ -125,7 +127,7 @@
|
||||
android:excludeFromRecents="true"
|
||||
android:noHistory="true"
|
||||
android:taskAffinity="${applicationId}.home"
|
||||
android:screenOrientation="sensorLandscape"
|
||||
android:screenOrientation="user"
|
||||
android:theme="@android:style/Theme.Translucent.NoTitleBar">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
@@ -146,14 +148,14 @@
|
||||
<activity
|
||||
android:name=".files.FileManagerActivity"
|
||||
android:exported="false"
|
||||
android:screenOrientation="sensorLandscape"
|
||||
android:screenOrientation="user"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
<activity
|
||||
android:name=".files.FilePickerActivity"
|
||||
android:exported="false"
|
||||
android:screenOrientation="sensorLandscape"
|
||||
android:screenOrientation="user"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
@@ -178,6 +180,15 @@
|
||||
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|density|navigation|uiMode"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
<!-- GeForce NOW (OpenNOW's core and streamer): the core child and the player share the :gfn process;
|
||||
the Stores page reaches the core through GfnCoreService. -->
|
||||
<service android:name=".stores.gfn.GfnCoreService" android:exported="false" android:process=":gfn" />
|
||||
|
||||
<activity android:name=".stores.gfn.GfnPlayerActivity" android:exported="false"
|
||||
android:process=":gfn" android:screenOrientation="sensorLandscape" android:hardwareAccelerated="true"
|
||||
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|density|navigation|uiMode"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
<activity android:name=".stores.xbox.XboxCloudSettingsActivity" android:exported="false"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
||||
android:theme="@style/AppTheme" />
|
||||
@@ -185,7 +196,7 @@
|
||||
<activity
|
||||
android:name=".stores.StoreLoginActivity"
|
||||
android:exported="false"
|
||||
android:screenOrientation="sensorLandscape"
|
||||
android:screenOrientation="user"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
|
||||
@@ -75,13 +75,11 @@ Java_com_droiddeck_launcher_gpu_VulkanInfo_nativeQuery(JNIEnv *env, jclass clazz
|
||||
VkPhysicalDeviceDriverProperties driver = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES };
|
||||
VkPhysicalDeviceProperties2 p2 = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, .pNext = &driver };
|
||||
vkGetPhysicalDeviceProperties2(device, &p2);
|
||||
LINE("driver_id=%u\n", driver.driverID);
|
||||
LINE("driver_name=%s\n", driver.driverName);
|
||||
LINE("driver_info=%s\n", driver.driverInfo);
|
||||
LINE("conformance=%u.%u.%u.%u\n", driver.conformanceVersion.major, driver.conformanceVersion.minor,
|
||||
driver.conformanceVersion.subminor, driver.conformanceVersion.patch);
|
||||
}
|
||||
LINE("driver_version_raw=%u\n", p.driverVersion);
|
||||
LINE("extension_count=%u\n", extCount);
|
||||
for (size_t e = 0; e < sizeof(EXTENSIONS) / sizeof(*EXTENSIONS); e++) {
|
||||
int has = 0;
|
||||
|
||||
@@ -184,8 +184,9 @@ bool FrameGen::onResize(VkExtent2D extent, VkFormat , bool force) {
|
||||
VkExtent2D e = levelExtent(extent, l);
|
||||
if (!makeImage(pyrA_[l], e, VK_FORMAT_R32_SFLOAT, lumaUsage)) return false;
|
||||
if (!makeImage(pyrB_[l], e, VK_FORMAT_R32_SFLOAT, lumaUsage)) return false;
|
||||
if (!makeImage(flowLvl_[l], e, VK_FORMAT_R16G16B16A16_SFLOAT, flowUsage)) return false;
|
||||
}
|
||||
for (int l = flowFinest_; l < kLevels; ++l)
|
||||
if (!makeImage(flowLvl_[l], levelExtent(extent, l), VK_FORMAT_R16G16B16A16_SFLOAT, flowUsage)) return false;
|
||||
pyrAs_.resize(kLevels);
|
||||
for (int l = flowFinest_; l < kLevels; ++l)
|
||||
if (!makeImage(pyrAs_[l], levelExtent(extent, l), VK_FORMAT_R32_SFLOAT, lumaUsage)) return false;
|
||||
|
||||
@@ -439,7 +439,7 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
|
||||
makeUbo(dd, dev, mp, sizeof(FlowRegUBO), S.flowRegUbo, S.flowRegUboMem, S.flowRegUboPtr);
|
||||
if (S.flowRegUboPtr) { FlowRegUBO fu{cfg.frDt, cfg.frLambda, cfg.frEdge, cfg.frEps}; std::memcpy(S.flowRegUboPtr, &fu, sizeof(fu)); }
|
||||
S.flowUbo.resize(kLevels); S.flowUboMem.resize(kLevels); S.flowUboPtr.resize(kLevels);
|
||||
for (int l = 0; l < kLevels; ++l) {
|
||||
for (int l = fg->flowFinest(); l < kLevels; ++l) {
|
||||
makeUbo(dd, dev, mp, sizeof(FlowUBO), S.flowUbo[l], S.flowUboMem[l], S.flowUboPtr[l]);
|
||||
if (S.flowUboPtr[l]) { FlowUBO u{cfg.flowScale, (uint32_t)l, 0.6f, 1.6f}; std::memcpy(S.flowUboPtr[l], &u, sizeof(u)); }
|
||||
}
|
||||
@@ -464,13 +464,12 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
|
||||
}
|
||||
|
||||
S.sFlow.resize(kLevels);
|
||||
for (int l = 0; l < kLevels; ++l) {
|
||||
for (int l = fg->flowFinest(); l < kLevels; ++l) {
|
||||
S.sFlow[l] = allocSet(dd, dev, pool, pFlow.setLayout);
|
||||
int pred = (l + 1 < kLevels) ? l + 1 : l;
|
||||
VkImageView currLvl = (l >= fg->flowFinest()) ? pyrAs[l].view : pyrA[l].view;
|
||||
wUbo(dd, dev, S.sFlow[l], 0, S.flowUbo[l], sizeof(FlowUBO));
|
||||
wImg(dd, dev, S.sFlow[l], 32, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, pyrB[l].view, samp, GEN);
|
||||
wImg(dd, dev, S.sFlow[l], 33, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, currLvl, samp, GEN);
|
||||
wImg(dd, dev, S.sFlow[l], 33, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, pyrAs[l].view, samp, GEN);
|
||||
wImg(dd, dev, S.sFlow[l], 34, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, flowLvl[pred].view, samp, GEN);
|
||||
wImg(dd, dev, S.sFlow[l], 48, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, flowLvl[l].view, VK_NULL_HANDLE, GEN);
|
||||
}
|
||||
|
||||
@@ -10,8 +10,6 @@ add_library(droiddeckwayland SHARED
|
||||
src/waylandcomp_jni.c
|
||||
src/gpu_clock_pin.c
|
||||
src/droiddeck_ext.c
|
||||
src/wl_android_buffer.c
|
||||
generated/wayland-android-protocol.c
|
||||
src/wl_dmabuf.c
|
||||
src/wl_clipboard.c
|
||||
src/wl_text_input.c
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
/* Generated by wayland-scanner 1.26.0 */
|
||||
|
||||
/*
|
||||
* Copyright © 2012 Collabora, Ltd.
|
||||
*
|
||||
* Permission to use, copy, modify, distribute, and sell this
|
||||
* software and its documentation for any purpose is hereby granted
|
||||
* without fee, provided that the above copyright notice appear in
|
||||
* all copies and that both that copyright notice and this permission
|
||||
* notice appear in supporting documentation, and that the name of
|
||||
* the copyright holders not be used in advertising or publicity
|
||||
* pertaining to distribution of the software without specific,
|
||||
* written prior permission. The copyright holders make no
|
||||
* representations about the suitability of this software for any
|
||||
* purpose. It is provided "as is" without express or implied
|
||||
* warranty.
|
||||
*
|
||||
* THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
|
||||
* SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||
* FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
* SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
|
||||
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
|
||||
* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
|
||||
* THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdint.h>
|
||||
#include "wayland-util.h"
|
||||
|
||||
#ifndef __has_attribute
|
||||
# define __has_attribute(x) 0 /* Compatibility with non-clang compilers. */
|
||||
#endif
|
||||
|
||||
#if (__has_attribute(visibility) || defined(__GNUC__) && __GNUC__ >= 4)
|
||||
#define WL_PRIVATE __attribute__ ((visibility("hidden")))
|
||||
#else
|
||||
#define WL_PRIVATE
|
||||
#endif
|
||||
|
||||
extern const struct wl_interface android_wlegl_handle_interface;
|
||||
extern const struct wl_interface android_wlegl_server_buffer_handle_interface;
|
||||
extern const struct wl_interface wl_buffer_interface;
|
||||
|
||||
static const struct wl_interface *android_types[] = {
|
||||
NULL,
|
||||
NULL,
|
||||
&android_wlegl_handle_interface,
|
||||
NULL,
|
||||
NULL,
|
||||
&wl_buffer_interface,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
&android_wlegl_handle_interface,
|
||||
&android_wlegl_server_buffer_handle_interface,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
&wl_buffer_interface,
|
||||
NULL,
|
||||
NULL,
|
||||
};
|
||||
|
||||
static const struct wl_message android_wlegl_requests[] = {
|
||||
{ "create_handle", "nia", android_types + 2 },
|
||||
{ "create_buffer", "niiiiio", android_types + 5 },
|
||||
{ "get_server_buffer_handle", "2niiii", android_types + 12 },
|
||||
};
|
||||
|
||||
WL_PRIVATE const struct wl_interface android_wlegl_interface = {
|
||||
"android_wlegl", 3,
|
||||
3, android_wlegl_requests,
|
||||
0, NULL,
|
||||
};
|
||||
|
||||
static const struct wl_message android_wlegl_handle_requests[] = {
|
||||
{ "add_fd", "h", android_types + 0 },
|
||||
{ "destroy", "", android_types + 0 },
|
||||
};
|
||||
|
||||
WL_PRIVATE const struct wl_interface android_wlegl_handle_interface = {
|
||||
"android_wlegl_handle", 1,
|
||||
2, android_wlegl_handle_requests,
|
||||
0, NULL,
|
||||
};
|
||||
|
||||
static const struct wl_message android_wlegl_server_buffer_handle_events[] = {
|
||||
{ "buffer_fd", "h", android_types + 0 },
|
||||
{ "buffer_ints", "a", android_types + 0 },
|
||||
{ "buffer", "nii", android_types + 17 },
|
||||
{ "linear_layout", "3uu", android_types + 0 },
|
||||
};
|
||||
|
||||
WL_PRIVATE const struct wl_interface android_wlegl_server_buffer_handle_interface = {
|
||||
"android_wlegl_server_buffer_handle", 3,
|
||||
0, NULL,
|
||||
4, android_wlegl_server_buffer_handle_events,
|
||||
};
|
||||
@@ -1,341 +0,0 @@
|
||||
/* Generated by wayland-scanner 1.26.0 */
|
||||
|
||||
#ifndef ANDROID_SERVER_PROTOCOL_H
|
||||
#define ANDROID_SERVER_PROTOCOL_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include "wayland-server.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
struct wl_client;
|
||||
struct wl_resource;
|
||||
|
||||
/**
|
||||
* @page page_android The android protocol
|
||||
* @section page_ifaces_android Interfaces
|
||||
* - @subpage page_iface_android_wlegl - Android EGL graphics buffer support
|
||||
* - @subpage page_iface_android_wlegl_handle - An Android native_handle_t object
|
||||
* - @subpage page_iface_android_wlegl_server_buffer_handle - a server allocated buffer
|
||||
* @section page_copyright_android Copyright
|
||||
* <pre>
|
||||
*
|
||||
* Copyright © 2012 Collabora, Ltd.
|
||||
*
|
||||
* Permission to use, copy, modify, distribute, and sell this
|
||||
* software and its documentation for any purpose is hereby granted
|
||||
* without fee, provided that the above copyright notice appear in
|
||||
* all copies and that both that copyright notice and this permission
|
||||
* notice appear in supporting documentation, and that the name of
|
||||
* the copyright holders not be used in advertising or publicity
|
||||
* pertaining to distribution of the software without specific,
|
||||
* written prior permission. The copyright holders make no
|
||||
* representations about the suitability of this software for any
|
||||
* purpose. It is provided "as is" without express or implied
|
||||
* warranty.
|
||||
*
|
||||
* THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
|
||||
* SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||
* FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
* SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
|
||||
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
|
||||
* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
|
||||
* THIS SOFTWARE.
|
||||
* </pre>
|
||||
*/
|
||||
struct android_wlegl;
|
||||
struct android_wlegl_handle;
|
||||
struct android_wlegl_server_buffer_handle;
|
||||
struct wl_buffer;
|
||||
|
||||
#ifndef ANDROID_WLEGL_INTERFACE
|
||||
#define ANDROID_WLEGL_INTERFACE
|
||||
/**
|
||||
* @page page_iface_android_wlegl android_wlegl
|
||||
* @section page_iface_android_wlegl_desc Description
|
||||
*
|
||||
* Interface used in the Android wrapper libEGL to share
|
||||
* graphics buffers between the server and the client.
|
||||
* @section page_iface_android_wlegl_api API
|
||||
* See @ref iface_android_wlegl.
|
||||
*/
|
||||
/**
|
||||
* @defgroup iface_android_wlegl The android_wlegl interface
|
||||
*
|
||||
* Interface used in the Android wrapper libEGL to share
|
||||
* graphics buffers between the server and the client.
|
||||
*/
|
||||
extern const struct wl_interface android_wlegl_interface;
|
||||
#endif
|
||||
#ifndef ANDROID_WLEGL_HANDLE_INTERFACE
|
||||
#define ANDROID_WLEGL_HANDLE_INTERFACE
|
||||
/**
|
||||
* @page page_iface_android_wlegl_handle android_wlegl_handle
|
||||
* @section page_iface_android_wlegl_handle_desc Description
|
||||
*
|
||||
* The Android native_handle_t is a semi-opaque object, that
|
||||
* contains an EGL implementation specific number of int32
|
||||
* values and file descriptors.
|
||||
*
|
||||
* We cannot send a variable size array of file descriptors
|
||||
* over the Wayland protocol, so we send them one by one.
|
||||
* @section page_iface_android_wlegl_handle_api API
|
||||
* See @ref iface_android_wlegl_handle.
|
||||
*/
|
||||
/**
|
||||
* @defgroup iface_android_wlegl_handle The android_wlegl_handle interface
|
||||
*
|
||||
* The Android native_handle_t is a semi-opaque object, that
|
||||
* contains an EGL implementation specific number of int32
|
||||
* values and file descriptors.
|
||||
*
|
||||
* We cannot send a variable size array of file descriptors
|
||||
* over the Wayland protocol, so we send them one by one.
|
||||
*/
|
||||
extern const struct wl_interface android_wlegl_handle_interface;
|
||||
#endif
|
||||
#ifndef ANDROID_WLEGL_SERVER_BUFFER_HANDLE_INTERFACE
|
||||
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_INTERFACE
|
||||
/**
|
||||
* @page page_iface_android_wlegl_server_buffer_handle android_wlegl_server_buffer_handle
|
||||
* @section page_iface_android_wlegl_server_buffer_handle_desc Description
|
||||
*
|
||||
* On creation a server_side_buffer object will immediately send
|
||||
* the "buffer_fd" and "buffer_ints" events needed by the client to
|
||||
* reference the gralloc buffer, followed by the "buffer" event carrying
|
||||
* the wl_buffer object.
|
||||
* @section page_iface_android_wlegl_server_buffer_handle_api API
|
||||
* See @ref iface_android_wlegl_server_buffer_handle.
|
||||
*/
|
||||
/**
|
||||
* @defgroup iface_android_wlegl_server_buffer_handle The android_wlegl_server_buffer_handle interface
|
||||
*
|
||||
* On creation a server_side_buffer object will immediately send
|
||||
* the "buffer_fd" and "buffer_ints" events needed by the client to
|
||||
* reference the gralloc buffer, followed by the "buffer" event carrying
|
||||
* the wl_buffer object.
|
||||
*/
|
||||
extern const struct wl_interface android_wlegl_server_buffer_handle_interface;
|
||||
#endif
|
||||
|
||||
#ifndef ANDROID_WLEGL_ERROR_ENUM
|
||||
#define ANDROID_WLEGL_ERROR_ENUM
|
||||
enum android_wlegl_error {
|
||||
ANDROID_WLEGL_ERROR_BAD_HANDLE = 0,
|
||||
ANDROID_WLEGL_ERROR_BAD_VALUE = 1,
|
||||
};
|
||||
#endif /* ANDROID_WLEGL_ERROR_ENUM */
|
||||
|
||||
#ifndef ANDROID_WLEGL_ERROR_ENUM_IS_VALID
|
||||
#define ANDROID_WLEGL_ERROR_ENUM_IS_VALID
|
||||
/**
|
||||
* @ingroup iface_android_wlegl
|
||||
* Validate a android_wlegl error value.
|
||||
*
|
||||
* @return true on success, false on error.
|
||||
* @ref android_wlegl_error
|
||||
*/
|
||||
static inline bool
|
||||
android_wlegl_error_is_valid(uint32_t value, uint32_t version) {
|
||||
switch (value) {
|
||||
case ANDROID_WLEGL_ERROR_BAD_HANDLE:
|
||||
return version >= 1;
|
||||
case ANDROID_WLEGL_ERROR_BAD_VALUE:
|
||||
return version >= 1;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
#endif /* ANDROID_WLEGL_ERROR_ENUM_IS_VALID */
|
||||
|
||||
/**
|
||||
* @ingroup iface_android_wlegl
|
||||
* @struct android_wlegl_interface
|
||||
*/
|
||||
struct android_wlegl_interface {
|
||||
/**
|
||||
* Create an Android native_handle_t object
|
||||
*
|
||||
* This creator method initialises the native_handle_t object
|
||||
* with everything except the file descriptors, which have to be
|
||||
* submitted separately.
|
||||
* @param ints an array of int32_t
|
||||
*/
|
||||
void (*create_handle)(struct wl_client *client,
|
||||
struct wl_resource *resource,
|
||||
uint32_t id,
|
||||
int32_t num_fds,
|
||||
struct wl_array *ints);
|
||||
/**
|
||||
* Create a wl_buffer from the native handle
|
||||
*
|
||||
* Pass the Android native_handle_t to the server and attach it
|
||||
* to the new wl_buffer object.
|
||||
*
|
||||
* The android_wlegl_handle object must be destroyed immediately
|
||||
* after this request.
|
||||
*/
|
||||
void (*create_buffer)(struct wl_client *client,
|
||||
struct wl_resource *resource,
|
||||
uint32_t id,
|
||||
int32_t width,
|
||||
int32_t height,
|
||||
int32_t stride,
|
||||
int32_t format,
|
||||
int32_t usage,
|
||||
struct wl_resource *native_handle);
|
||||
/**
|
||||
* @since 2
|
||||
*/
|
||||
void (*get_server_buffer_handle)(struct wl_client *client,
|
||||
struct wl_resource *resource,
|
||||
uint32_t id,
|
||||
int32_t width,
|
||||
int32_t height,
|
||||
int32_t format,
|
||||
int32_t usage);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @ingroup iface_android_wlegl
|
||||
*/
|
||||
#define ANDROID_WLEGL_CREATE_HANDLE_SINCE_VERSION 1
|
||||
/**
|
||||
* @ingroup iface_android_wlegl
|
||||
*/
|
||||
#define ANDROID_WLEGL_CREATE_BUFFER_SINCE_VERSION 1
|
||||
/**
|
||||
* @ingroup iface_android_wlegl
|
||||
*/
|
||||
#define ANDROID_WLEGL_GET_SERVER_BUFFER_HANDLE_SINCE_VERSION 2
|
||||
|
||||
#ifndef ANDROID_WLEGL_HANDLE_ERROR_ENUM
|
||||
#define ANDROID_WLEGL_HANDLE_ERROR_ENUM
|
||||
enum android_wlegl_handle_error {
|
||||
ANDROID_WLEGL_HANDLE_ERROR_TOO_MANY_FDS = 0,
|
||||
};
|
||||
#endif /* ANDROID_WLEGL_HANDLE_ERROR_ENUM */
|
||||
|
||||
#ifndef ANDROID_WLEGL_HANDLE_ERROR_ENUM_IS_VALID
|
||||
#define ANDROID_WLEGL_HANDLE_ERROR_ENUM_IS_VALID
|
||||
/**
|
||||
* @ingroup iface_android_wlegl_handle
|
||||
* Validate a android_wlegl_handle error value.
|
||||
*
|
||||
* @return true on success, false on error.
|
||||
* @ref android_wlegl_handle_error
|
||||
*/
|
||||
static inline bool
|
||||
android_wlegl_handle_error_is_valid(uint32_t value, uint32_t version) {
|
||||
switch (value) {
|
||||
case ANDROID_WLEGL_HANDLE_ERROR_TOO_MANY_FDS:
|
||||
return version >= 1;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
#endif /* ANDROID_WLEGL_HANDLE_ERROR_ENUM_IS_VALID */
|
||||
|
||||
/**
|
||||
* @ingroup iface_android_wlegl_handle
|
||||
* @struct android_wlegl_handle_interface
|
||||
*/
|
||||
struct android_wlegl_handle_interface {
|
||||
/**
|
||||
*/
|
||||
void (*add_fd)(struct wl_client *client,
|
||||
struct wl_resource *resource,
|
||||
int32_t fd);
|
||||
/**
|
||||
*/
|
||||
void (*destroy)(struct wl_client *client,
|
||||
struct wl_resource *resource);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @ingroup iface_android_wlegl_handle
|
||||
*/
|
||||
#define ANDROID_WLEGL_HANDLE_ADD_FD_SINCE_VERSION 1
|
||||
/**
|
||||
* @ingroup iface_android_wlegl_handle
|
||||
*/
|
||||
#define ANDROID_WLEGL_HANDLE_DESTROY_SINCE_VERSION 1
|
||||
|
||||
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_FD 0
|
||||
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_INTS 1
|
||||
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER 2
|
||||
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_LINEAR_LAYOUT 3
|
||||
|
||||
/**
|
||||
* @ingroup iface_android_wlegl_server_buffer_handle
|
||||
*/
|
||||
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_FD_SINCE_VERSION 1
|
||||
/**
|
||||
* @ingroup iface_android_wlegl_server_buffer_handle
|
||||
*/
|
||||
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_INTS_SINCE_VERSION 1
|
||||
/**
|
||||
* @ingroup iface_android_wlegl_server_buffer_handle
|
||||
*/
|
||||
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_SINCE_VERSION 1
|
||||
/**
|
||||
* @ingroup iface_android_wlegl_server_buffer_handle
|
||||
*/
|
||||
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_LINEAR_LAYOUT_SINCE_VERSION 3
|
||||
|
||||
|
||||
/**
|
||||
* @ingroup iface_android_wlegl_server_buffer_handle
|
||||
* Sends an buffer_fd event to the client owning the resource.
|
||||
* @param resource_ The client's resource
|
||||
*/
|
||||
static inline void
|
||||
android_wlegl_server_buffer_handle_send_buffer_fd(struct wl_resource *resource_, int32_t fd)
|
||||
{
|
||||
wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_FD, fd);
|
||||
}
|
||||
|
||||
/**
|
||||
* @ingroup iface_android_wlegl_server_buffer_handle
|
||||
* Sends an buffer_ints event to the client owning the resource.
|
||||
* @param resource_ The client's resource
|
||||
*/
|
||||
static inline void
|
||||
android_wlegl_server_buffer_handle_send_buffer_ints(struct wl_resource *resource_, struct wl_array *ints)
|
||||
{
|
||||
wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_INTS, ints);
|
||||
}
|
||||
|
||||
/**
|
||||
* @ingroup iface_android_wlegl_server_buffer_handle
|
||||
* Sends an buffer event to the client owning the resource.
|
||||
* @param resource_ The client's resource
|
||||
*/
|
||||
static inline void
|
||||
android_wlegl_server_buffer_handle_send_buffer(struct wl_resource *resource_, struct wl_resource *buffer, int32_t format, int32_t stride)
|
||||
{
|
||||
wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER, buffer, format, stride);
|
||||
}
|
||||
|
||||
/**
|
||||
* @ingroup iface_android_wlegl_server_buffer_handle
|
||||
* Sends an linear_layout event to the client owning the resource.
|
||||
* @param resource_ The client's resource
|
||||
*/
|
||||
static inline void
|
||||
android_wlegl_server_buffer_handle_send_linear_layout(struct wl_resource *resource_, uint32_t drm_format, uint32_t stride)
|
||||
{
|
||||
wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_LINEAR_LAYOUT, drm_format, stride);
|
||||
}
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -1,139 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<protocol name="android">
|
||||
|
||||
<copyright>
|
||||
Copyright © 2012 Collabora, Ltd.
|
||||
|
||||
Permission to use, copy, modify, distribute, and sell this
|
||||
software and its documentation for any purpose is hereby granted
|
||||
without fee, provided that the above copyright notice appear in
|
||||
all copies and that both that copyright notice and this permission
|
||||
notice appear in supporting documentation, and that the name of
|
||||
the copyright holders not be used in advertising or publicity
|
||||
pertaining to distribution of the software without specific,
|
||||
written prior permission. The copyright holders make no
|
||||
representations about the suitability of this software for any
|
||||
purpose. It is provided "as is" without express or implied
|
||||
warranty.
|
||||
|
||||
THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
|
||||
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||
FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
|
||||
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
|
||||
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
|
||||
THIS SOFTWARE.
|
||||
</copyright>
|
||||
|
||||
<interface name="android_wlegl" version="3">
|
||||
<description summary="Android EGL graphics buffer support">
|
||||
Interface used in the Android wrapper libEGL to share
|
||||
graphics buffers between the server and the client.
|
||||
</description>
|
||||
|
||||
<enum name="error">
|
||||
<entry name="bad_handle" value="0" />
|
||||
<entry name="bad_value" value="1" />
|
||||
</enum>
|
||||
|
||||
<request name="create_handle">
|
||||
<description summary="Create an Android native_handle_t object">
|
||||
This creator method initialises the native_handle_t object
|
||||
with everything except the file descriptors, which have to be
|
||||
submitted separately.
|
||||
</description>
|
||||
|
||||
<arg name="id" type="new_id" interface="android_wlegl_handle" />
|
||||
<arg name="num_fds" type="int" />
|
||||
<arg name="ints" type="array" summary="an array of int32_t" />
|
||||
</request>
|
||||
|
||||
<request name="create_buffer">
|
||||
<description summary="Create a wl_buffer from the native handle">
|
||||
Pass the Android native_handle_t to the server and attach it
|
||||
to the new wl_buffer object.
|
||||
|
||||
The android_wlegl_handle object must be destroyed immediately
|
||||
after this request.
|
||||
</description>
|
||||
|
||||
<arg name="id" type="new_id" interface="wl_buffer" />
|
||||
<arg name="width" type="int" />
|
||||
<arg name="height" type="int" />
|
||||
<arg name="stride" type="int" />
|
||||
<arg name="format" type="int" />
|
||||
<arg name="usage" type="int" />
|
||||
<arg name="native_handle" type="object" interface="android_wlegl_handle" />
|
||||
</request>
|
||||
|
||||
|
||||
<request name="get_server_buffer_handle" since="2">
|
||||
<arg name="id" type="new_id" interface="android_wlegl_server_buffer_handle"/>
|
||||
<arg name="width" type="int"/>
|
||||
<arg name="height" type="int"/>
|
||||
<arg name="format" type="int"/>
|
||||
<arg name="usage" type="int"/>
|
||||
</request>
|
||||
|
||||
</interface>
|
||||
|
||||
<interface name="android_wlegl_handle" version="1">
|
||||
<description summary="An Android native_handle_t object">
|
||||
The Android native_handle_t is a semi-opaque object, that
|
||||
contains an EGL implementation specific number of int32
|
||||
values and file descriptors.
|
||||
|
||||
We cannot send a variable size array of file descriptors
|
||||
over the Wayland protocol, so we send them one by one.
|
||||
</description>
|
||||
|
||||
<enum name="error">
|
||||
<entry name="too_many_fds" value="0" />
|
||||
</enum>
|
||||
|
||||
<request name="add_fd">
|
||||
<arg name="fd" type="fd" />
|
||||
</request>
|
||||
|
||||
<request name="destroy" type="destructor" />
|
||||
|
||||
</interface>
|
||||
|
||||
|
||||
<interface name="android_wlegl_server_buffer_handle" version="3">
|
||||
<description summary="a server allocated buffer">
|
||||
On creation a server_side_buffer object will immediately send
|
||||
the "buffer_fd" and "buffer_ints" events needed by the client to
|
||||
reference the gralloc buffer, followed by the "buffer" event carrying
|
||||
the wl_buffer object.
|
||||
</description>
|
||||
<event name="buffer_fd">
|
||||
<arg name="fd" type="fd"/>
|
||||
</event>
|
||||
<event name="buffer_ints">
|
||||
<arg name="ints" type="array"/>
|
||||
</event>
|
||||
<event name="buffer">
|
||||
<description summary="the wl_buffer">
|
||||
This event will be sent after the ints and all the fds have been sent
|
||||
</description>
|
||||
<arg name="buffer" type="new_id" interface="wl_buffer"/>
|
||||
<arg name="format" type="int"/>
|
||||
<arg name="stride" type="int"/>
|
||||
</event>
|
||||
<event name="linear_layout" since="3">
|
||||
<description summary="verified single-plane linear allocation">
|
||||
Optional metadata sent before the buffer event. The first buffer_fd
|
||||
contains one uncompressed 32-bit RGB plane at byte offset zero.
|
||||
drm_format is its DRM FourCC and stride is its row pitch in bytes.
|
||||
The server has verified the layout and allocation bounds using
|
||||
Android mapper metadata, not inferred them from opaque handle ints.
|
||||
Absence of this event means the layout is unspecified.
|
||||
</description>
|
||||
<arg name="drm_format" type="uint"/>
|
||||
<arg name="stride" type="uint"/>
|
||||
</event>
|
||||
</interface>
|
||||
|
||||
</protocol>
|
||||
@@ -371,8 +371,8 @@ void ahb_swapchain_set_mode(int on, int live) {
|
||||
: "; gralloc frames still in flight stay on the layer (or take the copy path) until then");
|
||||
else
|
||||
droiddeck_log("layer", "zero-copy: %s at launch (%s)", on ? "on" : "off",
|
||||
on ? "DROIDDECK_WAYLAND_ZERO_COPY=1: games present their own gralloc buffers on the display layer"
|
||||
: "the drawer's Zero-copy presentation switch turns it on live");
|
||||
on ? "HDR session: games present their own gralloc buffers on the display layer"
|
||||
: "only HDR sessions turn it on");
|
||||
if (live) wl_display_flush_clients(droiddeck_get_display());
|
||||
droiddeck_request_redraw();
|
||||
}
|
||||
|
||||
@@ -186,6 +186,9 @@ static void on_client_created(struct wl_listener *l, void *data) {
|
||||
|
||||
enum surface_role { ROLE_NONE, ROLE_TOPLEVEL, ROLE_SUBSURFACE, ROLE_DESKTOP, ROLE_CURSOR };
|
||||
|
||||
#define DAMAGE_RECTS 8
|
||||
struct damage_list { int32_t r[DAMAGE_RECTS][4]; int n; };
|
||||
|
||||
struct surface {
|
||||
struct wl_resource *resource;
|
||||
struct wl_list link;
|
||||
@@ -207,6 +210,7 @@ struct surface {
|
||||
int buf_w, buf_h, has_content;
|
||||
int buf_alpha;
|
||||
int opaque[4], pending_opaque[4], pending_opaque_set;
|
||||
struct damage_list damage_buf, pending_damage_buf, damage_local, pending_damage_local;
|
||||
int src_set, dst_set;
|
||||
float src[4];
|
||||
int dst[2];
|
||||
@@ -624,6 +628,68 @@ static void fire_frames(struct wl_list *frames) {
|
||||
}
|
||||
}
|
||||
|
||||
static void scene_size(int *w, int *h);
|
||||
static int64_t damage_area(const struct damage_list *d, int bound_w, int bound_h);
|
||||
static struct surface *g_hud_surface, *g_hud_shm;
|
||||
static int64_t g_hud_shm_ns;
|
||||
static int64_t g_hud_last_ns, g_hud_alive_ns;
|
||||
static int g_hud_fresh;
|
||||
static int g_hud_new;
|
||||
#define HUD_TIMES 256
|
||||
static pthread_mutex_t g_hud_times_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static float g_hud_times[HUD_TIMES];
|
||||
static int64_t g_hud_times_total, g_hud_shown_ns;
|
||||
|
||||
static void hud_frame_shown(int64_t t) {
|
||||
const int64_t previous = g_hud_shown_ns;
|
||||
g_hud_shown_ns = t;
|
||||
if (!previous || t <= previous) return;
|
||||
pthread_mutex_lock(&g_hud_times_lock);
|
||||
g_hud_times[g_hud_times_total % HUD_TIMES] = (float)((t - previous) / 1e6);
|
||||
g_hud_times_total++;
|
||||
pthread_mutex_unlock(&g_hud_times_lock);
|
||||
}
|
||||
|
||||
static int tree_rank(const struct surface *s, const struct surface *want, int *rank, int depth) {
|
||||
const struct surface *c;
|
||||
if (depth > 8) return 0;
|
||||
wl_list_for_each(c, &s->children, child_link)
|
||||
if (c->below_parent && tree_rank(c, want, rank, depth + 1)) return 1;
|
||||
if (s == want) return 1;
|
||||
(*rank)++;
|
||||
wl_list_for_each(c, &s->children, child_link)
|
||||
if (!c->below_parent && tree_rank(c, want, rank, depth + 1)) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int render_rank(const struct surface *want) {
|
||||
const struct surface *s;
|
||||
int rank = 0;
|
||||
if (g_desktop && tree_rank(g_desktop, want, &rank, 0)) return rank;
|
||||
wl_list_for_each(s, &g_toplevels, toplevel_link)
|
||||
if (tree_rank(s, want, &rank, 0)) return rank;
|
||||
return -1;
|
||||
}
|
||||
|
||||
static int below_surface(const struct surface *s, const struct surface *other) {
|
||||
const int a = render_rank(s), b = render_rank(other);
|
||||
return a >= 0 && b >= 0 && a < b;
|
||||
}
|
||||
|
||||
int droiddeck_hud_frame_times(float *out, int len, int64_t *total) {
|
||||
pthread_mutex_lock(&g_hud_times_lock);
|
||||
*total = g_hud_times_total;
|
||||
int64_t n = *total < len ? *total : len;
|
||||
if (n > HUD_TIMES) n = HUD_TIMES;
|
||||
for (int64_t i = 0; i < n; i++) out[i] = g_hud_times[(*total - n + i) % HUD_TIMES];
|
||||
pthread_mutex_unlock(&g_hud_times_lock);
|
||||
return (int)n;
|
||||
}
|
||||
static uint64_t g_game_frames;
|
||||
extern void droiddeck_on_game_surface(const char *window, const char *gpu);
|
||||
extern void droiddeck_on_game_frame(void);
|
||||
extern void droiddeck_on_game_program(int pid, const char *program);
|
||||
|
||||
static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_resource *buffer) {
|
||||
int32_t w = wl_shm_buffer_get_width(shm), h = wl_shm_buffer_get_height(shm);
|
||||
int32_t stride = wl_shm_buffer_get_stride(shm);
|
||||
@@ -646,6 +712,33 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res
|
||||
g_stat_shm++;
|
||||
struct client_info *ci = client_info_of(wl_resource_get_client(s->resource));
|
||||
if (ci && ci->asked_feedback) ci->shm_frames++;
|
||||
int local_w, local_h;
|
||||
surface_size(s, &local_w, &local_h);
|
||||
const double region = s->src_set ? (double)s->src[2] * s->src[3] : (double)w * h;
|
||||
const int64_t local_max = damage_area(&s->damage_local, local_w, local_h);
|
||||
const int64_t local = local_w > 0 && local_h > 0
|
||||
? (int64_t)((double)local_max * region / ((double)local_w * local_h)) : local_max;
|
||||
const int64_t buffer_max = damage_area(&s->damage_buf, w, h);
|
||||
const int64_t area = (int64_t)w * h;
|
||||
int64_t damaged = buffer_max > local ? buffer_max : local;
|
||||
if (damaged > area) damaged = area;
|
||||
const int64_t now = now_ns();
|
||||
if (damaged * 16 >= area && (!g_hud_surface || now - g_hud_last_ns > 1000000000LL) &&
|
||||
(s == g_hud_shm || !g_hud_shm || now - g_hud_shm_ns > 1000000000LL)) {
|
||||
const struct surface *top = s;
|
||||
int scene_w, scene_h, top_w, top_h, depth = 0;
|
||||
while (top->parent && depth++ < 8) top = top->parent;
|
||||
scene_size(&scene_w, &scene_h);
|
||||
surface_size(top, &top_w, &top_h);
|
||||
int64_t shown = (int64_t)local_w * local_h;
|
||||
if ((int64_t)top_w * top_h > shown) shown = (int64_t)top_w * top_h;
|
||||
if (top->role == ROLE_TOPLEVEL && top->mapped && shown * 2 >= (int64_t)scene_w * scene_h) {
|
||||
g_hud_shm = s;
|
||||
g_hud_shm_ns = now;
|
||||
g_hud_new = 1;
|
||||
droiddeck_on_game_frame();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resource *buffer) {
|
||||
@@ -662,14 +755,6 @@ static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resou
|
||||
s->has_content = s->shm_img != NULL;
|
||||
}
|
||||
|
||||
static struct surface *g_hud_surface;
|
||||
static int64_t g_hud_last_ns, g_hud_alive_ns;
|
||||
static int g_hud_fresh;
|
||||
static uint64_t g_game_frames;
|
||||
extern void droiddeck_on_game_surface(const char *window, const char *gpu);
|
||||
extern void droiddeck_on_game_frame(void);
|
||||
extern void droiddeck_on_game_program(int pid, const char *program);
|
||||
|
||||
static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_resource *buffer) {
|
||||
const int repeat = s->dmabuf == buffer && s->dmabuf_buf == b;
|
||||
if (!repeat) {
|
||||
@@ -724,8 +809,9 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
|
||||
name, b->width, b->height, (unsigned long long)b->modifier);
|
||||
}
|
||||
if (s != g_hud_surface && (b->img || ahb_swapchain_has_ahb(b)) &&
|
||||
(!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL ||
|
||||
(announced_now && (int64_t)b->width * b->height >= (int64_t)g_hud_surface->buf_w * g_hud_surface->buf_h))) {
|
||||
(!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL || (!repeat && below_surface(s, g_hud_surface)) ||
|
||||
(announced_now && !below_surface(g_hud_surface, s) &&
|
||||
(int64_t)b->width * b->height >= (int64_t)g_hud_surface->buf_w * g_hud_surface->buf_h))) {
|
||||
char name[160];
|
||||
describe(s, name, sizeof(name));
|
||||
g_hud_surface = s;
|
||||
@@ -749,7 +835,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
|
||||
}
|
||||
if (s == g_hud_surface) {
|
||||
g_hud_alive_ns = now_ns();
|
||||
if (!repeat) { g_hud_last_ns = g_hud_alive_ns; g_hud_fresh = 1; g_game_frames++; droiddeck_on_game_frame(); }
|
||||
if (!repeat) { g_hud_last_ns = g_hud_alive_ns; g_hud_fresh = 1; g_hud_new = 1; g_game_frames++; droiddeck_on_game_frame(); }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -786,8 +872,45 @@ static void surface_attach(struct wl_client *c, struct wl_resource *r,
|
||||
wl_resource_add_destroy_listener(buffer, &s->pending_buffer_destroy);
|
||||
}
|
||||
}
|
||||
static int64_t rect_area(const int32_t *r, int bound_w, int bound_h) {
|
||||
int64_t x0 = r[0], y0 = r[1], x1 = (int64_t)r[0] + r[2], y1 = (int64_t)r[1] + r[3];
|
||||
if (bound_w > 0 && bound_h > 0) {
|
||||
if (x0 < 0) x0 = 0;
|
||||
if (y0 < 0) y0 = 0;
|
||||
if (x1 > bound_w) x1 = bound_w;
|
||||
if (y1 > bound_h) y1 = bound_h;
|
||||
}
|
||||
if (x1 <= x0 || y1 <= y0) return 0;
|
||||
const int64_t w = x1 - x0, h = y1 - y0;
|
||||
return (w < 65536 ? w : 65536) * (h < 65536 ? h : 65536);
|
||||
}
|
||||
static void note_damage(struct damage_list *d, int32_t x, int32_t y, int32_t w, int32_t h) {
|
||||
if (w <= 0 || h <= 0) return;
|
||||
const int32_t rect[4] = { x, y, w, h };
|
||||
int slot = d->n;
|
||||
if (slot == DAMAGE_RECTS) {
|
||||
slot = 0;
|
||||
for (int i = 1; i < DAMAGE_RECTS; i++)
|
||||
if (rect_area(d->r[i], 0, 0) < rect_area(d->r[slot], 0, 0)) slot = i;
|
||||
if (rect_area(rect, 0, 0) <= rect_area(d->r[slot], 0, 0)) return;
|
||||
} else {
|
||||
d->n++;
|
||||
}
|
||||
memcpy(d->r[slot], rect, sizeof(rect));
|
||||
}
|
||||
static int64_t damage_area(const struct damage_list *d, int bound_w, int bound_h) {
|
||||
int64_t max = 0;
|
||||
for (int i = 0; i < d->n; i++) {
|
||||
const int64_t area = rect_area(d->r[i], bound_w, bound_h);
|
||||
if (area > max) max = area;
|
||||
}
|
||||
return max;
|
||||
}
|
||||
static void surface_damage(struct wl_client *c, struct wl_resource *r,
|
||||
int32_t x, int32_t y, int32_t w, int32_t h) {}
|
||||
int32_t x, int32_t y, int32_t w, int32_t h) {
|
||||
struct surface *s = wl_resource_get_user_data(r);
|
||||
note_damage(&s->pending_damage_local, x, y, w, h);
|
||||
}
|
||||
static void frame_callback_destroy(struct wl_resource *r) {
|
||||
wl_list_remove(wl_resource_get_link(r));
|
||||
}
|
||||
@@ -987,6 +1110,9 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
|
||||
s->pending_opaque_set = 0;
|
||||
}
|
||||
|
||||
s->damage_buf = s->pending_damage_buf;
|
||||
s->damage_local = s->pending_damage_local;
|
||||
s->pending_damage_buf.n = s->pending_damage_local.n = 0;
|
||||
if (s->pending_attach) {
|
||||
struct wl_resource *buffer = s->pending_buffer;
|
||||
struct dmabuf_buffer *db = get_dmabuf(buffer);
|
||||
@@ -1051,7 +1177,10 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
|
||||
static void surface_set_buffer_transform(struct wl_client *c, struct wl_resource *r, int32_t t) {}
|
||||
static void surface_set_buffer_scale(struct wl_client *c, struct wl_resource *r, int32_t s) {}
|
||||
static void surface_damage_buffer(struct wl_client *c, struct wl_resource *r,
|
||||
int32_t x, int32_t y, int32_t w, int32_t h) {}
|
||||
int32_t x, int32_t y, int32_t w, int32_t h) {
|
||||
struct surface *s = wl_resource_get_user_data(r);
|
||||
note_damage(&s->pending_damage_buf, x, y, w, h);
|
||||
}
|
||||
static void surface_offset(struct wl_client *c, struct wl_resource *r, int32_t x, int32_t y) {}
|
||||
|
||||
static const struct wl_surface_interface surface_impl = {
|
||||
@@ -1094,6 +1223,7 @@ static void surface_resource_destroy(struct wl_resource *r) {
|
||||
droiddeck_text_input_surface_gone(r);
|
||||
if (g_desktop == s) { g_desktop = NULL; droiddeck_log("desktop", "the desktop closed"); }
|
||||
if (g_hud_surface == s) { g_hud_surface = NULL; droiddeck_on_game_surface(NULL, NULL); }
|
||||
if (g_hud_shm == s) g_hud_shm = NULL;
|
||||
constraints_surface_gone(s);
|
||||
|
||||
unmap_toplevel(s);
|
||||
@@ -2103,6 +2233,10 @@ static void render_scene(void) {
|
||||
if (rendered) {
|
||||
int64_t t = presented_ns(t_scene);
|
||||
g_stat_frames++;
|
||||
if (g_hud_new) {
|
||||
g_hud_new = 0;
|
||||
hud_frame_shown(t);
|
||||
}
|
||||
wl_list_for_each(s, &g_surfaces, link) {
|
||||
if (s->drawn) feedback_present_all(&s->feedback, t);
|
||||
else feedback_discard_all(&s->feedback);
|
||||
@@ -3390,9 +3524,7 @@ int droiddeck_wayland_run(void) {
|
||||
|
||||
wl_global_create(display, &wl_output_interface, 4, NULL, bind_output);
|
||||
wl_global_create(display, &xdg_wm_base_interface, 1, NULL, bind_xdg_wm_base);
|
||||
if (vkp_dmabuf_supported())
|
||||
wl_global_create(display, &zwp_linux_dmabuf_v1_interface, 4, NULL, bind_dmabuf);
|
||||
droiddeck_android_wlegl_init(display);
|
||||
wl_global_create(display, &zwp_linux_dmabuf_v1_interface, 4, NULL, bind_dmabuf);
|
||||
wl_global_create(display, &wl_seat_interface, 9, NULL, bind_seat);
|
||||
wl_global_create(display, &banner_desktop_v1_interface, 1, NULL, bind_desktop);
|
||||
wl_global_create(display, &wp_presentation_interface, 2, NULL, bind_presentation);
|
||||
|
||||
@@ -61,6 +61,3 @@ extern volatile int g_no_render_node;
|
||||
|
||||
COMPOSITOR_INTERNAL extern dev_t g_main_device;
|
||||
COMPOSITOR_INTERNAL void bind_dmabuf(struct wl_client *c, void *data, uint32_t ver, uint32_t id);
|
||||
|
||||
/* ---- wl_android_buffer.c */
|
||||
COMPOSITOR_INTERNAL void droiddeck_android_wlegl_init(struct wl_display *display);
|
||||
@@ -1,47 +0,0 @@
|
||||
#ifndef VK_EXTERNAL_IMAGE_SYNC_H
|
||||
#define VK_EXTERNAL_IMAGE_SYNC_H
|
||||
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
struct vkp_external_client_barrier_pair {
|
||||
VkImageMemoryBarrier acquire;
|
||||
VkImageMemoryBarrier release;
|
||||
};
|
||||
|
||||
static inline int vkp_is_external_client_image(int dmabuf, int blit_dst) {
|
||||
return dmabuf && !blit_dst;
|
||||
}
|
||||
|
||||
/* Client-owned dma-bufs, including AHardwareBuffers, live in GENERAL while
|
||||
* FOREIGN owns them. Layer pool dma-bufs are destinations with a separate
|
||||
* acquire/release lifecycle and must never take this source-image path. */
|
||||
static inline int vkp_external_client_barrier_pair(
|
||||
VkImage image, uint32_t queue_family, int dmabuf, int blit_dst,
|
||||
struct vkp_external_client_barrier_pair *pair) {
|
||||
if (!vkp_is_external_client_image(dmabuf, blit_dst) || !pair) return 0;
|
||||
|
||||
const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
|
||||
pair->acquire = (VkImageMemoryBarrier){
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
|
||||
.oldLayout = VK_IMAGE_LAYOUT_GENERAL,
|
||||
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT,
|
||||
.dstQueueFamilyIndex = queue_family,
|
||||
.image = image,
|
||||
.subresourceRange = range,
|
||||
.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT,
|
||||
};
|
||||
pair->release = (VkImageMemoryBarrier){
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
|
||||
.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
|
||||
.srcQueueFamilyIndex = queue_family,
|
||||
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT,
|
||||
.image = image,
|
||||
.subresourceRange = range,
|
||||
.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT,
|
||||
};
|
||||
return 1;
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,7 +1,6 @@
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include "vk_present.h"
|
||||
#include "vk_loader.h"
|
||||
#include "vk_external_image_sync.h"
|
||||
#include "sc_layer.h"
|
||||
#include "effects_chain.h"
|
||||
#include "cardboard.h"
|
||||
@@ -38,7 +37,6 @@ struct vkp_image {
|
||||
int in_general;
|
||||
VkFormat fmt;
|
||||
int sampled;
|
||||
AHardwareBuffer *android_buffer;
|
||||
};
|
||||
|
||||
static ANativeWindow *g_window;
|
||||
@@ -49,7 +47,6 @@ static VkInstance g_inst;
|
||||
static VkPhysicalDevice g_pd;
|
||||
static VkDevice g_dev;
|
||||
static VkQueue g_queue;
|
||||
static int g_dmabuf_supported;
|
||||
static uint32_t g_qfam;
|
||||
static VkCommandPool g_pool;
|
||||
#define MAX_PRESENTS (1 + VKP_FG_MAX_GENERATIONS)
|
||||
@@ -466,23 +463,16 @@ static int dev_init(void) {
|
||||
|
||||
static const char *const import_exts[4] = {"VK_KHR_external_memory_fd", "VK_EXT_external_memory_dma_buf",
|
||||
"VK_EXT_image_drm_format_modifier", "VK_KHR_image_format_list"};
|
||||
const char *dev_exts[10] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME};
|
||||
const char *dev_exts[9] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME};
|
||||
uint32_t n_dev_exts = 1;
|
||||
uint32_t ne = 0;
|
||||
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, NULL);
|
||||
VkExtensionProperties *exts = calloc(ne ? ne : 1, sizeof(*exts));
|
||||
if (!exts) { g_dev_state = -1; return -1; }
|
||||
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, exts);
|
||||
/* Only what the driver has: the system driver lacks the dma-buf ones, which the cloud player and
|
||||
* android_wlegl clients never need. */
|
||||
g_dmabuf_supported = 1;
|
||||
/* Only what the driver has: the system driver lacks the dma-buf ones, which the cloud player never needs. */
|
||||
for (unsigned i = 0; i < 4; i++) {
|
||||
if (has_ext(exts, ne, import_exts[i])) {
|
||||
dev_exts[n_dev_exts++] = import_exts[i];
|
||||
} else {
|
||||
LOGE("present: driver MISSING %s (dmabuf import will fail)", import_exts[i]);
|
||||
if (i < 3) g_dmabuf_supported = 0;
|
||||
}
|
||||
if (has_ext(exts, ne, import_exts[i])) dev_exts[n_dev_exts++] = import_exts[i];
|
||||
else LOGE("present: driver MISSING %s (dmabuf import will fail)", import_exts[i]);
|
||||
}
|
||||
int want_hdr_md = 0;
|
||||
if (droiddeck_color_requested()) {
|
||||
@@ -491,8 +481,7 @@ static int dev_init(void) {
|
||||
}
|
||||
const int want_sem_fd = has_ext(exts, ne, VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME);
|
||||
if (want_sem_fd) dev_exts[n_dev_exts++] = VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME;
|
||||
/* The cloud player's decoded frames (vkp_image_from_ahb) and android_wlegl clients
|
||||
* (vkp_image_from_android_buffer) arrive as AHardwareBuffers. */
|
||||
/* The cloud player's decoded frames arrive as AHardwareBuffers (vkp_image_from_ahb). */
|
||||
g_ahb_import = has_ext(exts, ne, VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME) &&
|
||||
has_ext(exts, ne, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
|
||||
if (g_ahb_import) {
|
||||
@@ -928,107 +917,12 @@ struct vkp_image *vkp_image_from_dmabuf(int fd, uint32_t drm_format, uint64_t mo
|
||||
return vkp_image_import_dmabuf(fd, drm_format, modifier, w, h, stride, offset, 0);
|
||||
}
|
||||
|
||||
/* Return client sources to FOREIGN after their final read. The consuming paths
|
||||
* wait for our fence before Wayland can release an ordinary dma-buf or an
|
||||
* android_wlegl AHardwareBuffer. Producer-fence synchronization is separate from
|
||||
* these image-layout and ownership transfers. */
|
||||
static void release_external_client_image(VkCommandBuffer cmd, struct vkp_image *img) {
|
||||
struct vkp_external_client_barrier_pair pair;
|
||||
if (!img || !vkp_external_client_barrier_pair(
|
||||
img->image, g_qfam, img->dmabuf, img->blit_dst, &pair))
|
||||
return;
|
||||
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
|
||||
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &pair.release);
|
||||
}
|
||||
|
||||
static void release_external_client_draws(VkCommandBuffer cmd, const struct vkp_draw *draws, int count) {
|
||||
for (int i = 0; i < count; i++) {
|
||||
int seen = 0;
|
||||
for (int j = 0; j < i; j++) if (draws[j].img == draws[i].img) { seen = 1; break; }
|
||||
if (!seen) release_external_client_image(cmd, draws[i].img);
|
||||
}
|
||||
}
|
||||
|
||||
int vkp_image_is_dmabuf(const struct vkp_image *img) {
|
||||
return img && vkp_is_external_client_image(img->dmabuf, img->blit_dst);
|
||||
}
|
||||
|
||||
int vkp_android_buffer_supported(void) {
|
||||
return dev_init() == 0 && g_ahb_import && g_vk.GetAndroidHardwareBufferPropertiesANDROID != NULL;
|
||||
}
|
||||
|
||||
int vkp_dmabuf_supported(void) {
|
||||
return dev_init() == 0 && g_dmabuf_supported;
|
||||
}
|
||||
|
||||
struct vkp_image *vkp_image_from_android_buffer(AHardwareBuffer *buffer) {
|
||||
if (!buffer || !vkp_android_buffer_supported()) return NULL;
|
||||
AHardwareBuffer_Desc desc;
|
||||
AHardwareBuffer_describe(buffer, &desc);
|
||||
if (!desc.width || !desc.height || desc.layers != 1 ||
|
||||
(desc.usage & (AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT | AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE)) ||
|
||||
!(desc.usage & AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE)) return NULL;
|
||||
VkAndroidHardwareBufferFormatPropertiesANDROID format = {
|
||||
.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID};
|
||||
VkAndroidHardwareBufferPropertiesANDROID props = {
|
||||
.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID, .pNext = &format};
|
||||
VkResult result = g_vk.GetAndroidHardwareBufferPropertiesANDROID(g_dev, buffer, &props);
|
||||
if (result != VK_SUCCESS ||
|
||||
(format.format != VK_FORMAT_R8G8B8A8_UNORM && format.format != VK_FORMAT_R8G8B8A8_SRGB &&
|
||||
format.format != VK_FORMAT_B8G8R8A8_UNORM && format.format != VK_FORMAT_B8G8R8A8_SRGB) ||
|
||||
!props.memoryTypeBits ||
|
||||
!(format.formatFeatures & VK_FORMAT_FEATURE_BLIT_SRC_BIT)) {
|
||||
LOGE("android_wlegl: unsupported Android buffer import (%s, format %d)",
|
||||
vk_result_name(result), format.format);
|
||||
return NULL;
|
||||
}
|
||||
struct vkp_image *img = calloc(1, sizeof(*img));
|
||||
if (!img) return NULL;
|
||||
img->w = (int)desc.width; img->h = (int)desc.height;
|
||||
img->fmt = format.format; img->dmabuf = 1;
|
||||
const VkFormatFeatureFlags sampled = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT |
|
||||
VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT;
|
||||
img->sampled = (format.formatFeatures & sampled) == sampled;
|
||||
VkExternalMemoryImageCreateInfo external = {
|
||||
.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
|
||||
.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID};
|
||||
VkImageCreateInfo create = {
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .pNext = &external,
|
||||
.imageType = VK_IMAGE_TYPE_2D, .format = img->fmt,
|
||||
.extent = {desc.width, desc.height, 1}, .mipLevels = 1, .arrayLayers = 1,
|
||||
.samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL,
|
||||
.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | (img->sampled ? VK_IMAGE_USAGE_SAMPLED_BIT : 0),
|
||||
.sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
|
||||
result = g_vk.CreateImage(g_dev, &create, NULL, &img->image);
|
||||
if (result != VK_SUCCESS) goto fail;
|
||||
/* AHB image requirements are not queryable before binding. The AHB query supplies them. */
|
||||
uint32_t memory_type = 0;
|
||||
while (!(props.memoryTypeBits & (1u << memory_type))) memory_type++;
|
||||
VkImportAndroidHardwareBufferInfoANDROID import = {
|
||||
.sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID, .buffer = buffer};
|
||||
VkMemoryDedicatedAllocateInfo dedicated = {
|
||||
.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
|
||||
.pNext = &import, .image = img->image};
|
||||
VkMemoryAllocateInfo allocate = {
|
||||
.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .pNext = &dedicated,
|
||||
.allocationSize = props.allocationSize, .memoryTypeIndex = memory_type};
|
||||
result = g_vk.AllocateMemory(g_dev, &allocate, NULL, &img->mem);
|
||||
if (result != VK_SUCCESS) goto fail;
|
||||
result = g_vk.BindImageMemory(g_dev, img->image, img->mem, 0);
|
||||
if (result != VK_SUCCESS) goto fail;
|
||||
AHardwareBuffer_acquire(buffer);
|
||||
img->android_buffer = buffer;
|
||||
return img;
|
||||
fail:
|
||||
LOGE("android_wlegl: Vulkan buffer import failed: %s", vk_result_name(result));
|
||||
vkp_image_destroy(img);
|
||||
return NULL;
|
||||
}
|
||||
int vkp_image_is_dmabuf(const struct vkp_image *img) { return img && img->dmabuf && !img->blit_dst; }
|
||||
|
||||
struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t modifier, int w, int h,
|
||||
uint32_t stride, uint32_t offset, int as_blit_dst) {
|
||||
if (modifier == MOD_INVALID || w <= 0 || h <= 0) return NULL;
|
||||
if (dev_init() != 0 || !g_dmabuf_supported) return NULL;
|
||||
if (dev_init() != 0) return NULL;
|
||||
|
||||
struct vkp_image *img = calloc(1, sizeof(*img));
|
||||
if (!img) return NULL;
|
||||
@@ -1231,7 +1125,6 @@ void vkp_image_destroy(struct vkp_image *img) {
|
||||
if (img->image) g_vk.DestroyImage(g_dev, img->image, NULL);
|
||||
if (img->mem) g_vk.FreeMemory(g_dev, img->mem, NULL);
|
||||
}
|
||||
if (img->android_buffer) AHardwareBuffer_release(img->android_buffer);
|
||||
free(img);
|
||||
}
|
||||
|
||||
@@ -1276,14 +1169,11 @@ static int draw_to_scene_blit(const struct vkp_draw *d, int scene_w, int scene_h
|
||||
static void record_draw(VkCommandBuffer cmd, const struct vkp_draw *d, const VkImageBlit *blit, VkImage target,
|
||||
VkFormat target_fmt, int target_w, int target_h, VkFilter filter) {
|
||||
const struct vkp_image *im = d->img;
|
||||
const int external_client = vkp_image_is_dmabuf(im);
|
||||
if (d->blend && im->sampled &&
|
||||
blendp_draw(cmd, im->image, im->fmt, im->w, im->h, !external_client,
|
||||
target, target_fmt, target_w, target_h,
|
||||
blendp_draw(cmd, im->image, im->fmt, im->w, im->h, !im->dmabuf, target, target_fmt, target_w, target_h,
|
||||
blit) == 0)
|
||||
return;
|
||||
g_vk.CmdBlitImage(cmd, im->image,
|
||||
external_client ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
|
||||
g_vk.CmdBlitImage(cmd, im->image, im->dmabuf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
|
||||
target, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, blit, filter);
|
||||
}
|
||||
|
||||
@@ -1722,11 +1612,13 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
int seen = 0;
|
||||
for (int j = 0; j < i; j++) if (draws[j].img == im) { seen = 1; break; }
|
||||
if (seen || !im) continue;
|
||||
struct vkp_external_client_barrier_pair pair;
|
||||
if (vkp_external_client_barrier_pair(
|
||||
im->image, g_qfam, im->dmabuf, im->blit_dst, &pair)) {
|
||||
bars[nb++] = pair.acquire;
|
||||
} else if (!im->blit_dst && !im->in_general) {
|
||||
if (im->dmabuf) {
|
||||
bars[nb++] = (VkImageMemoryBarrier){
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam,
|
||||
.image = im->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
|
||||
} else if (!im->in_general) {
|
||||
bars[nb++] = (VkImageMemoryBarrier){
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED,
|
||||
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
|
||||
@@ -1783,7 +1675,6 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
drawn++;
|
||||
}
|
||||
|
||||
release_external_client_draws(cmd, draws, n);
|
||||
int ngen = 0;
|
||||
VkImage gens[VKP_FG_MAX_GENERATIONS] = {VK_NULL_HANDLE};
|
||||
VkImage result = scene_img;
|
||||
@@ -1986,7 +1877,7 @@ int vkp_map_draw(const struct vkp_draw *d, int out[8]) {
|
||||
}
|
||||
|
||||
int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
|
||||
if (!src || src->blit_dst || !dst || !dst->blit_dst || g_dev_state == -2 || dev_init() != 0) {
|
||||
if (!src || !dst || !dst->blit_dst || g_dev_state == -2 || dev_init() != 0) {
|
||||
if (wait_fd >= 0) close(wait_fd);
|
||||
return -1;
|
||||
}
|
||||
@@ -1999,21 +1890,17 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
|
||||
VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
|
||||
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
|
||||
g_vk.BeginCommandBuffer(g_cmd, &bi);
|
||||
struct vkp_external_client_barrier_pair src_pair;
|
||||
const int src_external = vkp_external_client_barrier_pair(
|
||||
src->image, g_qfam, src->dmabuf, src->blit_dst, &src_pair);
|
||||
VkImageMemoryBarrier acq[2] = {
|
||||
src_external ? src_pair.acquire : (VkImageMemoryBarrier){
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.srcQueueFamilyIndex = src->dmabuf ? VK_QUEUE_FAMILY_FOREIGN_EXT : VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = src->dmabuf ? g_qfam : VK_QUEUE_FAMILY_IGNORED,
|
||||
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT},
|
||||
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
|
||||
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam,
|
||||
.image = dst->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}};
|
||||
if (!src_external) {
|
||||
if (!src->dmabuf) {
|
||||
acq[0].oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED;
|
||||
acq[0].newLayout = VK_IMAGE_LAYOUT_GENERAL;
|
||||
acq[0].srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
|
||||
@@ -2027,9 +1914,8 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
|
||||
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
|
||||
.dstOffsets = {{0, 0, 0}, {bw, bh, 1}}};
|
||||
g_vk.CmdBlitImage(g_cmd, src->image,
|
||||
src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
|
||||
src->dmabuf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
|
||||
dst->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_NEAREST);
|
||||
release_external_client_image(g_cmd, src);
|
||||
VkImageMemoryBarrier rel = {
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
|
||||
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam,
|
||||
@@ -2064,7 +1950,7 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
|
||||
static struct vkp_image *g_rb;
|
||||
|
||||
int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) {
|
||||
if (!src || src->blit_dst || !out || src->w <= 0 || src->h <= 0 || src->w * src->h > max_px ||
|
||||
if (!src || !out || src->w <= 0 || src->h <= 0 || src->w * src->h > max_px ||
|
||||
g_dev_state == -2 || dev_init() != 0)
|
||||
return -1;
|
||||
if (g_rb && (g_rb->w != src->w || g_rb->h != src->h)) { vkp_image_destroy(g_rb); g_rb = NULL; }
|
||||
@@ -2105,15 +1991,11 @@ int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) {
|
||||
VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
|
||||
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
|
||||
g_vk.BeginCommandBuffer(cmd, &bi);
|
||||
struct vkp_external_client_barrier_pair src_pair;
|
||||
const int src_external = vkp_external_client_barrier_pair(
|
||||
src->image, g_qfam, src->dmabuf, src->blit_dst, &src_pair);
|
||||
VkImageMemoryBarrier acq[2] = {
|
||||
src_external ? src_pair.acquire : (VkImageMemoryBarrier){
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.srcQueueFamilyIndex = src->dmabuf ? VK_QUEUE_FAMILY_FOREIGN_EXT : VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = src->dmabuf ? g_qfam : VK_QUEUE_FAMILY_IGNORED,
|
||||
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT},
|
||||
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
@@ -2131,20 +2013,15 @@ int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) {
|
||||
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_GENERAL,
|
||||
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .image = g_rb->image, .subresourceRange = range,
|
||||
.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, .dstAccessMask = VK_ACCESS_HOST_READ_BIT}};
|
||||
uint32_t done_count = 1;
|
||||
if (!src_external) {
|
||||
done[done_count++] = (VkImageMemoryBarrier){
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, .dstAccessMask = VK_ACCESS_HOST_READ_BIT},
|
||||
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
|
||||
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.image = src->image, .subresourceRange = range, .srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
|
||||
}
|
||||
.srcQueueFamilyIndex = src->dmabuf ? g_qfam : VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = src->dmabuf ? VK_QUEUE_FAMILY_FOREIGN_EXT : VK_QUEUE_FAMILY_IGNORED,
|
||||
.image = src->image, .subresourceRange = range, .srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT}};
|
||||
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
|
||||
0, 0, NULL, 0, NULL, done_count, done);
|
||||
release_external_client_image(cmd, src);
|
||||
0, 0, NULL, 0, NULL, 2, done);
|
||||
g_vk.EndCommandBuffer(cmd);
|
||||
VkSubmitInfo si = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .commandBufferCount = 1, .pCommandBuffers = &cmd};
|
||||
g_vk.ResetFences(g_dev, 1, &g_fence);
|
||||
@@ -2216,11 +2093,13 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
|
||||
int seen = 0;
|
||||
for (int j = 0; j < i; j++) if (draws[j].img == im) { seen = 1; break; }
|
||||
if (seen || !im) continue;
|
||||
struct vkp_external_client_barrier_pair pair;
|
||||
if (vkp_external_client_barrier_pair(
|
||||
im->image, g_qfam, im->dmabuf, im->blit_dst, &pair)) {
|
||||
bars[nb++] = pair.acquire;
|
||||
} else if (!im->blit_dst && !im->in_general) {
|
||||
if (im->dmabuf) {
|
||||
bars[nb++] = (VkImageMemoryBarrier){
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam,
|
||||
.image = im->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
|
||||
} else if (!im->in_general) {
|
||||
bars[nb++] = (VkImageMemoryBarrier){
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED,
|
||||
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
|
||||
@@ -2259,7 +2138,6 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
|
||||
if (vkp_effects_active()) vkp_effects_set_formats(VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM);
|
||||
}
|
||||
|
||||
release_external_client_draws(cmd, draws, n);
|
||||
int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f);
|
||||
g_pass.rw = scene_w; g_pass.rh = scene_h;
|
||||
g_pass.result = vkp_effects_run(cmd, scene_img, scene_w, scene_h, mapped_w, mapped_h,
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
#define VK_PRESENT_H
|
||||
#include <stdint.h>
|
||||
#include <android/native_window.h>
|
||||
#include <android/hardware_buffer.h>
|
||||
void vk_present_set_driver(const char *driver_path, const char *library_name,
|
||||
const char *native_lib_dir);
|
||||
|
||||
@@ -21,10 +20,6 @@ void vkp_output_size(int *w, int *h);
|
||||
|
||||
struct vkp_image;
|
||||
|
||||
int vkp_android_buffer_supported(void);
|
||||
int vkp_dmabuf_supported(void);
|
||||
struct vkp_image *vkp_image_from_android_buffer(AHardwareBuffer *buffer);
|
||||
|
||||
#define VKP_MOD_LINEAR 0x0000000000000000ULL
|
||||
#define VKP_MOD_QCOM_COMPRESSED 0x0500000000000001ULL
|
||||
#define VKP_MOD_INVALID 0x00ffffffffffffffULL
|
||||
|
||||
@@ -25,6 +25,7 @@ extern void droiddeck_wayland_send_pointer(int action, int x, int y);
|
||||
extern void droiddeck_wayland_send_touch(int action, int pointer_id, int x, int y);
|
||||
extern int droiddeck_cursor_snapshot(int *out, int cap);
|
||||
extern int droiddeck_cursor_serial(void);
|
||||
extern int droiddeck_hud_frame_times(float *out, int len, int64_t *total);
|
||||
extern void droiddeck_wayland_send_key(int evdev, int state);
|
||||
extern void droiddeck_wayland_send_scene_input(int type, int a, int b);
|
||||
extern void droiddeck_wayland_vsync(int64_t frame_time_ns);
|
||||
@@ -268,6 +269,20 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSnapshot(
|
||||
return n;
|
||||
}
|
||||
|
||||
JNIEXPORT jlong JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeHudFrameTimes(JNIEnv *env, jclass clazz, jfloatArray out) {
|
||||
(void)clazz;
|
||||
if (!out) return 0;
|
||||
jint cap = (*env)->GetArrayLength(env, out);
|
||||
float *buf = cap > 0 ? malloc(sizeof(float) * (size_t)cap) : NULL;
|
||||
if (!buf) return 0;
|
||||
int64_t total = 0;
|
||||
int n = droiddeck_hud_frame_times(buf, cap, &total);
|
||||
if (n > 0) (*env)->SetFloatArrayRegion(env, out, 0, n, buf);
|
||||
free(buf);
|
||||
return (jlong)total;
|
||||
}
|
||||
|
||||
JNIEXPORT jint JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSerial(JNIEnv *env, jclass clazz) {
|
||||
(void)env; (void)clazz;
|
||||
|
||||
@@ -1,216 +0,0 @@
|
||||
/* android_wlegl buffer import for the existing libhybris Wayland WSI.
|
||||
* Protocol: Collabora/libhybris, vendored with its license in protocols/wayland-android.xml.
|
||||
* Native handles are cloned through Android; opaque vendor integers are never interpreted. */
|
||||
#include "compositor_internal.h"
|
||||
#include "droiddeck_ext.h"
|
||||
#include "wayland-android-server-protocol.h"
|
||||
#include <android/hardware_buffer.h>
|
||||
#include <dlfcn.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
/* Stable native_handle_t ABI, unavailable in the public NDK. */
|
||||
struct android_native_handle {
|
||||
int version, num_fds, num_ints;
|
||||
int data[];
|
||||
};
|
||||
struct wire_handle {
|
||||
struct android_native_handle *handle;
|
||||
int received;
|
||||
};
|
||||
enum { MAX_HANDLE_FDS = 64, MAX_HANDLE_INTS = 256, MAX_BUFFER_SIDE = 8192 };
|
||||
/* VNDK ABI (not exposed by the NDK): frameworks/native/libs/nativewindow/include/
|
||||
* vndk/hardware_buffer.h, AHARDWAREBUFFER_CREATE_FROM_HANDLE_METHOD_CLONE = 3.
|
||||
* Method 1 is not accepted by AHardwareBuffer_createFromHandle. */
|
||||
enum { CREATE_FROM_HANDLE_CLONE = 3 };
|
||||
static int (*import_handle)(const AHardwareBuffer_Desc *, const struct android_native_handle *,
|
||||
int32_t, AHardwareBuffer **);
|
||||
static const struct android_native_handle *(*native_handle)(const AHardwareBuffer *);
|
||||
|
||||
static int valid_description(int32_t width, int32_t height, int32_t stride, int32_t format) {
|
||||
return width > 0 && height > 0 && width <= MAX_BUFFER_SIDE && height <= MAX_BUFFER_SIDE &&
|
||||
stride >= width && stride <= MAX_BUFFER_SIDE * 4 &&
|
||||
(format == 1 || format == 2 || format == 5);
|
||||
}
|
||||
|
||||
static void handle_resource_destroy(struct wl_resource *resource) {
|
||||
struct wire_handle *wire = wl_resource_get_user_data(resource);
|
||||
if (!wire) return;
|
||||
for (int i = 0; i < wire->received; i++) close(wire->handle->data[i]);
|
||||
free(wire->handle);
|
||||
free(wire);
|
||||
}
|
||||
|
||||
static void handle_add_fd(struct wl_client *client, struct wl_resource *resource, int32_t fd) {
|
||||
struct wire_handle *wire = wl_resource_get_user_data(resource);
|
||||
if (wire->received >= wire->handle->num_fds) {
|
||||
close(fd);
|
||||
wl_resource_post_error(resource, ANDROID_WLEGL_HANDLE_ERROR_TOO_MANY_FDS,
|
||||
"more native handle descriptors than declared");
|
||||
return;
|
||||
}
|
||||
wire->handle->data[wire->received++] = fd;
|
||||
}
|
||||
|
||||
static void handle_destroy(struct wl_client *client, struct wl_resource *resource) {
|
||||
wl_resource_destroy(resource);
|
||||
}
|
||||
|
||||
static const struct android_wlegl_handle_interface handle_impl = {
|
||||
.add_fd = handle_add_fd, .destroy = handle_destroy,
|
||||
};
|
||||
|
||||
static void create_handle(struct wl_client *client, struct wl_resource *resource,
|
||||
uint32_t id, int32_t fds, struct wl_array *ints) {
|
||||
if (fds < 0 || fds > MAX_HANDLE_FDS || ints->size % sizeof(int32_t) ||
|
||||
ints->size > MAX_HANDLE_INTS * sizeof(int32_t)) {
|
||||
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "invalid native handle size");
|
||||
return;
|
||||
}
|
||||
struct wire_handle *wire = calloc(1, sizeof(*wire));
|
||||
if (!wire) { wl_client_post_no_memory(client); return; }
|
||||
wire->handle = calloc(1, sizeof(*wire->handle) + (size_t)fds * sizeof(int32_t) + ints->size);
|
||||
if (!wire->handle) { free(wire); wl_client_post_no_memory(client); return; }
|
||||
wire->handle->version = sizeof(*wire->handle);
|
||||
wire->handle->num_fds = fds;
|
||||
wire->handle->num_ints = (int)(ints->size / sizeof(int32_t));
|
||||
if (ints->size) memcpy(wire->handle->data + fds, ints->data, ints->size);
|
||||
struct wl_resource *handle = wl_resource_create(client, &android_wlegl_handle_interface, 1, id);
|
||||
if (!handle) {
|
||||
free(wire->handle); free(wire); wl_client_post_no_memory(client); return;
|
||||
}
|
||||
wl_resource_set_implementation(handle, &handle_impl, wire, handle_resource_destroy);
|
||||
}
|
||||
|
||||
static void buffer_resource_destroy(struct wl_resource *resource) {
|
||||
dmabuf_buffer_unref(wl_resource_get_user_data(resource));
|
||||
}
|
||||
|
||||
static struct wl_resource *create_android_buffer(struct wl_client *client, uint32_t id,
|
||||
AHardwareBuffer *hardware) {
|
||||
AHardwareBuffer_Desc desc;
|
||||
AHardwareBuffer_describe(hardware, &desc);
|
||||
struct vkp_image *image = vkp_image_from_android_buffer(hardware);
|
||||
if (!image) return NULL;
|
||||
struct dmabuf_buffer *buffer = calloc(1, sizeof(*buffer));
|
||||
if (!buffer) { vkp_image_destroy(image); wl_client_post_no_memory(client); return NULL; }
|
||||
buffer->refs = 1;
|
||||
buffer->width = (int32_t)desc.width; buffer->height = (int32_t)desc.height;
|
||||
buffer->format = desc.format == 5 ? DRM_ARGB8888 : desc.format == 2 ? DRM_XBGR8888 : DRM_ABGR8888;
|
||||
buffer->modifier = MOD_INVALID; /* No DMA-BUF layout was inferred from the native handle. */
|
||||
buffer->img = image;
|
||||
for (int i = 0; i < MAX_PLANES; i++) buffer->fd[i] = -1;
|
||||
struct wl_resource *result = wl_resource_create(client, &wl_buffer_interface, 1, id);
|
||||
if (!result) { dmabuf_buffer_unref(buffer); wl_client_post_no_memory(client); return NULL; }
|
||||
wl_resource_set_implementation(result, &dbuf_buffer_impl, buffer, buffer_resource_destroy);
|
||||
struct client_info *info = client_info_of(client);
|
||||
if (info) info->dmabuf_buffers++;
|
||||
return result;
|
||||
}
|
||||
|
||||
static void create_buffer(struct wl_client *client, struct wl_resource *resource, uint32_t id,
|
||||
int32_t width, int32_t height, int32_t stride, int32_t format,
|
||||
int32_t usage, struct wl_resource *handle_resource) {
|
||||
/* Some vendor allocators (Samsung Xclipse) record no stride for GPU-only buffers. The import
|
||||
* must pass that 0 back unchanged: gralloc validates it against the handle's own value. */
|
||||
if (!valid_description(width, height, stride ? stride : width, format) ||
|
||||
!wl_resource_instance_of(handle_resource, &android_wlegl_handle_interface, &handle_impl)) {
|
||||
droiddeck_log("display", "android_wlegl rejected: %dx%d stride=%d format=%d usage=0x%x",
|
||||
width, height, stride, format, (uint32_t)usage);
|
||||
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "invalid Android buffer description");
|
||||
return;
|
||||
}
|
||||
struct wire_handle *wire = wl_resource_get_user_data(handle_resource);
|
||||
if (wire->received != wire->handle->num_fds || !wire->received) {
|
||||
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "incomplete native handle");
|
||||
return;
|
||||
}
|
||||
AHardwareBuffer_Desc desc = {
|
||||
.width = (uint32_t)width, .height = (uint32_t)height, .layers = 1,
|
||||
.format = (uint32_t)format, .usage = (uint32_t)usage, .stride = (uint32_t)stride};
|
||||
AHardwareBuffer *hardware = NULL;
|
||||
int status = import_handle(&desc, wire->handle, CREATE_FROM_HANDLE_CLONE, &hardware);
|
||||
if (status != 0 || !hardware) {
|
||||
droiddeck_log("display", "android_wlegl import failed: status=%d %dx%d stride=%d format=%d usage=0x%x fds=%d ints=%d",
|
||||
status, width, height, stride, format, (uint32_t)usage,
|
||||
wire->handle->num_fds, wire->handle->num_ints);
|
||||
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE,
|
||||
"Android rejected the native handle (status %d)", status);
|
||||
return;
|
||||
}
|
||||
struct wl_resource *buffer = create_android_buffer(client, id, hardware);
|
||||
AHardwareBuffer_release(hardware);
|
||||
if (!buffer) wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "Vulkan cannot import this buffer");
|
||||
}
|
||||
|
||||
static void get_server_buffer(struct wl_client *client, struct wl_resource *resource, uint32_t id,
|
||||
int32_t width, int32_t height, int32_t format, int32_t usage) {
|
||||
if (!format) format = 1;
|
||||
if (!valid_description(width, height, width, format)) {
|
||||
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "invalid buffer allocation request");
|
||||
return;
|
||||
}
|
||||
AHardwareBuffer_Desc desc = {
|
||||
.width = (uint32_t)width, .height = (uint32_t)height, .layers = 1,
|
||||
.format = (uint32_t)format,
|
||||
.usage = (uint32_t)usage | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT};
|
||||
AHardwareBuffer *hardware = NULL;
|
||||
if (AHardwareBuffer_allocate(&desc, &hardware) != 0 || !hardware) {
|
||||
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "Android buffer allocation failed");
|
||||
return;
|
||||
}
|
||||
AHardwareBuffer_describe(hardware, &desc);
|
||||
const struct android_native_handle *handle = native_handle(hardware);
|
||||
if (!handle || handle->num_fds < 1 || handle->num_fds > MAX_HANDLE_FDS ||
|
||||
handle->num_ints < 0 || handle->num_ints > MAX_HANDLE_INTS) {
|
||||
AHardwareBuffer_release(hardware);
|
||||
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "invalid allocated native handle");
|
||||
return;
|
||||
}
|
||||
struct wl_resource *buffer = create_android_buffer(client, 0, hardware);
|
||||
if (!buffer) {
|
||||
AHardwareBuffer_release(hardware);
|
||||
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "Vulkan cannot import allocated buffer");
|
||||
return;
|
||||
}
|
||||
struct wl_resource *reply = wl_resource_create(client, &android_wlegl_server_buffer_handle_interface,
|
||||
wl_resource_get_version(resource), id);
|
||||
if (!reply) {
|
||||
wl_resource_destroy(buffer); AHardwareBuffer_release(hardware);
|
||||
wl_client_post_no_memory(client); return;
|
||||
}
|
||||
struct wl_array ints = {.size = (size_t)handle->num_ints * sizeof(int32_t),
|
||||
.alloc = 0, .data = (void *)(handle->data + handle->num_fds)};
|
||||
android_wlegl_server_buffer_handle_send_buffer_ints(reply, &ints);
|
||||
for (int i = 0; i < handle->num_fds; i++)
|
||||
android_wlegl_server_buffer_handle_send_buffer_fd(reply, handle->data[i]);
|
||||
/* No linear_layout event: Android's opaque allocation need not be linear. */
|
||||
android_wlegl_server_buffer_handle_send_buffer(reply, buffer, (int32_t)desc.format, (int32_t)desc.stride);
|
||||
wl_resource_destroy(reply);
|
||||
AHardwareBuffer_release(hardware);
|
||||
}
|
||||
|
||||
static const struct android_wlegl_interface wlegl_impl = {
|
||||
.create_handle = create_handle, .create_buffer = create_buffer,
|
||||
.get_server_buffer_handle = get_server_buffer,
|
||||
};
|
||||
|
||||
static void bind_android_wlegl(struct wl_client *client, void *data, uint32_t version, uint32_t id) {
|
||||
struct wl_resource *resource = wl_resource_create(client, &android_wlegl_interface,
|
||||
version < 3 ? version : 3, id);
|
||||
if (!resource) { wl_client_post_no_memory(client); return; }
|
||||
wl_resource_set_implementation(resource, &wlegl_impl, NULL, NULL);
|
||||
}
|
||||
|
||||
void droiddeck_android_wlegl_init(struct wl_display *display) {
|
||||
if (!vkp_android_buffer_supported()) return;
|
||||
void *library = dlopen("libnativewindow.so", RTLD_NOW | RTLD_LOCAL);
|
||||
if (!library) return;
|
||||
import_handle = dlsym(library, "AHardwareBuffer_createFromHandle");
|
||||
native_handle = dlsym(library, "AHardwareBuffer_getNativeHandle");
|
||||
if (!import_handle || !native_handle) { dlclose(library); return; }
|
||||
/* Keep the platform entry points valid for the compositor's lifetime. */
|
||||
if (wl_global_create(display, &android_wlegl_interface, 3, NULL, bind_android_wlegl))
|
||||
droiddeck_log("display", "android_wlegl v3: Android buffer import available");
|
||||
}
|
||||
@@ -19,8 +19,6 @@ import com.droiddeck.launcher.gpu.GpuInfo
|
||||
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
|
||||
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
|
||||
import com.droiddeck.launcher.gpu.TurnipDriver
|
||||
import com.droiddeck.launcher.gpu.QualcommSystemDriver
|
||||
import com.droiddeck.launcher.gpu.QualcommDriverPackage
|
||||
import com.droiddeck.launcher.gpu.TurnipReleases
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
@@ -145,10 +143,6 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
}
|
||||
linuxRows = LinuxVulkanDriver.optionValues(activity).map { id ->
|
||||
if (id.isEmpty()) DriverRow("", activity.getString(R.string.gpu_runtime_default), activity.getString(R.string.drivers_runtime_builtin), false)
|
||||
else if (id == QualcommSystemDriver.ID) DriverRow(id, "System Qualcomm driver", QualcommSystemDriver.label(), false)
|
||||
else if (QualcommDriverPackage.isRuntimeId(id)) DriverRow(id,
|
||||
QualcommDriverPackage.label(activity, id), listOf(QualcommDriverPackage.version(activity, id),
|
||||
activity.getString(R.string.drivers_qualcomm_runtime_display)).filter { it.isNotEmpty() }.joinToString(" · "), false, DriverRow.IMPORTED)
|
||||
else bundleRow(id, linux = true) ?: DriverRow(
|
||||
id, lm.getDriverName(id),
|
||||
listOfNotNull(
|
||||
@@ -163,8 +157,6 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
val td = TurnipDriver(activity)
|
||||
val auto = td.autoId()
|
||||
androidRows = buildList {
|
||||
if (QualcommSystemDriver.detected()) add(DriverRow(TurnipDriver.SYSTEM,
|
||||
"System Qualcomm driver", QualcommSystemDriver.label(), false))
|
||||
add(DriverRow(
|
||||
TurnipDriver.AUTO, activity.getString(R.string.gpu_auto_by_gpu),
|
||||
if (auto == "system") activity.getString(R.string.drivers_system_vulkan) else activity.getString(R.string.drivers_bundled, td.displayName(auto)),
|
||||
@@ -439,10 +431,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
val bundle = DriverBundle.containing(activity, id, linux)
|
||||
when {
|
||||
bundle != null -> useBundle(bundle)
|
||||
linux -> {
|
||||
SessionPrefs.setLinuxDriver(activity, id)
|
||||
if (QualcommSystemDriver.handles(id)) SessionPrefs.setAndroidDriver(activity, TurnipDriver.SYSTEM)
|
||||
}
|
||||
linux -> SessionPrefs.setLinuxDriver(activity, id)
|
||||
else -> SessionPrefs.setAndroidDriver(activity, id)
|
||||
}
|
||||
pairModeOpen = false
|
||||
|
||||
@@ -168,6 +168,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var picturePosition by mutableStateOf("center")
|
||||
private var stretch16x9 by mutableStateOf(false)
|
||||
private var orientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
|
||||
private var launcherOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
|
||||
private var launcherFullscreen by mutableStateOf(true)
|
||||
private var downloadSource by mutableStateOf(DownloadSource.MODE_AUTO)
|
||||
private var downloadMirror by mutableStateOf("")
|
||||
@@ -391,7 +392,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var theme by mutableStateOf("graphite")
|
||||
private var appScale by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE)
|
||||
private var hdrOn by mutableStateOf(false)
|
||||
private var fpsLimit by mutableStateOf(0)
|
||||
private var performanceMode by mutableStateOf(false)
|
||||
private var upscaler by mutableStateOf(0)
|
||||
private var upscaleSharpness by mutableStateOf(75)
|
||||
@@ -775,7 +775,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
steamGamesX64 = cachedX64
|
||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||
orientation = SessionPrefs.orientation(this)
|
||||
requestedOrientation = orientation
|
||||
launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
||||
requestedOrientation = launcherOrientation
|
||||
launcherFullscreen = SessionPrefs.launcherFullscreen(this)
|
||||
downloadSource = DownloadSource.mode(this)
|
||||
downloadMirror = DownloadSource.mirror(this)
|
||||
@@ -844,6 +845,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
phantomProcessStatus = phantomProcessStatus,
|
||||
showPhantomGate = showPhantomGate,
|
||||
orientation = orientation,
|
||||
launcherOrientation = launcherOrientation,
|
||||
launcherFullscreen = launcherFullscreen,
|
||||
downloadSource = downloadSource,
|
||||
downloadMirror = downloadMirror,
|
||||
@@ -1026,6 +1028,10 @@ class FrontEndActivity : ComponentActivity() {
|
||||
onOrientation = { value ->
|
||||
SessionPrefs.setOrientation(this, value)
|
||||
orientation = value
|
||||
},
|
||||
onLauncherOrientation = { value ->
|
||||
com.droiddeck.launcher.core.AppUiPrefs.setOrientation(this, value)
|
||||
launcherOrientation = value
|
||||
requestedOrientation = value
|
||||
},
|
||||
onLauncherFullscreen = { on ->
|
||||
@@ -1301,23 +1307,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
override fun onUserInteraction() {
|
||||
super.onUserInteraction()
|
||||
com.droiddeck.launcher.ui.Ambient.poke()
|
||||
}
|
||||
|
||||
override fun dispatchTouchEvent(event: android.view.MotionEvent): Boolean {
|
||||
if (event.actionMasked == android.view.MotionEvent.ACTION_UP || event.actionMasked == android.view.MotionEvent.ACTION_CANCEL) {
|
||||
com.droiddeck.launcher.ui.Ambient.poke()
|
||||
}
|
||||
return super.dispatchTouchEvent(event)
|
||||
}
|
||||
|
||||
override fun dispatchGenericMotionEvent(event: android.view.MotionEvent): Boolean {
|
||||
com.droiddeck.launcher.ui.Ambient.poke()
|
||||
return super.dispatchGenericMotionEvent(event)
|
||||
}
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
if (event.keyCode == KeyEvent.KEYCODE_BUTTON_A) com.droiddeck.launcher.ui.HeldKeys.confirm = event.action == KeyEvent.ACTION_DOWN
|
||||
if (showComponents && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
|
||||
@@ -1338,13 +1327,13 @@ class FrontEndActivity : ComponentActivity() {
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
orientation = SessionPrefs.orientation(this)
|
||||
requestedOrientation = orientation
|
||||
launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
||||
requestedOrientation = launcherOrientation
|
||||
refreshWifiDiscovery()
|
||||
com.droiddeck.launcher.stores.StoresState.refresh(this)
|
||||
com.droiddeck.launcher.stores.StoresState.libraryListener = { refreshAddedGames(); refresh() }
|
||||
com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = { args -> openBattleNet(args) }
|
||||
com.droiddeck.launcher.ui.Motion.refresh(this)
|
||||
com.droiddeck.launcher.ui.Ambient.poke()
|
||||
com.droiddeck.launcher.ui.QuitFlood.take()?.let { c ->
|
||||
returning = ReturningFlood(c, com.droiddeck.launcher.ui.LaunchOrigin.takeReturn())
|
||||
}
|
||||
@@ -1713,7 +1702,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
ModeSettings(
|
||||
mode = mode, resolution = resolution,
|
||||
panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
|
||||
hdr = hdrOn, hdrReason = hdrReason, fpsLimit = fpsLimit, performanceMode = performanceMode,
|
||||
hdr = hdrOn, hdrReason = hdrReason, performanceMode = performanceMode,
|
||||
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
|
||||
gpuDrivers = drivers.summary(),
|
||||
touchMode = touchMode,
|
||||
@@ -1721,8 +1710,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
steamDownloadsInBackground = steamDownloadsInBackground,
|
||||
pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this),
|
||||
pipAutoEnter = pipAutoEnter,
|
||||
unfoldedControls = if (mode == SessionService.MODE_STEAM &&
|
||||
com.droiddeck.launcher.session.SessionDisplay.foldable(this)) unfoldedControls else null,
|
||||
unfoldedControls = if (mode == SessionService.MODE_STEAM) unfoldedControls else null,
|
||||
unfoldedControlsWithController = unfoldedControlsWithController,
|
||||
oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null,
|
||||
backActionsInverted = backActionsInverted,
|
||||
@@ -1779,7 +1767,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
onResolution = { value -> SessionPrefs.setResolutionChoice(this, mode, value); resolution = value },
|
||||
onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on },
|
||||
onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) },
|
||||
onFpsLimit = { fps -> SessionPrefs.setFpsLimit(this, mode, fps); fpsLimit = fps },
|
||||
onPerformanceMode = { on -> SessionPrefs.setPerformanceMode(this, mode, on); performanceMode = on },
|
||||
onUpscaler = { m -> SessionPrefs.setUpscaler(this, m); upscaler = m },
|
||||
onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct },
|
||||
@@ -2031,7 +2018,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
runSteamAtStartup = SessionPrefs.runSteamAtStartup(this)
|
||||
loadBootMovie()
|
||||
hdrOn = SessionPrefs.hdr(this, mode)
|
||||
fpsLimit = SessionPrefs.fpsLimit(this, mode)
|
||||
performanceMode = SessionPrefs.performanceMode(this, mode)
|
||||
upscaler = SessionPrefs.upscaler(this)
|
||||
upscaleSharpness = SessionPrefs.upscaleSharpness(this)
|
||||
@@ -2138,7 +2124,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
val scanGeneration = ++libraryScanGeneration
|
||||
val artRefreshesAtStart = HashMap(steamArtRefreshes)
|
||||
if (shortcutPicker) shortcutLibraryScanning = true
|
||||
if (SessionPrefs.steamClientArch(this) == "x86_64" && !OfflineMode.enabled(this)) {
|
||||
if (!OfflineMode.enabled(this)) {
|
||||
Thread({ com.droiddeck.launcher.session.FexCatalog.refresh(this) }, "fex-catalog").start()
|
||||
}
|
||||
Thread({
|
||||
|
||||
@@ -13,7 +13,7 @@ class HomeActivity : Activity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
|
||||
requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
||||
routeHome()
|
||||
}
|
||||
|
||||
|
||||
@@ -257,6 +257,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private val cursorResync = Runnable { if (syncClientCursor() && clientHidesCursor) cursorVisible = false }
|
||||
private val uiHandler = Handler(Looper.getMainLooper())
|
||||
private var pendingBackAction: Runnable? = null
|
||||
private val backQamInput = com.droiddeck.launcher.input.BackQamInput(
|
||||
setPressed = { padBridge?.setBackQamPressed(it) },
|
||||
onTap = { performBackAction(double = it) },
|
||||
)
|
||||
private var drawerDirectionKey = KeyEvent.KEYCODE_UNKNOWN
|
||||
private var drawerDirectionDownTime = 0L
|
||||
private var drawerDirectionDeviceId = -1
|
||||
@@ -318,8 +322,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private var drawerPage by mutableStateOf(SessionDrawerPage.CONTROLLER)
|
||||
private var drawerControllerActive by mutableStateOf(false)
|
||||
private var backActionsInverted by mutableStateOf(false)
|
||||
private var lowLatencyController by mutableStateOf(false)
|
||||
private var lowLatencyTouch by mutableStateOf(false)
|
||||
private var lowLatency by mutableStateOf(true)
|
||||
private var padType by mutableStateOf(SessionPrefs.CONTROLLER_DECK)
|
||||
private var pcKeyboardOpen by mutableStateOf(false)
|
||||
private var achievementsInFront by mutableStateOf<AchievementsInFront?>(null)
|
||||
@@ -447,6 +450,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
override fun onInputDeviceRemoved(deviceId: Int) {
|
||||
Log.i(TAG, "input device $deviceId disconnected")
|
||||
backQamInput.onDeviceRemoved(deviceId)
|
||||
joyConVr?.refresh()
|
||||
padBridge?.onDeviceRemoved(deviceId)
|
||||
if (::padMouse.isInitialized) padMouse.reset()
|
||||
@@ -493,7 +497,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
if (!SessionState.running) {
|
||||
val prefMode = SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM)
|
||||
SessionState.fpsLimit = SessionPrefs.fpsLimit(this, prefMode)
|
||||
SessionState.performanceMode = SessionPrefs.performanceMode(this, prefMode)
|
||||
}
|
||||
applyOutputPacing()
|
||||
@@ -775,6 +778,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, pipUi, SessionState.suspended) {
|
||||
if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || pipUi || SessionState.suspended) {
|
||||
backQamInput.cancel()
|
||||
cancelTouchGestures()
|
||||
screenKeys?.stopEditing()
|
||||
}
|
||||
@@ -1019,16 +1023,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
SessionPrefs.setBackActionsInverted(this@SessionActivity, inverted)
|
||||
backActionsInverted = inverted
|
||||
},
|
||||
lowLatencyController = lowLatencyController,
|
||||
lowLatencyTouch = lowLatencyTouch,
|
||||
onLowLatencyController = { on ->
|
||||
SessionPrefs.setLowLatencyController(this@SessionActivity, on)
|
||||
lowLatencyController = on
|
||||
applyLowLatency()
|
||||
},
|
||||
onLowLatencyTouch = { on ->
|
||||
SessionPrefs.setLowLatencyTouch(this@SessionActivity, on)
|
||||
lowLatencyTouch = on
|
||||
lowLatency = lowLatency,
|
||||
onLowLatency = { on ->
|
||||
SessionPrefs.setLowLatency(this@SessionActivity, on)
|
||||
lowLatency = on
|
||||
applyLowLatency()
|
||||
},
|
||||
onOsc = { v ->
|
||||
@@ -1092,7 +1090,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
pipAutoEnter = on
|
||||
pip.refresh(true)
|
||||
},
|
||||
unfoldedControls = if (com.droiddeck.launcher.session.SessionDisplay.foldable(this@SessionActivity)) unfoldedControls else null,
|
||||
unfoldedControls = unfoldedControls,
|
||||
onUnfoldedControls = ::chooseUnfoldedControls,
|
||||
unfoldedControlsWithController = unfoldedControlsWithController,
|
||||
onUnfoldedControlsWithController = ::chooseUnfoldedControlsWithController,
|
||||
@@ -1633,8 +1631,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
|
||||
oscMode = SessionPrefs.oscMode(this)
|
||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||
lowLatencyController = SessionPrefs.lowLatencyController(this)
|
||||
lowLatencyTouch = SessionPrefs.lowLatencyTouch(this)
|
||||
lowLatency = SessionPrefs.lowLatency(this)
|
||||
padType = SessionPrefs.steamController(this)
|
||||
}
|
||||
|
||||
@@ -1795,9 +1792,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
val driverId = if (CompositorHost.isStarted) null else turnip.install()
|
||||
|
||||
val previous = SessionState.outputSize
|
||||
val live = if (SessionState.followScreen && !isInPictureInPictureMode)
|
||||
com.droiddeck.launcher.session.SessionDisplay.followSize(holder.surfaceFrame.width(), holder.surfaceFrame.height())
|
||||
else null
|
||||
val live = windowOutputSize(holder.surfaceFrame.width(), holder.surfaceFrame.height())
|
||||
val size = live ?: if (SessionState.running) previous else glassesOutputSize() ?: outputSize()
|
||||
SessionState.outputSize = size
|
||||
if (!SessionState.running) SessionState.refreshHz = refreshHz()
|
||||
@@ -1854,7 +1849,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
)
|
||||
onOutputAttached(holder)
|
||||
if (SessionState.running && size != previous) {
|
||||
Log.i(TAG, "follow screen: ${previous.first}x${previous.second} -> ${size.first}x${size.second} on a new surface")
|
||||
Log.i(TAG, "output resized: ${previous.first}x${previous.second} -> ${size.first}x${size.second} on a new surface")
|
||||
WaylandCompositor.nativeResizeOutput(size.first, size.second)
|
||||
}
|
||||
if (!SessionState.running) SessionEvents.record("compositor.started")
|
||||
@@ -1886,15 +1881,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
cancelTouchGestures()
|
||||
Log.i(TAG, "surface resized to ${width}x$height - rebinding the compositor")
|
||||
CompositorHost.resize(holder.surface) { applyFrameGen() }
|
||||
followWindow(width, height)
|
||||
resizeOutputForWindow(width, height)
|
||||
}
|
||||
}
|
||||
|
||||
private fun followWindow(width: Int, height: Int) {
|
||||
if (!SessionState.followScreen || isInPictureInPictureMode || !CompositorHost.isStarted) return
|
||||
val size = com.droiddeck.launcher.session.SessionDisplay.followSize(width, height) ?: return
|
||||
private fun windowOutputSize(width: Int, height: Int): Pair<Int, Int>? {
|
||||
if (isInPictureInPictureMode || width <= 0 || height <= 0) return null
|
||||
return if (SessionState.followScreen)
|
||||
com.droiddeck.launcher.session.SessionDisplay.followSize(width, height, controlsBelowWanted())
|
||||
else if (glassesScreen == null) outputSize() else null
|
||||
}
|
||||
|
||||
private fun resizeOutputForWindow(width: Int, height: Int) {
|
||||
if (!CompositorHost.isStarted) return
|
||||
val size = windowOutputSize(width, height) ?: return
|
||||
if (size == SessionState.outputSize) return
|
||||
Log.i(TAG, "follow screen: ${SessionState.outputSize.first}x${SessionState.outputSize.second} -> ${size.first}x${size.second}")
|
||||
Log.i(TAG, "output resized: ${SessionState.outputSize.first}x${SessionState.outputSize.second} -> ${size.first}x${size.second}")
|
||||
SessionState.outputSize = size
|
||||
val panel = panelBounds()
|
||||
SessionState.upscaleRatio = maxOf(panel.width(), panel.height()).toFloat() / maxOf(size.first, size.second).coerceAtLeast(1)
|
||||
@@ -1908,11 +1910,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
private fun applyFollowOrientation(config: android.content.res.Configuration) {
|
||||
val wanted = if (SessionState.followScreen && config.smallestScreenWidthDp >= 600) {
|
||||
android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER
|
||||
} else {
|
||||
SessionPrefs.orientation(this)
|
||||
}
|
||||
val wanted = SessionPrefs.windowOrientation(this, SessionState.followScreen, config.smallestScreenWidthDp)
|
||||
if (requestedOrientation != wanted) requestedOrientation = wanted
|
||||
}
|
||||
|
||||
@@ -1924,6 +1922,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
cancelTouchGestures()
|
||||
applyFollowOrientation(newConfig)
|
||||
applyUnfoldedControls()
|
||||
resizeOutputForWindow(surfaceW, surfaceH)
|
||||
}
|
||||
|
||||
override fun surfaceDestroyed(holder: SurfaceHolder) {
|
||||
@@ -1965,7 +1964,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
Library.drawsAtPanel(program) && !SessionPrefs.resolutionChosen(this, mode))
|
||||
com.droiddeck.launcher.session.SessionDisplay.MATCH_SCREEN
|
||||
else SessionPrefs.resolutionChoice(this, mode, panel)
|
||||
return com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panel, choice)
|
||||
return com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panel, choice,
|
||||
SessionPrefs.portrait(this) && !controlsBelowWanted())
|
||||
}
|
||||
|
||||
private fun refreshHz(): Float {
|
||||
@@ -1984,7 +1984,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
GlassesRendering.mirrorRefreshLimit(glassesSettings, glasses, glassesScreen != null)
|
||||
|
||||
private fun outputFpsLimit(): Int = SessionPrefs.compositorFpsLimit(
|
||||
GlassesRendering.fpsLimit(SessionState.fpsLimit, mirrorRefreshLimit()), SessionState.performanceMode,
|
||||
mirrorRefreshLimit(), SessionState.performanceMode,
|
||||
)
|
||||
|
||||
private fun applyOutputPacing() {
|
||||
@@ -2081,9 +2081,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
return
|
||||
}
|
||||
val driverHint = runtimeDriverHint()
|
||||
Thread({
|
||||
val hint = driverHint ?: runtimeDamageHint() ?: sessionEndHint(SessionState.logFile)
|
||||
val hint = runtimeDamageHint() ?: sessionEndHint(SessionState.logFile) ?: prootFailureHint()
|
||||
runOnUiThread {
|
||||
if (isFinishing || isDestroyed) return@runOnUiThread
|
||||
showEnded(status, hint)
|
||||
@@ -2113,6 +2112,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
private fun releasePads() {
|
||||
backQamInput.cancel()
|
||||
padBridge?.releaseAll()
|
||||
joyConVr?.releaseButtons()
|
||||
}
|
||||
@@ -2139,12 +2139,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
private class EndHint(val text: String, val evenOnSuccess: Boolean = false, val repair: Boolean = false)
|
||||
|
||||
private fun runtimeDriverHint(): EndHint? {
|
||||
if (SessionState.failureCode != SessionService.FAILURE_RUNTIME_DRIVER) return null
|
||||
val message = getString(R.string.session_end_runtime_driver, getString(R.string.gpu_mode_mix), getString(R.string.gpu_change_runtime))
|
||||
return EndHint(listOfNotNull(message, SessionState.failureMessage?.takeIf { it.isNotBlank() }).joinToString("\n"))
|
||||
}
|
||||
|
||||
private fun runtimeDamageHint(): EndHint? {
|
||||
val broken = runCatching { com.droiddeck.launcher.runtime.RuntimeHealth.brokenLibraryLinks(this) }.getOrDefault(emptyList())
|
||||
if (broken.isEmpty()) return null
|
||||
@@ -2152,6 +2146,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
return EndHint(resources.getQuantityString(R.plurals.session_end_runtime_damaged, broken.size, broken.size, broken.first()), repair = true)
|
||||
}
|
||||
|
||||
private fun prootFailureHint(): EndHint? {
|
||||
if (SessionState.failureCode != "PROOT_MISSING") return null
|
||||
val message = SessionState.failureMessage ?: return null
|
||||
return EndHint(message)
|
||||
}
|
||||
|
||||
private fun sessionEndHint(log: File?): EndHint? {
|
||||
if (log == null || !log.isFile) return null
|
||||
return try {
|
||||
@@ -2191,6 +2191,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE ->
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
val backToQam = !pipUi && !screenKeyTextFocus && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
|
||||
SessionState.mode == SessionService.MODE_STEAM && SessionState.running && SessionState.firstFrameSeen &&
|
||||
!SessionState.suspended && padBridge?.canHoldQam() == true
|
||||
if (backQamInput.onKeyEvent(event, backToQam)) {
|
||||
pendingBackAction?.let(uiHandler::removeCallbacks)
|
||||
pendingBackAction = null
|
||||
return true
|
||||
}
|
||||
if (pipUi) return true
|
||||
if (screenKeyTextFocus) return super.dispatchKeyEvent(event)
|
||||
val pad = com.droiddeck.launcher.input.JoyCon.normalize(event)
|
||||
@@ -2692,21 +2700,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
screenKeys?.refreshAppearance()
|
||||
}
|
||||
|
||||
private fun controlsBelowWanted(): Boolean {
|
||||
if (!::sessionRoot.isInitialized || glassesScreen != null || cardboard.enabled) return false
|
||||
return SessionPrefs.controlsBelowWanted(this, SessionState.mode, sessionRoot.width, sessionRoot.height,
|
||||
pipUi || isInPictureInPictureMode)
|
||||
}
|
||||
|
||||
private fun applyUnfoldedControls() {
|
||||
if (!::sessionRoot.isInitialized) return
|
||||
val width = sessionRoot.width
|
||||
val height = sessionRoot.height
|
||||
val wanted = com.droiddeck.launcher.session.SessionDisplay.unfoldedControlsWanted(
|
||||
enabled = unfoldedControls,
|
||||
foldable = com.droiddeck.launcher.session.SessionDisplay.foldable(this),
|
||||
controllerConnected = PadBridge.anyControllerConnected() || SteamControllerBle.connected,
|
||||
keepWithController = unfoldedControlsWithController,
|
||||
steamDeckPad = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad,
|
||||
pip = pipUi || isInPictureInPictureMode,
|
||||
width = width,
|
||||
height = height,
|
||||
smallestWidthDp = resources.configuration.smallestScreenWidthDp,
|
||||
)
|
||||
val wanted = controlsBelowWanted()
|
||||
val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height)
|
||||
else FrameLayout.LayoutParams.MATCH_PARENT
|
||||
val params = surfaceView.layoutParams as FrameLayout.LayoutParams
|
||||
@@ -2716,13 +2720,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
else "unfolded controls: game full screen")
|
||||
}
|
||||
var panel = unfoldedPanel
|
||||
if (panel != null && panel.deckControls != SessionState.deckPad) {
|
||||
sessionRoot.removeView(panel)
|
||||
unfoldedPanel = null
|
||||
panel = null
|
||||
}
|
||||
if (!wanted) {
|
||||
if (panel != null) { sessionRoot.removeView(panel); unfoldedPanel = null; updateOnScreenControls() }
|
||||
return
|
||||
}
|
||||
if (panel == null) {
|
||||
panel = com.droiddeck.launcher.ui.DeckControlsPanel(this, onClose = { chooseUnfoldedControls(false) },
|
||||
onSteamMenu = ::tapSteamButton, onQam = ::tapQam, pad = padBridge)
|
||||
onSteamMenu = ::tapSteamButton, onQam = ::tapQam, pad = padBridge,
|
||||
portraitDock = !com.droiddeck.launcher.session.SessionDisplay.foldable(this))
|
||||
sessionRoot.addView(panel, sessionRoot.indexOfChild(surfaceView) + 1)
|
||||
unfoldedPanel = panel
|
||||
updateOnScreenControls()
|
||||
@@ -3158,7 +3168,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
override fun onPictureInPictureModeChanged(inPip: Boolean, newConfig: android.content.res.Configuration) {
|
||||
super.onPictureInPictureModeChanged(inPip, newConfig)
|
||||
if (::pip.isInitialized) pip.changed(inPip)
|
||||
if (!inPip && surfaceW > 0) followWindow(surfaceW, surfaceH)
|
||||
if (!inPip && surfaceW > 0) resizeOutputForWindow(surfaceW, surfaceH)
|
||||
applyUnfoldedControls()
|
||||
updateGlassesScreen()
|
||||
}
|
||||
@@ -3258,6 +3268,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
override fun onPause() {
|
||||
if (runtimeRemovalBlocked) { super.onPause(); return }
|
||||
backQamInput.cancel()
|
||||
capturePausedFrame()
|
||||
sessionClipboard.stop()
|
||||
if (::touchscreenGestures.isInitialized) touchscreenGestures.cancel()
|
||||
@@ -3632,15 +3643,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
private fun unbufferedSources() =
|
||||
if (lowLatencyTouch) UNBUFFERED_SOURCES or InputDevice.SOURCE_CLASS_POINTER else UNBUFFERED_SOURCES
|
||||
if (lowLatency) UNBUFFERED_SOURCES or InputDevice.SOURCE_CLASS_POINTER else UNBUFFERED_SOURCES
|
||||
|
||||
private fun applyLowLatency() {
|
||||
com.droiddeck.launcher.input.FakeInputWriter.setLowLatency(lowLatencyController, lowLatencyTouch)
|
||||
com.droiddeck.launcher.input.FakeInputWriter.setLowLatency(lowLatency)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) window.decorView.requestUnbufferedDispatch(unbufferedSources())
|
||||
}
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
if (!hasFocus) backQamInput.cancel()
|
||||
if (!hasFocus && ::padMouse.isInitialized) padMouse.reset()
|
||||
if (runtimeRemovalBlocked) return
|
||||
if (!hasFocus) {
|
||||
@@ -3688,6 +3700,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
backQamInput.cancel()
|
||||
steamVrRecovery.close()
|
||||
uiHandler.removeCallbacks(steamTouchRetry)
|
||||
if (runtimeRemovalBlocked) { super.onDestroy(); return }
|
||||
|
||||
@@ -26,6 +26,7 @@ public class PulseAudioComponent extends SessionPart {
|
||||
|
||||
|
||||
private final File workingDir;
|
||||
private final File deviceControls;
|
||||
private File logFile;
|
||||
private final String micFifoPath;
|
||||
private volatile int pid = -1;
|
||||
@@ -36,6 +37,8 @@ public class PulseAudioComponent extends SessionPart {
|
||||
|
||||
public PulseAudioComponent(Context context, String micFifoPath) {
|
||||
this.workingDir = new File(context.getFilesDir(), "pulseaudio");
|
||||
this.deviceControls = com.droiddeck.launcher.runtime.DeviceControlsComponent.directory(
|
||||
com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context));
|
||||
this.micFifoPath = micFifoPath;
|
||||
}
|
||||
|
||||
@@ -94,7 +97,7 @@ public class PulseAudioComponent extends SessionPart {
|
||||
config.add("load-module module-native-protocol-unix auth-anonymous=1 auth-cookie-enabled=0 socket=\""
|
||||
+ socket().getAbsolutePath() + "\"");
|
||||
config.add(".nofail");
|
||||
config.add("load-module module-directaudio-native-sink sink_name=DirectAudio performance_mode=1 adaptive=1 decay=0 limiter=1 watchdog=1 volume=1.0");
|
||||
config.add("load-module module-directaudio-native-sink sink_name=DirectAudio performance_mode=1 adaptive=1 decay=0 limiter=1 watchdog=1 volume=1.0 control_dir=" + deviceControls);
|
||||
config.add("set-default-sink DirectAudio");
|
||||
config.add(".fail");
|
||||
if (micFifoPath != null && !micFifoPath.isEmpty()) {
|
||||
@@ -139,7 +142,7 @@ public class PulseAudioComponent extends SessionPart {
|
||||
} else if (sinks.contains("\tDirectAudio\t") || sinks.startsWith("DirectAudio\t") || sinks.contains("\tDirectAudio\n") || sinks.matches("(?s).*\\bDirectAudio\\b.*")) {
|
||||
line = "== client sink: DirectAudio (module-directaudio-native-sink)";
|
||||
} else {
|
||||
boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0") != null
|
||||
boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) != null
|
||||
&& pactl("set-default-sink", "AAudioSink") != null;
|
||||
line = loaded ? "== client sink: DirectAudio did not come up; FALLBACK to the plain AAudio sink (AAudioSink)"
|
||||
: "== client sink: DirectAudio did not come up and the AAudio fallback failed too - no client sound";
|
||||
|
||||
@@ -1,11 +1,32 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.ActivityInfo
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
object AppUiPrefs {
|
||||
const val DEFAULT_SCALE = 100
|
||||
val scales = listOf(75, 85, 100, 115, 125, 150)
|
||||
|
||||
val orientationOptions = listOf(
|
||||
ActivityInfo.SCREEN_ORIENTATION_USER to R.string.setup_launcher_orientation_auto,
|
||||
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT to R.string.setup_orientation_portrait,
|
||||
ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE to R.string.setup_orientation_auto,
|
||||
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE to R.string.setup_orientation_landscape,
|
||||
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE to R.string.setup_orientation_reverse,
|
||||
)
|
||||
|
||||
fun orientation(context: Context): Int =
|
||||
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE)
|
||||
.getInt("orientation", ActivityInfo.SCREEN_ORIENTATION_USER)
|
||||
.takeIf { value -> orientationOptions.any { it.first == value } }
|
||||
?: ActivityInfo.SCREEN_ORIENTATION_USER
|
||||
|
||||
fun setOrientation(context: Context, value: Int) {
|
||||
require(orientationOptions.any { it.first == value })
|
||||
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putInt("orientation", value).apply()
|
||||
}
|
||||
|
||||
internal fun normalizeScale(percent: Int): Int = percent.takeIf { it in scales } ?: DEFAULT_SCALE
|
||||
|
||||
fun scale(context: Context): Int = normalizeScale(
|
||||
|
||||
@@ -222,10 +222,7 @@ object DeviceReport {
|
||||
val lm = LinuxVulkanDriverManager(context)
|
||||
run {
|
||||
val id = SessionPrefs.linuxDriver(context)
|
||||
val label = if (id == com.droiddeck.launcher.gpu.QualcommSystemDriver.ID) com.droiddeck.launcher.gpu.QualcommSystemDriver.label()
|
||||
else if (com.droiddeck.launcher.gpu.QualcommDriverPackage.isRuntimeId(id))
|
||||
"${com.droiddeck.launcher.gpu.QualcommDriverPackage.label(context, id)} ${com.droiddeck.launcher.gpu.QualcommDriverPackage.version(context, id)}"
|
||||
else if (id.isEmpty()) "runtime default (the Turnip built into the runtime)"
|
||||
val label = if (id.isEmpty()) "runtime default (the Turnip built into the runtime)"
|
||||
else "${lm.getDriverName(id)} ${lm.getDriverVersion(id)}".trim() +
|
||||
lm.getMinGlibc(id).let { if (it.isEmpty()) "" else " (glibc $it+)" } +
|
||||
if (lm.isInstalled(id)) "" else " [MISSING - falls back to the runtime's own]"
|
||||
@@ -264,6 +261,8 @@ object DeviceReport {
|
||||
k("VRAM cap", SessionPrefs.vramCapMb(context).let { if (it > 0) "$it MB" else "driver default" })
|
||||
k("proot without seccomp", SessionPrefs.prootNoSeccomp(context))
|
||||
k("proot fast path", SessionPrefs.prootFastPath(context))
|
||||
k("proot binary", LinuxRuntime.prootSource(context) + " " + LinuxRuntime.prootBinary(context).path)
|
||||
k("proot fast path (eligible)", com.droiddeck.launcher.runtime.ProotFastPath.enabled(context))
|
||||
k("Guest host name", SessionPrefs.guestHostname(context))
|
||||
k("DirectAudio for games", SessionPrefs.directAudio(context))
|
||||
k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context))
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.ui.focusGlide
|
||||
import android.content.res.Configuration
|
||||
import androidx.compose.animation.core.animateDpAsState
|
||||
import androidx.compose.foundation.background
|
||||
@@ -181,14 +183,14 @@ fun CollapsibleRail(
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
if (!state.portraitLocked) {
|
||||
IconButton(onClick = state.onToggle, modifier = Modifier.size(28.dp)) {
|
||||
IconButton(onClick = state.onToggle, modifier = Modifier.size(28.dp).focusGlide(CircleShape)) {
|
||||
Text("‹‹", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 15.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (collapsed && !state.portraitLocked) {
|
||||
IconButton(onClick = state.onToggle, modifier = Modifier.fillMaxWidth().height(24.dp)) {
|
||||
IconButton(onClick = state.onToggle, modifier = Modifier.fillMaxWidth().height(24.dp).focusGlide(CircleShape)) {
|
||||
Text("››", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 15.sp)
|
||||
}
|
||||
}
|
||||
@@ -197,14 +199,14 @@ fun CollapsibleRail(
|
||||
if (collapsed) {
|
||||
Row(horizontalArrangement = Arrangement.Center, modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)) {
|
||||
links.forEach { link ->
|
||||
IconButton(onClick = link.onClick, modifier = Modifier.size(32.dp)) {
|
||||
IconButton(onClick = link.onClick, modifier = Modifier.size(32.dp).focusGlide(CircleShape)) {
|
||||
Icon(link.icon, link.label, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
links.forEach { link ->
|
||||
TextButton(onClick = link.onClick, modifier = Modifier.padding(start = 4.dp)) {
|
||||
TextButton(onClick = link.onClick, modifier = Modifier.padding(start = 4.dp).focusGlide(CircleShape)) {
|
||||
Icon(link.icon, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(15.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(link.label, fontSize = 12.sp)
|
||||
@@ -250,11 +252,11 @@ fun CollapsibleRail(
|
||||
if (active) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline.copy(alpha = 0.5f),
|
||||
shape,
|
||||
)
|
||||
.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = item.onClick)
|
||||
.focusGlide(shape).clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = item.onClick)
|
||||
.padding(horizontal = if (collapsed) 2.dp else 11.dp, vertical = if (collapsed) 6.dp else 9.dp)
|
||||
} else {
|
||||
base
|
||||
.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = item.onClick)
|
||||
.focusGlide(shape).clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = item.onClick)
|
||||
.background(if (active) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent)
|
||||
.padding(horizontal = if (collapsed) 2.dp else 13.dp, vertical = if (collapsed) 7.dp else 11.dp)
|
||||
}
|
||||
@@ -361,6 +363,7 @@ private fun TopTabCell(
|
||||
modifier = modifier
|
||||
.clip(RoundedCornerShape(9.dp))
|
||||
.background(if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent)
|
||||
.focusGlide(RoundedCornerShape(9.dp))
|
||||
.then(
|
||||
if (isTab) {
|
||||
Modifier.selectable(selected = selected, role = androidx.compose.ui.semantics.Role.Tab, onClick = onClick)
|
||||
|
||||
@@ -21,7 +21,7 @@ class FileManagerActivity : ComponentActivity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
|
||||
requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
||||
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.ui.focusGlide
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
@@ -39,7 +41,7 @@ import androidx.compose.material.icons.filled.Storage
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import com.droiddeck.launcher.ui.GlideDropdownMenu as DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
@@ -105,12 +107,14 @@ private fun FileContextMenuItems(
|
||||
text = { Text(stringResource(R.string.fm_select)) },
|
||||
leadingIcon = { Icon(Icons.Filled.Checklist, null, tint = MaterialTheme.colorScheme.primary) },
|
||||
onClick = { onDismissMenu(); onSelect() },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
MenuItemDivider()
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.fm_properties)) },
|
||||
leadingIcon = { Icon(Icons.Filled.Info, null, tint = MaterialTheme.colorScheme.primary) },
|
||||
onClick = { onDismissMenu(); onProperties() },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
MenuItemDivider()
|
||||
if (isDir) {
|
||||
@@ -124,6 +128,7 @@ private fun FileContextMenuItems(
|
||||
)
|
||||
},
|
||||
onClick = { onToggleFavorite() },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
MenuItemDivider()
|
||||
}
|
||||
@@ -131,24 +136,28 @@ private fun FileContextMenuItems(
|
||||
text = { Text(stringResource(R.string.fm_rename)) },
|
||||
leadingIcon = { Icon(Icons.Filled.Edit, null, tint = MaterialTheme.colorScheme.primary) },
|
||||
onClick = { onDismissMenu(); onRename() },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
MenuItemDivider()
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.fm_copy)) },
|
||||
leadingIcon = { Icon(Icons.Filled.FileCopy, null, tint = MaterialTheme.colorScheme.primary) },
|
||||
onClick = { onDismissMenu(); onCopy() },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
MenuItemDivider()
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.fm_cut)) },
|
||||
leadingIcon = { Icon(Icons.Filled.ContentCut, null, tint = MaterialTheme.colorScheme.primary) },
|
||||
onClick = { onDismissMenu(); onCut() },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
MenuItemDivider()
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.common_delete)) },
|
||||
leadingIcon = { Icon(Icons.Filled.Delete, null, tint = MaterialTheme.colorScheme.primary) },
|
||||
onClick = { onDismissMenu(); onDelete() },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -193,7 +202,7 @@ internal fun FileItemRow(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 3.dp)
|
||||
.combinedClickable(role = androidx.compose.ui.semantics.Role.Button,
|
||||
.focusGlide(RoundedCornerShape(10.dp)).combinedClickable(role = androidx.compose.ui.semantics.Role.Button,
|
||||
onClick = { if (selectionMode) onToggleSelect() else onTap() },
|
||||
onLongClick = onLongPress,
|
||||
),
|
||||
@@ -212,7 +221,7 @@ internal fun FileItemRow(
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = if (compact) 3.dp else 8.dp),
|
||||
) {
|
||||
if (selectionMode) {
|
||||
androidx.compose.material3.Checkbox(checked = selected, onCheckedChange = { onToggleSelect() })
|
||||
androidx.compose.material3.Checkbox(checked = selected, onCheckedChange = { onToggleSelect() }, modifier = Modifier.focusGlide())
|
||||
Spacer(Modifier.width(4.dp))
|
||||
}
|
||||
when {
|
||||
@@ -270,7 +279,7 @@ internal fun FileItemRow(
|
||||
)
|
||||
}
|
||||
if (showActions) Box {
|
||||
IconButton(onClick = onMenu) {
|
||||
IconButton(onClick = onMenu, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(Icons.Filled.MoreVert, stringResource(R.string.fm_actions), tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(20.dp))
|
||||
}
|
||||
DropdownMenu(
|
||||
@@ -302,7 +311,7 @@ internal fun ParentFolderRow(compact: Boolean = false, onTap: () -> Unit) {
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 3.dp)
|
||||
.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onTap),
|
||||
.focusGlide(RoundedCornerShape(10.dp)).clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onTap),
|
||||
shape = RoundedCornerShape(10.dp),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
|
||||
@@ -370,6 +379,7 @@ internal fun FavoritesList(
|
||||
TextButton(
|
||||
onClick = onPinCurrent,
|
||||
enabled = !currentAlreadyPinned,
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) {
|
||||
Icon(Icons.Filled.PushPin, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
@@ -422,7 +432,7 @@ private fun FavoriteCard(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 3.dp)
|
||||
.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onJump),
|
||||
.focusGlide(RoundedCornerShape(10.dp)).clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onJump),
|
||||
shape = RoundedCornerShape(10.dp),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
|
||||
@@ -480,7 +490,7 @@ private fun FavoriteCard(
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
IconButton(onClick = onUnpin) {
|
||||
IconButton(onClick = onUnpin, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(
|
||||
Icons.Filled.Star,
|
||||
contentDescription = stringResource(R.string.fm_unpin_favorite),
|
||||
@@ -526,7 +536,7 @@ internal fun FileGridTile(
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.padding(4.dp)
|
||||
.combinedClickable(role = androidx.compose.ui.semantics.Role.Button,
|
||||
.focusGlide(RoundedCornerShape(10.dp)).combinedClickable(role = androidx.compose.ui.semantics.Role.Button,
|
||||
onClick = { if (selectionMode) onToggleSelect() else onTap() },
|
||||
onLongClick = onLongPress,
|
||||
),
|
||||
@@ -570,7 +580,7 @@ internal fun FileGridTile(
|
||||
androidx.compose.material3.Checkbox(
|
||||
checked = selected,
|
||||
onCheckedChange = { onToggleSelect() },
|
||||
modifier = Modifier.align(Alignment.TopStart),
|
||||
modifier = Modifier.align(Alignment.TopStart).focusGlide(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.ui.focusGlide
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import android.content.res.Configuration
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
@@ -19,6 +23,7 @@ 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.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.grid.GridCells
|
||||
@@ -50,7 +55,7 @@ import androidx.compose.material.icons.filled.Description
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material.icons.filled.SportsEsports
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import com.droiddeck.launcher.ui.GlideDropdownMenu as DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
@@ -318,10 +323,10 @@ fun FileManagerScreen(
|
||||
navigate(action)
|
||||
}
|
||||
}
|
||||
}) { Text(stringResource(R.string.fm_accept)) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_accept)) }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { pendingNavigation = null }) {
|
||||
TextButton(onClick = { pendingNavigation = null }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.fm_decline))
|
||||
}
|
||||
},
|
||||
@@ -509,15 +514,16 @@ fun FileManagerScreen(
|
||||
onValueChange = { folderName = it },
|
||||
label = { Text(stringResource(R.string.fm_folder_name)) },
|
||||
singleLine = true,
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
showNewFolderDialog = false
|
||||
if (folderName.isNotBlank()) createFolder(currentDir, folderName)
|
||||
}) { Text(stringResource(R.string.fm_create)) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_create)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { showNewFolderDialog = false }) { Text(stringResource(R.string.common_cancel)) } },
|
||||
dismissButton = { TextButton(onClick = { showNewFolderDialog = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -532,6 +538,7 @@ fun FileManagerScreen(
|
||||
onValueChange = { newName = it },
|
||||
label = { Text(stringResource(R.string.fm_new_name)) },
|
||||
singleLine = true,
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
@@ -539,9 +546,9 @@ fun FileManagerScreen(
|
||||
val file = renameTarget
|
||||
renameTarget = null
|
||||
if (file != null && newName.isNotBlank()) performRename(file, newName)
|
||||
}) { Text(stringResource(R.string.fm_rename)) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_rename)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { renameTarget = null }) { Text(stringResource(R.string.common_cancel)) } },
|
||||
dismissButton = { TextButton(onClick = { renameTarget = null }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -563,9 +570,9 @@ fun FileManagerScreen(
|
||||
TextButton(onClick = {
|
||||
selectedEntry = null
|
||||
performDelete(file)
|
||||
}) { Text(stringResource(R.string.common_delete)) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_delete)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { selectedEntry = null }) { Text(stringResource(R.string.common_cancel)) } },
|
||||
dismissButton = { TextButton(onClick = { selectedEntry = null }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -611,9 +618,9 @@ fun FileManagerScreen(
|
||||
Toast.makeText(context, context.resources.getQuantityString(R.plurals.fm_delete_some_failed, failed, failed), Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
}) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { pendingBulkDelete = emptyList() }) { Text(stringResource(R.string.common_cancel)) } },
|
||||
dismissButton = { TextButton(onClick = { pendingBulkDelete = emptyList() }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -636,6 +643,7 @@ fun FileManagerScreen(
|
||||
androidx.compose.material3.Checkbox(
|
||||
checked = conflictApplyToAll,
|
||||
onCheckedChange = { conflictApplyToAll = it },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
Text(stringResource(R.string.fm_conflict_apply_all), fontSize = 12.sp)
|
||||
}
|
||||
@@ -648,7 +656,7 @@ fun FileManagerScreen(
|
||||
ConflictChoice.SKIP to stringResource(R.string.fm_conflict_skip),
|
||||
).forEach { (choice, label) ->
|
||||
TextButton(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
modifier = Modifier.fillMaxWidth().focusGlide(CircleShape),
|
||||
onClick = { conflictChoice = choice; pendingConflict = null },
|
||||
) { Text(label, modifier = Modifier.fillMaxWidth()) }
|
||||
}
|
||||
@@ -656,13 +664,14 @@ fun FileManagerScreen(
|
||||
},
|
||||
confirmButton = {},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { conflictChoice = ConflictChoice.SKIP; pendingConflict = null }) {
|
||||
TextButton(onClick = { conflictChoice = ConflictChoice.SKIP; pendingConflict = null }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.common_cancel))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
val compactToolbar = LocalConfiguration.current.screenWidthDp < 600
|
||||
Column(modifier = Modifier.fillMaxSize()) {
|
||||
if (pickMode && !pickerTitle.isNullOrEmpty()) {
|
||||
Text(
|
||||
@@ -681,7 +690,7 @@ fun FileManagerScreen(
|
||||
onClick = { onPick?.invoke(currentDir) },
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp).focusGlide(CircleShape),
|
||||
) {
|
||||
Icon(Icons.Filled.Folder, null, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
@@ -693,9 +702,10 @@ fun FileManagerScreen(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.background(MaterialTheme.colorScheme.surfaceContainer)
|
||||
.then(if (compactToolbar) Modifier.horizontalScroll(rememberScrollState()) else Modifier)
|
||||
.padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
) {
|
||||
IconButton(onClick = { requestNavigation(FileManagerNavigation.UP) }, enabled = canGoUp && !cancellingNavigation) {
|
||||
IconButton(onClick = { requestNavigation(FileManagerNavigation.UP) }, enabled = canGoUp && !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(Icons.Filled.ArrowBack, stringResource(R.string.fm_back), tint = MaterialTheme.colorScheme.primary)
|
||||
}
|
||||
|
||||
@@ -744,6 +754,7 @@ fun FileManagerScreen(
|
||||
).show()
|
||||
}
|
||||
},
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
}
|
||||
linuxRoot?.let { root ->
|
||||
@@ -754,6 +765,7 @@ fun FileManagerScreen(
|
||||
Icon(Icons.Filled.Terminal, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp))
|
||||
},
|
||||
onClick = { showDriveMenu = false; openDrive(root) },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -769,10 +781,10 @@ fun FileManagerScreen(
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f),
|
||||
)
|
||||
} else if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT) {
|
||||
Spacer(Modifier.weight(1f))
|
||||
if (!compactToolbar) Spacer(Modifier.weight(1f))
|
||||
} else {
|
||||
Text(
|
||||
text = currentDir.name.ifBlank { currentDir.absolutePath },
|
||||
@@ -781,12 +793,12 @@ fun FileManagerScreen(
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
|
||||
if (launchDir != null) {
|
||||
IconButton(onClick = { requestNavigation(FileManagerNavigation.RETURN_TO_START) }, enabled = !cancellingNavigation) {
|
||||
IconButton(onClick = { requestNavigation(FileManagerNavigation.RETURN_TO_START) }, enabled = !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(Icons.AutoMirrored.Filled.KeyboardReturn, stringResource(R.string.fm_return_to_start), tint = MaterialTheme.colorScheme.primary)
|
||||
}
|
||||
if (LocalConfiguration.current.screenWidthDp >= 700) Spacer(Modifier.width(56.dp))
|
||||
@@ -798,7 +810,7 @@ fun FileManagerScreen(
|
||||
onClick = { showNewFolderDialog = true },
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.6f)),
|
||||
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 2.dp),
|
||||
modifier = Modifier.height(32.dp),
|
||||
modifier = Modifier.height(32.dp).focusGlide(CircleShape),
|
||||
) {
|
||||
Icon(Icons.Filled.CreateNewFolder, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
|
||||
Spacer(Modifier.width(5.dp))
|
||||
@@ -808,18 +820,18 @@ fun FileManagerScreen(
|
||||
IconButton(onClick = {
|
||||
gridView = !gridView
|
||||
browsePrefs.edit().putBoolean("fmGridView", gridView).apply()
|
||||
}) {
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(
|
||||
if (gridView) Icons.Filled.ViewList else Icons.Filled.GridView,
|
||||
if (gridView) stringResource(R.string.fm_list_view) else stringResource(R.string.fm_grid_view),
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
IconButton(onClick = { showSearch = !showSearch; if (!showSearch) searchQuery = "" }) {
|
||||
IconButton(onClick = { showSearch = !showSearch; if (!showSearch) searchQuery = "" }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(Icons.Filled.Search, stringResource(R.string.fm_search), tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
Box {
|
||||
IconButton(onClick = { showSortMenu = true }) {
|
||||
IconButton(onClick = { showSortMenu = true }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(Icons.Filled.Sort, stringResource(R.string.fm_sort), tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
DropdownMenu(expanded = showSortMenu, onDismissRequest = { showSortMenu = false }) {
|
||||
@@ -836,6 +848,7 @@ fun FileManagerScreen(
|
||||
showSortMenu = false
|
||||
loadDirectory(currentDir, resetScroll = false)
|
||||
},
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
}
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
|
||||
@@ -846,6 +859,7 @@ fun FileManagerScreen(
|
||||
browsePrefs.edit().putBoolean("fmCompactRows", compactRows).apply()
|
||||
showSortMenu = false
|
||||
},
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
DropdownMenuItem(
|
||||
text = { Text(if (showHidden) stringResource(R.string.fm_hide_hidden) else stringResource(R.string.fm_show_hidden)) },
|
||||
@@ -855,12 +869,13 @@ fun FileManagerScreen(
|
||||
showSortMenu = false
|
||||
loadDirectory(currentDir, resetScroll = false)
|
||||
},
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
IconButton(onClick = { showFavorites = !showFavorites }) {
|
||||
IconButton(onClick = { showFavorites = !showFavorites }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
if (showFavorites) {
|
||||
Icon(Icons.Filled.Star, stringResource(R.string.fm_hide_favorites), tint = MaterialTheme.colorScheme.primary)
|
||||
} else {
|
||||
@@ -868,7 +883,7 @@ fun FileManagerScreen(
|
||||
}
|
||||
}
|
||||
if (!pickMode && onExit != null) {
|
||||
IconButton(onClick = { requestNavigation(FileManagerNavigation.EXIT) }, enabled = !cancellingNavigation) {
|
||||
IconButton(onClick = { requestNavigation(FileManagerNavigation.EXIT) }, enabled = !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(Icons.AutoMirrored.Filled.ExitToApp, stringResource(R.string.fm_exit), tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
@@ -880,7 +895,7 @@ fun FileManagerScreen(
|
||||
onValueChange = { searchQuery = it },
|
||||
singleLine = true,
|
||||
placeholder = { Text(stringResource(R.string.fm_filter_folder), fontSize = 13.sp) },
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp).focusGlide(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -918,13 +933,14 @@ fun FileManagerScreen(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.background(MaterialTheme.colorScheme.primary.copy(alpha = 0.12f))
|
||||
.then(if (compactToolbar) Modifier.horizontalScroll(rememberScrollState()) else Modifier)
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
) {
|
||||
Text(
|
||||
stringResource(R.string.fm_selected_count, selectedPaths.size),
|
||||
color = MaterialTheme.colorScheme.onBackground,
|
||||
fontSize = 13.sp,
|
||||
modifier = Modifier.weight(1f),
|
||||
modifier = if (compactToolbar) Modifier.padding(end = 12.dp) else Modifier.weight(1f),
|
||||
)
|
||||
val allVisibleSelected = visibleEntries.isNotEmpty() && visibleEntries.all { it.absolutePath in selectedPaths }
|
||||
val anyVisibleSelected = visibleEntries.any { it.absolutePath in selectedPaths }
|
||||
@@ -935,6 +951,7 @@ fun FileManagerScreen(
|
||||
selectedPaths = if (allVisibleSelected) selectedPaths - shown.toSet() else selectedPaths + shown
|
||||
},
|
||||
contentPadding = selBarPadding,
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) { Text(if (allVisibleSelected) stringResource(R.string.fm_select_none) else stringResource(R.string.fm_select_all), fontSize = 12.sp) }
|
||||
Spacer(Modifier.width(4.dp))
|
||||
OutlinedButton(
|
||||
@@ -946,6 +963,7 @@ fun FileManagerScreen(
|
||||
selectedPaths = emptySet()
|
||||
},
|
||||
contentPadding = selBarPadding,
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) { Text(stringResource(R.string.fm_copy), fontSize = 12.sp) }
|
||||
Spacer(Modifier.width(4.dp))
|
||||
OutlinedButton(
|
||||
@@ -957,6 +975,7 @@ fun FileManagerScreen(
|
||||
selectedPaths = emptySet()
|
||||
},
|
||||
contentPadding = selBarPadding,
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) { Text(stringResource(R.string.fm_cut), fontSize = 12.sp) }
|
||||
Spacer(Modifier.width(4.dp))
|
||||
OutlinedButton(
|
||||
@@ -964,11 +983,13 @@ fun FileManagerScreen(
|
||||
onClick = { pendingBulkDelete = visibleEntries.filter { it.absolutePath in selectedPaths } },
|
||||
contentPadding = selBarPadding,
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.error),
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error, fontSize = 12.sp) }
|
||||
Spacer(Modifier.width(4.dp))
|
||||
OutlinedButton(
|
||||
onClick = { selectionMode = false; selectedPaths = emptySet() },
|
||||
contentPadding = selBarPadding,
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) { Text(stringResource(R.string.fm_done), fontSize = 12.sp) }
|
||||
}
|
||||
}
|
||||
@@ -990,7 +1011,7 @@ fun FileManagerScreen(
|
||||
if (isCutOperation) stringResource(R.string.fm_paste_move_here, what) else stringResource(R.string.fm_paste_here, what),
|
||||
color = MaterialTheme.colorScheme.onBackground, fontSize = 13.sp, modifier = Modifier.weight(1f),
|
||||
)
|
||||
TextButton(onClick = { clipboardFiles = emptyList(); isCutOperation = false }) {
|
||||
TextButton(onClick = { clipboardFiles = emptyList(); isCutOperation = false }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.common_cancel), color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 12.sp)
|
||||
}
|
||||
}
|
||||
@@ -1021,7 +1042,7 @@ fun FileManagerScreen(
|
||||
isOperationRunning = false
|
||||
operationDeterminate = false
|
||||
loadDirectory(currentDir, resetScroll = false)
|
||||
}) { Text(stringResource(R.string.common_cancel), fontSize = 12.sp) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel), fontSize = 12.sp) }
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
|
||||
@@ -25,7 +25,7 @@ class FilePickerActivity : ComponentActivity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
|
||||
requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
||||
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.ui.focusGlide
|
||||
import android.widget.Toast
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
@@ -128,7 +130,7 @@ internal fun FilePropertiesDialog(
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.fm_done)) } },
|
||||
confirmButton = { TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_done)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -182,6 +184,7 @@ private fun AttributeToggleRow(
|
||||
checked = checked,
|
||||
enabled = enabled,
|
||||
onCheckedChange = onToggle,
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
|
||||
import androidx.compose.material3.AlertDialogDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
|
||||
@@ -32,12 +32,6 @@ internal object GlassesRendering {
|
||||
return if (hz == 30 && kotlin.math.abs(state.hz - 30f) >= 0.5f) 60 else hz
|
||||
}
|
||||
|
||||
fun fpsLimit(requested: Int, mirrorRefreshLimit: Int): Int = when {
|
||||
mirrorRefreshLimit <= 0 -> requested
|
||||
requested <= 0 -> mirrorRefreshLimit
|
||||
else -> minOf(requested, mirrorRefreshLimit)
|
||||
}
|
||||
|
||||
fun usesGlasses(state: GlassesState, outputActive: Boolean, steamVrRunning: Boolean): Boolean =
|
||||
outputActive || (steamVrRunning && state.usable)
|
||||
|
||||
|
||||
@@ -149,9 +149,7 @@ object DeviceInfo {
|
||||
add("Display driver", "${turnip.displayName(choice)} ${turnip.driverVersion(choice)}".trim())
|
||||
val linux = LinuxVulkanDriverManager(context)
|
||||
val id = SessionPrefs.linuxDriver(context)
|
||||
add("Game driver", if (id == QualcommSystemDriver.ID) QualcommSystemDriver.label()
|
||||
else if (QualcommDriverPackage.isRuntimeId(id)) "${QualcommDriverPackage.label(context, id)} ${QualcommDriverPackage.version(context, id)}"
|
||||
else if (id.isEmpty()) "the runtime's own Turnip" else "${linux.getDriverName(id)} ${linux.getDriverVersion(id)}".trim())
|
||||
add("Game driver", if (id.isEmpty()) "the runtime's own Turnip" else "${linux.getDriverName(id)} ${linux.getDriverVersion(id)}".trim())
|
||||
if (gpu.oneUi8Gen2) add("Note", "One UI on an 8 Gen 2: needs the OneUI Turnip build")
|
||||
})
|
||||
}
|
||||
@@ -12,8 +12,8 @@ public final class LinuxVulkanDriver {
|
||||
|
||||
public static final String HELP_TEXT =
|
||||
"The driver the Steam client, the games it launches and the desktop's programs render on, "
|
||||
+ "inside the Linux runtime. Import \"-Linux\" Turnip zips, or select the experimental system "
|
||||
+ "Qualcomm bridge or a Qualcomm package already imported as an AdrenoTools zip. Frames reach the screen through the "
|
||||
+ "inside the Linux runtime. Imported \"-Linux\" Turnip zips only: these are Linux processes "
|
||||
+ "and cannot load an Android or Wayland driver. Frames still reach the screen through the "
|
||||
+ "display driver below. Takes effect at the next session start.";
|
||||
|
||||
private LinuxVulkanDriver() {}
|
||||
@@ -21,18 +21,12 @@ public final class LinuxVulkanDriver {
|
||||
public static List<String> optionValues(Context context) {
|
||||
ArrayList<String> values = new ArrayList<>();
|
||||
values.add("");
|
||||
if (QualcommSystemDriver.detected()) {
|
||||
values.add(QualcommSystemDriver.ID);
|
||||
values.addAll(QualcommDriverPackage.available(context));
|
||||
}
|
||||
values.addAll(new LinuxVulkanDriverManager(context).enumerateInstalledDrivers());
|
||||
return values;
|
||||
}
|
||||
|
||||
public static String optionLabel(Context context, String value) {
|
||||
if (value == null || value.isEmpty()) return "Runtime default (built into the runtime)";
|
||||
if (QualcommSystemDriver.ID.equals(value)) return QualcommSystemDriver.label();
|
||||
if (QualcommDriverPackage.isRuntimeId(value)) return QualcommDriverPackage.label(context, value);
|
||||
LinuxVulkanDriverManager m = new LinuxVulkanDriverManager(context);
|
||||
if (!m.isInstalled(value)) return value + " (imported, missing - uses the runtime default)";
|
||||
String ver = m.getDriverVersion(value);
|
||||
@@ -41,11 +35,6 @@ public final class LinuxVulkanDriver {
|
||||
|
||||
public static String resolveIcdPath(Context context, String value) {
|
||||
if (value == null || value.isEmpty()) return null;
|
||||
if (QualcommSystemDriver.handles(value)) {
|
||||
if (QualcommDriverPackage.isRuntimeId(value) && !QualcommDriverPackage.isInstalled(context, value))
|
||||
throw new QualcommSystemDriver.Unavailable("The selected Qualcomm AdrenoTools package is missing or incompatible");
|
||||
return QualcommSystemDriver.prepare(context).getAbsolutePath();
|
||||
}
|
||||
LinuxVulkanDriverManager m = new LinuxVulkanDriverManager(context);
|
||||
String icd = m.getIcdPath(value);
|
||||
if (icd == null) {
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
object QualcommDriverPackage {
|
||||
private const val PREFIX = "qualcomm-adrenotools:"
|
||||
|
||||
@JvmStatic fun runtimeId(importedId: String): String {
|
||||
require(validName(importedId)) { "Invalid imported driver ID" }
|
||||
return PREFIX + importedId
|
||||
}
|
||||
|
||||
@JvmStatic fun importedId(runtimeId: String?): String? = runtimeId
|
||||
?.takeIf { it.startsWith(PREFIX) }?.removePrefix(PREFIX)?.takeIf(::validName)
|
||||
|
||||
@JvmStatic fun isRuntimeId(id: String?): Boolean = id?.startsWith(PREFIX) == true
|
||||
|
||||
private fun validName(name: String): Boolean = name.isNotBlank() && name != "." && !name.contains("..") &&
|
||||
name.none { it == '/' || it == '\\' || it == ':' || it == '\u0000' }
|
||||
|
||||
private fun metadata(context: Context, id: String): JSONObject? {
|
||||
if (!validName(id)) return null
|
||||
return runCatching { JSONObject(FileUtils.readString(File(TurnipDriver(context).driverPath(id), "meta.json"))) }.getOrNull()
|
||||
}
|
||||
|
||||
@JvmStatic fun available(context: Context): List<String> = TurnipDriver(context).enumerateImported()
|
||||
.filter { isInstalled(context, runtimeId(it)) }.map(::runtimeId)
|
||||
|
||||
@JvmStatic fun isInstalled(context: Context, runtimeId: String): Boolean {
|
||||
val id = importedId(runtimeId) ?: return false
|
||||
val meta = metadata(context, id) ?: return false
|
||||
val vendor = meta.optString("vendor")
|
||||
val description = listOf(meta.optString("name"), meta.optString("description"), meta.optString("libraryName")).joinToString(" ")
|
||||
if (!vendor.equals("Qualcomm", true) || description.contains("turnip", true) || description.contains("mesa", true)) return false
|
||||
if (meta.optInt("minApi", 0) > Build.VERSION.SDK_INT) return false
|
||||
val library = meta.optString("libraryName")
|
||||
return validName(library) && library.endsWith(".so") && TurnipDriver(context).isInstalled(id) &&
|
||||
LinuxVulkanDriverManager.isAarch64Elf(File(TurnipDriver(context).driverPath(id), library))
|
||||
}
|
||||
|
||||
@JvmStatic fun label(context: Context, runtimeId: String): String {
|
||||
val id = importedId(runtimeId) ?: return "Invalid Qualcomm package"
|
||||
val driver = TurnipDriver(context)
|
||||
return "${driver.displayName(id)} · Qualcomm (AdrenoTools, experimental)" +
|
||||
if (isInstalled(context, runtimeId)) "" else " [missing or incompatible]"
|
||||
}
|
||||
|
||||
@JvmStatic fun version(context: Context, runtimeId: String): String = importedId(runtimeId)
|
||||
?.let { TurnipDriver(context).driverVersion(it) }.orEmpty()
|
||||
|
||||
@JvmStatic fun mounts(context: Context, runtimeId: String): List<String> {
|
||||
ensureAvailable(isInstalled(context, runtimeId)) { "The selected Qualcomm AdrenoTools package is missing or incompatible" }
|
||||
val id = importedId(runtimeId)!!
|
||||
val driver = TurnipDriver(context)
|
||||
val directory = File(driver.driverPath(id))
|
||||
val primary = driver.libraryName(id)!!
|
||||
val mounts = arrayListOf("${File(directory, primary).path}:${QualcommSystemDriver.HAL}")
|
||||
for (library in directory.listFiles().orEmpty().sortedBy { it.name }) {
|
||||
val name = library.name
|
||||
if (name == primary || !name.endsWith(".so") || !validName(name) ||
|
||||
name in setOf("libc.so", "libdl.so", "libm.so", "liblog.so", "libvulkan.so") ||
|
||||
!LinuxVulkanDriverManager.isAarch64Elf(library)) continue
|
||||
mounts.add("${library.path}:/vendor/lib64/$name")
|
||||
// The SP-HAL namespace resolves libc++ from system before vendor.
|
||||
if (name == "libc++.so") mounts.add("${library.path}:/system/lib64/$name")
|
||||
}
|
||||
return mounts
|
||||
}
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import com.droiddeck.launcher.BuildConfig
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.core.TarZst
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
internal inline fun ensureAvailable(condition: Boolean, message: () -> String) {
|
||||
if (!condition) throw QualcommSystemDriver.Unavailable(message())
|
||||
}
|
||||
|
||||
object QualcommSystemDriver {
|
||||
class Unavailable(message: String) : IllegalStateException(message)
|
||||
|
||||
const val ID = "system-qualcomm"
|
||||
const val HAL = "/vendor/lib64/hw/vulkan.adreno.so"
|
||||
private val required = listOf("lib/libhybris-vulkan-icd.so.0", "lib/libhybris-common.so.1", "lib/libhybris/linker/q.so",
|
||||
"bin/gamescope", "shaders/qualcomm-shaders.so", "wsi/libVkLayer_window_system_integration.so",
|
||||
"mesa/libgallium-26.2.3.so", "mesa/dri/zink_dri.so", "mesa/libGLX_droiddeck_qualcomm.so.0",
|
||||
"mesa/libEGL_droiddeck_qualcomm.so.0", "mesa/libgbm.so.1", "mesa/gbm/dri_gbm.so",
|
||||
"mesa/egl-vendor.json", "mesa/qualcomm-gl.sh")
|
||||
|
||||
@JvmStatic fun detected(): Boolean {
|
||||
if (Build.VERSION.SDK_INT < 29 || !File(HAL).canRead()) return false
|
||||
val vk = VulkanInfo.query()
|
||||
return isQualcomm(vk)
|
||||
}
|
||||
|
||||
internal fun isQualcomm(vk: Map<String, String>): Boolean =
|
||||
vk["vendor_id"] == "0x5143" && (vk["driver_id"] == "8" ||
|
||||
(vk["driver_id"] == null && vk["driver_name"]?.contains("Qualcomm", ignoreCase = true) == true))
|
||||
|
||||
@JvmStatic fun handles(id: String?) = id == ID || QualcommDriverPackage.isRuntimeId(id)
|
||||
|
||||
@JvmStatic fun selected(context: Context) = handles(SessionPrefs.linuxDriver(context))
|
||||
|
||||
@JvmStatic fun mounts(context: Context, id: String): List<String> = androidPaths() +
|
||||
if (QualcommDriverPackage.isRuntimeId(id)) QualcommDriverPackage.mounts(context, id) else emptyList()
|
||||
|
||||
@JvmStatic fun label(): String {
|
||||
val vk = VulkanInfo.query()
|
||||
val version = vk["driver_version_raw"]?.toULongOrNull()?.let { "${(it shr 22) and 0x7fu}.${(it shr 12) and 0x3ffu}.${it and 0xfffu}" }
|
||||
?: vk["driver_version"] ?: "unknown version"
|
||||
return "System Qualcomm · ${vk["device"] ?: "Adreno"} · $version (experimental)"
|
||||
}
|
||||
|
||||
@JvmStatic @Synchronized fun prepare(context: Context): File {
|
||||
ensureAvailable(detected()) { "The installed Vulkan driver is not a supported Qualcomm Android driver" }
|
||||
val sha = BuildConfig.QUALCOMM_BRIDGE_SHA256 + "-" + BuildConfig.QUALCOMM_FIXES_REVISION.take(16)
|
||||
val root = File(context.filesDir, "qualcomm-system")
|
||||
val dir = File(root, sha)
|
||||
if (!File(dir, ".complete").isFile || required.any { !File(dir, it).isFile }) {
|
||||
val staging = File(root, "$sha.partial")
|
||||
FileUtils.delete(staging)
|
||||
ensureAvailable(TarZst.extractAsset(context, "qualcomm/runtime.tzst", staging)) { "Cannot extract the Qualcomm Vulkan bridge" }
|
||||
val gamescope = File(staging, "bin/gamescope")
|
||||
gamescope.parentFile!!.mkdirs()
|
||||
ensureAvailable(FileUtils.copyAsset(context, "qualcomm/gamescope", gamescope)) { "Cannot prepare Qualcomm Gamescope" }
|
||||
ensureAvailable(gamescope.setExecutable(true, false)) { "Cannot prepare Qualcomm Gamescope" }
|
||||
copyAssets(context, "qualcomm/wsi", File(staging, "wsi"))
|
||||
copyAssets(context, "qualcomm/shaders", File(staging, "shaders"))
|
||||
copyAssets(context, "qualcomm/licenses", File(staging, "licenses"))
|
||||
copyAssets(context, "qualcomm/mesa", File(staging, "mesa"))
|
||||
ensureAvailable(required.all { File(staging, it).isFile }) { "The Qualcomm Vulkan bridge is incomplete" }
|
||||
File(staging, ".complete").writeText(sha)
|
||||
FileUtils.delete(dir)
|
||||
ensureAvailable(staging.renameTo(dir)) { "Cannot install the Qualcomm Vulkan bridge" }
|
||||
}
|
||||
val manifest = JSONObject().put("file_format_version", "1.0.0").put("ICD", JSONObject()
|
||||
.put("library_path", File(dir, "lib/libhybris-vulkan-icd.so.0").path)
|
||||
.put("api_version", VulkanInfo.query()["api"] ?: "1.1.0"))
|
||||
val icd = File(dir, "icd.json")
|
||||
if (!icd.isFile || icd.readText() != manifest.toString()) icd.writeText(manifest.toString())
|
||||
return icd
|
||||
}
|
||||
|
||||
@JvmStatic @JvmOverloads fun addEnvironment(context: Context, environment: MutableList<String>, id: String = SessionPrefs.linuxDriver(context)) {
|
||||
if (QualcommDriverPackage.isRuntimeId(id)) ensureAvailable(QualcommDriverPackage.isInstalled(context, id)) {
|
||||
"The selected Qualcomm AdrenoTools package is missing or incompatible"
|
||||
}
|
||||
val icd = prepare(context)
|
||||
val source = if (id == ID) label() else QualcommDriverPackage.label(context, id)
|
||||
android.util.Log.i("QualcommSystemDriver", "$source; Android mounts: ${mounts(context, id).joinToString()}")
|
||||
environment.addAll(sessionEnvironment(icd, id))
|
||||
}
|
||||
|
||||
internal fun sessionEnvironment(icd: File, id: String): List<String> {
|
||||
val dir = icd.parentFile!!
|
||||
return listOf(
|
||||
"VK_DRIVER_FILES=${icd.path}", "VK_ICD_FILENAMES=${icd.path}",
|
||||
"HYBRIS_ANDROID_SDK_VERSION=${Build.VERSION.SDK_INT}", "HYBRIS_VULKAN_HAL=$HAL",
|
||||
"HYBRIS_LINKER_DIR=${File(dir, "lib/libhybris/linker").path}",
|
||||
"HYBRIS_LD_LIBRARY_PATH=/system/lib64:/system_ext/lib64:/vendor/lib64/egl:/vendor/lib64/hw:/vendor/lib64",
|
||||
// The compat layer's Mali-only image-bounds pass rewrites unrelated OpSelects; DXVK comparisons become constants on Adreno.
|
||||
"HYBRIS_VULKAN_COMPAT_IMAGE_BOUNDS=0",
|
||||
"DROIDDECK_SYSTEM_QUALCOMM=1", "BL_GAMESCOPE_BACKEND=sdl",
|
||||
"DROIDDECK_QUALCOMM_DRIVER=$id",
|
||||
"BL_GAMESCOPE_BINARY=${File(dir, "bin/gamescope").path}",
|
||||
"DROIDDECK_QUALCOMM_ROOT=${dir.path}",
|
||||
"DROIDDECK_QUALCOMM_SHADERS=${File(dir, "shaders").path}",
|
||||
"VK_LAYER_PATH=${File(dir, "shaders").path}",
|
||||
"VK_INSTANCE_LAYERS=VK_LAYER_DROIDDECK_qualcomm_shaders",
|
||||
"PATH=${File(dir, "bin").path}:/usr/local/bin:/usr/bin:/bin",
|
||||
)
|
||||
}
|
||||
|
||||
private fun copyAssets(context: Context, path: String, destination: File) {
|
||||
val children = context.assets.list(path) ?: emptyArray()
|
||||
if (children.isEmpty()) {
|
||||
ensureAvailable(FileUtils.copyAsset(context, path, destination)) { "Cannot prepare $path" }
|
||||
} else {
|
||||
ensureAvailable(destination.isDirectory || destination.mkdirs()) { "Cannot prepare $path" }
|
||||
for (child in children) copyAssets(context, "$path/$child", File(destination, child))
|
||||
}
|
||||
}
|
||||
|
||||
@JvmStatic fun androidPaths(): List<String> = listOf(
|
||||
"/system", "/vendor", "/odm", "/system_ext", "/product", "/apex", "/linkerconfig",
|
||||
"/dev/__properties__"
|
||||
).filter { File(it).exists() }
|
||||
}
|
||||
@@ -37,7 +37,6 @@ public final class TurnipDriver {
|
||||
private static final String PREFS = "graphics_driver";
|
||||
private static final String KEY_HIDDEN = "hiddenBundled";
|
||||
public static final String AUTO = "";
|
||||
public static final String SYSTEM = "system";
|
||||
|
||||
public static final String HELP_TEXT =
|
||||
"The driver the app's compositor puts frames on the screen with - the last step of every "
|
||||
@@ -140,8 +139,6 @@ public final class TurnipDriver {
|
||||
Log.d(TAG, "removing imported driver " + driverId);
|
||||
FileUtils.delete(new File(contentDir, driverId));
|
||||
if (driverId.equals(SessionPrefs.androidDriver(context))) SessionPrefs.setAndroidDriver(context, AUTO);
|
||||
if (driverId.equals(QualcommDriverPackage.importedId(SessionPrefs.INSTANCE.linuxDriver(context))))
|
||||
SessionPrefs.INSTANCE.setLinuxDriver(context, "");
|
||||
}
|
||||
|
||||
public String installFromZip(Uri zipUri, String displayName) throws IOException {
|
||||
@@ -260,7 +257,6 @@ public final class TurnipDriver {
|
||||
|
||||
private String choose() {
|
||||
String chosen = SessionPrefs.androidDriver(context);
|
||||
if (SYSTEM.equals(chosen)) return null;
|
||||
if (chosen != null && !chosen.isEmpty()) {
|
||||
if (BUNDLED.contains(chosen)) {
|
||||
Log.i(TAG, "driver pinned by the user: " + chosen);
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.view.KeyEvent
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
|
||||
class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap: (Boolean) -> Unit) {
|
||||
private class Press(val hold: Runnable, var held: Boolean = false, var used: Boolean = false)
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val presses = mutableMapOf<Int, Press>()
|
||||
private val cancelled = mutableSetOf<Int>()
|
||||
private var tapPending = false
|
||||
private val singleTap = Runnable { tapPending = false; onTap(false) }
|
||||
|
||||
private fun cancelTap() {
|
||||
handler.removeCallbacks(singleTap)
|
||||
tapPending = false
|
||||
}
|
||||
|
||||
fun onKeyEvent(event: KeyEvent, enabled: Boolean): Boolean {
|
||||
if (!enabled) cancel()
|
||||
if (event.keyCode != KeyEvent.KEYCODE_BACK) return false
|
||||
val device = event.deviceId
|
||||
return when (event.action) {
|
||||
KeyEvent.ACTION_DOWN -> {
|
||||
if (event.repeatCount > 0) return enabled || device in presses || device in cancelled
|
||||
cancelled.remove(device)
|
||||
if (!enabled || event.isCanceled) return false
|
||||
if (device in presses) return true
|
||||
handler.removeCallbacks(singleTap)
|
||||
val hold = Runnable {
|
||||
val press = presses[device] ?: return@Runnable
|
||||
val alreadyHeld = presses.values.any { it.held }
|
||||
press.held = true
|
||||
presses.values.forEach { it.used = true }
|
||||
cancelTap()
|
||||
if (!alreadyHeld) setPressed(true)
|
||||
}
|
||||
presses[device] = Press(hold, used = presses.values.any { it.held })
|
||||
handler.postDelayed(hold, 700)
|
||||
true
|
||||
}
|
||||
KeyEvent.ACTION_UP -> {
|
||||
val press = presses.remove(device)
|
||||
val wasCancelled = cancelled.remove(device)
|
||||
if (press != null) {
|
||||
handler.removeCallbacks(press.hold)
|
||||
if (press.held && presses.values.none { it.held }) setPressed(false)
|
||||
if (!press.used && !event.isCanceled) {
|
||||
if (tapPending) { cancelTap(); onTap(true) }
|
||||
else { tapPending = true; handler.postDelayed(singleTap, 500) }
|
||||
} else if (event.isCanceled) cancelTap()
|
||||
}
|
||||
press != null || wasCancelled || enabled
|
||||
}
|
||||
else -> device in presses || device in cancelled
|
||||
}
|
||||
}
|
||||
|
||||
fun cancel() {
|
||||
cancelTap()
|
||||
val wasHeld = presses.values.any { it.held }
|
||||
presses.values.forEach { handler.removeCallbacks(it.hold) }
|
||||
cancelled.addAll(presses.keys)
|
||||
presses.clear()
|
||||
if (wasHeld) setPressed(false)
|
||||
}
|
||||
|
||||
fun onDeviceRemoved(device: Int) {
|
||||
cancelled.remove(device)
|
||||
val press = presses.remove(device) ?: return
|
||||
handler.removeCallbacks(press.hold)
|
||||
cancelTap()
|
||||
if (press.held && presses.values.none { it.held }) setPressed(false)
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import com.droiddeck.launcher.ui.focusGlide
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.view.Gravity
|
||||
@@ -104,6 +105,7 @@ class ControllerEditorActivity : ComponentActivity() {
|
||||
else -> Color.White.copy(alpha = 0.06f)
|
||||
},
|
||||
)
|
||||
.focusGlide(RoundedCornerShape(50))
|
||||
.then(
|
||||
if (selected == null) Modifier.clickable(onClick = onClick)
|
||||
else Modifier.toggleable(value = selected, role = Role.Switch, onValueChange = { onClick() }),
|
||||
|
||||
@@ -525,8 +525,8 @@ public class FakeInputWriter {
|
||||
}
|
||||
}
|
||||
|
||||
public static void setLowLatency(boolean controller, boolean touch) {
|
||||
int flags = (controller ? LATENCY_CONTROLLER : 0) | (touch ? LATENCY_TOUCH : 0);
|
||||
public static void setLowLatency(boolean enabled) {
|
||||
int flags = enabled ? LATENCY_CONTROLLER | LATENCY_TOUCH : 0;
|
||||
latency = flags;
|
||||
RingSlot ringSlot;
|
||||
synchronized (RING_LOCK) {
|
||||
|
||||
@@ -61,6 +61,7 @@ public final class PadBridge {
|
||||
private final PadState routedTouch = new PadState();
|
||||
private boolean systemGuidePressed;
|
||||
private boolean systemQamPressed;
|
||||
private boolean backQamPressed;
|
||||
private boolean qamChordActive;
|
||||
private int chordButton = -1;
|
||||
private boolean chordButtonPressed;
|
||||
@@ -132,6 +133,7 @@ public final class PadBridge {
|
||||
routedTouch.clear();
|
||||
systemGuidePressed = false;
|
||||
systemQamPressed = false;
|
||||
backQamPressed = false;
|
||||
qamTapPressed = false;
|
||||
qamChordActive = false;
|
||||
chordButtonPressed = false;
|
||||
@@ -165,6 +167,7 @@ public final class PadBridge {
|
||||
}
|
||||
systemGuidePressed = false;
|
||||
systemQamPressed = false;
|
||||
backQamPressed = false;
|
||||
qamChordActive = false;
|
||||
chordButtonPressed = false;
|
||||
qamTapPressed = false;
|
||||
@@ -459,6 +462,7 @@ public final class PadBridge {
|
||||
|
||||
public synchronized void releaseAll() {
|
||||
routedTouch.clear();
|
||||
backQamPressed = false;
|
||||
releaseBackPaddles();
|
||||
state.clear();
|
||||
publish();
|
||||
@@ -479,6 +483,17 @@ public final class PadBridge {
|
||||
return SessionState.getDeckPad() && FakeInputWriter.padHasQam();
|
||||
}
|
||||
|
||||
public boolean canHoldQam() {
|
||||
return builtinPad && nativeQam();
|
||||
}
|
||||
|
||||
public synchronized void setBackQamPressed(boolean pressed) {
|
||||
if (pressed && !canHoldQam()) return;
|
||||
if (backQamPressed == pressed) return;
|
||||
backQamPressed = pressed;
|
||||
publish();
|
||||
}
|
||||
|
||||
public synchronized void triggerQam() {
|
||||
if (!builtinPad) return;
|
||||
if (!nativeQam()) {
|
||||
@@ -684,7 +699,7 @@ public final class PadBridge {
|
||||
return;
|
||||
}
|
||||
boolean guide = systemGuidePressed || qamChordActive;
|
||||
boolean qam = nativeQam() && (systemQamPressed || qamTapPressed);
|
||||
boolean qam = nativeQam() && (systemQamPressed || qamTapPressed || backQamPressed);
|
||||
if (!guide && !qam) {
|
||||
writer.writePad(state);
|
||||
return;
|
||||
|
||||
@@ -17,45 +17,45 @@ object BattleNet {
|
||||
|
||||
const val PROGRAM = "/usr/local/bin/droiddeck-battlenet"
|
||||
|
||||
class Title(val uid: String, val name: String, val code: String, val steam: Int? = null, val shop: String? = null)
|
||||
class Title(val uid: String, val name: String, val code: String, val steam: Int? = null, val shop: String? = null, val product: String? = null)
|
||||
|
||||
internal val TITLES = listOf(
|
||||
Title("wow", "World of Warcraft", "WoW", shop = "world-of-warcraft-midnight"),
|
||||
Title("wow_classic", "World of Warcraft Classic", "WoWC", shop = "world-of-warcraft-burning-crusade-classic-anniversary-edition-upgrades"),
|
||||
Title("wow_classic_era", "World of Warcraft Classic", "WoWC"),
|
||||
Title("wow_classic_anniversary", "World of Warcraft Classic", "WoWC"),
|
||||
Title("diablo3", "Diablo III", "D3", shop = "diablo-iii"),
|
||||
Title("wow", "World of Warcraft", "WoW", shop = "world-of-warcraft-midnight", product = "wow"),
|
||||
Title("wow_classic", "World of Warcraft Classic", "WoWC", shop = "world-of-warcraft-burning-crusade-classic-anniversary-edition-upgrades", product = "wow_classic"),
|
||||
Title("wow_classic_era", "World of Warcraft Classic", "WoWC", product = "wow_classic_era"),
|
||||
Title("wow_classic_anniversary", "World of Warcraft Classic", "WoWC", product = "wow_anniversary"),
|
||||
Title("diablo3", "Diablo III", "D3", shop = "diablo-iii", product = "d3"),
|
||||
Title("d3cn", "Diablo III", "D3CN", shop = "diablo-iii"),
|
||||
Title("s2", "StarCraft II", "S2", shop = "starcraft-ii"),
|
||||
Title("s1", "StarCraft", "S1", shop = "starcraft-remastered"),
|
||||
Title("hs_beta", "Hearthstone", "WTCG", shop = "hearthstone"),
|
||||
Title("heroes", "Heroes of the Storm", "Hero", shop = "heroes-of-the-storm"),
|
||||
Title("prometheus", "Overwatch 2", "Pro", 2357570, shop = "overwatch"),
|
||||
Title("w3", "Warcraft III: Reforged", "W3", shop = "warcraft-3-reforged"),
|
||||
Title("viper", "Call of Duty: Black Ops 4", "VIPR", shop = "call-of-duty-black-ops-4"),
|
||||
Title("odin", "Call of Duty: Modern Warfare", "ODIN", 2000950, shop = "call-of-duty-modern-warfare"),
|
||||
Title("lazarus", "Call of Duty: Modern Warfare 2 Campaign Remastered", "LAZR", shop = "call-of-duty-modern-warfare-2-campaign-remastered"),
|
||||
Title("zeus", "Call of Duty: Black Ops Cold War", "ZEUS", shop = "call-of-duty-black-ops-cold-war"),
|
||||
Title("fore", "Call of Duty: Vanguard", "FORE", shop = "call-of-duty-vanguard"),
|
||||
Title("auks", "Call of Duty: Modern Warfare II", "AUKS", shop = "call-of-duty-modern-warfare-ii"),
|
||||
Title("pinta", "Call of Duty: Modern Warfare III", "PNTA", 2519060, shop = "call-of-duty-modern-warfare-iii"),
|
||||
Title("wlby", "Crash Bandicoot 4: It's About Time", "WLBY", 1378990, shop = "crash-bandicoot-4"),
|
||||
Title("osi", "Diablo II: Resurrected", "OSI"),
|
||||
Title("rtro", "Blizzard Arcade Collection", "RTRO", shop = "blizzard-arcade-collection"),
|
||||
Title("anbs", "Diablo Immortal", "ANBS", shop = "diablo-immortal"),
|
||||
Title("fenris", "Diablo IV", "Fen", 2344520, shop = "diablo-iv"),
|
||||
Title("fen", "Diablo IV", "Fen", 2344520, shop = "diablo-iv"),
|
||||
Title("d1", "Diablo", "D1", shop = "diablo"),
|
||||
Title("w1", "Warcraft: Orcs & Humans", "W1", shop = "warcraft-orcs-and-humans"),
|
||||
Title("w2", "Warcraft II: Battle.net Edition", "W2", shop = "warcraft-2-battle-net-edition"),
|
||||
Title("w1r", "Warcraft: Remastered", "W1R", shop = "warcraft-1-remastered"),
|
||||
Title("w2r", "Warcraft II: Remastered", "W2R", shop = "warcraft-2-remastered"),
|
||||
Title("gryphon", "Warcraft Rumble", "GRY", shop = "warcraft-rumble"),
|
||||
Title("aris", "Doom: The Dark Ages", "ARIS", 3017860, shop = "doom-the-dark-ages"),
|
||||
Title("scorpio", "Sea of Thieves", "SCOR", 1172620, shop = "sea-of-thieves"),
|
||||
Title("arkansas", "The Outer Worlds 2", "ARK", 1449110, shop = "the-outer-worlds-2"),
|
||||
Title("libra", "Tony Hawk's Pro Skater 3 + 4", "LBRA", 2545710),
|
||||
Title("aqua", "Avowed", "AQUA", 2457220, shop = "avowed"),
|
||||
Title("s2", "StarCraft II", "S2", shop = "starcraft-ii", product = "s2"),
|
||||
Title("s1", "StarCraft", "S1", shop = "starcraft-remastered", product = "s1"),
|
||||
Title("hs_beta", "Hearthstone", "WTCG", shop = "hearthstone", product = "hsb"),
|
||||
Title("heroes", "Heroes of the Storm", "Hero", shop = "heroes-of-the-storm", product = "hero"),
|
||||
Title("prometheus", "Overwatch 2", "Pro", 2357570, shop = "overwatch", product = "pro"),
|
||||
Title("w3", "Warcraft III: Reforged", "W3", shop = "warcraft-3-reforged", product = "w3"),
|
||||
Title("viper", "Call of Duty: Black Ops 4", "VIPR", shop = "call-of-duty-black-ops-4", product = "viper"),
|
||||
Title("odin", "Call of Duty: Modern Warfare", "ODIN", 2000950, shop = "call-of-duty-modern-warfare", product = "odin"),
|
||||
Title("lazarus", "Call of Duty: Modern Warfare 2 Campaign Remastered", "LAZR", shop = "call-of-duty-modern-warfare-2-campaign-remastered", product = "lazr"),
|
||||
Title("zeus", "Call of Duty: Black Ops Cold War", "ZEUS", shop = "call-of-duty-black-ops-cold-war", product = "zeus"),
|
||||
Title("fore", "Call of Duty: Vanguard", "FORE", shop = "call-of-duty-vanguard", product = "fore"),
|
||||
Title("auks", "Call of Duty: Modern Warfare II", "AUKS", shop = "call-of-duty-modern-warfare-ii", product = "auks"),
|
||||
Title("pinta", "Call of Duty: Modern Warfare III", "PNTA", 2519060, shop = "call-of-duty-modern-warfare-iii", product = "pinta"),
|
||||
Title("wlby", "Crash Bandicoot 4: It's About Time", "WLBY", 1378990, shop = "crash-bandicoot-4", product = "wlby"),
|
||||
Title("osi", "Diablo II: Resurrected", "OSI", product = "osi"),
|
||||
Title("rtro", "Blizzard Arcade Collection", "RTRO", shop = "blizzard-arcade-collection", product = "rtro"),
|
||||
Title("anbs", "Diablo Immortal", "ANBS", shop = "diablo-immortal", product = "anbs"),
|
||||
Title("fenris", "Diablo IV", "Fen", 2344520, shop = "diablo-iv", product = "fenris"),
|
||||
Title("fen", "Diablo IV", "Fen", 2344520, shop = "diablo-iv", product = "fenris"),
|
||||
Title("d1", "Diablo", "D1", shop = "diablo", product = "drtl"),
|
||||
Title("w1", "Warcraft: Orcs & Humans", "W1", shop = "warcraft-orcs-and-humans", product = "war1"),
|
||||
Title("w2", "Warcraft II: Battle.net Edition", "W2", shop = "warcraft-2-battle-net-edition", product = "w2bn"),
|
||||
Title("w1r", "Warcraft: Remastered", "W1R", shop = "warcraft-1-remastered", product = "w1r"),
|
||||
Title("w2r", "Warcraft II: Remastered", "W2R", shop = "warcraft-2-remastered", product = "w2r"),
|
||||
Title("gryphon", "Warcraft Rumble", "GRY", shop = "warcraft-rumble", product = "gryphon"),
|
||||
Title("aris", "Doom: The Dark Ages", "ARIS", 3017860, shop = "doom-the-dark-ages", product = "aris"),
|
||||
Title("scorpio", "Sea of Thieves", "SCOR", 1172620, shop = "sea-of-thieves", product = "scor"),
|
||||
Title("arkansas", "The Outer Worlds 2", "ARK", 1449110, shop = "the-outer-worlds-2", product = "ark"),
|
||||
Title("libra", "Tony Hawk's Pro Skater 3 + 4", "LBRA", 2545710, product = "lbra"),
|
||||
Title("aqua", "Avowed", "AQUA", 2457220, shop = "avowed", product = "aqua"),
|
||||
)
|
||||
|
||||
val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" }
|
||||
@@ -104,7 +104,7 @@ object BattleNet {
|
||||
|
||||
private val NOT_GAMES = setOf("agent", "bna", "battle.net")
|
||||
|
||||
class Game(val uid: String, val name: String, val code: String, val folder: File) {
|
||||
class Game(val uid: String, val name: String, val code: String, val folder: File, val installUid: String = uid) {
|
||||
val title: Title get() = title(uid) ?: Title(uid, name, code)
|
||||
}
|
||||
|
||||
@@ -161,8 +161,10 @@ object BattleNet {
|
||||
|
||||
fun games(context: Context): List<Game> {
|
||||
val pfx = File(prefix(context), "pfx")
|
||||
val entries = runCatching { File(pfx, "system.reg").useLines { uninstallEntries(it) } }.getOrDefault(emptyList()) +
|
||||
runCatching { productDbEntries(File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").readBytes()) }.getOrDefault(emptyList())
|
||||
val entries = installs(
|
||||
runCatching { File(pfx, "system.reg").useLines { uninstallEntries(it) } }.getOrDefault(emptyList()),
|
||||
runCatching { productDbEntries(File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").readBytes()) }.getOrNull(),
|
||||
)
|
||||
val found = LinkedHashMap<String, Game>()
|
||||
for ((uid, path) in entries) {
|
||||
val title = title(uid)
|
||||
@@ -172,11 +174,17 @@ object BattleNet {
|
||||
}
|
||||
if (title.code in found) continue
|
||||
val folder = hostFolder(context, path)?.takeIf { it.isDirectory } ?: continue
|
||||
found[title.code] = Game(title.uid, title.name, title.code, folder)
|
||||
found[title.code] = Game(title.uid, title.name, title.code, folder, uid)
|
||||
}
|
||||
return found.values.toList()
|
||||
}
|
||||
|
||||
internal fun installs(registry: List<Pair<String, String>>, agent: List<Pair<String, String>>?): List<Pair<String, String>> {
|
||||
if (agent == null) return registry
|
||||
val tracked = agent.map { it.first.lowercase() }.toSet()
|
||||
return registry.filter { it.first.lowercase() in tracked } + agent
|
||||
}
|
||||
|
||||
internal fun hostFolder(context: Context, path: String): File? {
|
||||
val drive = Regex("""^([CcZz]):[\\/](.*)$""").matchEntire(path.trim()) ?: return null
|
||||
val relative = drive.groupValues[2].replace('\\', '/').trim('/')
|
||||
@@ -242,9 +250,9 @@ object BattleNet {
|
||||
return out.toString()
|
||||
}
|
||||
|
||||
internal fun productDbEntries(bytes: ByteArray): List<Pair<String, String>> {
|
||||
val installs = runCatching { fields(bytes, 0, bytes.size) }.getOrDefault(emptyList()).filter { it.first == 1 }
|
||||
return installs.mapNotNull { (_, start, end) ->
|
||||
internal fun productDbEntries(bytes: ByteArray): List<Pair<String, String>>? {
|
||||
val installs = runCatching { fields(bytes, 0, bytes.size) }.getOrNull()?.filter { it.first == 1 }?.takeIf { it.isNotEmpty() } ?: return null
|
||||
return installs.map { (_, start, end) ->
|
||||
runCatching {
|
||||
val install = fields(bytes, start, end)
|
||||
val uid = install.firstOrNull { it.first == 1 }?.let { String(bytes, it.second, it.third - it.second) }
|
||||
@@ -253,8 +261,8 @@ object BattleNet {
|
||||
val installed = install.firstOrNull { it.first == 4 }?.let { s -> fields(bytes, s.second, s.third).firstOrNull { it.first == 1 } }
|
||||
?.let { s -> varints(bytes, s.second, s.third)[1] }
|
||||
if (uid.isNullOrEmpty() || path.isNullOrEmpty() || installed == 0L) null else uid to path
|
||||
}.getOrNull()
|
||||
}
|
||||
}.getOrElse { return null }
|
||||
}.filterNotNull()
|
||||
}
|
||||
|
||||
private fun fields(bytes: ByteArray, from: Int, to: Int): List<Triple<Int, Int, Int>> = walk(bytes, from, to) { _, _ -> }
|
||||
|
||||
@@ -179,15 +179,6 @@ 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) } }
|
||||
val runtimeDriver = com.droiddeck.launcher.session.SessionState.runtimeDriver
|
||||
if (com.droiddeck.launcher.gpu.QualcommSystemDriver.handles(runtimeDriver)) {
|
||||
val driver = com.droiddeck.launcher.gpu.QualcommSystemDriver
|
||||
val variables = ArrayList<String>()
|
||||
driver.addEnvironment(context, variables, runtimeDriver!!)
|
||||
for (entry in variables) env.putIfAbsent(entry.substringBefore('='), entry.substringAfter('='))
|
||||
for (path in driver.mounts(context, runtimeDriver) + File(context.filesDir, "qualcomm-system").path)
|
||||
addBind(Bind.parse(path))
|
||||
}
|
||||
if (binds.any { it.guest == "/dev" }) gpu(rootfs, root, env)?.forEach { addBind(it) }
|
||||
preload(session, rootfs, env).forEach { addBind(it) }
|
||||
zypakShims(binds, root, dir).forEach { addBind(it) }
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.database.ContentObserver
|
||||
import android.media.AudioManager
|
||||
import android.net.Uri
|
||||
import android.os.FileObserver
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import com.droiddeck.launcher.R
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.StandardCopyOption
|
||||
import org.json.JSONObject
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
class DeviceControlsComponent(context: Context, root: File, private val activityVisible: () -> Boolean = { false }) : SessionPart() {
|
||||
private val context = context.applicationContext
|
||||
private val audio = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
||||
private val directory = directory(root)
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private var running = false
|
||||
private var pendingBrightness: Float? = null
|
||||
private var permissionRequestAt = -5_000L
|
||||
private var previous = ""
|
||||
private var revision = 0L
|
||||
init { prepareBacklight(context, root) }
|
||||
private val observer = object : ContentObserver(handler) {
|
||||
override fun onChange(selfChange: Boolean) { if (running) publish() }
|
||||
}
|
||||
private val requests = object : FileObserver(directory.path, CLOSE_WRITE or MOVED_TO) {
|
||||
override fun onEvent(event: Int, path: String?) {
|
||||
if (path in REQUESTS) handler.post { if (running) consume() }
|
||||
}
|
||||
}
|
||||
private val refresh = object : Runnable {
|
||||
override fun run() {
|
||||
if (!running) return
|
||||
consume()
|
||||
pendingBrightness?.let { value ->
|
||||
if (Settings.System.canWrite(context)) {
|
||||
pendingBrightness = null
|
||||
context.getSystemService(NotificationManager::class.java).cancel(PERMISSION_NOTIFICATION)
|
||||
brightness(value)
|
||||
}
|
||||
}
|
||||
publish()
|
||||
handler.postDelayed(this, 250)
|
||||
}
|
||||
}
|
||||
|
||||
fun publish(force: Boolean = false) {
|
||||
try {
|
||||
directory.mkdirs()
|
||||
val level = audio.getStreamVolume(AudioManager.STREAM_MUSIC)
|
||||
val maximum = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC).coerceAtLeast(1)
|
||||
val muted = audio.isStreamMute(AudioManager.STREAM_MUSIC)
|
||||
write("volume.state", "$level $maximum ${if (muted) 1 else 0}\n")
|
||||
val value = Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 128)
|
||||
write("backlight/droiddeck/brightness", "$value\n")
|
||||
write("backlight/droiddeck/actual_brightness", "$value\n")
|
||||
val state = JSONObject().put("brightness", (value.coerceIn(1, 255) - 1) / 254.0)
|
||||
.put("brightnessWritable", Settings.System.canWrite(context)).toString()
|
||||
if (force || state != previous) {
|
||||
write("state.json", JSONObject(state).put("revision", ++revision).toString())
|
||||
previous = state
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not publish Android controls", e)
|
||||
}
|
||||
}
|
||||
|
||||
override fun start() {
|
||||
handler.post {
|
||||
REQUESTS.forEach {
|
||||
File(directory, it).delete()
|
||||
File(directory, "$it.processing").delete()
|
||||
}
|
||||
running = true
|
||||
context.contentResolver.registerContentObserver(Settings.System.CONTENT_URI, true, observer)
|
||||
requests.startWatching()
|
||||
refresh.run()
|
||||
}
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
handler.post {
|
||||
running = false
|
||||
handler.removeCallbacks(refresh)
|
||||
requests.stopWatching()
|
||||
context.contentResolver.unregisterContentObserver(observer)
|
||||
pendingBrightness = null
|
||||
context.getSystemService(NotificationManager::class.java).cancel(PERMISSION_NOTIFICATION)
|
||||
}
|
||||
}
|
||||
|
||||
private fun consume() {
|
||||
for (name in REQUESTS) {
|
||||
val file = File(directory, name)
|
||||
if (!file.isFile) continue
|
||||
val claimed = File(directory, "$name.processing")
|
||||
try {
|
||||
Files.move(file.toPath(), claimed.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
|
||||
if (claimed.length() > 64) continue
|
||||
val text = claimed.readText().trim()
|
||||
when (name) {
|
||||
"brightness.request" -> text.toFloatOrNull()?.takeIf { it.isFinite() && it in 0f..1f }?.let(::brightness)
|
||||
"volume.request" -> text.toIntOrNull()?.let {
|
||||
audio.setStreamVolume(AudioManager.STREAM_MUSIC,
|
||||
it.coerceIn(0, audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC)), 0)
|
||||
}
|
||||
"mute.request" -> if (text == "0" || text == "1") {
|
||||
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
|
||||
if (text == "1") AudioManager.ADJUST_MUTE else AudioManager.ADJUST_UNMUTE, 0)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not apply $name", e)
|
||||
} finally {
|
||||
publish(force = true)
|
||||
claimed.delete()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun brightness(value: Float) {
|
||||
if (!Settings.System.canWrite(context)) {
|
||||
pendingBrightness = value
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
if (now - permissionRequestAt >= 5_000) {
|
||||
permissionRequestAt = now
|
||||
try {
|
||||
val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
|
||||
Uri.parse("package:${context.packageName}")).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
val manager = context.getSystemService(NotificationManager::class.java)
|
||||
manager.createNotificationChannel(NotificationChannel(PERMISSION_CHANNEL,
|
||||
context.getString(R.string.brightness_permission_title), NotificationManager.IMPORTANCE_DEFAULT))
|
||||
val action = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE)
|
||||
manager.notify(PERMISSION_NOTIFICATION, Notification.Builder(context, PERMISSION_CHANNEL)
|
||||
.setSmallIcon(R.drawable.ic_stat_session)
|
||||
.setContentTitle(context.getString(R.string.brightness_permission_title))
|
||||
.setContentText(context.getString(R.string.brightness_permission_text))
|
||||
.setContentIntent(action).setOnlyAlertOnce(true).setAutoCancel(true).build())
|
||||
if (activityVisible()) context.startActivity(intent)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not open brightness permission", e)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
val level = 1 + (value * 254).roundToInt()
|
||||
try {
|
||||
Settings.System.putInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE,
|
||||
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL)
|
||||
Settings.System.putInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, level)
|
||||
} catch (e: SecurityException) {
|
||||
Log.w(TAG, "Brightness permission was revoked", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun write(name: String, text: String) {
|
||||
val file = File(directory, name)
|
||||
if (file.isFile && file.readText() == text) return
|
||||
val staged = File(directory, "$name.tmp")
|
||||
staged.writeText(text)
|
||||
Files.move(staged.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "DeviceControls"
|
||||
private const val PERMISSION_CHANNEL = "brightness_permission"
|
||||
private const val PERMISSION_NOTIFICATION = 0x4442
|
||||
private val REQUESTS = setOf("brightness.request", "volume.request", "mute.request")
|
||||
@JvmStatic fun directory(root: File) = File(root, "etc/droiddeck-device-controls")
|
||||
@JvmStatic fun prepareBacklight(context: Context, root: File): File {
|
||||
val base = File(directory(root), "backlight")
|
||||
val panel = File(base, "droiddeck").apply { mkdirs() }
|
||||
val value = Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 128)
|
||||
for ((name, text) in mapOf("type" to "raw", "max_brightness" to "255", "brightness" to "$value",
|
||||
"actual_brightness" to "$value", "bl_power" to "0", "scale" to "linear")) {
|
||||
File(panel, name).writeText("$text\n")
|
||||
}
|
||||
return base
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -63,15 +63,48 @@ public final class LinuxRuntime {
|
||||
}
|
||||
|
||||
private static final String HOST_DIR = "opt/android-host";
|
||||
/** The downloaded add-on pack. The APK does not ship this binary. */
|
||||
public static final String PROOT_PACK = "add-on pack";
|
||||
/** Termux's unpatched proot inside the rootfs. Developer switch only. */
|
||||
public static final String PROOT_ROOTFS = "rootfs fallback";
|
||||
public static final String PROOT_MISSING = "missing";
|
||||
|
||||
private static File rootfsProot(Context context) {
|
||||
return new File(rootDir(context), HOST_DIR + "/proot");
|
||||
}
|
||||
|
||||
private static File rootfsLoader(Context context) {
|
||||
return new File(rootDir(context), HOST_DIR + "/loader");
|
||||
}
|
||||
|
||||
private static boolean rootfsProotReady(Context context) {
|
||||
return rootfsProot(context).isFile() && rootfsLoader(context).isFile();
|
||||
}
|
||||
|
||||
/** Patched proot is the add-on pack. The rootfs copy is not that binary. */
|
||||
public static boolean patchedProot(Context context) {
|
||||
return AddonPack.PROOT.installed(context);
|
||||
}
|
||||
|
||||
public static File prootBinary(Context context) {
|
||||
if (AddonPack.PROOT.installed(context)) return AddonPack.PROOT.file(context, "libproot.so");
|
||||
return new File(rootDir(context), HOST_DIR + "/proot");
|
||||
if (SessionPrefs.allowStockProot(context)) return rootfsProot(context);
|
||||
return AddonPack.PROOT.file(context, "libproot.so");
|
||||
}
|
||||
|
||||
public static File prootLoader(Context context) {
|
||||
if (AddonPack.PROOT.installed(context)) return AddonPack.PROOT.file(context, "libproot-loader.so");
|
||||
return new File(rootDir(context), HOST_DIR + "/loader");
|
||||
if (SessionPrefs.allowStockProot(context)) return rootfsLoader(context);
|
||||
return AddonPack.PROOT.file(context, "libproot-loader.so");
|
||||
}
|
||||
|
||||
/** Where {@link #prootBinary} came from: {@link #PROOT_PACK}, {@link #PROOT_ROOTFS} or {@link #PROOT_MISSING}. */
|
||||
public static String prootSource(Context context) {
|
||||
File bin = prootBinary(context);
|
||||
if (!bin.isFile()) return PROOT_MISSING;
|
||||
if (AddonPack.PROOT.installed(context)
|
||||
&& bin.getPath().equals(AddonPack.PROOT.file(context, "libproot.so").getPath())) return PROOT_PACK;
|
||||
return PROOT_ROOTFS;
|
||||
}
|
||||
|
||||
public static String prootLibraryPath(Context context) {
|
||||
@@ -85,8 +118,7 @@ public final class LinuxRuntime {
|
||||
return new File(root, "usr/bin/gamescope").isFile()
|
||||
&& (new File(root, SESSION_SCRIPT.substring(1)).isFile()
|
||||
|| new File(root, LegacyNames.SESSION_SCRIPT.substring(1)).isFile())
|
||||
&& prootBinary(context).isFile()
|
||||
&& prootLoader(context).isFile();
|
||||
&& (patchedProot(context) || rootfsProotReady(context));
|
||||
}
|
||||
|
||||
public static File vulkanIcd(Context context) {
|
||||
@@ -160,10 +192,7 @@ public final class LinuxRuntime {
|
||||
bind(cmd, "/dev");
|
||||
bind(cmd, "/proc");
|
||||
bind(cmd, "/sys");
|
||||
if (com.droiddeck.launcher.gpu.QualcommSystemDriver.selected(context)) {
|
||||
for (String path : com.droiddeck.launcher.gpu.QualcommSystemDriver.mounts(context,
|
||||
SessionPrefs.INSTANCE.linuxDriver(context))) bind(cmd, path);
|
||||
}
|
||||
bind(cmd, DeviceControlsComponent.prepareBacklight(context, root).getPath() + ":/sys/class/backlight");
|
||||
bind(cmd, "/dev/urandom:/dev/random");
|
||||
bind(cmd, "/proc/self/fd:/dev/fd");
|
||||
bind(cmd, "/proc/self/fd/0:/dev/stdin");
|
||||
|
||||
@@ -6,6 +6,7 @@ import android.util.Log;
|
||||
|
||||
|
||||
import com.droiddeck.launcher.R;
|
||||
import com.droiddeck.launcher.session.SessionPrefs;
|
||||
import com.droiddeck.launcher.core.ArchivePaths;
|
||||
import com.droiddeck.launcher.core.Downloader;
|
||||
import com.droiddeck.launcher.core.Hashes;
|
||||
@@ -262,7 +263,9 @@ public final class LinuxRuntimeInstaller {
|
||||
emptyTrash(LinuxRuntime.rootDir(context).getParentFile());
|
||||
String downloading = context.getString(R.string.rtinst_downloading);
|
||||
if (listener != null) listener.onProgress(Step.DOWNLOADING, downloading, 0);
|
||||
if (!AddonPack.PROOT.await(context)) throw new IOException("Cannot download proot");
|
||||
if (!LinuxRuntime.patchedProot(context) && !AddonPack.PROOT.await(context)
|
||||
&& !SessionPrefs.allowStockProot(context))
|
||||
throw new IOException("Cannot download proot");
|
||||
if (!AddonPack.DIRECTAUDIO.await(context)) throw new IOException("Cannot download DirectAudio");
|
||||
boolean ok = Downloader.downloadFile(release.url, archive, true, release.sha256, (fraction) -> {
|
||||
if (listener != null) {
|
||||
|
||||
@@ -1,18 +1,32 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.core.AddonPack
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
|
||||
object ProotFastPath {
|
||||
private const val TAG = "ProotFastPath"
|
||||
const val LIBRARY = "/usr/local/lib/libblfastpath.so"
|
||||
const val MAX_BINDS = 256
|
||||
|
||||
fun enabled(context: Context): Boolean =
|
||||
SessionPrefs.prootFastPath(context) && !SessionPrefs.prootNoSeccomp(context) &&
|
||||
LinuxRuntime.prootBinary(context).parentFile == AddonPack.PROOT.dir(context)
|
||||
/**
|
||||
* The fast path's trampoline is let through only by the proot built with patches/0014.
|
||||
* The rootfs copy (Termux's stock proot) is not that binary, so the library stays out.
|
||||
*/
|
||||
fun allows(preference: Boolean, noSeccomp: Boolean, source: String): Boolean =
|
||||
preference && !noSeccomp && source == LinuxRuntime.PROOT_PACK
|
||||
|
||||
fun enabled(context: Context): Boolean {
|
||||
val preference = SessionPrefs.prootFastPath(context)
|
||||
val noSeccomp = SessionPrefs.prootNoSeccomp(context)
|
||||
val source = LinuxRuntime.prootSource(context)
|
||||
val on = allows(preference, noSeccomp, source)
|
||||
if (preference && !noSeccomp && !on)
|
||||
Log.i(TAG, "proot: fast path off - binary is $source, not the patched proot")
|
||||
return on
|
||||
}
|
||||
|
||||
fun key(root: File, binds: List<String>): String? {
|
||||
if (binds.size > MAX_BINDS || binds.any { it.contains('|') } || root.path.contains('|')) return null
|
||||
|
||||
@@ -8,7 +8,7 @@ import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* The FEX build DroidDeck-Components' fex.json names for the x86-64 client. A session uses the last copy read.
|
||||
* The FEX build DroidDeck-Components' fex.json names for x86 programs. A session uses the last copy read.
|
||||
* Components' build-fex.yml replaces the archive on its single `fex` release and records the build's version;
|
||||
* a release per build (fex-2610-r5) is still read.
|
||||
*/
|
||||
@@ -62,7 +62,7 @@ object FexCatalog {
|
||||
return build
|
||||
}
|
||||
|
||||
/** For droiddeck-steam-x64: the build and every source its archive may come from (it checks the sha256). */
|
||||
/** For droiddeck-fex-update: the build and every source its archive may come from (it checks the sha256). */
|
||||
fun environment(build: Build, sources: List<String> = DownloadSource.candidates(build.url)): List<String> = listOf(
|
||||
"BL_FEX_TAG=${build.tag}",
|
||||
"BL_FEX_SHA256=${build.sha256}",
|
||||
|
||||
@@ -18,7 +18,6 @@ import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
class PerfHud(context: Context) {
|
||||
var text by mutableStateOf("")
|
||||
@@ -32,9 +31,9 @@ class PerfHud(context: Context) {
|
||||
private var lastFps = 0f
|
||||
private var running = false
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val intervals = FloatArray(GRAPH)
|
||||
private val graphWrite = AtomicInteger()
|
||||
private val lastFrameNs = AtomicLong()
|
||||
private val samples = FloatArray(GRAPH)
|
||||
private var graphBase = 0L
|
||||
private var graphSeen = 0L
|
||||
|
||||
@Volatile private var showFps = true
|
||||
@Volatile private var showBattery = true
|
||||
@@ -59,14 +58,6 @@ class PerfHud(context: Context) {
|
||||
}
|
||||
override fun onGameFrame() {
|
||||
frames.incrementAndGet()
|
||||
if (!showGraph) return
|
||||
val now = System.nanoTime()
|
||||
val previous = lastFrameNs.getAndSet(now)
|
||||
if (previous == 0L) return
|
||||
val ms = ((now - previous) / 1_000_000f).coerceIn(0f, 50f)
|
||||
val slot = graphWrite.get()
|
||||
intervals[slot and (GRAPH - 1)] = ms
|
||||
graphWrite.compareAndSet(slot, slot + 1)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,9 +91,9 @@ class PerfHud(context: Context) {
|
||||
if (!enabled || !anyPart || running) return
|
||||
running = true
|
||||
lastTick = SystemClock.elapsedRealtime()
|
||||
lastFrameNs.set(0L)
|
||||
frames.set(0)
|
||||
graphWrite.set(0)
|
||||
graphBase = shownTotal()
|
||||
graphSeen = graphBase
|
||||
WaylandCompositor.setGameListener(listener)
|
||||
handler.postDelayed(tick, TICK_MS)
|
||||
}
|
||||
@@ -135,23 +126,19 @@ class PerfHud(context: Context) {
|
||||
return sticky.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0)
|
||||
}
|
||||
|
||||
private fun shownTotal(): Long = try { WaylandCompositor.nativeHudFrameTimes(samples) } catch (t: Throwable) { 0L }
|
||||
|
||||
private fun clearGraph() {
|
||||
lastFrameNs.set(0L)
|
||||
graphWrite.set(0)
|
||||
graphBase = shownTotal()
|
||||
graphSeen = graphBase
|
||||
if (graph.isNotEmpty()) graph = FloatArray(0)
|
||||
}
|
||||
|
||||
private fun publishGraph() {
|
||||
val count = graphWrite.get()
|
||||
val shown = minOf(count, GRAPH)
|
||||
if (shown < 2) {
|
||||
graph = FloatArray(0)
|
||||
return
|
||||
}
|
||||
val out = FloatArray(shown)
|
||||
val start = count - shown
|
||||
for (i in 0 until shown) out[i] = intervals[(start + i) and (GRAPH - 1)]
|
||||
graph = out
|
||||
val total = shownTotal()
|
||||
if (total == graphSeen && graph.isNotEmpty()) return
|
||||
graphSeen = total
|
||||
graph = recent(samples, total, graphBase)
|
||||
}
|
||||
|
||||
private fun line(base: Float): String {
|
||||
@@ -176,6 +163,14 @@ class PerfHud(context: Context) {
|
||||
companion object {
|
||||
private const val TICK_MS = 1_000L
|
||||
private const val GRAPH = 128
|
||||
internal const val GRAPH_MAX_MS = 50f
|
||||
|
||||
internal fun recent(samples: FloatArray, total: Long, base: Long): FloatArray {
|
||||
val filled = minOf(total, samples.size.toLong()).toInt()
|
||||
val shown = minOf(filled.toLong(), (total - base).coerceAtLeast(0L)).toInt()
|
||||
if (shown < 2) return FloatArray(0)
|
||||
return FloatArray(shown) { samples[filled - shown + it].coerceIn(0f, GRAPH_MAX_MS) }
|
||||
}
|
||||
|
||||
internal fun batteryCelsius(deci: Int): String? =
|
||||
if (deci <= 0) null else String.format(Locale.US, "%.1f°C", deci / 10f)
|
||||
|
||||
@@ -17,12 +17,13 @@ object SessionDisplay {
|
||||
fun screenSize(panel: Pair<Int, Int>): Pair<Int, Int> =
|
||||
(maxOf(panel.first, panel.second) and 1.inv()) to (minOf(panel.first, panel.second) and 1.inv())
|
||||
|
||||
fun resolveChoice(panel: Pair<Int, Int>, choice: String): Pair<Int, Int> {
|
||||
if (choice == MATCH_SCREEN || choice == FOLLOW_SCREEN) return screenSize(panel)
|
||||
presetHeight(choice)?.let { return resolve(panel, it, SessionPrefs.SHAPE_AUTO) }
|
||||
fun resolveChoice(panel: Pair<Int, Int>, choice: String, portrait: Boolean = false): Pair<Int, Int> {
|
||||
fun orient(size: Pair<Int, Int>) = if (portrait) size.second to size.first else size
|
||||
if (choice == MATCH_SCREEN || choice == FOLLOW_SCREEN) return orient(screenSize(panel))
|
||||
presetHeight(choice)?.let { return orient(resolve(panel, it, SessionPrefs.SHAPE_AUTO)) }
|
||||
val parts = choice.split('x').map { it.toIntOrNull() }
|
||||
return if (parts.size == 2 && parts.all { it != null && it > 0 }) parts[0]!! to parts[1]!!
|
||||
else resolve(panel, 720, SessionPrefs.SHAPE_AUTO)
|
||||
else orient(resolve(panel, 720, SessionPrefs.SHAPE_AUTO))
|
||||
}
|
||||
|
||||
fun resolutionOptions(panel: Pair<Int, Int>): List<String> {
|
||||
@@ -31,8 +32,10 @@ object SessionDisplay {
|
||||
.filter { resolveChoice(panel, it) != screenSize(panel) } + MATCH_SCREEN + FOLLOW_SCREEN
|
||||
}
|
||||
|
||||
fun followSize(width: Int, height: Int): Pair<Int, Int>? =
|
||||
if (minOf(width, height) < FOLLOW_MIN_SIDE) null else (width and 1.inv()) to (height and 1.inv())
|
||||
fun followSize(width: Int, height: Int, controlsBelow: Boolean = false): Pair<Int, Int>? =
|
||||
if (width <= 0 || height <= 0 ||
|
||||
(if (controlsBelow) width else minOf(width, height)) < FOLLOW_MIN_SIDE) null
|
||||
else (width and 1.inv()) to (height and 1.inv())
|
||||
|
||||
const val UNFOLDED_MAX_GAME_SHARE = 0.8f
|
||||
|
||||
@@ -49,13 +52,14 @@ object SessionDisplay {
|
||||
foldable: Boolean,
|
||||
controllerConnected: Boolean,
|
||||
keepWithController: Boolean,
|
||||
steamDeckPad: Boolean,
|
||||
gamepadAvailable: Boolean,
|
||||
pip: Boolean,
|
||||
width: Int,
|
||||
height: Int,
|
||||
smallestWidthDp: Int,
|
||||
): Boolean = enabled && foldable && (keepWithController || !controllerConnected) && steamDeckPad &&
|
||||
!pip && width > 0 && height > 0 && smallestWidthDp >= UNFOLDED_MIN_DP
|
||||
): Boolean = enabled && (keepWithController || !controllerConnected) && gamepadAvailable &&
|
||||
!pip && width > 0 && height > 0 &&
|
||||
(height > width || (foldable && smallestWidthDp >= UNFOLDED_MIN_DP))
|
||||
|
||||
|
||||
fun panelSize(context: Context): Pair<Int, Int> {
|
||||
|
||||
@@ -56,9 +56,6 @@ object SessionFiles {
|
||||
"usr/local/bin/droiddeck-desktop-clipboard" to "usr/local/bin/droiddeck-desktop-clipboard",
|
||||
"usr/local/bin/droiddeck-gpu-window" to "usr/local/bin/droiddeck-gpu-window",
|
||||
"usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install",
|
||||
"usr/local/bin/droiddeck-steam-taskset" to "usr/local/bin/droiddeck-steam-taskset",
|
||||
"usr/local/bin/droiddeck-steam-taskset" to "usr/local/libexec/droiddeck-steam/taskset",
|
||||
"usr/local/bin/droiddeck-qualcomm-caps" to "usr/local/bin/droiddeck-qualcomm-caps",
|
||||
"usr/local/bin/droiddeck-steam-ui-scale" to "usr/local/bin/droiddeck-steam-ui-scale",
|
||||
"usr/local/bin/droiddeck-steam-language" to "usr/local/bin/droiddeck-steam-language",
|
||||
"usr/local/bin/droiddeck-steam-shaders" to "usr/local/bin/droiddeck-steam-shaders",
|
||||
@@ -84,6 +81,7 @@ object SessionFiles {
|
||||
"usr/local/bin/droiddeck-steam-games" to "usr/local/bin/droiddeck-steam-games",
|
||||
"usr/local/bin/droiddeck-pad-defaults" to "usr/local/bin/droiddeck-pad-defaults",
|
||||
"usr/local/bin/droiddeck-steam-x64" to "usr/local/bin/droiddeck-steam-x64",
|
||||
"usr/local/bin/droiddeck-fex-update" to "usr/local/bin/droiddeck-fex-update",
|
||||
"usr/local/bin/droiddeck-steamrt-shim" to "usr/local/bin/droiddeck-steamrt-shim",
|
||||
"usr/local/bin/droiddeck-x64-arm-proton" to "usr/local/bin/droiddeck-x64-arm-proton",
|
||||
"usr/local/bin/droiddeck-x64-arm-webhelper" to "usr/local/bin/droiddeck-x64-arm-webhelper",
|
||||
|
||||
@@ -9,6 +9,7 @@ import com.droiddeck.launcher.core.TextureFiltering
|
||||
import com.droiddeck.launcher.gpu.Cardboard
|
||||
import com.droiddeck.launcher.gpu.ScreenEffects
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
object SessionPrefs {
|
||||
data class GameTextureFiltering(val anisotropy: Int? = null, val lodBias: String? = null)
|
||||
@@ -43,6 +44,8 @@ object SessionPrefs {
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||
|
||||
val orientationOptions = listOf(
|
||||
ActivityInfo.SCREEN_ORIENTATION_USER to R.string.setup_launcher_orientation_auto,
|
||||
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT to R.string.setup_orientation_portrait,
|
||||
ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE to R.string.setup_orientation_auto,
|
||||
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE to R.string.setup_orientation_landscape,
|
||||
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE to R.string.setup_orientation_reverse,
|
||||
@@ -58,6 +61,17 @@ object SessionPrefs {
|
||||
prefs(context).edit().putInt("orientation", orientation).apply()
|
||||
}
|
||||
|
||||
fun windowOrientation(context: Context, followScreen: Boolean, smallestWidthDp: Int): Int =
|
||||
if (followScreen && smallestWidthDp >= SessionDisplay.UNFOLDED_MIN_DP && !prefs(context).contains("orientation"))
|
||||
ActivityInfo.SCREEN_ORIENTATION_USER else orientation(context)
|
||||
|
||||
fun portrait(context: Context): Boolean = when (orientation(context)) {
|
||||
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT -> true
|
||||
ActivityInfo.SCREEN_ORIENTATION_USER ->
|
||||
context.resources.configuration.orientation == android.content.res.Configuration.ORIENTATION_PORTRAIT
|
||||
else -> false
|
||||
}
|
||||
|
||||
fun launcherFullscreen(context: Context): Boolean = prefs(context).getBoolean("launcherFullscreen", true)
|
||||
|
||||
fun setLauncherFullscreen(context: Context, on: Boolean) {
|
||||
@@ -111,6 +125,12 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("storesView", if (view in STORES_VIEWS) view else STORES_VIEWS.first()).apply()
|
||||
}
|
||||
|
||||
fun libraryShowUninstalled(context: Context): Boolean = prefs(context).getBoolean("libraryShowUninstalled", false)
|
||||
|
||||
fun setLibraryShowUninstalled(context: Context, show: Boolean) {
|
||||
prefs(context).edit().putBoolean("libraryShowUninstalled", show).apply()
|
||||
}
|
||||
|
||||
fun storesTabOrder(context: Context): List<String> = idList(prefs(context).getString("storesTabOrder", null))
|
||||
|
||||
fun setStoresTabOrder(context: Context, order: List<String>) {
|
||||
@@ -223,16 +243,10 @@ object SessionPrefs {
|
||||
private fun mangoappSession(context: Context) =
|
||||
SessionState.mode == SessionService.MODE_STEAM && mangoapp(context)
|
||||
|
||||
fun lowLatencyController(context: Context): Boolean = prefs(context).getBoolean("lowLatencyController", false)
|
||||
fun lowLatency(context: Context): Boolean = prefs(context).getBoolean("lowLatency", true)
|
||||
|
||||
fun setLowLatencyController(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("lowLatencyController", on).apply()
|
||||
}
|
||||
|
||||
fun lowLatencyTouch(context: Context): Boolean = prefs(context).getBoolean("lowLatencyTouch", false)
|
||||
|
||||
fun setLowLatencyTouch(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("lowLatencyTouch", on).apply()
|
||||
fun setLowLatency(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("lowLatency", on).apply()
|
||||
}
|
||||
|
||||
fun backActionsInverted(context: Context): Boolean = prefs(context).getBoolean("backActionsInverted", false)
|
||||
@@ -527,6 +541,15 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("cursorComposite", on).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* The rootfs ships Termux's unpatched proot. A session uses it only when this file exists,
|
||||
* so a missing add-on pack cannot silently fall back to it.
|
||||
* Path: Android/data/<package>/files/droiddeck-stock-proot
|
||||
*/
|
||||
@JvmStatic
|
||||
fun allowStockProot(context: Context): Boolean =
|
||||
context.getExternalFilesDir(null)?.let { File(it, "droiddeck-stock-proot").isFile } == true
|
||||
|
||||
const val DEFAULT_GUEST_HOSTNAME = "DroidDeck"
|
||||
|
||||
@JvmStatic
|
||||
@@ -654,8 +677,10 @@ object SessionPrefs {
|
||||
parseResolution(value)?.let { return "${it.first}x${it.second}" }
|
||||
}
|
||||
if (!resolutionChosen(context, mode) && !saved.contains("shape")) return SessionDisplay.DEFAULT_RESOLUTION
|
||||
val legacy = SessionDisplay.resolve(panel, resolutionCap(context, mode), shapeMode(context), customResolution(context, mode))
|
||||
val custom = customResolution(context, mode)
|
||||
val legacy = SessionDisplay.resolve(panel, resolutionCap(context, mode), shapeMode(context), custom)
|
||||
return if (legacy == SessionDisplay.screenSize(panel)) SessionDisplay.MATCH_SCREEN
|
||||
else if (custom == null && legacy == SessionDisplay.resolve(panel, legacy.second, SHAPE_AUTO)) "${legacy.second}p"
|
||||
else "${legacy.first}x${legacy.second}"
|
||||
}
|
||||
|
||||
@@ -903,19 +928,8 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("hdr.$mode", on).apply()
|
||||
}
|
||||
|
||||
fun fpsLimit(context: Context, mode: String): Int = prefs(context).getInt("fpsLimit.$mode", 0).coerceAtLeast(0)
|
||||
|
||||
fun setFpsLimit(context: Context, mode: String, fps: Int) {
|
||||
prefs(context).edit().putInt("fpsLimit.$mode", fps.coerceAtLeast(0)).apply()
|
||||
}
|
||||
|
||||
val fpsLimitChoices = listOf(0 to "Off", 30 to "30", 40 to "40", 45 to "45", 60 to "60", 90 to "90", 120 to "120")
|
||||
|
||||
fun fpsLimitChoices(context: Context): List<Pair<Int, String>> =
|
||||
fpsLimitChoices.map { (fps, label) -> fps to if (fps == 0) context.getString(R.string.frame_gen_off) else label }
|
||||
|
||||
/**
|
||||
* Performance mode: without a frame limit, buffers go back to the game as soon as they are replaced
|
||||
* Performance mode: buffers go back to the game as soon as they are replaced
|
||||
* instead of once per refresh, and gamescope's WSI layer and winex11 reuse their per-present window checks.
|
||||
*/
|
||||
fun performanceMode(context: Context, mode: String): Boolean = prefs(context).getBoolean("performanceMode.$mode", false)
|
||||
@@ -927,8 +941,9 @@ object SessionPrefs {
|
||||
/** Compositor frame limit that releases buffers to the game unpaced. */
|
||||
const val FPS_UNPACED = -1
|
||||
|
||||
/** The limit handed to the compositor: Performance mode without a limit is unpaced, a chosen limit still paces. */
|
||||
fun compositorFpsLimit(limit: Int, performanceMode: Boolean): Int = if (performanceMode && limit <= 0) FPS_UNPACED else limit
|
||||
/** Mirroring still follows the glasses' refresh rate when Performance mode is on. */
|
||||
fun compositorFpsLimit(mirrorRefreshLimit: Int, performanceMode: Boolean): Int =
|
||||
if (performanceMode && mirrorRefreshLimit <= 0) FPS_UNPACED else mirrorRefreshLimit
|
||||
|
||||
val upscalerChoices = listOf(
|
||||
0 to "Linear", 2 to "Nearest", 4 to "AMD FSR 1", 3 to "Snapdragon GSR",
|
||||
@@ -1117,6 +1132,18 @@ object SessionPrefs {
|
||||
|
||||
fun unfoldedControls(context: Context): Boolean = prefs(context).getBoolean("unfoldedControls", false)
|
||||
|
||||
fun controlsBelowWanted(context: Context, mode: String, width: Int, height: Int, pip: Boolean = false): Boolean =
|
||||
SessionDisplay.unfoldedControlsWanted(
|
||||
enabled = unfoldedControls(context),
|
||||
foldable = SessionDisplay.foldable(context),
|
||||
controllerConnected = com.droiddeck.launcher.input.PadBridge.anyControllerConnected() ||
|
||||
com.droiddeck.launcher.input.SteamControllerBle.connected,
|
||||
keepWithController = unfoldedControlsWithController(context),
|
||||
gamepadAvailable = mode == SessionService.MODE_STEAM && builtinPad(context),
|
||||
pip = pip, width = width, height = height,
|
||||
smallestWidthDp = context.resources.configuration.smallestScreenWidthDp,
|
||||
)
|
||||
|
||||
fun setUnfoldedControls(context: Context, enabled: Boolean) {
|
||||
prefs(context).edit().putBoolean("unfoldedControls", enabled).apply()
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ import android.os.PowerManager
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.view.Display
|
||||
import android.util.Log
|
||||
import android.widget.Toast
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.SessionActivity
|
||||
import com.droiddeck.launcher.audio.DirectAudioRelayComponent
|
||||
@@ -378,15 +379,7 @@ class SessionService : Service() {
|
||||
Thread({
|
||||
OrphanReaper.reap("session starting")
|
||||
ProtonExtras.awaitReplacement(120_000)
|
||||
try {
|
||||
runSession(gen)
|
||||
} catch (e: com.droiddeck.launcher.gpu.QualcommSystemDriver.Unavailable) {
|
||||
Log.e(TAG, "runtime driver unavailable", e)
|
||||
if (gen == sessionGen) {
|
||||
SessionEvents.fail(FAILURE_RUNTIME_DRIVER, e.message.orEmpty())
|
||||
stopSession(-1)
|
||||
}
|
||||
}
|
||||
runSession(gen)
|
||||
}, "session-start").start()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
@@ -438,8 +431,30 @@ class SessionService : Service() {
|
||||
val sessionRoot = LinuxRuntime.sessionRoot(this).apply { mkdirs() }
|
||||
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
|
||||
killStragglers()
|
||||
for (pack in listOf(AddonPack.PROOT, AddonPack.DIRECTAUDIO))
|
||||
if (!pack.await(this, { gen == sessionGen && SessionState.running })) Log.w(TAG, "${pack.name} pack unavailable")
|
||||
val stillStarting = { gen == sessionGen && SessionState.running }
|
||||
val prootPack = LinuxRuntime.patchedProot(this) || AddonPack.PROOT.await(this, stillStarting)
|
||||
val directAudioPack = AddonPack.DIRECTAUDIO.await(this, stillStarting)
|
||||
if (!stillStarting()) {
|
||||
Log.i(TAG, "session stopped while add-on packs were downloading")
|
||||
return
|
||||
}
|
||||
if (!directAudioPack) {
|
||||
Log.w(TAG, "directaudio pack unavailable; game audio drivers will not be staged")
|
||||
mainHandler.post {
|
||||
Toast.makeText(this, R.string.session_directaudio_missing, Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
if (!LinuxRuntime.patchedProot(this)) {
|
||||
if (SessionPrefs.allowStockProot(this)) {
|
||||
Log.w(TAG, "proot: patched proot missing; droiddeck-stock-proot allows the rootfs copy")
|
||||
} else {
|
||||
val message = getString(R.string.session_proot_missing)
|
||||
Log.e(TAG, "$message (pack ready=$prootPack)")
|
||||
SessionEvents.fail("PROOT_MISSING", message, -1)
|
||||
stopSession(-1)
|
||||
return
|
||||
}
|
||||
}
|
||||
val agentEnvironment = runCatching { com.droiddeck.launcher.agent.AgentEnv.beginSession(this) }
|
||||
.onFailure { Log.w(TAG, "agent environment skipped", it) }
|
||||
.getOrDefault(emptyList())
|
||||
@@ -454,6 +469,10 @@ class SessionService : Service() {
|
||||
|
||||
val sessionDir = openSessionFolder()
|
||||
val sessionLog = File(sessionDir, "session.log")
|
||||
val prootLine = "== proot: ${LinuxRuntime.prootBinary(this).path} (${LinuxRuntime.prootSource(this)})"
|
||||
Log.i(TAG, prootLine)
|
||||
runCatching { sessionLog.appendText(prootLine + "\n") }
|
||||
.onFailure { Log.w(TAG, "could not write the proot line to ${sessionLog.path}", it) }
|
||||
|
||||
Log.i(TAG, GpuClockPin.start(this))
|
||||
Log.i(TAG, GameThreadHints.start(this))
|
||||
@@ -470,7 +489,7 @@ class SessionService : Service() {
|
||||
if (steamHere) guest.add("BL_EPIC_APP_ID=" + com.droiddeck.launcher.stores.epic.EpicClient.shortcutAppId)
|
||||
val fastPathAt = guest.size
|
||||
|
||||
val pulse = startAudio(guest, sessionDir)
|
||||
val pulse = startAudio(guest, sessionDir, directAudioPack)
|
||||
if (steamHere) {
|
||||
val encoder = VideoEncodeBridge(File(filesDir, "venc/venc.sock"))
|
||||
encoder.attach(this)
|
||||
@@ -480,23 +499,24 @@ class SessionService : Service() {
|
||||
|
||||
guest.add("BL_WIDTH=" + size.first)
|
||||
guest.add("BL_HEIGHT=" + size.second)
|
||||
if (SessionState.followScreen) guest.add("BL_FOLLOW_OUTPUT=1")
|
||||
if (SessionState.followScreen || size.first < size.second ||
|
||||
SessionPrefs.orientation(this) == android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
|
||||
guest.add("BL_FOLLOW_OUTPUT=1")
|
||||
if (SessionState.hdr) {
|
||||
guest.add("BL_HDR=1")
|
||||
guest.add("DXVK_HDR=1")
|
||||
Log.i(TAG, "hdr: gamescope --hdr-enabled, DXVK_HDR=1")
|
||||
}
|
||||
guest.add("BL_FPS=" + SessionState.fpsLimit)
|
||||
// gamescope's WSI layer and winex11 reuse their per-present window checks for this long; 0 checks on every present.
|
||||
val windowCheckMs = if (SessionState.performanceMode) 100 else 0
|
||||
guest.add("DROIDDECK_WSI_BYPASS_CHECK_MS=$windowCheckMs")
|
||||
guest.add("WINE_OFFSCREEN_CHECK_MS=$windowCheckMs")
|
||||
if (SessionPrefs.compositorFpsLimit(SessionState.fpsLimit, SessionState.performanceMode) == SessionPrefs.FPS_UNPACED) {
|
||||
if (SessionState.performanceMode) {
|
||||
// gamescope turns buffers around slower than an unpaced game draws; more images keep it drawing.
|
||||
guest.add("GAMESCOPE_WSI_MIN_IMAGE_COUNT=8")
|
||||
guest.add("GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT=1")
|
||||
}
|
||||
Log.i(TAG, "performance mode " + (if (SessionState.performanceMode) "on" else "off") + ", frame limit " + SessionState.fpsLimit)
|
||||
Log.i(TAG, "performance mode " + (if (SessionState.performanceMode) "on" else "off"))
|
||||
guest.add("BL_REFRESH=" + Math.round(SessionState.refreshHz))
|
||||
guest.add("BL_LOG=" + sessionLog.path)
|
||||
guest.add("BL_DEBUG_DIR=" + sessionDir.path)
|
||||
@@ -610,6 +630,10 @@ class SessionService : Service() {
|
||||
networkLink.attach(this)
|
||||
networkLink.publish()
|
||||
components.add(networkLink)
|
||||
val deviceControls = com.droiddeck.launcher.runtime.DeviceControlsComponent(this, root) { activityVisible && screenOn }
|
||||
deviceControls.attach(this)
|
||||
deviceControls.publish()
|
||||
components.add(deviceControls)
|
||||
if (gen != sessionGen || !SessionState.running) {
|
||||
Log.i(TAG, "session stopped while it was starting; not launching it")
|
||||
if (gen == sessionGen) components.clear()
|
||||
@@ -727,10 +751,8 @@ class SessionService : Service() {
|
||||
guest.add("MESA_LOADER_DRIVER_OVERRIDE=zink")
|
||||
guest.add("GALLIUM_DRIVER=zink")
|
||||
guest.add("LIBGL_KOPPER_DRI2=true")
|
||||
LinuxRuntime.vulkanIcd(this)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
|
||||
val linuxDriverId = SessionPrefs.linuxDriver(this)
|
||||
val systemQualcomm = com.droiddeck.launcher.gpu.QualcommSystemDriver.handles(linuxDriverId)
|
||||
if (systemQualcomm) com.droiddeck.launcher.gpu.QualcommSystemDriver.addEnvironment(this, guest)
|
||||
else LinuxRuntime.vulkanIcd(this)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
|
||||
SessionState.runtimeDriver = linuxDriverId
|
||||
com.droiddeck.launcher.gpu.AutoDriverTrial.sessionStarting(
|
||||
this,
|
||||
@@ -740,9 +762,9 @@ class SessionService : Service() {
|
||||
)
|
||||
LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)
|
||||
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
|
||||
val tuOverride = if (systemQualcomm) null else tuDebugOverride()
|
||||
val tuOverride = tuDebugOverride()
|
||||
val tuDriver = sysmemDriver(linuxDriverId)
|
||||
if (!systemQualcomm) (tuOverride ?: "sysmem".takeIf { tuDriver || SessionPrefs.tuSysmem(this) })?.let { guest.add("TU_DEBUG=$it") }
|
||||
(tuOverride ?: "sysmem".takeIf { tuDriver || SessionPrefs.tuSysmem(this) })?.let { guest.add("TU_DEBUG=$it") }
|
||||
if (SessionPrefs.zinkLazy(this)) {
|
||||
guest.add("ZINK_DESCRIPTORS=lazy")
|
||||
guest.add("ZINK_DEBUG=compact")
|
||||
@@ -750,9 +772,7 @@ class SessionService : Service() {
|
||||
if (SessionPrefs.glThread(this)) guest.add("mesa_glthread=true")
|
||||
if (SessionPrefs.noGlError(this)) guest.add("MESA_NO_ERROR=1")
|
||||
guest.add("MESA_DISK_CACHE_DATABASE=1")
|
||||
// Steam loads libhybris after other TLS users; its Bionic TLS bridge requires static storage.
|
||||
val staticTls = if (systemQualcomm) ":glibc.rtld.optional_static_tls=16384" else ""
|
||||
guest.add("GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.top_pad=16777216$staticTls")
|
||||
guest.add("GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.top_pad=16777216")
|
||||
if (SessionState.mode == MODE_STEAM) guest.add("BL_MANGOAPP=" + (if (SessionPrefs.mangoapp(this)) "1" else "0"))
|
||||
SessionState.steamClientArch = if (steamHere) SessionPrefs.steamClientArch(this) else null
|
||||
SessionState.steamClientArch?.let { arch ->
|
||||
@@ -761,8 +781,8 @@ class SessionService : Service() {
|
||||
SessionArtifacts.recordClient(it, arch)
|
||||
SessionArtifacts.markSteamLogs(it, File(SessionPrefs.steamRoot(this, arch), "logs"))
|
||||
}
|
||||
if (arch == "x86_64") FexCatalog.cached(this)?.let { guest.addAll(FexCatalog.environment(it)) }
|
||||
}
|
||||
FexCatalog.cached(this)?.let { guest.addAll(FexCatalog.environment(it)) }
|
||||
if (SessionState.mode == MODE_STEAM) {
|
||||
guest.add("BL_GAMESCOPE_STRETCH_16X9=" + (if (SessionPrefs.stretch16x9(this)) "1" else "0"))
|
||||
}
|
||||
@@ -794,8 +814,9 @@ class SessionService : Service() {
|
||||
private fun noSteamGame(): Boolean =
|
||||
SessionState.mode == MODE_RUN && SessionState.program in setOf(NoSteamLaunch.PROTON_RUN, NoSteamLaunch.EPIC, NoSteamLaunch.BATTLENET)
|
||||
|
||||
private fun startAudio(guest: MutableList<String>, sessionDir: File): PulseAudioComponent {
|
||||
val wantsDirectAudio = (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP || noSteamGame()) &&
|
||||
private fun startAudio(guest: MutableList<String>, sessionDir: File, directAudioPack: Boolean): PulseAudioComponent {
|
||||
val wantsDirectAudio = directAudioPack &&
|
||||
(SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP || noSteamGame()) &&
|
||||
SessionPrefs.directAudio(this)
|
||||
val wantsMic = SessionPrefs.micEnabled(this) &&
|
||||
checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
|
||||
@@ -864,7 +885,7 @@ class SessionService : Service() {
|
||||
SessionState.deckPad = deckBinds.isNotEmpty()
|
||||
if (wantsDeck && !SessionState.deckPad) Log.w(TAG, "deck pad: not available this session; the pad stays an Xbox 360 controller")
|
||||
logControllersAtStart()
|
||||
com.droiddeck.launcher.input.FakeInputWriter.setLowLatency(SessionPrefs.lowLatencyController(this), SessionPrefs.lowLatencyTouch(this))
|
||||
com.droiddeck.launcher.input.FakeInputWriter.setLowLatency(SessionPrefs.lowLatency(this))
|
||||
if (uinput) {
|
||||
guest.add("FAKE_EVDEV_UINPUT=1")
|
||||
if (SessionState.deckPad) {
|
||||
@@ -2089,7 +2110,6 @@ class SessionService : Service() {
|
||||
const val MODE_STEAM = "steam"
|
||||
const val MODE_DESKTOP = "lxqt"
|
||||
const val MODE_RUN = "run"
|
||||
const val FAILURE_RUNTIME_DRIVER = "RUNTIME_DRIVER_UNAVAILABLE"
|
||||
const val EXTRA_PROGRAM = "program"
|
||||
private const val RUN_STATUS = "run-status"
|
||||
const val EXTRA_PROGRAM_ARGS = "programArgs"
|
||||
|
||||
@@ -103,9 +103,6 @@ object SessionState {
|
||||
@Volatile
|
||||
var upscaleRatio: Float = 0f
|
||||
|
||||
@Volatile
|
||||
var fpsLimit: Int = 0
|
||||
|
||||
@Volatile
|
||||
var performanceMode = false
|
||||
|
||||
|
||||
@@ -88,6 +88,7 @@ class StoreLoginActivity : ComponentActivity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
||||
store = Store.byId(intent.getStringExtra(EXTRA_STORE))
|
||||
clientUrl = intent.getStringExtra(EXTRA_CLIENT_URL)?.takeIf { store == Store.EPIC }
|
||||
oauthState = savedInstanceState?.getString(KEY_STATE) ?: generateState()
|
||||
|
||||
@@ -236,7 +236,7 @@ object StoresState {
|
||||
fun install(context: Context, item: CatalogItem, root: java.io.File? = null, language: String? = null) {
|
||||
val app = context.applicationContext
|
||||
val targetRoot = root ?: StoreInstallRoot.defaultTarget(app)?.root ?: StoreInstallRoot.installRoot(app)
|
||||
if (item.store == Store.BATTLENET) {
|
||||
if (item.store == Store.BATTLENET && !com.droiddeck.launcher.stores.battlenet.BattleNetInstall.headless(item)) {
|
||||
backends[item.store]?.install(app, item, targetRoot)
|
||||
return
|
||||
}
|
||||
@@ -273,7 +273,7 @@ object StoresState {
|
||||
uninstalling[key] = 0f
|
||||
background("stores-uninstall", onFailure = { main.post { uninstalling.remove(key); onDone() } }) {
|
||||
runCatching { backends[game.sidecar.store]?.uninstall(app, game) }
|
||||
if (game.sidecar.store == Store.BATTLENET) {
|
||||
if (game.sidecar.store == Store.BATTLENET && com.droiddeck.launcher.runtime.BattleNet.games(app).any { it.folder.absolutePath == game.folder.absolutePath }) {
|
||||
main.post { uninstalling.remove(key); onDone() }
|
||||
return@background
|
||||
}
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
package com.droiddeck.launcher.stores.battlenet
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.frontend.AddedGames
|
||||
import com.droiddeck.launcher.runtime.BattleNet
|
||||
import com.droiddeck.launcher.runtime.GuestCommand
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.GameStorage
|
||||
import com.droiddeck.launcher.session.SecondaryLibrary
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.StoreLanguage
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.download.DownloadEntry
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
object BattleNetInstall {
|
||||
private const val TAG = "BattleNetInstall"
|
||||
internal const val PROGRESS = "BNET_PROGRESS "
|
||||
internal const val STATE = "BNET_STATE "
|
||||
internal const val DONE = "BNET_DONE "
|
||||
internal const val ERROR = "BNET_ERROR "
|
||||
private const val VERSIONS = "https://%s.version.battle.net/v2/products/%s/versions"
|
||||
private const val BUILD_INFO = ".build.info"
|
||||
private const val CHECK_AGAIN_MS = 30 * 60_000L
|
||||
private const val START_WAIT_MS = 60_000L
|
||||
|
||||
internal val LOCALES = listOf(
|
||||
"enUS", "enGB", "esMX", "esES", "ptBR", "ptPT", "frFR", "deDE", "itIT", "ruRU", "jaJP", "koKR", "plPL", "trTR",
|
||||
"zhTW", "zhCN", "thTH", "arSA",
|
||||
)
|
||||
|
||||
internal val checks = Executors.newSingleThreadExecutor { r -> Thread(r, "battlenet-updates") }
|
||||
internal val checkedAt = HashMap<String, Long>()
|
||||
|
||||
val updates = mutableStateMapOf<String, Boolean>()
|
||||
|
||||
fun product(id: String): String? = BattleNet.title(id)?.product
|
||||
|
||||
fun headless(item: CatalogItem): Boolean = item.store == Store.BATTLENET && product(item.id) != null
|
||||
|
||||
internal fun locale(locale: Locale): String {
|
||||
val language = locale.language.lowercase(Locale.ROOT)
|
||||
if (language == "zh") {
|
||||
val traditional = locale.script.equals("Hant", true) || locale.country.uppercase(Locale.ROOT) in setOf("TW", "HK", "MO")
|
||||
return if (traditional) "zhTW" else "zhCN"
|
||||
}
|
||||
val exact = language + locale.country.uppercase(Locale.ROOT)
|
||||
return LOCALES.firstOrNull { it == exact } ?: LOCALES.firstOrNull { it.startsWith(language) } ?: "enUS"
|
||||
}
|
||||
|
||||
internal fun country(locale: Locale): Pair<String, String> {
|
||||
val two = locale.country.uppercase(Locale.ROOT)
|
||||
val three = runCatching { locale.isO3Country.uppercase(Locale.ROOT) }.getOrDefault("")
|
||||
return if (two.matches(Regex("[A-Z]{2}")) && three.matches(Regex("[A-Z]{3}"))) three to two else "USA" to "US"
|
||||
}
|
||||
|
||||
internal fun binds(context: Context): List<String> {
|
||||
val out = ArrayList<String>(StoreInstallRoot.externalBindSpecs(context))
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
GameStorage.effective(context)?.let { library ->
|
||||
if (!File(library.path).isDirectory) throw IllegalStateException(context.getString(R.string.game_sync_err_game_storage))
|
||||
val content = SecondaryLibrary.contentPath(File(library.path)).path
|
||||
for (guest in SecondaryLibrary.CARD_GUESTS) {
|
||||
File(root, guest.removePrefix("/")).mkdirs()
|
||||
out += "$content:$guest"
|
||||
}
|
||||
}
|
||||
for (folder in AddedGames.roots(context)) {
|
||||
if (!folder.host.isDirectory || !folder.host.canRead()) continue
|
||||
File(root, folder.guest.removePrefix("/")).mkdirs()
|
||||
out += folder.host.path + ":" + folder.guest
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
internal fun run(context: Context, args: List<String>, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int =
|
||||
GuestCommand.run(
|
||||
context, listOf(BattleNet.PROGRAM) + args, logName = "battlenet-agent",
|
||||
extraBinds = binds(context), fastPath = true, cancelled = cancelled, onLine = onLine,
|
||||
)
|
||||
|
||||
fun enqueue(context: Context, item: CatalogItem, folder: File, update: Boolean = false) {
|
||||
val app = context.applicationContext
|
||||
val entry = DownloadEntry(
|
||||
Store.BATTLENET, item.id, item.title, cover = item.tallImageUrl ?: item.imageUrl,
|
||||
location = StoreInstallRoot.labelFor(app, folder),
|
||||
)
|
||||
DownloadQueue.enqueue(app, entry) { BattleNetInstaller(app, item, folder, update) }
|
||||
}
|
||||
|
||||
fun update(context: Context, game: InstalledStoreGame) {
|
||||
val app = context.applicationContext
|
||||
Thread({
|
||||
val item = CatalogItem(
|
||||
Store.BATTLENET, game.sidecar.id, game.sidecar.title, game.sidecar.hero, tallImageUrl = game.sidecar.cover, owned = true,
|
||||
extra = mapOf(INSTALL_UID to installUid(app, game)),
|
||||
)
|
||||
game.folder.parentFile?.parentFile?.let { com.droiddeck.launcher.stores.download.SavedQueue.remember(app, item, it) }
|
||||
enqueue(app, item, game.folder, update = true)
|
||||
}, "battlenet-update").start()
|
||||
}
|
||||
|
||||
internal const val INSTALL_UID = "installUid"
|
||||
|
||||
internal fun installUid(context: Context, game: InstalledStoreGame): String =
|
||||
runCatching { BattleNet.games(context).firstOrNull { it.uid == game.sidecar.id }?.installUid }.getOrNull() ?: game.sidecar.id
|
||||
|
||||
fun uninstall(context: Context, game: InstalledStoreGame): Boolean {
|
||||
if (product(game.sidecar.id) == null || !BattleNet.installed(context)) return false
|
||||
val done = agentUninstall(context, installUid(context, game))
|
||||
if (done) StoresState.post { StoresState.notifyLibraryChanged(context.applicationContext) }
|
||||
return done
|
||||
}
|
||||
|
||||
internal fun agentUninstall(context: Context, uid: String): Boolean {
|
||||
val stop = AtomicBoolean(false)
|
||||
val started = AtomicBoolean(false)
|
||||
val done = AtomicBoolean(false)
|
||||
val guard = Thread({
|
||||
try {
|
||||
Thread.sleep(START_WAIT_MS)
|
||||
if (!started.get()) stop.set(true)
|
||||
} catch (_: InterruptedException) {
|
||||
}
|
||||
}, "battlenet-uninstall-wait").apply { isDaemon = true; start() }
|
||||
val code = runCatching {
|
||||
run(context, listOf("agent-uninstall", uid), stop) { line ->
|
||||
if (line == STATE + "starting") started.set(true)
|
||||
if (line.startsWith(DONE)) done.set(true)
|
||||
}
|
||||
}.onFailure { Log.w(TAG, "uninstall $uid", it) }.getOrDefault(-1)
|
||||
guard.interrupt()
|
||||
Log.i(TAG, "uninstall $uid: ${if (done.get()) "done" else if (stop.get()) "Battle.net stayed busy" else "exit $code"}")
|
||||
return done.get()
|
||||
}
|
||||
|
||||
internal fun buildKey(text: String): Pair<String, String>? {
|
||||
val rows = text.lines().filter { it.isNotBlank() }
|
||||
if (rows.size < 2) return null
|
||||
val head = rows[0].split('|').map { it.substringBefore('!') }
|
||||
val branch = head.indexOf("Branch")
|
||||
val active = head.indexOf("Active")
|
||||
val key = head.indexOf("Build Key")
|
||||
if (branch < 0 || key < 0) return null
|
||||
val row = rows.drop(1).map { it.split('|') }.firstOrNull { active < 0 || it.getOrNull(active) == "1" } ?: return null
|
||||
val region = row.getOrNull(branch)?.takeIf { it.matches(Regex("[a-z]{2}")) } ?: return null
|
||||
val build = row.getOrNull(key)?.takeIf { it.matches(Regex("[0-9a-f]{32}")) } ?: return null
|
||||
return region to build
|
||||
}
|
||||
|
||||
internal fun latestBuild(text: String, region: String): String? {
|
||||
val rows = text.lines().filter { it.isNotBlank() && !it.startsWith("##") }
|
||||
if (rows.isEmpty()) return null
|
||||
val head = rows[0].split('|').map { it.substringBefore('!') }
|
||||
val at = head.indexOf("Region")
|
||||
val key = head.indexOf("BuildConfig")
|
||||
if (at < 0 || key < 0) return null
|
||||
return rows.drop(1).map { it.split('|') }.firstOrNull { it.getOrNull(at) == region }?.getOrNull(key)
|
||||
?.takeIf { it.matches(Regex("[0-9a-f]{32}")) }
|
||||
}
|
||||
|
||||
fun checkUpdate(context: Context, game: InstalledStoreGame, force: Boolean = false) = check(game.sidecar.id, game.folder, force)
|
||||
|
||||
internal fun check(id: String, folder: File, force: Boolean) {
|
||||
val product = product(id) ?: return
|
||||
val now = System.currentTimeMillis()
|
||||
synchronized(checkedAt) {
|
||||
if (!force && now - (checkedAt[id] ?: 0L) < CHECK_AGAIN_MS) return
|
||||
checkedAt[id] = now
|
||||
}
|
||||
fun retryLater() = synchronized(checkedAt) { if (checkedAt[id] == now) checkedAt.remove(id) }
|
||||
checks.execute {
|
||||
val local = runCatching { buildKey(File(folder, BUILD_INFO).readText()) }.getOrNull()
|
||||
?: return@execute retryLater()
|
||||
val latest = runCatching { latestBuild(fetch(VERSIONS.format(Locale.ROOT, local.first, product)), local.first) }
|
||||
.onFailure { Log.w(TAG, "versions of $product: ${it.javaClass.simpleName}") }.getOrNull()
|
||||
?: return@execute retryLater()
|
||||
val behind = latest != local.second
|
||||
Log.i(TAG, "$id: ${if (behind) "update available" else "up to date"}")
|
||||
StoresState.post { if (behind) updates[id] = true else updates.remove(id) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun fetch(url: String): String {
|
||||
val conn = (URL(url).openConnection() as HttpURLConnection).apply {
|
||||
connectTimeout = 15_000
|
||||
readTimeout = 15_000
|
||||
setRequestProperty("User-Agent", "DroidDeck")
|
||||
}
|
||||
try {
|
||||
if (conn.responseCode != 200) throw java.io.IOException("HTTP ${conn.responseCode}")
|
||||
return conn.inputStream.bufferedReader().use { it.readText() }
|
||||
} finally {
|
||||
conn.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
internal fun failure(context: Context, reason: String?, code: Int): String {
|
||||
val detail = when {
|
||||
reason == null -> "exit $code"
|
||||
reason == "client" -> return context.getString(R.string.bnet_dl_client_first)
|
||||
reason.startsWith("agent ") -> context.getString(R.string.bnet_dl_agent_error, reason.removePrefix("agent "))
|
||||
else -> reason.removePrefix("stopped ")
|
||||
}
|
||||
return context.getString(R.string.bnet_dl_failed, detail)
|
||||
}
|
||||
|
||||
internal fun localeTag(context: Context): String = locale(StoreLanguage.localeFor(null, context))
|
||||
|
||||
internal enum class Step { PREPARING, DOWNLOADING, APPLYING }
|
||||
|
||||
internal fun step(state: Int, phase: Int, current: Long, total: Long): Step = when {
|
||||
state == DONE_STATE || phase == APPLY_PHASE || total > 0L && current >= total -> Step.APPLYING
|
||||
total > 0L -> Step.DOWNLOADING
|
||||
else -> Step.PREPARING
|
||||
}
|
||||
|
||||
private const val DONE_STATE = 1004
|
||||
private const val APPLY_PHASE = 2000
|
||||
}
|
||||
|
||||
internal class BattleNetInstaller(
|
||||
private val app: Context,
|
||||
private val item: CatalogItem,
|
||||
private val folder: File,
|
||||
private val update: Boolean,
|
||||
) : DownloadQueue.DownloadJob {
|
||||
private val cancelled = AtomicBoolean(false)
|
||||
private val started = AtomicBoolean(false)
|
||||
private val ended = java.util.concurrent.CountDownLatch(1)
|
||||
private var before = 0L
|
||||
private var kept = -1L
|
||||
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||
started.set(true)
|
||||
try {
|
||||
return if (cancelled.get()) null else work(handle)
|
||||
} finally {
|
||||
ended.countDown()
|
||||
}
|
||||
}
|
||||
|
||||
private fun work(handle: DownloadQueue.JobHandle): String? {
|
||||
before = DownloadQueue.entry(handle.key)?.bytesTotal ?: 0L
|
||||
handle.stage(DownloadStage.MANIFEST, app.getString(R.string.bnet_dl_starting))
|
||||
if (!BattleNet.installed(app)) throw IllegalStateException(app.getString(R.string.bnet_dl_client_first))
|
||||
val title = BattleNet.title(item.id)
|
||||
val product = title?.product ?: throw IllegalStateException(app.getString(R.string.bnet_dl_failed, item.id))
|
||||
val uid = item.extra[BattleNetInstall.INSTALL_UID] ?: title.uid
|
||||
if (!update) folder.mkdirs()
|
||||
val guest = AddedGames.guestPath(app, folder) ?: throw IllegalStateException(app.getString(R.string.bnet_dl_failed, folder.path))
|
||||
val (country, region) = BattleNetInstall.country(Locale.getDefault())
|
||||
val args = if (update) listOf("agent-update", uid)
|
||||
else listOf("agent-install", uid, product, guest, BattleNetInstall.localeTag(app), country, region)
|
||||
var done: JSONObject? = null
|
||||
var reason: String? = null
|
||||
val code = BattleNetInstall.run(app, args, cancelled) { line ->
|
||||
when {
|
||||
line.startsWith(BattleNetInstall.PROGRESS) ->
|
||||
runCatching { JSONObject(line.removePrefix(BattleNetInstall.PROGRESS)) }.getOrNull()?.let { progress(handle, it) }
|
||||
line == BattleNetInstall.STATE + "waiting" -> handle.stage(DownloadStage.MANIFEST, app.getString(R.string.bnet_dl_waiting))
|
||||
line == BattleNetInstall.STATE + "queued" -> handle.stage(DownloadStage.MANIFEST, app.getString(R.string.bnet_dl_queued))
|
||||
line == BattleNetInstall.STATE + "starting" -> handle.stage(DownloadStage.MANIFEST, app.getString(R.string.bnet_dl_starting))
|
||||
line.startsWith(BattleNetInstall.DONE) -> done = runCatching { JSONObject(line.removePrefix(BattleNetInstall.DONE)) }.getOrNull()
|
||||
line.startsWith(BattleNetInstall.ERROR) -> reason = line.removePrefix(BattleNetInstall.ERROR)
|
||||
}
|
||||
}
|
||||
if (cancelled.get()) return null
|
||||
if (done == null) throw IllegalStateException(BattleNetInstall.failure(app, reason, code))
|
||||
handle.log("Battle.net: ${item.title} ${if (update) "updated" else "installed"} ${done?.optString("version").orEmpty()}".trimEnd())
|
||||
StoresState.post {
|
||||
BattleNetInstall.updates.remove(item.id)
|
||||
StoresState.notifyLibraryChanged(app)
|
||||
}
|
||||
BattleNetInstall.check(item.id, folder, force = true)
|
||||
return folder.absolutePath
|
||||
}
|
||||
|
||||
private fun progress(handle: DownloadQueue.JobHandle, status: JSONObject) {
|
||||
val current = status.optLong("download_current", 0L)
|
||||
val total = status.optLong("download_total", 0L)
|
||||
when (BattleNetInstall.step(status.optInt("state", 0), status.optInt("phase", 0), current, total)) {
|
||||
BattleNetInstall.Step.PREPARING -> handle.stage(DownloadStage.MANIFEST, app.getString(R.string.stores_stage_checking))
|
||||
BattleNetInstall.Step.DOWNLOADING -> {
|
||||
if (kept < 0L) kept = (before - total).coerceAtLeast(0L)
|
||||
handle.progress(kept + current, kept + total)
|
||||
}
|
||||
BattleNetInstall.Step.APPLYING -> handle.stage(DownloadStage.INSTALL)
|
||||
}
|
||||
}
|
||||
|
||||
override fun cancel(deleteFiles: Boolean) {
|
||||
cancelled.set(true)
|
||||
if (!deleteFiles || update) return
|
||||
val uid = item.extra[BattleNetInstall.INSTALL_UID] ?: BattleNet.title(item.id)?.uid ?: return
|
||||
Thread({
|
||||
if (started.get() && !ended.await(END_WAIT_S, TimeUnit.SECONDS)) Log.w("BattleNetInstall", "the cancelled install of $uid is still stopping")
|
||||
val gone = BattleNetInstall.agentUninstall(app, uid)
|
||||
if (folder.isDirectory && (gone || folder.list().isNullOrEmpty())) com.droiddeck.launcher.core.FileUtils.delete(folder)
|
||||
Log.i("BattleNetInstall", "cancelled install of $uid: ${if (gone) "removed" else "left for Battle.net to remove"}")
|
||||
}, "battlenet-cancel").start()
|
||||
}
|
||||
}
|
||||
|
||||
private const val END_WAIT_S = 120L
|
||||
@@ -189,9 +189,15 @@ object BattleNetBackend : StoreBackend {
|
||||
override fun search(context: Context, query: String): List<CatalogItem> =
|
||||
BattleNet.STORE.filter { it.name.contains(query, ignoreCase = true) }.map { item(context, it) }
|
||||
|
||||
override fun install(context: Context, item: CatalogItem, root: File) = BattleNetClient.installGame(context, item.id, root)
|
||||
override fun install(context: Context, item: CatalogItem, root: File) {
|
||||
if (!BattleNetInstall.headless(item)) return BattleNetClient.installGame(context, item.id, root)
|
||||
val app = context.applicationContext
|
||||
BattleNetInstall.enqueue(app, item, StoreInstallRoot.folderFor(app, store, item.id, item.title, root))
|
||||
}
|
||||
|
||||
override fun uninstall(context: Context, game: InstalledStoreGame) = BattleNetClient.open(emptyList())
|
||||
override fun uninstall(context: Context, game: InstalledStoreGame) {
|
||||
if (!BattleNetInstall.uninstall(context, game)) BattleNetClient.open(emptyList())
|
||||
}
|
||||
|
||||
fun installed(context: Context): List<BattleNet.Game> = if (BattleNet.installed(context)) BattleNet.games(context) else emptyList()
|
||||
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
package com.droiddeck.launcher.stores.gfn
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import org.json.JSONObject
|
||||
import java.io.BufferedWriter
|
||||
import java.io.File
|
||||
import java.util.concurrent.CompletableFuture
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.TimeoutException
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
class GfnError(val code: String, message: String) : Exception(message)
|
||||
|
||||
/**
|
||||
* OpenNOW's core service (external/opennow, MIT, by Zortos) as a child process: sign-in, the
|
||||
* GeForce NOW catalog and CloudMatch sessions, spoken as newline-delimited JSON on its stdin and
|
||||
* stdout (external/opennow/docs/core-protocol.md). It ships as libopennowcore.so in the native
|
||||
* library directory, the one place the app may run programs from.
|
||||
*/
|
||||
object GfnCore {
|
||||
private const val TAG = "GfnCore"
|
||||
private const val PROTOCOL_VERSION = 5
|
||||
private const val BINARY = "libopennowcore.so"
|
||||
|
||||
private var process: Process? = null
|
||||
private var writer: BufferedWriter? = null
|
||||
private val pending = ConcurrentHashMap<String, CompletableFuture<JSONObject>>()
|
||||
private val nextId = AtomicLong(1)
|
||||
private val listeners = java.util.concurrent.CopyOnWriteArrayList<(String, JSONObject) -> Unit>()
|
||||
|
||||
/** The core runs in the :gfn process; other processes reach it through [GfnCoreService]. */
|
||||
private val inCoreProcess: Boolean by lazy {
|
||||
val name = if (android.os.Build.VERSION.SDK_INT >= 28) android.app.Application.getProcessName()
|
||||
else runCatching { File("/proc/self/cmdline").readText().trimEnd('\u0000') }.getOrDefault("")
|
||||
name.endsWith(":gfn")
|
||||
}
|
||||
|
||||
fun addListener(listener: (String, JSONObject) -> Unit) { listeners += listener }
|
||||
fun removeListener(listener: (String, JSONObject) -> Unit) { listeners -= listener }
|
||||
|
||||
/** Starts the core if it is not running, then checks the protocol and turns its reporting off. */
|
||||
@Synchronized
|
||||
fun ensureStarted(context: Context) {
|
||||
if (process?.isAlive == true) return
|
||||
val app = context.applicationContext
|
||||
val binary = File(app.applicationInfo.nativeLibraryDir, BINARY)
|
||||
check(binary.isFile) { "This build has no GeForce NOW core ($BINARY)" }
|
||||
val dataDir = File(app.filesDir, "gfn/core").apply { mkdirs() }
|
||||
val logFile = File(app.filesDir, "gfn/core.log")
|
||||
val started = ProcessBuilder(binary.path, "--data-dir", dataDir.path)
|
||||
.directory(dataDir)
|
||||
.redirectError(ProcessBuilder.Redirect.appendTo(logFile))
|
||||
.start()
|
||||
process = started
|
||||
writer = started.outputStream.bufferedWriter()
|
||||
Thread({ readLoop(started) }, "gfn-core-out").apply { isDaemon = true; start() }
|
||||
Log.i(TAG, "core started")
|
||||
request(app, "core.hello", JSONObject()
|
||||
.put("protocolVersion", PROTOCOL_VERSION)
|
||||
.put("shell", "qt")
|
||||
.put("shellVersion", "droiddeck"), timeoutMs = 10_000)
|
||||
// DroidDeck never sends OpenNOW's analytics or crash reports anywhere.
|
||||
for ((key, value) in listOf("automaticBugReports" to "disabled", "errorReportingConsent" to "denied")) {
|
||||
runCatching { request(app, "settings.set", JSONObject().put("key", key).put("value", value)) }
|
||||
.onFailure { Log.w(TAG, "could not set $key: ${it.message}") }
|
||||
}
|
||||
}
|
||||
|
||||
/** One request, answered with its `result` or thrown as [GfnError]. Blocking: call off the main thread. */
|
||||
fun request(context: Context, method: String, params: JSONObject = JSONObject(), timeoutMs: Long = 30_000): JSONObject {
|
||||
if (!inCoreProcess) return GfnRemote.request(context, method, params, timeoutMs)
|
||||
if (method != "core.hello") ensureStarted(context)
|
||||
val id = "dd-" + nextId.getAndIncrement()
|
||||
val answer = CompletableFuture<JSONObject>()
|
||||
pending[id] = answer
|
||||
try {
|
||||
val line = JSONObject().put("type", "request").put("id", id).put("method", method).put("params", params).toString()
|
||||
synchronized(this) {
|
||||
val out = writer ?: throw GfnError("core_stopped", "The GeForce NOW core is not running")
|
||||
out.write(line)
|
||||
out.newLine()
|
||||
out.flush()
|
||||
}
|
||||
val response = try {
|
||||
answer.get(timeoutMs, TimeUnit.MILLISECONDS)
|
||||
} catch (e: TimeoutException) {
|
||||
throw GfnError("timeout", "GeForce NOW did not answer in time ($method)")
|
||||
}
|
||||
if (response.optBoolean("ok")) return response.optJSONObject("result") ?: JSONObject()
|
||||
val error = response.optJSONObject("error")
|
||||
throw GfnError(error?.optString("code").orEmpty().ifEmpty { "error" },
|
||||
error?.optString("message").orEmpty().ifEmpty { "GeForce NOW request failed ($method)" })
|
||||
} finally {
|
||||
pending.remove(id)
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun stop() {
|
||||
runCatching { writer?.close() }
|
||||
process?.destroy()
|
||||
process = null
|
||||
writer = null
|
||||
pending.values.forEach { it.completeExceptionally(GfnError("core_stopped", "The GeForce NOW core stopped")) }
|
||||
pending.clear()
|
||||
}
|
||||
|
||||
private fun readLoop(running: Process) {
|
||||
try {
|
||||
running.inputStream.bufferedReader().useLines { lines ->
|
||||
lines.forEach { line ->
|
||||
val message = runCatching { JSONObject(line) }.getOrNull() ?: return@forEach
|
||||
when (message.optString("type")) {
|
||||
"event" -> {
|
||||
val name = message.optString("name")
|
||||
val payload = message.optJSONObject("payload") ?: JSONObject()
|
||||
listeners.forEach { runCatching { it(name, payload) } }
|
||||
}
|
||||
else -> pending[message.optString("id")]?.complete(message)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
Log.w(TAG, "core output ended")
|
||||
synchronized(this) {
|
||||
if (process === running) {
|
||||
process = null
|
||||
writer = null
|
||||
}
|
||||
}
|
||||
pending.values.forEach { it.completeExceptionally(GfnError("core_stopped", "The GeForce NOW core stopped")) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package com.droiddeck.launcher.stores.gfn
|
||||
|
||||
import android.app.Service
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.ServiceConnection
|
||||
import android.os.Binder
|
||||
import android.os.IBinder
|
||||
import android.os.Parcel
|
||||
import android.os.Process
|
||||
import android.os.RemoteException
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* Hosts the one OpenNOW core in the :gfn process (the core locks its data directory, so a second
|
||||
* copy cannot run) and answers core requests from the Stores page in the main process.
|
||||
*/
|
||||
class GfnCoreService : Service() {
|
||||
private val binder = object : Binder() {
|
||||
override fun onTransact(code: Int, data: Parcel, reply: Parcel?, flags: Int): Boolean {
|
||||
if (code != REQUEST) return super.onTransact(code, data, reply, flags)
|
||||
if (getCallingUid() != Process.myUid() || reply == null) return false
|
||||
val method = data.readString().orEmpty()
|
||||
val params = runCatching { JSONObject(data.readString() ?: "{}") }.getOrDefault(JSONObject())
|
||||
val timeoutMs = data.readLong()
|
||||
try {
|
||||
val result = GfnCore.request(applicationContext, method, params, timeoutMs)
|
||||
reply.writeInt(1)
|
||||
reply.writeString(result.toString())
|
||||
} catch (e: Exception) {
|
||||
reply.writeInt(0)
|
||||
reply.writeString(JSONObject().put("code", (e as? GfnError)?.code ?: "error")
|
||||
.put("message", e.message ?: "GeForce NOW request failed ($method)").toString())
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder = binder
|
||||
|
||||
companion object {
|
||||
const val REQUEST = IBinder.FIRST_CALL_TRANSACTION
|
||||
}
|
||||
}
|
||||
|
||||
/** The main process's side of [GfnCoreService]. Blocking: call off the main thread. */
|
||||
internal object GfnRemote {
|
||||
private val lock = Object()
|
||||
@Volatile private var binder: IBinder? = null
|
||||
private var bound = false
|
||||
|
||||
private val connection = object : ServiceConnection {
|
||||
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
|
||||
synchronized(lock) { binder = service; lock.notifyAll() }
|
||||
}
|
||||
override fun onServiceDisconnected(name: ComponentName?) { binder = null }
|
||||
override fun onBindingDied(name: ComponentName?) { synchronized(lock) { binder = null; bound = false } }
|
||||
}
|
||||
|
||||
fun request(context: Context, method: String, params: JSONObject, timeoutMs: Long): JSONObject {
|
||||
val service = connect(context)
|
||||
val data = Parcel.obtain()
|
||||
val reply = Parcel.obtain()
|
||||
try {
|
||||
data.writeString(method)
|
||||
data.writeString(params.toString())
|
||||
data.writeLong(timeoutMs)
|
||||
if (!service.transact(GfnCoreService.REQUEST, data, reply, 0))
|
||||
throw GfnError("core_stopped", "The GeForce NOW service refused the request")
|
||||
val ok = reply.readInt() == 1
|
||||
val body = reply.readString() ?: "{}"
|
||||
if (ok) return JSONObject(body)
|
||||
val error = JSONObject(body)
|
||||
throw GfnError(error.optString("code").ifEmpty { "error" }, error.optString("message"))
|
||||
} catch (e: RemoteException) {
|
||||
binder = null
|
||||
throw GfnError("core_stopped", "The GeForce NOW service stopped")
|
||||
} finally {
|
||||
data.recycle()
|
||||
reply.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
private fun connect(context: Context): IBinder {
|
||||
synchronized(lock) {
|
||||
binder?.takeIf { it.isBinderAlive }?.let { return it }
|
||||
val app = context.applicationContext
|
||||
if (!bound) bound = app.bindService(Intent(app, GfnCoreService::class.java), connection, Context.BIND_AUTO_CREATE)
|
||||
if (!bound) throw GfnError("core_stopped", "The GeForce NOW service could not start")
|
||||
val deadline = System.currentTimeMillis() + 15_000
|
||||
while (binder?.isBinderAlive != true) {
|
||||
val left = deadline - System.currentTimeMillis()
|
||||
if (left <= 0) throw GfnError("timeout", "The GeForce NOW service did not start")
|
||||
lock.wait(left)
|
||||
}
|
||||
return binder!!
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
package com.droiddeck.launcher.stores.gfn
|
||||
|
||||
import android.app.AlertDialog
|
||||
import android.graphics.Color
|
||||
import android.os.Bundle
|
||||
import android.util.Log
|
||||
import android.view.Gravity
|
||||
import android.view.InputDevice
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
import android.view.SurfaceHolder
|
||||
import android.view.SurfaceView
|
||||
import android.view.WindowManager
|
||||
import android.widget.FrameLayout
|
||||
import android.widget.TextView
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.OnBackPressedCallback
|
||||
import androidx.core.view.WindowCompat
|
||||
import androidx.core.view.WindowInsetsCompat
|
||||
import androidx.core.view.WindowInsetsControllerCompat
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.Executors
|
||||
import kotlin.math.hypot
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/** Plays one GeForce NOW game: books a seat, waits in the queue, then streams onto a SurfaceView. */
|
||||
class GfnPlayerActivity : ComponentActivity() {
|
||||
companion object {
|
||||
const val EXTRA_APP_ID = "appId"
|
||||
const val EXTRA_VARIANT_ID = "variantId"
|
||||
const val EXTRA_TITLE = "title"
|
||||
private const val TAG = "GfnPlayer"
|
||||
private const val DEADZONE = 0.15f
|
||||
}
|
||||
|
||||
private lateinit var status: TextView
|
||||
private val worker = Executors.newSingleThreadExecutor()
|
||||
private var streamer: GfnStreamer? = null
|
||||
@Volatile private var session: JSONObject? = null
|
||||
@Volatile private var closed = false
|
||||
@Volatile private var capabilities: JSONObject? = null
|
||||
private val helloWait = java.util.concurrent.CompletableFuture<JSONObject>()
|
||||
private val pads = Pads()
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
WindowCompat.setDecorFitsSystemWindows(window, false)
|
||||
WindowInsetsControllerCompat(window, window.decorView).apply {
|
||||
hide(WindowInsetsCompat.Type.systemBars())
|
||||
systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
|
||||
}
|
||||
val root = FrameLayout(this).apply { setBackgroundColor(Color.BLACK) }
|
||||
val surface = SurfaceView(this)
|
||||
surface.holder.addCallback(object : SurfaceHolder.Callback {
|
||||
override fun surfaceCreated(holder: SurfaceHolder) = GfnStreamer.setSurface(holder.surface)
|
||||
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {}
|
||||
override fun surfaceDestroyed(holder: SurfaceHolder) = GfnStreamer.setSurface(null)
|
||||
})
|
||||
root.addView(surface, FrameLayout.LayoutParams(-1, -1))
|
||||
status = TextView(this).apply {
|
||||
setTextColor(Color.WHITE)
|
||||
textSize = 18f
|
||||
gravity = Gravity.CENTER
|
||||
setPadding(48, 48, 48, 48)
|
||||
}
|
||||
root.addView(status, FrameLayout.LayoutParams(-1, -1))
|
||||
setContentView(root)
|
||||
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
|
||||
override fun handleOnBackPressed() = confirmLeave()
|
||||
})
|
||||
val appId = intent.getStringExtra(EXTRA_APP_ID).orEmpty()
|
||||
val variantId = intent.getStringExtra(EXTRA_VARIANT_ID).orEmpty()
|
||||
val title = intent.getStringExtra(EXTRA_TITLE).orEmpty()
|
||||
show("Starting $title…")
|
||||
worker.execute {
|
||||
runCatching { play(appId, variantId, title) }.onFailure {
|
||||
Log.w(TAG, "could not start: ${it.message}")
|
||||
show(it.message ?: "GeForce NOW could not start this game.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun play(appId: String, variantId: String, title: String) {
|
||||
val engine = GfnStreamer(::onStreamerMessage)
|
||||
streamer = engine
|
||||
engine.send("hello", JSONObject().put("protocolVersion", 7))
|
||||
val caps = helloWait.get(10, java.util.concurrent.TimeUnit.SECONDS)
|
||||
capabilities = caps
|
||||
|
||||
val inspect = GfnCore.request(this, "catalog.launch.inspect", JSONObject().put("appId", appId).put("variantId", variantId))
|
||||
val decision = inspect.optJSONObject("decision")
|
||||
if (decision?.optString("status") != "ready") {
|
||||
show(decision?.optString("message").orEmpty().ifEmpty { "This game can't be started with this account." })
|
||||
return
|
||||
}
|
||||
show("Requesting a GeForce NOW seat…")
|
||||
var current = GfnCore.request(this, "session.create", JSONObject()
|
||||
.put("appId", variantId)
|
||||
.put("variantId", variantId)
|
||||
.put("catalogAppId", appId)
|
||||
.put("scope", inspect.opt("scope"))
|
||||
.put("title", title)
|
||||
.put("runtimeCapabilities", caps), timeoutMs = 60_000)
|
||||
current = current.optJSONObject("session") ?: current
|
||||
session = current
|
||||
while (!closed && !ready(current)) {
|
||||
val position = current.optInt("queuePosition", 0)
|
||||
show(if (position > 0) "In the queue: position $position" else "Preparing your seat…")
|
||||
Thread.sleep(2_000)
|
||||
val polled = GfnCore.request(this, "session.poll", JSONObject()
|
||||
.put("sessionId", current.opt("sessionId"))
|
||||
.put("streamingBaseUrl", current.opt("streamingBaseUrl")), timeoutMs = 35_000)
|
||||
current = polled.optJSONObject("session") ?: polled
|
||||
session = current
|
||||
if (current.optString("phase") == "failed") {
|
||||
show("GeForce NOW could not prepare this session.")
|
||||
return
|
||||
}
|
||||
}
|
||||
if (closed) return
|
||||
show("Connecting…")
|
||||
val prepared = GfnCore.request(this, "streamer.prepare",
|
||||
JSONObject().put("session", current).put("runtimeCapabilities", caps))
|
||||
prepared.optJSONObject("session")?.let { session = it }
|
||||
val context = prepared.optJSONObject("context") ?: error("GeForce NOW returned no stream context")
|
||||
engine.send("start", JSONObject().put("context", context).put("microphoneEnabled", false))
|
||||
}
|
||||
|
||||
private fun ready(session: JSONObject): Boolean {
|
||||
val phase = session.optString("phase")
|
||||
return phase == "ready" || phase == "streaming" || session.optInt("status", 0) >= 2
|
||||
}
|
||||
|
||||
private fun onStreamerMessage(message: JSONObject) {
|
||||
when (message.optString("type")) {
|
||||
"ready" -> message.optJSONObject("capabilities")?.let { helloWait.complete(it) }
|
||||
"error" -> {
|
||||
Log.w(TAG, "streamer error ${message.optString("code")}: ${message.optString("message")}")
|
||||
show(message.optString("message").ifEmpty { "The stream stopped." })
|
||||
}
|
||||
"status" -> when (message.optString("event")) {
|
||||
"first-frame" -> runOnUiThread { status.visibility = android.view.View.GONE }
|
||||
}
|
||||
"stopped" -> show("The stream ended.")
|
||||
}
|
||||
}
|
||||
|
||||
private fun show(text: String) = runOnUiThread {
|
||||
status.text = text
|
||||
status.visibility = android.view.View.VISIBLE
|
||||
}
|
||||
|
||||
private fun confirmLeave() {
|
||||
AlertDialog.Builder(this)
|
||||
.setTitle("Leave the game?")
|
||||
.setMessage("This ends your GeForce NOW session.")
|
||||
.setPositiveButton("Leave") { _, _ -> finish() }
|
||||
.setNegativeButton("Keep playing", null)
|
||||
.show()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
closed = true
|
||||
val engine = streamer
|
||||
val active = session
|
||||
streamer = null
|
||||
Thread({
|
||||
runCatching { engine?.send("stop") }
|
||||
if (active != null) {
|
||||
runCatching {
|
||||
GfnCore.request(applicationContext, "session.stop", JSONObject()
|
||||
.put("sessionId", active.opt("sessionId"))
|
||||
.put("streamingBaseUrl", active.opt("streamingBaseUrl")))
|
||||
}.onFailure { Log.w(TAG, "session stop: ${it.message}") }
|
||||
}
|
||||
engine?.close()
|
||||
}, "gfn-leave").start()
|
||||
worker.shutdownNow()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
// --- controllers: Android gamepads in XInput layout, the same mapping OpenNOW uses ---
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
if (event.isFromSource(InputDevice.SOURCE_GAMEPAD) || event.isFromSource(InputDevice.SOURCE_JOYSTICK)) {
|
||||
val bit = buttonBit(event.keyCode)
|
||||
if (bit != 0) {
|
||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) pads.press(event.deviceId, bit, true)
|
||||
else if (event.action == KeyEvent.ACTION_UP) pads.press(event.deviceId, bit, false)
|
||||
return true
|
||||
}
|
||||
}
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
|
||||
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
|
||||
if (event.isFromSource(InputDevice.SOURCE_JOYSTICK) && event.action == MotionEvent.ACTION_MOVE) {
|
||||
pads.move(event)
|
||||
return true
|
||||
}
|
||||
return super.dispatchGenericMotionEvent(event)
|
||||
}
|
||||
|
||||
private fun buttonBit(keyCode: Int): Int = when (keyCode) {
|
||||
KeyEvent.KEYCODE_BUTTON_A -> 0x1000
|
||||
KeyEvent.KEYCODE_BUTTON_B -> 0x2000
|
||||
KeyEvent.KEYCODE_BUTTON_X -> 0x4000
|
||||
KeyEvent.KEYCODE_BUTTON_Y -> 0x8000
|
||||
KeyEvent.KEYCODE_BUTTON_SELECT -> 0x0020
|
||||
KeyEvent.KEYCODE_BUTTON_START -> 0x0010
|
||||
KeyEvent.KEYCODE_BUTTON_THUMBL -> 0x0040
|
||||
KeyEvent.KEYCODE_BUTTON_THUMBR -> 0x0080
|
||||
KeyEvent.KEYCODE_BUTTON_L1 -> 0x0100
|
||||
KeyEvent.KEYCODE_BUTTON_R1 -> 0x0200
|
||||
KeyEvent.KEYCODE_DPAD_UP -> 0x0001
|
||||
KeyEvent.KEYCODE_DPAD_DOWN -> 0x0002
|
||||
KeyEvent.KEYCODE_DPAD_LEFT -> 0x0004
|
||||
KeyEvent.KEYCODE_DPAD_RIGHT -> 0x0008
|
||||
else -> 0
|
||||
}
|
||||
|
||||
private inner class Pads {
|
||||
private inner class Pad(val slot: Int) {
|
||||
var buttons = 0
|
||||
var hatButtons = 0
|
||||
var lt = 0
|
||||
var rt = 0
|
||||
var lx = 0
|
||||
var ly = 0
|
||||
var rx = 0
|
||||
var ry = 0
|
||||
}
|
||||
|
||||
private val bySlot = arrayOfNulls<Pad>(4)
|
||||
private val byDevice = HashMap<Int, Pad>()
|
||||
|
||||
@Synchronized
|
||||
private fun pad(deviceId: Int): Pad? = byDevice[deviceId] ?: run {
|
||||
val free = (0 until 4).firstOrNull { bySlot[it] == null } ?: return null
|
||||
Pad(free).also { bySlot[free] = it; byDevice[deviceId] = it }
|
||||
}
|
||||
|
||||
private fun connected(): Int = (0 until 4).filter { bySlot[it] != null }.fold(0) { bits, slot -> bits or (1 shl slot) or (1 shl (slot + 8)) }
|
||||
|
||||
fun press(deviceId: Int, bit: Int, down: Boolean) {
|
||||
val pad = pad(deviceId) ?: return
|
||||
pad.buttons = if (down) pad.buttons or bit else pad.buttons and bit.inv()
|
||||
send(pad)
|
||||
}
|
||||
|
||||
fun move(event: MotionEvent) {
|
||||
val pad = pad(event.deviceId) ?: return
|
||||
val (lx, ly) = stick(event.getAxisValue(MotionEvent.AXIS_X), event.getAxisValue(MotionEvent.AXIS_Y))
|
||||
val rightX = event.getAxisValue(MotionEvent.AXIS_Z).takeIf { it != 0f } ?: event.getAxisValue(MotionEvent.AXIS_RX)
|
||||
val rightY = event.getAxisValue(MotionEvent.AXIS_RZ).takeIf { it != 0f } ?: event.getAxisValue(MotionEvent.AXIS_RY)
|
||||
val (rx, ry) = stick(rightX, rightY)
|
||||
pad.lx = lx; pad.ly = ly; pad.rx = rx; pad.ry = ry
|
||||
pad.lt = trigger(maxOf(event.getAxisValue(MotionEvent.AXIS_LTRIGGER), event.getAxisValue(MotionEvent.AXIS_BRAKE)))
|
||||
pad.rt = trigger(maxOf(event.getAxisValue(MotionEvent.AXIS_RTRIGGER), event.getAxisValue(MotionEvent.AXIS_GAS)))
|
||||
val hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X)
|
||||
val hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y)
|
||||
pad.hatButtons = (if (hatY < -0.5f) 0x0001 else 0) or (if (hatY > 0.5f) 0x0002 else 0) or
|
||||
(if (hatX < -0.5f) 0x0004 else 0) or (if (hatX > 0.5f) 0x0008 else 0)
|
||||
send(pad)
|
||||
}
|
||||
|
||||
/** Radial deadzone, Y flipped so up is positive (XInput). */
|
||||
private fun stick(x: Float, y: Float): Pair<Int, Int> {
|
||||
val magnitude = hypot(x, y)
|
||||
if (magnitude < DEADZONE) return 0 to 0
|
||||
val scaled = ((magnitude - DEADZONE) / (1f - DEADZONE)).coerceIn(0f, 1f) / magnitude
|
||||
return (x * scaled * 32767f).roundToInt() to (-y * scaled * 32767f).roundToInt()
|
||||
}
|
||||
|
||||
private fun trigger(value: Float): Int = (value.coerceIn(0f, 1f) * 255f).roundToInt()
|
||||
|
||||
private fun send(pad: Pad) {
|
||||
streamer?.gamepad(pad.slot, connected(), pad.buttons or pad.hatButtons, pad.lt, pad.rt, pad.lx, pad.ly, pad.rx, pad.ry)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
package com.droiddeck.launcher.stores.gfn
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.json.JSONObject
|
||||
|
||||
data class GfnGame(val id: String, val variantId: String, val title: String, val store: String,
|
||||
val imageUrl: String, val inLibrary: Boolean, val search: String)
|
||||
|
||||
data class GfnStoreAccount(val provider: String, val label: String, val displayName: String, val connected: Boolean,
|
||||
val status: String, val syncState: String, val canLink: Boolean, val canSync: Boolean)
|
||||
|
||||
/**
|
||||
* The GeForce NOW tab on the Stores page: NVIDIA sign-in, the store catalog, the account's library
|
||||
* and its connected stores, all through OpenNOW's core. Kept here so it survives switching tabs.
|
||||
*/
|
||||
object GfnState {
|
||||
sealed interface Phase {
|
||||
data object Loading : Phase
|
||||
data class SignedOut(val error: String? = null) : Phase
|
||||
data class Code(val userCode: String, val url: String, val attemptId: String, val intervalMs: Long) : Phase
|
||||
data class SignedIn(val user: String) : Phase
|
||||
data class Failed(val message: String) : Phase
|
||||
}
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
|
||||
|
||||
var phase by mutableStateOf<Phase>(Phase.Loading)
|
||||
private set
|
||||
private var started = false
|
||||
private var signInJob: Job? = null
|
||||
|
||||
var storeGames by mutableStateOf(emptyList<GfnGame>())
|
||||
private set
|
||||
var storeTotal by mutableStateOf(0)
|
||||
private set
|
||||
var storeLoading by mutableStateOf(false)
|
||||
private set
|
||||
var storeError by mutableStateOf<String?>(null)
|
||||
private set
|
||||
private var storeQuery = ""
|
||||
private var storeNext = ""
|
||||
private var storeMore = true
|
||||
private var storeGeneration = 0
|
||||
private var storeJob: Job? = null
|
||||
|
||||
var library by mutableStateOf<List<GfnGame>?>(null)
|
||||
private set
|
||||
var libraryError by mutableStateOf<String?>(null)
|
||||
private set
|
||||
private var libraryJob: Job? = null
|
||||
|
||||
var accounts by mutableStateOf<List<GfnStoreAccount>?>(null)
|
||||
private set
|
||||
var accountsMessage by mutableStateOf<String?>(null)
|
||||
private set
|
||||
var accountsBusy by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
/** Loads the sign-in state once; [force] checks again (Try again). */
|
||||
fun start(context: Context, force: Boolean = false) {
|
||||
if (started && !force) return
|
||||
started = true
|
||||
val app = context.applicationContext
|
||||
phase = Phase.Loading
|
||||
scope.launch { phase = withContext(Dispatchers.IO) { loadSignedIn(app) } }
|
||||
}
|
||||
|
||||
fun signIn(context: Context) {
|
||||
val app = context.applicationContext
|
||||
signInJob?.cancel()
|
||||
signInJob = scope.launch {
|
||||
val code = withContext(Dispatchers.IO) { runCatching { startSignIn(app) } }
|
||||
.getOrElse { phase = Phase.SignedOut(it.message); return@launch }
|
||||
phase = code
|
||||
phase = waitForSignIn(app, code)
|
||||
}
|
||||
}
|
||||
|
||||
fun cancelSignIn() {
|
||||
signInJob?.cancel()
|
||||
phase = Phase.SignedOut()
|
||||
}
|
||||
|
||||
fun signOut(context: Context) {
|
||||
val app = context.applicationContext
|
||||
signInJob?.cancel()
|
||||
scope.launch {
|
||||
withContext(Dispatchers.IO) { runCatching { GfnCore.request(app, "auth.logout") } }
|
||||
clearAccountData()
|
||||
phase = Phase.SignedOut()
|
||||
}
|
||||
}
|
||||
|
||||
private fun clearAccountData() {
|
||||
storeJob?.cancel(); libraryJob?.cancel()
|
||||
storeGames = emptyList(); storeTotal = 0; storeNext = ""; storeMore = true; storeError = null; storeLoading = false
|
||||
library = null; libraryError = null
|
||||
accounts = null; accountsMessage = null
|
||||
}
|
||||
|
||||
/** Shows the store for [query]: loads it when the query changed or nothing is loaded yet. */
|
||||
fun showStore(context: Context, query: String) {
|
||||
if (query.trim() != storeQuery || (storeGames.isEmpty() && !storeLoading && storeError == null)) loadStore(context, query, reset = true)
|
||||
}
|
||||
|
||||
/** NVIDIA's signed-in store catalog, a page at a time; a new [query] starts over. */
|
||||
fun loadStore(context: Context, query: String, reset: Boolean) {
|
||||
val text = query.trim()
|
||||
if (!reset && (storeLoading || !storeMore || text != storeQuery)) return
|
||||
val app = context.applicationContext
|
||||
storeGeneration += 1
|
||||
val asked = storeGeneration
|
||||
storeQuery = text
|
||||
if (reset) { storeNext = ""; storeMore = true }
|
||||
val cursor = storeNext
|
||||
storeLoading = true
|
||||
storeJob?.cancel()
|
||||
storeJob = scope.launch {
|
||||
if (reset && text.isNotEmpty()) delay(350)
|
||||
val page = withContext(Dispatchers.IO) { runCatching { storePage(app, cursor, text) } }
|
||||
if (asked != storeGeneration) return@launch
|
||||
storeLoading = false
|
||||
page.onSuccess {
|
||||
storeError = null
|
||||
val seen = if (reset) HashSet() else storeGames.map { game -> game.id }.toHashSet()
|
||||
storeGames = (if (reset) emptyList() else storeGames) + it.games.filter { game -> seen.add(game.id) }
|
||||
storeNext = it.next
|
||||
storeMore = it.more
|
||||
storeTotal = maxOf(it.total, storeGames.size)
|
||||
}.onFailure { storeError = it.message ?: "The GeForce NOW store did not answer." }
|
||||
}
|
||||
}
|
||||
|
||||
fun loadLibrary(context: Context, force: Boolean = false) {
|
||||
if (!force && (library != null || libraryJob?.isActive == true)) return
|
||||
val app = context.applicationContext
|
||||
if (force) library = null
|
||||
libraryError = null
|
||||
libraryJob?.cancel()
|
||||
libraryJob = scope.launch {
|
||||
withContext(Dispatchers.IO) { runCatching { libraryGames(app) } }
|
||||
.onSuccess { library = it.sortedBy { game -> game.title.lowercase() } }
|
||||
.onFailure { libraryError = it.message ?: "Your GeForce NOW library could not be loaded." }
|
||||
}
|
||||
}
|
||||
|
||||
fun loadAccounts(context: Context) {
|
||||
val app = context.applicationContext
|
||||
scope.launch {
|
||||
withContext(Dispatchers.IO) { runCatching { storeAccounts(app) } }
|
||||
.onSuccess { accounts = it }
|
||||
.onFailure { accountsMessage = it.message ?: "Connected stores could not be loaded." }
|
||||
}
|
||||
}
|
||||
|
||||
fun link(context: Context, account: GfnStoreAccount) = perform(context) { app -> linkStore(app, account) }
|
||||
fun sync(context: Context, account: GfnStoreAccount) = perform(context) { app -> syncStore(app, account) }
|
||||
fun unlink(context: Context, account: GfnStoreAccount) = perform(context) { app ->
|
||||
withContext(Dispatchers.IO) {
|
||||
GfnCore.request(app, "account.connections.unlink", JSONObject().put("provider", account.provider))
|
||||
.optString("message").ifEmpty { "${account.label} disconnected." }
|
||||
}
|
||||
}
|
||||
|
||||
private fun perform(context: Context, action: suspend (Context) -> String) {
|
||||
if (accountsBusy) return
|
||||
val app = context.applicationContext
|
||||
accountsBusy = true
|
||||
scope.launch {
|
||||
accountsMessage = runCatching { action(app) }.getOrElse { it.message ?: "That did not work. Try again." }
|
||||
accountsBusy = false
|
||||
loadAccounts(app)
|
||||
loadLibrary(app, force = true)
|
||||
}
|
||||
}
|
||||
|
||||
fun play(context: Context, game: GfnGame) {
|
||||
context.startActivity(Intent(context, GfnPlayerActivity::class.java)
|
||||
.apply { if (context !is android.app.Activity) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }
|
||||
.putExtra(GfnPlayerActivity.EXTRA_APP_ID, game.id)
|
||||
.putExtra(GfnPlayerActivity.EXTRA_VARIANT_ID, game.variantId)
|
||||
.putExtra(GfnPlayerActivity.EXTRA_TITLE, game.title))
|
||||
}
|
||||
|
||||
/** OpenNOW's own rule for which action a connected-store row offers. */
|
||||
fun actionFor(account: GfnStoreAccount): String = when {
|
||||
account.canLink && (!account.connected || account.status == "expired" ||
|
||||
(account.syncState == "SYNC_DENIED" && account.provider != "STEAM")) -> "link"
|
||||
account.canSync -> "sync"
|
||||
account.connected && account.canLink -> "unlink"
|
||||
else -> "none"
|
||||
}
|
||||
|
||||
private fun loadSignedIn(context: Context): Phase = runCatching {
|
||||
val auth = GfnCore.request(context, "auth.session.get")
|
||||
val user = auth.optJSONObject("session")?.optJSONObject("user") ?: auth.optJSONObject("user")
|
||||
if (user == null || user.optString("userId").isEmpty()) return Phase.SignedOut()
|
||||
Phase.SignedIn(user.optString("displayName").ifEmpty { "Signed in" })
|
||||
}.getOrElse { Phase.Failed(it.message ?: "GeForce NOW could not start.") }
|
||||
|
||||
private fun startSignIn(context: Context): Phase.Code {
|
||||
val challenge = GfnCore.request(context, "auth.device.start")
|
||||
return Phase.Code(
|
||||
userCode = challenge.optString("userCode"),
|
||||
url = challenge.optString("verificationUriComplete").ifEmpty { challenge.optString("verificationUri") },
|
||||
attemptId = challenge.optString("attemptId"),
|
||||
intervalMs = (challenge.optDouble("intervalSeconds", 5.0) * 1000).toLong().coerceAtLeast(1000))
|
||||
}
|
||||
|
||||
private suspend fun waitForSignIn(context: Context, code: Phase.Code): Phase {
|
||||
var interval = code.intervalMs
|
||||
while (true) {
|
||||
delay(interval)
|
||||
val poll = withContext(Dispatchers.IO) {
|
||||
runCatching { GfnCore.request(context, "auth.device.poll", JSONObject().put("attemptId", code.attemptId)) }
|
||||
}.getOrElse { return Phase.SignedOut(it.message) }
|
||||
when (poll.optString("status")) {
|
||||
"authorized" -> {
|
||||
withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
GfnCore.request(context, "auth.device.complete",
|
||||
JSONObject().put("attemptId", code.attemptId).put("staySignedIn", true))
|
||||
}
|
||||
}.onFailure { return Phase.SignedOut(it.message) }
|
||||
clearAccountData()
|
||||
return withContext(Dispatchers.IO) { loadSignedIn(context) }
|
||||
}
|
||||
"pending", "slow_down" -> interval = poll.optLong("retryAfterMs",
|
||||
(poll.optDouble("intervalSeconds", interval / 1000.0) * 1000).toLong()).coerceAtLeast(1000)
|
||||
else -> return Phase.SignedOut(poll.optString("message").ifEmpty { "Sign-in did not finish. Try again." })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class Page(val games: List<GfnGame>, val next: String, val more: Boolean, val total: Int)
|
||||
|
||||
/** Browsing reads the core's local copy of the catalog, which grows a page at a time; a search asks NVIDIA. */
|
||||
private fun storePage(context: Context, cursor: String, query: String): Page {
|
||||
val params = JSONObject().put("limit", 40).put("cursor", cursor).put("searchQuery", query)
|
||||
if (query.isEmpty()) params.put("genre", "").put("store", "").put("categoryId", "").put("refresh", false)
|
||||
val result = GfnCore.request(context, if (query.isEmpty()) "catalog.store.local" else "catalog.store.list", params, timeoutMs = 60_000)
|
||||
val games = gamesOf(result)
|
||||
return Page(games, result.optString("nextCursor"), result.optBoolean("hasNextPage") && result.optString("nextCursor").isNotEmpty(),
|
||||
result.optInt("totalCount", games.size))
|
||||
}
|
||||
|
||||
/** Pages of 50 keep each answer well under the binder transaction limit. */
|
||||
private fun libraryGames(context: Context): List<GfnGame> {
|
||||
val games = LinkedHashMap<String, GfnGame>()
|
||||
val traversal = System.currentTimeMillis().toString()
|
||||
var cursor = ""
|
||||
var revision: Any? = null
|
||||
var catalogContext = ""
|
||||
repeat(100) {
|
||||
val params = JSONObject().put("limit", 50).put("cursor", cursor).put("traversalId", traversal)
|
||||
.put("catalogRevision", revision ?: JSONObject.NULL).put("catalogContext", catalogContext)
|
||||
val page = GfnCore.request(context, "catalog.library.list", params, timeoutMs = 60_000)
|
||||
gamesOf(page).forEach { games.putIfAbsent(it.id, it.copy(inLibrary = true)) }
|
||||
revision = page.opt("catalogRevision")
|
||||
catalogContext = page.optString("catalogContext")
|
||||
cursor = page.optString("nextCursor")
|
||||
if (!page.optBoolean("hasNextPage") || cursor.isEmpty()) return games.values.toList()
|
||||
}
|
||||
return games.values.toList()
|
||||
}
|
||||
|
||||
private fun gamesOf(result: JSONObject): List<GfnGame> {
|
||||
val list = result.optJSONArray("games") ?: return emptyList()
|
||||
return (0 until list.length()).mapNotNull { index ->
|
||||
val game = list.optJSONObject(index) ?: return@mapNotNull null
|
||||
val variants = game.optJSONArray("variants")
|
||||
val variant = variants?.optJSONObject(game.optInt("selectedVariantIndex", 0).coerceIn(0, (variants.length() - 1).coerceAtLeast(0)))
|
||||
GfnGame(id = game.optString("id"),
|
||||
variantId = variant?.optString("id").orEmpty().ifEmpty { game.optString("launchAppId") },
|
||||
title = game.optString("title"),
|
||||
store = storeLabel(variant?.optString("store").orEmpty()),
|
||||
imageUrl = game.optString("imageUrl"),
|
||||
inLibrary = game.optBoolean("isInLibrary") || variant?.optBoolean("inLibrary") == true,
|
||||
search = game.optString("searchText").ifEmpty { game.optString("title").lowercase() })
|
||||
}.filter { it.id.isNotEmpty() && it.variantId.isNotEmpty() }
|
||||
}
|
||||
|
||||
private fun storeLabel(store: String): String = when (store.uppercase()) {
|
||||
"STEAM" -> "Steam"
|
||||
"EPIC" -> "Epic"
|
||||
"XBOX" -> "Xbox"
|
||||
"BATTLENET" -> "Battle.net"
|
||||
"UPLAY", "UBISOFT" -> "Ubisoft"
|
||||
"GOG" -> "GOG"
|
||||
"EA_APP", "EA", "ORIGIN" -> "EA"
|
||||
"GAIJIN" -> "Gaijin"
|
||||
else -> store.lowercase().replaceFirstChar { it.uppercase() }
|
||||
}
|
||||
|
||||
private fun storeAccounts(context: Context): List<GfnStoreAccount> {
|
||||
val list = GfnCore.request(context, "account.connections.list").optJSONArray("accounts") ?: return emptyList()
|
||||
return (0 until list.length()).mapNotNull { index ->
|
||||
val account = list.optJSONObject(index) ?: return@mapNotNull null
|
||||
if (account.optString("provider") in setOf("", "UNKNOWN", "NONE", "NVIDIA")) return@mapNotNull null
|
||||
GfnStoreAccount(provider = account.optString("provider"), label = account.optString("label").ifEmpty { account.optString("provider") },
|
||||
displayName = account.optString("displayName"),
|
||||
connected = account.optBoolean("isConnected") || account.optString("status") == "connected",
|
||||
status = account.optString("status"), syncState = account.optString("syncState"),
|
||||
canLink = account.optBoolean("supportsLinking"), canSync = account.optBoolean("supportsSync"))
|
||||
}.filter { it.canLink || it.canSync || it.connected }
|
||||
}
|
||||
|
||||
private suspend fun linkStore(context: Context, account: GfnStoreAccount): String {
|
||||
val attempt = withContext(Dispatchers.IO) {
|
||||
GfnCore.request(context, "account.connections.link.start", JSONObject().put("provider", account.provider))
|
||||
}
|
||||
val url = attempt.optString("loginUrl")
|
||||
if (url.isNotEmpty()) runCatching {
|
||||
context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
}
|
||||
repeat(150) {
|
||||
delay(2_000)
|
||||
val poll = withContext(Dispatchers.IO) {
|
||||
GfnCore.request(context, "account.connections.link.poll",
|
||||
JSONObject().put("attemptId", attempt.optString("attemptId")), timeoutMs = 10_000)
|
||||
}
|
||||
when (poll.optString("status")) {
|
||||
"pending" -> {}
|
||||
"complete" -> return "${account.label} connected."
|
||||
else -> return poll.optString("message").ifEmpty { "${account.label} was not connected." }
|
||||
}
|
||||
}
|
||||
return "Stopped waiting for ${account.label}. Finish signing in, then refresh."
|
||||
}
|
||||
|
||||
private suspend fun syncStore(context: Context, account: GfnStoreAccount): String = withContext(Dispatchers.IO) {
|
||||
var state = GfnCore.request(context, "account.connections.sync", JSONObject().put("provider", account.provider))
|
||||
val operation = state.optString("operationId")
|
||||
if (operation.isEmpty()) return@withContext state.optString("message").ifEmpty { "${account.label} synced." }
|
||||
repeat(90) {
|
||||
when (state.optString("phase")) {
|
||||
"waiting_remote", "starting" -> {
|
||||
delay(state.optLong("retryAfterMs", 2_000).coerceAtLeast(2_000))
|
||||
state = GfnCore.request(context, "account.connections.sync.status", JSONObject().put("operationId", operation))
|
||||
}
|
||||
"refreshing_library" -> {
|
||||
runCatching { libraryGames(context) }
|
||||
runCatching {
|
||||
GfnCore.request(context, "account.connections.sync.status",
|
||||
JSONObject().put("operationId", operation).put("libraryRefreshed", true), timeoutMs = 10_000)
|
||||
}
|
||||
return@withContext "${account.label} synced. Your library is up to date."
|
||||
}
|
||||
"timed_out" -> return@withContext "The sync could not be confirmed. ${account.label} may still finish; refresh later."
|
||||
else -> return@withContext "${account.label} could not finish the sync. Try again."
|
||||
}
|
||||
}
|
||||
"Still waiting for ${account.label}; refresh later."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.droiddeck.launcher.stores.gfn
|
||||
|
||||
import android.view.Surface
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
/**
|
||||
* OpenNOW's native streamer engine (external/opennow, MIT, by Zortos) inside libdroiddeckgfn.so,
|
||||
* with DroidDeck's Android media backend: MediaCodec onto [setSurface]'s Surface, AAudio sound.
|
||||
* Commands are the engine's JSON protocol (`hello`, `start`, `stop`, ...); answers and events
|
||||
* arrive on [onMessage] from a polling thread.
|
||||
*/
|
||||
class GfnStreamer(private val onMessage: (JSONObject) -> Unit) {
|
||||
private var handle = nativeOpen()
|
||||
private val ids = AtomicLong(1)
|
||||
@Volatile private var open = true
|
||||
private val poller = Thread({
|
||||
while (open) {
|
||||
val line = nativePoll(handle, 250) ?: continue
|
||||
runCatching { JSONObject(line) }.getOrNull()?.let { message -> runCatching { onMessage(message) } }
|
||||
}
|
||||
}, "gfn-streamer-poll").apply { isDaemon = true; start() }
|
||||
|
||||
/** Sends one command; returns its id (responses carry it), or "" if the engine is closed. */
|
||||
fun send(type: String, fields: JSONObject = JSONObject()): String {
|
||||
if (!open) return ""
|
||||
val id = "dd-" + ids.getAndIncrement()
|
||||
fields.put("id", id).put("type", type)
|
||||
return if (nativeCommand(handle, fields.toString())) id else ""
|
||||
}
|
||||
|
||||
fun gamepad(slot: Int, connected: Int, buttons: Int, leftTrigger: Int, rightTrigger: Int,
|
||||
leftX: Int, leftY: Int, rightX: Int, rightY: Int) {
|
||||
if (open) nativeGamepad(handle, slot, connected, buttons, leftTrigger, rightTrigger, leftX, leftY, rightX, rightY)
|
||||
}
|
||||
|
||||
fun key(virtualKey: Int, modifiers: Int, pressed: Boolean) {
|
||||
if (open) nativeKey(handle, virtualKey, modifiers, pressed)
|
||||
}
|
||||
|
||||
fun close() {
|
||||
if (!open) return
|
||||
open = false
|
||||
poller.join(1_000)
|
||||
nativeClose(handle)
|
||||
handle = 0
|
||||
}
|
||||
|
||||
companion object {
|
||||
init { System.loadLibrary("droiddeckgfn") }
|
||||
|
||||
@JvmStatic fun setSurface(surface: Surface?) = nativeSetSurface(surface)
|
||||
|
||||
@JvmStatic private external fun nativeOpen(): Long
|
||||
@JvmStatic private external fun nativeCommand(handle: Long, json: String): Boolean
|
||||
@JvmStatic private external fun nativePoll(handle: Long, timeoutMs: Int): String?
|
||||
@JvmStatic private external fun nativeClose(handle: Long)
|
||||
@JvmStatic private external fun nativeSetSurface(surface: Surface?)
|
||||
@JvmStatic private external fun nativeGamepad(handle: Long, slot: Int, connected: Int, buttons: Int,
|
||||
leftTrigger: Int, rightTrigger: Int,
|
||||
leftX: Int, leftY: Int, rightX: Int, rightY: Int)
|
||||
@JvmStatic private external fun nativeKey(handle: Long, virtualKey: Int, modifiers: Int, pressed: Boolean)
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.droiddeck.launcher.stores.xbox
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.ui.focusGlide
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
@@ -45,7 +47,7 @@ class XboxCloudSettingsActivity : ComponentActivity() {
|
||||
}
|
||||
Column(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background).verticalScroll(rememberScrollState())) {
|
||||
Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
OutlinedButton(onClick = { finish() }) { Text("Back") }
|
||||
OutlinedButton(onClick = { finish() }, modifier = Modifier.focusGlide(CircleShape)) { Text("Back") }
|
||||
Text("Xbox Cloud Gaming", style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.onBackground, modifier = Modifier.padding(horizontal = 16.dp))
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
package com.droiddeck.launcher.stores.xbox
|
||||
|
||||
import com.droiddeck.launcher.ui.glideBorder
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.ui.focusGlide
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
@@ -16,7 +19,6 @@ import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.gestures.detectTapGestures
|
||||
@@ -148,7 +150,7 @@ private fun PanelContent(
|
||||
Toggle("Toon", "Cartoon outlines.", settings.toon) { onChange(settings.copy(toon = it)) }
|
||||
Choice("Frame-rate cap", listOf(0 to "Off", 30 to "30 fps", 45 to "45 fps", 60 to "60 fps"), settings.maxFps) { onChange(settings.copy(maxFps = it)) }
|
||||
Row(Modifier.fillMaxWidth().padding(top = 6.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
OutlinedButton(onClick = { onChange(settings.withoutEffects()) }) { Text("Reset picture") }
|
||||
OutlinedButton(onClick = { onChange(settings.withoutEffects()) }, modifier = Modifier.focusGlide(CircleShape)) { Text("Reset picture") }
|
||||
}
|
||||
Text("Effects cost a little GPU time; with none set the stream is shown directly.", style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 4.dp))
|
||||
@@ -220,7 +222,7 @@ private fun SettingRow(
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(vertical = 1.dp).clip(shape)
|
||||
.background(if (focused) cs.primary.copy(alpha = 0.16f) else Color.Transparent)
|
||||
.border(2.dp, if (focused) cs.primary else Color.Transparent, shape)
|
||||
.glideBorder(focused, shape, cs.primary, hotFillAlpha = 0f)
|
||||
.let { if (panel != null && index >= 0) it.focusRequester(panel.requester(index)) else it }
|
||||
.onFocusChanged { state -> focused = state.isFocused; if (state.isFocused && index >= 0) panel?.onFocused?.invoke(index) }
|
||||
.onKeyEvent { event ->
|
||||
@@ -299,8 +301,9 @@ internal fun XboxMenuEntry(title: String, note: String?, focus: FocusRequester?
|
||||
val shape = RoundedCornerShape(10.dp)
|
||||
androidx.compose.material3.Surface(
|
||||
onClick = onClick, color = if (focused) cs.primary.copy(alpha = 0.2f) else cs.surfaceContainerHigh, shape = shape,
|
||||
border = if (focused) androidx.compose.foundation.BorderStroke(2.dp, cs.primary) else null,
|
||||
border = null,
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 3.dp)
|
||||
.glideBorder(focused, shape, cs.primary, hotFillAlpha = 0f)
|
||||
.let { if (focus != null) it.focusRequester(focus) else it }
|
||||
.onFocusChanged { state -> focused = state.isFocused; if (state.isFocused) onFocused() }
|
||||
.onKeyEvent { event -> if (event.type == KeyEventType.KeyDown && event.key == Key.ButtonA) { onClick(); true } else false },
|
||||
|
||||
@@ -36,6 +36,7 @@ class XboxLoginActivity : ComponentActivity() {
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
||||
host = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; setBackgroundColor(Color.BLACK) }
|
||||
status = TextView(this).apply { setTextColor(Color.WHITE); text = "Preparing Microsoft sign-in…"; setPadding(24, 16, 24, 16) }
|
||||
host.addView(status)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.droiddeck.launcher.stores.xbox
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.ui.focusGlide
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.graphics.Color
|
||||
@@ -181,10 +183,10 @@ class XboxNativePlayerActivity : ComponentActivity() {
|
||||
fun NoticeButton(label: String, focus: androidx.compose.ui.focus.FocusRequester?, onClick: () -> Unit) =
|
||||
androidx.compose.material3.TextButton(onClick = onClick,
|
||||
modifier = androidx.compose.ui.Modifier.let { if (focus != null) it.focusRequester(focus) else it }
|
||||
.onKeyEvent { e -> if (e.type == KeyEventType.KeyDown && e.key == Key.ButtonA) { onClick(); true } else false }) {
|
||||
.onKeyEvent { e -> if (e.type == KeyEventType.KeyDown && e.key == Key.ButtonA) { onClick(); true } else false }.focusGlide(CircleShape)) {
|
||||
androidx.compose.material3.Text(label)
|
||||
}
|
||||
androidx.compose.material3.AlertDialog(
|
||||
com.droiddeck.launcher.ui.GlideAlertDialog(
|
||||
onDismissRequest = { finish() },
|
||||
properties = androidx.compose.ui.window.DialogProperties(dismissOnClickOutside = false),
|
||||
title = { androidx.compose.material3.Text(title) },
|
||||
|
||||
@@ -88,7 +88,7 @@ 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 androidx.compose.ui.window.Dialog
|
||||
import com.droiddeck.launcher.ui.GlideDialog as Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import coil.compose.AsyncImage
|
||||
import coil.request.ImageRequest
|
||||
|
||||
@@ -475,7 +475,7 @@ internal fun TextEntryDialog(title: String, initial: String, onDismiss: () -> Un
|
||||
AppDialog(shown, close, "textEntry", wide = false, maxWidth = 460.dp) {
|
||||
DialogTitleRow(title, onClose = close)
|
||||
androidx.compose.material3.OutlinedTextField(
|
||||
value, { value = it }, singleLine = true, modifier = Modifier.fillMaxWidth().focusRequester(focus),
|
||||
value, { value = it }, singleLine = true, modifier = Modifier.fillMaxWidth().focusRequester(focus).focusGlide(),
|
||||
keyboardActions = androidx.compose.foundation.text.KeyboardActions(onDone = { onSave(value.trim()); close() }),
|
||||
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(imeAction = androidx.compose.ui.text.input.ImeAction.Done),
|
||||
)
|
||||
@@ -644,7 +644,7 @@ private fun SgdbSearchDialog(
|
||||
SmallIconButton(Icons.AutoMirrored.Filled.ArrowBack, stringResource(R.string.common_back), colors.onBackground, onClick = back)
|
||||
})
|
||||
androidx.compose.material3.OutlinedTextField(
|
||||
query, { query = it }, singleLine = true, modifier = Modifier.fillMaxWidth(),
|
||||
query, { query = it }, singleLine = true, modifier = Modifier.fillMaxWidth().focusGlide(),
|
||||
label = { Text(stringResource(R.string.art_sgdb_search_label)) },
|
||||
keyboardActions = androidx.compose.foundation.text.KeyboardActions(onSearch = { leaveField(); search() }),
|
||||
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(imeAction = androidx.compose.ui.text.input.ImeAction.Search),
|
||||
|
||||
@@ -308,12 +308,12 @@ private fun InstalledMoviesDialog(a: ModeSettingsActions, onDismiss: () -> Unit)
|
||||
|
||||
@Composable
|
||||
private fun RemoveMovieDialog(entry: BootMovieLibrary.Entry, onConfirm: () -> Unit, onDismiss: () -> Unit) {
|
||||
androidx.compose.material3.AlertDialog(
|
||||
com.droiddeck.launcher.ui.GlideAlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(stringResource(R.string.boot_movie_remove_confirm, entry.title)) },
|
||||
text = { Text(stringResource(R.string.boot_movie_remove_confirm_body)) },
|
||||
confirmButton = { androidx.compose.material3.TextButton(onClick = onConfirm) { Text(stringResource(R.string.boot_movie_remove)) } },
|
||||
dismissButton = { androidx.compose.material3.TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } },
|
||||
confirmButton = { androidx.compose.material3.TextButton(onClick = onConfirm, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.boot_movie_remove)) } },
|
||||
dismissButton = { androidx.compose.material3.TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Delete
|
||||
import androidx.compose.material.icons.outlined.Refresh
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
|
||||
@@ -37,10 +37,12 @@ class DeckControlsPanel(
|
||||
private val onSteamMenu: () -> Unit,
|
||||
private val onQam: () -> Unit,
|
||||
private val pad: PadBridge? = null,
|
||||
private val portraitDock: Boolean = false,
|
||||
) : LinearLayout(context) {
|
||||
private enum class Tab(val label: Int) { GAMEPAD(R.string.deck_tab_gamepad), GRIPS(R.string.deck_tab_grips), LEFT(R.string.deck_tab_left), RIGHT(R.string.deck_tab_right), BOTH(R.string.deck_tab_both) }
|
||||
|
||||
private val content = FrameLayout(context)
|
||||
val deckControls = pad == null || SessionState.deckPad
|
||||
private val tabViews = HashMap<Tab, TextView>()
|
||||
private val topBar: View by lazy { topBar() }
|
||||
|
||||
@@ -49,7 +51,7 @@ class DeckControlsPanel(
|
||||
setBackgroundColor(Color.BLACK)
|
||||
addView(topBar, LayoutParams(LayoutParams.MATCH_PARENT, dp(64)))
|
||||
addView(content, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f))
|
||||
select(if (pad != null) selectedWithPad else selected)
|
||||
select(if (pad != null && !deckControls) Tab.GAMEPAD else if (pad != null) selectedWithPad else selected)
|
||||
}
|
||||
|
||||
override fun onDetachedFromWindow() {
|
||||
@@ -67,6 +69,7 @@ class DeckControlsPanel(
|
||||
background = outline(CORNER_PILL, SURFACE)
|
||||
setPadding(dp(4), dp(4), dp(4), dp(4))
|
||||
for (tab in Tab.values()) {
|
||||
if (!deckControls && tab != Tab.GAMEPAD) continue
|
||||
if (tab == Tab.GAMEPAD && pad == null) continue
|
||||
val view = TextView(context).apply {
|
||||
text = context.getString(tab.label)
|
||||
@@ -170,7 +173,7 @@ class DeckControlsPanel(
|
||||
addView(grips, LayoutParams(LayoutParams.MATCH_PARENT, dp(84)))
|
||||
}
|
||||
|
||||
private fun gamepad(pad: PadBridge): View = GamepadLayout(context).apply {
|
||||
private fun gamepad(pad: PadBridge): View = GamepadLayout(context, portraitDock).apply {
|
||||
fun pill(label: String, write: (PadState, Boolean) -> Unit) = PadButton(context, pad, label, write)
|
||||
place(surfaceSlot(pad, right = false), GamepadGeometry.Slot.LEFT_MAIN)
|
||||
place(DirectionPad(context, pad), GamepadGeometry.Slot.LEFT_SECOND)
|
||||
@@ -186,14 +189,22 @@ class DeckControlsPanel(
|
||||
place(centreTap("\u2022\u2022\u2022", context.getString(R.string.drawer_open_qam), onQam), GamepadGeometry.Slot.QAM)
|
||||
}
|
||||
place(pill("MENU") { st, d -> st.press(PadState.START, d) }, GamepadGeometry.Slot.MENU)
|
||||
place(centreTap("\u25a6 " + context.getString(R.string.deck_panels), context.getString(R.string.deck_more_controls)) { select(Tab.BOTH) },
|
||||
if (deckControls) place(centreTap("\u25a6 " + context.getString(R.string.deck_panels), context.getString(R.string.deck_more_controls)) { select(Tab.BOTH) },
|
||||
GamepadGeometry.Slot.PANELS)
|
||||
if (portraitDock && deckControls) {
|
||||
place(GripButton(context, "L4", null, DeckControls.L4), GamepadGeometry.Slot.L4)
|
||||
place(GripButton(context, "L5", null, DeckControls.L5), GamepadGeometry.Slot.L5)
|
||||
place(GripButton(context, "R5", null, DeckControls.R5), GamepadGeometry.Slot.R5)
|
||||
place(GripButton(context, "R4", null, DeckControls.R4), GamepadGeometry.Slot.R4)
|
||||
}
|
||||
}
|
||||
|
||||
private fun centreTap(label: String, description: String, onClick: () -> Unit) = TextView(context).apply {
|
||||
text = label
|
||||
contentDescription = description
|
||||
textSize = 13f
|
||||
maxLines = 1
|
||||
setAutoSizeTextTypeUniformWithConfiguration(9, 13, 1, android.util.TypedValue.COMPLEX_UNIT_SP)
|
||||
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
|
||||
letterSpacing = 0.08f
|
||||
gravity = Gravity.CENTER
|
||||
@@ -206,6 +217,11 @@ class DeckControlsPanel(
|
||||
}
|
||||
|
||||
private fun surfaceSlot(pad: PadBridge, right: Boolean): View = FrameLayout(context).apply {
|
||||
if (!deckControls) {
|
||||
addView(StickView(context, pad, right),
|
||||
FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT))
|
||||
return@apply
|
||||
}
|
||||
val slot = this
|
||||
fun show() {
|
||||
slot.removeAllViews()
|
||||
@@ -617,7 +633,7 @@ class DeckControlsPanel(
|
||||
}
|
||||
}
|
||||
|
||||
private class GamepadLayout(context: Context) : ViewGroup(context) {
|
||||
private class GamepadLayout(context: Context, private val portraitDock: Boolean) : ViewGroup(context) {
|
||||
private val slots = LinkedHashMap<View, GamepadGeometry.Slot>()
|
||||
|
||||
fun place(view: View, slot: GamepadGeometry.Slot) {
|
||||
@@ -625,7 +641,7 @@ class DeckControlsPanel(
|
||||
addView(view)
|
||||
}
|
||||
|
||||
private fun boxes(w: Int, h: Int) = GamepadGeometry.layout(w.toFloat(), h.toFloat(), resources.displayMetrics.density)
|
||||
private fun boxes(w: Int, h: Int) = GamepadGeometry.layout(w.toFloat(), h.toFloat(), resources.displayMetrics.density, portraitDock)
|
||||
|
||||
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
|
||||
val w = MeasureSpec.getSize(widthMeasureSpec)
|
||||
|
||||
@@ -31,7 +31,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Delete
|
||||
import androidx.compose.material.icons.outlined.Refresh
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
|
||||
@@ -11,6 +11,7 @@ import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableFloatStateOf
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
@@ -23,6 +24,7 @@ import androidx.compose.runtime.withFrameNanos
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.drawWithContent
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.geometry.CornerRadius
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Rect
|
||||
@@ -54,10 +56,21 @@ internal class GlideSource {
|
||||
var shape: Shape by mutableStateOf<Shape>(androidx.compose.ui.graphics.RectangleShape)
|
||||
var color by mutableStateOf(Color.Transparent)
|
||||
var width by mutableStateOf(2.dp)
|
||||
var fillAlpha by mutableFloatStateOf(RING_FILL)
|
||||
val requester = androidx.compose.ui.focus.FocusRequester()
|
||||
}
|
||||
|
||||
internal class FocusGlide(val view: View) {
|
||||
internal class FocusGlide(view: View?) {
|
||||
private val deferredWindow = view == null
|
||||
var view = view
|
||||
private set
|
||||
|
||||
fun accepts(view: View): Boolean {
|
||||
// DropdownMenu recreates its popup view after closing.
|
||||
if (this.view == null || deferredWindow && this.view !== view && host?.isAttached != true) this.view = view
|
||||
return this.view === view
|
||||
}
|
||||
|
||||
var host: LayoutCoordinates? = null
|
||||
val hot = mutableStateListOf<GlideSource>()
|
||||
var moves by mutableIntStateOf(0)
|
||||
@@ -107,15 +120,17 @@ internal fun Modifier.glideBorder(
|
||||
restColor: Color = Color.Transparent,
|
||||
hotWidth: Dp = 2.dp,
|
||||
restWidth: Dp = 1.dp,
|
||||
hotFillAlpha: Float = RING_FILL,
|
||||
): Modifier {
|
||||
val glide = LocalFocusGlide.current
|
||||
if (glide == null || glide.view !== LocalView.current) {
|
||||
if (glide == null || !glide.accepts(LocalView.current)) {
|
||||
return border(if (hot) hotWidth else restWidth, if (hot) hotColor else restColor, shape)
|
||||
}
|
||||
val src = remember { GlideSource() }
|
||||
src.shape = shape
|
||||
src.color = hotColor
|
||||
src.width = hotWidth
|
||||
src.fillAlpha = hotFillAlpha
|
||||
DisposableEffect(glide, hot) {
|
||||
if (hot) glide.claim(src)
|
||||
onDispose { glide.release(src) }
|
||||
@@ -140,12 +155,36 @@ private const val REPEAT_MS = 180L
|
||||
|
||||
private val FAR = 360.dp
|
||||
|
||||
@Composable
|
||||
internal fun Modifier.focusGlide(
|
||||
shape: Shape = Shape12,
|
||||
color: Color = LocalPalette.current.signal,
|
||||
): Modifier {
|
||||
var focused by remember { mutableStateOf(false) }
|
||||
return glideBorder(focused, shape, color, hotFillAlpha = 0f)
|
||||
.onFocusChanged { focused = it.isFocused }
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable () -> Unit) {
|
||||
val view = LocalView.current
|
||||
val glide = remember(view) { FocusGlide(view) }
|
||||
Box(modifier.focusGlideOverlay(glide)) {
|
||||
CompositionLocalProvider(LocalFocusGlide provides glide) { content() }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun FocusGlideWindow(content: @Composable (Modifier) -> Unit) {
|
||||
val glide = remember { FocusGlide(null) }
|
||||
val overlay = Modifier.focusGlideOverlay(glide)
|
||||
CompositionLocalProvider(LocalFocusGlide provides glide) { content(overlay) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
|
||||
val density = LocalDensity.current
|
||||
val dir = LocalLayoutDirection.current
|
||||
val glide = remember(view) { FocusGlide(view) }
|
||||
val edges = remember { List(4) { Animatable(0f) } }
|
||||
val corner = remember { Animatable(0f) }
|
||||
val solid = remember { Animatable(0f) }
|
||||
@@ -162,6 +201,8 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
|
||||
val color by animateColorAsState(cur?.color ?: lastColor, Motion.tw(160), label = "glideColor")
|
||||
var width by remember { mutableStateOf(2.dp) }
|
||||
if (cur != null) width = cur.width
|
||||
var fillAlpha by remember { mutableFloatStateOf(RING_FILL) }
|
||||
if (cur != null) fillAlpha = cur.fillAlpha
|
||||
|
||||
LaunchedEffect(glide, Motion.scale) {
|
||||
var shown: GlideSource? = null
|
||||
@@ -339,8 +380,7 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
|
||||
}
|
||||
}
|
||||
|
||||
Box(
|
||||
modifier
|
||||
return this
|
||||
.onGloballyPositioned { glide.host = it }
|
||||
.drawWithContent {
|
||||
drawContent()
|
||||
@@ -359,15 +399,12 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
|
||||
if (f < 0.99f) {
|
||||
drawRoundRect(
|
||||
color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh),
|
||||
cornerRadius = CornerRadius(rad), alpha = a * (1f - f) * RING_FILL,
|
||||
cornerRadius = CornerRadius(rad), alpha = a * (1f - f) * fillAlpha,
|
||||
)
|
||||
drawRoundRect(
|
||||
color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh),
|
||||
cornerRadius = CornerRadius(rad), style = Stroke(w), alpha = a,
|
||||
)
|
||||
}
|
||||
},
|
||||
) {
|
||||
CompositionLocalProvider(LocalFocusGlide provides glide) { content() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,9 @@ 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.horizontalScroll
|
||||
import androidx.compose.foundation.relocation.BringIntoViewRequester
|
||||
import androidx.compose.foundation.relocation.bringIntoViewRequester
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Apps
|
||||
@@ -87,6 +90,40 @@ import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
|
||||
internal val AttentionAmber = Color(0xFFFFB547)
|
||||
|
||||
@Composable
|
||||
internal fun BottomBar(
|
||||
s: FrontEndState, selected: String,
|
||||
onSelect: (String) -> Unit, onFocusSelect: (String) -> Unit, a: FrontEndActions, modifier: Modifier,
|
||||
) {
|
||||
val shown = Hops.railPreview ?: selected
|
||||
val keys = navigationKeys(s)
|
||||
val bounds = remember { androidx.compose.runtime.mutableStateMapOf<String, androidx.compose.ui.geometry.Rect>() }
|
||||
val tint = androidx.compose.runtime.rememberUpdatedState(LocalPalette.current.signal)
|
||||
var barAt by remember { mutableStateOf(androidx.compose.ui.geometry.Offset.Zero) }
|
||||
Row(modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surface), verticalAlignment = Alignment.CenterVertically) {
|
||||
BoxWithConstraints(Modifier.weight(1f)) {
|
||||
val itemWidth = (maxWidth / keys.size).coerceIn(56.dp, 88.dp)
|
||||
Box(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).onGloballyPositioned { barAt = it.boundsInRoot().topLeft }) {
|
||||
if (shown in keys) ChipGlide(keys.indexOf(shown), bounds[shown]?.translate(-barAt), tint, GlideAxis.Horizontal, corner = 14.dp, fill = 0.14f, outline = 0f)
|
||||
Row(Modifier.selectableGroup().padding(vertical = 4.dp), horizontalArrangement = Arrangement.Center) {
|
||||
NavigationItems(s, shown, compact = true, iconOnly = false, height = 56.dp, width = itemWidth,
|
||||
place = { key -> Modifier.onGloballyPositioned { bounds[key] = it.boundsInRoot(); Hops.railBounds[key] = it.boundsInRoot() } },
|
||||
onSelect = onSelect, onFocusSelect = onFocusSelect)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (s.running != null) ResumeRailItem(s.running, compact = true, iconOnly = true, a.onResume)
|
||||
}
|
||||
}
|
||||
|
||||
private fun navigationKeys(s: FrontEndState) = buildList {
|
||||
add("steam"); add("games")
|
||||
if (s.gameStoresEnabled) add("stores")
|
||||
add("desktop"); add("components")
|
||||
if (s.isHomeApp) add("android-apps")
|
||||
add("setup"); add("updates")
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SideRail(
|
||||
s: FrontEndState, selected: String,
|
||||
@@ -95,8 +132,6 @@ internal fun SideRail(
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val compact = LocalConfiguration.current.screenHeightDp < 420
|
||||
val iconOnly = isNarrowScreen()
|
||||
val setupNeedsAttention = !s.ready || (s.available != null && s.available != s.installed) ||
|
||||
PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = modifier.width(if (iconOnly) 64.dp else 92.dp).background(colors.surface).padding(vertical = if (compact) 8.dp else 12.dp),
|
||||
@@ -105,14 +140,7 @@ internal fun SideRail(
|
||||
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) {
|
||||
val fit = (maxHeight / count - 4.dp).coerceIn(44.dp, if (iconOnly) 48.dp else if (compact) 52.dp else 60.dp)
|
||||
val shown = Hops.railPreview ?: selected
|
||||
val keys = buildList {
|
||||
add("steam"); add("games")
|
||||
if (s.gameStoresEnabled) add("stores")
|
||||
add("desktop")
|
||||
add("components")
|
||||
if (s.isHomeApp) add("android-apps")
|
||||
add("setup"); add("updates")
|
||||
}
|
||||
val keys = navigationKeys(s)
|
||||
val bounds = remember { androidx.compose.runtime.mutableStateMapOf<String, androidx.compose.ui.geometry.Rect>() }
|
||||
val tint = androidx.compose.runtime.rememberUpdatedState(LocalPalette.current.signal)
|
||||
var railAt by remember { mutableStateOf(androidx.compose.ui.geometry.Offset.Zero) }
|
||||
@@ -129,14 +157,7 @@ internal fun SideRail(
|
||||
Hops.railBounds[key] = it.boundsInRoot()
|
||||
}
|
||||
}
|
||||
RailItem(stringResource(R.string.rail_steam), Icons.Outlined.SportsEsports, "steam", shown == "steam", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("steam") }) { onSelect("steam") }
|
||||
RailItem(stringResource(R.string.rail_games), Icons.Outlined.VideoLibrary, "games", shown == "games", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("games") }) { onSelect("games") }
|
||||
if (s.gameStoresEnabled) RailItem(stringResource(R.string.rail_stores), Icons.Outlined.LocalMall, "stores", shown == "stores", compact, iconOnly, fit, count = s.storeDownloadsActive, place = place, onFocus = { onFocusSelect("stores") }) { onSelect("stores") }
|
||||
RailItem(stringResource(R.string.rail_desktop), Icons.Outlined.DesktopWindows, "desktop", shown == "desktop", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("desktop") }) { onSelect("desktop") }
|
||||
RailItem(stringResource(R.string.rail_components), Icons.Outlined.Layers, "components", shown == "components", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("components") }) { onSelect("components") }
|
||||
if (s.isHomeApp) RailItem(stringResource(R.string.rail_apps), Icons.Outlined.Apps, "android-apps", shown == "android-apps", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("android-apps") }) { onSelect("android-apps") }
|
||||
RailItem(stringResource(R.string.rail_setup), Icons.Outlined.Tune, "setup", shown == "setup", compact, iconOnly, fit, badge = setupNeedsAttention, place = place, onFocus = { onFocusSelect("setup") }) { onSelect("setup") }
|
||||
RailItem(stringResource(R.string.rail_updates), Icons.Outlined.SystemUpdate, "updates", shown == "updates", compact, iconOnly, fit, badge = s.updates.hasUpdate, place = place, onFocus = { onFocusSelect("updates") }) { onSelect("updates") }
|
||||
NavigationItems(s, shown, compact, iconOnly, fit, if (iconOnly) 52.dp else 80.dp, place, onSelect, onFocusSelect)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -151,8 +172,36 @@ internal fun SideRail(
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun NavigationItems(
|
||||
s: FrontEndState, shown: String, compact: Boolean, iconOnly: Boolean, height: Dp, width: Dp,
|
||||
place: (String) -> Modifier, onSelect: (String) -> Unit, onFocusSelect: (String) -> Unit,
|
||||
) {
|
||||
val setupNeedsAttention = !s.ready || (s.available != null && s.available != s.installed) ||
|
||||
PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
|
||||
for (key in navigationKeys(s)) {
|
||||
val (label, icon) = when (key) {
|
||||
"steam" -> R.string.rail_steam to Icons.Outlined.SportsEsports
|
||||
"games" -> R.string.rail_games to Icons.Outlined.VideoLibrary
|
||||
"stores" -> R.string.rail_stores to Icons.Outlined.LocalMall
|
||||
"desktop" -> R.string.rail_desktop to Icons.Outlined.DesktopWindows
|
||||
"components" -> R.string.rail_components to Icons.Outlined.Layers
|
||||
"android-apps" -> R.string.rail_apps to Icons.Outlined.Apps
|
||||
"setup" -> R.string.rail_setup to Icons.Outlined.Tune
|
||||
else -> R.string.rail_updates to Icons.Outlined.SystemUpdate
|
||||
}
|
||||
key(key) {
|
||||
RailItem(stringResource(label), icon, key, shown == key, compact, iconOnly, height, width,
|
||||
badge = (key == "setup" && setupNeedsAttention) || (key == "updates" && s.updates.hasUpdate),
|
||||
count = if (key == "stores") s.storeDownloadsActive else 0,
|
||||
place = place, onFocus = { onFocusSelect(key) }) { onSelect(key) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
|
||||
private fun RailItem(
|
||||
label: String, icon: ImageVector, key: String, current: Boolean, compact: Boolean, iconOnly: Boolean, height: Dp,
|
||||
label: String, icon: ImageVector, key: String, current: Boolean, compact: Boolean, iconOnly: Boolean, height: Dp, width: Dp,
|
||||
badge: Boolean = false,
|
||||
count: Int = 0,
|
||||
place: (String) -> Modifier = { Modifier },
|
||||
@@ -181,6 +230,8 @@ private fun RailItem(
|
||||
Motion.tw(220), label = "railFill",
|
||||
)
|
||||
val scale by animateFloatAsState(if (pressed) 0.95f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "railScale")
|
||||
val bringIntoView = remember { BringIntoViewRequester() }
|
||||
LaunchedEffect(current) { if (current) bringIntoView.bringIntoView() }
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier
|
||||
@@ -189,7 +240,8 @@ private fun RailItem(
|
||||
.then(place(key))
|
||||
.landingPop(Hops.railLanded[key] ?: 0)
|
||||
.graphicsLayer { scaleX = scale; scaleY = scale }
|
||||
.size(width = if (iconOnly) 52.dp else 80.dp, height = height)
|
||||
.size(width = width, height = height)
|
||||
.bringIntoViewRequester(bringIntoView)
|
||||
.clip(Shape14)
|
||||
.background(fill)
|
||||
.glideBorder(focused, Shape14, pal.signal)
|
||||
|
||||
@@ -11,6 +11,7 @@ import androidx.compose.foundation.focusGroup
|
||||
import androidx.compose.ui.focus.focusProperties
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.FocusDirection
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import android.provider.Settings
|
||||
import android.view.Display
|
||||
@@ -138,6 +139,7 @@ class FrontEndState(
|
||||
val phantomProcessStatus: PhantomProcessStatus = PhantomProcessStatus.NOT_APPLICABLE,
|
||||
val showPhantomGate: Boolean = false,
|
||||
val orientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE,
|
||||
val launcherOrientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER,
|
||||
val launcherFullscreen: Boolean = true,
|
||||
val downloadSource: String = DownloadSource.MODE_AUTO,
|
||||
val downloadMirror: String = "",
|
||||
@@ -219,6 +221,7 @@ class FrontEndActions(
|
||||
val onAppScale: (Int) -> Unit = {},
|
||||
val onLauncherIcon: (String) -> Unit = {},
|
||||
val onOrientation: (Int) -> Unit = {},
|
||||
val onLauncherOrientation: (Int) -> Unit = {},
|
||||
val onLauncherFullscreen: (Boolean) -> Unit = {},
|
||||
val onAnimationsEnabled: (Boolean) -> Unit = {},
|
||||
val onDownloadSource: (String) -> Unit = {},
|
||||
@@ -265,12 +268,6 @@ internal object Motion {
|
||||
if (scale == 0f) snap() else spring(damping, stiffness)
|
||||
}
|
||||
|
||||
internal object Ambient {
|
||||
var poked by mutableStateOf(0L)
|
||||
private set
|
||||
fun poke() { poked = android.os.SystemClock.uptimeMillis() }
|
||||
}
|
||||
|
||||
private val Shape10 = RoundedCornerShape(10.dp)
|
||||
|
||||
internal val Shape12 = RoundedCornerShape(12.dp)
|
||||
@@ -392,7 +389,12 @@ internal suspend fun focusSoon(target: () -> FocusRequester) {
|
||||
@Composable
|
||||
fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)? = null) {
|
||||
val frontFocus = remember { FrontFocus() }
|
||||
CompositionLocalProvider(LocalFrontFocus provides frontFocus) { FrontEndScreenBody(s, a, page, frontFocus) }
|
||||
androidx.compose.foundation.layout.BoxWithConstraints(Modifier.fillMaxSize()) {
|
||||
CompositionLocalProvider(
|
||||
LocalFrontFocus provides frontFocus,
|
||||
LocalNarrowPane provides (maxWidth < NarrowPaneWidth),
|
||||
) { FrontEndScreenBody(s, a, page, frontFocus) }
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalComposeUiApi::class)
|
||||
@@ -492,11 +494,12 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
val window = LocalWindowInfo.current
|
||||
val androidContext = androidx.compose.ui.platform.LocalContext.current
|
||||
var anyFocused by remember { mutableStateOf(false) }
|
||||
Box(
|
||||
androidx.compose.foundation.layout.BoxWithConstraints(
|
||||
modifier = Modifier.fillMaxSize().background(colors.background)
|
||||
.windowInsetsPadding(if (s.launcherFullscreen) WindowInsets.displayCutout else WindowInsets.systemBars)
|
||||
.onFocusChanged { anyFocused = it.hasFocus },
|
||||
) {
|
||||
val bottomNavigation = maxHeight > maxWidth
|
||||
LaunchedEffect(processSettingsPageVisible) {
|
||||
if (processSettingsPageVisible) return@LaunchedEffect
|
||||
snapshotFlow { window.isWindowFocused }.first { it }
|
||||
@@ -533,10 +536,19 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
focusWithinFrames({ frontFocus.focusedRail == null && anyFocused }) { frontFocus.paneEntry() }
|
||||
}
|
||||
val paneFocus = Modifier
|
||||
.focusProperties { enter = { frontFocus.paneEntry() } }
|
||||
.focusProperties {
|
||||
enter = { frontFocus.paneEntry() }
|
||||
exit = { direction ->
|
||||
if (bottomNavigation && direction == FocusDirection.Down) frontFocus.railFor(railSelection)
|
||||
else FocusRequester.Default
|
||||
}
|
||||
}
|
||||
.focusGroup()
|
||||
val railFocus = Modifier
|
||||
.focusProperties { enter = { frontFocus.railFor(railSelection) } }
|
||||
.focusProperties {
|
||||
enter = { frontFocus.railFor(railSelection) }
|
||||
if (bottomNavigation) up = frontFocus.paneEntry()
|
||||
}
|
||||
.focusGroup()
|
||||
LaunchedEffect(Hops.restore) {
|
||||
val r = Hops.restore ?: return@LaunchedEffect
|
||||
@@ -550,12 +562,16 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
}
|
||||
var screenAt by remember { mutableStateOf(Offset.Zero) }
|
||||
CompositionLocalProvider(LocalShowSection provides { key -> selected = key }) {
|
||||
Row(modifier = Modifier.fillMaxSize().onGloballyPositioned { screenAt = it.positionInRoot() }) {
|
||||
SideRail(s, railSelection, onRailSelect, onRailFocus, a, railFocus.fillMaxHeight())
|
||||
Box(Modifier.width(1.dp).fillMaxHeight().background(pal.line))
|
||||
Column(modifier = Modifier.weight(1f).fillMaxHeight()) {
|
||||
LauncherLayout(
|
||||
bottomNavigation, pal.line,
|
||||
Modifier.fillMaxSize().onGloballyPositioned { screenAt = it.positionInRoot() },
|
||||
navigation = {
|
||||
if (bottomNavigation) BottomBar(s, railSelection, onRailSelect, onRailFocus, a, railFocus)
|
||||
else SideRail(s, railSelection, onRailSelect, onRailFocus, a, railFocus.fillMaxHeight())
|
||||
},
|
||||
) {
|
||||
Pane(
|
||||
s, selected, a, page, Modifier.weight(1f).fillMaxWidth().then(paneFocus), { selected = it },
|
||||
s, selected, a, page, Modifier.fillMaxSize().then(paneFocus), { selected = it },
|
||||
onAndroidAppClick = { app ->
|
||||
if (s.secondScreenDisplays.isEmpty()) a.onAndroidApp(app, null)
|
||||
else appToChooseDisplay = app
|
||||
@@ -563,12 +579,12 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
onOpenDeveloperOptions = requestDeveloperOptions,
|
||||
onRequestWirelessAdb = requestWirelessAdbFix,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
FlightsLayer(screenAt)
|
||||
GamesDialogs(a, s.steamGames)
|
||||
StoreTheme(com.droiddeck.launcher.stores.Store.XBOX) { XboxStoreDialogs() }
|
||||
com.droiddeck.launcher.stores.StoresState.pendingInstall?.let { item -> StoreTheme(item.store) { InstallWhere(item) } }
|
||||
com.droiddeck.launcher.stores.StoresState.itchPicking?.let { item -> StoreTheme(item.store) { ItchBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.itchPicking = null } } }
|
||||
StepsLayer(screenAt)
|
||||
|
||||
@@ -398,7 +398,12 @@ internal fun SetupPanel(
|
||||
ActionRow(stringResource(R.string.setup_default_home), s.defaultHomeLabel ?: stringResource(R.string.setup_choose_home), stringResource(R.string.setup_choose), a.onHomeApp)
|
||||
}
|
||||
ChoiceRow(
|
||||
host, "orientation", stringResource(R.string.setup_orientation), null,
|
||||
host, "launcher-orientation", stringResource(R.string.setup_launcher_orientation), null,
|
||||
com.droiddeck.launcher.core.AppUiPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) },
|
||||
s.launcherOrientation, onPick = a.onLauncherOrientation,
|
||||
)
|
||||
ChoiceRow(
|
||||
host, "orientation", stringResource(R.string.setup_session_orientation), stringResource(R.string.setup_session_orientation_hint),
|
||||
SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) },
|
||||
s.orientation, onPick = a.onOrientation,
|
||||
)
|
||||
|
||||
@@ -186,7 +186,7 @@ internal fun PrimaryButton(
|
||||
.clip(Shape12)
|
||||
.background(if (enabled) Brush.linearGradient(listOf(colors.primary, pal.primary2)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surfaceVariant)))
|
||||
.then(if (enabled) Modifier else Modifier.border(1.dp, pal.line2, Shape12))
|
||||
.then(if (hot) Modifier.border(2.dp, pal.signal, Shape12) else Modifier)
|
||||
.glideBorder(hot, Shape12, pal.signal, hotFillAlpha = 0f)
|
||||
.hoverable(src).clickable(role = Role.Button, interactionSource = src, indication = null, enabled = enabled) {
|
||||
placed[0]?.takeIf { it.isAttached }?.let { LaunchOrigin.mark(it.boundsInRoot(), placed) }
|
||||
onClick()
|
||||
|
||||
@@ -56,6 +56,7 @@ import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.layout.boundsInRoot
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.layout.positionInRoot
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
@@ -86,6 +87,7 @@ import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.StoreLanguage
|
||||
import com.droiddeck.launcher.stores.StoreSizes
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.battlenet.BattleNetInstall
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadState
|
||||
import com.droiddeck.launcher.stores.formatBytes
|
||||
@@ -267,13 +269,15 @@ private fun GameHero(
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.matchParentSize().background(Brush.horizontalGradient(0f to colors.background.copy(alpha = 0.94f), 0.55f to colors.background.copy(alpha = 0.58f), 1f to Color.Transparent)))
|
||||
var scoresWidth by remember { mutableStateOf(0) }
|
||||
if (scores != null) {
|
||||
Spacer(Modifier.matchParentSize().background(Brush.horizontalGradient(0.45f to Color.Transparent, 1f to colors.background.copy(alpha = 0.75f))))
|
||||
HeroScores(scores, Modifier.align(Alignment.BottomEnd).padding(end = 16.dp, bottom = 18.dp))
|
||||
HeroScores(scores, Modifier.align(Alignment.BottomEnd).padding(end = 16.dp, bottom = 18.dp).onSizeChanged { scoresWidth = it.width })
|
||||
}
|
||||
val scoresSpace = with(LocalDensity.current) { if (scores != null && scoresWidth > 0) scoresWidth.toDp() + 16.dp else 0.dp }
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
modifier = Modifier.align(Alignment.BottomStart).padding(horizontal = 22.dp, vertical = 18.dp),
|
||||
modifier = Modifier.align(Alignment.BottomStart).padding(start = 22.dp, end = 22.dp + scoresSpace, top = 18.dp, bottom = 18.dp),
|
||||
content = content,
|
||||
)
|
||||
Box(Modifier.align(Alignment.TopEnd).padding(12.dp), content = corner)
|
||||
@@ -319,7 +323,7 @@ private fun GameTitle(title: String, logo: Any?, titleSize: TextUnit) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GameActions(
|
||||
internal fun GameActions(
|
||||
store: Store?, id: String?, game: Library.SteamGame?, item: CatalogItem?, installed: InstalledStoreGame?,
|
||||
s: FrontEndState, a: FrontEndActions, leadOn: Modifier,
|
||||
) {
|
||||
@@ -328,22 +332,14 @@ private fun GameActions(
|
||||
val rawDownload = storeKey?.let { StoresState.download(it) }
|
||||
val download = rawDownload?.takeIf { it.isActive }
|
||||
val failed = rawDownload?.takeIf { it.state == DownloadState.FAILED }
|
||||
val cloud = game?.library == Library.XBOX_CLOUD && installed == null
|
||||
Actions {
|
||||
when {
|
||||
s.shortcutPicker && game != null -> {
|
||||
PrimaryButton(stringResource(R.string.game_shortcut_choose), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn) { a.onSteamGame(game) }
|
||||
FileButtons(game, a)
|
||||
}
|
||||
game?.library == Library.XBOX_CLOUD -> {
|
||||
val cloudId = game.storeId.orEmpty()
|
||||
XboxStreamButton(cloudId, game.name, main = true, modifier = leadOn)
|
||||
if (download != null) ActionChip(downloadLabel(download), ok = false)
|
||||
else if (item?.installable == true) SecondaryButton(
|
||||
if (item.sizeBytes > 0) stringResource(R.string.stores_install_size, formatBytes(item.sizeBytes)) else stringResource(R.string.stores_install),
|
||||
) { StoresState.requestInstall(ctx, item) }
|
||||
XboxLibraryButton(cloudId, item)
|
||||
}
|
||||
game != null || installed != null -> {
|
||||
!cloud && (game != null || installed != null) -> {
|
||||
val gone = storeKey?.let { StoresState.uninstalling[it] }
|
||||
val xboxBusy = store == Store.XBOX && id != null && XboxContent.busy(id)
|
||||
PrimaryButton(
|
||||
@@ -366,7 +362,19 @@ private fun GameActions(
|
||||
}
|
||||
SecondaryButton(stringResource(R.string.stores_xbox_manage), enabled = download == null) { XboxContent.manage(ctx, installed) }
|
||||
}
|
||||
if (store == Store.BATTLENET) SecondaryButton(stringResource(R.string.bnet_open)) { a.onBattleNet() }
|
||||
if (store == Store.BATTLENET) {
|
||||
if (installed != null && id != null) {
|
||||
LaunchedEffect(id) { BattleNetInstall.checkUpdate(ctx, installed) }
|
||||
if (download != null) {
|
||||
ActionChip(downloadLabel(download), ok = false)
|
||||
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(download.key) }
|
||||
else SecondaryButton(stringResource(R.string.stores_dl_resume)) { DownloadQueue.resume(ctx, download.key) }
|
||||
} else if (BattleNetInstall.updates[id] == true) {
|
||||
SecondaryButton(stringResource(R.string.bnet_update)) { BattleNetInstall.update(ctx, installed) }
|
||||
}
|
||||
}
|
||||
SecondaryButton(stringResource(R.string.bnet_open)) { a.onBattleNet() }
|
||||
}
|
||||
}
|
||||
download != null -> {
|
||||
ActionChip(downloadLabel(download), ok = false)
|
||||
@@ -381,6 +389,19 @@ private fun GameActions(
|
||||
}
|
||||
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { DownloadQueue.clear(ctx, failed.key) }
|
||||
}
|
||||
cloud -> {
|
||||
val cloudId = game.storeId.orEmpty()
|
||||
XboxStreamButton(cloudId, game.name, main = true, modifier = leadOn)
|
||||
if (item?.installable == true && item.xboxPc) {
|
||||
SecondaryButton(
|
||||
if (StoresState.isUnfinished(item)) stringResource(R.string.stores_resume_install)
|
||||
else if (item.sizeBytes > 0) stringResource(R.string.stores_install_size, formatBytes(item.sizeBytes))
|
||||
else stringResource(R.string.stores_install),
|
||||
) { StoresState.requestInstall(ctx, item) }
|
||||
}
|
||||
if (item != null && StoresState.isUnfinished(item)) ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) }
|
||||
XboxLibraryButton(cloudId, item)
|
||||
}
|
||||
store == Store.BATTLENET && item != null -> InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) }
|
||||
store == Store.XBOX && item != null && !item.xboxPc && item.xboxCloud -> {
|
||||
XboxStreamButton(item.id, item.title, main = true, modifier = leadOn)
|
||||
@@ -408,6 +429,10 @@ private fun GameActions(
|
||||
item != null && item.isFree -> PrimaryButton(stringResource(R.string.stores_get_free), main = true, modifier = leadOn) { openStoreUrl(ctx, item) }
|
||||
item != null -> PrimaryButton(buyLabel(item), main = true, modifier = leadOn) { openStoreUrl(ctx, item) }
|
||||
}
|
||||
if (cloud && (download != null || failed != null)) {
|
||||
XboxStreamButton(game.storeId.orEmpty(), game.name)
|
||||
XboxLibraryButton(game.storeId.orEmpty(), item)
|
||||
}
|
||||
BusyChip(s)
|
||||
}
|
||||
}
|
||||
@@ -525,7 +550,7 @@ private fun IconAction(icon: androidx.compose.ui.graphics.vector.ImageVector, la
|
||||
private fun RemoveButton(title: String, game: Library.SteamGame?, installed: InstalledStoreGame?, a: FrontEndActions) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
if ((installed?.sidecar?.store?.id ?: game?.source) == Store.BATTLENET.id) return
|
||||
if ((installed?.sidecar?.store?.id ?: game?.source) == Store.BATTLENET.id && installed?.sidecar?.id?.let(BattleNetInstall::product) == null) return
|
||||
if (installed != null) {
|
||||
val key = installed.key
|
||||
val gone = StoresState.uninstalling[key]
|
||||
|
||||
@@ -8,6 +8,7 @@ object GamepadGeometry {
|
||||
LEFT_OUTER_SHOULDER, LEFT_INNER_SHOULDER, RIGHT_INNER_SHOULDER, RIGHT_OUTER_SHOULDER,
|
||||
VIEW, STEAM, QAM, MENU,
|
||||
PANELS,
|
||||
L4, L5, R5, R4,
|
||||
}
|
||||
|
||||
data class Box(val cx: Float, val cy: Float, val width: Float, val height: Float) {
|
||||
@@ -25,8 +26,11 @@ object GamepadGeometry {
|
||||
|
||||
fun tall(w: Float, h: Float): Boolean = h >= w * 0.45f
|
||||
|
||||
fun layout(w: Float, h: Float, density: Float): Map<Slot, Box> {
|
||||
fun layout(w: Float, h: Float, density: Float, portraitDock: Boolean = false): Map<Slot, Box> {
|
||||
if (w <= 0f || h <= 0f) return emptyMap()
|
||||
if (portraitDock && h >= w * 0.9f && w >= 300 * density && h >= 360 * density) {
|
||||
return portraitLayout(w, h, density)
|
||||
}
|
||||
val pad = 8 * density
|
||||
val buttonH = 40 * density
|
||||
val rowButton = 64 * density
|
||||
@@ -67,7 +71,7 @@ object GamepadGeometry {
|
||||
}
|
||||
middleGrid(columns, gap - 2 * gutter, shoulderY - buttonH / 2f)
|
||||
} else {
|
||||
val side = min(w * 0.5f, h * 0.70f)
|
||||
val side = min(min(w * 0.5f, h * 0.70f), (w - 2 * gridButton - 2 * gutter) / 1.42f)
|
||||
val main = side * 0.62f
|
||||
val second = side * 0.46f
|
||||
val secondCy = h - side * 0.97f
|
||||
@@ -87,4 +91,39 @@ object GamepadGeometry {
|
||||
}
|
||||
return boxes
|
||||
}
|
||||
|
||||
private fun portraitLayout(w: Float, h: Float, density: Float): Map<Slot, Box> {
|
||||
val pad = 8 * density
|
||||
val gap = 8 * density
|
||||
val buttonH = 44 * density
|
||||
val scale = min(1f, (h - 2 * pad - 4 * gap - 3 * buttonH) / (w * 0.7f))
|
||||
val main = w * 0.4f * scale
|
||||
val second = w * 0.3f * scale
|
||||
val mainY = h - pad - main / 2f
|
||||
val secondY = mainY - main / 2f - gap - second / 2f
|
||||
val shoulderY = secondY - second / 2f - gap - buttonH / 2f
|
||||
val boxes = linkedMapOf(
|
||||
Slot.LEFT_MAIN to Box(w * 0.25f, mainY, main, main),
|
||||
Slot.RIGHT_MAIN to Box(w * 0.75f, mainY, main, main),
|
||||
Slot.LEFT_SECOND to Box(w * 0.25f, secondY, second, second),
|
||||
Slot.RIGHT_SECOND to Box(w * 0.75f, secondY, second, second),
|
||||
)
|
||||
val utilityW = (w - 2 * pad - 3 * gap) / 4f
|
||||
for ((i, slot) in middle.withIndex()) {
|
||||
boxes[slot] = Box(pad + utilityW / 2f + i * (utilityW + gap), pad + buttonH / 2f, utilityW, buttonH)
|
||||
}
|
||||
val gripTop = pad + buttonH + gap
|
||||
val gripH = min(64 * density, shoulderY - buttonH / 2f - gap - gripTop)
|
||||
for ((i, slot) in listOf(Slot.L4, Slot.L5, Slot.R5, Slot.R4).withIndex()) {
|
||||
boxes[slot] = Box(pad + utilityW / 2f + i * (utilityW + gap), gripTop + gripH / 2f, utilityW, gripH)
|
||||
}
|
||||
val panelsW = min(112 * density, w * 0.22f)
|
||||
val shoulderW = (w - 2 * pad - 4 * gap - panelsW) / 4f
|
||||
boxes[Slot.PANELS] = Box(w / 2f, shoulderY, panelsW, buttonH)
|
||||
boxes[Slot.LEFT_OUTER_SHOULDER] = Box(pad + shoulderW / 2f, shoulderY, shoulderW, buttonH)
|
||||
boxes[Slot.LEFT_INNER_SHOULDER] = Box(pad + shoulderW * 1.5f + gap, shoulderY, shoulderW, buttonH)
|
||||
boxes[Slot.RIGHT_INNER_SHOULDER] = Box(w - pad - shoulderW * 1.5f - gap, shoulderY, shoulderW, buttonH)
|
||||
boxes[Slot.RIGHT_OUTER_SHOULDER] = Box(w - pad - shoulderW / 2f, shoulderY, shoulderW, buttonH)
|
||||
return boxes
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.animation.core.Spring
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.foundation.LocalIndication
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.focusGroup
|
||||
import androidx.compose.foundation.hoverable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.lazy.grid.GridCells
|
||||
import androidx.compose.foundation.lazy.grid.GridItemSpan
|
||||
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
|
||||
import androidx.compose.foundation.lazy.grid.items
|
||||
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.Login
|
||||
import androidx.compose.material.icons.filled.Check
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.derivedStateOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.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.graphics.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
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.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.gfn.GfnGame
|
||||
import com.droiddeck.launcher.stores.gfn.GfnState
|
||||
import com.droiddeck.launcher.stores.gfn.GfnStoreAccount
|
||||
|
||||
/** The GeForce NOW tab's chip key; it sits after the store tabs and is not a [com.droiddeck.launcher.stores.Store]. */
|
||||
internal const val GEFORCE_NOW = "geforce-now"
|
||||
|
||||
internal val GfnGreen = Color(0xFF76B900)
|
||||
internal val GfnColours = SourceColours(Color(0xFF1C2A0A), Color(0xFFCDEB8B), GfnGreen)
|
||||
|
||||
internal fun gfnPalette(base: Palette): Palette = Palette(
|
||||
base.id, base.label, base.detail, base.background, base.surface, base.surfaceVariant, base.line, base.line2,
|
||||
base.onBackground, base.onSurfaceVariant, primary = GfnGreen, primary2 = Color(0xFF5A8F00), onPrimary = Color(0xFF0B0B0D), signal = GfnGreen,
|
||||
good = base.good, error = base.error,
|
||||
)
|
||||
|
||||
@Composable
|
||||
internal fun GfnTheme(content: @Composable () -> Unit) {
|
||||
val base = LocalPalette.current
|
||||
val p = remember(base) { gfnPalette(base) }
|
||||
val scheme = MaterialTheme.colorScheme.copy(primary = p.primary, onPrimary = p.onPrimary)
|
||||
CompositionLocalProvider(LocalPalette provides p) { MaterialTheme(colorScheme = scheme, typography = MaterialTheme.typography, content = content) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun GfnPane(height: Dp) {
|
||||
val ctx = LocalContext.current
|
||||
LaunchedEffect(Unit) { GfnState.start(ctx) }
|
||||
when (val phase = GfnState.phase) {
|
||||
GfnState.Phase.Loading -> Box(Modifier.fillMaxWidth().padding(top = 16.dp)) {
|
||||
androidx.compose.material3.LinearProgressIndicator(Modifier.fillMaxWidth().height(3.dp))
|
||||
}
|
||||
is GfnState.Phase.Failed -> Column(verticalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.fillMaxWidth().padding(top = 8.dp)) {
|
||||
Note(phase.message)
|
||||
PrimaryButton(stringResource(R.string.gfn_try_again), main = true) { GfnState.start(ctx, force = true) }
|
||||
}
|
||||
is GfnState.Phase.SignedOut, is GfnState.Phase.Code -> Box(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(top = 4.dp, bottom = 16.dp)) {
|
||||
GfnSignInCard(phase, height)
|
||||
}
|
||||
is GfnState.Phase.SignedIn -> GfnStorefront(phase.user)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GfnSignInCard(phase: GfnState.Phase, height: Dp) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val narrow = LocalNarrowPane.current
|
||||
val shape = RoundedCornerShape(20.dp)
|
||||
Box(
|
||||
Modifier.fillMaxWidth().heightIn(min = height.coerceAtLeast(0.dp)).clip(shape)
|
||||
.background(Brush.linearGradient(listOf(GfnColours.fill, colors.background))).border(1.dp, pal.line, shape)
|
||||
.drawBehind {
|
||||
drawRect(Brush.radialGradient(listOf(GfnGreen.copy(alpha = 0.28f), Color.Transparent), center = Offset(size.width * 0.16f, size.height * 0.9f), radius = size.height * 0.8f))
|
||||
},
|
||||
) {
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
modifier = Modifier.align(Alignment.BottomStart).padding(start = if (narrow) 20.dp else 40.dp, bottom = if (narrow) 20.dp else 36.dp, end = 20.dp, top = 20.dp),
|
||||
) {
|
||||
Rise(2) {
|
||||
Text(
|
||||
stringResource(R.string.gfn_name), fontSize = if (narrow) 30.sp else 42.sp, lineHeight = if (narrow) 34.sp else 46.sp,
|
||||
fontWeight = FontWeight.Black, color = colors.onBackground,
|
||||
)
|
||||
}
|
||||
Text(stringResource(R.string.gfn_pitch), fontSize = 15.sp, color = colors.onBackground)
|
||||
Text(stringResource(R.string.gfn_unofficial), fontSize = 12.sp, color = colors.onSurfaceVariant)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
when (phase) {
|
||||
is GfnState.Phase.Code -> {
|
||||
Text(stringResource(R.string.gfn_code_hint, phase.url), fontSize = 14.sp, color = colors.onBackground)
|
||||
Text(phase.userCode, fontSize = 34.sp, fontWeight = FontWeight.Black, letterSpacing = 4.sp, color = GfnGreen)
|
||||
Actions {
|
||||
PrimaryButton(stringResource(R.string.gfn_open_page), main = true) { openUrl(ctx, phase.url) }
|
||||
SecondaryButton(stringResource(R.string.common_cancel)) { GfnState.cancelSignIn() }
|
||||
}
|
||||
Text(stringResource(R.string.gfn_code_waiting), fontSize = 12.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
else -> {
|
||||
(phase as? GfnState.Phase.SignedOut)?.error?.let { Text(it, fontSize = 13.sp, color = colors.error) }
|
||||
Rise(3) {
|
||||
PrimaryButton(stringResource(R.string.stores_signin), main = true, large = true, icon = Icons.AutoMirrored.Filled.Login) { GfnState.signIn(ctx) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private const val MODE_STORE = 0
|
||||
private const val MODE_LIBRARY = 1
|
||||
private const val MODE_ACCOUNTS = 2
|
||||
|
||||
@Composable
|
||||
private fun GfnStorefront(user: String) {
|
||||
val ctx = LocalContext.current
|
||||
var mode by rememberSaveable { mutableIntStateOf(MODE_STORE) }
|
||||
var query by rememberSaveable { mutableStateOf("") }
|
||||
val grid = rememberLazyGridState()
|
||||
LaunchedEffect(mode) {
|
||||
when (mode) {
|
||||
MODE_LIBRARY -> GfnState.loadLibrary(ctx)
|
||||
MODE_ACCOUNTS -> GfnState.loadAccounts(ctx)
|
||||
}
|
||||
grid.scrollToItem(0)
|
||||
}
|
||||
LaunchedEffect(Unit) { GfnState.loadLibrary(ctx) }
|
||||
LaunchedEffect(mode, query) { if (mode == MODE_STORE) GfnState.showStore(ctx, query) }
|
||||
val nearEnd by remember {
|
||||
derivedStateOf {
|
||||
val last = grid.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0
|
||||
last >= grid.layoutInfo.totalItemsCount - 10
|
||||
}
|
||||
}
|
||||
LaunchedEffect(nearEnd, GfnState.storeGames.size, mode) {
|
||||
if (mode == MODE_STORE && nearEnd && GfnState.storeGames.isNotEmpty()) GfnState.loadStore(ctx, query, reset = false)
|
||||
}
|
||||
val words = query.trim().lowercase().split(' ').filter { it.isNotEmpty() }
|
||||
val library = GfnState.library
|
||||
val libraryShown = remember(library, query) { library.orEmpty().filter { game -> words.all { game.search.contains(it) } } }
|
||||
val full: androidx.compose.foundation.lazy.grid.LazyGridItemSpanScope.() -> GridItemSpan = { GridItemSpan(maxLineSpan) }
|
||||
LazyVerticalGrid(
|
||||
columns = GridCells.Adaptive(CardWidth), state = grid, modifier = Modifier.fillMaxSize().focusGroup(),
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
contentPadding = PaddingValues(top = 4.dp, bottom = 16.dp),
|
||||
) {
|
||||
item(key = "profile", span = full) { Rise(1) { GfnProfile(user, library?.size, onRefresh = {
|
||||
when (mode) {
|
||||
MODE_STORE -> GfnState.loadStore(ctx, query, reset = true)
|
||||
MODE_LIBRARY -> GfnState.loadLibrary(ctx, force = true)
|
||||
else -> GfnState.loadAccounts(ctx)
|
||||
}
|
||||
}) } }
|
||||
item(key = "modes", span = full) {
|
||||
Rise(2) {
|
||||
val pills: @Composable () -> Unit = {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
GfnModePill(stringResource(R.string.gfn_mode_store), mode == MODE_STORE, "store") { mode = MODE_STORE; query = "" }
|
||||
GfnModePill(stringResource(R.string.gfn_mode_library), mode == MODE_LIBRARY, "library") { mode = MODE_LIBRARY; query = "" }
|
||||
GfnModePill(stringResource(R.string.gfn_mode_accounts), mode == MODE_ACCOUNTS, "accounts") { mode = MODE_ACCOUNTS; query = "" }
|
||||
}
|
||||
}
|
||||
if (mode == MODE_ACCOUNTS) Column(Modifier.fillMaxWidth()) {
|
||||
Box(Modifier.heightIn(min = 52.dp).padding(vertical = 4.dp), contentAlignment = Alignment.CenterStart) { pills() }
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(LocalPalette.current.line))
|
||||
} else ModeHeader(
|
||||
stringResource(R.string.gfn_name), query, { query = it },
|
||||
placeholder = if (mode == MODE_STORE) stringResource(R.string.gfn_search_store, GfnState.storeTotal)
|
||||
else stringResource(R.string.gfn_search_library, library?.size ?: 0),
|
||||
lead = pills,
|
||||
) {}
|
||||
}
|
||||
}
|
||||
when (mode) {
|
||||
MODE_STORE -> {
|
||||
GfnState.storeError?.let { line -> item(key = "error", span = full) { Note(line) } }
|
||||
val games = GfnState.storeGames
|
||||
items(games, key = { "gfn:${it.id}" }, contentType = { "game" }) { game -> GfnCard(game, first = game.id == games.first().id, showOwned = true) }
|
||||
if (GfnState.storeLoading) item(key = "loading", span = full) {
|
||||
if (games.isEmpty()) Note(stringResource(R.string.gfn_loading_store))
|
||||
else androidx.compose.material3.LinearProgressIndicator(Modifier.fillMaxWidth().height(3.dp))
|
||||
} else if (games.isEmpty() && GfnState.storeError == null) item(key = "empty", span = full) { GfnEmpty(stringResource(R.string.stores_nothing_matches)) }
|
||||
}
|
||||
MODE_LIBRARY -> {
|
||||
GfnState.libraryError?.let { line -> item(key = "error", span = full) { Note(line) } }
|
||||
when {
|
||||
library == null && GfnState.libraryError == null -> item(key = "loading", span = full) { Note(stringResource(R.string.gfn_loading_library)) }
|
||||
library?.isEmpty() == true -> item(key = "empty", span = full) { Note(stringResource(R.string.gfn_library_empty)) }
|
||||
libraryShown.isEmpty() && library != null -> item(key = "nothing", span = full) { GfnEmpty(stringResource(R.string.stores_nothing_matches)) }
|
||||
else -> items(libraryShown, key = { "gfn:${it.id}" }, contentType = { "game" }) { game ->
|
||||
GfnCard(game, first = game.id == libraryShown.first().id, showOwned = false)
|
||||
}
|
||||
}
|
||||
}
|
||||
else -> {
|
||||
item(key = "note", span = full) {
|
||||
Text(stringResource(R.string.gfn_accounts_note), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 2.dp))
|
||||
}
|
||||
GfnState.accountsMessage?.let { line -> item(key = "message", span = full) { Note(line) } }
|
||||
val accounts = GfnState.accounts
|
||||
if (accounts == null) item(key = "loading", span = full) { androidx.compose.material3.LinearProgressIndicator(Modifier.fillMaxWidth().height(3.dp)) }
|
||||
else items(accounts, key = { "account:${it.provider}" }, span = { full() }) { account -> GfnAccountRow(account) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GfnEmpty(text: String) {
|
||||
Box(Modifier.padding(vertical = 32.dp).fillMaxWidth(), contentAlignment = Alignment.Center) {
|
||||
Text(text, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GfnProfile(user: String, owned: Int?, onRefresh: () -> Unit) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val shape = RoundedCornerShape(16.dp)
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(bottom = 4.dp).clip(shape).background(colors.surface).border(1.dp, pal.line, shape)
|
||||
.padding(horizontal = 14.dp, vertical = 10.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(36.dp).clip(CircleShape).background(GfnGreen)) {
|
||||
Text(user.take(1).uppercase().ifEmpty { "G" }, fontSize = 16.sp, fontWeight = FontWeight.Black, color = Color.Black)
|
||||
}
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(user, fontSize = 15.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
if (owned != null) stringResource(R.string.gfn_profile_line, owned) else stringResource(R.string.gfn_name),
|
||||
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
Actions {
|
||||
SecondaryButton(stringResource(R.string.stores_refresh), compact = true) { onRefresh() }
|
||||
ConfirmButton(stringResource(R.string.stores_signout_go), stringResource(R.string.gfn_signout_confirm), compact = true) { GfnState.signOut(ctx) }
|
||||
}
|
||||
}
|
||||
Text(stringResource(R.string.gfn_unofficial), fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 2)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GfnModePill(label: String, on: Boolean, key: String, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
val shape = RoundedCornerShape(99.dp)
|
||||
Text(
|
||||
label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1,
|
||||
color = if (on) colors.onPrimary else if (hot) colors.onBackground else colors.onSurfaceVariant,
|
||||
modifier = Modifier.paneItem("gfnmode:$key").clip(shape)
|
||||
.background(if (on) pal.signal else Color.Transparent)
|
||||
.glideBorder(hot, shape, pal.signal, if (on) Color.Transparent else pal.line)
|
||||
.hoverable(src).clickable(role = Role.Tab, interactionSource = src, indication = LocalIndication.current, onClick = onClick)
|
||||
.controllerConfirm(onClick = onClick)
|
||||
.padding(horizontal = 14.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GfnCard(game: GfnGame, first: Boolean, showOwned: Boolean) {
|
||||
val ctx = LocalContext.current
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
val pressed by src.collectIsPressedAsState()
|
||||
val scale by animateFloatAsState(if (pressed) 0.985f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "gfnCardScale")
|
||||
val play = { GfnState.play(ctx, game) }
|
||||
Column(
|
||||
Modifier.fillMaxWidth().paneItem("card:gfn:${game.id}").then(if (first) Modifier.firstTile() else Modifier)
|
||||
.graphicsLayer { scaleX = scale; scaleY = scale }
|
||||
.clip(RoundedCornerShape(10.dp)).glideBorder(hot, RoundedCornerShape(10.dp), pal.signal, pal.line)
|
||||
.hoverable(src).clickable(role = Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = play)
|
||||
.controllerConfirm(onClick = play),
|
||||
) {
|
||||
CardFace(game.title, game.imageUrl.ifEmpty { null }, null, null, hot) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
if (showOwned && game.inLibrary) Icon(Icons.Filled.Check, null, tint = GfnGreen, modifier = Modifier.size(11.dp))
|
||||
Text(game.store, fontSize = 9.sp, fontWeight = FontWeight.SemiBold, color = Color.White.copy(alpha = 0.75f), maxLines = 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GfnAccountRow(account: GfnStoreAccount) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val shape = RoundedCornerShape(14.dp)
|
||||
val busy = GfnState.accountsBusy
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.fillMaxWidth().clip(shape).background(colors.surface).border(1.dp, pal.line, shape).padding(horizontal = 14.dp, vertical = 10.dp),
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(36.dp).clip(Shape12).background(if (account.connected) GfnColours.fill else colors.surfaceVariant)) {
|
||||
Text(account.label.take(1).uppercase(), fontSize = 15.sp, fontWeight = FontWeight.Black, color = if (account.connected) GfnColours.ink else colors.onSurfaceVariant)
|
||||
}
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(account.label, fontSize = 15.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
when {
|
||||
account.status == "expired" -> stringResource(R.string.gfn_status_expired)
|
||||
account.status == "sync_error" -> stringResource(R.string.gfn_status_sync_error)
|
||||
account.connected && account.displayName.isNotEmpty() -> stringResource(R.string.gfn_status_connected_as, account.displayName)
|
||||
account.connected -> stringResource(R.string.gfn_status_connected)
|
||||
else -> stringResource(R.string.gfn_status_not_connected)
|
||||
},
|
||||
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
Box {
|
||||
when (GfnState.actionFor(account)) {
|
||||
"link" -> PrimaryButton(stringResource(if (account.connected) R.string.gfn_reconnect else R.string.gfn_connect), enabled = !busy, compact = true) { GfnState.link(ctx, account) }
|
||||
"sync" -> SecondaryButton(stringResource(R.string.gfn_sync), enabled = !busy, compact = true) { GfnState.sync(ctx, account) }
|
||||
"unlink" -> ConfirmButton(stringResource(R.string.gfn_disconnect), stringResource(R.string.gfn_disconnect_confirm), compact = true) { GfnState.unlink(ctx, account) }
|
||||
else -> if (account.provider == "STEAM" && !account.connected)
|
||||
Text(stringResource(R.string.gfn_steam_link), fontSize = 12.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
@@ -32,8 +34,8 @@ internal fun GlassesCalibrationControls(
|
||||
onDismissRequest = { reset = false },
|
||||
title = { Text(stringResource(R.string.glasses_calibration_reset)) },
|
||||
text = { Text(stringResource(R.string.glasses_calibration_reset_hint)) },
|
||||
confirmButton = { TextButton(onClick = { onReset(); reset = false }) { Text(stringResource(R.string.glasses_calibration_reset_button)) } },
|
||||
dismissButton = { TextButton(onClick = { reset = false }) { Text(stringResource(R.string.common_cancel)) } },
|
||||
confirmButton = { TextButton(onClick = { onReset(); reset = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.glasses_calibration_reset_button)) } },
|
||||
dismissButton = { TextButton(onClick = { reset = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
if (shown) AlertDialog(
|
||||
onDismissRequest = { onCancel(); shown = false },
|
||||
@@ -57,8 +59,8 @@ internal fun GlassesCalibrationControls(
|
||||
if (!state.running) TextButton(onClick = {
|
||||
if (state.phase == CalibrationPhase.SAVED) { onDone(); onCancel(); shown = false }
|
||||
else onStart()
|
||||
}) { Text(stringResource(if (state.phase == CalibrationPhase.SAVED) R.string.glasses_calibration_done else R.string.glasses_calibration_start)) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(if (state.phase == CalibrationPhase.SAVED) R.string.glasses_calibration_done else R.string.glasses_calibration_start)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { onCancel(); shown = false }) { Text(stringResource(R.string.common_cancel)) } },
|
||||
dismissButton = { TextButton(onClick = { onCancel(); shown = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
@@ -347,6 +347,7 @@ internal fun GlassesCornerButton(slot: Int, tint: Int, opacity: Int, onClick: ()
|
||||
.clip(CircleShape)
|
||||
.background(fill)
|
||||
.border(1.5.dp, line, CircleShape)
|
||||
.focusGlide(CircleShape)
|
||||
.clickable(interactionSource = source, indication = null, role = Role.Button, onClick = onClick)
|
||||
.testTag("glasses-button"),
|
||||
) {
|
||||
@@ -382,6 +383,7 @@ private fun GlassesRecenterAction(label: String, tag: String, tint: Int, opacity
|
||||
.clip(shape)
|
||||
.background(fill)
|
||||
.border(1.5.dp, line, shape)
|
||||
.focusGlide(shape)
|
||||
.clickable(interactionSource = source, indication = null, role = Role.Button, onClick = onClick)
|
||||
.padding(horizontal = 18.dp)
|
||||
.testTag(tag),
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.ScrollState
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.AlertDialogDefaults
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Shape
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.DpOffset
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.compose.ui.window.Popup
|
||||
import androidx.compose.ui.window.PopupPositionProvider
|
||||
import androidx.compose.ui.window.PopupProperties
|
||||
|
||||
@Composable
|
||||
internal fun GlideDialog(
|
||||
onDismissRequest: () -> Unit,
|
||||
properties: DialogProperties = DialogProperties(),
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
Dialog(onDismissRequest, properties) { FocusGlideHost(content = content) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun GlidePopup(
|
||||
popupPositionProvider: PopupPositionProvider,
|
||||
onDismissRequest: (() -> Unit)? = null,
|
||||
properties: PopupProperties = PopupProperties(),
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
Popup(popupPositionProvider, onDismissRequest, properties) { FocusGlideHost(content = content) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun GlideAlertDialog(
|
||||
onDismissRequest: () -> Unit,
|
||||
confirmButton: @Composable () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
dismissButton: (@Composable () -> Unit)? = null,
|
||||
icon: (@Composable () -> Unit)? = null,
|
||||
title: (@Composable () -> Unit)? = null,
|
||||
text: (@Composable () -> Unit)? = null,
|
||||
shape: Shape = AlertDialogDefaults.shape,
|
||||
containerColor: Color = AlertDialogDefaults.containerColor,
|
||||
iconContentColor: Color = AlertDialogDefaults.iconContentColor,
|
||||
titleContentColor: Color = AlertDialogDefaults.titleContentColor,
|
||||
textContentColor: Color = AlertDialogDefaults.textContentColor,
|
||||
tonalElevation: Dp = AlertDialogDefaults.TonalElevation,
|
||||
properties: DialogProperties = DialogProperties(),
|
||||
) {
|
||||
FocusGlideWindow { overlay ->
|
||||
AlertDialog(
|
||||
onDismissRequest, confirmButton, modifier.then(overlay), dismissButton, icon, title, text,
|
||||
shape, containerColor, iconContentColor, titleContentColor, textContentColor, tonalElevation, properties,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun GlideDropdownMenu(
|
||||
expanded: Boolean,
|
||||
onDismissRequest: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
offset: DpOffset = DpOffset.Zero,
|
||||
scrollState: ScrollState = rememberScrollState(),
|
||||
properties: PopupProperties = PopupProperties(focusable = true),
|
||||
content: @Composable ColumnScope.() -> Unit,
|
||||
) {
|
||||
FocusGlideWindow { overlay ->
|
||||
DropdownMenu(expanded, onDismissRequest, modifier.then(overlay), offset, scrollState, properties, content)
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,6 @@ package com.droiddeck.launcher.ui
|
||||
import com.droiddeck.launcher.R
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.foundation.focusGroup
|
||||
import androidx.compose.foundation.relocation.BringIntoViewRequester
|
||||
import androidx.compose.foundation.relocation.bringIntoViewRequester
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.layout.LayoutCoordinates
|
||||
import androidx.compose.ui.layout.boundsInRoot
|
||||
@@ -21,7 +19,6 @@ import androidx.compose.material.icons.outlined.SportsEsports
|
||||
import androidx.compose.material.icons.outlined.ExpandLess
|
||||
import androidx.compose.material.icons.outlined.ExpandMore
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.withFrameNanos
|
||||
import androidx.compose.ui.platform.LocalClipboardManager
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
@@ -51,7 +48,7 @@ import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.AutoAwesome
|
||||
import androidx.compose.material.icons.outlined.Memory
|
||||
import androidx.compose.material.icons.outlined.Tune
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import com.droiddeck.launcher.ui.GlideDropdownMenu as DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
@@ -212,7 +209,7 @@ private fun DeviceInfoSection(section: DeviceInfo.Section) {
|
||||
|
||||
private const val STALE_MS = 6 * 3_600_000L
|
||||
|
||||
@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class, androidx.compose.foundation.ExperimentalFoundationApi::class)
|
||||
@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class)
|
||||
@Composable
|
||||
internal fun GpuDriversBody(
|
||||
gpu: GpuDriversState,
|
||||
@@ -227,13 +224,6 @@ internal fun GpuDriversBody(
|
||||
}
|
||||
val scroll = rememberScrollState()
|
||||
val scope = rememberCoroutineScope()
|
||||
val driverControls = remember { BringIntoViewRequester() }
|
||||
LaunchedEffect(gpu.mode) {
|
||||
if (gpu.mode == GPU_MODE_MIX) {
|
||||
withFrameNanos { }
|
||||
driverControls.bringIntoView()
|
||||
}
|
||||
}
|
||||
val placed = remember { arrayOfNulls<LayoutCoordinates>(2) }
|
||||
// Focusing the top mode shows as much of the in-use card above it as fits, without hiding the mode itself.
|
||||
val revealCard = {
|
||||
@@ -261,10 +251,7 @@ internal fun GpuDriversBody(
|
||||
stringResource(title), stringResource(detail), gpu.mode == id,
|
||||
modifier = mod.then(if (gpu.mode == id) Modifier.focusRequester(first) else Modifier)
|
||||
.then(if (i == 0) Modifier.onGloballyPositioned { placed[1] = it }.onFocusChanged { if (it.isFocused) revealCard() } else Modifier),
|
||||
onClick = {
|
||||
if (gpu.mode != id) actions.onMode(id)
|
||||
else if (id == GPU_MODE_MIX) scope.launch { driverControls.bringIntoView() }
|
||||
},
|
||||
onClick = { if (gpu.mode != id) actions.onMode(id) },
|
||||
)
|
||||
}
|
||||
if (single) Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { modes.indices.forEach { choice(it, Modifier) } }
|
||||
@@ -274,7 +261,7 @@ internal fun GpuDriversBody(
|
||||
when (gpu.mode) {
|
||||
GPU_MODE_AUTO -> AutoBody(gpu)
|
||||
GPU_MODE_PAIR -> PairBody(gpu, actions)
|
||||
else -> MixBody(single, actions, slotFocus, onOpenSlot, Modifier.bringIntoViewRequester(driverControls))
|
||||
else -> MixBody(single, actions, slotFocus, onOpenSlot)
|
||||
}
|
||||
gpu.tpUbwcMode?.let { selected ->
|
||||
var advanced by rememberSaveable { mutableStateOf(false) }
|
||||
@@ -408,7 +395,7 @@ private fun PairBody(gpu: GpuDriversState, actions: GpuDriversActions) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MixBody(single: Boolean, actions: GpuDriversActions, slotFocus: Map<String, FocusRequester>, onOpenSlot: (String, Rect) -> Unit, controlsModifier: Modifier) {
|
||||
private fun MixBody(single: Boolean, actions: GpuDriversActions, slotFocus: Map<String, FocusRequester>, onOpenSlot: (String, Rect) -> Unit) {
|
||||
val pal = LocalPalette.current
|
||||
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
PanelTitle(stringResource(R.string.gpu_mix_title), stringResource(R.string.gpu_mix_hint))
|
||||
@@ -423,8 +410,8 @@ private fun MixBody(single: Boolean, actions: GpuDriversActions, slotFocus: Map<
|
||||
slotButton(SLOT_DISPLAY, R.string.gpu_change_display, mod)
|
||||
slotButton(SLOT_RUNTIME, R.string.gpu_change_runtime, mod)
|
||||
}
|
||||
if (single) Column(controlsModifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) { buttons(Modifier.fillMaxWidth()) }
|
||||
else Row(controlsModifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) { buttons(Modifier.weight(1f)) }
|
||||
if (single) Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { buttons(Modifier.fillMaxWidth()) }
|
||||
else Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { buttons(Modifier.weight(1f)) }
|
||||
FocusText(stringResource(R.string.comp_import_zip), pal.signal, onClick = actions.onImportZip)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.core.AddonPack
|
||||
import android.Manifest
|
||||
import android.content.Intent
|
||||
@@ -28,7 +29,7 @@ import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.selection.selectable
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.RadioButton
|
||||
@@ -63,7 +64,7 @@ import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import com.droiddeck.launcher.ui.GlideDialog as Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
@@ -129,7 +130,7 @@ internal fun HandCameraPrompt(sides: Set<String>, onAllow: (String?) -> Unit, on
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))
|
||||
.selectable(side == id, role = Role.RadioButton) { side = id }
|
||||
.focusGlide(RoundedCornerShape(8.dp)).selectable(side == id, role = Role.RadioButton) { side = id }
|
||||
.testTag("hand-camera-$id")
|
||||
.padding(vertical = 4.dp),
|
||||
) {
|
||||
@@ -144,12 +145,12 @@ internal fun HandCameraPrompt(sides: Set<String>, onAllow: (String?) -> Unit, on
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = { onAllow(if (choose) side else null) }, modifier = Modifier.testTag("hand-camera-allow")) {
|
||||
TextButton(onClick = { onAllow(if (choose) side else null) }, modifier = Modifier.testTag("hand-camera-allow").focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.hand_camera_allow))
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = onNotNow, modifier = Modifier.testTag("hand-camera-not-now")) { Text(stringResource(R.string.hand_camera_not_now)) }
|
||||
TextButton(onClick = onNotNow, modifier = Modifier.testTag("hand-camera-not-now").focusGlide(CircleShape)) { Text(stringResource(R.string.hand_camera_not_now)) }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
@@ -9,7 +10,7 @@ import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
@@ -91,7 +92,7 @@ internal fun ItchKeyDialog(onDismiss: () -> Unit) {
|
||||
Row(horizontalArrangement = Arrangement.Start) {
|
||||
TextButton(onClick = {
|
||||
ctx.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(ItchApi.KEYS_PAGE)))
|
||||
}) { Text(stringResource(R.string.stores_itch_get_key)) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.stores_itch_get_key)) }
|
||||
}
|
||||
if (rejected) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
@@ -104,12 +105,12 @@ internal fun ItchKeyDialog(onDismiss: () -> Unit) {
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(enabled = key.isNotBlank() && !busy, onClick = { submit() }) {
|
||||
TextButton(enabled = key.isNotBlank() && !busy, onClick = { submit() }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.game_env_save))
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(enabled = !busy, onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) }
|
||||
TextButton(enabled = !busy, onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) }
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -2,6 +2,12 @@ package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.compositionLocalOf
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.layout.Layout
|
||||
import androidx.compose.ui.unit.Constraints
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@@ -13,3 +19,38 @@ val LocalNarrowPane = compositionLocalOf { false }
|
||||
@Composable
|
||||
internal fun isNarrowScreen(): Boolean = LocalConfiguration.current.screenWidthDp < 600
|
||||
|
||||
@Composable
|
||||
internal fun LauncherLayout(
|
||||
bottomNavigation: Boolean, divider: Color, modifier: Modifier = Modifier,
|
||||
navigation: @Composable () -> Unit, content: @Composable () -> Unit,
|
||||
) {
|
||||
Layout(modifier = modifier, content = {
|
||||
Box { content() }
|
||||
Box(Modifier.background(divider))
|
||||
Box { navigation() }
|
||||
}) { children, constraints ->
|
||||
val width = constraints.maxWidth
|
||||
val height = constraints.maxHeight
|
||||
val line = 1.dp.roundToPx()
|
||||
val nav = children[2].measure(Constraints(
|
||||
minWidth = if (bottomNavigation) width else 0, maxWidth = width,
|
||||
minHeight = if (bottomNavigation) 0 else height, maxHeight = height,
|
||||
))
|
||||
val contentWidth = if (bottomNavigation) width else (width - nav.width - line).coerceAtLeast(0)
|
||||
val contentHeight = if (bottomNavigation) (height - nav.height - line).coerceAtLeast(0) else height
|
||||
val pane = children[0].measure(Constraints.fixed(contentWidth, contentHeight))
|
||||
val edge = children[1].measure(Constraints.fixed(if (bottomNavigation) width else line, if (bottomNavigation) line else height))
|
||||
layout(width, height) {
|
||||
if (bottomNavigation) {
|
||||
pane.placeRelative(0, 0)
|
||||
edge.placeRelative(0, contentHeight)
|
||||
nav.placeRelative(0, contentHeight + line)
|
||||
} else {
|
||||
nav.placeRelative(0, 0)
|
||||
edge.placeRelative(nav.width, 0)
|
||||
pane.placeRelative(nav.width + line, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ import androidx.compose.foundation.selection.selectable
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.FilterList
|
||||
import androidx.compose.material.icons.filled.FilterAlt
|
||||
import androidx.compose.material.icons.filled.GridView
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material.icons.filled.Sort
|
||||
@@ -86,6 +86,7 @@ import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreSizes
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.arrangeStoreTabs
|
||||
import com.droiddeck.launcher.stores.download.DownloadEntry
|
||||
import com.droiddeck.launcher.stores.formatBytes
|
||||
import com.droiddeck.launcher.stores.retainOrder
|
||||
@@ -108,12 +109,16 @@ internal fun libraryEntries(
|
||||
): List<LibraryEntry> {
|
||||
val claimed = HashSet<String>()
|
||||
val out = ArrayList<LibraryEntry>()
|
||||
for (g in games) {
|
||||
for (g in games.sortedBy { it.library == Library.XBOX_CLOUD }) {
|
||||
if (g.library == Library.EPIC_LAUNCHER) continue
|
||||
val storeKey = g.storeId?.let { "${g.source}:$it" }
|
||||
val item = storeKey?.let { k -> Store.byId(g.source)?.let { st -> owned[st]?.firstOrNull { it.key == k } } }
|
||||
if (storeKey != null) claimed += storeKey
|
||||
out += LibraryEntry(GameRef.key(g), g.source, g.name, g, item, installed = true)
|
||||
if (storeKey != null) {
|
||||
if (g.library == Library.XBOX_CLOUD && storeKey in claimed) continue
|
||||
claimed.add(storeKey)
|
||||
}
|
||||
out += LibraryEntry(GameRef.key(g), g.source, g.name, g, item,
|
||||
installed = g.library != Library.XBOX_CLOUD || storeKey in installedStore)
|
||||
}
|
||||
for (store in Store.entries) for (item in owned[store].orEmpty()) {
|
||||
if (!claimed.add(item.key)) continue
|
||||
@@ -125,15 +130,21 @@ internal fun libraryEntries(
|
||||
internal fun installedFirst(entries: List<LibraryEntry>): List<LibraryEntry> = entries.partition { it.installed }.let { (on, off) -> on + off }
|
||||
|
||||
internal const val LIBRARY_ALL = "all"
|
||||
internal val LIBRARY_SOURCES = listOf(Library.SOURCE_STEAM) + Store.entries.map { it.id } + Library.ADDED
|
||||
internal fun librarySources(entries: List<LibraryEntry>, order: List<String>): List<String> =
|
||||
(listOf(Library.SOURCE_STEAM) + arrangeStoreTabs(order, emptySet()).map { it.store.id } + Library.ADDED)
|
||||
.filter { source -> entries.any { it.source == source } }
|
||||
|
||||
/** Survives leaving the page, so Stores can open the Library on one store's owned games. */
|
||||
internal object LibraryView {
|
||||
var source by mutableStateOf(LIBRARY_ALL)
|
||||
var query by mutableStateOf("")
|
||||
var focusFirst = false
|
||||
var ownedRequest by mutableIntStateOf(0)
|
||||
private set
|
||||
|
||||
fun showOwned(store: Store) {
|
||||
fun showOwned(context: android.content.Context, store: Store) {
|
||||
SessionPrefs.setLibraryShowUninstalled(context, true)
|
||||
ownedRequest++
|
||||
source = store.id
|
||||
query = ""
|
||||
focusFirst = true
|
||||
@@ -157,13 +168,20 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
|
||||
val cloudRows = rememberXboxCloudRows(s)
|
||||
val all = remember(s.steamGames, cloudRows, owned, installedStore) { libraryEntries(s.steamGames + cloudRows, owned, installedStore) }
|
||||
LaunchedEffect(Unit) { XboxLibraryFilter.load(ctx) }
|
||||
val sources = LIBRARY_SOURCES.filter { src -> all.any { it.source == src } }
|
||||
var showUninstalled by remember(LibraryView.ownedRequest) { mutableStateOf(SessionPrefs.libraryShowUninstalled(ctx)) }
|
||||
val setShowUninstalled = { show: Boolean ->
|
||||
showUninstalled = show
|
||||
SessionPrefs.setLibraryShowUninstalled(ctx, show)
|
||||
}
|
||||
val sources = librarySources(all, SessionPrefs.storesTabOrder(ctx))
|
||||
val source = LibraryView.source.takeIf { it == LIBRARY_ALL || it in sources } ?: LIBRARY_ALL
|
||||
val q = LibraryView.query.trim().lowercase()
|
||||
val xboxFilter = if (source == Store.XBOX.id) XboxLibraryFilter.current else XboxLibraryFilter.ALL
|
||||
val candidates = all.filter {
|
||||
val matching = all.filter {
|
||||
(source == LIBRARY_ALL || it.source == source) && (q.isEmpty() || it.title.lowercase().contains(q)) && keepsXbox(xboxFilter, it)
|
||||
}
|
||||
val candidates = if (showUninstalled) matching else matching.filter { it.installed }
|
||||
val hiddenUninstalled = if (showUninstalled) 0 else matching.count { !it.installed }
|
||||
val sort = s.storesSort
|
||||
val sizeSort = sort == "sizeAsc" || sort == "sizeDesc"
|
||||
val installedAt = StoresState.installed.associate { it.key to it.sidecar.installedAt }
|
||||
@@ -254,7 +272,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
|
||||
val detailScroll = rememberScrollState()
|
||||
var cycled by remember { mutableIntStateOf(0) }
|
||||
var gridFocused by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(source, sort) { grid.scrollToItem(0) }
|
||||
LaunchedEffect(source, sort, showUninstalled) { grid.scrollToItem(0) }
|
||||
LaunchedEffect(cycled) {
|
||||
if (cycled == 0 || ff == null || inputMode.inputMode != androidx.compose.ui.input.InputMode.Keyboard) return@LaunchedEffect
|
||||
focusWithinFrames({ gridFocused }) {
|
||||
@@ -269,7 +287,9 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
|
||||
wrap = { key, content -> StoreTheme(GameRef.parse(key).let { r -> r.store ?: r.game(s.steamGames)?.source?.let { Store.byId(it) } }) { content() } },
|
||||
grid = {
|
||||
LibraryGrid(
|
||||
s, a, grid, visible, split, all.size, sources, source, sizesPending, syncing,
|
||||
s, a, grid, visible, split, visible.size, sources, source, sizesPending, syncing,
|
||||
showUninstalled = showUninstalled.takeIf { stores }, onShowUninstalled = setShowUninstalled,
|
||||
hiddenUninstalled = hiddenUninstalled,
|
||||
onSource = { LibraryView.source = it },
|
||||
onCycle = { step ->
|
||||
val ids = listOf(LIBRARY_ALL) + sources
|
||||
@@ -308,6 +328,7 @@ private fun LibraryEmpty(s: FrontEndState, a: FrontEndActions, modifier: Modifie
|
||||
private fun LibraryGrid(
|
||||
s: FrontEndState, a: FrontEndActions, grid: LazyGridState, visible: List<LibraryEntry>, split: Int, total: Int,
|
||||
sources: List<String>, source: String, sizesPending: Boolean, syncing: List<Pair<Store, String>>,
|
||||
showUninstalled: Boolean?, onShowUninstalled: (Boolean) -> Unit, hiddenUninstalled: Int,
|
||||
onSource: (String) -> Unit, onCycle: (Int) -> Unit, onOpen: (String) -> Unit, onFocus: (Boolean) -> Unit, searchCleared: Boolean,
|
||||
) {
|
||||
val listMode = s.storesView == "list"
|
||||
@@ -361,7 +382,9 @@ private fun LibraryGrid(
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
contentPadding = PaddingValues(top = 4.dp, bottom = 16.dp),
|
||||
) {
|
||||
item(key = "header", span = { GridItemSpan(maxLineSpan) }) { Rise(0) { LibraryHeader(s, a, total, searchCleared, xbox = source == Store.XBOX.id) } }
|
||||
item(key = "header", span = { GridItemSpan(maxLineSpan) }) {
|
||||
Rise(0) { LibraryHeader(s, a, total, searchCleared, source == Store.XBOX.id, showUninstalled, onShowUninstalled) }
|
||||
}
|
||||
item(key = "filters", span = { GridItemSpan(maxLineSpan) }) {
|
||||
Rise(1) { LibraryFilters(sources, source, onSource) }
|
||||
}
|
||||
@@ -379,7 +402,13 @@ private fun LibraryGrid(
|
||||
}
|
||||
}
|
||||
val empty = R.string.stores_nothing_matches
|
||||
if (split == 0) libraryGrid(visible, empty, tile)
|
||||
if (visible.isEmpty() && hiddenUninstalled > 0) item(key = "browse-owned", span = { GridItemSpan(maxLineSpan) }) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.fillMaxWidth().padding(vertical = 32.dp)) {
|
||||
Text(stringResource(R.string.library_no_installed_matches), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
SecondaryButton(stringResource(R.string.library_browse_owned), modifier = Modifier.testTag("library-browse-owned")) { onShowUninstalled(true) }
|
||||
}
|
||||
}
|
||||
else if (split == 0) libraryGrid(visible, empty, tile)
|
||||
else {
|
||||
item(key = "installed-label", span = { GridItemSpan(maxLineSpan) }) { SectionLabel(stringResource(R.string.stores_section_installed)) }
|
||||
libraryGrid(visible.take(split), empty, tile)
|
||||
@@ -399,7 +428,10 @@ private fun LazyGridScope.libraryGrid(entries: List<LibraryEntry>, empty: Int, t
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LibraryHeader(s: FrontEndState, a: FrontEndActions, total: Int, searchCleared: Boolean, xbox: Boolean) {
|
||||
private fun LibraryHeader(
|
||||
s: FrontEndState, a: FrontEndActions, total: Int, searchCleared: Boolean, xbox: Boolean,
|
||||
showUninstalled: Boolean?, onShowUninstalled: (Boolean) -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val narrow = LocalNarrowPane.current
|
||||
ModeHeader(
|
||||
@@ -414,7 +446,7 @@ private fun LibraryHeader(s: FrontEndState, a: FrontEndActions, total: Int, sear
|
||||
}
|
||||
},
|
||||
) {
|
||||
if (xbox) XboxFilterButton()
|
||||
if (showUninstalled != null || xbox) LibraryFilterButton(showUninstalled, onShowUninstalled, xbox)
|
||||
SortButton(s, a)
|
||||
ViewButton(s, a)
|
||||
GameFileFolderActions(s, a)
|
||||
@@ -428,7 +460,7 @@ private fun LibraryFilters(sources: List<String>, source: String, onSource: (Str
|
||||
if (sources.size < 2) return
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(top = 4.dp, bottom = 2.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 2.dp).horizontalScroll(rememberScrollState()),
|
||||
) {
|
||||
SourceFilterChip(LIBRARY_ALL, stringResource(R.string.stores_tab_all), source == LIBRARY_ALL, dot = null) { onSource(LIBRARY_ALL) }
|
||||
for (src in sources) {
|
||||
@@ -506,18 +538,31 @@ private fun LibraryTile(e: LibraryEntry, capsule: Boolean, first: Boolean, navig
|
||||
@Composable
|
||||
private fun RequestSize(e: LibraryEntry) {
|
||||
val ctx = LocalContext.current
|
||||
if (e.installed) {
|
||||
val inst = e.storeKey?.let { k -> StoresState.installed.firstOrNull { it.key == k } }
|
||||
LaunchedEffect(e.key, inst) {
|
||||
if (inst != null) StoreSizes.requestDisk(ctx, inst.key, inst)
|
||||
else e.game?.gameFiles?.let { FolderSizes.request(it) }
|
||||
}
|
||||
return
|
||||
}
|
||||
val item = e.item?.takeIf { !e.installed && it.accessible && it.sizeBytes <= 0 } ?: return
|
||||
LaunchedEffect(item.key) { StoreSizes.request(ctx, item) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LibraryMarker(e: LibraryEntry, download: DownloadEntry?) {
|
||||
internal fun LibraryMarker(e: LibraryEntry, download: DownloadEntry?) {
|
||||
val pal = LocalPalette.current
|
||||
val size = if (e.installed) e.storeKey?.let { StoreSizes.onDisk[it] }
|
||||
?: e.game?.gameFiles?.let { FolderSizes.known[it.path] }
|
||||
else e.item?.let { StoreSizes.size(it) }?.takeIf { it > 0 }
|
||||
when {
|
||||
download != null -> Text("${download.percent}%", fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
|
||||
e.installed -> Unit
|
||||
e.item != null && StoresState.isUnfinished(e.item) -> Text(stringResource(R.string.stores_resume), fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
|
||||
else -> Icon(Icons.Outlined.Download, stringResource(R.string.stores_section_not_installed), tint = Color.White, modifier = Modifier.size(12.dp))
|
||||
else -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
if (size != null && size > 0) Text(formatBytes(size), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 1)
|
||||
if (!e.installed) Icon(Icons.Outlined.Download, stringResource(R.string.stores_section_not_installed), tint = Color.White, modifier = Modifier.size(12.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -599,7 +644,7 @@ private fun Modifier.paneEntry(): Modifier {
|
||||
|
||||
internal fun keepsXbox(filter: String, e: LibraryEntry): Boolean = when {
|
||||
filter == XboxLibraryFilter.ALL || e.source != Store.XBOX.id -> true
|
||||
e.game?.library == Library.XBOX_CLOUD -> filter == XboxLibraryFilter.CLOUD
|
||||
e.game?.library == Library.XBOX_CLOUD && e.item == null -> filter == XboxLibraryFilter.CLOUD
|
||||
else -> e.item?.let { XboxLibraryFilter.keeps(filter, it) } == true
|
||||
}
|
||||
|
||||
@@ -612,24 +657,38 @@ private fun xboxFilterLabel(filter: String): String = when (filter) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun XboxFilterButton() {
|
||||
private fun LibraryFilterButton(showUninstalled: Boolean?, onShowUninstalled: (Boolean) -> Unit, xbox: Boolean) {
|
||||
val pal = LocalPalette.current
|
||||
val ctx = LocalContext.current
|
||||
val title = stringResource(R.string.xbox_filter_show)
|
||||
val title = stringResource(R.string.library_filter)
|
||||
val visibility = stringResource(if (showUninstalled == true) R.string.library_filter_all_owned else R.string.library_filter_installed)
|
||||
val description = title + " · " + if (showUninstalled == null) xboxFilterLabel(XboxLibraryFilter.current) else visibility
|
||||
val offset = if (showUninstalled == null) 0 else 2
|
||||
var at by remember { mutableStateOf<Rect?>(null) }
|
||||
Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }) {
|
||||
HeaderIconButton(title + " · " + xboxFilterLabel(XboxLibraryFilter.current), Icons.Filled.FilterList, "xbox-filter") {
|
||||
HeaderIconButton(description, Icons.Filled.FilterAlt, "library-filter") {
|
||||
val from = at ?: return@HeaderIconButton
|
||||
Steps.ask(StepAsk(
|
||||
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = XboxLibraryFilter.ALL_FILTERS.size,
|
||||
handle = { Text(title, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = pal.signal, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = offset + if (xbox) XboxLibraryFilter.ALL_FILTERS.size else 0,
|
||||
handle = { Icon(Icons.Filled.FilterAlt, null, tint = pal.signal, modifier = Modifier.size(18.dp)) },
|
||||
) {
|
||||
StepTitle(title)
|
||||
StepList {
|
||||
XboxLibraryFilter.ALL_FILTERS.forEachIndexed { i, filter ->
|
||||
if (showUninstalled != null) listOf(false, true).forEachIndexed { i, show ->
|
||||
StepChoice(
|
||||
stringResource(if (show) R.string.library_filter_all_owned else R.string.library_filter_installed),
|
||||
selected = show == showUninstalled, enabled = open,
|
||||
modifier = Modifier.fillMaxWidth().stepItem(i).then(if (show == showUninstalled) Modifier.focusRequester(first) else Modifier),
|
||||
) {
|
||||
onShowUninstalled(show)
|
||||
Steps.fold()
|
||||
}
|
||||
}
|
||||
if (xbox && showUninstalled != null) Text(Store.XBOX.shortLabel, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.stepItem(offset).padding(start = 4.dp, top = 10.dp, bottom = 4.dp))
|
||||
if (xbox) XboxLibraryFilter.ALL_FILTERS.forEachIndexed { i, filter ->
|
||||
StepChoice(
|
||||
xboxFilterLabel(filter), selected = filter == XboxLibraryFilter.current, enabled = open,
|
||||
modifier = Modifier.fillMaxWidth().stepItem(i).then(if (filter == XboxLibraryFilter.current) Modifier.focusRequester(first) else Modifier),
|
||||
modifier = Modifier.fillMaxWidth().stepItem(offset + i).then(if (showUninstalled == null && filter == XboxLibraryFilter.current) Modifier.focusRequester(first) else Modifier),
|
||||
) {
|
||||
XboxLibraryFilter.set(ctx, filter)
|
||||
Steps.fold()
|
||||
@@ -651,7 +710,7 @@ private fun SortButton(s: FrontEndState, a: FrontEndActions) {
|
||||
val from = at ?: return@HeaderIconButton
|
||||
Steps.ask(StepAsk(
|
||||
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = SessionPrefs.STORES_SORTS.size,
|
||||
handle = { Text(title, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = pal.signal, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
handle = { Icon(Icons.Filled.Sort, null, tint = pal.signal, modifier = Modifier.size(18.dp)) },
|
||||
) {
|
||||
StepTitle(title)
|
||||
StepList {
|
||||
|
||||
@@ -641,7 +641,11 @@ internal fun LiftHero(
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun handleBob(): Float {
|
||||
internal fun Handle(height: Dp, above: Boolean = false) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val shape = if (above) RoundedCornerShape(topStart = 12.dp, topEnd = 12.dp) else RoundedCornerShape(bottomStart = 12.dp, bottomEnd = 12.dp)
|
||||
val still = Motion.scale == 0f
|
||||
val bob = androidx.compose.animation.core.rememberInfiniteTransition(label = "handle")
|
||||
val lift by bob.animateFloat(
|
||||
0f, 0f,
|
||||
@@ -656,16 +660,6 @@ private fun handleBob(): Float {
|
||||
),
|
||||
label = "handleBob",
|
||||
)
|
||||
return lift
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun Handle(height: Dp, above: Boolean = false) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val shape = if (above) RoundedCornerShape(topStart = 12.dp, topEnd = 12.dp) else RoundedCornerShape(bottomStart = 12.dp, bottomEnd = 12.dp)
|
||||
val still = Motion.scale == 0f || !ambientAwake()
|
||||
val lift = if (still) 0f else handleBob()
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
modifier = Modifier.height(height).clip(shape).background(colors.surface)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.R
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
@@ -12,7 +13,7 @@ import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.selection.toggleable
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
@@ -46,9 +47,9 @@ fun ChooseAppDisplayDialog(
|
||||
?: stringResource(R.string.main_secondary_gone),
|
||||
)
|
||||
},
|
||||
confirmButton = { TextButton(onClick = onPrimary) { Text(stringResource(R.string.main_primary)) } },
|
||||
confirmButton = { TextButton(onClick = onPrimary, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.main_primary)) } },
|
||||
dismissButton = {
|
||||
TextButton(onClick = onSecondary, enabled = secondaryDisplay != null) {
|
||||
TextButton(onClick = onSecondary, enabled = secondaryDisplay != null, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.main_secondary))
|
||||
}
|
||||
},
|
||||
@@ -61,8 +62,8 @@ fun ConfirmDialog(title: String, text: String, confirm: String, onConfirm: () ->
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(title) },
|
||||
text = { Text(text) },
|
||||
confirmButton = { TextButton(onClick = { onDismiss(); onConfirm() }) { Text(confirm) } },
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } },
|
||||
confirmButton = { TextButton(onClick = { onDismiss(); onConfirm() }, modifier = Modifier.focusGlide(CircleShape)) { Text(confirm) } },
|
||||
dismissButton = { TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -72,11 +73,11 @@ fun RuntimeActionsDialog(onRepair: () -> Unit, onRemove: () -> Unit, onDismiss:
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(stringResource(R.string.runtime_actions_title)) },
|
||||
text = { Text(stringResource(R.string.runtime_actions_text)) },
|
||||
confirmButton = { TextButton(onClick = onRepair) { Text(stringResource(R.string.runtime_repair)) } },
|
||||
confirmButton = { TextButton(onClick = onRepair, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.runtime_repair)) } },
|
||||
dismissButton = {
|
||||
Row {
|
||||
TextButton(onClick = onRemove) { Text(stringResource(R.string.store_remove)) }
|
||||
TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) }
|
||||
TextButton(onClick = onRemove, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.store_remove)) }
|
||||
TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) }
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -92,7 +93,7 @@ fun ResetSettingsDialog(onConfirm: (gameProfiles: Boolean) -> Unit, onDismiss: (
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text(stringResource(R.string.setup_reset_settings_body))
|
||||
Row(
|
||||
Modifier.fillMaxWidth().toggleable(gameProfiles, role = Role.Checkbox) { gameProfiles = it },
|
||||
Modifier.fillMaxWidth().focusGlide().toggleable(gameProfiles, role = Role.Checkbox) { gameProfiles = it },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Checkbox(checked = gameProfiles, onCheckedChange = null)
|
||||
@@ -102,10 +103,10 @@ fun ResetSettingsDialog(onConfirm: (gameProfiles: Boolean) -> Unit, onDismiss: (
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = { onDismiss(); onConfirm(gameProfiles) }) {
|
||||
TextButton(onClick = { onDismiss(); onConfirm(gameProfiles) }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.setup_reset_settings_button), color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
},
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } },
|
||||
dismissButton = { TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.foundation.clickable
|
||||
@@ -7,7 +8,7 @@ import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
@@ -59,7 +60,6 @@ class ModeSettings(
|
||||
val hdr: Boolean,
|
||||
val hdrReason: String?,
|
||||
val gpuDrivers: String? = null,
|
||||
val fpsLimit: Int = 0,
|
||||
val performanceMode: Boolean = false,
|
||||
val upscaler: Int = 0,
|
||||
val upscaleSharpness: Int = 75,
|
||||
@@ -116,7 +116,6 @@ class ModeSettingsActions(
|
||||
val onResolution: (String) -> Unit,
|
||||
val onHdr: (Boolean) -> Unit,
|
||||
val onGpuDrivers: () -> Unit = {},
|
||||
val onFpsLimit: (Int) -> Unit = {},
|
||||
val onPerformanceMode: (Boolean) -> Unit = {},
|
||||
val onUpscaler: (Int) -> Unit = {},
|
||||
val onUpscaleSharpness: (Int) -> Unit = {},
|
||||
@@ -160,7 +159,7 @@ class ModeSettingsActions(
|
||||
val onDismiss: () -> Unit,
|
||||
)
|
||||
|
||||
/** "2610 r3" from droiddeck-steam-x64's FEX_TAG line (fex-2610-r3), the build the x86-64 client downloads. */
|
||||
/** "2610 r3" from droiddeck-fex-update's FEX_TAG line (fex-2610-r3), the build x86 programs fall back to. */
|
||||
internal fun fexVersionOf(script: String): String? =
|
||||
Regex("""(?m)^FEX_TAG=(fex-\d+-r\d+)\s*$""").find(script)?.let { fexVersionOfTag(it.groupValues[1]) }
|
||||
|
||||
@@ -175,7 +174,7 @@ private fun x64FexVersion(context: android.content.Context): String? = remember
|
||||
runCatching { java.io.File(root, "usr/local/share/fex-emu/.droiddeck-tag").readText() }.getOrNull()?.let(::fexVersionOfTag)
|
||||
?: com.droiddeck.launcher.session.FexCatalog.cached(context)?.tag?.let(::fexVersionOfTag)
|
||||
?: runCatching {
|
||||
context.assets.open("linuxfs/usr/local/bin/droiddeck-steam-x64").bufferedReader().use { fexVersionOf(it.readText()) }
|
||||
context.assets.open("linuxfs/usr/local/bin/droiddeck-fex-update").bufferedReader().use { fexVersionOf(it.readText()) }
|
||||
}.getOrNull()
|
||||
}
|
||||
|
||||
@@ -211,9 +210,16 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
val host = rememberMenuHost()
|
||||
var explainWifiDiscovery by remember { mutableStateOf(false) }
|
||||
if (tab == SheetTab.DISPLAY) {
|
||||
val displaySize = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(s.panelSize, s.resolution)
|
||||
val context = LocalContext.current
|
||||
val portraitWindow = SessionPrefs.portrait(context)
|
||||
val longSide = maxOf(s.panelSize.first, s.panelSize.second)
|
||||
val shortSide = minOf(s.panelSize.first, s.panelSize.second)
|
||||
val controlsBelow = SessionPrefs.controlsBelowWanted(context, s.mode,
|
||||
if (portraitWindow) shortSide else longSide, if (portraitWindow) longSide else shortSide)
|
||||
val portrait = portraitWindow && !controlsBelow
|
||||
val displaySize = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(s.panelSize, s.resolution, portrait)
|
||||
SettingsGroup(stringResource(R.string.display_session)) {
|
||||
ResolutionRow(host, s.resolution, s.panelSize, a.onResolution)
|
||||
ResolutionRow(host, s.resolution, s.panelSize, a.onResolution, portrait = portrait)
|
||||
s.picturePosition?.let { position ->
|
||||
ChoiceRow(host, "picture-position", stringResource(R.string.display_picture_position), null,
|
||||
listOf("top" to stringResource(R.string.display_position_top),
|
||||
@@ -245,8 +251,6 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
SettingsGroup(stringResource(R.string.display_frame_rate)) {
|
||||
ToggleRow(host, "performance", stringResource(R.string.mode_performance), stringResource(R.string.mode_performance_hint),
|
||||
s.performanceMode, onChange = a.onPerformanceMode)
|
||||
ChoiceRow(host, "fps", stringResource(R.string.mode_fps), stringResource(R.string.common_applies_next_session),
|
||||
SessionPrefs.fpsLimitChoices(LocalContext.current), s.fpsLimit, note = stringResource(R.string.mode_fps_note), onPick = a.onFpsLimit)
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.mode_hdr)) {
|
||||
ToggleRow(
|
||||
@@ -309,6 +313,9 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
true to stringResource(SessionPrefs.BACK_QAM_THEN_MENU),
|
||||
), s.backActionsInverted, onPick = a.onBackActionsInverted,
|
||||
)
|
||||
if (steam && s.steamController in listOf(SessionPrefs.CONTROLLER_DECK, SessionPrefs.CONTROLLER_STEAM)) {
|
||||
Note(stringResource(R.string.back_native_qam_hint))
|
||||
}
|
||||
}
|
||||
}
|
||||
if (tab == SheetTab.AUDIO && steam) {
|
||||
@@ -530,12 +537,12 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
title = { Text(stringResource(R.string.mode_wifi_explain_title)) },
|
||||
text = { Text(stringResource(R.string.mode_wifi_explain_text)) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = { explainWifiDiscovery = false; a.onWifiDiscovery(true) }) {
|
||||
TextButton(onClick = { explainWifiDiscovery = false; a.onWifiDiscovery(true) }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(if (s.wifiDiscoveryBlocked) R.string.mode_wifi_open_settings else R.string.mode_wifi_continue))
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { explainWifiDiscovery = false }) { Text(stringResource(R.string.common_cancel)) }
|
||||
TextButton(onClick = { explainWifiDiscovery = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) }
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -582,14 +589,14 @@ internal fun DeckyZipWarningDialog(onConfirm: () -> Unit, onCancel: () -> Unit)
|
||||
title = { Text(stringResource(R.string.decky_zip_warning_title)) },
|
||||
text = { Text(stringResource(R.string.decky_zip_warning_text)) },
|
||||
confirmButton = {
|
||||
androidx.compose.material3.TextButton(onClick = onConfirm, enabled = left == 0) {
|
||||
androidx.compose.material3.TextButton(onClick = onConfirm, enabled = left == 0, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(
|
||||
if (left > 0) androidx.compose.ui.res.pluralStringResource(R.plurals.decky_zip_warning_wait, left, left)
|
||||
else stringResource(R.string.decky_zip_warning_continue),
|
||||
)
|
||||
}
|
||||
},
|
||||
dismissButton = { androidx.compose.material3.TextButton(onClick = onCancel) { Text(stringResource(R.string.common_cancel)) } },
|
||||
dismissButton = { androidx.compose.material3.TextButton(onClick = onCancel, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -624,7 +631,7 @@ private fun DeckyUninstall(enabled: Boolean, onUninstall: () -> Unit) {
|
||||
@Composable
|
||||
internal fun SgdbKeyDialog(hasKey: Boolean, onSave: (String) -> Unit, onDismiss: () -> Unit) {
|
||||
var key by remember { mutableStateOf("") }
|
||||
androidx.compose.material3.AlertDialog(
|
||||
com.droiddeck.launcher.ui.GlideAlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(stringResource(R.string.mode_sgdb_key)) },
|
||||
text = {
|
||||
@@ -632,14 +639,14 @@ internal fun SgdbKeyDialog(hasKey: Boolean, onSave: (String) -> Unit, onDismiss:
|
||||
key, { v -> key = v.trim() }, label = { Text(stringResource(R.string.mode_sgdb_key)) },
|
||||
singleLine = true, visualTransformation = androidx.compose.ui.text.input.PasswordVisualTransformation(),
|
||||
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Password),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
modifier = Modifier.fillMaxWidth().focusGlide(),
|
||||
)
|
||||
},
|
||||
confirmButton = { androidx.compose.material3.TextButton(onClick = { onSave(key) }, enabled = key.isNotEmpty()) { Text(stringResource(R.string.common_ok)) } },
|
||||
confirmButton = { androidx.compose.material3.TextButton(onClick = { onSave(key) }, enabled = key.isNotEmpty(), modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_ok)) } },
|
||||
dismissButton = {
|
||||
androidx.compose.foundation.layout.Row {
|
||||
if (hasKey) androidx.compose.material3.TextButton(onClick = { onSave("") }) { Text(stringResource(R.string.common_delete)) }
|
||||
androidx.compose.material3.TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) }
|
||||
if (hasKey) androidx.compose.material3.TextButton(onClick = { onSave("") }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_delete)) }
|
||||
androidx.compose.material3.TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) }
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -651,7 +658,7 @@ internal fun CustomResolutionDialog(initial: Pair<Int, Int>?, onSave: (Pair<Int,
|
||||
var w by remember { mutableStateOf(initial?.first?.toString() ?: "") }
|
||||
var h by remember { mutableStateOf(initial?.second?.toString() ?: "") }
|
||||
val parsed = SessionPrefs.parseResolution("${w}x$h")
|
||||
androidx.compose.material3.AlertDialog(
|
||||
com.droiddeck.launcher.ui.GlideAlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(stringResource(R.string.mode_custom_res_title)) },
|
||||
text = {
|
||||
@@ -667,12 +674,12 @@ internal fun CustomResolutionDialog(initial: Pair<Int, Int>?, onSave: (Pair<Int,
|
||||
val numbers = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Number)
|
||||
androidx.compose.material3.OutlinedTextField(
|
||||
w, { v -> w = v.filter(Char::isDigit).take(4) }, label = { Text(stringResource(R.string.mode_width)) },
|
||||
singleLine = true, keyboardOptions = numbers, modifier = Modifier.weight(1f),
|
||||
singleLine = true, keyboardOptions = numbers, modifier = Modifier.weight(1f).focusGlide(),
|
||||
)
|
||||
Text("×", fontSize = 18.sp, modifier = Modifier.padding(horizontal = 10.dp))
|
||||
androidx.compose.material3.OutlinedTextField(
|
||||
h, { v -> h = v.filter(Char::isDigit).take(4) }, label = { Text(stringResource(R.string.mode_height)) },
|
||||
singleLine = true, keyboardOptions = numbers, modifier = Modifier.weight(1f),
|
||||
singleLine = true, keyboardOptions = numbers, modifier = Modifier.weight(1f).focusGlide(),
|
||||
)
|
||||
}
|
||||
androidx.compose.foundation.layout.FlowRow(
|
||||
@@ -683,6 +690,7 @@ internal fun CustomResolutionDialog(initial: Pair<Int, Int>?, onSave: (Pair<Int,
|
||||
androidx.compose.material3.AssistChip(
|
||||
onClick = { w = pw.toString(); h = ph.toString() },
|
||||
label = { Text("$pw×$ph · $tag", fontSize = 12.sp) },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -692,7 +700,7 @@ internal fun CustomResolutionDialog(initial: Pair<Int, Int>?, onSave: (Pair<Int,
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = { androidx.compose.material3.TextButton(enabled = parsed != null, onClick = { parsed?.let(onSave) }) { Text(stringResource(R.string.common_use)) } },
|
||||
dismissButton = { androidx.compose.material3.TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } },
|
||||
confirmButton = { androidx.compose.material3.TextButton(enabled = parsed != null, onClick = { parsed?.let(onSave) }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_use)) } },
|
||||
dismissButton = { androidx.compose.material3.TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
@@ -212,7 +212,7 @@ fun PerformancePage(
|
||||
},
|
||||
singleLine = true, isError = !valid && draft.isNotBlank(),
|
||||
placeholder = { Text(SessionPrefs.DEFAULT_GUEST_HOSTNAME) },
|
||||
modifier = Modifier.width(220.dp),
|
||||
modifier = Modifier.width(220.dp).focusGlide(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.R
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import android.content.Context
|
||||
@@ -17,7 +18,7 @@ import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
@@ -276,12 +277,12 @@ fun DeveloperDisplayChoiceDialog(
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
Text(stringResource(R.string.gate_choose_display))
|
||||
TextButton(modifier = Modifier.fillMaxWidth(), onClick = onMainScreen) { Text(stringResource(R.string.gate_main_screen)) }
|
||||
TextButton(modifier = Modifier.fillMaxWidth().focusGlide(CircleShape), onClick = onMainScreen) { Text(stringResource(R.string.gate_main_screen)) }
|
||||
displays.forEach { (id, label) ->
|
||||
TextButton(modifier = Modifier.fillMaxWidth(), onClick = { onSecondaryScreen(id) }) { Text(label) }
|
||||
TextButton(modifier = Modifier.fillMaxWidth().focusGlide(CircleShape), onClick = { onSecondaryScreen(id) }) { Text(label) }
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } },
|
||||
confirmButton = { TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
@@ -14,16 +14,17 @@ import com.droiddeck.launcher.session.SessionDisplay
|
||||
fun ResolutionRow(
|
||||
host: MenuHost, choice: String, panel: Pair<Int, Int>, onPick: (String) -> Unit,
|
||||
chipModifier: Modifier = Modifier,
|
||||
portrait: Boolean = false,
|
||||
) {
|
||||
val custom = "custom"
|
||||
val size = SessionDisplay.resolveChoice(panel, choice)
|
||||
val screen = SessionDisplay.screenSize(panel)
|
||||
val size = SessionDisplay.resolveChoice(panel, choice, portrait)
|
||||
val screen = SessionDisplay.resolveChoice(panel, SessionDisplay.MATCH_SCREEN, portrait)
|
||||
val choices = SessionDisplay.resolutionOptions(panel)
|
||||
val selected = if (choice == SessionDisplay.FOLLOW_SCREEN) choice
|
||||
else if (size == screen) SessionDisplay.MATCH_SCREEN else choice
|
||||
var editCustom by remember { mutableStateOf(false) }
|
||||
val options = choices.map { value ->
|
||||
val dimensions = SessionDisplay.resolveChoice(panel, value)
|
||||
val dimensions = SessionDisplay.resolveChoice(panel, value, portrait)
|
||||
value to if (value == SessionDisplay.MATCH_SCREEN) stringResource(R.string.display_match_screen, screen.first, screen.second)
|
||||
else if (value == SessionDisplay.FOLLOW_SCREEN) stringResource(R.string.display_follow_screen)
|
||||
else if (value == SessionDisplay.DEFAULT_RESOLUTION) stringResource(R.string.mode_res_default, "${dimensions.first}×${dimensions.second}")
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.R
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
@@ -38,10 +39,10 @@ fun RomsDialog(path: String?, onChoose: () -> Unit, onClear: () -> Unit, onDismi
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = onChoose) { Text(if (path == null) stringResource(R.string.roms_choose) else stringResource(R.string.roms_change)) } },
|
||||
confirmButton = { TextButton(onClick = onChoose, modifier = Modifier.focusGlide(CircleShape)) { Text(if (path == null) stringResource(R.string.roms_choose) else stringResource(R.string.roms_change)) } },
|
||||
dismissButton = {
|
||||
if (path != null) TextButton(onClick = onClear) { Text(stringResource(R.string.common_forget)) }
|
||||
else TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) }
|
||||
if (path != null) TextButton(onClick = onClear, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_forget)) }
|
||||
else TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) }
|
||||
},
|
||||
)
|
||||
}
|
||||
Loaded 100 of 1045 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user