Merge remote-tracking branch 'origin/main' into feat/steam-touch-controller

This commit is contained in:
maxjivi05 committed 2026-10-08 14:57:02 -04:00
commit 1b31899896
92 files changed
+6434 -2865

No files matched your search

-2
View File
@@ -6,7 +6,6 @@ on:
push:
paths:
- 'tools/aaudio-sink/**'
- 'tools/directaudio-relay/**'
- '.github/workflows/build-aaudio-sink.yml'
workflow_dispatch:
@@ -26,7 +25,6 @@ jobs:
set -euo pipefail
export NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"
tools/aaudio-sink/build.sh "$PWD/pa13" "$PWD/out"
tools/directaudio-relay/build.sh "$PWD/out"
- uses: actions/upload-artifact@v4
with:
name: audio-sink-modules
+6 -7
View File
@@ -331,6 +331,11 @@ jobs:
set -euo pipefail
curl -fsSL -o pa.tar.gz https://github.com/pulseaudio/pulseaudio/archive/refs/tags/v13.0.tar.gz
mkdir -p pa13 && tar -xzf pa.tar.gz -C pa13 --strip-components=1 && rm pa.tar.gz
# DirectAudio - the game driver (one set per Wine audio interface), the Android-side helper and
# the Steam client's sinks - comes from a pinned release of The412Banner/directaudio, checksummed,
# exactly like gamescope; nothing compiled for audio is kept in this repo.
- name: Fetch DirectAudio (tools/directaudio/release.env)
run: tools/directaudio/fetch.sh "$PWD" "$PWD/sink-out"
- name: Build the AAudio sink into the audio bundle
run: |
set -euo pipefail
@@ -340,17 +345,11 @@ jobs:
tar --use-compress-program=unzstd -xf app/src/main/assets/pulseaudio.tzst -C pa-bundle
test ! -f pa-bundle/modules/arm64/module-aaudio-sink.so
install -m755 sink-out/module-aaudio-sink.so pa-bundle/modules/arm64/module-aaudio-sink.so
install -m755 sink-out/module-directaudio-sink.so pa-bundle/modules/arm64/module-directaudio-sink.so
install -m755 sink-out/module-directaudio-native-sink.so pa-bundle/modules/arm64/module-directaudio-native-sink.so
(cd pa-bundle && tar --use-compress-program='zstd -19' -cf ../pulseaudio.tzst .)
mv pulseaudio.tzst app/src/main/assets/pulseaudio.tzst
tar --use-compress-program=unzstd -tf app/src/main/assets/pulseaudio.tzst | grep -c '\.so$'
rm -rf pa-bundle sink-out
- name: Build the DirectAudio relay
run: |
set -euo pipefail
export NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"
tools/directaudio-relay/build.sh app/src/main/jniLibs/arm64-v8a
- name: Cache proot
id: proot
uses: actions/cache@v4
+29
View File
@@ -13,13 +13,28 @@ permissions:
contents: read
pull-requests: read
concurrency:
group: pr-release-${{ github.event.pull_request.number }}
cancel-in-progress: false
queue: max
jobs:
cleanup:
runs-on: ubuntu-24.04
timeout-minutes: 5
steps:
- name: Check the current PR state
id: state
env:
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ github.event.pull_request.number }}
run: |
set -euo pipefail
state=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER" --jq .state)
echo "closed=$([ "$state" = closed ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
# A token of the org's "DroidDeck CI Publisher" app, as build.yml's announce job uses.
- uses: actions/create-github-app-token@v2
if: ${{ steps.state.outputs.closed == 'true' }}
id: ci-token
with:
app-id: ${{ vars.DROIDDECK_CI_APP_ID }}
@@ -27,6 +42,7 @@ jobs:
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 }}
@@ -42,6 +58,19 @@ jobs:
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: Retire the Discord PR announcement
if: ${{ steps.state.outputs.closed == 'true' }}
env:
WEBHOOK: ${{ secrets.DISCORD_PR_BUILDS_WEBHOOK }}
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ github.event.pull_request.number }}
run: python3 tools/release/pr_discord.py retire
catalog:
needs: cleanup
if: ${{ always() }}
+14 -21
View File
@@ -26,6 +26,7 @@ permissions:
concurrency:
group: pr-release-${{ github.event_name == 'pull_request_target' && github.event.pull_request.number || github.event_name == 'workflow_run' && github.event.workflow_run.pull_requests[0].number || inputs.pr_number }}
cancel-in-progress: false
queue: max
jobs:
authorize:
@@ -178,6 +179,10 @@ jobs:
issues: write
pull-requests: write
steps:
- uses: actions/checkout@v4
with:
ref: main
persist-credentials: false
- uses: actions/download-artifact@v4
with:
pattern: droiddeck-pr-signed-*
@@ -307,39 +312,27 @@ jobs:
$NEXT
EOF
)
id=$(gh api "repos/$GITHUB_REPOSITORY/issues/$PR_NUMBER/comments" --paginate \
--jq ".[] | select(.body | startswith(\"$mark\")) | .id" | head -1 || true)
comment=$(gh api "repos/$GITHUB_REPOSITORY/issues/$PR_NUMBER/comments" --paginate --slurp | \
jq "[.[][] | select(.user.login == \"github-actions[bot]\") | select(.body | startswith(\"$mark\"))] | first // {}")
id=$(jq -r '.id // empty' <<<"$comment")
if [ -n "$id" ]; then
state=$(jq -r '.body | split("\n")[] | select(startswith("<!-- droiddeck-discord: ") and endswith(" -->"))' <<<"$comment")
if [ -n "$state" ]; then body=$(printf '%s\n%s' "$body" "$state"); fi
gh api -X PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$id" -f body="$body" >/dev/null
else
gh api -X POST "repos/$GITHUB_REPOSITORY/issues/$PR_NUMBER/comments" -f body="$body" >/dev/null
fi
# Asked for (the label, a manual run): always announced. Signed on its own after a push:
# only a PR's first test build is, and later ones update its release quietly.
- name: Post to Discord
if: ${{ always() && steps.publish.outcome == 'success' && (needs.authorize.outputs.automatic != 'true' || steps.publish.outputs.first == 'true') }}
- name: Update the Discord PR announcement
if: ${{ always() && steps.publish.outcome == 'success' }}
env:
WEBHOOK: ${{ secrets.DISCORD_BUILDS_WEBHOOK }}
WEBHOOK: ${{ secrets.DISCORD_PR_BUILDS_WEBHOOK }}
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ needs.authorize.outputs.pr_number }}
HEAD_SHA: ${{ needs.authorize.outputs.head_sha }}
RELEASE: ${{ steps.publish.outputs.release }}
APK: ${{ steps.publish.outputs.apk }}
run: |
set -euo pipefail
if [ -z "$WEBHOOK" ]; then
echo "::notice::No DISCORD_BUILDS_WEBHOOK secret; nothing posted"
exit 0
fi
short=${HEAD_SHA:0:7}
title=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER" --jq .title)
what="[#$PR_NUMBER]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/pull/$PR_NUMBER): $title"
get=$(printf 'Download: [standard APK](<%s>) · [all variants](<%s>)' "$APK" "$RELEASE")
content=$(printf '**New signed PR test build** \`pr-%s\` · \`%s\`\n%s\n_Not merged — for testing._\n%s' "$PR_NUMBER" "$short" "$what" "$get")
jq -n --arg content "$content" '{content: $content, allowed_mentions: {parse: []}}' |
curl -fsS -H 'Content-Type: application/json' -d @- "$WEBHOOK" -o /dev/null
echo "Posted: $content"
run: python3 tools/release/pr_discord.py publish
catalog:
needs: publish
+1
View File
@@ -13,6 +13,7 @@ permissions:
concurrency:
group: update-app-catalog
cancel-in-progress: false
queue: max
jobs:
catalog:
+1
View File
@@ -35,3 +35,4 @@ __pycache__/
# Local signing with the release key (tools/build_local.sh); holds a password.
.signing.env
app/src/main/assets/directaudio/
+2 -2
View File
@@ -79,8 +79,8 @@ android {
// file out of its own data directory, and this app's entire job is to exec a rootfs:
// proot, gamescope, the Steam client and everything it launches all live under files/.
targetSdkVersion 28
versionCode 11
versionName "0.3.1"
versionCode 12
versionName "0.3.2"
buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\""
buildConfigField "String", "SOURCE_COMMIT", "\"${sourceCommit}\""
buildConfigField "int", "PR_NUMBER", "${prNumber}"
@@ -1,115 +0,0 @@
# DirectAudio for the Linux Steam client (relay build)
This is the driver for games that run under **Valve's ARM64 Proton inside a Linux
runtime on Android** - Bannerlator's linuxfs session with the native Steam client -
where the game process is a glibc process and cannot touch Android's audio
libraries itself.
Two pieces, both required:
| piece | what it is | where it runs |
|---|---|---|
| `aarch64-unix/winedirectaudio.so` + the two PE shells | the Wine `mmdevapi` driver, glibc build, **no AAudio inside** | in the game, inside the Linux rootfs |
| `directaudio-relay` | a small bionic program that owns the AAudio output and microphone streams | on the Android side, under the app's uid |
They meet over a unix socket. The driver connects, sends its launch config, and
gets back two shared-memory rings: one it fills with mixed game audio, one the
helper fills with microphone audio. The helper plays and records; the driver
keeps doing everything else it always did.
## Which Proton
Built inside `ValveSoftware/wine` at `proton_11.0`. The private `mmdevapi`
interface it implements is byte-identical across **Proton 11.0 (ARM64)**,
**Proton Experimental (ARM64)** and our own Wine-11 layers (checked 2026-09-19),
so this one build serves any of them. A future Proton on a Wine 12 base will
need a rebuild - the interface is not versioned, and a mismatch is silence, not
an error.
## Installing the driver next to Proton (not into it)
Steam verifies and updates its Proton depots, so files added under
`steamapps/common/Proton .../files/lib/wine/` will not survive. Put the driver
in a directory of its own and point Wine at it:
```
<somewhere>/directaudio/lib/wine/aarch64-unix/winedirectaudio.so
<somewhere>/directaudio/lib/wine/aarch64-windows/winedirectaudio.drv
<somewhere>/directaudio/lib/wine/i386-windows/winedirectaudio.drv
```
and set, for the game process:
```
WINEDLLPATH=<somewhere>/directaudio/lib/wine
```
Wine searches `WINEDLLPATH` entries with the per-arch subdirectories appended,
so both the PE shell and the unixlib are found there. In Bannerlator's runtime
the natural place to export it is the `bannerlator-proton` compatibility-tool
wrapper, which every Proton launch goes through.
## Selecting the driver
`mmdevapi` only tries the drivers named in the registry (or its built-in
`pulse,alsa,oss,coreaudio` list, which does not know about this one). Set, in the
game's prefix:
```
wine reg add "HKCU\Software\Wine\Drivers" /v Audio /d directaudio /f
```
Under Proton the prefix is `compatdata/<appid>/pfx`; run the command with that
prefix as `WINEPREFIX` using Proton's own `bin-arm64/wine`, or write the key from
the wrapper before it hands off to Proton.
## Running the helper
```
directaudio-relay --socket <path> [--log]
```
- Run it **under the app's uid**, the way the app already runs its PulseAudio
daemon. Android checks `RECORD_AUDIO` against the calling uid, so a helper
started any other way can play but cannot record.
- Start it **before** the game: the driver asks "is a helper there?" once, when
Wine picks an audio driver, and falls back to unavailable if not.
- The socket path must be reachable from inside the Linux rootfs. Bannerlator
binds the app's files directory and its runtime directory into the session at
their own paths, so any socket under either works unchanged on both sides.
- The helper serves any number of game processes; each gets its own streams.
It exits on `SIGTERM`; a game exiting tears down that game's streams only.
## Telling the driver where the helper is
```
BANNER_AUDIO_DIRECT_RELAY=<the same socket path>
```
Unset, the driver looks for `$XDG_RUNTIME_DIR/directaudio-relay`.
## Everything else is unchanged
All `BANNER_AUDIO_DIRECT_*` knobs mean what they mean in the in-process build:
`_PERF`, `_ADAPTIVE`, `_DECAY`, `_MS`, `_MAXMS`, `_BF`, `_MBF`, `_EXCLUSIVE`,
`_WATCHDOG`, `_STALL_MS`, `_DECAY_*`, `_LOG`, `_PERIOD_MS`, `_MINPERIOD_MS`, and
the live-config mailbox `_RUNTIME` (the helper watches the file; it must be a
path the helper can read on the Android side). **`BANNER_AUDIO_DIRECT_MIC=1`**
exposes the capture endpoint exactly as before: the helper opens the input
stream (`VOICE_COMMUNICATION` preset) when the game connects and makes it hot on
the game's first capture start.
One thing is different: there is one extra hand-off, the ring. The helper's
callback pulls a burst from it, so the driver keeps two bursts queued (about 8 ms
on a 192-frame device) on top of the AAudio buffer the presets control, and the
helper raises that if a callback ever finds the ring short. `get_latency` reports
the sum, so a game that sizes its own buffers from it still sees the truth.
## Proving it is running
- Helper side: `logcat -s DA-Relay:I` shows `hello from <exe>`, then `open: buffer
... ring target ...`, then `capture open` / `capture start` for the mic.
- Game side: the session log carries `DirectAudio: relay: connected - ...`.
- The game process's `/proc/<pid>/maps` shows `winedirectaudio.so` and **no**
`libaaudio.so` (it is in the helper's maps instead). The AudioFlinger track is
owned by the helper's pid.
@@ -1,4 +0,0 @@
directaudio linux-wine11 relay build
source 3548a4a730e8d01cb0cb0268d51a2fb8f23dcd33
wine ValveSoftware/wine@proton_11.0
unixlib.h sha256 fdbed263338d0719c4d12e02b045c23721de33219ec8878e4c2d7ebc9efcbe09
@@ -35,6 +35,7 @@ import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
import com.droiddeck.launcher.runtime.DeckyManager
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.ui.PackageRow
import com.droiddeck.launcher.ui.exposeTestTags
import com.droiddeck.launcher.session.OfflineMode
import com.droiddeck.launcher.session.ProtonExtras
import com.droiddeck.launcher.session.ComponentsManager
@@ -159,7 +160,6 @@ class MainActivity : ComponentActivity() {
private var phantomProcessStatus by mutableStateOf(PhantomProcessStatus.NOT_APPLICABLE)
private var showPhantomGate by mutableStateOf(false)
private var directAudio by mutableStateOf(false)
private var clientDirectAudio by mutableStateOf(true)
private var stretch16x9 by mutableStateOf(false)
private var launcherFullscreen by mutableStateOf(true)
private var animationsEnabled by mutableStateOf(true)
@@ -355,6 +355,7 @@ class MainActivity : ComponentActivity() {
private var emulatorList by mutableStateOf<List<Library.Emulator>>(emptyList())
private var runningLabel by mutableStateOf<String?>(null)
private var logsEnabled by mutableStateOf(true)
private var agentCommands by mutableStateOf(false)
private var showRoms by mutableStateOf(false)
private var homeAppSelected by mutableStateOf(false)
private var homeScreenEnabled by mutableStateOf(false)
@@ -526,7 +527,7 @@ class MainActivity : ComponentActivity() {
updates.start()
setContent {
DroidDeckTheme(theme, appScale = appScale) {
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) {
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize().exposeTestTags()) {
val sm = settingsMode
val page: (@Composable () -> Unit)? = when {
sm != null -> { { ModeSettingsHost(sm) } }
@@ -546,7 +547,7 @@ class MainActivity : ComponentActivity() {
busy = busy, stage = stage, percent = percent,
desktopInstalled = desktopInstalled,
offlineAccount = offlineAccount, offline = offline,
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled,
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled, agentCommands = agentCommands,
steamGames = steamGames, emulators = emulatorList, running = runningLabel,
frameGen = FrameGen.mode(this),
lossless = lossless,
@@ -658,6 +659,10 @@ class MainActivity : ComponentActivity() {
SessionPrefs.setLogsEnabled(this, !SessionPrefs.logsEnabled(this))
logsEnabled = SessionPrefs.logsEnabled(this)
},
onAgentCommands = {
com.droiddeck.launcher.agent.AgentAccess.setCommandsEnabled(this, !com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this))
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
},
onShareLogs = {
SessionLogShare.prepare(this, { SessionLogShare.latest(this) }) { zip ->
if (zip == null) android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show()
@@ -1187,7 +1192,6 @@ class MainActivity : ComponentActivity() {
oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null,
backActionsInverted = backActionsInverted,
directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null,
clientDirectAudio = clientDirectAudio,
stretch16x9 = if (mode == SessionService.MODE_STEAM) stretch16x9 else null,
mic = if (mode == SessionService.MODE_STEAM) mic else null,
renderer = if (mode == SessionService.MODE_DESKTOP) renderer else null,
@@ -1252,7 +1256,6 @@ class MainActivity : ComponentActivity() {
backActionsInverted = inverted
},
onDirectAudio = { on -> SessionPrefs.setDirectAudio(this, on); directAudio = on },
onClientDirectAudio = { on -> SessionPrefs.setClientDirectAudio(this, on); clientDirectAudio = on },
onStretch16x9 = { on -> SessionPrefs.setStretch16x9(this, on); stretch16x9 = on },
onMic = { on ->
SessionPrefs.setMicEnabled(this, on)
@@ -1417,7 +1420,6 @@ class MainActivity : ComponentActivity() {
oscMode = SessionPrefs.oscMode(this)
backActionsInverted = SessionPrefs.backActionsInverted(this)
directAudio = SessionPrefs.directAudio(this)
clientDirectAudio = SessionPrefs.clientDirectAudio(this)
stretch16x9 = SessionPrefs.stretch16x9(this)
mic = SessionPrefs.micEnabled(this)
refreshWifiDiscovery()
@@ -1492,6 +1494,7 @@ class MainActivity : ComponentActivity() {
frameGenLabel = FrameGen.label(this)
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
logsEnabled = SessionPrefs.logsEnabled(this)
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
runningLabel = if (SessionState.running) when (SessionState.mode) {
SessionService.MODE_DESKTOP -> getString(R.string.rail_desktop)
SessionService.MODE_RUN -> Library.nameForProgram(SessionState.program)
@@ -45,6 +45,7 @@ import com.droiddeck.launcher.gpu.ScreenEffects
import com.droiddeck.launcher.gpu.Lossless
import com.droiddeck.launcher.gpu.TurnipDriver
import com.droiddeck.launcher.input.EvdevKeys
import com.droiddeck.launcher.input.InputSpace
import com.droiddeck.launcher.input.KeyboardHost
import com.droiddeck.launcher.input.ControllerPrefs
import com.droiddeck.launcher.input.SessionClipboard
@@ -367,6 +368,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val bridge = PadBridge(File(LinuxRuntime.sessionRoot(this), "dev/input"))
padBridge = bridge
SessionState.padBridge = bridge
padMotion = com.droiddeck.launcher.input.PadMotion(this) {
@Suppress("DEPRECATION")
(if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay)?.rotation ?: android.view.Surface.ROTATION_0
@@ -1503,18 +1505,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun movePointer(x: Float, y: Float) {
val width = surfaceView.width.takeIf { it > 0 } ?: return
val height = surfaceView.height.takeIf { it > 0 } ?: return
val out = SessionState.outputSize
val scale = minOf(width / out.first.toFloat(), height / out.second.toFloat())
val drawnW = out.first * scale
val drawnH = out.second * scale
val left = (width - drawnW) / 2f
val top = (height - drawnH) / 2f
val px = ((x - left) / drawnW * 1920f).toInt().coerceIn(0, 1919)
val py = ((y - top) / drawnH * 1080f).toInt().coerceIn(0, 1079)
WaylandCompositor.nativeSendPointer(1, px, py)
showCursor(x.coerceIn(left, left + drawnW), y.coerceIn(top, top + drawnH))
val rect = drawnRect() ?: return
val cx = x.coerceIn(rect.left, rect.right)
val cy = y.coerceIn(rect.top, rect.bottom)
WaylandCompositor.nativeSendPointer(1, InputSpace.x(cx, surfaceView.width), InputSpace.y(cy, surfaceView.height))
showCursor(cx, cy)
}
/**
@@ -1661,10 +1656,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (width <= 0f || height <= 0f) return
val nx = (x / width).coerceIn(0f, 1f)
val ny = (y / height).coerceIn(0f, 1f)
WaylandCompositor.nativeSendPointer(1, (nx * 1919f).toInt(), (ny * 1079f).toInt())
drawnRect()?.let { rect ->
showCursor(rect.left + nx * rect.width(), rect.top + ny * rect.height())
}
val rect = drawnRect() ?: return
val px = rect.left + nx * rect.width()
val py = rect.top + ny * rect.height()
WaylandCompositor.nativeSendPointer(1, InputSpace.x(px, surfaceView.width), InputSpace.y(py, surfaceView.height))
showCursor(px, py)
}
private fun closeSecondScreen(reset: Boolean) {
@@ -1711,9 +1707,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
val rect = drawnRect() ?: return false
fun sendTouch(action: Int, index: Int) {
val x = ((event.getX(index) - rect.left) / rect.width()).coerceIn(0f, 1f)
val y = ((event.getY(index) - rect.top) / rect.height()).coerceIn(0f, 1f)
WaylandCompositor.nativeSendTouch(action, event.getPointerId(index), (x * 1919f).toInt(), (y * 1079f).toInt())
val x = event.getX(index).coerceIn(rect.left, rect.right)
val y = event.getY(index).coerceIn(rect.top, rect.bottom)
WaylandCompositor.nativeSendTouch(action, event.getPointerId(index),
InputSpace.x(x, surfaceView.width), InputSpace.y(y, surfaceView.height))
}
when (event.actionMasked) {
// A first finger starts a new gesture, and Android has ended every earlier one: whatever
@@ -2122,6 +2119,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
closeSecondScreen(reset = false)
if (::hud.isInitialized) hud.stop()
padBridge?.stop()
if (SessionState.padBridge === padBridge) SessionState.padBridge = null
padMotion?.stop()
if (SessionState.deckPadListener === deckPadListener) SessionState.deckPadListener = null
if (SessionState.endListener === endListener) SessionState.endListener = null
@@ -0,0 +1,48 @@
package com.droiddeck.launcher.agent
import android.content.Context
/**
* Who may run code through the agent bridge. Reading state, starting and stopping sessions,
* launching and quitting games and sending input only need the shell (the provider's DUMP
* permission). Running commands in the guest, evaluating JavaScript in the Steam client, session
* environment, binary overrides and preference writes reach inside the app's sandbox - the guest
* holds the Steam login - which the shell of a stock device otherwise cannot. They require
* Setup > Session > Debugging tools to be on, in every build. The bridge itself cannot turn it on.
*/
object AgentAccess {
const val MAX_REQUEST_CHARS = 256 * 1024
private const val PREFS = "agent"
private const val KEY_COMMANDS = "commands"
/** The preferences file the bridge must never write: set-pref refuses it. */
const val PROTECTED_PREFS = PREFS
fun commandsAllowed(context: Context): Boolean =
prefs(context).getBoolean(KEY_COMMANDS, false)
/** The Setup toggle's own state. */
fun commandsEnabled(context: Context): Boolean = prefs(context).getBoolean(KEY_COMMANDS, false)
fun setCommandsEnabled(context: Context, enabled: Boolean) {
prefs(context).edit().putBoolean(KEY_COMMANDS, enabled).apply()
if (!enabled) runCatching { AgentEnv.revoke(context) }
.onFailure { android.util.Log.w("AgentAccess", "Could not finish clearing debugging experiments") }
}
fun requireCommands(context: Context) {
if (!commandsAllowed(context)) throw AgentException(
"AGENT_COMMANDS_DISABLED",
"Debugging tools are off: turn on Setup > Session > Debugging tools on the device",
)
}
fun requireStart(context: Context, request: org.json.JSONObject) {
if (request.optString("mode") == "run") requireCommands(context)
}
private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
}
/** A refusal with a stable code, answered as {"ok": false, "error": {code, message}}. */
class AgentException(val code: String, message: String) : RuntimeException(message)
@@ -10,13 +10,14 @@ import android.net.Uri
import android.os.Binder
import android.os.Bundle
import android.os.Process
import android.util.Base64
import com.droiddeck.launcher.BuildConfig
import com.droiddeck.launcher.frontend.GameLaunchLink
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
import com.droiddeck.launcher.session.SessionArtifacts
import com.droiddeck.launcher.session.SessionEvents
import com.droiddeck.launcher.session.SessionPhase
import com.droiddeck.launcher.session.SessionPaths
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import org.json.JSONArray
@@ -25,7 +26,14 @@ import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
/** A shell-only control surface, installed only by debug builds. */
/**
* The shell's control surface (docs/agent-control.md), in every build: the provider and its start
* Activity need android.permission.DUMP, held by the shell and privileged or explicitly granted callers. Commands that
* reach into the app's sandbox are further gated by [AgentAccess].
*
* A method's request is JSON, base64-encoded in the "request" extra; every answer is JSON in the
* "json" key of the returned Bundle, {"ok": true, ...} or {"ok": false, "error": {code, message}}.
*/
class AgentBridgeProvider : ContentProvider() {
override fun onCreate(): Boolean {
val appContext = context?.applicationContext ?: return false
@@ -48,17 +56,53 @@ class AgentBridgeProvider : ContentProvider() {
}
val response = try {
when (method) {
"state" -> state(context).put("ok", true)
"start" -> error("USE_DROIDDECKCTL", "Start sessions with tools/droiddeckctl so Android launches a visible Activity")
"stop" -> stop(context)
"resume" -> resume(context)
else -> error("UNKNOWN_COMMAND", "Unknown agent command '$method'")
val request = decode(extras?.getString(EXTRA_REQUEST))
// Binder identity is the shell's; everything below acts as the app.
val token = Binder.clearCallingIdentity()
try {
dispatch(context, method, request)
} finally {
Binder.restoreCallingIdentity(token)
}
} catch (e: AgentException) {
error(e.code, e.message ?: e.code)
} catch (e: Exception) {
error("COMMAND_FAILED", e.message ?: e.javaClass.simpleName)
}
return Bundle().apply { putString(RESULT_JSON, response.toString()) }
val json = response.toString().let {
if (it.length <= 384 * 1024) it else error("RESPONSE_TOO_LARGE", "Reduce the command output or select fewer fields").toString()
}
return Bundle().apply { putString(RESULT_JSON, json) }
}
private fun dispatch(context: Context, method: String, request: JSONObject): JSONObject = when (method) {
"state" -> state(context).put("ok", true)
"start" -> error("USE_DROIDDECKCTL", "Start sessions with tools/droiddeckctl so Android launches a visible Activity")
"stop" -> stop(context)
"resume" -> resume(context)
"launch" -> launch(context, request)
"focus" -> guest(context, JSONObject().put("kind", "focus"), 15_000)
"quit" -> guest(context, JSONObject().put("kind", "quit").put("appId", request.opt("appId"))
.put("timeout", request.optDouble("timeout", 15.0)), timeoutMs(request, 15.0, 30_000))
"input" -> AgentInput.handle(request)
"ui" -> AgentUi.handle(request)
"guest" -> {
AgentAccess.requireCommands(context)
guest(context, JSONObject(request.toString()).put("kind", "exec"), timeoutMs(request, 30.0, 10_000))
}
"cdp" -> {
AgentAccess.requireCommands(context)
guest(context, JSONObject(request.toString()).put("kind", "cdp"), timeoutMs(request, 15.0, 5_000))
}
"env" -> env(context, request)
"override" -> {
AgentAccess.requireCommands(context)
AgentEnv.override(context, request.optString("name")).put("ok", true).put("command", "override")
}
"prefs" -> prefs(context, request)
"access" -> JSONObject().put("ok", true).put("commands", AgentAccess.commandsAllowed(context))
.put("debugBuild", BuildConfig.DEBUG).put("inbox", AgentEnv.inbox(context).absolutePath)
else -> error("UNKNOWN_COMMAND", "Unknown agent command '$method'")
}
private fun state(context: Context): JSONObject {
@@ -91,13 +135,31 @@ class AgentBridgeProvider : ContentProvider() {
.put("status", SessionState.failureStatus ?: JSONObject.NULL)
session.put("failure", failure)
// gamescope's focus as last published by the guest agent, without the window lists
// (the focus command returns those, fresh).
val focus = AgentGuest.focus(context)?.let { snap ->
JSONObject()
.put("focusedApp", snap.opt("focusedApp") ?: JSONObject.NULL)
.put("focusedWindow", snap.opt("focusedWindow") ?: JSONObject.NULL)
.put("focusableApps", snap.optJSONArray("focusableApps") ?: JSONArray())
.put("baselayerAppIds", snap.optJSONArray("baselayerAppIds") ?: JSONArray())
.put("seq", snap.optInt("seq"))
.put("t", snap.optLong("t"))
}
session.put("focus", focus ?: JSONObject.NULL)
val hello = AgentGuest.hello(context)
return JSONObject()
.put("schema", 1)
.put("schema", SCHEMA)
.put("build", BuildConfig.BUILD_LABEL)
.put("appVersion", context.packageManager.getPackageInfo(context.packageName, 0).versionName)
.put("runtime", JSONObject()
.put("installed", LinuxRuntime.isInstalled(context))
.put("version", runtimeVersion ?: JSONObject.NULL))
.put("agent", JSONObject()
.put("guest", hello != null)
.put("guestFocus", hello?.optBoolean("focus") ?: false)
.put("commands", AgentAccess.commandsAllowed(context)))
.put("session", session)
}
@@ -131,6 +193,67 @@ class AgentBridgeProvider : ContentProvider() {
return JSONObject().put("ok", true).put("command", "resume")
}
private fun launch(context: Context, request: JSONObject): JSONObject {
val appId = request.optString("appId")
if (!GameLaunchLink.validId(appId)) throw AgentException("INVALID_APP_ID", "appId must be a decimal Steam app id")
if (!SessionState.running || SessionState.mode != SessionService.MODE_STEAM) {
throw AgentException("NO_STEAM_SESSION", "Games launch inside a running Steam session")
}
if (!SessionService.launchGame(context, appId)) throw AgentException("LAUNCH_REJECTED", "The session did not accept the launch")
SessionEvents.record("agent.launch_requested", mapOf("appId" to appId))
return JSONObject().put("ok", true).put("command", "launch").put("appId", appId)
}
private fun env(context: Context, request: JSONObject): JSONObject {
AgentAccess.requireCommands(context)
val result = when (val op = request.optString("op", "list")) {
"list" -> AgentEnv.list(context)
"set" -> {
val lines = request.optJSONArray("lines") ?: JSONArray()
AgentEnv.set(context, List(lines.length()) { lines.optString(it) }, request.optBoolean("persistent"))
}
"clear" -> AgentEnv.clear(context, request.optString("scope", "next"))
else -> throw AgentException("INVALID_REQUEST", "env op '$op' is not list, set or clear")
}
return result.put("ok", true).put("command", "env")
}
private fun prefs(context: Context, request: JSONObject): JSONObject {
AgentAccess.requireCommands(context)
val file = request.optString("file")
val result = when (val op = request.optString("op", "get")) {
"get" -> AgentPrefs.get(context, file)
"set" -> AgentPrefs.set(context, file, request.optString("key"), request.optString("type", "string"),
if (request.isNull("value")) null else request.optString("value"))
else -> throw AgentException("INVALID_REQUEST", "prefs op '$op' is not get or set")
}
return result.put("ok", true).put("command", "prefs")
}
/** A guest agent request; its own answer already carries ok or error. */
private fun guest(context: Context, request: JSONObject, timeoutMs: Long): JSONObject =
AgentGuest.call(context, request, timeoutMs)
/** The guest's own timeout plus slack for the round trip. */
private fun timeoutMs(request: JSONObject, defaultSeconds: Double, slackMs: Long): Long {
val seconds = if (request.has("timeout")) request.opt("timeout")?.toString()?.toDoubleOrNull()
?: throw AgentException("INVALID_REQUEST", "timeout must be a number") else defaultSeconds
if (!seconds.isFinite() || seconds <= 0 || seconds > 600) {
throw AgentException("INVALID_REQUEST", "timeout must be a positive number no greater than 600 seconds")
}
return (seconds * 1000).toLong() + slackMs
}
private fun decode(encoded: String?): JSONObject {
if (encoded.isNullOrBlank()) return JSONObject()
if (encoded.length > AgentAccess.MAX_REQUEST_CHARS) throw AgentException("INVALID_REQUEST", "The encoded request exceeds 256 KiB")
return try {
JSONObject(String(Base64.decode(encoded, Base64.DEFAULT), Charsets.UTF_8))
} catch (e: Exception) {
throw AgentException("INVALID_REQUEST", "The request extra is not base64 JSON")
}
}
private fun error(code: String, message: String) = JSONObject()
.put("ok", false)
.put("error", JSONObject().put("code", code).put("message", message))
@@ -143,6 +266,9 @@ class AgentBridgeProvider : ContentProvider() {
companion object {
const val RESULT_JSON = "json"
const val EXTRA_REQUEST = "request"
/** 2 added agent and session.focus; everything in 1 is unchanged. */
const val SCHEMA = 2
private val recoveryComplete = CountDownLatch(1)
fun awaitRecovery() {
@@ -0,0 +1,222 @@
package com.droiddeck.launcher.agent
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.nio.file.Files
import java.nio.file.LinkOption.NOFOLLOW_LINKS
import java.nio.file.StandardOpenOption.READ
/**
* Experiment switches an agent sets without touching Download/droiddeck-env or rebuilding the apk:
*
* - environment lines (KEY=VALUE) for the session, applied after the user's own droiddeck-env, so
* they win. "next" lines are taken by the next session that starts and dropped when it ends;
* "persistent" ones stay until cleared.
* - binary overrides: a file pushed to the app's external files (agent-inbox/<name>) is installed
* as /opt/droiddeck-agent/bin/<name> in the rootfs and put first on the next session's PATH -
* a gamescope build under test, say. Removed when that session ends.
*
* Kept in the app's own files (agent-env.json), never in a place the shell can write.
*/
object AgentEnv {
private const val TAG = "AgentEnv"
private const val FILE = "agent-env.json"
private const val GUEST_BIN = "/opt/droiddeck-agent/bin"
private const val BASE_PATH = "/usr/local/bin:/usr/bin:/bin"
private val NAME = Regex("[A-Za-z0-9._-]{1,64}")
private val KEY = Regex("[A-Za-z_][A-Za-z0-9_]*")
private val lock = Any()
fun inbox(context: Context): File = File(context.getExternalFilesDir(null), "agent-inbox")
fun list(context: Context): JSONObject = synchronized(lock) {
AgentAccess.requireCommands(context)
load(context)
}
/** Add [lines] for the next session ([persistent] = every session until cleared). */
fun set(context: Context, lines: List<String>, persistent: Boolean): JSONObject = synchronized(lock) {
AgentAccess.requireCommands(context)
if (lines.any { line -> KEY.matchEntire(line.substringBefore('=', "")) == null || !line.contains('=') || line.any { it == '\n' || it == '\r' || it == '\u0000' } }) {
throw AgentException("INVALID_ENV", "Environment entries must be single KEY=VALUE lines without NUL bytes")
}
val state = load(context)
val key = if (persistent) "persistent" else "pending"
val merged = merge(strings(state.optJSONArray(key)), lines)
state.put(key, JSONArray(merged))
save(context, state)
state
}
/** Drop lines: [scope] is "next", "persistent" or "all". */
fun clear(context: Context, scope: String): JSONObject = synchronized(lock) {
AgentAccess.requireCommands(context)
val state = load(context)
when (scope) {
"next" -> state.put("pending", JSONArray())
"persistent" -> state.put("persistent", JSONArray())
"all" -> { state.put("pending", JSONArray()); state.put("persistent", JSONArray()); state.put("pendingOverrides", JSONArray()) }
else -> throw AgentException("INVALID_SCOPE", "Scope must be next, persistent or all")
}
save(context, state)
state
}
/** Install agent-inbox/[name] as an override for the next session. */
fun override(context: Context, name: String): JSONObject = synchronized(lock) {
AgentAccess.requireCommands(context)
if (NAME.matchEntire(name) == null || name in setOf(".", "..")) throw AgentException("INVALID_NAME", "Override names are letters, digits, '.', '_' and '-'")
val source = File(inbox(context), name)
if (Files.isSymbolicLink(source.toPath())) throw AgentException("INVALID_NAME", "The override must be a regular file")
if (!source.isFile) throw AgentException("NO_SUCH_FILE", "Push the binary to ${source.path} first")
val target = File(bin(context), name)
target.parentFile?.mkdirs()
val staged = File.createTempFile("override-", ".tmp", target.parentFile)
try {
Files.newInputStream(source.toPath(), READ, NOFOLLOW_LINKS).use { input -> staged.outputStream().use { input.copyTo(it) } }
} catch (e: Exception) {
staged.delete()
throw AgentException("OVERRIDE_FAILED", "Could not stage the override")
}
if (!staged.setExecutable(true, false) || !staged.renameTo(target)) {
staged.delete()
throw AgentException("OVERRIDE_FAILED", "Could not install $name in the rootfs")
}
source.delete()
val state = load(context)
state.put("pendingOverrides", JSONArray(merge(strings(state.optJSONArray("pendingOverrides")), listOf(name))))
save(context, state)
state.put("installed", "$GUEST_BIN/$name")
}
/**
* At session start: the lines this session gets, after the user's droiddeck-env. Pending lines
* and overrides become this session's own, to be dropped by [endSession].
*/
fun beginSession(context: Context): List<String> = synchronized(lock) {
if (!AgentAccess.commandsAllowed(context)) {
revoke(context)
return@synchronized emptyList()
}
val state = load(context)
val active = strings(state.optJSONArray("pending"))
val overrides = strings(state.optJSONArray("pendingOverrides"))
state.put("active", JSONArray(active)).put("pending", JSONArray())
state.put("activeOverrides", JSONArray(overrides)).put("pendingOverrides", JSONArray())
save(context, state)
// Anything else there was left by a session that never reached endSession (the app died).
bin(context).listFiles()
?.filter { it.name !in overrides }?.forEach { it.delete() }
val lines = strings(state.optJSONArray("persistent")) + active
val withPath = if (overrides.isEmpty()) lines else lines + "PATH=$GUEST_BIN:${pathOf(lines)}"
if (withPath.isNotEmpty()) Log.i(TAG, "agent environment keys for this session: ${withPath.map { it.substringBefore('=') }}")
withPath
}
fun revoke(context: Context) = synchronized(lock) {
val state = load(context)
for (key in listOf("pending", "active", "persistent", "pendingOverrides", "activeOverrides")) state.put(key, JSONArray())
save(context, state)
bin(context).listFiles()?.forEach { it.delete() }
}
/** At session end: this session's lines and override binaries go. */
fun endSession(context: Context) = synchronized(lock) {
val state = load(context)
val overrides = strings(state.optJSONArray("activeOverrides"))
val pending = strings(state.optJSONArray("pendingOverrides"))
val bin = bin(context)
overrides.filter { it !in pending }.forEach { File(bin, it).delete() }
state.put("active", JSONArray()).put("activeOverrides", JSONArray())
save(context, state)
}
/** A PATH= line among [lines] (the user's or an agent's) is extended rather than replaced. */
private fun pathOf(lines: List<String>) =
lines.lastOrNull { it.startsWith("PATH=") }?.substringAfter('=')?.takeIf { it.isNotBlank() } ?: BASE_PATH
private fun bin(context: Context): File {
val root = LinuxRuntime.rootDir(context).canonicalFile.toPath()
val directory = root.resolve(GUEST_BIN.removePrefix("/"))
var path = directory
while (path != root) {
if (Files.isSymbolicLink(path)) throw AgentException("OVERRIDE_FAILED", "The override directory must not contain symbolic links")
path = path.parent
}
return directory.toFile()
}
private fun merge(existing: List<String>, added: List<String>): List<String> {
val keys = added.map { it.substringBefore('=') }.toSet()
return existing.filter { it.substringBefore('=') !in keys } + added
}
private fun strings(array: JSONArray?): List<String> =
if (array == null) emptyList() else List(array.length()) { array.optString(it) }.filter { it.isNotEmpty() }
private fun load(context: Context): JSONObject {
val file = File(context.filesDir, FILE)
val state = try { if (file.isFile) JSONObject(file.readText()) else JSONObject() } catch (e: Exception) { JSONObject() }
for (key in listOf("pending", "active", "persistent", "pendingOverrides", "activeOverrides")) {
if (!state.has(key)) state.put(key, JSONArray())
}
return state
}
private fun save(context: Context, state: JSONObject) {
val file = File(context.filesDir, FILE)
val staged = File(context.filesDir, "$FILE.tmp")
staged.writeText(state.toString())
if (!staged.renameTo(file)) {
staged.delete()
throw AgentException("ENV_WRITE_FAILED", "Could not save the debugging environment")
}
}
}
/** Typed writes to the app's SharedPreferences, for driving a settings matrix without the UI. */
object AgentPrefs {
fun set(context: Context, file: String, key: String, type: String, value: String?): JSONObject {
AgentAccess.requireCommands(context)
validateFile(file)
if (file == AgentAccess.PROTECTED_PREFS) throw AgentException("PROTECTED_PREFS", "The agent preferences are set on the device only")
if (file.isBlank() || key.isBlank()) throw AgentException("INVALID_PREF", "file and key are required")
val prefs = context.getSharedPreferences(file, Context.MODE_PRIVATE)
val previous = prefs.all[key]
val editor = prefs.edit()
try {
when (type) {
"remove" -> editor.remove(key)
"bool" -> editor.putBoolean(key, value?.toBooleanStrictOrNull() ?: throw NumberFormatException("not true/false"))
"int" -> editor.putInt(key, value!!.toInt())
"long" -> editor.putLong(key, value!!.toLong())
"float" -> editor.putFloat(key, value!!.toFloat())
"string" -> editor.putString(key, value ?: "")
else -> throw AgentException("INVALID_PREF", "type must be bool, int, long, float, string or remove")
}
} catch (e: RuntimeException) {
if (e is AgentException) throw e
throw AgentException("INVALID_PREF", "The value is not a $type")
}
if (!editor.commit()) throw AgentException("PREF_WRITE_FAILED", "Could not write $file/$key")
return JSONObject().put("file", file).put("key", key).put("type", type)
.put("previous", previous ?: JSONObject.NULL).put("value", prefs.all[key] ?: JSONObject.NULL)
}
fun get(context: Context, file: String): JSONObject {
AgentAccess.requireCommands(context)
validateFile(file)
val all = context.getSharedPreferences(file, Context.MODE_PRIVATE).all
return JSONObject().put("file", file).put("values", JSONObject(all.mapValues { it.value ?: JSONObject.NULL }))
}
private fun validateFile(file: String) {
if (!Regex("[A-Za-z0-9_-][A-Za-z0-9._-]{0,127}").matches(file)) {
throw AgentException("INVALID_PREF", "Preference files must be simple names")
}
}
}
@@ -0,0 +1,128 @@
package com.droiddeck.launcher.agent
import android.content.Context
import android.os.FileObserver
import android.util.Log
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.SessionEvents
import com.droiddeck.launcher.session.SessionState
import org.json.JSONObject
import java.io.File
import java.util.UUID
/**
* The app's side of the guest agent (tools/linuxfs/overlay/usr/local/bin/droiddeck-agent): requests
* go in as files under the session root's agent directory and answers come back the same way, so
* whatever runs does so inside the live session with its own environment.
*/
object AgentGuest {
private const val TAG = "AgentGuest"
private const val POLL_MS = 50L
private val lock = Any()
private var observer: FileObserver? = null
private var lastFocusKey: String? = null
fun dir(context: Context) = File(LinuxRuntime.sessionRoot(context), "agent")
/**
* Before each session: nothing of the last one's daemon, answers or focus may be read as
* current. Then watch for the new daemon's hello and focus snapshots, which go into the
* session's events.jsonl.
*/
fun reset(context: Context) {
synchronized(lock) {
observer?.stopWatching()
observer = null
lastFocusKey = null
val dir = dir(context)
dir.deleteRecursively()
dir.mkdirs()
@Suppress("DEPRECATION")
observer = object : FileObserver(dir.path, MOVED_TO or CLOSE_WRITE) {
override fun onEvent(event: Int, path: String?) {
when (path) {
"hello.json" -> readJson(File(dir, path))?.let {
SessionEvents.record("agent.ready", mapOf("pid" to it.optInt("pid"), "focus" to it.optBoolean("focus")))
}
"focus.json" -> readJson(File(dir, path))?.let(::recordFocus)
}
}
}.also { it.startWatching() }
}
}
/** At the end of a session: no more events for a folder that is being closed. */
fun stop() {
synchronized(lock) {
observer?.stopWatching()
observer = null
}
}
private fun recordFocus(snapshot: JSONObject) {
val fields = linkedMapOf<String, Any?>(
"focusedApp" to snapshot.opt("focusedApp"),
"focusableApps" to snapshot.optJSONArray("focusableApps")?.toString(),
"baselayerAppIds" to snapshot.optJSONArray("baselayerAppIds")?.toString(),
)
val key = fields.values.joinToString("|")
synchronized(lock) {
if (key == lastFocusKey) return
lastFocusKey = key
}
SessionEvents.record("focus.changed", fields + ("seq" to snapshot.optInt("seq")))
}
/** The daemon's hello, when it is running in the current session. */
fun hello(context: Context): JSONObject? {
if (!SessionState.running) return null
val hello = readJson(File(dir(context), "hello.json")) ?: return null
val pid = hello.optInt("pid", -1)
return hello.takeIf { pid > 1 && File("/proc/$pid").exists() }
}
/** The newest focus snapshot the daemon published, when a session is running. */
fun focus(context: Context): JSONObject? =
if (SessionState.running) readJson(File(dir(context), "focus.json")) else null
/** Send one request and wait for its answer. Throws [AgentException] with a stable code. */
fun call(context: Context, request: JSONObject, timeoutMs: Long): JSONObject {
if (request.optString("kind") in setOf("exec", "cdp")) AgentAccess.requireCommands(context)
if (!SessionState.running) throw AgentException("NO_ACTIVE_SESSION", "There is no running session")
hello(context) ?: throw AgentException("AGENT_UNAVAILABLE", "The guest agent is not running in this session (yet)")
val dir = dir(context)
val requests = File(dir, "req").apply { mkdirs() }
val answers = File(dir, "resp").apply { mkdirs() }
val id = UUID.randomUUID().toString()
val staged = File(requests, "$id.json.tmp")
val published = File(requests, "$id.json")
val answer = File(answers, "$id.json")
staged.writeText(request.toString())
if (!staged.renameTo(published)) {
staged.delete()
throw AgentException("AGENT_UNAVAILABLE", "Could not hand the request to the guest agent")
}
val deadline = System.currentTimeMillis() + timeoutMs
while (System.currentTimeMillis() < deadline) {
if (answer.isFile) {
if (answer.length() > 1024 * 1024) {
answer.delete()
throw AgentException("RESPONSE_TOO_LARGE", "The guest response exceeds 1 MiB")
}
val result = readJson(answer)
answer.delete()
return result ?: throw AgentException("INVALID_AGENT_RESPONSE", "The guest agent's answer was not JSON")
}
Thread.sleep(POLL_MS)
}
published.delete()
Log.w(TAG, "no answer to ${request.optString("kind")} in ${timeoutMs}ms")
throw AgentException("TIMEOUT", "The guest agent did not answer within ${timeoutMs / 1000}s")
}
private fun readJson(file: File): JSONObject? = try {
if (file.isFile && file.length() <= 1024 * 1024) JSONObject(file.readText()) else null
} catch (e: Exception) {
null
}
}
@@ -0,0 +1,221 @@
package com.droiddeck.launcher.agent
import com.droiddeck.launcher.input.PadState
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.wayland.WaylandCompositor
import org.json.JSONObject
/**
* Input into the running session the way a player gives it: keys and touches through the
* compositor (what the session screen sends), and the virtual pad through the same PadBridge the
* on-screen controls drive, so games that ignore touch still see a controller.
*/
object AgentInput {
/** Out of the way of real fingers, which Android numbers from 0. */
private const val TOUCH_ID = 9
private const val TOUCH_SCALE_X = 1919f
private const val TOUCH_SCALE_Y = 1079f
fun handle(request: JSONObject): JSONObject {
if (!SessionState.running || !SessionState.firstFrameSeen) {
throw AgentException("SESSION_NOT_READY", "Input needs a running session that has drawn its first frame")
}
return when (val type = request.optString("type")) {
"key" -> key(request)
"text" -> text(request)
"tap" -> tap(request)
"swipe" -> swipe(request)
"pad" -> pad(request)
"stick" -> stick(request)
"trigger" -> trigger(request)
else -> throw AgentException("INVALID_INPUT", "Unknown input type '$type'")
}.put("ok", true).put("command", "input").put("type", request.optString("type"))
}
private fun key(request: JSONObject): JSONObject {
val name = request.optString("key")
val code = KEYS[name.uppercase()] ?: name.toIntOrNull()
?: throw AgentException("INVALID_INPUT", "Unknown key '$name' (a name such as ENTER or an evdev code)")
val modifiers = request.optJSONArray("modifiers")?.let { array ->
List(array.length()) { i ->
KEYS[array.optString(i).uppercase()] ?: throw AgentException("INVALID_INPUT", "Unknown modifier '${array.optString(i)}'")
}
}.orEmpty()
when (val action = request.optString("action", "tap")) {
"down" -> WaylandCompositor.nativeSendKey(code, 1)
"up" -> WaylandCompositor.nativeSendKey(code, 0)
"tap" -> {
modifiers.forEach { WaylandCompositor.nativeSendKey(it, 1) }
WaylandCompositor.nativeSendKey(code, 1)
hold(request, 40)
WaylandCompositor.nativeSendKey(code, 0)
modifiers.asReversed().forEach { WaylandCompositor.nativeSendKey(it, 0) }
}
else -> throw AgentException("INVALID_INPUT", "Key action '$action' is not tap, down or up")
}
return JSONObject().put("code", code)
}
/** Typed as key presses (US layout), which reaches X programs that have no text-input support. */
private fun text(request: JSONObject): JSONObject {
val text = request.optString("text")
if (request.optBoolean("commit")) {
WaylandCompositor.textInputCommit(text)
return JSONObject().put("length", text.length).put("via", "text-input")
}
val missing = text.filter { TYPED[it] == null }
if (missing.isNotEmpty()) throw AgentException("INVALID_INPUT", "Cannot type '${missing.toSet().joinToString("")}' as keys; use commit")
val delay = request.optLong("delayMs", 15)
for (ch in text) {
val (code, shift) = TYPED.getValue(ch)
if (shift) WaylandCompositor.nativeSendKey(KEYS.getValue("LEFTSHIFT"), 1)
WaylandCompositor.nativeSendKey(code, 1)
WaylandCompositor.nativeSendKey(code, 0)
if (shift) WaylandCompositor.nativeSendKey(KEYS.getValue("LEFTSHIFT"), 0)
Thread.sleep(delay)
}
return JSONObject().put("length", text.length).put("via", "keys")
}
private fun tap(request: JSONObject): JSONObject {
val (x, y) = point(request, "x", "y")
WaylandCompositor.nativeSendTouch(0, TOUCH_ID, x, y)
hold(request, 60)
WaylandCompositor.nativeSendTouch(2, TOUCH_ID, x, y)
return JSONObject().put("touch", org.json.JSONArray().put(x).put(y))
}
private fun swipe(request: JSONObject): JSONObject {
val (x1, y1) = point(request, "x", "y")
val (x2, y2) = point(request, "x2", "y2")
val duration = request.optLong("durationMs", 300).coerceIn(16, 10_000)
val steps = (duration / 16).toInt().coerceAtLeast(2)
WaylandCompositor.nativeSendTouch(0, TOUCH_ID, x1, y1)
for (i in 1..steps) {
Thread.sleep(duration / steps)
WaylandCompositor.nativeSendTouch(1, TOUCH_ID, x1 + (x2 - x1) * i / steps, y1 + (y2 - y1) * i / steps)
}
WaylandCompositor.nativeSendTouch(2, TOUCH_ID, x2, y2)
return JSONObject().put("from", org.json.JSONArray().put(x1).put(y1)).put("to", org.json.JSONArray().put(x2).put(y2))
}
/**
* A point in the compositor's touch space (0..1919 x 0..1079 whatever the session's size), from
* the session's output pixels (space "output", the default: what the guest draws at) or 0..1
* fractions (space "fraction").
*/
private fun point(request: JSONObject, xKey: String, yKey: String): Pair<Int, Int> {
if (!request.has(xKey) || !request.has(yKey)) throw AgentException("INVALID_INPUT", "$xKey and $yKey are required")
val x = request.getDouble(xKey)
val y = request.getDouble(yKey)
val (fx, fy) = when (val space = request.optString("space", "output")) {
"fraction" -> x to y
"output" -> {
val (w, h) = SessionState.outputSize
x / (w - 1).coerceAtLeast(1) to y / (h - 1).coerceAtLeast(1)
}
else -> throw AgentException("INVALID_INPUT", "space '$space' is not output or fraction")
}
return (fx.coerceIn(0.0, 1.0) * TOUCH_SCALE_X).toInt() to (fy.coerceIn(0.0, 1.0) * TOUCH_SCALE_Y).toInt()
}
private fun pad(request: JSONObject): JSONObject {
val bridge = SessionState.padBridge ?: throw AgentException("NO_PAD", "The session has no virtual pad")
val name = request.optString("button").lowercase()
if (name == "qam") {
bridge.triggerQam()
return JSONObject().put("button", name)
}
val button = BUTTONS[name]
if (button == null && name !in DPAD) throw AgentException("INVALID_INPUT", "Unknown pad button '$name'")
val apply = { s: PadState, down: Boolean ->
when (name) {
"up" -> s.up = down
"down" -> s.down = down
"left" -> s.left = down
"right" -> s.right = down
else -> s.press(button!!, down)
}
}
when (val action = request.optString("action", "tap")) {
"down" -> bridge.applyTouch { apply(it, true) }
"up" -> bridge.applyTouch { apply(it, false) }
"tap" -> {
bridge.applyTouch { apply(it, true) }
hold(request, 120)
bridge.applyTouch { apply(it, false) }
}
else -> throw AgentException("INVALID_INPUT", "Pad action '$action' is not tap, down or up")
}
return JSONObject().put("button", name)
}
private fun stick(request: JSONObject): JSONObject {
val bridge = SessionState.padBridge ?: throw AgentException("NO_PAD", "The session has no virtual pad")
val right = request.optString("stick", "left") == "right"
val x = request.optDouble("x", 0.0).toFloat().coerceIn(-1f, 1f)
val y = request.optDouble("y", 0.0).toFloat().coerceIn(-1f, 1f)
bridge.applyTouch { if (right) { it.rightX = x; it.rightY = y } else { it.leftX = x; it.leftY = y } }
hold(request, 300)
bridge.applyTouch { if (right) { it.rightX = 0f; it.rightY = 0f } else { it.leftX = 0f; it.leftY = 0f } }
return JSONObject().put("stick", if (right) "right" else "left")
}
private fun trigger(request: JSONObject): JSONObject {
val bridge = SessionState.padBridge ?: throw AgentException("NO_PAD", "The session has no virtual pad")
val right = request.optString("trigger", "right") == "right"
val value = request.optDouble("value", 1.0).toFloat().coerceIn(0f, 1f)
bridge.applyTouch { if (right) it.rightTrigger = value else it.leftTrigger = value }
hold(request, 200)
bridge.applyTouch { if (right) it.rightTrigger = 0f else it.leftTrigger = 0f }
return JSONObject().put("trigger", if (right) "right" else "left")
}
private fun hold(request: JSONObject, defaultMs: Long) =
Thread.sleep(request.optLong("holdMs", defaultMs).coerceIn(0, 10_000))
private val DPAD = setOf("up", "down", "left", "right")
private val BUTTONS = mapOf(
"a" to PadState.A, "b" to PadState.B, "x" to PadState.X, "y" to PadState.Y,
"lb" to PadState.LB, "rb" to PadState.RB, "select" to PadState.SELECT, "back" to PadState.SELECT,
"start" to PadState.START, "menu" to PadState.START, "l3" to PadState.L3, "r3" to PadState.R3,
"guide" to PadState.GUIDE, "steam" to PadState.GUIDE,
)
/** Linux evdev codes (input-event-codes.h) by name. */
private val KEYS: Map<String, Int> = buildMap {
"1234567890".forEachIndexed { i, c -> put(c.toString(), 2 + i) }
"QWERTYUIOP".forEachIndexed { i, c -> put(c.toString(), 16 + i) }
"ASDFGHJKL".forEachIndexed { i, c -> put(c.toString(), 30 + i) }
"ZXCVBNM".forEachIndexed { i, c -> put(c.toString(), 44 + i) }
(1..10).forEach { put("F$it", 58 + it) }
put("F11", 87); put("F12", 88)
putAll(mapOf(
"ESC" to 1, "MINUS" to 12, "EQUAL" to 13, "BACKSPACE" to 14, "TAB" to 15, "LEFTBRACE" to 26,
"RIGHTBRACE" to 27, "ENTER" to 28, "LEFTCTRL" to 29, "SEMICOLON" to 39, "APOSTROPHE" to 40,
"GRAVE" to 41, "LEFTSHIFT" to 42, "BACKSLASH" to 43, "COMMA" to 51, "DOT" to 52, "SLASH" to 53,
"RIGHTSHIFT" to 54, "LEFTALT" to 56, "SPACE" to 57, "CAPSLOCK" to 58, "RIGHTCTRL" to 97,
"RIGHTALT" to 100, "HOME" to 102, "UP" to 103, "PAGEUP" to 104, "LEFT" to 105, "RIGHT" to 106,
"END" to 107, "DOWN" to 108, "PAGEDOWN" to 109, "INSERT" to 110, "DELETE" to 111, "LEFTMETA" to 125,
"CTRL" to 29, "SHIFT" to 42, "ALT" to 56, "META" to 125, "SUPER" to 125, "RETURN" to 28, "ESCAPE" to 1,
))
}
/** US-layout characters as (evdev code, shift). */
private val TYPED: Map<Char, Pair<Int, Boolean>> = buildMap {
for (c in 'a'..'z') put(c, KEYS.getValue(c.uppercase()) to false)
for (c in 'A'..'Z') put(c, KEYS.getValue(c.toString()) to true)
for (c in '0'..'9') put(c, KEYS.getValue(c.toString()) to false)
"!@#$%^&*()".forEachIndexed { i, c -> put(c, KEYS.getValue(((i + 1) % 10).toString()) to true) }
putAll(mapOf(
' ' to (57 to false), '\n' to (28 to false), '\t' to (15 to false),
'-' to (12 to false), '_' to (12 to true), '=' to (13 to false), '+' to (13 to true),
'[' to (26 to false), '{' to (26 to true), ']' to (27 to false), '}' to (27 to true),
';' to (39 to false), ':' to (39 to true), '\'' to (40 to false), '"' to (40 to true),
'`' to (41 to false), '~' to (41 to true), '\\' to (43 to false), '|' to (43 to true),
',' to (51 to false), '<' to (51 to true), '.' to (52 to false), '>' to (52 to true),
'/' to (53 to false), '?' to (53 to true),
))
}
}
@@ -38,6 +38,10 @@ class AgentStartActivity : Activity() {
Log.e(TAG, "missing agent start request")
return null
}
if (encoded.length > AgentAccess.MAX_REQUEST_CHARS) {
Log.w(TAG, "agent start request is too large")
return null
}
return try {
JSONObject(String(Base64.decode(encoded, Base64.DEFAULT), Charsets.UTF_8))
} catch (e: Exception) {
@@ -47,6 +51,13 @@ class AgentStartActivity : Activity() {
}
private fun startSession(request: JSONObject) {
try {
AgentAccess.requireStart(this, request)
} catch (e: AgentException) {
Log.w(TAG, e.code)
finish()
return
}
val requestedMode = request.optString("mode")
val sessionMode = when (requestedMode) {
"steam" -> SessionService.MODE_STEAM
@@ -0,0 +1,157 @@
package com.droiddeck.launcher.agent
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.ViewGroup
import android.view.inspector.WindowInspector
import androidx.compose.ui.platform.ViewRootForTest
import androidx.compose.ui.semantics.SemanticsActions
import androidx.compose.ui.semantics.SemanticsConfiguration
import androidx.compose.ui.semantics.SemanticsNode
import androidx.compose.ui.semantics.SemanticsProperties
import androidx.compose.ui.semantics.getOrNull
import androidx.compose.ui.text.AnnotatedString
import org.json.JSONArray
import org.json.JSONObject
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
/**
* The app's own UI as an agent sees it: every Compose node in every window of the process (popups
* and menus included), read from Compose's semantics rather than through UI Automator, which on a
* dual-screen device dumps whichever window has focus - often not this app's. Nodes carry their
* test tag (ui/TestTags.kt), text, content description, role, state and on-screen bounds; click
* and set-text act on a node by tag or text, so a test needs no coordinates.
*/
object AgentUi {
private const val TIMEOUT_MS = 5_000L
/** Setup's Debugging tools toggle: the bridge never acts on its own gate (AgentAccess). */
private const val GATE_TAG = "setting-agent-commands"
fun handle(request: JSONObject): JSONObject = when (val op = request.optString("op", "dump")) {
"dump" -> onMain { dump(request.optBoolean("all")) }
"click" -> onMain { act(request) { node -> perform(node, SemanticsActions.OnClick) } }
"set-text" -> onMain {
val text = request.optString("text")
act(request) { node ->
node.config.getOrNull(SemanticsActions.SetText)?.action?.invoke(AnnotatedString(text))
?: throw AgentException("NOT_EDITABLE", "That node takes no text")
}
}
else -> throw AgentException("INVALID_REQUEST", "ui op '$op' is not dump, click or set-text")
}.put("ok", true).put("command", "ui")
private fun roots(): List<Pair<View, ViewRootForTest>> {
if (Build.VERSION.SDK_INT < 29) throw AgentException("UNSUPPORTED", "The UI dump needs Android 10 or later")
val found = mutableListOf<Pair<View, ViewRootForTest>>()
fun walk(view: View) {
if (view is ViewRootForTest) found += view to view
if (view is ViewGroup) for (i in 0 until view.childCount) walk(view.getChildAt(i))
}
WindowInspector.getGlobalWindowViews().filter { it.isAttachedToWindow && it.isShown }.forEach(::walk)
return found
}
private fun dump(all: Boolean): JSONObject {
val windows = JSONArray()
for ((view, root) in roots()) {
val nodes = JSONArray()
val location = IntArray(2).also { view.getLocationOnScreen(it) }
fun visit(node: SemanticsNode) {
val json = describe(node, location)
if (all || json.has("tag") || json.has("text") || json.has("description") || json.optBoolean("clickable")) nodes.put(json)
node.children.forEach(::visit)
}
visit(root.semanticsOwner.rootSemanticsNode)
windows.put(JSONObject()
.put("display", view.display?.displayId ?: JSONObject.NULL)
.put("window", view.rootView.javaClass.simpleName)
.put("nodes", nodes))
}
return JSONObject().put("windows", windows)
}
private fun describe(node: SemanticsNode, origin: IntArray): JSONObject {
val config = node.config
val json = JSONObject().put("id", node.id)
config.getOrNull(SemanticsProperties.TestTag)?.let { json.put("tag", it) }
val text = textFields(config)
text.keys().forEach { json.put(it, text.get(it)) }
config.getOrNull(SemanticsProperties.Role)?.let { json.put("role", it.toString()) }
config.getOrNull(SemanticsProperties.ToggleableState)?.let { json.put("toggle", it.name) }
config.getOrNull(SemanticsProperties.Selected)?.let { json.put("selected", it) }
config.getOrNull(SemanticsProperties.Focused)?.let { json.put("focused", it) }
if (config.contains(SemanticsProperties.Disabled)) json.put("disabled", true)
if (config.contains(SemanticsActions.OnClick)) json.put("clickable", true)
if (config.contains(SemanticsActions.SetText)) json.put("editable", true)
val b = node.boundsInWindow
json.put("bounds", JSONArray()
.put(origin[0] + b.left.toInt()).put(origin[1] + b.top.toInt())
.put(origin[0] + b.right.toInt()).put(origin[1] + b.bottom.toInt()))
return json
}
internal fun textFields(config: SemanticsConfiguration): JSONObject {
val password = config.contains(SemanticsProperties.Password)
val json = JSONObject()
for ((key, value) in listOf(
"text" to config.getOrNull(SemanticsProperties.Text)?.joinToString(" ") { it.text },
"editableText" to config.getOrNull(SemanticsProperties.EditableText)?.text,
"description" to config.getOrNull(SemanticsProperties.ContentDescription)?.joinToString(" "),
"state" to config.getOrNull(SemanticsProperties.StateDescription),
)) value?.let { json.put(key, if (password) "<redacted>" else it) }
return json
}
/**
* The node a request names by "tag" (exact) or "match" (text or description containing it,
* ignoring case); "index" picks among several, in tree order.
*/
private fun act(request: JSONObject, action: (SemanticsNode) -> Unit): JSONObject {
val tag = request.optString("tag").takeIf { it.isNotEmpty() }
val text = if (tag == null) request.optString("match").takeIf { it.isNotEmpty() } else null
if (tag == null && text == null) throw AgentException("INVALID_REQUEST", "Name the node by tag or match")
val matches = mutableListOf<Pair<SemanticsNode, IntArray>>()
for ((view, root) in roots()) {
val origin = IntArray(2).also { view.getLocationOnScreen(it) }
fun visit(node: SemanticsNode) {
val config = node.config
val hit = if (tag != null) config.getOrNull(SemanticsProperties.TestTag) == tag
else (config.getOrNull(SemanticsProperties.Text)?.joinToString(" ") { it.text }
?: config.getOrNull(SemanticsProperties.ContentDescription)?.joinToString(" ") ?: "")
.contains(text!!, ignoreCase = true)
if (hit) matches += node to origin
node.children.forEach(::visit)
}
visit(root.semanticsOwner.rootSemanticsNode)
}
val index = request.optInt("index", 0)
val (node, origin) = matches.getOrNull(index)
?: throw AgentException("NO_SUCH_NODE", "No node with ${if (tag != null) "tag '$tag'" else "text '$text'"} (${matches.size} found)")
if (generateSequence(node) { it.parent }.any { it.config.getOrNull(SemanticsProperties.TestTag) == GATE_TAG }) {
throw AgentException("PROTECTED_CONTROL", "Debugging tools are switched on the device only")
}
action(node)
return JSONObject().put("matches", matches.size).put("node", describe(node, origin))
}
private fun perform(node: SemanticsNode, key: androidx.compose.ui.semantics.SemanticsPropertyKey<androidx.compose.ui.semantics.AccessibilityAction<() -> Boolean>>) {
val action = node.config.getOrNull(key)?.action ?: throw AgentException("NOT_CLICKABLE", "That node has no click action")
action()
}
private fun <T> onMain(block: () -> T): T {
if (Looper.myLooper() == Looper.getMainLooper()) return block()
val result = AtomicReference<Result<T>>()
val done = CountDownLatch(1)
Handler(Looper.getMainLooper()).post {
result.set(runCatching(block))
done.countDown()
}
if (!done.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)) throw AgentException("TIMEOUT", "The UI thread did not answer")
return result.get().getOrThrow()
}
}
@@ -28,7 +28,9 @@ public class PulseAudioComponent extends SessionPart {
/** Where the guest reaches the daemon; the session exports PULSE_SERVER=unix:<this>. */
public static final String SOCKET_NAME = "PS0";
/** Identifies the bundled pulseaudio.tzst; a change here re-unpacks it over what a device has. */
private static final String BUNDLE_STAMP = "2026-09-23-pa13-suspend-r5";
private static final String BUNDLE_STAMP = "2026-10-08-pa13-directaudio-native";
private final File workingDir;
/** Where the daemon's own output is kept for this session, or null for logcat only. */
@@ -40,8 +42,6 @@ public class PulseAudioComponent extends SessionPart {
* turns that one stream into a source the client can see, named DirectAudioMic.
*/
private final String micFifoPath;
/** The DirectAudio relay's socket when the client's output should go through it, else null. */
private String relaySocketPath;
private volatile int pid = -1;
public PulseAudioComponent(Context context) {
@@ -54,15 +54,6 @@ public class PulseAudioComponent extends SessionPart {
this.micFifoPath = micFifoPath;
}
/**
* Route the daemon's output through the DirectAudio relay at this socket instead of an AAudio
* stream of its own. The relay owns the stream outside proot, with its adaptive buffer; the
* daemon only fills a shared ring. Set before {@link #start()}; the relay may start later.
*/
public void setRelaySocket(String path) {
this.relaySocketPath = path;
}
/** CRC-32 of the bundled pulseaudio.tzst, or "?" if it cannot be read. About 600 KB; cheap. */
private String bundleChecksum() {
java.util.zip.CRC32 crc = new java.util.zip.CRC32();
@@ -106,6 +97,7 @@ public class PulseAudioComponent extends SessionPart {
String have = FileUtils.readString(stamp);
String want = BUNDLE_STAMP + "-" + bundleChecksum();
if (!new File(modulesDir, "arm64/module-aaudio-sink.so").isFile()
|| !new File(modulesDir, "arm64/module-directaudio-native-sink.so").isFile()
|| !new File(workingDir, "pactl").isFile()
|| have == null || !want.equals(have.trim())) {
Log.i(TAG, "unpacking pulseaudio.tzst (" + want + "; had " + have + ")");
@@ -139,13 +131,15 @@ public class PulseAudioComponent extends SessionPart {
// the sink to 0% and the session plays silence.
// The sink's name is what the client's Audio settings show as the output device, so it
// says which road the sound takes.
if (relaySocketPath != null && !relaySocketPath.isEmpty()) {
config.add("load-module module-directaudio-sink sink_name=DirectAudio socket=\"" + relaySocketPath + "\" performance_mode=1 adaptive=1 volume=1.0");
config.add("set-default-sink DirectAudio");
} else {
config.add("load-module module-aaudio-sink sink_name=AAudioSink performance_mode=1 adaptive=1 volume=1.0");
config.add("set-default-sink AAudioSink");
}
// The client's sound: DirectAudio's own engine, in this process, one step from Android.
// decay=0: shrinking the device buffer after a quiet spell probes below what works and that
// probe is a click; the client plays menus. Between .nofail and .fail a module that cannot
// open its stream does not take the daemon down; ensureClientSink() then loads the plain
// AAudio sink in its place.
config.add(".nofail");
config.add("load-module module-directaudio-native-sink sink_name=DirectAudio performance_mode=1 adaptive=1 decay=0 limiter=1 watchdog=1 volume=1.0");
config.add("set-default-sink DirectAudio");
config.add(".fail");
if (micFifoPath != null && !micFifoPath.isEmpty()) {
// The format is the helper's, fixed at s16le/48000/mono: it resamples when the device
// grants another input rate, so the daemon is never told a rate the bytes are not.
@@ -177,6 +171,74 @@ public class PulseAudioComponent extends SessionPart {
Log.i(TAG, line);
if (out != null) synchronized (out) { out.println(line); out.flush(); }
});
Thread guard = new Thread(() -> ensureClientSink(out), "pulse-sink-guard");
guard.setDaemon(true);
guard.start();
}
/**
* The fallback: once the daemon answers, if the DirectAudio sink is not
* there (the module failed to load or to open its stream), load the plain AAudio sink so the
* client is never left without an output. Says so in the audio log either way.
*/
private void ensureClientSink(java.io.PrintWriter out) {
long deadline = System.currentTimeMillis() + 15000L;
String sinks = null;
while (System.currentTimeMillis() < deadline && pid > 1) {
if (socket().exists() && (sinks = pactl("list", "short", "sinks")) != null) break;
try { Thread.sleep(250L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
}
String line;
if (sinks == null) {
line = "== client sink: the daemon did not answer in 15 s; no fallback attempted";
} else if (sinks.contains("\tDirectAudio\t") || sinks.startsWith("DirectAudio\t") || sinks.contains("\tDirectAudio\n") || sinks.matches("(?s).*\\bDirectAudio\\b.*")) {
line = "== client sink: DirectAudio (module-directaudio-native-sink)";
} else {
boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0") != null
&& pactl("set-default-sink", "AAudioSink") != null;
line = loaded ? "== client sink: DirectAudio did not come up; FALLBACK to the plain AAudio sink (AAudioSink)"
: "== client sink: DirectAudio did not come up and the AAudio fallback failed too - no client sound";
Log.w(TAG, line);
}
Log.i(TAG, line);
if (out != null) synchronized (out) { out.println(line); out.flush(); }
}
/** 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;
java.lang.Process process = null;
try {
File modules = new File(workingDir, "modules/arm64");
ArrayList<String> cmd = new ArrayList<>();
cmd.add(pactl.getAbsolutePath());
java.util.Collections.addAll(cmd, args);
ProcessBuilder builder = new ProcessBuilder(cmd);
builder.directory(workingDir);
builder.redirectErrorStream(true);
builder.environment().put("LD_LIBRARY_PATH", "/system/lib64:" + modules + ":" + workingDir);
builder.environment().put("HOME", workingDir.getAbsolutePath());
builder.environment().put("TMPDIR", workingDir.getAbsolutePath());
builder.environment().put("PULSE_SERVER", "unix:" + socket().getAbsolutePath());
process = builder.start();
String output;
try (InputStream in = process.getInputStream()) {
output = new String(in.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8);
}
if (!process.waitFor(5, TimeUnit.SECONDS)) {
process.destroyForcibly();
return null;
}
return process.exitValue() == 0 ? output : null;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return null;
} catch (Exception e) {
return null;
} finally {
if (process != null && process.isAlive()) process.destroyForcibly();
}
}
@Override
@@ -167,7 +167,6 @@ object DeviceReport {
k("Guest host name", SessionPrefs.guestHostname(context))
k("DirectAudio for games", SessionPrefs.directAudio(context))
k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context))
k("Client audio", if (SessionPrefs.clientDirectAudio(context)) "DirectAudio" else "classic")
k("Microphone", SessionPrefs.micEnabled(context))
k("On-screen controls", SessionPrefs.oscMode(context))
k("Touch mode", SessionPrefs.touchMode(context))
@@ -40,7 +40,7 @@ object HostProcess {
if (onLine == null) builder.redirectOutput(File("/dev/null"))
val process = builder.start()
val pid = pidOf(process)
Log.i(TAG, "started pid $pid: $command")
Log.i(TAG, "started pid $pid: ${argv.first()} (${argv.size - 1} arguments)")
if (onLine != null) {
Thread({
try {
@@ -59,7 +59,7 @@ object HostProcess {
}
pid
} catch (e: Exception) {
Log.e(TAG, "could not start: $command", e)
Log.e(TAG, "could not start: ${argv.first()}", e)
-1
}
}
@@ -60,6 +60,15 @@ object LogRedactor {
private val IPV4 = Regex("(?<![0-9.])(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})(?![0-9.])")
/** An IPv6 literal: "::" somewhere, or all eight groups (a clock's 10:03:05 is neither). */
private val IPV6 = Regex("(?<![0-9A-Za-z:])[0-9A-Fa-f]{0,4}(?::[0-9A-Fa-f]{0,4}){2,7}(?:%[A-Za-z0-9_.]+)?(?![0-9A-Za-z:])")
private val MAC = Regex("(?i)(?<![0-9a-z:-])[0-9a-f]{2}([:-])(?:[0-9a-f]{2}\\1){4}[0-9a-f]{2}(?![0-9a-z:-])")
private val MAC_FIELD = Regex(
"(?i)(\\bmac(?:[_ ]?address)?[\"']?\\s*[:=]\\s*[\"']?)[0-9a-f]{2}([:-])" +
"(?:[0-9a-f]{2}\\2){4}[0-9a-f]{2}(?![0-9a-z:-])"
)
private val DEVICE_IDENTIFIER = Regex(
"(?i)(\\b(?:android[_ ]?id|(?:device|controller)[_ ]?serial|serial(?:[_ ]?number)?|build\\.serial)" +
"[\"']?\\s*[:=]\\s*)(\"[^\"\\r\\n<>]+\"|'[^'\\r\\n<>]+'|[^\\s\"'<>&;,\\[\\]{}]+)"
)
/**
* The account a Steam UI login line names ("Login: OnLoginStateChange <account> 2 1 0 0"): a
@@ -196,7 +205,7 @@ object LogRedactor {
* only when that matches, so a folder scrubbed under older rules is scrubbed again on the way
* out.
*/
const val RULES_VERSION = 1
const val RULES_VERSION = 2
/** [src]'s lines, scrubbed, to [out]. */
fun scrubTo(src: java.io.File, out: java.io.Writer) {
@@ -208,6 +217,13 @@ object LogRedactor {
if (line.isEmpty()) return line
return try {
var out = line
out = MAC_FIELD.replace(out) { "${it.groupValues[1]}<redacted:mac>" }
out = MAC.replace(out, "<redacted:mac>")
out = DEVICE_IDENTIFIER.replace(out) {
val value = it.groupValues[2]
val quote = value.first().takeIf { char -> char == '\"' || char == '\'' }?.toString().orEmpty()
"${it.groupValues[1]}${quote}<redacted:serial>${quote}"
}
out = GUID.replace(out, "<redacted:guid>")
out = JWT_LABELLED.replace(out) { "${it.groupValues[1]}<redacted:jwt>" }
out = JWT_BASE64.replace(out, "<redacted:jwt>")
@@ -0,0 +1,13 @@
package com.droiddeck.launcher.input
object InputSpace {
const val WIDTH = 1920
const val HEIGHT = 1080
fun x(position: Float, viewWidth: Int): Int = scale(position, viewWidth, WIDTH)
fun y(position: Float, viewHeight: Int): Int = scale(position, viewHeight, HEIGHT)
private fun scale(position: Float, extent: Int, size: Int): Int =
if (extent <= 0) 0 else (position / extent * size).toInt().coerceIn(0, size - 1)
}
@@ -93,9 +93,10 @@ object FlatpakManager {
return GuestCommand.run(context, argv, fakeRoot, name, onLine = onLine)
}
private inline fun <T> exclusive(what: String, block: () -> T): T? {
/** [block]'s result, or [ifBusy]'s while another operation has the installation. */
private inline fun <T> exclusive(what: String, ifBusy: () -> T, block: () -> T): T {
synchronized(this) {
if (busy != null) return null
if (busy != null) return ifBusy()
busy = what
}
try { return block() } finally { busy = null }
@@ -104,7 +105,7 @@ object FlatpakManager {
/** Puts Flatpak into the runtime and adds Flathub. Null on success, else what went wrong. */
fun setup(context: Context, onProgress: (String, Int) -> Unit): String? {
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
return exclusive("setup") {
return exclusive("setup", { context.getString(R.string.flatpakmgr_busy) }) {
var failure: String? = null
val status = runGuest(context, listOf("/bin/bash", SETUP), fakeRoot = true) { line ->
Log.i(TAG, "setup: $line")
@@ -119,16 +120,18 @@ object FlatpakManager {
!ready(context) -> context.getString(R.string.flatpakmgr_setup_unfinished)
else -> null
}
} ?: context.getString(R.string.flatpakmgr_busy)
}
}
/**
* One store operation - install, uninstall or update - with its progress as a stage line and
* an overall percentage across the steps Flatpak plans (a runtime, its extensions, the app).
*/
private fun transaction(context: Context, verb: String, id: String?, onProgress: (String, Int) -> Unit): String? {
private fun transaction(
context: Context, verb: String, id: String?, onProgress: (String, Int) -> Unit, onDone: (JSONObject) -> Unit = {},
): String? {
if (!ready(context)) return context.getString(R.string.flatpakmgr_not_ready)
return exclusive("$verb:${id ?: "all"}") {
return exclusive("$verb:${id ?: "all"}", { context.getString(R.string.flatpakmgr_busy) }) {
var error: String? = null
// Progress lines carry no ref; they belong to the step the last "op" line started.
var step = context.getString(R.string.flatpakmgr_starting)
@@ -141,10 +144,11 @@ object FlatpakManager {
"progress" -> onProgress(step, overall(o, o.optInt("percent")))
"error" -> { error = o.optString("message"); Log.w(TAG, "$verb $id: $error") }
"warning" -> Log.w(TAG, "$verb $id: ${o.optString("message")}")
"done" -> onDone(o)
}
}
error ?: if (status != 0) context.getString(R.string.flatpakmgr_exit_status, status) else null
} ?: context.getString(R.string.flatpakmgr_busy)
}
}
private fun stage(context: Context, o: JSONObject): String {
@@ -195,13 +199,20 @@ object FlatpakManager {
fun install(context: Context, id: String, onProgress: (String, Int) -> Unit) = transaction(context, "install", id, onProgress)
fun uninstall(context: Context, id: String, onProgress: (String, Int) -> Unit) = transaction(context, "uninstall", id, onProgress)
/** Installs the .flatpak bundle at [guestPath], its runtimes from Flathub: the app's ID, and what went wrong if anything. */
fun installBundle(context: Context, guestPath: String, onProgress: (String, Int) -> Unit): Pair<String?, String?> {
var id: String? = null
val problem = transaction(context, "install-bundle", guestPath, onProgress) { id = it.optString("id").ifEmpty { null } }
return id to problem
}
fun update(context: Context, id: String?, onProgress: (String, Int) -> Unit) = transaction(context, "update", id, onProgress)
/** Installed apps with an update on Flathub, or null when that could not be checked. */
fun updates(context: Context): Set<String>? {
if (!ready(context)) return emptySet()
var apps: Set<String>? = null
exclusive("updates") {
exclusive("updates", {}) {
runGuest(context, listOf("/usr/bin/python3", HELPER, "updates"), fakeRoot = false) { line ->
val o = runCatching { JSONObject(line) }.getOrNull() ?: return@runGuest
if (o.optString("e") == "updates") {
@@ -69,6 +69,7 @@ object UserApps {
class AppImage(val file: File) : Source()
class GitHub(val repo: String) : Source()
class Flatpak(val id: String) : Source()
class FlatpakBundle(val file: File) : Source()
}
/** [icon]: a picked file's path or a suggested icon's URL. */
@@ -124,6 +125,7 @@ object UserApps {
is Source.AppImage -> AppImageManager.import(context, s.file, name, icon) { onProgress(it, -1) }
is Source.GitHub -> addFromGitHub(context, s.repo, name, icon, onProgress)
is Source.Flatpak -> addFlatpak(context, s.id, name, icon, onProgress)
is Source.FlatpakBundle -> addFlatpakBundle(context, s.file, name, icon, onProgress)
}
}
}
@@ -422,9 +424,36 @@ object UserApps {
private fun addFlatpak(context: Context, id: String, name: String?, icon: File?, onProgress: (String, Int) -> Unit): String? {
if (!FlatpakManager.ready(context)) FlatpakManager.setup(context, onProgress)?.let { return it }
FlatpakManager.install(context, id, onProgress)?.let { return it }
val custom = overrides(context, id)
if (name != null) FileUtils.writeString(File(custom.apply { mkdirs() }, "name"), name)
if (icon != null && !saveIcon(icon, File(custom, "icon.png"))) Log.w(TAG, "icon ${icon.path} could not be read")
customiseFlatpak(context, id, name, icon)
return null
}
private fun addFlatpakBundle(context: Context, file: File, name: String?, icon: File?, onProgress: (String, Int) -> Unit): String? {
if (!file.isFile) return context.getString(R.string.user_apps_file_gone)
if (!FlatpakManager.ready(context)) FlatpakManager.setup(context, onProgress)?.let { return it }
// Shared storage is bound into the runtime at its own path; a file anywhere else is copied in.
val shared = Environment.getExternalStorageDirectory().canonicalPath
val copy = File(LinuxRuntime.rootDir(context), "tmp/droiddeck-bundle.flatpak").takeIf { !file.canonicalPath.startsWith("$shared/") }
try {
if (copy != null) {
onProgress(context.getString(R.string.user_apps_copying, file.name), -1)
file.copyTo(copy.apply { parentFile?.mkdirs() }, overwrite = true)
}
val (id, problem) = FlatpakManager.installBundle(context, copy?.let { "/tmp/${it.name}" } ?: file.canonicalPath, onProgress)
problem?.let { return it }
if (id != null) customiseFlatpak(context, id, name, icon)
return null
} catch (e: Exception) {
Log.e(TAG, "bundle ${file.path}", e)
return e.message ?: context.getString(R.string.user_apps_failed)
} finally {
copy?.delete()
}
}
private fun customiseFlatpak(context: Context, id: String, name: String?, icon: File?) {
val custom = overrides(context, id)
if (name != null) FileUtils.writeString(File(custom.apply { mkdirs() }, "name"), name)
if (icon != null && !saveIcon(icon, File(custom.apply { mkdirs() }, "icon.png"))) Log.w(TAG, "icon ${icon.path} could not be read")
}
}
@@ -16,6 +16,8 @@ object SessionFiles {
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
/** Where the DirectAudio driver lives inside the runtime; the wrappers get it as BL_DIRECTAUDIO. */
const val DIRECTAUDIO_DIR = "usr/local/lib/directaudio"
/** The driver sets staged under it: classic Wine 11 (Valve, GE) and the system-thread interface (Proton-CachyOS). */
val DIRECTAUDIO_SETS = arrayOf("linux-wine11", "linux-wine11-systhread")
/**
* The libraries and scripts the session runs, refreshed from the apk at every launch.
@@ -41,6 +43,8 @@ object SessionFiles {
"libblfastpath.so" to "usr/local/lib/libblfastpath.so",
"libssbs.so" to "usr/local/lib/libssbs.so",
"usr/local/bin/droiddeck-session" to "usr/local/bin/droiddeck-session",
"usr/local/bin/droiddeck-fonts" to "usr/local/bin/droiddeck-fonts",
"usr/local/bin/droiddeck-agent" to "usr/local/bin/droiddeck-agent",
"usr/local/bin/steam-compatibility" to "usr/local/bin/steam-compatibility",
"usr/local/bin/droiddeck-clipboard" to "usr/local/bin/droiddeck-clipboard",
"usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install",
@@ -150,30 +154,37 @@ object SessionFiles {
ComponentsManager.migrateLaunchDir(context)
EsyncPacks.stageBundled(context, root)
// The DirectAudio driver for games under Proton: the glibc build of winedirectaudio, which
// the Proton wrappers add to WINEDLLPATH when the session asks for it (BL_DIRECTAUDIO).
// Staged like the scripts, so a driver fix reaches an installed runtime without re-hosting.
// the Proton wrappers add to WINEDLLPATH when the session asks for it (BL_DIRECTAUDIO). Two
// sets, one per Wine audio interface - the wrapper picks by what the Proton's own winepulse.so
// imports (see steam-compatibility), because both Wines call themselves 11.0 and the wrong set
// plays silence. Staged like the scripts, so a driver fix reaches an installed runtime without
// re-hosting. The sets come from the pinned DirectAudio release (tools/directaudio/release.env).
val directAudio = arrayOf(
"aarch64-unix/winedirectaudio.so",
"aarch64-windows/winedirectaudio.drv",
"i386-windows/winedirectaudio.drv",
"version.txt",
)
for (relative in directAudio) {
val target = File(root, "$DIRECTAUDIO_DIR/lib/wine/$relative")
for (set in DIRECTAUDIO_SETS) for (relative in directAudio) {
val target = File(root, "$DIRECTAUDIO_DIR/$set/lib/wine/$relative")
val staged = File(target.parentFile, target.name + ".staged")
var installed = false
try {
target.parentFile?.mkdirs()
context.assets.open("directaudio/linux-wine11/$relative").use { input ->
context.assets.open("directaudio/$set/$relative").use { input ->
staged.outputStream().use { output -> FileUtils.copy(input, output) }
}
installed = staged.setReadable(true, false) && staged.renameTo(target)
} catch (e: Exception) {
Log.w(TAG, "could not stage DirectAudio $relative", e)
Log.w(TAG, "could not stage DirectAudio $set/$relative", e)
} finally {
if (!installed) staged.delete()
}
if (!installed) Log.e(TAG, "DirectAudio $relative NOT staged")
if (!installed) Log.e(TAG, "DirectAudio $set/$relative NOT staged")
}
// A runtime from before the sets had names kept the driver at the directory's root; it would
// never be picked again, so it goes.
for (old in arrayOf("aarch64-unix", "aarch64-windows", "i386-windows")) File(root, "$DIRECTAUDIO_DIR/lib/wine/$old").deleteRecursively()
// What every process in the session preloads. LD_PRELOAD in the environment would not
// survive: the Steam client rebuilds it for each process it starts and appends its own
// overlay entry without a separator, which silently drops whatever was there.
@@ -169,15 +169,9 @@ object SessionPrefs {
prefs(context).edit().putStringSet("gpuAutoInstalled", ids.toSet()).apply()
}
/**
* The Steam client's own sound through the DirectAudio relay instead of the classic AAudio
* sink. On unless the user picked Classic.
*/
fun clientDirectAudio(context: Context): Boolean = prefs(context).getBoolean("clientDirectAudio", true)
fun setClientDirectAudio(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("clientDirectAudio", on).apply()
}
// The Steam client's own sound has one route now: DirectAudio's engine inside the PulseAudio
// daemon (PulseAudioComponent), one step from Android. The old "clientDirectAudio" boolean
// (which meant the relay route, one hop more) is no longer read.
fun stretch16x9(context: Context): Boolean = prefs(context).getBoolean("stretch16x9", false)
@@ -293,7 +293,7 @@ class SessionService : Service() {
val lines = FileUtils.readString(file)?.lines().orEmpty()
.map { it.trim() }
.filter { it.isNotEmpty() && !it.startsWith("#") && it.contains('=') && !it.startsWith("=") }
if (lines.isNotEmpty()) Log.i(TAG, "extra environment from ${file.path}: $lines")
if (lines.isNotEmpty()) Log.i(TAG, "extra environment keys from ${file.path}: ${lines.map { it.substringBefore('=') }}")
return lines
}
@@ -324,6 +324,7 @@ class SessionService : Service() {
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
killStragglers()
SessionFiles.stage(this, root)
com.droiddeck.launcher.agent.AgentGuest.reset(this)
val sessionDir = openSessionFolder()
val sessionLog = File(sessionDir, "session.log")
@@ -423,7 +424,7 @@ class SessionService : Service() {
}
guest.add(program)
guest.addAll(SessionState.programArgs)
Log.i(TAG, "run: $program ${SessionState.programArgs.joinToString(" ")} under gamescope")
Log.i(TAG, "run: $program (${SessionState.programArgs.size} arguments) under gamescope")
}
// Android has no /dev/shm; the cache stands in for it and, unlike the real thing, keeps
@@ -659,6 +660,8 @@ class SessionService : Service() {
// (ZINK_DESCRIPTORS=lazy, MESA_*), gamescope's, the client's - whatever the experiment
// needs, without a build per attempt.
extraEnv().forEach { guest.add(it) }
// The agent bridge's experiment lines (AgentEnv), after the user's so an agent's win.
com.droiddeck.launcher.agent.AgentEnv.beginSession(this).forEach { guest.add(it) }
// Core masks, Bannerlator's two (cfca3912). The client's is sent whenever the override is
// on, even naming every core: it exists to undo the pin Steam applies to its own interface
// renderer, and the scheduler's default is exactly what that pin takes away. A game's is
@@ -691,16 +694,13 @@ class SessionService : Service() {
val audioLog = File(sessionDir, "audio.log")
val pulse = PulseAudioComponent(this, micFifo?.absolutePath)
// With DirectAudio on, the client's own sound goes through the relay too: the daemon
// fills the relay's ring and the relay, outside proot, drives the device.
// The client's own sound: the classic AAudio sink unless the user chose the relay.
val clientDirectAudio = SessionState.mode == MODE_STEAM && SessionPrefs.clientDirectAudio(this)
if (clientDirectAudio) pulse.setRelaySocket(relaySocket.absolutePath)
// The client's own sound: DirectAudio's engine inside the daemon, one step from Android (the
// daemon runs on the Android side). The relay below is for games and the microphone only.
pulse.setLogFile(audioLog)
pulse.attach(this)
guest.add("PULSE_SERVER=unix:" + pulse.socket().absolutePath)
components.add(pulse)
if (wantsDirectAudio || wantsMic || clientDirectAudio) {
if (wantsDirectAudio || wantsMic) {
// After the daemon in the list, so it can wait for the pipe the daemon makes.
val relay = DirectAudioRelayComponent(relaySocket, micFifo)
relay.setLogFile(audioLog)
@@ -714,7 +714,7 @@ class SessionService : Service() {
guest.add("BL_DIRECTAUDIO=/" + SessionFiles.DIRECTAUDIO_DIR)
guest.add("BANNER_AUDIO_DIRECT_RELAY=" + relaySocket.absolutePath)
}
Log.i(TAG, "audio: client " + (if (clientDirectAudio) "DirectAudio" else "classic AAudio sink") + (if (wantsDirectAudio) " + DirectAudio for games" else "")
Log.i(TAG, "audio: client DirectAudio (in-process sink)" + (if (wantsDirectAudio) " + DirectAudio for games" else "")
+ (if (wantsMic) " + microphone" else "") +
(if (SessionPrefs.micEnabled(this) && !wantsMic) " (microphone wanted but RECORD_AUDIO not granted)" else ""))
return pulse
@@ -1410,6 +1410,9 @@ class SessionService : Service() {
SessionState.pipActive = false
pipTask = false
SessionState.guestPid = -1
com.droiddeck.launcher.agent.AgentGuest.stop()
runCatching { com.droiddeck.launcher.agent.AgentEnv.endSession(this) }
.onFailure { Log.w(TAG, "clearing the agent's session environment", it) }
releaseLocks()
if (status == 0) {
SessionEvents.transition(SessionPhase.IDLE, "session.stopped", mapOf("status" to status))
@@ -80,6 +80,9 @@ object SessionState {
/** Told (on the thread that changed it) whenever [deckPad] changes. */
@Volatile var deckPadListener: (() -> Unit)? = null
/** The session screen's virtual pad, for the agent bridge's pad input (AgentInput). */
@Volatile var padBridge: com.droiddeck.launcher.input.PadBridge? = null
/** What the second screen shows, and on which display: kept for the session, so a screen
* turned off (sleep, a closed lid) or an activity recreated brings it back as it was. */
@Volatile var secondScreenMode = com.droiddeck.launcher.input.SecondScreenMode.NONE
@@ -124,6 +124,7 @@ internal fun AddAppDialog(runtimeReady: Boolean, onDismiss: () -> Unit, onAdd: (
var imagePath by rememberSaveable { mutableStateOf<String?>(null) }
var repo by rememberSaveable { mutableStateOf("") }
var flatpak by rememberSaveable { mutableStateOf("") }
var bundlePath by rememberSaveable { mutableStateOf<String?>(null) }
var name by rememberSaveable { mutableStateOf("") }
var iconPath by rememberSaveable { mutableStateOf<String?>(null) }
@@ -133,6 +134,9 @@ internal fun AddAppDialog(runtimeReady: Boolean, onDismiss: () -> Unit, onAdd: (
val pickImage = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == Activity.RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { imagePath = it.path }
}
val pickBundle = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == Activity.RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { bundlePath = it.path; flatpak = "" }
}
val pickIcon = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == Activity.RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { iconPath = it.path }
}
@@ -146,7 +150,9 @@ internal fun AddAppDialog(runtimeReady: Boolean, onDismiss: () -> Unit, onAdd: (
AddSource.APPIMAGE -> imagePath?.takeIf { it.endsWith(".appimage", ignoreCase = true) }?.let { File(it) }
?.let { UserApps.Request(UserApps.Source.AppImage(it), custom, iconPath) to (custom ?: it.nameWithoutExtension) }
AddSource.GITHUB -> repoId?.let { UserApps.Request(UserApps.Source.GitHub(it), custom, iconPath) to (custom ?: it) }
AddSource.FLATPAK -> flatpakId?.let { UserApps.Request(UserApps.Source.Flatpak(it), custom, iconPath) to (custom ?: it) }
AddSource.FLATPAK -> bundlePath?.takeIf { it.endsWith(".flatpak", ignoreCase = true) }?.let { File(it) }
?.let { UserApps.Request(UserApps.Source.FlatpakBundle(it), custom, iconPath) to (custom ?: it.nameWithoutExtension) }
?: flatpakId?.let { UserApps.Request(UserApps.Source.Flatpak(it), custom, iconPath) to (custom ?: it) }
}
val busy = UserAppsState.working
val tabFocus = remember { AddSource.entries.map { FocusRequester() } }
@@ -192,11 +198,17 @@ internal fun AddAppDialog(runtimeReady: Boolean, onDismiss: () -> Unit, onAdd: (
stringResource(R.string.add_app_repository_placeholder),
stringResource(R.string.add_app_repository_invalid).takeIf { repo.isNotBlank() && repoId == null },
)
AddSource.FLATPAK -> CheckedField(
flatpak, { flatpak = it.take(200) }, stringResource(R.string.add_app_flatpak_id),
stringResource(R.string.add_app_flatpak_placeholder),
stringResource(R.string.add_app_flatpak_invalid).takeIf { flatpak.isNotBlank() && flatpakId == null },
)
AddSource.FLATPAK -> {
CheckedField(
flatpak, { flatpak = it.take(200); bundlePath = null }, stringResource(R.string.add_app_flatpak_id),
stringResource(R.string.add_app_flatpak_placeholder),
stringResource(R.string.add_app_flatpak_invalid).takeIf { flatpak.isNotBlank() && flatpakId == null },
)
Small(stringResource(R.string.add_app_flatpak_bundle_hint))
FileRow(bundlePath) {
pickBundle.launch(InAppFilePicker.buildIntent(ctx, listOf("flatpak"), ctx.getString(R.string.add_app_pick_flatpak)))
}
}
}
}
}
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.platform.testTag
import com.droiddeck.launcher.R
import androidx.compose.ui.res.stringResource
import androidx.compose.foundation.LocalIndication
@@ -71,7 +72,7 @@ internal fun GamesPage(s: FrontEndState, a: FrontEndActions, selected: String, o
Rise(0) { PageHeader(stringResource(R.string.content_games)) }
Rise(1) { Note(stringResource(if (s.shortcutPicker && s.shortcutLibraryScanning) R.string.game_shortcut_scanning else R.string.games_empty)) }
if (!s.shortcutPicker) Rise(2) {
Actions { PrimaryButton(stringResource(R.string.games_play_steam), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = Modifier.padding(top = 12.dp), onClick = a.onPlay) }
Actions { PrimaryButton(stringResource(R.string.games_play_steam), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = Modifier.padding(top = 12.dp).testTag("play-steam"), onClick = a.onPlay) }
}
GameFileFolderActions(s, a)
}
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.platform.testTag
import com.droiddeck.launcher.R
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.focus.focusRequester
@@ -162,6 +163,7 @@ private fun RailItem(
contentAlignment = Alignment.Center,
modifier = Modifier
.then(if (frontFocus != null) Modifier.focusRequester(frontFocus.railFor(key)) else Modifier)
.testTag("rail-$key")
.graphicsLayer { scaleX = scale; scaleY = scale }
.size(width = if (iconOnly) 52.dp else 80.dp, height = height)
.clip(Shape14)
@@ -91,6 +91,8 @@ class FrontEndState(
val frameGenLabel: String,
val romsDir: String?,
val logsEnabled: Boolean,
/** Setup's Debugging tools toggle (AgentAccess): off unless the user turns it on. */
val agentCommands: Boolean = false,
val steamGames: List<Library.SteamGame>,
val emulators: List<Library.Emulator>,
val running: String?,
@@ -166,6 +168,7 @@ class FrontEndActions(
val onFiles: () -> Unit,
val onBrowseFiles: (File) -> Unit = {},
val onLogs: () -> Unit,
val onAgentCommands: () -> Unit = {},
val onShareLogs: () -> Unit = {},
val onClearLogs: () -> Unit = {},
val onOffline: () -> Unit,
@@ -307,6 +307,7 @@ internal fun SetupPanel(
}
}
ToggleRow(host, "logs", stringResource(R.string.setup_logs), stringResource(R.string.setup_logs_hint), s.logsEnabled) { a.onLogs() }
ToggleRow(host, "agent-commands", stringResource(R.string.setup_agent_commands), null, s.agentCommands) { a.onAgentCommands() }
ActionRow(stringResource(R.string.setup_latest_logs), stringResource(R.string.drawer_logs_hint), stringResource(R.string.drawer_share_logs), a.onShareLogs,
progress = com.droiddeck.launcher.session.SessionLogShare.progress)
ActionRow(stringResource(R.string.setup_saved_logs), stringResource(R.string.setup_saved_logs_hint, com.droiddeck.launcher.session.SessionPaths.KEEP_SESSIONS), stringResource(R.string.setup_clear_logs), a.onClearLogs)
@@ -75,7 +75,6 @@ class ModeSettings(
/** Steam only: whether single and double Back actions are swapped. */
val backActionsInverted: Boolean = false,
val directAudio: Boolean?,
val clientDirectAudio: Boolean = true,
val mic: Boolean?,
val renderer: String?,
val gameStorage: String? = null,
@@ -140,7 +139,6 @@ class ModeSettingsActions(
val onOsc: (String) -> Unit,
val onBackActionsInverted: (Boolean) -> Unit = {},
val onDirectAudio: (Boolean) -> Unit,
val onClientDirectAudio: (Boolean) -> Unit = {},
val onMic: (Boolean) -> Unit,
val onRenderer: (String) -> Unit,
val onGameStorage: (path: String, label: String) -> Unit = { _, _ -> },
@@ -486,11 +484,6 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
}
if (steam && tab == ModeSettingsTab.AUDIO && s.directAudio != null && s.mic != null) SettingsGroup(stringResource(R.string.mode_audio)) {
ToggleRow(host, "da", stringResource(R.string.mode_directaudio), stringResource(R.string.mode_directaudio_hint), s.directAudio, onChange = a.onDirectAudio)
ChoiceRow(
host, "clientAudio", stringResource(R.string.mode_client_audio), stringResource(R.string.mode_client_audio_hint),
listOf("classic" to stringResource(R.string.mode_client_audio_classic), "directaudio" to stringResource(R.string.mode_client_audio_direct)), if (s.clientDirectAudio) "directaudio" else "classic",
onPick = { id -> a.onClientDirectAudio(id == "directaudio") },
)
ToggleRow(host, "mic", stringResource(R.string.mode_mic), stringResource(R.string.mode_mic_hint), s.mic, onChange = a.onMic)
}
if (steam && tab == ModeSettingsTab.GAMES && s.gameStorage != null) SettingsGroup(stringResource(R.string.mode_storage)) {
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.draw.alpha
import androidx.compose.animation.core.Animatable
import androidx.compose.foundation.Canvas
@@ -315,7 +316,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
modifier = Modifier.fillMaxSize()
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { host.open = null; a.onClose() },
)
androidx.compose.foundation.layout.BoxWithConstraints(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.CenterEnd) {
androidx.compose.foundation.layout.BoxWithConstraints(modifier = Modifier.fillMaxSize().exposeTestTags(), contentAlignment = Alignment.CenterEnd) {
// A 4:3 or near-square screen (under 440dp tall) gets tighter padding and a shorter tab row,
// so the settings keep most of the height; a narrow one keeps some of the game in view.
val short = maxHeight < 440.dp
@@ -634,7 +635,7 @@ private fun StopSessionButton(modifier: Modifier = Modifier, onClick: () -> Unit
val stopDescription = stringResource(R.string.stop_session)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = modifier.heightIn(min = 44.dp).semantics { contentDescription = stopDescription }
modifier = modifier.heightIn(min = 44.dp).semantics { contentDescription = stopDescription }.testTag("drawer-stop")
.clip(shape).background(fill).glideBorder(hot, shape, colors.error.copy(alpha = 0.9f), colors.error.copy(alpha = 0.55f))
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick)
.controllerConfirm(onClick = onClick)
@@ -745,6 +746,7 @@ private fun DrawerPageTabs(page: SessionDrawerPage, pages: List<SessionDrawerPag
)
.glideBorder(focused, RoundedCornerShape(16.dp), colors.onBackground)
.semantics { contentDescription = pageDescription }
.testTag("drawer-tab-${item.name.lowercase()}")
.hoverable(source)
.clickable(interactionSource = source, indication = LocalIndication.current, onClick = select)
.controllerConfirm(onClick = select),
@@ -1185,14 +1187,14 @@ private fun StopConfirm(
ConfirmChoice(
stringResource(R.string.common_cancel), danger = false, enabled = open,
modifier = Modifier.graphicsLayer { alpha = items[1].value; translationY = (1f - items[1].value) * 6.dp.toPx() }
.focusRequester(cancelFocus).onFocusChanged { cancelFocused = it.isFocused },
.focusRequester(cancelFocus).onFocusChanged { cancelFocused = it.isFocused }.testTag("drawer-stop-cancel"),
onClick = onCancel,
)
ConfirmChoice(
stringResource(R.string.drawer_stop), danger = true, enabled = open,
modifier = Modifier.graphicsLayer { alpha = items[2].value; translationY = (1f - items[2].value) * 6.dp.toPx() }
.onFocusChanged { stopFocused = it.isFocused }
.onGloballyPositioned { stopCoords = it },
.onGloballyPositioned { stopCoords = it }.testTag("drawer-stop-confirm"),
) {
val at = IntArray(2).also { view.rootView.getLocationOnScreen(it) }
onStop(stopCoords?.takeIf { it.isAttached }?.boundsInWindow()?.translate(at[0].toFloat(), at[1].toFloat()))
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.platform.testTag
import com.droiddeck.launcher.R
import androidx.compose.ui.res.stringResource
import android.view.KeyEvent
@@ -186,6 +187,7 @@ internal fun TabStrip(
color = if (on) pal.onSignal else if (hot) colors.onBackground else colors.onSurfaceVariant,
modifier = Modifier
.bringIntoViewRequester(reveal)
.testTag("tab-$i")
.then(focusRequesters?.getOrNull(i)?.let { Modifier.focusRequester(it) } ?: Modifier)
.clip(tabShape)
.background(if (on) pal.signal else if (hot) pal.signal.copy(alpha = 0.16f) else Color.Transparent)
@@ -456,7 +458,7 @@ fun <T> ChoiceRow(
val open = host.open == key
SettingsRow(label, hint, highlighted = open, hintLines = hintLines) {
Box {
ValueChip(options.firstOrNull { it.first == selected }?.second ?: "-", open, enabled, modifier = chipModifier) { host.open = if (open) null else key }
ValueChip(options.firstOrNull { it.first == selected }?.second ?: "-", open, enabled, modifier = chipModifier.testTag("setting-$key")) { host.open = if (open) null else key }
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) { firstItemFocus ->
options.forEachIndexed { index, (value, text) ->
MenuItem(text, checked = value == selected, focusRequester = if (index == 0) firstItemFocus else null) {
@@ -472,7 +474,7 @@ fun <T> ChoiceRow(
@Composable
fun ToggleRow(host: MenuHost, key: String, label: String, hint: String?, checked: Boolean, enabled: Boolean = true, chipModifier: Modifier = Modifier, onChange: (Boolean) -> Unit) =
SettingsRow(label, hint) {
ToggleSwitch(checked, enabled, label, chipModifier) { host.open = null; onChange(it) }
ToggleSwitch(checked, enabled, label, chipModifier.testTag("setting-$key")) { host.open = null; onChange(it) }
}
/** An on/off switch: one tap or one A press flips it, where a menu of On and Off took three. */
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.platform.testTag
import com.droiddeck.launcher.R
import androidx.compose.ui.res.stringResource
import androidx.compose.animation.core.FastOutSlowInEasing
@@ -91,7 +92,7 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
Spacer(Modifier.height(18.dp))
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
// Enabled without a runtime: the session's loading screen installs it first.
PrimaryButton(stringResource(R.string.games_play_steam), enabled = !s.busy, main = true, large = true, icon = Icons.Filled.PlayArrow, onClick = a.onPlay)
PrimaryButton(stringResource(R.string.games_play_steam), enabled = !s.busy, main = true, large = true, icon = Icons.Filled.PlayArrow, modifier = Modifier.testTag("play-steam"), onClick = a.onPlay)
Cog(size = 54.dp, onClick = a.onSteamSettings)
}
}
@@ -0,0 +1,14 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTagsAsResourceId
/**
* Compose test tags as Android resource ids below this node, so UI Automator (`uiautomator dump`,
* droiddeckctl ui-dump) sees stable ids such as `rail-steam` or `setting-logs` rather than only
* labels that change with the language. Tags are named in docs/agent-control.md.
*/
@OptIn(ExperimentalComposeUiApi::class)
fun Modifier.exposeTestTags(): Modifier = semantics { testTagsAsResourceId = true }
+6 -9
View File
@@ -79,7 +79,7 @@
<string name="game_env_no_fsync">Pon 1 para que este juego no use droiddeck-fsync; usa droiddeck-esync si hay un paquete y, si no, droiddeck-ntsync.</string>
<string name="game_env_fsync_first">Pon 1 para que este juego use droiddeck-fsync, o 0 para dar prioridad a droiddeck-esync cuando haya un paquete para su Proton.</string>
<string name="game_env_xalia">Pon 0 para desactivar el asistente de navegación con mando de Proton en este juego.</string>
<string name="game_env_hud">Overlay de DXVK para D3D9–11. fps muestra la tasa de fotogramas; sin definir la oculta.</string>
<string name="game_env_hud">Superposición de DXVK para D3D9–11. fps muestra la tasa de fotogramas; sin definir la oculta.</string>
<string name="game_env_dxvk_config">Ajustes de DXVK separados por punto y coma. Las versiones recientes usan dxvk.maxFrameRate para limitar fotogramas; para el uso normal prefiere el límite de fotogramas de la sesión.</string>
<string name="game_env_vkd3d_limit">Límite de fotogramas de D3D12. 0 desactiva el límite.</string>
<string name="game_env_glthread">Subprocesos de OpenGL de Mesa. true puede ayudar a juegos OpenGL limitados por la CPU; pruébalo en cada juego.</string>
@@ -287,7 +287,7 @@
<string name="mode_client">Cliente</string>
<string name="mode_deck_mode">Modo Steam Deck</string>
<string name="mode_deck_mode_hint">La interfaz Deck de Steam y los controles de rendimiento de Quick Access. Se aplica en la próxima sesión.</string>
<string name="mode_mangoapp">Overlay de rendimiento</string>
<string name="mode_mangoapp">Superposición de rendimiento</string>
<string name="mode_mangoapp_hint">Desactívalo si los juegos fallan o se quedan en negro en modo Deck. Se aplica en la próxima sesión.</string>
<string name="mode_branch">Rama del cliente</string>
<string name="mode_branch_deck">Beta pública de Steam Deck (requerida por el modo Deck).</string>
@@ -337,20 +337,16 @@
<string name="mode_audio">Audio</string>
<string name="mode_directaudio">DirectAudio para juegos</string>
<string name="mode_directaudio_hint">Evita PulseAudio para menor latencia.</string>
<string name="mode_client_audio">Audio del cliente de Steam</string>
<string name="mode_client_audio_hint">Se aplica en la próxima sesión.</string>
<string name="mode_client_audio_classic">Clásico</string>
<string name="mode_client_audio_direct">DirectAudio</string>
<string name="mode_mic">Micrófono</string>
<string name="mode_mic_hint">Para el chat de voz.</string>
<string name="mode_network">Red</string>
<string name="mode_wifi_discovery">Detección de Wi-Fi</string>
<string name="mode_wifi_discovery">Detección de redes Wi-Fi</string>
<string name="mode_wifi_discovery_hint">Muestra en Steam los nombres de Wi-Fi y las redes cercanas.</string>
<string name="mode_wifi_location_off">Los servicios de ubicación están desactivados.</string>
<string name="mode_wifi_permission_denied">No se concedió el permiso de ubicación.</string>
<string name="mode_wifi_open_settings">Abrir ajustes</string>
<string name="mode_wifi_continue">Continuar</string>
<string name="mode_wifi_explain_title">¿Activar la detección de Wi-Fi?</string>
<string name="mode_wifi_explain_title">¿Activar la detección de redes Wi-Fi?</string>
<string name="mode_wifi_explain_text">Android exige el permiso de ubicación para leer los nombres de Wi-Fi y detectar redes cercanas. DroidDeck usa este acceso para mostrar esas redes en Steam. No rastreamos tu ubicación. El acceso a internet funciona sin este permiso.</string>
<string name="mode_storage">Almacenamiento de juegos</string>
<string name="mode_storage_auto">Automático - la tarjeta SD si está presente, y tus carpetas de juegos</string>
@@ -392,7 +388,7 @@
<string name="comp_display_driver_hint">Dibuja los fotogramas en pantalla en ambos modos. Reinicia la app para aplicarlo.</string>
<string name="comp_import_adrenotools">Importar un zip de AdrenoTools…</string>
<string name="comp_never">nunca</string>
<string name="comp_nightlies_checked">Nightlies comprobadas %1$s</string>
<string name="comp_nightlies_checked">Última comprobación de Nightlies: %1$s</string>
<string name="comp_title">Componentes</string>
<string name="comp_about">Acerca de Componentes</string>
<string name="comp_check_drivers">Buscar controladores nuevos</string>
@@ -613,6 +609,7 @@
<string name="setup_session">Sesión</string>
<string name="setup_logs">Registros de sesión</string>
<string name="setup_logs_hint">Se guardan tras cada sesión</string>
<string name="setup_agent_commands">Herramientas de depuración</string>
<string name="setup_latest_logs">Últimos registros de sesión</string>
<string name="setup_saved_logs">Registros de sesión guardados</string>
<string name="setup_saved_logs_hint">Conserva los %1$d más recientes</string>
+1 -4
View File
@@ -284,10 +284,6 @@
<string name="mode_audio">Audio</string>
<string name="mode_directaudio">Utiliser DirectAudio pour le jeu</string>
<string name="mode_directaudio_hint">Contourne PulseAudio pour réduire la latence.</string>
<string name="mode_client_audio">Audio du client Steam</string>
<string name="mode_client_audio_hint">Prendra effet à la prochaine session.</string>
<string name="mode_client_audio_classic">Classique</string>
<string name="mode_client_audio_direct">DirectAudio</string>
<string name="mode_mic">Microphone</string>
<string name="mode_mic_hint">Utilisé pour le chat vocal.</string>
<string name="mode_network">Réseau</string>
@@ -514,6 +510,7 @@
<string name="setup_session">Session</string>
<string name="setup_logs">Journaux de session</string>
<string name="setup_logs_hint">Enregistré après chaque fin de session</string>
<string name="setup_agent_commands">Outils de débogage</string>
<string name="setup_latest_logs">Derniers journaux de session</string>
<string name="setup_saved_logs">Journaux de session enregistrés</string>
<string name="setup_saved_logs_hint">Conserver les %1$d plus récents</string>
+3 -6
View File
@@ -278,12 +278,12 @@
<string name="mode_decky_installed">インストール済み · %1$s</string>
<string name="mode_decky_update">アップデートあり · %1$s</string>
<string name="mode_decky_current">最新です · %1$s</string>
<string name="mode_decky_loader">ローダー</string>
<string name="mode_decky_loader">Loader</string>
<string name="mode_decky_install_latest">最新バージョンをインストール</string>
<string name="mode_decky_on">Steamと共に起動します。有効にすると、このデバイス上の他のアプリがSteamを制御できる場合があります。</string>
<string name="mode_decky_off">オフ。Steamのリモートデバッグポートは閉じたままになります。</string>
<string name="mode_decky_remove_title">Decky Loaderをアンインストールしますか?</string>
<string name="mode_decky_remove_text">ローダーを削除します。プラグインと設定は保持されます。</string>
<string name="mode_decky_remove_text">Loaderを削除します。プラグインと設定は保持されます。</string>
<string name="mode_client">クライアント</string>
<string name="mode_deck_mode">Steam Deckモード</string>
<string name="mode_deck_mode_hint">Steam DeckのUIとクイックアクセスパフォーマンスコントロール。次回のセッションで有効になります。</string>
@@ -337,10 +337,6 @@
<string name="mode_audio">オーディオ</string>
<string name="mode_directaudio">ゲームでDirectAudioを使用</string>
<string name="mode_directaudio_hint">PulseAudioをバイパスして遅延を減らします。</string>
<string name="mode_client_audio">Steamクライアントオーディオ</string>
<string name="mode_client_audio_hint">次回のセッションで有効になります。</string>
<string name="mode_client_audio_classic">クラシック</string>
<string name="mode_client_audio_direct">DirectAudio</string>
<string name="mode_mic">マイク</string>
<string name="mode_mic_hint">ボイスチャットに使用します。</string>
<string name="mode_network">ネットワーク</string>
@@ -611,6 +607,7 @@
<string name="setup_session">セッション</string>
<string name="setup_logs">セッションログ</string>
<string name="setup_logs_hint">各セッション終了後に保存</string>
<string name="setup_agent_commands">デバッグツール</string>
<string name="setup_latest_logs">最新のセッションログ</string>
<string name="setup_saved_logs">保存されたセッションログ</string>
<string name="setup_saved_logs_hint">最新の%1$d件を保持</string>
+1 -4
View File
@@ -337,10 +337,6 @@
<string name="mode_audio">오디오</string>
<string name="mode_directaudio">게임에서 DirectAudio 사용</string>
<string name="mode_directaudio_hint">PulseAudio를 우회하여 지연 시간을 줄입니다.</string>
<string name="mode_client_audio">Steam 클라이언트 오디오</string>
<string name="mode_client_audio_hint">다음 세션에 적용됩니다.</string>
<string name="mode_client_audio_classic">클래식</string>
<string name="mode_client_audio_direct">DirectAudio</string>
<string name="mode_mic">마이크</string>
<string name="mode_mic_hint">음성 채팅에 사용됩니다.</string>
<string name="mode_network">네트워크</string>
@@ -611,6 +607,7 @@
<string name="setup_session">세션</string>
<string name="setup_logs">세션 로그</string>
<string name="setup_logs_hint">각 세션 종료 후 저장</string>
<string name="setup_agent_commands">디버깅 도구</string>
<string name="setup_latest_logs">최신 세션 로그</string>
<string name="setup_saved_logs">저장된 세션 로그</string>
<string name="setup_saved_logs_hint">최신 %1$d개 유지</string>
+247 -151
View File
@@ -4,31 +4,31 @@
<string-array name="loading_hints">
<item>При первом запуске будет загружен Steam. Это может занять несколько минут.</item>
<item>По умолчанию при выходе из приложения Steam приостанавливается; при возвращении работа возобновляется с того же места.</item>
<item>Ваш контроллер будет отображаться как геймпад Xbox 360. В противном случае используйте экранные элементы управления.</item>
<item>Ваш контроллер отображается как геймпад Xbox 360. Если контроллера нет, используйте экранные элементы управления.</item>
</string-array>
<string-array name="loading_hints_desktop">
<item>При первом запуске будет настроен рабочий стол. Это может занять несколько минут.</item>
<item>По умолчанию при выходе из приложения сессия приостанавливается; при возвращении работа возобновляется с того же места.</item>
<item>Сенсорный ввод работает как тачпад: перетаскивайте для перемещения курсора, нажимайте для клика.</item>
<item>Ваш контроллер будет отображаться как геймпад Xbox 360. В противном случае используйте экранные элементы управления.</item>
<item>Ваш контроллер отображается как геймпад Xbox 360. Если контроллера нет, используйте экранные элементы управления.</item>
</string-array>
<string name="session_channel">Сессия</string>
<string name="session_channel_description">Отображается при открытии сессии Steam или рабочего стола</string>
<string name="session_channel_description">Отображается, пока открыта сессия Steam или рабочего стола</string>
<string name="session_notification">Steam запущен</string>
<string name="session_notification_paused">Сессия приостановлена - нажмите, чтобы продолжить</string>
<string name="session_notification_paused">Сессия приостановлена — нажмите «Продолжить»</string>
<string name="resume_session">Продолжить</string>
<string name="stop_session">Завершить сессию</string>
<string name="stop_session">Остановить сессию</string>
<string name="frame_gen_title">Генерация кадров</string>
<string name="frame_gen_hint">Выберите режим генерации кадров</string>
<string name="frame_gen_off">Выкл.</string>
<string name="frame_gen_winfg">Win-FG %1$d×</string>
<string name="frame_gen_lsfg">LSFG %1$d×</string>
<string name="frame_gen_lsfg_adaptive">LSFG Адаптивный %1$d</string>
<string name="frame_gen_lsfg_adaptive">LSFG Adaptive %1$d</string>
<string name="lsfg_needs_steam">Требуется Lossless Scaling из Steam</string>
<string name="lsfg_needs_install">Установите Lossless Scaling в Steam или импортируйте Lossless.dll</string>
<string name="lsfg_import">Импорт Lossless.dll…</string>
<string name="lsfg_using_steam">Используется версия из Steam</string>
<string name="lsfg_using_import">Используется импортированная версия</string>
<string name="lsfg_using_steam">Используется копия из Steam</string>
<string name="lsfg_using_import">Используется импортированная копия</string>
<string name="lsfg_pick_title">Выберите файл Lossless.dll</string>
<string name="lsfg_imported">Lossless.dll импортирован</string>
<string name="lsfg_import_unchanged">Этот Lossless.dll уже используется</string>
@@ -36,14 +36,14 @@
<string name="lsfg_import_invalid">Этот файл не является Lossless.dll от Lossless Scaling</string>
<string name="lsfg_import_failed">Не удалось подготовить LSFG из этого Lossless.dll</string>
<string name="lsfg_problem_missing">Для LSFG требуется Lossless Scaling из Steam или импортированный файл Lossless.dll</string>
<string name="lsfg_problem_failed">LSFG не может подготовить свои шейдеры из этого Lossless.dll</string>
<string name="lsfg_problem_failed">LSFG не удалось подготовить шейдеры из Lossless.dll</string>
<string name="hud_fg_unsupported">%1$s: не поддерживается</string>
<string name="hud_fg_failed">%1$s: сбой движка</string>
<string name="hud_fg_needs_lossless">%1$s: требуется Lossless Scaling</string>
<string name="hud_fg_starting">%1$s %2$s · Запуск</string>
<string name="added_games_import_hint">Папка, содержащая несколько подпапок, каждая из которых соответствует игре Windows. Игры, которыми вы владеете в Steam, будут использовать соответствующие записи Steam после перезапуска Steam, остальные игры станут ярлыками, отличными от Steam. Если для параметра «Вторая библиотека» выбрано «Авто», Steam также может устанавливать игры в эту папку.</string>
<string name="second_library_import_hint">Добавьте библиотеку Steam и отсканируйте в ней игры Windows. Имеющиеся игры будут использовать соответствующие записи Steam, остальные станут ярлыками, отличными от Steam.</string>
<string name="added_games_forget_hint">«Забыть» удалит эти ярлыки в следующей сессии. Но файлы останутся на диске.</string>
<string name="hud_fg_starting">%1$s %2$s · запуск</string>
<string name="added_games_import_hint">Папка, где каждая подпапка — отдельная игра для Windows. Игры из вашей библиотеки Steam после перезапуска Steam используют свои записи, остальные добавляются как ярлыки сторонних игр. Если для параметра «Вторая библиотека» выбрано «Авто», Steam также может устанавливать игры в эту папку.</string>
<string name="second_library_import_hint">Добавляет библиотеку Steam и ищет в ней игры для Windows. Игры из вашей библиотеки Steam используют свои записи Steam, остальные добавляются как ярлыки сторонних игр.</string>
<string name="added_games_forget_hint">«Забыть» удалит ярлыки в следующей сессии. Файлы останутся на диске.</string>
<string name="game_env_title">Игровая среда</string>
<string name="game_env_hint">Переменные среды для игр Proton.</string>
<string name="game_env_edit">Изменить</string>
@@ -59,7 +59,7 @@
<string name="game_env_remove">Удалить</string>
<string name="game_env_restore">Восстановить наследование</string>
<string name="game_env_reset">Сбросить профиль</string>
<string name="game_env_unset">Снять настройку для профиля</string>
<string name="game_env_unset">Не задавать в этом профиле</string>
<string name="game_env_empty">Переменные не заданы.</string>
<string name="game_env_inherited">Унаследовано</string>
<string name="game_env_custom">Пользовательская переменная</string>
@@ -71,19 +71,29 @@
<string name="game_env_shader">Переопределение модели шейдеров D3D12. 6_9 требует достаточно нового VKD3D и соответствующих функций GPU. Оставьте пустым для автоопределения.</string>
<string name="game_env_cache">Поддерживать кэш шейдеров Mesa включенным для уменьшения повторной компиляции. Установите false, чтобы включить кэш.</string>
<string name="game_env_cache_size">Максимальный размер кэша шейдеров Mesa, например 1G. Больший кэш занимает больше места.</string>
<string name="game_env_vkd3d_config">Параметры VKD3D для D3D12. nodxr отключает трассировку лучей; используйте только при необходимости в игре.</string>
<string name="game_env_vkd3d_config">Параметры VKD3D для D3D12. nodxr отключает трассировку лучей; используйте только для игры, которой это нужно.</string>
<string name="game_env_proton_log">Установите 1 для создания диагностического журнала Proton. Ведение журнала может снизить производительность и занять место.</string>
<string name="game_env_wined3d">Установите 1, чтобы использовать WineD3D на базе OpenGL вместо DXVK для тестирования совместимости с D3D9–11.</string>
<string name="game_env_no_ntsync">Установите 1, чтобы не использовать ntsync (droiddeck-ntsync или драйвер ядра) для этой игры; тогда используется droiddeck-esync, если есть пакет, иначе droiddeck-fsync.</string>
<string name="game_env_no_esync">Установите 1, чтобы отключить droiddeck-esync для этой игры; вместо него используется droiddeck-fsync или droiddeck-ntsync, если fsync тоже отключен.</string>
<string name="game_env_no_fsync">Установите 1, чтобы не использовать droiddeck-fsync для этой игры; тогда используется droiddeck-esync, если есть пакет, иначе droiddeck-ntsync.</string>
<string name="game_env_fsync_first">Установите 1, чтобы запускать эту игру на droiddeck-fsync, или 0, чтобы ставить droiddeck-esync первым, когда для ее Proton есть пакет.</string>
<string name="game_env_xalia">Установите 0, чтобы отключить помощник навигации геймпада Proton для этой игры.</string>
<string name="game_env_hud">Оверлей DXVK для D3D9–11. fps показывает частоту кадров; снимите настройку, чтобы скрыть оверлей.</string>
<string name="game_env_hud">Оверлей DXVK для D3D9–11. fps показывает частоту кадров; если не задано — оверлей скрыт.</string>
<string name="game_env_dxvk_config">Настройки DXVK, разделенные точкой с запятой. В последних версиях используется dxvk.maxFrameRate для ограничения частоты кадров; для повседневной игры рекомендуется использовать ограничитель частоты кадров сессии.</string>
<string name="game_env_vkd3d_limit">Ограничение частоты кадров D3D12. 0 отключает ограничение.</string>
<string name="game_env_glthread">Многопоточность Mesa OpenGL. Для игр OpenGL с ограничением CPU значение true может помочь; тестируйте отдельно для каждой игры.</string>
<string name="fex_preset_title">Пресеты FEX</string>
<string name="sync_backend_title">Синхронизация Wine</string>
<string name="sync_backend_hint">Как игры синхронизируют свои потоки. Вступит в силу в следующей сессии.</string>
<string name="sync_backend_esync">esync</string>
<string name="sync_backend_ntsync">ntsync</string>
<string name="sync_backend_fsync">fsync</string>
<string name="sync_backend_wineserver">wineserver</string>
<string name="fex_preset_title">Пресет FEX</string>
<string name="fex_next_launch">Вступит в силу при следующем запуске игры.</string>
<string name="game_settings_title">Игра</string>
<string name="game_settings_title">Игры</string>
<string name="fex_default_label">FEX по умолчанию</string>
<string name="fex_default_detail">Использовать настройки FEX по умолчанию.</string>
<string name="fex_default_detail">Настройки FEX по умолчанию.</string>
<string name="fex_stability_label">Стабильность</string>
<string name="fex_stability_detail">Самые безопасные и медленные настройки.</string>
<string name="fex_compatibility_label">Совместимость</string>
@@ -91,17 +101,17 @@
<string name="fex_intermediate_label">Средний</string>
<string name="fex_intermediate_detail">Сбалансированные настройки TSO со сниженной точностью x87.</string>
<string name="fex_performance_label">Производительность</string>
<string name="fex_performance_detail">Отключить все TSO; включить multiblock.</string>
<string name="fex_performance_detail">Весь TSO отключен; multiblock.</string>
<string name="fex_performance_tso_label">Производительность + TSO</string>
<string name="fex_performance_tso_detail">Настройки производительности с включенным основным TSO.</string>
<string name="fex_extreme_label">Экстрим</string>
<string name="fex_extreme_detail">Отключить проверку самомодифицирующегося кода. Игры JIT и DRM могут не работать.</string>
<string name="fex_extreme_detail">Отключает проверки самомодифицирующегося кода. Игры с JIT и DRM могут сломаться.</string>
<string name="fex_extreme_tso_label">Экстрим + TSO</string>
<string name="fex_extreme_tso_detail">Настройки экстрим с включенным основным TSO.</string>
<string name="fex_extreme_gn_label">Экстрим-gn</string>
<string name="fex_extreme_gn_detail">Настройки производительности с включенными TSC и подсказками метаданных. Рекомендуется сначала попробовать этот режим, а затем «Экстрим».</string>
<string name="fex_denuvo_label">Denuvo</string>
<string name="fex_denuvo_detail">Настройки производительности с включенной полной проверкой кода и скрытием битов гипервизора.</string>
<string name="fex_denuvo_detail">Настройки производительности с полной проверкой кода и скрытым битом гипервизора.</string>
<string name="game_env_custom_value">Пользовательское значение</string>
<string name="game_env_select_value">Выберите значение</string>
<string name="user_apps_section">Эмуляторы и приложения</string>
@@ -113,14 +123,14 @@
<string name="user_apps_progress">%1$s · %2$s</string>
<string name="user_apps_progress_percent">%1$s · %2$s · %3$d%%</string>
<string name="user_apps_starting">Запуск…</string>
<string name="user_apps_added">%1$s добавлено</string>
<string name="user_apps_removed">%1$s удалено</string>
<string name="user_apps_added">Добавлено: %1$s</string>
<string name="user_apps_removed">Удалено: %1$s</string>
<string name="user_apps_back">Рабочий стол</string>
<string name="user_apps_gone">Приложение не существует. Выберите его заново на рабочем столе.</string>
<string name="user_apps_gone">Это приложение больше недоступно. Выберите его заново на рабочем столе.</string>
<string name="user_apps_open">Открыть %1$s</string>
<string name="user_apps_remove">Удалить</string>
<string name="user_apps_remove_confirm">Нажмите еще раз для удаления</string>
<string name="user_apps_stop_session">Сначала завершите сессию</string>
<string name="user_apps_stop_session">Чтобы удалить, остановите сессию</string>
<string name="user_apps_script_linked">Запускает %1$s из своей папки и связывает эту папку с сессией. Удаление приложения не повлияет на папку.</string>
<string name="user_apps_script_copied">Запускает %1$s из папки, скопированной в DroidDeck. Удаление приложения удалит копию, но не оригинал.</string>
<string name="user_apps_runtime_required">Сначала установите среду выполнения Linux</string>
@@ -130,18 +140,18 @@
<string name="user_apps_failed">Ошибка добавления приложения</string>
<string name="user_apps_github_checking">Поиск выпусков %1$s</string>
<string name="user_apps_github_unreachable">Не удалось прочитать выпуски %1$s</string>
<string name="user_apps_github_no_appimage">%1$s не предоставляет выпуск ARM64 AppImage</string>
<string name="user_apps_github_no_appimage">Ни в одном выпуске %1$s нет AppImage для ARM64 или x86_64</string>
<string name="user_apps_downloading">Загрузка %1$s</string>
<string name="user_apps_download_failed">Ошибка загрузки</string>
<string name="user_apps_update_failed">Ошибка обновления приложения</string>
<string name="user_apps_icon_failed">Не удалось прочитать иконку</string>
<string name="user_apps_saved">%1$s сохранено</string>
<string name="user_apps_saved">Сохранено: %1$s</string>
<string name="user_apps_edit">Изменить</string>
<string name="user_apps_check_updates">Проверить обновления</string>
<string name="user_apps_checking_updates">Проверка обновлений…</string>
<string name="user_apps_update_to">Обновить до %1$s</string>
<string name="user_apps_up_to_date">Актуально · %1$s</string>
<string name="user_apps_updated">%1$s обновлено</string>
<string name="user_apps_updated">Обновлено: %1$s</string>
<string name="user_apps_github_version">%1$s · %2$s</string>
<string name="add_app_title">Добавить приложение</string>
<string name="add_app_tab_script">Скрипт</string>
@@ -149,9 +159,18 @@
<string name="add_app_tab_github">GitHub</string>
<string name="add_app_tab_flatpak">Flatpak</string>
<string name="add_app_script_hint">Файл .sh. Запускается из своей папки и отображается в полноэкранном режиме через gamescope.</string>
<string name="add_app_appimage_hint">ARM64 (aarch64) AppImage. Распаковывается в среду выполнения Linux при первом использовании.</string>
<string name="add_app_github_hint">Установить ARM64 AppImage из последнего выпуска репозитория.</string>
<string name="add_app_flatpak_hint">ID приложения Flathub или его страница Flathub. Если Flatpak не настроен, он будет настроен сначала.</string>
<string name="add_app_appimage_hint">AppImage для ARM64 (aarch64) или для x86_64 — тогда он работает через FEX. Распаковывается в среду выполнения Linux один раз.</string>
<string name="add_app_github_hint">Устанавливает ARM64 AppImage из последнего выпуска репозитория или x86_64-версию через FEX.</string>
<string name="app_fex_title">Использовать FEX</string>
<string name="app_fex_auto">Авто</string>
<string name="app_fex_on">Вкл.</string>
<string name="app_fex_off">Выкл.</string>
<string name="app_fex_hint">FEX запускает x86-программы Linux на этом ARM64-устройстве. «Авто» использует его, если программа собрана для x86.</string>
<string name="app_fex_x86">%1$s через FEX</string>
<string name="app_fex_not_ready">Эта программа собрана для ПК на %1$s и работает через FEX, который еще не настроен. Откройте Steam один раз, войдя в аккаунт: DroidDeck скачает через него FEX и нужную Steam Linux Runtime, после чего программа откроется.</string>
<string name="session_end_program">Эта программа</string>
<string name="session_end_fex_missing">%1$s — сборка для x86-ПК, которая работает через FEX, а он еще не установлен. Запустите Steam один раз, войдя в аккаунт, и дайте ему скачать FEX и Steam Linux Runtime, затем запустите программу снова.</string>
<string name="add_app_flatpak_hint">ID приложения Flathub или ссылка на его страницу. Если Flatpak еще не настроен, сначала будет выполнена его настройка.</string>
<string name="add_app_file">Файл</string>
<string name="add_app_no_file">Файл не выбран</string>
<string name="add_app_choose_file">Выбрать файл</string>
@@ -166,7 +185,7 @@
<string name="add_app_flatpak_placeholder">org.ppsspp.PPSSPP</string>
<string name="add_app_flatpak_invalid">Недействительный ID приложения Flathub</string>
<string name="add_app_source">Источник</string>
<string name="add_app_appearance">Показывать на рабочем столе</string>
<string name="add_app_appearance">На рабочем столе</string>
<string name="add_app_preview_name">Новое приложение</string>
<string name="add_app_name">Название</string>
<string name="add_app_name_placeholder">Из приложения</string>
@@ -184,8 +203,11 @@
<string name="add_app_folder_copied">Эта папка содержит программы Linux, которые не могут работать из общего хранилища, поэтому она будет скопирована в DroidDeck (%1$s).</string>
<string name="add_app_confirm">Добавить</string>
<string name="add_app_cancel">Отмена</string>
<string name="add_app_runtime_required">Сначала установите среду выполнения Linux в «Настройках».</string>
<string name="add_app_runtime_required">Сначала установите среду выполнения Linux на странице «Настройка».</string>
<string name="add_app_busy">Подождите, пока завершится %1$s.</string>
<string name="steam_compat_label">Совместимо</string>
<string name="proton_compatible_note">Сборки с пометкой «%1$s» в меню совместимости Steam содержат исправления префикса от DroidDeck и запускают игры здесь. По умолчанию используется Proton Experimental ARM64 (%1$s) или Proton 11.0 ARM64 (%1$s), когда эта более новая сборка установлена. Собственные записи Proton от Valve без пометки не могут запустить игру на этом устройстве.</string>
<string name="proton_installed_compatible">Установлено %1$s · %2$s</string>
<string name="common_cancel">Отмена</string>
<string name="common_auto">Авто</string>
<string name="common_never">Никогда</string>
@@ -197,7 +219,7 @@
<string name="common_working">Обработка…</string>
<string name="common_forget">Забыть</string>
<string name="common_add_ellipsis">Добавить…</string>
<string name="common_use">Использовать</string>
<string name="common_use">Применить</string>
<string name="common_applies_next_session">Вступит в силу в следующей сессии.</string>
<string name="mode_steam_title">Сессия Steam</string>
<string name="mode_desktop_title">Сессия рабочего стола</string>
@@ -208,14 +230,14 @@
<string name="mode_res_1080">До 1080p</string>
<string name="mode_res_native">Нативное</string>
<string name="mode_res_default">%1$s (по умолчанию)</string>
<string name="mode_res_custom_value">Пользовательское · %1$d×%2$d</string>
<string name="mode_res_custom">Пользовательское…</string>
<string name="mode_res_custom_value">Свое · %1$d×%2$d</string>
<string name="mode_res_custom">Свое…</string>
<string name="mode_res_note">720p может ускорить отклик меню.</string>
<string name="mode_ratio">Соотношение сторон</string>
<string name="mode_ratio_custom">Задается пользовательским разрешением.</string>
<string name="mode_ratio_auto">Автоматический режим использует не менее 16:9.</string>
<string name="mode_fps">Ограничение частоты кадров</string>
<string name="mode_fps_note">Ограничивает частоту кадров всей сессии. Монитор переключится на частоту обновления, кратную этому пределу.</string>
<string name="mode_fps_note">Ограничивает частоту кадров всей сессии. Экран переключится на частоту обновления, кратную этому пределу.</string>
<string name="mode_hdr">HDR</string>
<string name="mode_hdr10">Вывод HDR10</string>
<string name="mode_hdr_unavailable">Недоступно: %1$s.</string>
@@ -224,7 +246,7 @@
<string name="mode_gpu_drivers">Драйверы GPU</string>
<string name="mode_gpu_drivers_hint">Общие для Steam и рабочего стола. Настройте на странице «Компоненты».</string>
<string name="mode_touch_controls">Сенсорный ввод и управление</string>
<string name="mode_touch">Сенсорный</string>
<string name="mode_touch">Сенсорный ввод</string>
<string name="mode_touch_touchpad">Тачпад</string>
<string name="mode_touch_direct">Прямой</string>
<string name="mode_touch_note">Авто: тачпад для рабочего стола, прямой сенсорный ввод для Steam.</string>
@@ -241,7 +263,9 @@
<string name="mode_suspend">Поведение в фоне</string>
<string name="mode_suspend_hint">Поведение при скрытии приложения или выключении экрана.</string>
<string name="mode_suspend_manual">Вручную</string>
<string name="mode_suspend_note">Автоматический режим приостанавливает работу в фоне и возобновляет при отображении. Ручной режим требует нажатия «Продолжить». Никогда не остается запущенным.</string>
<string name="mode_suspend_native">Штатный</string>
<string name="mode_suspend_steam_note">Авто: пауза и возобновление при показе. Штатный: сначала подготавливает Steam к переходу в режим сна. Вручную: ждет нажатия «Продолжить». Никогда: сессия продолжает работать.</string>
<string name="mode_suspend_note">Авто: пауза в фоне и возобновление при показе. Вручную: ждет нажатия «Продолжить». Никогда: сессия продолжает работать.</string>
<string name="mode_startup">Запуск</string>
<string name="mode_steam_startup">Запускать Steam при открытии DroidDeck</string>
<string name="mode_steam_startup_hint">Открывает сессию Steam при запуске DroidDeck.</string>
@@ -253,8 +277,8 @@
<string name="mode_decky_update">Доступно обновление · %1$s</string>
<string name="mode_decky_current">Актуально · %1$s</string>
<string name="mode_decky_loader">Загрузчик</string>
<string name="mode_decky_install_latest">Установить последнюю версию</string>
<string name="mode_decky_on">Запускается вместе со Steam. После включения другие приложения на этом устройстве могут управлять Steam.</string>
<string name="mode_decky_install_latest">Установить последнюю</string>
<string name="mode_decky_on">Запускается вместе со Steam. Пока включено, другие приложения на этом устройстве могут управлять Steam.</string>
<string name="mode_decky_off">Выкл. Порт удаленной отладки Steam остается закрытым.</string>
<string name="mode_decky_remove_title">Удалить Decky Loader?</string>
<string name="mode_decky_remove_text">Удаляет загрузчик. Ваши плагины и настройки сохранятся.</string>
@@ -262,37 +286,37 @@
<string name="mode_deck_mode">Режим Steam Deck</string>
<string name="mode_deck_mode_hint">Интерфейс Steam Deck и управление производительностью через быстрый доступ. Вступит в силу в следующей сессии.</string>
<string name="mode_mangoapp">Оверлей производительности</string>
<string name="mode_mangoapp_hint">Отключите, если игры падают или появляется черный экран в режиме Deck. Вступит в силу в следующей сессии.</string>
<string name="mode_mangoapp_hint">Отключите, если игры вылетают или показывают черный экран в режиме Deck. Вступит в силу в следующей сессии.</string>
<string name="mode_branch">Ветка клиента</string>
<string name="mode_branch_deck">Бета-версия Steam Deck (требуется для режима Deck).</string>
<string name="mode_branch_deck">Публичная бета Steam Deck (требуется для режима Deck).</string>
<string name="mode_branch_hint">Вступит в силу в следующей сессии. Steam может обновиться самостоятельно один раз.</string>
<string name="mode_branch_public">Бета</string>
<string name="mode_branch_deck_beta">Бета-версия Steam Deck</string>
<string name="mode_branch_note">Режим Deck всегда использует бета-версию Steam Deck.</string>
<string name="mode_branch_public">Публичная бета</string>
<string name="mode_branch_deck_beta">Публичная бета Steam Deck</string>
<string name="mode_branch_note">Режим Deck всегда использует публичную бету Steam Deck.</string>
<string name="mode_steam_repair">Восстановить клиент Steam</string>
<string name="mode_steam_repair_hint">При следующем запуске Steam клиент будет скачан заново. Используйте, если Steam зависает на экране загрузки. Игры, вход и настройки сохраняются.</string>
<string name="mode_steam_repair_queued">Клиент Steam будет скачан заново при следующем запуске Steam.</string>
<string name="mode_steam_repair_button">Восстановить</string>
<string name="mode_added_games">Добавленные игры</string>
<string name="mode_added_none">Папки с играми .exe не найдены</string>
<string name="mode_added_none">папок с играми (.exe) не найдено</string>
<string name="mode_games_folder">Папка с играми</string>
<string name="mode_games_folder_another">Другая папка с играми</string>
<string name="mode_added_art">Изображения из Steam</string>
<string name="mode_added_art">Обложки из Steam</string>
<string name="mode_added_art_hint">Дополняет отсутствующие изображения по имени папки. Файлы cover.jpg, hero.jpg, logo.png или icon.png в папке с игрой имеют приоритет.</string>
<string name="mode_added_launches">Запустить %1$s</string>
<string name="mode_added_launches_in">Запустить %1$s · в %2$s</string>
<string name="mode_added_launches">Запускает %1$s</string>
<string name="mode_added_launches_in">Запускает %1$s · в %2$s</string>
<string name="mode_added_choose">Выбрать другой файл…</string>
<string name="mode_added_exe_note">По умолчанию используется .exe с именем папки, иначе самый большой .exe.</string>
<string name="mode_stretch169">Растянуть игры 16:9</string>
<string name="mode_stretch169_hint">На экранах с соотношением сторон менее 16:9 растягивает игру на весь экран вместо черных полос. Вступит в силу в следующей сессии.</string>
<string name="mode_stretch169_hint">На экранах уже 16:9 растягивает игры на весь экран вместо черных полос. Вступит в силу в следующей сессии.</string>
<string name="mode_audio">Аудио</string>
<string name="mode_directaudio">Использовать DirectAudio в игре</string>
<string name="mode_directaudio">DirectAudio для игр</string>
<string name="mode_directaudio_hint">Обходит PulseAudio для снижения задержки.</string>
<string name="mode_client_audio">Аудио клиента Steam</string>
<string name="mode_client_audio_hint">Вступит в силу в следующей сессии.</string>
<string name="mode_client_audio_classic">Классический</string>
<string name="mode_client_audio_direct">DirectAudio</string>
<string name="mode_mic">Микрофон</string>
<string name="mode_mic_hint">Используется для голосового чата.</string>
<string name="mode_network">Сеть</string>
<string name="mode_wifi_discovery">Обнаружение Wi-Fi</string>
<string name="mode_wifi_discovery_hint">Показывает названия Wi-Fi и ближайшие сети в Steam.</string>
<string name="mode_wifi_discovery_hint">Показывает названия сетей Wi-Fi и сети поблизости в Steam.</string>
<string name="mode_wifi_location_off">Службы геолокации отключены.</string>
<string name="mode_wifi_permission_denied">Разрешение на определение местоположения не предоставлено.</string>
<string name="mode_wifi_open_settings">Открыть настройки</string>
@@ -300,19 +324,21 @@
<string name="mode_wifi_explain_title">Включить обнаружение Wi-Fi?</string>
<string name="mode_wifi_explain_text">Android требует разрешение на определение местоположения для чтения имен Wi-Fi и обнаружения ближайших сетей. DroidDeck использует это разрешение для отображения этих сетей в Steam. Мы не отслеживаем ваше местоположение. Доступ в интернет возможен и без этого разрешения.</string>
<string name="mode_storage">Хранилище игр</string>
<string name="mode_storage_auto">Авто - Использовать SD-карту при наличии, а также ваши папки с играми</string>
<string name="mode_storage_auto_none">Авто - Использовать ваши папки с играми, а также SD-карту при наличии (сейчас нет SD-карты)</string>
<string name="mode_storage_auto">Авто — SD-карта (если есть) и ваши папки с играми</string>
<string name="mode_storage_auto_none">Авто — ваши папки с играми и SD-карта, если есть (сейчас SD-карты нет)</string>
<string name="mode_storage_internal">Только внутреннее хранилище</string>
<string name="mode_storage_folder">Папка: %1$s</string>
<string name="mode_second_library">Вторая библиотека</string>
<string name="mode_storage_note">Игры, читающие ресурсы с SD-карты или из общего хранилища, могут подтормаживать.</string>
<string name="mode_storage_diagnostics">Диагностика хранилища</string>
<string name="mode_storage_diagnostics_hint">Записывает результаты выделения места и выборочные замеры скорости хранилища в журналы. Пока включено, установка может идти медленнее. Вступит в силу в следующей сессии.</string>
<string name="mode_choose_folder">Выбрать папку…</string>
<string name="mode_renderer">Рендерер</string>
<string name="mode_desktop_renderer">Рендерер рабочего стола</string>
<string name="mode_renderer_hint">Отвечает за отрисовку рабочего стола.</string>
<string name="mode_renderer_vulkan">vulkan - GPU</string>
<string name="mode_renderer_gles2">gles2 - GPU (экспериментально)</string>
<string name="mode_renderer_pixman">pixman - Программный</string>
<string name="mode_renderer_vulkan">vulkan — GPU</string>
<string name="mode_renderer_gles2">gles2 — GPU (экспериментально)</string>
<string name="mode_renderer_pixman">pixman — программный</string>
<string name="mode_renderer_note">Vulkan использует GPU для запуска программ рабочего стола, при сбое переключается на pixman. При использовании pixman игры по-прежнему запускаются в полноэкранном режиме на GPU.</string>
<string name="mode_custom_res_title">Пользовательское разрешение</string>
<string name="mode_custom_res_text">Заменяет предел разрешения и соотношение сторон. Размеры, не соответствующие экрану, будут отображаться с черными полосами.</string>
@@ -337,17 +363,24 @@
<string name="comp_display_driver">Драйвер дисплея</string>
<string name="comp_display_driver_hint">Отвечает за вывод изображения на экран в обоих режимах. Вступит в силу после перезапуска приложения.</string>
<string name="comp_import_adrenotools">Импорт AdrenoTools zip…</string>
<string name="comp_never">Никогда</string>
<string name="comp_nightlies_checked">Nightlies проверено %1$s</string>
<string name="comp_never">никогда</string>
<string name="comp_nightlies_checked">Nightlies проверены: %1$s</string>
<string name="comp_title">Компоненты</string>
<string name="comp_about">О компонентах</string>
<string name="comp_check_drivers">Проверить новые драйверы</string>
<string name="comp_check_nightlies">Проверить новые пакеты в Nightlies</string>
<string name="comp_proton">Proton</string>
<string name="comp_proton_note">При обновлении Steam заменяет Proton от Valve; оригинальные файлы каждой сборки сохраняются.</string>
<string name="comp_proton_note">Выбранный здесь Proton запускает все игры, для которых в Steam не выбран свой; изменение, сделанное в Steam, тоже отображается здесь. При обновлении Steam заменяет Proton от Valve; оригинальные файлы каждой сборки сохраняются.</string>
<string name="comp_default_live">%1$s теперь запускает все игры, для которых в Steam не выбран свой Proton.</string>
<string name="comp_default_next">%1$s будет запускать все игры, для которых не выбран свой Proton, со следующего запуска Steam.</string>
<string name="comp_default_not_runnable">%1$s не может запускать игры здесь, поэтому не может быть Proton по умолчанию.</string>
<string name="comp_default_failed">Не удалось сохранить Proton по умолчанию: %1$s</string>
<string name="comp_swapped">%1$s · заменено %2$d</string>
<string name="comp_all_original">%1$s · все оригинальные файлы</string>
<string name="comp_game_running_suffix">%1$s · игра запущена</string>
<string name="comp_esync_pack">%1$s · пакет droiddeck-esync</string>
<string name="comp_esync_wanted">%1$s · пакета droiddeck-esync пока нет</string>
<string name="comp_esync_builtin">%1$s · esync встроен, пакет не нужен</string>
<string name="comp_gpu_drivers">Драйверы GPU</string>
<string name="comp_reapplied">%1$s · повторно применено при запуске %2$s</string>
<string name="comp_next_queued">Далее: %1$s · после закрытия игры</string>
@@ -356,7 +389,7 @@
<string name="comp_applies_next_game">Вступит в силу при следующем запуске игры</string>
<string name="comp_import_zip">Импорт .zip</string>
<string name="comp_reading">Чтение Proton…</string>
<string name="comp_no_proton">Proton не установлен. Запустите Steam один раз для загрузки ARM64 Proton или добавьте GE-Proton или CachyOS в «Настройках».</string>
<string name="comp_no_proton">Proton еще не установлен. Запустите Steam один раз, чтобы скачать ARM64 Proton, или добавьте GE-Proton или CachyOS на странице «Настройка».</string>
<string name="comp_original">Оригинал · %1$s</string>
<string name="comp_this_build">%1$s · текущая сборка</string>
<string name="comp_earlier_build">%1$s · более ранняя сборка</string>
@@ -365,19 +398,19 @@
<string name="comp_waits_long">Игра использует этот Proton, поэтому нужно дождаться ее закрытия.</string>
<string name="comp_applies_long">Вступит в силу при следующем запуске игры.</string>
<string name="comp_swap_title">Заменить %1$s?</string>
<string name="comp_swap_body">Поместить %1$s в %2$s? Оригинальные файлы продолжат сохраняться. %3$s</string>
<string name="comp_swap_body">Поместить %1$s в %2$s? Оригинальные файлы остаются сохраненными. %3$s</string>
<string name="comp_restore_title">Восстановить %1$s?</string>
<string name="comp_restore_body">Вернуть оригинальные файлы %1$s в %2$s? %3$s</string>
<string name="comp_delete_package_body">Удалить пакет из приложения. Его можно будет скачать снова.</string>
<string name="comp_delete_package_body">Удаляет пакет из приложения. Его можно будет скачать снова.</string>
<string name="comp_delete_original_title">Удалить оригинальную версию?</string>
<string name="comp_delete_original_body">Эта оригинальная версия %1$s из более ранней сборки %2$s. Оригинальная версия текущей сборки всегда сохраняется.</string>
<string name="comp_nightlies_count">В Nightlies · %1$d</string>
<string name="comp_refresh_to_list">Обновить, чтобы показать пакеты в Nightlies.</string>
<string name="comp_refresh_to_list">Обновите, чтобы увидеть пакеты в Nightlies.</string>
<string name="comp_nothing_new">С момента последней проверки нового нет.</string>
<string name="comp_import_wcp">Импорт .wcp</string>
<string name="comp_restore_original">Восстановить оригинальные файлы этого Proton</string>
<string name="comp_restore_original_body">Вернуть оригинальные файлы %2$s из %1$s?</string>
<string name="comp_swap">Переключить</string>
<string name="comp_restore_original_body">Вернуть оригинальный %2$s для %1$s?</string>
<string name="comp_swap">Заменить</string>
<string name="comp_about_text">FEX, DXVK и VKD3D-Proton: для каждого Proton, используемого Steam для запуска игр.\n\nВыберите установленный элемент, чтобы заменить его. Это вступит в силу при следующем запуске игры или после закрытия текущей запущенной игры.\n\nВаш выбор будет перепроверяться перед каждым запуском; если он был изменен, он будет восстановлен. Оригинальные файлы каждого Proton сохраняются, поэтому обновления Steam никогда их не потеряют.</string>
<string name="comp_tag_original">Оригинал</string>
<string name="comp_tag_in_use">Используется</string>
@@ -387,7 +420,7 @@
<string name="perf_lede">Ядра CPU, исправления сессии и имя хоста. Вступит в силу в следующей сессии.</string>
<string name="perf_client_cores_group">Ядра клиента Steam</string>
<string name="perf_override">Переопределить выбор ядер Steam</string>
<string name="perf_override_hint">Закрепить Steam, помощник интерфейса и gamescope за выбранными ниже ядрами.</string>
<string name="perf_override_hint">Закрепляет Steam, его помощник интерфейса и gamescope за ядрами ниже.</string>
<string name="perf_client_cores">Ядра клиента</string>
<string name="perf_client_cores_on">Ядра, используемые Steam.</string>
<string name="perf_client_cores_off">Включите переопределение для выбора.</string>
@@ -400,7 +433,7 @@
<string name="perf_zink">Zink: отложенные дескрипторы</string>
<string name="perf_zink_hint">Рекомендуется для драйверов без буфера дескрипторов.</string>
<string name="perf_noglerror">Пропустить проверку ошибок GL</string>
<string name="perf_noglerror_hint">Отключить проверку GL для каждого вызова.</string>
<string name="perf_noglerror_hint">Отключает проверку ошибок GL при каждом вызове.</string>
<string name="perf_gsrealtime">gamescope: очередь GPU в реальном времени</string>
<string name="perf_gsrealtime_hint">Повышает приоритет работы GPU композитора. Может улучшить стабильность времени кадра, но потребляет часть производительности игры.</string>
<string name="perf_gpu">GPU</string>
@@ -410,13 +443,19 @@
<string name="perf_sysmem">Turnip: рендеринг sysmem</string>
<string name="perf_sysmem_hint">Steam и большинство игр будут быстрее. Требуется для Adreno 710/720/722.</string>
<string name="perf_xalia">Пропустить помощник xalia в Steam</string>
<string name="perf_fastsync">droiddeck-ntsync (экспериментально)</string>
<string name="perf_fastsync_hint">Замена драйвера ntsync Linux в пространстве пользователя, для тестирования. Пока включено, Proton использует ее вместо droiddeck-esync и droiddeck-fsync. Работает с Proton Experimental ARM64, GE-Proton и proton-cachyos. Вступит в силу в следующей сессии.</string>
<string name="perf_esync">droiddeck-esync</string>
<string name="perf_fsync">droiddeck-fsync в приоритете</string>
<string name="perf_fsync_hint">Запускает собственный fsync Proton на стандартных файлах Proton, а futex_waitv предоставляется в пространстве пользователя: пакет не нужен, и все продолжает работать сразу после обновления Proton в Steam. Пока включено, игры используют его раньше droiddeck-esync, кроме тех немногих, для которых Proton отключает fsync. Вступит в силу в следующей сессии.</string>
<string name="perf_esync_hint">Потоки Windows в играх ждут друг друга через eventfd и общую память вместо обращений к wineserver. Использует пакет droiddeck-esync, собранный под конкретную сборку Proton; пакеты скачиваются автоматически. Пока для новой сборки Proton пакета нет, его заменяет droiddeck-fsync. Вступит в силу в следующей сессии.</string>
<string name="perf_xalia_hint">Отключает помощник навигации геймпада Proton, который потребляет CPU в каждой игре.</string>
<string name="perf_seccomp">Запускать proot без seccomp</string>
<string name="perf_seccomp_hint">Может исправить ошибки отсутствующих системных вызовов на некоторых ядрах, но может снизить производительность.</string>
<string name="perf_fastpath">Быстрый путь proot</string>
<string name="perf_fastpath_needs_seccomp">Требуется фильтр seccomp для proot.</string>
<string name="perf_fastpath_hint">Быстрый поиск файлов, меньше подтормаживаний. Отключите, если программа не находит файлы.</string>
<string name="perf_identity">Идентификация сессии</string>
<string name="perf_identity">Имя сессии</string>
<string name="perf_hostname">Имя хоста</string>
<string name="perf_hostname_hint">Имя, под которым Steam видит это устройство. Оставьте пустым, чтобы вернуть %1$s.</string>
<string name="perf_hostname_invalid">Только буквы, цифры и дефисы посередине, до 63 символов.</string>
@@ -424,14 +463,16 @@
<string name="driver_installed">Установлен</string>
<string name="driver_available">Доступен для скачивания</string>
<string name="driver_nothing_new">С момента последней проверки нового нет.</string>
<string name="driver_restore_builtin">Восстановить встроенный драйвер</string>
<string name="driver_delete_builtin">Встроенный драйвер приложения: удалит распакованные файлы и скроет драйвер. Используйте «Восстановить встроенный драйвер» для восстановления.</string>
<string name="driver_restore_builtin">Восстановить встроенные драйверы</string>
<string name="driver_delete_builtin">Встроен в приложение: распакованные файлы будут удалены, а драйвер скрыт. Вернуть его можно кнопкой «Восстановить встроенные драйверы».</string>
<string name="driver_delete_bundle">Половина пакета Android + Linux: обе части будут удалены. Используемый драйвер вернется к драйверу по умолчанию.</string>
<string name="driver_delete_plain">Файлы будут удалены из приложения.</string>
<string name="driver_delete_in_use">Файлы будут удалены. Поскольку драйвер используется, будет применен драйвер по умолчанию.</string>
<string name="drawer_page_display">Экран</string>
<string name="drawer_page_effects">Эффекты</string>
<string name="drawer_page_controls">Управление</string>
<string name="drawer_page_components">Компоненты</string>
<string name="drawer_page_controller">Контроллер</string>
<string name="drawer_page_settings">Настройки</string>
<string name="drawer_page_desc">Страница %1$s</string>
<string name="drawer_steam">Steam</string>
@@ -442,11 +483,39 @@
<string name="drawer_prev_page">Предыдущая страница</string>
<string name="drawer_next_page">Следующая страница</string>
<string name="drawer_hud">HUD производительности</string>
<string name="drawer_scaling">Режим масштабирования</string>
<string name="drawer_scaling_sharpness">Резкость масштабирования</string>
<string name="drawer_effects">Экранные эффекты</string>
<string name="drawer_effects_hint">Применяется сразу. Пока включен любой эффект, немного нагружает GPU.</string>
<string name="drawer_look">Пресеты</string>
<string name="drawer_look_custom">Свой</string>
<string name="drawer_effects_advanced">Дополнительно</string>
<string name="widgets_expanded">Развернуто</string>
<string name="widgets_collapsed">Свернуто</string>
<string name="drawer_cas">Резкость (CAS)</string>
<string name="drawer_cas_level">Уровень резкости</string>
<string name="drawer_fake_hdr">Псевдо-HDR</string>
<string name="drawer_deband">Удаление полос (debanding)</string>
<string name="drawer_deband_strength">Сила удаления полос</string>
<string name="drawer_brightness">Яркость</string>
<string name="drawer_contrast">Контраст</string>
<string name="drawer_gamma">Гамма</string>
<string name="drawer_saturation">Насыщенность</string>
<string name="drawer_fxaa">FXAA (сглаживание краев)</string>
<string name="drawer_toon">Контуры (toon)</string>
<string name="drawer_crt">CRT</string>
<string name="drawer_ntsc">NTSC</string>
<string name="drawer_texture">Фильтрация текстур</string>
<string name="drawer_texture_hint">Игры DirectX 9–11, со следующего их запуска.</string>
<string name="drawer_anisotropy">Анизотропная фильтрация</string>
<string name="drawer_texture_sharpness">Резкость текстур</string>
<string name="drawer_texture_sharpness_note">Отрицательное смещение мип-уровней: текстуры резче, возможно мерцание. «Авто» подбирает значение по тому, насколько изображение сессии увеличено до размера экрана.</string>
<string name="drawer_touch_auto">Авто (%1$s)</string>
<string name="drawer_keyboard">Клавиатура</string>
<string name="drawer_pc_keyboard">Клавиатура ПК</string>
<string name="drawer_android_keyboard">Android</string>
<string name="drawer_second_screen">Второй экран</string>
<string name="drawer_second_screen_mode">Режим</string>
<string name="drawer_second_screen_shows">Показывать</string>
<string name="drawer_android_apps">Приложения Android</string>
<string name="drawer_launch_app">Запустить приложение</string>
@@ -458,16 +527,16 @@
<string name="drawer_next_session">Следующая сессия</string>
<string name="drawer_support">Поддержка</string>
<string name="drawer_logs">Журналы сессии</string>
<string name="drawer_logs_hint">Прикрепить к отчету об ошибке</string>
<string name="drawer_logs_hint">Приложите к отчету об ошибке</string>
<string name="drawer_share_logs">Поделиться журналами</string>
<string name="drawer_background">Фон</string>
<string name="drawer_background">В фон</string>
<string name="drawer_stop">Остановить</string>
<string name="drawer_stop_title">Остановить сессию?</string>
<string name="drawer_running_now">Сейчас выполняется</string>
<string name="drawer_no_game">Сейчас нет игр, запущенных через Proton</string>
<string name="drawer_no_proton">Proton не установлен.</string>
<string name="drawer_game_running">Игра запущена</string>
<string name="drawer_reapplied">Повторно применено при запуске %1$s</string>
<string name="drawer_game_running">игра запущена</string>
<string name="drawer_reapplied">повторно применено при запуске %1$s</string>
<string name="drawer_original">Оригинал</string>
<string name="drawer_components_note">Скачивайте, импортируйте и удаляйте на странице «Компоненты».</string>
<string name="setup_check_done">Готово</string>
@@ -516,23 +585,27 @@
<string name="setup_session">Сессия</string>
<string name="setup_logs">Журналы сессии</string>
<string name="setup_logs_hint">Сохраняется после каждой сессии</string>
<string name="setup_agent_commands">Инструменты отладки</string>
<string name="setup_latest_logs">Последние журналы сессии</string>
<string name="setup_saved_logs">Сохраненные журналы сессии</string>
<string name="setup_saved_logs_hint">Хранить последние %1$d</string>
<string name="setup_saved_logs_hint">Хранятся последние %1$d</string>
<string name="setup_clear_logs">Очистить журналы</string>
<string name="setup_offline">Автономный режим</string>
<string name="setup_sign_in_first">Сначала войдите в Steam</string>
<string name="setup_launcher">Лаунчер</string>
<string name="setup_app_scale">Масштаб приложения</string>
<string name="setup_app_scale_hint">Текст и элементы управления DroidDeck</string>
<string name="setup_app_scale_default">%1$d%% (по умолчанию)</string>
<string name="setup_theme">Тема</string>
<string name="setup_theme_hint">Внешний вид лаунчера</string>
<string name="setup_home">Использовать как главный экран</string>
<string name="setup_home_on">DroidDeck может использоваться как приложение главного экрана</string>
<string name="setup_home_off">DroidDeck не будет доступен как приложение главного экрана</string>
<string name="setup_fullscreen">Полноэкранный режим</string>
<string name="setup_fullscreen_on">Скрыть строку состояния и навигации Android</string>
<string name="setup_fullscreen_off">Показать строку состояния и навигации Android</string>
<string name="setup_default_home">Приложение главного экрана по умолчанию</string>
<string name="setup_choose_home">Выбрать приложение главного экрана</string>
<string name="setup_fullscreen_on">Скрывает строку состояния и панель навигации Android</string>
<string name="setup_fullscreen_off">Показывает строку состояния и панель навигации Android</string>
<string name="setup_default_home">Главный экран по умолчанию</string>
<string name="setup_choose_home">Выбрать главный экран</string>
<string name="setup_choose">Выбрать</string>
<string name="setup_linux_apps">Приложения Linux (бета)</string>
<string name="setup_store">Магазин Flathub</string>
@@ -544,12 +617,12 @@
<string name="setup_tool_protons_hint">Установить сборки ARM64 Proton</string>
<string name="setup_tool_performance">Производительность</string>
<string name="setup_tool_performance_hint">Распределение ядер CPU</string>
<string name="setup_tool_roms">Папки ROM</string>
<string name="setup_tool_roms">Папка ROM</string>
<string name="setup_tool_roms_hint">Место хранения игр эмулятора</string>
<string name="setup_card_components">Компоненты</string>
<string name="setup_card_components_hint">FEX, DXVK, VKD3D</string>
<string name="setup_card_controls">Управление</string>
<string name="setup_card_controls_hint">Сопоставление клавиш</string>
<string name="setup_card_controls_hint">Назначение кнопок</string>
<string name="store_tab_discover">Обзор</string>
<string name="store_tab_search">Поиск</string>
<string name="store_tab_installed">Установлено</string>
@@ -557,7 +630,7 @@
<string name="store_title">Магазин</string>
<string name="store_chip_flathub">Flathub · ARM64</string>
<string name="store_chip_ready">● Flatpak готов</string>
<string name="store_needs_runtime">Сначала установите среду выполнения Linux в «Настройках».</string>
<string name="store_needs_runtime">Сначала установите среду выполнения Linux на странице «Настройка».</string>
<string name="store_setup_title">Настройка Flatpak</string>
<string name="store_setup_text">Добавление Flatpak и подключение к Flathub (около 20 МБ). Первое приложение также загрузит свою среду выполнения.</string>
<string name="store_setting_up">Настройка…</string>
@@ -590,7 +663,7 @@
<string name="store_installing">Установка…</string>
<string name="store_install">Установить</string>
<string name="store_setup_first">Сначала настройте Flatpak</string>
<string name="store_download_size">Скачать %1$s</string>
<string name="store_download_size">Загрузка: %1$s</string>
<string name="store_installed_chip">● Установлено</string>
<string name="store_details_failed">Не удалось загрузить страницу Flathub этого приложения.</string>
<string name="store_loading">Загрузка из Flathub…</string>
@@ -607,30 +680,30 @@
<string name="upd_title">Обновления</string>
<string name="upd_build">DroidDeck %1$s · %2$s</string>
<string name="upd_checked">Проверено %1$s</string>
<string name="upd_not_checked">Не проверено</string>
<string name="upd_perm_title">Разрешить DroidDeck самообновление</string>
<string name="upd_not_checked">Еще не проверялось</string>
<string name="upd_perm_title">Разрешить DroidDeck обновляться самостоятельно</string>
<string name="upd_perm_text">Включите «Разрешить из этого источника» на следующей странице и вернитесь. Обновление продолжится автоматически.</string>
<string name="upd_open_settings">Открыть настройки</string>
<string name="upd_not_now">Не сейчас</string>
<string name="upd_signed_status">Другая подпись</string>
<string name="upd_signed_headline">Невозможно обновить на месте</string>
<string name="upd_signed_detail">Эта копия подписана не ключом выпуска DroidDeck, поэтому ее нельзя перезаписать напрямую. Удалите и переключитесь.</string>
<string name="upd_signed_detail">Эта копия подписана не ключом релизов DroidDeck, поэтому обновление не может установиться поверх нее. Чтобы перейти, удалите эту копию.</string>
<string name="upd_available">Доступно обновление</string>
<string name="upd_blocked_status">Невозможно установить</string>
<string name="upd_switch">Можно переключить</string>
<string name="upd_switch">Готово к переключению</string>
<string name="upd_ahead_status">Опережает Stable</string>
<string name="upd_ahead_headline">Вы опережаете Stable</string>
<string name="upd_ahead_detail">Эта сборка новее последней Stable. Вы переключитесь на Stable после выпуска следующей версии Stable.</string>
<string name="upd_gone_status">Тест завершен</string>
<string name="upd_gone_headline">Этот тест завершен</string>
<string name="upd_gone_detail">Исправление было объединено или отменено. Следите за Preview, чтобы получать последние исправления.</string>
<string name="upd_gone_detail">Исправление влито в основную ветку или отклонено. Следите за Preview, чтобы получать новейшие исправления.</string>
<string name="upd_current_status">Актуально</string>
<string name="upd_current_headline">У вас последняя версия %1$s</string>
<string name="upd_current_headline">У вас последняя версия: %1$s</string>
<string name="upd_dot_ago">· %1$s</string>
<string name="upd_stage_percent">%1$s… %2$d%%</string>
<string name="upd_stage">%1$s…</string>
<string name="upd_update_button">Обновить %1$s</string>
<string name="upd_install_button">Установить %1$s</string>
<string name="upd_update_button">Обновить%1$s</string>
<string name="upd_install_button">Установить%1$s</string>
<string name="upd_install_anyway">Все равно установить Stable %1$s</string>
<string name="upd_follow_preview">Следить за Preview</string>
<string name="upd_stop_session">Остановите текущую сессию перед обновлением.</string>
@@ -640,9 +713,9 @@
<string name="upd_new_preview">Новая сборка Preview</string>
<string name="upd_new_test">Тестовая сборка PR #%1$d</string>
<string name="upd_mb">%1$d МБ</string>
<string name="upd_channel">Канал обновлений</string>
<string name="upd_channel">КАНАЛ ОБНОВЛЕНИЙ</string>
<string name="upd_stable">Stable</string>
<string name="upd_stable_hint">Протестированная версия, подходит большинству</string>
<string name="upd_stable_hint">Проверенные выпуски, для большинства</string>
<string name="upd_version_ago">%1$s · %2$s</string>
<string name="upd_preview">Preview</string>
<string name="upd_preview_hint">Последние исправления перед Stable</string>
@@ -652,10 +725,10 @@
<string name="upd_tests_none">Сейчас нет</string>
<string name="upd_pr">PR #%1$d</string>
<string name="upd_not_built">Не собрано для этой копии DroidDeck</string>
<string name="upd_updated">%1$s обновлено</string>
<string name="upd_test_name">Тестовая версия PR #%1$d</string>
<string name="upd_while_ago">Недавно</string>
<string name="upd_just_now">Только что</string>
<string name="upd_updated">Обновлено %1$s</string>
<string name="upd_test_name">тестовая сборка PR #%1$d</string>
<string name="upd_while_ago">некоторое время назад</string>
<string name="upd_just_now">только что</string>
<plurals name="upd_tests_count">
<item quantity="one">%1$d доступный тест</item>
<item quantity="few">%1$d доступных теста</item>
@@ -663,10 +736,10 @@
<item quantity="other">%1$d доступных тестов</item>
</plurals>
<plurals name="upd_preview_behind">
<item quantity="one">Изменения с момента вашей сборки · Отставание на %1$d сборку</item>
<item quantity="few">Изменения с момента вашей сборки · Отставание на %1$d сборки</item>
<item quantity="many">Изменения с момента вашей сборки · Отставание на %1$d сборок</item>
<item quantity="other">Изменения с момента вашей сборки · Отставание на %1$d сборки</item>
<item quantity="one">Изменения с момента вашей сборки · отставание на %1$d сборку</item>
<item quantity="few">Изменения с момента вашей сборки · отставание на %1$d сборки</item>
<item quantity="many">Изменения с момента вашей сборки · отставание на %1$d сборок</item>
<item quantity="other">Изменения с момента вашей сборки · отставание на %1$d сборки</item>
</plurals>
<plurals name="upd_preview_recent">
<item quantity="one">Недавние изменения · %1$d сборка</item>
@@ -677,12 +750,12 @@
<string name="gate_title">Одна настройка Android, которую нужно изменить</string>
<string name="gate_eyebrow">Steam</string>
<string name="gate_lede">Android останавливает приложения, запускающие множество фоновых процессов, а Steam запускает десятки. До изменения этой настройки игры могут закрываться без сообщения об ошибке.</string>
<string name="gate_fix_for_me">Исправить за меня</string>
<string name="gate_toggle_steps">Включите «Отключить ограничение дочерних процессов» и вернитесь. Оставьте параметры разработчика включенными, иначе переключатель снова отключится.</string>
<string name="gate_open_dev">Открыть параметры разработчика</string>
<string name="gate_fix_for_me">Исправить автоматически</string>
<string name="gate_toggle_steps">Включите «Отключить ограничение дочерних процессов» и вернитесь. Оставьте раздел «Для разработчиков» включенным, иначе переключатель снова отключится.</string>
<string name="gate_open_dev">Открыть «Для разработчиков»</string>
<string name="gate_no_toggle">В этой версии Android нет такого переключателя, поэтому DroidDeck внесет изменения через отладку по Wi-Fi. Это займет около минуты, компьютер не нужен.</string>
<string name="gate_needs_wifi">Для отладки по Wi-Fi требуется Wi-Fi. Подойдет любая сеть, интернет не нужен.</string>
<string name="gate_needs_notifications">Код сопряжения отобразится в уведомлении. Разрешите DroidDeck отправлять уведомления или используйте «Другой способ».</string>
<string name="gate_needs_notifications">Код сопряжения придет в уведомлении. Разрешите DroidDeck отправлять уведомления или используйте «Другие способы».</string>
<string name="gate_allow_notifications">Разрешить уведомления</string>
<string name="gate_step1">Откройте Настройки → Для разработчиков → Отладка по Wi-Fi и включите ее</string>
<string name="gate_step2">Нажмите «Сопряжение устройства с помощью кода»</string>
@@ -693,12 +766,12 @@
<string name="gate_polling">Проверка каждые 2 секунды. После отключения этого переключателя страница закроется автоматически.</string>
<string name="gate_other_ways">Другие способы</string>
<string name="gate_other_toggle">Отладка по Wi-Fi, ручной ввод адреса, ADB на ПК</string>
<string name="gate_other_no_toggle">Ручной ввод адреса, ADB на ПК, параметры разработчика</string>
<string name="gate_other_no_toggle">Ручной ввод адреса, ADB на ПК, «Для разработчиков»</string>
<string name="gate_use_wireless_instead">Использовать отладку по Wi-Fi</string>
<string name="gate_some_roms">Некоторые ROM все еще предоставляют этот переключатель. Найдите «дочерние процессы» в параметрах разработчика.</string>
<string name="gate_some_roms">В некоторых прошивках переключатель все же есть. Поищите «дочерние процессы» в разделе «Для разработчиков».</string>
<string name="gate_manual_hint">Если способ с уведомлением не работает, введите адрес и код сопряжения из окна вручную.</string>
<string name="gate_enter_manually">Ввести адрес вручную</string>
<string name="gate_from_computer">Использовать ADB с компьютера:</string>
<string name="gate_from_computer">С компьютера через ADB:</string>
<string name="gate_copy_command">Копировать команду</string>
<string name="gate_choose_display">Выберите экран для открытия настроек Android.</string>
<string name="gate_main_screen">Главный экран</string>
@@ -723,17 +796,17 @@
<string name="wadb_pin_placeholder">6 цифр</string>
<string name="wadb_pair">Сопряжение</string>
<string name="wadb_apply_group">2 · Применение через отладку по Wi-Fi</string>
<string name="wadb_connect_address">Подключить IP-адрес и порт</string>
<string name="wadb_connect_address">IP-адрес и порт подключения</string>
<string name="wadb_pair_again">Сопряжение заново</string>
<string name="wadb_turn_off">Отключить ограничение</string>
<string name="wadb_other_ways">Другие способы изменения</string>
<string name="wadb_dev_try_first">1 · Для разработчиков (попробовать первым)</string>
<string name="wadb_dev_try_first">1 · Для разработчиков (сначала попробуйте это)</string>
<string name="wadb_restrict_on">Включите «Ограничение дочерних процессов».</string>
<string name="wadb_restrict_off">Отключите «Ограничение дочерних процессов».</string>
<string name="wadb_computer_last">3 · ADB на ПК (крайняя мера)</string>
<string name="wadb_only_if">Используйте только если отладка по Wi-Fi недоступна.</string>
<string name="wadb_computer_group">3 · ADB на ПК (крайняя мера)</string>
<string name="ctrl_osc_hint">При показе экранных элементов управления в сессии</string>
<string name="ctrl_osc_hint">Когда показывать экранные элементы управления в сессии</string>
<string name="ctrl_color">Цвет</string>
<string name="ctrl_color_hint">Оттенок экранных кнопок</string>
<string name="ctrl_custom">Пользовательский</string>
@@ -743,30 +816,30 @@
<string name="ctrl_size_hint" formatted="false">100% — стандартный размер</string>
<string name="ctrl_stick_click">Нажатие стика</string>
<string name="ctrl_stick_click_hint">Дважды нажмите и удерживайте стик для L3 или R3</string>
<string name="ctrl_adaptive">Адаптивный стик</string>
<string name="ctrl_rumble">Вибрация игры</string>
<string name="ctrl_adaptive">Адаптивные стики</string>
<string name="ctrl_rumble">Вибрация в играх</string>
<string name="ctrl_steam_button">Кнопка Steam</string>
<string name="ctrl_qam_button">Кнопка QAM</string>
<string name="ctrl_keyboard_button">Кнопка клавиатуры</string>
<string name="setup_animations">Анимации</string>
<string name="ctrl_adaptive_hint">Стик появится в месте касания и скроется после отпускания</string>
<string name="ctrl_adaptive_hint">Стики появляются в месте касания и исчезают после отпускания</string>
<string name="ctrl_layout">Раскладка</string>
<string name="ctrl_layout_custom">Сохранена пользовательская позиция</string>
<string name="ctrl_layout_custom">Сохранено свое расположение</string>
<string name="ctrl_layout_default">Адаптировано под этот экран</string>
<string name="ctrl_edit">Изменить</string>
<string name="ctrl_reset">Сбросить</string>
<string name="ctrl_mapping">Сопоставление кнопок</string>
<string name="ctrl_mapping_default">Каждая кнопка отправляет соответствующий исходный ввод</string>
<string name="ctrl_mapping_count">%1$d/%2$d кнопок переназначено</string>
<string name="ctrl_mapping">Назначение кнопок</string>
<string name="ctrl_mapping_default">Каждая кнопка отправляет свой ввод</string>
<string name="ctrl_mapping_count">Переназначено кнопок: %1$d из %2$d</string>
<string name="ctrl_configure">Настроить</string>
<string name="ctrl_reset_all">Сбросить контроллер</string>
<string name="ctrl_reset_all_hint">Восстановить все настройки и раскладки контроллера</string>
<string name="ctrl_mapping_lede">Настройте ввод, отправляемый каждой экранной кнопкой в игру. «Скрыть» удалит кнопку.</string>
<string name="ctrl_reset_all_hint">Восстанавливает все настройки контроллера и раскладку</string>
<string name="ctrl_mapping_lede">Что каждая экранная кнопка отправляет в игру. Значение «Скрыто» убирает кнопку.</string>
<string name="ctrl_onscreen_buttons">Экранные кнопки</string>
<string name="ctrl_defaults">По умолчанию</string>
<string name="ctrl_reset_mapping">Сбросить сопоставление</string>
<string name="ctrl_reset_mapping">Сбросить назначение</string>
<string name="content_android_apps">Приложения Android</string>
<string name="content_apps_count">%1$d приложений</string>
<string name="content_apps_count">Приложений: %1$d</string>
<string name="content_no_android_apps">Не найдено приложений Android для запуска.</string>
<string name="content_desktop_installed">● Рабочий стол установлен</string>
<string name="content_desktop_first_open">Устанавливается при первом открытии</string>
@@ -777,15 +850,15 @@
<string name="content_games">Игры</string>
<string name="content_choose_roms">Выберите папку ROM.</string>
<string name="content_retroarch_roms">В RetroArch перейдите в /root/ROMs.</string>
<string name="content_add_roms">Добавлено %1$s игр в ROMs/%2$s.</string>
<string name="content_add_roms">Добавьте игры %1$s в ROMs/%2$s.</string>
<string name="content_install_named">Установить %1$s</string>
<string name="content_stop_to_install">Остановите сессию для установки</string>
<string name="content_runtime_required">Требуется среда выполнения</string>
<string name="content_loading_details">Загрузка подробностей установки…</string>
<string name="content_details_unavailable">Подробности установки недоступны. Повторите попытку позже.</string>
<string name="content_needs_runtime">Сначала установите среду выполнения Linux в «Настройках».</string>
<string name="content_needs_runtime">Сначала установите среду выполнения Linux на странице «Настройка».</string>
<string name="content_stop_first">Остановите текущую сессию перед установкой приложения рабочего стола.</string>
<string name="content_install_into">Установить %1$s на рабочий стол Linux.</string>
<string name="content_install_into">Устанавливает %1$s в среду рабочего стола Linux.</string>
<string name="store_busy_percent_short">%1$s · %2$d%%</string>
<string name="content_hide_note">Скрытие удалит его с рабочего стола. Файлы останутся в среде выполнения Linux.</string>
<string name="content_rom_gone">Этой игры больше нет в папке ROM.</string>
@@ -805,8 +878,8 @@
<string name="games_prefix">Префикс Proton</string>
<string name="games_saves_looking">Поиск сохранений…</string>
<string name="games_saves_none">Папка сохранений не найдена по имени. При экспорте будет включена вся папка пользователя.</string>
<string name="games_saves_folders">%1$d папок сохранений</string>
<string name="games_saves_summary">%1$s · %2$d файлов · %3$s</string>
<string name="games_saves_folders">Папок сохранений: %1$d</string>
<string name="games_saves_summary">%1$s · файлов: %2$d · %3$s</string>
<string name="games_kb">%1$d КБ</string>
<string name="games_manage_saves">Управление сохранениями</string>
<string name="games_saves">Сохранения игры</string>
@@ -820,13 +893,13 @@
<string name="games_never_played">Никогда не запускалась</string>
<string name="games_runtime_busy_percent">Среда выполнения занята · %1$d%%</string>
<string name="games_runtime_busy">Среда выполнения занята</string>
<string name="games_runtime_first_play">Установка среды выполнения при первом запуске игры</string>
<string name="games_runtime_first_play">Среда выполнения установится при первом запуске игры</string>
<string name="games_runtime_update">Доступно обновление среды выполнения</string>
<string name="games_runtime_ready">● Среда выполнения готова</string>
<string name="games_last_played">Последний запуск %1$s</string>
<string name="games_internal">Внутреннее хранилище</string>
<string name="games_added">Добавленные игры</string>
<string name="gpu_auto_hint">Выбирает лучшую комбинацию драйверов для этого GPU и поддерживает ее в актуальном состоянии</string>
<string name="games_added">Добавленная игра</string>
<string name="gpu_auto_hint">Лучшая пара для этого GPU, обновляется автоматически</string>
<string name="gpu_manual_hint">Выбрать комбинацию драйверов вручную</string>
<string name="gpu_checking">Проверка драйверов…</string>
<string name="gpu_none_listed">Драйверы пока не перечислены. Обновите, чтобы найти драйверы.</string>
@@ -836,16 +909,16 @@
<string name="gpu_set_with_display">Настраивается вместе с драйвером дисплея: %1$s включает оба.</string>
<string name="gpu_set_with_runtime">Настраивается вместе с драйвером среды выполнения: %1$s включает оба.</string>
<string name="gpu_runtime_hint">Используется играми и рабочим столом.</string>
<string name="gpu_runtime_default">По умолчанию среды выполнения</string>
<string name="gpu_runtime_default">Стандартный драйвер среды выполнения</string>
<string name="gpu_display_hint">Отвечает за вывод изображения на экран. Вступит в силу после перезапуска DroidDeck.</string>
<string name="gpu_auto_by_gpu">Авто - Выбор по GPU</string>
<string name="gpu_auto_by_gpu">Авто — по GPU</string>
<string name="gpu_manage">Скачать, импортировать или удалить…</string>
<string name="gpu_in_use_caps">Используется</string>
<string name="gpu_builtin">Встроенный драйвер DroidDeck</string>
<string name="gpu_in_use_caps">ИСПОЛЬЗУЕТСЯ</string>
<string name="gpu_builtin">Драйверы, встроенные в DroidDeck</string>
<string name="gpu_matched_pair">Драйвер среды выполнения и драйвер дисплея настраиваются вместе как совместимая пара.</string>
<string name="gpu_recommended_for">Рекомендуется для этого GPU: %1$s.</string>
<string name="gpu_refresh_hint">Обновите, чтобы найти драйверы, подходящие для этого GPU.</string>
<string name="gpu_recommended_caps">Рекомендуется</string>
<string name="gpu_recommended_caps">РЕКОМЕНДУЕТСЯ</string>
<string name="gpu_unavailable">Недоступно</string>
<string name="load_runtime">Среда выполнения Linux</string>
<string name="load_runtime_detail">Подготовка среды выполнения Linux</string>
@@ -869,11 +942,11 @@
<string name="deck_tab_both">Оба</string>
<string name="deck_close">Закрыть управление вторым экраном</string>
<string name="deck_open_steam_menu">Открыть меню Steam</string>
<string name="deck_left_upper">Слева · Сверху</string>
<string name="deck_left_lower">Слева · Снизу</string>
<string name="deck_right_upper">Справа · Сверху</string>
<string name="deck_right_lower">Справа · Снизу</string>
<string name="deck_click">Нажать</string>
<string name="deck_left_upper">Слева · сверху</string>
<string name="deck_left_lower">Слева · снизу</string>
<string name="deck_right_upper">Справа · сверху</string>
<string name="deck_right_lower">Справа · снизу</string>
<string name="deck_click">Клик</string>
<string name="deck_right_trackpad">Правый тачпад</string>
<string name="deck_left_trackpad">Левый тачпад</string>
<string name="second_trackpad">Тачпад</string>
@@ -899,11 +972,11 @@
<string name="proton_lede">Установите сборку ARM64 Proton, затем выберите ее для каждой игры в Steam → Свойства → Совместимость.</string>
<string name="proton_stop_first">Остановите текущую сессию перед установкой или удалением инструментов совместимости.</string>
<string name="proton_available">Доступные сборки</string>
<string name="proton_installed">%1$s установлено</string>
<string name="proton_queued">Ожидающий элемент от предыдущего запроса</string>
<string name="proton_installed">Установлено: %1$s</string>
<string name="proton_queued">В очереди по предыдущему запросу</string>
<string name="proton_not_installed">Не установлено</string>
<string name="proton_install_now">Установить сейчас</string>
<string name="proton_cancel_queued">Отменить очередь</string>
<string name="proton_cancel_queued">Убрать из очереди</string>
<string name="pckb_android">Клавиатура Android</string>
<string name="pckb_hide">Скрыть ✕</string>
<string name="main_launch_named">Запустить %1$s</string>
@@ -948,7 +1021,7 @@
<string name="setup_retry_removal">Повторить удаление</string>
<string name="runtime_removing">Удаление</string>
<string name="runtime_removal_incomplete">Удаление не завершено</string>
<string name="game_file_export">Экспорт файлов игры</string>
<string name="game_file_export">Экспорт файла игры</string>
<string name="game_file_sync">Синхронизировать все файлы игры в папку</string>
<string name="game_file_stop_sync">Остановить синхронизацию файлов игры</string>
<string name="game_file_folder">Выбрать папку для файлов игры фронтенда</string>
@@ -956,4 +1029,27 @@
<string name="game_frontend_files">Файлы фронтенда</string>
<string name="fm_up_one_level">На уровень вверх</string>
<string name="fm_drive_linux">Система Linux</string>
<string name="display_session">Экран сессии</string>
<string name="display_resolution">Разрешение</string>
<string name="display_game_fit">Игры 16:9</string>
<string name="display_game_fit_hint">Как игры 16:9 вписываются в этот экран. Вступит в силу в следующей сессии.</string>
<string name="display_game_fit_unavailable">Выберите «По размеру экрана» или свой размер уже 16:9.</string>
<string name="display_preserve">Сохранять пропорции</string>
<string name="display_stretch">Растянуть на экран</string>
<string name="display_image_scaling">Масштабирование изображения</string>
<string name="display_filter">Фильтр масштабирования</string>
<string name="display_filter_hint">Общий для Steam и рабочего стола.</string>
<string name="display_filter_live">Применяется сразу. Общий для Steam и рабочего стола.</string>
<string name="display_filter_note">FSR, GSR и NIS работают при увеличении изображения сессии. «Sharpen only» работает и без увеличения.</string>
<string name="display_sharpness">Резкость фильтра</string>
<string name="display_frame_rate">Частота кадров</string>
<string name="display_look_filter">%1$s Устанавливает масштабирование: %2$s.</string>
<string name="display_match_screen">По размеру экрана (%1$d×%2$d)</string>
<string name="mode_tab_steam">Steam</string>
<string name="device_info_show">Показать сведения об устройстве</string>
<string name="device_info_hide">Скрыть сведения об устройстве</string>
<string name="device_info_loading">Чтение данных устройства…</string>
<string name="device_info_copy">Копировать</string>
<string name="device_info_copy_hint">Скопируйте эти сведения в отчет об ошибке.</string>
<string name="device_info_copied">Скопировано.</string>
</resources>
+1 -4
View File
@@ -337,10 +337,6 @@
<string name="mode_audio">音频</string>
<string name="mode_directaudio">游戏使用 DirectAudio</string>
<string name="mode_directaudio_hint">绕过 PulseAudio 以降低延迟。</string>
<string name="mode_client_audio">Steam 客户端音频</string>
<string name="mode_client_audio_hint">将在下次会话生效。</string>
<string name="mode_client_audio_classic">经典</string>
<string name="mode_client_audio_direct">DirectAudio</string>
<string name="mode_mic">麦克风</string>
<string name="mode_mic_hint">用于语音聊天。</string>
<string name="mode_network">网络</string>
@@ -611,6 +607,7 @@
<string name="setup_session">会话</string>
<string name="setup_logs">会话日志</string>
<string name="setup_logs_hint">每次会话后保存</string>
<string name="setup_agent_commands">调试工具</string>
<string name="setup_latest_logs">最新会话日志</string>
<string name="setup_saved_logs">已保存的会话日志</string>
<string name="setup_saved_logs_hint">保留最新的 %1$d 个</string>
+1 -4
View File
@@ -337,10 +337,6 @@
<string name="mode_audio">音訊</string>
<string name="mode_directaudio">遊戲使用 DirectAudio</string>
<string name="mode_directaudio_hint">繞過 PulseAudio 以減低延遲。</string>
<string name="mode_client_audio">Steam 用戶端音訊</string>
<string name="mode_client_audio_hint">下次會話生效。</string>
<string name="mode_client_audio_classic">經典</string>
<string name="mode_client_audio_direct">DirectAudio</string>
<string name="mode_mic">麥克風</string>
<string name="mode_mic_hint">用於語音聊天。</string>
<string name="mode_network">網絡</string>
@@ -611,6 +607,7 @@
<string name="setup_session">會話</string>
<string name="setup_logs">會話記錄</string>
<string name="setup_logs_hint">每次會話後儲存</string>
<string name="setup_agent_commands">偵錯工具</string>
<string name="setup_latest_logs">最新的會話記錄</string>
<string name="setup_saved_logs">已儲存的會話記錄</string>
<string name="setup_saved_logs_hint">保留最新的 %1$d 個</string>
+1 -4
View File
@@ -337,10 +337,6 @@
<string name="mode_audio">音訊</string>
<string name="mode_directaudio">遊戲使用 DirectAudio</string>
<string name="mode_directaudio_hint">繞過 PulseAudio 以降低延遲。</string>
<string name="mode_client_audio">Steam 用戶端音訊</string>
<string name="mode_client_audio_hint">下次工作階段生效。</string>
<string name="mode_client_audio_classic">傳統</string>
<string name="mode_client_audio_direct">DirectAudio</string>
<string name="mode_mic">麥克風</string>
<string name="mode_mic_hint">用於語音聊天。</string>
<string name="mode_network">網路</string>
@@ -611,6 +607,7 @@
<string name="setup_session">工作階段</string>
<string name="setup_logs">工作階段日誌</string>
<string name="setup_logs_hint">每次工作階段結束後儲存</string>
<string name="setup_agent_commands">偵錯工具</string>
<string name="setup_latest_logs">最新工作階段日誌</string>
<string name="setup_saved_logs">已儲存的工作階段日誌</string>
<string name="setup_saved_logs_hint">保留最新的 %1$d 個</string>
+3 -4
View File
@@ -186,6 +186,8 @@
<string name="add_app_flatpak_id">App ID</string>
<string name="add_app_flatpak_placeholder">org.ppsspp.PPSSPP</string>
<string name="add_app_flatpak_invalid">Not a Flathub app ID</string>
<string name="add_app_flatpak_bundle_hint">Or a .flatpak file, for an app not on Flathub.</string>
<string name="add_app_pick_flatpak">Choose a .flatpak file</string>
<string name="add_app_source">Source</string>
<string name="add_app_appearance">On your Desktop</string>
<string name="add_app_preview_name">New app</string>
@@ -348,10 +350,6 @@
<string name="mode_audio">Audio</string>
<string name="mode_directaudio">DirectAudio for games</string>
<string name="mode_directaudio_hint">Bypasses PulseAudio for lower latency.</string>
<string name="mode_client_audio">Steam client audio</string>
<string name="mode_client_audio_hint">Applies next session.</string>
<string name="mode_client_audio_classic">Classic</string>
<string name="mode_client_audio_direct">DirectAudio</string>
<string name="mode_mic">Microphone</string>
<string name="mode_mic_hint">For voice chat.</string>
<string name="mode_network">Network</string>
@@ -623,6 +621,7 @@
<string name="setup_session">Session</string>
<string name="setup_logs">Session logs</string>
<string name="setup_logs_hint">Saved after each session</string>
<string name="setup_agent_commands">Debugging tools</string>
<string name="setup_latest_logs">Latest session logs</string>
<string name="setup_saved_logs">Saved session logs</string>
<string name="setup_saved_logs_hint">Keeps the newest %1$d</string>
@@ -0,0 +1,266 @@
package com.droiddeck.launcher.agent
import android.content.Context
import android.os.Bundle
import android.os.Process
import android.util.Base64
import androidx.compose.ui.semantics.SemanticsConfiguration
import androidx.compose.ui.semantics.SemanticsProperties
import androidx.compose.ui.text.AnnotatedString
import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowBinder
import org.robolectric.shadows.ShadowLog
import java.io.File
import java.nio.file.Files
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class AgentSecurityTest {
private lateinit var context: Context
@Before fun prepare() {
context = RuntimeEnvironment.getApplication()
AgentAccess.setCommandsEnabled(context, false)
ShadowBinder.setCallingUid(Process.myUid())
ShadowLog.clear()
}
@After fun cleanup() {
ShadowBinder.setCallingUid(Process.myUid())
AgentAccess.setCommandsEnabled(context, false)
}
private fun refused(code: String, action: () -> Unit): AgentException {
try {
action()
throw AssertionError("Expected $code")
} catch (e: AgentException) {
assertEquals(code, e.code)
return e
}
}
private fun call(provider: AgentBridgeProvider, method: String, request: JSONObject = JSONObject()): JSONObject {
val extras = Bundle().apply {
putString("request", Base64.encodeToString(request.toString().toByteArray(), Base64.NO_WRAP))
}
return JSONObject(provider.call(method, null, extras).getString("json")!!)
}
@Test fun commandsRequireTheToggleInEveryBuild() {
assertFalse(AgentAccess.commandsAllowed(context))
refused("AGENT_COMMANDS_DISABLED") { AgentAccess.requireCommands(context) }
AgentAccess.setCommandsEnabled(context, true)
assertTrue(AgentAccess.commandsAllowed(context))
AgentAccess.requireCommands(context)
AgentAccess.setCommandsEnabled(context, false)
assertFalse(AgentAccess.commandsAllowed(context))
}
@Test fun runCannotBypassTheToggle() {
refused("AGENT_COMMANDS_DISABLED") { AgentAccess.requireStart(context, JSONObject().put("mode", "run")) }
AgentAccess.requireStart(context, JSONObject().put("mode", "steam"))
AgentAccess.requireStart(context, JSONObject().put("mode", "desktop"))
val blocked = Robolectric.buildActivity(AgentStartActivity::class.java).get()
val start = AgentStartActivity::class.java.getDeclaredMethod("startSession", JSONObject::class.java).apply { isAccessible = true }
val request = JSONObject().put("mode", "run").put("program", "/usr/bin/sh")
start.invoke(blocked, request)
assertTrue(blocked.isFinishing)
assertNull(shadowOf(blocked).nextStartedActivity)
AgentAccess.setCommandsEnabled(context, true)
AgentAccess.requireStart(context, JSONObject().put("mode", "run"))
val allowed = Robolectric.buildActivity(AgentStartActivity::class.java).get()
start.invoke(allowed, request)
assertEquals("/usr/bin/sh", shadowOf(allowed).nextStartedActivity.getStringExtra("program"))
}
@Test fun providerRefusesPrivilegedMethodsBeforePerformingThem() {
val provider = Robolectric.buildContentProvider(AgentBridgeProvider::class.java).create().get()
for (method in listOf("guest", "cdp", "override", "prefs", "env")) {
assertEquals(method, "AGENT_COMMANDS_DISABLED", call(provider, method).getJSONObject("error").getString("code"))
}
assertFalse(call(provider, "access").getBoolean("commands"))
assertTrue(call(provider, "state").getBoolean("ok"))
}
@Test fun providerChecksCallerPermissionBeforeDecoding() {
val provider = Robolectric.buildContentProvider(AgentBridgeProvider::class.java).create().get()
ShadowBinder.setCallingUid(Process.myUid() + 10001)
try {
provider.call("access", null, Bundle().apply { putString("request", "invalid") })
throw AssertionError("Expected permission refusal")
} catch (e: SecurityException) {
assertTrue(e.message!!.contains("DUMP"))
}
}
@Test fun oversizedRequestsAreRefused() {
val provider = Robolectric.buildContentProvider(AgentBridgeProvider::class.java).create().get()
val response = provider.call("access", null, Bundle().apply { putString("request", "A".repeat(256 * 1024 + 1)) })
assertEquals("INVALID_REQUEST", JSONObject(response.getString("json")!!).getJSONObject("error").getString("code"))
}
@Test fun oversizedResponsesReturnAnErrorInsteadOfOverflowingBinder() {
AgentAccess.setCommandsEnabled(context, true)
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().putString("large", "x".repeat(400 * 1024)).commit()
val provider = Robolectric.buildContentProvider(AgentBridgeProvider::class.java).create().get()
val response = call(provider, "prefs", JSONObject().put("file", "session"))
assertEquals("RESPONSE_TOO_LARGE", response.getJSONObject("error").getString("code"))
}
@Test fun invalidTimeoutsAreRefusedBeforeDispatchingToTheGuest() {
AgentAccess.setCommandsEnabled(context, true)
val provider = Robolectric.buildContentProvider(AgentBridgeProvider::class.java).create().get()
for (value in listOf("NaN", "Infinity", "invalid", "0", "601")) {
val response = call(provider, "guest", JSONObject().put("timeout", value))
assertEquals(value, "INVALID_REQUEST", response.getJSONObject("error").getString("code"))
}
}
@Test fun directEnvironmentAndPreferenceCallsAlsoRequireConsent() {
refused("AGENT_COMMANDS_DISABLED") { AgentEnv.list(context) }
refused("AGENT_COMMANDS_DISABLED") { AgentEnv.set(context, listOf("TEST=value"), false) }
refused("AGENT_COMMANDS_DISABLED") { AgentEnv.clear(context, "all") }
refused("AGENT_COMMANDS_DISABLED") { AgentEnv.override(context, "gamescope") }
refused("AGENT_COMMANDS_DISABLED") { AgentPrefs.get(context, "session") }
refused("AGENT_COMMANDS_DISABLED") { AgentPrefs.set(context, "session", "test", "bool", "true") }
}
@Test fun disablingDiscardsEnvironmentAndBinaryOverrides() {
AgentAccess.setCommandsEnabled(context, true)
AgentEnv.set(context, listOf("NEXT=one"), false)
AgentEnv.set(context, listOf("PERSISTENT=two"), true)
File(AgentEnv.inbox(context).apply { mkdirs() }, "gamescope").writeText("test binary")
AgentEnv.override(context, "gamescope")
val installed = File(LinuxRuntime.rootDir(context), "opt/droiddeck-agent/bin/gamescope")
assertTrue(installed.isFile)
AgentAccess.setCommandsEnabled(context, false)
assertFalse(installed.exists())
assertTrue(AgentEnv.beginSession(context).isEmpty())
AgentAccess.setCommandsEnabled(context, true)
val state = AgentEnv.list(context)
for (key in listOf("pending", "persistent", "active", "pendingOverrides", "activeOverrides")) {
assertEquals(key, 0, state.getJSONArray(key).length())
}
}
@Test fun oldPersistedExperimentsCannotApplyWhileDisabled() {
File(context.filesDir, "agent-env.json").writeText("""{"pending":["TEST=one"],"persistent":["TEST=two"]}""")
assertTrue(AgentEnv.beginSession(context).isEmpty())
AgentAccess.setCommandsEnabled(context, true)
assertEquals(0, AgentEnv.list(context).getJSONArray("persistent").length())
}
@Test fun authorisedExperimentsKeepTheirSessionLifecycle() {
AgentAccess.setCommandsEnabled(context, true)
AgentEnv.set(context, listOf("TEST=old", "STICKY=1"), true)
AgentEnv.set(context, listOf("TEST=new"), false)
assertEquals(listOf("TEST=old", "STICKY=1", "TEST=new"), AgentEnv.beginSession(context))
AgentEnv.endSession(context)
assertEquals(listOf("TEST=old", "STICKY=1"), AgentEnv.beginSession(context))
}
@Test fun environmentValuesAreNotLogged() {
AgentAccess.setCommandsEnabled(context, true)
AgentEnv.set(context, listOf("CUSTOM=synthetic-private-value"), false)
AgentEnv.beginSession(context)
assertFalse(ShadowLog.getLogsForTag("AgentEnv").any { it.msg.contains("synthetic-private-value") })
assertTrue(ShadowLog.getLogsForTag("AgentEnv").any { it.msg.contains("CUSTOM") })
}
@Test fun passwordSemanticsNeverReturnTextOrDescriptions() {
val config = SemanticsConfiguration().apply {
this[SemanticsProperties.Password] = Unit
this[SemanticsProperties.Text] = listOf(AnnotatedString("synthetic-secret"))
this[SemanticsProperties.EditableText] = AnnotatedString("synthetic-secret")
this[SemanticsProperties.ContentDescription] = listOf("synthetic-secret")
this[SemanticsProperties.StateDescription] = "synthetic-secret"
}
val result = AgentUi.textFields(config)
for (key in listOf("text", "editableText", "description", "state")) assertEquals("<redacted>", result.getString(key))
assertFalse(result.toString().contains("synthetic-secret"))
}
@Test fun ordinarySemanticsStayReadableForAgents() {
val config = SemanticsConfiguration().apply {
this[SemanticsProperties.Text] = listOf(AnnotatedString("Play Steam"))
this[SemanticsProperties.StateDescription] = "On"
}
val result = AgentUi.textFields(config)
assertEquals("Play Steam", result.getString("text"))
assertEquals("On", result.getString("state"))
}
@Test fun disablingDoesNotCrashOrLeaveQueuedValuesWhenCleanupIsUnsafe() {
AgentAccess.setCommandsEnabled(context, true)
AgentEnv.set(context, listOf("TEST=value"), true)
val outside = File(context.filesDir, "cleanup-outside").apply { mkdirs() }
val privateFile = File(outside, "keep").apply { writeText("private") }
val link = File(LinuxRuntime.rootDir(context).apply { mkdirs() }, "opt")
Files.createSymbolicLink(link.toPath(), outside.toPath())
try {
AgentAccess.setCommandsEnabled(context, false)
assertFalse(AgentAccess.commandsAllowed(context))
val state = JSONObject(File(context.filesDir, "agent-env.json").readText())
assertEquals(0, state.getJSONArray("persistent").length())
assertEquals("private", privateFile.readText())
} finally {
Files.delete(link.toPath())
}
}
@Test fun invalidEnvironmentErrorsDoNotEchoValues() {
AgentAccess.setCommandsEnabled(context, true)
for (line in listOf("=synthetic-private-value", "TEST=synthetic-private-value\nOTHER=x", "TEST=synthetic-private-value\u0000")) {
val error = refused("INVALID_ENV") { AgentEnv.set(context, listOf(line), false) }
assertFalse(error.message!!.contains("synthetic-private-value"))
}
}
@Test fun preferencesCannotWriteTheGateOrUsePathAliases() {
AgentAccess.setCommandsEnabled(context, true)
refused("PROTECTED_PREFS") { AgentPrefs.set(context, "agent", "commands", "bool", "true") }
for (name in listOf("../agent", "./agent", "/agent", "agent/../agent")) {
refused("INVALID_PREF") { AgentPrefs.set(context, name, "commands", "bool", "true") }
refused("INVALID_PREF") { AgentPrefs.get(context, name) }
}
assertTrue(AgentPrefs.set(context, "session", "test", "bool", "true").getBoolean("value"))
val error = refused("INVALID_PREF") { AgentPrefs.set(context, "session", "test", "int", "synthetic-private-value") }
assertFalse(error.message!!.contains("synthetic-private-value"))
}
@Test fun overrideRefusesLinksAndTraversalNames() {
AgentAccess.setCommandsEnabled(context, true)
for (name in listOf(".", "..", "../gamescope")) refused("INVALID_NAME") { AgentEnv.override(context, name) }
val target = File(context.filesDir, "private-source").apply { writeText("private") }
val link = File(AgentEnv.inbox(context).apply { mkdirs() }, "linked")
Files.createSymbolicLink(link.toPath(), target.toPath())
refused("INVALID_NAME") { AgentEnv.override(context, "linked") }
}
@Test fun overrideNeverFollowsItsInstallDirectoryLink() {
AgentAccess.setCommandsEnabled(context, true)
val outside = File(context.filesDir, "outside").apply { mkdirs() }
val root = LinuxRuntime.rootDir(context).apply { mkdirs() }
val link = File(root, "opt")
Files.createSymbolicLink(link.toPath(), outside.toPath())
try {
File(AgentEnv.inbox(context).apply { mkdirs() }, "gamescope").writeText("test binary")
refused("OVERRIDE_FAILED") { AgentEnv.override(context, "gamescope") }
assertTrue(outside.listFiles()!!.isEmpty())
} finally {
Files.delete(link.toPath())
}
}
}
@@ -42,6 +42,34 @@ class LogRedactorTest {
assertEquals(line, LogRedactor.redact(line))
}
@Test fun macAddressesAreRedactedInAnyLog() {
assertEquals(" mac <redacted:mac>", LogRedactor.redact(" mac 02:ab:cd:ef:12:34"))
assertEquals("controller <redacted:mac> connected", LogRedactor.redact("controller A2-B3-C4-D5-E6-F7 connected"))
assertEquals("mac=<redacted:mac>, peer=<redacted:mac>", LogRedactor.redact("mac=02:ab:cd:ef:12:34, peer=a2:b3:c4:d5:e6:f7"))
assertEquals("MAC:<redacted:mac>", LogRedactor.redact("MAC:02:ab:cd:ef:12:34"))
assertEquals("MacAddress:<redacted:mac>", LogRedactor.redact("MacAddress:A2-B3-C4-D5-E6-F7"))
assertEquals("{\"mac_address\":\"<redacted:mac>\"}", LogRedactor.redact("{\"mac_address\":\"02:ab:cd:ef:12:34\"}"))
}
@Test fun macRedactionPreservesOtherDiagnosticValues() {
val line = "[12:34:56] server ab:cd:ef:12:34:56:78:90 partial=ab:cd:ef:12:34 mixed=ab:cd-ef:12:34:56"
assertEquals(line, LogRedactor.redact(line))
}
@Test fun labelledDeviceIdentifiersAreRedacted() {
for (label in listOf("Serial number", "serial_number", "serialNumber", "serial", "device_serial", "Controller Serial", "ANDROID_ID", "build.serial")) {
assertEquals("$label: <redacted:serial>", LogRedactor.redact("$label: controller-123456"))
}
assertEquals("Serial number: <redacted:serial> connected", LogRedactor.redact("Serial number: 12345678901234567 connected"))
assertEquals("{\"serial_number\":\"<redacted:serial>\",\"result\":0}", LogRedactor.redact("{\"serial_number\":\"controller 123456\",\"result\":0}"))
assertEquals("device_serial = '<redacted:serial>'", LogRedactor.redact("device_serial = 'controller 123456'"))
}
@Test fun serialRedactionPreservesUnlabelledDiagnostics() {
val line = "serial port initialized; serial_number_count=2; controller=12345678901234567"
assertEquals(line, LogRedactor.redact(line))
}
@Test fun redactingTwiceChangesNothing() {
val lines = listOf(
"Using JWT 25484942796017334",
@@ -49,6 +77,10 @@ class LogRedactorTest {
"user 76561198012341234 [U:1:52075506]",
"external address 2607:f8b0:4005:80a::200e",
"OnLoginStateChange someaccount 2 1 0 0",
"mac 02:ab:cd:ef:12:34 controller A2-B3-C4-D5-E6-F7",
"MAC:02:ab:cd:ef:12:34",
"Serial number: 12345678901234567",
"{\"ANDROID_ID\":\"0123456789abcdef\"}",
)
for (line in lines) {
val once = LogRedactor.redact(line)
@@ -0,0 +1,43 @@
package com.droiddeck.launcher.input
import org.junit.Assert.*
import org.junit.Test
class InputSpaceTest {
private fun sceneUnder(viewX: Float, viewY: Float, view: Pair<Int, Int>, scene: Pair<Int, Int>): Pair<Double, Double> {
val k = minOf(view.first.toDouble() / scene.first, view.second.toDouble() / scene.second)
val offX = (view.first - scene.first * k) / 2
val offY = (view.second - scene.second * k) / 2
val ox = InputSpace.x(viewX, view.first).toDouble() * view.first / InputSpace.WIDTH
val oy = InputSpace.y(viewY, view.second).toDouble() * view.second / InputSpace.HEIGHT
return ((ox - offX) / k).coerceIn(0.0, scene.first - 1.0) to ((oy - offY) / k).coerceIn(0.0, scene.second - 1.0)
}
private fun assertLandsUnderFinger(view: Pair<Int, Int>, scene: Pair<Int, Int>) {
val k = minOf(view.first.toFloat() / scene.first, view.second.toFloat() / scene.second)
val offX = (view.first - scene.first * k) / 2
val offY = (view.second - scene.second * k) / 2
val stepX = view.first.toDouble() / InputSpace.WIDTH / k
val stepY = view.second.toDouble() / InputSpace.HEIGHT / k
for (sx in listOf(10, scene.first / 4, scene.first / 2, scene.first - 10))
for (sy in listOf(10, scene.second / 4, scene.second / 2, scene.second - 10)) {
val (x, y) = sceneUnder(offX + sx * k, offY + sy * k, view, scene)
assertEquals("x at $sx,$sy on $view showing $scene", sx.toDouble(), x, stepX + 0.01)
assertEquals("y at $sx,$sy on $view showing $scene", sy.toDouble(), y, stepY + 0.01)
}
}
@Test fun aTouchReachesTheScenePixelUnderTheFinger() {
assertLandsUnderFinger(2400 to 1504, 1280 to 720)
assertLandsUnderFinger(2400 to 1080, 1280 to 720)
assertLandsUnderFinger(2400 to 1504, 1148 to 720)
assertLandsUnderFinger(1080 to 2400, 1280 to 720)
}
@Test fun positionsOutsideTheViewStayInRange() {
assertEquals(0, InputSpace.x(-50f, 2400))
assertEquals(InputSpace.WIDTH - 1, InputSpace.x(2400f, 2400))
assertEquals(InputSpace.HEIGHT - 1, InputSpace.y(5000f, 1504))
assertEquals(0, InputSpace.y(10f, 0))
}
}
@@ -66,6 +66,18 @@ class SessionLogShareTest {
assertFalse(zip(folder).getValue("session.log").contains(leaked))
}
@Test fun olderRuleRecordReScrubsDeviceIdentifiers() {
val folder = tmp.newFolder("2026-10-07-01-steam")
File(folder, "network.txt").writeText("mac 02:ab:cd:ef:12:34\n")
File(folder, "steam").mkdirs()
File(folder, "steam/controller_support.txt").writeText("Serial number: controller-123456\n")
record(folder, "network.txt", "steam/controller_support.txt", rules = 1)
val out = zip(folder)
assertEquals("mac <redacted:mac>\n", out.getValue("network.txt"))
assertEquals("Serial number: <redacted:serial>\n", out.getValue("steam/controller_support.txt"))
}
@Test fun withoutARecordEveryFileIsScrubbed() {
val folder = tmp.newFolder("2026-10-06-04-steam")
File(folder, "session.log").writeText("$secret\n")
+176 -26
View File
@@ -1,41 +1,191 @@
# Agent control
The debug APK exposes a ContentProvider at `content://com.droiddeck.launcher.agent` and an Activity for starting sessions. Android's shell-only `DUMP` permission protects both. They are absent from release APKs.
`tools/droiddeckctl` drives DroidDeck on a real device over ADB, for agents and scripts that test
the app end to end: start and stop sessions, launch and quit Steam games, wait for a game to have
focus, send input, inspect the app's UI and gamescope's windows, run commands inside the session,
and collect logs, screenshots and recordings. `tools/droiddeck-scenario` repeats a scripted test
and reports every run.
Build and install the debug APK:
## How it works
- **The provider** `content://com.droiddeck.launcher.agent` (`agent/AgentBridgeProvider.kt`)
answers each command with JSON. It and the session-start Activity (`AgentStartActivity`) are in
every build and require `android.permission.DUMP`, held by the ADB shell and privileged or
explicitly granted callers. The provider checks the calling permission before decoding requests.
- **The guest agent** `droiddeck-agent` runs inside every session (started by
`droiddeck-session`). It runs commands with the session's own environment, publishes gamescope's
focus, and talks to the Steam client's DevTools, which only accepts guest processes. The app and
the agent exchange request and answer files under the session root (`files/session/agent`).
- **The UI dump** reads the app's Compose semantics from inside the app (`agent/AgentUi.kt`), so it
works on every display and window. UI Automator, by contrast, dumps whichever window has focus,
which on a dual-screen device is often another app's.
## Access
Player controls and observations work over authorized ADB on any build: `state`, `start`, `stop`,
`resume`, `wait`, `launch`, `quit`, `focus`, `input`, `ui`, `logs`, `screenshot`, `record`, `displays`,
`wake`, and `access`.
**Setup > Session > Debugging tools** is off by default in every build, including debug builds.
It enables `run`, `guest`, `cdp`, all `env` operations, `override`, and `prefs`. The toggle switches
directly without a confirmation dialog. The bridge refuses to change it through `ui` or preference
writes. The existing preference key, `setting-agent-commands` test tag, JSON command names, and
`AGENT_COMMANDS_DISABLED` error code are unchanged. Refusals exit 7; `droiddeckctl access` reports
whether commands are enabled.
Disabling the toggle clears queued and persistent agent environment settings and installed binary
overrides. Disabled settings cannot apply at the next session start. Already running commands and
effects already applied to a session are not undone; stop and restart that session to discard them.
Authorized command execution runs inside the runtime containing Steam's saved login. CDP evaluates
JavaScript in the authenticated Steam client, and preferences can contain private values. These
capabilities remain unrestricted when enabled: the toggle is an explicit opt-in, not credential
isolation or a sandbox against the authorized caller. Main already supported arbitrary guest
programs through `run`; restricting credential access would require addressing that route too.
ADB access remains a trust boundary, and ADB input can operate the device's own toggle.
The helper exchanges private files with the app and adds no network listener. The guarded Steam
DevTools port is bound to loopback and accepts only peers with a fresh private registration for a
live socket descriptor, matching socket inode, destination port, and address family. The existing
x86_64 Decky loader exception remains: that mode does not enable the guest-only acceptance guard.
Requests are limited to 256 KiB of encoded JSON. Guest responses and DevTools messages are limited
to 1 MiB; provider replies above 384 Ki characters return `RESPONSE_TOO_LARGE` to avoid overflowing
Binder. Command output retains at most 256 KiB per stream while continuing to drain both streams.
Timeouts must be finite, positive, and no greater than 600 seconds, and terminate the command's
process group. Override installation refuses path traversal and symbolic links.
Automatic process logs record environment keys and argument counts rather than values or full
argument lists. UI nodes marked as passwords redact text, editable text, descriptions, and state
text. This does not redact arbitrary authorized command results, CDP data, preferences, or screen
captures. Scenario directories are owner-only and JSON reports are written with mode 0600. Review
artifacts before sharing; a live `logs` pull copies the current folder without a fresh export scrub.
## Device selection and output
The CLI resolves one authorized device using `ADB_SERIAL` or `ANDROID_SERIAL` when set. Otherwise it
de-duplicates transports that report the same device serial and asks for an explicit serial if
multiple devices remain. Pass `--serial` before the command to choose directly; set `ADB` (or pass
`--adb`) to choose an adb executable. `tools/deploy_local.sh` uses the same resolver.
Every command writes one JSON object to stdout and its resolved serial to stderr. Exit codes: 0
success, 2 invalid or rejected command, 3 ADB or device error, 4 session error, 5 timeout, 6
artifact or file error, 7 debugging tools disabled.
## Commands
```sh
./gradlew assembleDebug --console=plain
adb install -r app/build/outputs/apk/debug/app-debug.apk
```
The provider can also be called directly for state, stop, and resume:
```sh
adb shell content call --uri content://com.droiddeck.launcher.agent --method state
adb shell content call --uri content://com.droiddeck.launcher.agent --method stop
```
Start requests go through `tools/droiddeckctl`, which launches the protected debug Activity from the ADB shell. Calling the provider's `start` method directly returns an error because a background provider cannot reliably open the session screen.
The host CLI resolves one authorized device using `ADB_SERIAL` or `ANDROID_SERIAL` when set. Otherwise it deduplicates transports that report the same device serial and asks for an explicit serial if multiple devices remain.
```sh
tools/droiddeckctl state --json
tools/droiddeckctl start steam
tools/droiddeckctl wait ready --timeout 90
tools/droiddeckctl state # schema 2, below
tools/droiddeckctl start steam --wait # --ui desktop, --url steam://..., --timeout
tools/droiddeckctl start steam --wait --reuse # keep a Steam session that is already up
tools/droiddeckctl start desktop
tools/droiddeckctl run /usr/bin/foo -- arg1 arg2
tools/droiddeckctl wait ready|idle|failed # --timeout (default 90 s)
tools/droiddeckctl stop
tools/droiddeckctl resume
tools/droiddeckctl launch 489830 --wait # Steam game by app id; --wait = until it has focus
tools/droiddeckctl wait focused 489830 # gamescope focuses it AND Steam lists it focusable
tools/droiddeckctl wait game # any app but the Steam client (769) has focus
tools/droiddeckctl quit 489830 # Steam's TerminateApp, then SIGTERM/SIGKILL
tools/droiddeckctl focus # focus properties and every Xwayland server's windows
tools/droiddeckctl input key ENTER # names (ESC, F1, UP, A...) or evdev codes; --mod CTRL
tools/droiddeckctl input text 'hello world' # as US-layout keys; --commit for text-input
tools/droiddeckctl input tap 640 360 # session output pixels; --space fraction for 0..1
tools/droiddeckctl input swipe 100 600 100 100 --duration 400
tools/droiddeckctl input pad a # a b x y lb rb start select guide qam up down left right
tools/droiddeckctl input stick left 0 -1 --hold 500
tools/droiddeckctl input trigger right 1.0
tools/droiddeckctl ui dump # tagged, labelled and clickable nodes; --all for every node
tools/droiddeckctl ui click rail-steam # by test tag
tools/droiddeckctl ui click --match "Play" # by text or description; --index for the nth match
tools/droiddeckctl ui set-text some-field --text abc
tools/droiddeckctl guest -- xprop -root GAMESCOPE_FOCUSED_APP # --timeout --env K=V --cwd --stdin --check
tools/droiddeckctl cdp targets
tools/droiddeckctl cdp eval 'SteamClient.Apps.GetMyRunningApps?.()' # --target, --no-await
tools/droiddeckctl env set DXVK_HUD=fps # next session only; --persistent until cleared
tools/droiddeckctl env list
tools/droiddeckctl env clear [next|persistent|all]
tools/droiddeckctl override gamescope ./gamescope # first on the next session's PATH, removed after it
tools/droiddeckctl prefs get session
tools/droiddeckctl prefs set session some_key true --type bool # returns the previous value
tools/droiddeckctl logs latest ./session-artifacts
tools/droiddeckctl screenshot ./screen.png
tools/droiddeckctl screenshot ./screen.png --display 4
tools/droiddeckctl record ./clip.mp4 --seconds 8 --display 0
tools/droiddeckctl displays # logical ids, names, sizes, capture ids
tools/droiddeckctl wake # wake the screen, dismiss the keyguard
```
Every command writes JSON to stdout and reports its resolved ADB serial to stderr. Exit codes are 0 for success, 2 for invalid or rejected commands, 3 for ADB/device errors, 4 for session failures, 5 for timeouts, and 6 for artifact or file errors. Set `ADB` to select an adb executable (or pass `--adb`); pass `--serial` before the command to select a device directly.
A sleeping device suspends the session and hides the app's windows from `ui dump`; `wake` first.
`start` accepts `steam` or `desktop`. Steam starts in Big Picture by default; `--ui desktop` selects the client's desktop UI, and `--url steam://...` passes a client URL. Use `--wait` to wait for `READY` as part of `start`. `run` accepts a program path and optional guest arguments.
`input` needs a session that has drawn its first frame. Pad input goes through the session screen's
virtual pad, the same one the on-screen controls drive, so games that ignore touch still respond.
`launch`, `quit` and `cdp` need a Steam session; `focus` and `wait focused` need gamescope (every
mode except the desktop).
The `state` response uses schema 1 and includes the build label, runtime version, session ID and phase, mode, requested program, suspend and first-frame state, output size, guest PID, failure details, and artifact paths. Phases are `IDLE`, `PREPARING`, `INSTALLING_RUNTIME`, `STARTING_COMPOSITOR`, `STARTING_GUEST`, `STARTING_STEAM`, `READY`, `SUSPENDED`, `STOPPING`, and `FAILED`. Each session also writes `events.jsonl` alongside its existing artifacts.
## State (schema 2)
`tools/deploy_local.sh` uses the same device resolver. If multiple distinct devices are connected, select one with `ADB_SERIAL` or `ANDROID_SERIAL`.
`state` returns `schema`, `build`, `appVersion`, `runtime {installed, version}`,
`agent {guest, guestFocus, commands}` and `session`:
- `id`, `phase`, `running`, `mode`, `program`, `steamUi`, `steamUrl`, `suspended`, `pip`,
`firstFrame`, `output` [w, h], `refreshHz`, `lastTransitionAt`, `guestPid`, `installing`
- `logDir`, `eventsFile`, `artifactsAvailable`, `artifactsComplete`, `failure {code, message, status}`
- `focus`: gamescope's focus as the guest agent last published it, or null:
`focusedApp`, `focusedWindow`, `focusableApps`, `baselayerAppIds`, `seq`, `t`.
Phases: `IDLE`, `PREPARING`, `INSTALLING_RUNTIME`, `STARTING_COMPOSITOR`, `STARTING_GUEST`,
`STARTING_STEAM`, `READY`, `SUSPENDED`, `STOPPING`, `FAILED`. Schema 2 only added `agent` and
`session.focus`; every schema 1 field is unchanged.
A game the player can see is `focusedApp == appId` **and** `appId in focusableApps`.
`GAMESCOPE_FOCUSABLE_WINDOWS` is what the Steam client orders the base layer from: a game missing
there stays behind the client's loading screen however healthy its window looks
(docs/development/steam-focus-debugging.md). `focus` returns the full snapshot, including each
server's windows with map state, override-redirect, app id, `WM_STATE`, pid, class, opacity and
`_NET_WM_STATE`.
## Events
Each session writes `events.jsonl` beside its other artifacts: the lifecycle (`session.created`,
`compositor.started`, `guest.exited`, ...) plus `agent.ready` (the guest agent is up),
`focus.changed` (the focused app, focusable apps or base-layer order changed) and
`agent.launch_requested`.
## UI test tags
Compose test tags are exposed as resource ids (`ui/TestTags.kt`), so both `ui dump` and UI
Automator show them:
| Tag | Where |
|---|---|
| `rail-steam`, `rail-games`, `rail-desktop`, `rail-store`, `rail-components`, `rail-android-apps`, `rail-setup`, `rail-updates` | the front end's rail |
| `play-steam` | Play on the Steam and Games pages |
| `setting-<key>` | every toggle and choice row, by its key (`setting-logs`, `setting-agent-commands`, ...) |
| `tab-<n>` | a page's tab strip (Setup's Overview, Controller, Session, Launcher...), by position |
| `drawer-tab-controller`, `-second_screen`, `-display`, `-effects`, `-games`, `-session` | the session drawer's pages |
| `drawer-stop`, `drawer-stop-confirm`, `drawer-stop-cancel` | stopping a session from the drawer |
## Scenarios
`tools/droiddeck-scenario` runs a JSON scenario: `setup` once, `steps` `repeat` times, `teardown`
once. Each run starts with `before` (typically `start steam --wait --reuse`, so a session that died
in one run, to a crash or the low-memory killer, is started again for the next) and ends with
`after`, whether it passed or not, so a failed run cannot leave a game running into the next. A list step is a droiddeckctl command line; `{"assert": "dotted.path", "equals"|"in"|
"contains"|"not"|"exists": ...}` checks the last answer; `{"sleep"}`, `{"screenshot"}` and
`{"record"}` do what they say. A failing run keeps a screenshot, the focus snapshot and the
session's logs in its folder, and `report.json` sums up the runs.
```sh
tools/droiddeck-scenario tools/scenarios/steam-game-focus.json --var appId=489830 --repeat 10 --keep-going
```
`tools/scenarios/steam-game-focus.json` launches a game, checks it has focus the way a player
sees it, and quits it: the test that catches a game left behind Steam's loading screen, which only
shows up in some fraction of launches. A game with a launcher of its own needs the launcher pressed
through first, since the launcher window carries the game's app id too:
`tools/scenarios/skyrim-launcher-focus.json` taps Skyrim's Play before checking.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

+55
View File
@@ -7,6 +7,61 @@ the timeline, then lessons and backlog. Companion to the README (what the app *d
---
## 2026-10-08 - `feat/directaudio-from-release`: DirectAudio from its own release, picked by interface, and the client gets the real engine
Three things were wrong with audio at once, and one tidy-up @xXJSONDeruloXx asked for.
- **Proton-CachyOS games never got DirectAudio.** Both CachyOS Protons we offer carry Wine's newer
*system-thread* audio interface (`dlls/mmdevapi/unixlib.h` differs from Valve's); the one driver
we shipped was built for the classic table, and the wrapper only asked "is this Wine 11?", which
CachyOS passes. Now two driver sets ship (`linux-wine11` for Valve Proton 11 / Experimental /
GE-Proton, `linux-wine11-systhread` for Proton-CachyOS) and `steam-compatibility` picks by what
the Proton's own `winepulse.so` imports (`PsCreateSystemThread` only on the system-thread table) -
never by the version string. No set for the interface, or no `winepulse.so`: DirectAudio stays
off and Proton's audio runs. Confirmed on the FIT: Experimental 20260924 and GE-Proton11-7
classic, cachyos-11.0-20261005-slr system-thread.
- **CachyOS also overrode the registry** (device log: `init_driver Loading driver list
L"pulse,alsa"`): its launcher sets `WINE_AUDIO_DRIVER=pulse,alsa` (setdefault) and its mmdevapi
reads that variable before the registry; Valve's and GE's mmdevapi ignore it. The wrapper now
exports `WINE_AUDIO_DRIVER=directaudio,pulse` as well as writing the registry. On CachyOS that
also means DirectAudio engages on a game's first launch, no registry value needed.
- **Some games ran on PulseAudio while the log said DirectAudio.** Two prefixes on the FIT had the
driver linked into `system32` but a pristine `user.reg` with no `Audio` value: Steam runs the
compat tool several times per launch, and a wineserver from an earlier verb still holding the
registry saves its copy over the line we appended. The wrapper now says so when a server is
live. Two stronger fixes were tried on the device and withdrawn the same day: writing the value
through the live server with a bare `wine reg add`, and having Proton create a missing prefix
first (`proton run wineboot`) - the second Proton run inside Steam's launch sequence got the
launch aborted (`KeyboardInterrupt` in Proton, games bounced back to their page, a half-made
prefix). On Valve/GE a first launch therefore still takes DirectAudio from the second run.
- **The Steam client's own sound was "DirectAudio" in name only.** PulseAudio → sink → relay →
AAudio is one hop more than a plain AAudio sink; the only gain was sharing the games' stream.
The daemon runs on the Android side, so DirectAudio's engine can run *in* it:
`module-directaudio-native-sink` (from the DirectAudio release) - the game driver's adaptive
buffer, two-burst floor, primed ring with fades, route-change reopen, watchdog and limiter, one
step from Android. It is now the only route: the *Steam client audio* choice is gone from the
menu (the relay route was one hop more for no gain, and the old "Classic" sink is the automatic
fallback). If the native sink cannot open its stream the daemon keeps running (`.nofail`) and
`PulseAudioComponent.ensureClientSink` loads the plain AAudio sink instead, saying so in
`audio.log`. The relay helper now starts only for games and the microphone.
- **Binaries out of tree** (@xXJSONDeruloXx): the driver sets, the relay helper and both sinks come
from the pinned release in `tools/directaudio/release.env` (`directaudio-linux-v1.1.0`, four
zips, sha256-checked) through `tools/directaudio/fetch.sh`, in CI and `build_local.sh`, like
gamescope. Deleted: `app/src/main/assets/directaudio/` (now generated, ignored),
`tools/directaudio-relay/`, `tools/aaudio-sink/module-directaudio-sink.c` + `da_relay_proto.h`.
`tools/aaudio-sink` keeps only `module-aaudio-sink` (the fallback). The release carries
MaxsTechReview's #338 fixes, credited there.
- Audio bundle stamp bumped so an installed app re-unpacks the modules.
- **Device-proven on the FIT, four cases:** the client's sink opened at 12 ms / 4 ms bursts with
0 underruns after 10 s (`client sink: DirectAudio (module-directaudio-native-sink)`); FEZ on
`cachyos-11.0-20261005-slr` took the system-thread set - Proton log `Loading driver list
L"directaudio,pulse"` → `Selecting driver L"directaudio"`, relay `hello from FEZ.exe`, 12 ms;
FEZ on Proton Experimental 20260924 on `linux-wine11`, relay hello, 12 ms (no regression);
Curse of the Dead Gods on CachyOS from a cold prefix - DirectAudio on its first launch, one
early xrun and the buffer grew 12 → 16 ms. Open: a Thor (20 ms bursts). An added game (Noita,
a Winlator-era folder never launched here before) bounced on launch with and without this
branch's wrapper steps, before Proton wrote a log - its own issue.
## 2026-09-29 - `feat/controller-input`: the pad the way SteamOS has it
Device-tested on the AYN Thor (Katamari under Proton Experimental ARM64).
+64
View File
@@ -0,0 +1,64 @@
# DroidDeck 0.3.2
### Features
- Added **Keep downloads running** toggle, so Steam downloads can continue when Android sleeps. (@jmarti326, @xXJSONDeruloXx, [#335](https://github.com/Droid-Deck/DroidDeck/pull/335))
<img src="media/0.3.2/keep-downloads-running.gif" width="50%" alt="Closing the handheld mid-download and opening it again: Steam's download keeps going while asleep and finishes with the lid shut">
- Added **Native Steam sleep** with dynamic cloud save and wake movie support. (@xXJSONDeruloXx, [#291](https://github.com/Droid-Deck/DroidDeck/pull/291))
<img src="media/0.3.2/native-steam-sleep.gif" width="50%" alt="Octopath Traveler II on the title screen, the device going to sleep, then waking to Steam's wake movie and landing back in the game">
- Added **Adreno 6xx support**, including Adreno 650 (eg: Retroid Pocket 5). (@unbelievableflavour, @jmarti326, [#320](https://github.com/Droid-Deck/DroidDeck/pull/320), [#326](https://github.com/Droid-Deck/DroidDeck/pull/326))
- SD cards and external drives can now be used as full **Steam libraries**. (@maxjivi05, [#388](https://github.com/Droid-Deck/DroidDeck/pull/388))
- Added per-game **Windows components** with automatic dependency recommendations for Steam and non Steam games. (@The412Banner, [#287](https://github.com/Droid-Deck/DroidDeck/pull/287))
<img src="media/0.3.2/windows-components.jpg" width="50%" alt="Windows components for FlatOut 2: DirectX 9 (d3dx9) recommended for this game, above the full list of 66 components">
- Added XNA, PhysX, Games for Windows Live, MSXML and other Windows components without needing to run their original installers. (@The412Banner, [#347](https://github.com/Droid-Deck/DroidDeck/pull/347))
- Added optional **Force SSBS** for ARM64 Proton games on supported CPUs. (@The412Banner, [#328](https://github.com/Droid-Deck/DroidDeck/pull/328))
- Added a detailed **device report** with SoC, GPU, CPU, Vulkan, memory and driver information. (@The412Banner, [#295](https://github.com/Droid-Deck/DroidDeck/pull/295))
- Added **App scale** presets from 75% to 150%. (@xXJSONDeruloXx, [#272](https://github.com/Droid-Deck/DroidDeck/pull/272))
- File Manager can now browse DroidDeck’s Linux filesystem directly. (@The412Banner, [#392](https://github.com/Droid-Deck/DroidDeck/pull/392))
- Added a **Language** setting, with Steam automatically following the selected language. (@maxjivi05, [#284](https://github.com/Droid-Deck/DroidDeck/pull/284))
- Added opt-in **Debugging tools** for automated game/session control, input, UI inspection and repeatable test scenarios. (@xXJSONDeruloXx, [#406](https://github.com/Droid-Deck/DroidDeck/pull/406))
### Improvements
- Steam and games now run on separate Xwayland servers, closer to SteamOS behavior. (@xXJSONDeruloXx, [#344](https://github.com/Droid-Deck/DroidDeck/pull/344))
- DirectAudio is now the default on fresh installs, with major crackling and underrun improvements across both audio modes. (@maxjivi05, [#338](https://github.com/Droid-Deck/DroidDeck/pull/338))
- Steam now preserves edits made to added-game shortcuts, including Target, Start In, name and launch options. (@maxjivi05, [#393](https://github.com/Droid-Deck/DroidDeck/pull/393))
- Steam now uses the full session resolution on displays wider or larger than 1080p. (@xXJSONDeruloXx, [#391](https://github.com/Droid-Deck/DroidDeck/pull/391))
- Improved Snapdragon and Adreno detection on devices with incomplete hardware information. (@The412Banner, [#295](https://github.com/Droid-Deck/DroidDeck/pull/295))
- Improved layouts for small screens and longer translated text. (@xXJSONDeruloXx, @maxjivi05, [#268](https://github.com/Droid-Deck/DroidDeck/pull/268), [#284](https://github.com/Droid-Deck/DroidDeck/pull/284))
- File Manager and file pickers can now navigate upward from game folders, prefixes and remembered locations. (@The412Banner, [#377](https://github.com/Droid-Deck/DroidDeck/pull/377))
- Expanded and polished Spanish, Japanese, Korean, Chinese, French and Russian translations. (@maxjivi05, @starwishHi, @zeedif, @Tak-attack, @kmnkv1, [#284](https://github.com/Droid-Deck/DroidDeck/pull/284), [#286](https://github.com/Droid-Deck/DroidDeck/pull/286), [#234](https://github.com/Droid-Deck/DroidDeck/pull/234), [#314](https://github.com/Droid-Deck/DroidDeck/pull/314), [#324](https://github.com/Droid-Deck/DroidDeck/pull/324))
- Steam and Linux apps now use Android’s system fonts for Chinese, Japanese, Korean, Thai and other missing characters. (@maxjivi05, @0x1428571429, [#374](https://github.com/Droid-Deck/DroidDeck/pull/374), [#252](https://github.com/Droid-Deck/DroidDeck/pull/252))
- Sessions launched from Android frontends now return to that frontend when they close. (@xXJSONDeruloXx, [#300](https://github.com/Droid-Deck/DroidDeck/pull/300))
### Fixed
- Fixed MangoHud reporting roughly double the real battery power draw and incorrect remaining time. (Thanks Russ ❤️)(@xXJSONDeruloXx, [#270](https://github.com/Droid-Deck/DroidDeck/pull/270))
- Fixed slow Steam installs on SD cards and external storage, including long **Reserving space** / **Committing** stages and installs failing to begin. (@maxjivi05, [#388](https://github.com/Droid-Deck/DroidDeck/pull/388), [#410](https://github.com/Droid-Deck/DroidDeck/pull/410))
- Fixed some games staying behind Steam’s black** **loading screen while already running. (@xXJSONDeruloXx, [#401](https://github.com/Droid-Deck/DroidDeck/pull/401))
- Fixed a graphics-memory leak that could kill the session. (@The412Banner, @xXJSONDeruloXx, [#275](https://github.com/Droid-Deck/DroidDeck/pull/275), [#305](https://github.com/Droid-Deck/DroidDeck/pull/305))
- Fixed some added games starting in `C:\windows` instead of their own game folder. (@The412Banner, [#343](https://github.com/Droid-Deck/DroidDeck/pull/343))
- Fixed Firefox and LibreWolf tabs crashing on affected **Android 16** devices. (@The412Banner, [#280](https://github.com/Droid-Deck/DroidDeck/pull/280))
- Fixed resolution presets changing the screen shape, and fixed 16:9 stretch in Steam Deck mode. (@xXJSONDeruloXx, @magarto, [#337](https://github.com/Droid-Deck/DroidDeck/pull/337), [#133](https://github.com/Droid-Deck/DroidDeck/pull/133))
- Fixed several Steam sleep and wake edge cases. (@xXJSONDeruloXx, [#289](https://github.com/Droid-Deck/DroidDeck/pull/289))
- Fixed some new sessions starting with the wrong output size. (@xXJSONDeruloXx, [#357](https://github.com/Droid-Deck/DroidDeck/pull/357))
- Fixed Windows component installation failures and improved controller navigation in the component picker. (@The412Banner, [#347](https://github.com/Droid-Deck/DroidDeck/pull/347))
- Removed the old **Force game windows fullscreen** workaround now that games run on their own Xwayland server. (@xXJSONDeruloXx, [#349](https://github.com/Droid-Deck/DroidDeck/pull/349))
- Hardened the developer environment override so other apps with storage access cannot modify Steam session environment variables. (@The412Banner, [#413](https://github.com/Droid-Deck/DroidDeck/pull/413))
### New contributors
- @unbelievableflavour made their first contribution in [#320](https://github.com/Droid-Deck/DroidDeck/pull/320).
- @Lightfallingonionroom made their first contribution in [#232](https://github.com/Droid-Deck/DroidDeck/pull/232).
- @0x1428571429 made their first contribution in [#252](https://github.com/Droid-Deck/DroidDeck/pull/252).
- @zeedif made their first contribution in [#234](https://github.com/Droid-Deck/DroidDeck/pull/234).
- @Tak-attack made their first contribution in [#314](https://github.com/Droid-Deck/DroidDeck/pull/314).
- @kmnkv1 made their first contribution in [#324](https://github.com/Droid-Deck/DroidDeck/pull/324).
[Full changelog](https://github.com/Droid-Deck/DroidDeck/compare/0.3.1...0.3.2)
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

+2 -2
View File
@@ -2,7 +2,8 @@
# Compiles module-aaudio-sink.so against the upstream PulseAudio 13.0 headers and the daemon's own
# libraries the app ships (app/src/main/jniLibs/arm64-v8a), with the Android NDK.
# NDK=<ndk root> tools/aaudio-sink/build.sh <pulseaudio-13.0 source dir> <output dir>
# Produces module-aaudio-sink.so and module-directaudio-sink.so in the output dir.
# Produces module-aaudio-sink.so in the output dir (the fallback sink; the DirectAudio sinks come
# from the pinned DirectAudio release, see tools/directaudio/fetch.sh).
set -euo pipefail
PA_SRC=$1
OUTDIR=$2
@@ -61,4 +62,3 @@ build_one() {
ls -l "$OUT"
}
build_one module-aaudio-sink.c "$OUTDIR/module-aaudio-sink.so" -laaudio
build_one module-directaudio-sink.c "$OUTDIR/module-directaudio-sink.so" ""
-209
View File
@@ -1,209 +0,0 @@
/* DirectAudio relay - the contract between the driver and the relay helper.
*
* Copyright 2026 The412Banner
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* WHY THIS EXISTS. The driver's whole premise is an in-process AAudio client:
* the guest's WASAPI buffers are mixed and handed to Android's audio server
* from inside the game, no daemon in the path. That is only possible when the
* game process is a bionic process. Under a glibc runtime (the Linux Steam
* client, where the game runs inside a proot'd Arch rootfs on Valve's own
* ARM64 Proton) libaaudio cannot be loaded at all: it is a bionic library and
* the rootfs's dynamic linker does not know how to bring it into a glibc
* process. The game side therefore has to stop at a boundary it CAN cross, and
* the only thing both worlds agree on is the kernel: a unix socket, a memfd and
* a futex word.
*
* SHAPE. One helper process (directaudio-relay, bionic, links libaaudio) runs
* on the Android side and listens on a unix socket. Each game process that
* needs audio connects once, sends its launch config (the same knobs the
* in-process build reads from BANNER_AUDIO_DIRECT_*), and gets back one or two
* shared rings (memfds passed with SCM_RIGHTS):
*
* render ring game (producer) -> helper (consumer) -> AAudio OUTPUT
* capture ring helper (producer, AAudio INPUT) -> game (consumer)
*
* The driver keeps its mixer and its per-voice WASAPI rings exactly as in the
* in-process build; what used to be the AAudio data callback is now a pump
* thread that keeps the render ring topped up, and the capture callback is a
* pump that drains the capture ring into the capture voices. Everything that
* needs an AAudioStream (open, adaptive buffer growth and decay, route-change
* reopen, the stalled-callback watchdog, the live-config mailbox) moves to the
* helper unchanged in spirit.
*
* COST. One extra hand-off: the ring. The helper's callback pulls a burst from
* the ring, so the ring must hold at least one burst at every callback; the
* driver keeps DA_RING_TARGET_BURSTS bursts queued and the helper raises that
* target when a callback finds the ring short. Everything else - the AAudio
* buffer, AudioFlinger's own latency - is what the in-process build pays too.
*
* WIRE FORMAT. Fixed-width, native-endian, same-machine only. The two sides are
* different libcs but the same CPU, so no marshalling beyond fixed-size structs.
* Bump DA_RELAY_VERSION on any layout change; the helper refuses a mismatch.
*/
#ifndef DA_RELAY_PROTO_H
#define DA_RELAY_PROTO_H
#include <stdint.h>
#include <stddef.h>
#define DA_RELAY_VERSION 1
#define DA_RING_MAGIC 0x44415247u /* 'DARG' */
#define DA_HELLO_MAGIC 0x44414831u /* 'DAH1' */
#define DA_ACK_MAGIC 0x44414131u /* 'DAA1' */
/* Socket path. The driver reads BANNER_AUDIO_DIRECT_RELAY; when unset it falls
* back to $XDG_RUNTIME_DIR/DA_RELAY_DEFAULT_NAME, which a host that already
* hands its runtime dir into the session gets for free. */
#define DA_RELAY_ENV "BANNER_AUDIO_DIRECT_RELAY"
#define DA_RELAY_DEFAULT_NAME "directaudio-relay"
/* Both rings carry float32 interleaved stereo. The render ring is always
* 48 kHz (the mixer's output rate); the capture ring runs at whatever rate the
* input stream was granted, published in da_ring.rate, and the driver resamples
* per voice as the in-process build already does. */
#define DA_RING_RATE 48000
#define DA_RING_CHANNELS 2
/* Render ring sizing. Capacity is the ceiling adaptive growth can reach; the
* initial target is what the driver keeps queued. Two bursts: the helper's
* callback consumes one burst and wakes the pump, which then has a full burst
* period to refill before the next callback. */
#define DA_RING_CAP_MS 250
#define DA_RING_TARGET_BURSTS 2
#define DA_RING_MAX_TARGET_MS 100
/* Capture ring: 200 ms is far more than a game ever leaves queued; on overrun
* the helper drops the newest block, matching the in-process "guest is not
* draining" behaviour of dropping data rather than blocking the mic thread. */
#define DA_CAPTURE_RING_MS 200
enum da_ring_state
{
DA_RING_OPENING = 0,
DA_RING_PLAYING = 1,
DA_RING_ERROR = 2,
};
struct da_ring
{
uint32_t magic;
uint32_t version;
uint32_t cap_frames; /* ring capacity in frames */
uint32_t rate; /* frames per second of the data in this ring */
uint32_t channels; /* DA_RING_CHANNELS */
uint32_t _pad0;
/* Single producer, single consumer; monotonic frame totals, wrap-safe with
* unsigned arithmetic. Producer writes widx with RELEASE after the data;
* consumer writes ridx with RELEASE after it has copied the data out. */
volatile uint32_t widx;
volatile uint32_t ridx;
/* Futex word the CONSUMER of a render ring / PRODUCER of a capture ring
* bumps after each block, so the other side can sleep on it instead of
* polling. Waiters always use a timeout, so a missed wake only costs one
* period. */
volatile uint32_t wake;
volatile uint32_t quit; /* either side: tear down */
volatile uint32_t state; /* enum da_ring_state, helper-owned */
/* Render ring only, helper-owned, read by the driver: */
volatile int32_t target_frames; /* keep at least this many queued */
volatile int32_t hw_buf_frames; /* AAudio buffer size right now (get_latency) */
volatile int32_t hw_burst; /* frames per burst of the output stream */
volatile uint32_t underruns; /* callbacks that found fewer than they needed */
volatile uint32_t cb_count; /* data callbacks so far (liveness) */
uint32_t _pad1[3];
float data[]; /* cap_frames * channels */
};
static inline size_t da_ring_bytes(uint32_t cap_frames)
{
return sizeof(struct da_ring) + (size_t)cap_frames * DA_RING_CHANNELS * sizeof(float);
}
static inline uint32_t da_ring_avail(const struct da_ring *r)
{
uint32_t w = __atomic_load_n(&r->widx, __ATOMIC_ACQUIRE);
uint32_t rd = __atomic_load_n(&r->ridx, __ATOMIC_ACQUIRE);
return w - rd;
}
static inline uint32_t da_ring_space(const struct da_ring *r)
{
return r->cap_frames - da_ring_avail(r);
}
/* ---- wire messages ------------------------------------------------------- */
#define DA_HELLO_MIC 0x01u /* also open an INPUT stream + capture ring */
#define DA_HELLO_EXCLUSIVE 0x02u /* AAUDIO_SHARING_MODE_EXCLUSIVE requested */
#define DA_HELLO_ADAPTIVE 0x04u
#define DA_HELLO_DECAY 0x08u
#define DA_HELLO_WATCHDOG 0x10u
/* First message on a fresh connection, driver -> helper. Mirrors the launch
* config the in-process build derives from BANNER_AUDIO_DIRECT_* so a preset
* means the same thing under both runtimes. */
struct da_hello
{
uint32_t magic; /* DA_HELLO_MAGIC */
uint32_t version; /* DA_RELAY_VERSION */
uint32_t flags; /* DA_HELLO_* */
int32_t perf; /* 0 NONE, 1 LOW_LATENCY, 2 POWER_SAVING (host convention) */
int32_t target_ms; /* AAudio buffer, ms; 0 = use target_frames or the default */
int32_t max_ms; /* adaptive ceiling, ms; 0 = max_frames or the default */
int32_t target_frames; /* frame forms, used only when the ms forms are 0 */
int32_t max_frames;
uint32_t stall_ms; /* watchdog: callback silent this long => rebuild */
uint32_t quiet_ms; /* decay pacing, see the driver */
uint32_t punish_ms;
uint32_t max_backoff;
int32_t pid; /* the game process, for the log */
uint32_t log; /* BANNER_AUDIO_DIRECT_LOG */
char runtime_path[256]; /* BANNER_AUDIO_DIRECT_RUNTIME mailbox, "" = none */
char name[64]; /* process name, for the log */
};
#define DA_ACK_MIC_FAILED 0x01u /* mic asked for, input stream would not open */
/* Reply, helper -> driver, followed by SCM_RIGHTS carrying the ring fds:
* fd[0] = render ring, fd[1] = capture ring (present iff in_cap_frames > 0). */
struct da_ack
{
uint32_t magic; /* DA_ACK_MAGIC */
int32_t status; /* 0 = ok, else an AAudio error code (negative) */
int32_t rate; /* output stream rate (48000) */
int32_t burst; /* output frames per burst */
int32_t buf_frames; /* output buffer size as opened */
int32_t out_cap_frames; /* render ring capacity */
int32_t in_cap_frames; /* capture ring capacity, 0 = no capture ring */
int32_t in_rate; /* rate of the capture ring's data */
uint32_t flags; /* DA_ACK_* */
uint32_t _pad;
};
/* Subsequent messages, driver -> helper, on the same socket. The helper never
* writes after the ack; everything it has to say is in the ring header. EOF on
* the socket is how the helper learns the game is gone. */
enum da_msg_type
{
DA_MSG_MIC_START = 1, /* first capture voice started: make the mic hot */
DA_MSG_MIC_STOP = 2, /* last capture voice gone: stop (keep open) */
DA_MSG_PING = 3,
};
struct da_msg
{
uint32_t type;
int32_t arg;
};
#endif /* DA_RELAY_PROTO_H */
-481
View File
@@ -1,481 +0,0 @@
/*
* module-directaudio-sink: a PulseAudio 13 sink that hands the daemon's mixed output to the
* DirectAudio relay, the bionic helper that owns the AAudio stream on the Android side.
*
* The daemon runs under proot, where every system call is traced; an AAudio stream driven from
* in here is at the mercy of that. The relay is not: it is the same helper that plays games'
* DirectAudio, with its adaptive buffer, route-change reopen and watchdog. This module is a
* producer for its render ring (da_relay_proto.h): float stereo at the ring's rate, kept topped
* up to the target the relay asks for.
*
* The relay comes up after the daemon, so the sink loads without it and connects when the socket
* appears; until then it runs as a clocked null sink so clients are not stalled.
*
* SPDX-License-Identifier: LGPL-2.1-or-later
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <sys/un.h>
#include <time.h>
#include <unistd.h>
#include <pulse/rtclock.h>
#include <pulse/timeval.h>
#include <pulse/util.h>
#include <pulse/xmalloc.h>
#include <pulsecore/core-util.h>
#include <pulsecore/log.h>
#include <pulsecore/macro.h>
#include <pulsecore/modargs.h>
#include <pulsecore/module.h>
#include <pulsecore/rtpoll.h>
#include <pulsecore/sink.h>
#include <pulsecore/thread-mq.h>
#include <pulsecore/thread.h>
#include "da_relay_proto.h"
PA_MODULE_AUTHOR("The412Banner");
PA_MODULE_DESCRIPTION("Android audio output through the DirectAudio relay");
PA_MODULE_VERSION(PACKAGE_VERSION);
PA_MODULE_LOAD_ONCE(false);
PA_MODULE_USAGE(
"socket=<the relay's unix socket> "
"sink_name=<name for the sink> "
"sink_properties=<properties for the sink> "
"volume=<initial volume, linear, 1.0 = full> "
"performance_mode=<0 none, 1 low latency, 2 power saving> "
"adaptive=<let the relay grow its buffer after underruns: 0 or 1> "
"buffer_ms=<device buffer the relay starts with, in ms; rounded up to whole bursts>");
#define DEFAULT_SINK_NAME "DirectAudio"
#define RECONNECT_USEC (500 * PA_USEC_PER_MSEC)
#define OFFLINE_TICK_USEC (20 * PA_USEC_PER_MSEC)
#define STATS_EVERY_USEC (30 * PA_USEC_PER_SEC)
/* Never queue more than this ahead of the relay's target, whatever it asks for. */
#define MAX_AHEAD_MS 250
/* Always keep at least this much queued. The relay starts its target at two bursts (8 ms), which
* a producer inside proot misses while the client is loading: two underruns in the first seconds
* on the FIT, steady stutter on a slower phone. 40 ms of slack costs 40 ms of latency at most. */
#define MIN_AHEAD_MS 40
/* The device buffer asked of the relay. Its own default is 12 ms rounded up to whole bursts: three
* 4 ms bursts on a device that grants a fast stream, but ONE 20 ms burst where Android grants a
* legacy one (an AYN Thor, Android 13), and a single burst has nothing to cover a late callback.
* 24 ms is two bursts there, Android's recommended minimum; the relay still grows it on xruns. */
#define DEFAULT_BUFFER_MS 24
#define AUDIO_NICE (-16)
static const char* const valid_modargs[] = {
"socket", "sink_name", "sink_properties", "volume", "performance_mode", "adaptive", "buffer_ms", NULL
};
struct userdata {
pa_core *core;
pa_module *module;
pa_sink *sink;
pa_thread *thread;
pa_thread_mq thread_mq;
pa_rtpoll *rtpoll;
char *socket_path;
int perf;
bool adaptive;
uint32_t buffer_ms;
pa_sample_spec ss;
size_t frame_size;
int fd;
struct da_ring *ring;
size_t ring_bytes;
int32_t burst;
pa_usec_t next_connect;
pa_usec_t offline_at;
pa_usec_t stats_at;
uint32_t underruns_reported;
pa_usec_t settled_at;
};
static void disconnect_relay(struct userdata *u) {
if (u->ring) {
__atomic_store_n(&u->ring->quit, 1, __ATOMIC_RELEASE);
munmap(u->ring, u->ring_bytes);
u->ring = NULL;
}
if (u->fd >= 0) {
close(u->fd);
u->fd = -1;
}
}
/* One try at the socket; on success the render ring is mapped and u->burst known. */
static int connect_relay(struct userdata *u) {
struct sockaddr_un addr;
struct da_hello hello;
struct da_ack ack;
struct msghdr msg;
struct iovec iov;
struct cmsghdr *cm;
union { struct cmsghdr align; char buf[CMSG_SPACE(sizeof(int) * 2)]; } cmsg;
int fds[2] = { -1, -1 };
ssize_t n;
if (strlen(u->socket_path) >= sizeof(addr.sun_path))
return -1;
if ((u->fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0)) < 0)
return -1;
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, u->socket_path);
if (connect(u->fd, (struct sockaddr*) &addr, sizeof(addr)) < 0)
goto fail;
memset(&hello, 0, sizeof(hello));
hello.magic = DA_HELLO_MAGIC;
hello.version = DA_RELAY_VERSION;
hello.flags = u->adaptive ? DA_HELLO_ADAPTIVE : 0;
hello.perf = u->perf;
hello.target_ms = (int32_t) u->buffer_ms;
hello.pid = (int32_t) getpid();
pa_snprintf(hello.name, sizeof(hello.name), "pulseaudio");
if (pa_loop_write(u->fd, &hello, sizeof(hello), NULL) != (ssize_t) sizeof(hello))
goto fail;
memset(&msg, 0, sizeof(msg));
iov.iov_base = &ack;
iov.iov_len = sizeof(ack);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = cmsg.buf;
msg.msg_controllen = sizeof(cmsg.buf);
do {
n = recvmsg(u->fd, &msg, MSG_WAITALL);
} while (n < 0 && errno == EINTR);
if (n != (ssize_t) sizeof(ack) || ack.magic != DA_ACK_MAGIC)
goto fail;
for (cm = CMSG_FIRSTHDR(&msg); cm; cm = CMSG_NXTHDR(&msg, cm)) {
if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SCM_RIGHTS) {
size_t count = (cm->cmsg_len - CMSG_LEN(0)) / sizeof(int);
if (count > 2) count = 2;
memcpy(fds, CMSG_DATA(cm), count * sizeof(int));
}
}
if (fds[1] >= 0)
close(fds[1]); /* a capture ring, not for this sink */
if (ack.status != 0 || fds[0] < 0 || ack.out_cap_frames <= 0) {
pa_log("directaudio-sink: the relay refused (status %d)", ack.status);
goto fail;
}
u->ring_bytes = da_ring_bytes((uint32_t) ack.out_cap_frames);
u->ring = mmap(NULL, u->ring_bytes, PROT_READ | PROT_WRITE, MAP_SHARED, fds[0], 0);
close(fds[0]);
if (u->ring == MAP_FAILED) {
u->ring = NULL;
goto fail;
}
if (u->ring->magic != DA_RING_MAGIC || u->ring->version != DA_RELAY_VERSION || u->ring->channels != DA_RING_CHANNELS) {
pa_log("directaudio-sink: ring header mismatch");
goto fail;
}
u->burst = ack.burst > 0 ? ack.burst : 192;
if (u->ring->rate != u->ss.rate)
pa_log("directaudio-sink: the relay's ring runs at %u Hz, the sink at %u; expect resampling artefacts", u->ring->rate, u->ss.rate);
u->stats_at = pa_rtclock_now();
u->settled_at = u->stats_at + 10 * PA_USEC_PER_SEC;
u->underruns_reported = u->ring->underruns;
pa_log("directaudio-sink: connected to the relay: %d Hz, burst %d, device buffer %d frames (asked %u ms), ring %d frames, target %d",
ack.rate, ack.burst, ack.buf_frames, u->buffer_ms, ack.out_cap_frames, (int) u->ring->target_frames);
return 0;
fail:
if (fds[0] >= 0) close(fds[0]);
disconnect_relay(u);
return -1;
}
static pa_usec_t frames_to_usec(const struct userdata *u, int64_t frames) {
return (pa_usec_t) (frames * (int64_t) PA_USEC_PER_SEC / (int64_t) u->ss.rate);
}
static pa_usec_t sink_latency(struct userdata *u) {
if (!u->ring)
return 0;
return frames_to_usec(u, (int64_t) da_ring_avail(u->ring) + (u->ring->hw_buf_frames > 0 ? u->ring->hw_buf_frames : 0));
}
/* Renders `frames` frames from the sink (silence when it is not open) into the ring. */
static void produce(struct userdata *u, uint32_t frames) {
struct da_ring *r = u->ring;
uint32_t w = __atomic_load_n(&r->widx, __ATOMIC_ACQUIRE);
uint32_t pos = w % r->cap_frames;
uint32_t first = PA_MIN(frames, r->cap_frames - pos);
float *dst = r->data + (size_t) pos * DA_RING_CHANNELS;
size_t bytes = (size_t) frames * u->frame_size;
if (PA_SINK_IS_OPENED(u->sink->thread_info.state)) {
pa_memchunk chunk;
const uint8_t *src;
if (u->sink->thread_info.rewind_requested)
pa_sink_process_rewind(u->sink, 0);
pa_sink_render_full(u->sink, bytes, &chunk);
src = pa_memblock_acquire_chunk(&chunk);
memcpy(dst, src, (size_t) first * u->frame_size);
if (frames > first)
memcpy(r->data, src + (size_t) first * u->frame_size, (size_t) (frames - first) * u->frame_size);
pa_memblock_release(chunk.memblock);
pa_memblock_unref(chunk.memblock);
} else {
memset(dst, 0, (size_t) first * u->frame_size);
if (frames > first)
memset(r->data, 0, (size_t) (frames - first) * u->frame_size);
}
__atomic_store_n(&r->widx, w + frames, __ATOMIC_RELEASE);
}
/* Tops the ring up to the relay's target. */
static int service_ring(struct userdata *u) {
struct da_ring *r = u->ring;
uint32_t avail, target, space;
if (__atomic_load_n(&r->quit, __ATOMIC_ACQUIRE) || __atomic_load_n(&r->state, __ATOMIC_ACQUIRE) == DA_RING_ERROR) {
pa_log("directaudio-sink: the relay closed the ring; reconnecting");
return -1;
}
target = (uint32_t) (r->target_frames > 0 ? r->target_frames : 2 * u->burst);
if (target < u->ss.rate / 1000 * MIN_AHEAD_MS)
target = u->ss.rate / 1000 * MIN_AHEAD_MS;
if (target > (uint32_t) (u->ss.rate / 1000 * MAX_AHEAD_MS))
target = (uint32_t) (u->ss.rate / 1000 * MAX_AHEAD_MS);
avail = da_ring_avail(r);
space = da_ring_space(r);
if (avail < target) {
uint32_t want = PA_MIN(target - avail, space);
if (want > 0)
produce(u, want);
}
/* Once, ten seconds in: what the relay's buffer has settled at, so a session log shows it. */
if (u->settled_at && pa_rtclock_now() >= u->settled_at) {
pa_log("directaudio-sink: after 10 s: device buffer %d frames, ring target %d, relay underruns %u",
(int) r->hw_buf_frames, (int) r->target_frames, r->underruns);
u->settled_at = 0;
}
if (r->underruns != u->underruns_reported && pa_rtclock_now() - u->stats_at >= STATS_EVERY_USEC) {
pa_log("directaudio-sink: relay reports %u underrun(s), target %d frames, device buffer %d", r->underruns, (int) r->target_frames, (int) r->hw_buf_frames);
u->underruns_reported = r->underruns;
u->stats_at = pa_rtclock_now();
}
return 0;
}
static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
struct userdata *u = PA_SINK(o)->userdata;
switch (code) {
case PA_SINK_MESSAGE_GET_LATENCY:
*((pa_usec_t*) data) = sink_latency(u);
return 0;
}
return pa_sink_process_msg(o, code, data, offset, chunk);
}
static void thread_func(void *userdata) {
struct userdata *u = userdata;
pa_log_debug("IO thread starting");
pa_thread_mq_install(&u->thread_mq);
if (setpriority(PRIO_PROCESS, (id_t) syscall(SYS_gettid), AUDIO_NICE) < 0)
pa_log_debug("directaudio-sink: could not raise the IO thread's priority (%s)", strerror(errno));
if (u->core->realtime_scheduling)
pa_thread_make_realtime(u->core->realtime_priority);
pa_rtpoll_set_timer_relative(u->rtpoll, 0);
for (;;) {
int ret;
pa_usec_t now = pa_rtclock_now();
if (!u->ring && now >= u->next_connect) {
if (connect_relay(u) < 0) {
u->next_connect = now + RECONNECT_USEC;
u->offline_at = now;
}
}
if (u->ring) {
if (service_ring(u) < 0) {
disconnect_relay(u);
u->next_connect = pa_rtclock_now() + RECONNECT_USEC;
u->offline_at = u->next_connect;
}
pa_rtpoll_set_timer_relative(u->rtpoll, PA_MAX(frames_to_usec(u, u->burst) / 2, PA_USEC_PER_MSEC));
} else {
/* No relay yet: a clocked null sink, so clients keep flowing and time keeps passing. */
if (PA_SINK_IS_OPENED(u->sink->thread_info.state) && now >= u->offline_at) {
pa_memchunk chunk;
if (u->sink->thread_info.rewind_requested)
pa_sink_process_rewind(u->sink, 0);
pa_sink_render_full(u->sink, pa_usec_to_bytes(OFFLINE_TICK_USEC, &u->ss), &chunk);
pa_memblock_unref(chunk.memblock);
u->offline_at = now + OFFLINE_TICK_USEC;
}
pa_rtpoll_set_timer_absolute(u->rtpoll, PA_MIN(u->offline_at, u->next_connect));
}
if ((ret = pa_rtpoll_run(u->rtpoll)) < 0)
goto fail;
if (ret == 0)
goto finish;
}
fail:
pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
finish:
pa_log_debug("IO thread shutting down");
}
void pa__done(pa_module *m);
int pa__init(pa_module *m) {
struct userdata *u = NULL;
pa_modargs *ma = NULL;
pa_sink_new_data data;
pa_channel_map map;
pa_cvolume volume;
uint32_t perf = 1, buffer_ms = DEFAULT_BUFFER_MS;
double linear_volume = 1.0;
bool adaptive = true;
const char *path;
pa_assert(m);
if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
pa_log("Failed to parse module arguments.");
goto fail;
}
if (!(path = pa_modargs_get_value(ma, "socket", NULL))) {
pa_log("socket= is required: the DirectAudio relay's unix socket");
goto fail;
}
if (pa_modargs_get_value_u32(ma, "performance_mode", &perf) < 0 || perf > 2) {
pa_log("performance_mode must be 0, 1 or 2");
goto fail;
}
if (pa_modargs_get_value_u32(ma, "buffer_ms", &buffer_ms) < 0 || buffer_ms > 200) {
pa_log("buffer_ms must be between 0 and 200");
goto fail;
}
if (pa_modargs_get_value_boolean(ma, "adaptive", &adaptive) < 0) {
pa_log("adaptive must be 0 or 1");
goto fail;
}
if (pa_modargs_get_value_double(ma, "volume", &linear_volume) < 0 || linear_volume < 0.0 || linear_volume > 10.0) {
pa_log("volume must be a linear factor between 0 and 10");
goto fail;
}
m->userdata = u = pa_xnew0(struct userdata, 1);
u->core = m->core;
u->module = m;
u->fd = -1;
u->socket_path = pa_xstrdup(path);
u->perf = (int) perf;
u->adaptive = adaptive;
u->buffer_ms = buffer_ms;
/* The ring's format, fixed by the relay: float stereo at 48 kHz. */
u->ss.format = PA_SAMPLE_FLOAT32NE;
u->ss.rate = DA_RING_RATE;
u->ss.channels = DA_RING_CHANNELS;
u->frame_size = pa_frame_size(&u->ss);
u->burst = 192;
pa_channel_map_init_stereo(&map);
u->rtpoll = pa_rtpoll_new();
if (pa_thread_mq_init(&u->thread_mq, m->core->mainloop, u->rtpoll) < 0) {
pa_log("pa_thread_mq_init() failed.");
goto fail;
}
pa_sink_new_data_init(&data);
data.driver = __FILE__;
data.module = m;
pa_sink_new_data_set_name(&data, pa_modargs_get_value(ma, "sink_name", DEFAULT_SINK_NAME));
pa_sink_new_data_set_sample_spec(&data, &u->ss);
pa_sink_new_data_set_channel_map(&data, &map);
pa_cvolume_set(&volume, u->ss.channels, pa_sw_volume_from_linear(linear_volume));
pa_sink_new_data_set_volume(&data, &volume);
pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, "directaudio");
pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, "Android audio output (DirectAudio)");
pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "directaudio");
if (pa_modargs_get_proplist(ma, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
pa_log("Invalid properties");
pa_sink_new_data_done(&data);
goto fail;
}
u->sink = pa_sink_new(m->core, &data, PA_SINK_HARDWARE | PA_SINK_LATENCY);
pa_sink_new_data_done(&data);
if (!u->sink) {
pa_log("Failed to create sink.");
goto fail;
}
u->sink->parent.process_msg = sink_process_msg;
u->sink->userdata = u;
pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
pa_sink_set_rtpoll(u->sink, u->rtpoll);
pa_sink_set_max_request(u->sink, pa_usec_to_bytes(MAX_AHEAD_MS * PA_USEC_PER_MSEC, &u->ss));
pa_sink_set_fixed_latency(u->sink, 40 * PA_USEC_PER_MSEC);
if (!(u->thread = pa_thread_new("directaudio-sink", thread_func, u))) {
pa_log("Failed to create thread.");
goto fail;
}
pa_sink_put(u->sink);
pa_modargs_free(ma);
return 0;
fail:
if (ma)
pa_modargs_free(ma);
pa__done(m);
return -1;
}
int pa__get_n_used(pa_module *m) {
struct userdata *u;
pa_assert(m);
pa_assert_se(u = m->userdata);
return pa_sink_linked_by(u->sink);
}
void pa__done(pa_module *m) {
struct userdata *u;
pa_assert(m);
if (!(u = m->userdata))
return;
if (u->sink)
pa_sink_unlink(u->sink);
if (u->thread) {
pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
pa_thread_free(u->thread);
}
pa_thread_mq_done(&u->thread_mq);
if (u->sink)
pa_sink_unref(u->sink);
disconnect_relay(u);
if (u->rtpoll)
pa_rtpoll_free(u->rtpoll);
pa_xfree(u->socket_path);
pa_xfree(u);
}
+5 -5
View File
@@ -300,8 +300,8 @@ if [[ ! -f "${pa_source}/src/pulse/version.h.in" ]]; then
fi
sink_output="${staging_dir}/sink-out"
"${repo_root}/tools/directaudio/fetch.sh" "${repo_root}" "${sink_output}"
"${repo_root}/tools/aaudio-sink/build.sh" "${pa_source}" "${sink_output}"
"${repo_root}/tools/directaudio-relay/build.sh" "${repo_root}/app/src/main/jniLibs/arm64-v8a"
# proot is rebuilt only when its sources (source.env, the patches, the build script) changed since
# the libraries in jniLibs were built.
proot_out="${repo_root}/app/src/main/jniLibs/arm64-v8a"
@@ -319,14 +319,14 @@ bundle_dir="${staging_dir}/pulseaudio-bundle"
mkdir -p "${bundle_dir}"
zstd -dc "${bundle_asset}" | tar -xf - -C "${bundle_dir}"
if [[ -e "${bundle_dir}/modules/arm64/module-aaudio-sink.so" \
|| -e "${bundle_dir}/modules/arm64/module-directaudio-sink.so" ]]; then
|| -e "${bundle_dir}/modules/arm64/module-directaudio-native-sink.so" ]]; then
echo "The committed audio bundle already contains a built ARM64 sink." >&2
exit 1
fi
install -m755 "${sink_output}/module-aaudio-sink.so" \
"${bundle_dir}/modules/arm64/module-aaudio-sink.so"
install -m755 "${sink_output}/module-directaudio-sink.so" \
"${bundle_dir}/modules/arm64/module-directaudio-sink.so"
install -m755 "${sink_output}/module-directaudio-native-sink.so" \
"${bundle_dir}/modules/arm64/module-directaudio-native-sink.so"
tar -cf - -C "${bundle_dir}" . | zstd -19 -T0 -c > "${staging_dir}/pulseaudio.tzst"
bundle_replaced=1
mv "${staging_dir}/pulseaudio.tzst" "${bundle_asset}"
@@ -344,7 +344,7 @@ unzip -p "${apk}" assets/pulseaudio.tzst | zstd -dc | tar -xf - -C "${audio_chec
for audio_file in \
pactl \
modules/arm64/module-aaudio-sink.so \
modules/arm64/module-directaudio-sink.so; do
modules/arm64/module-directaudio-native-sink.so; do
if [[ ! -f "${audio_check}/${audio_file}" ]]; then
echo "APK audio bundle is missing ${audio_file}." >&2
exit 1
-40
View File
@@ -1,40 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
OUTDIR=$1
mkdir -p "$OUTDIR"
: "${NDK:?set NDK to the Android NDK root}"
API=28
HERE=$(cd "$(dirname "$0")" && pwd)
REPO=$(cd "$HERE/../.." && pwd)
case "$(uname -s):$(uname -m)" in
Darwin:arm64) NDK_HOST=darwin-arm64 ;;
Darwin:x86_64) NDK_HOST=darwin-x86_64 ;;
Linux:x86_64) NDK_HOST=linux-x86_64 ;;
Linux:aarch64|Linux:arm64) NDK_HOST=linux-aarch64 ;;
*) echo "Unsupported build host: $(uname -s) $(uname -m)" >&2; exit 1 ;;
esac
TOOLCHAIN="$NDK/toolchains/llvm/prebuilt/$NDK_HOST/bin"
if [[ ! -d "$TOOLCHAIN" && "$NDK_HOST" == darwin-arm64 && -d "$NDK/toolchains/llvm/prebuilt/darwin-x86_64/bin" ]]; then
TOOLCHAIN="$NDK/toolchains/llvm/prebuilt/darwin-x86_64/bin"
fi
if [[ ! -d "$TOOLCHAIN" && "$NDK_HOST" == linux-aarch64 && -d "$NDK/toolchains/llvm/prebuilt/linux-x86_64/bin" ]]; then
TOOLCHAIN="$NDK/toolchains/llvm/prebuilt/linux-x86_64/bin"
fi
CC="$TOOLCHAIN/aarch64-linux-android${API}-clang"
if [[ ! -x "$CC" ]]; then
echo "Android NDK toolchain not found at $TOOLCHAIN" >&2
exit 1
fi
OUT="$OUTDIR/libdirectaudiorelay.so"
"$CC" -O2 -Wall -Wextra -Wno-unused-parameter -Wno-sign-compare -fPIE -pie -Wl,-z,max-page-size=16384 \
-I"$REPO/tools/aaudio-sink" \
-o "$OUT" "$HERE/directaudio-relay.c" -laaudio -llog
"$TOOLCHAIN/llvm-strip" --strip-unneeded "$OUT"
NEEDED=$("$TOOLCHAIN/llvm-readelf" -d "$OUT" | sed -n 's/.*NEEDED.*\[\(.*\)\]/\1/p' | tr '\n' ' ')
echo "$(basename "$OUT") NEEDED: $NEEDED"
for lib in $NEEDED; do
case $lib in libaaudio.so|liblog.so|libc.so|libm.so|libdl.so) ;;
*) echo "ERROR: unexpected dependency $lib"; exit 1 ;;
esac
done
ls -l "$OUT"
File diff suppressed because it is too large. Load diff
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env bash
# Fetches the DirectAudio pieces DroidDeck ships from the pinned release in tools/directaudio/release.env
# and puts them where the build reads them. Four zips, checksummed:
# directaudio-linux-wine11.zip the game driver for Valve Proton 11 / Experimental / GE-Proton
# directaudio-linux-wine11-systhread.zip the game driver for Proton-CachyOS (system-thread mmdevapi)
# directaudio-linux-relay.zip the Android-side helper (speaker + microphone for games)
# directaudio-linux-sink.zip the PulseAudio sinks; the app ships module-directaudio-native-sink
#
# tools/directaudio/fetch.sh <repo root> <dir to receive the sink modules>
#
# Driver sets -> app/src/main/assets/directaudio/<set>/ (generated, ignored by git)
# Helper -> app/src/main/jniLibs/arm64-v8a/libdirectaudiorelay.so (generated, ignored by git)
# Sink -> <sink dir>/module-directaudio-native-sink.so for the audio bundle, next to the
# module-aaudio-sink.so tools/aaudio-sink builds (the fallback).
set -euo pipefail
repo_root=$1
sink_out=$2
# shellcheck source=release.env
. "${repo_root}/tools/directaudio/release.env"
for v in DIRECTAUDIO_REPO DIRECTAUDIO_TAG DIRECTAUDIO_WINE11_SHA256 DIRECTAUDIO_SYSTHREAD_SHA256 DIRECTAUDIO_RELAY_SHA256 DIRECTAUDIO_SINK_SHA256; do
[[ -n "${!v:-}" && "${!v}" != TBD ]] || { echo "tools/directaudio/release.env: ${v} is not set" >&2; exit 1; }
done
work=$(mktemp -d)
trap 'rm -rf "${work}"' EXIT
fetch() {
local name=$1 sha=$2
curl -fsSL --retry 3 -o "${work}/${name}" \
"https://github.com/${DIRECTAUDIO_REPO}/releases/download/${DIRECTAUDIO_TAG}/${name}"
echo "${sha} ${work}/${name}" | sha256sum -c - >/dev/null || { echo "${name}: checksum mismatch" >&2; exit 1; }
}
fetch directaudio-linux-wine11.zip "${DIRECTAUDIO_WINE11_SHA256}"
fetch directaudio-linux-wine11-systhread.zip "${DIRECTAUDIO_SYSTHREAD_SHA256}"
fetch directaudio-linux-relay.zip "${DIRECTAUDIO_RELAY_SHA256}"
fetch directaudio-linux-sink.zip "${DIRECTAUDIO_SINK_SHA256}"
assets="${repo_root}/app/src/main/assets/directaudio"
rm -rf "${assets}"
for set in linux-wine11 linux-wine11-systhread; do
mkdir -p "${assets}/${set}"
unzip -q "${work}/directaudio-${set}.zip" -d "${assets}/${set}"
for f in aarch64-unix/winedirectaudio.so aarch64-windows/winedirectaudio.drv i386-windows/winedirectaudio.drv version.txt; do
test -f "${assets}/${set}/${f}" || { echo "${set}: ${f} missing from the release zip" >&2; exit 1; }
done
rm -f "${assets}/${set}/README.md"
done
# Each set says which interface it was built for; the name must not lie.
grep -q '^abi wine11$' "${assets}/linux-wine11/version.txt"
grep -q '^abi systhread$' "${assets}/linux-wine11-systhread/version.txt"
mkdir -p "${work}/relay" "${work}/sink" "${sink_out}" "${repo_root}/app/src/main/jniLibs/arm64-v8a"
unzip -q "${work}/directaudio-linux-relay.zip" -d "${work}/relay"
install -m755 "${work}/relay/libdirectaudiorelay.so" "${repo_root}/app/src/main/jniLibs/arm64-v8a/libdirectaudiorelay.so"
unzip -q "${work}/directaudio-linux-sink.zip" -d "${work}/sink"
install -m755 "${work}/sink/module-directaudio-native-sink.so" "${sink_out}/"
echo "DirectAudio ${DIRECTAUDIO_TAG}: two driver sets, the relay helper and the client sink in place"
+9
View File
@@ -0,0 +1,9 @@
# The DirectAudio release this build ships, pinned: nothing compiled for audio lives in this repo.
# Source and release notes: https://github.com/The412Banner/directaudio
# Bump the tag and the four checksums together (sha256 of each zip, from the release's SHA256SUMS.txt).
DIRECTAUDIO_REPO=The412Banner/directaudio
DIRECTAUDIO_TAG=directaudio-linux-v1.1.0
DIRECTAUDIO_WINE11_SHA256=835e6cab072f5148893c43379e60506483aeb3f1444e777b430c295cbeb472c9
DIRECTAUDIO_SYSTHREAD_SHA256=2ddc47f446142d5940540ad40a423ca8d47fd536e3225b888df1077c6be7329e
DIRECTAUDIO_RELAY_SHA256=b68eb6d7a892fd92a1cd73fac36dc05cabb77cc73792e2c582d3eeccad355942
DIRECTAUDIO_SINK_SHA256=1d5d3ed709e5389ef7603f019c62b07e4e8428bb42882193d4a144a5c15425b6
+245
View File
@@ -0,0 +1,245 @@
#!/usr/bin/env python3
"""Run a device scenario through droiddeckctl, repeatedly, and report each run.
A scenario is JSON (stdlib only, no YAML):
{
"name": "skyrim-focus",
"vars": {"appId": 489830},
"repeat": 6,
"setup": [["wake"]],
"before": [["start", "steam", "--wait", "--reuse", "--timeout", "180"]],
"steps": [["launch", "${appId}", "--wait", "--timeout", "240"],
{"assert": "session.focus.focusedApp", "equals": "${appId}"},
{"screenshot": "in-game"},
["quit", "${appId}"]],
"after": [["quit", "${appId}"]],
"teardown": [["stop"]]
}
A list step is a droiddeckctl command line; its JSON answer becomes "last". An assert step checks
a dotted path in the last answer ("equals", "in", "contains", "exists", "not"); {"sleep": s},
{"screenshot": "name"} and {"record": "name", "seconds": s} do what they say. ${var} is replaced
from "vars" and --var KEY=VALUE. setup and teardown run once; steps run "repeat" times (or
--repeat), each preceded by "before" (a failure there fails the run) and followed by "after"
whether it passed or not, so a failed run cannot leave a game running into the next and a session
that died in one run is started again for the next. A failing run gets a screenshot, the focus state and the session's logs in
its folder.
tools/droiddeck-scenario tools/scenarios/steam-game-focus.json --var appId=489830 --out ./runs
Exit status: 0 when every run passed, 1 when any failed, 2 for a bad scenario or a failed setup.
"""
from __future__ import annotations
import argparse
import importlib.machinery
import importlib.util
import json
import os
import re
import sys
import time
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
_loader = importlib.machinery.SourceFileLoader("droiddeckctl", str(HERE / "droiddeckctl"))
_spec = importlib.util.spec_from_loader("droiddeckctl", _loader)
ctl = importlib.util.module_from_spec(_spec)
_loader.exec_module(ctl)
class StepFailed(Exception):
pass
def write_json(path: Path, value) -> None:
with os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600), "w") as stream:
os.fchmod(stream.fileno(), 0o600)
json.dump(value, stream, indent=2, sort_keys=True)
def substitute(value, variables: dict):
if isinstance(value, str):
whole = re.fullmatch(r"\$\{(\w+)\}", value)
if whole and whole.group(1) in variables:
return variables[whole.group(1)]
return re.sub(r"\$\{(\w+)\}", lambda m: str(variables.get(m.group(1), m.group(0))), value)
if isinstance(value, list):
return [substitute(v, variables) for v in value]
if isinstance(value, dict):
return {k: substitute(v, variables) for k, v in value.items()}
return value
def lookup(data, path: str):
for part in path.split("."):
if isinstance(data, list) and part.isdigit():
data = data[int(part)] if int(part) < len(data) else None
elif isinstance(data, dict):
data = data.get(part)
else:
return None
return data
def check(step: dict, last: dict) -> None:
path = step["assert"]
value = lookup(last, path)
if "equals" in step and value != step["equals"]:
raise StepFailed(f"{path} is {value!r}, expected {step['equals']!r}")
if "not" in step and value == step["not"]:
raise StepFailed(f"{path} is {value!r}")
if "in" in step and value not in step["in"]:
raise StepFailed(f"{path} is {value!r}, expected one of {step['in']!r}")
if "contains" in step and (not isinstance(value, (list, str)) or step["contains"] not in value):
raise StepFailed(f"{path} is {value!r}, expected it to contain {step['contains']!r}")
if step.get("exists") is True and value is None:
raise StepFailed(f"{path} is missing")
class Runner:
def __init__(self, adb: str, serial: str, out: Path, global_args: list[str]):
self.adb = adb
self.serial = serial
self.out = out
self.global_args = global_args
self.parser = ctl.build_parser()
def ctl(self, words: list) -> dict:
args = self.parser.parse_args(self.global_args + [str(w) for w in words])
try:
return ctl.execute(args, self.adb, self.serial)
except ctl.ControlError as exc:
raise StepFailed(f"droiddeckctl {' '.join(map(str, words))}: {exc.code}: {exc}") from exc
def run_steps(self, steps: list, folder: Path, log: list) -> None:
last: dict = {}
for index, step in enumerate(steps):
started = time.monotonic()
entry = {"step": index, "what": step}
try:
if isinstance(step, list):
last = self.ctl(step)
entry["result"] = last
elif "assert" in step:
check(step, last)
elif "sleep" in step:
time.sleep(float(step["sleep"]))
elif "screenshot" in step:
entry["result"] = ctl.screenshot(self.adb, self.serial, str(folder / f"{step['screenshot']}.png"),
step.get("display"))
elif "record" in step:
entry["result"] = ctl.record(self.adb, self.serial, str(folder / f"{step['record']}.mp4"),
float(step.get("seconds", 10)), step.get("display"))
else:
raise StepFailed(f"Unknown step {step!r}")
entry["ok"] = True
except (StepFailed, ctl.ControlError) as exc:
entry["ok"] = False
entry["error"] = str(exc)
raise StepFailed(f"step {index} {json.dumps(step)}: {exc}") from exc
finally:
entry["seconds"] = round(time.monotonic() - started, 2)
log.append(entry)
def evidence(self, folder: Path) -> dict:
"""What a failed run leaves behind: the screen, gamescope's focus, the session's logs."""
found = {}
for name, action in (
("screenshot", lambda: ctl.screenshot(self.adb, self.serial, str(folder / "failure.png"), None)),
("focus", lambda: self.ctl(["focus"])),
("logs", lambda: self.ctl(["logs", "latest", str(folder / "session")])),
):
try:
found[name] = action()
except Exception as exc: # evidence is best effort
found[name] = {"ok": False, "error": str(exc)}
write_json(folder / "evidence.json", found)
return {k: v.get("ok", True) if isinstance(v, dict) else True for k, v in found.items()}
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("scenario")
parser.add_argument("--var", action="append", default=[], metavar="KEY=VALUE")
parser.add_argument("--repeat", type=int)
parser.add_argument("--out", default="scenario-runs")
parser.add_argument("--adb")
parser.add_argument("--serial")
parser.add_argument("--keep-going", action="store_true", help="run every repeat even after a failure")
args = parser.parse_args(argv)
try:
scenario = json.loads(Path(args.scenario).read_text())
except (OSError, ValueError) as exc:
print(json.dumps({"ok": False, "error": f"Cannot read scenario: {exc}"}))
return 2
variables = dict(scenario.get("vars", {}))
for item in args.var:
key, _, value = item.partition("=")
variables[key] = int(value) if value.lstrip("-").isdigit() else value
scenario = substitute(scenario, variables)
repeat = args.repeat or int(scenario.get("repeat", 1))
adb = ctl.adb_path(args.adb)
serial = ctl.resolve_serial(adb, args.serial, log=True)
out = Path(args.out).expanduser().resolve() / f"{scenario.get('name', 'scenario')}-{time.strftime('%Y%m%d-%H%M%S')}"
out.mkdir(parents=True, exist_ok=True, mode=0o700)
global_args = (["--adb", adb] if args.adb else []) + ["--serial", serial]
runner = Runner(adb, serial, out, global_args)
report = {"name": scenario.get("name"), "serial": serial, "vars": variables, "repeat": repeat,
"out": str(out), "runs": []}
status = 0
setup_log: list = []
try:
runner.run_steps(scenario.get("setup", []), out, setup_log)
for run in range(1, repeat + 1):
folder = out / f"run-{run:02d}"
folder.mkdir(mode=0o700)
log: list = []
started = time.monotonic()
result = {"run": run, "folder": str(folder)}
try:
runner.run_steps(scenario.get("before", []) + scenario.get("steps", []), folder, log)
result["ok"] = True
except StepFailed as exc:
result["ok"] = False
result["error"] = str(exc)
result["evidence"] = runner.evidence(folder)
status = 1
after: list = []
try:
runner.run_steps(scenario.get("after", []), folder, after)
except StepFailed as exc:
result["afterError"] = str(exc)
log.extend({**entry, "after": True} for entry in after)
result["seconds"] = round(time.monotonic() - started, 2)
write_json(folder / "steps.json", log)
report["runs"].append(result)
print(f"run {run}/{repeat}: {'PASS' if result['ok'] else 'FAIL ' + result['error']}", file=sys.stderr)
if not result["ok"] and not args.keep_going:
break
except StepFailed as exc:
report["setupError"] = str(exc)
status = 2
finally:
teardown_log: list = []
try:
runner.run_steps(scenario.get("teardown", []), out, teardown_log)
except StepFailed as exc:
report["teardownError"] = str(exc)
write_json(out / "setup.json", setup_log + teardown_log)
passed = sum(1 for r in report["runs"] if r["ok"])
report.update({"ok": status == 0, "passed": passed, "failed": len(report["runs"]) - passed})
write_json(out / "report.json", report)
print(json.dumps(report, indent=2, sort_keys=True))
return status
if __name__ == "__main__":
raise SystemExit(main())
+470 -96
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""Control a debug DroidDeck build over ADB."""
"""Control a DroidDeck build over ADB (docs/agent-control.md)."""
from __future__ import annotations
@@ -7,16 +7,21 @@ import argparse
import base64
import json
import os
import re
import shutil
import subprocess
import sys
import time
from pathlib import Path
from adb_device import DeviceResolutionError, resolve_serial
sys.path.insert(0, str(Path(__file__).resolve().parent))
from adb_device import DeviceResolutionError, resolve_serial # noqa: E402
AUTHORITY = "content://com.droiddeck.launcher.agent"
PACKAGE = "com.droiddeck.launcher"
STEAM_CLIENT_APP = 769
REQUEST_CAP = 256 * 1024
class ControlError(RuntimeError):
@@ -46,7 +51,7 @@ def adb_path(configured: str | None) -> str:
raise ControlError("adb not found; set ADB, ANDROID_HOME, or ANDROID_SDK_ROOT", "ADB_NOT_FOUND")
def run_adb(adb: str, serial: str, *args: str, timeout: int = 30) -> subprocess.CompletedProcess[bytes]:
def run_adb(adb: str, serial: str, *args: str, timeout: float = 30) -> subprocess.CompletedProcess[bytes]:
try:
return subprocess.run(
[adb, "-s", serial, *args], capture_output=True, check=False, timeout=timeout
@@ -59,7 +64,7 @@ def _content_result(output: str) -> dict:
marker = "json="
start = output.find(marker)
if start < 0:
detail = output.strip() or "The debug agent provider returned no result"
detail = output.strip() or "The agent provider returned no result"
raise ControlError(detail, "INVALID_PROVIDER_RESPONSE")
raw = output[start + len(marker):].lstrip()
try:
@@ -71,14 +76,22 @@ def _content_result(output: str) -> dict:
raise ControlError("Could not decode the agent provider response", "INVALID_PROVIDER_RESPONSE") from exc
def provider_call(adb: str, serial: str, method: str, arg: str | None = None, request: dict | None = None) -> dict:
def encode_request(request: dict) -> str:
encoded = base64.b64encode(json.dumps(request, separators=(",", ":")).encode()).decode()
if len(encoded) > REQUEST_CAP:
raise ControlError("The encoded request exceeds 256 KiB", "INVALID_REQUEST")
return encoded
def provider_call(adb: str, serial: str, method: str, arg: str | None = None, request: dict | None = None,
timeout: float = 30) -> dict:
command = ["shell", "content", "call", "--uri", AUTHORITY, "--method", method]
if arg is not None:
command.extend(["--arg", arg])
if request is not None:
encoded = base64.b64encode(json.dumps(request, separators=(",", ":")).encode()).decode()
encoded = encode_request(request)
command.extend(["--extra", f"request:s:{encoded}"])
result = run_adb(adb, serial, *command)
result = run_adb(adb, serial, *command, timeout=timeout)
output = (result.stdout + result.stderr).decode(errors="replace")
response = _content_result(output)
if result.returncode != 0 and response.get("ok") is not False:
@@ -86,8 +99,16 @@ def provider_call(adb: str, serial: str, method: str, arg: str | None = None, re
return response
def checked(response: dict, default_code: str) -> dict:
"""A provider or guest answer, raised as a ControlError when it carries ok: false."""
if response.get("ok") is False:
error = response.get("error", {})
raise ControlError(error.get("message", default_code), error.get("code", default_code))
return response
def start_agent_activity(adb: str, serial: str, request: dict) -> None:
encoded = base64.b64encode(json.dumps(request, separators=(",", ":")).encode()).decode()
encoded = encode_request(request)
result = run_adb(
adb,
serial,
@@ -96,7 +117,7 @@ def start_agent_activity(adb: str, serial: str, request: dict) -> None:
"start",
"-W",
"-n",
"com.droiddeck.launcher/.agent.AgentStartActivity",
f"{PACKAGE}/.agent.AgentStartActivity",
"--es",
"request",
encoded,
@@ -126,23 +147,18 @@ def confirm_start(adb: str, serial: str, request: dict, previous: dict) -> dict:
def get_state(adb: str, serial: str) -> dict:
response = provider_call(adb, serial, "state")
if response.get("ok") is False:
error = response.get("error", {})
raise ControlError(error.get("message", "state failed"), error.get("code", "STATE_FAILED"))
return response
return checked(provider_call(adb, serial, "state"), "STATE_FAILED")
def wait_for_phase(adb: str, serial: str, wanted: str, timeout: float) -> dict:
def wait_until(adb: str, serial: str, describe: str, done, timeout: float, poll: float = 1.0) -> dict:
"""Poll state until done(state) is true. A failed session ends the wait at once."""
deadline = time.monotonic() + timeout
last_state: dict | None = None
while True:
last_state = get_state(adb, serial)
session = last_state.get("session", {})
phase = session.get("phase")
if phase == wanted:
return last_state
if phase == "FAILED" and wanted != "FAILED":
state = get_state(adb, serial)
session = state.get("session", {})
if done(state):
return state
if session.get("phase") == "FAILED":
failure = session.get("failure") or {}
raise ControlError(
f"Session failed ({failure.get('code', 'FAILED')}): {failure.get('message', 'unknown error')}",
@@ -150,10 +166,35 @@ def wait_for_phase(adb: str, serial: str, wanted: str, timeout: float) -> dict:
)
remaining = deadline - time.monotonic()
if remaining <= 0:
focus = session.get("focus") or {}
raise ControlError(
f"Timed out waiting for {wanted}; last phase was {phase}", "TIMEOUT"
f"Timed out waiting for {describe}; phase {session.get('phase')}, focused app {focus.get('focusedApp')}",
"TIMEOUT",
)
time.sleep(min(1.0, remaining))
time.sleep(min(poll, remaining))
def wait_for_phase(adb: str, serial: str, wanted: str, timeout: float) -> dict:
if wanted == "FAILED":
deadline = time.monotonic() + timeout
while True:
state = get_state(adb, serial)
if state.get("session", {}).get("phase") == "FAILED":
return state
if time.monotonic() > deadline:
raise ControlError("Timed out waiting for FAILED", "TIMEOUT")
time.sleep(1)
return wait_until(adb, serial, wanted, lambda s: s.get("session", {}).get("phase") == wanted, timeout)
def focused(state: dict, app_id: int | None) -> bool:
"""The game has focus the way a player sees it: gamescope focuses it and it is in the list the
Steam client orders the base layer from. app_id None means any game (not the client)."""
focus = state.get("session", {}).get("focus") or {}
current = focus.get("focusedApp")
if app_id is None:
return current not in (None, 0, STEAM_CLIENT_APP)
return current == app_id and app_id in (focus.get("focusableApps") or [])
def wait_for_artifacts(adb: str, serial: str, state: dict, timeout: float) -> dict:
@@ -174,14 +215,123 @@ def add_serial(response: dict, serial: str) -> dict:
return response
# --- displays ------------------------------------------------------------------------------------
def displays(adb: str, serial: str) -> list[dict]:
"""Logical displays with the SurfaceFlinger (physical) id screencap and screenrecord want."""
result = run_adb(adb, serial, "shell", "dumpsys", "display", timeout=30)
text = result.stdout.decode(errors="replace")
devices = dict(re.findall(r'DisplayDeviceInfo\{"([^"]+)": uniqueId="local:(\d+)"', text))
out = []
for block in re.split(r"\n Display (?=\d+:)", text)[1:]:
logical = int(block.split(":", 1)[0])
device = re.search(r"mPrimaryDisplayDevice=(.+)", block)
size = re.search(r"real (\d+) x (\d+)", block)
name = device.group(1).strip() if device else None
out.append({
"display": logical,
"name": name,
"physicalId": devices.get(name) if name else None,
"size": [int(size.group(1)), int(size.group(2))] if size else None,
})
return out
def physical_display(adb: str, serial: str, logical: int | None) -> str | None:
if logical is None:
return None
for d in displays(adb, serial):
if d["display"] == logical:
if not d["physicalId"]:
raise ControlError(f"Display {logical} has no physical id to capture", "NO_SUCH_DISPLAY")
return d["physicalId"]
raise ControlError(f"No display {logical}; see `droiddeckctl displays`", "NO_SUCH_DISPLAY")
def screenshot(adb: str, serial: str, path: str, display: int | None) -> dict:
destination = Path(path).expanduser().resolve()
physical = physical_display(adb, serial, display)
command = ["exec-out", "screencap", "-p"] + (["-d", physical] if physical else [])
result = run_adb(adb, serial, *command, timeout=30)
if result.returncode != 0 or not result.stdout.startswith(b"\x89PNG"):
detail = result.stderr.decode(errors="replace").strip()
raise ControlError(detail or "screencap failed", "SCREENSHOT_FAILED")
try:
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_bytes(result.stdout)
except OSError as exc:
raise ControlError(str(exc), "FILE_IO") from exc
return {"ok": True, "command": "screenshot", "path": str(destination), "display": display}
def record(adb: str, serial: str, path: str, seconds: float, display: int | None) -> dict:
destination = Path(path).expanduser().resolve()
remote = "/data/local/tmp/droiddeckctl-record.mp4"
physical = physical_display(adb, serial, display)
command = ["shell", "screenrecord", "--time-limit", str(max(1, min(180, int(seconds))))]
if physical:
command += ["--display-id", physical]
result = run_adb(adb, serial, *command, remote, timeout=seconds + 30)
if result.returncode != 0:
raise ControlError(result.stderr.decode(errors="replace").strip() or "screenrecord failed", "RECORD_FAILED")
try:
destination.parent.mkdir(parents=True, exist_ok=True)
except OSError as exc:
raise ControlError(str(exc), "FILE_IO") from exc
pulled = run_adb(adb, serial, "pull", remote, str(destination), timeout=120)
run_adb(adb, serial, "shell", "rm", "-f", remote)
if pulled.returncode != 0:
raise ControlError(pulled.stderr.decode(errors="replace").strip() or "adb pull failed", "RECORD_FAILED")
return {"ok": True, "command": "record", "path": str(destination), "seconds": seconds, "display": display}
# --- commands ------------------------------------------------------------------------------------
def start_session(adb: str, serial: str, request: dict) -> dict:
if request.get("mode") == "run":
require_commands(adb, serial)
current = get_state(adb, serial)
if current["session"].get("phase") not in {"IDLE", "FAILED"} or current["session"].get("running"):
raise ControlError("A session is already starting or running", "SESSION_ACTIVE")
start_agent_activity(adb, serial, request)
return confirm_start(adb, serial, request, current["session"])
def require_commands(adb: str, serial: str) -> dict:
access = checked(provider_call(adb, serial, "access"), "ACCESS_FAILED")
if access.get("commands") is not True:
raise ControlError("Debugging tools are off: turn on Setup > Session > Debugging tools on the device",
"AGENT_COMMANDS_DISABLED")
return access
def input_request(args: argparse.Namespace) -> dict:
kind = args.input_type
if kind == "key":
return {"type": "key", "key": args.key, "action": args.action, "modifiers": args.mod or [], "holdMs": args.hold}
if kind == "text":
return {"type": "text", "text": args.text, "commit": args.commit}
if kind == "tap":
return {"type": "tap", "x": args.x, "y": args.y, "space": args.space, "holdMs": args.hold}
if kind == "swipe":
return {"type": "swipe", "x": args.x, "y": args.y, "x2": args.x2, "y2": args.y2,
"space": args.space, "durationMs": args.duration}
if kind == "pad":
return {"type": "pad", "button": args.button, "action": args.action, "holdMs": args.hold}
if kind == "stick":
return {"type": "stick", "stick": args.stick, "x": args.x, "y": args.y, "holdMs": args.hold}
if kind == "trigger":
return {"type": "trigger", "trigger": args.trigger, "value": args.value, "holdMs": args.hold}
raise ControlError(f"Unknown input type {kind}", "INVALID_INPUT")
def execute(args: argparse.Namespace, adb: str, serial: str) -> dict:
if args.command == "state":
command = args.command
if command == "state":
return add_serial(get_state(adb, serial), serial)
if args.command == "start":
current = get_state(adb, serial)
if current["session"].get("phase") not in {"IDLE", "FAILED"} or current["session"].get("running"):
raise ControlError("A session is already starting or running", "SESSION_ACTIVE")
if command == "start":
request = {"mode": args.mode}
if args.mode == "steam":
if args.ui == "desktop":
@@ -190,59 +340,152 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict:
if not args.url.startswith("steam://"):
raise ControlError("Steam URL must start with steam://", "INVALID_STEAM_URL")
request["steamUrl"] = args.url
start_agent_activity(adb, serial, request)
started = confirm_start(adb, serial, request, current["session"])
if args.reuse:
# A scenario's per-run "before": keep a session of this mode that is already up, so only
# a run after one that ended (a crash, the low-memory killer) starts a new one.
current = get_state(adb, serial)["session"]
wanted = {"steam": "steam", "desktop": "lxqt"}[args.mode]
if current.get("running") and current.get("mode") == wanted and current.get("phase") not in {"STOPPING", "FAILED"}:
state = wait_for_phase(adb, serial, "READY", args.timeout) if args.wait else get_state(adb, serial)
return add_serial(dict(state, reused=True), serial)
started = start_session(adb, serial, request)
if args.wait:
return add_serial(wait_for_phase(adb, serial, "READY", args.timeout), serial)
session = started["session"]
return add_serial({
"ok": True,
"command": "start",
"mode": args.mode,
"sessionId": session.get("id"),
"phase": session.get("phase"),
}, serial)
return add_serial({"ok": True, "command": "start", "mode": args.mode,
"sessionId": session.get("id"), "phase": session.get("phase")}, serial)
if args.command == "run":
current = get_state(adb, serial)
if current["session"].get("phase") not in {"IDLE", "FAILED"} or current["session"].get("running"):
raise ControlError("A session is already starting or running", "SESSION_ACTIVE")
if command == "run":
program_args = args.arguments[1:] if args.arguments[:1] == ["--"] else args.arguments
request = {"mode": "run", "program": args.program, "programArgs": program_args}
start_agent_activity(adb, serial, request)
started = confirm_start(adb, serial, request, current["session"])
started = start_session(adb, serial, {"mode": "run", "program": args.program, "programArgs": program_args})
session = started["session"]
return add_serial({
"ok": True,
"command": "start",
"mode": "run",
"sessionId": session.get("id"),
"phase": session.get("phase"),
}, serial)
return add_serial({"ok": True, "command": "start", "mode": "run",
"sessionId": session.get("id"), "phase": session.get("phase")}, serial)
if args.command == "wait":
if command == "wait":
if args.phase == "focused":
if args.app_id is None:
raise ControlError("wait focused needs an app id", "INVALID_ARGUMENTS")
return add_serial(wait_until(adb, serial, f"app {args.app_id} to have focus",
lambda s: focused(s, args.app_id), args.timeout, 0.5), serial)
if args.phase == "game":
return add_serial(wait_until(adb, serial, "a game to have focus",
lambda s: focused(s, None), args.timeout, 0.5), serial)
phases = {"ready": "READY", "idle": "IDLE", "failed": "FAILED"}
return add_serial(wait_for_phase(adb, serial, phases[args.phase], args.timeout), serial)
if args.command == "stop":
if command == "stop":
current = get_state(adb, serial)
if current["session"].get("phase") in {"IDLE", "FAILED"}:
return add_serial(wait_for_artifacts(adb, serial, current, args.timeout), serial)
response = provider_call(adb, serial, "stop")
if response.get("ok") is False:
error = response.get("error", {})
raise ControlError(error.get("message", "stop failed"), error.get("code", "STOP_FAILED"))
return add_serial(wait_for_artifacts(adb, serial, current, args.artifact_timeout), serial)
checked(provider_call(adb, serial, "stop"), "STOP_FAILED")
state = wait_for_phase(adb, serial, "IDLE", args.timeout)
return add_serial(wait_for_artifacts(adb, serial, state, args.timeout), serial)
return add_serial(wait_for_artifacts(adb, serial, state, args.artifact_timeout), serial)
if args.command == "resume":
response = provider_call(adb, serial, "resume")
if response.get("ok") is False:
error = response.get("error", {})
raise ControlError(error.get("message", "resume failed"), error.get("code", "RESUME_FAILED"))
if command == "resume":
return add_serial(checked(provider_call(adb, serial, "resume"), "RESUME_FAILED"), serial)
if command == "launch":
response = checked(provider_call(adb, serial, "launch", request={"appId": str(args.app_id)}), "LAUNCH_FAILED")
if args.wait:
state = wait_until(adb, serial, f"app {args.app_id} to have focus",
lambda s: focused(s, args.app_id), args.timeout, 0.5)
response["focus"] = state["session"].get("focus")
return add_serial(response, serial)
if args.command == "logs":
if command == "quit":
response = provider_call(adb, serial, "quit", request={"appId": args.app_id, "timeout": args.timeout},
timeout=args.timeout + 40)
return add_serial(checked(response, "QUIT_FAILED"), serial)
if command == "focus":
return add_serial(checked(provider_call(adb, serial, "focus", timeout=40), "FOCUS_FAILED"), serial)
if command == "guest":
argv = args.argv[1:] if args.argv[:1] == ["--"] else args.argv
if not argv:
raise ControlError("guest needs a command after --", "INVALID_ARGUMENTS")
env = {}
for item in args.env or []:
key, sep, value = item.partition("=")
if not sep:
raise ControlError(f"--env takes KEY=VALUE, not {item}", "INVALID_ARGUMENTS")
env[key] = value
request = {"argv": argv, "timeout": args.timeout, "env": env}
if args.cwd:
request["cwd"] = args.cwd
if args.stdin is not None:
request["stdin"] = args.stdin
response = checked(provider_call(adb, serial, "guest", request=request, timeout=args.timeout + 40), "GUEST_FAILED")
if args.check and response.get("exitCode") != 0:
raise ControlError(f"{argv[0]} exited with {response.get('exitCode')}: "
f"{(response.get('stderr') or {}).get('text', '')[-400:]}", "GUEST_EXIT")
return add_serial(response, serial)
if command == "cdp":
if args.cdp_op == "targets":
request = {"op": "targets"}
else:
request = {"op": "eval", "expression": args.expression, "awaitPromise": not args.no_await,
"timeout": args.timeout}
if args.target:
request["target"] = args.target
timeout = getattr(args, "timeout", 15)
return add_serial(checked(provider_call(adb, serial, "cdp", request=request, timeout=timeout + 40),
"CDP_FAILED"), serial)
if command == "input":
return add_serial(checked(provider_call(adb, serial, "input", request=input_request(args), timeout=60),
"INPUT_FAILED"), serial)
if command == "ui":
if args.ui_op == "dump":
request = {"op": "dump", "all": args.all}
else:
request = {"op": args.ui_op, "index": args.index}
if args.match:
request["match"] = args.match
else:
request["tag"] = args.tag
if args.ui_op == "set-text":
request["text"] = args.text
return add_serial(checked(provider_call(adb, serial, "ui", request=request), "UI_FAILED"), serial)
if command == "env":
if args.env_op == "set":
request = {"op": "set", "lines": args.lines, "persistent": args.persistent}
elif args.env_op == "clear":
request = {"op": "clear", "scope": args.scope}
else:
request = {"op": "list"}
return add_serial(checked(provider_call(adb, serial, "env", request=request), "ENV_FAILED"), serial)
if command == "override":
access = require_commands(adb, serial)
if not re.fullmatch(r"[A-Za-z0-9._-]{1,64}", args.name) or args.name in {".", ".."}:
raise ControlError("Override names must be simple filenames", "INVALID_NAME")
source = Path(args.path).expanduser()
if not source.is_file():
raise ControlError(f"No such file: {source}", "FILE_IO")
inbox = access["inbox"]
run_adb(adb, serial, "shell", "mkdir", "-p", inbox)
pushed = run_adb(adb, serial, "push", str(source), f"{inbox}/{args.name}", timeout=300)
if pushed.returncode != 0:
raise ControlError(pushed.stderr.decode(errors="replace").strip() or "adb push failed", "PUSH_FAILED")
return add_serial(checked(provider_call(adb, serial, "override", request={"name": args.name}),
"OVERRIDE_FAILED"), serial)
if command == "prefs":
if args.prefs_op == "set":
request = {"op": "set", "file": args.file, "key": args.key, "type": args.type, "value": args.value}
else:
request = {"op": "get", "file": args.file}
return add_serial(checked(provider_call(adb, serial, "prefs", request=request), "PREFS_FAILED"), serial)
if command == "access":
return add_serial(checked(provider_call(adb, serial, "access"), "ACCESS_FAILED"), serial)
if command == "logs":
state = get_state(adb, serial)
session = state.get("session", {})
if not session.get("running") and session.get("artifactsAvailable") and not session.get("artifactsComplete"):
@@ -258,20 +501,24 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict:
raise ControlError(detail or "adb pull failed", "LOG_PULL_FAILED")
return add_serial({"ok": True, "command": "logs", "sessionId": session["id"], "path": str(destination)}, serial)
if args.command == "screenshot":
destination = Path(args.path).expanduser().resolve()
result = run_adb(adb, serial, "exec-out", "screencap", "-p", timeout=30)
if result.returncode != 0:
detail = result.stderr.decode(errors="replace").strip()
raise ControlError(detail or "screencap failed", "SCREENSHOT_FAILED")
try:
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_bytes(result.stdout)
except OSError as exc:
raise ControlError(str(exc), "FILE_IO") from exc
return add_serial({"ok": True, "command": "screenshot", "path": str(destination)}, serial)
if command == "screenshot":
return add_serial(screenshot(adb, serial, args.path, args.display), serial)
raise ControlError(f"Unknown command: {args.command}", "UNKNOWN_COMMAND")
if command == "record":
return add_serial(record(adb, serial, args.path, args.seconds, args.display), serial)
if command == "wake":
# A sleeping device stops the session and hides the app's windows from ui dump.
run_adb(adb, serial, "shell", "input", "keyevent", "KEYCODE_WAKEUP")
run_adb(adb, serial, "shell", "wm", "dismiss-keyguard")
power = run_adb(adb, serial, "shell", "dumpsys", "power").stdout.decode(errors="replace")
awake = re.search(r"mWakefulness=(\w+)", power)
return add_serial({"ok": True, "command": "wake", "wakefulness": awake.group(1) if awake else None}, serial)
if command == "displays":
return add_serial({"ok": True, "command": "displays", "displays": displays(adb, serial)}, serial)
raise ControlError(f"Unknown command: {command}", "UNKNOWN_COMMAND")
def build_parser() -> argparse.ArgumentParser:
@@ -288,49 +535,172 @@ def build_parser() -> argparse.ArgumentParser:
start.add_argument("--ui", choices=["bigpicture", "desktop"], default="bigpicture")
start.add_argument("--url", help="steam:// URL to pass to the client")
start.add_argument("--wait", action="store_true", help="wait for READY after starting")
start.add_argument("--reuse", action="store_true", help="keep a running session of this mode instead of failing")
start.add_argument("--timeout", type=float, default=90)
run = commands.add_parser("run", help="run a guest program under Gamescope")
run.add_argument("program")
run.add_argument("arguments", nargs=argparse.REMAINDER)
wait = commands.add_parser("wait", help="wait for a session phase")
wait.add_argument("phase", choices=["ready", "idle", "failed"])
wait = commands.add_parser("wait", help="wait for a session phase, or for a game to have focus")
wait.add_argument("phase", choices=["ready", "idle", "failed", "focused", "game"])
wait.add_argument("app_id", nargs="?", type=int, help="with focused: the Steam app id")
wait.add_argument("--timeout", type=float, default=90)
stop = commands.add_parser("stop", help="stop the session and wait for IDLE")
stop.add_argument("--timeout", type=float, default=90)
# Collecting the client's logs and redacting them took about two minutes after a Skyrim session.
stop.add_argument("--artifact-timeout", type=float, default=300)
commands.add_parser("resume", help="resume a suspended session")
launch = commands.add_parser("launch", help="launch a Steam game in the running Steam session")
launch.add_argument("app_id", type=int)
launch.add_argument("--wait", action="store_true", help="wait until the game has focus")
launch.add_argument("--timeout", type=float, default=180)
quit_ = commands.add_parser("quit", help="quit a running game (through the client, then signals)")
quit_.add_argument("app_id", type=int)
quit_.add_argument("--timeout", type=float, default=15)
commands.add_parser("focus", help="gamescope's focus and every Xwayland server's windows, fresh")
guest = commands.add_parser("guest", help="run a command inside the session (debugging tools)")
guest.add_argument("--timeout", type=float, default=30)
guest.add_argument("--env", action="append", metavar="KEY=VALUE")
guest.add_argument("--cwd")
guest.add_argument("--stdin")
guest.add_argument("--check", action="store_true", help="fail unless the command exits 0")
guest.add_argument("argv", nargs=argparse.REMAINDER)
cdp = commands.add_parser("cdp", help="the Steam client's DevTools (debugging tools)")
cdp_ops = cdp.add_subparsers(dest="cdp_op", required=True)
cdp_ops.add_parser("targets", help="list DevTools targets")
evaluate = cdp_ops.add_parser("eval", help="evaluate JavaScript (default target SharedJSContext)")
evaluate.add_argument("expression")
evaluate.add_argument("--target", help="title or URL substring of the target")
evaluate.add_argument("--no-await", action="store_true", help="do not await a returned promise")
evaluate.add_argument("--timeout", type=float, default=15)
inp = commands.add_parser("input", help="keys, text, touch and pad input into the session")
kinds = inp.add_subparsers(dest="input_type", required=True)
key = kinds.add_parser("key", help="a key by name (ENTER, ESC, A, F1...) or evdev code")
key.add_argument("key")
key.add_argument("--action", choices=["tap", "down", "up"], default="tap")
key.add_argument("--mod", action="append", help="modifier held around a tap (CTRL, SHIFT, ALT, META)")
key.add_argument("--hold", type=int, default=40, help="ms between down and up")
text = kinds.add_parser("text", help="type text (US layout keys; --commit for text-input)")
text.add_argument("text")
text.add_argument("--commit", action="store_true")
tap = kinds.add_parser("tap", help="touch at a point of the session's output")
tap.add_argument("x", type=float)
tap.add_argument("y", type=float)
tap.add_argument("--space", choices=["output", "fraction"], default="output")
tap.add_argument("--hold", type=int, default=60)
swipe = kinds.add_parser("swipe", help="drag a touch from one point to another")
for name in ("x", "y", "x2", "y2"):
swipe.add_argument(name, type=float)
swipe.add_argument("--space", choices=["output", "fraction"], default="output")
swipe.add_argument("--duration", type=int, default=300)
pad = kinds.add_parser("pad", help="a virtual pad button (a, b, x, y, lb, rb, start, select, guide, qam, up...)")
pad.add_argument("button")
pad.add_argument("--action", choices=["tap", "down", "up"], default="tap")
pad.add_argument("--hold", type=int, default=120)
stick = kinds.add_parser("stick", help="hold a stick at x, y (-1..1)")
stick.add_argument("stick", choices=["left", "right"])
stick.add_argument("x", type=float)
stick.add_argument("y", type=float)
stick.add_argument("--hold", type=int, default=300)
trigger = kinds.add_parser("trigger", help="hold a trigger (0..1)")
trigger.add_argument("trigger", choices=["left", "right"])
trigger.add_argument("value", type=float, nargs="?", default=1.0)
trigger.add_argument("--hold", type=int, default=200)
ui = commands.add_parser("ui", help="the app's own UI: dump nodes, click or type by test tag")
ui_ops = ui.add_subparsers(dest="ui_op", required=True)
dump = ui_ops.add_parser("dump", help="tagged, labelled and clickable nodes of every app window")
dump.add_argument("--all", action="store_true", help="every node")
for name in ("click", "set-text"):
op = ui_ops.add_parser(name)
op.add_argument("tag", nargs="?", help="test tag, e.g. rail-steam")
op.add_argument("--match", help="instead of a tag: text or description containing this")
op.add_argument("--index", type=int, default=0, help="which match, in tree order")
if name == "set-text":
op.add_argument("--text", required=True)
env = commands.add_parser("env", help="session environment lines (debugging tools)")
env_ops = env.add_subparsers(dest="env_op", required=True)
env_ops.add_parser("list")
env_set = env_ops.add_parser("set", help="KEY=VALUE lines for the next session")
env_set.add_argument("lines", nargs="+")
env_set.add_argument("--persistent", action="store_true", help="every session until cleared")
env_clear = env_ops.add_parser("clear")
env_clear.add_argument("scope", nargs="?", choices=["next", "persistent", "all"], default="next")
override = commands.add_parser("override", help="put a binary first on the next session's PATH (debugging tools)")
override.add_argument("name", help="the program name, e.g. gamescope")
override.add_argument("path", help="the local file to push")
prefs = commands.add_parser("prefs", help="the app's preferences (debugging tools)")
prefs_ops = prefs.add_subparsers(dest="prefs_op", required=True)
prefs_get = prefs_ops.add_parser("get")
prefs_get.add_argument("file", help="preferences file, e.g. session")
prefs_set = prefs_ops.add_parser("set")
prefs_set.add_argument("file")
prefs_set.add_argument("key")
prefs_set.add_argument("value", nargs="?")
prefs_set.add_argument("--type", choices=["bool", "int", "long", "float", "string", "remove"], default="string")
commands.add_parser("access", help="whether debugging tools are enabled on the device")
logs = commands.add_parser("logs", help="pull the latest session artifact directory")
logs.add_argument("which", choices=["latest"])
logs.add_argument("destination", nargs="?")
logs.add_argument("--timeout", type=float, default=90)
screenshot = commands.add_parser("screenshot", help="save a device screenshot")
screenshot.add_argument("path")
shot = commands.add_parser("screenshot", help="save a device screenshot")
shot.add_argument("path")
shot.add_argument("--display", type=int, help="logical display id (see displays); default the default display")
rec = commands.add_parser("record", help="record the screen to an mp4")
rec.add_argument("path")
rec.add_argument("--seconds", type=float, default=10)
rec.add_argument("--display", type=int)
commands.add_parser("displays", help="the device's displays and their capture ids")
commands.add_parser("wake", help="wake the device and dismiss the keyguard")
return parser
EXIT_ADB = {"ADB_NOT_FOUND", "ADB_FAILED", "INVALID_PROVIDER_RESPONSE"}
EXIT_SESSION = {
"SESSION_ACTIVE", "NO_ACTIVE_SESSION", "SESSION_NOT_SUSPENDED", "SESSION_FAILED", "GUEST_EXIT",
"GUEST_START_FAILED", "RUNTIME_INSTALL_FAILED", "DESKTOP_INSTALL_FAILED", "ACTIVITY_START_FAILED",
"NO_STEAM_SESSION", "SESSION_NOT_READY", "AGENT_UNAVAILABLE", "LAUNCH_REJECTED", "NO_PAD",
}
EXIT_TIMEOUT = {"TIMEOUT", "ARTIFACT_TIMEOUT"}
EXIT_FILE = {"NO_SESSION_LOGS", "LOG_PULL_FAILED", "SCREENSHOT_FAILED", "FILE_IO", "RECORD_FAILED", "PUSH_FAILED"}
EXIT_DENIED = {"AGENT_COMMANDS_DISABLED", "PROTECTED_PREFS", "PROTECTED_CONTROL"}
def exit_code(exc: Exception) -> int:
if isinstance(exc, DeviceResolutionError):
return 3
code = getattr(exc, "code", "")
if code in {"ADB_NOT_FOUND", "ADB_FAILED", "INVALID_PROVIDER_RESPONSE"}:
if code in EXIT_ADB:
return 3
if code in {"SESSION_ACTIVE", "NO_ACTIVE_SESSION", "SESSION_NOT_SUSPENDED", "SESSION_FAILED",
"GUEST_EXIT", "GUEST_START_FAILED", "RUNTIME_INSTALL_FAILED", "DESKTOP_INSTALL_FAILED",
"ACTIVITY_START_FAILED"}:
if code in EXIT_SESSION:
return 4
if code in {"TIMEOUT", "ARTIFACT_TIMEOUT"}:
if code in EXIT_TIMEOUT:
return 5
if code in {"NO_SESSION_LOGS", "LOG_PULL_FAILED", "SCREENSHOT_FAILED", "FILE_IO"}:
if code in EXIT_FILE:
return 6
if code in EXIT_DENIED:
return 7
return 2
def main() -> int:
args = build_parser().parse_args()
def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
serial = None
try:
adb = adb_path(args.adb)
@@ -340,11 +710,15 @@ def main() -> int:
return 0
except (ControlError, DeviceResolutionError) as exc:
error = {"code": getattr(exc, "code", "DEVICE_RESOLUTION_FAILED"), "message": str(exc)}
response = {"ok": False, "error": error}
if serial:
response["deviceSerial"] = serial
print(json.dumps(response, indent=2, sort_keys=True))
return exit_code(exc)
code = exit_code(exc)
except Exception as exc: # the contract is JSON on stdout, even for a bug in this tool
error = {"code": "INTERNAL_ERROR", "message": f"{type(exc).__name__}: {exc}"}
code = 2
response = {"ok": False, "error": error}
if serial:
response["deviceSerial"] = serial
print(json.dumps(response, indent=2, sort_keys=True))
return code
if __name__ == "__main__":
+3 -34
View File
@@ -16,11 +16,6 @@ export QT_QPA_PLATFORMTHEME=lxqt
# The prefs for this are only advisory and a profile can override them; the environment is not.
export MOZ_DISABLE_CONTENT_SANDBOX=1 MOZ_DISABLE_GMP_SANDBOX=1 MOZ_DISABLE_RDD_SANDBOX=1
export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1
# Firefox seals the size of the shared memory it hands a tab; on Android 16 (Galaxy S25/S26,
# RedMagic) adding the seal fails, Firefox only warns, and the tab refuses the unsealed memory
# ("Shared memory PlatformHandle is not safe to map") and dies on signal 11 - every page. Firefox's
# own switch skips the seals.
export MOZ_SHM_NO_SEALS=1
# pixman composites in software and gives programs shm buffers only, so a Vulkan program on it
# fails at its swapchain. vulkan (or gles2) composite on the GPU and give programs DMA-BUFs, but
# stock wlroots allocates through gbm on a real DRM node and the KGSL stand-in is not one ("unable
@@ -89,35 +84,9 @@ fi
# already running and exit without a word - a desktop with a wallpaper and nothing on it.
# Only the app's own compositor socket (wayland-0) is kept.
find "$XDG_RUNTIME_DIR" -mindepth 1 -maxdepth 1 ! -name 'wayland-0*' ! -name 'keymap.xkb' -exec rm -rf {} + 2>/dev/null
# fontconfig's rules (sans-serif -> DejaVu Sans and the rest) live as links in /etc/fonts/conf.d,
# and the rootfs has none: applications then find fonts but no default font. Firefox logs
# "no fonts" and draws pages without text.
if [ -d /usr/share/fontconfig/conf.default ] && ! ls /etc/fonts/conf.d/*.conf 2>/dev/null | grep -qv droiddeck; then
for f in /usr/share/fontconfig/conf.default/*.conf; do ln -sf "$f" /etc/fonts/conf.d/; done
echo "== fontconfig: linked $(ls /etc/fonts/conf.d/*.conf | wc -l) default rules"
fi
# Those rules map sans-serif and friends onto whatever a full distribution installs, and this
# rootfs has one family. Naming it outright is what gives every toolkit a default font: without
# one Gecko reports "no fonts" with families found, and draws pages with no text at all.
if [ ! -f /etc/fonts/local.conf ]; then
{ echo '<?xml version="1.0"?><!DOCTYPE fontconfig SYSTEM "urn:fontconfig:fonts.dtd"><fontconfig>'
for generic in sans-serif sans serif monospace mono cursive fantasy system-ui ui-sans-serif; do
case $generic in
serif) face="DejaVu Serif" ;;
mono*|ui-mono) face="DejaVu Sans Mono" ;;
*) face="DejaVu Sans" ;;
esac
printf '<alias binding="weak"><family>%s</family><prefer><family>%s</family></prefer></alias>\n' "$generic" "$face"
done
echo '</fontconfig>'
} > /etc/fonts/local.conf
echo "== fontconfig: wrote local.conf (DejaVu as the default family)"
fi
# The cache in the image was built before those rules existed; rebuild it once, and only once.
if [ ! -f /var/cache/fontconfig/.droiddeck-built ] && command -v fc-cache >/dev/null 2>&1; then
fc-cache -f >/dev/null 2>&1 && touch /var/cache/fontconfig/.droiddeck-built
echo "== fontconfig: cache rebuilt, default sans is $(fc-match sans-serif 2>/dev/null)"
fi
# Fontconfig defaults and Android language fallbacks are set up by droiddeck-session before this
# script or any desktop program starts. The generated defaults live in conf.d, leaving local.conf
# available for the user's own final overrides.
# The menu's "Steam" / "Steam Big Picture" entries and one entry per installed game: all of them
# hand off to the app (droiddeck-steam-launch), since the client cannot draw on this desktop.
export BL_DESKTOP=1
+687
View File
@@ -0,0 +1,687 @@
#!/usr/bin/python3
"""The guest side of the agent bridge (docs/agent-control.md).
Started by droiddeck-session inside the session, so whatever it runs has the session's own
environment: DISPLAY, the games' Xwayland, XDG_RUNTIME_DIR, and the preloads every guest process
gets - which is what lets it reach the Steam client's DevTools port, open to guest processes only.
The app talks to it through files under $BL_LAUNCH_DIR/agent (the session root, the same path on
both sides):
req/<id>.json a request the app wrote (tmp + rename)
resp/<id>.json the answer, written the same way
hello.json this daemon is up: pid, version, what it can do
focus.json gamescope's focus and every server's top-level windows, rewritten on change
cdp-port the client's DevTools port, written by droiddeck-session
Requests: ping, exec, focus, cdp, quit. Each answer is {"ok": true, ...} or
{"ok": false, "error": {"code", "message"}}.
"""
import base64
import json
import math
import os
import selectors
import signal
import socket
import struct
import subprocess
import sys
import threading
import time
import urllib.request
import urllib.parse
from pathlib import Path
VERSION = 1
OUTPUT_CAP = 256 * 1024
REQUEST_CAP = 256 * 1024
RESPONSE_CAP = 1024 * 1024
FOCUS_PROPS = (
"GAMESCOPE_FOCUSED_APP", "GAMESCOPE_FOCUSED_WINDOW", "GAMESCOPE_FOCUSABLE_APPS",
"GAMESCOPE_FOCUSABLE_WINDOWS", "GAMESCOPECTRL_BASELAYER_APPID",
)
WINDOW_PROPS = (
"STEAM_GAME", "WM_STATE", "_NET_WM_PID", "WM_CLASS", "_NET_WM_WINDOW_OPACITY", "STEAM_OVERLAY",
"GAMESCOPE_EXTERNAL_OVERLAY", "STEAM_INPUT_FOCUS", "_NET_WM_STATE",
)
MAP_STATE = ("unmapped", "unviewable", "viewable")
WM_STATES = {0: "withdrawn", 1: "normal", 3: "iconic"}
def log(message):
print("== agent: " + message, flush=True)
def write_json(path, value):
tmp = path.with_name(path.name + ".tmp")
with os.fdopen(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600), "w") as stream:
os.fchmod(stream.fileno(), 0o600)
json.dump(value, stream, separators=(",", ":"))
os.replace(tmp, path)
class AgentError(Exception):
def __init__(self, code, message):
super().__init__(message)
self.code = code
# --- X11: just enough of the protocol for root properties, the window tree and events ---------
class X:
"""One connection to an Xwayland server. The rootfs has xprop but no python X library."""
def __init__(self, display):
num = display.lstrip(":").split(".")[0]
last = None
for address in ("\0/tmp/.X11-unix/X" + num, "/tmp/.X11-unix/X" + num):
try:
self.s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.s.settimeout(3)
self.s.connect(address)
break
except OSError as e:
last = e
self.s.close()
else:
raise last
self.s.sendall(struct.pack("<BxHHHHxx", 0x6C, 11, 0, 0, 0))
head = self._read(8)
if head[0] != 1:
raise OSError("X connection refused on " + display)
setup = self._read(struct.unpack_from("<H", head, 6)[0] * 4)
vendor = struct.unpack_from("<H", setup, 16)[0]
formats = setup[21]
self.root = struct.unpack_from("<I", setup, 32 + (vendor + 3) // 4 * 4 + formats * 8)[0]
self.events = []
self._atoms = {}
self._names = {}
def close(self):
try:
self.s.close()
except OSError:
pass
def _read(self, n):
buf = b""
while len(buf) < n:
chunk = self.s.recv(n - len(buf))
if not chunk:
raise OSError("X connection closed")
buf += chunk
return buf
def request(self, data):
"""Send one request and return its reply, or None for an X error (a window that went)."""
self.s.sendall(data)
while True:
head = self._read(32)
if head[0] == 0:
return None
if head[0] == 1:
return head + self._read(struct.unpack_from("<I", head, 4)[0] * 4)
self.events.append(head)
def next_event(self):
if self.events:
return self.events.pop(0)
while True:
head = self._read(32)
if head[0] > 1:
return head
def atom(self, name):
if name not in self._atoms:
n = name.encode()
pad = (4 - len(n) % 4) % 4
r = self.request(struct.pack("<BBHHxx", 16, 0, 2 + (len(n) + pad) // 4, len(n)) + n + b"\0" * pad)
self._atoms[name] = struct.unpack_from("<I", r, 8)[0] if r else 0
return self._atoms[name]
def atom_name(self, atom):
if atom not in self._names:
r = self.request(struct.pack("<BxHI", 17, 2, atom))
self._names[atom] = r[32:32 + struct.unpack_from("<H", r, 8)[0]].decode(errors="replace") if r else str(atom)
return self._names[atom]
def select(self, window, mask):
self.s.sendall(struct.pack("<BxHIII", 2, 4, window, 0x800, mask))
def children(self, window):
r = self.request(struct.pack("<BxHI", 15, 2, window))
if not r:
return []
n = struct.unpack_from("<H", r, 16)[0]
return list(struct.unpack_from("<%dI" % n, r, 32))
def attributes(self, window):
r = self.request(struct.pack("<BxHI", 3, 2, window))
return (r[26], r[27], struct.unpack_from("<H", r, 12)[0]) if r else None
def geometry(self, window):
r = self.request(struct.pack("<BxHI", 14, 2, window))
return struct.unpack_from("<hhHH", r, 12) if r else None
def prop(self, window, name, length=1024):
atom = self.atom(name)
if not atom:
return None
r = self.request(struct.pack("<BBHIIIII", 20, 0, 6, window, atom, 0, 0, length))
if not r or r[1] == 0:
return None
fmt, n = r[1], struct.unpack_from("<I", r, 16)[0]
data = r[32:32 + n * fmt // 8]
if fmt == 32:
return list(struct.unpack("<%dI" % n, data))
return data
def windows(x):
"""Top-level windows that are mapped or carry an app id: what gamescope picks focus from."""
out = []
for win in x.children(x.root):
attrs = x.attributes(win)
if not attrs:
continue
props = {name: x.prop(win, name) for name in WINDOW_PROPS}
if attrs[0] != 2 and not props["STEAM_GAME"]:
continue
geo = x.geometry(win) or (0, 0, 0, 0)
cls = props["WM_CLASS"]
state = props["WM_STATE"]
entry = {
"window": win,
"map": MAP_STATE[attrs[0]] if attrs[0] < 3 else attrs[0],
"overrideRedirect": bool(attrs[1]),
"inputOnly": attrs[2] == 2,
"geometry": [geo[0], geo[1], geo[2], geo[3]],
"appId": props["STEAM_GAME"][0] if props["STEAM_GAME"] else None,
"wmState": WM_STATES.get(state[0], state[0]) if state else None,
"pid": props["_NET_WM_PID"][0] if props["_NET_WM_PID"] else None,
"class": cls.split(b"\0")[-2].decode(errors="replace") if cls and b"\0" in cls else None,
}
if props["_NET_WM_WINDOW_OPACITY"]:
entry["opacity"] = props["_NET_WM_WINDOW_OPACITY"][0]
for key, name in (("overlay", "STEAM_OVERLAY"), ("externalOverlay", "GAMESCOPE_EXTERNAL_OVERLAY"),
("inputFocus", "STEAM_INPUT_FOCUS")):
if props[name]:
entry[key] = props[name][0]
if props["_NET_WM_STATE"]:
entry["netState"] = [x.atom_name(a).replace("_NET_WM_STATE_", "") for a in props["_NET_WM_STATE"]]
out.append(entry)
return out
def displays():
seen = []
for d in (os.environ.get("DISPLAY"), os.environ.get("STEAM_GAME_DISPLAY_0")):
if d and d not in seen:
seen.append(d)
return seen
def focus_snapshot():
"""gamescope's focus as Steam sees it (root properties on the client's server) and every
server's windows. GAMESCOPE_FOCUSABLE_WINDOWS is the list the client orders the base layer
from: a game missing there stays behind the client however healthy its window looks."""
shown = displays()
if not shown:
raise AgentError("NO_DISPLAY", "This session has no X display")
snap = {"t": int(time.time() * 1000), "displays": {}}
for i, d in enumerate(shown):
x = X(d)
try:
if i == 0:
values = {name: x.prop(x.root, name) for name in FOCUS_PROPS}
trip = values["GAMESCOPE_FOCUSABLE_WINDOWS"] or []
snap["focusedApp"] = (values["GAMESCOPE_FOCUSED_APP"] or [None])[0]
snap["focusedWindow"] = (values["GAMESCOPE_FOCUSED_WINDOW"] or [None])[0]
snap["focusableApps"] = values["GAMESCOPE_FOCUSABLE_APPS"] or []
snap["focusableWindows"] = [
{"window": trip[k], "appId": trip[k + 1], "pid": trip[k + 2]} for k in range(0, len(trip) - 2, 3)
]
snap["baselayerAppIds"] = values["GAMESCOPECTRL_BASELAYER_APPID"] or []
snap["displays"][d] = windows(x)
finally:
x.close()
return snap
class FocusWatcher(threading.Thread):
"""Rewrites focus.json when gamescope's focus properties change, and every few seconds when
the windows do (a window can change without any root property moving)."""
def __init__(self, path):
super().__init__(daemon=True, name="focus")
self.path = path
self.changed = threading.Event()
self.last = None
self.seq = 0
def run(self):
threading.Thread(target=self.listen, daemon=True, name="focus-events").start()
while True:
self.changed.wait(timeout=5)
self.changed.clear()
time.sleep(0.2) # let a burst of property changes settle
try:
snap = focus_snapshot()
except (OSError, AgentError) as e:
log("focus snapshot failed: %s" % e)
time.sleep(2)
continue
body = {k: v for k, v in snap.items() if k != "t"}
if body == self.last:
continue
self.last = body
self.seq += 1
snap["seq"] = self.seq
write_json(self.path, snap)
def listen(self):
while True:
try:
x = X(os.environ["DISPLAY"])
wanted = {x.atom(name) for name in FOCUS_PROPS}
x.select(x.root, 0x400000) # PropertyChangeMask
self.changed.set()
while True:
event = x.next_event()
if event[0] & 0x7F == 28 and struct.unpack_from("<I", event, 8)[0] in wanted:
self.changed.set()
except OSError as e:
log("focus events: %s; reconnecting" % e)
time.sleep(2)
# --- Steam client DevTools (CDP) -----------------------------------------------------------------
class WebSocket:
"""A minimal RFC 6455 client: text frames out, text frames in. Enough for CDP."""
def __init__(self, url, timeout):
target = urllib.parse.urlsplit(url)
if (target.scheme != "ws" or target.hostname not in ("127.0.0.1", "::1", "localhost")
or target.username is not None or target.password is not None or target.fragment):
raise AgentError("INVALID_TARGET", "DevTools targets must use a loopback WebSocket")
hostport = target.netloc
path = target.path or "/"
if target.query:
path += "?" + target.query
host = "127.0.0.1" if target.hostname == "localhost" else target.hostname
self.s = socket.create_connection((host, target.port or 80), timeout=timeout)
try:
self._handshake(path, hostport)
except Exception:
self.s.close()
raise
def _handshake(self, path, hostport):
key = base64.b64encode(os.urandom(16)).decode()
self.s.sendall((
"GET %s HTTP/1.1\r\nHost: %s\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
"Sec-WebSocket-Key: %s\r\nSec-WebSocket-Version: 13\r\n\r\n" % (path, hostport, key)
).encode())
head = b""
while b"\r\n\r\n" not in head:
chunk = self.s.recv(4096)
if not chunk:
raise OSError("DevTools closed the connection during the handshake")
head += chunk
if len(head) > 16 * 1024:
raise AgentError("RESPONSE_TOO_LARGE", "The DevTools handshake exceeds 16 KiB")
status = head.split(b"\r\n", 1)[0]
if b" 101 " not in status:
raise OSError("DevTools refused the WebSocket: " + status.decode(errors="replace"))
self.buffer = head.split(b"\r\n\r\n", 1)[1]
def _read(self, n):
while len(self.buffer) < n:
chunk = self.s.recv(65536)
if not chunk:
raise OSError("DevTools closed the connection")
self.buffer += chunk
data, self.buffer = self.buffer[:n], self.buffer[n:]
return data
def send(self, text):
payload = text.encode()
header = bytearray([0x81])
n = len(payload)
if n < 126:
header.append(0x80 | n)
elif n < 65536:
header.append(0x80 | 126)
header += struct.pack(">H", n)
else:
header.append(0x80 | 127)
header += struct.pack(">Q", n)
mask = os.urandom(4)
header += mask
self.s.sendall(bytes(header) + bytes(b ^ mask[i % 4] for i, b in enumerate(payload)))
def recv(self):
message = b""
while True:
b0, b1 = self._read(2)
n = b1 & 0x7F
if n == 126:
n = struct.unpack(">H", self._read(2))[0]
elif n == 127:
n = struct.unpack(">Q", self._read(8))[0]
if n > RESPONSE_CAP or len(message) + n > RESPONSE_CAP:
raise AgentError("RESPONSE_TOO_LARGE", "The DevTools response exceeds 1 MiB")
mask = self._read(4) if b1 & 0x80 else None
data = self._read(n)
if mask:
data = bytes(b ^ mask[i % 4] for i, b in enumerate(data))
op = b0 & 0x0F
if op == 8:
raise OSError("DevTools closed the WebSocket")
if op == 9: # ping
continue
if op in (0, 1, 2):
message += data
if b0 & 0x80:
return message.decode(errors="replace")
def close(self):
try:
self.s.close()
except OSError:
pass
def cdp_port(agent_dir):
try:
port = (agent_dir / "cdp-port").read_text().strip()
except OSError:
port = os.environ.get("BL_CDP_PORT", "")
if not port.isdigit():
raise AgentError("NO_DEVTOOLS", "The Steam client's DevTools port is not known (no Steam client in this session yet)")
return int(port)
def cdp_targets(agent_dir, timeout=5):
url = "http://127.0.0.1:%d/json" % cdp_port(agent_dir)
try:
with urllib.request.urlopen(url, timeout=timeout) as r:
data = r.read(RESPONSE_CAP + 1)
if len(data) > RESPONSE_CAP:
raise AgentError("RESPONSE_TOO_LARGE", "The DevTools response exceeds 1 MiB")
return json.loads(data.decode())
except OSError as e:
raise AgentError("DEVTOOLS_UNREACHABLE", "Could not reach the client's DevTools at %s: %s" % (url, e))
def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15):
targets = [t for t in cdp_targets(agent_dir) if t.get("webSocketDebuggerUrl")]
want = target or "SharedJSContext"
match = [t for t in targets if want in (t.get("title") or "") or want in (t.get("url") or "")]
if not match:
names = ", ".join(sorted({t.get("title") or t.get("url") or "?" for t in targets}))
raise AgentError("NO_TARGET", "No DevTools target matches '%s' (have: %s)" % (want, names))
ws = WebSocket(match[0]["webSocketDebuggerUrl"], timeout)
try:
ws.send(json.dumps({"id": 1, "method": "Runtime.evaluate", "params": {
"expression": expression, "returnByValue": True, "awaitPromise": await_promise,
"userGesture": True,
}}))
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
message = json.loads(ws.recv())
if message.get("id") != 1:
continue
if "error" in message:
raise AgentError("CDP_ERROR", json.dumps(message["error"]))
result = message.get("result", {})
if result.get("exceptionDetails"):
details = result["exceptionDetails"]
text = (details.get("exception") or {}).get("description") or details.get("text") or "exception"
raise AgentError("JS_EXCEPTION", text)
value = result.get("result", {})
return {"target": match[0].get("title"), "type": value.get("type"),
"value": value.get("value"), "description": value.get("description")}
raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout)
finally:
ws.close()
# --- Game processes ------------------------------------------------------------------------------
def game_pids(app_id):
"""Our processes started for this Steam app (Steam sets SteamAppId / SteamGameId in their
environment, and Proton's wine processes inherit it)."""
wanted = [("SteamAppId=%s" % app_id).encode(), ("SteamGameId=%s" % app_id).encode()]
me = os.getpid()
pids = []
for entry in os.listdir("/proc"):
if not entry.isdigit() or int(entry) == me:
continue
try:
with open("/proc/%s/environ" % entry, "rb") as f:
env = f.read().split(b"\0")
except OSError:
continue
if any(w in env for w in wanted):
pids.append(int(entry))
return pids
def quit_game(agent_dir, app_id, timeout):
if not str(app_id).isdigit():
raise AgentError("INVALID_APP_ID", "appId must be a decimal Steam app id")
steps = []
if game_pids(app_id):
try:
cdp_eval(agent_dir, "SteamClient.Apps.TerminateApp(%s, false)" % json.dumps(str(app_id)), timeout=5)
steps.append("client")
except AgentError as e:
steps.append("client unavailable: %s" % e)
deadline = time.monotonic() + timeout
while game_pids(app_id) and time.monotonic() < deadline:
time.sleep(0.5)
left = game_pids(app_id)
if left:
steps.append("SIGTERM %s" % left)
for pid in left:
try:
os.kill(pid, signal.SIGTERM)
except OSError:
pass
end = time.monotonic() + 5
while game_pids(app_id) and time.monotonic() < end:
time.sleep(0.5)
left = game_pids(app_id)
if left:
steps.append("SIGKILL %s" % left)
for pid in left:
try:
os.kill(pid, signal.SIGKILL)
except OSError:
pass
time.sleep(1)
return {"appId": int(app_id), "steps": steps, "remaining": game_pids(app_id)}
# --- Requests ------------------------------------------------------------------------------------
def run_exec(req):
argv = req.get("argv")
if not isinstance(argv, list) or not argv or not all(isinstance(a, str) and "\0" not in a for a in argv):
raise AgentError("INVALID_REQUEST", "exec needs argv, a non-empty list of strings")
timeout = request_timeout(req, 30)
env = dict(os.environ)
extra_env = req.get("env") if req.get("env") is not None else {}
if not isinstance(extra_env, dict) or any("\0" in str(k) or "=" in str(k) or "\0" in str(v) for k, v in extra_env.items()):
raise AgentError("INVALID_REQUEST", "env must be an object with valid environment entries")
env.update({str(k): str(v) for k, v in extra_env.items()})
stdin = req.get("stdin")
if stdin is not None and not isinstance(stdin, str):
raise AgentError("INVALID_REQUEST", "stdin must be a string")
started = time.monotonic()
try:
proc = subprocess.Popen(
argv, cwd=req.get("cwd") or None, env=env, start_new_session=True,
stdin=subprocess.PIPE if stdin is not None else subprocess.DEVNULL,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
)
except OSError as e:
raise AgentError("EXEC_FAILED", "%s: %s" % (argv[0], e))
captured = {"stdout": bytearray(), "stderr": bytearray()}
truncated = {"stdout": False, "stderr": False}
pending = memoryview(stdin.encode()) if stdin is not None else memoryview(b"")
deadline = started + timeout
timed_out = False
try:
with selectors.DefaultSelector() as selector:
for stream, name in ((proc.stdout, "stdout"), (proc.stderr, "stderr")):
os.set_blocking(stream.fileno(), False)
selector.register(stream, selectors.EVENT_READ, name)
if proc.stdin is not None:
os.set_blocking(proc.stdin.fileno(), False)
if pending:
selector.register(proc.stdin, selectors.EVENT_WRITE, "stdin")
else:
proc.stdin.close()
while selector.get_map() or proc.poll() is None:
remaining = deadline - time.monotonic()
if remaining <= 0:
timed_out = True
break
for key, _ in selector.select(min(0.1, remaining)):
stream, name = key.fileobj, key.data
if name == "stdin":
try:
pending = pending[os.write(stream.fileno(), pending[:65536]):]
except BrokenPipeError:
pending = pending[len(pending):]
if not pending:
selector.unregister(stream)
stream.close()
else:
data = os.read(stream.fileno(), 65536)
if not data:
selector.unregister(stream)
stream.close()
continue
available = OUTPUT_CAP - len(captured[name])
captured[name].extend(data[:available])
truncated[name] |= len(data) > available
if timed_out:
try:
os.killpg(proc.pid, signal.SIGKILL)
except ProcessLookupError:
pass
proc.wait(timeout=5)
finally:
if proc.poll() is None:
try:
os.killpg(proc.pid, signal.SIGKILL)
except ProcessLookupError:
pass
proc.wait(timeout=5)
for stream in (proc.stdin, proc.stdout, proc.stderr):
if stream is not None:
stream.close()
def text(name):
return {"text": captured[name].decode(errors="replace"), "truncated": truncated[name]}
return {"exitCode": proc.returncode, "timedOut": timed_out,
"seconds": round(time.monotonic() - started, 3), "stdout": text("stdout"), "stderr": text("stderr")}
def request_timeout(req, default):
try:
timeout = float(req.get("timeout", default))
except (TypeError, ValueError):
raise AgentError("INVALID_REQUEST", "timeout must be a positive number no greater than 600 seconds")
if not math.isfinite(timeout) or not 0 < timeout <= 600:
raise AgentError("INVALID_REQUEST", "timeout must be a positive number no greater than 600 seconds")
return timeout
def handle(agent_dir, req):
kind = req.get("kind")
if kind == "ping":
return {"pid": os.getpid(), "version": VERSION, "displays": displays()}
if kind == "exec":
return run_exec(req)
if kind == "focus":
return focus_snapshot()
if kind == "cdp":
if req.get("op") == "targets":
return {"targets": [{k: t.get(k) for k in ("title", "url", "type")} for t in cdp_targets(agent_dir)]}
expression = req.get("expression")
if not isinstance(expression, str) or not expression:
raise AgentError("INVALID_REQUEST", "cdp eval needs an expression")
return cdp_eval(agent_dir, expression, req.get("target"), bool(req.get("awaitPromise", True)),
request_timeout(req, 15))
if kind == "quit":
return quit_game(agent_dir, req.get("appId"), request_timeout(req, 15))
raise AgentError("UNKNOWN_REQUEST", "Unknown agent request '%s'" % kind)
def answer(agent_dir, path):
rid = path.stem
try:
with path.open("rb") as stream:
data = stream.read(REQUEST_CAP + 1)
if len(data) > REQUEST_CAP:
raise ValueError("The request exceeds 256 KiB")
req = json.loads(data)
if not isinstance(req, dict):
raise ValueError("The request must be a JSON object")
except (OSError, ValueError) as e:
req = None
result = {"ok": False, "error": {"code": "INVALID_REQUEST", "message": str(e)}}
finally:
try:
path.unlink()
except OSError:
pass
if req is not None:
try:
result = dict(handle(agent_dir, req), ok=True)
except AgentError as e:
result = {"ok": False, "error": {"code": e.code, "message": str(e)}}
except Exception as e: # an answer of some kind always goes back
result = {"ok": False, "error": {"code": "AGENT_FAILED", "message": "%s: %s" % (type(e).__name__, e)}}
write_json(agent_dir / "resp" / (rid + ".json"), result)
def serve(agent_dir, focus=True, poll=0.1):
(agent_dir / "req").mkdir(parents=True, exist_ok=True)
(agent_dir / "resp").mkdir(parents=True, exist_ok=True)
can_focus = focus and bool(os.environ.get("DISPLAY"))
if can_focus:
FocusWatcher(agent_dir / "focus.json").start()
write_json(agent_dir / "hello.json", {"pid": os.getpid(), "version": VERSION, "started": int(time.time() * 1000),
"displays": displays(), "focus": can_focus})
log("serving %s (focus %s)" % (agent_dir, "on" if can_focus else "off"))
taken = set()
while True:
for path in sorted((agent_dir / "req").glob("*.json")):
if path.name in taken:
continue
taken.add(path.name)
threading.Thread(target=lambda p=path: (answer(agent_dir, p), taken.discard(p.name)),
daemon=True, name="req").start()
time.sleep(poll)
def main(argv):
base = os.environ.get("BL_LAUNCH_DIR")
if not base:
print("BL_LAUNCH_DIR is not set", file=sys.stderr)
return 2
serve(Path(base) / "agent", focus="--no-focus" not in argv)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
@@ -4,13 +4,14 @@
# Flathub as the remote, this device's architecture.
#
# droiddeck-flatpak install <app-id> the app and whatever runtimes it needs
# droiddeck-flatpak install-bundle <file> a .flatpak file, its runtimes from Flathub
# droiddeck-flatpak uninstall <app-id> the app, then runtimes nothing uses any more
# droiddeck-flatpak update [<app-id>] one app, or everything with an update
# droiddeck-flatpak updates what has one (a "updates" line)
#
# Lines: {"e":"op","i":1,"n":3,"kind":"install","ref":"..."} as each step starts,
# {"e":"progress","i":1,"n":3,"percent":45,"status":"..."} while it runs,
# {"e":"error","message":"..."} and {"e":"done"} at the end. Exit status 0 on success.
# {"e":"error","message":"..."} and {"e":"done"} at the end (with "id" for a bundle). Exit status 0 on success.
import json
import os
import sys
@@ -20,7 +21,7 @@ os.environ.setdefault("FLATPAK_BWRAP", "/usr/local/bin/droiddeck-bwrap")
import gi # noqa: E402
gi.require_version("Flatpak", "1.0")
from gi.repository import Flatpak, GLib # noqa: E402
from gi.repository import Flatpak, Gio, GLib # noqa: E402
REMOTE = "flathub"
@@ -158,6 +159,29 @@ def install(app_id):
return rc
def install_bundle(path):
"""A single-file bundle (flatpak build-bundle), for apps Flathub does not carry."""
inst = installation()
bundle = Gio.File.new_for_path(path)
try:
app_id = Flatpak.BundleRef.new(bundle).get_name()
except GLib.Error as err:
emit(e="error", message="%s is not a Flatpak bundle (%s)" % (os.path.basename(path), err.message))
return 1
if app_ref(inst, app_id) is not None:
emit(e="done", id=app_id, note="already installed")
return 0
t, state = transaction(inst)
t.add_install_bundle(bundle, None)
rc = run(t, state, report_done=False)
if rc == 0 and app_ref(installation(), app_id) is None:
emit(e="error", message="%s did not install; see flatpak-install-bundle.log" % app_id)
return 1
if rc == 0:
emit(e="done", id=app_id)
return rc
def uninstall(app_id):
inst = installation()
ref = app_ref(inst, app_id)
@@ -216,20 +240,22 @@ def updates():
def main():
if len(sys.argv) < 2:
sys.stderr.write(__doc__ or "usage: droiddeck-flatpak install|uninstall|update|updates [app-id]\n")
sys.stderr.write(__doc__ or "usage: droiddeck-flatpak install|install-bundle|uninstall|update|updates [app-id|file]\n")
return 2
cmd, args = sys.argv[1], sys.argv[2:]
if cmd in ("install", "update"):
if cmd in ("install", "install-bundle", "update"):
prepare_rootfs()
if cmd == "install" and args:
return install(args[0])
if cmd == "install-bundle" and args:
return install_bundle(args[0])
if cmd == "uninstall" and args:
return uninstall(args[0])
if cmd == "update":
return update(args[0] if args else None)
if cmd == "updates":
return updates()
sys.stderr.write("usage: droiddeck-flatpak install|uninstall|update|updates [app-id]\n")
sys.stderr.write("usage: droiddeck-flatpak install|install-bundle|uninstall|update|updates [app-id|file]\n")
return 2
+46
View File
@@ -0,0 +1,46 @@
#!/bin/bash
# DroidDeck's fontconfig setup for the Linux runtime. The rootfs ships DejaVu alone and no rules
# for a default family: applications then find fonts but no default, and Firefox logs "no fonts"
# and draws pages without text. DejaVu also has no CJK, Thai or Arabic glyphs, so those draw as
# tofu boxes. The app binds Android's fonts for the session, which adds language-specific fallbacks
# separately. This script links fontconfig's default rules and writes generic DejaVu aliases to an
# owned conf.d file. Fontconfig reads local.conf afterward, so user overrides keep precedence and
# are never replaced.
# The first argument is the root to set up, "/" in a session; the tests point it at a temp tree.
set -u
root=${1:-/}
root=${root%/}
# "/" strips to empty above; put it back so the paths below read as absolute and the test for a
# real session ("/") still holds.
[ -n "$root" ] || root=/
conf_dir=$root/etc/fonts
defaults_dir=$root/usr/share/fontconfig/conf.default
mkdir -p "$conf_dir/conf.d" 2>/dev/null
# The default rules (sans-serif -> DejaVu Sans and the rest) live as links in /etc/fonts/conf.d,
# and the rootfs has none. Linked by name, so a file we ship is never overwritten.
if [ -d "$defaults_dir" ]; then
for f in "$defaults_dir"/*.conf; do
[ -e "$f" ] || continue
[ -e "$conf_dir/conf.d/${f##*/}" ] || ln -sf "$f" "$conf_dir/conf.d/${f##*/}"
done
fi
owned_conf=$conf_dir/conf.d/65-droiddeck-default-fonts.conf
{
echo '<?xml version="1.0"?><!DOCTYPE fontconfig SYSTEM "urn:fontconfig:fonts.dtd"><fontconfig>'
for generic in sans-serif sans serif monospace mono cursive fantasy system-ui ui-sans-serif; do
case $generic in
serif) face="DejaVu Serif" ;;
mono*|ui-mono) face="DejaVu Sans Mono" ;;
*) face="DejaVu Sans" ;;
esac
printf '<alias binding="weak"><family>%s</family><prefer><family>%s</family></prefer></alias>\n' "$generic" "$face"
done
echo '</fontconfig>'
} > "$owned_conf.new"
if ! cmp -s "$owned_conf.new" "$owned_conf" 2>/dev/null; then
mv -f "$owned_conf.new" "$owned_conf"
echo "== fontconfig: wrote DejaVu defaults"
fi
rm -f "$owned_conf.new"
@@ -97,6 +97,14 @@ export GAMESCOPE_FORCE_VULKAN_REALTIME=${BL_GAMESCOPE_REALTIME:-0}
# A sleep that starts no process. Under proot every exec is a traced execve plus the loader's
# opens and maps, and the watchers below poll for the whole session: `sleep 1` in a loop was 60
# execs a minute each. read -t on a pipe nothing ever writes to waits in bash itself.
# The agent bridge's guest side (docs/agent-control.md): runs what the app's agent provider asks
# for inside this session and publishes gamescope's focus. Its files live under the session root
# ($BL_LAUNCH_DIR/agent), which the app empties before each session.
start_agent() {
[ -n "${BL_LAUNCH_DIR:-}" ] && [ -x /usr/local/bin/droiddeck-agent ] || return 0
mkdir -p "$BL_LAUNCH_DIR/agent"
/usr/local/bin/droiddeck-agent "$@" 2>&1 &
}
nap() {
[ -n "${bl_nap_fd:-}" ] || exec {bl_nap_fd}<> <(:)
read -r -t "$1" -u "$bl_nap_fd" _ 2>/dev/null || :
@@ -136,6 +144,9 @@ program_cores() {
}
if [ -z "${BL_INSIDE:-}" ]; then
# Install the shared default-family aliases before Steam, gamescope or the desktop queries fonts.
/usr/local/bin/droiddeck-fonts 2>&1 | sed 's/^/[fonts] /'
# Android's directory binding and language-specific family matches handle CJK and Thai fonts.
device_fonts=/usr/local/share/fonts/android
if [ -d "$device_fonts" ] && [ -d /etc/fonts/conf.d ] && command -v fc-cache >/dev/null 2>&1; then
fonts_rules=$(
@@ -166,6 +177,7 @@ if [ -z "${BL_INSIDE:-}" ]; then
# into the app's: no gamescope in between.
if [ "$mode" = lxqt ]; then
step "starting the desktop"
start_agent --no-focus
[ -x /usr/local/bin/droiddeck-desktop ] || { echo "== the desktop package is not installed"; exit 66; }
cores=$(program_cores)
if [ -n "$cores" ]; then
@@ -284,6 +296,8 @@ if [ -n "${BL_ANDROID_CLIPBOARD:-}" ] && [ -x /usr/local/bin/droiddeck-clipboard
/usr/local/bin/droiddeck-clipboard "$BL_ANDROID_CLIPBOARD" &
fi
start_agent
case $mode in
desktop)
exec pcmanfm
@@ -710,6 +724,8 @@ BUSCONF
export BL_CDP_GUARD=$BL_CDP_PORT
echo "== steam: devtools port $BL_CDP_PORT, guest processes only"
fi
# The agent bridge drives the client through it (droiddeck-agent's cdp requests).
[ -n "${BL_LAUNCH_DIR:-}" ] && mkdir -p "$BL_LAUNCH_DIR/agent" && echo "$BL_CDP_PORT" > "$BL_LAUNCH_DIR/agent/cdp-port"
droiddeck-steam-compat "$steam_root" 2>&1 &
# The client exits 42 when it has updated itself and wants a fresh start (steam.sh does this).
# BL_STEAM_UI=desktop = the client's desktop UI (a window, the library as a list), which the
@@ -206,7 +206,7 @@ BL_DIRECTAUDIO_SETUP = """
bl_directaudio() {
base=$1
[ -n "${BL_DIRECTAUDIO:-}" ] || return 0
[ -d "$BL_DIRECTAUDIO/lib/wine" ] || return 0
[ -d "$BL_DIRECTAUDIO" ] || return 0
version=$("$base/files/bin-arm64/wine" --version 2>/dev/null)
major=${version#wine-}
major=${major%%.*}
@@ -214,10 +214,32 @@ bl_directaudio() {
echo "droiddeck-proton: DirectAudio left off - it is built for Wine 11 and this Proton is '${version:-unknown}'. Pairing them would be silent rather than broken, so it is not worth guessing." >&2
return 0
fi
# Two builds of the driver ship, one per Wine audio interface, and both Wines call themselves
# 11.0: the private mmdevapi table is not versioned, and the wrong set plays silence, not an
# error. Proton's own winepulse.so tells them apart - it imports PsCreateSystemThread only on
# the system-thread table (Proton-CachyOS), never on the classic one (Valve, GE-Proton).
winepulse="$base/files/lib/wine/aarch64-unix/winepulse.so"
if [ ! -f "$winepulse" ]; then
echo "droiddeck-proton: DirectAudio left off - no winepulse.so to read this Proton's audio interface from" >&2
return 0
fi
if grep -aq PsCreateSystemThread "$winepulse"; then set=linux-wine11-systhread; else set=linux-wine11; fi
da="$BL_DIRECTAUDIO/$set"
if [ ! -d "$da/lib/wine" ]; then
echo "droiddeck-proton: DirectAudio left off - no driver set for the $set interface is staged" >&2
return 0
fi
# Wine appends the per-architecture subdirectory to each entry, so the directory holding
# aarch64-unix/ and aarch64-windows/ is what goes here.
WINEDLLPATH="$BL_DIRECTAUDIO/lib/wine${WINEDLLPATH:+:$WINEDLLPATH}"
WINEDLLPATH="$da/lib/wine${WINEDLLPATH:+:$WINEDLLPATH}"
export WINEDLLPATH
# Proton-CachyOS's launcher sets WINE_AUDIO_DRIVER=pulse,alsa (setdefault, so an existing value
# wins), and its mmdevapi reads that variable BEFORE the registry - so the selection below was
# being overridden to pulse on every CachyOS game. Valve's and GE's mmdevapi do not read the
# variable at all and take the registry, which is why both are done. A value the user set for
# the game still wins: the per-game environment is applied after this.
WINE_AUDIO_DRIVER="directaudio,pulse"
export WINE_AUDIO_DRIVER
# mmdevapi only tries the drivers named in the registry; its built-in list is pulse, alsa, oss and
# coreaudio and knows nothing about this one. The key is appended to the prefix's user.reg rather
# than written with `wine reg`, which would start a wineserver here just to set one value.
@@ -226,25 +248,36 @@ bl_directaudio() {
if [ -f "$reg" ]; then
for pair in system32:aarch64-windows syswow64:i386-windows; do
dir="$pfx/drive_c/windows/${pair%%:*}"
src="$BL_DIRECTAUDIO/lib/wine/${pair#*:}/winedirectaudio.drv"
src="$da/lib/wine/${pair#*:}/winedirectaudio.drv"
if [ -d "$dir" ] && [ -f "$src" ] && [ "$(readlink "$dir/winedirectaudio.drv" 2>/dev/null)" != "$src" ]; then
ln -sfn "$src" "$dir/winedirectaudio.drv.bl-new" && mv -f "$dir/winedirectaudio.drv.bl-new" "$dir/winedirectaudio.drv"
fi
done
key='[Software\\\\Wine\\\\Drivers]'
if [ "$(readlink "$pfx/drive_c/windows/system32/winedirectaudio.drv" 2>/dev/null)" != "$BL_DIRECTAUDIO/lib/wine/aarch64-windows/winedirectaudio.drv" ]; then
if [ "$(readlink "$pfx/drive_c/windows/system32/winedirectaudio.drv" 2>/dev/null)" != "$da/lib/wine/aarch64-windows/winedirectaudio.drv" ]; then
echo "droiddeck-proton: DirectAudio could not be placed in the prefix; Proton's own audio stays" >&2
elif ! BL_KEY="$key" awk 'index($0, "[") == 1 { inside = index($0, ENVIRON["BL_KEY"] " ") == 1 } inside && index($0, "\\"Audio\\"=") == 1 { last = $0 } END { exit last != "\\"Audio\\"=\\"directaudio,pulse\\"" }' "$reg" 2>/dev/null; then
printf '\\n%s %s\\n"Audio"="directaudio,pulse"\\n' "$key" "$(date +%s)" >> "$reg"
echo "droiddeck-proton: DirectAudio selected in the prefix" >&2
# Steam runs this tool several times per launch (getcompatpath, run, waitforexitandrun); a
# wineserver from an earlier verb that still holds the registry saves its own copy on exit
# and drops this line. Said out loud so a game that stays on pulse once is explained; it
# takes on the next launch. (Writing through the live server with a bare `wine reg add` was
# tried and withdrawn: a second Wine invocation inside Steam's launch sequence is not safe.)
srv="${BL_WINE_SERVER_BASE:-/tmp/.wine-$(id -u)}/server-$(printf '%x-%x' $(stat -c '%d %i' "$pfx" 2>/dev/null || echo 0 0))/socket"
if [ -S "$srv" ]; then
echo "droiddeck-proton: a wineserver is already running for this prefix; DirectAudio may only engage on the next launch" >&2
fi
fi
else
# A prefix that does not exist yet is created by Proton moments from now, after this runs, so
# the key lands on the NEXT launch of that game. Said out loud because silent audio on a first
# launch would otherwise look like a fault.
# the value lands on the NEXT launch of that game. Said out loud so a first launch on Proton's
# own audio does not look like a fault. (Having Proton create the prefix from here first was
# tried and withdrawn: a second Proton run inside Steam's launch sequence got the launch
# aborted - Steam games bounced back to their page with a half-made prefix.)
echo "droiddeck-proton: no prefix yet - DirectAudio takes effect the next time this game starts" >&2
fi
echo "droiddeck-proton: DirectAudio ready (Wine $major)" >&2
echo "droiddeck-proton: DirectAudio ready (Wine $major, $set)" >&2
}
"""
+811
View File
@@ -0,0 +1,811 @@
/*
* The Steam client lists a whole content directory about ten times per file it creates, moves or
* deletes, to match names case-insensitively. On Android's FUSE storage that made reserving space
* quadratic. Listings under steamapps/ on FUSE are kept for at most DIR_TTL_NS and dropped on any
* inotify event the client's own patched changes don't account for; directory timestamps alone
* can't be trusted, as NTFS volumes report whole seconds. BL_NO_DIR_CACHE=1 turns it off.
*/
#define _GNU_SOURCE
#include <dirent.h>
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <pthread.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/inotify.h>
#include <sys/stat.h>
#include <sys/statfs.h>
#include <time.h>
#include <unistd.h>
#define DIR_TTL_NS 5000000000LL
#define MAX_LISTINGS 16
#define MAX_ENTRIES 100000
#define MAX_HANDLES 64
#define FUSE_MAGIC 0x65735546
#define WATCHED (IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO | IN_DELETE_SELF | IN_MOVE_SELF | IN_ONLYDIR)
/* The client is 64-bit; 32-bit builds only pass creates through. */
#if __SIZEOF_POINTER__ == 8
_Static_assert(sizeof(struct dirent) == sizeof(struct dirent64), "dirent layouts differ");
struct entry { ino_t ino; unsigned char type; char *name; };
struct listing {
dev_t dev;
ino_t ino;
struct timespec mtime, ctime;
off_t size;
nlink_t nlink;
long long filled;
long long used;
int refs;
int detached;
int wd;
size_t n, cap;
struct entry *e;
char *recs;
size_t len;
};
struct handle {
struct listing *snap;
struct listing *fill;
DIR *real;
size_t pos;
int fd;
int wd;
int dirty;
char *path;
struct dirent64 out;
};
struct expect { int wd; uint32_t mask; const char *name; };
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t oplock = PTHREAD_MUTEX_INITIALIZER;
static struct listing *table[MAX_LISTINGS];
static struct handle *handles[MAX_HANDLES];
static int high_water;
static int cached_listings;
static int changing;
static int notify = -1;
static int forked;
static struct { dev_t dev; int fuse; } devs[8];
static int ndevs;
static long long now_ns(void) {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC_COARSE, &t);
return (long long)t.tv_sec * 1000000000LL + t.tv_nsec;
}
/* A child shares the parent's inotify queue, so it stops keeping listings. */
static void after_fork(void) {
pthread_mutex_init(&lock, NULL);
pthread_mutex_init(&oplock, NULL);
forked = 1;
}
static int enabled(void) {
static int cached = -1;
if (cached < 0) {
const char *off = getenv("BL_NO_DIR_CACHE");
cached = strcmp(program_invocation_short_name, "steam") == 0 &&
strstr(program_invocation_name, "steamrtarm64") != NULL && !(off && strcmp(off, "1") == 0);
if (cached) pthread_atfork(NULL, NULL, after_fork);
}
return cached && !forked;
}
static int eligible(const char *path) {
if (path == NULL || path[0] != '/' || !enabled()) return 0;
const char *s = strstr(path, "/steamapps");
return s && (s[10] == '/' || s[10] == 0);
}
static int on_fuse(dev_t dev, const char *path) {
pthread_mutex_lock(&lock);
for (int i = 0; i < ndevs; i++) {
if (devs[i].dev == dev) {
int fuse = devs[i].fuse;
pthread_mutex_unlock(&lock);
return fuse;
}
}
pthread_mutex_unlock(&lock);
struct statfs fs;
int saved = errno;
int fuse = statfs(path, &fs) == 0 && (unsigned long)fs.f_type == FUSE_MAGIC;
errno = saved;
pthread_mutex_lock(&lock);
if (ndevs < 8) {
devs[ndevs].dev = dev;
devs[ndevs].fuse = fuse;
ndevs++;
}
pthread_mutex_unlock(&lock);
return fuse;
}
static int same(const struct listing *l, const struct stat *st) {
return l->ino == st->st_ino && l->dev == st->st_dev && l->size == st->st_size && l->nlink == st->st_nlink &&
l->mtime.tv_sec == st->st_mtim.tv_sec && l->mtime.tv_nsec == st->st_mtim.tv_nsec &&
l->ctime.tv_sec == st->st_ctim.tv_sec && l->ctime.tv_nsec == st->st_ctim.tv_nsec;
}
static void stamp(struct listing *l, const struct stat *st) {
l->dev = st->st_dev;
l->ino = st->st_ino;
l->size = st->st_size;
l->nlink = st->st_nlink;
l->mtime = st->st_mtim;
l->ctime = st->st_ctim;
}
static void destroy(struct listing *l) {
for (size_t i = 0; i < l->n; i++) free(l->e[i].name);
free(l->e);
free(l->recs);
free(l);
}
static void unref(struct listing *l) {
if (--l->refs == 0 && l->detached) destroy(l);
}
/* The rest is called with lock held. */
static void release(int wd) {
if (wd < 0 || notify < 0) return;
for (int i = 0; i < MAX_LISTINGS; i++)
if (table[i] && table[i]->wd == wd) return;
for (int i = 0; i < high_water; i++)
if (handles[i] && handles[i]->wd == wd) return;
inotify_rm_watch(notify, wd);
}
static void detach(struct listing *l) {
__atomic_sub_fetch(&cached_listings, 1, __ATOMIC_RELEASE);
l->detached = 1;
if (l->refs == 0) destroy(l);
}
/* Takes the listing out of the table; freed now or when its last reader closes. */
static void drop(int slot) {
struct listing *l = table[slot];
int wd = l->wd;
table[slot] = NULL;
detach(l);
release(wd);
}
static void changed(int wd) {
for (int i = 0; i < MAX_LISTINGS; i++)
if (table[i] && (table[i]->wd == wd || wd < 0)) drop(i);
for (int i = 0; i < high_water; i++)
if (handles[i] && (handles[i]->wd == wd || wd < 0)) __atomic_store_n(&handles[i]->dirty, 1, __ATOMIC_RELAXED);
}
/* Applies queued events; the expected ones are the client's own changes, already patched in. */
static void pump(struct expect *x, int nx) {
char buf[4096] __attribute__((aligned(__alignof__(struct inotify_event))));
if (notify < 0 || forked) return;
int saved = errno;
for (;;) {
ssize_t n = read(notify, buf, sizeof(buf));
if (n <= 0) {
if (n < 0 && errno != EAGAIN && errno != EINTR) {
notify = -2;
changed(-1);
}
break;
}
for (char *p = buf; p < buf + n;) {
struct inotify_event *ev = (struct inotify_event *)p;
p += sizeof(*ev) + ev->len;
if (ev->mask & IN_Q_OVERFLOW) {
changed(-1);
continue;
}
int k = 0;
while (k < nx && !(x[k].wd == ev->wd && (ev->mask & x[k].mask) && ev->len && strcmp(ev->name, x[k].name) == 0)) k++;
if (k < nx) {
x[k].wd = -1;
for (int i = 0; i < high_water; i++)
if (handles[i] && handles[i]->wd == ev->wd) __atomic_store_n(&handles[i]->dirty, 1, __ATOMIC_RELAXED);
} else {
changed(ev->wd);
}
}
}
errno = saved;
}
static int watch(const char *path) {
if (notify == -1) notify = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
if (notify < 0) {
notify = -2;
return -1;
}
int saved = errno;
int wd = inotify_add_watch(notify, path, WATCHED);
errno = saved;
return wd;
}
static int find(dev_t dev, ino_t ino) {
for (int i = 0; i < MAX_LISTINGS; i++)
if (table[i] && table[i]->dev == dev && table[i]->ino == ino) return i;
return -1;
}
static int push(struct listing *l, ino_t ino, unsigned char type, const char *name) {
if (l->n == l->cap) {
size_t cap = l->cap ? l->cap * 2 : 256;
struct entry *e = realloc(l->e, cap * sizeof(*e));
if (e == NULL) return -1;
l->e = e;
l->cap = cap;
}
char *copy = strdup(name);
if (copy == NULL) return -1;
l->e[l->n++] = (struct entry){ino, type, copy};
return 0;
}
static void install(struct listing *l) {
l->detached = 0;
__atomic_add_fetch(&cached_listings, 1, __ATOMIC_RELEASE);
int slot = find(l->dev, l->ino);
if (slot >= 0) {
struct listing *old = table[slot];
table[slot] = l;
detach(old);
if (old->wd != l->wd) release(old->wd);
return;
}
int victim = -1;
for (int i = 0; i < MAX_LISTINGS; i++) {
if (table[i] == NULL) { victim = i; break; }
if (victim < 0 || table[i]->used < table[victim]->used) victim = i;
}
if (table[victim]) drop(victim);
table[victim] = l;
}
static int registered(DIR *d) {
int n = __atomic_load_n(&high_water, __ATOMIC_ACQUIRE);
for (int i = 0; i < n; i++)
if (__atomic_load_n(&handles[i], __ATOMIC_ACQUIRE) == (struct handle *)d) return i;
return -1;
}
static DIR *wrap(struct handle *h) {
for (int i = 0; i < MAX_HANDLES; i++) {
if (handles[i] == NULL) {
__atomic_store_n(&handles[i], h, __ATOMIC_RELEASE);
if (i >= high_water) __atomic_store_n(&high_water, i + 1, __ATOMIC_RELEASE);
return (DIR *)h;
}
}
return NULL;
}
#define RECLEN(namelen) ((offsetof(struct dirent64, d_name) + (namelen) + 1 + 7) & ~(size_t)7)
/* The listing as packed dirent64 records, built once per version. */
static int records(struct listing *l) {
if (l->recs) return 0;
size_t len = 0;
for (size_t i = 0; i < l->n; i++) len += RECLEN(strlen(l->e[i].name));
char *recs = malloc(len ? len : 1);
if (recs == NULL) return -1;
size_t off = 0;
for (size_t i = 0; i < l->n; i++) {
size_t namelen = strlen(l->e[i].name), reclen = RECLEN(namelen);
struct dirent64 *r = (struct dirent64 *)(recs + off);
memset(r, 0, reclen);
off += reclen;
r->d_ino = l->e[i].ino;
r->d_off = (off_t)off;
r->d_reclen = (unsigned short)reclen;
r->d_type = l->e[i].type;
memcpy(r->d_name, l->e[i].name, namelen + 1);
}
l->recs = recs;
l->len = len;
return 0;
}
/* Lock-free from here on unless noted: a stream is only ever used by one thread at a time. */
static struct handle *lookup(DIR *d) {
return registered(d) >= 0 ? (struct handle *)d : NULL;
}
#define REAL(name) static __typeof__(&name) next_##name
#define NEXT(name) \
if (next_##name == NULL) next_##name = (__typeof__(&name))dlsym(RTLD_NEXT, #name)
REAL(opendir);
REAL(readdir64);
REAL(readdir);
REAL(closedir);
REAL(dirfd);
REAL(rewinddir);
REAL(telldir);
REAL(seekdir);
REAL(mkdir);
REAL(rmdir);
REAL(unlink);
REAL(remove);
REAL(rename);
REAL(link);
REAL(symlink);
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
REAL(readdir64_r);
REAL(readdir_r);
/* Resolved before the client starts threads; the calls below only fill gaps for earlier callers. */
__attribute__((constructor)) static void resolve(void) {
NEXT(opendir);
NEXT(readdir64);
NEXT(readdir);
NEXT(closedir);
NEXT(dirfd);
NEXT(rewinddir);
NEXT(telldir);
NEXT(seekdir);
NEXT(mkdir);
NEXT(rmdir);
NEXT(unlink);
NEXT(remove);
NEXT(rename);
NEXT(link);
NEXT(symlink);
NEXT(readdir64_r);
NEXT(readdir_r);
}
#pragma GCC diagnostic pop
/* A reader of the kept listing when it is still current. */
static DIR *hit(const struct stat *st, struct handle *h, long long now) {
pthread_mutex_lock(&lock);
if (!changing) pump(NULL, 0);
int slot = find(st->st_dev, st->st_ino);
if (slot >= 0 && same(table[slot], st) && now - table[slot]->filled < DIR_TTL_NS && records(table[slot]) == 0) {
h->snap = table[slot];
h->snap->refs++;
h->snap->used = now;
DIR *d = wrap(h);
if (d) {
pthread_mutex_unlock(&lock);
return d;
}
unref(h->snap);
h->snap = NULL;
} else if (slot >= 0) {
drop(slot);
}
pthread_mutex_unlock(&lock);
return NULL;
}
/* Registers the stream and its watch before anything is read, so no change goes unseen. */
static int track(struct handle *h, const char *path) {
pthread_mutex_lock(&lock);
h->wd = watch(path);
DIR *d = h->wd >= 0 ? wrap(h) : NULL;
if (d == NULL && h->wd >= 0) release(h->wd);
pthread_mutex_unlock(&lock);
return d != NULL;
}
/* Reads through the real stream, keeping what it returns. */
static void filling(struct handle *h, DIR *real, const struct stat *st, long long now) {
h->real = real;
h->fill = calloc(1, sizeof(*h->fill));
if (h->fill) {
stamp(h->fill, st);
h->fill->filled = now;
h->fill->used = now;
h->fill->wd = h->wd;
}
}
static void untrack(struct handle *h) {
pthread_mutex_lock(&lock);
int i = registered((DIR *)h);
if (i >= 0) __atomic_store_n(&handles[i], NULL, __ATOMIC_RELEASE);
release(h->wd);
pthread_mutex_unlock(&lock);
}
DIR *opendir(const char *path) {
NEXT(opendir);
struct stat st;
if (!eligible(path) || stat(path, &st) != 0 || !S_ISDIR(st.st_mode) || !on_fuse(st.st_dev, path))
return next_opendir(path);
struct handle *h = calloc(1, sizeof(*h));
char *copy = strdup(path);
if (h == NULL || copy == NULL) {
free(h);
free(copy);
return next_opendir(path);
}
h->fd = -1;
h->wd = -1;
h->path = copy;
long long now = now_ns();
DIR *d = hit(&st, h, now);
if (d) return d;
if (!track(h, path)) {
free(h->path);
free(h);
return next_opendir(path);
}
DIR *real = stat(path, &st) == 0 ? next_opendir(path) : NULL;
if (real == NULL) {
untrack(h);
free(h->path);
free(h);
return next_opendir(path);
}
filling(h, real, &st, now);
return (DIR *)h;
}
static void abandon(struct handle *h) {
if (h->fill) destroy(h->fill);
h->fill = NULL;
}
static void finish(struct handle *h) {
struct listing *l = h->fill;
struct stat st;
h->fill = NULL;
int current = stat(h->path, &st) == 0 && same(l, &st);
pthread_mutex_lock(&lock);
if (!changing) pump(NULL, 0);
if (current && !__atomic_load_n(&h->dirty, __ATOMIC_RELAXED)) install(l);
else destroy(l);
pthread_mutex_unlock(&lock);
}
static struct dirent64 *entry(struct handle *h) {
NEXT(readdir64);
if (h->real) {
int saved = errno;
errno = 0;
struct dirent64 *r = next_readdir64(h->real);
int error = errno;
if (h->fill) {
if (r) {
if (h->fill->n >= MAX_ENTRIES || push(h->fill, r->d_ino, r->d_type, r->d_name) != 0) abandon(h);
} else if (error == 0) {
finish(h);
} else {
abandon(h);
}
}
errno = error ? error : saved;
return r;
}
if (h->pos >= h->snap->len) return NULL;
const struct dirent64 *r = (const struct dirent64 *)(h->snap->recs + h->pos);
h->pos += r->d_reclen;
memcpy(&h->out, r, r->d_reclen);
return &h->out;
}
struct dirent64 *readdir64(DIR *d) {
NEXT(readdir64);
struct handle *h = lookup(d);
return h ? entry(h) : next_readdir64(d);
}
struct dirent *readdir(DIR *d) {
NEXT(readdir);
struct handle *h = lookup(d);
return h ? (struct dirent *)entry(h) : next_readdir(d);
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
int readdir64_r(DIR *d, struct dirent64 *out, struct dirent64 **result) {
NEXT(readdir64_r);
struct handle *h = lookup(d);
if (h == NULL) return next_readdir64_r(d, out, result);
if (h->real) {
abandon(h);
return next_readdir64_r(h->real, out, result);
}
struct dirent64 *r = entry(h);
if (r) memcpy(out, r, r->d_reclen);
*result = r ? out : NULL;
return 0;
}
int readdir_r(DIR *d, struct dirent *out, struct dirent **result) {
NEXT(readdir_r);
if (lookup(d) == NULL) return next_readdir_r(d, out, result);
return readdir64_r(d, (struct dirent64 *)out, (struct dirent64 **)result);
}
#pragma GCC diagnostic pop
int closedir(DIR *d) {
NEXT(closedir);
pthread_mutex_lock(&lock);
int i = registered(d);
struct handle *h = i >= 0 ? handles[i] : NULL;
if (h) {
__atomic_store_n(&handles[i], NULL, __ATOMIC_RELEASE);
if (h->snap) unref(h->snap);
release(h->wd);
}
pthread_mutex_unlock(&lock);
if (h == NULL) return next_closedir(d);
int r = 0;
if (h->real) r = next_closedir(h->real);
abandon(h);
if (h->fd >= 0) close(h->fd);
free(h->path);
free(h);
return r;
}
int dirfd(DIR *d) {
NEXT(dirfd);
struct handle *h = lookup(d);
if (h == NULL) return next_dirfd(d);
if (h->real) return next_dirfd(h->real);
if (h->fd < 0) h->fd = open(h->path, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
return h->fd;
}
void rewinddir(DIR *d) {
NEXT(rewinddir);
struct handle *h = lookup(d);
if (h == NULL) { next_rewinddir(d); return; }
if (h->real) {
abandon(h);
next_rewinddir(h->real);
} else {
h->pos = 0;
}
}
long telldir(DIR *d) {
NEXT(telldir);
struct handle *h = lookup(d);
if (h == NULL) return next_telldir(d);
return h->real ? next_telldir(h->real) : (long)h->pos;
}
void seekdir(DIR *d, long pos) {
NEXT(seekdir);
struct handle *h = lookup(d);
if (h == NULL) { next_seekdir(d, pos); return; }
if (h->real) {
abandon(h);
next_seekdir(h->real, pos);
} else {
size_t off = 0;
while (off < (size_t)pos && off < h->snap->len) off += ((const struct dirent64 *)(h->snap->recs + off))->d_reclen;
if (off == (size_t)pos) h->pos = off;
}
}
struct side { char dir[PATH_MAX]; const char *name; struct stat before; int known; };
static int split(const char *path, struct side *s) {
size_t n = strlen(path);
while (n > 1 && path[n - 1] == '/') n--;
const char *slash = memrchr(path, '/', n);
if (slash == NULL || (size_t)(slash - path) >= sizeof(s->dir) || slash[1] == 0) return 0;
size_t d = slash == path ? 1 : (size_t)(slash - path);
memcpy(s->dir, path, d);
s->dir[d] = 0;
s->name = slash + 1;
return strchr(s->name, '/') == NULL && strcmp(s->name, ".") != 0 && strcmp(s->name, "..") != 0;
}
static int watching(const char *path) {
return eligible(path) && __atomic_load_n(&cached_listings, __ATOMIC_ACQUIRE) > 0;
}
/* Called with oplock held: the client's tracked changes happen one at a time. */
static void begin(void) {
pthread_mutex_lock(&lock);
pump(NULL, 0);
changing = 1;
pthread_mutex_unlock(&lock);
}
static void before(struct side *s) {
s->known = stat(s->dir, &s->before) == 0;
}
enum { ADDED, REMOVED };
/* Patches the listing after the client's own change, or drops it when unsure. Called with lock held. */
static int patch(struct side *s, int what, uint32_t event, int ok, int error, const char *target, struct expect *x) {
struct stat now;
if (!s->known) return 0;
int slot = find(s->before.st_dev, s->before.st_ino);
if (slot < 0) return 0;
struct listing *l = table[slot];
if (!same(l, &s->before)) {
drop(slot);
return 0;
}
size_t exact = l->n, folded = l->n;
for (size_t i = 0; i < l->n; i++) {
if (strcmp(l->e[i].name, s->name) == 0) { exact = i; break; }
if (folded == l->n && strcasecmp(l->e[i].name, s->name) == 0) folded = i;
}
if (!ok) {
if ((what == ADDED && error == EEXIST && exact == l->n && folded == l->n) || (what == REMOVED && error == ENOENT && exact < l->n))
drop(slot);
return 0;
}
if (stat(s->dir, &now) != 0 || now.st_ino != l->ino) {
drop(slot);
return 0;
}
if (l->refs > 0) {
struct listing *copy = calloc(1, sizeof(*copy));
int failed = copy == NULL;
for (size_t i = 0; !failed && i < l->n; i++) failed = push(copy, l->e[i].ino, l->e[i].type, l->e[i].name) != 0;
if (failed) {
if (copy) destroy(copy);
drop(slot);
return 0;
}
copy->filled = l->filled;
copy->used = l->used;
copy->wd = l->wd;
copy->detached = 0;
stamp(copy, &s->before);
table[slot] = copy;
l->detached = 1;
l = copy;
}
free(l->recs);
l->recs = NULL;
l->len = 0;
int fine = 1, expected = 1;
struct stat t;
if (what == ADDED) {
if (exact < l->n) {
if (lstat(target, &t) == 0) l->e[exact].ino = t.st_ino;
expected = event == IN_MOVED_TO;
} else if (folded < l->n || lstat(target, &t) != 0) {
fine = 0;
} else {
unsigned char type = S_ISDIR(t.st_mode) ? DT_DIR : S_ISLNK(t.st_mode) ? DT_LNK : S_ISREG(t.st_mode) ? DT_REG : DT_UNKNOWN;
fine = l->n < MAX_ENTRIES && push(l, t.st_ino, type, s->name) == 0;
}
} else if (exact < l->n) {
free(l->e[exact].name);
memmove(&l->e[exact], &l->e[exact + 1], (l->n - exact - 1) * sizeof(l->e[0]));
l->n--;
} else {
fine = 0;
}
if (!fine) {
drop(slot);
return 0;
}
stamp(l, &now);
if (!expected) return 0;
*x = (struct expect){l->wd, event, s->name};
return 1;
}
static void end(struct expect *x, int nx) {
pthread_mutex_lock(&lock);
pump(x, nx);
changing = 0;
pthread_mutex_unlock(&lock);
}
int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
int (*real)(int, const char *, int, mode_t)) __attribute__((visibility("hidden")));
int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
int (*real)(int, const char *, int, mode_t)) {
struct side s;
if (!(flags & O_CREAT) || (dirfd != AT_FDCWD && (path == NULL || path[0] != '/')) || !watching(path) || !split(path, &s))
return real(dirfd, path, flags, mode);
pthread_mutex_lock(&oplock);
begin();
before(&s);
int fd = real(dirfd, path, flags, mode);
int saved = errno;
struct expect x;
pthread_mutex_lock(&lock);
int nx = patch(&s, ADDED, IN_CREATE, fd >= 0, saved, path, &x);
pthread_mutex_unlock(&lock);
end(&x, nx);
pthread_mutex_unlock(&oplock);
errno = saved;
return fd;
}
#define ONE_PATH(name, what, event, call, ...) \
int name(const char *path, ##__VA_ARGS__) { \
NEXT(name); \
struct side s; \
if (!watching(path) || !split(path, &s)) return call; \
pthread_mutex_lock(&oplock); \
begin(); \
before(&s); \
int r = call; \
int saved = errno; \
struct expect x; \
pthread_mutex_lock(&lock); \
int nx = patch(&s, what, event, r == 0, saved, what == ADDED ? path : NULL, &x); \
pthread_mutex_unlock(&lock); \
end(&x, nx); \
pthread_mutex_unlock(&oplock); \
errno = saved; \
return r; \
}
ONE_PATH(mkdir, ADDED, IN_CREATE, next_mkdir(path, mode), mode_t mode)
ONE_PATH(rmdir, REMOVED, IN_DELETE, next_rmdir(path))
ONE_PATH(unlink, REMOVED, IN_DELETE, next_unlink(path))
ONE_PATH(remove, REMOVED, IN_DELETE, next_remove(path))
#define TWO_PATHS(name, gone, event) \
int name(const char *from, const char *to) { \
NEXT(name); \
struct side a, b; \
int track_a = gone && watching(from) && split(from, &a), track_b = watching(to) && split(to, &b); \
if (!track_a && !track_b) return next_##name(from, to); \
pthread_mutex_lock(&oplock); \
begin(); \
if (track_a) before(&a); \
if (track_b) before(&b); \
int r = next_##name(from, to); \
int saved = errno; \
struct expect x[2]; \
int nx = 0; \
pthread_mutex_lock(&lock); \
if (track_a) nx += patch(&a, REMOVED, IN_MOVED_FROM, r == 0, saved, NULL, &x[nx]); \
if (track_b) { \
if (track_a && strcmp(a.dir, b.dir) == 0) b.known = stat(b.dir, &b.before) == 0; \
nx += patch(&b, ADDED, event, r == 0, saved, to, &x[nx]); \
} \
pthread_mutex_unlock(&lock); \
end(x, nx); \
pthread_mutex_unlock(&oplock); \
errno = saved; \
return r; \
}
TWO_PATHS(rename, 1, IN_MOVED_TO)
TWO_PATHS(link, 0, IN_CREATE)
TWO_PATHS(symlink, 0, IN_CREATE)
#else
int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
int (*real)(int, const char *, int, mode_t)) __attribute__((visibility("hidden")));
int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
int (*real)(int, const char *, int, mode_t)) {
return real(dirfd, path, flags, mode);
}
#endif
+65 -22
View File
@@ -41,6 +41,19 @@ static const char *net_dir(void) {
return dir;
}
static int loopback_family(const struct sockaddr *address, socklen_t length) {
if (address && address->sa_family == AF_INET && length >= sizeof(struct sockaddr_in)) {
return ((const struct sockaddr_in *)address)->sin_addr.s_addr == htonl(INADDR_LOOPBACK) ? AF_INET : 0;
}
if (address && address->sa_family == AF_INET6 && length >= sizeof(struct sockaddr_in6)) {
const struct in6_addr *ip = &((const struct sockaddr_in6 *)address)->sin6_addr;
if (IN6_IS_ADDR_LOOPBACK(ip)) return AF_INET6;
if (IN6_IS_ADDR_V4MAPPED(ip) && ip->s6_addr[12] == 127 && ip->s6_addr[13] == 0 &&
ip->s6_addr[14] == 0 && ip->s6_addr[15] == 1) return AF_INET;
}
return 0;
}
/* Record that this process owns a loopback socket on its local port; peer is the far end's port,
* 0 for a listening socket. */
static void record_port(int fd, unsigned peer) {
@@ -49,12 +62,11 @@ static void record_port(int fd, unsigned peer) {
if (getsockname(fd, (struct sockaddr *)&ss, &len) != 0) {
return;
}
int family = loopback_family((struct sockaddr *)&ss, len);
if (!family) return;
unsigned port;
if (ss.ss_family == AF_INET) {
struct sockaddr_in *in = (struct sockaddr_in *)&ss;
if (in->sin_addr.s_addr != htonl(INADDR_LOOPBACK)) {
return;
}
port = ntohs(in->sin_port);
} else if (ss.ss_family == AF_INET6) {
port = ntohs(((struct sockaddr_in6 *)&ss)->sin6_port);
@@ -64,14 +76,21 @@ static void record_port(int fd, unsigned peer) {
if (port == 0) {
return;
}
struct stat socket_stat;
if (fstat(fd, &socket_stat) != 0) return;
char path[300];
snprintf(path, sizeof(path), "%s/p%u", net_dir(), port);
char line[64];
int n = snprintf(line, sizeof(line), "%d %d %d %u\n", (int)getpid(), (int)getppid(), (int)getuid(), peer);
int out = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0666);
char staged[360];
snprintf(staged, sizeof(staged), "%s.tmp.%d.%d", path, (int)getpid(), fd);
char line[128];
int n = snprintf(line, sizeof(line), "%d %d %d %u %d %llu %d\n", (int)getpid(), (int)getppid(),
(int)getuid(), peer, fd, (unsigned long long)socket_stat.st_ino, family);
int out = open(staged, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0600);
if (out >= 0) {
if (write(out, line, n) != n) { /* best effort */ }
int complete = write(out, line, n) == n;
close(out);
if (complete) rename(staged, path);
unlink(staged);
}
}
@@ -98,6 +117,7 @@ typedef int (*bind_fn)(int, const struct sockaddr *, socklen_t);
typedef int (*listen_fn)(int, int);
typedef int (*connect_fn)(int, const struct sockaddr *, socklen_t);
typedef int (*accept4_fn)(int, struct sockaddr *, socklen_t *, int);
static unsigned guarded_port(void);
/* udevmon.c: a stand-in for the netlink socket the sandbox refuses, bound here without the kernel. */
__attribute__((visibility("hidden"))) int bl_udevmon_stand_in(int fd);
@@ -112,6 +132,18 @@ int bind(int fd, const struct sockaddr *addr, socklen_t len) {
}
return 0;
}
struct sockaddr_storage local;
unsigned guarded = guarded_port();
if (guarded && addr_port(addr, len) == guarded && len <= sizeof(local)) {
memcpy(&local, addr, len);
if (addr->sa_family == AF_INET) {
((struct sockaddr_in *)&local)->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr = (struct sockaddr *)&local;
} else if (addr->sa_family == AF_INET6) {
((struct sockaddr_in6 *)&local)->sin6_addr = in6addr_loopback;
addr = (struct sockaddr *)&local;
}
}
int ret = real(fd, addr, len);
if (ret == 0) record_port(fd, 0);
return ret;
@@ -135,22 +167,20 @@ static unsigned local_port(int fd) {
}
static void bind_before_loopback_connect(int fd, const struct sockaddr *addr, socklen_t len) {
if (!addr || addr->sa_family != AF_INET || len < sizeof(struct sockaddr_in) ||
((const struct sockaddr_in *)addr)->sin_addr.s_addr != htonl(INADDR_LOOPBACK)) {
return;
}
if (!loopback_family(addr, len)) return;
struct sockaddr_storage ss;
socklen_t slen = sizeof(ss);
if (getsockname(fd, (struct sockaddr *)&ss, &slen) != 0 || ss.ss_family != AF_INET ||
((struct sockaddr_in *)&ss)->sin_port != 0) {
if (getsockname(fd, (struct sockaddr *)&ss, &slen) != 0 || ss.ss_family != addr->sa_family ||
addr_port((struct sockaddr *)&ss, slen) != 0) {
return;
}
struct sockaddr_in local;
memset(&local, 0, sizeof(local));
local.sin_family = AF_INET;
local.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
struct sockaddr_storage local;
if (len > sizeof(local)) return;
memcpy(&local, addr, len);
if (addr->sa_family == AF_INET) ((struct sockaddr_in *)&local)->sin_port = 0;
else ((struct sockaddr_in6 *)&local)->sin6_port = 0;
int saved = errno;
bind(fd, (struct sockaddr *)&local, sizeof(local));
bind(fd, (struct sockaddr *)&local, len);
errno = saved;
}
@@ -165,6 +195,11 @@ static unsigned guarded_port(void) {
}
static int guest_peer(int fd) {
struct sockaddr_storage address;
socklen_t length = sizeof(address);
if (getpeername(fd, (struct sockaddr *)&address, &length) != 0) return 0;
int family = loopback_family((struct sockaddr *)&address, length);
if (!family) return 0;
unsigned peer = peer_port(fd);
if (peer == 0) {
return 0;
@@ -179,26 +214,34 @@ static int guest_peer(int fd) {
if (in < 0) {
return 0;
}
char buf[64];
char buf[128];
int n = read(in, buf, sizeof(buf) - 1);
close(in);
if (n <= 0) {
return 0;
}
buf[n] = '\0';
int pid = atoi(buf);
return pid > 0 && (kill(pid, 0) == 0 || errno != ESRCH);
int pid, parent, uid, descriptor, recorded_family;
unsigned destination;
unsigned long long inode;
if (sscanf(buf, "%d %d %d %u %d %llu %d", &pid, &parent, &uid, &destination, &descriptor,
&inode, &recorded_family) != 7 || pid <= 0 || descriptor < 0 || destination != guarded_port() ||
recorded_family != family) return 0;
snprintf(path, sizeof(path), "/proc/%d/fd/%d", pid, descriptor);
return stat(path, &st) == 0 && S_ISSOCK(st.st_mode) && (unsigned long long)st.st_ino == inode;
}
int connect(int fd, const struct sockaddr *addr, socklen_t len) {
static connect_fn real;
if (!real) real = (connect_fn)dlsym(RTLD_NEXT, "connect");
bind_before_loopback_connect(fd, addr, len);
unsigned peer = loopback_family(addr, len) ? addr_port(addr, len) : 0;
if (peer) record_port(fd, peer);
int ret = real(fd, addr, len);
if (ret == 0 || errno == EINPROGRESS) {
/* The caller goes on to test for EINPROGRESS, which the bookkeeping must not disturb. */
int saved = errno;
record_port(fd, addr_port(addr, len));
record_port(fd, peer);
errno = saved;
}
return ret;
+16 -4
View File
@@ -36,6 +36,20 @@
int bl_status_without_tracer(const char *path, int flags) __attribute__((visibility("hidden")));
int bl_writable_retry(int dirfd, const char *path, int flags) __attribute__((visibility("hidden")));
int bl_ntsync_open(const char *path, int flags) __attribute__((visibility("hidden")));
int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
int (*real)(int, const char *, int, mode_t)) __attribute__((visibility("hidden")));
static int (*real_open)(const char *, int, ...);
static int (*real_openat)(int, const char *, int, ...);
static int via_open(int dirfd, const char *path, int flags, mode_t mode) {
(void)dirfd;
return real_open(path, flags, mode);
}
static int via_openat(int dirfd, const char *path, int flags, mode_t mode) {
return real_openat(dirfd, path, flags, mode);
}
static int retry_without_noatime(int fd, int flags) {
return fd < 0 && errno == EPERM && (flags & O_NOATIME);
@@ -49,7 +63,6 @@ static int is_trace_marker(const char *path) {
}
int open(const char *path, int flags, ...) {
static int (*real_open)(const char *, int, ...);
va_list ap;
mode_t mode;
int fd;
@@ -68,7 +81,7 @@ int open(const char *path, int flags, ...) {
errno = ENOSYS;
return -1;
}
fd = real_open(path, flags, mode);
fd = bl_dircache_create(AT_FDCWD, path, flags, mode, via_open);
if (retry_without_noatime(fd, flags)) fd = real_open(path, flags & ~O_NOATIME, mode);
/* A read-only file the Steam client rewrites (perms.c). */
if (fd < 0 && bl_writable_retry(AT_FDCWD, path, flags)) fd = real_open(path, flags & ~O_NOATIME, mode);
@@ -76,7 +89,6 @@ int open(const char *path, int flags, ...) {
}
int openat(int dirfd, const char *path, int flags, ...) {
static int (*real_openat)(int, const char *, int, ...);
va_list ap;
mode_t mode;
int fd;
@@ -95,7 +107,7 @@ int openat(int dirfd, const char *path, int flags, ...) {
errno = ENOSYS;
return -1;
}
fd = real_openat(dirfd, path, flags, mode);
fd = bl_dircache_create(dirfd, path, flags, mode, via_openat);
if (retry_without_noatime(fd, flags)) fd = real_openat(dirfd, path, flags & ~O_NOATIME, mode);
if (fd < 0 && bl_writable_retry(dirfd, path, flags)) fd = real_openat(dirfd, path, flags & ~O_NOATIME, mode);
return fd;
+190
View File
@@ -0,0 +1,190 @@
import json
import os
import re
import subprocess
import sys
import time
import urllib.error
import urllib.request
REPORT = "<!-- droiddeck-pr-release -->"
STATE = re.compile(r"\n<!-- droiddeck-discord: (\{[^\n]*\}) -->")
def github(path, method="GET", body=None):
args = ["gh", "api", path, "--method", method]
if body is not None:
args += ["--input", "-"]
result = subprocess.run(args, input=json.dumps(body) if body is not None else None,
capture_output=True, text=True)
if result.returncode:
raise RuntimeError("GitHub request failed")
return json.loads(result.stdout) if result.stdout.strip() else None
def report_comment(repo, number):
page = 1
while True:
comments = github(f"repos/{repo}/issues/{number}/comments?per_page=100&page={page}")
for comment in comments:
if (comment.get("user", {}).get("login") == "github-actions[bot]"
and (comment.get("body") or "").startswith(REPORT)):
return comment
if len(comments) < 100:
return None
page += 1
def saved_message(body, webhook_id):
match = STATE.search(body)
if not match:
return None
try:
state = json.loads(match.group(1))
except ValueError:
return None
if (state.get("webhook_id") == webhook_id
and re.fullmatch(r"[0-9]{15,22}", str(state.get("message_id", "")))):
return state["message_id"]
return None
class Discord:
def __init__(self, webhook):
match = re.fullmatch(r"https://discord\.com/api(?:/v[0-9]+)?/webhooks/([0-9]{15,22})/([A-Za-z0-9_-]+)", webhook)
if not match:
raise RuntimeError("Invalid Discord webhook configuration")
self.url = webhook
self.id = match.group(1)
def request(self, method, suffix="", body=None):
data = json.dumps(body).encode() if body is not None else None
request = urllib.request.Request(self.url + suffix, data=data,
headers={"Content-Type": "application/json",
"User-Agent": "DroidDeck-PR-builds"}, method=method)
for attempt in range(3):
try:
with urllib.request.urlopen(request, timeout=30) as response:
return json.load(response)
except urllib.error.HTTPError as error:
if error.code == 404:
return None
if method != "POST" and error.code in (429, 500, 502, 503, 504) and attempt < 2:
time.sleep(2 ** attempt)
continue
raise RuntimeError(f"Discord request failed (HTTP {error.code})") from None
except (OSError, ValueError):
raise RuntimeError("Discord request failed") from None
def plain_title(title):
title = " ".join(title.split())[:300]
return re.sub(r"([\\`*_~|\[\]<>])", r"\\\1", title)
def description_excerpt(body):
body = re.sub(r"<!--.*?-->", "", body or "", flags=re.DOTALL)
body = re.sub(r"```.*?```", "", body, flags=re.DOTALL)
for paragraph in re.split(r"\n\s*\n", body):
lines = [line.strip() for line in paragraph.splitlines()]
lines = [line for line in lines if line and not re.match(r"^(#{1,6}\s|[-*]\s+\[[ xX]\]|🤖)", line)]
text = " ".join(lines)
if not text or text.strip("*_` :.").lower() in (
"summary", "description", "checklist", "testing", "n/a", "none",
"please describe your changes here", "describe your changes"):
continue
text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text)
if len(text) > 300:
text = text[:297].rsplit(" ", 1)[0] + "..."
return plain_title(text)
return ""
def build_content(repo, number, title, sha, apk, release, description=None):
excerpt = description_excerpt(description)
return (f"**Signed PR test build** `pr-{number}` · `{sha[:7]}`\n"
f"[#{number}](https://github.com/{repo}/pull/{number}): {plain_title(title)}\n"
+ (f"\n{excerpt}\n\n" if excerpt else "") +
"_Not merged — for testing._\n"
f"Download: [standard APK](<{apk}>) · [all variants](<{release}>)")
def retired_content(content, merged):
label = "Merged" if merged else "Closed"
if content.startswith(("**Merged** —", "**Closed** —")):
content = "\n".join(line[2:-2] if line.startswith("~~") and line.endswith("~~") else line
for line in content.splitlines()[2:])
struck = "\n".join(f"~~{line}~~" if line else "" for line in content.splitlines())
return f"**{label}** — this PR test build is no longer available.\n\n{struck}"
def sync(mode, repo, number, discord, sha="", apk="", release=""):
pull = github(f"repos/{repo}/pulls/{number}")
if mode == "publish":
if (pull["state"] != "open" or pull.get("draft") or pull["base"]["ref"] != "main"
or pull["head"]["sha"] != sha):
print("PR changed; no Discord announcement published")
return
elif pull["state"] != "closed":
print("PR is open; Discord announcement retained")
return
comment = report_comment(repo, number)
if comment is None:
if mode == "retire":
return
raise RuntimeError("Signed build report comment is missing")
message_id = saved_message(comment["body"], discord.id)
if mode == "retire":
if message_id:
message = discord.request("GET", f"/messages/{message_id}")
if message:
discord.request("PATCH", f"/messages/{message_id}",
{"content": retired_content(message["content"], pull.get("merged", False)),
"allowed_mentions": {"parse": []}, "flags": 4})
return
content = build_content(repo, number, pull["title"], sha, apk, release, pull.get("body"))
if len(content) > 1800:
raise RuntimeError("Discord announcement is too long")
payload = {"content": content, "allowed_mentions": {"parse": []}, "flags": 4}
message = discord.request("PATCH", f"/messages/{message_id}", payload) if message_id else None
if message is None:
message = discord.request("POST", "?wait=true", payload)
if message is None:
raise RuntimeError("Discord webhook no longer exists")
state = {"webhook_id": discord.id, "message_id": message["id"]}
latest = github(f"repos/{repo}/issues/comments/{comment['id']}")
body = STATE.sub("", latest["body"]).rstrip() + f"\n<!-- droiddeck-discord: {json.dumps(state)} -->"
github(f"repos/{repo}/issues/comments/{comment['id']}", "PATCH", {"body": body})
print("Discord PR announcement updated")
def main():
webhook = os.environ.get("WEBHOOK", "")
if not webhook:
print("::notice::No DISCORD_PR_BUILDS_WEBHOOK secret; nothing posted")
return
repo = os.environ["GITHUB_REPOSITORY"]
number = os.environ["PR_NUMBER"]
if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repo) or not re.fullmatch(r"[1-9][0-9]*", number):
raise RuntimeError("Invalid PR configuration")
mode = sys.argv[1]
if mode not in ("publish", "retire"):
raise RuntimeError("Invalid announcement mode")
sha, apk, release = (os.environ.get(key, "") for key in ("HEAD_SHA", "APK", "RELEASE"))
if mode == "publish":
prefix = f"https://github.com/Droid-Deck/DroidDeck-CI/releases/"
if (not re.fullmatch(r"[0-9a-f]{40}", sha)
or not apk.startswith(prefix + f"download/pr-{number}/")
or release != prefix + f"tag/pr-{number}"
or re.search(r"[\s<>]", apk)):
raise RuntimeError("Invalid published build configuration")
sync(mode, repo, number, Discord(webhook), sha, apk, release)
if __name__ == "__main__":
try:
main()
except Exception as error:
print(f"::error::{error}" if isinstance(error, RuntimeError) else "::error::Discord announcement failed", file=sys.stderr)
sys.exit(1)
@@ -0,0 +1,83 @@
{
"name": "skyrim-launcher-focus",
"vars": {
"appId": 489830
},
"repeat": 6,
"setup": [
[
"wake"
]
],
"before": [
[
"start",
"steam",
"--wait",
"--reuse",
"--timeout",
"240"
]
],
"steps": [
[
"launch",
"${appId}",
"--wait",
"--timeout",
"240"
],
{
"sleep": 8
},
[
"input",
"tap",
"0.927",
"0.111",
"--space",
"fraction"
],
{
"sleep": 30
},
[
"wait",
"focused",
"${appId}",
"--timeout",
"60"
],
{
"screenshot": "in-game"
},
[
"quit",
"${appId}",
"--timeout",
"20"
],
{
"assert": "remaining",
"equals": []
},
{
"sleep": 5
}
],
"after": [
[
"quit",
"${appId}",
"--timeout",
"20"
]
],
"teardown": [
[
"stop",
"--timeout",
"120"
]
]
}
+70
View File
@@ -0,0 +1,70 @@
{
"name": "steam-game-focus",
"vars": {
"appId": 489830
},
"repeat": 6,
"setup": [
[
"wake"
]
],
"before": [
[
"start",
"steam",
"--wait",
"--reuse",
"--timeout",
"240"
]
],
"steps": [
[
"launch",
"${appId}",
"--wait",
"--timeout",
"240"
],
{
"assert": "focus.focusedApp",
"equals": "${appId}"
},
{
"assert": "focus.focusableApps",
"contains": "${appId}"
},
{
"screenshot": "focused"
},
[
"quit",
"${appId}",
"--timeout",
"20"
],
{
"assert": "remaining",
"equals": []
},
{
"sleep": 5
}
],
"after": [
[
"quit",
"${appId}",
"--timeout",
"20"
]
],
"teardown": [
[
"stop",
"--timeout",
"120"
]
]
}
+118
View File
@@ -0,0 +1,118 @@
import os
from pathlib import Path
import shutil
import socket
import subprocess
import sys
import tempfile
import unittest
SOURCE = Path(__file__).resolve().parents[1] / "linuxfs/preload/net.c"
@unittest.skipUnless(sys.platform.startswith("linux") and shutil.which("cc"), "needs Linux and a C compiler")
class CdpGuardTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.build = tempfile.TemporaryDirectory()
cls.library = Path(cls.build.name) / "net.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", str(SOURCE), "-x", "c", "-", "-ldl", "-o", str(cls.library)],
input=b"int bl_udevmon_stand_in(int fd) { return 0; }", check=True, capture_output=True)
@classmethod
def tearDownClass(cls):
cls.build.cleanup()
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.registry = Path(self.temp.name) / "net"
self.registry.mkdir()
def port(self, ipv6=False):
with socket.socket(socket.AF_INET6 if ipv6 else socket.AF_INET) as s:
s.bind(("::1" if ipv6 else "127.0.0.1", 0))
return s.getsockname()[1]
def env(self, port):
return dict(os.environ, LD_PRELOAD=str(self.library), BL_CDP_GUARD=str(port), BL_SYSV_DIR=self.temp.name)
def test_guarded_ipv4_bind_is_loopback_only(self):
port = self.port()
program = "import socket; s=socket.socket(); s.bind(('0.0.0.0', %d)); print(s.getsockname()[0])" % port
result = subprocess.run([sys.executable, "-c", program], env=self.env(port), check=True, capture_output=True, text=True)
self.assertEqual("127.0.0.1", result.stdout.strip())
def test_guarded_ipv6_bind_is_loopback_only(self):
if not socket.has_ipv6:
self.skipTest("needs IPv6")
port = self.port(True)
program = "import socket; s=socket.socket(socket.AF_INET6); s.bind(('::', %d)); print(s.getsockname()[0])" % port
result = subprocess.run([sys.executable, "-c", program], env=self.env(port), check=True, capture_output=True, text=True)
self.assertEqual("::1", result.stdout.strip())
def test_other_listeners_are_unchanged(self):
port = self.port()
program = "import socket; s=socket.socket(); s.bind(('0.0.0.0', %d)); print(s.getsockname()[0])" % port
result = subprocess.run([sys.executable, "-c", program], env=self.env(0), check=True, capture_output=True, text=True)
self.assertEqual("0.0.0.0", result.stdout.strip())
def connect(self, address, registered, stale=False, wrong_destination=False):
port = self.port()
program = "import socket; s=socket.socket(); s.bind(('0.0.0.0', %d)); s.listen(); print('ready', flush=True); c,_=s.accept(); c.sendall(b'accepted')" % port
server = subprocess.Popen([sys.executable, "-u", "-c", program], env=self.env(port), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
self.assertEqual(b"ready\n", server.stdout.readline())
with socket.socket() as client:
client.settimeout(3)
client.bind((address, 0))
if registered:
peer = client.getsockname()[1]
inode = os.fstat(client.fileno()).st_ino + (1 if stale else 0)
destination = port + (1 if wrong_destination else 0)
(self.registry / ("p%d" % peer)).write_text("%d 1 %d %d %d %d %d\n" %
(os.getpid(), os.getuid(), destination, client.fileno(), inode, socket.AF_INET))
client.connect(("127.0.0.1", port))
try:
return client.recv(8)
except ConnectionResetError:
return b""
finally:
server.kill()
server.wait()
server.stdout.close()
server.stderr.close()
def test_registered_guest_loopback_peer_is_accepted(self):
self.assertEqual(b"accepted", self.connect("127.0.0.1", True))
def test_unregistered_local_peer_is_refused(self):
self.assertEqual(b"", self.connect("127.0.0.1", False))
def test_matching_port_record_cannot_authorize_another_address(self):
self.assertEqual(b"", self.connect("127.0.0.2", True))
def test_stale_socket_record_does_not_authorize_a_reused_port(self):
self.assertEqual(b"", self.connect("127.0.0.1", True, stale=True))
def test_record_for_another_destination_does_not_authorize_cdp(self):
self.assertEqual(b"", self.connect("127.0.0.1", True, wrong_destination=True))
def test_preloaded_guest_connect_still_works(self):
port = self.port()
program = "import socket; s=socket.socket(); s.bind(('0.0.0.0', %d)); s.listen(); print('ready', flush=True); c,_=s.accept(); c.sendall(b'accepted')" % port
server = subprocess.Popen([sys.executable, "-u", "-c", program], env=self.env(port), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
self.assertEqual(b"ready\n", server.stdout.readline())
client = "import socket; s=socket.create_connection(('127.0.0.1', %d), timeout=3); print(s.recv(8).decode())" % port
result = subprocess.run([sys.executable, "-c", client], env=self.env(port), check=True, capture_output=True, text=True, timeout=5)
self.assertEqual("accepted", result.stdout.strip())
finally:
server.kill()
server.wait()
server.stdout.close()
server.stderr.close()
if __name__ == "__main__":
unittest.main()
+410
View File
@@ -0,0 +1,410 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
FAKE = r"""
#define _GNU_SOURCE
#include <dirent.h>
#include <dlfcn.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/statfs.h>
#include <unistd.h>
int real_opendirs;
/* COARSE=1: directory stats that never change, like NTFS's whole-second times and fixed size. */
static void coarse(const char *path, struct stat *st) {
if (getenv("COARSE") && strstr(path, "/fuse/") && S_ISDIR(st->st_mode)) {
st->st_mtim = st->st_ctim = (struct timespec){1, 0};
st->st_size = 4096;
st->st_nlink = 1;
}
}
int stat(const char *path, struct stat *st) {
static int (*next)(const char *, struct stat *);
if (!next) next = dlsym(RTLD_NEXT, "stat");
int r = next(path, st);
if (r == 0) coarse(path, st);
return r;
}
int fstat(int fd, struct stat *st) {
static int (*next)(int, struct stat *);
if (!next) next = dlsym(RTLD_NEXT, "fstat");
char link[64], path[4096];
snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
ssize_t n = readlink(link, path, sizeof(path) - 1);
path[n > 0 ? n : 0] = 0;
int r = next(fd, st);
if (r == 0) coarse(path, st);
return r;
}
int fstatfs(int fd, struct statfs *out) {
static int (*next)(int, struct statfs *);
if (!next) next = dlsym(RTLD_NEXT, "fstatfs");
char link[64], path[4096];
snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
ssize_t n = readlink(link, path, sizeof(path) - 1);
path[n > 0 ? n : 0] = 0;
int r = next(fd, out);
if (r == 0 && strstr(path, "/fuse/")) out->f_type = 0x65735546;
return r;
}
int statfs(const char *path, struct statfs *out) {
static int (*next)(const char *, struct statfs *);
if (!next) next = dlsym(RTLD_NEXT, "statfs");
int r = next(path, out);
if (r == 0 && strstr(path, "/fuse/")) out->f_type = 0x65735546;
return r;
}
/* FASTPATH=1: open directories the way the fast-path preload does, through fdopendir. */
DIR *opendir(const char *path) {
static DIR *(*next)(const char *);
if (!next) next = dlsym(RTLD_NEXT, "opendir");
if (getenv("FASTPATH")) {
int fd = open(path, O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NONBLOCK);
DIR *d = fd < 0 ? NULL : fdopendir(fd);
if (d == NULL && fd >= 0) close(fd);
return d;
}
real_opendirs++;
return next(path);
}
DIR *fdopendir(int fd) {
static DIR *(*next)(int);
if (!next) next = dlsym(RTLD_NEXT, "fdopendir");
real_opendirs++;
return next(fd);
}
"""
PROGRAM = r"""
#define _GNU_SOURCE
#include <dirent.h>
#include <dlfcn.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <unistd.h>
static int by_name(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); }
static void print(char **names, int n) {
qsort(names, n, sizeof(*names), by_name);
for (int i = 0; i < n; i++) printf("%s%s", i ? "," : "", names[i]);
printf("\n");
}
static void list(const char *dir) {
char *names[256];
int n = 0;
DIR *d = opendir(dir);
struct dirent *e;
while (d && (e = readdir(d)))
if (strcmp(e->d_name, ".") && strcmp(e->d_name, "..")) names[n++] = strdup(e->d_name);
if (d) closedir(d);
print(names, n);
}
static void raw(const char *dir) {
char buf[8192], *names[256];
int n = 0, fd = open(dir, O_RDONLY | O_DIRECTORY);
long k;
while ((k = syscall(SYS_getdents64, fd, buf, sizeof(buf))) > 0) {
for (long off = 0; off < k;) {
struct dirent64 *e = (struct dirent64 *)(buf + off);
if (strcmp(e->d_name, ".") && strcmp(e->d_name, "..")) names[n++] = strdup(e->d_name);
off += e->d_reclen;
}
}
close(fd);
print(names, n);
}
static const char *stress_dir;
static int stop;
static void *reader(void *arg) {
(void)arg;
while (!__atomic_load_n(&stop, __ATOMIC_ACQUIRE)) {
DIR *d = opendir(stress_dir);
struct dirent *e;
while (d && (e = readdir(d)))
if (e->d_reclen == 0) abort();
if (d) closedir(d);
}
return NULL;
}
static void stress(const char *dir) {
pthread_t t[4];
char a[4096], b[4096];
stress_dir = dir;
for (int i = 0; i < 4; i++) pthread_create(&t[i], NULL, reader, NULL);
for (int i = 0; i < 300; i++) {
snprintf(a, sizeof(a), "%s/s%d", dir, i);
snprintf(b, sizeof(b), "%s/t%d", dir, i);
close(open(a, O_WRONLY | O_CREAT, 0644));
rename(a, b);
if (i % 3 == 0) unlink(b);
}
__atomic_store_n(&stop, 1, __ATOMIC_RELEASE);
for (int i = 0; i < 4; i++) pthread_join(t[i], NULL);
}
int main(int argc, char **argv) {
int *opens = dlsym(RTLD_DEFAULT, "real_opendirs");
for (int i = 1; i < argc; i++) {
const char *op = argv[i], *a = argv[i + 1];
if (!strcmp(op, "list")) { list(a); i++; }
else if (!strcmp(op, "raw")) { raw(a); i++; }
else if (!strcmp(op, "create")) { close(open(a, O_WRONLY | O_CREAT, 0644)); i++; }
else if (!strcmp(op, "sneak")) { close((int)syscall(SYS_openat, AT_FDCWD, a, O_WRONLY | O_CREAT, 0644)); i++; }
else if (!strcmp(op, "sneak-unlink")) { syscall(SYS_unlinkat, AT_FDCWD, a, 0); i++; }
else if (!strcmp(op, "unlink")) { unlink(a); i++; }
else if (!strcmp(op, "remove")) { remove(a); i++; }
else if (!strcmp(op, "mkdir")) { mkdir(a, 0755); i++; }
else if (!strcmp(op, "rmdir")) { rmdir(a); i++; }
else if (!strcmp(op, "rename")) { rename(a, argv[i + 2]); i += 2; }
else if (!strcmp(op, "half")) {
DIR *d = opendir(a);
readdir(d);
closedir(d);
i++;
}
else if (!strcmp(op, "rewind")) {
DIR *d = opendir(a);
int n = 0, m = 0;
while (readdir(d)) n++;
rewinddir(d);
while (readdir(d)) m++;
struct stat st;
printf("%d %d %d\n", n, m, fstat(dirfd(d), &st) == 0 && S_ISDIR(st.st_mode));
closedir(d);
i++;
}
else if (!strcmp(op, "seek")) {
DIR *d = opendir(a);
readdir(d);
readdir(d);
long at = telldir(d);
char want[256];
snprintf(want, sizeof(want), "%s", readdir(d)->d_name);
readdir(d);
seekdir(d, at);
int back = strcmp(readdir(d)->d_name, want) == 0;
seekdir(d, at + 1);
struct dirent *e = readdir(d);
printf("%d %d\n", back, e != NULL && e->d_reclen > 0);
closedir(d);
i++;
}
else if (!strcmp(op, "stress")) { stress(a); i++; }
else if (!strcmp(op, "drain")) {
DIR *d = opendir(a);
int rounds = 0, n;
do {
struct dirent *e;
n = 0;
while ((e = readdir(d)))
if (strcmp(e->d_name, ".") && strcmp(e->d_name, "..") && unlinkat(dirfd(d), e->d_name, 0) == 0) n++;
rewinddir(d);
} while (n > 0 && ++rounds < 50);
closedir(d);
printf("%d\n", rounds);
i++;
}
else if (!strcmp(op, "fork")) {
pid_t child = fork();
if (child == 0) {
DIR *d = opendir(a);
while (d && readdir(d)) {}
if (d) closedir(d);
close((int)syscall(SYS_openat, AT_FDCWD, argv[i + 2], O_WRONLY | O_CREAT, 0644));
DIR *e = opendir(a);
while (e && readdir(e)) {}
if (e) closedir(e);
_exit(0);
}
waitpid(child, NULL, 0);
i += 2;
}
else if (!strcmp(op, "opens")) printf("%d\n", opens ? *opens : -1);
}
return 0;
}
"""
@unittest.skipUnless(shutil.which("cc"), "needs a C compiler")
class DirCachePreloadTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.dir = Path(tempfile.mkdtemp())
build = cls.dir / "build"
build.mkdir()
(build / "fake.c").write_text(FAKE)
(build / "program.c").write_text(PROGRAM)
cls.cache = build / "libblsession.so"
cls.fake = build / "fake.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(cls.cache),
*map(str, sorted(PRELOAD.glob("*.c"))), "-ldl"], check=True)
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.fake), str(build / "fake.c"), "-ldl"], check=True)
cls.steam = cls.dir / "steamrtarm64/steam"
cls.steam.parent.mkdir()
subprocess.run(["cc", "-O2", "-pthread", "-o", str(cls.steam), str(build / "program.c"), "-ldl"], check=True)
cls.other = build / "steamwebhelper"
shutil.copy(cls.steam, cls.other)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.dir, True)
def setUp(self):
self.lib = Path(tempfile.mkdtemp(dir=self.dir)) / "fuse/steamapps"
self.staging = self.lib / "downloading/4992280"
self.staging.mkdir(parents=True)
for name in ("a.bundle", "b.bundle"):
(self.staging / name).touch()
def run_program(self, *args, program=None, env=None):
environment = dict(os.environ, LD_PRELOAD="%s:%s" % (self.cache, self.fake))
environment.update(env or {})
result = subprocess.run([str(program or self.steam), *map(str, args)], env=environment,
capture_output=True, text=True, check=True, timeout=60)
return result.stdout.splitlines()
def test_repeated_listings_read_the_directory_once(self):
out = self.run_program("list", self.staging, "list", self.staging, "list", self.staging, "opens")
self.assertEqual(["a.bundle,b.bundle"] * 3 + ["1"], out)
def test_own_changes_keep_the_listing_exact(self):
s = self.staging
out = self.run_program(
"list", s,
"create", s / "c.bundle", "list", s, "raw", s,
"create", s / "a.bundle", "list", s, "raw", s,
"mkdir", s / "sub", "list", s, "raw", s,
"rename", s / "c.bundle", s / "d.bundle", "list", s, "raw", s,
"unlink", s / "a.bundle", "list", s, "raw", s,
"rmdir", s / "sub", "list", s, "raw", s,
"remove", s / "b.bundle", "list", s, "raw", s,
"opens")
self.assertEqual(out[2:15:2], out[1:15:2])
self.assertEqual("d.bundle", out[-2])
self.assertEqual("1", out[-1])
def test_moves_between_directories_update_both(self):
common = self.lib / "common/Game"
common.mkdir(parents=True)
s = self.staging
out = self.run_program("list", s, "list", common,
"rename", s / "a.bundle", common / "a.bundle",
"list", s, "raw", s, "list", common, "raw", common, "opens")
self.assertEqual(["b.bundle", "b.bundle", "a.bundle", "a.bundle", "2"], out[2:])
def test_changes_made_around_the_cache_are_noticed(self):
s = self.staging
out = self.run_program("list", s, "sneak", s / "x.bundle", "list", s,
"sneak-unlink", s / "a.bundle", "list", s, "opens")
self.assertEqual(["a.bundle,b.bundle", "a.bundle,b.bundle,x.bundle", "b.bundle,x.bundle", "3"], out)
def test_changes_are_noticed_when_directory_times_are_coarse(self):
s = self.staging
out = self.run_program("list", s, "sneak", s / "x.bundle", "list", s,
"sneak-unlink", s / "a.bundle", "list", s,
"create", s / "c.bundle", "list", s, "raw", s, env={"COARSE": "1"})
self.assertEqual(["a.bundle,b.bundle", "a.bundle,b.bundle,x.bundle", "b.bundle,x.bundle"], out[:3])
self.assertEqual(out[4], out[3])
self.assertEqual("b.bundle,c.bundle,x.bundle", out[3])
def test_own_changes_stay_cached_when_directory_times_are_coarse(self):
s = self.staging
out = self.run_program("list", s, "create", s / "c.bundle", "rename", s / "c.bundle", s / "d.bundle",
"unlink", s / "a.bundle", "list", s, "raw", s, "opens", env={"COARSE": "1"})
self.assertEqual(["b.bundle,d.bundle", "b.bundle,d.bundle", "1"], out[1:])
def test_rewinddir_sees_what_changed_since(self):
s = self.staging
out = self.run_program("list", s, "drain", s, "list", s, "raw", s, env={"COARSE": "1"})
self.assertEqual(["1", "", ""], out[1:])
def test_directories_opened_through_fdopendir_underneath(self):
s = self.staging
out = self.run_program("list", s, "list", s, "sneak", s / "x.bundle", "list", s, "rewind", s,
"create", s / "c.bundle", "list", s, "raw", s, "opens",
env={"FASTPATH": "1", "COARSE": "1"})
self.assertEqual(["a.bundle,b.bundle", "a.bundle,b.bundle", "a.bundle,b.bundle,x.bundle"], out[:3])
self.assertEqual(out[5], out[4])
self.assertEqual("a.bundle,b.bundle,c.bundle,x.bundle", out[4])
self.assertEqual("2", out[-1])
def test_a_forked_child_leaves_the_parent_cache_alone(self):
s = self.staging
out = self.run_program("list", s, "fork", s, s / "f.bundle", "list", s, "raw", s, env={"COARSE": "1"})
self.assertEqual("a.bundle,b.bundle,f.bundle", out[1])
self.assertEqual(out[2], out[1])
def test_another_process_changing_the_directory_is_noticed(self):
s = self.staging
first = self.run_program("list", s)
(s / "y.bundle").touch()
self.assertEqual(["a.bundle,b.bundle"], first)
self.assertEqual(["a.bundle,b.bundle,y.bundle"], self.run_program("list", s))
def test_a_listing_read_halfway_is_not_kept(self):
out = self.run_program("half", self.staging, "list", self.staging, "list", self.staging, "opens")
self.assertEqual(["a.bundle,b.bundle", "a.bundle,b.bundle", "2"], out)
def test_rewind_and_dirfd_work_on_a_cached_listing(self):
out = self.run_program("list", self.staging, "rewind", self.staging, "opens")
self.assertEqual(["4 4 1", "1"], out[1:])
def test_seekdir_returns_to_a_told_position(self):
for name in ("c.bundle", "d.bundle", "e.bundle"):
(self.staging / name).touch()
out = self.run_program("list", self.staging, "seek", self.staging, "opens")
self.assertEqual(["1 1", "1"], out[1:])
def test_readers_and_changes_on_other_threads(self):
s = self.staging
out = self.run_program("list", s, "stress", s, "list", s, "raw", s)
self.assertEqual(out[-1], out[-2])
self.assertEqual(202, len(out[-1].split(",")))
def test_only_the_client_and_only_fuse_steamapps(self):
other = self.run_program("list", self.staging, "list", self.staging, "opens", program=self.other)
self.assertEqual("2", other[-1])
native = Path(tempfile.mkdtemp(dir=self.dir)) / "steamapps/downloading/1"
native.mkdir(parents=True)
self.assertEqual("2", self.run_program("list", native, "list", native, "opens")[-1])
outside = self.lib.parent / "elsewhere"
outside.mkdir()
self.assertEqual("2", self.run_program("list", outside, "list", outside, "opens")[-1])
def test_can_be_turned_off(self):
out = self.run_program("list", self.staging, "list", self.staging, "opens", env={"BL_NO_DIR_CACHE": "1"})
self.assertEqual("2", out[-1])
if __name__ == "__main__":
unittest.main()
+256
View File
@@ -0,0 +1,256 @@
"""The guest agent: its request files, exec, errors and the DevTools client, without a session."""
import base64
import hashlib
import importlib.machinery
import importlib.util
import json
import os
from pathlib import Path
import socket
import struct
import subprocess
import sys
import tempfile
import threading
import time
import unittest
from unittest.mock import patch
import tracemalloc
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-agent"
loader = importlib.machinery.SourceFileLoader("droiddeck_agent", str(SCRIPT))
spec = importlib.util.spec_from_loader(loader.name, loader)
agent = importlib.util.module_from_spec(spec)
loader.exec_module(agent)
class FakeDevTools(threading.Thread):
"""GET /json lists one target; its WebSocket answers Runtime.evaluate the way Chromium does."""
def __init__(self, answer):
super().__init__(daemon=True)
self.answer = answer
self.server = socket.socket()
self.server.bind(("127.0.0.1", 0))
self.server.listen(4)
self.port = self.server.getsockname()[1]
self.seen = []
def run(self):
while True:
try:
conn, _ = self.server.accept()
except OSError:
return
threading.Thread(target=self.serve, args=(conn,), daemon=True).start()
def serve(self, conn):
head = b""
while b"\r\n\r\n" not in head:
head += conn.recv(4096)
request = head.decode()
if request.startswith("GET /json"):
body = json.dumps([{"title": "SharedJSContext", "url": "https://steamloopback.host/", "type": "page",
"webSocketDebuggerUrl": "ws://127.0.0.1:%d/devtools/page/1" % self.port}]).encode()
conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: %d\r\n\r\n" % len(body) + body)
conn.close()
return
key = [l.split(":", 1)[1].strip() for l in request.split("\r\n") if l.lower().startswith("sec-websocket-key")][0]
accept = base64.b64encode(hashlib.sha1((key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode()).digest()).decode()
conn.sendall(("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
"Sec-WebSocket-Accept: %s\r\n\r\n" % accept).encode())
b0, b1 = conn.recv(2)
n = b1 & 0x7F
if n == 126:
n = struct.unpack(">H", conn.recv(2))[0]
mask = conn.recv(4)
data = b""
while len(data) < n:
data += conn.recv(n - len(data))
message = json.loads(bytes(b ^ mask[i % 4] for i, b in enumerate(data)))
self.seen.append(message)
for reply in ({"method": "Runtime.consoleAPICalled", "params": {}}, dict(self.answer, id=message["id"])):
payload = json.dumps(reply).encode()
header = bytes([0x81, 126]) + struct.pack(">H", len(payload)) if len(payload) > 125 else bytes([0x81, len(payload)])
conn.sendall(header + payload)
time.sleep(0.2)
conn.close()
class AgentTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.dir = Path(self.temp.name)
(self.dir / "resp").mkdir()
def ask(self, request):
path = self.dir / "req.json"
path.write_text(json.dumps(request))
agent.answer(self.dir, path)
self.assertFalse(path.exists(), "the request file is consumed")
return json.loads((self.dir / "resp" / "req.json").read_text())
def test_exec_output_and_status(self):
answer = self.ask({"kind": "exec", "argv": ["sh", "-c", "echo out; echo err >&2; exit 3"], "env": {"X": "1"}})
self.assertTrue(answer["ok"])
self.assertEqual(3, answer["exitCode"])
self.assertEqual("out\n", answer["stdout"]["text"])
self.assertEqual("err\n", answer["stderr"]["text"])
self.assertFalse(answer["timedOut"])
def test_exec_environment_stdin_and_cap(self):
answer = self.ask({"kind": "exec", "argv": ["sh", "-c", "printf %s \"$X\"; cat"], "env": {"X": "a"}, "stdin": "b"})
self.assertEqual("ab", answer["stdout"]["text"])
big = self.ask({"kind": "exec", "argv": ["sh", "-c", "head -c 300000 /dev/zero"]})
self.assertTrue(big["stdout"]["truncated"])
self.assertEqual(agent.OUTPUT_CAP, len(big["stdout"]["text"]))
def test_exec_timeout_kills_the_process_group(self):
started = time.monotonic()
answer = self.ask({"kind": "exec", "argv": ["sh", "-c", "sleep 30 & sleep 30"], "timeout": 0.5})
self.assertTrue(answer["timedOut"])
self.assertLess(time.monotonic() - started, 10)
def test_exec_memory_is_bounded_while_draining_large_output(self):
tracemalloc.start()
try:
answer = agent.run_exec({"argv": [sys.executable, "-c", "import os; [os.write(1, b'x' * 65536) for _ in range(1024)]"]})
_, peak = tracemalloc.get_traced_memory()
finally:
tracemalloc.stop()
self.assertEqual(0, answer["exitCode"])
self.assertEqual(agent.OUTPUT_CAP, len(answer["stdout"]["text"]))
self.assertTrue(answer["stdout"]["truncated"])
self.assertLess(peak, 6 * 1024 * 1024)
def test_exec_drains_both_streams_while_writing_stdin(self):
program = "import os, sys; os.write(1, b'x' * 300000); print(len(sys.stdin.read()), file=sys.stderr)"
answer = self.ask({"kind": "exec", "argv": [sys.executable, "-c", program], "stdin": "y" * 100000})
self.assertFalse(answer["timedOut"])
self.assertTrue(answer["stdout"]["truncated"])
self.assertEqual("100000\n", answer["stderr"]["text"])
def test_flooding_both_streams_still_times_out(self):
program = "import os\nwhile True:\n os.write(1, b'o' * 65536)\n os.write(2, b'e' * 65536)"
answer = self.ask({"kind": "exec", "argv": [sys.executable, "-c", program], "timeout": 0.5})
self.assertTrue(answer["timedOut"])
for name in ("stdout", "stderr"):
self.assertEqual(agent.OUTPUT_CAP, len(answer[name]["text"]))
self.assertTrue(answer[name]["truncated"])
def test_timeout_applies_when_parent_exits_with_inherited_pipes(self):
started = time.monotonic()
answer = self.ask({"kind": "exec", "argv": ["sh", "-c", "sleep 30 & exit 0"], "timeout": 0.5})
self.assertTrue(answer["timedOut"])
self.assertLess(time.monotonic() - started, 5)
def test_invalid_timeout_and_input_are_refused_before_exec(self):
for value in (0, -1, 601, "NaN", "Infinity", "invalid"):
answer = self.ask({"kind": "exec", "argv": ["true"], "timeout": value})
self.assertEqual("INVALID_REQUEST", answer["error"]["code"])
for fields in ({"stdin": 1}, {"env": []}, {"env": {"BAD=KEY": "value"}}, {"argv": ["true\0"]}):
answer = self.ask({"kind": "exec", "argv": ["true"], **fields})
self.assertEqual("INVALID_REQUEST", answer["error"]["code"])
def test_errors_are_answers(self):
self.assertEqual("INVALID_REQUEST", self.ask({"kind": "exec", "argv": []})["error"]["code"])
self.assertEqual("EXEC_FAILED", self.ask({"kind": "exec", "argv": ["/no/such/program"]})["error"]["code"])
self.assertEqual("UNKNOWN_REQUEST", self.ask({"kind": "nope"})["error"]["code"])
self.assertEqual("INVALID_APP_ID", self.ask({"kind": "quit", "appId": "x"})["error"]["code"])
(self.dir / "req.json").write_text("{not json")
agent.answer(self.dir, self.dir / "req.json")
self.assertEqual("INVALID_REQUEST", json.loads((self.dir / "resp" / "req.json").read_text())["error"]["code"])
def test_request_shape_and_size_are_bounded(self):
self.assertEqual("INVALID_REQUEST", self.ask([])["error"]["code"])
self.assertEqual("INVALID_REQUEST", self.ask({"kind": "ping", "unused": "x" * agent.REQUEST_CAP})["error"]["code"])
def test_replies_are_owner_only_even_when_replacing_a_public_file(self):
path = self.dir / "private.json"
path.write_text("old")
path.chmod(0o644)
agent.write_json(path, {"ok": True})
self.assertEqual(0o600, path.stat().st_mode & 0o777)
def test_oversized_websocket_frames_are_refused_before_reading_payload(self):
ws = agent.WebSocket.__new__(agent.WebSocket)
ws.buffer = bytes([0x81, 127]) + struct.pack(">Q", agent.RESPONSE_CAP + 1)
with self.assertRaises(agent.AgentError) as caught:
ws.recv()
self.assertEqual("RESPONSE_TOO_LARGE", caught.exception.code)
def test_devtools_targets_cannot_connect_to_remote_hosts(self):
for url in ("ws://example.com/devtools", "ws://127.0.0.1@example.com/devtools", "wss://127.0.0.1/devtools"):
with patch.object(agent.socket, "create_connection") as connect:
with self.assertRaises(agent.AgentError) as caught:
agent.WebSocket(url, 1)
self.assertEqual("INVALID_TARGET", caught.exception.code)
connect.assert_not_called()
def test_cdp_without_a_port(self):
os.environ.pop("BL_CDP_PORT", None)
self.assertEqual("NO_DEVTOOLS", self.ask({"kind": "cdp", "expression": "1"})["error"]["code"])
def test_cdp_eval(self):
server = FakeDevTools({"result": {"result": {"type": "number", "value": 42}}})
server.start()
self.addCleanup(server.server.close)
(self.dir / "cdp-port").write_text("%d\n" % server.port)
answer = self.ask({"kind": "cdp", "expression": "6 * 7"})
self.assertTrue(answer["ok"], answer)
self.assertEqual(42, answer["value"])
self.assertEqual("SharedJSContext", answer["target"])
self.assertEqual("Runtime.evaluate", server.seen[0]["method"])
self.assertEqual("6 * 7", server.seen[0]["params"]["expression"])
targets = self.ask({"kind": "cdp", "op": "targets"})
self.assertEqual("SharedJSContext", targets["targets"][0]["title"])
missing = self.ask({"kind": "cdp", "expression": "1", "target": "Nope"})
self.assertEqual("NO_TARGET", missing["error"]["code"])
def test_cdp_exception(self):
server = FakeDevTools({"result": {"result": {"type": "object"}, "exceptionDetails": {
"text": "Uncaught", "exception": {"description": "ReferenceError: SteamClient is not defined"}}}})
server.start()
self.addCleanup(server.server.close)
(self.dir / "cdp-port").write_text(str(server.port))
answer = self.ask({"kind": "cdp", "expression": "SteamClient"})
self.assertEqual("JS_EXCEPTION", answer["error"]["code"])
self.assertIn("ReferenceError", answer["error"]["message"])
def test_serve_answers_request_files(self):
server = subprocess.Popen([sys.executable, str(SCRIPT), "--no-focus"],
env=dict(os.environ, BL_LAUNCH_DIR=str(self.dir)),
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def stop_server():
server.terminate()
server.wait(timeout=5)
self.addCleanup(stop_server)
agent_dir = self.dir / "agent"
for _ in range(100):
if (agent_dir / "hello.json").exists():
break
time.sleep(0.02)
hello = json.loads((agent_dir / "hello.json").read_text())
self.assertEqual(server.pid, hello["pid"])
self.assertFalse(hello["focus"])
(agent_dir / "req" / "a.json.tmp").write_text(json.dumps({"kind": "ping"}))
os.replace(agent_dir / "req" / "a.json.tmp", agent_dir / "req" / "a.json")
for _ in range(200):
if (agent_dir / "resp" / "a.json").exists():
break
time.sleep(0.02)
self.assertEqual(agent.VERSION, json.loads((agent_dir / "resp" / "a.json").read_text())["version"])
def test_game_pids_reads_the_steam_environment(self):
import subprocess
if not Path("/proc").is_dir():
self.skipTest("needs /proc")
child = subprocess.Popen(["sleep", "30"], env=dict(os.environ, SteamAppId="424242"))
self.addCleanup(lambda: (child.kill(), child.wait()))
time.sleep(0.2)
self.assertIn(child.pid, agent.game_pids(424242))
if __name__ == "__main__":
unittest.main()
+76
View File
@@ -0,0 +1,76 @@
import subprocess
import tempfile
import unittest
from pathlib import Path
FONTS = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-fonts"
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
class DroidDeckFontsTest(unittest.TestCase):
def setUp(self):
temporary = tempfile.TemporaryDirectory()
self.addCleanup(temporary.cleanup)
self.root = Path(temporary.name)
defaults = self.root / "usr/share/fontconfig/conf.default"
defaults.mkdir(parents=True)
(defaults / "60-latin.conf").write_text("<fontconfig/>")
dejavu = self.root / "usr/share/fonts/truetype/dejavu"
dejavu.mkdir(parents=True)
(dejavu / "DejaVuSans.ttf").write_text("dejavu")
def run_fonts(self):
subprocess.run(["bash", str(FONTS), str(self.root)], check=True, capture_output=True)
def local_conf(self):
return (self.root / "etc/fonts/local.conf").read_text()
def owned_conf(self):
return (self.root / "etc/fonts/conf.d/65-droiddeck-default-fonts.conf").read_text()
def test_default_rules_linked_and_dejavu_is_the_default(self):
self.run_fonts()
self.assertTrue((self.root / "etc/fonts/conf.d/60-latin.conf").is_symlink())
text = self.owned_conf()
self.assertIn("<family>sans-serif</family><prefer><family>DejaVu Sans</family>", text)
self.assertIn("<family>monospace</family><prefer><family>DejaVu Sans Mono</family>", text)
self.assertNotIn("Noto Sans CJK", text)
self.assertFalse((self.root / "etc/fonts/local.conf").exists())
def test_an_existing_conf_d_rule_is_not_replaced(self):
conf_d = self.root / "etc/fonts/conf.d"
conf_d.mkdir(parents=True)
(conf_d / "60-latin.conf").write_text("mine")
self.run_fonts()
self.assertFalse((conf_d / "60-latin.conf").is_symlink())
self.assertEqual("mine", (conf_d / "60-latin.conf").read_text())
def test_custom_local_conf_survives_and_device_language_fallback_remains_configured(self):
custom = self.root / "etc/fonts/local.conf"
custom.parent.mkdir(parents=True, exist_ok=True)
custom.write_text("<fontconfig><rescan><int>45</int></rescan></fontconfig>")
self.run_fonts()
self.assertEqual("<fontconfig><rescan><int>45</int></rescan></fontconfig>", self.local_conf())
session = SESSION.read_text()
self.assertIn('device_fonts=/usr/local/share/fonts/android', session)
self.assertIn('zh-cn=Noto Sans CJK SC', session)
self.assertIn('ja=Noto Sans CJK JP', session)
self.assertIn('ko=Noto Sans CJK KR', session)
self.assertIn('th=Noto Sans Thai', session)
def test_unchanged_fonts_do_not_rewrite_owned_conf(self):
self.run_fonts()
owned = self.root / "etc/fonts/conf.d/65-droiddeck-default-fonts.conf"
before = owned.stat().st_mtime_ns
self.run_fonts()
self.assertEqual(before, owned.stat().st_mtime_ns)
def test_the_session_runs_the_bootstrap_before_it_starts_a_program(self):
text = SESSION.read_text()
self.assertIn("/usr/local/bin/droiddeck-fonts", text)
self.assertLess(text.index("droiddeck-fonts"), text.index("droiddeck-steam-install"))
if __name__ == "__main__":
unittest.main()
+353
View File
@@ -0,0 +1,353 @@
"""droiddeckctl and droiddeck-scenario against a fake adb: the JSON contract and exit codes."""
import base64
import contextlib
import importlib.machinery
import importlib.util
import io
import json
import os
from pathlib import Path
import stat
import sys
import tempfile
import textwrap
import unittest
TOOLS = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(TOOLS))
def load(name):
loader = importlib.machinery.SourceFileLoader(name.replace("-", "_"), str(TOOLS / name))
spec = importlib.util.spec_from_loader(loader.name, loader)
module = importlib.util.module_from_spec(spec)
loader.exec_module(module)
return module
ctl = load("droiddeckctl")
scenario = load("droiddeck-scenario")
# A stand-in for adb: answers the provider's content calls from a JSON config (a list answers
# successive calls), records every invocation, and fakes the few shell commands droiddeckctl uses.
FAKE_ADB = textwrap.dedent('''\
#!/usr/bin/env python3
import base64, json, os, sys
config_path = os.environ["FAKE_ADB_CONFIG"]
config = json.load(open(config_path))
args = sys.argv[1:]
if args[:1] == ["-s"]:
args = args[2:]
entry = {"args": args}
if args[:1] == ["get-state"]:
print("device"); sys.exit(0)
if args[:3] == ["shell", "content", "call"]:
method = args[args.index("--method") + 1]
request = None
if "--extra" in args:
request = json.loads(base64.b64decode(args[args.index("--extra") + 1].split(":", 2)[2]))
entry.update(method=method, request=request)
answers = config["provider"].get(method, {"ok": False, "error": {"code": "UNKNOWN_COMMAND", "message": method}})
if isinstance(answers, list):
count = config.setdefault("counts", {}).get(method, 0)
config["counts"][method] = count + 1
answers = answers[min(count, len(answers) - 1)]
json.dump(config, open(config_path, "w"))
print("Result: Bundle[{json=" + json.dumps(answers) + "}]")
elif args[:3] == ["shell", "dumpsys", "display"]:
print(config.get("dumpsys_display", ""))
elif args[:3] == ["shell", "dumpsys", "power"]:
print(" mWakefulness=Awake")
elif args[:2] == ["exec-out", "screencap"]:
sys.stdout.buffer.write(b"\\x89PNG fake")
with open(config["log"], "a") as log:
log.write(json.dumps(entry) + "\\n")
''')
DUMPSYS_DISPLAY = textwrap.dedent('''\
Display Devices: size=2
DisplayDeviceInfo{"Built-in Screen": uniqueId="local:111", 1080 x 1920}
DisplayDeviceInfo{"Screen-2": uniqueId="local:222", 1080 x 1240}
Logical Displays: size=2
Display 0:
mDisplayId=0
mPrimaryDisplayDevice=Built-in Screen
mBaseDisplayInfo=DisplayInfo{"Built-in Screen", displayId 0", real 1080 x 1920, x}
Display 4:
mDisplayId=4
mPrimaryDisplayDevice=Screen-2
mBaseDisplayInfo=DisplayInfo{"Screen-2", displayId 4", real 1080 x 1240, x}
''')
def state(phase="READY", focused=None, focusable=()):
focus = None if focused is None else {"focusedApp": focused, "focusableApps": list(focusable),
"baselayerAppIds": [], "seq": 1, "t": 0}
return {"ok": True, "schema": 2, "session": {"id": "s1", "phase": phase, "running": phase == "READY",
"focus": focus, "failure": None}}
class FakeAdbTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.dir = Path(self.temp.name)
self.adb = self.dir / "adb"
self.adb.write_text(FAKE_ADB)
self.adb.chmod(self.adb.stat().st_mode | stat.S_IEXEC)
self.config = self.dir / "config.json"
self.log = self.dir / "log.jsonl"
self.configure({})
os.environ["FAKE_ADB_CONFIG"] = str(self.config)
self.addCleanup(os.environ.pop, "FAKE_ADB_CONFIG", None)
def configure(self, provider, **extra):
self.config.write_text(json.dumps(dict({"provider": provider, "log": str(self.log)}, **extra)))
def run_ctl(self, *argv):
out = io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()):
code = ctl.main(["--adb", str(self.adb), "--serial", "fake-1", *argv])
return code, json.loads(out.getvalue())
def calls(self, method=None):
if not self.log.exists():
return []
entries = [json.loads(line) for line in self.log.read_text().splitlines()]
return [e for e in entries if method is None or e.get("method") == method]
class DroiddeckctlTest(FakeAdbTest):
def test_oversized_requests_are_refused_before_adb(self):
with self.assertRaises(ctl.ControlError) as caught:
ctl.provider_call(str(self.adb), "fake-1", "guest", request={"stdin": "x" * ctl.REQUEST_CAP})
self.assertEqual("INVALID_REQUEST", caught.exception.code)
self.assertFalse(self.calls())
def test_state_passes_through_with_the_serial(self):
self.configure({"state": state()})
code, out = self.run_ctl("state")
self.assertEqual(0, code)
self.assertEqual("READY", out["session"]["phase"])
self.assertEqual("fake-1", out["deviceSerial"])
def test_launch_sends_the_app_id_and_waits_for_focus(self):
self.configure({
"launch": {"ok": True, "command": "launch", "appId": "489830"},
"state": [state(focused=769, focusable=[769]), state(focused=489830, focusable=[769])],
})
# Focus alone is not enough: the game must also be in the list Steam orders from.
code, out = self.run_ctl("launch", "489830", "--wait", "--timeout", "1")
self.assertEqual(5, code)
self.assertEqual("TIMEOUT", out["error"]["code"])
self.assertIn("focused app 489830", out["error"]["message"])
self.assertEqual({"appId": "489830"}, self.calls("launch")[0]["request"])
self.configure({
"launch": {"ok": True, "command": "launch", "appId": "489830"},
"state": [state(focused=769, focusable=[769]), state(focused=489830, focusable=[489830, 769])],
})
code, out = self.run_ctl("launch", "489830", "--wait", "--timeout", "5")
self.assertEqual(0, code)
self.assertEqual(489830, out["focus"]["focusedApp"])
def test_start_reuse_keeps_a_running_session(self):
running = state(focused=769)
running["session"]["mode"] = "steam"
self.configure({"state": running})
code, out = self.run_ctl("start", "steam", "--reuse", "--wait")
self.assertEqual(0, code)
self.assertTrue(out["reused"])
self.assertFalse([c for c in self.calls() if c["args"][:2] == ["shell", "am"]])
def test_start_without_reuse_refuses_a_running_session(self):
running = state()
running["session"]["mode"] = "steam"
self.configure({"state": running})
code, out = self.run_ctl("start", "steam")
self.assertEqual(4, code)
self.assertEqual("SESSION_ACTIVE", out["error"]["code"])
def test_wait_game_ignores_the_client(self):
self.configure({"state": [state(focused=769), state(focused=752590, focusable=[752590])]})
code, out = self.run_ctl("wait", "game", "--timeout", "5")
self.assertEqual(0, code)
self.assertEqual(752590, out["session"]["focus"]["focusedApp"])
def test_a_failed_session_ends_a_wait(self):
failed = state(phase="FAILED")
failed["session"]["failure"] = {"code": "GUEST_EXIT", "message": "boom"}
self.configure({"state": failed})
code, out = self.run_ctl("wait", "focused", "1", "--timeout", "5")
self.assertEqual(4, code)
self.assertEqual("GUEST_EXIT", out["error"]["code"])
def test_disabled_agent_commands_exit_7(self):
self.configure({"guest": {"ok": False, "error": {"code": "AGENT_COMMANDS_DISABLED", "message": "off"}}})
code, out = self.run_ctl("guest", "--", "true")
self.assertEqual(7, code)
self.assertEqual("AGENT_COMMANDS_DISABLED", out["error"]["code"])
def test_run_checks_access_before_launching_an_activity(self):
self.configure({"access": {"ok": True, "commands": False}})
code, out = self.run_ctl("run", "/usr/bin/sh", "--", "-c", "true")
self.assertEqual(7, code)
self.assertEqual("AGENT_COMMANDS_DISABLED", out["error"]["code"])
self.assertIn("Debugging tools", out["error"]["message"])
self.assertEqual(["access"], [c.get("method") for c in self.calls()])
def test_override_checks_names_before_pushing_any_file(self):
self.configure({"access": {"ok": True, "commands": True, "inbox": "/tmp/inbox"}})
source = self.dir / "binary"
source.write_bytes(b"test")
code, out = self.run_ctl("override", "../outside", str(source))
self.assertEqual(2, code)
self.assertEqual("INVALID_NAME", out["error"]["code"])
self.assertEqual(["access"], [c.get("method") for c in self.calls()])
def test_guest_request_and_check(self):
self.configure({"guest": {"ok": True, "exitCode": 3, "stdout": {"text": ""}, "stderr": {"text": "nope"}}})
code, out = self.run_ctl("guest", "--timeout", "7", "--env", "A=1", "--check", "--", "xprop", "-root")
self.assertEqual(4, code)
self.assertEqual("GUEST_EXIT", out["error"]["code"])
self.assertEqual({"argv": ["xprop", "-root"], "timeout": 7.0, "env": {"A": "1"}},
self.calls("guest")[0]["request"])
def test_screenshot_resolves_the_logical_display(self):
self.configure({}, dumpsys_display=DUMPSYS_DISPLAY)
target = self.dir / "shot.png"
code, out = self.run_ctl("screenshot", str(target), "--display", "4")
self.assertEqual(0, code)
self.assertTrue(target.read_bytes().startswith(b"\x89PNG"))
shot = [c for c in self.calls() if c["args"][:2] == ["exec-out", "screencap"]][0]
self.assertEqual(["exec-out", "screencap", "-p", "-d", "222"], shot["args"])
def test_displays(self):
self.configure({}, dumpsys_display=DUMPSYS_DISPLAY)
code, out = self.run_ctl("displays")
self.assertEqual(0, code)
self.assertEqual([0, 4], [d["display"] for d in out["displays"]])
self.assertEqual("222", out["displays"][1]["physicalId"])
self.assertEqual([1080, 1240], out["displays"][1]["size"])
def test_unknown_display_is_an_error(self):
self.configure({}, dumpsys_display=DUMPSYS_DISPLAY)
code, out = self.run_ctl("screenshot", str(self.dir / "x.png"), "--display", "9")
self.assertEqual(2, code)
self.assertEqual("NO_SUCH_DISPLAY", out["error"]["code"])
def test_input_requests(self):
self.configure({"input": {"ok": True, "command": "input"}})
self.run_ctl("input", "tap", "0.5", "0.25", "--space", "fraction")
self.run_ctl("input", "key", "enter", "--mod", "CTRL")
self.run_ctl("input", "pad", "a", "--hold", "50")
requests = [c["request"] for c in self.calls("input")]
self.assertEqual({"type": "tap", "x": 0.5, "y": 0.25, "space": "fraction", "holdMs": 60}, requests[0])
self.assertEqual({"type": "key", "key": "enter", "action": "tap", "modifiers": ["CTRL"], "holdMs": 40}, requests[1])
self.assertEqual({"type": "pad", "button": "a", "action": "tap", "holdMs": 50}, requests[2])
def test_ui_click_by_tag_or_match(self):
self.configure({"ui": {"ok": True, "command": "ui"}})
self.run_ctl("ui", "click", "rail-steam")
self.run_ctl("ui", "click", "--match", "Play", "--index", "1")
requests = [c["request"] for c in self.calls("ui")]
self.assertEqual({"op": "click", "index": 0, "tag": "rail-steam"}, requests[0])
self.assertEqual({"op": "click", "index": 1, "match": "Play"}, requests[1])
def test_cdp_targets_and_eval_requests(self):
self.configure({"cdp": {"ok": True, "targets": []}})
self.assertEqual(0, self.run_ctl("cdp", "targets")[0])
self.assertEqual(0, self.run_ctl("cdp", "eval", "1+1", "--target", "Big Picture")[0])
requests = [c["request"] for c in self.calls("cdp")]
self.assertEqual({"op": "targets"}, requests[0])
self.assertEqual({"op": "eval", "expression": "1+1", "awaitPromise": True, "timeout": 15.0,
"target": "Big Picture"}, requests[1])
def test_a_bug_still_answers_json(self):
self.configure({"state": {"ok": True, "session": "not an object"}})
code, out = self.run_ctl("wait", "game", "--timeout", "1")
self.assertEqual(2, code)
self.assertEqual("INTERNAL_ERROR", out["error"]["code"])
def test_wake(self):
code, out = self.run_ctl("wake")
self.assertEqual(0, code)
self.assertEqual("Awake", out["wakefulness"])
self.assertIn(["shell", "input", "keyevent", "KEYCODE_WAKEUP"], [c["args"] for c in self.calls()])
def test_override_pushes_to_the_inbox_first(self):
self.configure({
"access": {"ok": True, "commands": True, "inbox": "/sdcard/Android/data/x/files/agent-inbox"},
"override": {"ok": True, "installed": "/opt/droiddeck-agent/bin/gamescope"},
})
binary = self.dir / "gamescope"
binary.write_bytes(b"\x7fELF")
code, out = self.run_ctl("override", "gamescope", str(binary))
self.assertEqual(0, code)
push = [c for c in self.calls() if c["args"][:1] == ["push"]][0]
self.assertEqual("/sdcard/Android/data/x/files/agent-inbox/gamescope", push["args"][2])
self.assertEqual({"name": "gamescope"}, self.calls("override")[0]["request"])
def test_override_refused_before_pushing_when_commands_are_off(self):
self.configure({"access": {"ok": True, "commands": False, "inbox": "/x"}})
binary = self.dir / "gamescope"
binary.write_bytes(b"x")
code, out = self.run_ctl("override", "gamescope", str(binary))
self.assertEqual(7, code)
self.assertFalse([c for c in self.calls() if c["args"][:1] == ["push"]])
class ScenarioTest(FakeAdbTest):
def write(self, body):
path = self.dir / "scenario.json"
path.write_text(json.dumps(body))
return path
def run_scenario(self, path, *extra):
out = io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()):
code = scenario.main([str(path), "--adb", str(self.adb), "--serial", "fake-1",
"--out", str(self.dir / "runs"), *extra])
return code, json.loads(out.getvalue())
def test_variables_asserts_and_repeats(self):
self.configure({"state": state(focused=489830, focusable=[489830])})
path = self.write({
"name": "t", "vars": {"appId": 1}, "repeat": 2,
"steps": [["state"], {"assert": "session.focus.focusedApp", "equals": "${appId}"}],
})
code, report = self.run_scenario(path, "--var", "appId=489830")
self.assertEqual(0, code)
self.assertEqual(2, report["passed"])
output = Path(report["out"])
self.assertEqual(0o700, output.stat().st_mode & 0o777)
for artifact in output.rglob("*.json"):
self.assertEqual(0o600, artifact.stat().st_mode & 0o777, str(artifact))
for run in report["runs"]:
self.assertEqual(0o700, Path(run["folder"]).stat().st_mode & 0o777)
def test_a_failed_assert_fails_the_run_and_collects_evidence(self):
self.configure({"state": state(focused=769, focusable=[769]), "focus": {"ok": True, "focusedApp": 769}},
dumpsys_display=DUMPSYS_DISPLAY)
path = self.write({"name": "t", "repeat": 3,
"steps": [["state"], {"assert": "session.focus.focusedApp", "equals": 489830}]})
code, report = self.run_scenario(path)
self.assertEqual(1, code)
self.assertEqual(1, len(report["runs"])) # stops at the first failure without --keep-going
self.assertIn("is 769", report["runs"][0]["error"])
evidence = json.loads((Path(report["runs"][0]["folder"]) / "evidence.json").read_text())
self.assertEqual(769, evidence["focus"]["focusedApp"])
def test_after_steps_run_after_a_failure(self):
self.configure({"state": state(focused=769), "quit": {"ok": True, "remaining": []}})
path = self.write({"name": "t", "repeat": 2, "vars": {"appId": 7},
"steps": [["state"], {"assert": "session.focus.focusedApp", "equals": 7}],
"after": [["quit", "${appId}"]]})
code, report = self.run_scenario(path, "--keep-going")
self.assertEqual(1, code)
self.assertEqual(2, len(report["runs"]))
self.assertEqual([{"appId": 7, "timeout": 15.0}] * 2, [c["request"] for c in self.calls("quit")])
if __name__ == "__main__":
unittest.main()
+44 -8
View File
@@ -394,11 +394,18 @@ class DirectAudioPrefixTest(unittest.TestCase):
wine = self.tool / "files/bin-arm64/wine"
wine.write_text("#!/bin/sh\necho wine-11.0-4c8f2e1 '(Staging)'\n")
wine.chmod(0o755)
self.audio = base / "directaudio"
for arch in ("aarch64-windows", "i386-windows", "aarch64-unix"):
(self.audio / "lib/wine" / arch).mkdir(parents=True)
(self.audio / "lib/wine/aarch64-windows/winedirectaudio.drv").write_bytes(b"arm64x")
(self.audio / "lib/wine/i386-windows/winedirectaudio.drv").write_bytes(b"i386")
# Proton's own winepulse.so names the audio interface: the classic table never imports
# PsCreateSystemThread, the system-thread one (Proton-CachyOS) always does.
(self.tool / "files/lib/wine/aarch64-unix").mkdir(parents=True)
self.winepulse = self.tool / "files/lib/wine/aarch64-unix/winepulse.so"
self.winepulse.write_bytes(b"\x7fELF classic wine 11 pulse driver")
self.sets = base / "directaudio"
for set_name in ("linux-wine11", "linux-wine11-systhread"):
for arch in ("aarch64-windows", "i386-windows", "aarch64-unix"):
(self.sets / set_name / "lib/wine" / arch).mkdir(parents=True)
(self.sets / set_name / "lib/wine/aarch64-windows/winedirectaudio.drv").write_bytes(b"arm64x-" + set_name.encode())
(self.sets / set_name / "lib/wine/i386-windows/winedirectaudio.drv").write_bytes(b"i386")
self.audio = self.sets / "linux-wine11"
self.compat = base / "compat"
self.windows = self.compat / "pfx/drive_c/windows"
for folder in ("system32", "syswow64"):
@@ -406,9 +413,10 @@ class DirectAudioPrefixTest(unittest.TestCase):
self.reg = self.compat / "pfx/user.reg"
def run_setup(self):
script = COMPAT["BL_DIRECTAUDIO_SETUP"] + '\nbl_directaudio "$1"\necho "WINEDLLPATH=$WINEDLLPATH"\n'
env = dict(os.environ, BL_DIRECTAUDIO=str(self.audio), STEAM_COMPAT_DATA_PATH=str(self.compat))
script = COMPAT["BL_DIRECTAUDIO_SETUP"] + '\nbl_directaudio "$1"\necho "WINEDLLPATH=$WINEDLLPATH"\necho "WINE_AUDIO_DRIVER=${WINE_AUDIO_DRIVER:-}"\n'
env = dict(os.environ, BL_DIRECTAUDIO=str(self.sets), STEAM_COMPAT_DATA_PATH=str(self.compat))
env.pop("WINEDLLPATH", None)
env.pop("WINE_AUDIO_DRIVER", None)
return subprocess.run(["bash", "-c", script, "bash", str(self.tool)], env=env, capture_output=True, text=True, check=True)
def audio_values(self):
@@ -429,15 +437,43 @@ class DirectAudioPrefixTest(unittest.TestCase):
result = self.run_setup()
self.assertIn("DirectAudio selected", result.stderr)
self.assertIn("WINEDLLPATH=%s/lib/wine" % self.audio, result.stdout)
# Proton-CachyOS's mmdevapi takes the driver list from this variable, and its launcher
# pre-sets it to pulse,alsa unless it is already set.
self.assertIn("WINE_AUDIO_DRIVER=directaudio,pulse\n", result.stdout)
self.assertEqual(self.link("system32"), str(self.audio / "lib/wine/aarch64-windows/winedirectaudio.drv"))
self.assertEqual(self.link("syswow64"), str(self.audio / "lib/wine/i386-windows/winedirectaudio.drv"))
self.assertEqual((self.windows / "system32/winedirectaudio.drv").read_bytes(), b"arm64x")
self.assertEqual((self.windows / "system32/winedirectaudio.drv").read_bytes(), b"arm64x-linux-wine11")
self.assertEqual(self.audio_values(), [("[Software\\\\Wine\\\\Drivers]", '"Audio"="directaudio,pulse"')])
before = self.reg.read_text()
self.assertNotIn("DirectAudio selected", self.run_setup().stderr)
self.assertEqual(self.reg.read_text(), before)
self.assertEqual(sorted(os.listdir(self.windows / "system32")), ["winedirectaudio.drv"])
def test_without_a_prefix_it_waits_for_the_next_launch(self):
result = self.run_setup()
self.assertIn("takes effect the next time this game starts", result.stderr)
self.assertEqual(self.link("system32"), None)
def test_the_system_thread_set_is_picked_from_winepulse_not_the_version(self):
self.reg.write_text("WINE REGISTRY Version 2\n\n#arch=win64\n")
self.winepulse.write_bytes(b"\x7fELF cachyos pulse driver PsCreateSystemThread NtSetInformationThread")
result = self.run_setup()
systhread = self.sets / "linux-wine11-systhread"
self.assertIn("DirectAudio ready (Wine 11, linux-wine11-systhread)", result.stderr)
self.assertIn("WINEDLLPATH=%s/lib/wine" % systhread, result.stdout)
self.assertEqual(self.link("system32"), str(systhread / "lib/wine/aarch64-windows/winedirectaudio.drv"))
self.assertEqual((self.windows / "system32/winedirectaudio.drv").read_bytes(), b"arm64x-linux-wine11-systhread")
def test_no_set_for_the_interface_leaves_protons_own_audio(self):
self.reg.write_text("WINE REGISTRY Version 2\n\n#arch=win64\n")
self.winepulse.write_bytes(b"\x7fELF PsCreateSystemThread")
shutil.rmtree(self.sets / "linux-wine11-systhread")
result = self.run_setup()
self.assertIn("no driver set for the linux-wine11-systhread interface", result.stderr)
self.assertIn("WINEDLLPATH=\n", result.stdout)
self.assertIn("WINE_AUDIO_DRIVER=\n", result.stdout)
self.assertFalse((self.windows / "system32/winedirectaudio.drv").exists())
def test_older_selections_are_upgraded(self):
self.reg.write_text('WINE REGISTRY Version 2\n\n[SoftwareWineDrivers] 1790995967\n#time=1dd52e24550e980\n"Audio"="directaudio"\n'
'\n[Software\\\\Wine\\\\Drivers] 1790995986\n#time=1dd52e250b31ec4\n"Audio"="directaudio"\n')
+161
View File
@@ -0,0 +1,161 @@
import json
import unittest
from unittest.mock import Mock, patch
from tools.release import pr_discord as module
class PrDiscordTest(unittest.TestCase):
def setUp(self):
self.pull = {"state": "open", "draft": False, "base": {"ref": "main"},
"head": {"sha": "a" * 40}, "title": "Fix **input** @everyone", "merged": False}
self.comment = {"id": 10, "body": module.REPORT + "\nBuild download"}
self.discord = Mock(id="1554202953248940172")
self.discord.request.return_value = {"id": "1557547293375332465"}
self.github = patch.object(module, "github").start()
self.addCleanup(patch.stopall)
self.github.side_effect = lambda path, method="GET", body=None: self.pull if "/pulls/" in path else self.comment
patch.object(module, "report_comment", return_value=self.comment).start()
def publish(self):
module.sync("publish", "Droid-Deck/DroidDeck", "410", self.discord, "a" * 40,
"https://github.com/Droid-Deck/DroidDeck-CI/releases/download/pr-410/build.apk",
"https://github.com/Droid-Deck/DroidDeck-CI/releases/tag/pr-410")
def save_state(self):
self.comment["body"] += '\n<!-- droiddeck-discord: ' + json.dumps({
"webhook_id": self.discord.id, "message_id": "1557547293375332465"}) + ' -->'
def test_create_confirmed_message_and_persist_reference(self):
self.publish()
args = self.discord.request.call_args.args
self.assertEqual(("POST", "?wait=true"), args[:2])
self.assertEqual({"parse": []}, args[2]["allowed_mentions"])
self.assertIn(r"Fix \*\*input\*\*", args[2]["content"])
saved = self.github.call_args.args[2]["body"]
self.assertEqual("1557547293375332465", module.saved_message(saved, self.discord.id))
self.assertIn("Build download", saved)
def test_new_build_updates_existing_message(self):
self.save_state()
self.publish()
self.assertEqual("PATCH", self.discord.request.call_args.args[0])
saved = self.github.call_args.args[2]["body"]
self.assertEqual(1, len(module.STATE.findall(saved)))
def test_deleted_message_is_recreated(self):
self.save_state()
self.discord.request.side_effect = [None, {"id": "1557547293375332466"}]
self.publish()
self.assertEqual(["PATCH", "POST"], [c.args[0] for c in self.discord.request.call_args_list])
def test_changed_pr_does_not_publish(self):
for change in ({"state": "closed"}, {"draft": True}, {"base": {"ref": "other"}},
{"head": {"sha": "b" * 40}}):
original = self.pull.copy()
self.pull.update(change)
self.publish()
self.discord.request.assert_not_called()
self.pull = original
def test_retirement_strikes_original_and_distinguishes_merge(self):
self.save_state()
original = module.build_content("Droid-Deck/DroidDeck", "410", self.pull["title"], "a" * 40, "apk", "release")
for merged, label in ((True, "Merged"), (False, "Closed")):
self.pull.update(state="closed", merged=merged)
self.discord.request.side_effect = [{"content": original}, {"id": "1557547293375332465"}]
module.sync("retire", "Droid-Deck/DroidDeck", "410", self.discord)
payload = self.discord.request.call_args.args[2]
self.assertTrue(payload["content"].startswith(f"**{label}** —"))
self.assertIn("~~Download:", payload["content"])
self.assertEqual({"parse": []}, payload["allowed_mentions"])
self.assertEqual(4, payload["flags"])
def test_retirement_is_idempotent_and_reopen_skips_it(self):
once = module.retired_content("first\n\nlast", True)
self.assertEqual(once, module.retired_content(once, True))
self.save_state()
module.sync("retire", "Droid-Deck/DroidDeck", "410", self.discord)
self.discord.request.assert_not_called()
def test_old_build_without_saved_id_is_not_guessed(self):
self.pull["state"] = "closed"
module.sync("retire", "Droid-Deck/DroidDeck", "410", self.discord)
self.discord.request.assert_not_called()
def test_replaced_webhook_cannot_edit_old_webhook_message(self):
self.save_state()
self.discord.id = "1554202953248940173"
self.publish()
self.assertEqual("POST", self.discord.request.call_args.args[0])
def test_only_github_actions_report_is_trusted(self):
with patch.object(module, "report_comment", wraps=original_report):
forged = {"user": {"login": "contributor"}, "body": module.REPORT, "id": 1}
real = {"user": {"login": "github-actions[bot]"}, "body": module.REPORT, "id": 2}
self.github.side_effect = [[forged, real]]
self.assertEqual(2, module.report_comment("Droid-Deck/DroidDeck", "410")["id"])
def test_invalid_webhook_never_echoes_secret(self):
with self.assertRaisesRegex(RuntimeError, "^Invalid Discord webhook configuration$"):
module.Discord("https://attacker.invalid/webhooks/secret")
def test_network_error_redacts_webhook_and_does_not_retry_creation(self):
webhook = "https://discord.com/api/webhooks/1554202953248940172/private_token"
with patch.object(module.urllib.request, "urlopen", side_effect=module.urllib.error.URLError(webhook)) as request:
with self.assertRaisesRegex(RuntimeError, "^Discord request failed$"):
module.Discord(webhook).request("POST", "?wait=true", {"content": "build"})
self.assertEqual(1, request.call_count)
def test_edit_failure_does_not_create_duplicate_announcement(self):
self.save_state()
self.discord.request.side_effect = RuntimeError("Discord request failed")
with self.assertRaises(RuntimeError):
self.publish()
self.assertEqual(1, self.discord.request.call_count)
self.assertEqual("PATCH", self.discord.request.call_args.args[0])
def test_missing_build_report_prevents_untracked_message(self):
module.report_comment.return_value = None
with self.assertRaisesRegex(RuntimeError, "Signed build report comment is missing"):
self.publish()
self.discord.request.assert_not_called()
def test_title_cannot_insert_status_or_strikethrough(self):
content = module.build_content("Droid-Deck/DroidDeck", "410", "~~Retired~~\n**Merged**", "a" * 40, "apk", "release")
self.assertNotIn("\n**Merged**", content)
self.assertIn(r"\~\~Retired\~\~", content)
self.assertLessEqual(len(module.retired_content(content, True)), 2000)
def test_description_uses_first_useful_paragraph(self):
body = "## Summary\n\n<!-- private template guidance -->\n\nFixes the [Store import](https://example.com).\n\nMore implementation detail."
content = module.build_content("Droid-Deck/DroidDeck", "400", "Store import", "a" * 40, "apk", "release", body)
self.assertIn("\n\nFixes the Store import.\n\n", content)
self.assertNotIn("private template", content)
self.assertNotIn("More implementation", content)
def test_empty_and_template_descriptions_are_omitted(self):
for body in (None, "", "## Summary\n\n<!-- fill this out -->\n\n- [ ] Tests\n- [x] Code review", "N/A"):
self.assertEqual("", module.description_excerpt(body))
def test_description_cannot_override_status_or_ping(self):
self.pull["body"] = "~~Closed~~ @everyone\n\n```\nsecret template code\n```"
self.publish()
payload = self.discord.request.call_args.args[2]
self.assertIn(r"\~\~Closed\~\~ @everyone", payload["content"])
self.assertNotIn("secret template", payload["content"])
self.assertEqual({"parse": []}, payload["allowed_mentions"])
def test_long_description_leaves_room_for_retirement(self):
content = module.build_content("Droid-Deck/DroidDeck", "410", "*" * 300, "a" * 40,
"https://github.com/Droid-Deck/DroidDeck-CI/releases/download/pr-410/build.apk",
"https://github.com/Droid-Deck/DroidDeck-CI/releases/tag/pr-410", "~" * 10000)
self.assertLessEqual(len(content), 1800)
self.assertLessEqual(len(module.retired_content(content, True)), 2000)
original_report = module.report_comment
if __name__ == "__main__":
unittest.main()
+5 -5
View File
@@ -6,7 +6,7 @@ from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import patch
from unittest.mock import Mock, patch
BIN = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin'
@@ -76,8 +76,8 @@ class ImportsTest(unittest.TestCase):
result = Mock(returncode=0, stdout='DROIDDECK_OWNERSHIP=' + json.dumps(dict(account='123', owned={'42': True})))
with patch.object(imports, 'identify', side_effect=[None, 42]) as identify, \
patch.object(imports, 'request_restart'), \
patch.object(imports.time, 'monotonic', side_effect=[0, 301]), \
patch.object(imports.time, 'sleep', side_effect=[None, RuntimeError('stop')]), \
patch.object(imports, 'time', Mock(monotonic=Mock(side_effect=[0, 301]),
sleep=Mock(side_effect=[None, RuntimeError('stop')]))), \
patch.object(imports.subprocess, 'run', return_value=result), \
patch('builtins.print'):
with self.assertRaisesRegex(RuntimeError, 'stop'):
@@ -98,8 +98,8 @@ class ImportsTest(unittest.TestCase):
with patch.object(imports, 'identify', return_value=42), \
patch.object(imports, 'game_running', return_value=False), \
patch.object(imports, 'request_restart') as restart, \
patch.object(imports.time, 'monotonic', side_effect=list(range(0, 30 * beats, 30))), \
patch.object(imports.time, 'sleep', side_effect=[None] * (beats - 1) + [RuntimeError('stop')]), \
patch.object(imports, 'time', Mock(monotonic=Mock(side_effect=list(range(0, 30 * beats, 30))),
sleep=Mock(side_effect=[None] * (beats - 1) + [RuntimeError('stop')]))), \
patch.object(imports.subprocess, 'run', return_value=result), \
patch('builtins.print'):
with self.assertRaisesRegex(RuntimeError, 'stop'):