diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 146e7fe3b..1d39651c0 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -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:
diff --git a/README.md b/README.md
index 653df9f72..794e272cc 100644
--- a/README.md
+++ b/README.md
@@ -9,6 +9,10 @@ DroidDeck brings the SteamOS experience to Android: Valve's Steam client in Big

+
+
+
+
@@ -57,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. The registry entries a GOG game's install script (`goggame-.script`) sets are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher)'s GOG setup (GPL-3.0) reads them. LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. x86 AppImages, and any whose own runtime cannot unpack them, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence, which also starts the arm64 emulator AppImages whose own runtime cannot run its extractor on Android. The Steam client's audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink` with its request size kept to its ring so clients are not asked to queue 100 ms ahead. mmap ring-buffer controller input was developed by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). Why the x86-64 Steam client refused the arm64 client's sign-in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest). x86 programs that link OpenSSL 3 under FEX use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt) platform. Hooks written with `WriteProcessMemory` into code [FEX](https://github.com/FEX-Emu/FEX) has translated go through `/proc//mem` again when the kernel refuses `process_vm_writev`, as [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` wrote them before Wine 11. x86 Linux games under FEX get the same `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes into the Steam Linux Runtime, so ALSA plays through PulseAudio. Games render with [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's own per-render-pass choice between tile memory and system memory, while the Steam client keeps `TU_DEBUG=sysmem`; [FEX](https://github.com/FEX-Emu/FEX)'s code disk cache was checked in its source and is already on through Proton. The proot fast path picks the guest name of a host file bound under several names in the order [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later) sorts its bindings, so links and `/proc/self/fd` read back as they do through proot. The session's [PipeWire](https://gitlab.freedesktop.org/pipewire/pipewire) (MIT) opens its sockets with the per-socket access settings documented in its `module-access.c`, and [WirePlumber](https://gitlab.freedesktop.org/pipewire/wireplumber) (MIT) keeps those clients at full permissions through its `access.rules`. Wine write watches use the userfaultfd support in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/ntdll/unix/virtual.c` (LGPL-2.1-or-later): libblsession gives it the arm64 syscall number and answers its `PAGEMAP_SCAN` from `/proc/self/pagemap` where Android refuses the ioctl. Wine on arm64 sets a thread's full context by raising `SIGUSR2` from `syscall_dispatcher_return_slowpath` in [Wine](https://gitlab.winehq.org/wine/wine)'s `dlls/ntdll/unix/signal_arm64.c` (LGPL-2.1-or-later); libblsession runs that handler in place on a frame laid out as the [Linux](https://github.com/torvalds/linux) kernel's `arch/arm64/kernel/signal.c` builds it and returns through `rt_sigreturn`, so proot does not stop the thread for it. Wine's process list reads each process's memory counters from `/proc//status` in `fill_vm_counters` ([Wine](https://gitlab.winehq.org/wine/wine) `dlls/ntdll/unix/process.c`, LGPL-2.1-or-later), so libblsession gives those reads the kernel's file instead of a copy with `TracerPid` cleared. droiddeck-ntsync is checked against the object, wait and error semantics documented for the [Linux](https://github.com/torvalds/linux) ntsync driver in `Documentation/userspace-api/ntsync.rst` (GPL-2.0). Xbox games load the Windows modules of [@domsvoboda](https://github.com/domsvoboda)'s [xodus-nexus](https://github.com/domsvoboda/xodus-nexus) runtime (LGPL-2.1-or-later), including its `wintypes.dll`, whose `ApiInformation` answer Minecraft for Windows needs to start; how Minecraft installs GameInput under Wine was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT). See [LICENSE](LICENSE). Steam and Proton belong to Valve Corporation; this project is not affiliated with Valve.
+GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). Epic Games and GOG support build on [Phobos’s](https://github.com/phobos665) adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl), respectively. Battle.net support is [@kayakyakr](https://github.com/kayakyakr)'s: it runs Blizzard's own Battle.net client, downloaded from Blizzard and not included, in Proton, and shows the key art from each game's [Battle.net Shop](https://shop.battle.net) page; without the Steam client its games see DroidDeck's pad as an Xbox 360 controller through `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`. Its games install from Stores through Blizzard's own Agent and the local HTTP API it serves, driven the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) drives it, with the requests described on [wowdev.wiki](https://wowdev.wiki/Agent); how other launchers find, install and start Blizzard games was read in [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader, without taking their code. The registry entries a GOG game's install script (`goggame-.script`) sets are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher)'s GOG setup (GPL-3.0) reads them. LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. x86 AppImages, and any whose own runtime cannot unpack them, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence, which also starts the arm64 emulator AppImages whose own runtime cannot run its extractor on Android. The Steam client's audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink` with its request size kept to its ring so clients are not asked to queue 100 ms ahead. mmap ring-buffer controller input was developed by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). Why the x86-64 Steam client refused the arm64 client's sign-in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest). x86 programs that link OpenSSL 3 under FEX use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt) platform. Hooks written with `WriteProcessMemory` into code [FEX](https://github.com/FEX-Emu/FEX) has translated go through `/proc//mem` again when the kernel refuses `process_vm_writev`, as [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` wrote them before Wine 11. x86 Linux games under FEX get the same `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes into the Steam Linux Runtime, so ALSA plays through PulseAudio. Games render with [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's own per-render-pass choice between tile memory and system memory, while the Steam client keeps `TU_DEBUG=sysmem`; [FEX](https://github.com/FEX-Emu/FEX)'s code disk cache was checked in its source and is already on through Proton. The proot fast path picks the guest name of a host file bound under several names in the order [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later) sorts its bindings, so links and `/proc/self/fd` read back as they do through proot. The session's [PipeWire](https://gitlab.freedesktop.org/pipewire/pipewire) (MIT) opens its sockets with the per-socket access settings documented in its `module-access.c`, and [WirePlumber](https://gitlab.freedesktop.org/pipewire/wireplumber) (MIT) keeps those clients at full permissions through its `access.rules`. Wine write watches use the userfaultfd support in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/ntdll/unix/virtual.c` (LGPL-2.1-or-later): libblsession gives it the arm64 syscall number and answers its `PAGEMAP_SCAN` from `/proc/self/pagemap` where Android refuses the ioctl. Wine on arm64 sets a thread's full context by raising `SIGUSR2` from `syscall_dispatcher_return_slowpath` in [Wine](https://gitlab.winehq.org/wine/wine)'s `dlls/ntdll/unix/signal_arm64.c` (LGPL-2.1-or-later); libblsession runs that handler in place on a frame laid out as the [Linux](https://github.com/torvalds/linux) kernel's `arch/arm64/kernel/signal.c` builds it and returns through `rt_sigreturn`, so proot does not stop the thread for it. Wine's process list reads each process's memory counters from `/proc//status` in `fill_vm_counters` ([Wine](https://gitlab.winehq.org/wine/wine) `dlls/ntdll/unix/process.c`, LGPL-2.1-or-later), so libblsession gives those reads the kernel's file instead of a copy with `TracerPid` cleared. droiddeck-ntsync is checked against the object, wait and error semantics documented for the [Linux](https://github.com/torvalds/linux) ntsync driver in `Documentation/userspace-api/ntsync.rst` (GPL-2.0). Xbox games load the Windows modules of [@domsvoboda](https://github.com/domsvoboda)'s [xodus-nexus](https://github.com/domsvoboda/xodus-nexus) runtime (LGPL-2.1-or-later), including its `wintypes.dll`, whose `ApiInformation` answer Minecraft for Windows needs to start; how Minecraft installs GameInput under Wine was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT). See [LICENSE](LICENSE). Steam and Proton belong to Valve Corporation; this project is not affiliated with Valve.
XR glasses support builds on WinNative's VITURE glasses work. VITURE protocol details were checked against [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) by [@wheaney](https://github.com/wheaney), including the VITURE protocol header it ships, [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) by [@badicsalex](https://github.com/badicsalex) and the [go-macos/iokit VITURE package](https://pkg.go.dev/github.com/go-macos/iokit/viture); the optional VITURE SDK belongs to VITURE and is not included. RayNeo support adapts [@informalTechCode](https://github.com/informalTechCode)'s [RayNeo-Air-Series-3DoF-Scaffold](https://github.com/informalTechCode/RayNeo-Air-Series-3DoF-Scaffold) (Apache-2.0) and references [@verncat](https://github.com/verncat)'s [RayNeo-Air-3S-Pro-OpenVR](https://github.com/verncat/RayNeo-Air-3S-Pro-OpenVR) (MIT) and [Monado](https://gitlab.freedesktop.org/monado/monado) (BSL-1.0); see [docs/third-party/rayneo](docs/third-party/rayneo/README.md). XREAL 1S support references [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) and [xrealOneDeviceKit](https://github.com/wheaney/xrealOneDeviceKit) by @wheaney, [xreal_one_driver](https://github.com/rohitsangwan01/xreal_one_driver) by [@rohitsangwan01](https://github.com/rohitsangwan01) (MIT) and [xr-tools](https://github.com/0xcaff/xr-tools) by [@0xcaff](https://github.com/0xcaff). Rokid support follows the Rokid protocol notes in [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) and @badicsalex's [Void Computing write-ups](https://voidcomputing.hu/blog/worse-better-prettier/), and [Monado](https://gitlab.freedesktop.org/monado/monado)'s Rokid driver. The REDMAGIC glasses-display findings draw on [@mekhontsev](https://github.com/mekhontsev)'s [MagicDesk investigation](https://github.com/mekhontsev/magicdesk/blob/main/docs/xr-resolution-fix.md) and [@Coding-BR](https://github.com/Coding-BR)'s [decompiled Nubia kernel](https://github.com/Coding-BR/android_kernel_nubia_sm8850_qwjujube). VITURE, RayNeo, XREAL, Rokid and REDMAGIC are trademarks of their owners; this project is not affiliated with them.
@@ -68,3 +72,5 @@ Camera hand tracking runs Google's [MediaPipe](https://github.com/google-ai-edge
The Store installs and runs apps with [Flatpak](https://github.com/flatpak/flatpak) (LGPL-2.1). Its sandbox goes through DroidDeck's own bubblewrap shim, which follows how Flatpak hands bwrap its environment. Chromium and Electron apps from Flathub start their browser processes through [zypak](https://github.com/refi64/zypak) by [@refi64](https://github.com/refi64) (BSD-3-Clause); its source was read to see that it always spawns them through Flatpak's spawn portal, which is why DroidDeck starts them directly without Chromium's sandbox instead.
Steam's Browse buttons open a GTK 3 file chooser through PyGObject (LGPL-2.1-or-later). It runs under Steam's own `reaper` with Steam's app ID, which [gamescope](https://github.com/ValveSoftware/gamescope) (BSD-2-Clause) reads from the process tree (`GetAppIdFromReaper` in `src/Utils/Process.cpp`) to show it over Steam.
+
+Black Ops III and Dark Souls Remastered start without [umu-protonfixes](https://github.com/Open-Wine-Components/umu-protonfixes) (BSD-2-Clause), whose fixes for them (`311210.py` sets ALSA audio, `570940.py` installs VC++ 2017) fail under ARM64 Proton.
diff --git a/app/build.gradle b/app/build.gradle
index 8ba8c8ea0..1c9b9bad8 100644
--- a/app/build.gradle
+++ b/app/build.gradle
@@ -87,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')
@@ -262,6 +270,7 @@ def runtimeAssetsDir = layout.buildDirectory.dir('runtimeAssets')
def stageRuntimeAssets = tasks.register('stageRuntimeAssets', Sync) {
dependsOn(stageSessionScripts)
from(layout.projectDirectory.dir('src/main/assets')) { exclude 'pulseaudio.tzst' }
+ from(rootProject.file('tools/linuxfs/innoextract'))
from(layout.buildDirectory.dir('prepared-assets'))
into(runtimeAssetsDir)
}
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 29718e087..1ce7b0ac7 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -2,6 +2,15 @@
+
+
+
+
+
+
+
+
+
@@ -64,7 +73,7 @@
@@ -116,7 +125,7 @@
android:excludeFromRecents="true"
android:noHistory="true"
android:taskAffinity="${applicationId}.home"
- android:screenOrientation="sensorLandscape"
+ android:screenOrientation="user"
android:theme="@android:style/Theme.Translucent.NoTitleBar">
@@ -137,14 +146,14 @@
@@ -176,7 +185,7 @@
diff --git a/app/src/main/cpp/framegen/ddfg/framegen.cpp b/app/src/main/cpp/framegen/ddfg/framegen.cpp
index 82d0a764b..5200f6b09 100644
--- a/app/src/main/cpp/framegen/ddfg/framegen.cpp
+++ b/app/src/main/cpp/framegen/ddfg/framegen.cpp
@@ -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;
diff --git a/app/src/main/cpp/framegen/ddfg/record_impl.inc b/app/src/main/cpp/framegen/ddfg/record_impl.inc
index 554c05c7f..734d94cdc 100644
--- a/app/src/main/cpp/framegen/ddfg/record_impl.inc
+++ b/app/src/main/cpp/framegen/ddfg/record_impl.inc
@@ -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);
}
diff --git a/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c b/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c
index 6cf0c8037..cb4447835 100644
--- a/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c
+++ b/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c
@@ -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();
}
diff --git a/app/src/main/cpp/waylandcomp/src/compositor.c b/app/src/main/cpp/waylandcomp/src/compositor.c
index 562a83a75..256d8f659 100644
--- a/app/src/main/cpp/waylandcomp/src/compositor.c
+++ b/app/src/main/cpp/waylandcomp/src/compositor.c
@@ -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];
@@ -264,6 +268,8 @@ static struct wl_event_source *g_fallback_timer;
static int g_fallback_armed;
volatile int g_fps_limit;
+/* fps limit -1 (Performance mode without a limit): replaced buffers go back to the client at once instead of once per refresh. */
+volatile int g_release_unpaced;
volatile int g_hide_shell;
@@ -371,7 +377,7 @@ static int on_release_timer(int fd, uint32_t mask, void *data) {
static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_t since_ns) {
const int limit = g_fps_limit;
const int64_t interval = limit > 0 ? 1000000000LL / limit : g_refresh_ns;
- if (interval <= 0 || g_release_timer_fd < 0) { wl_buffer_send_release(buffer); perf_note_release(since_ns); return; }
+ if (g_release_unpaced || interval <= 0 || g_release_timer_fd < 0) { wl_buffer_send_release(buffer); perf_note_release(since_ns); return; }
int64_t now = now_ns();
int64_t at = s->next_release_ns + interval;
int64_t latest = now + interval * (int64_t)(s->releases_pending + 1);
@@ -622,6 +628,17 @@ 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 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);
@@ -644,6 +661,32 @@ 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;
+ droiddeck_on_game_frame();
+ }
+ }
}
static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resource *buffer) {
@@ -660,14 +703,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) {
@@ -784,8 +819,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));
}
@@ -985,6 +1057,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);
@@ -1049,7 +1124,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 = {
@@ -1092,6 +1170,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);
diff --git a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c
index 16e42d1b5..e6bb03027 100644
--- a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c
+++ b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c
@@ -34,6 +34,7 @@ extern unsigned droiddeck_stream_frames(void);
extern void droiddeck_wayland_output_resized(void);
extern void droiddeck_wayland_set_output_refresh_rate(int mhz);
extern volatile int g_fps_limit;
+extern volatile int g_release_unpaced;
extern volatile int g_hide_shell;
extern volatile int g_zero_copy;
extern volatile unsigned g_zero_copy_last;
@@ -574,6 +575,7 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetLookName(JNIEnv *
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFpsLimit(JNIEnv *env, jclass clazz, jint fps) {
g_fps_limit = fps > 0 ? fps : 0;
+ g_release_unpaced = fps < 0;
__android_log_print(ANDROID_LOG_INFO, TAG, "fps limit %d", fps);
}
diff --git a/app/src/main/java/com/droiddeck/launcher/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt
index 928d7caa8..324941bd4 100644
--- a/app/src/main/java/com/droiddeck/launcher/App.kt
+++ b/app/src/main/java/com/droiddeck/launcher/App.kt
@@ -53,6 +53,7 @@ class App : Application() {
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.amazon.AmazonBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.itch.ItchBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.xbox.XboxBackend)
+ com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.battlenet.BattleNetBackend)
}
/** Fetches the packs an existing setup already relies on, so the first use after an update does not wait. */
diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt
index e2ce59eff..1f754d0b7 100644
--- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt
@@ -139,6 +139,7 @@ class FrontEndActivity : ComponentActivity() {
private var pkgPercent by mutableIntStateOf(-1)
private var desktopInstalled by mutableStateOf(false)
private var desktopPresent by mutableStateOf(false)
+ private var battleNetInstalled by mutableStateOf(false)
private var offlineAccount by mutableStateOf(null)
private var offline by mutableStateOf(false)
private var showPerformance by mutableStateOf(false)
@@ -152,6 +153,9 @@ class FrontEndActivity : ComponentActivity() {
private var syncFallback by mutableStateOf(true)
private var fsyncFirst by mutableStateOf(false)
private var gamescopeRealtime by mutableStateOf(false)
+ private var ramCapMb by mutableStateOf(0)
+ private var zramClient by mutableStateOf(true)
+ private var vramCapMb by mutableStateOf(0)
private var gpuClockPin by mutableStateOf(false)
private var prootNoSeccomp by mutableStateOf(false)
private var prootFastPath by mutableStateOf(true)
@@ -164,15 +168,16 @@ 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("")
private var downloadPrefix by mutableStateOf("")
+ private var downloadProxy by mutableStateOf("")
private var animationsEnabled by mutableStateOf(true)
private var launcherIcon by mutableStateOf(LauncherIcon.DARK)
private var gameStoresEnabled by mutableStateOf(true)
private var gameStoresSpeedTier by mutableStateOf("fast")
- private var storesOpenTab by mutableStateOf(SessionPrefs.STORES_OPEN_LIBRARY)
private var navRequest by mutableStateOf(null)
private var storesShowMature by mutableStateOf(false)
private var storesSort by mutableStateOf(SessionPrefs.STORES_SORTS.first())
@@ -387,7 +392,7 @@ 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)
private var hdrReason by mutableStateOf(null)
@@ -412,6 +417,10 @@ class FrontEndActivity : ComponentActivity() {
private var logsEnabled by mutableStateOf(true)
private var vacDiagnostics by mutableStateOf(false)
private var agentCommands by mutableStateOf(false)
+ private var clearCachedApps by mutableStateOf(false)
+ private var adbPaired by mutableStateOf(false)
+ private var memoryHud by mutableStateOf(SessionPrefs.MEMORY_HUD_OFF)
+ private var backgroundAppLimit by mutableStateOf(com.droiddeck.launcher.core.BackgroundAppLimit.OFF)
private var showRoms by mutableStateOf(false)
private var homeAppSelected by mutableStateOf(false)
private var homeScreenEnabled by mutableStateOf(false)
@@ -589,9 +598,11 @@ class FrontEndActivity : ComponentActivity() {
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN)
.putExtra(SessionService.EXTRA_PROGRAM, command.program)
.putExtra(SessionService.EXTRA_PROGRAM_ARGS, command.args.toTypedArray())
+ .putExtra(SessionService.EXTRA_GAME_ID, com.droiddeck.launcher.session.NoSteamLaunch.scope(game))
when {
!SessionState.running -> startSessionOrWait(next)
SessionState.stopRequested -> android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show()
+ command.program == com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET && handToBattleNet(command.args, returnHome) { pendingSwitch = next } -> {}
SessionState.mode == SessionService.MODE_RUN && SessionState.program == command.program && SessionState.programArgs == command.args ->
startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME)
.returnTo(returnHome)
@@ -689,7 +700,8 @@ class FrontEndActivity : ComponentActivity() {
}
private fun startSessionOrWait(next: Intent): Boolean {
- val started = startSession(next, steamSession = next.hasExtra(SessionService.EXTRA_STEAM_URL))
+ val started = startSession(next, steamSession = next.hasExtra(SessionService.EXTRA_STEAM_URL) ||
+ next.getStringExtra(SessionService.EXTRA_PROGRAM) in setOf(com.droiddeck.launcher.session.NoSteamLaunch.PROTON_RUN, com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET))
if (!started && (busy || LinuxRuntimeInstaller.isBusy())) android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
return started
}
@@ -754,6 +766,7 @@ class FrontEndActivity : ComponentActivity() {
gameSyncFolder = GameFileSync.folder(this)
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
refreshPhantomStatus()
+ if (!SessionState.running) com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(this)
theme = SessionPrefs.theme(this)
frameGenLabel = getString(R.string.frame_gen_off)
appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)
@@ -762,18 +775,19 @@ 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)
downloadPrefix = DownloadSource.custom(this)
+ downloadProxy = DownloadSource.proxyHostPort(this)
DownloadSource.probe()
animationsEnabled = SessionPrefs.animationsEnabled(this)
LauncherIcon.repair(this, intent?.component)
launcherIcon = LauncherIcon.current(this)
gameStoresEnabled = SessionPrefs.gameStoresEnabled(this)
gameStoresSpeedTier = SessionPrefs.gameStoresSpeedTier(this)
- storesOpenTab = SessionPrefs.storesOpenTab(this)
storesShowMature = SessionPrefs.storesShowMature(this)
storesSort = SessionPrefs.storesSort(this)
storesView = SessionPrefs.storesView(this)
@@ -803,6 +817,7 @@ class FrontEndActivity : ComponentActivity() {
offlineAccount = offlineAccount, offline = offline,
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled,
vacDiagnostics = vacDiagnostics, agentCommands = agentCommands,
+ clearCachedApps = clearCachedApps, adbPaired = adbPaired, memoryHud = memoryHud, backgroundAppLimit = backgroundAppLimit,
steamGames = steamGames, steamGamesX64 = steamGamesX64, emulators = emulatorList, running = runningLabel,
frameGen = FrameGen.mode(this),
lossless = lossless,
@@ -821,6 +836,7 @@ class FrontEndActivity : ComponentActivity() {
packageStage = pkgStage,
packagePercent = pkgPercent,
sessionRunning = SessionState.running,
+ battleNetInstalled = battleNetInstalled,
backActionsInverted = backActionsInverted,
buildLabel = BuildConfig.BUILD_LABEL,
oscMode = oscMode,
@@ -829,15 +845,16 @@ class FrontEndActivity : ComponentActivity() {
phantomProcessStatus = phantomProcessStatus,
showPhantomGate = showPhantomGate,
orientation = orientation,
+ launcherOrientation = launcherOrientation,
launcherFullscreen = launcherFullscreen,
downloadSource = downloadSource,
downloadMirror = downloadMirror,
downloadPrefix = downloadPrefix,
+ downloadProxy = downloadProxy,
animationsEnabled = animationsEnabled,
launcherIcon = launcherIcon,
gameStoresEnabled = gameStoresEnabled,
gameStoresSpeedTier = gameStoresSpeedTier,
- storesOpenTab = storesOpenTab,
navigate = navRequest,
addedGamesArt = addedGamesArt,
sgdbUserKey = sgdbUserKey,
@@ -909,6 +926,7 @@ class FrontEndActivity : ComponentActivity() {
.putExtra(SessionService.EXTRA_PROGRAM, app.program)
.putExtra(SessionService.EXTRA_PROGRAM_ARGS, app.args.toTypedArray()))
},
+ onBattleNet = { openBattleNet() },
onFlatpakApp = { id, name ->
Library.flatpakNames[id] = name
startActivity(Intent(this, SessionActivity::class.java)
@@ -963,6 +981,12 @@ class FrontEndActivity : ComponentActivity() {
com.droiddeck.launcher.agent.AgentAccess.setCommandsEnabled(this, !com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this))
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
},
+ onClearCachedApps = { on -> SessionPrefs.setClearCachedApps(this, on); clearCachedApps = on },
+ onMemoryHud = { value -> SessionPrefs.setMemoryHud(this, value); memoryHud = value },
+ onBackgroundAppLimit = { limit ->
+ SessionPrefs.setBackgroundAppLimit(this, limit); backgroundAppLimit = limit
+ if (limit == com.droiddeck.launcher.core.BackgroundAppLimit.OFF) com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(this)
+ },
onShareLogs = {
SessionLogShare.prepare(this, { SessionLogShare.latest(this) }) { zip ->
if (zip == null) android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show()
@@ -1004,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 ->
@@ -1012,7 +1040,6 @@ class FrontEndActivity : ComponentActivity() {
applyLauncherFullscreen()
},
onGameStoresSpeedTier = { tier -> SessionPrefs.setGameStoresSpeedTier(this, tier); gameStoresSpeedTier = tier },
- onStoresOpenTab = { tab -> SessionPrefs.setStoresOpenTab(this, tab); storesOpenTab = tab },
onNavigated = { navRequest = null },
onStoresShowMature = { show -> SessionPrefs.setStoresShowMature(this, show); storesShowMature = show },
onStoresSort = { sort -> SessionPrefs.setStoresSort(this, sort); storesSort = sort },
@@ -1035,6 +1062,10 @@ class FrontEndActivity : ComponentActivity() {
DownloadSource.setCustom(this, prefix)
downloadPrefix = DownloadSource.custom(this)
},
+ onDownloadProxy = { value ->
+ DownloadSource.setProxy(this, value)
+ downloadProxy = DownloadSource.proxyHostPort(this)
+ },
onHomeApp = { manageHomeApp() },
onHomeScreen = { on ->
HomeApp.setHomeScreenEnabled(this, on)
@@ -1296,10 +1327,12 @@ 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.QuitFlood.take()?.let { c ->
returning = ReturningFlood(c, com.droiddeck.launcher.ui.LaunchOrigin.takeReturn())
@@ -1366,6 +1399,7 @@ class FrontEndActivity : ComponentActivity() {
unregisterReceiver(mediaReceiver)
ui.removeCallbacks(mediaRefresh)
com.droiddeck.launcher.stores.StoresState.libraryListener = null
+ com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = null
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
flood = null
returning = null
@@ -1559,6 +1593,50 @@ class FrontEndActivity : ComponentActivity() {
desktopPresent = DesktopCatalog.desktopPresent(this)
}
+ private fun openBattleNet(args: List = emptyList()) {
+ if (protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
+ android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
+ return
+ }
+ val app = applicationContext
+ Thread({
+ val full = if (args.firstOrNull() == "--library") args else com.droiddeck.launcher.stores.battlenet.BattleNetClient.library(app) + args
+ ui.post {
+ if (isDestroyed) return@post
+ val next = Intent(this, SessionActivity::class.java)
+ .putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN)
+ .putExtra(SessionService.EXTRA_PROGRAM, com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET)
+ .putExtra(SessionService.EXTRA_PROGRAM_ARGS, full.toTypedArray())
+ when {
+ !SessionState.running -> startSessionOrWait(next)
+ SessionState.stopRequested -> android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show()
+ handToBattleNet(full) { pendingSwitch = next } -> {}
+ else -> pendingSwitch = next
+ }
+ }
+ }, "battlenet-open").start()
+ }
+
+ private fun handToBattleNet(args: List, returnHome: Boolean = false, otherwise: () -> Unit): Boolean {
+ if (SessionState.mode != SessionService.MODE_RUN || SessionState.program != com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET) return false
+ val library = args.takeIf { it.firstOrNull() == "--library" }?.getOrNull(1)
+ val sessionLibrary = SessionState.programArgs.takeIf { it.firstOrNull() == "--library" }?.getOrNull(1)
+ if (library != null && sessionLibrary != null && library != sessionLibrary) return false
+ val request = if (library != null) args.drop(2) else args
+ val app = applicationContext
+ Thread({
+ val handed = request.isEmpty() || com.droiddeck.launcher.stores.battlenet.BattleNetClient.request(LinuxRuntime.sessionRoot(app), request)
+ ui.post {
+ if (isDestroyed) return@post
+ if (!handed) otherwise()
+ else startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME)
+ .returnTo(returnHome)
+ .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP))
+ }
+ }, "battlenet-request").start()
+ return true
+ }
+
private fun launchProgram(path: String) {
startActivity(Intent(this, SessionActivity::class.java)
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN)
@@ -1624,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,
+ hdr = hdrOn, hdrReason = hdrReason, performanceMode = performanceMode,
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
gpuDrivers = drivers.summary(),
touchMode = touchMode,
@@ -1690,7 +1768,7 @@ 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 },
onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t },
@@ -1785,6 +1863,10 @@ class FrontEndActivity : ComponentActivity() {
fsyncFirst = fsyncFirst,
gamescopeRealtime = gamescopeRealtime,
gpuClockPin = gpuClockPin,
+ ramCapMb = ramCapMb, vramCapMb = vramCapMb, zramClient = zramClient,
+ deviceRamMb = (android.app.ActivityManager.MemoryInfo()
+ .also((getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)::getMemoryInfo).totalMem / (1024 * 1024)).toInt(),
+ ramCapAvailable = com.droiddeck.launcher.core.ZramSupport.supported(),
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, cursorComposite = cursorComposite,
guestHostname = guestHostname, phantomWarning = phantomWarning,
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
@@ -1798,6 +1880,9 @@ class FrontEndActivity : ComponentActivity() {
onFsyncFirst = { on -> SessionPrefs.setFsyncFirst(this, on); fsyncFirst = on },
onGamescopeRealtime = { on -> SessionPrefs.setGamescopeRealtime(this, on); gamescopeRealtime = on },
onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on },
+ onRamCapMb = { mb -> SessionPrefs.setRamCapMb(this, mb); ramCapMb = mb },
+ onZramClient = { on -> SessionPrefs.setZramClient(this, on); zramClient = on },
+ onVramCapMb = { mb -> SessionPrefs.setVramCapMb(this, mb); vramCapMb = mb },
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
onCursorComposite = { on -> SessionPrefs.setCursorComposite(this, on); cursorComposite = on },
@@ -1934,7 +2019,7 @@ 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)
hdrReason = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason
@@ -1993,6 +2078,9 @@ class FrontEndActivity : ComponentActivity() {
syncFallback = SessionPrefs.syncFallback(this)
fsyncFirst = SessionPrefs.fsyncFirst(this)
gamescopeRealtime = SessionPrefs.gamescopeRealtime(this)
+ ramCapMb = SessionPrefs.ramCapMb(this)
+ zramClient = SessionPrefs.zramClient(this)
+ vramCapMb = SessionPrefs.vramCapMb(this)
gpuClockPin = SessionPrefs.gpuClockPin(this)
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
prootFastPath = SessionPrefs.prootFastPath(this)
@@ -2013,6 +2101,7 @@ class FrontEndActivity : ComponentActivity() {
addedGamesArt = SessionPrefs.addedGamesArt(this)
desktopInstalled = DesktopCatalog.desktopInstalled(this)
desktopPresent = DesktopCatalog.desktopPresent(this)
+ battleNetInstalled = com.droiddeck.launcher.runtime.BattleNet.installed(this)
offlineAccount = OfflineMode.account(this)
offline = OfflineMode.enabled(this)
installed = LinuxRuntimeInstaller.installedVersion(this)
@@ -2023,6 +2112,10 @@ class FrontEndActivity : ComponentActivity() {
logsEnabled = SessionPrefs.logsEnabled(this)
vacDiagnostics = SessionPrefs.vacDiagnostics(this)
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
+ clearCachedApps = SessionPrefs.clearCachedApps(this)
+ adbPaired = WirelessAdbFix.hasSavedPairing(this)
+ memoryHud = SessionPrefs.memoryHud(this)
+ backgroundAppLimit = SessionPrefs.backgroundAppLimit(this)
runningLabel = if (SessionState.running) when (SessionState.mode) {
SessionService.MODE_DESKTOP -> getString(R.string.rail_desktop)
SessionService.MODE_RUN -> Library.nameForProgram(SessionState.program)
@@ -2120,6 +2213,7 @@ class FrontEndActivity : ComponentActivity() {
private fun refreshPhantomStatus() {
phantomProcessStatus = PhantomProcessLimit.read(this)
+ adbPaired = WirelessAdbFix.hasSavedPairing(this)
phantomWarning = if (PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
getString(
R.string.phantom_warning, PhantomProcessLimit.title(this, phantomProcessStatus),
diff --git a/app/src/main/java/com/droiddeck/launcher/HomeActivity.kt b/app/src/main/java/com/droiddeck/launcher/HomeActivity.kt
index 71304e883..59e10c48e 100644
--- a/app/src/main/java/com/droiddeck/launcher/HomeActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/HomeActivity.kt
@@ -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()
}
diff --git a/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt b/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt
index 5e49b5cf5..1d870a6bc 100644
--- a/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt
@@ -41,6 +41,7 @@ internal class ProtonMenu(
ui.post { protonStage = label; protonPercent = value }
}
}.getOrElse { it.message ?: it.javaClass.simpleName }
+ if (problem == null && !automatic && tool.id == ProtonExtras.OWN) ProtonExtras.setDeclined(activity, false)
ui.post {
protonBusyId = null
protonStage = null
@@ -63,6 +64,7 @@ internal class ProtonMenu(
protonPercent = -1
Thread({
if (older) ProtonExtras.removeOlder(activity, tool) else ProtonExtras.remove(activity, tool, dir)
+ if (tool.id == ProtonExtras.OWN && ProtonExtras.installedAll(activity, tool).isEmpty()) ProtonExtras.setDeclined(activity, true)
ui.post {
protonBusyId = null
protonStage = null
@@ -94,9 +96,22 @@ internal class ProtonMenu(
ProtonExtras.installInProgress || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) ||
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity) || AutoComponents.unfavourable(activity)) return
+ if (ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size > 1) {
+ protonBusyId = ProtonExtras.OWN
+ Thread({
+ ProtonExtras.tidy(activity)
+ val tidied = ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size <= 1
+ ui.post {
+ protonBusyId = null
+ refreshProtons()
+ if (tidied) ensureAutoUpdates()
+ }
+ }, "proton-tidy").start()
+ return
+ }
val attempts = activity.getSharedPreferences("proton-auto-updates", android.content.Context.MODE_PRIVATE)
val (tool, update) = ProtonExtras.tools.firstNotNullOfOrNull { tool ->
- val update = ProtonExtras.update(activity, tool) ?: return@firstNotNullOfOrNull null
+ val update = ProtonExtras.update(activity, tool) ?: ProtonExtras.missing(activity, tool) ?: return@firstNotNullOfOrNull null
val previous = attempts.getLong("${tool.id}.at", 0L)
if (attempts.getString("${tool.id}.tag", null) != update || now - previous !in 0 until 15L * 60 * 1000) tool to update else null
} ?: return
diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
index 478c6c706..9a762212d 100644
--- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
@@ -75,8 +75,10 @@ import com.droiddeck.launcher.input.OnScreenControls
import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.input.PadMouse
import com.droiddeck.launcher.input.PadState
+import com.droiddeck.launcher.input.ScreenKeys
import com.droiddeck.launcher.input.SteamControllerBle
import com.droiddeck.launcher.input.DirectTouchHold
+import com.droiddeck.launcher.input.GestureTouchStreamGate
import com.droiddeck.launcher.input.PointerGestures
import com.droiddeck.launcher.input.SecondScreenDisplay
import com.droiddeck.launcher.input.SecondScreenDisplays
@@ -155,6 +157,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private lateinit var sessionOverlay: ComposeView
private lateinit var loading: LoadingState
private lateinit var hud: PerfHud
+ private lateinit var memoryHud: com.droiddeck.launcher.session.MemoryHud
private var padBridge: PadBridge? = null
private var joyConVr: com.droiddeck.launcher.input.JoyConVr? = null
private var handCamera: com.droiddeck.launcher.handtracking.HandCamera? = null
@@ -198,10 +201,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var gestureConfig = com.droiddeck.launcher.input.TouchGestureConfig()
private var gestureGame: String? = null
private var gestureSettingsOpen by mutableStateOf(false)
+ private var screenKeyPickerOpen by mutableStateOf(false)
+ private var screenKeyBind: List? = null
+ private var screenKeyDir: Int? = null
+ private var screenKeyTextFocus = false
+ private var screenKeyEdit by mutableStateOf(null)
+ private var screenLayoutsOpen by mutableStateOf(false)
+ private var screenKeysShown by mutableStateOf(true)
+ private var screenLayoutNames by mutableStateOf(listOf())
+ private var screenKeys: ScreenKeys? = null
private var recognizedGesture by mutableStateOf(null)
private var gesturePointerX = 0f
private var gesturePointerY = 0f
private var gesturePointerReady = false
+ private val gestureTouchStreamGate = GestureTouchStreamGate()
private val clearRecognizedGesture = Runnable { recognizedGesture = null }
private val gestureKeysDown = mutableSetOf()
private lateinit var scrollTouch: ScrollTouchGestures
@@ -270,6 +283,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}
private val resumeKeysDown = mutableSetOf>()
+ private val drawerShortcutKeysDown = mutableSetOf>()
private var drawerOpen by mutableStateOf(false)
private var quitFrom by mutableStateOf(null)
@@ -280,6 +294,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var drawerDefaultProton by mutableStateOf(null)
private val drawerComponentMenu by lazy { ComponentsMenu(this, uiHandler) }
private var drawerGameProfileId by mutableStateOf(null)
+
+ private fun noSteamSession(): Boolean = SessionState.mode == SessionService.MODE_RUN &&
+ SessionState.program in setOf(com.droiddeck.launcher.session.NoSteamLaunch.PROTON_RUN, com.droiddeck.launcher.session.NoSteamLaunch.EPIC)
private val drawerGameInventory = GameProfileInventoryCache()
private var drawerGameInventoryRevision = 0L
private var drawerGameFexPresetSaving by mutableStateOf(false)
@@ -301,8 +318,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(null)
@@ -475,9 +491,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
com.droiddeck.launcher.gpu.SteamVrHealth.begin(this, SessionState.sessionId)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
if (!SessionState.running) {
- SessionState.fpsLimit = SessionPrefs.fpsLimit(
- this, SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM),
- )
+ val prefMode = SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM)
+ SessionState.performanceMode = SessionPrefs.performanceMode(this, prefMode)
}
applyOutputPacing()
if (!SessionState.running) SessionState.followScreen = followChoice()
@@ -534,6 +549,21 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
cursorVisible = false
}
onScreenControls = OnScreenControls(this, bridge, onKeyboard = ::togglePcKeyboard).also { root.addView(it) }
+ screenKeysShown = com.droiddeck.launcher.input.ControllerPrefs.screenKeysShown(this)
+ screenKeys = ScreenKeys(this) { code, down -> if (CompositorHost.isStarted) sendGuestKey(code, down) }.also { keys ->
+ keys.onTouchMiss = miss@{ event ->
+ if (routedTouchMode == SessionPrefs.TOUCH_GESTURES &&
+ !gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, event)) return@miss
+ event.offsetLocation(keys.left - surfaceView.left.toFloat(), keys.top - surfaceView.top.toFloat())
+ onTouchEvent(event)
+ }
+ keys.onAdd = { screenKeyPickerOpen = true }
+ keys.onSelect = { codes -> screenKeyEdit = screenKeys?.stateOf(codes) }
+ keys.onEditingChanged = { if (!it) screenKeyEdit = null }
+ keys.steamStyle = { steamTouchControls?.style }
+ keys.visibility = if (screenKeysShown) View.VISIBLE else View.GONE
+ root.addView(keys)
+ }
keyboard = KeyboardHost(this).also { root.addView(it) }
touchpad = TouchpadGestures(PointerGestures.slop(this), pointerListener)
directTouchHold = DirectTouchHold(PointerGestures.slop(this), pointerListener) {
@@ -548,7 +578,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
// game surface and on-screen buttons, in either finger-down order.
root.isMotionEventSplittingEnabled = true
surfaceView.setOnTouchListener { _, event ->
- routedTouchMode == SessionPrefs.TOUCH_GESTURES && onTouchEvent(event)
+ if (routedTouchMode != SessionPrefs.TOUCH_GESTURES) {
+ gestureTouchStreamGate.reset()
+ false
+ } else if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SURFACE, event)) {
+ false
+ } else onTouchEvent(event)
}
padMouse = PadMouse(padMouseListener)
bridge.setTouchRoute(object : PadBridge.TouchRoute {
@@ -572,17 +607,21 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val needResume = !needRuntime && com.droiddeck.launcher.runtime.DesktopCatalog.interrupted(this).isNotEmpty()
val needDesktop = intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_DESKTOP &&
(repair || !com.droiddeck.launcher.runtime.DesktopCatalog.desktopInstalled(this))
- val needProton = (intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM) == SessionService.MODE_STEAM &&
- com.droiddeck.launcher.runtime.DesktopCatalog.protonSeedNeeded(this)
+ val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
+ val protonUser = (intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM) == SessionService.MODE_STEAM ||
+ program == com.droiddeck.launcher.runtime.BattleNet.PROGRAM || program == com.droiddeck.launcher.session.NoSteamLaunch.PROTON_RUN
+ val needProton = protonUser && com.droiddeck.launcher.runtime.DesktopCatalog.protonSeedNeeded(this)
if (needRuntime || needResume || needDesktop || needProton) installThenStart(needRuntime, needDesktop, needProton, needResume)
}
hud = PerfHud(this)
+ memoryHud = com.droiddeck.launcher.session.MemoryHud(this)
hud.onPresentingWindowChanged = {
if (FrameGen.engine(this) != FrameGen.ENGINE_OFF) CompositorHost.rearmFrameGen { applyFrameGen() }
}
if (SessionState.running && SessionState.firstFrameSeen) {
loading.visible = false
hud.start()
+ memoryHud.start()
}
readPrefs()
@@ -677,7 +716,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) {
CursorOverlay({ cursorPos }, cursorVisible, resources.displayMetrics.density,
cursorImage, cursorHotX, cursorHotY, cursorImageScale)
- if (hud.text.isNotEmpty() || hud.graph.size >= 2) HudText(hud.text, hud.graph, hudColor, hudOpacity)
+ val hudLines = listOf(hud.text, memoryHud.text).filter { it.isNotEmpty() }
+ if (hudLines.isNotEmpty() || hud.graph.size >= 2)
+ HudText(hudLines.joinToString("\n"), hud.graph, hudColor, hudOpacity)
val phonePanel = glassesOutputActive && !loading.visible && !drawerOpen && !pcKeyboardOpen
if (phonePanel) GlassesPhonePanel(glasses, steamVrStatus == SteamVr.Status.RUNNING, headTracking)
if (trackingRecovery != null && !drawerOpen && !pcKeyboardOpen && !loading.visible) {
@@ -733,6 +774,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, pipUi, SessionState.suspended) {
if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || pipUi || SessionState.suspended) {
cancelTouchGestures()
+ screenKeys?.stopEditing()
}
}
com.droiddeck.launcher.ui.GestureFeedback(recognizedGesture)
@@ -741,6 +783,84 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
onDismiss = { gestureSettingsOpen = false },
onSaved = { gestureSettingsOpen = false; refreshGestureConfig() },
)
+ if (screenKeyPickerOpen) {
+ val dir = screenKeyDir
+ com.droiddeck.launcher.ui.ScreenKeyPicker(
+ initial = if (dir != null) {
+ listOfNotNull((screenKeyEdit?.codes?.getOrNull(dir) ?: 0).takeIf { it != 0 })
+ } else {
+ screenKeyBind ?: emptyList()
+ },
+ onDismiss = { screenKeyPickerOpen = false; screenKeyBind = null; screenKeyDir = null },
+ onAdd = { codes ->
+ val bind = screenKeyBind
+ if (dir != null && bind != null) {
+ screenKeys?.setDirection(bind, dir, codes.lastOrNull() ?: 0)?.let { screenKeyEdit = it }
+ } else if (bind != null) {
+ screenKeys?.setCodes(bind, codes)?.let { screenKeyEdit = it }
+ } else {
+ screenKeys?.add(codes)
+ screenKeyEdit = screenKeys?.stateOf(codes)
+ }
+ screenKeyPickerOpen = false
+ screenKeyBind = null
+ screenKeyDir = null
+ },
+ )
+ }
+ screenKeyEdit?.let { key ->
+ com.droiddeck.launcher.ui.ScreenKeyEditor(
+ codes = key.codes, keyY = key.y,
+ size = key.size, opacity = key.opacity, shape = key.shape, toggle = key.toggle,
+ labels = key.labels,
+ text = key.text, hasImage = key.image.isNotEmpty(),
+ onResize = { screenKeys?.resize(key.codes, it); screenKeyEdit = screenKeys?.stateOf(key.codes) },
+ onOpacity = { screenKeys?.setOpacity(key.codes, it); screenKeyEdit = screenKeys?.stateOf(key.codes) },
+ onShape = { screenKeys?.setShape(key.codes, it); screenKeyEdit = screenKeys?.stateOf(key.codes) },
+ onToggle = { on -> screenKeys?.setToggle(key.codes, on); screenKeyEdit = screenKeys?.stateOf(key.codes) },
+ onLabels = { on -> screenKeys?.setLabels(key.codes, on); screenKeyEdit = screenKeys?.stateOf(key.codes) },
+ onDirection = { index -> screenKeyBind = key.codes; screenKeyDir = index; screenKeyPickerOpen = true },
+ onText = { screenKeys?.setText(key.codes, it); screenKeyEdit = screenKeys?.stateOf(key.codes) },
+ onImage = { screenKeys?.setImage(key.codes, it); screenKeyEdit = screenKeys?.stateOf(key.codes) },
+ onClearImage = { screenKeys?.setImage(key.codes, ""); screenKeyEdit = screenKeys?.stateOf(key.codes) },
+ onBind = { screenKeyBind = key.codes; screenKeyDir = null; screenKeyPickerOpen = true },
+ onTextFocus = { screenKeyTextFocus = true; keyboard?.hide() },
+ onTextBlur = { screenKeyTextFocus = false },
+ onRemove = { screenKeys?.remove(key.codes); screenKeyEdit = null },
+ onDismiss = { screenKeyEdit = null; screenKeyTextFocus = false; screenKeys?.deselect() },
+ )
+ }
+ if (screenLayoutsOpen) com.droiddeck.launcher.ui.ScreenLayoutPanel(
+ layouts = screenLayoutNames,
+ onSave = { name ->
+ screenKeys?.let { keys ->
+ com.droiddeck.launcher.input.ControllerPrefs.saveScreenLayout(this@SessionActivity, name, keys.export())
+ }
+ screenLayoutNames = layoutNames()
+ },
+ onLoad = { name ->
+ com.droiddeck.launcher.input.ControllerPrefs.screenLayouts(this@SessionActivity)[name]?.let { screenKeys?.load(it) }
+ screenLayoutsOpen = false
+ },
+ onDelete = { name ->
+ com.droiddeck.launcher.input.ControllerPrefs.deleteScreenLayout(this@SessionActivity, name)
+ screenLayoutNames = layoutNames()
+ },
+ onImport = { text ->
+ val width = (screenKeys?.width ?: 0).takeIf { it > 0 } ?: resources.displayMetrics.widthPixels
+ val keys = com.droiddeck.launcher.input.importScreenLayout(text, width, resources.displayMetrics.density)
+ if (keys != null) {
+ screenKeys?.load(com.droiddeck.launcher.input.ControllerPrefs.encodeScreenKeys(keys))
+ screenLayoutsOpen = false
+ }
+ },
+ exportText = {
+ val width = (screenKeys?.width ?: 0).takeIf { it > 0 } ?: resources.displayMetrics.widthPixels
+ val keys = com.droiddeck.launcher.input.ControllerPrefs.decodeScreenKeys(screenKeys?.export().orEmpty())
+ com.droiddeck.launcher.input.exportScreenLayout(keys, width, resources.displayMetrics.density)
+ },
+ onDismiss = { screenLayoutsOpen = false },
+ )
androidx.compose.runtime.LaunchedEffect(drawerOpen) {
if (drawerOpen) {
syncLossless()
@@ -787,6 +907,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
)
SessionDrawer(drawerOpen, drawerPage, drawerControllerActive, onPageChange = { drawerPage = it }, a = DrawerActions(
steam = SessionState.mode == SessionService.MODE_STEAM,
+ direct = noSteamSession(),
title = if (SessionState.mode == SessionService.MODE_RUN)
com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_title_game) else null,
isHomeApp = isHomeApp,
@@ -818,6 +939,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
lossless = lossless,
oscMode = oscMode, onScreenButtonsVisible = onScreenButtonsVisible, suspendPolicy = suspendPolicy,
steamDownloadsInBackground = steamDownloadsInBackground, touchMode = touchMode,
+ micAvailable = SessionState.micAvailable && !SessionState.suspended,
+ micEnabled = SessionState.micEnabled,
+ onMicEnabled = { SessionService.setMicEnabled(this@SessionActivity, it) },
touchAuto = getString(if (usingTouchpad()) R.string.session_touch_auto_touchpad else R.string.session_touch_auto_direct),
fexPreset = fexPreset,
secondScreenMode = secondScreenMode,
@@ -893,16 +1017,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 ->
@@ -928,6 +1046,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
},
onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() },
onGestureSettings = { drawerOpen = false; gestureSettingsOpen = true },
+ onScreenKeys = { drawerOpen = false; screenKeys?.startEditing() },
+ screenKeysShown = screenKeysShown,
+ onScreenKeysShown = { shown ->
+ screenKeysShown = shown
+ com.droiddeck.launcher.input.ControllerPrefs.setScreenKeysShown(this@SessionActivity, shown)
+ screenKeys?.stopEditing()
+ screenKeys?.visibility = if (shown) View.VISIBLE else View.GONE
+ },
+ onScreenLayouts = {
+ drawerOpen = false
+ screenLayoutNames = layoutNames()
+ screenLayoutsOpen = true
+ },
onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() },
onSecondScreenMode = ::selectSecondScreenMode,
onSecondScreenDisplay = ::selectSecondScreenDisplay,
@@ -1238,6 +1369,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val activeAppId = AgentGuest.activeSteamAppId(this, installedAppIds)
val selectedSteamAppId = runCatching { AgentGuest.selectedSteamAppId(this) }
AgentGuest.selectedOrActiveInstalledSteamAppId(selectedSteamAppId, activeAppId, installedAppIds)
+ ?: SessionState.gameId?.toLongOrNull()
?: refresh.requestedAppId
} else {
refresh.requestedAppId
@@ -1484,15 +1616,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (nextTouchMode == SessionPrefs.TOUCH_OFF || !usingTouchpad()) cursorVisible = false
}
touchMode = nextTouchMode
- routedTouchMode = effectiveTouchMode()
+ val nextRoutedTouchMode = effectiveTouchMode()
+ if (routedTouchMode != nextRoutedTouchMode) gestureTouchStreamGate.reset()
+ routedTouchMode = nextRoutedTouchMode
frameGen = FrameGen.mode(this)
fexPreset = SessionPrefs.fexPreset(this)
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
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)
}
@@ -1724,6 +1857,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
intent.getStringExtra(SessionService.EXTRA_STEAM_UI),
intent.getStringExtra(SessionService.EXTRA_STEAM_URL),
intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS),
+ intent.getStringExtra(SessionService.EXTRA_GAME_ID),
sessionActivityDisplayId,
)
}
@@ -1840,7 +1974,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun mirrorRefreshLimit(): Int =
GlassesRendering.mirrorRefreshLimit(glassesSettings, glasses, glassesScreen != null)
- private fun outputFpsLimit(): Int = GlassesRendering.fpsLimit(SessionState.fpsLimit, mirrorRefreshLimit())
+ private fun outputFpsLimit(): Int = SessionPrefs.compositorFpsLimit(
+ mirrorRefreshLimit(), SessionState.performanceMode,
+ )
private fun applyOutputPacing() {
Log.i(TAG, "perf: " + PerfMode.apply(this, outputFpsLimit(), mirrorRefreshLimit()))
@@ -1937,7 +2073,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return
}
Thread({
- val hint = runtimeDamageHint() ?: sessionEndHint(SessionState.logFile)
+ val hint = runtimeDamageHint() ?: sessionEndHint(SessionState.logFile) ?: prootFailureHint()
runOnUiThread {
if (isFinishing || isDestroyed) return@runOnUiThread
showEnded(status, hint)
@@ -1959,7 +2095,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
repairOffered = hint?.repair == true
loading.showEnded(
hint?.text ?: stopped,
- getString(R.string.session_ended_detail, status, SessionState.logFile?.path ?: getString(R.string.session_ended_no_log)),
+ getString(R.string.session_ended_detail, status,
+ SessionState.logFile?.path?.let { android.text.BidiFormatter.getInstance().unicodeWrap(it, android.text.TextDirectionHeuristics.LTR) }
+ ?: getString(R.string.session_ended_no_log)),
)
focusEndedScreen()
}
@@ -1998,6 +2136,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 {
@@ -2038,6 +2182,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return super.dispatchKeyEvent(event)
}
if (pipUi) return true
+ if (screenKeyTextFocus) return super.dispatchKeyEvent(event)
val pad = com.droiddeck.launcher.input.JoyCon.normalize(event)
if (pad !== event) return dispatchKeyEvent(pad)
val fromController = PadBridge.isControllerKeyEvent(event)
@@ -2059,6 +2204,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
return super.dispatchKeyEvent(event)
}
+ val drawerShortcutKey = event.deviceId to event.keyCode
+ if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_SELECT || event.keyCode == KeyEvent.KEYCODE_BUTTON_START) &&
+ ((drawerOpen && SessionState.mode == SessionService.MODE_STEAM) || drawerShortcutKey in drawerShortcutKeysDown)) {
+ if (event.action == KeyEvent.ACTION_DOWN) {
+ drawerShortcutKeysDown.add(drawerShortcutKey)
+ if (event.repeatCount == 0) {
+ releaseDrawerDirection()
+ if (event.keyCode == KeyEvent.KEYCODE_BUTTON_SELECT) sendSteamGuide() else triggerSteamQam()
+ }
+ } else if (event.action == KeyEvent.ACTION_UP) {
+ drawerShortcutKeysDown.remove(drawerShortcutKey)
+ }
+ return true
+ }
if (drawerOpen) {
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
@@ -2225,9 +2384,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
super.dispatchKeyEvent(event)
}
+ private fun layoutNames(): List =
+ com.droiddeck.launcher.input.ControllerPrefs.screenLayouts(this).keys.sorted()
+
private fun refreshGestureConfig() {
gestureConfig = com.droiddeck.launcher.input.GesturePrefs.read(this, gestureGame)
+ gestureTouchStreamGate.reset()
if (::touchscreenGestures.isInitialized) touchscreenGestures.configure(gestureConfig)
+ if (::directTouchHold.isInitialized) directTouchHold.configure(gestureConfig)
gesturePointerReady = false
recognizedGesture = null
}
@@ -2515,6 +2679,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun refreshControls() {
applyUnfoldedControls()
updateOnScreenControls()
+ screenKeys?.refreshAppearance()
}
private fun applyUnfoldedControls() {
@@ -2600,6 +2765,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (::scrollTouch.isInitialized) scrollTouch.cancel()
if (CompositorHost.isStarted) WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
if (next == SessionPrefs.TOUCH_OFF) cursorVisible = false
+ gestureTouchStreamGate.reset()
routedTouchMode = next
}
@@ -2790,6 +2956,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
device.plugged = false
uiHandler.postDelayed({ updateOnScreenControls() }, 700)
}
+ view.onStyle = { screenKeys?.refreshAppearance() }
root.addView(view, root.indexOfChild(onScreenControls) + 1)
steamTouchControls = view
steamTouchAvailable = true
@@ -2820,6 +2987,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
controls.visibility = View.GONE
steamTouchControls?.let { it.releaseAll(); it.visibility = View.GONE }
com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = false
+ screenKeys?.followSteam = false
applyTouchRouting()
return
}
@@ -2848,6 +3016,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
onScreenButtonsVisible = show
val drawn = show && !keyboardCoversPad()
if (steam != null) {
+ screenKeys?.followSteam = drawn
if (controls.visibility == View.VISIBLE) { controls.releaseAll(); controls.visibility = View.GONE }
if (!drawn) steam.releaseAll()
steam.visibility = if (drawn) View.VISIBLE else View.GONE
@@ -2856,6 +3025,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
Log.i(TAG, "on-screen controls: Steam's touch controller " + if (drawn) "shown" else "hidden")
return
}
+ screenKeys?.followSteam = false
if (drawn == (controls.visibility == View.VISIBLE)) return
if (!drawn) controls.releaseAll()
controls.visibility = if (drawn) View.VISIBLE else View.GONE
@@ -2941,6 +3111,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
pendingBackAction = null
releaseDrawerDirection()
onScreenControls?.releaseAll()
+ screenKeys?.releaseAll()
releasePads()
touchpad.cancel()
scrollTouch.cancel()
@@ -3053,6 +3224,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (!SessionState.suspended) pausedFrame = null
com.droiddeck.launcher.ui.Motion.refresh(this)
refreshHomeApp()
+ if (::memoryHud.isInitialized && SessionState.running && SessionState.firstFrameSeen) memoryHud.refresh()
if (intent?.action == SessionService.ACTION_RESUME) {
intent.action = null
SessionService.resume(this)
@@ -3450,10 +3622,10 @@ 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())
}
@@ -3498,8 +3670,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionEvents.firstFrame()
if (SessionState.mode == SessionService.MODE_STEAM) SteamRepair.clientShown(this)
runOnUiThread {
+ if (isFinishing || isDestroyed) return@runOnUiThread
loading.visible = false
hud.start()
+ memoryHud.start()
}
}
@@ -3517,6 +3691,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
glassesScreen?.let { screen -> glassesScreen = null; runCatching { screen.dismiss() } }
headTracker?.stop()
if (::hud.isInitialized) hud.stop()
+ if (::memoryHud.isInitialized) memoryHud.stop()
joyConVr?.close()
joyConVr = null
handCamera?.stop()
diff --git a/app/src/main/java/com/droiddeck/launcher/UpdatesMenu.kt b/app/src/main/java/com/droiddeck/launcher/UpdatesMenu.kt
index 8459bc7d9..5eb9ff450 100644
--- a/app/src/main/java/com/droiddeck/launcher/UpdatesMenu.kt
+++ b/app/src/main/java/com/droiddeck/launcher/UpdatesMenu.kt
@@ -29,6 +29,7 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
private var pending: AppUpdates.Release? = null
private var lastCheck = 0L
private var request = 0
+ @Volatile private var session = -1
fun state() = UpdatesState(catalog, follow, checking, error, stage, percent, askPermission)
@@ -87,13 +88,14 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
if (SessionState.running) { error = activity.getString(R.string.upd_stop_first); return }
if (!SelfInstaller.canInstall(activity)) { pending = r; askPermission = true; return }
error = null
+ session = -1
stage = activity.getString(R.string.upd_stage_downloading)
percent = 0
Thread({
val result = runCatching {
val file = SelfInstaller.download(activity, apk) { pct -> ui.post { percent = pct } }
ui.post { stage = activity.getString(R.string.upd_stage_installing); percent = -1 }
- SelfInstaller.install(activity, file)
+ SelfInstaller.install(activity, file) { id -> session = id }
}
result.onFailure { e -> ui.post { stage = null; error = e.message ?: activity.getString(R.string.upd_failed) } }
}, "app-update-install").start()
@@ -101,13 +103,15 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
+ if (intent.getIntExtra(PackageInstaller.EXTRA_SESSION_ID, -1).let { it < 0 || it != session }) return
when (val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE)) {
PackageInstaller.STATUS_PENDING_USER_ACTION -> {
val confirm = if (Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)
else @Suppress("DEPRECATION") intent.getParcelableExtra(Intent.EXTRA_INTENT)
- if (confirm == null) { stage = null; error = activity.getString(R.string.upd_not_offered); return }
+ val safe = confirm?.let { SelfInstaller.safeConfirmIntent(activity, it) }
+ if (safe == null) { stage = null; error = activity.getString(R.string.upd_not_offered); return }
stage = activity.getString(R.string.upd_stage_confirm)
- activity.startActivity(confirm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
+ if (runCatching { activity.startActivity(safe) }.isFailure) { stage = null; error = activity.getString(R.string.upd_not_offered) }
}
PackageInstaller.STATUS_SUCCESS -> stage = null
else -> {
diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentEnv.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentEnv.kt
index 5f7f09262..0842f6b5a 100644
--- a/app/src/main/java/com/droiddeck/launcher/agent/AgentEnv.kt
+++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentEnv.kt
@@ -3,9 +3,13 @@ package com.droiddeck.launcher.agent
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.runtime.LinuxRuntime
+import com.droiddeck.launcher.runtime.ProotFastPath
+import com.droiddeck.launcher.session.SessionPhase
+import com.droiddeck.launcher.session.SessionState
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
+import java.security.MessageDigest
import java.nio.file.Files
import java.nio.file.LinkOption.NOFOLLOW_LINKS
import java.nio.file.StandardOpenOption.READ
@@ -55,6 +59,9 @@ object AgentEnv {
fun override(context: Context, name: String): JSONObject = synchronized(lock) {
AgentAccess.requireCommands(context)
if (NAME.matchEntire(name) == null || name in setOf(".", "..")) throw AgentException("INVALID_NAME", "Override names are letters, digits, '.', '_' and '-'")
+ if (name == "libblfastpath.so" && (SessionState.running || SessionState.guestPid > 0 || SessionState.phase == SessionPhase.STOPPING)) {
+ throw AgentException("SESSION_ACTIVE", "Stop the session before installing a fast-path library")
+ }
val source = File(inbox(context), name)
if (Files.isSymbolicLink(source.toPath())) throw AgentException("INVALID_NAME", "The override must be a regular file")
if (!source.isFile) throw AgentException("NO_SUCH_FILE", "Push the binary to ${source.path} first")
@@ -67,6 +74,10 @@ object AgentEnv {
staged.delete()
throw AgentException("OVERRIDE_FAILED", "Could not stage the override")
}
+ if (name == "libblfastpath.so" && !arm64SharedLibrary(staged)) {
+ staged.delete()
+ throw AgentException("INVALID_LIBRARY", "The fast path must be a 64-bit little-endian ARM64 ELF shared library")
+ }
if (!staged.setExecutable(true, false) || !staged.renameTo(target)) {
staged.delete()
throw AgentException("OVERRIDE_FAILED", "Could not install $name in the rootfs")
@@ -76,6 +87,40 @@ object AgentEnv {
state.put("pendingOverrides", JSONArray(merge(strings(state.optJSONArray("pendingOverrides")), listOf(name))))
save(context, state)
state.put("installed", "$GUEST_BIN/$name")
+ if (name == "libblfastpath.so") {
+ val digest = MessageDigest.getInstance("SHA-256")
+ target.inputStream().use { input ->
+ val buffer = ByteArray(65536)
+ while (true) {
+ val count = input.read(buffer)
+ if (count < 0) break
+ digest.update(buffer, 0, count)
+ }
+ }
+ state.put("sha256", digest.digest().joinToString("") { "%02x".format(it) })
+ }
+ state
+ }
+
+ fun fastPathLibrary(context: Context): String = synchronized(lock) {
+ if (!AgentAccess.commandsAllowed(context)) return@synchronized ProotFastPath.LIBRARY
+ if ("libblfastpath.so" !in strings(load(context).optJSONArray("activeOverrides"))) return@synchronized ProotFastPath.LIBRARY
+ val file = File(bin(context), "libblfastpath.so")
+ if (!file.isFile || Files.isSymbolicLink(file.toPath())) return@synchronized ProotFastPath.LIBRARY
+ "$GUEST_BIN/libblfastpath.so"
+ }
+
+ private fun arm64SharedLibrary(file: File): Boolean = file.inputStream().use { input ->
+ val header = ByteArray(20)
+ var count = 0
+ while (count < header.size) {
+ val read = input.read(header, count, header.size - count)
+ if (read < 0) return@use false
+ count += read
+ }
+ header.take(7) == listOf(0x7f, 0x45, 0x4c, 0x46, 2, 1, 1) &&
+ header[16] == 3.toByte() && header[17] == 0.toByte() &&
+ header[18] == 183.toByte() && header[19] == 0.toByte()
}
fun beginSession(context: Context): List = synchronized(lock) {
@@ -86,13 +131,13 @@ object AgentEnv {
val state = load(context)
val active = strings(state.optJSONArray("pending"))
val overrides = strings(state.optJSONArray("pendingOverrides"))
- state.put("active", JSONArray(active)).put("pending", JSONArray())
- state.put("activeOverrides", JSONArray(overrides)).put("pendingOverrides", JSONArray())
- save(context, state)
bin(context).listFiles()
?.filter { it.name !in overrides }?.forEach { it.delete() }
val lines = strings(state.optJSONArray("persistent")) + active
- val withPath = if (overrides.isEmpty()) lines else lines + "PATH=$GUEST_BIN:${pathOf(lines)}"
+ val withPath = if (overrides.none { it != "libblfastpath.so" }) lines else lines + "PATH=$GUEST_BIN:${pathOf(lines)}"
+ state.put("active", JSONArray(active)).put("pending", JSONArray())
+ state.put("activeOverrides", JSONArray(overrides)).put("pendingOverrides", JSONArray())
+ save(context, state)
if (withPath.isNotEmpty()) Log.i(TAG, "agent environment keys for this session: ${withPath.map { it.substringBefore('=') }}")
withPath
}
diff --git a/app/src/main/java/com/droiddeck/launcher/audio/DirectAudioRelayComponent.java b/app/src/main/java/com/droiddeck/launcher/audio/DirectAudioRelayComponent.java
index f1fa53492..f8f1b2a3e 100644
--- a/app/src/main/java/com/droiddeck/launcher/audio/DirectAudioRelayComponent.java
+++ b/app/src/main/java/com/droiddeck/launcher/audio/DirectAudioRelayComponent.java
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.audio;
import android.os.Process;
import android.util.Log;
+import com.droiddeck.launcher.core.FileUtils;
import com.droiddeck.launcher.core.SessionPart;
import com.droiddeck.launcher.core.HostProcess;
@@ -19,10 +20,13 @@ public class DirectAudioRelayComponent extends SessionPart {
private volatile int pid = -1;
private final Object micLock = new Object();
private boolean micHot;
+ private final File micControl;
+ public java.util.function.Consumer onMicEnabled;
public DirectAudioRelayComponent(File socketPath, File micFifoPath) {
this.socketPath = socketPath;
this.micFifoPath = micFifoPath;
+ this.micControl = micFifoPath == null ? null : new File(micFifoPath.getParentFile(), "mic-enabled");
}
public void setLogFile(File file) {
@@ -63,8 +67,13 @@ public class DirectAudioRelayComponent extends SessionPart {
StringBuilder command = new StringBuilder(binary.getAbsolutePath());
command.append(" --socket ").append(socketPath.getAbsolutePath());
command.append(" --log");
- if (micFifoPath != null) {
+ final boolean withMic = micFifoPath != null && setMicEnabled(true);
+ if (withMic) {
command.append(" --mic-fifo ").append(micFifoPath.getAbsolutePath());
+ command.append(" --mic-control ").append(micControl.getAbsolutePath());
+ } else if (micFifoPath != null) {
+ Log.w(TAG, "microphone control unavailable; starting with capture disabled");
+ command.append(" --mic-control /dev/null");
}
ArrayList env = new ArrayList<>();
env.add("HOME=" + app().getFilesDir());
@@ -73,7 +82,7 @@ public class DirectAudioRelayComponent extends SessionPart {
try {
out = new java.io.PrintWriter(new java.io.FileWriter(logFile, true));
out.println("== DirectAudio relay helper starting"
- + (micFifoPath != null ? " with the microphone" : " (no microphone)"));
+ + (withMic ? " with the microphone" : " (no microphone)"));
out.flush();
} catch (Exception e) {
Log.w(TAG, "could not open " + logFile, e);
@@ -84,14 +93,23 @@ public class DirectAudioRelayComponent extends SessionPart {
app().getFilesDir(), null,
line -> {
Log.i(TAG, line);
- trackMic(line);
+ if (withMic) trackMic(line);
if (log != null) synchronized (log) { log.println(line); log.flush(); }
});
Log.i(TAG, "started pid=" + pid + " socket=" + socketPath
- + (micFifoPath != null ? " mic=" + micFifoPath : " (no microphone)"));
+ + (withMic ? " mic=" + micFifoPath : " (no microphone)"));
+ }
+
+ public synchronized boolean setMicEnabled(boolean enabled) {
+ if (micControl == null) return false;
+ File next = new File(micControl.getPath() + ".new");
+ return FileUtils.writeString(next, enabled ? "1" : "0") && next.renameTo(micControl);
}
private void trackMic(String line) {
+ if (line.startsWith("DA-Relay: mic enabled=") && onMicEnabled != null) {
+ onMicEnabled.accept(line.equals("DA-Relay: mic enabled=1"));
+ }
boolean start = line.startsWith("DA-Relay: mic start ");
if (!start && !line.startsWith("DA-Relay: mic stop ")) return;
synchronized (micLock) {
diff --git a/app/src/main/java/com/droiddeck/launcher/core/AppUiPrefs.kt b/app/src/main/java/com/droiddeck/launcher/core/AppUiPrefs.kt
index 3021b7196..7b8536202 100644
--- a/app/src/main/java/com/droiddeck/launcher/core/AppUiPrefs.kt
+++ b/app/src/main/java/com/droiddeck/launcher/core/AppUiPrefs.kt
@@ -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(
diff --git a/app/src/main/java/com/droiddeck/launcher/core/BackgroundAppLimit.kt b/app/src/main/java/com/droiddeck/launcher/core/BackgroundAppLimit.kt
new file mode 100644
index 000000000..02447f360
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/core/BackgroundAppLimit.kt
@@ -0,0 +1,59 @@
+package com.droiddeck.launcher.core
+
+import android.content.Context
+import android.util.Log
+import java.util.concurrent.Executors
+
+object BackgroundAppLimit {
+ private const val TAG = "BackgroundAppLimit"
+ const val OFF = -1
+ val CHOICES = listOf(OFF, 4, 1, 0)
+ private const val KEY = "max_cached_processes"
+ private const val STATE = "background-app-limit"
+ private const val APPLIED = "applied"
+ private const val PREVIOUS = "previous"
+
+ private val worker = Executors.newSingleThreadExecutor { Thread(it, "background-app-limit").apply { isDaemon = true } }
+
+ internal fun readCommand() = "device_config get activity_manager $KEY"
+ internal fun setCommand(limit: Int): String {
+ require(limit in 0..1024)
+ return "device_config put activity_manager $KEY $limit"
+ }
+ internal fun restoreCommand(previous: String?) =
+ if (previous == null) "device_config delete activity_manager $KEY" else "device_config put activity_manager $KEY $previous"
+
+ internal fun parse(output: String): String? = output.trim().takeIf { it.toIntOrNull() != null }
+
+ private fun state(context: Context) = context.applicationContext.getSharedPreferences(STATE, Context.MODE_PRIVATE)
+
+ fun applied(context: Context): Boolean = state(context).getBoolean(APPLIED, false)
+
+ fun applyAsync(context: Context, limit: Int) {
+ val app = context.applicationContext
+ worker.execute {
+ runCatching {
+ if (!applied(app)) {
+ val previous = parse(WirelessAdbFix.shell(app, readCommand()))
+ check(state(app).edit().putBoolean(APPLIED, true).putString(PREVIOUS, previous).commit()) { "previous value not saved" }
+ }
+ WirelessAdbFix.shell(app, setCommand(limit))
+ }.onSuccess { Log.i(TAG, "at most $limit cached app(s) while the session runs") }
+ .onFailure { Log.w(TAG, "limit not set: ${it.message}") }
+ }
+ }
+
+ fun restoreAsync(context: Context) {
+ val app = context.applicationContext
+ worker.execute {
+ if (!applied(app)) return@execute
+ val previous = state(app).getString(PREVIOUS, null)
+ runCatching { WirelessAdbFix.shell(app, restoreCommand(previous)) }
+ .onSuccess {
+ state(app).edit().putBoolean(APPLIED, false).remove(PREVIOUS).commit()
+ Log.i(TAG, "cached-app limit put back (${previous ?: "Android's own"})")
+ }
+ .onFailure { Log.w(TAG, "limit not put back yet: ${it.message}") }
+ }
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt
index 058b07dd5..d587ecb7c 100644
--- a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt
+++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt
@@ -256,8 +256,13 @@ object DeviceReport {
EsyncPacks.status(LinuxRuntime.rootDir(context)).let { k("droiddeck-esync packs", "${it.installed} installed, ${it.wanted} wanted") }
k("Linux x86 (FEX)", if (com.droiddeck.launcher.runtime.LinuxFex.ready(context)) "ready" else "not set up")
k("gamescope realtime", SessionPrefs.gamescopeRealtime(context))
+ k("zRAM: compress Steam during games", SessionPrefs.zramClient(context))
+ k("RAM cap", SessionPrefs.ramCapMb(context).let { if (it > 0) "$it MB" else "off" })
+ 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))
diff --git a/app/src/main/java/com/droiddeck/launcher/core/DownloadSource.kt b/app/src/main/java/com/droiddeck/launcher/core/DownloadSource.kt
index 870e8ed42..b11e3113a 100644
--- a/app/src/main/java/com/droiddeck/launcher/core/DownloadSource.kt
+++ b/app/src/main/java/com/droiddeck/launcher/core/DownloadSource.kt
@@ -3,6 +3,8 @@ package com.droiddeck.launcher.core
import android.content.Context
import android.content.SharedPreferences
import java.net.HttpURLConnection
+import java.net.InetSocketAddress
+import java.net.Proxy
import java.net.URL
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CountDownLatch
@@ -20,6 +22,7 @@ object DownloadSource {
private const val KEY_MODE = "mode"
private const val KEY_MIRROR = "mirror"
private const val KEY_CUSTOM = "custom"
+ private const val KEY_PROXY = "proxy"
private const val KEY_FASTEST = "fastest"
private const val PROBE = "https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/README.md"
@@ -175,6 +178,22 @@ object DownloadSource {
prefs(context)?.edit()?.putString(KEY_CUSTOM, normalizePrefix(prefix))?.apply()
}
+ fun proxyHostPort(context: Context): String = prefs(context)?.getString(KEY_PROXY, "") ?: ""
+
+ fun setProxy(context: Context, value: String) {
+ prefs(context)?.edit()?.putString(KEY_PROXY, normalizeProxy(value))?.apply()
+ }
+
+ /** An HTTP proxy every Downloader connection uses, or null when none is configured. */
+ fun httpProxy(): Proxy? = proxyOf(prefs()?.getString(KEY_PROXY, "") ?: "")
+
+ internal fun proxyOf(value: String): Proxy? {
+ val host = value.substringBefore(':')
+ val port = value.substringAfter(':', "").toIntOrNull() ?: return null
+ if (host.isEmpty()) return null
+ return Proxy(Proxy.Type.HTTP, InetSocketAddress(host, port))
+ }
+
fun reset(context: Context) {
lastGood = null
prefs(context)?.edit()?.clear()?.apply()
@@ -205,4 +224,11 @@ object DownloadSource {
if (trimmed.isEmpty() || trimmed.startsWith("http://")) return ""
return if (trimmed.startsWith("https://")) trimmed else "https://$trimmed"
}
+
+ internal fun normalizeProxy(value: String): String {
+ val trimmed = value.trim().removePrefix("http://").trimEnd('/')
+ val host = trimmed.substringBefore(':')
+ val port = trimmed.substringAfter(':', "").toIntOrNull() ?: 0
+ return if (host.isNotEmpty() && port in 1..65535) "$host:$port" else ""
+ }
}
diff --git a/app/src/main/java/com/droiddeck/launcher/core/Downloader.java b/app/src/main/java/com/droiddeck/launcher/core/Downloader.java
index 183076188..98e41ab6f 100644
--- a/app/src/main/java/com/droiddeck/launcher/core/Downloader.java
+++ b/app/src/main/java/com/droiddeck/launcher/core/Downloader.java
@@ -11,6 +11,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
+import java.net.Proxy;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
@@ -277,7 +278,10 @@ public final class Downloader {
}
private static HttpURLConnection open(String url, int readTimeoutMs) throws java.io.IOException {
- HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
+ // An explicit Proxy routes the connection through the app setting instead of the system-wide proxy.
+ Proxy proxy = DownloadSource.INSTANCE.httpProxy();
+ HttpURLConnection connection = (HttpURLConnection) (proxy != null
+ ? new URL(url).openConnection(proxy) : new URL(url).openConnection());
connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
connection.setReadTimeout(readTimeoutMs);
connection.setInstanceFollowRedirects(true);
diff --git a/app/src/main/java/com/droiddeck/launcher/core/GameEnvironmentOptions.kt b/app/src/main/java/com/droiddeck/launcher/core/GameEnvironmentOptions.kt
index 3ad45c1fa..bcf3a0448 100644
--- a/app/src/main/java/com/droiddeck/launcher/core/GameEnvironmentOptions.kt
+++ b/app/src/main/java/com/droiddeck/launcher/core/GameEnvironmentOptions.kt
@@ -14,6 +14,8 @@ object GameEnvironmentOptions {
Option("MESA_SHADER_CACHE_MAX_SIZE", "1G", R.string.game_env_cache_size, Type.CHOICE, listOf("512M", "1G", "2G", "4G")),
Option("PROTON_LOG", "1", R.string.game_env_proton_log, Type.TOGGLE, listOf("0", "1")),
Option("PROTON_USE_WINED3D", "1", R.string.game_env_wined3d, Type.TOGGLE, listOf("0", "1")),
+ Option("PROTON_DXVK_D3D8", "1", R.string.game_env_dxvk_d3d8, Type.TOGGLE, listOf("0", "1")),
+ Option("WINE_D3D_CONFIG", "renderer=vulkan", R.string.game_env_wined3d_renderer, Type.CHOICE, listOf("renderer=vulkan", "renderer=gl")),
Option("PROTON_USE_XALIA", "0", R.string.game_env_xalia, Type.TOGGLE, listOf("0", "1")),
Option("PROTON_NO_NTSYNC", "1", R.string.game_env_no_ntsync, Type.TOGGLE, listOf("0", "1")),
Option("PROTON_NO_ESYNC", "1", R.string.game_env_no_esync, Type.TOGGLE, listOf("0", "1")),
@@ -32,6 +34,7 @@ object GameEnvironmentOptions {
Option("MESA_EXTENSION_MAX_YEAR", "", 0, Type.TEXT),
Option("MESA_GL_VERSION_OVERRIDE", "", 0, Type.TEXT),
Option("PULSE_LATENCY_MSEC", "", 0, Type.NUMBER),
+ Option("DROIDDECK_GAME_CORES", "", R.string.game_env_cores, Type.TEXT),
Option("DROIDDECK_ANTICHEAT_OFFLINE", "1", R.string.game_env_anticheat_offline, Type.TOGGLE, listOf("0", "1")),
Option("WINE_LARGE_ADDRESS_AWARE", "0", 0, Type.TOGGLE, listOf("0", "1")),
Option("WINEDLLOVERRIDES", "", 0, Type.TEXT),
diff --git a/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt b/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt
index 4a8b12934..075719246 100644
--- a/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt
+++ b/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt
@@ -8,7 +8,11 @@ object HostProcess {
private const val TAG = "HostProcess"
@JvmStatic
- fun start(command: String, env: Array?, dir: File?, onExit: Consumer?, onLine: Consumer?): Int {
+ fun start(command: String, env: Array?, dir: File?, onExit: Consumer?, onLine: Consumer?): Int =
+ start(command, env, dir, onExit, onLine, null)
+
+ @JvmStatic
+ fun start(command: String, env: Array?, dir: File?, onExit: Consumer?, onLine: Consumer?, outputFile: File?): Int {
val argv = split(command)
if (argv.isEmpty()) return -1
return try {
@@ -19,7 +23,10 @@ object HostProcess {
if (eq > 0) builder.environment()[line.substring(0, eq)] = line.substring(eq + 1)
}
builder.redirectErrorStream(true)
- if (onLine == null) builder.redirectOutput(File("/dev/null"))
+ if (onLine == null) {
+ if (outputFile == null) builder.redirectOutput(File("/dev/null"))
+ else builder.redirectOutput(ProcessBuilder.Redirect.appendTo(outputFile))
+ }
val process = builder.start()
val pid = pidOf(process)
Log.i(TAG, "started pid $pid: ${argv.first()} (${argv.size - 1} arguments)")
diff --git a/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt b/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt
index 491101dba..20073c4ca 100644
--- a/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt
+++ b/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt
@@ -76,7 +76,7 @@ object LogRedactor {
private const val ACCOUNT_VALUE = "(\"[^\"<\\r\\n]+\"|'[^'<\\r\\n]+'|[^\\s\"'<>&;,}]+)"
private val ACCOUNT_KV = Regex(
- "(?i)(? setChildProcessLimit(appContext, host, port, enabled) }
+ }
+
+ fun hasSavedPairing(context: Context): Boolean = savedConnection(context.applicationContext) != null
+
+ fun clearCachedApps(context: Context) {
+ shell(context, "am kill-all")
+ }
+
+ fun shell(context: Context, command: String): String {
+ var output = ""
+ withSavedPairing(context) { appContext, host, port ->
+ loadOrCreateIdentity(appContext)
+ Kadb.create(host, port).use { adb ->
+ val result = adb.shell(command)
+ check(result.exitCode == 0) { result.allOutput.ifBlank { appContext.getString(R.string.adbfix_command_failed, result.exitCode) } }
+ output = result.output
+ }
+ saveConnection(appContext, host, port)
+ }
+ return output
+ }
+
+ private fun withSavedPairing(context: Context, action: (Context, String, Int) -> Unit) {
val appContext = context.applicationContext
val saved = savedConnection(appContext)
?: error(appContext.getString(R.string.adbfix_no_pairing))
val cachedPort = saved.port
if (cachedPort != null) {
- val cachedResult = runCatching {
- setChildProcessLimit(appContext, saved.host, cachedPort, enabled)
- }
+ val cachedResult = runCatching { action(appContext, saved.host, cachedPort) }
if (cachedResult.isSuccess) return
val discoveredPort = findConnectPort(appContext, saved.host)
if (discoveredPort != null && discoveredPort != cachedPort) {
- setChildProcessLimit(appContext, saved.host, discoveredPort, enabled)
+ action(appContext, saved.host, discoveredPort)
} else {
cachedResult.getOrThrow()
}
} else {
val discoveredPort = findConnectPort(appContext, saved.host)
?: error(appContext.getString(R.string.adbfix_enter_address))
- setChildProcessLimit(appContext, saved.host, discoveredPort, enabled)
+ action(appContext, saved.host, discoveredPort)
}
}
}
diff --git a/app/src/main/java/com/droiddeck/launcher/files/CollapsibleRail.kt b/app/src/main/java/com/droiddeck/launcher/files/CollapsibleRail.kt
index bcba0189b..b1d93fdab 100644
--- a/app/src/main/java/com/droiddeck/launcher/files/CollapsibleRail.kt
+++ b/app/src/main/java/com/droiddeck/launcher/files/CollapsibleRail.kt
@@ -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)
diff --git a/app/src/main/java/com/droiddeck/launcher/files/FileManagerActivity.kt b/app/src/main/java/com/droiddeck/launcher/files/FileManagerActivity.kt
index 1425a78e7..873a413ad 100644
--- a/app/src/main/java/com/droiddeck/launcher/files/FileManagerActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/files/FileManagerActivity.kt
@@ -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)
}
diff --git a/app/src/main/java/com/droiddeck/launcher/files/FileManagerItems.kt b/app/src/main/java/com/droiddeck/launcher/files/FileManagerItems.kt
index e6289a3b9..3fb876ac2 100644
--- a/app/src/main/java/com/droiddeck/launcher/files/FileManagerItems.kt
+++ b/app/src/main/java/com/droiddeck/launcher/files/FileManagerItems.kt
@@ -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(),
)
}
}
diff --git a/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt b/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt
index 627761c2d..4ea75ab1c 100644
--- a/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt
+++ b/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt
@@ -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
@@ -70,6 +75,7 @@ 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
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
@@ -99,7 +105,9 @@ import kotlinx.coroutines.withContext
import java.io.File
import java.util.Date
-private enum class FileManagerNavigation { EXIT, RETURN_TO_START, BACK }
+private enum class FileManagerNavigation { EXIT, RETURN_TO_START, BACK, UP }
+
+private const val HISTORY_LIMIT = 50
internal fun canNavigateUp(currentDir: File, currentRoot: File): Boolean =
currentDir != currentRoot && currentDir.parentFile?.exists() == true
@@ -193,10 +201,17 @@ fun FileManagerScreen(
var favTick by remember { mutableIntStateOf(0) }
var listingJob by remember { mutableStateOf(null) }
+ val history = remember { mutableStateListOf>() }
+ var shownRoot by remember { mutableStateOf(initialRoot) }
- fun loadDirectory(dir: File, resetScroll: Boolean = true) {
+ fun loadDirectory(dir: File, resetScroll: Boolean = true, record: Boolean = true) {
if (cancellingNavigation) return
+ if (record && dir != currentDir) {
+ history.add(currentDir to shownRoot)
+ if (history.size > HISTORY_LIMIT) history.removeAt(0)
+ }
currentDir = dir
+ shownRoot = currentRoot
if (pickMode) pickPrefs.edit().putString("lastFilePickerDir", dir.absolutePath).apply()
listingJob?.cancel()
listingJob = scope.launch {
@@ -251,6 +266,18 @@ fun FileManagerScreen(
FileManagerNavigation.EXIT -> onExit?.invoke()
FileManagerNavigation.RETURN_TO_START -> returnToStart()
FileManagerNavigation.BACK -> {
+ if (showFavorites) showFavorites = false
+ else {
+ while (history.isNotEmpty() && !history.last().first.isDirectory) history.removeAt(history.lastIndex)
+ val previous = history.removeLastOrNull()
+ if (previous != null) {
+ currentRoot = previous.second
+ loadDirectory(previous.first, record = false)
+ } else if (canNavigateUp(currentDir, currentRoot)) currentDir.parentFile?.let { loadDirectory(it, record = false) }
+ else onExit?.invoke()
+ }
+ }
+ FileManagerNavigation.UP -> {
if (showFavorites) showFavorites = false
else if (canNavigateUp(currentDir, currentRoot)) currentDir.parentFile?.let { loadDirectory(it) }
else onExit?.invoke()
@@ -263,7 +290,7 @@ fun FileManagerScreen(
if (isOperationActive()) pendingNavigation = action else navigate(action)
}
- BackHandler(enabled = operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot) {
+ BackHandler(enabled = operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot || history.isNotEmpty()) {
requestNavigation(FileManagerNavigation.BACK)
}
@@ -296,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))
}
},
@@ -487,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)) } },
)
}
@@ -510,6 +538,7 @@ fun FileManagerScreen(
onValueChange = { newName = it },
label = { Text(stringResource(R.string.fm_new_name)) },
singleLine = true,
+ modifier = Modifier.focusGlide(),
)
},
confirmButton = {
@@ -517,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)) } },
)
}
@@ -541,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)) } },
)
}
@@ -589,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)) } },
)
}
@@ -614,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)
}
@@ -626,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()) }
}
@@ -634,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(
@@ -659,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))
@@ -671,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.BACK) }, 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)
}
@@ -722,6 +754,7 @@ fun FileManagerScreen(
).show()
}
},
+ modifier = Modifier.focusGlide(),
)
}
linuxRoot?.let { root ->
@@ -732,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(),
)
}
}
@@ -747,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 },
@@ -759,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))
@@ -776,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))
@@ -786,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 }) {
@@ -814,6 +848,7 @@ fun FileManagerScreen(
showSortMenu = false
loadDirectory(currentDir, resetScroll = false)
},
+ modifier = Modifier.focusGlide(),
)
}
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
@@ -824,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)) },
@@ -833,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 {
@@ -846,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)
}
}
@@ -858,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(),
)
}
@@ -896,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 }
@@ -913,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(
@@ -924,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(
@@ -935,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(
@@ -942,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) }
}
}
@@ -968,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)
}
}
@@ -999,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))
@@ -1089,7 +1132,7 @@ fun FileManagerScreen(
contentPadding = PaddingValues(8.dp),
) {
if (canGoUp) item(key = "..", span = { GridItemSpan(maxLineSpan) }) {
- ParentFolderRow(compact = compactRows, onTap = { requestNavigation(FileManagerNavigation.BACK) })
+ ParentFolderRow(compact = compactRows, onTap = { requestNavigation(FileManagerNavigation.UP) })
}
items(shownEntries, key = { it.absolutePath }) { file ->
val isFav = remember(file.absolutePath, favTick) {
@@ -1155,7 +1198,7 @@ fun FileManagerScreen(
} else
LazyColumn(state = listState, modifier = Modifier.fillMaxSize()) {
if (canGoUp) item(key = "..") {
- ParentFolderRow(compact = compactRows, onTap = { requestNavigation(FileManagerNavigation.BACK) })
+ ParentFolderRow(compact = compactRows, onTap = { requestNavigation(FileManagerNavigation.UP) })
}
if (entries.isEmpty()) {
item {
diff --git a/app/src/main/java/com/droiddeck/launcher/files/FilePickerActivity.kt b/app/src/main/java/com/droiddeck/launcher/files/FilePickerActivity.kt
index 498ec504e..39a83e40e 100644
--- a/app/src/main/java/com/droiddeck/launcher/files/FilePickerActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/files/FilePickerActivity.kt
@@ -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)
}
diff --git a/app/src/main/java/com/droiddeck/launcher/files/FilePropertiesDialog.kt b/app/src/main/java/com/droiddeck/launcher/files/FilePropertiesDialog.kt
index f4f8d80fb..07fbb1560 100644
--- a/app/src/main/java/com/droiddeck/launcher/files/FilePropertiesDialog.kt
+++ b/app/src/main/java/com/droiddeck/launcher/files/FilePropertiesDialog.kt
@@ -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(),
)
}
}
diff --git a/app/src/main/java/com/droiddeck/launcher/files/OutlinedAlertDialog.kt b/app/src/main/java/com/droiddeck/launcher/files/OutlinedAlertDialog.kt
index 3919e89b0..2eda726c3 100644
--- a/app/src/main/java/com/droiddeck/launcher/files/OutlinedAlertDialog.kt
+++ b/app/src/main/java/com/droiddeck/launcher/files/OutlinedAlertDialog.kt
@@ -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
diff --git a/app/src/main/java/com/droiddeck/launcher/files/StorageRoots.kt b/app/src/main/java/com/droiddeck/launcher/files/StorageRoots.kt
index 99e940157..273917b00 100644
--- a/app/src/main/java/com/droiddeck/launcher/files/StorageRoots.kt
+++ b/app/src/main/java/com/droiddeck/launcher/files/StorageRoots.kt
@@ -29,6 +29,50 @@ object StorageRoots {
val seeds = LinkedHashSet()
}
+ private val EXTERNAL_MOUNT_TYPES = setOf(
+ "vfat", "exfat", "texfat", "ntfs", "ntfs3", "fuseblk", "fuse", "sdcardfs",
+ )
+
+ internal data class MountPoint(val target: File, val type: String)
+
+ internal fun parseMountPoints(mounts: String): List {
+ val out = ArrayList()
+ for (line in mounts.lineSequence()) {
+ val parts = line.split(' ')
+ if (parts.size < 3) continue
+ out.add(MountPoint(File(parts[1].replace("\\040", " ")), parts[2].lowercase()))
+ }
+ return out.distinct()
+ }
+
+ internal fun isExternalMount(mount: MountPoint): Boolean {
+ val path = mount.target.path
+ val name = when {
+ path.startsWith("/storage/") -> path.removePrefix("/storage/")
+ path.startsWith("/mnt/media_rw/") -> path.removePrefix("/mnt/media_rw/")
+ path.startsWith("/mnt/") -> path.removePrefix("/mnt/")
+ else -> return false
+ }
+ if ('/' in name || name.isEmpty() || name == "emulated" || name == "self") return false
+ if (mount.type in EXTERNAL_MOUNT_TYPES) {
+ if (path.startsWith("/mnt/") && !path.startsWith("/mnt/media_rw/")) {
+ val lower = name.lowercase()
+ if (!lower.contains("usb") && !lower.contains("otg") &&
+ !lower.contains("udisk") && !lower.contains("disk")
+ ) return false
+ }
+ return true
+ }
+ // vold-managed locations only hold removable volumes, whatever the fstype is.
+ return path.startsWith("/storage/") || path.startsWith("/mnt/media_rw/")
+ }
+
+ internal fun parseExternalMounts(mounts: String): List =
+ parseMountPoints(mounts).filter(::isExternalMount).map { it.target }
+
+ fun externalMounts(): List =
+ runCatching { parseExternalMounts(File("/proc/mounts").readText()) }.getOrDefault(emptyList())
+
fun list(context: Context): List {
val volumes = LinkedHashMap()
@@ -44,21 +88,31 @@ object StorageRoots {
val storageManager = context.getSystemService(StorageManager::class.java)
storageManager?.storageVolumes.orEmpty()
- .filter { isMounted(it.state) }
- .forEach { volume ->
+ .filter { present(it.state) }
+ .forEachIndexed { index, volume ->
val uuid = volume.uuid?.takeIf { it.isNotBlank() }
- val entry = volumeOf(if (volume.isPrimary) PRIMARY_KEY else uuid ?: return@forEach)
+ val dirName = volume.directory?.name?.takeIf { it.isNotBlank() }
+ // Unmounted volumes often report neither uuid nor directory; never drop the
+ // volume or a plugged-in drive stays invisible with no explanation.
+ val descSlug = volume.getDescription(context)?.trim()
+ ?.takeIf { it.isNotBlank() && !it.equals("android", ignoreCase = true) }
+ ?.replace(Regex("[^A-Za-z0-9._-]+"), "-")
+ val entry = volumeOf(if (volume.isPrimary) PRIMARY_KEY else uuid ?: dirName ?: descSlug ?: "volume-$index")
entry.removable = !volume.isPrimary && volume.isRemovable
- if (entry.label == null) entry.label = labelFor(context, volume, uuid)
+ if (entry.label == null) entry.label = labelFor(context, volume, uuid ?: dirName ?: descSlug)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
volume.directory?.let { entry.candidates += it }
}
- if (uuid != null) {
- entry.candidates += File("/storage/$uuid")
- entry.candidates += File("/mnt/media_rw/$uuid")
+ val name = uuid ?: dirName
+ if (name != null) {
+ entry.candidates += File("/storage/$name")
+ entry.candidates += File("/mnt/media_rw/$name")
+ // Only strict uuid matches own an app directory; a loose match would
+ // attach another volume's folder to this entry.
+ if (uuid != null) appDirs.filter { belongsTo(storageManager!!, it, volume) }
+ .forEach { entry.seeds += it }
}
- appDirs.filter { belongsTo(storageManager!!, it, volume) }.forEach { entry.seeds += it }
}
File("/storage").listFiles().orEmpty().forEach { child ->
@@ -68,6 +122,13 @@ object StorageRoots {
File("/mnt/media_rw").listFiles().orEmpty().forEach { child ->
if (child.isDirectory) volumeOf(child.name).candidates += child
}
+ // USB OTG drives do not always appear as storage volumes or under /storage for
+ // third-party apps, but their kernel mounts are still visible in /proc/mounts.
+ for (mount in externalMounts()) {
+ val entry = volumeOf(mount.name)
+ if (entry.label == null) entry.label = mount.name
+ entry.candidates += mount
+ }
appDirs.forEach { dir ->
val root = volumeRootOf(dir) ?: return@forEach
@@ -141,15 +202,19 @@ object StorageRoots {
private fun labelFor(context: Context, volume: StorageVolume, uuid: String?): String {
if (volume.isPrimary) return context.getString(R.string.fm_drive_internal)
- if (volume.isRemovable) return context.getString(R.string.fm_drive_sd)
val description = volume.getDescription(context)?.trim()
- return description?.takeIf { it.isNotBlank() && !it.equals("android", ignoreCase = true) }
- ?: uuid
+ if (!description.isNullOrBlank() && !description.equals("android", ignoreCase = true)) return description
+ if (volume.isRemovable) return context.getString(R.string.fm_drive_sd)
+ return uuid
?: context.getString(R.string.fm_drive_storage)
}
private fun isEmulated(dir: File): Boolean = dir.absolutePath.startsWith(EMULATED_PREFIX)
+ private fun present(state: String?): Boolean =
+ isMounted(state) || state == Environment.MEDIA_UNMOUNTED || state == Environment.MEDIA_CHECKING ||
+ state == Environment.MEDIA_NOFS || state == Environment.MEDIA_UNMOUNTABLE
+
private fun isMounted(state: String?): Boolean =
state == Environment.MEDIA_MOUNTED || state == Environment.MEDIA_MOUNTED_READ_ONLY
diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGameArt.kt b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGameArt.kt
index 8315c22e9..28eb1bf72 100644
--- a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGameArt.kt
+++ b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGameArt.kt
@@ -4,7 +4,9 @@ import android.content.Context
import android.graphics.Bitmap
import android.util.Log
import com.droiddeck.launcher.files.PeIconExtractor
+import com.droiddeck.launcher.runtime.BattleNet
import com.droiddeck.launcher.session.SessionPrefs
+import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreArt
import com.droiddeck.launcher.stores.StoreGameSidecar
import org.json.JSONObject
@@ -75,14 +77,18 @@ object AddedGameArt {
)
}
+ private fun storeArt(context: Context, game: AddedGames.Game): BattleNet.Art? =
+ if (game.source != Store.BATTLENET.id) null else game.storeId?.let(BattleNet::title)?.let { BattleNet.art(context, it) }
+
fun resolve(context: Context, game: AddedGames.Game): Art {
val own = local(game)
val cache = cacheDir(context, game)
+ val store = storeArt(context, game)
fun cached(name: String) = File(cache, name).takeIf { it.isFile }
return Art(
- portrait = chosen(cache, Slot.COVER) ?: own.portrait ?: cached("p.jpg") ?: exeArt(context, game, cover = true),
- header = chosen(cache, Slot.WIDE) ?: own.header ?: cached("header.jpg") ?: exeArt(context, game, cover = false),
- hero = chosen(cache, Slot.BACKGROUND) ?: own.hero ?: cached("hero.jpg"),
+ portrait = chosen(cache, Slot.COVER) ?: own.portrait ?: store?.cover ?: cached("p.jpg") ?: exeArt(context, game, cover = true),
+ header = chosen(cache, Slot.WIDE) ?: own.header ?: store?.header ?: cached("header.jpg") ?: exeArt(context, game, cover = false),
+ hero = chosen(cache, Slot.BACKGROUND) ?: own.hero ?: store?.header ?: cached("hero.jpg"),
logo = chosen(cache, Slot.LOGO) ?: own.logo ?: cached("logo.png"),
icon = chosen(cache, Slot.ICON) ?: own.icon ?: cached("icon-sgdb.png") ?: exeIcon(context, game),
)
@@ -91,15 +97,16 @@ object AddedGameArt {
fun describe(context: Context, game: AddedGames.Game): List {
val own = local(game)
val cache = cacheDir(context, game)
+ val store = storeArt(context, game)
fun cached(name: String): Pair? = File(cache, name).takeIf { it.isFile }?.let { f ->
f to (File(cache, "$name.src").takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() } ?: STEAM)
}
return Slot.values().map { slot ->
chosen(cache, slot)?.let { return@map SlotState(slot, it, chosenSource(context, game, slot).first.ifEmpty { FILE }, true) }
val auto: Pair? = when (slot) {
- Slot.COVER -> own.portrait?.let { it to FOLDER } ?: cached("p.jpg") ?: exeArt(context, game, cover = true)?.let { it to EXE }
- Slot.WIDE -> own.header?.let { it to FOLDER } ?: cached("header.jpg") ?: exeArt(context, game, cover = false)?.let { it to EXE }
- Slot.BACKGROUND -> own.hero?.let { it to FOLDER } ?: cached("hero.jpg")
+ Slot.COVER -> own.portrait?.let { it to FOLDER } ?: store?.cover?.let { it to AUTO } ?: cached("p.jpg") ?: exeArt(context, game, cover = true)?.let { it to EXE }
+ Slot.WIDE -> own.header?.let { it to FOLDER } ?: store?.header?.let { it to AUTO } ?: cached("header.jpg") ?: exeArt(context, game, cover = false)?.let { it to EXE }
+ Slot.BACKGROUND -> own.hero?.let { it to FOLDER } ?: store?.header?.let { it to AUTO } ?: cached("hero.jpg")
Slot.LOGO -> own.logo?.let { it to FOLDER } ?: cached("logo.png")
Slot.ICON -> own.icon?.let { it to FOLDER } ?: File(cache, "icon-sgdb.png").takeIf { it.isFile }?.let { it to SGDB }
?: exeIcon(context, game)?.let { it to EXE }
@@ -253,12 +260,13 @@ object AddedGameArt {
internal fun missing(context: Context, game: AddedGames.Game): Set {
val own = local(game)
val cache = cacheDir(context, game)
+ val store = storeArt(context, game)
fun has(slot: Slot, mine: File?, cached: String) = chosen(cache, slot) != null || mine != null || File(cache, cached).isFile
return Slot.values().filterNot { slot ->
when (slot) {
- Slot.COVER -> has(slot, own.portrait, "p.jpg")
- Slot.WIDE -> has(slot, own.header, "header.jpg")
- Slot.BACKGROUND -> has(slot, own.hero, "hero.jpg")
+ Slot.COVER -> has(slot, own.portrait ?: store?.cover, "p.jpg")
+ Slot.WIDE -> has(slot, own.header ?: store?.header, "header.jpg")
+ Slot.BACKGROUND -> has(slot, own.hero ?: store?.header, "hero.jpg")
Slot.LOGO -> has(slot, own.logo, "logo.png")
Slot.ICON -> has(slot, own.icon, "icon-sgdb.png")
}
@@ -322,6 +330,10 @@ object AddedGameArt {
}
internal fun steamMatch(context: Context, game: AddedGames.Game, search: (String) -> Int?): SteamMatch.Match {
+ if (game.source == Store.BATTLENET.id) {
+ val id = game.storeId?.let(BattleNet::title)?.steam
+ return SteamMatch.Match(id, if (id == null) SteamMatch.Certainty.NONE else SteamMatch.Certainty.FILES, Store.BATTLENET.id, System.currentTimeMillis())
+ }
val match = SteamMatch.resolve(context, game.folder.path, game.exe, game.name, legacy = File(cacheDir(context, game), "steam-appid"), search = search)
match.appId?.let { Log.i(TAG, "${game.name}: Steam app $it (${match.certainty.name.lowercase()})") }
return match
@@ -361,14 +373,14 @@ object AddedGameArt {
.filter { it.second > 0 && it.first.isNotEmpty() }
.maxByOrNull { it.second }?.first
- private fun search(name: String): String? {
+ internal fun search(name: String): String? {
val term = name.replace(EDITION, " ").trim().ifEmpty { name }
val json = get(STORE_SEARCH + URLEncoder.encode(term, "UTF-8"))?.toString(Charsets.UTF_8) ?: return null
val items = JSONObject(json).optJSONArray("items") ?: return null
return pickStoreResult(name, (0 until items.length()).map { items.getJSONObject(it) }.map { it.optString("id") to it.optString("name") })
}
- private fun download(id: String, cache: File, slots: Set): Boolean {
+ internal fun download(id: String, cache: File, slots: Set = Slot.entries.toSet()): Boolean {
var got = false
for ((slot, remote, localName) in listOf(
Triple(Slot.COVER, "library_600x900.jpg", "p.jpg"), Triple(Slot.WIDE, "header.jpg", "header.jpg"),
diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt
index 340bc83ce..aa1c6eef4 100644
--- a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt
+++ b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt
@@ -79,6 +79,18 @@ object AddedGames {
return null
}
+ fun hostPath(context: Context, guest: String): File? {
+ if (!guest.startsWith("/") || guest.split('/').any { it == ".." }) return null
+ val mapped = roots(context).map { it.host to it.guest } + StoreInstallRoot.externalRoots(context) +
+ listOfNotNull(GameStorage.effective(context)?.let { File(it.path) to LIBRARY }) +
+ (android.os.Environment.getExternalStorageDirectory() to "/root/Storage")
+ for ((host, root) in mapped.sortedByDescending { it.second.length }) {
+ if (guest == root) return host
+ if (guest.startsWith("$root/")) return File(host, guest.removePrefix("$root/"))
+ }
+ return File(LinuxRuntime.rootDir(context), guest.removePrefix("/"))
+ }
+
fun candidates(folder: File): List = rank(folder).exes
fun rank(folder: File): GameExePicker.Ranking {
@@ -177,6 +189,9 @@ object AddedGames {
scanGame(context, folder, out, single = entry)
}
for (folder in StoreInstallRoot.gameFolders(context)) if (StoreInstallRoot.isFinished(folder)) scanGame(context, folder, out)
+ for (game in com.droiddeck.launcher.runtime.BattleNet.games(context)) {
+ if (game.folder.path !in removed) com.droiddeck.launcher.runtime.BattleNet.shortcut(context, game)?.let(out::add)
+ }
return out.distinctBy { it.folder.canonicalPath }
}
diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/AutoComponents.kt b/app/src/main/java/com/droiddeck/launcher/frontend/AutoComponents.kt
index fc3274427..650c717d8 100644
--- a/app/src/main/java/com/droiddeck/launcher/frontend/AutoComponents.kt
+++ b/app/src/main/java/com/droiddeck/launcher/frontend/AutoComponents.kt
@@ -257,14 +257,18 @@ object AutoComponents {
private const val FINDINGS = "wincomp-findings.json"
+ private const val DETECTORS = "d3"
internal fun signature(context: Context, game: Library.SteamGame): String {
val folder = game.gameFiles
val parts = listOfNotNull(
+ DETECTORS,
folder?.lastModified(),
folder?.let { SteamRedists.manifest(it, game.appId)?.lastModified() },
folder?.let { StoreGameSidecar.file(it).lastModified() },
folder?.let { File(it, "fuel.json").lastModified() },
+ folder?.listFiles { f -> f.name.lowercase().let { it.startsWith("installscript") && it.endsWith(".vdf") } }
+ ?.maxOfOrNull { it.lastModified() },
SteamAppInfo.appinfoFile(context).lastModified(),
folder?.let { SteamMatch.get(context, it.path) }?.let { "${it.appId}/${it.certainty}" },
steamAppOf(context, game)?.let { SteamAppInfo.state(context, it) },
diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/GameRemoval.kt b/app/src/main/java/com/droiddeck/launcher/frontend/GameRemoval.kt
index ab997f027..388448e18 100644
--- a/app/src/main/java/com/droiddeck/launcher/frontend/GameRemoval.kt
+++ b/app/src/main/java/com/droiddeck/launcher/frontend/GameRemoval.kt
@@ -11,7 +11,7 @@ object GameRemoval {
enum class Kind { STORE, SHORTCUT, LAUNCHER }
fun kind(game: Library.SteamGame): Kind = when {
- game.library == Library.EPIC_LAUNCHER -> Kind.LAUNCHER
+ game.library == Library.EPIC_LAUNCHER || game.library == Library.BATTLENET_LAUNCHER -> Kind.LAUNCHER
game.library == Library.ADDED && game.source == Library.ADDED -> Kind.SHORTCUT
else -> Kind.STORE
}
diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt b/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt
index 05f3f9869..9fb776447 100644
--- a/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt
+++ b/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt
@@ -22,11 +22,16 @@ object Library {
SteamGame(appId, name, art, library, gameId, hero, lastPlayed, gameFiles, protonPrefix, icon, source, storeId, logo)
val gameIdString: String get() = java.lang.Long.toUnsignedString(gameId)
- val profileKey: String get() = if (library == ADDED) java.lang.Integer.toUnsignedString(appId) else appId.toString()
+ val profileKey: String get() = when {
+ source == com.droiddeck.launcher.stores.Store.BATTLENET.id -> com.droiddeck.launcher.runtime.BattleNet.APP_ID.toString()
+ library == ADDED -> java.lang.Integer.toUnsignedString(appId)
+ else -> appId.toString()
+ }
}
const val ADDED = "added"
const val EPIC_LAUNCHER = "epic-launcher"
const val EPIC_LAUNCHER_NAME = "Epic Games Launcher"
+ const val BATTLENET_LAUNCHER = "battlenet-launcher"
const val XBOX_CLOUD = "xbox-cloud"
const val SOURCE_STEAM = "steam"
@@ -204,9 +209,24 @@ object Library {
(runCatching { g.folder.canonicalPath }.getOrDefault(g.folder.absolutePath) !in claimed &&
AddedGames.guestPath(context, g.folder).let { it == null || it !in claimed })
}
- return (steam + own.map { g -> addedGame(context, g, roots) }).distinctBy { it.gameId }
+ val played = shortcutsLastPlayed(SessionPrefs.steamRoot(context, arch))
+ return (steam + own.map { g -> addedGame(context, g, roots, played[g.appId] ?: 0L) }).distinctBy { it.gameId }
}
+ /** Steam's LastPlayTime for each non-Steam shortcut, by its unsigned shortcut app id. */
+ internal fun shortcutsLastPlayed(root: File): Map = runCatching {
+ val config = AddedGames.accountConfig(root) ?: return emptyMap()
+ val bytes = File(config, "shortcuts.vdf").takeIf { it.isFile }?.readBytes() ?: return emptyMap()
+ val vdf = SteamAppInfo.readMap(java.nio.ByteBuffer.wrap(bytes).order(java.nio.ByteOrder.LITTLE_ENDIAN), null)
+ (vdf["shortcuts"] as? Map<*, *>)?.values?.filterIsInstance