mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 20:45:43 +00:00
Compare commits
54
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
62b61e64bb | ||
|
|
03812bb3b7 | ||
|
|
cbcf39d7c2 | ||
|
|
91a217879f | ||
|
|
605f85b4b9 | ||
|
|
fb14b99d50 | ||
|
|
f1a0b7e2ff | ||
|
|
cdecd09e3c | ||
|
|
a8aff1c1a3 | ||
|
|
fc0f8a8530 | ||
|
|
d0398fd853 | ||
|
|
4e3eeea5e2 | ||
|
|
2e64ae7575 | ||
|
|
a62933d023 | ||
|
|
ab7e17a09d | ||
|
|
de5f0fe6df | ||
|
|
5dd973587f | ||
|
|
a4558c841a | ||
|
|
decab6ea90 | ||
|
|
de70e37f30 | ||
|
|
33cd43237e | ||
|
|
253756d45f | ||
|
|
4759a01ef3 | ||
|
|
7dedf945c2 | ||
|
|
4527e93118 | ||
|
|
56fabbdbf0 | ||
|
|
b424bfa353 | ||
|
|
1570d4457c | ||
|
|
75c321123d | ||
|
|
fbb705cf6f | ||
|
|
448d296a2b | ||
|
|
a9524ea991 | ||
|
|
73ccae2425 | ||
|
|
6384b220fc | ||
|
|
e3d86c4b17 | ||
|
|
76aa3771b7 | ||
|
|
9c349e185e | ||
|
|
c2663ebee8 | ||
|
|
f15c0af34e | ||
|
|
68f1d5baa3 | ||
|
|
293ed4fb08 | ||
|
|
52e8028609 | ||
|
|
9ce6d45be8 | ||
|
|
ae9bac225d | ||
|
|
7b4b86b0f3 | ||
|
|
a7032530da | ||
|
|
7254a88391 | ||
|
|
fdf3d98c36 | ||
|
|
6f7d7f827f | ||
|
|
a0cd5b0cad | ||
|
|
97c6229e85 | ||
|
|
0ff1bebdf6 | ||
|
|
e5824dabab | ||
|
|
8276b29b7d |
No files matched your search
@@ -0,0 +1,39 @@
|
||||
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
|
||||
@@ -992,3 +992,35 @@ 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
|
||||
@@ -40,36 +40,19 @@ 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:
|
||||
|
||||
@@ -226,6 +226,8 @@ jobs:
|
||||
publish:
|
||||
needs: [authorize, sign]
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
keep: ${{ steps.publish.outputs.keep }}
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
@@ -322,12 +324,8 @@ 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
|
||||
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
|
||||
# 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"
|
||||
|
||||
published=$(gh release view "$tag" -R "$repo" --json tagName,assets)
|
||||
jq -e --arg tag "$tag" '.tagName == $tag and (.assets | length) > 0' <<<"$published" >/dev/null
|
||||
@@ -417,3 +415,41 @@ 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
|
||||
@@ -26,35 +26,15 @@ jobs:
|
||||
private-key: ${{ secrets.DROIDDECK_CI_APP_KEY }}
|
||||
owner: Droid-Deck
|
||||
repositories: DroidDeck-CI
|
||||
- name: Delete test builds whose PR is no longer open
|
||||
- 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
|
||||
env:
|
||||
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"
|
||||
SOURCE_GITHUB_TOKEN: ${{ github.token }}
|
||||
CI_GITHUB_TOKEN: ${{ steps.ci-token.outputs.token }}
|
||||
run: python3 tools/release/retire_test_builds.py
|
||||
|
||||
catalog:
|
||||
needs: sweep
|
||||
|
||||
@@ -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 [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`.
|
||||
- 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.
|
||||
- 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.
|
||||
- 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'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`. 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`. 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).
|
||||
- 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.
|
||||
|
||||
@@ -295,6 +295,16 @@ 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'))
|
||||
|
||||
@@ -89,21 +89,11 @@
|
||||
android:label="@string/steam_wall_label"
|
||||
android:theme="@android:style/Theme.Translucent.NoTitleBar"
|
||||
android:exported="true" />
|
||||
<service android:name=".input.HomeButtonService"
|
||||
android:label="@string/integration_shortcuts_service"
|
||||
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
|
||||
android:exported="true">
|
||||
<service android:name=".input.ShortcutsRelay" android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.accessibilityservice.AccessibilityService" />
|
||||
<action android:name="com.droiddeck.shortcuts.RELAY" />
|
||||
</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"
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"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.
Binary file not shown.
|
After Width: | Height: | Size: 21 KiB |
@@ -37,6 +37,7 @@
|
||||
#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>
|
||||
@@ -157,6 +158,8 @@ 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);
|
||||
@@ -195,6 +198,7 @@ static constexpr size_t kSnapshotButtonCount =
|
||||
|
||||
namespace Logger {
|
||||
void init();
|
||||
void log(const char *message, ...);
|
||||
}
|
||||
|
||||
static void controller_fork_prepare();
|
||||
@@ -286,6 +290,68 @@ 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;
|
||||
|
||||
@@ -411,22 +477,49 @@ __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, uint16_t slot) {
|
||||
check_ff_event(const struct input_event *ev, FakeController &controller) {
|
||||
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;
|
||||
@@ -1185,10 +1278,13 @@ 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,
|
||||
@@ -1395,6 +1491,25 @@ __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())
|
||||
@@ -1439,7 +1554,7 @@ __attribute__((visibility("hidden"))) static bool is_withdrawn_pad_path(const ch
|
||||
free(fake);
|
||||
return !exposed;
|
||||
}
|
||||
return number == 0 || !process_is_steam_client();
|
||||
return number == 0 || !process_reads_pads();
|
||||
}
|
||||
|
||||
static bool fake_pad_withdrawn(const FakeController &fake) {
|
||||
@@ -1654,7 +1769,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_is_steam_client()) {
|
||||
if (!process_reads_pads()) {
|
||||
Logger::log("deck: %s refused: not the Steam client\n", path);
|
||||
errno = ENOENT;
|
||||
return -1;
|
||||
@@ -1863,7 +1978,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_is_steam_client()) {
|
||||
if (!process_reads_pads()) {
|
||||
errno = ENOENT;
|
||||
return -1;
|
||||
}
|
||||
@@ -2004,15 +2119,19 @@ __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_is_steam_client() && touch_ring();
|
||||
return pathname && !strcmp(pathname, TOUCH_HIDRAW_PATH) && process_reads_pads() && 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;
|
||||
static std::mutex mutex;
|
||||
std::lock_guard<std::mutex> guard(mutex);
|
||||
std::lock_guard<std::mutex> guard(touch_state_mutex);
|
||||
ProcessSlotLock slot(touch_state_lock_fd, "touch-state", 20);
|
||||
if (!slot.may_write()) return;
|
||||
__atomic_fetch_add(&ring->state_seq, 1, __ATOMIC_ACQ_REL);
|
||||
write(*ring);
|
||||
__atomic_fetch_add(&ring->state_seq, 1, __ATOMIC_ACQ_REL);
|
||||
@@ -2264,9 +2383,10 @@ __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");
|
||||
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) {
|
||||
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)) {
|
||||
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) {
|
||||
@@ -2285,7 +2405,7 @@ __attribute__((visibility("hidden"))) static void *pad_type_thread(void *) {
|
||||
|
||||
__attribute__((constructor)) static void start_pad_type_watch() {
|
||||
config();
|
||||
if (!process_is_steam_client() || !fake_deck_enabled()) return;
|
||||
if (!process_reads_pads() || !fake_deck_enabled()) return;
|
||||
pthread_t thread;
|
||||
if (pthread_create(&thread, nullptr, pad_type_thread, nullptr) == 0) pthread_detach(thread);
|
||||
}
|
||||
@@ -2306,7 +2426,7 @@ __attribute__((visibility("hidden"))) static void *touch_plug_thread(void *) {
|
||||
|
||||
__attribute__((constructor)) static void start_touch_controller() {
|
||||
config();
|
||||
if (!process_is_steam_client() || !touch_ring()) return;
|
||||
if (!process_reads_pads() || !touch_ring()) return;
|
||||
pthread_t thread;
|
||||
if (pthread_create(&thread, nullptr, touch_plug_thread, nullptr) == 0) pthread_detach(thread);
|
||||
}
|
||||
@@ -2413,8 +2533,13 @@ __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;
|
||||
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))
|
||||
// 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))
|
||||
Logger::log("deck: imu mode not published (%s)\n", strerror(errno));
|
||||
syscall(SYS_close, fd);
|
||||
}
|
||||
@@ -2619,7 +2744,10 @@ __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) &&
|
||||
@@ -2651,7 +2779,13 @@ __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);
|
||||
@@ -2839,7 +2973,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_is_steam_client()) {
|
||||
if (saved_errno == ENOENT || !pathname || !process_reads_pads()) {
|
||||
errno = saved_errno;
|
||||
return path;
|
||||
}
|
||||
@@ -2878,7 +3012,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_is_steam_client()) return {};
|
||||
if (!path || !listing || errno != EACCES || !fake_deck_enabled() || !process_reads_pads()) 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;
|
||||
@@ -2947,7 +3081,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_is_steam_client() && deck_device_library(__builtin_return_address(0))) {
|
||||
process_reads_pads() && 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))
|
||||
@@ -3136,7 +3270,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_is_steam_client())) {
|
||||
sony_pad_path(pathname)) && !process_reads_pads())) {
|
||||
errno = ENOENT;
|
||||
return -1;
|
||||
}
|
||||
@@ -3261,9 +3395,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_is_steam_client()) return 0;
|
||||
if (is_deck_hidraw_path(pathname) && process_reads_pads()) return 0;
|
||||
if ((is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || sony_pad_path(pathname)) &&
|
||||
process_is_steam_client())
|
||||
process_reads_pads())
|
||||
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) ||
|
||||
@@ -3302,9 +3436,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_is_steam_client()) return 0;
|
||||
if (is_deck_hidraw_path(pathname) && process_reads_pads()) return 0;
|
||||
if ((is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || sony_pad_path(pathname)) &&
|
||||
process_is_steam_client())
|
||||
process_reads_pads())
|
||||
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) ||
|
||||
@@ -3371,7 +3505,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_is_steam_client()) {
|
||||
} else if (!strcmp(pathname, "/dev") && fake_deck_enabled() && process_reads_pads()) {
|
||||
std::string events = hidraw_event_dir();
|
||||
mkdir(events.c_str(), 0700);
|
||||
my_inotify_add_watch(fd, events.c_str(), mask);
|
||||
@@ -3657,10 +3791,12 @@ 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;
|
||||
@@ -3740,6 +3876,7 @@ 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);
|
||||
}
|
||||
@@ -3937,12 +4074,8 @@ EXPORT ssize_t write(int fd, const void *buf, size_t count) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
if (count == sizeof(struct input_event))
|
||||
check_ff_event(static_cast<const struct input_event *>(buf), *controller->second);
|
||||
|
||||
return static_cast<ssize_t>(count);
|
||||
}
|
||||
@@ -3982,14 +4115,10 @@ 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)) {
|
||||
const struct input_event *ev =
|
||||
static_cast<const struct input_event *>(iov[i].iov_base);
|
||||
check_ff_event(ev, slot);
|
||||
}
|
||||
if (iov[i].iov_len == sizeof(struct input_event))
|
||||
check_ff_event(static_cast<const struct input_event *>(iov[i].iov_base), *controller->second);
|
||||
total += static_cast<ssize_t>(iov[i].iov_len);
|
||||
}
|
||||
return total;
|
||||
|
||||
@@ -127,6 +127,9 @@ 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
|
||||
@@ -582,6 +585,13 @@ 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);
|
||||
@@ -1339,6 +1349,7 @@ 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); }
|
||||
@@ -3240,14 +3251,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(int px, int py, double *x, double *y) {
|
||||
static void input_output_to_scene(double px, double 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((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;
|
||||
!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;
|
||||
}
|
||||
if (*x < 0) *x = 0;
|
||||
if (*y < 0) *y = 0;
|
||||
@@ -3476,6 +3487,57 @@ 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) {
|
||||
@@ -3627,6 +3689,7 @@ 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;
|
||||
@@ -3666,6 +3729,13 @@ 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 };
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
#include <stdlib.h>
|
||||
#include <sys/stat.h>
|
||||
#include <android/log.h>
|
||||
#include <string.h>
|
||||
|
||||
#define TAG "DroidDeckWayland"
|
||||
|
||||
@@ -45,6 +46,13 @@ 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) {
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
#define VK_GLOBAL_FUNCS(X) X(CreateInstance) X(EnumerateInstanceExtensionProperties)
|
||||
|
||||
#define VK_INSTANCE_FUNCS(X) \
|
||||
X(EnumeratePhysicalDevices) X(GetPhysicalDeviceProperties) \
|
||||
X(DestroyInstance) X(EnumeratePhysicalDevices) X(GetPhysicalDeviceProperties) \
|
||||
X(GetPhysicalDeviceQueueFamilyProperties) X(GetPhysicalDeviceSurfaceSupportKHR) \
|
||||
X(GetPhysicalDeviceSurfaceCapabilitiesKHR) X(GetPhysicalDeviceSurfaceFormatsKHR) \
|
||||
X(CreateAndroidSurfaceKHR) X(DestroySurfaceKHR) X(CreateDevice) \
|
||||
@@ -43,6 +43,7 @@ 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);
|
||||
|
||||
@@ -46,6 +46,7 @@ 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);
|
||||
@@ -250,6 +251,8 @@ 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++) {
|
||||
@@ -426,7 +429,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 = align == VKP_ALIGN_PICTURE_TOP || align == VKP_ALIGN_PICTURE_BOTTOM || align == VKP_ALIGN_PICTURE_LEFT || align == VKP_ALIGN_PICTURE_RIGHT;
|
||||
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_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;
|
||||
@@ -549,6 +552,18 @@ 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,6 +7,7 @@
|
||||
|
||||
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,6 +24,7 @@ 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);
|
||||
@@ -253,12 +254,13 @@ 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) {
|
||||
jstring driverPath, jstring libraryName, jstring nativeLibDir, jboolean allowDriverFallback) {
|
||||
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);
|
||||
@@ -280,6 +282,12 @@ 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) {
|
||||
@@ -448,6 +456,18 @@ 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,7 +48,6 @@ 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)
|
||||
@@ -57,6 +56,7 @@ 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,7 +286,13 @@ 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, if (SessionPrefs.vkBridge(activity)) "bridge" else "")
|
||||
SessionPrefs.setMaliFallbackByAuto(
|
||||
activity,
|
||||
MaliAutoRoute.initialOwnership(
|
||||
SessionPrefs.vkBridge(activity), bridgeExplicit(),
|
||||
SessionPrefs.venus(activity), venusExplicit(),
|
||||
),
|
||||
)
|
||||
// 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)
|
||||
@@ -356,8 +362,14 @@ 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 -> autoStatus = problem?.let { activity.getString(R.string.drivers_up_to_date_check_failed, it) }
|
||||
?: activity.getString(R.string.upd_current_status)
|
||||
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)
|
||||
}
|
||||
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)
|
||||
@@ -397,6 +409,12 @@ 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
|
||||
@@ -410,12 +428,21 @@ 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)
|
||||
SessionPrefs.setMaliFallbackByAuto(activity, "venus")
|
||||
if (SessionPrefs.vkBridge(activity) && !bridgeExplicit())
|
||||
SessionPrefs.setVkBridge(activity, false)
|
||||
SessionPrefs.setMaliFallbackByAuto(activity, ownership)
|
||||
} else if (!venus && !SessionPrefs.vkBridge(activity)) {
|
||||
SessionPrefs.setVkBridge(activity, true)
|
||||
SessionPrefs.setMaliFallbackByAuto(activity, "bridge")
|
||||
SessionPrefs.setMaliFallbackByAuto(activity, ownership)
|
||||
} else if (ownership != MaliAutoRoute.NONE) {
|
||||
SessionPrefs.setMaliFallbackByAuto(activity, ownership)
|
||||
}
|
||||
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}"})")
|
||||
@@ -503,7 +530,9 @@ 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 (gpu.family.mali && DriverPairs.isNonAdreno(pair.key)) endMaliFallback()
|
||||
if (MaliAutoRoute.shouldEnd(
|
||||
SessionPrefs.maliFallbackByAuto(activity), gpu.family.mali, DriverPairs.isNonAdreno(pair.key),
|
||||
)) endMaliFallback()
|
||||
val restart = displayChanged && CompositorHost.isStarted
|
||||
if (auto) {
|
||||
val trial = AutoDriverTrial.current(activity)
|
||||
@@ -744,4 +773,3 @@ internal fun Context.displayNameOf(uri: Uri): String? = if (uri.scheme == "file"
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
|
||||
@@ -182,6 +182,7 @@ 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)
|
||||
@@ -366,15 +367,78 @@ 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) shortcutsTried = true
|
||||
SteamIntegration.setShortcutsListed(this, true)
|
||||
integrationSettings(SteamIntegration.shortcutSettings(this), android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS)
|
||||
if (integrationState.shortcuts) openShortcutSettings() else installShortcuts()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun openAppInfo() =
|
||||
integrationSettings(Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName")))
|
||||
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 openWifiDiscoverySettings() {
|
||||
if (!WifiDiscovery.permissionGranted(this)) {
|
||||
@@ -535,6 +599,7 @@ 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)
|
||||
@@ -1138,6 +1203,9 @@ 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"
|
||||
@@ -1974,7 +2042,6 @@ 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() }
|
||||
@@ -2083,6 +2150,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
gameLaunchRequest.incrementAndGet()
|
||||
cancelCompatLaunch()
|
||||
updates.unregister()
|
||||
runCatching { unregisterReceiver(shortcutsInstallStatus) }
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
@@ -2471,6 +2539,7 @@ 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),
|
||||
@@ -2523,6 +2592,7 @@ 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)
|
||||
@@ -2632,7 +2702,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
fsyncFirst = fsyncFirst,
|
||||
gamescopeRealtime = gamescopeRealtime,
|
||||
gpuClockPin = gpuClockPin,
|
||||
ramCapMb = ramCapMb, vramCapMb = vramCapMb, zramClient = zramClient,
|
||||
ramCapMb = ramCapMb, vramCapMb = vramCapMb, zramClient = zramClient, zramIdle = zramIdle,
|
||||
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(),
|
||||
@@ -2652,6 +2722,7 @@ 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 },
|
||||
@@ -2869,6 +2940,8 @@ 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)
|
||||
@@ -2949,6 +3022,7 @@ 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)
|
||||
@@ -3300,3 +3374,9 @@ 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
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
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,7 +96,17 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
|
||||
percent = 0
|
||||
Thread({
|
||||
val result = runCatching {
|
||||
val file = SelfInstaller.download(activity, apk) { pct -> ui.post { percent = pct } }
|
||||
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 } }
|
||||
}
|
||||
ui.post { stage = activity.getString(R.string.upd_stage_installing); percent = -1 }
|
||||
SelfInstaller.install(activity, file) { id -> session = id }
|
||||
}
|
||||
|
||||
@@ -16,6 +16,8 @@ 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";
|
||||
@@ -29,7 +31,55 @@ public class PulseAudioComponent extends SessionPart {
|
||||
private final File deviceControls;
|
||||
private File logFile;
|
||||
private final String micFifoPath;
|
||||
private volatile int pid = -1;
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
public PulseAudioComponent(Context context) {
|
||||
this(context, null);
|
||||
@@ -64,7 +114,12 @@ public class PulseAudioComponent extends SessionPart {
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
stop();
|
||||
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;
|
||||
if (!workingDir.isDirectory()) {
|
||||
workingDir.mkdirs();
|
||||
FileUtils.chmod(workingDir, 0771);
|
||||
@@ -118,17 +173,23 @@ 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();
|
||||
pid = HostProcess.start(command, env.toArray(new String[0]), workingDir, null,
|
||||
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);
|
||||
}
|
||||
},
|
||||
line -> {
|
||||
Log.i(TAG, line);
|
||||
if (out != null) synchronized (out) { out.println(line); out.flush(); }
|
||||
});
|
||||
Thread guard = new Thread(() -> ensureClientSink(out), "pulse-sink-guard");
|
||||
}))) return;
|
||||
long token = host.token();
|
||||
Thread guard = new Thread(() -> ensureClientSink(out, token), "pulse-sink-guard");
|
||||
guard.setDaemon(true);
|
||||
guard.start();
|
||||
}
|
||||
|
||||
private void ensureClientSink(java.io.PrintWriter out) {
|
||||
private void ensureClientSink(java.io.PrintWriter out, long token) {
|
||||
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
|
||||
@@ -137,14 +198,14 @@ public class PulseAudioComponent extends SessionPart {
|
||||
long deadline = started + 30000L;
|
||||
String sinks = null;
|
||||
boolean socketSeen = false;
|
||||
while (System.currentTimeMillis() < deadline && pid > 1) {
|
||||
while (System.currentTimeMillis() < deadline && host.live(token)) {
|
||||
socketSeen |= socket().exists();
|
||||
if (socketSeen && (sinks = pactl("list", "short", "sinks")) != null) break;
|
||||
if (socketSeen && (sinks = pactlFor(token, "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 " + pid + ")");
|
||||
+ (new File(workingDir, "pactl").isFile() ? "present" : "MISSING") + ", daemon pid " + host.pid + ")");
|
||||
String line;
|
||||
if (sinks == null) {
|
||||
line = "== client sink: the daemon did not answer in 30 s; no fallback attempted";
|
||||
@@ -155,15 +216,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 && pid > 1; attempt++) {
|
||||
for (int attempt = 1; attempt <= 5 && loadedAs == null && host.live(token); attempt++) {
|
||||
try { Thread.sleep(2000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
|
||||
if (pactl("load-module", "module-directaudio-native-sink", "sink_name=DirectAudio", "performance_mode=1",
|
||||
if (pactlFor(token, "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
|
||||
&& pactl("set-default-sink", "DirectAudio") != null) {
|
||||
&& pactlFor(token, "set-default-sink", "DirectAudio") != null) {
|
||||
loadedAs = "DirectAudio on attempt " + attempt;
|
||||
} else if (pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink",
|
||||
} else if (pactlFor(token, "load-module", "module-aaudio-sink", "sink_name=AAudioSink",
|
||||
"performance_mode=" + (attempt == 1 ? "1" : "0"), "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) != null
|
||||
&& pactl("set-default-sink", "AAudioSink") != null) {
|
||||
&& pactlFor(token, "set-default-sink", "AAudioSink") != null) {
|
||||
loadedAs = "the plain AAudio sink (AAudioSink) on attempt " + attempt;
|
||||
}
|
||||
}
|
||||
@@ -186,10 +247,14 @@ 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() || pid <= 1) return null;
|
||||
if (!pactl.isFile() || host.pid <= 1) return null;
|
||||
java.lang.Process process = null;
|
||||
try {
|
||||
File modules = new File(workingDir, "modules/arm64");
|
||||
@@ -231,10 +296,7 @@ public class PulseAudioComponent extends SessionPart {
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
if (pid != -1) {
|
||||
Process.killProcess(pid);
|
||||
pid = -1;
|
||||
}
|
||||
host.stop();
|
||||
}
|
||||
|
||||
public boolean setSinkSuspended(boolean suspended) {
|
||||
@@ -247,7 +309,7 @@ public class PulseAudioComponent extends SessionPart {
|
||||
|
||||
private boolean suspend(String kind, String name, boolean suspended) {
|
||||
File pactl = new File(workingDir, "pactl");
|
||||
if (!pactl.isFile() || pid <= 1) {
|
||||
if (!pactl.isFile() || host.pid <= 1) {
|
||||
Log.w(TAG, "cannot change " + kind + " state: PulseAudio control client or server unavailable");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -233,6 +233,10 @@ 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 {
|
||||
@@ -242,7 +246,9 @@ 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]"
|
||||
k("Linux driver", label)
|
||||
val route = DeviceInfo.hostRoute(context)
|
||||
k("Linux driver", route ?: label)
|
||||
if (route != null) k(" chosen, not used", label)
|
||||
}
|
||||
k("Runtime's own ICD", LinuxRuntime.vulkanIcd(context)?.path)
|
||||
k("Mali (Venus)", if (com.droiddeck.launcher.session.VenusComponent.wanted(context)) "in use"
|
||||
@@ -290,6 +296,8 @@ 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) {
|
||||
fun start(target: File, sinceMillis: Long) {
|
||||
stop()
|
||||
try {
|
||||
val out = target.bufferedWriter()
|
||||
@@ -28,7 +28,7 @@ object SessionLogCapture {
|
||||
writer = out
|
||||
this.target = target
|
||||
pid = HostProcess.start(
|
||||
"/system/bin/logcat -v threadtime -T 1 --pid=" + Process.myPid(),
|
||||
command(Process.myPid(), sinceMillis),
|
||||
null, target.parentFile, null,
|
||||
) { line ->
|
||||
synchronized(this) {
|
||||
@@ -49,6 +49,11 @@ 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
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
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,20 +1,21 @@
|
||||
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(
|
||||
@@ -36,11 +37,7 @@ object SteamIntegration {
|
||||
locationOn = WifiDiscovery.locationEnabled(context),
|
||||
brightness = Settings.System.canWrite(context),
|
||||
home = HomeApp.isDefault(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)
|
||||
},
|
||||
shortcuts = shortcutsEnabled(context),
|
||||
shortcutsRestricted = restrictedSettings(context),
|
||||
suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false),
|
||||
)
|
||||
@@ -48,48 +45,53 @@ 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", android.os.Process.myUid(), context.packageName)
|
||||
.unsafeCheckOpNoThrow("android:access_restricted_settings", uid, Relay.PACKAGE)
|
||||
}.getOrDefault(android.app.AppOpsManager.MODE_ALLOWED)
|
||||
return mode == android.app.AppOpsManager.MODE_ERRORED || mode == android.app.AppOpsManager.MODE_IGNORED
|
||||
}
|
||||
|
||||
private fun shortcutsComponent(context: Context) = ComponentName(context, HomeButtonService::class.java)
|
||||
private val shortcutsComponent = ComponentName(Relay.PACKAGE, Relay.SERVICE)
|
||||
|
||||
fun shortcutsChosen(context: Context): Boolean = shortcutsSelection(context) == true
|
||||
|
||||
private fun shortcutsSelection(context: Context): Boolean? {
|
||||
val target = shortcutsComponent(context)
|
||||
fun shortcutsEnabled(context: Context): Boolean {
|
||||
val enabled = runCatching {
|
||||
Settings.Secure.getString(context.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES)
|
||||
}.getOrElse { return null }.orEmpty()
|
||||
return enabled.split(':').any { ComponentName.unflattenFromString(it.trim()) == target }
|
||||
}.getOrNull().orEmpty()
|
||||
return enabled.split(':').any { ComponentName.unflattenFromString(it.trim()) == shortcutsComponent }
|
||||
}
|
||||
|
||||
fun setShortcutsListed(context: Context, listed: Boolean) {
|
||||
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 {
|
||||
val packages = context.packageManager
|
||||
val component = shortcutsComponent(context)
|
||||
val state = if (listed) PackageManager.COMPONENT_ENABLED_STATE_ENABLED else PackageManager.COMPONENT_ENABLED_STATE_DISABLED
|
||||
runCatching {
|
||||
if (packages.getComponentEnabledSetting(component) != state) {
|
||||
packages.setComponentEnabledSetting(component, state, PackageManager.DONT_KILL_APP)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun syncShortcutsListing(context: Context) {
|
||||
shortcutsSelection(context)?.let { setShortcutsListed(context, it) }
|
||||
@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
|
||||
}
|
||||
|
||||
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 = ComponentName(context, HomeButtonService::class.java).flattenToString()
|
||||
val service = shortcutsComponent.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,6 +112,10 @@ 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(
|
||||
@@ -269,8 +273,10 @@ fun FileManagerScreen(
|
||||
if (showFavorites) showFavorites = false
|
||||
else {
|
||||
while (history.isNotEmpty() && !history.last().first.isDirectory) history.removeAt(history.lastIndex)
|
||||
val previous = history.removeLastOrNull()
|
||||
if (previous != null) {
|
||||
val previous = history.lastOrNull()
|
||||
if (previous != null && backExitsAtRootHop(currentDir, currentRoot, previous)) onExit?.invoke()
|
||||
else if (previous != null) {
|
||||
history.removeLastOrNull()
|
||||
currentRoot = previous.second
|
||||
loadDirectory(previous.first, record = false)
|
||||
} else if (canNavigateUp(currentDir, currentRoot)) currentDir.parentFile?.let { loadDirectory(it, record = false) }
|
||||
|
||||
@@ -43,11 +43,14 @@ 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(File(previousStorage).isDirectory) { context.getString(R.string.game_sync_err_previous_sd) }
|
||||
check(libraryReadable(File(previousStorage))) { context.getString(R.string.game_sync_err_previous_sd) }
|
||||
}
|
||||
storage?.let { check(File(it.path).listFiles() != null) { context.getString(R.string.game_sync_err_game_storage) } }
|
||||
storage?.let { check(libraryReadable(File(it.path))) { 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 === XrealModel || usb.hasPermission(device))
|
||||
val permitted = controllable && device != null && (m is 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 === XrealModel) it.sunblock else _settings.value.sunblock ?: it.sunblock,
|
||||
sunblock = if (m is XrealModel) it.sunblock else _settings.value.sunblock ?: it.sunblock,
|
||||
hardwareControls = m?.hardwareControls == true &&
|
||||
(device?.vendorId == VitureProtocol.VENDOR_ID || m === XrealModel || m is RokidModel),
|
||||
(device?.vendorId == VitureProtocol.VENDOR_ID || m is 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 === XrealModel || (m is VitureProtocol.Model && m.family == VitureProtocol.Family.PRO2 && !m.needsSdk),
|
||||
experimental = m is 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 if (XrealModel.matches(device.vendorId, device.productId)) XrealModel
|
||||
else RokidModel.model(device.vendorId, device.productId, name)
|
||||
else XrealModel.model(device.vendorId, device.productId)
|
||||
?: 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 === XrealModel) {
|
||||
XrealLink.open(app, xrealListener(generation))
|
||||
} else if (model is XrealModel) {
|
||||
XrealLink.open(app, model as XrealModel, xrealListener(generation))
|
||||
} else if (model is RokidModel) {
|
||||
RokidLink.open(usb, device, rokidListener(generation))
|
||||
} else {
|
||||
|
||||
@@ -10,6 +10,7 @@ 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()
|
||||
@@ -29,7 +30,8 @@ internal class XrealLink internal constructor(
|
||||
private val worker = Thread(::run, "xreal-control").apply { isDaemon = true; start() }
|
||||
|
||||
companion object {
|
||||
fun open(context: Context, listener: Listener) = XrealLink(AndroidXrealConnector(context), listener)
|
||||
fun open(context: Context, model: XrealModel, listener: Listener) =
|
||||
XrealLink(AndroidXrealConnector(context), listener, model)
|
||||
}
|
||||
|
||||
override fun send(msgId: Int, payload: ByteArray): Boolean {
|
||||
@@ -43,9 +45,10 @@ 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 -> value in 2..5 || value == XrealModel.NATIVE_60HZ
|
||||
VitureProtocol.MSG_BRIGHTNESS -> value in 0..9
|
||||
VitureProtocol.MSG_FILM -> value in 0..1
|
||||
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
|
||||
else -> false
|
||||
}
|
||||
return valid && commands.offer(Command(msgId, value))
|
||||
@@ -61,12 +64,12 @@ internal class XrealLink internal constructor(
|
||||
channels = connector.connect()
|
||||
connection.set(channels)
|
||||
if (!running) break
|
||||
val control = XrealControl(channels)
|
||||
val control = XrealControl(channels, stereoOnly = model.stereoOnlyControl)
|
||||
listener.onValue(VitureProtocol.MSG_GET_DISPLAY, control.display())
|
||||
val current = channels
|
||||
reports = Thread({
|
||||
try {
|
||||
var filter = XrealOrientationFilter()
|
||||
var filter = XrealOrientationFilter(model.flipsYz)
|
||||
var wasTracking = false
|
||||
var lastSensor = System.nanoTime()
|
||||
while (running && connection.get() === current) {
|
||||
@@ -75,7 +78,7 @@ internal class XrealLink internal constructor(
|
||||
if (sample != null) {
|
||||
lastSensor = System.nanoTime()
|
||||
val enabled = tracking
|
||||
if (enabled && !wasTracking) filter = XrealOrientationFilter()
|
||||
if (enabled && !wasTracking) filter = XrealOrientationFilter(model.flipsYz)
|
||||
wasTracking = enabled
|
||||
if (enabled) filter.update(sample)?.let {
|
||||
if (running && ready && tracking && connection.get() === current)
|
||||
@@ -149,7 +152,11 @@ internal class XrealLink internal constructor(
|
||||
}
|
||||
}
|
||||
|
||||
internal class XrealControl(private val channels: XrealChannels, private val settleDelayMs: Long = 150) {
|
||||
internal class XrealControl(
|
||||
private val channels: XrealChannels,
|
||||
private val settleDelayMs: Long = 150,
|
||||
private val stereoOnly: Boolean = false,
|
||||
) {
|
||||
private var transaction = 0
|
||||
private fun exchange(command: Int, value: Int? = null): ByteArray {
|
||||
transaction = if (transaction == Int.MAX_VALUE) 1 else transaction + 1
|
||||
@@ -163,26 +170,42 @@ internal class XrealControl(private val channels: XrealChannels, private val set
|
||||
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) return current
|
||||
if (current == mode || stereoOnly) 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) {
|
||||
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 (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")
|
||||
}
|
||||
if (System.nanoTime() > deadline) throw IOException("XREAL display transition timed out")
|
||||
Thread.sleep(settleDelayMs)
|
||||
}
|
||||
|
||||
@@ -1,25 +1,63 @@
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
object XrealModel : GlassesModel {
|
||||
const val VENDOR_ID = 0x3318
|
||||
const val PRODUCT_1S = 0x043e
|
||||
const val NATIVE_60HZ = 29
|
||||
override val name = "XREAL 1S"
|
||||
internal class XrealModel private constructor(
|
||||
override val name: String,
|
||||
val family: Family,
|
||||
override val diagonalFovDeg: Float,
|
||||
) : GlassesModel {
|
||||
enum class Family {
|
||||
ONE_S,
|
||||
ONE,
|
||||
AURA,
|
||||
}
|
||||
|
||||
override val controllable = true
|
||||
override val brightnessMax = 9
|
||||
override val volumeMax = 0
|
||||
override val hasSunblock = true
|
||||
override val diagonalFovDeg = 52f
|
||||
override val hasSunblock get() = family == Family.ONE_S
|
||||
override val hardwareControls get() = family == Family.ONE_S
|
||||
override val sbs90 = false
|
||||
override val rates2d get() = if (family == Family.ONE_S) super.rates2d else listOf(60)
|
||||
|
||||
fun matches(vid: Int, pid: Int) = vid == VENDOR_ID && pid == PRODUCT_1S
|
||||
fun isDisplay(name: String) = name.contains("XREAL", ignoreCase = true)
|
||||
// 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
|
||||
|
||||
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,12 +2,13 @@ package com.droiddeck.launcher.glasses
|
||||
|
||||
import kotlin.math.abs
|
||||
|
||||
internal class XrealOrientationFilter {
|
||||
internal class XrealOrientationFilter(private val flipYz: Boolean = true) {
|
||||
private val fusion = ImuFusion()
|
||||
|
||||
fun update(sample: XrealProtocol.Sample): FloatArray? = fusion.update(sample.timeNs,
|
||||
Vec3(sample.accel.x, -sample.accel.y, -sample.accel.z),
|
||||
Vec3(sample.gyro.x, -sample.gyro.y, -sample.gyro.z))
|
||||
sample.accel.headAxes(), sample.gyro.headAxes())
|
||||
|
||||
private fun Vec3.headAxes() = if (flipYz) Vec3(x, -y, -z) else this
|
||||
}
|
||||
|
||||
internal class ImuFusion {
|
||||
|
||||
@@ -13,6 +13,7 @@ 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,16 +145,22 @@ 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 = SessionPrefs.androidDriver(context).ifEmpty { turnip.autoId() }
|
||||
val choice = turnip.effectiveId()
|
||||
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", if (id.isEmpty()) builtinDriverLabel(powerVr, runtime = true) else "${linux.getDriverName(id)} ${linux.getDriverVersion(id)}".trim())
|
||||
add("Game driver", hostRoute(context) ?: 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,6 +34,8 @@ 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";
|
||||
@@ -140,6 +142,25 @@ 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;
|
||||
@@ -257,6 +278,11 @@ 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;
|
||||
@@ -282,6 +308,12 @@ 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;
|
||||
@@ -318,6 +350,10 @@ 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);
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
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,10 +1,8 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.accessibilityservice.AccessibilityService
|
||||
import android.accessibilityservice.AccessibilityServiceInfo
|
||||
import android.content.Context
|
||||
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
|
||||
@@ -12,9 +10,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 {
|
||||
@@ -45,7 +43,7 @@ object BottomScreenGuests {
|
||||
sdk >= 33 && DualScreen.yieldsBottom(model)
|
||||
}
|
||||
|
||||
class BottomScreenWatch(private val service: AccessibilityService) {
|
||||
class BottomScreenWatch(private val service: Context) {
|
||||
private class Arrival(val pkg: String, val at: Long)
|
||||
|
||||
private val thread = HandlerThread("bottom-screen").apply { start() }
|
||||
@@ -57,33 +55,22 @@ class BottomScreenWatch(private val service: AccessibilityService) {
|
||||
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 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 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 stop() {
|
||||
@@ -97,25 +84,22 @@ class BottomScreenWatch(private val service: AccessibilityService) {
|
||||
thread.quitSafely()
|
||||
}
|
||||
|
||||
private fun evaluate() {
|
||||
private fun evaluate(all: Map<Int, List<Relay.Window>>) {
|
||||
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 (i in 0 until all.size()) {
|
||||
val id = all.keyAt(i)
|
||||
for ((id, list) in all) {
|
||||
if (id == Display.DEFAULT_DISPLAY) continue
|
||||
val display = displays.getDisplay(id)?.takeIf(DualScreen::builtIn) ?: continue
|
||||
val windows = all.valueAt(i)
|
||||
val windows = list
|
||||
.filter { !BottomScreenGuests.ignorable(it.type) && cover(it, display) >= BottomScreenGuests.MIN_COVER }
|
||||
.sortedByDescending { it.layer }
|
||||
.map { it to packageOf(it) }
|
||||
val ours = windows.filter { it.second == own }.map { it.first.id }.toSet()
|
||||
val ours = windows.filter { it.pkg == own }.map { it.id }.toSet()
|
||||
if (!ownWindows[id].orEmpty().containsAll(ours)) ownShownAt[id] = now
|
||||
shown[id] = ours
|
||||
val topPkg = windows.firstNotNullOfOrNull { it.second?.takeUnless { pkg -> pkg == own } }
|
||||
val topPkg = windows.firstNotNullOfOrNull { it.pkg?.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 }
|
||||
@@ -127,15 +111,11 @@ class BottomScreenWatch(private val service: AccessibilityService) {
|
||||
DualScreen.setTaken(taken.keys)
|
||||
}
|
||||
|
||||
private fun cover(window: AccessibilityWindowInfo, display: Display): Float {
|
||||
val bounds = Rect().also(window::getBoundsInScreen)
|
||||
private fun cover(window: Relay.Window, display: Display): Float {
|
||||
val area = display.mode.physicalWidth.toFloat() * display.mode.physicalHeight
|
||||
return if (area <= 0f) 0f else bounds.width().toFloat() * bounds.height() / area
|
||||
return if (area <= 0f) 0f else window.bounds.width().toFloat() * window.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 ->
|
||||
@@ -154,6 +134,7 @@ class BottomScreenWatch(private val service: AccessibilityService) {
|
||||
|
||||
private companion object {
|
||||
@Volatile var current: BottomScreenWatch? = null
|
||||
|
||||
const val TAG = "BottomScreen"
|
||||
const val SYSTEM_UI = "com.android.systemui"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
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() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
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,6 +82,8 @@ 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;
|
||||
@@ -231,6 +233,8 @@ 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);
|
||||
@@ -494,8 +498,11 @@ public class FakeInputWriter {
|
||||
if (ringSlot == null) return -1;
|
||||
synchronized (ringSlot) {
|
||||
ByteBuffer ring = ringSlot.data;
|
||||
int value = ring == null ? 0 : ring.getInt(IMU_MODE_OFFSET);
|
||||
return value < 0 ? value & 0xffff : -1;
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
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 = 14
|
||||
private const val VERSION = 15
|
||||
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("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown).put("stickImage", e.stickImage))
|
||||
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.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true), e.optBoolean("alwaysShown", false), e.optString("stickImage", ""))
|
||||
}
|
||||
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,7 +244,8 @@ data class InputLibrary(
|
||||
for (e in layout.elements) {
|
||||
inputName(e.name)
|
||||
require(e.icon == 0 || InputButtonIcons.has(e.icon))
|
||||
require(e.image.isEmpty() || e.image.matches(Regex("[A-Za-z0-9_.-]{1,128}")) && e.image != "." && e.image != "..")
|
||||
for (image in listOf(e.image, e.stickImage))
|
||||
require(image.isEmpty() || image.matches(Regex("[A-Za-z0-9_.-]{1,128}")) && image != "." && 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,11 +3,16 @@ 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,6 +35,7 @@ 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,6 +57,16 @@ 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)
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
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,13 +23,20 @@ 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])
|
||||
getPointerCoords(index, coordinates[target])
|
||||
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
|
||||
}
|
||||
return MotionEvent.obtain(
|
||||
downTime, eventTime, splitAction, indices.size, properties, coordinates,
|
||||
fun time(position: Int) = if (position < historySize) getHistoricalEventTime(position) else eventTime
|
||||
val split = MotionEvent.obtain(
|
||||
downTime, time(0), splitAction, indices.size, properties, sample(0),
|
||||
metaState, buttonState, xPrecision, yPrecision,
|
||||
deviceId, edgeFlags, source, flags,
|
||||
)
|
||||
for (position in 1..historySize) split.addBatch(time(position), sample(position), metaState)
|
||||
return split
|
||||
}
|
||||
+64
-21
@@ -1,14 +1,17 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.accessibilityservice.AccessibilityService
|
||||
import android.app.Service
|
||||
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
|
||||
@@ -101,38 +104,78 @@ object SystemKeyCapture {
|
||||
}
|
||||
}
|
||||
|
||||
class HomeButtonService : AccessibilityService(), InputManager.InputDeviceListener {
|
||||
class ShortcutsRelay : Service(), InputManager.InputDeviceListener {
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
private val trusted = java.util.concurrent.ConcurrentHashMap.newKeySet<Int>()
|
||||
private var bottomScreen: BottomScreenWatch? = null
|
||||
|
||||
override fun onServiceConnected() {
|
||||
getSystemService(InputManager::class.java).registerInputDeviceListener(this, Handler(Looper.getMainLooper()))
|
||||
if (bottomScreen == null && BottomScreenGuests.supported()) bottomScreen = BottomScreenWatch(this).also { it.start() }
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
private fun stopBottomScreen() {
|
||||
bottomScreen?.stop()
|
||||
bottomScreen = null
|
||||
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)
|
||||
}
|
||||
|
||||
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()
|
||||
stopBottomScreen()
|
||||
bottomScreen?.stop()
|
||||
bottomScreen = null
|
||||
getSystemService(InputManager::class.java).unregisterInputDeviceListener(this)
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val KEY_TIMEOUT_MS = 200L
|
||||
}
|
||||
}
|
||||
@@ -129,8 +129,9 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu
|
||||
}
|
||||
}
|
||||
}
|
||||
g.disconnect()
|
||||
g.close()
|
||||
// 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) }
|
||||
Log.i(TAG, "disconnected: $why")
|
||||
listener?.invoke()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
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,8 +150,37 @@ 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 named = SessionFiles.startupMovieLocalPath(BootMovieLibrary.steamConfig(context)) ?: return false
|
||||
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 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 (3), wheel (4) and smooth-scroll (12) input, as `WaylandCompositor.nativeSendSceneInput` takes it. */
|
||||
/** Button, wheel and finger-scroll input, using the `WaylandCompositor.SCENE_*` types `nativeSendSceneInput` takes. */
|
||||
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,6 +20,7 @@ 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,6 +8,7 @@ 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
|
||||
@@ -26,13 +27,14 @@ 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 || Build.SOC_MODEL != "CQ8725S") return "game thread hints: Odin 3 only"
|
||||
if (Build.VERSION.SDK_INT < 31 || !supported(Build.SOC_MODEL)) return "game thread hints: Snapdragon 8 Elite only"
|
||||
val hm = context.getSystemService(PerformanceHintManager::class.java)
|
||||
?: return "game thread hints: no PerformanceHintManager"
|
||||
val pm = context.getSystemService(PowerManager::class.java)
|
||||
@@ -99,6 +101,8 @@ 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,17 +60,19 @@ 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: " + linux.ifEmpty { "(runtime default)" })
|
||||
appendLine("runtime driver: " + (com.droiddeck.launcher.gpu.DeviceInfo.hostRoute(context)
|
||||
?.let { "$it (picked ${linux.ifEmpty { "runtime default" }}, not used)" } ?: 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") + ")")
|
||||
@@ -161,8 +163,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. */
|
||||
private val COMPOSITOR = Regex(
|
||||
"""vk_present|waylandcomp|vk_loader|compositor|vkCreateDevice|extension|adrenotools|TurnipDriver|""" +
|
||||
internal val COMPOSITOR = Regex(
|
||||
"""vk_present|waylandcomp|vk_loader|compositor|vkCreateDevice|extension|adrenotools|hook_impl|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,6 +19,7 @@ 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() {
|
||||
@@ -39,6 +40,10 @@ 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
|
||||
@@ -66,7 +71,9 @@ class RumbleComponent : SessionPart() {
|
||||
try {
|
||||
val bytes = ByteArray(8)
|
||||
DataInputStream(client.inputStream).readFully(bytes)
|
||||
buzz(u16(bytes, 0), u16(bytes, 2), u16(bytes, 4), u16(bytes, 6))
|
||||
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())
|
||||
} catch (e: Exception) {
|
||||
} finally {
|
||||
try { client.close() } catch (e: Exception) { }
|
||||
@@ -94,7 +101,9 @@ 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)
|
||||
|
||||
@Synchronized private fun buzz(strong: Int, weak: Int, ms: Int, slot: Int) {
|
||||
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) {
|
||||
if (!enabled || quiet) return
|
||||
val target = target(slot)
|
||||
val previous = playing[slot]
|
||||
@@ -105,10 +114,19 @@ 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) { target.cancel(); forget(slot); 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
|
||||
}
|
||||
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)
|
||||
@@ -116,19 +134,37 @@ class RumbleComponent : SessionPart() {
|
||||
if (wait > 0) handler.postDelayed(effect, wait) else play(effect)
|
||||
}
|
||||
|
||||
@Synchronized private fun play(effect: Effect) {
|
||||
@Synchronized private fun play(effect: Effect, keepalive: Boolean = false) {
|
||||
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) handler?.postDelayed(effect, KEEPALIVE_MS)
|
||||
if (effect.hold) {
|
||||
effect.armed = true
|
||||
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) }
|
||||
}
|
||||
@@ -170,8 +206,32 @@ 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 &&
|
||||
@@ -185,7 +245,7 @@ class RumbleComponent : SessionPart() {
|
||||
until = now + duration
|
||||
}
|
||||
|
||||
override fun run() = play(this)
|
||||
override fun run() = play(this, keepalive = true)
|
||||
}
|
||||
|
||||
internal interface Motors {
|
||||
@@ -256,6 +316,7 @@ 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)
|
||||
@@ -263,6 +324,13 @@ 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,6 +75,17 @@ 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,6 +14,9 @@ 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"
|
||||
@@ -73,6 +76,7 @@ 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",
|
||||
@@ -356,6 +360,11 @@ 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)
|
||||
}
|
||||
@@ -368,28 +377,30 @@ object SessionFiles {
|
||||
}
|
||||
|
||||
internal fun resetMissingStartupMovie(config: File, force: Boolean): Boolean {
|
||||
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
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -490,6 +501,42 @@ 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(
|
||||
@@ -512,69 +559,71 @@ object SessionFiles {
|
||||
}
|
||||
|
||||
internal fun ensureStartupMovieDefault(config: File, force: Boolean = false): Boolean {
|
||||
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")
|
||||
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)
|
||||
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")
|
||||
} 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
|
||||
}
|
||||
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 + "}"
|
||||
}
|
||||
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)
|
||||
}
|
||||
} 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)) {
|
||||
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) {
|
||||
staged.delete()
|
||||
Log.e(TAG, "could not write Steam startup movie selection")
|
||||
Log.w(TAG, "could not write Steam startup movie selection", e)
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -660,32 +709,34 @@ object SessionFiles {
|
||||
private val IDLE_SLEEP_TIMERS = listOf("IdleSuspendBatterySeconds", "IdleSuspendACSeconds")
|
||||
|
||||
internal fun disableIdleSleep(steamHome: File): Boolean {
|
||||
val config = File(steamHome, "config/config.vdf")
|
||||
val text = runCatching { config.readText() }.getOrNull() ?: return false
|
||||
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
|
||||
val steam = findSteamBlock(text) ?: return false
|
||||
val system = findObject(text, "system", steam.open + 1, steam.close)
|
||||
val updated = if (system != null) {
|
||||
val block = text.substring(system.keyStart, system.close + 1)
|
||||
text.replaceRange(system.keyStart, system.close + 1, IDLE_SLEEP_TIMERS.fold(block) { acc, key -> setScalar(acc, key, "0", newline) })
|
||||
} else {
|
||||
val lineStart = text.lastIndexOf('\n', steam.close).let { if (it < 0) 0 else it + 1 }
|
||||
val indent = text.substring(lineStart, steam.close).takeWhile { it == '\t' || it == ' ' } + "\t"
|
||||
val section = (listOf(indent + "\"system\"", indent + "{") +
|
||||
IDLE_SLEEP_TIMERS.map { "$indent\t\"$it\"\t\t\"0\"" } + (indent + "}")).joinToString(newline) + newline
|
||||
text.substring(0, lineStart) + section + text.substring(lineStart)
|
||||
}
|
||||
val staged = File(config.parentFile, config.name + ".staged")
|
||||
return try {
|
||||
if (updated != text) {
|
||||
staged.writeText(updated)
|
||||
if (!staged.renameTo(config)) { staged.delete(); return false }
|
||||
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
|
||||
}
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
staged.delete()
|
||||
Log.w(TAG, "could not disable Steam's idle sleep", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -737,7 +788,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 ]*)$")
|
||||
val pattern = Regex("(?m)^([\\t ]*\"${Regex.escape(key)}\"[\\t ]+)\"[^\"\\r\\n]*\"([\\t ]*(?://[^\\r\\n]*)?)$")
|
||||
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,6 +23,9 @@ 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 }
|
||||
@@ -38,6 +41,7 @@ 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)) {
|
||||
@@ -49,6 +53,8 @@ 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,6 +13,8 @@ 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)
|
||||
|
||||
@@ -514,6 +516,38 @@ 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"
|
||||
@@ -780,6 +814,12 @@ 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) {
|
||||
@@ -873,8 +913,12 @@ 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) {
|
||||
@@ -1185,6 +1229,13 @@ 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()
|
||||
@@ -1374,6 +1425,13 @@ 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))
|
||||
|
||||
@@ -1443,15 +1501,136 @@ 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,7 +114,10 @@ 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()
|
||||
@@ -390,9 +393,28 @@ 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
|
||||
@@ -413,8 +435,9 @@ class SessionService : Service() {
|
||||
if (SessionPrefs.clearCachedApps(this)) clearCachedApps()
|
||||
cancelQueuedSteamGame(clearMailbox = false)
|
||||
clearSteamGameMailbox()
|
||||
if (SessionState.mode == MODE_STEAM) SessionState.steamUrl
|
||||
?.takeIf { it.startsWith(GAME_URL_PREFIX) }?.let { watchGameExit(it.removePrefix(GAME_URL_PREFIX), gen) }
|
||||
if (SessionState.mode == MODE_STEAM) {
|
||||
resolvedGameId?.let { watchGameExit(it, gen, ++gameExitWatchToken) }
|
||||
}
|
||||
acquireLocks()
|
||||
Thread({
|
||||
OrphanReaper.reap("session starting")
|
||||
@@ -554,7 +577,7 @@ class SessionService : Service() {
|
||||
|
||||
val sessionDir = openSessionFolder()
|
||||
try {
|
||||
GameEnvironmentStore.publish(this)
|
||||
SessionEvents.step("game-environment") { GameEnvironmentStore.publish(this) }
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "could not publish the game environment", e)
|
||||
stopSession(-1, gen)
|
||||
@@ -566,22 +589,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, GpuClockPin.start(this))
|
||||
Log.i(TAG, GameThreadHints.start(this))
|
||||
Log.i(TAG, SessionEvents.step("gpu-clock-pin") { GpuClockPin.start(this) })
|
||||
Log.i(TAG, SessionEvents.step("thread-hints") { GameThreadHints.start(this) })
|
||||
|
||||
val size = SessionState.outputSize
|
||||
val guest = ArrayList<String>()
|
||||
val steamHere = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
|
||||
runCatching { ComponentsManager.republish(this) }
|
||||
runCatching { SessionEvents.step("components-republish") { 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 { ComponentsManager.ensureForcedPackages(this) }
|
||||
runCatching { SessionEvents.step("components-forced") { ComponentsManager.ensureForcedPackages(this) } }
|
||||
.onSuccess { if (it != null) Log.i(TAG, it) }
|
||||
.onFailure { Log.w(TAG, "forced components", it) }
|
||||
}
|
||||
try {
|
||||
addClientEnvironment(guest, steamHere, agentEnvironment)
|
||||
SessionEvents.step("client-environment") { 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)
|
||||
@@ -591,8 +614,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 = startAudio(guest, sessionDir, directAudioPack)
|
||||
startVkBridge(guest, sessionDir)
|
||||
val pulse = SessionEvents.step("audio") { startAudio(guest, sessionDir, directAudioPack) }
|
||||
SessionEvents.step("vk-bridge") { startVkBridge(guest, sessionDir) }
|
||||
if (VenusComponent.wanted(this)) {
|
||||
components.add(VenusComponent(File(sessionDir, "venus.log")).also { it.attach(this) })
|
||||
}
|
||||
@@ -638,20 +661,20 @@ class SessionService : Service() {
|
||||
deckBinds = emptyList()
|
||||
inputSysfs = null
|
||||
if (controllersOn) {
|
||||
addControllerEnvironment(guest, fakeInputDir, sessionDir)
|
||||
SessionState.padBridge?.syncConnectedControllers()
|
||||
SessionEvents.step("controller-environment") { addControllerEnvironment(guest, fakeInputDir, sessionDir) }
|
||||
SessionEvents.step("controller-sync") { 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 { com.droiddeck.launcher.stores.epic.EpicClientLibrary.sync(this) }
|
||||
runCatching { SessionEvents.step("epic-library") { com.droiddeck.launcher.stores.epic.EpicClientLibrary.sync(this) } }
|
||||
.onFailure { Log.w(TAG, "Epic library sync failed", it) }
|
||||
runCatching { com.droiddeck.launcher.stores.epic.EpicClient.prepareInstallDir(this) }
|
||||
runCatching { SessionEvents.step("epic-install-dir") { com.droiddeck.launcher.stores.epic.EpicClient.prepareInstallDir(this) } }
|
||||
.onFailure { Log.w(TAG, "Epic install directory setup failed", it) }
|
||||
}
|
||||
if (steamHere || noSteamGame) {
|
||||
val added = com.droiddeck.launcher.frontend.AddedGames.scan(this)
|
||||
val listing = com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added)
|
||||
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) }
|
||||
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")
|
||||
@@ -663,7 +686,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")
|
||||
GraphicsReport.begin(this, sessionDir, guest)
|
||||
SessionEvents.step("graphics-report") { GraphicsReport.begin(this, sessionDir, guest) }
|
||||
val shellGuest = ArrayList(guest).apply {
|
||||
add("SHELL=/bin/bash")
|
||||
add("TERM=xterm-256color")
|
||||
@@ -691,7 +714,7 @@ class SessionService : Service() {
|
||||
Log.i(TAG, "run: $program (${SessionState.programArgs.size} arguments) under gamescope")
|
||||
}
|
||||
|
||||
FileUtils.clear(File(LinuxRuntime.liveDir(this), "shm"))
|
||||
SessionEvents.step("shm-clear") { 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)
|
||||
@@ -797,7 +820,7 @@ class SessionService : Service() {
|
||||
watchLaunchRequests(sessionRoot)
|
||||
watchSyncWanted(root)
|
||||
EsyncPacks.fetchInBackground(this, root)
|
||||
val pid = HostProcess.start(line, hostEnv.asArray(), root, { status ->
|
||||
val pid = SessionEvents.step("guest-launch") { 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
|
||||
@@ -805,7 +828,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")
|
||||
@@ -893,7 +916,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"))
|
||||
SessionLogCapture.start(File(sessionDir, "app.log"), SessionPaths.startedAt(sessionDir))
|
||||
MemoryLog.start()
|
||||
return sessionDir
|
||||
}
|
||||
@@ -1014,13 +1037,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
|
||||
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")
|
||||
}
|
||||
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=")
|
||||
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)
|
||||
@@ -1521,7 +1544,19 @@ class SessionService : Service() {
|
||||
return
|
||||
}
|
||||
val accepted = gameId!!
|
||||
if (pendingSteamGameId != null) Log.i(TAG, "replacing a queued game launch with $accepted")
|
||||
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))
|
||||
pendingSteamGameId = accepted
|
||||
pendingSteamGameGeneration = sessionGen
|
||||
if (SessionState.suspended) resumeSession()
|
||||
@@ -1532,9 +1567,29 @@ 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 || !GameLaunchLink.validId(gameId)) {
|
||||
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
|
||||
|
||||
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) {
|
||||
@@ -1561,33 +1616,95 @@ 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)
|
||||
watchGameExit(gameId, gen, exitWatchToken, pendingSteamPreviousGameId)
|
||||
Log.i(TAG, "queued Steam game $gameId for the running client")
|
||||
}
|
||||
|
||||
private fun watchGameExit(gameId: String, gen: Int) {
|
||||
if (!SessionPrefs.returnAfterGame(this)) return
|
||||
val token = ++gameExitWatchToken
|
||||
private fun watchGameExit(
|
||||
gameId: String,
|
||||
gen: Int,
|
||||
token: Int,
|
||||
previousGameId: String? = null
|
||||
) {
|
||||
Thread({
|
||||
val startBy = android.os.SystemClock.elapsedRealtime() + GAME_START_TIMEOUT_MS
|
||||
var startupRemaining = GAME_START_TIMEOUT_MS
|
||||
var lastStartupCheck = android.os.SystemClock.elapsedRealtime()
|
||||
var startupWasSuspended = false
|
||||
var seen = false
|
||||
var goneSince = 0L
|
||||
while (token == gameExitWatchToken && gen == sessionGen && SessionState.running && !SessionState.stopRequested) {
|
||||
val now = android.os.SystemClock.elapsedRealtime()
|
||||
if (steamGameRunning()) {
|
||||
if (!seen) Log.i(TAG, "game $gameId started; returning to the launcher when it closes")
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
seen = true
|
||||
goneSince = 0L
|
||||
} else if (!seen) {
|
||||
if (now > startBy) {
|
||||
Log.i(TAG, "game $gameId did not start; not watching for its exit")
|
||||
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)
|
||||
}
|
||||
}
|
||||
return@Thread
|
||||
}
|
||||
} else if (goneSince == 0L) {
|
||||
goneSince = now
|
||||
} else if (now - goneSince >= GAME_EXIT_GRACE_MS) {
|
||||
mainHandler.post { returnAfterGame(gameId, gen, token) }
|
||||
mainHandler.post {
|
||||
if (SessionPrefs.returnAfterGame(this@SessionService)) {
|
||||
returnAfterGame(gameId, gen, token)
|
||||
} else {
|
||||
clearActiveScreenEffectsProfile(gameId, gen, token)
|
||||
}
|
||||
}
|
||||
return@Thread
|
||||
}
|
||||
try { Thread.sleep(GAME_EXIT_POLL_MS) } catch (e: InterruptedException) { return@Thread }
|
||||
@@ -1595,17 +1712,52 @@ class SessionService : Service() {
|
||||
}, "game-exit-watch").start()
|
||||
}
|
||||
|
||||
private fun returnAfterGame(gameId: String, gen: Int, token: Int) {
|
||||
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 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 steamGameRunning(): Boolean = SteamGameProcess.running()
|
||||
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)
|
||||
}
|
||||
|
||||
private fun steamGameRunning(gameId: String): Boolean =
|
||||
SteamGameProcess.running(gameId)
|
||||
|
||||
private fun resumeSession(panelVisible: Boolean = true) {
|
||||
if (SessionState.suspended) SessionState.resumeRequested = true
|
||||
@@ -1625,7 +1777,11 @@ 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()
|
||||
}
|
||||
|
||||
@@ -2108,10 +2264,11 @@ 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() }
|
||||
}
|
||||
SessionTerminal.clear(sessionGen)
|
||||
} + listOfNotNull(shell)
|
||||
BottomDesktop.stop(this, stoppedGen)
|
||||
val controller = suspendController
|
||||
suspendController = null
|
||||
@@ -2448,6 +2605,7 @@ 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,6 +14,12 @@ 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>,
|
||||
@@ -32,8 +38,41 @@ 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
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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", "osc", "shape", "steamController",
|
||||
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "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",
|
||||
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores", "ramCapMb", "vramCapMb", "zramClient", "zramIdle",
|
||||
"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",
|
||||
"bootMovieApplyNext", "bootMovieSteamSeen", "bootMovieShuffle",
|
||||
"questDefaultsV1", "telemetryAuto", "telemetryOff", "statsStrip", "statsHud", "bottomHud", "bottomStripMetrics", "bottomStripTabs", "statsDash", "statsSpeedUnit",
|
||||
)
|
||||
|
||||
|
||||
@@ -5,14 +5,59 @@ import java.io.File
|
||||
object SteamGameProcess {
|
||||
fun matches(cmdline: ByteArray): Boolean {
|
||||
val args = String(cmdline).split('\u0000')
|
||||
for (i in args.indices) {
|
||||
if (args[i] == "waitforexitandrun") return true
|
||||
if (args[i] == "SteamLaunch" && args.getOrNull(i + 1)?.startsWith("AppId=") == true) return true
|
||||
return 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
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
fun running(proc: File = File("/proc")): Boolean = proc.listFiles()?.any { p ->
|
||||
p.name.all(Char::isDigit) && runCatching { File(p, "cmdline").readBytes() }.getOrNull()?.let(::matches) == true
|
||||
} == true
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
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,9 +25,11 @@ 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) {
|
||||
class Result(val result: String, val files: Int, val bytes: Long, val reason: String, val conflicts: Int = 0, val detail: String = "") {
|
||||
val ok: Boolean get() = result != "failed"
|
||||
val line: String get() = "result=$result files=$files bytes=$bytes reason=$reason" + if (conflicts > 0) " conflicts=$conflicts" else ""
|
||||
val line: String get() = "result=$result files=$files bytes=$bytes reason=$reason" +
|
||||
(if (conflicts > 0) " conflicts=$conflicts" else "") +
|
||||
if (detail.isNotEmpty()) " detail=\"$detail\"" else ""
|
||||
}
|
||||
|
||||
class Status(val supported: Boolean, val folder: File?, val lastSync: Long, val reason: String, val conflicts: List<String> = emptyList())
|
||||
@@ -126,7 +128,7 @@ object CloudSaves {
|
||||
)
|
||||
if (picked == null) GogConfig("", "") else GogConfig(picked.name, picked.template)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "gog remote-config: ${e.javaClass.simpleName}")
|
||||
Log.w(TAG, "gog remote-config: ${cloudFailureDetail(e)}")
|
||||
null
|
||||
}
|
||||
}
|
||||
@@ -166,7 +168,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))
|
||||
else GogCloud(userId, clientId, gogScopedToken(context, id, clientId) ?: galaxy, gogLocationName(context, id, folder), tempDir = context.cacheDir)
|
||||
}
|
||||
Store.EPIC -> {
|
||||
val token = EpicCredentialStore.getValidAccessToken(context)
|
||||
@@ -312,7 +314,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)
|
||||
Result("failed", 0, 0, e.javaClass.simpleName, detail = cloudFailureDetail(e))
|
||||
}
|
||||
return done(store, id, way, result)
|
||||
}
|
||||
|
||||
@@ -59,6 +59,69 @@ 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()
|
||||
|
||||
@@ -183,6 +246,8 @@ 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)
|
||||
|
||||
@@ -195,9 +260,10 @@ 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 Galaxy"
|
||||
private val ua = GOG_CLOUD_UA
|
||||
private var prefix: String? = location?.let { "$it/" }
|
||||
|
||||
private fun key(name: String) = URLEncoder.encode(name, "UTF-8").replace("+", "%20")
|
||||
@@ -209,10 +275,10 @@ class GogCloud(
|
||||
val code = c.responseCode
|
||||
if (code == 404) { c.disconnect(); return emptyList() }
|
||||
if (code !in 200..299) {
|
||||
val err = runCatching { c.errorStream?.readBytes()?.decodeToString().orEmpty() }.getOrDefault("")
|
||||
val err = runCatching { cloudErrorPrefix(c.errorStream) }.getOrDefault(CloudErrorPrefix("", false))
|
||||
c.disconnect()
|
||||
if ("not_enabled_for_client" in err || "disabled" in err) throw NoCloudSaves()
|
||||
throw java.io.IOException("GOG cloud list HTTP $code")
|
||||
if ("not_enabled_for_client" in err.text || "disabled" in err.text) throw NoCloudSaves()
|
||||
throw httpFailure("list", null, code, err.snippet())
|
||||
}
|
||||
val text = c.body().decodeToString().trim()
|
||||
c.disconnect()
|
||||
@@ -255,12 +321,20 @@ 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; c.disconnect(); throw java.io.IOException("GOG cloud get HTTP $code") }
|
||||
if (c.responseCode !in 200..299) {
|
||||
val code = c.responseCode
|
||||
val err = c.errorSnippet()
|
||||
c.disconnect()
|
||||
throw httpFailure("get", file.name, code, err)
|
||||
}
|
||||
val modified = httpDate(c.getHeaderField("Last-Modified"))
|
||||
val encoding = c.getHeaderField("Content-Encoding")
|
||||
val data = c.body()
|
||||
c.disconnect()
|
||||
return gogDecodeCloudBody(data, encoding) to modified
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
override fun put(files: Map<String, ByteArray>, modifiedMs: Map<String, Long>): Map<String, Long> = files.mapValues { (name, data) ->
|
||||
@@ -269,7 +343,11 @@ class GogCloud(
|
||||
}
|
||||
|
||||
override fun putFiles(files: Map<String, File>, modifiedMs: Map<String, Long>): Map<String, CloudPut> = files.mapValues { (name, file) ->
|
||||
val compressed = File.createTempFile("gog-cloud-", ".gz")
|
||||
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)
|
||||
}
|
||||
try {
|
||||
val gz = gzipFile(file, compressed)
|
||||
val modified = putBody(name, compressed.inputStream(), gz.length, gz.etag, modifiedMs[name] ?: file.lastModified())
|
||||
@@ -287,10 +365,16 @@ 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)
|
||||
c.outputStream.use { out -> source.use { it.copyTo(out, 64 * 1024) } }
|
||||
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)
|
||||
}
|
||||
val code = c.responseCode
|
||||
if (code !in 200..299) throw java.io.IOException("GOG cloud put HTTP $code")
|
||||
if (code !in 200..299) throw httpFailure("put", name, code, c.errorSnippet())
|
||||
return CloudFile(name, -1L).also { details(it) }.modifiedMs
|
||||
} finally {
|
||||
c.disconnect()
|
||||
|
||||
@@ -84,6 +84,11 @@ 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,6 +26,7 @@ data class EpicGame(
|
||||
val publisher: String = "",
|
||||
val isDlc: Boolean = false,
|
||||
val artLogo: String = "",
|
||||
val thirdPartyManagedApp: String = "",
|
||||
)
|
||||
|
||||
object EpicLibrary {
|
||||
@@ -52,7 +53,10 @@ 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) },
|
||||
.apply {
|
||||
if (g.artLogo.isNotEmpty()) put("artLogo", g.artLogo)
|
||||
if (g.thirdPartyManagedApp.isNotEmpty()) put("thirdPartyManagedApp", g.thirdPartyManagedApp)
|
||||
},
|
||||
)
|
||||
}.toString()
|
||||
|
||||
@@ -76,6 +80,7 @@ object EpicLibrary {
|
||||
releaseDate = o.optString("releaseDate", ""),
|
||||
publisher = o.optString("publisher", ""),
|
||||
artLogo = o.optString("artLogo", ""),
|
||||
thirdPartyManagedApp = o.optString("thirdPartyManagedApp", ""),
|
||||
)
|
||||
}
|
||||
return tidy(games)
|
||||
@@ -108,7 +113,12 @@ 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),
|
||||
extra = mapOf(
|
||||
"namespace" to game.namespace,
|
||||
"catalogItemId" to game.catalogItemId,
|
||||
"version" to game.version,
|
||||
"thirdPartyManagedApp" to game.thirdPartyManagedApp,
|
||||
),
|
||||
logoUrl = game.artLogo.ifEmpty { null },
|
||||
)
|
||||
}
|
||||
@@ -133,6 +143,7 @@ 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(),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -341,7 +341,28 @@ internal fun AndroidAppsPage(s: FrontEndState, a: FrontEndActions, modifier: Mod
|
||||
openFolder = f.id
|
||||
}
|
||||
|
||||
Box(modifier) {
|
||||
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
|
||||
},
|
||||
) {
|
||||
Column(Modifier.fillMaxSize().imePadding()) {
|
||||
Box(Modifier.fillMaxWidth().padding(start = padH, end = padH, top = if (narrow) 8.dp else 12.dp)) {
|
||||
ModeHeader(
|
||||
@@ -443,7 +464,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 }) {
|
||||
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 }) {
|
||||
openFolder = null
|
||||
renameOnOpen = false
|
||||
}
|
||||
@@ -813,7 +834,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, onClose: () -> Unit,
|
||||
onChangeIcon: (HomeApp.LaunchableApp) -> Unit, onHoldFocus: () -> Unit, onClose: () -> Unit,
|
||||
) {
|
||||
SwipeLock()
|
||||
val ctx = LocalContext.current
|
||||
@@ -831,20 +852,24 @@ 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)
|
||||
repeat(2) { androidx.compose.runtime.withFrameNanos { } }
|
||||
if (!closing) runCatching { firstApp.requestFocus() }
|
||||
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 }
|
||||
}
|
||||
}
|
||||
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() }
|
||||
@@ -861,6 +886,7 @@ 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)
|
||||
MovieTab.INSTALLED -> InstalledTab(a, host)
|
||||
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) {
|
||||
private fun InstalledTab(a: ModeSettingsActions, host: MenuHost) {
|
||||
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,6 +183,12 @@ private fun InstalledTab(a: ModeSettingsActions) {
|
||||
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,6 +28,7 @@ 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(
|
||||
@@ -289,10 +290,10 @@ class BottomDesktopPanel(
|
||||
|
||||
override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) {
|
||||
movePointer(x, y)
|
||||
BottomDesktop.sendScene(SCENE_BUTTON, button, if (pressed) 1 else 0)
|
||||
BottomDesktop.sendScene(WaylandCompositor.SCENE_BUTTON, button, if (pressed) 1 else 0)
|
||||
}
|
||||
|
||||
override fun onWheel(steps: Int) = BottomDesktop.sendScene(SCENE_WHEEL, steps)
|
||||
override fun onWheel(steps: Int) = BottomDesktop.sendScene(WaylandCompositor.SCENE_WHEEL, steps)
|
||||
|
||||
override fun onScroll(dx: Float, dy: Float) {
|
||||
val (outW, outH) = BottomDesktop.outputSize
|
||||
@@ -303,18 +304,18 @@ class BottomDesktopPanel(
|
||||
if (h == 0 && v == 0) return
|
||||
scrollRestX -= h
|
||||
scrollRestY -= v
|
||||
BottomDesktop.sendScene(SCENE_AXIS, v, h)
|
||||
BottomDesktop.sendScene(WaylandCompositor.SCENE_AXIS_FINGER, v, h)
|
||||
}
|
||||
|
||||
override fun onScrollEnd() {
|
||||
scrollRestX = 0f
|
||||
scrollRestY = 0f
|
||||
BottomDesktop.sendScene(SCENE_AXIS, 0, 0)
|
||||
BottomDesktop.sendScene(WaylandCompositor.SCENE_AXIS_FINGER, 0, 0)
|
||||
}
|
||||
|
||||
override fun onZoom(steps: Int) {
|
||||
BottomDesktop.sendKey(KEY_LEFTCTRL, true)
|
||||
BottomDesktop.sendScene(SCENE_WHEEL, steps)
|
||||
BottomDesktop.sendScene(WaylandCompositor.SCENE_WHEEL, steps)
|
||||
BottomDesktop.sendKey(KEY_LEFTCTRL, false)
|
||||
}
|
||||
|
||||
@@ -331,9 +332,6 @@ 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,6 +19,7 @@ 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
|
||||
@@ -51,7 +52,7 @@ class BottomGameScreen(
|
||||
activity.dispatchKeyEvent(event) || super.dispatchKeyEvent(event)
|
||||
|
||||
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean =
|
||||
activity.dispatchGenericMotionEvent(event) || super.dispatchGenericMotionEvent(event)
|
||||
onHover(event) || activity.dispatchGenericMotionEvent(event) || super.dispatchGenericMotionEvent(event)
|
||||
}
|
||||
|
||||
object GameScreenSwap {
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.content.ContextWrapper
|
||||
import android.os.SystemClock
|
||||
|
||||
internal fun Context.finishTask() {
|
||||
var c: Context = this
|
||||
while (c is ContextWrapper) {
|
||||
if (c is Activity) {
|
||||
c.finishAndRemoveTask()
|
||||
return
|
||||
}
|
||||
c = c.baseContext
|
||||
}
|
||||
}
|
||||
|
||||
internal object ExitGesture {
|
||||
private const val WINDOW_MS = 2_000L
|
||||
|
||||
private var count = 0
|
||||
private var firstAt = 0L
|
||||
|
||||
fun back(): Int {
|
||||
val now = SystemClock.uptimeMillis()
|
||||
if (count == 0 || now - firstAt > WINDOW_MS) {
|
||||
count = 1
|
||||
firstAt = now
|
||||
} else {
|
||||
count += 1
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
fun reset() {
|
||||
count = 0
|
||||
firstAt = 0L
|
||||
}
|
||||
}
|
||||
@@ -212,6 +212,8 @@ internal fun inPane(o: Origin): Origin =
|
||||
private fun Backdrop(art: File?) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
// True black keeps the page unlit: no art wash and no corner glow.
|
||||
if (pal.id == Themes.TRUE_BLACK) return
|
||||
Crossfade(targetState = art, animationSpec = Motion.tw(700), label = "backdrop") { a ->
|
||||
if (a != null && Build.VERSION.SDK_INT >= 31) {
|
||||
Box(modifier = Modifier.fillMaxSize().alpha(0.26f).blur(70.dp)) {
|
||||
|
||||
@@ -845,8 +845,19 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
(s.pageKey == null && Hops.origin?.page == selected) ||
|
||||
((s.pageKey == null || page == null) &&
|
||||
(selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:") || selected == "store"))
|
||||
BackHandler(enabled = !processSettingsPageVisible && !hasBackTarget) {
|
||||
if (inputModeManager.inputMode != InputMode.Keyboard) inputModeManager.requestInputMode(InputMode.Keyboard)
|
||||
runCatching { frontFocus.railFor(railSelection).requestFocus() }
|
||||
val exitArmed = !processSettingsPageVisible && !hasBackTarget
|
||||
LaunchedEffect(exitArmed, selected) { ExitGesture.reset() }
|
||||
BackHandler(enabled = exitArmed) {
|
||||
when (ExitGesture.back()) {
|
||||
2 -> android.widget.Toast.makeText(ctx, R.string.exit_hint_back, android.widget.Toast.LENGTH_SHORT).show()
|
||||
3 -> {
|
||||
ExitGesture.reset()
|
||||
ctx.finishTask()
|
||||
}
|
||||
else -> {
|
||||
if (inputModeManager.inputMode != InputMode.Keyboard) inputModeManager.requestInputMode(InputMode.Keyboard)
|
||||
runCatching { frontFocus.railFor(railSelection).requestFocus() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -436,6 +436,7 @@ internal fun SetupPanel(
|
||||
}
|
||||
if (s.theme == Themes.INNER_GAMER) RgbSpeedRow()
|
||||
if (s.theme == Themes.GRADIENT) GradientColorRows()
|
||||
if (s.theme == Themes.TRUE_BLACK) HighlightColorRow()
|
||||
ChoiceRow(
|
||||
host, "app-scale", stringResource(R.string.setup_app_scale), stringResource(R.string.setup_app_scale_hint),
|
||||
com.droiddeck.launcher.core.AppUiPrefs.scales.map { percent ->
|
||||
@@ -910,7 +911,15 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron
|
||||
val ready = current != null && !state.saving
|
||||
val launcher = game.library == com.droiddeck.launcher.frontend.Library.EPIC_LAUNCHER
|
||||
fun save(change: (android.content.Context) -> com.droiddeck.launcher.core.GameEnvironment.Config?) = state.save(change)
|
||||
var controlsProfile by remember(scope) { mutableStateOf(com.droiddeck.launcher.input.GameInputControls.profile(appContext, scope)) }
|
||||
val controlsKey = "game-settings-controls"
|
||||
val key = GAME_SETTINGS_MENU
|
||||
val controlsMenuOpen = host.open == key || host.open == controlsKey
|
||||
val inputLibrary by androidx.compose.runtime.produceState<com.droiddeck.launcher.input.InputLibrary?>(null, controlsMenuOpen) {
|
||||
value = if (controlsMenuOpen) kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
|
||||
com.droiddeck.launcher.input.InputLibraries.read(appContext)
|
||||
} else null
|
||||
}
|
||||
val fexKey = "game-settings-fex"
|
||||
val syncKey = "game-settings-sync"
|
||||
val syncLabels = mapOf(
|
||||
@@ -977,10 +986,13 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron
|
||||
trailing = { Text("›", fontSize = 16.sp, color = colors.onSurfaceVariant) },
|
||||
) { host.open = syncKey }
|
||||
}
|
||||
MenuItem(stringResource(R.string.community_game_controls), checked = false,
|
||||
detail = inputLibrary?.profiles?.firstOrNull { it.id == controlsProfile }?.name ?: useDefault) { host.open = controlsKey }
|
||||
MenuItem(stringResource(R.string.game_settings_default), checked = false, enabled = ready,
|
||||
detail = stringResource(R.string.game_settings_default_detail)) {
|
||||
save {
|
||||
val failure = runCatching { com.droiddeck.launcher.session.GameProfileManager.reset(it, scope) }.exceptionOrNull()
|
||||
if (failure == null) controlsProfile = null
|
||||
com.droiddeck.launcher.stores.StoresState.post {
|
||||
android.widget.Toast.makeText(
|
||||
it,
|
||||
@@ -992,6 +1004,20 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron
|
||||
}
|
||||
}
|
||||
}
|
||||
AnchoredMenu(host.open == controlsKey, onDismiss = { if (host.open == controlsKey) host.open = null },
|
||||
title = stringResource(R.string.community_game_controls)) { first ->
|
||||
MenuItem(useDefault, checked = controlsProfile == null, focusRequester = first) {
|
||||
runCatching { com.droiddeck.launcher.input.GameInputControls.set(appContext, scope, null) }
|
||||
.onSuccess { controlsProfile = null; host.open = key }
|
||||
.onFailure { android.widget.Toast.makeText(appContext, it.message, android.widget.Toast.LENGTH_SHORT).show() }
|
||||
}
|
||||
for (profile in inputLibrary?.profiles.orEmpty()) MenuItem(profile.name, checked = profile.id == controlsProfile,
|
||||
detail = stringResource(R.string.community_game_controls_hint)) {
|
||||
runCatching { com.droiddeck.launcher.input.GameInputControls.set(appContext, scope, profile.id) }
|
||||
.onSuccess { controlsProfile = profile.id; host.open = key }
|
||||
.onFailure { android.widget.Toast.makeText(appContext, it.message, android.widget.Toast.LENGTH_SHORT).show() }
|
||||
}
|
||||
}
|
||||
AnchoredMenu(host.open == resKey, onDismiss = { if (host.open == resKey) host.open = null }, title = stringResource(R.string.game_res_title)) { first ->
|
||||
MenuItem(matchScreen, checked = resolution == null, enabled = ready, focusRequester = first) { pickResolution(null) }
|
||||
com.droiddeck.launcher.core.GameResolution.scales.forEach { scale ->
|
||||
@@ -1177,6 +1203,16 @@ private fun RgbSpeedRow() {
|
||||
SliderRow(stringResource(R.string.theme_rgb_speed), stringResource(R.string.theme_rgb_speed_hint), Themes.rgbSpeed, 1..Themes.RGB_SPEEDS) { Themes.setRgbSpeed(ctx, it) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun HighlightColorRow() {
|
||||
val ctx = androidx.compose.ui.platform.LocalContext.current.applicationContext
|
||||
val highlight = Themes.trueBlackHighlight
|
||||
var picking by remember { mutableStateOf(false) }
|
||||
val label = stringResource(R.string.theme_true_black_highlight)
|
||||
SettingsRow(label, stringResource(R.string.theme_true_black_highlight_hint)) { ColorCube(androidx.compose.ui.graphics.Color(highlight), label) { picking = true } }
|
||||
if (picking) ColorPickerDialog(label, highlight, onDismiss = { picking = false }) { argb -> Themes.setTrueBlackHighlight(ctx, argb) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GradientColorRows() {
|
||||
val ctx = androidx.compose.ui.platform.LocalContext.current.applicationContext
|
||||
|
||||
@@ -1,17 +1,39 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.ScrollState
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.AlertDialogDefaults
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.LocalContentColor
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.ProvideTextStyle
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Shape
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.DpOffset
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
import androidx.compose.ui.unit.IntRect
|
||||
import androidx.compose.ui.unit.IntSize
|
||||
import androidx.compose.ui.unit.LayoutDirection
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.compose.ui.window.Popup
|
||||
@@ -41,13 +63,82 @@ internal fun TrackKeyWindow() {
|
||||
}
|
||||
}
|
||||
|
||||
internal val LocalPresentationWindow = staticCompositionLocalOf { false }
|
||||
|
||||
private val OriginPosition = object : PopupPositionProvider {
|
||||
override fun calculatePosition(anchorBounds: IntRect, windowSize: IntSize, layoutDirection: LayoutDirection, popupContentSize: IntSize) = IntOffset.Zero
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun WindowDialog(
|
||||
onDismissRequest: () -> Unit,
|
||||
properties: DialogProperties = DialogProperties(),
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
if (!LocalPresentationWindow.current) {
|
||||
Dialog(onDismissRequest, properties, content)
|
||||
return
|
||||
}
|
||||
Popup(
|
||||
OriginPosition, onDismissRequest,
|
||||
PopupProperties(focusable = true, dismissOnBackPress = properties.dismissOnBackPress, dismissOnClickOutside = false, clippingEnabled = false),
|
||||
) {
|
||||
Box(
|
||||
Modifier.fillMaxSize().background(androidx.compose.ui.graphics.Color.Black.copy(alpha = 0.6f))
|
||||
.tapOutside { if (properties.dismissOnClickOutside) onDismissRequest() },
|
||||
contentAlignment = Alignment.Center,
|
||||
) { content() }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun GlideDialog(
|
||||
onDismissRequest: () -> Unit,
|
||||
properties: DialogProperties = DialogProperties(),
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
Dialog(onDismissRequest, properties) { TrackKeyWindow(); FocusGlideHost(content = content) }
|
||||
WindowDialog(onDismissRequest, properties) { TrackKeyWindow(); FocusGlideHost(content = content) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PresentationAlert(
|
||||
confirmButton: @Composable () -> Unit,
|
||||
modifier: Modifier,
|
||||
dismissButton: (@Composable () -> Unit)?,
|
||||
icon: (@Composable () -> Unit)?,
|
||||
title: (@Composable () -> Unit)?,
|
||||
text: (@Composable () -> Unit)?,
|
||||
shape: Shape,
|
||||
containerColor: Color,
|
||||
iconContentColor: Color,
|
||||
titleContentColor: Color,
|
||||
textContentColor: Color,
|
||||
tonalElevation: Dp,
|
||||
) {
|
||||
Surface(modifier.blockTouches().padding(24.dp).widthIn(min = 280.dp, max = 560.dp), shape, containerColor, tonalElevation = tonalElevation) {
|
||||
Column(Modifier.padding(24.dp)) {
|
||||
icon?.let {
|
||||
Box(Modifier.align(Alignment.CenterHorizontally)) { CompositionLocalProvider(LocalContentColor provides iconContentColor, content = it) }
|
||||
Spacer(Modifier.height(16.dp))
|
||||
}
|
||||
title?.let {
|
||||
ProvideTextStyle(MaterialTheme.typography.headlineSmall) {
|
||||
CompositionLocalProvider(LocalContentColor provides titleContentColor, content = it)
|
||||
}
|
||||
Spacer(Modifier.height(16.dp))
|
||||
}
|
||||
text?.let {
|
||||
ProvideTextStyle(MaterialTheme.typography.bodyMedium) {
|
||||
CompositionLocalProvider(LocalContentColor provides textContentColor, content = it)
|
||||
}
|
||||
Spacer(Modifier.height(24.dp))
|
||||
}
|
||||
Row(Modifier.align(Alignment.End), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
dismissButton?.invoke()
|
||||
confirmButton()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -81,7 +172,13 @@ internal fun GlideAlertDialog(
|
||||
properties: DialogProperties = DialogProperties(),
|
||||
) {
|
||||
FocusGlideWindow { overlay ->
|
||||
AlertDialog(
|
||||
if (LocalPresentationWindow.current) WindowDialog(onDismissRequest, properties) {
|
||||
TrackKeyWindow()
|
||||
PresentationAlert(
|
||||
confirmButton, modifier.then(overlay), dismissButton, icon, title, text,
|
||||
shape, containerColor, iconContentColor, titleContentColor, textContentColor, tonalElevation,
|
||||
)
|
||||
} else AlertDialog(
|
||||
onDismissRequest, confirmButton, modifier.then(overlay), dismissButton, icon, title, text,
|
||||
shape, containerColor, iconContentColor, titleContentColor, textContentColor, tonalElevation, properties,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.input.*
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
@Composable
|
||||
internal fun InputCommunityPage(library: InputLibrary, profile: String, initialRole: InputRole, initialEntries: List<CommunityControls.Entry>? = null,
|
||||
onInstalled: (InputLibrary) -> Unit) {
|
||||
val context = LocalContext.current
|
||||
var targetProfile by remember { mutableStateOf(profile) }
|
||||
val scope = rememberCoroutineScope()
|
||||
val host = rememberMenuHost()
|
||||
var role by remember { mutableStateOf(initialRole.takeUnless { it == InputRole.PHYSICAL } ?: InputRole.PRIMARY) }
|
||||
var sources by remember { mutableStateOf(ControlSources.read(context)) }
|
||||
var selectedSource by remember { mutableStateOf(sources.first()) }
|
||||
var addingSource by remember { mutableStateOf(false) }
|
||||
var sourceUrl by remember { mutableStateOf("") }
|
||||
var entries by remember { mutableStateOf(initialEntries ?: CommunityControls.bundled(context)) }
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
var status by remember { mutableStateOf<String?>(null) }
|
||||
var pending by remember { mutableStateOf<CommunityControls.Pack?>(null) }
|
||||
var exporting by remember { mutableStateOf<ByteArray?>(null) }
|
||||
var search by remember { mutableStateOf("") }
|
||||
val filtered = remember(entries, search, role) { entries.filter { it.screen.supports(role) &&
|
||||
(search.isBlank() || "${it.name} ${it.author} ${it.game}".contains(search, ignoreCase = true)) } }
|
||||
var page by remember(selectedSource.id, entries, search, role) { mutableIntStateOf(0) }
|
||||
val pageCount = ((filtered.size + 11) / 12).coerceAtLeast(1)
|
||||
val pageEntries = filtered.drop(page * 12).take(12)
|
||||
val previews = remember(selectedSource.id, pageEntries) { mutableStateMapOf<String, android.graphics.Bitmap>() }
|
||||
LaunchedEffect(previews, pageEntries) {
|
||||
for (entry in pageEntries) {
|
||||
if (entry.preview == null || entry.key in previews) continue
|
||||
var decoded: android.graphics.Bitmap? = null
|
||||
try {
|
||||
withContext(Dispatchers.IO) { decoded = runCatching { CommunityControls.preview(context, entry) }.getOrNull() }
|
||||
decoded?.let { previews[entry.key] = it; decoded = null }
|
||||
} finally { decoded?.recycle() }
|
||||
}
|
||||
}
|
||||
fun task(action: suspend () -> Unit) {
|
||||
if (busy) return
|
||||
busy = true
|
||||
status = null
|
||||
scope.launch {
|
||||
try { action() } catch (e: kotlinx.coroutines.CancellationException) { throw e }
|
||||
catch (e: Exception) { status = e.message ?: context.getString(R.string.community_failed) }
|
||||
finally { busy = false }
|
||||
}
|
||||
}
|
||||
fun load(source: ControlSources.Source) {
|
||||
task {
|
||||
val remote = withContext(Dispatchers.IO) { CommunityControls.fetchCatalog(source) }
|
||||
val bundled = if (source.id == ControlSources.DROIDDECK.id) CommunityControls.bundled(context) else emptyList()
|
||||
entries = (remote + bundled).distinctBy { it.path }
|
||||
status = context.getString(R.string.community_refreshed)
|
||||
}
|
||||
}
|
||||
val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||
if (uri != null) task {
|
||||
pending = withContext(Dispatchers.IO) {
|
||||
val bytes = requireNotNull(context.contentResolver.openInputStream(uri)).use { CommunityControls.readLimited(it, 32 * 1024 * 1024) }
|
||||
CommunityControls.importFile(context, bytes, requireNotNull(library.layout(targetProfile, role)),
|
||||
library.preset(library.profile(targetProfile).binding(role)))
|
||||
}
|
||||
}
|
||||
}
|
||||
val exporter = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/zip")) { uri ->
|
||||
val bytes = exporting
|
||||
exporting = null
|
||||
if (uri != null && bytes != null) task {
|
||||
withContext(Dispatchers.IO) {
|
||||
requireNotNull(context.contentResolver.openOutputStream(uri, "wt")).use { it.write(bytes) }
|
||||
}
|
||||
status = context.getString(R.string.community_exported)
|
||||
}
|
||||
}
|
||||
InputHint(stringResource(R.string.community_description))
|
||||
SettingsGroup(stringResource(R.string.community_sources)) {
|
||||
ChoiceRow(host, "community-source", stringResource(R.string.community_source), null,
|
||||
sources.map { it.id to it.name }, selectedSource.id) { id ->
|
||||
if (!busy) {
|
||||
selectedSource = sources.first { it.id == id }
|
||||
entries = if (id == ControlSources.DROIDDECK.id) CommunityControls.bundled(context) else emptyList()
|
||||
load(selectedSource)
|
||||
}
|
||||
}
|
||||
PadTextButton(enabled = !busy, onClick = { sourceUrl = ""; addingSource = true }, modifier = Modifier.padding(8.dp).testTag("community-add-source")) {
|
||||
Text(stringResource(R.string.community_add_source))
|
||||
}
|
||||
if (!selectedSource.builtIn) PadTextButton(enabled = !busy, onClick = { task {
|
||||
ControlSources.remove(context, selectedSource)
|
||||
sources = ControlSources.read(context)
|
||||
selectedSource = sources.first()
|
||||
entries = CommunityControls.bundled(context)
|
||||
} }, modifier = Modifier.padding(8.dp)) { Text(stringResource(R.string.community_remove_source)) }
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.community_target)) {
|
||||
ChoiceRow(host, "community-profile", stringResource(R.string.input_profile), null,
|
||||
library.profiles.map { it.id to it.name }, targetProfile) { if (!busy) targetProfile = it }
|
||||
ChoiceRow(host, "community-screen", stringResource(R.string.community_screen), null,
|
||||
listOf(InputRole.PRIMARY, InputRole.SECONDARY).map { it to roleLabel(it) }, role) { if (!busy) role = it }
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.community_title)) {
|
||||
OutlinedTextField(search, { search = it.take(160) }, singleLine = true,
|
||||
label = { Text(stringResource(R.string.community_search)) }, modifier = Modifier.fillMaxWidth().padding(12.dp))
|
||||
for (entry in pageEntries) {
|
||||
InputNavigationRow(entry.name, listOf(entry.author, entry.game, entry.license).filter { it.isNotEmpty() }.joinToString(" · "),
|
||||
Modifier.testTag("community-pack-${entry.path}"), leading = {
|
||||
previews[entry.key]?.let { Image(it.asImageBitmap(), null, Modifier.width(112.dp).height(76.dp).testTag("community-preview-${entry.path}"), contentScale = ContentScale.Fit) }
|
||||
}) {
|
||||
task { pending = withContext(Dispatchers.IO) { CommunityControls.download(context, entry, library.layout(targetProfile, role),
|
||||
library.preset(library.profile(targetProfile).binding(role))) } }
|
||||
}
|
||||
}
|
||||
if (pageCount > 1) Row(Modifier.fillMaxWidth().padding(8.dp), horizontalArrangement = Arrangement.SpaceBetween) {
|
||||
PadTextButton(enabled = page > 0 && !busy, onClick = { page-- }, modifier = Modifier.testTag("community-previous")) { Text(stringResource(R.string.community_previous)) }
|
||||
Text(stringResource(R.string.community_page, page + 1, pageCount), Modifier.align(androidx.compose.ui.Alignment.CenterVertically))
|
||||
PadTextButton(enabled = page + 1 < pageCount && !busy, onClick = { page++ }, modifier = Modifier.testTag("community-next")) { Text(stringResource(R.string.community_next)) }
|
||||
}
|
||||
if (filtered.isEmpty())
|
||||
InputHint(stringResource(R.string.community_empty))
|
||||
PadTextButton(enabled = !busy, onClick = { load(selectedSource) }, modifier = Modifier.padding(8.dp)) { Text(stringResource(R.string.community_refresh)) }
|
||||
PadTextButton(enabled = !busy, onClick = { importer.launch(arrayOf("application/zip", "application/octet-stream", "application/x-zip-compressed")) },
|
||||
modifier = Modifier.padding(8.dp).testTag("community-import")) { Text(stringResource(R.string.community_import)) }
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.community_share)) {
|
||||
InputHint(stringResource(R.string.community_submit_hint))
|
||||
val layout = library.layout(targetProfile, role)
|
||||
if (layout?.editable == true) PadTextButton(enabled = !busy, onClick = { task {
|
||||
exporting = withContext(Dispatchers.IO) { CommunityControls.export(context, layout, library.preset(library.profile(targetProfile).binding(role))) }
|
||||
exporter.launch(layout.name.replace(Regex("[^A-Za-z0-9_-]"), "_").take(60) + ".ddcontrols.zip")
|
||||
} }, modifier = Modifier.padding(8.dp).testTag("community-export")) { Text(stringResource(R.string.community_export)) }
|
||||
if (layout?.editable == true && layout.elements.any { it.image.isNotEmpty() || it.stickImage.isNotEmpty() })
|
||||
PadTextButton(enabled = !busy, onClick = { task {
|
||||
exporting = withContext(Dispatchers.IO) { ArmsControlSkins.export(context, layout,
|
||||
library.preset(library.profile(targetProfile).binding(role))) }
|
||||
exporter.launch(layout.name.replace(Regex("[^A-Za-z0-9_-]"), "_").take(60) + ".skin.zip")
|
||||
} }, modifier = Modifier.padding(8.dp).testTag("community-export-skin")) { Text(stringResource(R.string.community_export_skin)) }
|
||||
PadTextButton(onClick = {
|
||||
runCatching { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(selectedSource.submit ?: selectedSource.manifest))) }
|
||||
.onFailure { status = context.getString(R.string.community_failed) }
|
||||
}, modifier = Modifier.padding(8.dp)) { Text(stringResource(R.string.community_submit)) }
|
||||
}
|
||||
if (busy) LinearProgressIndicator(Modifier.fillMaxWidth().padding(12.dp))
|
||||
status?.let { InputHint(it) }
|
||||
if (addingSource) AlertDialog(onDismissRequest = { if (!busy) addingSource = false },
|
||||
title = { Text(stringResource(R.string.community_add_source)) }, text = { Column {
|
||||
Text(stringResource(R.string.community_source_hint))
|
||||
OutlinedTextField(sourceUrl, { sourceUrl = it.take(2048) }, singleLine = true,
|
||||
label = { Text(stringResource(R.string.community_source_url)) }, modifier = Modifier.testTag("community-source-url"))
|
||||
status?.let { Text(it) }
|
||||
} }, confirmButton = {
|
||||
PadTextButton(enabled = !busy && sourceUrl.isNotBlank(), onClick = { task {
|
||||
val (source, remote) = withContext(Dispatchers.IO) {
|
||||
var failure: Exception? = null
|
||||
var found: Pair<ControlSources.Source, List<CommunityControls.Entry>>? = null
|
||||
for (candidate in ControlSources.candidates(sourceUrl)) {
|
||||
try { found = candidate to CommunityControls.fetchCatalog(candidate); break }
|
||||
catch (e: Exception) { failure = e }
|
||||
}
|
||||
found ?: throw (failure ?: IllegalArgumentException(context.getString(R.string.community_failed)))
|
||||
}
|
||||
ControlSources.add(context, source)
|
||||
sources = ControlSources.read(context)
|
||||
selectedSource = sources.first { it.id == source.id }
|
||||
entries = remote
|
||||
addingSource = false
|
||||
} }) { Text(stringResource(R.string.community_connect)) }
|
||||
}, dismissButton = { PadTextButton(enabled = !busy, onClick = { addingSource = false }) { Text(stringResource(R.string.common_cancel)) } })
|
||||
pending?.let { pack ->
|
||||
AlertDialog(onDismissRequest = { if (!busy) pending = null }, title = { Text(pack.layout.name) },
|
||||
text = { Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
InputLayoutThumbnail(pack.layout, role, pack.images, Modifier.fillMaxWidth().height(180.dp))
|
||||
Text(stringResource(R.string.community_apply_hint, pack.layout.elements.size, library.profile(targetProfile).name, roleLabel(role)))
|
||||
} }, confirmButton = {
|
||||
PadTextButton(enabled = !busy && pack.layout.supports(role), onClick = { task {
|
||||
val installed = withContext(Dispatchers.IO) { CommunityControls.install(context, pack, targetProfile, role) }
|
||||
onInstalled(installed)
|
||||
pending = null
|
||||
status = context.getString(R.string.community_installed)
|
||||
} }) { Text(stringResource(R.string.community_apply)) }
|
||||
}, dismissButton = { PadTextButton(enabled = !busy, onClick = { pending = null }) { Text(stringResource(R.string.common_cancel)) } })
|
||||
}
|
||||
}
|
||||
@@ -36,13 +36,17 @@ internal fun InputLayoutRow(layout: SavedInputLayout, role: InputRole, detail: S
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun InputLayoutThumbnail(layout: SavedInputLayout, role: InputRole) {
|
||||
AndroidView(factory = { InputLayoutPreviewView(it) }, modifier = Modifier.width(112.dp).height(76.dp).testTag("layout-preview-${layout.id}"),
|
||||
update = { it.update(layout, role) })
|
||||
internal fun InputLayoutThumbnail(layout: SavedInputLayout, role: InputRole, images: Map<String, ByteArray> = emptyMap(),
|
||||
modifier: Modifier = Modifier.width(112.dp).height(76.dp)) {
|
||||
val bitmaps = remember(images) { images.mapValues { (_, bytes) -> android.graphics.BitmapFactory.decodeByteArray(bytes, 0, bytes.size) } }
|
||||
key(bitmaps) {
|
||||
AndroidView(factory = { InputLayoutPreviewView(it, bitmaps.filterValues { it != null }.mapValues { it.value!! }) },
|
||||
modifier = modifier.testTag("layout-preview-${layout.id}"), update = { it.update(layout, role) })
|
||||
}
|
||||
}
|
||||
|
||||
internal class InputLayoutPreviewView(context: Context) : View(context) {
|
||||
private val renderer = InputSurfaceView(context)
|
||||
internal class InputLayoutPreviewView(context: Context, images: Map<String, android.graphics.Bitmap> = emptyMap()) : View(context) {
|
||||
private val renderer = InputSurfaceView(context, previewImages = images)
|
||||
private var sourceHeight = 563
|
||||
fun update(layout: SavedInputLayout, role: InputRole) {
|
||||
sourceHeight = if (role == InputRole.PRIMARY) 563 else 870
|
||||
|
||||
@@ -33,7 +33,10 @@ internal fun InputQuickSettings(host: MenuHost, desktop: Boolean, onChanged: (In
|
||||
runCatching { InputLibraries.update(context, change) }.onSuccess { library = it; onChanged(role) }
|
||||
.onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) }
|
||||
}
|
||||
val selection = library.selection(desktop)
|
||||
val game = (context.findActivity() as? com.droiddeck.launcher.SessionActivity)?.inputGameScope()
|
||||
fun effective(value: InputLibrary) = GameInputControls.resolve(context, value, desktop, game)
|
||||
val resolved = effective(library)
|
||||
val selection = resolved.selection(desktop)
|
||||
val mixed = selection.parts.isNotEmpty()
|
||||
val active = library.profile(library.activeId(desktop))
|
||||
val profiles = listOf(InputProfiles.AUTO to stringResource(R.string.input_quick_auto, if (desktop) library.profile(library.desktop).name else library.profile(library.steam).name)) +
|
||||
@@ -61,7 +64,7 @@ internal fun InputQuickSettings(host: MenuHost, desktop: Boolean, onChanged: (In
|
||||
if (role == InputRole.PHYSICAL) binding.physical
|
||||
else !binding.physical && library.layouts.any { it.id == binding.layoutId && it.supports(role) }
|
||||
}.map { it.id to it.name }
|
||||
ChoiceRow(host, "input-part-${role.name}", roleLabel(role), null, options, library.activePart(desktop, role).bindings,
|
||||
ChoiceRow(host, "input-part-${role.name}", roleLabel(role), null, options, resolved.activePart(desktop, role).bindings,
|
||||
chipModifier = track("input-part-${role.name}")) { id -> update(role) { it.selectPart(desktop, role, id) } }
|
||||
}
|
||||
if (mixed) SecondaryButton(stringResource(R.string.input_save_combination)) { naming = true }
|
||||
@@ -73,7 +76,7 @@ internal fun InputQuickSettings(host: MenuHost, desktop: Boolean, onChanged: (In
|
||||
var name by remember { mutableStateOf("") }
|
||||
AlertDialog(onDismissRequest = { naming = false }, title = { Text(stringResource(R.string.input_save_combination)) },
|
||||
text = { OutlinedTextField(name, { name = it.take(80) }, singleLine = true, label = { Text(stringResource(R.string.input_name)) }) },
|
||||
confirmButton = { PadTextButton(enabled = name.isNotBlank(), onClick = { update(null) { it.saveSelection(desktop, name) }; naming = false }) { Text(stringResource(R.string.gesture_save_changes)) } },
|
||||
confirmButton = { PadTextButton(enabled = name.isNotBlank(), onClick = { update(null) { effective(it).saveSelection(desktop, name) }; naming = false }) { Text(stringResource(R.string.gesture_save_changes)) } },
|
||||
dismissButton = { PadTextButton(onClick = { naming = false }) { Text(stringResource(R.string.common_cancel)) } })
|
||||
}
|
||||
failure?.let { message -> AlertDialog(onDismissRequest = { failure = null }, title = { Text(stringResource(R.string.input_save_failed)) },
|
||||
|
||||
@@ -65,7 +65,7 @@ private fun InputSettingsPane(onBack: () -> Unit, onChanged: () -> Unit) {
|
||||
}
|
||||
}
|
||||
|
||||
private enum class InputPage { HOME, PROFILE, SOURCE, LAYOUTS, REUSE }
|
||||
private enum class InputPage { HOME, PROFILE, SOURCE, LAYOUTS, REUSE, COMMUNITY }
|
||||
private data class InputBindingEdit(val preset: String, val control: InputControl, val element: InputSurfaceElement? = null, val key: PhysicalInputKey? = null, val click: Boolean = false)
|
||||
private data class InputNameRequest(val title: Int, val initial: String, val sources: List<Pair<String, String>> = emptyList(),
|
||||
val source: String = "", val offerSharing: Boolean = false, val save: (String, String, Boolean) -> Unit)
|
||||
@@ -85,6 +85,7 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
|
||||
val host = rememberMenuHost()
|
||||
var library by remember { mutableStateOf(InputLibraries.read(context)) }
|
||||
var page by remember { mutableStateOf(InputPage.HOME) }
|
||||
var communityBack by remember { mutableStateOf(InputPage.HOME) }
|
||||
var bindingsTab by remember { mutableIntStateOf(0) }
|
||||
var profileId by remember { mutableStateOf(InputProfile.GAME) }
|
||||
var role by remember { mutableStateOf(InputRole.PHYSICAL) }
|
||||
@@ -104,12 +105,13 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
|
||||
var oscMode by remember { mutableStateOf(SessionPrefs.oscMode(context)) }
|
||||
fun update(change: (InputLibrary) -> InputLibrary): Boolean = runCatching { InputLibraries.update(context, change) }
|
||||
.onSuccess { library = it; onChanged() }.onFailure { error = it.message ?: context.getString(R.string.input_save_failed) }.isSuccess
|
||||
fun go(next: InputPage) { page = next; host.open = null }
|
||||
fun go(next: InputPage) { if (next == InputPage.COMMUNITY) communityBack = page; page = next; host.open = null }
|
||||
fun back() {
|
||||
when {
|
||||
edit != null -> edit = null
|
||||
page == InputPage.HOME -> onBack()
|
||||
page == InputPage.PROFILE -> go(InputPage.HOME)
|
||||
page == InputPage.COMMUNITY -> go(communityBack)
|
||||
page == InputPage.SOURCE -> go(InputPage.PROFILE)
|
||||
else -> go(InputPage.SOURCE)
|
||||
}
|
||||
@@ -191,6 +193,7 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
|
||||
InputPage.SOURCE -> roleLabel(role)
|
||||
InputPage.LAYOUTS -> stringResource(R.string.input_saved_layouts)
|
||||
InputPage.REUSE -> stringResource(R.string.input_use_settings_from)
|
||||
InputPage.COMMUNITY -> stringResource(R.string.community_title)
|
||||
}, eyebrow = when (page) {
|
||||
InputPage.SOURCE -> profile.name
|
||||
InputPage.LAYOUTS, InputPage.REUSE -> "${profile.name} · ${roleLabel(role)}"
|
||||
@@ -198,7 +201,12 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
|
||||
},
|
||||
onBack = ::back, showBack = !(embedded && page == InputPage.HOME), compactLayout = true) {
|
||||
when (page) {
|
||||
InputPage.COMMUNITY -> InputCommunityPage(library, profileId, role) { installed -> library = installed; onChanged() }
|
||||
InputPage.HOME -> {
|
||||
SettingsGroup(stringResource(R.string.community_title)) {
|
||||
InputNavigationRow(stringResource(R.string.community_title), stringResource(R.string.community_home_hint),
|
||||
Modifier.testTag("input-community")) { go(InputPage.COMMUNITY) }
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.input_default_profiles)) {
|
||||
ChoiceRow(host, "auto-desktop", stringResource(R.string.input_desktop_mode), null,
|
||||
library.profiles.map { it.id to it.name }, library.desktop) { id -> update { it.copy(desktop = id) } }
|
||||
@@ -284,6 +292,7 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
|
||||
for (button in layout.quickButtons) ToggleRow(host, "quick-${button.name.lowercase()}", stringResource(quickButtonLabel(button)), null,
|
||||
button !in layout.style.hidden) { on -> update { it.withLayout(layout.withQuickButton(button, on)) } }
|
||||
}
|
||||
InputNavigationRow(stringResource(R.string.community_title), stringResource(R.string.community_home_hint)) { go(InputPage.COMMUNITY) }
|
||||
if (role == InputRole.SECONDARY) InputHint(stringResource(R.string.input_second_screen_enable))
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.input_assign_actions)) {
|
||||
@@ -449,7 +458,7 @@ private fun InputControlGrid(preset: SavedInputBindings, available: List<InputCo
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InputNavigationRow(title: String, detail: String?, modifier: Modifier = Modifier, leading: (@Composable () -> Unit)? = null, onClick: () -> Unit) {
|
||||
internal fun InputNavigationRow(title: String, detail: String?, modifier: Modifier = Modifier, leading: (@Composable () -> Unit)? = null, onClick: () -> Unit) {
|
||||
Row(modifier.fillMaxWidth().focusRow(RoundedCornerShape(0.dp), onClick = onClick).heightIn(min = 64.dp).padding(14.dp),
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
leading?.invoke()
|
||||
@@ -499,6 +508,6 @@ internal fun roleLabel(role: InputRole) = stringResource(when (role) {
|
||||
})
|
||||
|
||||
@Composable
|
||||
private fun InputHint(text: String) {
|
||||
internal fun InputHint(text: String) {
|
||||
Text(text, Modifier.padding(14.dp), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
@@ -51,6 +51,7 @@ class InputSurfaceView(
|
||||
private val inputRole: InputRole = InputRole.SECONDARY,
|
||||
private var surfaceStyle: InputSurfaceStyle = InputSurfaceStyle(),
|
||||
private val haptics: Boolean = inputRole != InputRole.PRIMARY,
|
||||
private val previewImages: Map<String, android.graphics.Bitmap> = emptyMap(),
|
||||
) : FrameLayout(context) {
|
||||
private val content = FrameLayout(context)
|
||||
private val elementSources = ArrayList<InputSurfaceSource>()
|
||||
@@ -326,13 +327,7 @@ class InputSurfaceView(
|
||||
protected fun textColor(lit: Boolean) = if (lit) Color.WHITE else tint?.let { light(it, 210, 0.75f) } ?: TEXT
|
||||
}
|
||||
|
||||
private inner class HoldButton(context: Context, private val element: InputSurfaceElement, private val source: InputSurfaceSource?) : Surface(context) {
|
||||
private var down = false
|
||||
private val pointers = HashSet<Int>()
|
||||
val round get() = element.buttonShape == InputButtonShape.CIRCLE
|
||||
val gamepad get() = round || element.buttonShape == InputButtonShape.PILL
|
||||
private val symbol = InputButtonIcons.drawable(context, element.icon)
|
||||
private val bitmap = InputButtonImages.file(context, element.image)?.let { file ->
|
||||
private fun imageBitmap(name: String): android.graphics.Bitmap? = previewImages[name] ?: InputButtonImages.file(context, name)?.let { file ->
|
||||
val size = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeFile(file.path, size)
|
||||
val options = BitmapFactory.Options().apply {
|
||||
@@ -341,6 +336,14 @@ class InputSurfaceView(
|
||||
}
|
||||
if (file.isFile) BitmapFactory.decodeFile(file.path, options) else null
|
||||
}
|
||||
|
||||
private inner class HoldButton(context: Context, private val element: InputSurfaceElement, private val source: InputSurfaceSource?) : Surface(context) {
|
||||
private var down = false
|
||||
private val pointers = HashSet<Int>()
|
||||
val round get() = element.buttonShape == InputButtonShape.CIRCLE
|
||||
val gamepad get() = round || element.buttonShape == InputButtonShape.PILL
|
||||
private val symbol = InputButtonIcons.drawable(context, element.icon)
|
||||
private val bitmap = imageBitmap(element.image)
|
||||
private val imageRect = RectF()
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
@@ -511,6 +514,17 @@ class InputSurfaceView(
|
||||
private var knobY = 0f
|
||||
private val ring = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
|
||||
private val knob = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
private val baseImage = imageBitmap(element.image)
|
||||
private val stickImage = imageBitmap(element.stickImage)
|
||||
private val imagePaint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
|
||||
private val imageBounds = RectF()
|
||||
|
||||
private fun drawImage(canvas: Canvas, image: android.graphics.Bitmap, x: Float, y: Float, radius: Float) {
|
||||
val scale = min(radius * 2 / image.width, radius * 2 / image.height)
|
||||
imageBounds.set(x - image.width * scale / 2, y - image.height * scale / 2,
|
||||
x + image.width * scale / 2, y + image.height * scale / 2)
|
||||
canvas.drawBitmap(image, null, imageBounds, imagePaint)
|
||||
}
|
||||
|
||||
val adaptive get() = adaptive(element)
|
||||
|
||||
@@ -534,6 +548,14 @@ class InputSurfaceView(
|
||||
val cx = if (touching) originX else centreX()
|
||||
val cy = if (touching) originY else height / 2f
|
||||
val color = tint
|
||||
if (baseImage != null || stickImage != null) {
|
||||
val radius = min(width, height) / 2f - .75f * density
|
||||
if (baseImage != null) drawImage(canvas, baseImage, cx, cy, radius)
|
||||
else { ring.color = LINE; ring.strokeWidth = 2 * density; canvas.drawCircle(cx, cy, radius, ring) }
|
||||
if (stickImage != null) drawImage(canvas, stickImage, cx + knobX, cy + knobY, radius * .46f)
|
||||
else { knob.color = if (touching) ACCENT else KNOB; canvas.drawCircle(cx + knobX, cy + knobY, radius * .46f, knob) }
|
||||
return
|
||||
}
|
||||
if (classic(element) && color != null) {
|
||||
val radius = min(width, height) / 2f - 0.75f * density
|
||||
drawCircle(canvas, cx, cy, radius,
|
||||
|
||||
@@ -63,6 +63,7 @@ class ModeSettings(
|
||||
val upscaler: Int = 0,
|
||||
val upscaleSharpness: Int = 75,
|
||||
val touchMode: String,
|
||||
val pen: SessionPrefs.Pen? = null,
|
||||
val suspendPolicy: String,
|
||||
val steamDownloadsInBackground: Boolean = false,
|
||||
val pipSupported: Boolean = false,
|
||||
@@ -116,6 +117,7 @@ class ModeSettingsActions(
|
||||
val onUpscaler: (Int) -> Unit = {},
|
||||
val onUpscaleSharpness: (Int) -> Unit = {},
|
||||
val onTouch: (String) -> Unit,
|
||||
val onPen: (key: String, value: String) -> Unit = { _, _ -> },
|
||||
val onSuspendPolicy: (String) -> Unit,
|
||||
val onSteamDownloadsInBackground: (Boolean) -> Unit = {},
|
||||
val onPipAutoEnter: (Boolean) -> Unit = {},
|
||||
@@ -321,6 +323,7 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
}
|
||||
PhysicalShortcutRows()
|
||||
}
|
||||
s.pen?.let { PenSettingsGroup(host, it, onPick = a.onPen) }
|
||||
}
|
||||
if (tab == SheetTab.AUDIO && steam) {
|
||||
if (s.directAudio != null && s.mic != null) SettingsGroup(stringResource(R.string.mode_audio)) {
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
|
||||
@Composable
|
||||
internal fun PenSettingsGroup(
|
||||
host: MenuHost, pen: SessionPrefs.Pen, track: (String) -> Modifier = { Modifier },
|
||||
onPick: (key: String, value: String) -> Unit,
|
||||
) {
|
||||
SettingsGroup(stringResource(R.string.mode_pen)) {
|
||||
ChoiceRow(host, "pen", stringResource(R.string.mode_pen), null,
|
||||
listOf(SessionPrefs.PEN_MOUSE to stringResource(R.string.mode_pen_mouse),
|
||||
SessionPrefs.PEN_TOUCH to stringResource(R.string.mode_pen_touch)),
|
||||
pen.mode, chipModifier = track("pen")) { onPick("pen", it) }
|
||||
if (pen.mode != SessionPrefs.PEN_TOUCH) ChoiceRow(host, "pen-button", stringResource(R.string.mode_pen_button), null,
|
||||
listOf(SessionPrefs.PEN_BUTTON_RIGHT to stringResource(R.string.gesture_right_click),
|
||||
SessionPrefs.PEN_BUTTON_MIDDLE to stringResource(R.string.gesture_middle_click),
|
||||
SessionPrefs.PEN_BUTTON_OFF to stringResource(R.string.widgets_off)),
|
||||
pen.button, chipModifier = track("pen-button")) { onPick("penButton", it) }
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,7 @@ fun PerformancePage(
|
||||
gpuClockPin: Boolean,
|
||||
ramCapMb: Int,
|
||||
zramClient: Boolean,
|
||||
zramIdle: Boolean,
|
||||
vramCapMb: Int,
|
||||
deviceRamMb: Int,
|
||||
ramCapAvailable: Boolean,
|
||||
@@ -72,6 +73,7 @@ fun PerformancePage(
|
||||
onGpuClockPin: (Boolean) -> Unit,
|
||||
onRamCapMb: (Int) -> Unit,
|
||||
onZramClient: (Boolean) -> Unit,
|
||||
onZramIdle: (Boolean) -> Unit,
|
||||
onVramCapMb: (Int) -> Unit,
|
||||
onProotNoSeccomp: (Boolean) -> Unit,
|
||||
onProotFastPath: (Boolean) -> Unit,
|
||||
@@ -146,6 +148,11 @@ fun PerformancePage(
|
||||
val top = (deviceRamMb / MEMORY_CAP_STEP_MB * MEMORY_CAP_STEP_MB).coerceAtLeast(MEMORY_CAP_STEP_MB)
|
||||
val off = stringResource(R.string.perf_cap_off)
|
||||
val auto = stringResource(R.string.perf_cap_auto)
|
||||
ToggleRow(
|
||||
host, "zramidle", stringResource(R.string.perf_zram_idle),
|
||||
if (ramCapAvailable) stringResource(R.string.perf_zram_idle_hint) else stringResource(R.string.perf_ram_cap_unavailable),
|
||||
zramIdle && ramCapAvailable, enabled = ramCapAvailable, onChange = onZramIdle,
|
||||
)
|
||||
ToggleRow(
|
||||
host, "zramclient", stringResource(R.string.perf_zram_client),
|
||||
if (ramCapAvailable) stringResource(R.string.perf_zram_client_hint) else stringResource(R.string.perf_ram_cap_unavailable),
|
||||
|
||||
@@ -143,7 +143,7 @@ class SecondScreenPresentation(
|
||||
val view = androidx.compose.ui.platform.ComposeView(context).apply {
|
||||
isFocusable = true
|
||||
isFocusableInTouchMode = true
|
||||
setContent { content() }
|
||||
setContent { PresentationWindows(content) }
|
||||
}
|
||||
chatView = view
|
||||
root.addView(view, 1.coerceAtMost(root.childCount), LinearLayout.LayoutParams(-1, -2))
|
||||
@@ -179,7 +179,7 @@ class SecondScreenPresentation(
|
||||
isFocusable = true
|
||||
isFocusableInTouchMode = true
|
||||
defaultFocusHighlightEnabled = false
|
||||
setContent { content() }
|
||||
setContent { PresentationWindows(content) }
|
||||
frame.addView(this, FrameLayout.LayoutParams(-1, -1))
|
||||
menuView = this
|
||||
}
|
||||
@@ -306,8 +306,12 @@ class SecondScreenPresentation(
|
||||
}
|
||||
}
|
||||
|
||||
private fun panelLayout(mode: SecondScreenMode) = com.droiddeck.launcher.input.InputLibraries.read(context)
|
||||
.panelLayout(SessionState.mode == SessionService.MODE_DESKTOP, mode.panel(context))
|
||||
private fun panelLayout(mode: SecondScreenMode): com.droiddeck.launcher.input.SavedInputLayout? {
|
||||
val desktop = SessionState.mode == SessionService.MODE_DESKTOP
|
||||
return com.droiddeck.launcher.input.GameInputControls.resolve(context,
|
||||
com.droiddeck.launcher.input.InputLibraries.read(context), desktop, sessionActivity.inputGameScope())
|
||||
.panelLayout(desktop, mode.panel(context))
|
||||
}
|
||||
|
||||
private fun bar(mode: SecondScreenMode) {
|
||||
val first = barModel(mode) ?: return
|
||||
@@ -340,7 +344,7 @@ class SecondScreenPresentation(
|
||||
private fun renderDashboard() {
|
||||
val content = dashboard ?: return
|
||||
bar(SecondScreenMode.DASHBOARD)
|
||||
val view = androidx.compose.ui.platform.ComposeView(context).apply { setContent { content() } }
|
||||
val view = androidx.compose.ui.platform.ComposeView(context).apply { setContent { PresentationWindows(content) } }
|
||||
dashboardView = view
|
||||
root.addView(view, weightParams())
|
||||
}
|
||||
@@ -364,7 +368,7 @@ class SecondScreenPresentation(
|
||||
|
||||
private fun renderTerminal() {
|
||||
bar(SecondScreenMode.TERMINAL)
|
||||
val panel = SessionTerminalPanel(context)
|
||||
val panel = SessionTerminalPanel(context, keepShell = true)
|
||||
terminalPanel = panel
|
||||
root.addView(panel, weightParams())
|
||||
}
|
||||
@@ -388,3 +392,8 @@ class SecondScreenPresentation(
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
|
||||
}
|
||||
}
|
||||
|
||||
@androidx.compose.runtime.Composable
|
||||
private fun PresentationWindows(content: @androidx.compose.runtime.Composable () -> Unit) {
|
||||
androidx.compose.runtime.CompositionLocalProvider(LocalPresentationWindow provides true) { content() }
|
||||
}
|
||||
@@ -239,10 +239,15 @@ class DrawerActions(
|
||||
val onPadType: (String) -> Unit = {},
|
||||
val touchMode: String,
|
||||
val touchAuto: String,
|
||||
val pen: SessionPrefs.Pen? = null,
|
||||
val onPen: (key: String, value: String) -> Unit = { _, _ -> },
|
||||
val fexPreset: String,
|
||||
val upscaler: Int = 0,
|
||||
val upscaleSharpness: Int = 75,
|
||||
val effects: ScreenEffects = ScreenEffects.OFF,
|
||||
val screenEffectsTarget: String = "auto",
|
||||
val screenEffectsTargets: List<Pair<String, String>> = emptyList(),
|
||||
val screenEffectsCanDelete: Boolean = false,
|
||||
val cardboard: Cardboard = Cardboard.OFF,
|
||||
val cardboardSensor: Boolean = false,
|
||||
val steamVr: SteamVr.Status? = null,
|
||||
@@ -304,8 +309,13 @@ class DrawerActions(
|
||||
val onDirectHoldBehavior: (String) -> Unit = {},
|
||||
val onFexPreset: (String) -> Unit,
|
||||
val onUpscaler: (Int) -> Unit = {},
|
||||
val onPresetUpscaler: (Int) -> Unit = onUpscaler,
|
||||
val onUpscaleSharpness: (Int) -> Unit = {},
|
||||
val onEffects: (ScreenEffects) -> Unit = {},
|
||||
val onScreenEffectsTarget: (String) -> Unit = {},
|
||||
val onScreenEffectsReset: () -> Unit = {},
|
||||
val onScreenEffectsDelete: () -> Unit = {},
|
||||
val onScreenEffectsProfilesRefresh: () -> Unit = {},
|
||||
val onCardboard: (Cardboard) -> Unit = {},
|
||||
val onCardboardRecenter: () -> Unit = {},
|
||||
val onGlassesRecenter: () -> Unit = {},
|
||||
@@ -422,6 +432,9 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
}
|
||||
}
|
||||
}
|
||||
LaunchedEffect(open, page) {
|
||||
if (open && page == SessionDrawerPage.EFFECTS) a.onScreenEffectsProfilesRefresh()
|
||||
}
|
||||
LaunchedEffect(open, controllerActive) {
|
||||
if (open && !controllerActive) focusManager.clearFocus(force = true)
|
||||
}
|
||||
@@ -661,6 +674,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
onPick = a.onDirectHoldBehavior)
|
||||
}
|
||||
}
|
||||
a.pen?.let { PenSettingsGroup(host, it, track = { key -> focus.track(page, key) }, onPick = a.onPen) }
|
||||
SettingsGroup(stringResource(R.string.input_screen_visibility)) {
|
||||
ChoiceRow(host, "osc", stringResource(R.string.mode_osc), null,
|
||||
if (a.steam) listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never))
|
||||
@@ -1064,12 +1078,32 @@ private fun ScreenEffectsGroup(
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
SettingsGroup(stringResource(R.string.drawer_effects)) {
|
||||
ChoiceRow(
|
||||
host, "effects-profile", stringResource(R.string.screen_effects_target),
|
||||
stringResource(R.string.screen_effects_target_hint), a.screenEffectsTargets,
|
||||
a.screenEffectsTarget, chipModifier = track("effects-profile"),
|
||||
onPick = a.onScreenEffectsTarget,
|
||||
)
|
||||
ActionRow(
|
||||
stringResource(R.string.screen_effects_reset),
|
||||
stringResource(R.string.screen_effects_reset_hint),
|
||||
stringResource(R.string.hud_reset_button),
|
||||
a.onScreenEffectsReset,
|
||||
modifier = track("effects-reset"),
|
||||
)
|
||||
if (a.screenEffectsCanDelete) ActionRow(
|
||||
stringResource(R.string.screen_effects_delete),
|
||||
stringResource(R.string.screen_effects_delete_hint),
|
||||
stringResource(R.string.common_delete),
|
||||
a.onScreenEffectsDelete,
|
||||
modifier = track("effects-delete"),
|
||||
)
|
||||
val presets = ScreenEffectLooks.LOOKS.map { it.name to stringResource(it.label) }
|
||||
ChoiceRow(host, "look", stringResource(R.string.drawer_look), null,
|
||||
if (preset == null) listOf(LOOK_CUSTOM to stringResource(R.string.drawer_look_custom)) + presets else presets,
|
||||
preset?.name ?: LOOK_CUSTOM, chipModifier = track("look")) { name ->
|
||||
ScreenEffectLooks.LOOKS.firstOrNull { it.name == name }?.let { picked ->
|
||||
picked.scalingMode?.let(a.onUpscaler)
|
||||
picked.scalingMode?.let(a.onPresetUpscaler)
|
||||
a.onEffects(picked.effects)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ import com.termux.terminal.TerminalSessionClient
|
||||
import com.termux.view.TerminalView
|
||||
import com.termux.view.TerminalViewClient
|
||||
|
||||
class SessionTerminalPanel(context: Context) : LinearLayout(context) {
|
||||
class SessionTerminalPanel(context: Context, private val keepShell: Boolean = false) : LinearLayout(context) {
|
||||
private var terminalSession: TerminalSession? = null
|
||||
private var terminalView: TerminalView? = null
|
||||
private var terminalPid = -1
|
||||
@@ -45,7 +45,8 @@ class SessionTerminalPanel(context: Context) : LinearLayout(context) {
|
||||
isFocusableInTouchMode = true
|
||||
}
|
||||
terminalView = view
|
||||
val session = SessionTerminal.create(terminalClient)
|
||||
val session = (if (keepShell) SessionTerminal.reuse(terminalClient) else null)
|
||||
?: SessionTerminal.create(terminalClient)?.also { if (keepShell) SessionTerminal.keep(it) }
|
||||
if (session == null) {
|
||||
addView(TextView(context).apply {
|
||||
text = context.getString(R.string.second_terminal_not_ready)
|
||||
@@ -82,6 +83,7 @@ class SessionTerminalPanel(context: Context) : LinearLayout(context) {
|
||||
key("→", "\u001b[C")
|
||||
key(context.getString(R.string.second_key_ctrl_c), "\u0003")
|
||||
key(context.getString(R.string.second_key_ctrl_d), "\u0004")
|
||||
key(context.getString(R.string.second_key_clear), "\u000c")
|
||||
keyStrip.addView(keys)
|
||||
addView(keyStrip, LayoutParams(-1, -2))
|
||||
|
||||
@@ -121,8 +123,12 @@ class SessionTerminalPanel(context: Context) : LinearLayout(context) {
|
||||
(context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
|
||||
.hideSoftInputFromWindow(view.windowToken, 0)
|
||||
}
|
||||
val pid = terminalPid.takeIf { it > 1 } ?: (terminalSession?.pid ?: -1)
|
||||
if (pid > 1) SessionService.stopTerminalProcess(context, pid)
|
||||
val session = terminalSession
|
||||
if (!keepShell || session?.isRunning != true) {
|
||||
val pid = terminalPid.takeIf { it > 1 } ?: (session?.pid ?: -1)
|
||||
if (pid > 1) SessionService.stopTerminalProcess(context, pid)
|
||||
SessionTerminal.release(session)
|
||||
}
|
||||
terminalPid = -1
|
||||
terminalSession = null
|
||||
terminalView = null
|
||||
@@ -140,6 +146,7 @@ class SessionTerminalPanel(context: Context) : LinearLayout(context) {
|
||||
override fun onSessionFinished(finishedSession: TerminalSession) {
|
||||
val pid = terminalPid.takeIf { it > 1 } ?: finishedSession.pid
|
||||
if (pid > 1) SessionService.terminalProcessExited(context, pid)
|
||||
SessionTerminal.release(finishedSession)
|
||||
terminalPid = -1
|
||||
terminalView?.onScreenUpdated()
|
||||
}
|
||||
|
||||
@@ -59,6 +59,11 @@ object Themes {
|
||||
const val DEFAULT_RGB_SPEED = 3
|
||||
const val RGB_HUE_STEP = 3f
|
||||
const val WHITE_RED = "white_red"
|
||||
const val TRUE_BLACK = "true_black"
|
||||
const val DEFAULT_HIGHLIGHT = 0xFF1A9FFF.toInt()
|
||||
|
||||
var trueBlackHighlight by mutableStateOf(DEFAULT_HIGHLIGHT)
|
||||
private set
|
||||
|
||||
var rgbSpeed by mutableStateOf(DEFAULT_RGB_SPEED)
|
||||
private set
|
||||
@@ -81,6 +86,12 @@ object Themes {
|
||||
fun loadGradient(context: Context) {
|
||||
gradientColors = SessionPrefs.gradientColors(context)
|
||||
rgbSpeed = SessionPrefs.rgbSpeed(context)
|
||||
trueBlackHighlight = SessionPrefs.trueBlackHighlight(context)
|
||||
}
|
||||
|
||||
fun setTrueBlackHighlight(context: Context, highlight: Int) {
|
||||
SessionPrefs.setTrueBlackHighlight(context, highlight)
|
||||
trueBlackHighlight = highlight
|
||||
}
|
||||
|
||||
fun innerGamer(hue: Float): Palette = ThemeColors.palette(
|
||||
@@ -95,7 +106,7 @@ object Themes {
|
||||
|
||||
fun current(context: Context): Palette {
|
||||
val id = SessionPrefs.theme(context)
|
||||
if (id == GRADIENT || id == INNER_GAMER) loadGradient(context)
|
||||
if (id == GRADIENT || id == INNER_GAMER || id == TRUE_BLACK) loadGradient(context)
|
||||
return byId(id)
|
||||
}
|
||||
|
||||
@@ -128,6 +139,7 @@ object Themes {
|
||||
primary = Color(0xFF2E86FF), primary2 = Color(0xFF2684FF), onPrimary = Color(0xFF03111F), signal = Color(0xFF2E86FF),
|
||||
good = Color(0xFF4CD37F),
|
||||
),
|
||||
ThemeColors.trueBlack(DEFAULT_HIGHLIGHT),
|
||||
Palette(
|
||||
WHITE_RED, R.string.theme_white_red, R.string.theme_white_red_detail,
|
||||
background = Color(0xFFF8F8F8), surface = Color(0xFFFFFFFF), surfaceVariant = Color(0xFFF0F0F0), line = Color(0xFFDDDDDD), line2 = Color(0xFFC8C8C8),
|
||||
@@ -141,6 +153,7 @@ object Themes {
|
||||
|
||||
fun byId(id: String): Palette {
|
||||
if (id == INNER_GAMER) return innerGamer(rgbHue)
|
||||
if (id == TRUE_BLACK) return ThemeColors.trueBlack(trueBlackHighlight)
|
||||
if (id == GRADIENT) return ThemeColors.palette(gradientColors.first, gradientColors.second, R.string.theme_gradient, R.string.theme_gradient_detail)
|
||||
return all.firstOrNull { it.id == id } ?: all[0]
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.ui
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.luminance
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
import com.droiddeck.launcher.R
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.roundToInt
|
||||
@@ -147,4 +148,18 @@ internal object ThemeColors {
|
||||
good = Color(0xFF4CD37F),
|
||||
)
|
||||
}
|
||||
|
||||
// Page and panels are pure black so an OLED panel leaves those pixels off; only raised cards, rules and the highlight are lit.
|
||||
fun trueBlack(highlight: Int): Palette {
|
||||
val seen = readable(highlight)
|
||||
val ink = inkFor(seen, seen)
|
||||
val accent = Color(fitTo(ink, seen))
|
||||
return Palette(
|
||||
Themes.TRUE_BLACK, R.string.theme_true_black, R.string.theme_true_black_detail,
|
||||
background = Color.Black, surface = Color.Black, surfaceVariant = Color(0xFF0C0C0D), line = Color(0xFF1C1D20), line2 = Color(0xFF2A2C30),
|
||||
onBackground = Color(0xFFF2F4F7), onSurfaceVariant = Color(0xFF8E9196),
|
||||
primary = accent, primary2 = accent, onPrimary = ink, signal = accent,
|
||||
good = Color(0xFF4CD37F),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -90,10 +90,11 @@ object SelfInstaller {
|
||||
}
|
||||
}
|
||||
|
||||
fun install(context: Context, apk: File, onSession: (Int) -> Unit = {}) {
|
||||
fun install(context: Context, apk: File, packageName: String = context.packageName, action: String = ACTION_STATUS,
|
||||
onSession: (Int) -> Unit = {}) {
|
||||
val installer = context.packageManager.packageInstaller
|
||||
val params = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL).apply {
|
||||
setAppPackageName(context.packageName)
|
||||
setAppPackageName(packageName)
|
||||
setSize(apk.length())
|
||||
if (Build.VERSION.SDK_INT >= 31) setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_NOT_REQUIRED)
|
||||
}
|
||||
@@ -105,7 +106,7 @@ object SelfInstaller {
|
||||
session.fsync(out)
|
||||
}
|
||||
}
|
||||
val status = Intent(ACTION_STATUS).setPackage(context.packageName)
|
||||
val status = Intent(action).setPackage(context.packageName)
|
||||
val flags = PendingIntent.FLAG_UPDATE_CURRENT or (if (Build.VERSION.SDK_INT >= 31) PendingIntent.FLAG_MUTABLE else 0)
|
||||
onSession(id)
|
||||
session.commit(PendingIntent.getBroadcast(context, id, status, flags).intentSender)
|
||||
|
||||
Loaded 100 of 248 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user