Compare commits

..
280 changed files with 2457 additions and 15030 deletions

No files matched your search

@@ -1,39 +0,0 @@
name: Community controls pack
description: Submit on-screen controls for the community catalog.
title: "[Controls]: "
body:
- type: markdown
attributes:
value: Export a ZIP from Controller settings → Community controls. Attach the ZIP and a screenshot below. Submissions are reviewed before inclusion in the catalog.
- type: input
id: name
attributes:
label: Pack name and author
validations:
required: true
- type: input
id: game
attributes:
label: Game (optional)
description: Include the store and game ID if these controls target a specific game.
- type: textarea
id: files
attributes:
label: Controls ZIP and screenshot
description: Drag the exported .ddcontrols.zip and a preview screenshot here. Describe the screen orientation and bindings.
validations:
required: true
- type: input
id: license
attributes:
label: License and artwork credits
description: Specify a license that permits redistribution, and credit any third-party artwork with its source and license.
validations:
required: true
- type: checkboxes
id: permission
attributes:
label: Distribution permission
options:
- label: I have permission to share this pack and all included artwork under the stated license.
required: true
+1 -43
View File
@@ -849,7 +849,7 @@ jobs:
run: test "$(git rev-parse 'HEAD^{tree}')" = "$XBOX_SOURCE_TREE"
- name: Install Python test dependencies
timeout-minutes: 7
run: bash tools/ci/install-ubuntu-packages.sh python3-yaml gcc-aarch64-linux-gnu libc6-dev-arm64-cross qemu-user libvulkan-dev mesa-vulkan-drivers spirv-tools
run: bash tools/ci/install-ubuntu-packages.sh python3-yaml gcc-aarch64-linux-gnu libc6-dev-arm64-cross qemu-user libvulkan-dev mesa-vulkan-drivers
- name: Resolve the pinned Android NDK
run: bash tools/ci/resolve-ndk.sh
@@ -879,16 +879,6 @@ jobs:
-ldl -o /tmp/test-presenter-shutdown
timeout 10 /tmp/test-presenter-shutdown
- name: Fetch the Mali compatibility layer's headers
run: |
set -euo pipefail
sdk=$(sed -n 's/^SDK=//p' tools/venus/ci-build.sh)
bcdec=$(grep -o 'https://raw.githubusercontent.com/iOrange/bcdec/[^ ]*' tools/venus/ci-build.sh)
mkdir -p build/layer-deps/bcdec
git -c advice.detachedHead=false clone -q --depth 1 -b "$sdk" https://github.com/KhronosGroup/Vulkan-Headers.git build/layer-deps/vulkan
git -c advice.detachedHead=false clone -q --depth 1 -b "$sdk" https://github.com/KhronosGroup/SPIRV-Headers.git build/layer-deps/spirv
curl -sSfL -o build/layer-deps/bcdec/bcdec.h "$bcdec"
- name: Steam import and game environment tests
run: bash tools/ci/run-python-tests.sh
@@ -992,35 +982,3 @@ jobs:
if: ${{ always() && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && needs.announce.result != 'skipped' }}
uses: ./.github/workflows/update-catalog.yml
secrets: inherit
retire-tests:
needs: catalog
if: ${{ always() && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && needs.catalog.result == 'success' }}
runs-on: ubuntu-24.04
timeout-minutes: 10
permissions:
contents: read
pull-requests: read
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.sha }}
persist-credentials: false
- uses: actions/create-github-app-token@v2
id: ci-token
with:
app-id: ${{ vars.DROIDDECK_CI_APP_ID }}
private-key: ${{ secrets.DROIDDECK_CI_APP_KEY }}
owner: Droid-Deck
repositories: DroidDeck-CI
- name: Delete the test builds this Preview build replaces
env:
SOURCE_GITHUB_TOKEN: ${{ github.token }}
CI_GITHUB_TOKEN: ${{ steps.ci-token.outputs.token }}
run: python3 tools/release/retire_test_builds.py
catalog-after-retire:
needs: retire-tests
if: ${{ always() && needs.retire-tests.result == 'success' }}
uses: ./.github/workflows/update-catalog.yml
secrets: inherit
+25 -8
View File
@@ -40,19 +40,36 @@ jobs:
private-key: ${{ secrets.DROIDDECK_CI_APP_KEY }}
owner: Droid-Deck
repositories: DroidDeck-CI
- name: Delete the test build
if: ${{ steps.state.outputs.closed == 'true' }}
env:
GH_TOKEN: ${{ steps.ci-token.outputs.token }}
PR_NUMBER: ${{ github.event.pull_request.number }}
run: |
set -euo pipefail
retry() {
for attempt in 1 2 3 4; do
"$@" && return 0
[ "$attempt" = 4 ] || sleep $((attempt * 20))
done
return 1
}
existing=$(retry gh api --paginate "repos/Droid-Deck/DroidDeck-CI/releases?per_page=100" --jq '.[].tag_name')
found=0
for tag in "pr-$PR_NUMBER" "pr-$PR_NUMBER.0"; do
if grep -qxF "$tag" <<<"$existing"; then
retry gh release delete "$tag" -R Droid-Deck/DroidDeck-CI --yes --cleanup-tag
echo "Deleted $tag"
found=1
fi
done
[ "$found" = 1 ] || echo "No test build for PR #$PR_NUMBER"
- uses: actions/checkout@v4
if: ${{ steps.state.outputs.closed == 'true' }}
with:
ref: main
persist-credentials: false
- name: Delete the test build unless main still needs it
if: ${{ steps.state.outputs.closed == 'true' }}
env:
SOURCE_GITHUB_TOKEN: ${{ github.token }}
CI_GITHUB_TOKEN: ${{ steps.ci-token.outputs.token }}
PR_NUMBER: ${{ github.event.pull_request.number }}
# A merged PR's build stays until a Preview build carries the merge; build.yml and the sweep remove it then.
run: python3 tools/release/retire_test_builds.py --pr "$PR_NUMBER"
- name: Retire the Discord PR announcement
if: ${{ steps.state.outputs.closed == 'true' }}
env:
+6 -42
View File
@@ -226,8 +226,6 @@ jobs:
publish:
needs: [authorize, sign]
runs-on: ubuntu-24.04
outputs:
keep: ${{ steps.publish.outputs.keep }}
permissions:
actions: read
contents: read
@@ -324,8 +322,12 @@ jobs:
cp pr-packs/* signed/ 2>/dev/null || true
gh release upload "$tag" signed/* -R "$repo" --clobber
gh release edit "$tag" -R "$repo" --title "PR #$PR_NUMBER" --notes "$notes" --prerelease
# The previous push's files stay until the catalog names these (the prune job), so a download started from the old catalog still finds its APK.
echo "keep=$(cd signed && ls | jq -R . | jq -sc .)" >> "$GITHUB_OUTPUT"
keep=$(cd signed && ls | jq -R . | jq -sc .)
gh api "repos/$repo/releases/tags/$tag" |
jq -r --argjson keep "$keep" '.assets[] | select(.name as $n | $keep | index($n) | not) | .id' |
while IFS= read -r id; do
gh api --method DELETE "repos/$repo/releases/assets/$id" >/dev/null
done
published=$(gh release view "$tag" -R "$repo" --json tagName,assets)
jq -e --arg tag "$tag" '.tagName == $tag and (.assets | length) > 0' <<<"$published" >/dev/null
@@ -415,41 +417,3 @@ jobs:
if: ${{ always() && needs.publish.result != 'skipped' }}
uses: ./.github/workflows/update-catalog.yml
secrets: inherit
prune:
needs: [authorize, publish, catalog]
if: ${{ always() && needs.publish.result == 'success' && needs.catalog.result == 'success' }}
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
- uses: actions/create-github-app-token@v2
id: ci-token
with:
app-id: ${{ vars.DROIDDECK_CI_APP_ID }}
private-key: ${{ secrets.DROIDDECK_CI_APP_KEY }}
owner: Droid-Deck
repositories: DroidDeck-CI
- name: Remove the previous push's files
env:
GH_TOKEN: ${{ steps.ci-token.outputs.token }}
PR_NUMBER: ${{ needs.authorize.outputs.pr_number }}
KEEP: ${{ needs.publish.outputs.keep }}
run: |
set -euo pipefail
repo=Droid-Deck/DroidDeck-CI
tag="pr-$PR_NUMBER"
# An app that read the catalog just before it changed may still be starting that download.
sleep 300
# Delete nothing the published catalog still names.
named=$(gh api -H "Accept: application/vnd.github.raw+json" "repos/$repo/contents/catalog.json?ref=main" |
jq -c --argjson pr "$PR_NUMBER" '[.tests[] | select(.pr == $pr) | .apks[].name]')
stale=$(jq -nr --argjson named "$named" --argjson keep "$KEEP" '$named - $keep | join(" ")')
if [ -n "$stale" ]; then
echo "::warning::The catalog still names $stale; keeping every file of $tag"
exit 0
fi
gh api "repos/$repo/releases/tags/$tag" |
jq -r --argjson keep "$KEEP" '.assets[] | select(.name as $n | $keep | index($n) | not) | .id' |
while IFS= read -r id; do
gh api --method DELETE "repos/$repo/releases/assets/$id" >/dev/null
done
+28 -8
View File
@@ -26,15 +26,35 @@ jobs:
private-key: ${{ secrets.DROIDDECK_CI_APP_KEY }}
owner: Droid-Deck
repositories: DroidDeck-CI
- uses: actions/checkout@v4
with:
ref: main
persist-credentials: false
- name: Delete test builds of closed PRs, and of merged PRs a Preview build carries
- name: Delete test builds whose PR is no longer open
env:
SOURCE_GITHUB_TOKEN: ${{ github.token }}
CI_GITHUB_TOKEN: ${{ steps.ci-token.outputs.token }}
run: python3 tools/release/retire_test_builds.py
CI_TOKEN: ${{ steps.ci-token.outputs.token }}
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
retry() {
for attempt in 1 2 3 4; do
"$@" && return 0
[ "$attempt" = 4 ] || sleep $((attempt * 20))
done
return 1
}
tags=$(GH_TOKEN="$CI_TOKEN" retry gh api --paginate "repos/Droid-Deck/DroidDeck-CI/releases?per_page=100" --jq '.[].tag_name' |
grep -E '^pr-[0-9]+(\.0)?$' || true)
failed=0
for tag in $tags; do
number=${tag#pr-}
number=${number%.0}
state=$(retry gh api "repos/$GITHUB_REPOSITORY/pulls/$number" --jq .state) || { failed=1; continue; }
if [ "$state" != open ]; then
if GH_TOKEN="$CI_TOKEN" retry gh release delete "$tag" -R Droid-Deck/DroidDeck-CI --yes --cleanup-tag; then
echo "Deleted $tag (PR #$number is $state)"
else
failed=1
fi
fi
done
exit "$failed"
catalog:
needs: sweep
+3 -3
View File
@@ -80,7 +80,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
- The proot fast path orders bindings like [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later).
- DiRT 3 and DiRT Showdown keep their telemetry socket the way RoccoC's DiRTTelemetryErrorFix (MIT) does, based on the fix by Carsten Gottschling.
- Zink on PowerVR keeps colour textures in colour with Icenowy Zheng's upstream [Mesa](https://gitlab.freedesktop.org/mesa/mesa) fix d55418dae7 (MIT), carried as a runtime patch.
- Games and AppImage, Flatpak and Snap programs such as emulators use `TU_DEBUG=sysmem` by default, as does the Steam client. Turnip sysmem rendering can be turned off in Performance settings, except with the Adreno 710/720 driver, which always uses it.
- Games and AppImage, Flatpak and Snap programs such as emulators use [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's per render pass memory choice. The Steam client and Chromium-based apps keep `TU_DEBUG=sysmem`.
- Black Ops III and Dark Souls Remastered start without [umu-protonfixes](https://github.com/Open-Wine-Components/umu-protonfixes) (BSD-2-Clause), whose `311210.py` and `570940.py` fail under ARM64 Proton.
- [ReSkate](https://github.com/Dingo-Shenanigans/ReSkate) (GPL-3.0) by Dingo Shenanigans uses the launch option from its README and D3D12 feature level 12_1.
- The arm64 client's sign in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest).
@@ -90,7 +90,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
<details>
<summary><b>Stores</b></summary>
- Epic Games and GOG build on [Phobos](https://github.com/phobos665)'s adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl). GOG install script registry entries are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher) (GPL-3.0) reads them. GOG cloud storage requests send the Galaxy communication-service User-Agent that gogdl and [Lutris](https://github.com/lutris/lutris) (GPL-3.0) send.
- Epic Games and GOG build on [Phobos](https://github.com/phobos665)'s adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl). GOG install script registry entries are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher) (GPL-3.0) reads them.
- Epic's official Linux launcher preview runs through FEX. That setup is outside Epic's listed Linux support.
- The launcher's .deb gets the WebKitGTK and GTK 3 libraries it needs from unmodified [Debian](https://www.debian.org) 13 packages, following [@zooluis](https://github.com/zooluis)'s research in [#2268](https://github.com/Droid-Deck/DroidDeck/pull/2268).
- Battle.net is by [@kayakyakr](https://github.com/kayakyakr). It runs Blizzard's own client in Proton (downloaded from Blizzard, not included) and shows key art from the [Battle.net Shop](https://shop.battle.net). Without Steam, its games see the pad as an Xbox 360 controller via `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`.
@@ -98,7 +98,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
- Battle.net installs drive Blizzard's Agent the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) does, with requests from [wowdev.wiki](https://wowdev.wiki/Agent). Read without taking code: [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader.
- World of Warcraft addon imports replace an addon's folder from a temporary copy, as [WowUp](https://github.com/WowUp/WowUp) does, and read flavour folders the way [WoWDeck](https://github.com/sigboe/wowdeck) does. No code from either is used.
- The World of Warcraft addon Download window searches [WoWInterface](https://www.wowinterface.com) through its MMOUI API. [CurseForge](https://www.curseforge.com/wow) opens in the user's browser, with no API and no key.
- Xbox games load [@domsvoboda](https://github.com/domsvoboda)'s [xodus-nexus](https://github.com/domsvoboda/xodus-nexus) modules (LGPL-2.1-or-later), including `wintypes.dll`. Content licensing sends delegation-compact device tickets in the licensing wire form, following the [nexus-backend](https://github.com/domsvoboda/nexus-backend) commit `27c335e`. Minecraft's GameInput setup was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT).
- Xbox games load [@domsvoboda](https://github.com/domsvoboda)'s [xodus-nexus](https://github.com/domsvoboda/xodus-nexus) modules (LGPL-2.1-or-later), including `wintypes.dll`. Minecraft's GameInput setup was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT).
- The Xbox Cloud Gaming player uses the WebRTC client of [@unknownskl](https://github.com/unknownskl)'s [Greenlight](https://github.com/unknownskl/greenlight) (MIT), and its offer tweaks and sharpening follow [@redphx](https://github.com/redphx)'s [Better xCloud](https://github.com/redphx/better-xcloud) (MIT). See `tools/xcloud-player/NOTICE.md`.
- The itch.io butler pack ships butler's `7z.so`, itch.io's build of [7-Zip](https://www.7-zip.org) by Igor Pavlov (LGPL-2.1, unRAR restriction on RAR code), unmodified. Other archives use Apache Commons Compress and the runtime's bsdtar (libarchive).
- The Store uses [Flatpak](https://github.com/flatpak/flatpak) (LGPL-2.1) through DroidDeck's own bubblewrap shim. Chromium and Electron apps start directly, since [zypak](https://github.com/refi64/zypak) by [@refi64](https://github.com/refi64) (BSD-3-Clause) always uses Flatpak's spawn portal.
-10
View File
@@ -295,16 +295,6 @@ if (uvcDir) {
}
tasks.named('preBuild').configure { dependsOn(stageRuntimeAssets) }
android.sourceSets.main.java.srcDir(rootProject.file('shortcuts/src/protocol/java'))
def stageShortcuts = tasks.register('stageShortcuts', Copy) {
dependsOn(':shortcuts:assembleRelease')
from(project(':shortcuts').layout.buildDirectory.file('outputs/apk/release/shortcuts-release.apk'))
into(layout.buildDirectory.dir('shortcutsAssets'))
rename { 'shortcuts.apk' }
}
android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('shortcutsAssets'))
tasks.named('preBuild').configure { dependsOn(stageShortcuts) }
def stageGogNotices = tasks.register('stageGogNotices', Copy) {
from(layout.projectDirectory.dir('src/main/rust/stores/vendor/xdelta3')) { include 'LICENSE', 'README.droiddeck.md' }
into(layout.buildDirectory.dir('gogNotices/licenses/xdelta3'))
+12 -2
View File
@@ -89,11 +89,21 @@
android:label="@string/steam_wall_label"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:exported="true" />
<service android:name=".input.ShortcutsRelay" android:exported="true">
<service android:name=".input.HomeButtonService"
android:label="@string/integration_shortcuts_service"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
android:exported="true">
<intent-filter>
<action android:name="com.droiddeck.shortcuts.RELAY" />
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data android:name="android.accessibilityservice" android:resource="@xml/home_button_service" />
</service>
<receiver android:name=".core.ShortcutsListingReceiver" android:exported="false"
android:process=":shortcuts_sync">
<intent-filter>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>
</receiver>
<meta-data android:name="com.oculus.supportedDevices" android:value="quest2|quest3|quest3s" />
<activity android:name=".QuestXrActivity" android:exported="true" android:launchMode="singleTask"
android:permission="android.permission.DUMP"
@@ -1,15 +0,0 @@
{
"version": 1,
"controls": [
{
"name": "Compact gamepad",
"author": "DroidDeck",
"game": "",
"license": "GPL-3.0",
"file": "packs/compact-gamepad.ddcontrols.zip",
"sha256": "8b747e86268a1f607e312f2c39dd67402658bd5cf9e4e4ff524a4640417c9f3e",
"screen": "BOTH",
"preview": "previews/compact-gamepad.png"
}
]
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

+35 -164
View File
@@ -37,7 +37,6 @@
#include <stdio.h>
#include <string.h>
#include <sys/eventfd.h>
#include <sys/file.h>
#include <sys/inotify.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
@@ -158,8 +157,6 @@ struct FakeController {
bool closed = false;
bool needs_keyframe = true;
bool mouse = false;
int playing_ff = -1;
pid_t owner = getpid();
~FakeController() {
if (ring) munmap(ring, mapping_size);
@@ -198,7 +195,6 @@ static constexpr size_t kSnapshotButtonCount =
namespace Logger {
void init();
void log(const char *message, ...);
}
static void controller_fork_prepare();
@@ -290,68 +286,6 @@ static bool fake_vibration_enabled() { return config().vibration_enabled; }
static bool fake_xbox360_identity() { return config().xbox360_identity; }
static bool fake_uinput_enabled() { return config().uinput_enabled; }
static bool process_is_steam_client();
// Steam and its Remote Play client write the same shared slots; the caller's mutex serialises its own threads.
// Without the lock Steam stays the only writer, as before streaming_client could open these devices. The wait
// is bounded because a session freeze can stop the holder, and callers wait with controller_mutex held.
class ProcessSlotLock {
public:
ProcessSlotLock(int &fd, const char *name, int timeout_ms) : fd_(fd) {
int saved_errno = errno;
if (fd_ < 0) {
std::string path = std::string(fake_hook_dir()) + "/." + name + ".lock";
fd_ = fd = static_cast<int>(syscall(SYS_openat, AT_FDCWD, path.c_str(), O_CREAT | O_RDWR | O_CLOEXEC, 0600));
}
int error = fd_ < 0 ? errno : 0;
if (fd_ >= 0) {
struct timespec start, now, pause = {0, 1000 * 1000};
clock_gettime(CLOCK_MONOTONIC, &start);
for (;;) {
if (flock(fd_, LOCK_EX | LOCK_NB) == 0) {
locked_ = true;
break;
}
if (errno == EINTR) continue;
if (errno != EWOULDBLOCK) {
error = errno;
break;
}
clock_gettime(CLOCK_MONOTONIC, &now);
if ((now.tv_sec - start.tv_sec) * 1000 + (now.tv_nsec - start.tv_nsec) / 1000000 >= timeout_ms) {
busy_ = true;
break;
}
nanosleep(&pause, nullptr);
}
}
if (busy_) {
static std::atomic<unsigned> waits;
unsigned n = ++waits;
if ((n & (n - 1)) == 0) Logger::log("lock: %s still held after %d ms, skipped (x%u)\n", name, timeout_ms, n);
} else if (!locked_) {
static std::atomic<bool> noted{false};
if (!noted.exchange(true))
Logger::log("lock: %s not taken (%s)%s\n", name, strerror(error),
process_is_steam_client() ? "" : "; this process leaves the shared slots alone");
}
errno = saved_errno;
}
~ProcessSlotLock() {
int saved_errno = errno;
if (locked_) flock(fd_, LOCK_UN);
errno = saved_errno;
}
bool may_write() const { return locked_ || (!busy_ && process_is_steam_client()); }
ProcessSlotLock(const ProcessSlotLock &) = delete;
ProcessSlotLock &operator=(const ProcessSlotLock &) = delete;
private:
int fd_;
bool locked_ = false;
bool busy_ = false;
};
static bool ring_paths_loaded = false;
static int next_ff_id = 0;
@@ -477,49 +411,22 @@ __attribute__((visibility("hidden"))) static void send_ff_effect(const struct ff
send_vibration(effect.u.periodic.magnitude, effect.u.periodic.magnitude, duration, slot);
}
static std::unordered_map<int, const FakeController *> &ff_players() {
static auto *players = new std::unordered_map<int, const FakeController *>();
return *players;
}
__attribute__((visibility("hidden"))) static void ff_played(FakeController &controller, int id) {
controller.playing_ff = id;
controller.owner = getpid();
ff_players()[controller.slot] = &controller;
}
__attribute__((visibility("hidden"))) static bool ff_release(FakeController &controller) {
auto player = ff_players().find(controller.slot);
bool current = player != ff_players().end() && player->second == &controller;
if (current) ff_players().erase(player);
controller.playing_ff = -1;
return current;
}
__attribute__((visibility("hidden"))) static void
check_ff_event(const struct input_event *ev, FakeController &controller) {
check_ff_event(const struct input_event *ev, uint16_t slot) {
if (ev->type != EV_FF)
return;
uint16_t slot = static_cast<uint16_t>(controller.slot);
int id = ev->code;
if (ev->value > 0) {
auto it = ff_effects().find(id);
if (it == ff_effects().end())
return;
send_ff_effect(it->second, slot);
ff_played(controller, id);
} else {
send_vibration(0, 0, 0, slot);
ff_release(controller);
}
}
__attribute__((visibility("hidden"))) static void stop_ff(FakeController &controller) {
bool playing = controller.playing_ff >= 0 && controller.owner == getpid();
if (ff_release(controller) && playing) send_vibration(0, 0, 0, static_cast<uint16_t>(controller.slot));
}
__attribute__((visibility("hidden"))) char *
from_real_to_fake_path(const char *pathname) {
const char *event = strrchr(pathname, '/') + 1;
@@ -1278,13 +1185,10 @@ struct DeckImu {
uint32_t controls;
uint32_t pad_type;
uint32_t latency;
uint32_t remote_imu_mode;
uint32_t remote_imu_pid;
};
static_assert(offsetof(DeckImu, pad_type) == FAKE_INPUT_RING_PAD_TYPE_OFFSET,
"DeckImu::pad_type matches FakeInputWriter and the ring reader");
static_assert(offsetof(DeckImu, latency) == 48, "DeckImu::latency matches FakeInputWriter");
static_assert(offsetof(DeckImu, remote_imu_mode) == 52, "DeckImu::remote_imu_mode matches FakeInputWriter");
static constexpr uint32_t LATENCY_CONTROLLER = 1, LATENCY_TOUCH = 2;
static constexpr int LOW_LATENCY_REPORT_INTERVAL_US = 1000;
static constexpr uint32_t DECK_EXTRA_L4 = 1, DECK_EXTRA_R4 = 2, DECK_EXTRA_L5 = 4,
@@ -1491,25 +1395,6 @@ __attribute__((visibility("hidden"))) static bool process_is_steam_client() {
return known == 1;
}
// Steam's Remote Play client reads the controller itself, in its own streaming_client process.
__attribute__((visibility("hidden"))) static bool process_reads_pads() {
static int known;
if (known == 0) {
bool reader = process_is_steam_client();
if (!reader) {
char exe[PATH_MAX];
ssize_t length = readlink("/proc/self/exe", exe, sizeof(exe) - 1);
if (length > 0) {
exe[length] = '\0';
const char *name = strrchr(exe, '/');
reader = !strcmp(name ? name + 1 : exe, "streaming_client");
}
}
known = reader ? 1 : -1;
}
return known == 1;
}
__attribute__((constructor)) static void log_client_start() {
config();
if (process_is_steam_client())
@@ -1554,7 +1439,7 @@ __attribute__((visibility("hidden"))) static bool is_withdrawn_pad_path(const ch
free(fake);
return !exposed;
}
return number == 0 || !process_reads_pads();
return number == 0 || !process_is_steam_client();
}
static bool fake_pad_withdrawn(const FakeController &fake) {
@@ -1769,7 +1654,7 @@ __attribute__((visibility("hidden"))) static void *sony_report_thread(void *arg)
__attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags, uint8_t sony = 0) {
const char *path = sony == 4 ? DS4_HIDRAW_PATH : sony == 5 ? DUALSENSE_HIDRAW_PATH : DECK_HIDRAW_PATH;
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
if (!process_reads_pads()) {
if (!process_is_steam_client()) {
Logger::log("deck: %s refused: not the Steam client\n", path);
errno = ENOENT;
return -1;
@@ -1978,7 +1863,7 @@ __attribute__((visibility("hidden"))) static void *triton_pad_thread(void *arg)
__attribute__((visibility("hidden"))) static int open_triton_hidraw(int flags, bool emulated) {
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
if (!process_reads_pads()) {
if (!process_is_steam_client()) {
errno = ENOENT;
return -1;
}
@@ -2119,19 +2004,15 @@ __attribute__((visibility("hidden"))) static bool touch_plugged() {
}
__attribute__((visibility("hidden"))) static bool is_touch_hidraw_path(const char *pathname) {
return pathname && !strcmp(pathname, TOUCH_HIDRAW_PATH) && process_reads_pads() && touch_ring();
return pathname && !strcmp(pathname, TOUCH_HIDRAW_PATH) && process_is_steam_client() && touch_ring();
}
static std::mutex touch_state_mutex;
static int touch_state_lock_fd = -1;
template <typename F>
__attribute__((visibility("hidden"))) static void touch_state(F &&write) {
TouchRingFile *ring = touch_ring();
if (!ring) return;
std::lock_guard<std::mutex> guard(touch_state_mutex);
ProcessSlotLock slot(touch_state_lock_fd, "touch-state", 20);
if (!slot.may_write()) return;
static std::mutex mutex;
std::lock_guard<std::mutex> guard(mutex);
__atomic_fetch_add(&ring->state_seq, 1, __ATOMIC_ACQ_REL);
write(*ring);
__atomic_fetch_add(&ring->state_seq, 1, __ATOMIC_ACQ_REL);
@@ -2383,10 +2264,9 @@ __attribute__((visibility("hidden"))) static void *pad_type_thread(void *) {
struct timespec settle = {0, 300 * 1000 * 1000};
nanosleep(&settle, nullptr);
int added = pad_type_uevent(now, "add");
bool shared = process_is_steam_client();
if (shared && was != PAD_TYPE_XBOX) poke_hidraw_watchers(pad_type_minor(was));
if (shared && now != PAD_TYPE_XBOX) poke_hidraw_watchers(pad_type_minor(now));
if (shared && (was == PAD_TYPE_XBOX || now == PAD_TYPE_XBOX)) {
if (was != PAD_TYPE_XBOX) poke_hidraw_watchers(pad_type_minor(was));
if (now != PAD_TYPE_XBOX) poke_hidraw_watchers(pad_type_minor(now));
if (was == PAD_TYPE_XBOX || now == PAD_TYPE_XBOX) {
std::string node = std::string(fake_hook_dir()) + "/event0";
std::string aside = std::string(fake_hook_dir()) + "/.event0-switching";
if (rename(node.c_str(), aside.c_str()) == 0) {
@@ -2405,7 +2285,7 @@ __attribute__((visibility("hidden"))) static void *pad_type_thread(void *) {
__attribute__((constructor)) static void start_pad_type_watch() {
config();
if (!process_reads_pads() || !fake_deck_enabled()) return;
if (!process_is_steam_client() || !fake_deck_enabled()) return;
pthread_t thread;
if (pthread_create(&thread, nullptr, pad_type_thread, nullptr) == 0) pthread_detach(thread);
}
@@ -2426,7 +2306,7 @@ __attribute__((visibility("hidden"))) static void *touch_plug_thread(void *) {
__attribute__((constructor)) static void start_touch_controller() {
config();
if (!process_reads_pads() || !touch_ring()) return;
if (!process_is_steam_client() || !touch_ring()) return;
pthread_t thread;
if (pthread_create(&thread, nullptr, touch_plug_thread, nullptr) == 0) pthread_detach(thread);
}
@@ -2533,13 +2413,8 @@ __attribute__((visibility("hidden"))) static void publish_imu_mode(const DeckHid
std::string path = get_ring_path_for_slot(0);
int fd = path.empty() ? -1 : my_open(path.c_str(), O_WRONLY | O_CLOEXEC);
if (fd < 0) return;
// Steam and its Remote Play client each keep their own word, so one turning motion off does not starve the
// other; Android reads motion while either wants it. The pid lets it ignore a Remote Play client that has gone.
uint32_t value[2] = {0x80000000u | static_cast<uint32_t>(mode), static_cast<uint32_t>(getpid())};
bool steam = process_is_steam_client();
size_t length = steam ? sizeof(value[0]) : sizeof(value);
off_t offset = FAKE_INPUT_RING_SIZE + (steam ? offsetof(DeckImu, imu_mode) : offsetof(DeckImu, remote_imu_mode));
if (pwrite(fd, value, length, offset) != static_cast<ssize_t>(length))
uint32_t value = 0x80000000u | static_cast<uint32_t>(mode);
if (pwrite(fd, &value, sizeof(value), FAKE_INPUT_RING_SIZE + offsetof(DeckImu, imu_mode)) != sizeof(value))
Logger::log("deck: imu mode not published (%s)\n", strerror(errno));
syscall(SYS_close, fd);
}
@@ -2744,10 +2619,7 @@ __attribute__((visibility("hidden"))) static void triton_queue_output(DeckHidraw
auto *shared = reinterpret_cast<TritonSharedData *>(reinterpret_cast<uint8_t *>(triton.ring) + TRITON_SHARED_OFFSET);
if (__atomic_load_n(&shared->magic, __ATOMIC_ACQUIRE) != TRITON_SHARED_MAGIC) return;
static std::mutex one_at_a_time;
static int lock_fd = -1;
std::lock_guard<std::mutex> guard(one_at_a_time);
ProcessSlotLock slot(lock_fd, "triton-output", TRITON_OUTPUT_TIMEOUT_MS * 2);
if (!slot.may_write()) return;
for (int waited = 0;
static_cast<uint32_t>(__atomic_load_n(&shared->output_seq, __ATOMIC_ACQUIRE)) !=
__atomic_load_n(&shared->output_ack, __ATOMIC_ACQUIRE) &&
@@ -2779,13 +2651,7 @@ __attribute__((visibility("hidden"))) static int triton_get_feature(DeckHidraw &
}
auto *shared = reinterpret_cast<TritonSharedData *>(reinterpret_cast<uint8_t *>(triton.ring) + TRITON_SHARED_OFFSET);
static std::mutex one_at_a_time;
static int lock_fd = -1;
std::lock_guard<std::mutex> guard(one_at_a_time);
ProcessSlotLock slot(lock_fd, "triton-feature", TRITON_FEATURE_TIMEOUT_MS);
if (!slot.may_write()) {
errno = EIO;
return -1;
}
uint8_t report_id = report[0];
__atomic_store_n(&shared->get_report_id, report_id, __ATOMIC_RELAXED);
uint64_t request = __atomic_add_fetch(&shared->get_request, 1, __ATOMIC_RELEASE);
@@ -2973,7 +2839,7 @@ __attribute__((visibility("hidden"))) static int ioctl_triton(DeckHidraw &triton
__attribute__((visibility("hidden"))) static std::string note_sys_failure(int dirfd, const char *pathname) {
int saved_errno = errno;
std::string path;
if (saved_errno == ENOENT || !pathname || !process_reads_pads()) {
if (saved_errno == ENOENT || !pathname || !process_is_steam_client()) {
errno = saved_errno;
return path;
}
@@ -3012,7 +2878,7 @@ __attribute__((visibility("hidden"))) static std::string note_sys_failure(int di
__attribute__((visibility("hidden"))) static std::string deck_listing_for(const char *path) {
const char *listing = deck_listing_dir();
if (!path || !listing || errno != EACCES || !fake_deck_enabled() || !process_reads_pads()) return {};
if (!path || !listing || errno != EACCES || !fake_deck_enabled() || !process_is_steam_client()) return {};
std::string p(path);
while (p.size() > 1 && p.back() == '/') p.pop_back();
int which = p == "/sys" ? 0 : p == "/sys/class" ? 1 : p == "/sys/bus" ? 2 : -1;
@@ -3081,7 +2947,7 @@ EXPORT int statx(int dirfd, const char *path, int flags, unsigned mask, struct s
constexpr unsigned unique_mount_id = 0x4000;
if (result == 0 && (mask & STATX_MNT_ID) &&
!(buf->stx_mask & (STATX_MNT_ID | unique_mount_id)) && fake_deck_enabled() &&
process_reads_pads() && deck_device_library(__builtin_return_address(0))) {
process_is_steam_client() && deck_device_library(__builtin_return_address(0))) {
bool recovered = deck_mount_id_from_fdinfo(dirfd, path, flags, buf);
static std::atomic<bool> noted_success{false}, noted_failure{false};
if (!(recovered ? noted_success : noted_failure).exchange(true))
@@ -3270,7 +3136,7 @@ template <typename S, typename Real>
static int fake_stat_path(const char *pathname, S *statbuf, Real real) {
if (is_withdrawn_pad_path(pathname) ||
((is_deck_hidraw_path(pathname) || is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) ||
sony_pad_path(pathname)) && !process_reads_pads())) {
sony_pad_path(pathname)) && !process_is_steam_client())) {
errno = ENOENT;
return -1;
}
@@ -3395,9 +3261,9 @@ EXPORT int fstat(int fd, struct stat *buf) {
EXPORT int access(const char *pathname, int mode) {
static auto my_access = reinterpret_cast<decltype(&::access)>(dlsym(RTLD_NEXT, "access"));
if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0;
if (is_deck_hidraw_path(pathname) && process_reads_pads()) return 0;
if (is_deck_hidraw_path(pathname) && process_is_steam_client()) return 0;
if ((is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || sony_pad_path(pathname)) &&
process_reads_pads())
process_is_steam_client())
return 0;
if (is_touch_hidraw_path(pathname)) return 0;
if (is_withdrawn_pad_path(pathname) || is_deck_hidraw_path(pathname) || is_triton_hidraw_path(pathname) ||
@@ -3436,9 +3302,9 @@ EXPORT int access(const char *pathname, int mode) {
EXPORT int faccessat(int dirfd, const char *pathname, int mode, int flags) {
static auto my_faccessat = reinterpret_cast<decltype(&::faccessat)>(dlsym(RTLD_NEXT, "faccessat"));
if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0;
if (is_deck_hidraw_path(pathname) && process_reads_pads()) return 0;
if (is_deck_hidraw_path(pathname) && process_is_steam_client()) return 0;
if ((is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || sony_pad_path(pathname)) &&
process_reads_pads())
process_is_steam_client())
return 0;
if (is_touch_hidraw_path(pathname)) return 0;
if (is_withdrawn_pad_path(pathname) || is_deck_hidraw_path(pathname) || is_triton_hidraw_path(pathname) ||
@@ -3505,7 +3371,7 @@ EXPORT int inotify_add_watch(int fd, const char *pathname, uint32_t mask) {
pathname = fake_path;
} else if (!strcmp(pathname, "/dev/input")) {
pathname = fake_hook_dir();
} else if (!strcmp(pathname, "/dev") && fake_deck_enabled() && process_reads_pads()) {
} else if (!strcmp(pathname, "/dev") && fake_deck_enabled() && process_is_steam_client()) {
std::string events = hidraw_event_dir();
mkdir(events.c_str(), 0700);
my_inotify_add_watch(fd, events.c_str(), mask);
@@ -3791,12 +3657,10 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
effect->id = next_ff_id++;
ff_effects()[effect->id] = *effect;
send_ff_effect(*effect, static_cast<uint16_t>(event_number));
ff_played(*controller->second, effect->id);
return 0;
} else if (type == 0x45 && number == 0x81) {
int id = (intptr_t)argp;
ff_effects().erase(id);
if (controller->second->playing_ff == id) stop_ff(*controller->second);
return 0;
} else if (type == 0x45 && number == 0x84) {
int max_effects = 16;
@@ -3876,7 +3740,6 @@ EXPORT int close(int fd) {
if (controller != controller_map().end()) {
Logger::log("Removing controller, fd %d event %s\n", controller->first,
controller->second->event ? controller->second->event : "(unknown)");
stop_ff(*controller->second);
controller->second->closed = true;
controller_map().erase(fd);
}
@@ -4074,8 +3937,12 @@ EXPORT ssize_t write(int fd, const void *buf, size_t count) {
return -1;
}
if (count == sizeof(struct input_event))
check_ff_event(static_cast<const struct input_event *>(buf), *controller->second);
const struct input_event *ev = nullptr;
uint16_t slot = static_cast<uint16_t>(controller->second->slot);
if (count == sizeof(struct input_event)) {
ev = static_cast<const struct input_event *>(buf);
check_ff_event(ev, slot);
}
return static_cast<ssize_t>(count);
}
@@ -4115,10 +3982,14 @@ EXPORT ssize_t writev(int fd, const struct iovec *iov, int iovcnt) {
return -1;
}
uint16_t slot = static_cast<uint16_t>(controller->second->slot);
ssize_t total = 0;
for (int i = 0; i < iovcnt; i++) {
if (iov[i].iov_len == sizeof(struct input_event))
check_ff_event(static_cast<const struct input_event *>(iov[i].iov_base), *controller->second);
if (iov[i].iov_len == sizeof(struct input_event)) {
const struct input_event *ev =
static_cast<const struct input_event *>(iov[i].iov_base);
check_ff_event(ev, slot);
}
total += static_cast<ssize_t>(iov[i].iov_len);
}
return total;
-106
View File
@@ -1,106 +0,0 @@
#pragma once
#include <vulkan/vulkan.h>
#include <vulkan/vulkan_android.h>
struct VkTable {
PFN_vkCreateInstance CreateInstance;
PFN_vkDestroyInstance DestroyInstance;
PFN_vkEnumeratePhysicalDevices EnumeratePhysicalDevices;
PFN_vkGetPhysicalDeviceProperties GetPhysicalDeviceProperties;
PFN_vkGetPhysicalDeviceMemoryProperties GetPhysicalDeviceMemoryProperties;
PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR GetPhysicalDeviceSurfaceCapabilitiesKHR;
PFN_vkGetPhysicalDeviceSurfaceFormatsKHR GetPhysicalDeviceSurfaceFormatsKHR;
PFN_vkGetPhysicalDeviceSurfacePresentModesKHR GetPhysicalDeviceSurfacePresentModesKHR;
PFN_vkGetPhysicalDeviceQueueFamilyProperties GetPhysicalDeviceQueueFamilyProperties;
PFN_vkGetPhysicalDeviceSurfaceSupportKHR GetPhysicalDeviceSurfaceSupportKHR;
PFN_vkGetPhysicalDeviceFormatProperties GetPhysicalDeviceFormatProperties;
PFN_vkGetPhysicalDeviceFeatures2 GetPhysicalDeviceFeatures2;
PFN_vkCreateDevice CreateDevice;
PFN_vkDestroySurfaceKHR DestroySurfaceKHR;
PFN_vkCreateAndroidSurfaceKHR CreateAndroidSurfaceKHR;
PFN_vkGetDeviceProcAddr GetDeviceProcAddr;
PFN_vkDestroyDevice DestroyDevice;
PFN_vkGetDeviceQueue GetDeviceQueue;
PFN_vkDeviceWaitIdle DeviceWaitIdle;
PFN_vkCreateSwapchainKHR CreateSwapchainKHR;
PFN_vkDestroySwapchainKHR DestroySwapchainKHR;
PFN_vkGetSwapchainImagesKHR GetSwapchainImagesKHR;
PFN_vkAcquireNextImageKHR AcquireNextImageKHR;
PFN_vkQueuePresentKHR QueuePresentKHR;
PFN_vkQueueSubmit QueueSubmit;
PFN_vkCreateQueryPool CreateQueryPool;
PFN_vkDestroyQueryPool DestroyQueryPool;
PFN_vkCmdResetQueryPool CmdResetQueryPool;
PFN_vkCmdWriteTimestamp CmdWriteTimestamp;
PFN_vkGetQueryPoolResults GetQueryPoolResults;
PFN_vkCreateRenderPass CreateRenderPass;
PFN_vkDestroyRenderPass DestroyRenderPass;
PFN_vkCreateFramebuffer CreateFramebuffer;
PFN_vkDestroyFramebuffer DestroyFramebuffer;
PFN_vkCreateImageView CreateImageView;
PFN_vkDestroyImageView DestroyImageView;
PFN_vkCreateImage CreateImage;
PFN_vkDestroyImage DestroyImage;
PFN_vkCreateBuffer CreateBuffer;
PFN_vkDestroyBuffer DestroyBuffer;
PFN_vkAllocateMemory AllocateMemory;
PFN_vkFreeMemory FreeMemory;
PFN_vkMapMemory MapMemory;
PFN_vkFlushMappedMemoryRanges FlushMappedMemoryRanges;
PFN_vkBindBufferMemory BindBufferMemory;
PFN_vkBindImageMemory BindImageMemory;
PFN_vkGetBufferMemoryRequirements GetBufferMemoryRequirements;
PFN_vkGetImageMemoryRequirements GetImageMemoryRequirements;
PFN_vkCreateDescriptorSetLayout CreateDescriptorSetLayout;
PFN_vkDestroyDescriptorSetLayout DestroyDescriptorSetLayout;
PFN_vkCreateDescriptorPool CreateDescriptorPool;
PFN_vkDestroyDescriptorPool DestroyDescriptorPool;
PFN_vkAllocateDescriptorSets AllocateDescriptorSets;
PFN_vkFreeDescriptorSets FreeDescriptorSets;
PFN_vkUpdateDescriptorSets UpdateDescriptorSets;
PFN_vkCreatePipelineLayout CreatePipelineLayout;
PFN_vkDestroyPipelineLayout DestroyPipelineLayout;
PFN_vkCreateShaderModule CreateShaderModule;
PFN_vkDestroyShaderModule DestroyShaderModule;
PFN_vkCreateGraphicsPipelines CreateGraphicsPipelines;
PFN_vkDestroyPipeline DestroyPipeline;
PFN_vkCreateCommandPool CreateCommandPool;
PFN_vkDestroyCommandPool DestroyCommandPool;
PFN_vkAllocateCommandBuffers AllocateCommandBuffers;
PFN_vkFreeCommandBuffers FreeCommandBuffers;
PFN_vkBeginCommandBuffer BeginCommandBuffer;
PFN_vkEndCommandBuffer EndCommandBuffer;
PFN_vkResetCommandBuffer ResetCommandBuffer;
PFN_vkCmdBeginRenderPass CmdBeginRenderPass;
PFN_vkCmdEndRenderPass CmdEndRenderPass;
PFN_vkCmdBindPipeline CmdBindPipeline;
PFN_vkCmdBindDescriptorSets CmdBindDescriptorSets;
PFN_vkCmdDraw CmdDraw;
PFN_vkCmdPushConstants CmdPushConstants;
PFN_vkCmdSetViewport CmdSetViewport;
PFN_vkCmdSetScissor CmdSetScissor;
PFN_vkCmdPipelineBarrier CmdPipelineBarrier;
PFN_vkCmdCopyImage CmdCopyImage;
PFN_vkCmdBlitImage CmdBlitImage;
PFN_vkCmdDispatch CmdDispatch;
PFN_vkCreateComputePipelines CreateComputePipelines;
PFN_vkUnmapMemory UnmapMemory;
PFN_vkCmdClearColorImage CmdClearColorImage;
PFN_vkResetDescriptorPool ResetDescriptorPool;
PFN_vkCmdCopyBufferToImage CmdCopyBufferToImage;
PFN_vkCreateSampler CreateSampler;
PFN_vkDestroySampler DestroySampler;
PFN_vkCreateSemaphore CreateSemaphore;
PFN_vkDestroySemaphore DestroySemaphore;
PFN_vkCreateFence CreateFence;
PFN_vkDestroyFence DestroyFence;
PFN_vkWaitForFences WaitForFences;
PFN_vkResetFences ResetFences;
PFN_vkGetFenceStatus GetFenceStatus;
PFN_vkGetAndroidHardwareBufferPropertiesANDROID GetAndroidHardwareBufferPropertiesANDROID;
};
@@ -0,0 +1,680 @@
#pragma once
#include <vulkan/vulkan.h>
#include <list>
#include <vulkan/vulkan_android.h>
struct VkTable {
PFN_vkCreateInstance CreateInstance;
PFN_vkDestroyInstance DestroyInstance;
PFN_vkEnumeratePhysicalDevices EnumeratePhysicalDevices;
PFN_vkGetPhysicalDeviceProperties GetPhysicalDeviceProperties;
PFN_vkGetPhysicalDeviceMemoryProperties GetPhysicalDeviceMemoryProperties;
PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR GetPhysicalDeviceSurfaceCapabilitiesKHR;
PFN_vkGetPhysicalDeviceSurfaceFormatsKHR GetPhysicalDeviceSurfaceFormatsKHR;
PFN_vkGetPhysicalDeviceSurfacePresentModesKHR GetPhysicalDeviceSurfacePresentModesKHR;
PFN_vkGetPhysicalDeviceQueueFamilyProperties GetPhysicalDeviceQueueFamilyProperties;
PFN_vkGetPhysicalDeviceSurfaceSupportKHR GetPhysicalDeviceSurfaceSupportKHR;
PFN_vkGetPhysicalDeviceFormatProperties GetPhysicalDeviceFormatProperties;
PFN_vkGetPhysicalDeviceFeatures2 GetPhysicalDeviceFeatures2;
PFN_vkCreateDevice CreateDevice;
PFN_vkDestroySurfaceKHR DestroySurfaceKHR;
PFN_vkCreateAndroidSurfaceKHR CreateAndroidSurfaceKHR;
PFN_vkGetDeviceProcAddr GetDeviceProcAddr;
PFN_vkDestroyDevice DestroyDevice;
PFN_vkGetDeviceQueue GetDeviceQueue;
PFN_vkDeviceWaitIdle DeviceWaitIdle;
PFN_vkCreateSwapchainKHR CreateSwapchainKHR;
PFN_vkDestroySwapchainKHR DestroySwapchainKHR;
PFN_vkGetSwapchainImagesKHR GetSwapchainImagesKHR;
PFN_vkAcquireNextImageKHR AcquireNextImageKHR;
PFN_vkQueuePresentKHR QueuePresentKHR;
PFN_vkQueueSubmit QueueSubmit;
PFN_vkCreateQueryPool CreateQueryPool;
PFN_vkDestroyQueryPool DestroyQueryPool;
PFN_vkCmdResetQueryPool CmdResetQueryPool;
PFN_vkCmdWriteTimestamp CmdWriteTimestamp;
PFN_vkGetQueryPoolResults GetQueryPoolResults;
PFN_vkCreateRenderPass CreateRenderPass;
PFN_vkDestroyRenderPass DestroyRenderPass;
PFN_vkCreateFramebuffer CreateFramebuffer;
PFN_vkDestroyFramebuffer DestroyFramebuffer;
PFN_vkCreateImageView CreateImageView;
PFN_vkDestroyImageView DestroyImageView;
PFN_vkCreateImage CreateImage;
PFN_vkDestroyImage DestroyImage;
PFN_vkCreateBuffer CreateBuffer;
PFN_vkDestroyBuffer DestroyBuffer;
PFN_vkAllocateMemory AllocateMemory;
PFN_vkFreeMemory FreeMemory;
PFN_vkMapMemory MapMemory;
PFN_vkFlushMappedMemoryRanges FlushMappedMemoryRanges;
PFN_vkBindBufferMemory BindBufferMemory;
PFN_vkBindImageMemory BindImageMemory;
PFN_vkGetBufferMemoryRequirements GetBufferMemoryRequirements;
PFN_vkGetImageMemoryRequirements GetImageMemoryRequirements;
PFN_vkCreateDescriptorSetLayout CreateDescriptorSetLayout;
PFN_vkDestroyDescriptorSetLayout DestroyDescriptorSetLayout;
PFN_vkCreateDescriptorPool CreateDescriptorPool;
PFN_vkDestroyDescriptorPool DestroyDescriptorPool;
PFN_vkAllocateDescriptorSets AllocateDescriptorSets;
PFN_vkFreeDescriptorSets FreeDescriptorSets;
PFN_vkUpdateDescriptorSets UpdateDescriptorSets;
PFN_vkCreatePipelineLayout CreatePipelineLayout;
PFN_vkDestroyPipelineLayout DestroyPipelineLayout;
PFN_vkCreateShaderModule CreateShaderModule;
PFN_vkDestroyShaderModule DestroyShaderModule;
PFN_vkCreateGraphicsPipelines CreateGraphicsPipelines;
PFN_vkDestroyPipeline DestroyPipeline;
PFN_vkCreateCommandPool CreateCommandPool;
PFN_vkDestroyCommandPool DestroyCommandPool;
PFN_vkAllocateCommandBuffers AllocateCommandBuffers;
PFN_vkFreeCommandBuffers FreeCommandBuffers;
PFN_vkBeginCommandBuffer BeginCommandBuffer;
PFN_vkEndCommandBuffer EndCommandBuffer;
PFN_vkResetCommandBuffer ResetCommandBuffer;
PFN_vkCmdBeginRenderPass CmdBeginRenderPass;
PFN_vkCmdEndRenderPass CmdEndRenderPass;
PFN_vkCmdBindPipeline CmdBindPipeline;
PFN_vkCmdBindDescriptorSets CmdBindDescriptorSets;
PFN_vkCmdDraw CmdDraw;
PFN_vkCmdPushConstants CmdPushConstants;
PFN_vkCmdSetViewport CmdSetViewport;
PFN_vkCmdSetScissor CmdSetScissor;
PFN_vkCmdPipelineBarrier CmdPipelineBarrier;
PFN_vkCmdCopyImage CmdCopyImage;
PFN_vkCmdBlitImage CmdBlitImage;
PFN_vkCmdDispatch CmdDispatch;
PFN_vkCreateComputePipelines CreateComputePipelines;
PFN_vkUnmapMemory UnmapMemory;
PFN_vkCmdClearColorImage CmdClearColorImage;
PFN_vkResetDescriptorPool ResetDescriptorPool;
PFN_vkCmdCopyBufferToImage CmdCopyBufferToImage;
PFN_vkCreateSampler CreateSampler;
PFN_vkDestroySampler DestroySampler;
PFN_vkCreateSemaphore CreateSemaphore;
PFN_vkDestroySemaphore DestroySemaphore;
PFN_vkCreateFence CreateFence;
PFN_vkDestroyFence DestroyFence;
PFN_vkWaitForFences WaitForFences;
PFN_vkResetFences ResetFences;
PFN_vkGetFenceStatus GetFenceStatus;
PFN_vkGetAndroidHardwareBufferPropertiesANDROID GetAndroidHardwareBufferPropertiesANDROID;
};
#include <android/log.h>
#include <string>
#define WLOG_TAG "DroidDeck_Renderer"
#define RLOG(...) if(verboseLog) __android_log_print(ANDROID_LOG_DEBUG,WLOG_TAG,__VA_ARGS__)
#define RLOG_E(...) __android_log_print(ANDROID_LOG_ERROR,WLOG_TAG,__VA_ARGS__)
#define SCANOUT_LOG(...) __android_log_print(ANDROID_LOG_DEBUG,"DroidDeck_Scanout",__VA_ARGS__)
#include <vulkan/vulkan_android.h>
#include <android/hardware_buffer.h>
#include <android/native_window.h>
#include <vector>
#include <unordered_map>
#include <thread>
#include <atomic>
#include <mutex>
#include <shared_mutex>
#include <condition_variable>
#include <chrono>
#include "../scanout/ScanoutContext.h"
#include "lsfg/lsfg_probe.h"
#include <memory>
#include <string>
namespace lsfg { class Engine; }
namespace ddfg { class Engine; }
static constexpr uint32_t MAX_FRAMES_IN_FLIGHT = 2;
struct SgsrPushConstants {
float ndc[4];
float viewportInfo[4];
float edgeSharpness;
};
struct NisPushConstants {
float ndc[4];
float viewportInfo[4];
float sharpness;
};
struct EasuPushConstants {
float ndc[4];
uint32_t con0[4], con1[4], con2[4], con3[4];
float outW, outH;
};
struct RcasPushConstants {
float ndc[4];
uint32_t con[4];
float outW, outH;
};
struct CasPushConstants {
float ndc[4];
float resolution[2];
float sharpness;
float _pad;
};
struct HdrPushConstants {
float ndc[4];
float resolution[2];
};
struct FxaaPushConstants {
float ndc[4];
float resolution[2];
};
struct ToonPushConstants {
float ndc[4];
float resolution[2];
};
struct ColorPushConstants {
float ndc[4];
float brightness;
float contrast;
float gamma;
float saturation;
};
struct NtscPushConstants {
float ndc[4];
float resolution[2];
float frameCount;
};
struct CrtPushConstants {
float ndc[4];
float resolution[2];
};
struct DebandPushConstants {
float ndc[4];
float resolution[2];
float strength;
};
class VulkanRendererContext {
public:
VulkanRendererContext(ANativeWindow* window, int cWidth, int cHeight, void* adrenotoolsHandle = nullptr,
bool lsfgVk11Compat = false);
~VulkanRendererContext();
void onSurfaceResized(int width, int height);
void setTransform(float ox, float oy, float sx, float sy);
void setClipRegion(int x, int y, int w, int h);
void updatePointerPosition(short x, short y);
void updateWindowContent(int64_t id, void* pixels, short w, short h, short stride, int x, int y);
void updateWindowContentAHB(int64_t id, AHardwareBuffer* ahb, short w, short h, int x, int y);
void updateCursorImage(void* pixels, short w, short h, short hotX, short hotY);
void setCursorVisible(bool visible);
void setRenderList(const int64_t* ids, const int* xs, const int* ys, int count);
void removeWindow(int64_t id);
void clearBackbuffer() {}
void beginBatch() {}
void endBatch() {}
void initScanout();
void destroyScanout();
void applyScanoutBuffer();
void initScanoutFromWindows(ANativeWindow* gameWin, ANativeWindow* cursorWin);
void scanoutSetDst(int x, int y, int w, int h);
void scanoutSetBuffer(AHardwareBuffer* ahb, int x, int y, int w, int h, int fenceFd = -1);
void scanoutSetCursorImage(void* pixels, short w, short h, short stride);
void scanoutSetCursorPos(short x, short y, short hotX, short hotY);
ScanoutContext scanout;
std::atomic<bool>& scanoutActive = scanout.scanoutActive;
std::atomic<bool>& gameFrameDelivered = scanout.gameFrameDelivered;
std::atomic<bool> surfaceDetached{false};
void detachSurface();
bool reattachSurface(ANativeWindow* newWindow);
bool verboseLog = true;
void setVerboseLog(bool v) { verboseLog = v; scanout.setVerboseLog(v); }
void dumpRendererInfo();
std::string adrenoDriverPath;
std::string adrenoDriverName;
std::string adrenoNativeLibDir;
void* vulkanHandle = nullptr;
std::atomic<bool> scanoutBlackFrameDone{false};
PFN_vkGetInstanceProcAddr gipa = nullptr;
VkTable vk_ = {};
void loadCustomDriver();
void loadInstanceDispatch();
void loadDeviceDispatch();
void setFilterMode(int mode);
void setUpscaler(int mode);
void setHqDownscale(bool enabled);
void setCas(bool enabled, int sharpness);
void setHdr(bool enabled);
void setDeband(bool enabled, int strength);
void setUpscaleSharpness(int sharpness);
void setFxaa(bool enabled);
void setToon(bool enabled);
void setCrt(bool enabled);
void setNtsc(bool enabled);
void setColorGrade(float brightness, float contrast, float gamma, float saturation);
void setSwapRB(bool enabled);
void setPresentMode(VkPresentModeKHR mode);
std::vector<int> getSupportedPresentModes() const;
const lsfg::Caps& lsfgCaps() const { return lsfgCaps_; }
void setFrameGenArmed(bool armed, int multiplier);
bool frameGenArmed() const { return fgArmed_.load(std::memory_order_relaxed); }
void frameGenStats(float out[6]) const;
int frameGenProblem() const;
void setLsfgCachePath(const char* path);
static constexpr int32_t kFgCaptureGame = -1;
void setFrameGenTuning(float flowScale, float refreshHz, int32_t captureHeight = 0);
void setFrameGenEngine(int kind);
void setDdFgTuning(int model, int perfPreset);
private:
struct WinTex {
VkImage img = VK_NULL_HANDLE;
VkDeviceMemory mem = VK_NULL_HANDLE;
VkImageView view = VK_NULL_HANDLE;
VkDescriptorSet ds = VK_NULL_HANDLE;
VkBuffer stg = VK_NULL_HANDLE;
VkDeviceMemory stgMem = VK_NULL_HANDLE;
void* mapped = nullptr;
VkDeviceSize cap = 0;
int w = 0;
int h = 0;
bool dirty = false;
bool isAHB = false;
bool needsTransition = false;
AHardwareBuffer* ahb = nullptr;
};
struct RenderEntry { int64_t id; int x, y; };
struct DrawEntry {
VkImage img = VK_NULL_HANDLE;
VkDescriptorSet ds = VK_NULL_HANDLE;
VkBuffer upload = VK_NULL_HANDLE;
int x=0, y=0, w=0, h=0;
bool needsTransition = false;
bool isAHB = false;
};
ANativeWindow* window;
int surfaceWidth, surfaceHeight, containerWidth, containerHeight;
std::atomic<int> clipRegionX{0}, clipRegionY{0}, clipRegionW{0}, clipRegionH{0};
void* adrenotoolsHandle = nullptr;
bool lsfgVk11Compat_ = false;
int filterMode = 0;
bool swapRB = false;
float maxAnisotropy = 1.0f;
bool cubicSupported = false;
VkPhysicalDeviceMemoryProperties memProperties{};
VkPresentModeKHR requestedPresentMode = VK_PRESENT_MODE_FIFO_KHR;
uint32_t graphicsQueueFamilyIndex = 0;
std::vector<VkPresentModeKHR> availablePresentModes;
std::unordered_map<int64_t, WinTex> texMap;
std::unordered_map<AHardwareBuffer*, WinTex> ahbImportCache;
std::unordered_map<int64_t, std::vector<AHardwareBuffer*>> windowAhbs;
std::vector<WinTex> deleteQueue;
std::vector<RenderEntry> renderList;
std::vector<DrawEntry> frameDraws;
std::vector<VkImageMemoryBarrier> frameAhbTransitions;
std::vector<VkImageMemoryBarrier> framePreUpload;
std::vector<VkImageMemoryBarrier> framePostUpload;
std::atomic<int> pointerX{0}, pointerY{0};
float sceneOffsetX=0.f, sceneOffsetY=0.f, sceneScaleX=1.f, sceneScaleY=1.f;
std::atomic<bool> cursorVisible{false};
short cursorHotX=0, cursorHotY=0, cursorTexW=0, cursorTexH=0;
std::vector<uint32_t> cursorPixels;
std::atomic<bool> isCursorImageDirty{false};
std::atomic<bool> cursorMoved{false};
VkImage cursorImg = VK_NULL_HANDLE;
VkDeviceMemory cursorMem = VK_NULL_HANDLE;
VkImageView cursorView = VK_NULL_HANDLE;
VkDescriptorSet cursorDS = VK_NULL_HANDLE;
VkBuffer cursorStg = VK_NULL_HANDLE;
VkDeviceMemory cursorStgM = VK_NULL_HANDLE;
void* cursorStgP = nullptr;
VkDeviceSize cursorStgC = 0;
VkDeviceSize cursorUploadSize = 0;
VkInstance instance;
VkSurfaceKHR surface;
VkPhysicalDevice physicalDevice;
VkDevice device;
VkQueue graphicsQueue;
VkSwapchainKHR swapchain = VK_NULL_HANDLE;
VkFormat swapchainFmt;
VkExtent2D swapchainExt;
std::vector<VkImage> swapchainImages;
std::vector<VkImageView> swapchainViews;
std::vector<VkFramebuffer> swapchainFBs;
VkRenderPass renderPass = VK_NULL_HANDLE;
VkDescriptorSetLayout dsLayout = VK_NULL_HANDLE;
VkPipelineLayout pipeLayout = VK_NULL_HANDLE;
VkPipeline pipeline = VK_NULL_HANDLE;
int upscalerMode = 0;
bool hqDownscale = false;
bool casEnabled = false;
int casSharpness = 60;
bool hdrEnabled = false;
float upscaleSharpness01 = 0.75f;
bool debandEnabled = false;
int debandStrength = 100;
bool fxaaEnabled = false;
bool toonEnabled = false;
bool crtEnabled = false;
bool ntscEnabled = false;
bool colorEnabled = false;
float colorBrightness = 0.0f;
float colorContrast = 0.0f;
float colorGamma = 1.0f;
float colorSaturation = 1.0f;
uint32_t ntscFrameCounter = 0;
VkSampler upscaleSampler = VK_NULL_HANDLE;
struct CompositeTarget {
VkImage img = VK_NULL_HANDLE;
VkDeviceMemory mem = VK_NULL_HANDLE;
VkImageView view = VK_NULL_HANDLE;
VkImageView storageView = VK_NULL_HANDLE;
VkFramebuffer fb = VK_NULL_HANDLE;
VkDescriptorSet ds = VK_NULL_HANDLE;
};
static constexpr uint32_t kMaxCompositeTargets = 7;
std::vector<CompositeTarget> compositeTargets;
VkRenderPass compositeRenderPass = VK_NULL_HANDLE;
uint32_t compositeW = 0, compositeH = 0;
uint32_t compositeIndex = 0;
bool compositeArmed = false;
bool swapchainTransferDst = false;
std::atomic<bool> fgArmed_{false};
std::atomic<int> fgMultiplier_{0};
std::atomic<float> fgFlowScale_{1.0f};
std::atomic<float> fgRefreshHz_{0.0f};
std::atomic<bool> fgConfigDirty_{true};
std::atomic<int32_t> fgCaptureHeight_{0};
void compositeExtentFor(uint32_t& w, uint32_t& h) const;
VkExtent2D renderExtent() const {
if (compositeActive() && (compositeW != swapchainExt.width || compositeH != swapchainExt.height))
return VkExtent2D{compositeW, compositeH};
return swapchainExt;
}
void recordCompositeToSwapchainTransfer(VkCommandBuffer cb, VkImage src, uint32_t imgIdx);
bool createCompositeRenderPass();
bool ensureCompositeTargets(uint32_t w, uint32_t h, uint32_t count);
void destroyCompositeTargets();
bool compositeActive() const;
VkRenderPass targetRenderPass() const;
VkFramebuffer targetFramebuffer(uint32_t imgIdx) const;
void copyCompositeToSwapchain(VkCommandBuffer cb, uint32_t imgIdx);
VkRenderPass cursorOverlayRenderPass = VK_NULL_HANDLE;
struct CursorOverlay {
bool draw = false;
float ox = 0, oy = 0, sx = 0, sy = 0, cw = 0, ch = 0;
short ptrX = 0, ptrY = 0, hotX = 0, hotY = 0, w = 0, h = 0;
};
CursorOverlay cursorOverlay_{};
bool createCursorOverlayRenderPass();
void recordCursorOverlay(VkCommandBuffer cb, uint32_t imgIdx);
bool cursorDrawnPerPresent() const;
static constexpr uint32_t kMaxPresentsPerFrame = 4;
struct FrameGenPlan {
uint32_t generations = 0;
uint32_t presents = 1;
uint32_t imgIdx[kMaxPresentsPerFrame] = {};
};
FrameGenPlan fgPlan_{};
std::unique_ptr<lsfg::Engine> lsfgEngine_;
uint64_t fgSourceFrames_ = 0;
std::string lsfgCachePath_;
bool lsfgEngineTried_ = false;
std::unique_ptr<ddfg::Engine> ddfgEngine_;
bool ddfgEngineTried_ = false;
std::atomic<int> fgEngineKind_{0};
std::atomic<int> fgModel_{4};
std::atomic<int> fgPerfPreset_{1};
bool ensureDdFgEngine();
bool fgCapsOk() const;
uint32_t syncSlot(uint32_t k) const { return currentFrame * kMaxPresentsPerFrame + k; }
void recreateSyncObjects();
uint32_t fgAcquireFailLog_ = 0;
float fgPresentedRate_ = 0.0f;
float fgSourceRate_ = 0.0f;
uint32_t fgSourceAccum_ = 0;
uint32_t fgPresentAccum_ = 0;
std::chrono::steady_clock::time_point fgRateWindowStart_{};
bool fgRateWindowOpen_ = false;
void trackPresentedRate(uint32_t presents);
bool ensureLsfgEngine();
uint32_t cmdSlot(uint32_t k) const { return currentFrame * kMaxPresentsPerFrame + k; }
void recordFrameGenProcess(VkCommandBuffer cb);
void recordFrameGenGeneration(VkCommandBuffer cb, uint32_t g);
VkQueryPool fgQueryPool_ = VK_NULL_HANDLE;
bool fgTimestampsOk_ = false;
float fgTimestampPeriodNs_ = 0.0f;
bool fgQueryPending_[MAX_FRAMES_IN_FLIGHT] = {};
uint32_t fgQueryGens_[MAX_FRAMES_IN_FLIGHT] = {};
float fgChainMsPerGen_ = -1.0f;
uint32_t fgChainLogCount_ = 0;
void ensureFgQueryPool();
void destroyFgQueryPool();
void readFgQueryResult();
VkFormat offscreenFmt = VK_FORMAT_R8G8B8A8_UNORM;
VkRenderPass offscreenRenderPass = VK_NULL_HANDLE;
VkPipelineLayout postPipeLayout = VK_NULL_HANDLE;
VkPipeline sgsrPipeline = VK_NULL_HANDLE;
VkPipeline nisPipeline = VK_NULL_HANDLE;
VkPipeline sgsrQualityPipeline = VK_NULL_HANDLE;
VkPipeline easuPipeline = VK_NULL_HANDLE;
VkPipeline rcasPipeline = VK_NULL_HANDLE;
VkPipeline downscalePipeline = VK_NULL_HANDLE;
VkPipeline casPipelineOff = VK_NULL_HANDLE;
VkPipeline casPipelineSwap = VK_NULL_HANDLE;
VkPipeline hdrPipelineOff = VK_NULL_HANDLE;
VkPipeline hdrPipelineSwap = VK_NULL_HANDLE;
VkPipeline fxaaPipelineOff = VK_NULL_HANDLE;
VkPipeline fxaaPipelineSwap = VK_NULL_HANDLE;
VkPipeline toonPipelineOff = VK_NULL_HANDLE;
VkPipeline toonPipelineSwap = VK_NULL_HANDLE;
VkPipeline colorPipelineOff = VK_NULL_HANDLE;
VkPipeline colorPipelineSwap = VK_NULL_HANDLE;
VkPipeline ntscPipelineOff = VK_NULL_HANDLE;
VkPipeline ntscPipelineSwap = VK_NULL_HANDLE;
VkPipeline crtPipelineOff = VK_NULL_HANDLE;
VkPipeline crtPipelineSwap = VK_NULL_HANDLE;
VkPipeline debandPipelineSwap = VK_NULL_HANDLE;
VkImage offscreenImg = VK_NULL_HANDLE;
VkDeviceMemory offscreenMem = VK_NULL_HANDLE;
VkImageView offscreenView = VK_NULL_HANDLE;
VkFramebuffer offscreenFB = VK_NULL_HANDLE;
VkDescriptorSet offscreenDS = VK_NULL_HANDLE;
int offscreenW = 0, offscreenH = 0;
VkImage midImg = VK_NULL_HANDLE;
VkDeviceMemory midMem = VK_NULL_HANDLE;
VkImageView midView = VK_NULL_HANDLE;
VkFramebuffer midFB = VK_NULL_HANDLE;
VkDescriptorSet midDS = VK_NULL_HANDLE;
int midW = 0, midH = 0;
VkImage fx1Img = VK_NULL_HANDLE;
VkDeviceMemory fx1Mem = VK_NULL_HANDLE;
VkImageView fx1View = VK_NULL_HANDLE;
VkFramebuffer fx1FB = VK_NULL_HANDLE;
VkDescriptorSet fx1DS = VK_NULL_HANDLE;
int fx1W = 0, fx1H = 0;
VkImage fx2Img = VK_NULL_HANDLE;
VkDeviceMemory fx2Mem = VK_NULL_HANDLE;
VkImageView fx2View = VK_NULL_HANDLE;
VkFramebuffer fx2FB = VK_NULL_HANDLE;
VkDescriptorSet fx2DS = VK_NULL_HANDLE;
int fx2W = 0, fx2H = 0;
struct UpscaleFrame {
bool active = false;
int mode = 0;
int outX = 0, outY = 0, outW = 0, outH = 0;
bool cas = false;
bool hdr = false;
bool fxaa = false;
bool toon = false;
bool color = false;
bool ntsc = false;
bool crt = false;
bool deband = false;
SgsrPushConstants sgsrPC{};
NisPushConstants nisPC{};
EasuPushConstants easuPC{};
RcasPushConstants rcasPC{};
CasPushConstants casPC{};
HdrPushConstants hdrPC{};
FxaaPushConstants fxaaPC{};
ToonPushConstants toonPC{};
ColorPushConstants colorPC{};
NtscPushConstants ntscPC{};
CrtPushConstants crtPC{};
DebandPushConstants debandPC{};
} upFrame;
VkCommandPool cmdPool = VK_NULL_HANDLE;
std::vector<VkCommandBuffer> cmdBufs;
std::vector<VkSemaphore> imgAvailSems;
std::vector<VkSemaphore> renderDoneSems;
std::vector<VkFence> inFlightFences;
std::vector<VkFence> imgInFlight;
uint32_t currentFrame = 0;
VkSampler sampler = VK_NULL_HANDLE;
VkDescriptorPool winTexPool = VK_NULL_HANDLE;
std::atomic<bool> needsRender{false};
std::thread renderThread;
std::atomic<bool> isRunning{false};
std::atomic<bool> fbResized{false};
std::mutex renderMutex;
std::mutex dirtyMutex;
std::condition_variable dirtyCV;
std::shared_mutex frameMutex;
void createInstance();
void createSurface();
void pickPhysicalDevice();
lsfg::Caps lsfgCaps_{};
void createLogicalDevice();
void createSwapchain();
void createRenderPass();
void createDSLayout();
void createPipeline(bool blend, VkPipeline& out);
void createFramebuffers();
void createCmdPool();
void createSampler();
void createUpscaleSampler();
void createOffscreenRenderPass();
void createPostPipelines();
VkPipeline createPostPipeline(const uint32_t* fragCode, size_t fragSz, VkRenderPass rp);
bool createColorTarget(int w, int h, VkImage& img, VkDeviceMemory& mem,
VkImageView& view, VkFramebuffer& fb, VkDescriptorSet& ds);
void destroyColorTarget(VkImage& img, VkDeviceMemory& mem, VkImageView& view,
VkFramebuffer& fb, VkDescriptorSet& ds);
bool ensureOffscreen(int w, int h);
bool ensureMid(int w, int h);
bool ensureFx1(int w, int h);
bool ensureFx2(int w, int h);
void recordUpscalePasses(VkCommandBuffer cb, uint32_t imgIdx,
const std::vector<DrawEntry>& draws, bool cursorDrawn,
short ptrX, short ptrY, short curHotX, short curHotY,
short curW, short curH,
float ox, float oy, float sx, float sy,
float cw, float ch);
void planUpscaleFrame();
void createWinTexPool();
void createCursorPipeline();
void createCursorDS();
void createCmdBufs();
void createSyncObjects();
void cleanupSwapchain();
bool createWinTexResources(WinTex& wt, int w, int h);
bool importAHBToWinTex(WinTex& wt, AHardwareBuffer* ahb);
void cleanupAllAHBCache();
void flushDeleteQueue();
void destroyWinTex(WinTex& wt);
void ensureCursorTex(short w, short h);
void cleanupCursorTex();
void ensureCursorStaging(VkDeviceSize sz);
void recordCmdBuf(VkCommandBuffer cb, uint32_t imgIdx,
const std::vector<DrawEntry>& draws,
std::vector<VkImageMemoryBarrier>& ahbTransitions,
std::vector<VkImageMemoryBarrier>& preUpload,
std::vector<VkImageMemoryBarrier>& postUpload,
VkBuffer cursorUpload, bool hasCursorUpload,
float ox, float oy, float sx, float sy, float cw, float ch,
short ptrX, short ptrY, short curHotX, short curHotY,
short curW, short curH, bool curVis);
void renderLoop();
void renderFrame();
uint32_t findMemType(uint32_t filter, VkMemoryPropertyFlags props);
void createBuffer(VkDeviceSize sz, VkBufferUsageFlags usage,
VkMemoryPropertyFlags props, VkBuffer& buf, VkDeviceMemory& mem);
VkCommandBuffer beginOneTime();
void endOneTime(VkCommandBuffer cmd);
void transition(VkCommandBuffer cmd, VkImage img,
VkImageLayout oldL, VkImageLayout newL,
VkAccessFlags srcA, VkAccessFlags dstA,
VkPipelineStageFlags srcS, VkPipelineStageFlags dstS);
VkShaderModule makeShader(const uint32_t* code, size_t sz);
};
+1 -1
View File
@@ -1,5 +1,5 @@
#include "ddfg_vkd.h"
#include "../VkDispatchTable.h"
#include "../VulkanRendererContext.h"
#include <android/log.h>
bool ddfgVkdInit(const VkTable& table, ddfg::DeviceDispatch& dd, ddfg::InstanceDispatch& id) {
@@ -1,6 +1,6 @@
#include "lsfg_probe.h"
#include "../VkDispatchTable.h"
#include "../VulkanRendererContext.h"
#include <cstdio>
#include <cstring>
+1 -1
View File
@@ -1,6 +1,6 @@
#include "lsfg_vkd.h"
#include "../VkDispatchTable.h"
#include "../VulkanRendererContext.h"
#include <android/log.h>
+82
View File
@@ -0,0 +1,82 @@
#pragma once
#include <android/hardware_buffer.h>
#include <android/native_window.h>
#include <android/rect.h>
#include <android/log.h>
#include <atomic>
#include <mutex>
#include <cstdint>
#ifndef SCANOUT_LOG
#define SCANOUT_LOG(...) __android_log_print(ANDROID_LOG_DEBUG,"DroidDeck_Scanout",__VA_ARGS__)
#endif
class ScanoutContext {
public:
bool loadApi();
void initFromWindow(ANativeWindow* win = nullptr);
void initFromWindows(ANativeWindow* gameWin, ANativeWindow* cursorWin);
void destroy();
void setBuffer(AHardwareBuffer* ahb, int x, int y, int w, int h, int fenceFd = -1);
bool setCursorImage(void* pixels, short w, short h, short stride);
bool setCursorPos(short x, short y, short hotX, short hotY);
void applyPendingCursor();
void setDst(int x, int y, int w, int h);
void setContainerSize(int w, int h) { containerWidth = w; containerHeight = h; }
void setSurfaceSize(int w, int h) { surfaceWidth = w; surfaceHeight = h; }
void setFallbackWindow(ANativeWindow* win) { window = win; }
void setVerboseLog(bool v) { verboseLog = v; }
bool isActive() const { return scanoutActive.load(); }
bool isGameFrameDelivered() const {
return gameFrameDelivered.load(std::memory_order_acquire);
}
void* debugGameSC() const { return scanoutGameSC; }
std::atomic<bool> scanoutActive{false};
std::atomic<bool> gameFrameDelivered{false};
private:
ANativeWindow* window = nullptr;
bool verboseLog = true;
int surfaceWidth = 0, surfaceHeight = 0, containerWidth = 0, containerHeight = 0;
void* scanoutGameSC = nullptr;
void* scanoutCursorSC = nullptr;
void* scanoutCursorBuf = nullptr;
int32_t scanoutCursorBufW = 0;
int32_t scanoutCursorBufH = 0;
void* scanoutTx = nullptr;
void* scanoutGameTx = nullptr;
ARect scanoutLastSrc{}, scanoutLastDst{};
bool scanoutGeoDirty = true;
bool scanoutVisShown = false;
bool scanoutApiLoaded = false;
void* fnSCCreateFromWin = nullptr;
void* fnSCRelease = nullptr;
void* fnSTCreate = nullptr;
void* fnSTDelete = nullptr;
void* fnSTApply = nullptr;
void* fnSTSetBuffer = nullptr;
void* fnSTSetZOrder = nullptr;
void* fnSTSetVisibility = nullptr;
void* fnSTSetGeometry = nullptr;
int32_t scanoutDstX = 0, scanoutDstY = 0, scanoutDstW = 0, scanoutDstH = 0;
bool gameScVisible = false;
std::mutex scanoutMutex;
short pendingCursorX = 0, pendingCursorY = 0, pendingCursorHotX = 0, pendingCursorHotY = 0;
bool cursorPosDirty = false;
bool cursorImageDirty = false;
};
+4 -74
View File
@@ -127,9 +127,6 @@ static int log_budget(void) {
#ifndef BTN_RIGHT
#define BTN_RIGHT 0x111
#endif
#ifndef BTN_MIDDLE
#define BTN_MIDDLE 0x112
#endif
#define INPUT_SPACE_W 1920
#define INPUT_SPACE_H 1080
@@ -585,13 +582,6 @@ int droiddeck_cursor_snapshot(int *out, int cap) {
}
struct active_touch { struct surface *surface; int pointer_fallback; };
static struct active_touch g_touch_points[MAX_TOUCH_POINTS];
#define PEN_IN (1 << 0)
#define PEN_TIP (1 << 1)
#define PEN_RIGHT (1 << 2)
#define PEN_MIDDLE (1 << 3)
#define PEN_BIT(button) (1 << ((button) - BTN_LEFT))
struct pen_state { int in, buttons; struct surface *grab; };
static struct pen_state g_pen;
static void touch_cancel_surface(struct surface *surface);
static struct surface *g_grab;
static void publish_query_state(void);
@@ -1349,7 +1339,6 @@ static void surface_resource_destroy(struct wl_resource *r) {
if (g_grab == s) g_grab = NULL;
if (g_key_target == s) g_key_target = NULL;
if (g_ime_click == s) g_ime_click = NULL;
if (g_pen.grab == s) g_pen.grab = NULL;
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); }
@@ -3251,14 +3240,14 @@ static void deliver_pointer(const struct input_msg *m) {
pointer_event(x, y, m->p1 == 1 ? 0 : BTN_LEFT, m->p1 == 0);
}
static void input_output_to_scene(double px, double py, double *x, double *y) {
static void input_output_to_scene(int px, int py, double *x, double *y) {
int w, h, ow, oh;
scene_size(&w, &h);
vkp_output_size(&ow, &oh);
if (ow <= 0 || oh <= 0 ||
!vkp_output_to_scene(px * ow / INPUT_SPACE_W, py * oh / INPUT_SPACE_H, x, y)) {
*x = px * w / INPUT_SPACE_W;
*y = py * h / INPUT_SPACE_H;
!vkp_output_to_scene((double)px * ow / INPUT_SPACE_W, (double)py * oh / INPUT_SPACE_H, x, y)) {
*x = (double)px * w / INPUT_SPACE_W;
*y = (double)py * h / INPUT_SPACE_H;
}
if (*x < 0) *x = 0;
if (*y < 0) *y = 0;
@@ -3487,57 +3476,6 @@ static void deliver_touch(const struct input_msg *m) {
publish_query_state();
}
static void pen_log_target(void) {
static struct wl_client *said;
for (int i = 0; i < g_nptrs; i++) {
if (!g_ptrs[i].focus) continue;
struct wl_client *client = wl_resource_get_client(g_ptrs[i].focus);
if (client != said && log_budget()) {
char name[160];
describe(wl_resource_get_user_data(g_ptrs[i].focus), name, sizeof(name));
droiddeck_log("pen", "%s gets the pen as the pointer", name);
}
said = client;
return;
}
}
static int pen_buttons(int flags) {
int held = 0;
if (flags & PEN_TIP) held |= PEN_BIT(BTN_LEFT);
if (flags & PEN_RIGHT) held |= PEN_BIT(BTN_RIGHT);
if (flags & PEN_MIDDLE) held |= PEN_BIT(BTN_MIDDLE);
return held;
}
static void pen_release(int buttons) {
for (uint32_t button = BTN_LEFT; button <= BTN_MIDDLE; button++)
if (buttons & PEN_BIT(button)) pointer_button(button, 0);
}
static void deliver_pen(const struct input_msg *m) {
if (!(m->p1 & PEN_IN)) {
pen_release(g_pen.buttons);
if (g_pen.in) g_raw_valid = 0;
memset(&g_pen, 0, sizeof(g_pen));
return;
}
int held = pen_buttons(m->p1);
if (!g_pen.in) g_raw_valid = 0;
g_pen.in = 1;
double x, y;
input_output_to_scene(m->p2 / 256.0, m->p3 / 256.0, &x, &y);
if (g_pen.buttons) g_grab = g_pen.grab;
if (!pointer_locked_for_cursor()) pointer_event(x, y, 0, 0);
for (uint32_t button = BTN_LEFT; button <= BTN_MIDDLE; button++)
if (held & ~g_pen.buttons & PEN_BIT(button)) pointer_button(button, 1);
g_pen.grab = g_grab;
pen_release(g_pen.buttons & ~held);
if (held) g_grab = g_pen.grab;
g_pen.buttons = held;
pen_log_target();
}
static void key_event(uint32_t evdev, int pressed);
struct wl_resource *droiddeck_ime_target(void);
static void deliver_key(const struct input_msg *m) {
@@ -3689,7 +3627,6 @@ static int on_input_readable(int fd, uint32_t mask, void *data) {
case 10: break;
case 11: axis_event(m.p1, m.p2, 0); break;
case 12: axis_event(m.p1, m.p2, 1); break;
case 13: deliver_pen(&m); break;
case 20: stream_take(); break;
case 21: if (!m.p1) stream_forget_all(); schedule_render(); break;
case 22: schedule_render(); break;
@@ -3729,13 +3666,6 @@ void droiddeck_wayland_send_touch(int action, int pointer_id, int x, int y) {
(void)n;
}
void droiddeck_wayland_send_pen(int flags, int x, int y) {
if (g_input_pipe[1] < 0) return;
struct input_msg m = { 13, flags, x, y, 0 };
ssize_t n = write(g_input_pipe[1], &m, sizeof(m));
(void)n;
}
void droiddeck_wayland_send_key(int evdev, int state) {
if (g_input_pipe[1] < 0) return;
struct input_msg m = { 1, evdev, state, 0, 0 };
@@ -8,7 +8,7 @@
#include <android/log.h>
#include "VkDispatchTable.h"
#include "VulkanRendererContext.h"
#include "lsfg/lsfg_engine.h"
#include "lsfg/lsfg_probe.h"
#include "lsfg/lsfg_vkd.h"
@@ -6,7 +6,6 @@
#include <stdlib.h>
#include <sys/stat.h>
#include <android/log.h>
#include <string.h>
#define TAG "DroidDeckWayland"
@@ -46,13 +45,6 @@ int vk_loader_open(const char *driver_path, const char *library_name,
return g_vk.CreateInstance ? 0 : -1;
}
void vk_loader_close(void) {
if (g_handle) dlclose(g_handle);
g_handle = NULL;
g_gip = NULL;
memset(&g_vk, 0, sizeof(g_vk));
}
PFN_vkGetInstanceProcAddr vk_loader_gipa(void) { return g_gip; }
void vk_loader_load_instance(VkInstance instance) {
+1 -2
View File
@@ -6,7 +6,7 @@
#define VK_GLOBAL_FUNCS(X) X(CreateInstance) X(EnumerateInstanceExtensionProperties)
#define VK_INSTANCE_FUNCS(X) \
X(DestroyInstance) X(EnumeratePhysicalDevices) X(GetPhysicalDeviceProperties) \
X(EnumeratePhysicalDevices) X(GetPhysicalDeviceProperties) \
X(GetPhysicalDeviceQueueFamilyProperties) X(GetPhysicalDeviceSurfaceSupportKHR) \
X(GetPhysicalDeviceSurfaceCapabilitiesKHR) X(GetPhysicalDeviceSurfaceFormatsKHR) \
X(CreateAndroidSurfaceKHR) X(DestroySurfaceKHR) X(CreateDevice) \
@@ -43,7 +43,6 @@ extern struct vk_api g_vk;
int vk_loader_open(const char *driver_path, const char *library_name,
const char *native_lib_dir);
void vk_loader_close(void);
void vk_loader_load_instance(VkInstance instance);
void vk_loader_load_device(VkDevice device);
PFN_vkGetInstanceProcAddr vk_loader_gipa(void);
+1 -16
View File
@@ -46,7 +46,6 @@ struct vkp_image {
static ANativeWindow *g_window;
static int g_ahb_import;
static char *g_driver_path, *g_library_name, *g_native_lib_dir;
static int g_allow_driver_fallback;
static int g_dev_state;
static void device_lost(const char *where);
static const char *vk_result_name(VkResult r);
@@ -251,8 +250,6 @@ void vk_present_set_driver(const char *driver_path, const char *library_name,
g_native_lib_dir = native_lib_dir ? strdup(native_lib_dir) : NULL;
}
void vk_present_set_driver_fallback(int allow) { g_allow_driver_fallback = allow; }
static void reset_sync(void) {
VkSemaphoreCreateInfo semci = {.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO};
for (int k = 0; k < MAX_PRESENTS; k++) {
@@ -429,7 +426,7 @@ static void update_map(int scene_w, int scene_h) {
else if (align == VKP_ALIGN_PICTURE_RIGHT) g_map.off_x = W - scene_w * g_map.kx;
g_map.valid = 1;
pthread_mutex_lock(&g_game_picture_lock);
g_game_picture_placed = mode == VKP_MODE_INTEGER || align == VKP_ALIGN_PICTURE_TOP || align == VKP_ALIGN_PICTURE_BOTTOM || align == VKP_ALIGN_PICTURE_LEFT || align == VKP_ALIGN_PICTURE_RIGHT;
g_game_picture_placed = align == VKP_ALIGN_PICTURE_TOP || align == VKP_ALIGN_PICTURE_BOTTOM || align == VKP_ALIGN_PICTURE_LEFT || align == VKP_ALIGN_PICTURE_RIGHT;
g_game_picture_rect[0] = g_map.off_x;
g_game_picture_rect[1] = g_map.off_y;
g_game_picture_rect[2] = g_map.off_x + scene_w * g_map.kx;
@@ -552,18 +549,6 @@ static int dev_init(void) {
uint32_t npd = 0;
g_vk.EnumeratePhysicalDevices(g_inst, &npd, NULL);
if (!npd) {
if (g_allow_driver_fallback && g_driver_path && g_library_name) {
LOGE("present: display driver exposed no physical devices; retrying the system Vulkan driver");
g_vk.DestroyInstance(g_inst, NULL);
g_inst = VK_NULL_HANDLE;
vk_loader_close();
free(g_driver_path); g_driver_path = NULL;
free(g_library_name); g_library_name = NULL;
g_allow_driver_fallback = 0;
g_colorspace_ext = 0;
g_dev_state = 0;
return dev_init();
}
LOGE("present: no physical devices"); g_dev_state = -1;
set_fault("the display driver exposed no GPU to the app");
return -1;
@@ -7,7 +7,6 @@
void vk_present_set_driver(const char *driver_path, const char *library_name,
const char *native_lib_dir);
void vk_present_set_driver_fallback(int allow);
void vk_present_set_window(ANativeWindow *window);
int vkp_apply_window_request(void);
@@ -24,7 +24,6 @@ extern int droiddeck_wayland_run(void);
extern void droiddeck_wayland_set_scale_mode(int mode, int alignment);
extern void droiddeck_wayland_send_pointer(int action, int x, int y);
extern void droiddeck_wayland_send_touch(int action, int pointer_id, int x, int y);
extern void droiddeck_wayland_send_pen(int flags, int x, int y);
extern int droiddeck_cursor_snapshot(int *out, int cap);
extern int droiddeck_cursor_serial(void);
extern int droiddeck_hud_frame_times(float *out, int len, int64_t *total);
@@ -254,13 +253,12 @@ static char *dup_jstr(JNIEnv *env, jstring s) {
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStartWithSurface(
JNIEnv *env, jclass clazz, jobject surface, jstring xdgRuntimeDir,
jstring driverPath, jstring libraryName, jstring nativeLibDir, jboolean allowDriverFallback) {
jstring driverPath, jstring libraryName, jstring nativeLibDir) {
set_runtime_dir(env, xdgRuntimeDir);
char *dp = dup_jstr(env, driverPath);
char *ln = dup_jstr(env, libraryName);
char *nl = dup_jstr(env, nativeLibDir);
vk_present_set_driver(dp, ln, nl);
vk_present_set_driver_fallback(allowDriverFallback == JNI_TRUE);
free(dp); free(ln); free(nl);
if (surface) {
ANativeWindow *win = ANativeWindow_fromSurface(env, surface);
@@ -282,12 +280,6 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendTouch(
droiddeck_wayland_send_touch(action, pointer_id, x, y);
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendPen(
JNIEnv *env, jclass clazz, jint flags, jint x, jint y) {
droiddeck_wayland_send_pen(flags, x, y);
}
JNIEXPORT jint JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSnapshot(
JNIEnv *env, jclass clazz, jintArray out) {
@@ -456,18 +448,6 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeGamePictureRect(JNIE
return JNI_TRUE;
}
JNIEXPORT jboolean JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeOutputSize(JNIEnv *env, jclass clazz, jintArray out) {
(void)clazz;
if (!out || (*env)->GetArrayLength(env, out) < 2) return JNI_FALSE;
int width = 0, height = 0;
vkp_output_size(&width, &height);
if (width <= 0 || height <= 0) return JNI_FALSE;
jint size[2] = {(jint)width, (jint)height};
(*env)->SetIntArrayRegion(env, out, 0, 2, size);
return JNI_TRUE;
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetUpscaler(JNIEnv *env, jclass clazz, jint mode) {
vkp_effects_set_scaling(mode);
@@ -48,6 +48,7 @@ class App : Application() {
com.droiddeck.launcher.ui.AgentPet.install(this)
if (com.droiddeck.launcher.agent.AgentTab.visible) com.droiddeck.launcher.lab.LabNotice.openOnInstall = "agent"
com.droiddeck.launcher.lab.LabNotice.started(this)
com.droiddeck.launcher.core.SteamIntegration.syncShortcutsListing(this)
com.droiddeck.launcher.session.QuestExperimental.initialize(this)
com.droiddeck.launcher.session.SessionPrefs.applyNtsyncDefault(this)
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
@@ -56,7 +57,6 @@ class App : Application() {
com.droiddeck.launcher.core.DownloadSource.init(this)
prefetchAddonPacks()
GpuClockPin.clearLeftover(this)
com.droiddeck.launcher.input.UsbMouse.returnLeftover(this)
com.droiddeck.launcher.glasses.Glasses.init(this)
com.droiddeck.launcher.glasses.GlassesMenuMirror.initialize(this)
BwrapSpawner.start(this)
@@ -286,13 +286,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
// Builds before 0.5.0-nad1 turned the bridge on under Auto without recording it, and
// left it on for good (it wins over the pair). Under Auto that switch is taken as Auto's.
if (!SessionPrefs.maliFallbackKnown(activity))
SessionPrefs.setMaliFallbackByAuto(
activity,
MaliAutoRoute.initialOwnership(
SessionPrefs.vkBridge(activity), bridgeExplicit(),
SessionPrefs.venus(activity), venusExplicit(),
),
)
SessionPrefs.setMaliFallbackByAuto(activity, if (SessionPrefs.vkBridge(activity)) "bridge" else "")
// A lone imported PanVK Android driver set by hand stalls the display the same way
// ("black screen with the start-up logo"), so under Auto any imported display goes.
val display = SessionPrefs.androidDriver(activity)
@@ -362,14 +356,8 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
val pair = pairs.firstOrNull { it.key == key }
val row = pairRows.firstOrNull { it.key == key }
when {
row?.active == true -> {
if (MaliAutoRoute.shouldEnd(
SessionPrefs.maliFallbackByAuto(activity), gpu.family.mali,
pair?.key?.let { DriverPairs.isNonAdreno(it) } == true,
)) endMaliFallback()
autoStatus = problem?.let { activity.getString(R.string.drivers_up_to_date_check_failed, it) }
?: activity.getString(R.string.upd_current_status)
}
row?.active == true -> autoStatus = problem?.let { activity.getString(R.string.drivers_up_to_date_check_failed, it) }
?: activity.getString(R.string.upd_current_status)
gpu.family == GpuInfo.Family.POWERVR && (pair == null || !pair.complete) -> {
// RADV is not published right now: the Xclipse falls back to the system route.
SessionPrefs.ensurePowerVrAutoDrivers(activity)
@@ -409,12 +397,6 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
}, "gpu-driver-auto").start()
}
private fun bridgeExplicit(): Boolean =
MaliAutoRoute.userChoice(SessionPrefs.vkBridgeExplicit(activity), SessionPrefs.maliFallbackByAuto(activity), MaliAutoRoute.BRIDGE)
private fun venusExplicit(): Boolean =
MaliAutoRoute.userChoice(SessionPrefs.venusExplicit(activity), SessionPrefs.maliFallbackByAuto(activity), MaliAutoRoute.VENUS)
/**
* A Mali with no open driver pair to install ([missing] names the unpublished pair, or null when
* no PanVK build covers this GPU) runs through the phone's own driver: Mali (Venus) where this
@@ -428,21 +410,12 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
val oldVulkan = com.droiddeck.launcher.session.VenusComponent.hostVulkanTooOld(activity)
val venus = oldVulkan == null && com.droiddeck.launcher.session.VenusComponent.available(activity)
if (oldVulkan != null) Log.i(TAG, "auto: Mali driver reports Vulkan $oldVulkan; Venus needs 1.2, the bridge stands in")
val ownership = MaliAutoRoute.fallbackOwnership(
venus,
SessionPrefs.vkBridge(activity), bridgeExplicit(),
SessionPrefs.venus(activity), venusExplicit(),
)
if (venus && !SessionPrefs.venus(activity)) {
SessionPrefs.setVenus(activity, true)
if (SessionPrefs.vkBridge(activity) && !bridgeExplicit())
SessionPrefs.setVkBridge(activity, false)
SessionPrefs.setMaliFallbackByAuto(activity, ownership)
SessionPrefs.setMaliFallbackByAuto(activity, "venus")
} else if (!venus && !SessionPrefs.vkBridge(activity)) {
SessionPrefs.setVkBridge(activity, true)
SessionPrefs.setMaliFallbackByAuto(activity, ownership)
} else if (ownership != MaliAutoRoute.NONE) {
SessionPrefs.setMaliFallbackByAuto(activity, ownership)
SessionPrefs.setMaliFallbackByAuto(activity, "bridge")
}
val route = activity.getString(if (venus) R.string.drivers_route_venus else R.string.drivers_route_bridge)
Log.i(TAG, "auto: Mali stand-in route $route (missing pair: ${missing ?: "none covers ${gpu.name}"})")
@@ -530,9 +503,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
// A route Auto switched on in place of a missing pair goes off now that one is
// here. A Mali bridge or Venus switch the user set stays: it wins for the session
// (DeviceSupport.vkBridge, VenusComponent.wanted) and the pair waits.
if (MaliAutoRoute.shouldEnd(
SessionPrefs.maliFallbackByAuto(activity), gpu.family.mali, DriverPairs.isNonAdreno(pair.key),
)) endMaliFallback()
if (gpu.family.mali && DriverPairs.isNonAdreno(pair.key)) endMaliFallback()
val restart = displayChanged && CompositorHost.isStarted
if (auto) {
val trial = AutoDriverTrial.current(activity)
@@ -773,3 +744,4 @@ internal fun Context.displayNameOf(uri: Uri): String? = if (uri.scheme == "file"
} catch (e: Exception) {
null
}
@@ -182,7 +182,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var paceCores by mutableStateOf(true)
private var ramCapMb by mutableStateOf(0)
private var zramClient by mutableStateOf(true)
private var zramIdle by mutableStateOf(true)
private var vramCapMb by mutableStateOf(0)
private var gpuClockPin by mutableStateOf(false)
private var prootNoSeccomp by mutableStateOf(false)
@@ -367,78 +366,15 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
SteamIntegration.Feature.BRIGHTNESS -> integrationSettings(SteamIntegration.brightnessSettings(this))
SteamIntegration.Feature.HOME -> if (HomeApp.isDefault(this)) HomeApp.openSystemHomeSettings(this) else offerHomeScreen()
SteamIntegration.Feature.SHORTCUTS -> {
if (integrationState.shortcuts) openShortcutSettings() else installShortcuts()
if (!integrationState.shortcuts) shortcutsTried = true
SteamIntegration.setShortcutsListed(this, true)
integrationSettings(SteamIntegration.shortcutSettings(this), android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS)
}
}
}
private fun openShortcutSettings() =
integrationSettings(SteamIntegration.shortcutSettings(this), android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS)
private fun installShortcuts() {
if (ShortcutsInstall.running) return
ShortcutsInstall.running = true
Thread({
val result = runCatching {
val apk = SteamIntegration.bundledShortcuts(this)
when {
SteamIntegration.shortcutsInstalled(this, apk) -> {
ShortcutsInstall.running = false
ui.post { shortcutsReady() }
}
!com.droiddeck.launcher.update.SelfInstaller.canInstall(this) -> {
ShortcutsInstall.running = false
ui.post { integrationSettings(com.droiddeck.launcher.update.SelfInstaller.permissionIntent(this)) }
}
else -> com.droiddeck.launcher.update.SelfInstaller.install(this, apk, com.droiddeck.shortcuts.Relay.PACKAGE,
SteamIntegration.SHORTCUTS_STATUS) { id -> ShortcutsInstall.session = id }
}
}
result.onFailure { e ->
ShortcutsInstall.running = false
ui.post { shortcutsFailed(e.message) }
}
}, "shortcuts-install").start()
}
private fun shortcutsReady() {
shortcutsTried = true
Thread({
val deadline = android.os.SystemClock.uptimeMillis() + 3000
while (!SteamIntegration.shortcutsListed(this) && android.os.SystemClock.uptimeMillis() < deadline) Thread.sleep(100)
ui.post { openShortcutSettings() }
}, "shortcuts-listed").start()
}
private fun shortcutsFailed(message: String?) {
android.widget.Toast.makeText(this, message?.let { getString(R.string.integration_shortcuts_install_failed_with, it) }
?: getString(R.string.integration_shortcuts_install_failed), android.widget.Toast.LENGTH_LONG).show()
}
private val shortcutsInstallStatus = object : android.content.BroadcastReceiver() {
override fun onReceive(context: android.content.Context, intent: Intent) {
val session = intent.getIntExtra(android.content.pm.PackageInstaller.EXTRA_SESSION_ID, -1)
if (session < 0 || session != ShortcutsInstall.session) return
val status = intent.getIntExtra(android.content.pm.PackageInstaller.EXTRA_STATUS,
android.content.pm.PackageInstaller.STATUS_FAILURE)
if (status != android.content.pm.PackageInstaller.STATUS_PENDING_USER_ACTION) {
ShortcutsInstall.session = -1
ShortcutsInstall.running = false
}
when (status) {
android.content.pm.PackageInstaller.STATUS_PENDING_USER_ACTION -> {
val confirm = if (android.os.Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)
else @Suppress("DEPRECATION") intent.getParcelableExtra(Intent.EXTRA_INTENT)
val safe = confirm?.let { com.droiddeck.launcher.update.SelfInstaller.safeConfirmIntent(this@FrontEndActivity, it) }
if (safe == null || runCatching { startActivity(safe) }.isFailure) shortcutsFailed(null)
}
android.content.pm.PackageInstaller.STATUS_SUCCESS -> shortcutsReady()
else -> shortcutsFailed(intent.getStringExtra(android.content.pm.PackageInstaller.EXTRA_STATUS_MESSAGE))
}
}
}
private fun openAppInfo() = integrationSettings(SteamIntegration.shortcutsAppInfo())
private fun openAppInfo() =
integrationSettings(Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName")))
private fun openWifiDiscoverySettings() {
if (!WifiDiscovery.permissionGranted(this)) {
@@ -599,7 +535,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var upscaleSharpness by mutableStateOf(75)
private var hdrReason by mutableStateOf<String?>(null)
private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO)
private var pen by mutableStateOf<SessionPrefs.Pen?>(null)
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
private var steamDownloadsInBackground by mutableStateOf(false)
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
@@ -1203,9 +1138,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
homeChoiceOpen = savedInstanceState?.getBoolean(STATE_HOME_CHOICE_OPEN) == true
gameSpaceOffered = savedInstanceState?.getBoolean(STATE_GAME_SPACE_OFFERED) == true
if (savedInstanceState == null) readIntegrationIntent(intent)
val shortcutsFilter = android.content.IntentFilter(SteamIntegration.SHORTCUTS_STATUS)
if (android.os.Build.VERSION.SDK_INT >= 33) registerReceiver(shortcutsInstallStatus, shortcutsFilter, RECEIVER_NOT_EXPORTED)
else registerReceiver(shortcutsInstallStatus, shortcutsFilter)
readGameIntent(intent)
// A Lab build is usually the agent's work, so the app comes back where the agent is.
if (savedInstanceState == null && navRequest == null && com.droiddeck.launcher.lab.LabOverlay.promoted && com.droiddeck.launcher.agent.AgentTab.visible) navRequest = "agent"
@@ -2042,6 +1974,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
requestedOrientation = launcherOrientation
homePage = com.droiddeck.launcher.core.AppUiPrefs.homePage(this)
SteamIntegration.syncShortcutsListing(this)
refreshWifiDiscovery()
com.droiddeck.launcher.stores.StoresState.refresh(this)
com.droiddeck.launcher.stores.StoresState.libraryListener = { refreshAddedGames(); refresh() }
@@ -2150,7 +2083,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
gameLaunchRequest.incrementAndGet()
cancelCompatLaunch()
updates.unregister()
runCatching { unregisterReceiver(shortcutsInstallStatus) }
super.onDestroy()
}
@@ -2539,7 +2471,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
gpuDrivers = drivers.summary(),
touchMode = touchMode,
pen = pen,
suspendPolicy = suspendPolicy,
steamDownloadsInBackground = steamDownloadsInBackground,
pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this),
@@ -2592,7 +2523,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onUpscaler = { m -> SessionPrefs.setUpscaler(this, m); upscaler = m },
onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct },
onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t },
onPen = { key, value -> SessionPrefs.setPenSetting(this, key, value); pen = SessionPrefs.pen(this) },
onSuspendPolicy = { policy -> SessionPrefs.setSuspendPolicy(this, mode, policy); suspendPolicy = policy },
onSteamDownloadsInBackground = { enabled ->
SessionPrefs.setSteamDownloadsInBackground(this, enabled)
@@ -2702,7 +2632,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
fsyncFirst = fsyncFirst,
gamescopeRealtime = gamescopeRealtime,
gpuClockPin = gpuClockPin,
ramCapMb = ramCapMb, vramCapMb = vramCapMb, zramClient = zramClient, zramIdle = zramIdle,
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(),
@@ -2722,7 +2652,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on },
onRamCapMb = { mb -> SessionPrefs.setRamCapMb(this, mb); ramCapMb = mb },
onZramClient = { on -> SessionPrefs.setZramClient(this, on); zramClient = on },
onZramIdle = { on -> SessionPrefs.setZramIdle(this, on); zramIdle = 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 },
@@ -2940,8 +2869,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
upscaleSharpness = SessionPrefs.upscaleSharpness(this)
hdrReason = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason
touchMode = SessionPrefs.touchMode(this)
if (!SessionPrefs.penSeen(this) && com.droiddeck.launcher.input.PenStream.penConnected()) SessionPrefs.setPenSeen(this)
pen = SessionPrefs.pen(this).takeIf { SessionPrefs.penSeen(this) }
suspendPolicy = SessionPrefs.suspendPolicy(this, mode)
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
oscMode = SessionPrefs.oscMode(this)
@@ -3022,7 +2949,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
paceCores = SessionPrefs.paceCores(this)
ramCapMb = SessionPrefs.ramCapMb(this)
zramClient = SessionPrefs.zramClient(this)
zramIdle = SessionPrefs.zramIdle(this)
vramCapMb = SessionPrefs.vramCapMb(this)
gpuClockPin = SessionPrefs.gpuClockPin(this)
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
@@ -3374,9 +3300,3 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private val WCP_EXT = listOf("wcp")
}
}
// The install session outlives the activity when Android recreates it mid-install.
private object ShortcutsInstall {
@Volatile var session = -1
@Volatile var running = false
}
@@ -1,31 +0,0 @@
package com.droiddeck.launcher
internal object MaliAutoRoute {
const val NONE = ""
const val BRIDGE = "bridge"
const val VENUS = "venus"
fun initialOwnership(bridgeOn: Boolean, bridgeExplicit: Boolean, venusOn: Boolean, venusExplicit: Boolean): String =
when {
venusOn && !venusExplicit -> VENUS
bridgeOn && !bridgeExplicit -> BRIDGE
else -> NONE
}
fun fallbackOwnership(
venusAvailable: Boolean,
bridgeOn: Boolean,
bridgeExplicit: Boolean,
venusOn: Boolean,
venusExplicit: Boolean,
): String = if (venusAvailable) {
if (!venusOn || !venusExplicit) VENUS else NONE
} else {
if (!bridgeOn || !bridgeExplicit) BRIDGE else NONE
}
fun userChoice(keyStored: Boolean, owner: String, route: String): Boolean = keyStored && owner != route
fun shouldEnd(ownsRoute: String, mali: Boolean, installedPair: Boolean): Boolean =
mali && installedPair && ownsRoute != NONE
}
File diff suppressed because it is too large. Load diff
@@ -96,17 +96,7 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
percent = 0
Thread({
val result = runCatching {
val file = try {
SelfInstaller.download(activity, apk) { pct -> ui.post { percent = pct } }
} catch (e: java.io.IOException) {
// Each push replaces a test build's APK, so a list read before the push names a file that is gone.
if (r.pr <= 0) throw e
val fresh = runCatching { AppUpdates.refresh(activity) }.getOrNull() ?: throw e
ui.post { catalog = fresh }
val newer = fresh.tests.firstOrNull { it.tag == r.tag }?.apk?.takeIf { it.url != apk.url } ?: throw e
ui.post { percent = 0 }
SelfInstaller.download(activity, newer) { pct -> ui.post { percent = pct } }
}
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) { id -> session = id }
}
@@ -1,13 +1,9 @@
package com.droiddeck.launcher.agent
import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import android.provider.OpenableColumns
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
@@ -54,22 +50,6 @@ object AgentAttachments {
if (host(context, path).renameTo(moved)) "$GUEST_DIR/$chat/${moved.name}" else path
}
/** Copies the running game's frame; set while a session is open. */
var gameFrame by mutableStateOf<(((Bitmap?) -> Unit) -> Unit)?>(null)
/** Saves [frame] for [chat] (or a new conversation) on the calling thread; returns its guest path. */
fun saveFrame(context: Context, chat: String?, frame: Bitmap): String? = runCatching {
val folder = chat ?: NEW
val dir = File(hostDir(context), folder).apply { mkdirs() }
val target = File(dir, "game-${System.currentTimeMillis()}.jpg")
val written = target.outputStream().use { frame.compress(Bitmap.CompressFormat.JPEG, 88, it) }
if (!written) {
target.delete()
return@runCatching null
}
"$GUEST_DIR/$folder/${target.name}"
}.getOrNull()
/** Deletes copies that will not be sent. */
fun discard(context: Context, files: List<String>) = files.forEach { host(context, it).delete() }
@@ -37,21 +37,6 @@ object AgentChats {
}
.sortedByDescending { it.updated }
/** The chats among [chats] where the user or the agent wrote [query], ignoring case. */
fun search(context: Context, chats: List<Chat>, query: String): List<Chat> {
val q = query.trim()
if (q.isEmpty()) return chats
return chats.filter { chat ->
chat.title.contains(q, ignoreCase = true) || read(file(context, chat.id)).entries.any { matches(it, q) }
}
}
internal fun matches(entry: Entry, query: String) = when (entry) {
is Entry.Asked -> entry.text.contains(query, ignoreCase = true)
is Entry.Said -> entry.text.contains(query, ignoreCase = true)
else -> false
}
fun delete(context: Context, id: String) {
file(context, id).delete()
File(AgentAttachments.hostDir(context), id).deleteRecursively()
@@ -87,7 +72,6 @@ object AgentChats {
is Entry.Thought -> JSONObject().put("thought", entry.text)
is Entry.Result -> JSONObject().put("result", entry.id).put("output", entry.output).put("failed", entry.failed)
is Entry.Used -> JSONObject().put("used", entry.tool).put("detail", entry.detail).put("id", entry.id).put("input", entry.input)
.apply { if (entry.parent.isNotEmpty()) put("parent", entry.parent) }
.apply { entry.output?.let { put("output", it).put("failed", entry.failed) } }
is Entry.Finished -> JSONObject().put("finished", true).put("error", entry.error ?: JSONObject.NULL).put("stopped", entry.stopped).apply {
if (entry.planned) put("planned", true)
@@ -121,7 +105,7 @@ object AgentChats {
o.has("said") -> Entry.Said(o.getString("said"))
o.has("thought") -> Entry.Thought(o.getString("thought"))
o.has("used") -> Entry.Used(o.optString("id"), o.getString("used"), o.optString("detail"), o.optString("input"),
if (o.has("output")) o.optString("output") else null, o.optBoolean("failed"), o.optString("parent"))
if (o.has("output")) o.optString("output") else null, o.optBoolean("failed"))
o.has("result") -> Entry.Result(o.getString("result"), o.optString("output"), o.optBoolean("failed"))
o.has("finished") -> Entry.Finished(
if (o.isNull("error")) null else o.optString("error"), o.optBoolean("stopped"),
@@ -108,11 +108,8 @@ object ClaudeCode : AgentHarness {
override fun parse(line: String): AgentEvent? {
val o = runCatching { JSONObject(line) }.getOrNull() ?: return null
val conversation = o.optString("session_id").takeIf { it.isNotEmpty() }
// A subagent's messages carry the call that started it; only its tool calls are shown, under that call.
val parent = o.optString("parent_tool_use_id").takeIf { it.isNotEmpty() && it != "null" }
return when (o.optString("type")) {
"stream_event" -> {
if (parent != null) return null
val delta = o.optJSONObject("event")?.takeIf { it.optString("type") == "content_block_delta" }?.optJSONObject("delta") ?: return null
when (delta.optString("type")) {
"text_delta" -> AgentEvent(conversation, text = delta.optString("text"))
@@ -126,18 +123,18 @@ object ClaudeCode : AgentHarness {
val entries = (0 until content.length()).mapNotNull { i ->
val block = content.optJSONObject(i) ?: return@mapNotNull null
when (block.optString("type")) {
"text" -> if (parent != null) null else block.optString("text").trim().takeIf { it.isNotEmpty() }?.let { AgentHost.Entry.Said(it) }
"thinking" -> if (parent != null) null else block.optString("thinking").trim().takeIf { it.isNotEmpty() }?.let { AgentHost.Entry.Thought(it) }
"text" -> block.optString("text").trim().takeIf { it.isNotEmpty() }?.let { AgentHost.Entry.Said(it) }
"thinking" -> block.optString("thinking").trim().takeIf { it.isNotEmpty() }?.let { AgentHost.Entry.Thought(it) }
"tool_use" -> {
val input = block.optJSONObject("input")
AgentHost.Entry.Used(block.optString("id"), block.optString("name"), detail(input), fullInput(block.optString("name"), input), parent = parent.orEmpty())
AgentHost.Entry.Used(block.optString("id"), block.optString("name"), detail(input), fullInput(block.optString("name"), input))
}
else -> null
}
}
val usage = message?.optJSONObject("usage")
val context = usage?.let { it.optLong("input_tokens") + it.optLong("cache_read_input_tokens") + it.optLong("cache_creation_input_tokens") + it.optLong("output_tokens") }
AgentEvent(conversation, entries, context = context?.takeIf { it > 0 && parent == null })
AgentEvent(conversation, entries, context = context?.takeIf { it > 0 })
}
"user" -> {
val content = o.optJSONObject("message")?.optJSONArray("content") ?: return conversation?.let { AgentEvent(it) }
@@ -29,11 +29,8 @@ object AgentHost {
data class Asked(val text: String, val files: List<String> = emptyList()) : Entry
data class Said(val text: String) : Entry
data class Thought(val text: String) : Entry
/** A tool call; [output] stays null until its result arrives. [parent] is the subagent call it was made under, if any. */
data class Used(
val id: String, val tool: String, val detail: String, val input: String = "", val output: String? = null, val failed: Boolean = false,
val parent: String = "",
) : Entry
/** A tool call; [output] stays null until its result arrives. */
data class Used(val id: String, val tool: String, val detail: String, val input: String = "", val output: String? = null, val failed: Boolean = false) : Entry
data class Result(val id: String, val output: String, val failed: Boolean) : Entry
/** [planned]: the turn ran in plan mode, so it ends on a plan that nothing has carried out yet. */
data class Finished(val error: String?, val stopped: Boolean = false, val usage: Usage? = null, val planned: Boolean = false) : Entry
@@ -74,9 +71,7 @@ object AgentHost {
"Run it with run_in_background and keep checking its output, so the user can talk to you meanwhile. " +
"The restart ends this process, and this conversation continues on the new build. " +
"Files the user attaches are listed at the end of their message, under /root/.cache/droiddeck/attachments. " +
"Commits and pull requests you make are the user's own: add no co-author line, AI credit or generated-by note. " +
"To have the user pick between options, end your reply with a fenced code block whose language is choices, one short option per line, " +
"and end your turn: DroidDeck shows them as buttons and sends the one picked as the next message."
"Commits and pull requests you make are the user's own: add no co-author line, AI credit or generated-by note."
val entries = mutableStateListOf<Entry>()
val queue = mutableStateListOf<Queued>()
@@ -147,7 +142,6 @@ object AgentHost {
fun seen() {
unseen = false
appContext?.let { AgentNotice.clear(it) }
}
fun refresh(context: Context) {
@@ -468,19 +462,7 @@ object AgentHost {
if (!stopped && queue.isNotEmpty()) {
val next = queue.removeAt(0)
send(app, next.text, next.files)
} else if (!stopped) notifyEnded(app, error)
}
private fun notifyEnded(app: Context, error: String?) {
val start = entries.indexOfLast { it is Entry.Asked }
val said = entries.subList(start + 1, entries.size).lastOrNull { it is Entry.Said } as? Entry.Said
val reply = said?.let { choices(it.text) }
val kind = when {
error != null -> AgentNotice.Kind.FAILED
!reply?.options.isNullOrEmpty() -> AgentNotice.Kind.QUESTION
else -> AgentNotice.Kind.DONE
}
AgentNotice.post(app, kind, error ?: reply?.text?.takeIf { it.isNotBlank() }?.let { firstLine(it) } ?: "")
}
/** A message typed or retried by the user replaces the automatic resend. */
@@ -519,7 +501,7 @@ object AgentHost {
}
/** The latest todo list the agent wrote in this conversation. */
fun todos(): String? = entries.lastOrNull { it is Entry.Used && it.tool == "TodoWrite" && it.parent.isEmpty() }?.let { (it as Entry.Used).input }
fun todos(): String? = entries.lastOrNull { it is Entry.Used && it.tool == "TodoWrite" }?.let { (it as Entry.Used).input }
private fun tick() {
now = SystemClock.elapsedRealtime()
@@ -663,34 +645,3 @@ object AgentHost {
internal fun prefs(context: Context) = context.getSharedPreferences("agent", Context.MODE_PRIVATE)
}
/** A reply split into its text and the options of a trailing choices block. */
internal data class Choices(val text: String, val options: List<String>)
private val FENCE = Regex("""[ \t]{0,3}(`{3,}|~{3,})(.*)""")
/** Walks Markdown fences so a choices block counts only at the top level and only as the last thing in the reply. */
internal fun choices(reply: String): Choices {
val lines = reply.split('\n')
var open = ""
var opener = -1
var openChoices = false
var block: IntRange? = null
lines.forEachIndexed { i, line ->
val fence = FENCE.matchEntire(line)
if (open.isEmpty()) {
if (fence != null) {
open = fence.groupValues[1]
opener = i
openChoices = fence.groupValues[2].trim() == "choices"
block = null
} else if (line.isNotBlank()) block = null
} else if (fence != null && fence.groupValues[1][0] == open[0] && fence.groupValues[1].length >= open.length && fence.groupValues[2].isBlank()) {
block = if (openChoices) opener..i else null
open = ""
}
}
val found = block?.takeIf { open.isEmpty() } ?: return Choices(reply, emptyList())
val options = lines.subList(found.first + 1, found.last).map { it.trim().removePrefix("- ").removePrefix("* ").trim() }.filter { it.isNotEmpty() }
return Choices(lines.subList(0, found.first).joinToString("\n").trimEnd(), options)
}
@@ -1,58 +0,0 @@
package com.droiddeck.launcher.agent
import android.app.ActivityManager
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import com.droiddeck.launcher.FrontEndActivity
import com.droiddeck.launcher.R
import com.droiddeck.launcher.ui.AgentPet
/** Tells the user a turn has ended when nothing on screen already does. */
internal object AgentNotice {
private const val CHANNEL_ID = "agent_done"
private const val NOTIFICATION_ID = 4108
enum class Kind { DONE, FAILED, QUESTION }
fun post(context: Context, kind: Kind, text: String) {
if (onScreen(context)) return
val manager = context.getSystemService(NotificationManager::class.java) ?: return
manager.createNotificationChannel(NotificationChannel(CHANNEL_ID, context.getString(R.string.agent_done_channel), NotificationManager.IMPORTANCE_DEFAULT))
val open = PendingIntent.getActivity(context, 2,
Intent(context, FrontEndActivity::class.java)
.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
.putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, "agent"),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
val title = context.getString(when (kind) {
Kind.DONE -> R.string.agent_done
Kind.FAILED -> R.string.agent_done_failed
Kind.QUESTION -> R.string.agent_done_question
})
runCatching {
manager.notify(NOTIFICATION_ID, Notification.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_session)
.setContentTitle(title)
.setContentText(text)
.setStyle(Notification.BigTextStyle().bigText(text))
.setContentIntent(open)
.setAutoCancel(true)
.setCategory(Notification.CATEGORY_STATUS)
.build())
}
}
fun clear(context: Context) {
context.getSystemService(NotificationManager::class.java)?.cancel(NOTIFICATION_ID)
}
/** The chat in a DroidDeck window in front, or the pet, which shows the reply in its own bubble. */
private fun onScreen(context: Context): Boolean {
if (AgentPet.floating) return true
val state = ActivityManager.RunningAppProcessInfo().also { ActivityManager.getMyMemoryState(it) }
return AgentPet.agentOnScreen > 0 && state.importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
}
}
@@ -1,143 +0,0 @@
package com.droiddeck.launcher.agent
import android.content.Context
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
import java.nio.file.attribute.BasicFileAttributes
import java.util.concurrent.TimeUnit
/** Claude Code's MCP servers and skills in the userland, through its own CLI and skills folder. */
internal object AgentTools {
data class Server(val name: String, val target: String, val status: String) {
/** Connectors come from the claude.ai account and are managed there, not by the CLI. */
val account get() = name.startsWith("claude.ai ")
}
data class Skill(val name: String, val description: String)
class Result(val ok: Boolean, val output: String)
private const val SKILLS = "root/.claude/skills"
private val SERVER = Regex("""^(.+?): (.+) - (.+)$""")
fun servers(context: Context): List<Server>? {
val result = run(context, listOf(ClaudeCode.binary, "mcp", "list"))
if (!result.ok) return null
return parseServers(result.output)
}
internal fun parseServers(output: String): List<Server> = output.lines().mapNotNull { line ->
SERVER.find(line.trim())?.destructured?.let { (name, target, status) -> Server(name, target, status) }
}
/** A URL is added as an HTTP server; anything else is the command that starts a stdio server. */
internal fun addCommand(name: String, target: String): List<String> {
val t = target.trim()
val base = listOf(ClaudeCode.binary, "mcp", "add", "--scope", "user")
return if (t.startsWith("http://") || t.startsWith("https://")) base + listOf("--transport", "http", name.trim(), t)
else base + listOf(name.trim(), "--") + words(t)
}
/** Splits a command line the way a shell would for quotes and backslashes, without expanding anything. */
internal fun words(line: String): List<String> {
val words = mutableListOf<String>()
val word = StringBuilder()
var inWord = false
var quote: Char? = null
var i = 0
while (i < line.length) {
val c = line[i]
when {
quote == '\'' -> if (c == '\'') quote = null else word.append(c)
c == '\\' && i + 1 < line.length && (quote == null || line[i + 1] == '"' || line[i + 1] == '\\') -> {
word.append(line[++i])
inWord = true
}
quote == '"' -> if (c == '"') quote = null else word.append(c)
c == '\'' || c == '"' -> {
quote = c
inWord = true
}
c.isWhitespace() -> if (inWord) {
words += word.toString()
word.clear()
inWord = false
}
else -> {
word.append(c)
inWord = true
}
}
i++
}
if (inWord) words += word.toString()
return words
}
fun add(context: Context, name: String, target: String) = run(context, addCommand(name, target))
fun remove(context: Context, name: String) = run(context, listOf(ClaudeCode.binary, "mcp", "remove", name))
fun skills(context: Context): List<Skill> =
File(LinuxRuntime.rootDir(context), SKILLS).listFiles { f -> f.isDirectory }.orEmpty().sortedBy { it.name.lowercase() }.map { dir ->
Skill(dir.name, description(File(dir, "SKILL.md")))
}
internal fun description(file: File): String = runCatching {
val lines = file.readLines()
if (lines.firstOrNull()?.trim() != "---") return@runCatching ""
lines.drop(1).takeWhile { it.trim() != "---" }.firstOrNull { it.startsWith("description:") }
?.removePrefix("description:")?.trim()?.trim('"', '\'').orEmpty()
}.getOrDefault("")
fun deleteSkill(context: Context, name: String): Boolean {
if (name.isEmpty() || name.contains('/') || name.startsWith(".")) return false
val root = File(LinuxRuntime.rootDir(context), SKILLS)
val dir = File(root, name)
if (dir.parentFile?.path != root.path) return false
return deleteTree(dir.toPath())
}
/** Deletes [path] and what is under it; a symbolic link is removed itself, never what it points to. */
internal fun deleteTree(path: Path): Boolean = runCatching {
if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) return@runCatching true
Files.walkFileTree(path, object : SimpleFileVisitor<Path>() {
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
Files.delete(file)
return FileVisitResult.CONTINUE
}
override fun postVisitDirectory(dir: Path, exc: java.io.IOException?): FileVisitResult {
if (exc != null) throw exc
Files.delete(dir)
return FileVisitResult.CONTINUE
}
})
true
}.getOrDefault(false)
private fun run(context: Context, command: List<String>): Result {
val child = runCatching { AgentHost.guest(context.applicationContext, command, connectAdb = false).start() }
.getOrElse { return Result(false, it.message.orEmpty()) }
val output = StringBuffer()
// The CLI can hold its output open past the deadline, so it is read beside the wait rather than before it.
val reader = Thread({ runCatching { child.inputStream.bufferedReader().forEachLine { output.append(it).append('\n') } } }, "agent-tools").apply { start() }
return try {
val ended = child.waitFor(90, TimeUnit.SECONDS)
if (!ended) child.destroyForcibly()
reader.join(2_000)
Result(ended && child.exitValue() == 0, output.toString().trim())
} catch (e: InterruptedException) {
child.destroyForcibly()
Thread.currentThread().interrupt()
Result(false, output.toString().trim())
} finally {
runCatching { child.inputStream.close() }
}
}
}
@@ -16,8 +16,6 @@ import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.function.IntConsumer;
import java.util.function.IntSupplier;
public class PulseAudioComponent extends SessionPart {
private static final String TAG = "PulseAudio";
@@ -31,55 +29,7 @@ public class PulseAudioComponent extends SessionPart {
private final File deviceControls;
private File logFile;
private final String micFifoPath;
private final HostLifecycle host = new HostLifecycle(Process::killProcess);
static final class HostLifecycle {
volatile int pid = -1;
private long generation;
private long launches;
private final IntConsumer terminate;
HostLifecycle(IntConsumer terminate) {
this.terminate = terminate;
}
synchronized long begin() {
stop();
return generation;
}
synchronized void stop() {
generation++;
if (pid > 1) terminate.accept(pid);
pid = -1;
}
synchronized boolean launch(long expected, IntSupplier launch) {
if (expected != generation) return false;
launches++;
pid = launch.getAsInt();
return true;
}
synchronized boolean current(long expected) {
return expected == generation;
}
/** The latest launch; a sink guard holds it so it never reconfigures a host started after its own. */
synchronized long token() {
return launches;
}
synchronized boolean live(long token) {
return token == launches && pid > 1;
}
synchronized boolean exited(long expected) {
if (expected != generation || pid <= 1) return false;
pid = -1;
return true;
}
}
private volatile int pid = -1;
public PulseAudioComponent(Context context) {
this(context, null);
@@ -114,12 +64,7 @@ public class PulseAudioComponent extends SessionPart {
@Override
public void start() {
start(host.begin());
}
private synchronized void start(long generation) {
// An exit callback's restart can be overtaken by a newer start; it must not touch the newer host's socket.
if (!host.current(generation)) return;
stop();
if (!workingDir.isDirectory()) {
workingDir.mkdirs();
FileUtils.chmod(workingDir, 0771);
@@ -173,23 +118,17 @@ public class PulseAudioComponent extends SessionPart {
+ " -n --file=default.pa --daemonize=false --use-pid-file=false --exit-idle-time=-1"
+ " --log-level=info";
final java.io.PrintWriter out = openLog();
if (!host.launch(generation, () -> HostProcess.start(command, env.toArray(new String[0]), workingDir, status -> {
if (host.exited(generation)) {
Log.w(TAG, "audio host exited with status " + status + "; restarting");
start(generation);
}
},
pid = HostProcess.start(command, env.toArray(new String[0]), workingDir, null,
line -> {
Log.i(TAG, line);
if (out != null) synchronized (out) { out.println(line); out.flush(); }
}))) return;
long token = host.token();
Thread guard = new Thread(() -> ensureClientSink(out, token), "pulse-sink-guard");
});
Thread guard = new Thread(() -> ensureClientSink(out), "pulse-sink-guard");
guard.setDaemon(true);
guard.start();
}
private void ensureClientSink(java.io.PrintWriter out, long token) {
private void ensureClientSink(java.io.PrintWriter out) {
try {
// Nothing that may block (a sink whose AAudio open hangs: a Galaxy S24 FE (US) hung the
// daemon's start-up loading one from default.pa) is loaded by the daemon itself; the
@@ -198,14 +137,14 @@ public class PulseAudioComponent extends SessionPart {
long deadline = started + 30000L;
String sinks = null;
boolean socketSeen = false;
while (System.currentTimeMillis() < deadline && host.live(token)) {
while (System.currentTimeMillis() < deadline && pid > 1) {
socketSeen |= socket().exists();
if (socketSeen && (sinks = pactlFor(token, "list", "short", "sinks")) != null) break;
if (socketSeen && (sinks = pactl("list", "short", "sinks")) != null) break;
try { Thread.sleep(250L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
}
note(out, "client sink: daemon " + (sinks != null ? "answered" : "did not answer") + " after "
+ (System.currentTimeMillis() - started) + " ms (socket " + (socketSeen ? "present" : "never appeared") + ", pactl "
+ (new File(workingDir, "pactl").isFile() ? "present" : "MISSING") + ", daemon pid " + host.pid + ")");
+ (new File(workingDir, "pactl").isFile() ? "present" : "MISSING") + ", daemon pid " + pid + ")");
String line;
if (sinks == null) {
line = "== client sink: the daemon did not answer in 30 s; no fallback attempted";
@@ -216,15 +155,15 @@ public class PulseAudioComponent extends SessionPart {
// still switching the output route as the session starts (seen on a Galaxy S24 FE):
// try DirectAudio again, then the plain sink, a few times over ten seconds.
String loadedAs = null;
for (int attempt = 1; attempt <= 5 && loadedAs == null && host.live(token); attempt++) {
for (int attempt = 1; attempt <= 5 && loadedAs == null && pid > 1; attempt++) {
try { Thread.sleep(2000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
if (pactlFor(token, "load-module", "module-directaudio-native-sink", "sink_name=DirectAudio", "performance_mode=1",
if (pactl("load-module", "module-directaudio-native-sink", "sink_name=DirectAudio", "performance_mode=1",
"adaptive=1", "decay=0", "limiter=1", "watchdog=1", "volume=1.0", "control_dir=" + deviceControls) != null
&& pactlFor(token, "set-default-sink", "DirectAudio") != null) {
&& pactl("set-default-sink", "DirectAudio") != null) {
loadedAs = "DirectAudio on attempt " + attempt;
} else if (pactlFor(token, "load-module", "module-aaudio-sink", "sink_name=AAudioSink",
} else if (pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink",
"performance_mode=" + (attempt == 1 ? "1" : "0"), "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) != null
&& pactlFor(token, "set-default-sink", "AAudioSink") != null) {
&& pactl("set-default-sink", "AAudioSink") != null) {
loadedAs = "the plain AAudio sink (AAudioSink) on attempt " + attempt;
}
}
@@ -247,14 +186,10 @@ public class PulseAudioComponent extends SessionPart {
if (out != null) synchronized (out) { out.println(line); out.flush(); }
}
private String pactlFor(long token, String... args) {
return host.live(token) ? pactl(args) : null;
}
/** Runs pactl against this daemon; its stdout, or null when it failed or timed out. */
private String pactl(String... args) {
File pactl = new File(workingDir, "pactl");
if (!pactl.isFile() || host.pid <= 1) return null;
if (!pactl.isFile() || pid <= 1) return null;
java.lang.Process process = null;
try {
File modules = new File(workingDir, "modules/arm64");
@@ -296,7 +231,10 @@ public class PulseAudioComponent extends SessionPart {
@Override
public void stop() {
host.stop();
if (pid != -1) {
Process.killProcess(pid);
pid = -1;
}
}
public boolean setSinkSuspended(boolean suspended) {
@@ -309,7 +247,7 @@ public class PulseAudioComponent extends SessionPart {
private boolean suspend(String kind, String name, boolean suspended) {
File pactl = new File(workingDir, "pactl");
if (!pactl.isFile() || host.pid <= 1) {
if (!pactl.isFile() || pid <= 1) {
Log.w(TAG, "cannot change " + kind + " state: PulseAudio control client or server unavailable");
return false;
}
@@ -233,10 +233,6 @@ object DeviceReport {
else "${turnip.displayName(displayId)} ${turnip.driverVersion(displayId)}".trim()
k("Display driver (chosen)", if (androidChoice.isEmpty()) "Auto -> $displayLabel" else androidChoice)
k(" name / version", displayLabel)
turnip.effectiveId().takeIf { it != displayId }?.let { used ->
k(" in use", if (used == "system") DeviceInfo.builtinDriverLabel(SystemVulkanDriver.isPowerVr(), runtime = false)
else "${turnip.displayName(used)} ${turnip.driverVersion(used)}".trim())
}
k(" imported available", turnip.enumerateImported().ifEmpty { listOf("none") }.joinToString(", "))
val lm = LinuxVulkanDriverManager(context)
run {
@@ -246,9 +242,7 @@ object DeviceReport {
lm.getMinGlibc(id).let { if (it.isEmpty()) "" else " (glibc $it+)" } +
if (lm.isInstalled(id)) "" else if (SystemVulkanDriver.isPowerVr()) " [MISSING - select an installed driver or Auto]"
else " [MISSING - falls back to the runtime's own]"
val route = DeviceInfo.hostRoute(context)
k("Linux driver", route ?: label)
if (route != null) k(" chosen, not used", label)
k("Linux driver", label)
}
k("Runtime's own ICD", LinuxRuntime.vulkanIcd(context)?.path)
k("Mali (Venus)", if (com.droiddeck.launcher.session.VenusComponent.wanted(context)) "in use"
@@ -296,8 +290,6 @@ object DeviceReport {
k("Microphone", SessionPrefs.micEnabled(context))
k("On-screen controls", SessionPrefs.oscMode(context))
k("Touch mode", SessionPrefs.touchMode(context))
k("Pen mode", SessionPrefs.penMode(context))
k("Pen side button", SessionPrefs.penButton(context))
k("Performance HUD", SessionPrefs.hudEnabled(context))
k("Game storage", when (val g = SessionPrefs.gameStorage(context)) {
"" -> "automatic (" + (com.droiddeck.launcher.session.GameStorage.effective(context)?.path ?: "no card present") + ")"
@@ -18,7 +18,7 @@ object SessionLogCapture {
private var syncer: Thread? = null
@Synchronized
fun start(target: File, sinceMillis: Long) {
fun start(target: File) {
stop()
try {
val out = target.bufferedWriter()
@@ -28,7 +28,7 @@ object SessionLogCapture {
writer = out
this.target = target
pid = HostProcess.start(
command(Process.myPid(), sinceMillis),
"/system/bin/logcat -v threadtime -T 1 --pid=" + Process.myPid(),
null, target.parentFile, null,
) { line ->
synchronized(this) {
@@ -49,11 +49,6 @@ object SessionLogCapture {
}
}
internal fun command(pid: Int, sinceMillis: Long): String {
val since = if (sinceMillis > 0) "%d.%03d".format(java.util.Locale.US, sinceMillis / 1000, sinceMillis % 1000) else "1"
return "/system/bin/logcat -v threadtime -T $since --pid=$pid"
}
@Synchronized
fun stopFor(dir: File) {
val t = target ?: return
@@ -0,0 +1,11 @@
package com.droiddeck.launcher.core
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
class ShortcutsListingReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == Intent.ACTION_MY_PACKAGE_REPLACED) SteamIntegration.syncShortcutsListing(context)
}
}
@@ -1,21 +1,20 @@
package com.droiddeck.launcher.core
import android.accessibilityservice.AccessibilityServiceInfo
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.Settings
import android.view.accessibility.AccessibilityManager
import com.droiddeck.launcher.HomeApp
import com.droiddeck.launcher.input.HomeButtonService
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.shortcuts.Relay
import java.io.File
object SteamIntegration {
const val ACTION_SETUP = "com.droiddeck.launcher.STEAM_INTEGRATION"
const val EXTRA_FEATURE = "integration_feature"
const val SHORTCUTS_STATUS = "com.droiddeck.launcher.SHORTCUTS_INSTALL_STATUS"
private const val SHORTCUTS_ASSET = "shortcuts.apk"
enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS }
data class State(
@@ -37,7 +36,11 @@ object SteamIntegration {
locationOn = WifiDiscovery.locationEnabled(context),
brightness = Settings.System.canWrite(context),
home = HomeApp.isDefault(context),
shortcuts = shortcutsEnabled(context),
shortcuts = context.getSystemService(AccessibilityManager::class.java)
.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK).any {
val service = it.resolveInfo.serviceInfo
ComponentName(service.packageName, service.name) == ComponentName(context, HomeButtonService::class.java)
},
shortcutsRestricted = restrictedSettings(context),
suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false),
)
@@ -45,53 +48,48 @@ object SteamIntegration {
private fun restrictedSettings(context: Context): Boolean {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return false
val mode = runCatching {
val uid = context.packageManager.getApplicationInfo(Relay.PACKAGE, 0).uid
context.getSystemService(android.app.AppOpsManager::class.java)
.unsafeCheckOpNoThrow("android:access_restricted_settings", uid, Relay.PACKAGE)
.unsafeCheckOpNoThrow("android:access_restricted_settings", android.os.Process.myUid(), context.packageName)
}.getOrDefault(android.app.AppOpsManager.MODE_ALLOWED)
return mode == android.app.AppOpsManager.MODE_ERRORED || mode == android.app.AppOpsManager.MODE_IGNORED
}
private val shortcutsComponent = ComponentName(Relay.PACKAGE, Relay.SERVICE)
private fun shortcutsComponent(context: Context) = ComponentName(context, HomeButtonService::class.java)
fun shortcutsEnabled(context: Context): Boolean {
fun shortcutsChosen(context: Context): Boolean = shortcutsSelection(context) == true
private fun shortcutsSelection(context: Context): Boolean? {
val target = shortcutsComponent(context)
val enabled = runCatching {
Settings.Secure.getString(context.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES)
}.getOrNull().orEmpty()
return enabled.split(':').any { ComponentName.unflattenFromString(it.trim()) == shortcutsComponent }
}.getOrElse { return null }.orEmpty()
return enabled.split(':').any { ComponentName.unflattenFromString(it.trim()) == target }
}
fun shortcutsListed(context: Context): Boolean =
context.getSystemService(android.view.accessibility.AccessibilityManager::class.java)
?.installedAccessibilityServiceList.orEmpty()
.any { ComponentName(it.resolveInfo.serviceInfo.packageName, it.resolveInfo.serviceInfo.name) == shortcutsComponent }
fun bundledShortcuts(context: Context): File {
val target = File(context.cacheDir, SHORTCUTS_ASSET)
context.assets.open(SHORTCUTS_ASSET).use { input -> target.outputStream().use { input.copyTo(it) } }
return target
}
fun shortcutsInstalled(context: Context, bundled: File): Boolean {
fun setShortcutsListed(context: Context, listed: Boolean) {
val packages = context.packageManager
@Suppress("DEPRECATION")
val installed = runCatching { packages.getPackageInfo(Relay.PACKAGE, 0).versionCode }.getOrNull() ?: return false
@Suppress("DEPRECATION")
val shipped = packages.getPackageArchiveInfo(bundled.absolutePath, 0)?.versionCode ?: return true
return installed >= shipped
val component = shortcutsComponent(context)
val state = if (listed) PackageManager.COMPONENT_ENABLED_STATE_ENABLED else PackageManager.COMPONENT_ENABLED_STATE_DISABLED
runCatching {
if (packages.getComponentEnabledSetting(component) != state) {
packages.setComponentEnabledSetting(component, state, PackageManager.DONT_KILL_APP)
}
}
}
fun syncShortcutsListing(context: Context) {
shortcutsSelection(context)?.let { setShortcutsListed(context, it) }
}
fun dismissSuggestion(context: Context) {
SessionPrefs.sessionPrefs(context).edit().putBoolean("steam_integration_seen", true).apply()
}
fun shortcutsAppInfo() = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${Relay.PACKAGE}"))
fun brightnessSettings(context: Context) = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
Uri.parse("package:${context.packageName}"))
fun shortcutSettings(context: Context): Intent {
val service = shortcutsComponent.flattenToString()
val service = ComponentName(context, HomeButtonService::class.java).flattenToString()
return Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
.putExtra(":settings:fragment_args_key", service)
.putExtra(":settings:show_fragment_args", android.os.Bundle().apply { putString(":settings:fragment_args_key", service) })
@@ -112,10 +112,6 @@ private const val HISTORY_LIMIT = 50
internal fun canNavigateUp(currentDir: File, currentRoot: File): Boolean =
currentDir != currentRoot && currentDir.parentFile?.exists() == true
// Back leaves after a drive hop instead of replaying a stack of hops one press at a time.
internal fun backExitsAtRootHop(currentDir: File, currentRoot: File, previous: Pair<File, File>): Boolean =
currentDir == currentRoot && previous.first == previous.second
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FileManagerScreen(
@@ -273,10 +269,8 @@ fun FileManagerScreen(
if (showFavorites) showFavorites = false
else {
while (history.isNotEmpty() && !history.last().first.isDirectory) history.removeAt(history.lastIndex)
val previous = history.lastOrNull()
if (previous != null && backExitsAtRootHop(currentDir, currentRoot, previous)) onExit?.invoke()
else if (previous != null) {
history.removeLastOrNull()
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) }
@@ -43,14 +43,11 @@ object GameFileSync {
val storageSetting = SessionPrefs.gameStorage(context)
val previousStorage = prefs(context).getString("storagePath", null)
if (storageSetting.isEmpty() && prefs(context).getString("storageSetting", null) == storageSetting && previousStorage != null) {
check(libraryReadable(File(previousStorage))) { context.getString(R.string.game_sync_err_previous_sd) }
check(File(previousStorage).isDirectory) { context.getString(R.string.game_sync_err_previous_sd) }
}
storage?.let { check(libraryReadable(File(it.path))) { context.getString(R.string.game_sync_err_game_storage) } }
storage?.let { check(File(it.path).listFiles() != null) { context.getString(R.string.game_sync_err_game_storage) } }
AddedGames.roots(context).forEach { check(it.host.listFiles() != null) { context.getString(R.string.game_sync_err_added_games) } }
GameFiles.sync(context, folder, Library.launchableGames(context, strictRead = true))
prefs(context).edit().putString("storageSetting", storageSetting).putString("storagePath", storage?.path).apply()
}
internal fun libraryReadable(dir: File): Boolean =
dir.listFiles() != null || (!dir.exists() && dir.parentFile?.isDirectory == true)
}
@@ -563,7 +563,7 @@ object Glasses {
val device = selected?.first
val m = selected?.second
val controllable = m?.let(::canOpenModel) == true
val permitted = controllable && device != null && (m is XrealModel || usb.hasPermission(device))
val permitted = controllable && device != null && (m === XrealModel || usb.hasPermission(device))
val identity = device?.let {
GlassesModeState.Device(it.productId, if (permitted) runCatching { it.serialNumber }.getOrNull() else null)
}
@@ -614,9 +614,9 @@ object Glasses {
sbs = sbsByDisplay,
switching3d = modeState.pendingStereo,
brightnessMax = m?.brightnessMax ?: 8, volumeMax = m?.volumeMax ?: 8,
sunblock = if (m is XrealModel) it.sunblock else _settings.value.sunblock ?: it.sunblock,
sunblock = if (m === XrealModel) it.sunblock else _settings.value.sunblock ?: it.sunblock,
hardwareControls = m?.hardwareControls == true &&
(device?.vendorId == VitureProtocol.VENDOR_ID || m is XrealModel || m is RokidModel),
(device?.vendorId == VitureProtocol.VENDOR_ID || m === XrealModel || m is RokidModel),
supportsDisplayModeControl = m?.supportsDisplayModeControl == true,
hasSunblock = m?.hasSunblock == true,
diagonalFovDeg = m?.diagonalFovDeg ?: 46f,
@@ -624,7 +624,7 @@ object Glasses {
noSignal = noSignal,
sbs90 = m?.sbs90 == true,
rates2d = m?.rates2d ?: listOf(60, 90, 120),
experimental = m is XrealModel || (m is VitureProtocol.Model && m.family == VitureProtocol.Family.PRO2 && !m.needsSdk),
experimental = m === XrealModel || (m is VitureProtocol.Model && m.family == VitureProtocol.Family.PRO2 && !m.needsSdk),
supportsScreen3dof = link?.hasImu == true,
supports30Hz = display?.let(::supports30Hz) == true,
supportsSpatial = (link as? VitureSdkLink)?.isCarina == true,
@@ -660,8 +660,8 @@ object Glasses {
else VitureSdk.marketName(device.productId)?.let(VitureProtocol::sdkModel)
?: VitureProtocol.model(device.productId, name)
}
else XrealModel.model(device.vendorId, device.productId)
?: RokidModel.model(device.vendorId, device.productId, name)
else if (XrealModel.matches(device.vendorId, device.productId)) XrealModel
else RokidModel.model(device.vendorId, device.productId, name)
?: RayNeoModel.model(device.vendorId, device.productId, name)
}
@@ -729,8 +729,8 @@ object Glasses {
VitureSdkLink.open(usb, device, File(app.noBackupFilesDir, "viture"), sdkListener(generation),
(model as? VitureProtocol.Model)?.family, spatial)
} else VitureLink.open(usb, device, linkListener(generation))
} else if (model is XrealModel) {
XrealLink.open(app, model as XrealModel, xrealListener(generation))
} else if (model === XrealModel) {
XrealLink.open(app, xrealListener(generation))
} else if (model is RokidModel) {
RokidLink.open(usb, device, rokidListener(generation))
} else {
@@ -10,7 +10,6 @@ import java.util.concurrent.atomic.AtomicReference
internal class XrealLink internal constructor(
private val connector: XrealConnector,
private val listener: Listener,
private val model: XrealModel = XrealModel.ONE_S,
) : GlassesLink {
interface Listener {
fun onReady()
@@ -30,8 +29,7 @@ internal class XrealLink internal constructor(
private val worker = Thread(::run, "xreal-control").apply { isDaemon = true; start() }
companion object {
fun open(context: Context, model: XrealModel, listener: Listener) =
XrealLink(AndroidXrealConnector(context), listener, model)
fun open(context: Context, listener: Listener) = XrealLink(AndroidXrealConnector(context), listener)
}
override fun send(msgId: Int, payload: ByteArray): Boolean {
@@ -45,10 +43,9 @@ internal class XrealLink internal constructor(
if (msgId == VitureProtocol.MSG_GET_IMU) return true
val valid = when (msgId) {
VitureProtocol.MSG_GET_DISPLAY -> true
VitureProtocol.MSG_DISPLAY -> if (model.stereoOnlyControl) value == 5 || value == XrealModel.NATIVE_60HZ
else value in 2..5 || value == XrealModel.NATIVE_60HZ
VitureProtocol.MSG_BRIGHTNESS -> !model.stereoOnlyControl && value in 0..9
VitureProtocol.MSG_FILM -> !model.stereoOnlyControl && value in 0..1
VitureProtocol.MSG_DISPLAY -> value in 2..5 || value == XrealModel.NATIVE_60HZ
VitureProtocol.MSG_BRIGHTNESS -> value in 0..9
VitureProtocol.MSG_FILM -> value in 0..1
else -> false
}
return valid && commands.offer(Command(msgId, value))
@@ -64,12 +61,12 @@ internal class XrealLink internal constructor(
channels = connector.connect()
connection.set(channels)
if (!running) break
val control = XrealControl(channels, stereoOnly = model.stereoOnlyControl)
val control = XrealControl(channels)
listener.onValue(VitureProtocol.MSG_GET_DISPLAY, control.display())
val current = channels
reports = Thread({
try {
var filter = XrealOrientationFilter(model.flipsYz)
var filter = XrealOrientationFilter()
var wasTracking = false
var lastSensor = System.nanoTime()
while (running && connection.get() === current) {
@@ -78,7 +75,7 @@ internal class XrealLink internal constructor(
if (sample != null) {
lastSensor = System.nanoTime()
val enabled = tracking
if (enabled && !wasTracking) filter = XrealOrientationFilter(model.flipsYz)
if (enabled && !wasTracking) filter = XrealOrientationFilter()
wasTracking = enabled
if (enabled) filter.update(sample)?.let {
if (running && ready && tracking && connection.get() === current)
@@ -152,11 +149,7 @@ internal class XrealLink internal constructor(
}
}
internal class XrealControl(
private val channels: XrealChannels,
private val settleDelayMs: Long = 150,
private val stereoOnly: Boolean = false,
) {
internal class XrealControl(private val channels: XrealChannels, private val settleDelayMs: Long = 150) {
private var transaction = 0
private fun exchange(command: Int, value: Int? = null): ByteArray {
transaction = if (transaction == Int.MAX_VALUE) 1 else transaction + 1
@@ -170,42 +163,26 @@ internal class XrealControl(
throw IOException("XREAL control response was not received")
}
fun display(): Int {
if (stereoOnly) return stereoDisplay()
val reply = exchange(XrealProtocol.GET_DISPLAY)
return XrealProtocol.numeric(reply)?.takeIf { it in 2..5 || it == XrealModel.NATIVE_60HZ }
?: throw IOException("Unsupported XREAL display response: ${reply.take(32).joinToString("") { "%02x".format(it) }}")
}
private fun stereoDisplay(): Int {
val reply = exchange(XrealProtocol.GET_INPUT)
return when {
XrealProtocol.acknowledged(reply) -> XrealModel.NATIVE_60HZ
else -> when (XrealProtocol.numeric(reply)) {
0 -> XrealModel.NATIVE_60HZ
1 -> 5
else -> throw IOException("Unsupported XREAL stereo response: ${reply.take(32).joinToString("") { "%02x".format(it) }}")
}
}
}
fun changeDisplay(mode: Int): Int {
val stereo = mode == 5
set(XrealProtocol.SET_INPUT, if (stereo) 1 else 0)
val current = awaitDisplay { (it == 5) == stereo }
if (current == mode || stereoOnly) return current
if (current == mode) return current
set(XrealProtocol.SET_DISPLAY, mode)
return awaitDisplay { it == mode }
}
private fun awaitDisplay(matches: (Int) -> Boolean): Int {
val deadline = System.nanoTime() + 8_000_000_000L
repeat(40) {
if (stereoOnly) {
stereoDisplay().let { if (matches(it)) return it }
} else {
val reply = exchange(XrealProtocol.GET_DISPLAY)
val value = XrealProtocol.numeric(reply)
if (value != null && matches(value)) return value
if (value == null && !XrealProtocol.acknowledged(reply))
throw IOException("Invalid XREAL display transition response")
}
val reply = exchange(XrealProtocol.GET_DISPLAY)
val value = XrealProtocol.numeric(reply)
if (value != null && matches(value)) return value
if (value == null && !XrealProtocol.acknowledged(reply))
throw IOException("Invalid XREAL display transition response")
if (System.nanoTime() > deadline) throw IOException("XREAL display transition timed out")
Thread.sleep(settleDelayMs)
}
@@ -1,63 +1,25 @@
package com.droiddeck.launcher.glasses
internal class XrealModel private constructor(
override val name: String,
val family: Family,
override val diagonalFovDeg: Float,
) : GlassesModel {
enum class Family {
ONE_S,
ONE,
AURA,
}
object XrealModel : GlassesModel {
const val VENDOR_ID = 0x3318
const val PRODUCT_1S = 0x043e
const val NATIVE_60HZ = 29
override val name = "XREAL 1S"
override val controllable = true
override val brightnessMax = 9
override val volumeMax = 0
override val hasSunblock get() = family == Family.ONE_S
override val hardwareControls get() = family == Family.ONE_S
override val hasSunblock = true
override val diagonalFovDeg = 52f
override val sbs90 = false
override val rates2d get() = if (family == Family.ONE_S) super.rates2d else listOf(60)
// Only the 1S has been exercised with SET_DISPLAY; the Aura is known to reboot on an unexpected index.
val stereoOnlyControl get() = family != Family.ONE_S
// The Aura reports x right, y up, z back; the rest of the One family is a half turn about x from it.
val flipsYz get() = family != Family.AURA
fun matches(vid: Int, pid: Int) = vid == VENDOR_ID && pid == PRODUCT_1S
fun isDisplay(name: String) = name.contains("XREAL", ignoreCase = true)
override fun mode(hz: Int, sbs: Boolean) = when {
sbs -> 5
stereoOnlyControl -> NATIVE_60HZ
hz >= 120 -> 4
hz >= 90 -> 3
else -> NATIVE_60HZ
}
override fun modeForStep(step: Int): Int? = null
override fun toString() = name
companion object {
const val VENDOR_ID = 0x3318
const val PRODUCT_1S = 0x043e
const val NATIVE_60HZ = 29
val ONE_S = XrealModel("XREAL 1S", Family.ONE_S, 52f)
val ONE = XrealModel("XREAL One", Family.ONE, 50f)
val ONE_PRO = XrealModel("XREAL One Pro", Family.ONE, 57f)
val ONE_PRO_PLUS = XrealModel("XREAL One Pro+", Family.ONE, 57f)
val AURA = XrealModel("XREAL Aura", Family.AURA, 70f)
// The odd product ids one below these are the glasses' recovery mode.
private val products = mapOf(
PRODUCT_1S to ONE_S,
0x0438 to ONE,
0x0436 to ONE_PRO,
0x0444 to ONE_PRO_PLUS,
0x043a to AURA,
)
fun model(vid: Int, pid: Int): XrealModel? = if (vid == VENDOR_ID) products[pid] else null
fun matches(vid: Int, pid: Int) = model(vid, pid) != null
fun isDisplay(name: String) = name.contains("XREAL", ignoreCase = true)
}
}
@@ -2,13 +2,12 @@ package com.droiddeck.launcher.glasses
import kotlin.math.abs
internal class XrealOrientationFilter(private val flipYz: Boolean = true) {
internal class XrealOrientationFilter {
private val fusion = ImuFusion()
fun update(sample: XrealProtocol.Sample): FloatArray? = fusion.update(sample.timeNs,
sample.accel.headAxes(), sample.gyro.headAxes())
private fun Vec3.headAxes() = if (flipYz) Vec3(x, -y, -z) else this
Vec3(sample.accel.x, -sample.accel.y, -sample.accel.z),
Vec3(sample.gyro.x, -sample.gyro.y, -sample.gyro.z))
}
internal class ImuFusion {
@@ -13,7 +13,6 @@ internal object XrealProtocol {
const val REPORT = 0x2836
const val GET_DISPLAY = 0x275e
const val SET_DISPLAY = 0x275f
const val GET_INPUT = 0x2821
const val SET_INPUT = 0x2822
const val SET_BRIGHTNESS = 0x271c
const val SET_DIMMER = 0x2727
@@ -145,22 +145,16 @@ object DeviceInfo {
private fun drivers(context: Context, gpu: GpuInfo) = Section("Drivers DroidDeck uses", buildList<Pair<String, String>> {
add("Driver mode", SessionPrefs.gpuDriverMode(context))
val turnip = TurnipDriver(context)
val choice = turnip.effectiveId()
val choice = SessionPrefs.androidDriver(context).ifEmpty { turnip.autoId() }
val powerVr = gpu.family == GpuInfo.Family.POWERVR
add("Display driver", if (choice == "system") builtinDriverLabel(powerVr, runtime = false)
else "${turnip.displayName(choice)} ${turnip.driverVersion(choice)}".trim())
val linux = LinuxVulkanDriverManager(context)
val id = SessionPrefs.linuxDriver(context)
add("Game driver", hostRoute(context) ?: if (id.isEmpty()) builtinDriverLabel(powerVr, runtime = true) else "${linux.getDriverName(id)} ${linux.getDriverVersion(id)}".trim())
add("Game driver", if (id.isEmpty()) builtinDriverLabel(powerVr, runtime = true) else "${linux.getDriverName(id)} ${linux.getDriverVersion(id)}".trim())
if (gpu.oneUi8Gen2) add("Note", "One UI on an 8 Gen 2: needs the OneUI Turnip build")
})
internal fun hostRoute(context: Context): String? = when {
com.droiddeck.launcher.session.VenusComponent.wanted(context) -> "Mali (Venus)"
com.droiddeck.launcher.core.DeviceSupport.vkBridge(context) -> "the Mali bridge"
else -> null
}
/** Shared by the device card and the session report, which are written in English. */
internal fun builtinDriverLabel(powerVr: Boolean, runtime: Boolean): String = when {
powerVr -> "System PowerVR"
@@ -34,8 +34,6 @@ public final class TurnipDriver {
public static final List<String> BUNDLED = Collections.unmodifiableList(Arrays.asList(
DRIVER_A7XX, DRIVER_A8XX, com.droiddeck.launcher.session.QuestExperimental.DRIVER,
DRIVER_A6XX, com.droiddeck.launcher.session.QuestExperimental.DRIVER_A6XX));
private static final String KGSL_NODE = "/dev/kgsl-3d0";
private static final String KGSL_SYSFS = "/sys/class/kgsl/kgsl-3d0";
private static final String OVERRIDE_FILE = "Download/droiddeck-driver";
private static final String PREFS = "graphics_driver";
private static final String KEY_HIDDEN = "hiddenBundled";
@@ -142,25 +140,6 @@ public final class TurnipDriver {
return id == null ? "system" : id;
}
public String effectiveId() {
String id = choose();
return id == null || !reachesGpu(id) ? "system" : id;
}
public boolean reachesGpu(String driverId) {
String library = libraryName(driverId);
return library == null || !needsMissingKgsl(new File(new File(contentDir, driverId), library),
kgslPresent(new File(KGSL_NODE), new File(KGSL_SYSFS)));
}
static boolean kgslPresent(File node, File sysfs) {
return node.exists() || sysfs.exists();
}
static boolean needsMissingKgsl(File library, boolean kgsl) {
return !kgsl && library.isFile() && LinuxVulkanDriverManager.containsAscii(library, KGSL_NODE);
}
public void remove(String driverId) {
if (driverId == null || driverId.isEmpty() || BUNDLED.contains(driverId)
|| driverId.contains("/") || driverId.contains("..")) return;
@@ -278,11 +257,6 @@ public final class TurnipDriver {
Log.e(TAG, id + " unpacked without " + library);
return null;
}
if (!reachesGpu(id)) {
Log.w(TAG, id + " needs " + KGSL_NODE + ", which this GPU does not have; display on the system Vulkan loader");
DriverSetupLog.write(context, "install.no-kgsl driver=" + id);
return null;
}
Log.i(TAG, "graphics driver " + id + " (" + library + ")");
DriverSetupLog.write(context, "install.ready driver=" + id + " library=" + library);
return id;
@@ -308,12 +282,6 @@ public final class TurnipDriver {
}
}
if (chosen != null && !chosen.isEmpty()) {
if (SessionPrefs.GPU_DRIVERS_AUTO.equals(SessionPrefs.INSTANCE.gpuDriverMode(context))
&& SessionPrefs.INSTANCE.gpuAutoInstalled(context).contains(chosen)
&& gpuDetector.get().getFamily() == GpuInfo.Family.A7XX_LOW) {
Log.i(TAG, "Auto-selected display driver does not cover Adreno 710/720/722; leaving the display driver to the system");
return null;
}
if (BUNDLED.contains(chosen)) {
Log.i(TAG, "driver pinned by the user: " + chosen);
return chosen;
@@ -350,10 +318,6 @@ public final class TurnipDriver {
Log.i(TAG, "not an Adreno GPU; leaving the display driver to the system");
return null;
}
if (gpu.getFamily() == GpuInfo.Family.A7XX_LOW) {
Log.i(TAG, "no bundled display driver covers Adreno 710/720/722; leaving the display driver to the system");
return null;
}
int model = gpu.getModel();
Log.i(TAG, "gpu model: " + (model == 0 ? "unknown" : model));
return chooseByModel(model, android.os.Build.VERSION.SDK_INT);
@@ -1,115 +0,0 @@
package com.droiddeck.launcher.input
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.util.zip.ZipInputStream
internal object ArmsControlSkins {
private val buttons = mapOf(
InputControl.A to "cross", InputControl.B to "circle", InputControl.X to "square", InputControl.Y to "triangle",
InputControl.LB to "l1", InputControl.RB to "r1", InputControl.LT to "l2", InputControl.RT to "r2",
InputControl.L3 to "l3", InputControl.R3 to "r3", InputControl.SELECT to "select", InputControl.START to "start",
InputControl.UP to "up", InputControl.DOWN to "down", InputControl.LEFT to "left", InputControl.RIGHT to "right")
private val keys = buttons.values.toSet() + setOf("analog_base", "analog_stick", "analog_base_left", "analog_base_right",
"analog_stick_left", "analog_stick_right")
fun parse(context: android.content.Context, bytes: ByteArray, original: SavedInputLayout, actions: SavedInputBindings, name: String, nativeFailure: Exception? = null): CommunityControls.Pack {
require(bytes.size <= 32 * 1024 * 1024 && original.editable && actions.compatible(original))
val art = linkedMapOf<String, ByteArray>()
var total = 0
var entries = 0
ZipInputStream(ByteArrayInputStream(bytes)).use { zip ->
while (true) {
val entry = zip.nextEntry ?: break
require(++entries <= 256 && ControlSources.validPath(entry.name.trimEnd('/'))) { "Invalid skin archive path or file count." }
if (entry.isDirectory) continue
val data = CommunityControls.readLimited(zip, minOf(8 * 1024 * 1024, 64 * 1024 * 1024 - total))
total += data.size
if (entry.name == "controls.json") throw (nativeFailure ?: IllegalArgumentException("Import this file as a DroidDeck controls pack."))
val file = entry.name.substringAfterLast('/').lowercase()
if (file.startsWith("._") || !file.endsWith(".png")) continue
val key = file.removeSuffix(".png").removePrefix("ic_controller_").removeSuffix("_button")
if (key !in keys) continue
require(key !in art) { "Duplicate skin button artwork." }
art[key] = normalize(data)
}
}
require(art.isNotEmpty()) { "No supported controller PNGs found in this skin." }
val used = linkedMapOf<String, ByteArray>()
fun image(key: String): String? = art[key]?.let { data ->
val file = "skin_$key.png"
used[file] = data
file
}
var matched = 0
val elements = original.elements.map { e ->
val action = actions.action(e) as? InputAction.Native ?: return@map e
val control = action.target ?: e.control
if (e.kind == InputElementKind.STICK && (control == InputControl.LS || control == InputControl.RS)) {
val side = if (control == InputControl.LS) "left" else "right"
val base = image("analog_base_$side") ?: image("analog_base")
val stick = image("analog_stick_$side") ?: image("analog_stick")
if (base == null && stick == null) e else {
matched++
e.copy(image = base ?: e.image, stickImage = stick ?: e.stickImage, showLabel = false)
}
} else if (e.kind == InputElementKind.BUTTON || e.kind == InputElementKind.TRIGGER) {
val file = buttons[control]?.let(::image)
if (file == null) e else { matched++; e.copy(image = file, icon = 0, showLabel = false) }
} else e
}
require(matched > 0) { "This layout has no matching gamepad controls. Choose a gamepad profile and screen." }
val id = newInputId()
val label = name.trim().take(80).ifBlank { "Imported controller skin" }
val layout = original.copy(id = id, name = label, origin = null, elements = elements)
for (file in elements.flatMap { listOf(it.image, it.stickImage) }.filter { it.isNotEmpty() }.distinct()) {
if (file !in used) used[file] = requireNotNull(InputButtonImages.file(context, file)).inputStream().use {
CommunityControls.readLimited(it, 1024 * 1024)
}
}
return CommunityControls.Pack(layout, actions.copy(id = newInputId(), name = label, layoutId = id), used)
}
fun export(context: android.content.Context, layout: SavedInputLayout, actions: SavedInputBindings): ByteArray {
val images = linkedMapOf<String, String>()
for (element in layout.elements) {
val action = actions.action(element) as? InputAction.Native ?: continue
val control = action.target ?: element.control
if (element.kind == InputElementKind.STICK && (control == InputControl.LS || control == InputControl.RS)) {
val side = if (control == InputControl.LS) "left" else "right"
if (element.image.isNotEmpty()) images["ic_controller_analog_base_$side.png"] = element.image
if (element.stickImage.isNotEmpty()) images["ic_controller_analog_stick_$side.png"] = element.stickImage
} else if (element.image.isNotEmpty()) {
buttons[control]?.let { images["ic_controller_${it}_button.png"] = element.image }
}
}
require(images.isNotEmpty()) { "This layout has no controller skin artwork to export." }
val output = ByteArrayOutputStream()
java.util.zip.ZipOutputStream(output).use { zip ->
for ((name, local) in images) {
val bytes = requireNotNull(InputButtonImages.file(context, local)).inputStream().use {
CommunityControls.readLimited(it, 1024 * 1024)
}
zip.putNextEntry(java.util.zip.ZipEntry(name)); zip.write(bytes); zip.closeEntry()
}
}
return output.toByteArray().also { require(it.size <= 32 * 1024 * 1024) }
}
private fun normalize(data: ByteArray): ByteArray {
require(data.take(8) == listOf<Byte>(-119, 80, 78, 71, 13, 10, 26, 10)) { "Invalid skin PNG." }
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(data, 0, data.size, bounds)
require(bounds.outWidth in 1..8192 && bounds.outHeight in 1..8192) { "Invalid skin image dimensions." }
val options = BitmapFactory.Options().apply {
inSampleSize = 1
while (maxOf(bounds.outWidth, bounds.outHeight) / inSampleSize > 512) inSampleSize *= 2
}
val bitmap = requireNotNull(BitmapFactory.decodeByteArray(data, 0, data.size, options)) { "Unreadable skin image." }
return try {
ByteArrayOutputStream().also { check(bitmap.compress(Bitmap.CompressFormat.PNG, 100, it)) }.toByteArray()
} finally { bitmap.recycle() }
}
}
@@ -1,8 +1,10 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.AccessibilityServiceInfo
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Rect
import android.hardware.display.DisplayManager
import android.os.Build
import android.os.Handler
@@ -10,9 +12,9 @@ import android.os.HandlerThread
import android.os.SystemClock
import android.util.Log
import android.view.Display
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityWindowInfo
import android.view.inputmethod.InputMethodManager
import com.droiddeck.shortcuts.Relay
import java.util.concurrent.ConcurrentHashMap
object BottomScreenGuests {
@@ -43,7 +45,7 @@ object BottomScreenGuests {
sdk >= 33 && DualScreen.yieldsBottom(model)
}
class BottomScreenWatch(private val service: Context) {
class BottomScreenWatch(private val service: AccessibilityService) {
private class Arrival(val pkg: String, val at: Long)
private val thread = HandlerThread("bottom-screen").apply { start() }
@@ -55,22 +57,33 @@ class BottomScreenWatch(private val service: Context) {
private var holders: Map<Int, String?> = emptyMap()
private var ownWindows: Map<Int, Set<Int>> = emptyMap()
private val ownShownAt = mutableMapOf<Int, Long>()
private val check = Runnable { evaluate() }
fun start() {
current = this
service.serviceInfo = service.serviceInfo?.apply {
eventTypes = eventTypes or AccessibilityEvent.TYPE_WINDOWS_CHANGED or AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
flags = flags or AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS
}
handler.post {
homes = homePackages()
keyboards = keyboardPackages()
evaluate()
}
}
fun onArrival(displayId: Int, pkg: String, at: Long) {
if (displayId == Display.DEFAULT_DISPLAY || pkg == own || pkg == SYSTEM_UI) return
arrivals[displayId] = Arrival(pkg, at)
}
fun onWindows(all: Map<Int, List<Relay.Window>>) {
handler.post { evaluate(all) }
fun onEvent(event: AccessibilityEvent) {
when (event.eventType) {
AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED -> {
val pkg = event.packageName?.toString() ?: return
if (event.displayId == Display.DEFAULT_DISPLAY || pkg == own || pkg == SYSTEM_UI) return
arrivals[event.displayId] = Arrival(pkg, event.eventTime)
}
AccessibilityEvent.TYPE_WINDOWS_CHANGED -> Unit
else -> return
}
handler.removeCallbacks(check)
handler.postDelayed(check, 150)
}
fun stop() {
@@ -84,22 +97,25 @@ class BottomScreenWatch(private val service: Context) {
thread.quitSafely()
}
private fun evaluate(all: Map<Int, List<Relay.Window>>) {
private fun evaluate() {
val seen = HashMap(arrivals)
val all = runCatching { service.windowsOnAllDisplays }.getOrNull() ?: return
val displays = service.getSystemService(DisplayManager::class.java) ?: return
val taken = mutableMapOf<Int, String?>()
val shown = mutableMapOf<Int, Set<Int>>()
val now = SystemClock.uptimeMillis()
for ((id, list) in all) {
for (i in 0 until all.size()) {
val id = all.keyAt(i)
if (id == Display.DEFAULT_DISPLAY) continue
val display = displays.getDisplay(id)?.takeIf(DualScreen::builtIn) ?: continue
val windows = list
val windows = all.valueAt(i)
.filter { !BottomScreenGuests.ignorable(it.type) && cover(it, display) >= BottomScreenGuests.MIN_COVER }
.sortedByDescending { it.layer }
val ours = windows.filter { it.pkg == own }.map { it.id }.toSet()
.map { it to packageOf(it) }
val ours = windows.filter { it.second == own }.map { it.first.id }.toSet()
if (!ownWindows[id].orEmpty().containsAll(ours)) ownShownAt[id] = now
shown[id] = ours
val topPkg = windows.firstNotNullOfOrNull { it.pkg?.takeUnless { pkg -> pkg == own } }
val topPkg = windows.firstNotNullOfOrNull { it.second?.takeUnless { pkg -> pkg == own } }
val arrival = seen[id]?.takeIf { BottomScreenGuests.current(it.at, ownShownAt[id]) }
seen[id]?.takeIf { topPkg != null || arrival == null }?.let { arrivals.remove(id, it) }
BottomScreenGuests.holder(topPkg, arrival?.pkg?.takeUnless { it in keyboards }, homes)?.let { taken[id] = it }
@@ -111,11 +127,15 @@ class BottomScreenWatch(private val service: Context) {
DualScreen.setTaken(taken.keys)
}
private fun cover(window: Relay.Window, display: Display): Float {
private fun cover(window: AccessibilityWindowInfo, display: Display): Float {
val bounds = Rect().also(window::getBoundsInScreen)
val area = display.mode.physicalWidth.toFloat() * display.mode.physicalHeight
return if (area <= 0f) 0f else window.bounds.width().toFloat() * window.bounds.height() / area
return if (area <= 0f) 0f else bounds.width().toFloat() * bounds.height() / area
}
private fun packageOf(window: AccessibilityWindowInfo): String? =
runCatching { window.getRoot(0)?.packageName?.toString() }.getOrNull()
private fun homePackages(): Set<String> {
val pm = service.packageManager
return listOf(Intent.CATEGORY_HOME, Intent.CATEGORY_SECONDARY_HOME).flatMap { category ->
@@ -134,7 +154,6 @@ class BottomScreenWatch(private val service: Context) {
private companion object {
@Volatile var current: BottomScreenWatch? = null
const val TAG = "BottomScreen"
const val SYSTEM_UI = "com.android.systemui"
}
@@ -1,197 +0,0 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.BitmapFactory
import org.json.JSONObject
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL
import java.security.MessageDigest
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream
import java.util.zip.ZipOutputStream
internal object CommunityControls {
const val MAX_BYTES = 16 * 1024 * 1024
const val BASE = "https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/community/controls/"
const val SUBMIT = "https://github.com/Droid-Deck/DroidDeck/issues/new?template=community-controls.yml"
data class Pack(val layout: SavedInputLayout, val bindings: SavedInputBindings, val images: Map<String, ByteArray>)
data class Entry(val name: String, val author: String, val game: String, val license: String,
val path: String, val sha256: String, val screen: InputLayoutScreen, val preview: String? = null, val bundled: Boolean = false,
val source: ControlSources.Source = ControlSources.DROIDDECK, val skin: Boolean = false) {
val key get() = source.id + "/" + path
}
fun readLimited(input: InputStream, limit: Int = MAX_BYTES): ByteArray {
val output = ByteArrayOutputStream()
val buffer = ByteArray(8192)
while (true) {
val count = input.read(buffer)
if (count < 0) break
require(output.size() + count <= limit) { "Controls file is too large." }
output.write(buffer, 0, count)
}
return output.toByteArray()
}
fun export(context: Context, layout: SavedInputLayout, bindings: SavedInputBindings): ByteArray {
require(layout.editable && bindings.compatible(layout))
val library = InputLibraries.read(context).withLayout(layout).withPreset(bindings)
val doc = JSONObject(InputLibraries.encode(library))
fun item(key: String, id: String): JSONObject {
val array = doc.getJSONArray(key)
return (0 until array.length()).map { array.getJSONObject(it) }.first { it.getString("id") == id }
}
val manifest = JSONObject().put("format", "droiddeck-controls").put("version", 1)
.put("layout", item("layouts", layout.id)).put("bindings", item("bindings", bindings.id))
val output = ByteArrayOutputStream()
ZipOutputStream(output).use { zip ->
fun add(name: String, bytes: ByteArray) {
zip.putNextEntry(ZipEntry(name)); zip.write(bytes); zip.closeEntry()
}
add("controls.json", manifest.toString().toByteArray(Charsets.UTF_8))
for (name in layout.elements.flatMap { listOf(it.image, it.stickImage) }.filter { it.isNotEmpty() }.distinct()) {
val file = requireNotNull(InputButtonImages.file(context, name))
add("images/$name", file.inputStream().use { readLimited(it, 1024 * 1024) })
}
}
return output.toByteArray().also { parse(context, it) }
}
fun parse(context: Context, bytes: ByteArray): Pack {
require(bytes.size <= MAX_BYTES)
val files = linkedMapOf<String, ByteArray>()
var total = 0
ZipInputStream(ByteArrayInputStream(bytes)).use { zip ->
while (true) {
val entry = zip.nextEntry ?: break
require(!entry.isDirectory && files.size < 65 && entry.name !in files)
require(entry.name == "controls.json" || entry.name.matches(Regex("images/[A-Za-z0-9_-][A-Za-z0-9_.-]{0,127}")))
val data = readLimited(zip, minOf(if (entry.name == "controls.json") 2_000_000 else 1024 * 1024, MAX_BYTES - total))
total += data.size
files[entry.name] = data
}
}
val manifest = JSONObject(requireNotNull(files.remove("controls.json")).toString(Charsets.UTF_8))
require(manifest.getString("format") == "droiddeck-controls" && manifest.getInt("version") == 1)
val layout = manifest.getJSONObject("layout")
val bindings = manifest.getJSONObject("bindings")
val layoutId = newInputId()
val bindingId = newInputId()
layout.put("id", layoutId).remove("origin")
require(layout.getString("template") == InputLayoutTemplate.CUSTOM.name)
bindings.put("id", bindingId).put("layout", layoutId)
require(!bindings.getBoolean("physical") && bindings.getJSONArray("keys").length() == 0)
val doc = JSONObject(InputLibraries.encode(InputLibraries.read(context)))
doc.getJSONArray("layouts").put(layout)
doc.getJSONArray("bindings").put(bindings)
val decoded = requireNotNull(InputLibraries.decode(doc.toString())) { "Invalid controls or bindings." }
val saved = decoded.layouts.first { it.id == layoutId }
val names = saved.elements.flatMap { listOf(it.image, it.stickImage) }.filter { it.isNotEmpty() }.toSet()
require(files.keys == names.map { "images/$it" }.toSet()) { "Missing or unexpected button images." }
var pixels = 0L
val images = names.associateWith { name ->
val data = files.getValue("images/$name")
require(data.take(8) == listOf<Byte>(-119, 80, 78, 71, 13, 10, 26, 10))
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(data, 0, data.size, bounds)
require(bounds.outWidth in 1..1024 && bounds.outHeight in 1..1024)
pixels += bounds.outWidth.toLong() * bounds.outHeight
require(pixels <= 16_777_216)
val bitmap = requireNotNull(BitmapFactory.decodeByteArray(data, 0, data.size))
bitmap.recycle()
data
}
return Pack(saved, decoded.preset(bindingId), images)
}
fun importFile(context: Context, bytes: ByteArray, layout: SavedInputLayout, bindings: SavedInputBindings): Pack =
try { parse(context, bytes) } catch (nativeFailure: Exception) {
ArmsControlSkins.parse(context, bytes, layout, bindings, "Imported skin", nativeFailure)
}
fun install(context: Context, pack: Pack, profile: String, role: InputRole): InputLibrary {
require(pack.layout.supports(role))
val written = mutableListOf<java.io.File>()
try {
val names = pack.images.mapValues { (_, bytes) ->
val name = "key_${newInputId()}.png"
val file = requireNotNull(InputButtonImages.file(context, name))
file.parentFile!!.mkdirs()
written += file
file.writeBytes(bytes)
name
}
val layout = pack.layout.copy(elements = pack.layout.elements.map { e -> e.copy(image = names[e.image] ?: "", stickImage = names[e.stickImage] ?: "") })
return InputLibraries.update(context) {
it.withLayout(layout).withPreset(pack.bindings).chooseLayout(profile, role, layout.id)
}
} catch (e: Exception) {
written.forEach { it.delete() }
throw e
}
}
fun catalog(raw: String, source: ControlSources.Source = ControlSources.DROIDDECK): List<Entry> {
require(raw.length <= 1_000_000)
val doc = JSONObject(raw)
val skin = doc.has("skins") && !doc.has("controls")
require(skin || doc.getInt("version") == 1)
val list = doc.getJSONArray(if (skin) "skins" else "controls")
require(list.length() <= 256)
return (0 until list.length()).map { index ->
val e = list.getJSONObject(index)
fun text(key: String) = e.getString(key).also { require(it.isNotBlank() && it.length <= 160) }
val path = text("file")
require(ControlSources.validPath(path) && path.endsWith(".zip", ignoreCase = true))
val sha = e.optString("sha256").also { require(if (skin) it.isEmpty() || it.matches(Regex("[a-f0-9]{64}")) else it.matches(Regex("[a-f0-9]{64}"))) }
Entry(text("name"), e.optString("author").take(160), e.optString("game").take(160), e.optString("license").take(160), path, sha,
if (skin) InputLayoutScreen.BOTH else InputLayoutScreen.valueOf(e.getString("screen")), e.optString("preview").takeIf { it.isNotEmpty() }?.also {
require(ControlSources.validPath(it) && it.endsWith(".png", ignoreCase = true))
}, source = source, skin = skin)
}.also { require(it.map { e -> e.path }.distinct().size == it.size) }
}
fun bundled(context: Context): List<Entry> = context.assets.open("community-controls/catalog.json").use {
catalog(readLimited(it, 1_000_000).toString(Charsets.UTF_8)).map { e -> e.copy(bundled = true) }
}
fun fetchCatalog(source: ControlSources.Source = ControlSources.DROIDDECK): List<Entry> =
catalog(get(source.manifest, 1_000_000).toString(Charsets.UTF_8), source)
fun preview(context: Context, entry: Entry): android.graphics.Bitmap? {
val path = entry.preview ?: return null
val bytes = if (entry.bundled) context.assets.open("community-controls/$path").use { readLimited(it, 512 * 1024) }
else get(entry.source.url(path), 2 * 1024 * 1024)
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
require(bounds.outWidth in 1..4096 && bounds.outHeight in 1..4096)
val options = BitmapFactory.Options().apply {
inSampleSize = 1
while (maxOf(bounds.outWidth, bounds.outHeight) / inSampleSize > 256) inSampleSize *= 2
}
return BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
}
fun download(context: Context, entry: Entry, layout: SavedInputLayout? = null, bindings: SavedInputBindings? = null): Pack {
val bytes = if (entry.bundled) context.assets.open("community-controls/${entry.path}").use { readLimited(it) }
else get(entry.source.url(entry.path), if (entry.skin) 32 * 1024 * 1024 else MAX_BYTES)
val sha = MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) }
require(entry.sha256.isEmpty() && entry.skin || sha == entry.sha256) { "Controls download failed verification." }
return if (entry.skin) ArmsControlSkins.parse(context, bytes, requireNotNull(layout), requireNotNull(bindings), entry.name)
else parse(context, bytes).also { require(it.layout.screen == entry.screen) }
}
private fun get(url: String, limit: Int): ByteArray {
val connection = URL(url).openConnection() as HttpURLConnection
connection.connectTimeout = 15_000
connection.readTimeout = 30_000
connection.instanceFollowRedirects = false
return try {
require(connection.responseCode == 200) { "Could not download community controls (${connection.responseCode})." }
require(connection.contentLengthLong <= limit)
connection.inputStream.use { readLimited(it, limit) }
} finally { connection.disconnect() }
}
}
@@ -1,78 +0,0 @@
package com.droiddeck.launcher.input
import android.content.Context
import org.json.JSONArray
import java.net.URI
import java.net.URLEncoder
internal object ControlSources {
data class Source(val name: String, val manifest: String, val submit: String? = null, val builtIn: Boolean = false) {
val id get() = manifest
fun url(path: String): String {
require(validPath(path)) { "Invalid controls source path." }
return manifest.substringBeforeLast('/') + "/" + path.split('/').joinToString("/") {
URLEncoder.encode(it, "UTF-8").replace("+", "%20")
}
}
}
val DROIDDECK = Source("DroidDeck", CommunityControls.BASE + "catalog.json", CommunityControls.SUBMIT, true)
val ARMSX2 = Source("ARMSX2 community", "https://raw.githubusercontent.com/bagasromadon/ARMSX2-CustomControllerSkins/main/manifest.json",
"https://github.com/bagasromadon/ARMSX2-CustomControllerSkins/issues/new", true)
private fun prefs(context: Context) = context.getSharedPreferences("community-control-sources", Context.MODE_PRIVATE)
fun validPath(path: String) = path.length in 1..512 && path.split('/').all { it.isNotBlank() && it != "." && it != ".." } &&
path.none { it.isISOControl() || it in "\\:%?#" } && !path.startsWith('/')
private fun https(raw: String): URI {
require(raw.length <= 2048)
val uri = URI(raw.trim())
require(uri.scheme == "https" && !uri.host.isNullOrBlank() && uri.userInfo == null && uri.fragment == null && uri.query == null && !uri.path.isNullOrBlank() && !uri.path.endsWith('/')) {
"Enter an HTTPS catalog URL or a GitHub repository URL."
}
return uri
}
fun candidates(raw: String): List<Source> {
val uri = https(raw)
val parts = uri.path.trim('/').split('/')
if (uri.host.equals("github.com", true)) {
require(parts.size == 2 || parts.size >= 5 && parts[2] == "blob") { "Use a GitHub repository or manifest file URL." }
require(parts.take(2).all { it.matches(Regex("[A-Za-z0-9_.-]+")) && it != "." && it != ".." })
val repo = parts.take(2).joinToString("/")
val submit = "https://github.com/$repo/issues/new"
val base = "https://raw.githubusercontent.com/$repo/"
return if (parts.size == 2) listOf("catalog.json", "manifest.json").map { Source(repo, base + "main/" + it, submit) }
else listOf(Source(repo, base + parts.drop(3).joinToString("/"), submit))
}
val submit = if (uri.host.equals("raw.githubusercontent.com", true) && parts.size >= 4)
"https://github.com/${parts[0]}/${parts[1]}/issues/new" else null
return listOf(Source(if (submit != null) parts.take(2).joinToString("/") else uri.host, uri.toASCIIString(), submit))
}
fun read(context: Context): List<Source> {
val custom = runCatching {
val raw = prefs(context).getString("sources", "[]")!!
require(raw.length <= 32_000)
val array = JSONArray(raw)
require(array.length() <= 16)
(0 until array.length()).map { candidates(array.getString(it)).single() }
}.getOrDefault(emptyList())
return (listOf(DROIDDECK, ARMSX2) + custom).distinctBy { it.id }
}
fun add(context: Context, source: Source) {
val list = read(context)
require(list.none { it.id == source.id }) { "This source is already connected." }
require(list.size < 18) { "Remove a source before adding another." }
save(context, list + source)
}
fun remove(context: Context, source: Source) {
require(!source.builtIn)
save(context, read(context).filterNot { it.id == source.id })
}
private fun save(context: Context, sources: List<Source>) {
check(prefs(context).edit().putString("sources", JSONArray(sources.filterNot { it.builtIn }.map { it.manifest }).toString()).commit()) {
"Could not save controls sources."
}
}
}
@@ -82,8 +82,6 @@ public class FakeInputWriter {
private static final int PAD_TYPE_OFFSET = IMU_OFFSET + 44;
private static final int PAD_TYPE_SET = 0x80000000;
private static final int LATENCY_OFFSET = IMU_OFFSET + 48;
private static final int REMOTE_IMU_MODE_OFFSET = IMU_OFFSET + 52;
private static final int REMOTE_IMU_PID_OFFSET = IMU_OFFSET + 56;
public static final int LATENCY_CONTROLLER = 1;
public static final int LATENCY_TOUCH = 2;
private static volatile int latency = 0;
@@ -233,8 +231,6 @@ public class FakeInputWriter {
}
data.putInt(IMU_OFFSET, 0);
data.putInt(IMU_MODE_OFFSET, 0);
data.putInt(REMOTE_IMU_MODE_OFFSET, 0);
data.putInt(REMOTE_IMU_PID_OFFSET, 0);
data.putLong(IMU_SEQ_OFFSET, 0L);
for (int i = 0; i < 12; i++) {
data.putShort(IMU_ACCEL_OFFSET + (i * 2), (short) 0);
@@ -498,11 +494,8 @@ public class FakeInputWriter {
if (ringSlot == null) return -1;
synchronized (ringSlot) {
ByteBuffer ring = ringSlot.data;
if (ring == null) return 0;
int remote = ring.getInt(REMOTE_IMU_MODE_OFFSET);
int pid = ring.getInt(REMOTE_IMU_PID_OFFSET);
return ImuModes.combine(ring.getInt(IMU_MODE_OFFSET), remote,
remote < 0 && pid > 0 && new File("/proc/" + pid).exists());
int value = ring == null ? 0 : ring.getInt(IMU_MODE_OFFSET);
return value < 0 ? value & 0xffff : -1;
}
}
@@ -1,25 +0,0 @@
package com.droiddeck.launcher.input
import android.content.Context
object GameInputControls {
private fun prefs(context: Context) = context.getSharedPreferences("input-game-controls", Context.MODE_PRIVATE)
fun profile(context: Context, game: String?): String? = game?.let { prefs(context).getString(it, null) }
fun set(context: Context, game: String, profile: String?) {
require(game.isNotBlank() && game.length <= 512)
require(profile == null || InputLibraries.read(context).profiles.any { it.id == profile })
val edit = prefs(context).edit()
if (profile == null) edit.remove(game) else edit.putString(game, profile)
check(edit.commit()) { "Could not save game controls." }
}
fun resolve(context: Context, library: InputLibrary, desktop: Boolean, game: String?): InputLibrary {
val selection = library.selection(desktop)
if (game == null || selection.profile != InputProfiles.AUTO) return library
val target = profile(context, game)?.let { id -> library.profiles.firstOrNull { it.id == id } } ?: return library
var result = library
for (role in listOf(InputRole.PRIMARY, InputRole.SECONDARY)) {
if (role !in selection.parts) result = result.selectPart(desktop, role, target.binding(role))
}
return result
}
}
@@ -1,158 +0,0 @@
package com.droiddeck.launcher.input
/** Where a USB mouse's input report keeps its buttons, motion and wheel, as its HID report descriptor lays them out. */
class HidMouseReport(
val reportId: Int,
private val buttons: List<Field?>,
private val x: Field,
private val y: Field,
private val wheel: Field?,
) {
class Field(private val bit: Int, private val size: Int, private val signed: Boolean) {
fun read(report: ByteArray, length: Int, base: Int): Int {
var value = 0
for (i in 0 until minOf(size, 32)) {
val at = base + bit + i
if (at / 8 >= length) break
if ((report[at / 8].toInt() shr (at % 8)) and 1 != 0) value = value or (1 shl i)
}
return if (signed && size in 1..31 && value and (1 shl (size - 1)) != 0) value - (1 shl size) else value
}
}
/** [buttons] has bit 0 set for the first button. */
data class State(val buttons: Int, val dx: Int, val dy: Int, val wheel: Int)
/** Returns null for reports with another ID, such as a receiver's media keys. */
fun decode(report: ByteArray, length: Int): State? {
val base = if (reportId == 0) 0 else {
if (length < 1 || (report[0].toInt() and 0xff) != reportId) return null
8
}
var pressed = 0
buttons.forEachIndexed { i, field -> if (field != null && field.read(report, length, base) != 0) pressed = pressed or (1 shl i) }
return State(pressed, x.read(report, length, base), y.read(report, length, base), wheel?.read(report, length, base) ?: 0)
}
companion object {
/** The report every boot mouse sends after SET_PROTOCOL(boot): three buttons, then X and Y as signed bytes. */
val BOOT = HidMouseReport(0, List(3) { Field(it, 1, false) }, Field(8, 8, true), Field(16, 8, true), null)
private const val BUTTON_PAGE = 0x09
private const val MOUSE = 0x00010002
private const val X = 0x00010030
private const val Y = 0x00010031
private const val WHEEL = 0x00010038
private const val MAX_BUTTONS = 8
private const val MAX_FIELD_BITS = 32
private const val MAX_REPORT_COUNT = 4096
private class Global(var usagePage: Int = 0, var logicalMin: Int = 0, var reportSize: Int = 0,
var reportCount: Int = 0, var reportId: Int = 0) {
fun copy() = Global(usagePage, logicalMin, reportSize, reportCount, reportId)
}
private class Placed(val reportId: Int, val field: Field)
/** Returns null if [descriptor] has no mouse collection with X and Y in one report. */
fun parse(descriptor: ByteArray): HidMouseReport? {
var global = Global()
val pushed = ArrayDeque<Global>()
val usages = mutableListOf<Int>()
var usageMin = -1
var usageMax = -1
val offsets = HashMap<Int, Int>()
var depth = 0
var mouseDepth = -1
var mouseDone = false
val placed = HashMap<Int, Placed>()
fun usage(index: Int): Int = when {
usages.isNotEmpty() -> usages.getOrElse(index) { usages.last() }
usageMin >= 0 && usageMax >= usageMin -> minOf(usageMin + index, usageMax)
else -> -1
}
var i = 0
while (i < descriptor.size) {
val prefix = descriptor[i].toInt() and 0xff
if (prefix == 0xfe) {
if (i + 1 >= descriptor.size) break
i += 3 + (descriptor[i + 1].toInt() and 0xff)
continue
}
val size = intArrayOf(0, 1, 2, 4)[prefix and 3]
if (i + 1 + size > descriptor.size) break
var data = 0
for (b in 0 until size) data = data or ((descriptor[i + 1 + b].toInt() and 0xff) shl (8 * b))
val signedData = when (size) {
1 -> data.toByte().toInt()
2 -> data.toShort().toInt()
else -> data
}
val tag = prefix shr 4
when ((prefix shr 2) and 3) {
0 -> {
when (tag) {
0x8 -> {
if (global.reportSize !in 0..MAX_FIELD_BITS || global.reportCount !in 0..MAX_REPORT_COUNT) return null
val start = offsets[global.reportId] ?: 0
val isData = data and 1 == 0
val isVariable = data and 2 != 0
if (mouseDepth >= 0 && !mouseDone && isData && isVariable) {
for (n in 0 until global.reportCount) {
val u = usage(n)
if (u < 0) break
val field = Placed(global.reportId, Field(start + n * global.reportSize, global.reportSize, global.logicalMin < 0))
val button = if (u ushr 16 == BUTTON_PAGE) u and 0xffff else 0
when {
u == X || u == Y || u == WHEEL -> placed.putIfAbsent(u, field)
button in 1..MAX_BUTTONS -> placed.putIfAbsent(u, field)
}
}
}
offsets[global.reportId] = start + global.reportSize * global.reportCount
}
0xa -> {
depth++
if (mouseDepth < 0 && data == 1 && usage(0) == MOUSE) mouseDepth = depth
}
0xc -> {
if (depth == mouseDepth) mouseDone = true
depth--
}
}
usages.clear()
usageMin = -1
usageMax = -1
}
1 -> when (tag) {
0x0 -> global.usagePage = data
0x1 -> global.logicalMin = signedData
0x7 -> global.reportSize = data
0x8 -> global.reportId = data
0x9 -> global.reportCount = data
0xa -> pushed.addLast(global.copy())
0xb -> global = pushed.removeLastOrNull() ?: global
}
2 -> {
val full = if (size == 4) data else (global.usagePage shl 16) or data
when (tag) {
0x0 -> usages += full
0x1 -> usageMin = full
0x2 -> usageMax = full
}
}
}
i += 1 + size
}
val x = placed[X] ?: return null
val y = placed[Y]?.takeIf { it.reportId == x.reportId } ?: return null
val id = x.reportId
val buttons = (1..MAX_BUTTONS).map { n -> placed[(BUTTON_PAGE shl 16) or n]?.takeIf { it.reportId == id }?.field }
return HidMouseReport(id, buttons.dropLastWhile { it == null }, x.field, y.field,
placed[WHEEL]?.takeIf { it.reportId == id }?.field)
}
}
}
@@ -1,17 +1,14 @@
package com.droiddeck.launcher.input
import android.app.Service
import android.accessibilityservice.AccessibilityService
import android.content.Context
import android.content.Intent
import android.hardware.input.InputManager
import android.os.Binder
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Parcel
import android.view.KeyEvent
import android.view.accessibility.AccessibilityEvent
import com.droiddeck.launcher.HomeApp
import com.droiddeck.shortcuts.Relay
object HomeButtonShortcuts {
private var owner: Any? = null
@@ -104,78 +101,38 @@ object SystemKeyCapture {
}
}
class ShortcutsRelay : Service(), InputManager.InputDeviceListener {
private val main = Handler(Looper.getMainLooper())
private val trusted = java.util.concurrent.ConcurrentHashMap.newKeySet<Int>()
class HomeButtonService : AccessibilityService(), InputManager.InputDeviceListener {
private var bottomScreen: BottomScreenWatch? = null
private val binder = object : Binder() {
override fun onTransact(code: Int, data: Parcel, reply: Parcel?, flags: Int): Boolean {
if (code !in Relay.CONFIG..Relay.WINDOWS) return super.onTransact(code, data, reply, flags)
data.enforceInterface(Relay.DESCRIPTOR)
if (!trusts(Binder.getCallingUid())) return false
when (code) {
Relay.CONFIG -> reply?.writeInt(if (bottomScreen != null) Relay.WANTS_WINDOWS else 0)
Relay.KEY -> reply?.writeInt(if (onMain(KeyEvent.CREATOR.createFromParcel(data))) 1 else 0)
Relay.INTERRUPT -> main.post { HomeButtonShortcuts.release() }
Relay.ARRIVAL -> bottomScreen?.onArrival(data.readInt(), data.readString() ?: return true, data.readLong())
Relay.WINDOWS -> bottomScreen?.onWindows(Relay.decode(data.createByteArray() ?: return true))
}
return true
}
override fun onServiceConnected() {
getSystemService(InputManager::class.java).registerInputDeviceListener(this, Handler(Looper.getMainLooper()))
if (bottomScreen == null && BottomScreenGuests.supported()) bottomScreen = BottomScreenWatch(this).also { it.start() }
}
private fun trusts(uid: Int): Boolean {
if (uid !in trusted) {
if (!packageManager.getPackagesForUid(uid).orEmpty().contains(Relay.PACKAGE)) return false
trusted += uid
}
return com.droiddeck.launcher.core.SteamIntegration.shortcutsEnabled(this)
}
private fun onMain(event: KeyEvent): Boolean {
// A key the companion already gave up on must not run later and leave a press without its release.
val claimed = java.util.concurrent.atomic.AtomicBoolean(false)
val task = java.util.concurrent.FutureTask {
claimed.compareAndSet(false, true) &&
(SystemKeyCapture.onKeyEvent(event) || HomeButtonShortcuts.onKeyEvent(this, event))
}
main.postAtFrontOfQueue(task)
return try {
task.get(KEY_TIMEOUT_MS, java.util.concurrent.TimeUnit.MILLISECONDS)
} catch (e: java.util.concurrent.TimeoutException) {
if (claimed.compareAndSet(false, true)) false else runCatching { task.get() }.getOrDefault(false)
} catch (e: Exception) {
false
}
}
override fun onCreate() {
super.onCreate()
getSystemService(InputManager::class.java).registerInputDeviceListener(this, main)
if (BottomScreenGuests.supported()) bottomScreen = BottomScreenWatch(this).also { it.start() }
}
override fun onBind(intent: Intent?): IBinder = binder
override fun onUnbind(intent: Intent?): Boolean {
HomeButtonShortcuts.release()
return super.onUnbind(intent)
private fun stopBottomScreen() {
bottomScreen?.stop()
bottomScreen = null
}
override fun onKeyEvent(event: KeyEvent) =
SystemKeyCapture.onKeyEvent(event) || HomeButtonShortcuts.onKeyEvent(this, event)
override fun onAccessibilityEvent(event: AccessibilityEvent?) { event?.let { bottomScreen?.onEvent(it) } }
override fun onInterrupt() { HomeButtonShortcuts.release() }
override fun onInputDeviceAdded(deviceId: Int) {}
override fun onInputDeviceChanged(deviceId: Int) {}
override fun onInputDeviceRemoved(deviceId: Int) { HomeButtonShortcuts.onDeviceRemoved(deviceId) }
override fun onUnbind(intent: Intent?): Boolean {
HomeButtonShortcuts.release()
stopBottomScreen()
com.droiddeck.launcher.core.SteamIntegration.syncShortcutsListing(this)
return super.onUnbind(intent)
}
override fun onDestroy() {
HomeButtonShortcuts.release()
bottomScreen?.stop()
bottomScreen = null
stopBottomScreen()
getSystemService(InputManager::class.java).unregisterInputDeviceListener(this)
super.onDestroy()
}
private companion object {
const val KEY_TIMEOUT_MS = 200L
}
}
@@ -1,14 +0,0 @@
package com.droiddeck.launcher.input;
final class ImuModes {
private ImuModes() {}
// Steam and its Remote Play client each keep their own mode word, with the top bit set once written. Motion is
// read while either process wants it, and a word that has not been set leaves the choice to the other one.
// -1 means neither has set a mode yet.
static int combine(int steam, int remote, boolean remoteRunning) {
boolean remoteSet = remote < 0 && remoteRunning;
if (steam >= 0 && !remoteSet) return -1;
return ((steam < 0 ? steam : 0) | (remoteSet ? remote : 0)) & 0xffff;
}
}
@@ -10,7 +10,7 @@ import org.json.JSONObject
import java.util.UUID
object InputLibraries {
private const val VERSION = 15
private const val VERSION = 14
private const val KEY = "library"
private const val RECOVERY = "library-recovery."
const val OVERLAY = "builtin.overlay"
@@ -304,7 +304,7 @@ object InputLibraries {
for (e in layout.elements) elements.put(JSONObject().put("id", e.id).put("kind", e.kind.name)
.put("control", e.control.id).put("name", e.name).put("x", e.x.toDouble()).put("y", e.y.toDouble())
.put("width", e.width.toDouble()).put("height", e.height.toDouble()).put("floating", e.floating).put("hideWhenIdle", e.hideWhenIdle).put("mouseGestures", e.mouseGestures).put("toggle", e.toggle).put("icon", e.icon).put("image", e.image)
.put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown).put("stickImage", e.stickImage))
.put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown))
layouts.put(JSONObject().put("id", layout.id).put("name", layout.name).put("template", layout.template.name).put("elements", elements)
.put("tint", layout.style.tint ?: JSONObject.NULL).put("opacity", layout.style.opacity).put("screen", layout.screen.name).put("aspect", layout.aspect.toDouble()).put("scale", layout.scale.toDouble())
.put("hidden", JSONArray(layout.style.hidden.map { it.name }.sorted())).put("origin", layout.origin ?: JSONObject.NULL))
@@ -345,7 +345,7 @@ object InputLibraries {
e.getDouble("y").toFloat(), e.getDouble("width").toFloat(), e.getDouble("height").toFloat(),
e.getString("id"), InputElementKind.valueOf(e.getString("kind")), e.getString("name"),
e.optBoolean("floating", true), e.optBoolean("hideWhenIdle", false), e.optBoolean("mouseGestures", false), e.optBoolean("toggle", false), e.optInt("icon", 0), e.optString("image", ""),
e.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true), e.optBoolean("alwaysShown", false), e.optString("stickImage", ""))
e.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true), e.optBoolean("alwaysShown", false))
}
SavedInputLayout(layout.getString("id"), layout.getString("name"), elements, InputLayoutTemplate.valueOf(layout.getString("template")),
InputSurfaceStyle(if (!layout.has("tint")) ControllerPrefs.STEAM_BLUE else if (layout.isNull("tint")) null else layout.getInt("tint"), layout.optInt("opacity", 100),
@@ -244,8 +244,7 @@ data class InputLibrary(
for (e in layout.elements) {
inputName(e.name)
require(e.icon == 0 || InputButtonIcons.has(e.icon))
for (image in listOf(e.image, e.stickImage))
require(image.isEmpty() || image.matches(Regex("[A-Za-z0-9_.-]{1,128}")) && image != "." && image != "..")
require(e.image.isEmpty() || e.image.matches(Regex("[A-Za-z0-9_.-]{1,128}")) && e.image != "." && e.image != "..")
require(e.opacity.isFinite() && e.opacity in 0.01f..1f)
require(!e.toggle || e.kind == InputElementKind.BUTTON || e.kind == InputElementKind.TRIGGER)
require(listOf(e.x, e.y, e.width, e.height).all { it.isFinite() })
@@ -3,16 +3,11 @@ package com.droiddeck.launcher.input
object InputSpace {
const val WIDTH = 1920
const val HEIGHT = 1080
const val FIXED_ONE = 256
fun x(position: Float, viewWidth: Int): Int = scale(position, viewWidth, WIDTH)
fun y(position: Float, viewHeight: Int): Int = scale(position, viewHeight, HEIGHT)
fun fixedX(position: Float, viewWidth: Int): Int = scale(position, viewWidth, WIDTH * FIXED_ONE)
fun fixedY(position: Float, viewHeight: Int): Int = scale(position, viewHeight, HEIGHT * FIXED_ONE)
private fun scale(position: Float, extent: Int, size: Int): Int =
if (extent <= 0) 0 else (position / extent * size).toInt().coerceIn(0, size - 1)
}
@@ -35,7 +35,6 @@ data class InputSurfaceElement(
val buttonShape: InputButtonShape = InputButtonShape.ROUNDED,
val showLabel: Boolean = true,
val alwaysShown: Boolean = false,
val stickImage: String = "",
) {
val hasClick get() = kind == InputElementKind.STICK || kind == InputElementKind.TRACKPAD
@@ -57,16 +57,6 @@ class MouseBackInput(private val sendRight: (Boolean) -> Unit, private val mouse
!device.supportsSource(InputDevice.SOURCE_TOUCHSCREEN)
}
/** A controller's own mouse interface (8BitDo Ultimate Mobile) is not a mouse the user right-clicks with. */
fun externalMouse(devices: List<InputDevice?>): InputDevice? {
val controllers = devices.filterNotNull().filter { PadBridge.isFromController(it) }
return devices.filterNotNull().firstOrNull { mouse ->
isExternalMouse(mouse) && controllers.none {
it.vendorId != 0 && it.vendorId == mouse.vendorId && it.productId == mouse.productId
}
}
}
private val VIRTUAL_NAME = Regex("\\bvirtual\\b", RegexOption.IGNORE_CASE)
fun declaresVirtual(name: String?): Boolean = name != null && VIRTUAL_NAME.containsMatchIn(name)
@@ -1,46 +0,0 @@
package com.droiddeck.launcher.input
import kotlin.math.abs
/**
* Holding the middle button still opens the session menu. While the session reads the mouse over USB, Android has
* no cursor, so this is how a mouse reaches the menu and, through it, the system again.
*/
class MouseMenuHold(
private val schedule: (Runnable, Long) -> Unit,
private val cancel: (Runnable) -> Unit,
private val onMenu: () -> Unit,
) {
private var holding = false
private var travel = 0
private val fire = Runnable {
if (!holding) return@Runnable
holding = false
onMenu()
}
fun onButton(index: Int, down: Boolean) {
if (index != MIDDLE) return
cancel(fire)
holding = down
travel = 0
if (down) schedule(fire, HOLD_MS)
}
fun onMove(dx: Int, dy: Int) {
if (!holding) return
travel += abs(dx) + abs(dy)
if (travel > SLOP) reset()
}
fun reset() {
holding = false
cancel(fire)
}
companion object {
const val MIDDLE = 2
const val HOLD_MS = 2000L
const val SLOP = 48
}
}
@@ -1,14 +0,0 @@
package com.droiddeck.launcher.input
import com.droiddeck.launcher.session.SessionPrefs
object PenRouter {
enum class Route { BLOCKED, PEN, RELATIVE, TOUCH }
fun decide(uiBlocking: Boolean, mode: String, glasses: Boolean, programLock: Boolean): Route = when {
uiBlocking -> Route.BLOCKED
mode == SessionPrefs.PEN_TOUCH -> Route.TOUCH
glasses || programLock -> Route.RELATIVE
else -> Route.PEN
}
}
@@ -1,247 +0,0 @@
package com.droiddeck.launcher.input
import android.graphics.RectF
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.view.InputDevice
import android.view.KeyEvent
import android.view.MotionEvent
import com.droiddeck.launcher.session.SessionPrefs
class PenStream(private val sink: Sink) {
fun interface Sink {
fun sample(flags: Int, x: Int, y: Int)
}
private val handler = Handler(Looper.getMainLooper())
private val exitLater = Runnable { if (exitPending) leave() }
private val hoverWatchdog = Runnable { checkHover() }
private var watching = false
private var contact = false
private var barrel = 0
private var keyDown = false
private var keyDevice = Int.MIN_VALUE
private var keyCode = 0
private var exitPending = false
private var exitTime = 0L
private var deviceId = Int.MIN_VALUE
private var x = 0
private var y = 0
private var sampleTime = 0L
var sideButton = SessionPrefs.PEN_BUTTON_RIGHT
var inProximity = false
private set
fun onMotion(event: MotionEvent, pointer: Int, area: RectF, width: Int, height: Int): Boolean {
val action = event.actionMasked
val time = event.eventTime
val own = isPenAction(event, pointer)
expire(time)
when (action) {
MotionEvent.ACTION_HOVER_ENTER, MotionEvent.ACTION_HOVER_MOVE -> {
continueAt(time)
contact = false
enter(event)
samples(event, pointer, area, width, height)
}
MotionEvent.ACTION_HOVER_EXIT -> if (inProximity && !exitPending && !contact) pendExit(time)
MotionEvent.ACTION_BUTTON_PRESS, MotionEvent.ACTION_BUTTON_RELEASE -> {
continueAt(time)
if (!inProximity) return true
barrel = event.buttonState
samples(event, pointer, area, width, height)
}
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> if (own) {
continueAt(time)
enter(event)
contact = true
samples(event, pointer, area, width, height)
} else if (contact) samples(event, pointer, area, width, height)
MotionEvent.ACTION_MOVE -> if (contact) {
barrel = event.buttonState
samples(event, pointer, area, width, height)
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> if (!own) {
if (contact) samples(event, pointer, area, width, height)
} else if (contact) {
if (event.flags and MotionEvent.FLAG_CANCELED != 0) cancel()
else {
barrel = event.buttonState
samples(event, pointer, area, width, height, lift = true)
pendExit(time)
}
}
MotionEvent.ACTION_CANCEL -> cancel()
else -> return false
}
return true
}
fun onKey(event: KeyEvent): Boolean {
expire(event.eventTime)
val down = event.action == KeyEvent.ACTION_DOWN
val repeat = event.repeatCount > 0
if (exitPending && !repeat) leave()
if (!inProximity || exitPending) {
if (!repeat && event.deviceId == keyDevice && event.keyCode == keyCode) keyDown = down
return true
}
if (down == keyDown) return true
val before = state()
keyDown = down
if (down) {
keyDevice = event.deviceId
keyCode = event.keyCode
}
if (state() == before) return true
emit(state())
return true
}
fun cancel(releaseKey: Boolean = false) {
if (releaseKey) keyDown = false
leave()
}
fun holdsKey(event: KeyEvent): Boolean = keyDown && event.deviceId == keyDevice && event.keyCode == keyCode
fun deviceRemoved(deviceId: Int) {
if (deviceId == this.deviceId) cancel()
if (!keyDown || deviceId != keyDevice) return
val before = state()
keyDown = false
if (inProximity && state() != before) emit(state())
}
private fun enter(event: MotionEvent) {
barrel = event.buttonState
if (inProximity) return
inProximity = true
deviceId = event.deviceId
}
private fun continueAt(time: Long) {
if (!exitPending) return
if (time - exitTime > EXIT_GRACE_MS) { leave(); return }
exitPending = false
handler.removeCallbacks(exitLater)
}
private fun pendExit(time: Long) {
exitPending = true
exitTime = time
handler.removeCallbacks(exitLater)
handler.postDelayed(exitLater, EXIT_GRACE_MS)
}
private fun expire(time: Long) {
if (inProximity && !contact && time - sampleTime >= HOVER_TIMEOUT_MS) leave()
}
private fun watchHover(delay: Long = HOVER_TIMEOUT_MS) {
if (watching || contact) return
watching = true
handler.postDelayed(hoverWatchdog, delay)
}
private fun checkHover() {
watching = false
if (!inProximity || contact || exitPending) return
val silent = SystemClock.uptimeMillis() - sampleTime
if (silent >= HOVER_TIMEOUT_MS) leave() else watchHover(HOVER_TIMEOUT_MS - silent)
}
private fun leave() {
if (!inProximity) return
emit(0)
handler.removeCallbacks(exitLater)
handler.removeCallbacks(hoverWatchdog)
watching = false
inProximity = false
contact = false
exitPending = false
barrel = 0
}
private fun samples(event: MotionEvent, pointer: Int, area: RectF, width: Int, height: Int, lift: Boolean = false) {
for (h in 0 until event.historySize) sample(event, pointer, h, area, width, height)
if (lift) contact = false
sample(event, pointer, -1, area, width, height)
}
private fun sample(event: MotionEvent, pointer: Int, h: Int, area: RectF, width: Int, height: Int) {
x = InputSpace.fixedX(event.axis(MotionEvent.AXIS_X, pointer, h).coerceIn(area.left, area.right), width)
y = InputSpace.fixedY(event.axis(MotionEvent.AXIS_Y, pointer, h).coerceIn(area.top, area.bottom), height)
sampleTime = if (h < 0) event.eventTime else event.getHistoricalEventTime(h)
emit(state())
watchHover()
}
private fun emit(flags: Int) = sink.sample(flags, x, y)
private fun state(): Int =
PEN_IN or (if (contact) PEN_TIP else 0) or buttonFlags(keyDown || barrel and MotionEvent.BUTTON_STYLUS_PRIMARY != 0,
barrel and MotionEvent.BUTTON_STYLUS_SECONDARY != 0, sideButton)
private fun MotionEvent.axis(axis: Int, pointer: Int, h: Int): Float =
if (h < 0) getAxisValue(axis, pointer) else getHistoricalAxisValue(axis, pointer, h)
companion object {
const val PEN_IN = 1 shl 0
const val PEN_TIP = 1 shl 1
const val PEN_RIGHT = 1 shl 2
const val PEN_MIDDLE = 1 shl 3
const val HOVER_TIMEOUT_MS = 2_000L
const val EXIT_GRACE_MS = 50L
private val PEN_NAME = Regex("\\b(pen|stylus)", RegexOption.IGNORE_CASE)
fun isPen(event: MotionEvent, index: Int): Boolean = when (event.getToolType(index)) {
MotionEvent.TOOL_TYPE_STYLUS, MotionEvent.TOOL_TYPE_ERASER -> true
MotionEvent.TOOL_TYPE_UNKNOWN -> event.isFromSource(InputDevice.SOURCE_STYLUS)
else -> false
}
fun penConnected(): Boolean =
InputDevice.getDeviceIds().any { id -> InputDevice.getDevice(id)?.let { isPenDevice(it.sources) } == true }
// Before Android 14 a touchscreen that declares ABS_MT_TOOL_TYPE reports SOURCE_STYLUS without any pen.
fun isPenDevice(sources: Int, sdk: Int = Build.VERSION.SDK_INT): Boolean =
sources and InputDevice.SOURCE_STYLUS == InputDevice.SOURCE_STYLUS &&
(sources and InputDevice.SOURCE_TOUCHSCREEN != InputDevice.SOURCE_TOUCHSCREEN || sdk >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
fun penIndex(event: MotionEvent): Int {
for (index in 0 until event.pointerCount) if (isPen(event, index)) return index
return -1
}
fun isPenAction(event: MotionEvent, index: Int): Boolean = when (event.actionMasked) {
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> true
MotionEvent.ACTION_POINTER_DOWN, MotionEvent.ACTION_POINTER_UP -> event.actionIndex == index
else -> false
}
fun isPenKey(event: KeyEvent): Boolean {
val device = event.device ?: return false
return isPenKeyboard(device.name, device.sources, Build.VERSION.SDK_INT < Build.VERSION_CODES.Q || device.isExternal,
device.keyboardType == InputDevice.KEYBOARD_TYPE_ALPHABETIC)
}
fun isPenKeyboard(name: String?, sources: Int, external: Boolean, alphabetic: Boolean): Boolean =
external && !alphabetic && sources == InputDevice.SOURCE_KEYBOARD && name != null && PEN_NAME.containsMatchIn(name)
fun buttonFlags(primary: Boolean, secondary: Boolean, sideButton: String): Int {
val first = when (sideButton) {
SessionPrefs.PEN_BUTTON_RIGHT -> PEN_RIGHT
SessionPrefs.PEN_BUTTON_MIDDLE -> PEN_MIDDLE
else -> 0
}
val second = if (sideButton == SessionPrefs.PEN_BUTTON_RIGHT) PEN_MIDDLE else PEN_RIGHT
return (if (primary) first else 0) or (if (secondary) second else 0)
}
}
}
@@ -23,20 +23,13 @@ internal fun MotionEvent.pointerSubset(pointerIdBits: Int): MotionEvent? {
}
val properties = Array(indices.size) { MotionEvent.PointerProperties() }
val coordinates = Array(indices.size) { MotionEvent.PointerCoords() }
indices.forEachIndexed { target, index -> getPointerProperties(index, properties[target]) }
fun sample(position: Int): Array<MotionEvent.PointerCoords> {
indices.forEachIndexed { target, index ->
if (position < historySize) getHistoricalPointerCoords(index, position, coordinates[target])
else getPointerCoords(index, coordinates[target])
}
return coordinates
indices.forEachIndexed { target, index ->
getPointerProperties(index, properties[target])
getPointerCoords(index, coordinates[target])
}
fun time(position: Int) = if (position < historySize) getHistoricalEventTime(position) else eventTime
val split = MotionEvent.obtain(
downTime, time(0), splitAction, indices.size, properties, sample(0),
return MotionEvent.obtain(
downTime, eventTime, splitAction, indices.size, properties, coordinates,
metaState, buttonState, xPrecision, yPrecision,
deviceId, edgeFlags, source, flags,
)
for (position in 1..historySize) split.addBatch(time(position), sample(position), metaState)
return split
}
@@ -129,9 +129,8 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu
}
}
}
// Android can refuse these (BLUETOOTH_CONNECT revoked); an exception on this thread would end the app.
runCatching { g.disconnect() }.onFailure { Log.w(TAG, "disconnect failed", it) }
runCatching { g.close() }.onFailure { Log.w(TAG, "close failed", it) }
g.disconnect()
g.close()
Log.i(TAG, "disconnected: $why")
listener?.invoke()
}
@@ -1,262 +0,0 @@
package com.droiddeck.launcher.input
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbConstants
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbEndpoint
import android.hardware.usb.UsbInterface
import android.hardware.usb.UsbManager
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.util.Log
import android.view.InputDevice
/**
* Reads a USB mouse from its HID interface, detaching it from Android meanwhile. Android only grants pointer
* capture on the focused display, so an app shown elsewhere, as in REDMAGIC's cast mode, gets a cursor that
* stops at the screen edge.
*/
class UsbMouse(private val context: Context, private val listener: Listener) {
interface Listener {
fun onMove(dx: Int, dy: Int)
fun onButton(index: Int, down: Boolean)
fun onWheel(steps: Int)
fun onChanged()
/** The mouse stopped responding while read here, so buttons held then never got their releases. */
fun onLost()
}
private val usb by lazy { context.getSystemService(Context.USB_SERVICE) as UsbManager }
private val main = Handler(Looper.getMainLooper())
private val permissionAction by lazy { context.packageName + ".USB_MOUSE_PERMISSION" }
private val asked = mutableSetOf<String>()
private val failed = mutableSetOf<String>()
private var receiverRegistered = false
@Volatile private var grab: Grab? = null
private var lastReader: Thread? = null
val active: Boolean get() = grab != null
private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
Log.i(TAG, "USB mouse access ${if (granted) "granted" else "denied"}")
if (granted) listener.onChanged()
}
}
/**
* Returns whether the mouse is now read here, setting it up on the reader thread; asks for access once per
* plugged-in mouse. A mouse that fails setup after being claimed isn't tried again until it is replugged, since
* releasing it re-adds Android's mouse, which would start another attempt.
*/
fun grab(): Boolean {
if (grab != null) return true
val (device, mouse) = findMouse() ?: return false
if (device.deviceName in failed) return false
if (!usb.hasPermission(device)) {
if (asked.add(device.deviceName)) askPermission(device)
return false
}
val endpoint = (0 until mouse.endpointCount).map(mouse::getEndpoint).firstOrNull {
it.direction == UsbConstants.USB_DIR_IN && it.type == UsbConstants.USB_ENDPOINT_XFER_INT
} ?: return false
grab = Grab(device, mouse, endpoint, lastReader).also {
lastReader = it.thread
it.thread.start()
}
return true
}
/** Hands the mouse back to Android. */
fun release() {
val current = grab ?: return
grab = null
current.cancel()
}
fun close() {
release()
if (receiverRegistered) runCatching { context.unregisterReceiver(receiver) }
receiverRegistered = false
}
private fun findMouse(): Pair<UsbDevice, UsbInterface>? {
val androidMice = InputDevice.getDeviceIds().asList().mapNotNull { InputDevice.getDevice(it) }
.filter { !it.isVirtual && it.supportsSource(InputDevice.SOURCE_MOUSE) }
.map { it.vendorId to it.productId }.toSet()
return usb.deviceList.values.filter { (it.vendorId to it.productId) in androidMice }.firstNotNullOfOrNull { device ->
(0 until device.interfaceCount).map(device::getInterface).firstOrNull(::isBootMouse)?.let { device to it }
}
}
private fun askPermission(device: UsbDevice) {
if (!receiverRegistered) {
val filter = IntentFilter(permissionAction)
if (Build.VERSION.SDK_INT >= 33) context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
else context.registerReceiver(receiver, filter)
receiverRegistered = true
}
val flags = if (Build.VERSION.SDK_INT >= 31) PendingIntent.FLAG_MUTABLE else 0
val intent = PendingIntent.getBroadcast(context, 0, Intent(permissionAction).setPackage(context.packageName), flags)
runCatching { usb.requestPermission(device, intent) }.onFailure {
asked.remove(device.deviceName)
Log.w(TAG, "requestPermission", it)
}
}
private inner class Grab(
private val device: UsbDevice,
private val mouse: UsbInterface,
private val endpoint: UsbEndpoint,
private val previous: Thread?,
) {
@Volatile private var running = true
private val claimLock = Any()
val thread = Thread(::run, "usb-mouse")
/** Once this returns, the reader either never claims the interface or sees the cancellation after claiming. */
fun cancel() = synchronized(claimLock) { running = false }
// The reader owns the connection: closing it while a transfer is pending would free it under the transfer.
// A previous reader may still hold the interface, which would make this claim fail.
private fun run() {
runCatching { previous?.join() }
val connection = if (running) usb.openDevice(device) else null
if (connection == null) {
main.post { ended(markFailed = false) }
return
}
var claimed = false
var boot = false
try {
claimed = synchronized(claimLock) { running && connection.claimInterface(mouse, true) }
if (!claimed) {
main.post { ended(markFailed = false) }
return
}
if (!running) return
val format = setUp(connection)
if (format == null) {
main.post { ended(markFailed = true) }
return
}
boot = format === HidMouseReport.BOOT
if (!running) return
Log.i(TAG, String.format(java.util.Locale.ROOT, "reading USB mouse %04x:%04x \"%s\" directly (%s)",
device.vendorId, device.productId, device.productName, if (boot) "boot protocol" else "report ${format.reportId}"))
read(connection, format)
} finally {
if (claimed) {
if (boot) connection.controlTransfer(0x21, SET_PROTOCOL, HID_REPORT_PROTOCOL, mouse.id, null, 0, CONTROL_TIMEOUT_MS)
connection.releaseInterface(mouse)
}
connection.close()
}
}
/** HID 1.11 7.2.6: a host must not assume the protocol a device is in, so it is set either way. */
private fun setUp(connection: UsbDeviceConnection): HidMouseReport? {
val descriptor = ByteArray(1024)
val length = connection.controlTransfer(0x81, GET_DESCRIPTOR, HID_REPORT_DESCRIPTOR shl 8, mouse.id,
descriptor, descriptor.size, CONTROL_TIMEOUT_MS)
val parsed = if (length > 0) HidMouseReport.parse(descriptor.copyOf(length)) else null
if (parsed != null && running &&
connection.controlTransfer(0x21, SET_PROTOCOL, HID_REPORT_PROTOCOL, mouse.id, null, 0, CONTROL_TIMEOUT_MS) >= 0) return parsed
val boot = running &&
connection.controlTransfer(0x21, SET_PROTOCOL, HID_BOOT_PROTOCOL, mouse.id, null, 0, CONTROL_TIMEOUT_MS) >= 0
return HidMouseReport.BOOT.takeIf { boot }
}
private fun read(connection: UsbDeviceConnection, format: HidMouseReport) {
val report = ByteArray(maxOf(endpoint.maxPacketSize, 8))
var buttons = 0
var failures = 0
while (running) {
val started = SystemClock.uptimeMillis()
val length = connection.bulkTransfer(endpoint, report, report.size, READ_TIMEOUT_MS)
if (length <= 0) {
if (SystemClock.uptimeMillis() - started < READ_TIMEOUT_MS / 2 && ++failures >= MAX_FAILURES) {
main.post { lost() }
return
}
continue
}
failures = 0
val state = format.decode(report, length) ?: continue
val changed = buttons xor state.buttons
buttons = state.buttons
main.post { deliver(state, changed) }
}
}
private fun ended(markFailed: Boolean) {
if (grab !== this) return
if (markFailed) failed += device.deviceName
Log.i(TAG, "USB mouse \"${device.productName}\" could not be set up")
grab = null
}
private fun deliver(state: HidMouseReport.State, changed: Int) {
if (grab !== this) return
if (state.dx != 0 || state.dy != 0) listener.onMove(state.dx, state.dy)
for (i in 0 until BUTTONS) if (changed and (1 shl i) != 0) listener.onButton(i, state.buttons and (1 shl i) != 0)
if (state.wheel != 0) listener.onWheel(state.wheel)
}
private fun lost() {
if (grab !== this) return
failed += device.deviceName
Log.i(TAG, "USB mouse stopped responding")
grab = null
listener.onLost()
}
}
companion object {
private const val TAG = "UsbMouse"
private const val GET_DESCRIPTOR = 0x06
private const val SET_PROTOCOL = 0x0b
private const val HID_BOOT_PROTOCOL = 0
private const val HID_REPORT_PROTOCOL = 1
private const val HID_REPORT_DESCRIPTOR = 0x22
private const val SUBCLASS_BOOT = 1
private const val PROTOCOL_MOUSE = 2
private const val CONTROL_TIMEOUT_MS = 1000
private const val READ_TIMEOUT_MS = 100
private const val MAX_FAILURES = 5
private const val BUTTONS = 5
private fun isBootMouse(iface: UsbInterface) = iface.interfaceClass == UsbConstants.USB_CLASS_HID &&
iface.interfaceSubclass == SUBCLASS_BOOT && iface.interfaceProtocol == PROTOCOL_MOUSE
/**
* A process killed while reading a mouse leaves it with no driver until it is replugged. Claiming without
* force only succeeds when no driver has the interface, and releasing it reattaches Android's.
*/
fun returnLeftover(context: Context) {
Thread({
runCatching {
val usb = context.getSystemService(Context.USB_SERVICE) as UsbManager
for (device in usb.deviceList.values) {
if (!usb.hasPermission(device)) continue
val mouse = (0 until device.interfaceCount).map(device::getInterface).firstOrNull(::isBootMouse) ?: continue
val connection = usb.openDevice(device) ?: continue
if (connection.claimInterface(mouse, false)) {
connection.releaseInterface(mouse)
Log.i(TAG, "returned USB mouse \"${device.productName}\" to Android")
}
connection.close()
}
}.onFailure { Log.w(TAG, "returning a USB mouse to Android failed", it) }
}, "usb-mouse-return").start()
}
}
}
@@ -150,37 +150,8 @@ object BootMovie {
folder.listFiles()?.forEach { if (it.name != keep) it.delete() }
}
internal fun syncShuffleFromSteam(context: Context, config: File) = syncShuffleFromSteam(context, listOf(config))
// Staging writes Shuffle and its baseline under the same lock, so a poll never reads a half-staged value as Steam's.
internal fun syncShuffleFromSteam(context: Context, configs: List<File>) = synchronized(SessionFiles.STEAM_CONFIG) {
val read = configs.mapNotNull { config -> SessionFiles.startupMovieShuffle(config)?.let { config to it } }
val (known, unseen) = read.partition { (config, _) -> SessionPrefs.bootMovieShuffleSeen(context, config) != null }
var changed = false
known.forEach { (config, steam) ->
if (SessionPrefs.bootMovieShuffleSeen(context, config) != steam) {
SessionPrefs.setBootMovieShuffle(context, steam)
changed = true
}
SessionPrefs.setBootMovieShuffleSeen(context, config, steam)
}
// A config read for the first time only sets the choice when no known config changed, so it cannot undo a change.
unseen.forEach { (config, steam) ->
if (!changed && SessionPrefs.bootMovieShuffle(context) != steam) {
SessionPrefs.setBootMovieShuffle(context, steam)
changed = true
}
SessionPrefs.setBootMovieShuffleSeen(context, config, steam)
}
}
fun syncFromSteam(context: Context): Boolean {
val active = BootMovieLibrary.steamConfig(context)
syncShuffleFromSteam(
context,
BootMovieLibrary.steamRoots(context).map { File(it, "config/config.vdf") }.filter { it != active } + active,
)
val named = SessionFiles.startupMovieLocalPath(active) ?: return false
val named = SessionFiles.startupMovieLocalPath(BootMovieLibrary.steamConfig(context)) ?: return false
val seen = SessionPrefs.bootMovieSteamSeen(context)
if (named == seen) return false
SessionPrefs.setBootMovieSteamSeen(context, named)
@@ -194,7 +194,7 @@ object BottomDesktop {
send(target, Message.obtain(null, Comp.MSG_POINTER, x, y))
}
/** Button, wheel and finger-scroll input, using the `WaylandCompositor.SCENE_*` types `nativeSendSceneInput` takes. */
/** Button (3), wheel (4) and smooth-scroll (12) input, as `WaylandCompositor.nativeSendSceneInput` takes it. */
fun sendScene(type: Int, a: Int, b: Int = 0) {
val target = service ?: return
send(target, Message.obtain(null, Comp.MSG_SCENE, type, a).apply {
@@ -20,7 +20,6 @@ object GameProfileManager {
}
clear("Proton") { ProtonDefault.requestGame(context, scope, null) }
clear("component packages") { ComponentsManager.clearGameComponents(context, scope) }
clear("on-screen controls") { com.droiddeck.launcher.input.GameInputControls.set(context, scope, null) }
clear("texture filtering") { SessionPrefs.clearGameTextureFiltering(context, scope) }
clear("Windows components") { WinComponents.setPicks(context, scope, emptyList()) }
@@ -8,7 +8,6 @@ import android.os.Process
import android.system.Os
import android.system.OsConstants
import android.util.Log
import com.droiddeck.launcher.gpu.SocNames
import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import kotlin.math.abs
@@ -27,14 +26,13 @@ object GameThreadHints {
private const val PACE_TOLERANCE = 0.08
private val NOT_GAMES = setOf("steam", "steamwebhelper")
private val SOCS = setOf("CQ8725S", "SM8750")
private var worker: Thread? = null
@Synchronized
fun start(context: Context): String {
if (!SessionPrefs.gameThreadHints(context)) return "game thread hints: off"
if (Build.VERSION.SDK_INT < 31 || !supported(Build.SOC_MODEL)) return "game thread hints: Snapdragon 8 Elite only"
if (Build.VERSION.SDK_INT < 31 || Build.SOC_MODEL != "CQ8725S") return "game thread hints: Odin 3 only"
val hm = context.getSystemService(PerformanceHintManager::class.java)
?: return "game thread hints: no PerformanceHintManager"
val pm = context.getSystemService(PowerManager::class.java)
@@ -101,8 +99,6 @@ object GameThreadHints {
}
}
internal fun supported(soc: String): Boolean = SocNames.normalizedModel(soc) in SOCS
internal fun holdsPace(fps: Double, refreshHz: Double): Boolean =
fps >= 10 && refreshHz > 0 && (1..4).any { k -> abs(fps - refreshHz / k) < PACE_TOLERANCE * refreshHz / k }
@@ -60,19 +60,17 @@ object GraphicsReport {
appendLine("-- path")
appendLine("path: " + path(context))
appendLine("driver mode: " + SessionPrefs.gpuDriverMode(context))
appendLine("display driver (compositor): " + SessionPrefs.androidDriver(context).ifEmpty {
if (DeviceSupport.adreno()) "(auto: bundled Turnip)" else "(auto: the phone's own Vulkan driver, ${SystemVulkanDriver.hal() ?: "vendor HAL"})"
})
val display = SessionPrefs.androidDriver(context)
val shown = com.droiddeck.launcher.gpu.TurnipDriver(context).effectiveId()
appendLine("display driver (compositor): " +
(if (shown == "system") "the phone's own Vulkan driver, ${SystemVulkanDriver.hal() ?: "vendor HAL"}" else shown) +
if (display.isEmpty()) " (auto)" else if (display != shown) " (picked $display, not used)" else "")
appendLine("display driver chosen by: " + when {
display.isEmpty() -> "auto (or a pair on a non-Adreno GPU: the phone's own driver)"
DriverBundle.containing(context, display, false) != null -> "pair (its display half)"
else -> "user (picked on its own)"
})
val linux = SessionPrefs.linuxDriver(context)
appendLine("runtime driver: " + (com.droiddeck.launcher.gpu.DeviceInfo.hostRoute(context)
?.let { "$it (picked ${linux.ifEmpty { "runtime default" }}, not used)" } ?: linux.ifEmpty { "(runtime default)" }))
appendLine("runtime driver: " + linux.ifEmpty { "(runtime default)" })
if (linux.isNotEmpty()) {
val dir = com.droiddeck.launcher.gpu.LinuxVulkanDriverManager(context).getDriverDir(linux)
appendLine("runtime driver dir: ${dir.path} (" + (dir.listFiles()?.filter { it.name.endsWith(".so") }?.joinToString { it.name } ?: "missing") + ")")
@@ -163,8 +161,8 @@ object GraphicsReport {
private fun read(path: String): String? = FileUtils.readString(File(path))?.trim()?.takeIf { it.isNotEmpty() }
/** The compositor's driver lines from the app's own log. */
internal val COMPOSITOR = Regex(
"""vk_present|waylandcomp|vk_loader|compositor|vkCreateDevice|extension|adrenotools|hook_impl|TurnipDriver|""" +
private val COMPOSITOR = Regex(
"""vk_present|waylandcomp|vk_loader|compositor|vkCreateDevice|extension|adrenotools|TurnipDriver|""" +
"""graphics driver|display driver|DD_PRESENT_FAULT|SystemVulkan|vkbridge|VkBridge|mali_gralloc|panvk|PanVK|radv|MESA|native buffer|first frame|present|""" +
"""lsfg|FrameGen|device gates|AAudio|directaudio|pulse|gralloc|dma.?buf|modifier|import""",
RegexOption.IGNORE_CASE,
@@ -19,7 +19,6 @@ import com.droiddeck.launcher.input.ControllerPrefs
import com.droiddeck.launcher.input.JoyCon
import com.droiddeck.launcher.input.PadBridge
import java.io.DataInputStream
import java.io.File
import kotlin.math.max
class RumbleComponent : SessionPart() {
@@ -40,10 +39,6 @@ class RumbleComponent : SessionPart() {
internal var controllerMotors: (Int) -> Motors? = ::lookupController
internal var motorLooper: Looper? = null
internal var processStart: (Int) -> String? = ::readProcessStart
internal var gameRunning: () -> Boolean = { SteamGameProcess.running() }
private var gameCheckedAt = Long.MIN_VALUE
private var gameLastSeen = false
@Synchronized private fun refreshEnabled() {
enabled = app()?.let { ControllerPrefs.rumbleEnabled(it) } == true
@@ -71,9 +66,7 @@ class RumbleComponent : SessionPart() {
try {
val bytes = ByteArray(8)
DataInputStream(client.inputStream).readFully(bytes)
val peer = runCatching { client.peerCredentials }.getOrNull()
buzz(u16(bytes, 0), u16(bytes, 2), u16(bytes, 4), u16(bytes, 6), peer?.pid ?: 0,
peer?.uid == android.os.Process.myUid())
buzz(u16(bytes, 0), u16(bytes, 2), u16(bytes, 4), u16(bytes, 6))
} catch (e: Exception) {
} finally {
try { client.close() } catch (e: Exception) { }
@@ -101,9 +94,7 @@ class RumbleComponent : SessionPart() {
private fun u16(b: ByteArray, at: Int): Int = (b[at].toInt() and 0xFF) or ((b[at + 1].toInt() and 0xFF) shl 8)
private fun buzz(strong: Int, weak: Int, ms: Int, slot: Int) = buzz(strong, weak, ms, slot, 0, false)
@Synchronized private fun buzz(strong: Int, weak: Int, ms: Int, slot: Int, sender: Int, ownUser: Boolean) {
@Synchronized private fun buzz(strong: Int, weak: Int, ms: Int, slot: Int) {
if (!enabled || quiet) return
val target = target(slot)
val previous = playing[slot]
@@ -114,19 +105,10 @@ class RumbleComponent : SessionPart() {
target?.let { Log.i(TAG, "rumble: slot $slot playing on ${it.name}") }
}
if (target == null) return
if ((strong == 0 && weak == 0) || ms == 0) {
val from = effects[slot]?.from ?: 0
if (sender > 0 && from > 0 && from != sender) return
target.cancel()
forget(slot)
return
}
if ((strong == 0 && weak == 0) || ms == 0) { target.cancel(); forget(slot); return }
val handler = handler ?: return
val effect = effects.getOrPut(slot) { Effect(slot) }
val held = effect.hold
effect.want(strong, weak, ms)
effect.from = sender
if (effect.hold && (!held || effect.owner != sender)) effect.claim(sender, ownUser)
val now = SystemClock.uptimeMillis()
if (effect.playing(now)) return
handler.removeCallbacks(effect)
@@ -134,37 +116,19 @@ class RumbleComponent : SessionPart() {
if (wait > 0) handler.postDelayed(effect, wait) else play(effect)
}
@Synchronized private fun play(effect: Effect, keepalive: Boolean = false) {
@Synchronized private fun play(effect: Effect) {
val target = playing[effect.slot]
if (target == null || effects[effect.slot] !== effect) return
if (keepalive && effect.hold && effect.armed) effect.orphaned()?.let { why ->
Log.i(TAG, "rumble: slot ${effect.slot} stopped, $why")
target.cancel()
forget(effect.slot)
return
}
val duration = if (effect.hold) HOLD_EFFECT_MS else effect.ms.toLong().coerceIn(1L, 5000L)
try {
target.play(effect.strong, effect.weak, duration)
effect.played(SystemClock.uptimeMillis(), duration)
if (effect.hold) {
effect.armed = true
handler?.postDelayed(effect, KEEPALIVE_MS)
}
if (effect.hold) handler?.postDelayed(effect, KEEPALIVE_MS)
} catch (e: Exception) {
Log.w(TAG, "rumble: ${target.name}: $e")
}
}
private fun gameRecently(): Boolean {
val now = SystemClock.uptimeMillis()
if (!gameLastSeen || now - gameCheckedAt >= GAME_CHECK_MS) {
gameLastSeen = gameRunning()
gameCheckedAt = now
}
return gameLastSeen
}
private fun forget(slot: Int) {
effects.remove(slot)?.let { handler?.removeCallbacks(it) }
}
@@ -206,32 +170,8 @@ class RumbleComponent : SessionPart() {
private var playedWeak = 0
private var playedMs = 0
private var until = 0L
var owner = 0
var from = 0
private var ownerSeen = false
private var ownerStart: String? = null
private var duringGame = false
var armed = false
val hold get() = ms == HOLD_MS
fun claim(sender: Int, ownUser: Boolean) {
owner = sender
val start = if (sender > 0) processStart(sender) else null
ownerSeen = sender > 0 && (start != null || ownUser)
ownerStart = start?.takeIf { it != UNKNOWN_START }
duringGame = gameRecently()
armed = false
}
fun orphaned(): String? {
if (ownerSeen) {
val start = processStart(owner)
if (start == null || (ownerStart != null && start != UNKNOWN_START && start != ownerStart))
return "process $owner that started it is gone"
}
return if (duringGame && !gameRunning()) "the game it started in has exited" else null
}
fun want(strong: Int, weak: Int, ms: Int) { this.strong = strong; this.weak = weak; this.ms = ms }
fun playing(now: Long) = playedMs != 0 && playedStrong == strong && playedWeak == weak && playedMs == ms &&
@@ -245,7 +185,7 @@ class RumbleComponent : SessionPart() {
until = now + duration
}
override fun run() = play(this, keepalive = true)
override fun run() = play(this)
}
internal interface Motors {
@@ -316,7 +256,6 @@ class RumbleComponent : SessionPart() {
const val HOLD_MS = 0xFFFF
const val HOLD_EFFECT_MS = 2000L
const val KEEPALIVE_MS = 1500L
const val GAME_CHECK_MS = 1000L
private fun oneShot(vibrator: Vibrator, strength: Int, ms: Long): VibrationEffect {
val amplitude = if (vibrator.hasAmplitudeControl()) (strength * 255L / 65535L).toInt().coerceIn(1, 255)
@@ -324,13 +263,6 @@ class RumbleComponent : SessionPart() {
return VibrationEffect.createOneShot(ms, amplitude)
}
const val UNKNOWN_START = "?"
internal fun readProcessStart(pid: Int): String? = runCatching {
val stat = File("/proc/$pid/stat").readText()
stat.substring(stat.lastIndexOf(')') + 2).split(' ')[19]
}.getOrElse { if (File("/proc/$pid").exists()) UNKNOWN_START else null }
private fun lookupController(id: Int): Motors? {
val device = InputDevice.getDevice(id) ?: return null
val name = "\"${device.name}\""
@@ -75,17 +75,6 @@ object SessionEvents {
}
}
inline fun <T> step(name: String, block: () -> T): T {
val dir = SessionState.logDirectory ?: SessionPaths.current()
record("start.step", mapOf("step" to name, "state" to "begin"), dir)
val began = android.os.SystemClock.elapsedRealtime()
try {
return block()
} finally {
record("start.step", mapOf("step" to name, "state" to "end", "ms" to android.os.SystemClock.elapsedRealtime() - began), dir)
}
}
fun fail(code: String, message: String, status: Int? = null) {
synchronized(SessionState) {
SessionState.phase = SessionPhase.FAILED
@@ -14,9 +14,6 @@ import com.droiddeck.launcher.runtime.ProotFastPath
import java.io.File
object SessionFiles {
// Session start and Flatpak staging can both rewrite Steam's config.vdf; one writer at a time.
internal val STEAM_CONFIG = Any()
private const val TAG = "SessionFiles"
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
const val DIRECTAUDIO_DIR = "usr/local/lib/directaudio"
@@ -76,7 +73,6 @@ object SessionFiles {
"rockstar/helpers/Launcher32.exe" to "usr/local/lib/droiddeck-rockstar/Launcher32.exe",
"rockstar/helpers/Launcher64.exe" to "usr/local/lib/droiddeck-rockstar/Launcher64.exe",
"usr/local/bin/droiddeck-game-env" to "usr/local/bin/droiddeck-game-env",
"usr/local/bin/droiddeck-game-debug" to "usr/local/bin/droiddeck-game-debug",
"usr/local/bin/droiddeck-game-gpu" to "usr/local/bin/droiddeck-game-gpu",
"usr/local/bin/droiddeck-diagnostic-inventory" to "usr/local/bin/droiddeck-diagnostic-inventory",
"usr/local/bin/droiddeck-wincomponents" to "usr/local/bin/droiddeck-wincomponents",
@@ -360,11 +356,6 @@ object SessionFiles {
"staged=$bigPictureMovieInstalled done=$done steam=${home.path} config: $before -> ${startupMoviePath(config)}",
)
if (startsSession) {
synchronized(STEAM_CONFIG) {
val shuffle = SessionPrefs.bootMovieShuffle(context)
setStartupMovieShuffle(config, shuffle)
if (startupMovieShuffle(config) == shuffle) SessionPrefs.setBootMovieShuffleSeen(context, config, shuffle)
}
disableIdleSleep(home)
seedUserDefaults(home)
}
@@ -377,30 +368,28 @@ object SessionFiles {
}
internal fun resetMissingStartupMovie(config: File, force: Boolean): Boolean {
synchronized(STEAM_CONFIG) {
if (!config.isFile) return true
val text = runCatching { config.readText() }.getOrElse {
Log.w(TAG, "could not read Steam config to reset the startup movie", it)
return false
}
val movie = activeStartupMovie(text) ?: return true
val block = text.substring(movie.keyStart, movie.close + 1)
val path = scalar(block, "LocalPath").orEmpty()
if (path.isEmpty()) return true
val missing = File(config.parentFile, "uioverrides/movies/" + path.removePrefix(BOOT_MOVIES_DIR))
val gone = path.startsWith(BOOT_MOVIES_DIR) && !missing.isFile && (force || path == BOOT_MOVIE_PATH)
if (!gone) return false
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
val updated = setScalar(setScalar(block, "MovieID", "0", newline), "LocalPath", "", newline)
val staged = File(config.parentFile, config.name + ".staged")
return try {
staged.writeText(text.replaceRange(movie.keyStart, movie.close + 1, updated))
(staged.renameTo(config)).also { if (!it) staged.delete() }
} catch (e: Exception) {
staged.delete()
Log.w(TAG, "could not reset Steam startup movie selection", e)
false
}
if (!config.isFile) return true
val text = runCatching { config.readText() }.getOrElse {
Log.w(TAG, "could not read Steam config to reset the startup movie", it)
return false
}
val movie = activeStartupMovie(text) ?: return true
val block = text.substring(movie.keyStart, movie.close + 1)
val path = scalar(block, "LocalPath").orEmpty()
if (path.isEmpty()) return true
val missing = File(config.parentFile, "uioverrides/movies/" + path.removePrefix(BOOT_MOVIES_DIR))
val gone = path.startsWith(BOOT_MOVIES_DIR) && !missing.isFile && (force || path == BOOT_MOVIE_PATH)
if (!gone) return false
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
val updated = setScalar(setScalar(block, "MovieID", "0", newline), "LocalPath", "", newline)
val staged = File(config.parentFile, config.name + ".staged")
return try {
staged.writeText(text.replaceRange(movie.keyStart, movie.close + 1, updated))
(staged.renameTo(config)).also { if (!it) staged.delete() }
} catch (e: Exception) {
staged.delete()
Log.w(TAG, "could not reset Steam startup movie selection", e)
false
}
}
@@ -501,42 +490,6 @@ object SessionFiles {
return scalar(text.substring(movie.keyStart, movie.close + 1), "LocalPath")
}
internal fun startupMovieShuffle(config: File): Boolean? {
val text = runCatching { config.readText() }.getOrNull() ?: return null
val movie = activeStartupMovie(text) ?: return false
return scalar(text.substring(movie.keyStart, movie.close + 1), "Shuffle") == "1"
}
internal fun withStartupMovieShuffle(text: String, on: Boolean): String {
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
val value = if (on) "1" else "0"
return listOfNotNull(customizationMovie(text), olderMovie(text)).sortedByDescending { it.keyStart }.fold(text) { acc, movie ->
val block = acc.substring(movie.keyStart, movie.close + 1)
if (!on && scalar(block, "Shuffle") == null) acc else acc.replaceRange(movie.keyStart, movie.close + 1, setScalar(block, "Shuffle", value, newline))
}
}
internal fun setStartupMovieShuffle(config: File, on: Boolean): Boolean {
synchronized(STEAM_CONFIG) {
if (!config.isFile) return false
val text = runCatching { config.readText() }.getOrElse {
Log.w(TAG, "could not read Steam config to set the startup movie shuffle", it)
return false
}
val updated = withStartupMovieShuffle(text, on)
if (updated == text) return true
val staged = File(config.parentFile, config.name + ".staged")
return try {
staged.writeText(updated)
staged.renameTo(config).also { if (!it) staged.delete() }
} catch (e: Exception) {
staged.delete()
Log.w(TAG, "could not set Steam startup movie shuffle", e)
false
}
}
}
internal fun startupMovieBlock(config: File): String? {
val text = runCatching { config.readText() }.getOrNull() ?: return null
val parts = listOfNotNull(
@@ -559,71 +512,69 @@ object SessionFiles {
}
internal fun ensureStartupMovieDefault(config: File, force: Boolean = false): Boolean {
synchronized(STEAM_CONFIG) {
val path = BOOT_MOVIE_PATH
val legacyPath = "/uioverrides/movies/droiddeck-startup.webm"
var text = if (config.isFile) runCatching { config.readText() }.getOrElse {
Log.w(TAG, "could not read Steam config for startup movie", it)
val path = BOOT_MOVIE_PATH
val legacyPath = "/uioverrides/movies/droiddeck-startup.webm"
var text = if (config.isFile) runCatching { config.readText() }.getOrElse {
Log.w(TAG, "could not read Steam config for startup movie", it)
return false
} else ""
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
val custom = customizationMovie(text)
val active = custom ?: olderMovie(text)
if (active != null) {
val block = text.substring(active.keyStart, active.close + 1)
val selectedId = scalar(block, "MovieID")
val selectedPath = scalar(block, "LocalPath")
if (selectedPath == path && custom != null) {
Log.i(TAG, "Steam startup movie is set to DroidDeck")
return true
}
val legacyDefault = selectedId == "0" && selectedPath == legacyPath
val hasExplicitSelection =
(!selectedId.isNullOrEmpty() && selectedId != "0") || !selectedPath.isNullOrEmpty()
if (!force && !legacyDefault && hasExplicitSelection && selectedPath != path) {
Log.i(TAG, "Steam startup movie selection preserved")
return false
} else ""
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
val custom = customizationMovie(text)
val active = custom ?: olderMovie(text)
if (active != null) {
val block = text.substring(active.keyStart, active.close + 1)
val selectedId = scalar(block, "MovieID")
val selectedPath = scalar(block, "LocalPath")
if (selectedPath == path && custom != null) {
Log.i(TAG, "Steam startup movie is set to DroidDeck")
return true
}
val legacyDefault = selectedId == "0" && selectedPath == legacyPath
val hasExplicitSelection =
(!selectedId.isNullOrEmpty() && selectedId != "0") || !selectedPath.isNullOrEmpty()
if (!force && !legacyDefault && hasExplicitSelection && selectedPath != path) {
Log.i(TAG, "Steam startup movie selection preserved")
}
}
val targets = listOfNotNull(customizationMovie(text), olderMovie(text)).sortedByDescending { it.keyStart }
for (target in targets) text = pointAt(text, target, path, newline)
if (olderMovie(text) == null) {
val steam = findSteamBlock(text)
if (steam == null) {
if (text.isNotBlank() && customizationMovie(text) == null) {
Log.w(TAG, "Steam config has no Steam settings block; startup movie default not set")
return false
}
}
val targets = listOfNotNull(customizationMovie(text), olderMovie(text)).sortedByDescending { it.keyStart }
for (target in targets) text = pointAt(text, target, path, newline)
if (olderMovie(text) == null) {
val steam = findSteamBlock(text)
if (steam == null) {
if (text.isNotBlank() && customizationMovie(text) == null) {
Log.w(TAG, "Steam config has no Steam settings block; startup movie default not set")
return false
}
if (text.isBlank()) {
text = "\"InstallConfigStore\"${newline}{${newline}\t\"Software\"${newline}\t{${newline}\t\t\"Valve\"${newline}\t\t{${newline}\t\t\t\"Steam\"${newline}\t\t\t{${newline}"
val section = startupMovieSection("\t\t\t\t", path, newline)
text += section + newline + "\t\t\t}" + newline + "\t\t}" + newline + "\t}" + newline + "}"
}
} else {
val lineStart = text.lastIndexOf('\n', steam.close).let { if (it < 0) 0 else it + 1 }
val indent = text.substring(lineStart, steam.close).takeWhile { it == '\t' || it == ' ' }
val section = startupMovieSection(indent + "\t", path, newline)
text = text.substring(0, lineStart) + section + newline + indent + text.substring(lineStart)
if (text.isBlank()) {
text = "\"InstallConfigStore\"${newline}{${newline}\t\"Software\"${newline}\t{${newline}\t\t\"Valve\"${newline}\t\t{${newline}\t\t\t\"Steam\"${newline}\t\t\t{${newline}"
val section = startupMovieSection("\t\t\t\t", path, newline)
text += section + newline + "\t\t\t}" + newline + "\t\t}" + newline + "\t}" + newline + "}"
}
} else {
val lineStart = text.lastIndexOf('\n', steam.close).let { if (it < 0) 0 else it + 1 }
val indent = text.substring(lineStart, steam.close).takeWhile { it == '\t' || it == ' ' }
val section = startupMovieSection(indent + "\t", path, newline)
text = text.substring(0, lineStart) + section + newline + indent + text.substring(lineStart)
}
if (customizationMovie(text) == null) text = withCustomization(text, path, newline)
val staged = File(config.parentFile, config.name + ".staged")
return try {
config.parentFile?.mkdirs()
staged.writeText(text)
if (!staged.renameTo(config)) {
staged.delete()
Log.e(TAG, "could not write Steam startup movie selection")
false
} else {
Log.i(TAG, "Steam startup movie default selected")
true
}
} catch (e: Exception) {
}
if (customizationMovie(text) == null) text = withCustomization(text, path, newline)
val staged = File(config.parentFile, config.name + ".staged")
return try {
config.parentFile?.mkdirs()
staged.writeText(text)
if (!staged.renameTo(config)) {
staged.delete()
Log.w(TAG, "could not write Steam startup movie selection", e)
Log.e(TAG, "could not write Steam startup movie selection")
false
} else {
Log.i(TAG, "Steam startup movie default selected")
true
}
} catch (e: Exception) {
staged.delete()
Log.w(TAG, "could not write Steam startup movie selection", e)
false
}
}
@@ -709,34 +660,32 @@ object SessionFiles {
private val IDLE_SLEEP_TIMERS = listOf("IdleSuspendBatterySeconds", "IdleSuspendACSeconds")
internal fun disableIdleSleep(steamHome: File): Boolean {
synchronized(STEAM_CONFIG) {
val config = File(steamHome, "config/config.vdf")
val text = runCatching { config.readText() }.getOrNull() ?: return false
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
val steam = findSteamBlock(text) ?: return false
val system = findObject(text, "system", steam.open + 1, steam.close)
val updated = if (system != null) {
val block = text.substring(system.keyStart, system.close + 1)
text.replaceRange(system.keyStart, system.close + 1, IDLE_SLEEP_TIMERS.fold(block) { acc, key -> setScalar(acc, key, "0", newline) })
} else {
val lineStart = text.lastIndexOf('\n', steam.close).let { if (it < 0) 0 else it + 1 }
val indent = text.substring(lineStart, steam.close).takeWhile { it == '\t' || it == ' ' } + "\t"
val section = (listOf(indent + "\"system\"", indent + "{") +
IDLE_SLEEP_TIMERS.map { "$indent\t\"$it\"\t\t\"0\"" } + (indent + "}")).joinToString(newline) + newline
text.substring(0, lineStart) + section + text.substring(lineStart)
}
val staged = File(config.parentFile, config.name + ".staged")
return try {
if (updated != text) {
staged.writeText(updated)
if (!staged.renameTo(config)) { staged.delete(); return false }
}
true
} catch (e: Exception) {
staged.delete()
Log.w(TAG, "could not disable Steam's idle sleep", e)
false
val config = File(steamHome, "config/config.vdf")
val text = runCatching { config.readText() }.getOrNull() ?: return false
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
val steam = findSteamBlock(text) ?: return false
val system = findObject(text, "system", steam.open + 1, steam.close)
val updated = if (system != null) {
val block = text.substring(system.keyStart, system.close + 1)
text.replaceRange(system.keyStart, system.close + 1, IDLE_SLEEP_TIMERS.fold(block) { acc, key -> setScalar(acc, key, "0", newline) })
} else {
val lineStart = text.lastIndexOf('\n', steam.close).let { if (it < 0) 0 else it + 1 }
val indent = text.substring(lineStart, steam.close).takeWhile { it == '\t' || it == ' ' } + "\t"
val section = (listOf(indent + "\"system\"", indent + "{") +
IDLE_SLEEP_TIMERS.map { "$indent\t\"$it\"\t\t\"0\"" } + (indent + "}")).joinToString(newline) + newline
text.substring(0, lineStart) + section + text.substring(lineStart)
}
val staged = File(config.parentFile, config.name + ".staged")
return try {
if (updated != text) {
staged.writeText(updated)
if (!staged.renameTo(config)) { staged.delete(); return false }
}
true
} catch (e: Exception) {
staged.delete()
Log.w(TAG, "could not disable Steam's idle sleep", e)
false
}
}
@@ -788,7 +737,7 @@ object SessionFiles {
}
private fun setScalar(block: String, key: String, value: String, newline: String): String {
val pattern = Regex("(?m)^([\\t ]*\"${Regex.escape(key)}\"[\\t ]+)\"[^\"\\r\\n]*\"([\\t ]*(?://[^\\r\\n]*)?)$")
val pattern = Regex("(?m)^([\\t ]*\"${Regex.escape(key)}\"[\\t ]+)\"[^\"\\r\\n]*\"([\\t ]*)$")
val match = pattern.find(block)
if (match != null) return block.replaceRange(match.range, match.groupValues[1] + "\"" + value + "\"" + match.groupValues[2])
val close = block.lastIndexOf('}')
@@ -23,9 +23,6 @@ object SessionPaths {
@Volatile
private var ended: File? = null
@Volatile
private var startedAt = 0L
@Synchronized
fun beginOrCurrent(context: Context, label: String? = null): File {
dir?.let { if (it.isDirectory) return it }
@@ -41,7 +38,6 @@ object SessionPaths {
var made = File(parent, "$day-${"%02d".format(Locale.US, number)}-$what")
while (made.exists()) made = File(parent, "$day-${"%02d".format(Locale.US, ++number)}-$what")
EnhancedDiagnostics.clearRecordFor(context, made)
startedAt = System.currentTimeMillis()
if (!made.isDirectory && !made.mkdirs()) Log.e(TAG, "could not create $made")
dir = made
if (enhanced && !EnhancedDiagnostics.consumeInto(context, made)) {
@@ -53,8 +49,6 @@ object SessionPaths {
fun current(): File? = dir
fun startedAt(folder: File): Long = if (dir == folder) startedAt else 0L
fun currentSessionLogsRetained(context: Context): Boolean =
dir?.let { it.parentFile == SessionFiles.logDirectory(context) } ?: true
@@ -13,8 +13,6 @@ import com.droiddeck.launcher.gpu.TurnipDriver
import org.json.JSONObject
import java.io.File
private const val SCREEN_EFFECTS_PROFILE_UPSCALER_KEY = "upscaler"
object SessionPrefs {
data class GameTextureFiltering(val anisotropy: Int? = null, val lodBias: String? = null)
@@ -516,38 +514,6 @@ object SessionPrefs {
prefs(context).edit().putString("touch", mode).apply()
}
const val PEN_MOUSE = "mouse"
const val PEN_TOUCH = "touch"
const val PEN_BUTTON_RIGHT = "right"
const val PEN_BUTTON_MIDDLE = "middle"
const val PEN_BUTTON_OFF = "off"
data class Pen(val mode: String = PEN_MOUSE, val button: String = PEN_BUTTON_RIGHT)
private val PEN_SETTINGS = mapOf(
"pen" to setOf(PEN_MOUSE, PEN_TOUCH),
"penButton" to setOf(PEN_BUTTON_RIGHT, PEN_BUTTON_MIDDLE, PEN_BUTTON_OFF),
)
private fun penSetting(context: Context, key: String, default: String): String =
prefs(context).getString(key, default)?.takeIf { it in PEN_SETTINGS.getValue(key) } ?: default
fun setPenSetting(context: Context, key: String, value: String) {
require(value in PEN_SETTINGS.getValue(key))
prefs(context).edit().putString(key, value).apply()
}
fun penMode(context: Context): String = penSetting(context, "pen", PEN_MOUSE)
fun penButton(context: Context): String = penSetting(context, "penButton", PEN_BUTTON_RIGHT)
fun pen(context: Context): Pen = Pen(penMode(context), penButton(context))
fun penSeen(context: Context): Boolean = prefs(context).getBoolean("penSeen", false)
fun setPenSeen(context: Context) {
if (!penSeen(context)) prefs(context).edit().putBoolean("penSeen", true).apply()
}
const val SHAPE_AUTO = "auto"
const val SHAPE_WIDE = "16:9"
const val SHAPE_EXACT = "exact"
@@ -814,12 +780,6 @@ object SessionPrefs {
prefs(context).edit().putBoolean("zramClient", on).apply()
}
fun zramIdle(context: Context): Boolean = prefs(context).getBoolean("zramIdle", true)
fun setZramIdle(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("zramIdle", on).apply()
}
fun vramCapMb(context: Context): Int = prefs(context).getInt("vramCapMb", 0).coerceAtLeast(0)
fun setVramCapMb(context: Context, mb: Int) {
@@ -913,12 +873,8 @@ object SessionPrefs {
@JvmStatic
fun vkBridge(context: Context): Boolean = prefs(context).getBoolean("vkBridge", com.droiddeck.launcher.core.DeviceSupport.mali())
fun vkBridgeExplicit(context: Context): Boolean = prefs(context).contains("vkBridge")
fun venus(context: Context): Boolean = prefs(context).getBoolean("venus", false)
fun venusExplicit(context: Context): Boolean = prefs(context).contains("venus")
fun hostVulkanApi(context: Context): String = prefs(context).getString("hostVulkanApi", "").orEmpty()
fun setHostVulkanApi(context: Context, api: String) {
@@ -1229,13 +1185,6 @@ object SessionPrefs {
fun setBootMovieApplyNext(context: Context, on: Boolean) { prefs(context).edit().putBoolean("bootMovieApplyNext", on).apply() }
fun bootMovieSteamSeen(context: Context): String? = prefs(context).getString("bootMovieSteamSeen", null)
fun setBootMovieSteamSeen(context: Context, path: String) { prefs(context).edit().putString("bootMovieSteamSeen", path).apply() }
fun bootMovieShuffle(context: Context): Boolean = prefs(context).getBoolean("bootMovieShuffle", false)
fun setBootMovieShuffle(context: Context, on: Boolean) { prefs(context).edit().putBoolean("bootMovieShuffle", on).apply() }
fun bootMovieShuffleSeen(context: Context, config: java.io.File): Boolean? {
val key = "bootMovieShuffleSeen:${config.path}"
return prefs(context).takeIf { it.contains(key) }?.getBoolean(key, false)
}
fun setBootMovieShuffleSeen(context: Context, config: java.io.File, on: Boolean) { prefs(context).edit().putBoolean("bootMovieShuffleSeen:${config.path}", on).apply() }
fun bootMovieCustomName(context: Context): String? = prefs(context).getString("bootMovieCustomName", null)
fun setBootMovieCustomName(context: Context, name: String?) {
prefs(context).edit().apply { if (name == null) remove("bootMovieCustomName") else putString("bootMovieCustomName", name) }.apply()
@@ -1425,13 +1374,6 @@ object SessionPrefs {
prefs(context).edit().putInt("gradientPrimary", primary).putInt("gradientSecondary", secondary).apply()
}
fun trueBlackHighlight(context: Context): Int =
prefs(context).getInt("trueBlackHighlight", com.droiddeck.launcher.ui.Themes.DEFAULT_HIGHLIGHT)
fun setTrueBlackHighlight(context: Context, highlight: Int) {
prefs(context).edit().putInt("trueBlackHighlight", highlight).apply()
}
private fun customResolution(context: Context, mode: String): Pair<Int, Int>? =
parseResolution(prefs(context).getString("customRes.$mode", null))
@@ -1501,136 +1443,15 @@ object SessionPrefs {
}
private const val SCREEN_EFFECTS_PROFILES_KEY = "screenEffects.profiles"
const val SCREEN_EFFECTS_ACTIVE_PROFILE_KEY = "screenEffects.activeProfile"
fun screenEffectsProfileId(mode: String, gameId: String?, program: String?): String? {
if (mode == SessionService.MODE_DESKTOP) return "desktop"
val id = gameId?.trim()?.takeIf { it.isNotEmpty() }
if (id != null) return "game:$id"
return if (mode == SessionService.MODE_RUN) {
program?.trim()?.takeIf { it.isNotEmpty() }?.let { "program:$it" }
} else null
}
fun activeScreenEffectsProfileId(context: Context): String? =
prefs(context).getString(SCREEN_EFFECTS_ACTIVE_PROFILE_KEY, null)?.takeIf { it.isNotBlank() }
fun setActiveScreenEffectsProfile(context: Context, profileId: String?) {
prefs(context).edit().putString(SCREEN_EFFECTS_ACTIVE_PROFILE_KEY, profileId.orEmpty()).apply()
}
fun screenEffects(context: Context): ScreenEffects {
val text = prefs(context).getString("screenEffects", null) ?: return ScreenEffects.OFF
return runCatching { ScreenEffects.decode(JSONObject(text)) }.getOrDefault(ScreenEffects.OFF)
}
fun screenEffects(context: Context, profileId: String?): ScreenEffects {
if (profileId.isNullOrBlank()) return screenEffects(context)
val storedProfiles = prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null)
val profile = storedProfiles?.let { raw ->
runCatching { JSONObject(raw).optJSONObject(profileId) }.getOrNull()
}
return profile?.let {
runCatching { ScreenEffects.decode(it) }.getOrDefault(ScreenEffects.OFF)
} ?: screenEffects(context)
}
fun setScreenEffects(context: Context, effects: ScreenEffects) {
prefs(context).edit().putString("screenEffects", effects.encode().toString()).apply()
}
fun setScreenEffects(context: Context, profileId: String?, effects: ScreenEffects) {
if (profileId.isNullOrBlank()) {
setScreenEffects(context, effects)
return
}
val sessionPrefs = prefs(context)
val profiles = runCatching {
JSONObject(sessionPrefs.getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
}.getOrDefault(JSONObject())
val encoded = effects.encode()
profiles.optJSONObject(profileId)?.let { savedProfile ->
if (savedProfile.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY)) {
encoded.put(
SCREEN_EFFECTS_PROFILE_UPSCALER_KEY,
savedProfile.optInt(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY),
)
}
}
profiles.put(profileId, encoded)
sessionPrefs.edit().putString(SCREEN_EFFECTS_PROFILES_KEY, profiles.toString()).apply()
}
fun hasScreenEffectsUpscalerOverride(context: Context, profileId: String?): Boolean {
if (profileId.isNullOrBlank()) return false
return runCatching {
val profiles = JSONObject(prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
profiles.optJSONObject(profileId)?.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY) == true
}.getOrDefault(false)
}
fun screenEffectsUpscaler(context: Context, profileId: String?): Int {
if (profileId.isNullOrBlank()) return upscaler(context)
val stored = runCatching {
val profiles = JSONObject(prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
val profile = profiles.optJSONObject(profileId)
if (profile?.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY) == true) {
profile.optInt(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY, -1)
} else -1
}.getOrDefault(-1)
return if (stored >= 0) canonicalUpscaler(stored) else upscaler(context)
}
fun setScreenEffectsUpscaler(context: Context, profileId: String?, mode: Int) {
if (profileId.isNullOrBlank()) {
setUpscaler(context, mode)
return
}
val sessionPrefs = prefs(context)
val profiles = runCatching {
JSONObject(sessionPrefs.getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
}.getOrDefault(JSONObject())
val profile = profiles.optJSONObject(profileId)
?: screenEffects(context, profileId).encode()
profile.put(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY, canonicalUpscaler(mode))
profiles.put(profileId, profile)
sessionPrefs.edit().putString(SCREEN_EFFECTS_PROFILES_KEY, profiles.toString()).apply()
}
fun screenEffectsProfileIds(context: Context): Set<String> {
val profiles = runCatching {
JSONObject(prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
}.getOrElse { JSONObject() }
return buildSet {
val keys = profiles.keys()
while (keys.hasNext()) add(keys.next())
}
}
fun hasScreenEffectsOverride(context: Context, profileId: String?): Boolean {
if (profileId.isNullOrBlank()) return prefs(context).contains("screenEffects")
return profileId in screenEffectsProfileIds(context)
}
fun resetScreenEffectsProfile(context: Context, profileId: String?) {
setScreenEffects(context, profileId, ScreenEffects.OFF)
}
fun deleteScreenEffectsProfile(context: Context, profileId: String?) {
if (profileId.isNullOrBlank()) return
val sessionPrefs = prefs(context)
val profiles = runCatching {
JSONObject(sessionPrefs.getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
}.getOrElse { JSONObject() }
if (!profiles.has(profileId)) return
profiles.remove(profileId)
sessionPrefs.edit().apply {
if (profiles.length() == 0) remove(SCREEN_EFFECTS_PROFILES_KEY)
else putString(SCREEN_EFFECTS_PROFILES_KEY, profiles.toString())
}.apply()
}
const val CARDBOARD_KEY = "cardboard"
fun cardboard(context: Context): Cardboard {
@@ -114,10 +114,7 @@ class SessionService : Service() {
private var freezePending = false
private var freezeCancelled = false
private var pendingSteamGameId: String? = null
private var pendingSteamPreviousGameId: String? = null
private var pendingSteamPreviousGamePending = false
private var pendingSteamGameGeneration = -1
private var pendingSteamGameExitWatchToken = -1
@Volatile private var gameExitWatchToken = 0
private val flushSteamGame = object : Runnable {
override fun run() = flushQueuedSteamGame()
@@ -393,28 +390,9 @@ class SessionService : Service() {
pipTask = false
SessionState.program = intent?.getStringExtra(EXTRA_PROGRAM)
SessionState.programArgs = intent?.getStringArrayExtra(EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
SessionState.gameId = intent?.getStringExtra(EXTRA_GAME_ID)
SessionState.steamUi = intent?.getStringExtra(EXTRA_STEAM_UI)
SessionState.steamUrl = intent?.getStringExtra(EXTRA_STEAM_URL)
val steamUrlGameId = SessionState.steamUrl
?.let { url ->
when {
url.startsWith(GAME_URL_PREFIX) ->
url.removePrefix(GAME_URL_PREFIX)
url.startsWith("steam://run/") ->
url.removePrefix("steam://run/")
else -> null
}
}
?.takeIf(GameLaunchLink::validId)
val resolvedGameId = intent?.getStringExtra(EXTRA_GAME_ID)
?.trim()
?.takeIf(GameLaunchLink::validId)
?: steamUrlGameId
SessionState.gameId = resolvedGameId
SessionPrefs.setActiveScreenEffectsProfile(
this,
SessionPrefs.screenEffectsProfileId(SessionState.mode, resolvedGameId, SessionState.program),
)
com.droiddeck.launcher.stores.battlenet.BattleNetClient.clearRequests(LinuxRuntime.sessionRoot(this))
val gen = synchronized(stopLock) {
SessionState.steamClientArch = null
@@ -435,9 +413,8 @@ class SessionService : Service() {
if (SessionPrefs.clearCachedApps(this)) clearCachedApps()
cancelQueuedSteamGame(clearMailbox = false)
clearSteamGameMailbox()
if (SessionState.mode == MODE_STEAM) {
resolvedGameId?.let { watchGameExit(it, gen, ++gameExitWatchToken) }
}
if (SessionState.mode == MODE_STEAM) SessionState.steamUrl
?.takeIf { it.startsWith(GAME_URL_PREFIX) }?.let { watchGameExit(it.removePrefix(GAME_URL_PREFIX), gen) }
acquireLocks()
Thread({
OrphanReaper.reap("session starting")
@@ -577,7 +554,7 @@ class SessionService : Service() {
val sessionDir = openSessionFolder()
try {
SessionEvents.step("game-environment") { GameEnvironmentStore.publish(this) }
GameEnvironmentStore.publish(this)
} catch (e: Exception) {
Log.e(TAG, "could not publish the game environment", e)
stopSession(-1, gen)
@@ -589,22 +566,22 @@ class SessionService : Service() {
runCatching { sessionLog.appendText(prootLine + "\n") }
.onFailure { Log.w(TAG, "could not write the proot line to ${sessionLog.path}", it) }
Log.i(TAG, SessionEvents.step("gpu-clock-pin") { GpuClockPin.start(this) })
Log.i(TAG, SessionEvents.step("thread-hints") { GameThreadHints.start(this) })
Log.i(TAG, GpuClockPin.start(this))
Log.i(TAG, GameThreadHints.start(this))
val size = SessionState.outputSize
val guest = ArrayList<String>()
val steamHere = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
runCatching { SessionEvents.step("components-republish") { ComponentsManager.republish(this) } }
runCatching { ComponentsManager.republish(this) }
.onSuccess { if (it) Log.i(TAG, "component selections published for the installed Proton builds") }
.onFailure { Log.w(TAG, "component selections", it) }
if (steamHere) {
runCatching { SessionEvents.step("components-forced") { ComponentsManager.ensureForcedPackages(this) } }
runCatching { ComponentsManager.ensureForcedPackages(this) }
.onSuccess { if (it != null) Log.i(TAG, it) }
.onFailure { Log.w(TAG, "forced components", it) }
}
try {
SessionEvents.step("client-environment") { addClientEnvironment(guest, steamHere, agentEnvironment) }
addClientEnvironment(guest, steamHere, agentEnvironment)
} catch (e: IllegalStateException) {
Log.e(TAG, "Could not resolve the selected Linux Vulkan driver", e)
failSession(gen, "VULKAN_DRIVER_UNAVAILABLE", e.message ?: "Selected Linux Vulkan driver is unavailable", -1)
@@ -614,8 +591,8 @@ class SessionService : Service() {
if (steamHere) guest.add("BL_EPIC_APP_ID=" + com.droiddeck.launcher.stores.epic.EpicClient.shortcutAppId)
val fastPathAt = guest.size
val pulse = SessionEvents.step("audio") { startAudio(guest, sessionDir, directAudioPack) }
SessionEvents.step("vk-bridge") { startVkBridge(guest, sessionDir) }
val pulse = startAudio(guest, sessionDir, directAudioPack)
startVkBridge(guest, sessionDir)
if (VenusComponent.wanted(this)) {
components.add(VenusComponent(File(sessionDir, "venus.log")).also { it.attach(this) })
}
@@ -661,20 +638,20 @@ class SessionService : Service() {
deckBinds = emptyList()
inputSysfs = null
if (controllersOn) {
SessionEvents.step("controller-environment") { addControllerEnvironment(guest, fakeInputDir, sessionDir) }
SessionEvents.step("controller-sync") { SessionState.padBridge?.syncConnectedControllers() }
addControllerEnvironment(guest, fakeInputDir, sessionDir)
SessionState.padBridge?.syncConnectedControllers()
}
val noSteamGame = noSteamGame()
if (noSteamGame) guest.add("BL_PIN_CORES=0")
if ((steamHere || SessionState.program == NoSteamLaunch.EPIC) && com.droiddeck.launcher.stores.epic.EpicClient.read(this).installed) {
runCatching { SessionEvents.step("epic-library") { com.droiddeck.launcher.stores.epic.EpicClientLibrary.sync(this) } }
runCatching { com.droiddeck.launcher.stores.epic.EpicClientLibrary.sync(this) }
.onFailure { Log.w(TAG, "Epic library sync failed", it) }
runCatching { SessionEvents.step("epic-install-dir") { com.droiddeck.launcher.stores.epic.EpicClient.prepareInstallDir(this) } }
runCatching { com.droiddeck.launcher.stores.epic.EpicClient.prepareInstallDir(this) }
.onFailure { Log.w(TAG, "Epic install directory setup failed", it) }
}
if (steamHere || noSteamGame) {
val added = SessionEvents.step("added-games-scan") { com.droiddeck.launcher.frontend.AddedGames.scan(this) }
val listing = SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added) }
val added = com.droiddeck.launcher.frontend.AddedGames.scan(this)
val listing = com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added)
guest.add("BL_ADDED_GAMES=" + listing.path)
if (OfflineMode.enabled(this)) guest.add("BL_STEAM_OFFLINE=1")
if (com.droiddeck.launcher.gpu.Lossless.owned(this)) guest.add("BL_LOSSLESS_OWNED=1")
@@ -686,7 +663,7 @@ class SessionService : Service() {
// Detailed graphics logs: per-game logs and the guest's Vulkan summary (a GPU that is not
// an Adreno, or Setup's switch), and graphics-report.txt for every session.
if (GraphicsReport.detailed(this)) guest.add("BL_GAME_LOGS=1")
SessionEvents.step("graphics-report") { GraphicsReport.begin(this, sessionDir, guest) }
GraphicsReport.begin(this, sessionDir, guest)
val shellGuest = ArrayList(guest).apply {
add("SHELL=/bin/bash")
add("TERM=xterm-256color")
@@ -714,7 +691,7 @@ class SessionService : Service() {
Log.i(TAG, "run: $program (${SessionState.programArgs.size} arguments) under gamescope")
}
SessionEvents.step("shm-clear") { FileUtils.clear(File(LinuxRuntime.liveDir(this), "shm")) }
FileUtils.clear(File(LinuxRuntime.liveDir(this), "shm"))
val binds = sessionBinds(controllersOn, fakeInputDir, sessionDir, guest, sessionRoot, runtimeDir)
val nativeUserland = com.droiddeck.launcher.runtime.NativeGuest.enabled(this)
@@ -820,7 +797,7 @@ class SessionService : Service() {
watchLaunchRequests(sessionRoot)
watchSyncWanted(root)
EsyncPacks.fetchInBackground(this, root)
val pid = SessionEvents.step("guest-launch") { HostProcess.start(line, hostEnv.asArray(), root, { status ->
val pid = HostProcess.start(line, hostEnv.asArray(), root, { status ->
if (gen != sessionGen) {
Log.i(TAG, "an earlier session's process ended ($status); the current one carries on")
return@start
@@ -828,7 +805,7 @@ class SessionService : Service() {
val program = programStatus(sessionRoot)
Log.i(TAG, "session ended: $status" + if (program != null) " (program $program)" else "")
stopSession(program ?: status ?: -1, gen)
}, null, sessionLog.takeIf { "PROOT_PROFILE=1" in hostEnv.asArray() }) }
}, null, sessionLog.takeIf { "PROOT_PROFILE=1" in hostEnv.asArray() })
Log.i(TAG, "session pid $pid, log ${sessionLog.path}")
if (gen != sessionGen || !SessionState.running) {
Log.i(TAG, "session stopped while its guest was starting; taking it down")
@@ -916,7 +893,7 @@ class SessionService : Service() {
if (EnhancedDiagnostics.isActive(this, sessionDir)) SessionEvents.record("diagnostics.enhanced", mapOf("schema" to 1))
DeviceReport.write(this, File(sessionDir, "device.txt"), SessionState.mode)
NetworkReport.write(this, File(sessionDir, "network.txt"))
SessionLogCapture.start(File(sessionDir, "app.log"), SessionPaths.startedAt(sessionDir))
SessionLogCapture.start(File(sessionDir, "app.log"))
MemoryLog.start()
return sessionDir
}
@@ -1037,13 +1014,13 @@ class SessionService : Service() {
guest.add("BL_ZRAM=1")
if (steamHere) SessionPrefs.ramCapMb(this).takeIf { it > 0 }?.let { guest.add("BL_RAM_CAP_MB=$it") }
if (!SessionPrefs.zramClient(this)) guest.add("BL_ZRAM_CLIENT=0")
if (!SessionPrefs.zramIdle(this)) guest.add("BL_ZRAM_IDLE=0")
}
SessionPrefs.vramCapMb(this).takeIf { it > 0 }?.let { guest.add("BL_VRAM_MB=$it") }
guest.add("AUDIO_DIRECT_DECAY=0")
val extra = extraEnv() + agentEnvironment
guest.addAll(TurnipEnvironment.gameEnvironment(tuOverride, tuDriver, SessionPrefs.tuSysmem(this), extra))
if (extra.none { it.startsWith("MESA_NO_ERROR=") }) guest.add("${GAME_PREFIX}MESA_NO_ERROR=")
mapOf("TU_DEBUG" to (tuOverride ?: if (tuDriver) "sysmem" else ""), "MESA_NO_ERROR" to "").forEach { (name, game) ->
if (extra.none { it.startsWith("$name=") }) guest.add("$GAME_PREFIX$name=$game")
}
extra.forEach { guest.add(it) }
com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice(this)?.let { guest.add("${com.droiddeck.launcher.gpu.TpUbwcHint.ENV}=$it") }
val clientPinned = steamHere && SessionPrefs.clientCpusOverride(this)
@@ -1544,19 +1521,7 @@ class SessionService : Service() {
return
}
val accepted = gameId!!
if (!pendingSteamPreviousGamePending) {
pendingSteamPreviousGameId = SessionState.gameId
pendingSteamPreviousGamePending = true
}
if (pendingSteamGameId != null) {
Log.i(TAG, "replacing queued game ${pendingSteamGameId} with $accepted")
}
pendingSteamGameExitWatchToken = ++gameExitWatchToken
SessionState.gameId = accepted
val effectsProfileId = SessionPrefs.screenEffectsProfileId(MODE_STEAM, accepted, null)
SessionPrefs.setActiveScreenEffectsProfile(this, effectsProfileId)
SessionPrefs.screenEffects(this, effectsProfileId)
.push(SessionPrefs.screenEffectsUpscaler(this, effectsProfileId))
if (pendingSteamGameId != null) Log.i(TAG, "replacing a queued game launch with $accepted")
pendingSteamGameId = accepted
pendingSteamGameGeneration = sessionGen
if (SessionState.suspended) resumeSession()
@@ -1567,29 +1532,9 @@ class SessionService : Service() {
private fun flushQueuedSteamGame() {
val gameId = pendingSteamGameId ?: return
val gen = pendingSteamGameGeneration
val exitWatchToken = pendingSteamGameExitWatchToken
if (exitWatchToken != gameExitWatchToken) return
if (gen != sessionGen || !SessionState.running || SessionState.stopRequested ||
SessionState.mode != MODE_STEAM || SessionState.gameId != gameId ||
!GameLaunchLink.validId(gameId)) {
val previousGameId = pendingSteamPreviousGameId
val queuedProfileId = SessionPrefs.screenEffectsProfileId(MODE_STEAM, gameId, null)
val canRestore = gen == sessionGen &&
SessionState.running && !SessionState.stopRequested &&
SessionState.mode == MODE_STEAM &&
SessionState.gameId == gameId &&
SessionPrefs.activeScreenEffectsProfileId(this) == queuedProfileId
SessionState.mode != MODE_STEAM || !GameLaunchLink.validId(gameId)) {
cancelQueuedSteamGame()
if (canRestore) {
SessionState.gameId = previousGameId
val previousProfileId =
SessionPrefs.screenEffectsProfileId(MODE_STEAM, previousGameId, null)
SessionPrefs.setActiveScreenEffectsProfile(this, previousProfileId)
SessionPrefs.screenEffects(this, previousProfileId)
.push(SessionPrefs.screenEffectsUpscaler(this, previousProfileId))
}
return
}
if (SessionState.suspended) {
@@ -1616,95 +1561,33 @@ class SessionService : Service() {
}
pendingSteamGameId = null
pendingSteamGameGeneration = -1
pendingSteamGameExitWatchToken = -1
SessionEvents.record("steam.game_launch_requested", mapOf("gameId" to gameId, "generation" to gen))
watchGameExit(gameId, gen, exitWatchToken, pendingSteamPreviousGameId)
watchGameExit(gameId, gen)
Log.i(TAG, "queued Steam game $gameId for the running client")
}
private fun watchGameExit(
gameId: String,
gen: Int,
token: Int,
previousGameId: String? = null
) {
private fun watchGameExit(gameId: String, gen: Int) {
if (!SessionPrefs.returnAfterGame(this)) return
val token = ++gameExitWatchToken
Thread({
var startupRemaining = GAME_START_TIMEOUT_MS
var lastStartupCheck = android.os.SystemClock.elapsedRealtime()
var startupWasSuspended = false
val startBy = android.os.SystemClock.elapsedRealtime() + GAME_START_TIMEOUT_MS
var seen = false
var goneSince = 0L
while (token == gameExitWatchToken && gen == sessionGen && SessionState.running && !SessionState.stopRequested) {
val now = android.os.SystemClock.elapsedRealtime()
val startupSuspended = SessionState.suspended || SessionState.suspending || SessionState.phase != SessionPhase.READY
if (!seen) {
if (startupSuspended) {
startupWasSuspended = true
lastStartupCheck = now
} else if (startupWasSuspended) {
startupWasSuspended = false
lastStartupCheck = now
} else {
startupRemaining -= (now - lastStartupCheck).coerceAtLeast(0L)
lastStartupCheck = now
}
}
if (steamGameRunning(gameId)) {
if (!seen) {
Log.i(TAG, "game $gameId started; tracking its exit")
mainHandler.post {
if (token == gameExitWatchToken && gen == sessionGen &&
pendingSteamPreviousGamePending &&
pendingSteamPreviousGameId == previousGameId) {
pendingSteamPreviousGameId = null
pendingSteamPreviousGamePending = false
}
}
}
if (steamGameRunning()) {
if (!seen) Log.i(TAG, "game $gameId started; returning to the launcher when it closes")
seen = true
goneSince = 0L
} else if (!seen) {
if (!startupSuspended && startupRemaining <= 0L) {
mainHandler.post {
if (token != gameExitWatchToken || gen != sessionGen ||
!SessionState.running || SessionState.stopRequested) {
return@post
}
if (previousGameId != null && steamGameRunning(previousGameId)) {
Log.w(TAG, "game $gameId did not start; restoring previous game $previousGameId")
SessionState.gameId = previousGameId
val previousProfileId =
SessionPrefs.screenEffectsProfileId(MODE_STEAM, previousGameId, null)
val failedGameProfileId =
SessionPrefs.screenEffectsProfileId(MODE_STEAM, gameId, null)
if (SessionPrefs.activeScreenEffectsProfileId(this@SessionService) == failedGameProfileId) {
SessionPrefs.setActiveScreenEffectsProfile(this@SessionService, previousProfileId)
SessionPrefs.screenEffects(this@SessionService, previousProfileId)
.push(SessionPrefs.screenEffectsUpscaler(this@SessionService, previousProfileId))
}
pendingSteamPreviousGameId = null
pendingSteamPreviousGamePending = false
watchGameExit(previousGameId, gen, token)
} else {
Log.i(TAG, "game $gameId did not start; clearing its screen effects profile")
pendingSteamPreviousGameId = null
pendingSteamPreviousGamePending = false
clearActiveScreenEffectsProfile(gameId, gen, token)
}
}
if (now > startBy) {
Log.i(TAG, "game $gameId did not start; not watching for its exit")
return@Thread
}
} else if (goneSince == 0L) {
goneSince = now
} else if (now - goneSince >= GAME_EXIT_GRACE_MS) {
mainHandler.post {
if (SessionPrefs.returnAfterGame(this@SessionService)) {
returnAfterGame(gameId, gen, token)
} else {
clearActiveScreenEffectsProfile(gameId, gen, token)
}
}
mainHandler.post { returnAfterGame(gameId, gen, token) }
return@Thread
}
try { Thread.sleep(GAME_EXIT_POLL_MS) } catch (e: InterruptedException) { return@Thread }
@@ -1712,52 +1595,17 @@ class SessionService : Service() {
}, "game-exit-watch").start()
}
private fun clearActiveScreenEffectsProfile(gameId: String, gen: Int, token: Int) {
if (token != gameExitWatchToken || gen != sessionGen || !SessionState.running || SessionState.stopRequested) return
val gameProfileId = SessionPrefs.screenEffectsProfileId(MODE_STEAM, gameId, null)
if (SessionPrefs.activeScreenEffectsProfileId(this) != gameProfileId) return
SessionPrefs.setActiveScreenEffectsProfile(this, null)
SessionPrefs.screenEffects(this, null).push(SessionPrefs.screenEffectsUpscaler(this, null))
}
private fun returnAfterGame(gameId: String, gen: Int, token: Int) {
mainHandler.postDelayed({
if (token != gameExitWatchToken || gen != sessionGen || !SessionState.running ||
SessionState.stopRequested || SessionState.mode != MODE_STEAM ||
SessionState.gameId != gameId || pendingSteamGameId != null) {
return@postDelayed
}
if (steamGameRunning(gameId)) {
Log.i(TAG, "game $gameId is running again; restarting its exit watcher")
watchGameExit(gameId, gen, token)
return@postDelayed
}
if (SteamGameProcess.running()) {
Log.i(TAG, "another Steam game is still running after $gameId; checking again")
returnAfterGame(gameId, gen, token)
return@postDelayed
}
clearActiveScreenEffectsProfile(gameId, gen, token)
if (!SessionPrefs.returnAfterGame(this)) {
Log.i(TAG, "return after game disabled; keeping the Steam session open")
return@postDelayed
}
val written = runCatching { File(LinuxRuntime.sessionRoot(this), "steam-stop").writeText("") }
.onFailure { Log.w(TAG, "could not ask the client to exit after game $gameId", it) }.isSuccess
if (!written) return@postDelayed
SessionEvents.record("steam.return_after_game", mapOf("gameId" to gameId))
Log.i(TAG, "game $gameId closed: asking the client to exit and returning to the launcher")
}, GAME_EXIT_CONFIRM_MS)
if (token != gameExitWatchToken || gen != sessionGen || !SessionState.running ||
SessionState.stopRequested || SessionState.mode != MODE_STEAM || !SessionPrefs.returnAfterGame(this)) return
val written = runCatching { File(LinuxRuntime.sessionRoot(this), "steam-stop").writeText("") }
.onFailure { Log.w(TAG, "could not ask the client to exit after game $gameId", it) }.isSuccess
if (!written) return
SessionEvents.record("steam.return_after_game", mapOf("gameId" to gameId))
Log.i(TAG, "game $gameId closed: asking the client to exit and returning to the launcher")
}
private fun steamGameRunning(gameId: String): Boolean =
SteamGameProcess.running(gameId)
private fun steamGameRunning(): Boolean = SteamGameProcess.running()
private fun resumeSession(panelVisible: Boolean = true) {
if (SessionState.suspended) SessionState.resumeRequested = true
@@ -1777,11 +1625,7 @@ class SessionService : Service() {
private fun cancelQueuedSteamGame(clearMailbox: Boolean = true) {
mainHandler.removeCallbacks(flushSteamGame)
pendingSteamGameId = null
pendingSteamPreviousGameId = null
pendingSteamPreviousGamePending = false
pendingSteamGameGeneration = -1
pendingSteamGameExitWatchToken = -1
gameExitWatchToken++
if (clearMailbox) clearSteamGameMailbox()
}
@@ -2264,11 +2108,10 @@ class SessionService : Service() {
syncWatcher = null
val prootPid = sessionPid
sessionPid = -1
// The kept shell goes through the same teardown, which reads its descendants before signalling it.
val shell = SessionTerminal.detach(sessionGen)?.let { pid -> readStat(pid)?.second?.let { pid to it } }
val auxiliary = synchronized(auxiliaryProcessesLock) {
auxiliaryProcesses.toMap().also { auxiliaryProcesses.clear() }
} + listOfNotNull(shell)
}
SessionTerminal.clear(sessionGen)
BottomDesktop.stop(this, stoppedGen)
val controller = suspendController
suspendController = null
@@ -2605,7 +2448,6 @@ class SessionService : Service() {
private const val GAME_URL_PREFIX = "steam://rungameid/"
private const val GAME_START_TIMEOUT_MS = 20 * 60_000L
private const val GAME_EXIT_GRACE_MS = 10_000L
private const val GAME_EXIT_CONFIRM_MS = 2_000L
private const val GAME_EXIT_POLL_MS = 2_000L
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
private const val NO_UINPUT_SWITCH = "Download/droiddeck-no-uinput"
@@ -14,12 +14,6 @@ object SessionTerminal {
@Volatile private var launch: Launch? = null
private class Kept(val session: TerminalSession, val generation: Int)
// The bottom screen's presentation is dismissed whenever another app covers that display
// (a browser opened for a sign-in), so its shell is kept for the next panel.
@Volatile private var kept: Kept? = null
fun prepare(
command: List<String>,
hostEnvironment: Array<String>,
@@ -38,41 +32,8 @@ object SessionTerminal {
).also { it.mSessionName = "DroidDeck Linux shell" }
}
fun reuse(client: TerminalSessionClient): TerminalSession? {
val current = kept ?: return null
if (current.generation != launch?.generation || !current.session.isRunning) {
kept = null
return null
}
current.session.updateTerminalSessionClient(client)
return current.session
}
fun keep(session: TerminalSession) {
val generation = launch?.generation ?: return
kept = Kept(session, generation)
}
fun release(session: TerminalSession?) {
if (session != null && kept?.session === session) kept = null
}
fun clear(generation: Int? = null) {
val current = launch ?: return
if (generation == null || current.generation == generation) {
launch = null
kept?.session?.takeIf { it.pid > 0 }?.finishIfRunning()
kept = null
}
}
/** Ends this generation's terminal without killing its shell, and returns the shell's pid if it still runs. */
fun detach(generation: Int): Int? {
val current = launch ?: return null
if (current.generation != generation) return null
launch = null
val pid = kept?.session?.takeIf { it.isRunning && it.pid > 0 }?.pid
kept = null
return pid
if (generation == null || current.generation == generation) launch = null
}
}
@@ -16,17 +16,17 @@ object SettingsReset {
"dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard",
"gameStoresEnabled", "soundtracksEnabled", "soundtracksIngame", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
"storesInstallLanguage",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "backActionsInverted", "backDoubleTapMs", "touch", "osc", "shape", "steamController",
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
"stretch16x9", "picturePosition", "railLabels", "agentTab", "navTabOrder", "navTabShelved", "navTabHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores", "ramCapMb", "vramCapMb", "zramClient", "zramIdle",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores", "ramCapMb", "vramCapMb", "zramClient",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "nativeUserland", "cursorComposite",
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics", "buildWatermark",
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds", "skipBootMovie",
"bootMovieApplyNext", "bootMovieSteamSeen", "bootMovieShuffle",
"bootMovieApplyNext", "bootMovieSteamSeen",
"questDefaultsV1", "telemetryAuto", "telemetryOff", "statsStrip", "statsHud", "bottomHud", "bottomStripMetrics", "bottomStripTabs", "statsDash", "statsSpeedUnit",
)
@@ -5,59 +5,14 @@ import java.io.File
object SteamGameProcess {
fun matches(cmdline: ByteArray): Boolean {
val args = String(cmdline).split('\u0000')
return args.indices.any { i ->
args[i] == "waitforexitandrun" ||
(args[i] == "SteamLaunch" &&
args.getOrNull(i + 1)?.startsWith("AppId=") == true)
}
}
fun running(): Boolean =
File("/proc").listFiles()?.any { p ->
p.name.all(Char::isDigit) &&
runCatching { File(p, "cmdline").readBytes() }
.getOrNull()?.let(::matches) == true
} == true
private fun steamAppIdForGameId(gameId: String): String? {
if (gameId.isEmpty() || !gameId.all(Char::isDigit)) return null
val numericId = gameId.toULongOrNull() ?: return null
val appId = if (numericId > UInt.MAX_VALUE.toULong()) {
numericId shr 32
} else {
numericId
}
return appId.takeIf { it != 0uL }?.toString()
}
fun matches(cmdline: ByteArray, gameId: String): Boolean {
val expectedAppId = steamAppIdForGameId(gameId) ?: return false
val args = String(cmdline).split('\u0000')
for (i in args.indices) {
if (args[i] == "SteamLaunch") {
val appId = args.getOrNull(i + 1)
?.takeIf { it.startsWith("AppId=") }
?.removePrefix("AppId=")
if (appId == expectedAppId) return true
}
if (args[i] == "-applaunch" &&
args.getOrNull(i + 1) == expectedAppId
) {
return true
}
if (args[i] == "waitforexitandrun") return true
if (args[i] == "SteamLaunch" && args.getOrNull(i + 1)?.startsWith("AppId=") == true) return true
}
return false
}
fun running(gameId: String, proc: File = File("/proc")): Boolean =
proc.listFiles()?.any { p ->
p.name.all(Char::isDigit) &&
runCatching { File(p, "cmdline").readBytes() }
.getOrNull()?.let { matches(it, gameId) } == true
} == true
fun running(proc: File = File("/proc")): Boolean = proc.listFiles()?.any { p ->
p.name.all(Char::isDigit) && runCatching { File(p, "cmdline").readBytes() }.getOrNull()?.let(::matches) == true
} == true
}
@@ -1,16 +0,0 @@
package com.droiddeck.launcher.session
internal object TurnipEnvironment {
const val GAME_TU_DEBUG = "DROIDDECK_GAME_TU_DEBUG"
fun gameEnvironment(
tuOverride: String?,
tuDriver: Boolean,
tuSysmem: Boolean,
extra: List<String>,
): List<String> = if (extra.none { it.startsWith("TU_DEBUG=") }) {
listOf("$GAME_TU_DEBUG=${tuOverride ?: if (tuDriver || tuSysmem) "sysmem" else ""}")
} else {
emptyList()
}
}
@@ -25,11 +25,9 @@ object CloudSaves {
private const val PARALLEL = 6
private const val CLOUD_LAYOUT = 2
class Result(val result: String, val files: Int, val bytes: Long, val reason: String, val conflicts: Int = 0, val detail: String = "") {
class Result(val result: String, val files: Int, val bytes: Long, val reason: String, val conflicts: Int = 0) {
val ok: Boolean get() = result != "failed"
val line: String get() = "result=$result files=$files bytes=$bytes reason=$reason" +
(if (conflicts > 0) " conflicts=$conflicts" else "") +
if (detail.isNotEmpty()) " detail=\"$detail\"" else ""
val line: String get() = "result=$result files=$files bytes=$bytes reason=$reason" + if (conflicts > 0) " conflicts=$conflicts" else ""
}
class Status(val supported: Boolean, val folder: File?, val lastSync: Long, val reason: String, val conflicts: List<String> = emptyList())
@@ -128,7 +126,7 @@ object CloudSaves {
)
if (picked == null) GogConfig("", "") else GogConfig(picked.name, picked.template)
} catch (e: Exception) {
Log.w(TAG, "gog remote-config: ${cloudFailureDetail(e)}")
Log.w(TAG, "gog remote-config: ${e.javaClass.simpleName}")
null
}
}
@@ -168,7 +166,7 @@ object CloudSaves {
val galaxy = GogAuth.validToken(context)
val clientId = gogClientId(context, id, folder)
if (userId.isEmpty() || galaxy == null || clientId == null) null
else GogCloud(userId, clientId, gogScopedToken(context, id, clientId) ?: galaxy, gogLocationName(context, id, folder), tempDir = context.cacheDir)
else GogCloud(userId, clientId, gogScopedToken(context, id, clientId) ?: galaxy, gogLocationName(context, id, folder))
}
Store.EPIC -> {
val token = EpicCredentialStore.getValidAccessToken(context)
@@ -314,7 +312,7 @@ object CloudSaves {
rememberNoCloud(prefs(context, store), id)
Result("skipped", 0, 0, "no-cloud-saves")
} catch (e: Exception) {
Result("failed", 0, 0, e.javaClass.simpleName, detail = cloudFailureDetail(e))
Result("failed", 0, 0, e.javaClass.simpleName)
}
return done(store, id, way, result)
}
@@ -59,69 +59,6 @@ private fun httpDate(s: String?): Long = try {
SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US).apply { timeZone = TimeZone.getTimeZone("GMT") }.parse(s!!.trim())?.time ?: -1L
} catch (e: Exception) { -1L }
private val SECRET_PARAM = Regex("(?i)(token|secret|code|password|authorization)([\"']?\\s*[:=]\\s*[\"']?)[^\\s&\"',;}]+")
private val BEARER = Regex("(?i)bearer\\s+\\S+")
private val URL_TEXT = Regex("(?i)https?://(?:[^/\\s?#@]*@)?([^/\\s?#@]+)[^\\s]*")
private val LONG_TOKEN = Regex("[A-Za-z0-9._~+/=-]{32,}")
private val SPACES = Regex("\\s+")
private const val DETAIL_MAX = 400
internal fun scrubCloudText(text: String, longTokens: Boolean = true): String = text
.replace(BEARER, "Bearer <redacted>")
.replace(URL_TEXT) { it.groupValues[1] }
.replace(SECRET_PARAM) { it.groupValues[1] + it.groupValues[2] + "<redacted>" }
.let { if (longTokens) it.replace(LONG_TOKEN, "<redacted>") else it }
.replace(SPACES, " ")
.trim()
internal fun cloudFailureDetail(e: Throwable): String {
val parts = ArrayList<String>()
var t: Throwable? = e
while (t != null && parts.size < 3) {
val message = t.message?.let { scrubCloudText(it, longTokens = false) }.orEmpty()
parts += if (message.isEmpty()) t.javaClass.simpleName else "${t.javaClass.simpleName}: $message"
t = t.cause?.takeIf { it !== t }
}
return parts.joinToString(" <- ").take(DETAIL_MAX)
}
private const val SNIPPET_READ_MAX = 4096
private const val SNIPPET_MAX = 120
private data class CloudErrorPrefix(val text: String, val truncated: Boolean) {
fun snippet(): String {
val safe = if (truncated) text.substring(0, text.indexOfLast { it.isWhitespace() }.coerceAtLeast(0)) else text
return scrubCloudText(safe).take(SNIPPET_MAX)
}
}
private fun cloudErrorPrefix(input: InputStream?): CloudErrorPrefix {
if (input == null) return CloudErrorPrefix("", false)
return input.use { stream ->
val buffer = ByteArray(SNIPPET_READ_MAX + 1)
var read = 0
while (read < buffer.size) {
val n = stream.read(buffer, read, buffer.size - read)
if (n < 0) break
read += n
}
CloudErrorPrefix(buffer.decodeToString(0, minOf(read, SNIPPET_READ_MAX)), read > SNIPPET_READ_MAX)
}
}
internal fun cloudErrorSnippet(input: InputStream?): String =
cloudErrorPrefix(input).snippet()
private fun HttpURLConnection.errorSnippet(): String =
runCatching { cloudErrorSnippet(errorStream) }.getOrDefault("")
private fun httpFailure(step: String, name: String?, code: Int, error: String): java.io.IOException =
java.io.IOException(buildString {
append("GOG cloud ").append(step).append(" HTTP ").append(code)
if (name != null) append(" file=").append(name)
if (error.isNotEmpty()) append(" body=").append(error)
})
internal fun isGzip(data: ByteArray) =
data.size >= 10 && data[0] == 0x1f.toByte() && data[1] == 0x8b.toByte() && data[2] == 0x08.toByte()
@@ -246,8 +183,6 @@ private fun gzipFile(src: File, dst: File): GzipFile {
}
}
internal const val GOG_CLOUD_UA = "GOGGalaxyCommunicationService/2.0.13.27 (Windows_32bit) dont_sync_marker/true installation_source/gog"
/** GOG Galaxy parses `X-Object-Meta-LocalLastModified`; objects without it fail as "invalid data". */
private val GOG_STAMP = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssxxx", Locale.US)
@@ -260,10 +195,9 @@ class GogCloud(
private val token: String,
private val location: String? = null,
baseUrl: String? = null,
private val tempDir: File? = null,
) : CloudTransport {
private val base = baseUrl ?: "https://cloudstorage.gog.com/v1/$userId/$clientId"
private val ua = GOG_CLOUD_UA
private val ua = "GOG Galaxy"
private var prefix: String? = location?.let { "$it/" }
private fun key(name: String) = URLEncoder.encode(name, "UTF-8").replace("+", "%20")
@@ -275,10 +209,10 @@ class GogCloud(
val code = c.responseCode
if (code == 404) { c.disconnect(); return emptyList() }
if (code !in 200..299) {
val err = runCatching { cloudErrorPrefix(c.errorStream) }.getOrDefault(CloudErrorPrefix("", false))
val err = runCatching { c.errorStream?.readBytes()?.decodeToString().orEmpty() }.getOrDefault("")
c.disconnect()
if ("not_enabled_for_client" in err.text || "disabled" in err.text) throw NoCloudSaves()
throw httpFailure("list", null, code, err.snippet())
if ("not_enabled_for_client" in err || "disabled" in err) throw NoCloudSaves()
throw java.io.IOException("GOG cloud list HTTP $code")
}
val text = c.body().decodeToString().trim()
c.disconnect()
@@ -321,20 +255,12 @@ class GogCloud(
override fun get(file: CloudFile): Pair<ByteArray, Long> {
val c = open("$base/${cloudKey(file.name)}", "GET", token, ua)
c.setRequestProperty("Accept-Encoding", "identity")
if (c.responseCode !in 200..299) {
val code = c.responseCode
val err = c.errorSnippet()
c.disconnect()
throw httpFailure("get", file.name, code, err)
}
if (c.responseCode !in 200..299) { val code = c.responseCode; c.disconnect(); throw java.io.IOException("GOG cloud get HTTP $code") }
val modified = httpDate(c.getHeaderField("Last-Modified"))
val encoding = c.getHeaderField("Content-Encoding")
val data = try { c.body() } finally { c.disconnect() }
return try {
gogDecodeCloudBody(data, encoding) to modified
} catch (e: java.io.IOException) {
throw java.io.IOException("GOG cloud get file=${file.name} bytes=${data.size} encoding=$encoding", e)
}
val data = c.body()
c.disconnect()
return gogDecodeCloudBody(data, encoding) to modified
}
override fun put(files: Map<String, ByteArray>, modifiedMs: Map<String, Long>): Map<String, Long> = files.mapValues { (name, data) ->
@@ -343,11 +269,7 @@ class GogCloud(
}
override fun putFiles(files: Map<String, File>, modifiedMs: Map<String, Long>): Map<String, CloudPut> = files.mapValues { (name, file) ->
val compressed = try {
File.createTempFile("gog-cloud-", ".gz", tempDir?.apply { mkdirs() })
} catch (e: java.io.IOException) {
throw java.io.IOException("GOG cloud put file=$name temp file", e)
}
val compressed = File.createTempFile("gog-cloud-", ".gz")
try {
val gz = gzipFile(file, compressed)
val modified = putBody(name, compressed.inputStream(), gz.length, gz.etag, modifiedMs[name] ?: file.lastModified())
@@ -365,16 +287,10 @@ class GogCloud(
c.setRequestProperty("Content-Encoding", "gzip")
c.setRequestProperty("Etag", etag)
c.setRequestProperty("X-Object-Meta-LocalLastModified", gogStamp(modified))
c.setRequestProperty("X-Object-Meta-User-Agent", ua)
c.setFixedLengthStreamingMode(length)
try {
c.outputStream.use { out -> source.use { it.copyTo(out, 64 * 1024) } }
} catch (e: java.io.IOException) {
val code = runCatching { c.responseCode }.getOrNull()
throw java.io.IOException("GOG cloud put file=$name bytes=$length" + (code?.let { " HTTP $it" } ?: ""), e)
}
c.outputStream.use { out -> source.use { it.copyTo(out, 64 * 1024) } }
val code = c.responseCode
if (code !in 200..299) throw httpFailure("put", name, code, c.errorSnippet())
if (code !in 200..299) throw java.io.IOException("GOG cloud put HTTP $code")
return CloudFile(name, -1L).also { details(it) }.modifiedMs
} finally {
c.disconnect()
@@ -84,11 +84,6 @@ object EpicBackend : StoreBackend, EpicLaunchSupport {
Store.EPIC, item.id, item.title, cover = item.imageUrl, bytesTotal = item.sizeBytes,
location = StoreInstallRoot.labelFor(app, folder),
)
val launcher = item.extra["thirdPartyManagedApp"].orEmpty()
if (launcher.isNotBlank()) {
DownloadQueue.recordFailed(app, entry, app.getString(R.string.epic_third_party_managed, launcher))
return
}
DownloadQueue.enqueue(app, entry) { EpicInstaller(app, item, folder) }
}
@@ -26,7 +26,6 @@ data class EpicGame(
val publisher: String = "",
val isDlc: Boolean = false,
val artLogo: String = "",
val thirdPartyManagedApp: String = "",
)
object EpicLibrary {
@@ -53,10 +52,7 @@ object EpicLibrary {
.put("developer", g.developer).put("description", g.description).put("version", g.version)
.put("installSize", g.installSize).put("canRunOffline", g.canRunOffline)
.put("releaseDate", g.releaseDate).put("publisher", g.publisher)
.apply {
if (g.artLogo.isNotEmpty()) put("artLogo", g.artLogo)
if (g.thirdPartyManagedApp.isNotEmpty()) put("thirdPartyManagedApp", g.thirdPartyManagedApp)
},
.apply { if (g.artLogo.isNotEmpty()) put("artLogo", g.artLogo) },
)
}.toString()
@@ -80,7 +76,6 @@ object EpicLibrary {
releaseDate = o.optString("releaseDate", ""),
publisher = o.optString("publisher", ""),
artLogo = o.optString("artLogo", ""),
thirdPartyManagedApp = o.optString("thirdPartyManagedApp", ""),
)
}
return tidy(games)
@@ -113,12 +108,7 @@ object EpicLibrary {
owned = true,
sizeBytes = prefs.getLong("size_${game.appName}", 0L).takeIf { it > 0 } ?: game.installSize,
storeUrl = "https://store.epicgames.com/en-US/browse?q=" + URLEncoder.encode(title, "UTF-8"),
extra = mapOf(
"namespace" to game.namespace,
"catalogItemId" to game.catalogItemId,
"version" to game.version,
"thirdPartyManagedApp" to game.thirdPartyManagedApp,
),
extra = mapOf("namespace" to game.namespace, "catalogItemId" to game.catalogItemId, "version" to game.version),
logoUrl = game.artLogo.ifEmpty { null },
)
}
@@ -143,7 +133,6 @@ object EpicLibrary {
publisher = pick("publisher", before?.publisher.orEmpty()),
isDlc = d.optBoolean("dlc", false),
artLogo = pick("logo", before?.artLogo.orEmpty()),
thirdPartyManagedApp = details?.optString("thirdPartyManagedApp", "") ?: before?.thirdPartyManagedApp.orEmpty(),
)
}
@@ -6,8 +6,6 @@ import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
@@ -21,7 +19,6 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.CheckCircle
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.Description
import androidx.compose.material.icons.outlined.ContentCopy
import androidx.compose.material.icons.outlined.ErrorOutline
import androidx.compose.material.icons.outlined.ExpandLess
import androidx.compose.material.icons.outlined.ExpandMore
@@ -42,8 +39,6 @@ import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
@@ -58,13 +53,9 @@ import com.droiddeck.launcher.R
import com.droiddeck.launcher.agent.AgentAttachments
import com.droiddeck.launcher.agent.AgentHost
import com.droiddeck.launcher.agent.AgentHost.Entry
import com.droiddeck.launcher.agent.choices
@Composable
internal fun AgentEntry(
entry: Entry, running: Boolean, last: Boolean = false, changes: Changes? = null, answerable: Boolean = false,
children: List<Entry.Used> = emptyList(), turn: List<Entry> = emptyList(), onRevise: () -> Unit = {}, onSent: () -> Unit = {},
) {
internal fun AgentEntry(entry: Entry, running: Boolean, last: Boolean = false, changes: Changes? = null, onRevise: () -> Unit = {}) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
when (entry) {
@@ -75,43 +66,24 @@ internal fun AgentEntry(
modifier = Modifier.widthIn(max = 560.dp).clip(Shape16).background(pal.primary).padding(horizontal = 14.dp, vertical = 10.dp))
}
}
is Entry.Said -> {
val reply = remember(entry.text) { choices(entry.text) }
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
if (reply.text.isNotBlank()) SelectionContainer { AgentMarkdown(reply.text, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp)) }
if (reply.options.isNotEmpty()) AgentChoices(reply.options, answerable, onSent)
}
}
is Entry.Said -> SelectionContainer { AgentMarkdown(entry.text, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp)) }
is Entry.Thought -> AgentThought(entry.text, live = false)
is Entry.Used -> if (entry.tool == "TodoWrite") AgentTodos(entry.input) else AgentToolCall(entry, running, children)
is Entry.Used -> if (entry.tool == "TodoWrite") AgentTodos(entry.input) else AgentToolCall(entry, running)
is Entry.Result -> Unit
is Entry.Finished -> when {
last && AgentHost.answerless(AgentHost.entries) -> AgentNoReply()
last && entry.planned -> Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
AgentTurnEnd(entry, changes, turn)
AgentPlanActions(onRevise, onSent)
AgentTurnEnd(entry, changes)
AgentPlanActions(onRevise)
}
else -> AgentTurnEnd(entry, changes, turn)
}
}
}
/** The options a reply ends with; picking one sends it, while the reply is still the latest. */
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun AgentChoices(options: List<String>, answerable: Boolean, onSent: () -> Unit) {
val context = LocalContext.current
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(horizontal = 4.dp)) {
for (option in options) SecondaryButton(option, enabled = answerable, compact = true, modifier = Modifier.testTag("agent-choice")) {
AgentHost.send(context, option)
onSent()
else -> AgentTurnEnd(entry, changes)
}
}
}
/** A plan turn changed nothing; Go carries the plan out with plan mode off, Revise asks for another. */
@Composable
private fun AgentPlanActions(onRevise: () -> Unit, onSent: () -> Unit) {
private fun AgentPlanActions(onRevise: () -> Unit) {
val context = LocalContext.current
val pal = LocalPalette.current
val go = stringResource(R.string.agent_plan_go_message)
@@ -119,7 +91,6 @@ private fun AgentPlanActions(onRevise: () -> Unit, onSent: () -> Unit) {
PrimaryButton(stringResource(R.string.agent_plan_go), compact = true, modifier = Modifier.testTag("agent-plan-go")) {
AgentHost.choosePlan(context, false)
AgentHost.send(context, go)
onSent()
}
SecondaryButton(stringResource(R.string.agent_plan_revise), compact = true, modifier = Modifier.testTag("agent-plan-revise")) {
AgentHost.choosePlan(context, true)
@@ -135,18 +106,13 @@ internal data class Changes(val files: Int, val added: Int, val removed: Int)
/** The edits of the turn that ends at [end], or null when it changed no file. */
internal fun turnChanges(entries: List<Entry>, end: Int): Changes? {
val start = entries.subList(0, end).indexOfLast { it is Entry.Asked }
val edits = turnEdits(entries.subList(start + 1, end))
// Plan mode saves its plan as a file of its own, which is not a change to anything.
val edits = entries.subList(start + 1, end).filterIsInstance<Entry.Used>().filter { !it.failed }.mapNotNull { diffOf(it) }
.filter { !it.path.contains("/.claude/plans/") }
if (edits.isEmpty()) return null
return Changes(edits.map { it.path }.distinct().size, edits.sumOf { it.added }, edits.sumOf { it.removed })
}
/** The edits in [turn] that took, in order. Plan mode saves its plan as a file of its own, which is not a change to anything. */
internal fun turnEdits(turn: List<Entry>): List<Diff> =
turn.filterIsInstance<Entry.Used>().filter { !it.failed }.mapNotNull { diffOf(it) }.filter { !it.path.contains("/.claude/plans/") }
/** What the agent said in [turn], to copy as one text. */
internal fun turnReply(turn: List<Entry>): String = turn.filterIsInstance<Entry.Said>().joinToString("\n\n") { it.text }
internal class Diff(val path: String, val lines: List<String>) {
val added = lines.count { it.startsWith("+") }
val removed = lines.count { it.startsWith("-") }
@@ -163,11 +129,9 @@ internal fun diffOf(entry: Entry.Used): Diff? {
}
@Composable
private fun AgentTurnEnd(entry: Entry.Finished, changes: Changes?, turn: List<Entry>) {
private fun AgentTurnEnd(entry: Entry.Finished, changes: Changes?) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var open by rememberSaveable { mutableStateOf(false) }
val reply = turnReply(turn)
val text = when {
entry.stopped -> stringResource(R.string.agent_stopped)
entry.error != null -> stringResource(R.string.agent_failed, entry.error)
@@ -179,38 +143,18 @@ private fun AgentTurnEnd(entry: Entry.Finished, changes: Changes?, turn: List<En
}.joinToString(" · ")
}
}
if (text.isNullOrEmpty() && changes == null && reply.isEmpty()) return
if (text.isNullOrEmpty() && changes == null) return
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.padding(horizontal = 4.dp)) {
if (changes != null) Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.clip(Shape12).background(if (open) pal.primary.copy(alpha = 0.2f) else pal.surfaceVariant).clickable { open = !open }
.padding(horizontal = 9.dp, vertical = 4.dp).testTag("agent-changes"),
modifier = Modifier.clip(Shape12).background(pal.surfaceVariant).padding(horizontal = 9.dp, vertical = 4.dp).testTag("agent-changes"),
) {
Text(pluralStringResource(R.plurals.agent_files_changed, changes.files, changes.files), fontSize = 12.sp, color = pal.onSurfaceVariant)
Text("+${changes.added}", fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = pal.good)
Text("−${changes.removed}", fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.error)
Icon(if (open) Icons.Outlined.ExpandLess else Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp))
}
if (!text.isNullOrEmpty()) Text(text, fontSize = 12.sp, color = if (entry.error != null && !entry.stopped) colors.error else pal.onSurfaceVariant,
modifier = Modifier.weight(1f, fill = false))
if (reply.isNotEmpty()) CopyButton(reply, stringResource(R.string.agent_copy_reply))
if (!text.isNullOrEmpty()) Text(text, fontSize = 12.sp, color = if (entry.error != null && !entry.stopped) colors.error else pal.onSurfaceVariant)
}
if (open && changes != null) Column(Modifier.padding(start = 4.dp, end = 4.dp, top = 8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
for (diff in turnEdits(turn)) {
Text(diff.path, fontSize = 11.5.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
DiffBox(diff)
}
}
}
@Composable
private fun CopyButton(text: String, label: String) {
val clipboard = LocalClipboardManager.current
val pal = LocalPalette.current
Icon(
Icons.Outlined.ContentCopy, label, tint = pal.onSurfaceVariant,
modifier = Modifier.size(28.dp).clip(Shape12).clickable { clipboard.setText(AnnotatedString(text)) }.padding(6.dp).testTag("agent-copy"),
)
}
@Composable
@@ -272,7 +216,7 @@ private fun AgentTodos(list: String) {
/** A tool call: one line with its status, opening to the full input and output, or to the diff of an edit. */
@Composable
private fun AgentToolCall(entry: Entry.Used, running: Boolean, children: List<Entry.Used> = emptyList()) {
private fun AgentToolCall(entry: Entry.Used, running: Boolean) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var open by rememberSaveable(entry.id.ifEmpty { entry.detail }) { mutableStateOf(false) }
@@ -301,17 +245,6 @@ private fun AgentToolCall(entry: Entry.Used, running: Boolean, children: List<En
}
Icon(if (open) Icons.Outlined.ExpandLess else Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(18.dp))
}
if (children.isNotEmpty()) {
val latest = children.last()
Text(
pluralStringResource(R.plurals.agent_subagent_steps, children.size, children.size) + " · " + latest.tool + " " + latest.detail,
fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(start = 34.dp, end = 10.dp, bottom = 8.dp),
)
}
if (open && children.isNotEmpty()) Column(Modifier.padding(start = 10.dp, end = 4.dp, bottom = 6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
for (child in children) AgentToolCall(child, running && child.output == null)
}
if (open && diff != null) Column(Modifier.padding(start = 10.dp, end = 10.dp, bottom = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
if (diff.path.contains('/')) Text(diff.path, fontSize = 11.5.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
DiffBox(diff)
@@ -356,11 +289,7 @@ private fun DiffBox(diff: Diff) {
private fun CodeBox(label: String, text: String, color: Color) {
val pal = LocalPalette.current
Column {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(label, fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.sp, color = pal.onSurfaceVariant,
modifier = Modifier.weight(1f).padding(bottom = 3.dp))
CopyButton(text, stringResource(R.string.agent_copy))
}
Text(label, fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.sp, color = pal.onSurfaceVariant, modifier = Modifier.padding(bottom = 3.dp))
SelectionContainer {
Text(
text, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = color, lineHeight = 17.sp,
@@ -43,10 +43,6 @@ import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.Send
import androidx.compose.material.icons.outlined.Extension
import androidx.compose.material.icons.outlined.PhotoCamera
import androidx.compose.material.icons.outlined.MicOff
import androidx.compose.material.icons.outlined.Mic
import androidx.compose.material.icons.outlined.Add
import androidx.compose.material.icons.outlined.ArrowDownward
import androidx.compose.material.icons.outlined.AttachFile
@@ -70,12 +66,12 @@ import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.Stable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
@@ -97,7 +93,6 @@ import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalFocusManager
@@ -121,54 +116,34 @@ import com.droiddeck.launcher.agent.AgentHost.Entry
import com.droiddeck.launcher.agent.AgentSetup
import kotlinx.coroutines.launch
internal enum class AgentPanel { NONE, MODEL, USAGE, HISTORY, PROCESSES, TOOLS }
internal enum class AgentPanel { NONE, MODEL, USAGE, HISTORY, PROCESSES }
/** Slash commands the app handles itself; others go to the CLI, which has its own. */
private val LOCAL_COMMANDS = listOf("/new", "/model", "/plan", "/history", "/processes", "/stop")
private val CLI_COMMANDS = listOf("/compact", "/cost", "/review", "/init")
private const val COMPOSER_SLIDE_MS = 350L
/**
* The chat with the model, usage and menu on top and the editor at the bottom. Scrolling back
* through older messages hides the editor behind a small pill and stops following new output.
* [inputModifier] goes on the first control, where a controller lands without raising the keyboard.
* The chat with the composer at the bottom. The composer is the full editor only while it is
* being typed in; reading shrinks it to one line, and scrolling back through older messages
* hides it behind a small pill. [startTyping] opens an empty conversation ready to type.
*/
@Suppress("UNUSED_PARAMETER")
@Composable
internal fun AgentPage(
modifier: Modifier, inputModifier: Modifier = Modifier, visible: Boolean = true, startTyping: Boolean = true, hidesPet: Boolean = true,
menuSlot: AgentMenuSlot? = null,
) = AgentPageContent(modifier, inputModifier, visible, hidesPet, menuSlot)
) = AgentPageContent(modifier, inputModifier, visible, startTyping, hidesPet, showControlsWithoutKeyboard = false, menuSlot)
// Lab overlays run against the installed APK, so these entry points keep their JVM signatures.
@Suppress("UNUSED_PARAMETER")
@Composable
internal fun AgentPageWithControls(
modifier: Modifier, inputModifier: Modifier = Modifier, visible: Boolean = true, startTyping: Boolean = true,
showControlsWithoutKeyboard: Boolean,
) = AgentPageContent(modifier, inputModifier, visible, hidesPet = true, drawer = true)
/** Whether the session drawer's chat keeps the model, usage and menu in the editor's row, giving the conversation that row's height. */
internal object AgentDrawerLayout {
private const val KEY = "drawer_inline_controls"
var inline by mutableStateOf(true)
private set
private var loaded = false
fun load(context: android.content.Context) {
if (loaded) return
loaded = true
inline = AgentHost.prefs(context).getBoolean(KEY, true)
}
fun set(context: android.content.Context, on: Boolean) {
inline = on
AgentHost.prefs(context).edit().putBoolean(KEY, on).apply()
}
}
) = AgentPageContent(modifier, inputModifier, visible, startTyping, hidesPet = true, showControlsWithoutKeyboard = showControlsWithoutKeyboard)
@Composable
private fun AgentPageContent(
modifier: Modifier, inputModifier: Modifier, visible: Boolean, hidesPet: Boolean, menuSlot: AgentMenuSlot? = null, drawer: Boolean = false,
modifier: Modifier, inputModifier: Modifier, visible: Boolean, startTyping: Boolean, hidesPet: Boolean,
showControlsWithoutKeyboard: Boolean, menuSlot: AgentMenuSlot? = null,
) {
val context = LocalContext.current
val view = LocalView.current
@@ -183,19 +158,9 @@ private fun AgentPageContent(
}
}
remember { AgentHost.refresh(context) }
remember { AgentDrawerLayout.load(context) }
val inline = drawer && AgentDrawerLayout.inline
LaunchedEffect(AgentHost.unseen, visible) { if (visible) AgentHost.seen() }
// A stopped activity keeps its composition; the page is only on screen while its host is started.
val lifecycle = androidx.compose.ui.platform.LocalLifecycleOwner.current.lifecycle
var started by remember(lifecycle) { mutableStateOf(lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.STARTED)) }
DisposableEffect(lifecycle) {
val observer = androidx.lifecycle.LifecycleEventObserver { _, _ -> started = lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.STARTED) }
lifecycle.addObserver(observer)
onDispose { lifecycle.removeObserver(observer) }
}
DisposableEffect(visible, hidesPet, started) {
val counts = visible && hidesPet && started
DisposableEffect(visible, hidesPet) {
val counts = visible && hidesPet
if (counts) AgentPet.agentOnScreen++
onDispose { if (counts) AgentPet.agentOnScreen-- }
}
@@ -207,23 +172,17 @@ private fun AgentPageContent(
return
}
var panel by rememberSaveable { mutableStateOf(AgentPanel.NONE) }
val composer = remember { ComposerState() }
val composer = remember { ComposerState(startTyping && AgentHost.entries.isEmpty()) }
val focusManager = LocalFocusManager.current
val togglePanel: (AgentPanel) -> Unit = { panel = if (panel == it) AgentPanel.NONE else it }
var menuOpen by rememberSaveable { mutableStateOf(false) }
val menu: @Composable () -> Unit = {
AgentMenu(menuOpen, { menuOpen = it }, onPanel = { panel = it }, onSetup = { setup = true })
}
val topBar: @Composable () -> Unit = { AgentTopBar(panel, togglePanel, inputModifier, menu) }
val inlineControls: (@Composable () -> Unit)? = if (inline) ({
ModelChip(panel, togglePanel, inputModifier, compact = true)
ContextRing("agent-usage", onClick = { togglePanel(AgentPanel.USAGE) })
menu()
}) else null
// A host with a title bar shows the top bar there.
val inSlot = menuSlot != null && panel != AgentPanel.HISTORY && panel != AgentPanel.PROCESSES && panel != AgentPanel.TOOLS
// A host with a title bar shows the menu there; otherwise it floats over the conversation's top corner.
val inSlot = menuSlot != null && panel != AgentPanel.HISTORY && panel != AgentPanel.PROCESSES
if (menuSlot != null) DisposableEffect(menuSlot, inSlot) {
menuSlot.content = if (inSlot) topBar else null
menuSlot.content = if (inSlot) menu else null
onDispose { menuSlot.content = null }
}
// The keyboard leaves too little height for a panel and the editor together, so typing closes the panel.
@@ -232,7 +191,7 @@ private fun AgentPageContent(
Column(
modifier.fillMaxSize().imePadding().onPreviewKeyEvent { e ->
val k = e.nativeKeyEvent
if (k.keyCode != KeyEvent.KEYCODE_BUTTON_Y || composer.focused) return@onPreviewKeyEvent false
if (k.keyCode != KeyEvent.KEYCODE_BUTTON_Y || composer.typing) return@onPreviewKeyEvent false
if (k.action == KeyEvent.ACTION_UP) composer.open()
true
},
@@ -246,22 +205,11 @@ private fun AgentPageContent(
AgentPanelBar(stringResource(R.string.agent_processes)) { panel = AgentPanel.NONE }
AgentProcessList(Modifier.weight(1f))
}
AgentPanel.TOOLS -> {
AgentPanelBar(stringResource(R.string.agent_tools)) { panel = AgentPanel.NONE }
AgentToolsPanel(Modifier.weight(1f))
}
else -> {
if (menuSlot == null && !inline) Box(Modifier.padding(bottom = 6.dp)) { topBar() }
when (panel) {
AgentPanel.MODEL -> Box(Modifier.padding(bottom = 8.dp)) { AgentModelPicker() }
AgentPanel.USAGE -> Box(Modifier.padding(bottom = 8.dp)) { AgentUsage() }
else -> Unit
}
val list = rememberLazyListState()
val scope = rememberCoroutineScope()
// Only dragging back through older messages stops following the latest; reaching the bottom again resumes it.
// Only dragging back through older messages hides the composer; showing it again shrinks the list, which must not hide it once more.
var readingBack by remember { mutableStateOf(false) }
LaunchedEffect(AgentHost.chat) { readingBack = false }
LaunchedEffect(list) { snapshotFlow { list.canScrollForward }.collect { if (!it) readingBack = false } }
val dragBack = remember {
object : NestedScrollConnection {
@@ -275,53 +223,57 @@ private fun AgentPageContent(
readingBack = false
scope.launch { list.scrollToItem(maxOf(0, list.layoutInfo.totalItemsCount - 1), Int.MAX_VALUE / 2) }
}
val hidden = !composer.focused && !composer.hasUnconsumedFocusRequest() && readingBack && AgentHost.entries.isNotEmpty()
var listHeight by remember { mutableIntStateOf(0) }
Box(
Modifier.weight(1f).fillMaxWidth().clipToBounds().nestedScroll(dragBack).onGloballyPositioned {
// The editor sliding in or the keyboard rising shrinks the list from below; a list following the latest keeps it in view, even mid-drag.
// Scrolling remeasures the list, which Compose refuses during a measure pass, so this runs once positioning is done.
val height = it.size.height
val shrunk = listHeight - height
listHeight = height
if (shrunk > 0 && !readingBack) list.dispatchRawDelta(shrunk.toFloat())
},
) {
val hidden = !composer.typing && readingBack && AgentHost.entries.isNotEmpty()
var wasHidden by remember { mutableStateOf(false) }
LaunchedEffect(hidden) {
if (hidden) wasHidden = true
else if (wasHidden) {
wasHidden = false
// The composer takes its height back as it slides in; the latest message stays above it.
kotlinx.coroutines.delay(COMPOSER_SLIDE_MS)
list.scrollToItem(maxOf(0, list.layoutInfo.totalItemsCount - 1), Int.MAX_VALUE / 2)
}
}
Box(Modifier.weight(1f).fillMaxWidth().clipToBounds().nestedScroll(dragBack)) {
AgentConversation(
Modifier.fillMaxSize().pointerInput(Unit) {
awaitEachGesture {
awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)
if (panel == AgentPanel.MODEL || panel == AgentPanel.USAGE) panel = AgentPanel.NONE
if (composer.focused) focusManager.clearFocus()
if (composer.typing) focusManager.clearFocus()
}
},
list, following = !readingBack, onRevise = { composer.open() }, onSent = toLatest,
list, onRevise = { composer.open() },
)
androidx.compose.animation.AnimatedVisibility(
hidden, enter = fadeIn(), exit = fadeOut(), modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 8.dp),
) {
AgentJumpPill(toLatest)
}
if (menuSlot == null) Box(Modifier.align(Alignment.TopEnd).padding(top = 4.dp)) { menu() }
}
androidx.compose.animation.AnimatedVisibility(!hidden, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) {
AgentComposer(composer, draft, visible, inlineControls, onPanel = { panel = it }, onSent = toLatest)
AgentComposer(composer, draft, inputModifier, panel, togglePanel, showControlsWithoutKeyboard)
}
}
}
}
}
/** Whether the editor has the cursor; [open] puts it there. */
/** Whether the composer is the full editor; [open] also puts the cursor in it. */
@Stable
private class ComposerState {
var focused by mutableStateOf(false)
private class ComposerState(typing: Boolean) {
var typing by mutableStateOf(typing)
var focusRequests by mutableIntStateOf(0)
private set
private var consumedFocusRequests by mutableIntStateOf(0)
/** Opened and waiting for the text field to take focus; focus passes through nothing on the way. */
var opening = false
fun open() {
typing = true
opening = true
focusRequests++
if (focused) consumeFocusRequest()
}
fun hasUnconsumedFocusRequest() = focusRequests > consumedFocusRequests
@@ -337,37 +289,6 @@ internal class AgentMenuSlot {
var content by mutableStateOf<(@Composable () -> Unit)?>(null)
}
/** The model and how full the context is, then the [menu]. */
@Composable
private fun AgentTopBar(panel: AgentPanel, onPanel: (AgentPanel) -> Unit, firstControl: Modifier, menu: @Composable () -> Unit) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
ModelChip(panel, onPanel, firstControl, Modifier.weight(1f, fill = false))
ContextRing("agent-usage", onClick = { onPanel(AgentPanel.USAGE) })
}
menu()
}
}
/** The harness, model, effort and plan mode, opening the model picker; [compact] names only the model. */
@Composable
private fun ModelChip(panel: AgentPanel, onPanel: (AgentPanel) -> Unit, firstControl: Modifier, modifier: Modifier = Modifier, compact: Boolean = false) {
val context = LocalContext.current
val pal = LocalPalette.current
val model = AgentHost.models(context).firstOrNull { it.id == AgentHost.model }?.label ?: AgentHost.model ?: stringResource(R.string.agent_model_default)
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = modifier.then(if (compact) Modifier.widthIn(max = 120.dp) else Modifier).height(36.dp).clip(Shape12).then(firstControl)
.clickable { onPanel(AgentPanel.MODEL) }.padding(horizontal = 8.dp).testTag("agent-model"),
) {
val parts = if (compact) listOf(model)
else listOfNotNull(AgentHost.harness.name, model, AgentHost.effort, stringResource(R.string.agent_plan_short).takeIf { AgentHost.plan && AgentHost.harness.plans })
Text(parts.joinToString(" · "), fontSize = 13.sp, color = if (panel == AgentPanel.MODEL) pal.primary else pal.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
Icon(Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp))
}
}
/** History, processes, a new conversation, the pet and setup, folded behind one button. */
@Composable
private fun AgentMenu(open: Boolean, onOpen: (Boolean) -> Unit, onPanel: (AgentPanel) -> Unit, onSetup: () -> Unit) {
@@ -385,9 +306,6 @@ private fun AgentMenu(open: Boolean, onOpen: (Boolean) -> Unit, onPanel: (AgentP
Row(verticalAlignment = Alignment.CenterVertically) {
HeaderAction(Icons.Outlined.History, stringResource(R.string.agent_history), size = 36.dp, tag = "agent-history") { onOpen(false); onPanel(AgentPanel.HISTORY) }
HeaderAction(Icons.Outlined.Memory, stringResource(R.string.agent_processes), size = 36.dp, tag = "agent-processes") { onOpen(false); onPanel(AgentPanel.PROCESSES) }
if (AgentHost.harness == com.droiddeck.launcher.agent.ClaudeCode) HeaderAction(
Icons.Outlined.Extension, stringResource(R.string.agent_tools), size = 36.dp, tag = "agent-tools",
) { onOpen(false); onPanel(AgentPanel.TOOLS) }
HeaderAction(Icons.Outlined.Add, stringResource(R.string.agent_new), enabled = !working && AgentHost.entries.isNotEmpty(), size = 36.dp, tag = "agent-new") {
onOpen(false)
AgentHost.forget(context)
@@ -434,20 +352,18 @@ internal fun HeaderAction(
}
@Composable
private fun AgentConversation(modifier: Modifier, list: LazyListState, following: Boolean, onRevise: () -> Unit, onSent: () -> Unit) {
private fun AgentConversation(modifier: Modifier, list: LazyListState, onRevise: () -> Unit) {
val pal = LocalPalette.current
val working = AgentHost.state == AgentHost.State.WORKING
// A subagent's calls are shown inside the call that started it.
val shown = AgentHost.entries.indices.filter { (AgentHost.entries[it] as? Entry.Used)?.parent.isNullOrEmpty() }
val items = shown.size + (if (working) 1 else 0)
val follow by rememberUpdatedState(following)
val atBottom by remember { derivedStateOf { !list.canScrollForward } }
val items = AgentHost.entries.size + (if (working) 1 else 0)
LaunchedEffect(items) {
if (items == 0 || !follow) return@LaunchedEffect
if (items == 0) return@LaunchedEffect
list.animateScrollToItem(items - 1)
list.scrollToItem(items - 1, Int.MAX_VALUE / 2)
}
LaunchedEffect(AgentHost.live.length / 80, AgentHost.liveThinking.length / 80) {
if (follow && items > 0) list.scrollToItem(items - 1, Int.MAX_VALUE / 2)
if (atBottom && items > 0) list.scrollToItem(items - 1, Int.MAX_VALUE / 2)
}
if (AgentHost.entries.isEmpty() && !working) {
Column(modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
@@ -459,15 +375,11 @@ private fun AgentConversation(modifier: Modifier, list: LazyListState, following
}
val start = AgentHost.entries.indexOfLast { it is Entry.Asked }
LazyColumn(modifier.fillMaxWidth(), state = list, verticalArrangement = Arrangement.spacedBy(10.dp)) {
items(shown.size) { n ->
val i = shown[n]
items(AgentHost.entries.size) { i ->
val entry = AgentHost.entries[i]
AgentEntry(
entry, running = working && i > start && entry is Entry.Used && entry.output == null, last = !working && i == AgentHost.entries.lastIndex,
children = if (entry is Entry.Used) AgentHost.entries.filter { it is Entry.Used && it.parent == entry.id && entry.id.isNotEmpty() }.map { it as Entry.Used } else emptyList(),
changes = if (entry is Entry.Finished) turnChanges(AgentHost.entries, i) else null,
turn = if (entry is Entry.Finished) AgentHost.entries.subList(AgentHost.entries.subList(0, i).indexOfLast { it is Entry.Asked } + 1, i) else emptyList(),
answerable = !working && i > start && AgentHost.queue.isEmpty(), onRevise = onRevise, onSent = onSent,
changes = if (entry is Entry.Finished) turnChanges(AgentHost.entries, i) else null, onRevise = onRevise,
)
}
if (working) item { AgentLive() }
@@ -653,13 +565,14 @@ internal fun liveUsed(limit: AgentHost.Limit) = if (limit.resetsAt > 0 && limit.
@Composable
private fun AgentComposer(
composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?,
onPanel: (AgentPanel) -> Unit, onSent: () -> Unit,
composer: ComposerState, draftState: MutableState<String>, inputModifier: Modifier, panel: AgentPanel, onPanel: (AgentPanel) -> Unit,
showControlsWithoutKeyboard: Boolean,
) {
val context = LocalContext.current
var draft by draftState
var labOpen by rememberSaveable { mutableStateOf(false) }
if (AgentHost.lab == null) labOpen = false
var hadFocus by remember { mutableStateOf(false) }
val send = send@{
val text = draft.trim()
when (text.substringBefore(' ')) {
@@ -673,33 +586,90 @@ private fun AgentComposer(
if (text.isEmpty() && AgentAttachments.pending.isEmpty()) return@send
AgentHost.send(context, text, AgentAttachments.pending.toList())
AgentAttachments.pending.clear()
onSent()
}
}
draft = ""
}
val keyboardOpen = WindowInsets.ime.getBottom(LocalDensity.current) > 0
Column(Modifier.fillMaxWidth().padding(bottom = if (keyboardOpen) 4.dp else 8.dp)) {
// Leaving the composer for the conversation, by touch or D-pad, is reading.
Column(
Modifier.fillMaxWidth().padding(bottom = if (keyboardOpen) 4.dp else 8.dp).onFocusChanged {
if (it.hasFocus) hadFocus = true
else if (hadFocus) {
hadFocus = false
if (composer.typing && !composer.opening) composer.typing = false
}
},
) {
if (labOpen) AgentLabCard()
if (hasActivity()) Row(
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(top = 8.dp).fillMaxWidth().horizontalScroll(rememberScrollState()),
) { AgentActivity(labOpen) { labOpen = !labOpen } }
AgentEditor(composer, draftState, visible, controls, send)
when (panel) {
AgentPanel.MODEL -> Box(Modifier.padding(top = 8.dp)) { AgentModelPicker() }
AgentPanel.USAGE -> Box(Modifier.padding(top = 8.dp)) { AgentUsage() }
else -> Unit
}
if (composer.typing) {
if (hasActivity()) Row(
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(top = 8.dp).fillMaxWidth().horizontalScroll(rememberScrollState()),
) { AgentActivity(labOpen) { labOpen = !labOpen } }
AgentEditor(composer, draftState, inputModifier, panel, onPanel, highlightControls = showControlsWithoutKeyboard, send = send)
} else AgentReadingBar(
composer, draft, inputModifier, labOpen, onLab = { labOpen = !labOpen }, onUsage = { onPanel(AgentPanel.USAGE) },
) {
// The session drawer is driven by a controller, so its editor opens without raising the keyboard.
if (showControlsWithoutKeyboard) {
composer.typing = true
composer.opening = true
} else composer.open()
}
}
}
/** The text with attach, stop and send beside it, and [controls] while the text is not being typed in. */
/** The composer while reading: one line holding what is going on, opened by a press or by Y. */
@Composable
private fun AgentEditor(composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?, send: () -> Unit) {
private fun AgentReadingBar(
composer: ComposerState, draft: String, inputModifier: Modifier, labOpen: Boolean, onLab: () -> Unit, onUsage: () -> Unit, onOpen: () -> Unit,
) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val working = AgentHost.state == AgentHost.State.WORKING
var focused by remember { mutableStateOf(false) }
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(top = 8.dp).height(44.dp).clip(Shape16).background(colors.surface)
.border(if (focused) 2.dp else 1.dp, if (focused) pal.primary else pal.line, Shape16)
.then(inputModifier).onFocusChanged { focused = it.isFocused }.clickable(onClick = onOpen).testTag("agent-composer-bar")
.padding(start = 14.dp, end = 4.dp),
) {
Text(
draft.ifBlank { stringResource(if (working) R.string.agent_hint_working else R.string.agent_message) }, fontSize = 15.sp,
color = if (draft.isBlank()) pal.onSurfaceVariant else colors.onSurface, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f, fill = !hasActivity()).widthIn(min = 72.dp),
)
if (hasActivity()) Row(
horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.weight(1f).padding(start = 8.dp).horizontalScroll(rememberScrollState()),
) { AgentActivity(labOpen, onLab) }
ContextRing("agent-usage-bar", onUsage)
if (working) Box(
contentAlignment = Alignment.Center,
modifier = Modifier.padding(start = 4.dp).size(36.dp).clip(CircleShape).background(pal.error.copy(alpha = 0.22f))
.clickable { AgentHost.stop(context) }.testTag("agent-stop"),
) { Icon(Icons.Outlined.Stop, stringResource(R.string.agent_stop), tint = colors.error, modifier = Modifier.size(20.dp)) }
}
}
/** The full editor: model and usage on top, the text with attach, stop and send under them. */
@Composable
private fun AgentEditor(
composer: ComposerState, draftState: MutableState<String>, inputModifier: Modifier, panel: AgentPanel, onPanel: (AgentPanel) -> Unit,
highlightControls: Boolean = false, send: () -> Unit,
) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var draft by draftState
val voice = remember { AgentVoice(context.applicationContext, { draftState.value }) { draftState.value = it } }
val voiceAvailable = remember { AgentVoice.available(context) }
DisposableEffect(voice) { onDispose { voice.stop() } }
LaunchedEffect(visible) { if (!visible) voice.stop() }
val working = AgentHost.state == AgentHost.State.WORKING
if (draft.startsWith("/") && !draft.contains(' ')) {
val matches = (LOCAL_COMMANDS + CLI_COMMANDS).filter { it.startsWith(draft) && it != draft }
@@ -724,11 +694,26 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String
LaunchedEffect(composer.focusRequests) { if (composer.hasUnconsumedFocusRequest()) runCatching { field.requestFocus() } }
Column(
Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape16).background(colors.surface)
.border(if (focused) 2.dp else 1.dp, if (focused) pal.primary else pal.line, Shape16).padding(6.dp),
.border(if (focused || highlightControls) 2.dp else 1.dp, if (focused || highlightControls) pal.primary else pal.line, Shape16).padding(6.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().height(36.dp)) {
val model = AgentHost.models(context).firstOrNull { it.id == AgentHost.model }?.label ?: AgentHost.model ?: stringResource(R.string.agent_model_default)
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.weight(1f, fill = false).height(30.dp).clip(Shape12).clickable { onPanel(AgentPanel.MODEL) }
.padding(horizontal = 8.dp).testTag("agent-model"),
) {
val parts = listOfNotNull(AgentHost.harness.name, model, AgentHost.effort, stringResource(R.string.agent_plan_short).takeIf { AgentHost.plan && AgentHost.harness.plans })
Text(parts.joinToString(" · "), fontSize = 13.sp, color = if (panel == AgentPanel.MODEL) pal.primary else pal.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
Icon(Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp))
}
ContextRing("agent-usage", onClick = { onPanel(AgentPanel.USAGE) })
}
}
Row(verticalAlignment = Alignment.Bottom) {
if (LocalActivityResultRegistryOwner.current != null) AttachButton()
if (AgentAttachments.gameFrame != null) GameFrameButton()
Box(Modifier.weight(1f).padding(start = 8.dp, top = 10.dp, bottom = 10.dp)) {
if (draft.isEmpty()) Text(
stringResource(if (working) R.string.agent_hint_working else R.string.agent_hint), fontSize = 16.sp,
@@ -738,82 +723,27 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String
draft, { draft = it },
Modifier.fillMaxWidth().focusRequester(field).onFocusChanged {
focused = it.isFocused
composer.focused = it.isFocused
if (it.isFocused) composer.consumeFocusRequest()
}.testTag("agent-input"),
if (it.isFocused) {
composer.consumeFocusRequest()
composer.opening = false
}
}.testTag("agent-input").then(inputModifier),
textStyle = TextStyle(fontSize = 16.sp, color = colors.onSurface),
cursorBrush = SolidColor(pal.primary),
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
keyboardActions = KeyboardActions(onSend = {
voice.stop()
send()
}),
keyboardActions = KeyboardActions(onSend = { send() }),
minLines = 1,
maxLines = 8,
)
}
if (controls != null && !focused) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.height(42.dp)) { controls() }
if (working) RoundButton(Icons.Outlined.Stop, stringResource(R.string.agent_stop), pal.error.copy(alpha = 0.22f), colors.error, "agent-stop") {
AgentHost.stop(context)
}
val canSend = draft.isNotBlank() || AgentAttachments.pending.isNotEmpty()
// An empty message has nothing to send, so the button there dictates one instead.
if ((!canSend || voice.listening) && voiceAvailable) VoiceButton(voice) { voice.start(draft) }
else RoundButton(
RoundButton(
Icons.AutoMirrored.Outlined.Send, stringResource(if (working) R.string.agent_queue else R.string.agent_send),
if (canSend) pal.primary else pal.surfaceVariant, if (canSend) pal.onPrimary else pal.onSurfaceVariant, "agent-send", enabled = canSend,
) {
voice.stop()
send()
}
}
}
}
@Composable
private fun VoiceButton(voice: AgentVoice, onStart: () -> Unit) {
val context = LocalContext.current
val pal = LocalPalette.current
val ask = if (LocalActivityResultRegistryOwner.current != null) rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (granted) onStart() else android.widget.Toast.makeText(context, R.string.agent_voice_denied, android.widget.Toast.LENGTH_SHORT).show()
} else null
RoundButton(
if (voice.listening) Icons.Outlined.MicOff else Icons.Outlined.Mic, stringResource(if (voice.listening) R.string.agent_voice_stop else R.string.agent_voice),
if (voice.listening) pal.primary else pal.surfaceVariant, if (voice.listening) pal.onPrimary else pal.onBackground, "agent-voice",
) {
when {
voice.listening -> voice.finish()
context.checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) == android.content.pm.PackageManager.PERMISSION_GRANTED -> onStart()
ask != null -> ask.launch(android.Manifest.permission.RECORD_AUDIO)
else -> android.widget.Toast.makeText(context, R.string.agent_voice_denied, android.widget.Toast.LENGTH_SHORT).show()
}
}
}
/** Attaches what the running game shows, taken from its own surface so nothing drawn over it is in the picture. */
@Composable
private fun GameFrameButton() {
val context = LocalContext.current
val pal = LocalPalette.current
RoundButton(Icons.Outlined.PhotoCamera, stringResource(R.string.agent_attach_game), pal.surfaceVariant, pal.onBackground, "agent-game-frame") {
val grab = AgentAttachments.gameFrame ?: return@RoundButton
val chat = AgentHost.chat
grab frame@{ frame ->
if (frame == null) {
android.widget.Toast.makeText(context, R.string.agent_attach_game_failed, android.widget.Toast.LENGTH_SHORT).show()
return@frame
}
Thread({
val path = AgentAttachments.saveFrame(context, chat, frame)
frame.recycle()
android.os.Handler(android.os.Looper.getMainLooper()).post {
when {
path == null -> android.widget.Toast.makeText(context, R.string.agent_attach_game_failed, android.widget.Toast.LENGTH_SHORT).show()
AgentHost.chat == chat -> AgentAttachments.pending.add(path)
else -> AgentAttachments.discard(context, listOf(path))
}
}
}, "agent-game-frame").start()
) { send() }
}
}
}
@@ -41,18 +41,6 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.Search
import androidx.compose.material3.Icon
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.text.TextStyle
import androidx.compose.runtime.rememberCoroutineScope
import kotlinx.coroutines.launch
import com.droiddeck.launcher.agent.AgentTools
import com.droiddeck.launcher.R
import com.droiddeck.launcher.agent.AgentChats
import com.droiddeck.launcher.agent.AgentHarness
@@ -112,85 +100,44 @@ internal fun AgentHistory(modifier: Modifier, onOpened: () -> Unit) {
}
return
}
var query by rememberSaveable { mutableStateOf("") }
val found by produceState<List<AgentChats.Chat>?>(null, chats, query) {
if (query.isNotBlank()) delay(250)
value = withContext(Dispatchers.IO) { AgentChats.search(context, chats, query) }
}
val working = AgentHost.state == AgentHost.State.WORKING
Column(modifier.fillMaxWidth()) {
AgentHistorySearch(query) { query = it }
val shown = found ?: chats
if (shown.isEmpty()) Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
Text(stringResource(R.string.agent_history_no_match), fontSize = 15.sp, color = pal.onSurfaceVariant)
} else LazyColumn(Modifier.weight(1f).fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) {
items(shown, key = { it.id }) { chat -> AgentHistoryRow(chat, working, onOpened) { version++ } }
}
}
}
@Composable
private fun AgentHistorySearch(query: String, onQuery: (String) -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp).height(44.dp).clip(Shape14).background(colors.surface)
.border(1.dp, pal.line, Shape14).padding(horizontal = 12.dp),
) {
Icon(Icons.Outlined.Search, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(18.dp))
Box(Modifier.weight(1f).padding(start = 8.dp)) {
if (query.isEmpty()) Text(stringResource(R.string.agent_history_search), fontSize = 15.sp, color = pal.onSurfaceVariant, maxLines = 1)
BasicTextField(
query, onQuery, singleLine = true, textStyle = TextStyle(fontSize = 15.sp, color = colors.onSurface),
cursorBrush = SolidColor(pal.primary), modifier = Modifier.fillMaxWidth().testTag("agent-history-search"),
)
}
if (query.isNotEmpty()) Icon(Icons.Outlined.Close, stringResource(R.string.agent_close), tint = pal.onSurfaceVariant,
modifier = Modifier.size(28.dp).clip(CircleShape).clickable { onQuery("") }.padding(5.dp))
}
}
@Composable
private fun AgentHistoryRow(chat: AgentChats.Chat, working: Boolean, onOpened: () -> Unit, onDeleted: () -> Unit) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column {
var armed by remember(chat.id) { mutableStateOf(false) }
val current = chat.id == AgentHost.chat
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().heightIn(min = 62.dp)
.clickable(enabled = !working || current) {
AgentHost.open(context, chat.id)
onOpened()
}
.background(if (current) pal.primary.copy(alpha = 0.12f) else colors.surface)
.padding(horizontal = 14.dp, vertical = 10.dp).testTag("agent-chat"),
) {
Column(Modifier.weight(1f)) {
Text(chat.title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
if (armed) stringResource(R.string.agent_history_delete_warning)
else AgentHarness.byId(chat.harness).name + " · " + when {
System.currentTimeMillis() - chat.updated < 60_000 -> stringResource(R.string.agent_just_now)
else -> DateUtils.getRelativeTimeSpanString(chat.updated, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS).toString()
},
fontSize = 12.5.sp, color = if (armed) AttentionAmber else pal.onSurfaceVariant,
)
}
SecondaryButton(
stringResource(if (armed) R.string.agent_storage_confirm else R.string.agent_history_delete), compact = true,
enabled = !(current && working),
LazyColumn(modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) {
items(chats, key = { it.id }) { chat ->
var armed by remember(chat.id) { mutableStateOf(false) }
val current = chat.id == AgentHost.chat
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().heightIn(min = 62.dp)
.clickable(enabled = !working || current) {
AgentHost.open(context, chat.id)
onOpened()
}
.background(if (current) pal.primary.copy(alpha = 0.12f) else colors.surface)
.padding(horizontal = 14.dp, vertical = 10.dp).testTag("agent-chat"),
) {
if (armed) {
AgentHost.delete(context, chat.id)
onDeleted()
} else armed = true
Column(Modifier.weight(1f)) {
Text(chat.title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
if (armed) stringResource(R.string.agent_history_delete_warning)
else AgentHarness.byId(chat.harness).name + " · " + when {
System.currentTimeMillis() - chat.updated < 60_000 -> stringResource(R.string.agent_just_now)
else -> DateUtils.getRelativeTimeSpanString(chat.updated, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS).toString()
},
fontSize = 12.5.sp, color = if (armed) AttentionAmber else pal.onSurfaceVariant,
)
}
SecondaryButton(
stringResource(if (armed) R.string.agent_storage_confirm else R.string.agent_history_delete), compact = true,
enabled = !(current && working),
) {
if (armed) {
AgentHost.delete(context, chat.id)
version++
} else armed = true
}
}
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
}
@@ -313,117 +260,3 @@ private fun resetTime(context: android.content.Context, epochSeconds: Long): Str
else DateUtils.FORMAT_SHOW_WEEKDAY or DateUtils.FORMAT_ABBREV_WEEKDAY or DateUtils.FORMAT_SHOW_TIME
return DateUtils.formatDateTime(context, ms, flags)
}
/** Claude Code's MCP servers, with a way to add and remove them, and the skills in its skills folder. */
@Composable
internal fun AgentToolsPanel(modifier: Modifier) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val scope = rememberCoroutineScope()
var version by remember { mutableIntStateOf(0) }
var loading by remember { mutableStateOf(true) }
val servers by produceState<List<AgentTools.Server>?>(null, version) {
loading = true
value = withContext(Dispatchers.IO) { AgentTools.servers(context) }
loading = false
}
val skills by produceState(emptyList<AgentTools.Skill>(), version) { value = withContext(Dispatchers.IO) { AgentTools.skills(context) } }
var name by rememberSaveable { mutableStateOf("") }
var target by rememberSaveable { mutableStateOf("") }
var busy by remember { mutableStateOf(false) }
var message by remember { mutableStateOf<String?>(null) }
fun act(added: Boolean = false, action: suspend () -> AgentTools.Result) {
busy = true
message = null
scope.launch {
val result = withContext(Dispatchers.IO) { action() }
busy = false
if (!result.ok) message = result.output.ifBlank { context.getString(R.string.agent_tools_failed) }
else if (added) {
name = ""
target = ""
}
version++
}
}
LazyColumn(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
item { ToolsHeading(stringResource(R.string.agent_tools_servers)) }
val list = servers
when {
loading && list == null -> item { Text(stringResource(R.string.agent_tools_loading), fontSize = 13.sp, color = pal.onSurfaceVariant) }
list == null -> item { Text(stringResource(R.string.agent_tools_failed), fontSize = 13.sp, color = AttentionAmber) }
list.isEmpty() -> item { Text(stringResource(R.string.agent_tools_no_servers), fontSize = 13.sp, color = pal.onSurfaceVariant) }
else -> items(list, key = { "mcp:" + it.name }) { server ->
var armed by remember(server.name) { mutableStateOf(false) }
ToolsRow(server.name, server.target + " · " + server.status) {
if (!server.account) SecondaryButton(
stringResource(if (armed) R.string.agent_storage_confirm else R.string.agent_tools_remove), compact = true, enabled = !busy,
) { if (armed) act { AgentTools.remove(context, server.name) } else armed = true }
}
}
}
item {
Column(
Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14).padding(12.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
ToolsField(name, { name = it }, stringResource(R.string.agent_tools_name), "agent-tools-name")
ToolsField(target, { target = it }, stringResource(R.string.agent_tools_target), "agent-tools-target")
Row(verticalAlignment = Alignment.CenterVertically) {
Text(stringResource(R.string.agent_tools_add_hint), fontSize = 12.sp, color = pal.onSurfaceVariant, modifier = Modifier.weight(1f))
PrimaryButton(stringResource(R.string.agent_tools_add), enabled = !busy && name.isNotBlank() && target.isNotBlank(), compact = true) {
act(added = true) { AgentTools.add(context, name, target) }
}
}
message?.let { Text(it, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = AttentionAmber) }
}
}
item { ToolsHeading(stringResource(R.string.agent_tools_skills)) }
if (skills.isEmpty()) item { Text(stringResource(R.string.agent_tools_no_skills), fontSize = 13.sp, color = pal.onSurfaceVariant) }
items(skills, key = { "skill:" + it.name }) { skill ->
var armed by remember(skill.name) { mutableStateOf(false) }
ToolsRow(skill.name, skill.description) {
SecondaryButton(stringResource(if (armed) R.string.agent_storage_confirm else R.string.agent_history_delete), compact = true, enabled = !busy) {
if (armed) act {
AgentTools.Result(AgentTools.deleteSkill(context, skill.name), "")
} else armed = true
}
}
}
}
}
@Composable
private fun ToolsHeading(text: String) {
Text(text, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = LocalPalette.current.onSurfaceVariant, modifier = Modifier.padding(top = 6.dp))
}
@Composable
private fun ToolsRow(title: String, detail: String, action: @Composable () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14).padding(horizontal = 14.dp, vertical = 10.dp),
) {
Column(Modifier.weight(1f)) {
Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (detail.isNotBlank()) Text(detail, fontSize = 12.5.sp, color = pal.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
}
action()
}
}
@Composable
private fun ToolsField(value: String, onValue: (String) -> Unit, hint: String, tag: String) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Box(Modifier.fillMaxWidth().clip(Shape12).background(pal.surfaceVariant).padding(horizontal = 12.dp, vertical = 10.dp)) {
if (value.isEmpty()) Text(hint, fontSize = 14.sp, color = pal.onSurfaceVariant, maxLines = 1)
BasicTextField(
value, onValue, singleLine = true, textStyle = TextStyle(fontSize = 14.sp, fontFamily = FontFamily.Monospace, color = colors.onSurface),
cursorBrush = SolidColor(pal.primary), modifier = Modifier.fillMaxWidth().testTag(tag),
)
}
}
@@ -22,6 +22,7 @@ import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
@@ -33,6 +34,7 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
@@ -60,7 +62,9 @@ import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
@@ -553,7 +557,10 @@ internal fun PetChat(open: Boolean, motion: PetMotion, onClose: () -> Unit, onCl
.padding(start = 12.dp, end = 12.dp, top = 6.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(bottom = 2.dp)) {
Box(Modifier.weight(1f)) { menuSlot.content?.invoke() }
Text(stringResource(R.string.agent_pet_name), fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
modifier = Modifier.padding(start = 4.dp))
Spacer(Modifier.weight(1f))
menuSlot.content?.invoke()
HeaderAction(Icons.Outlined.Close, stringResource(R.string.agent_close), size = 34.dp, tag = "agent-pet-close", onClick = onClose)
}
AgentPage(Modifier.weight(1f).fillMaxWidth(), visible = open, startTyping = AgentHost.entries.isEmpty(), hidesPet = false, menuSlot = menuSlot)
@@ -40,7 +40,6 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.platform.testTag
import com.droiddeck.launcher.agent.AgentSetup.Status
import com.droiddeck.launcher.agent.AgentSetup.Step
import com.droiddeck.launcher.core.WirelessAdbPairingService
@@ -119,15 +118,6 @@ internal fun AgentSetupView(modifier: Modifier, onDone: () -> Unit = {}) {
}
}
}
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp)) {
Column(Modifier.weight(1f)) {
Text(stringResource(R.string.agent_drawer_inline), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Text(stringResource(R.string.agent_drawer_inline_hint), fontSize = 12.5.sp, color = pal.onSurfaceVariant)
}
ToggleSwitch(AgentDrawerLayout.inline, label = stringResource(R.string.agent_drawer_inline), modifier = Modifier.testTag("setting-agent-drawer-inline")) {
AgentDrawerLayout.set(context, it)
}
}
if (AgentSetup.ready || AgentSetup.completed(context)) PrimaryButton(stringResource(R.string.agent_setup_done), main = true, onClick = onDone)
StorageCard()
}
@@ -1,74 +0,0 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.speech.RecognitionListener
import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
/** Dictation into the Agent editor: what is heard so far follows the text already typed, until the user edits the draft. */
internal class AgentVoice(private val context: Context, private val draft: () -> String, private val onText: (String) -> Unit) {
var listening by mutableStateOf(false)
private set
private var recognizer: SpeechRecognizer? = null
private var base = ""
private var written = ""
fun start(typed: String) {
stop()
val speech = runCatching { SpeechRecognizer.createSpeechRecognizer(context) }.getOrNull() ?: return
recognizer = speech
base = typed.trimEnd().let { if (it.isEmpty()) it else "$it " }
written = typed
speech.setRecognitionListener(object : RecognitionListener {
override fun onReadyForSpeech(params: Bundle?) { listening = true }
override fun onBeginningOfSpeech() {}
override fun onRmsChanged(rmsdB: Float) {}
override fun onBufferReceived(buffer: ByteArray?) {}
override fun onEndOfSpeech() {}
override fun onError(error: Int) { if (recognizer === speech) stop() }
override fun onResults(results: Bundle?) {
if (recognizer !== speech) return
heard(results)
stop()
}
override fun onPartialResults(partialResults: Bundle?) { if (recognizer === speech) heard(partialResults) }
override fun onEvent(eventType: Int, params: Bundle?) {}
})
val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)
.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, context.packageName)
runCatching { speech.startListening(intent) }.onFailure { stop() }
}
private fun heard(results: Bundle?) {
val spoken = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull()?.takeIf { it.isNotBlank() } ?: return
if (draft() != written) return stop()
written = base + spoken
onText(written)
}
/** Ends listening but keeps the recognizer until its final result arrives. */
fun finish() {
val speech = recognizer ?: return
listening = false
runCatching { speech.stopListening() }.onFailure { stop() }
}
fun stop() {
listening = false
val speech = recognizer ?: return
recognizer = null
runCatching { speech.cancel() }
runCatching { speech.destroy() }
}
companion object {
fun available(context: Context) = SpeechRecognizer.isRecognitionAvailable(context)
}
}
@@ -341,28 +341,7 @@ internal fun AndroidAppsPage(s: FrontEndState, a: FrontEndActions, modifier: Mod
openFolder = f.id
}
val ff = LocalFrontFocus.current
var holdFocus by remember { mutableStateOf<String?>(null) }
var pageFocused by remember { mutableStateOf(false) }
LaunchedEffect(holdFocus) {
val key = "tile:folder:${holdFocus ?: return@LaunchedEffect}"
// A folder closed from its name field: the platform field and the fading sheet both drop focus after the sheet asked for the tile, so keep asking until the sheet is gone.
val until = System.nanoTime() + 400_000_000L
while (System.nanoTime() < until) {
androidx.compose.runtime.withFrameNanos { }
if (ff != null && !(ff.last == key && pageFocused)) runCatching { ff.items[key]?.requestFocus() }
}
holdFocus = null
}
Box(
modifier.onFocusChanged { pageFocused = it.hasFocus }
// A fresh press means the user is moving on, so the hold must not pull focus back to the folder.
.onPreviewKeyEvent { event ->
val k = event.nativeKeyEvent
if (holdFocus != null && k.action == KeyEvent.ACTION_DOWN && k.repeatCount == 0) holdFocus = null
false
},
) {
Box(modifier) {
Column(Modifier.fillMaxSize().imePadding()) {
Box(Modifier.fillMaxWidth().padding(start = padH, end = padH, top = if (narrow) 8.dp else 12.dp)) {
ModeHeader(
@@ -464,7 +443,7 @@ internal fun AndroidAppsPage(s: FrontEndState, a: FrontEndActions, modifier: Mod
var last by remember { mutableStateOf(folder) }
if (folder != null) last = folder
last?.let { f ->
FolderSheet(f, f.apps.mapNotNull(member).filter { it.key !in hidden }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label }), renameOnOpen, onLaunch, newFolder, { iconFor = it }, onHoldFocus = { holdFocus = f.id }) {
FolderSheet(f, f.apps.mapNotNull(member).filter { it.key !in hidden }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label }), renameOnOpen, onLaunch, newFolder, { iconFor = it }) {
openFolder = null
renameOnOpen = false
}
@@ -834,7 +813,7 @@ private fun FolderTile(entry: AppEntry.Folder, first: Boolean, onOpen: () -> Uni
private fun FolderSheet(
folder: HomeFolders.Folder, apps: List<HomeApp.LaunchableApp>, renameFirst: Boolean,
onLaunch: (HomeApp.LaunchableApp) -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit,
onChangeIcon: (HomeApp.LaunchableApp) -> Unit, onHoldFocus: () -> Unit, onClose: () -> Unit,
onChangeIcon: (HomeApp.LaunchableApp) -> Unit, onClose: () -> Unit,
) {
SwipeLock()
val ctx = LocalContext.current
@@ -852,24 +831,20 @@ private fun FolderSheet(
val ff = LocalFrontFocus.current
val grid = rememberLazyGridState()
var closing by remember { mutableStateOf(false) }
var inside by remember { mutableStateOf(false) }
LaunchedEffect(renaming, inputMode) {
if (!renaming && !closing && inputMode == InputMode.Keyboard && apps.isNotEmpty()) {
grid.scrollToItem(0)
androidx.compose.runtime.withFrameNanos { }
// After touch, focus starts outside the page and the first request is turned to the page's own entry, behind the sheet. Ask until it is in here.
focusWithinFrames({ inside || closing }) { firstApp }
repeat(2) { androidx.compose.runtime.withFrameNanos { } }
if (!closing) runCatching { firstApp.requestFocus() }
}
}
val close = {
val wasRenaming = renaming
closing = true
if (renaming) commit()
onClose()
if (inputMode == InputMode.Keyboard && ff != null) {
runCatching { ff.items.getValue("tile:folder:${folder.id}").requestFocus() }
.onFailure { runCatching { ff.firstTile.requestFocus() } }
if (wasRenaming) onHoldFocus()
}
}
BackHandler { close() }
@@ -886,7 +861,6 @@ private fun FolderSheet(
.glideBorder(false, Shape16, pal.signal, pal.signal.copy(alpha = 0.22f))
.pointerInput(Unit) { awaitEachGesture { awaitFirstDown(requireUnconsumed = false).consume() } }
.controllerBack(close)
.onFocusChanged { inside = it.hasFocus }
.focusProperties {
exit = { dir ->
if (dir == FocusDirection.Up || dir == FocusDirection.Down || dir == FocusDirection.Left || dir == FocusDirection.Right) FocusRequester.Cancel
@@ -160,7 +160,7 @@ internal fun BootMovieGroup(s: ModeSettings, a: ModeSettingsActions, host: MenuH
TabChip(stringResource(R.string.boot_movie_tab_sound), tab == MovieTab.SOUND, Modifier.weight(1f)) { tab = MovieTab.SOUND }
}
when (tab) {
MovieTab.INSTALLED -> InstalledTab(a, host)
MovieTab.INSTALLED -> InstalledTab(a)
MovieTab.IMPORT -> ImportTab(s, a)
MovieTab.REPO -> RepoTab(a)
MovieTab.SOUND -> SoundTab(s, a, host)
@@ -170,7 +170,7 @@ internal fun BootMovieGroup(s: ModeSettings, a: ModeSettingsActions, host: MenuH
}
@Composable
private fun InstalledTab(a: ModeSettingsActions, host: MenuHost) {
private fun InstalledTab(a: ModeSettingsActions) {
var browsing by remember { mutableStateOf(false) }
val snapshot = rememberMovies(0, a.onBootMovieChanged)
val current = snapshot?.let { snap -> snap.entries.firstOrNull { it.id == snap.selected }?.title }
@@ -183,12 +183,6 @@ private fun InstalledTab(a: ModeSettingsActions, host: MenuHost) {
modifier = Modifier.padding(horizontal = 14.dp).padding(bottom = 12.dp),
)
val app = LocalContext.current.applicationContext
var shuffle by remember { mutableStateOf(SessionPrefs.bootMovieShuffle(app)) }
LaunchedEffect(snapshot) { shuffle = SessionPrefs.bootMovieShuffle(app) }
ToggleRow(
host, "boot-movie-shuffle", stringResource(R.string.boot_movie_shuffle),
stringResource(R.string.common_applies_next_session), shuffle,
) { on -> shuffle = on; SessionPrefs.setBootMovieShuffle(app, on) }
val scope = rememberCoroutineScope()
var saving by remember { mutableStateOf(false) }
val debugging = remember { com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(app) }
@@ -28,7 +28,6 @@ import com.droiddeck.launcher.input.PointerGestures
import com.droiddeck.launcher.input.TouchpadGestures
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.BottomDesktop
import com.droiddeck.launcher.wayland.WaylandCompositor
@SuppressLint("ViewConstructor")
class BottomDesktopPanel(
@@ -290,10 +289,10 @@ class BottomDesktopPanel(
override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) {
movePointer(x, y)
BottomDesktop.sendScene(WaylandCompositor.SCENE_BUTTON, button, if (pressed) 1 else 0)
BottomDesktop.sendScene(SCENE_BUTTON, button, if (pressed) 1 else 0)
}
override fun onWheel(steps: Int) = BottomDesktop.sendScene(WaylandCompositor.SCENE_WHEEL, steps)
override fun onWheel(steps: Int) = BottomDesktop.sendScene(SCENE_WHEEL, steps)
override fun onScroll(dx: Float, dy: Float) {
val (outW, outH) = BottomDesktop.outputSize
@@ -304,18 +303,18 @@ class BottomDesktopPanel(
if (h == 0 && v == 0) return
scrollRestX -= h
scrollRestY -= v
BottomDesktop.sendScene(WaylandCompositor.SCENE_AXIS_FINGER, v, h)
BottomDesktop.sendScene(SCENE_AXIS, v, h)
}
override fun onScrollEnd() {
scrollRestX = 0f
scrollRestY = 0f
BottomDesktop.sendScene(WaylandCompositor.SCENE_AXIS_FINGER, 0, 0)
BottomDesktop.sendScene(SCENE_AXIS, 0, 0)
}
override fun onZoom(steps: Int) {
BottomDesktop.sendKey(KEY_LEFTCTRL, true)
BottomDesktop.sendScene(WaylandCompositor.SCENE_WHEEL, steps)
BottomDesktop.sendScene(SCENE_WHEEL, steps)
BottomDesktop.sendKey(KEY_LEFTCTRL, false)
}
@@ -332,6 +331,9 @@ class BottomDesktopPanel(
private fun dp(value: Int): Int = (value * resources.displayMetrics.density + 0.5f).toInt()
private companion object {
const val SCENE_BUTTON = 3
const val SCENE_WHEEL = 4
const val SCENE_AXIS = 12
const val KEY_LEFTCTRL = 29
const val AXIS_UNITS_PER_PIXEL = 3f
const val TEXT_FIELD_TAP_MS = 1_000L
@@ -19,7 +19,6 @@ class BottomGameScreen(
display: Display,
private val callback: SurfaceHolder.Callback,
private val onTouch: (MotionEvent) -> Boolean,
private val onHover: (MotionEvent) -> Boolean,
) : Presentation(activity, display) {
val surfaceView = SurfaceView(getContext())
val holder: SurfaceHolder get() = surfaceView.holder
@@ -52,7 +51,7 @@ class BottomGameScreen(
activity.dispatchKeyEvent(event) || super.dispatchKeyEvent(event)
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean =
onHover(event) || activity.dispatchGenericMotionEvent(event) || super.dispatchGenericMotionEvent(event)
activity.dispatchGenericMotionEvent(event) || super.dispatchGenericMotionEvent(event)
}
object GameScreenSwap {
Loaded 100 of 280 files, more files were not shown because too many files have changed in this diff. Show more